Tuesday 22 December 2015

Calling Procedure in Spring JDBC

        private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public void insertCustomerDetails(int id, String name, String address,
String phone) {
String query = "insert into customer (id,name,address,phone) values (?,?,?,?)";
template.update(query, id, name, address, phone);
System.out.println("Record inserted successfully");
}   

        public void callStoredProcedure() {
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(template)
.withProcedureName("customerDetails");
Map<String, Object> inParamMap = new HashMap<String, Object>();
inParamMap.put("id", 1);
SqlParameterSource in = new MapSqlParameterSource(inParamMap);
Map<String, Object> simpleJdbcCallResult = simpleJdbcCall.execute(in);
System.out.println(simpleJdbcCallResult);
}


     Another code

    public class EmployeeSP extends StoredProcedure{ 
private static final String SPROC_NAME = "usp_GetEmployeeName";
          public EmployeeSP(DataSource datasource ){
  super( datasource, SPROC_NAME ); 
  declareParameter( new SqlParameter( "id", Types.INTEGER) ); 
  //declaring sql in parameter to pass input  
  declareParameter( new SqlOutParameter( "name", Types.VARCHAR ) ); 
  //declaring sql out parameter compile();
          } 
public Object execute(int emp_id){
Map<String,Object> results = super.execute(emp_id); 
return results.get("name"); //reading output of stored procedure using out parameters 
}
    
}


Another Code Snippet

List<SqlParameter> declaredParameters = new ArrayList<SqlParameter>();

declaredParameters.add(new SqlOutParameter("id", Types.INTEGER));
declaredParameters.add(new SqlParameter("name", Types.VARCHAR));
declaredParameters.add(new SqlParameter("date", Types.DATE));

this.jdbcTemplate.call(new CallableStatementCreator() {

    @Override
    CallableStatement createCallableStatement(Connection con) throws SQLException {
        CallableStatement stmnt = con.createCall("{mypkg.doSomething(?, ?, ?)}");

        stmnt.registerOutParameter("id", Types.INTEGER);
        stmnt.setString("name", "<name>");
        stmnt.setDate("date", <date>);

        return stmnt;
    }
}, declaredParameters);

Circular Dependency in Spring?

Circular Dependency in Spring?

Bean1 ->> Referring ->>Bean2 ->Referring->>Bean3-->>Referring ->>Bean1

Spring will not allow Circular Dependency and will throw an exception (BeanCurrentlyInCreationException) at the time of loading the configuration files. 


Friday 18 December 2015

Java Method Logging with AOP and Annotations

Step-1

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>

</dependency>

Step-2

Enable AOP Annotations

    <!-- this will enable aspectJ annotation -->  
    <!-- We have concept for Proxy object for implementing AOP
         two kind of proxy
         1. Java Dynamic Proxy(proxy-target-class="false")
         2. CGLIB Proxy(proxy-target-class="true")  
     -->
   <aop:aspectj-autoproxy proxy-target-class="false"/>

   <context:component-scan base-package="com.synergy.bank.base.aop.logger"/>


Step-3
Define custom annotation for AOP

@Target(METHOD)
@Retention(RUNTIME)
public @interface Loggable {


}


Step-4
Define advice with above Annotation

@Component
@Aspect
public class SynergyDaoLogger {

private static Logger logger=Logger.getLogger(SynergyDaoLogger.class);

@Before("execution(* *(..)) && @annotation(Loggable)")
public void salute(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
String methodName = signature.getName();
String arguments = Arrays.toString(joinPoint.getArgs());
if(logger.isDebugEnabled()) {
logger.debug("____________________________________________________________________");
logger.debug("___________Magic of AOP with custom annotation________________");
logger.debug("____________________________________________________________________");

}
}
}


Step-5
Applying logging with custom annotation


@Repository("BankAdminDaoImpl") @Scope("singleton") @Transactional(propagation=Propagation.REQUIRED) public class BankAdminDaoImpl extends JdbcDaoSupport implements BankAdminDao{ @Autowired @Qualifier("bankDataSource") // here we are injecting bankDataSource inside JdbcDaoSupport super class public void setDataSourceInBank(DataSource dataSource) { super.setDataSource(dataSource); } @Override @Loggable public List<CustomerEntity> findPendingCustomerList(){ }





Wednesday 9 December 2015

Accessing Spring Root Web Container with ContextLoader in application

****Creating spring root web container with ContextLoaderListener
<!-- Responsible for instantiating spring root web application context container -->

 <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


      

 @Override
//@WebMethod(exclude=true)
public String addProgram(ProgramVO addProgramInput) {
if(iProgramService==null) {
//Accessing Spring Root Web Container
ApplicationContext pplicationContext=ContextLoader.getCurrentWebApplicationContext();
iProgramService =(IProgramService)applicationContext.getBean("ProgramService");
}
com.gps.quiz.service.model.ProgramVO programVO=new com.gps.quiz.service.model.ProgramVO();
 BeanUtils.copyProperties(addProgramInput, programVO, new String[]{"timestamp"});
      programVO.setTimestamp(DateUtils.getCurrentTimeIntoTimestamp());
      String result=iProgramService.addTempProgram(programVO);
      return result;
}

Tuesday 8 December 2015

Rest Web Service Best URL

http://apigee.com/about/blog/technology/restful-api-design-what-about-errors
http://apigee.com/about/blog/technology/restful-api-design-what-about-errors
http://www.codingpedia.org/ama/resources-on-how-to-design-error-handling-in-a-rest-api/
http://www.codingpedia.org/ama/error-handling-in-rest-api-with-jersey/
http://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-adding-validation-to-a-rest-api/
http://apigee.com/about/blog/technology/restful-api-design-tips-versioning
https://github.com/paulc4/mvc-exceptions/tree/master/src/main/java

Do you know versioning in REST? How to implement it in Rest Web Service.

http://thereisnorightway.blogspot.in/2011/02/versioning-and-types-in-resthttp-api.html
http://www.infoq.com/news/2010/06/rest-versioning
http://stackoverflow.com/questions/10742594/versioning-rest-api


@Controller
@Scope("request")
@RequestMapping(value = "/v1/questions")
public class QuestionsController {

@Autowired
@Qualifier("QuestionsService")
private IQuestionsService iQuestionsService;

public QuestionsController() {
System.out
.println("@_@__@)))))))))))))))))((((((((((((((((((((((((((((((((((((((((((((((((((((((");
}

@RequestMapping(value = "/auth", method = RequestMethod.GET, produces = {
"application/json", "application/xml" })
public @ResponseBody
UserForm findUserById(
@RequestParam(value = "userid", required = false) String userid) {

  }
}

How JSON data is processed in REST

How to remove null values from JSON Response in REST


Step-1 
Add below dependency in the pom.xml

<!--
    Used to generate JSON response
 -->
      <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>

Step-2
/**
 * 
 * @author nagendra
 *
 */
@XmlRootElement
@JsonInclude(Include.NON_NULL)
public class FruitForm {

}








@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD,
    ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@com.fasterxml.jackson.annotation.JacksonAnnotation
public @interface JsonInclude
{
    /**
     * Inclusion rule to use.
     */
    public Include value() default Include.ALWAYS;
    
    /*
    /**********************************************************
    /* Value enumerations needed
    /**********************************************************
     */

    /**
     * Enumeration used with {@link JsonInclude}
     * to define which properties
     * of Java Beans are to be included in serialization.
     *<p>
     * Note: Jackson 1.x had similarly named ("Inclusion") enumeration included
     * in <code>JsonSerialize</code> annotation: it is not deprecated
     * and this value used instead.
     */
    public enum Include
    {
        /**
         * Value that indicates that property is to be always included,
         * independent of value of the property.
         */
        ALWAYS,

        /**
         * Value that indicates that only properties with non-null
         * values are to be included.
         */
        NON_NULL,

        /**
         * Value that indicates that only properties that have values
         * that differ from default settings (meaning values they have
         * when Bean is constructed with its no-arguments constructor)
         * are to be included. Value is generally not useful with
         * {@link java.util.Map}s, since they have no default values;
         * and if used, works same as {@link #ALWAYS}.
         */
        NON_DEFAULT,

        /**
         * Value that indicates that only properties that have values
         * that values that are null or what is considered empty are
         * not to be included.
         *<p>
         * Default emptiness is defined for following type:
         *<ul>
         * <li>For {@link java.util.Collection}s and {@link java.util.Map}s,
         *    method <code>isEmpty()</code> is called;
         *   </li>
         * <li>For Java arrays, empty arrays are ones with length of 0
         *   </li>
         * <li>For Java {@link java.lang.String}s, <code>length()</code> is called,
         *   and return value of 0 indicates empty String (note that <code>String.isEmpty()</code>
         *   was added in Java 1.6 and as such can not be used by Jackson
         *   </li>
         * <ul>
         *  and for other types, non-null values are to be included.
         *<p>
         * Note that this default handling can be overridden by custom
         * <code>JsonSerializer</code> implementation: if method <code>isEmpty()</code>
         * is overridden, it will be called to see if non-null values are
         * considered empty (null is always considered empty).
         */
        NON_EMPTY
        ;

    }

SSL IN RESTFUL WEB SERVICE











Calling Rest with Ajax in jQuery

Difference between Rest and Soap based web service..............








WADL - Web Application Description Language for JAX-RS Rest Web Service
   
1. Rest is not standard while soap is standard


2. Rest is light and faster compare to Soap

3. Rest Supports only http protocol while SOAP supports other protocol like
    JMS,SMTP etc.

4. XSD is used in Soap & Rest both

5.  Rest uses protocol level security (SSL) only while SOAP support both protocol level security and message level security(SOAP-WS).

6. Soap supports WS Atomic transaction while rest is not

7. SOAP is message orientated & Rest is resource orientated

8. SOAP supports encoding while Rest is not.

9. REST can generate difference types of response like XML/JSON/JPEG etc. while SOAP response is only in XML Soap format.

10. Rest can be accessed from browser java script code while Soap is not...

      Example

$(document).ready(function() {
  $("#nextFruit").click(function(){
  var imagePath=$("#imageContainer").attr("src");
  var pathTokens=imagePath.split("/");
  var imageId=pathTokens[pathTokens.length-1];
  ///////////////////////////////////////////
  $.ajax( { url:contextPath+'/rest/v1/fruit/ajax/'+imageId,
  //  dataType: "xml",
  accept: "Application/json",
  success:function(data) {
              //var xmlString = (new XMLSerializer()).serializeToString(data);
               $("#imageContainer").attr("src","rest/v1/fruit/image/"+data['fid']);
               $("#fname").html(data['fruitName']);
               $("#fcolor").html(data['color']);
               $("#fprice").html(data['price']);
               $("#ftaste").html(data['taste']);
             },
             error:function(){
              alert("+__@_ERROR__##");
             }
          });   
 
    //end of ajax call
     ///////////////////////////////////////
    //this should come from ajax
    
  });
   }); 


11. Rest is based on JAX-RS while SOAP is based JAX-WS







A Comparison of Spring MVC and JAX-RS


http://www.infoq.com/articles/springmvc_jsx-rs

JAX-RS Rest web service annotations

http://www.devx.com/Java/Article/42873/0/page/5

What is HATEOAS and why is it important in REST API?

Reference :
http://restcookbook.com/Basics/hateoas/


HATEOAS stands for Hypertext As The Engine Of Application State. It means that hypertext should be used to find your way through the API. An example:


GET /account/12345 HTTP/1.1 HTTP/1.1 200 OK 
















Apart from the fact that we have 100 dollars (US) in our account, we can see 4 options: deposit more money, withdraw money, transfer money to another account, or close our account. The "link"-tags allows us to find out the URLs that are needed for the specified actions. Now, let's suppose we didn't have 100 usd in the bank, but we actually are in the red: 













Now we are 25 dollars in the red. Do you see that right now we have lost many of our options, and only depositing money is valid? As long as we are in the red, we cannot close our account, nor transfer or withdraw any money from the account. The hypertext is actually telling us what is allowed and what not: HATEOAS -

How do you consume a RESTFUL webservice?


###########################
######Rest Provider code#####
##########################

@Controller
@Scope("request")
@RequestMapping(value = "/v1/program")
public class ProgramController {

@Autowired
@Qualifier("ProgramService")
private IProgramService iProgramService;

@RequestMapping(value = ProgramURIConstant.ADD_PROGRAM, method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody
String addProgram(@RequestBody ProgramVO programVO) {
programVO.setTimestamp(DateUtils.getCurrentTimeIntoTimestamp());
String result = iProgramService.addProgram(programVO);
return result;
}

}

 Step-1
 Access the RestTemplate Bean

<beans>
<bean id="crestTemplate" class="org.springframework.web.client.RestTemplate">
</bean>          
</beans> 

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("rest-template.xml");
RestTemplate restTemplate = (RestTemplate) applicationContext.getBean("crestTemplate"); 


 Step-2

Define Accept Media (Which is responsible for output format from Restful Web service)

List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);


Step-3

Creating HttpHeader object

HttpHeaders headers = new HttpHeaders();


Step-4
Setting Accept media inside the header
// what output we are expecting
headers.setAccept(acceptableMediaTypes);


Step-5
Setting Content Type iinside the header

// /We are setting the format of data which will from client to server
headers.setContentType(MediaType.APPLICATION_JSON);


Step-6

Define JSON Data which we want to send to the provider

ProgramVO programVO=new ProgramVO();
programVO.setCode("fororueueueueu");
programVO.setId("P039393");
programVO.setLanguage("Kava");
programVO.setLevel("1");
programVO.setProgramTiitle("Binary Nuber");
programVO.setTopic("Coding");
programVO.setUserid("akash");


Step-7
// setting header and data inside the HttpEntity which will work as a request
//in Restful communication
HttpEntity<ProgramVO> requestEntity = new HttpEntity<ProgramVO>(programVO,headers);


Step-8
Calling the Restful web service

ResponseEntity<String> response = restTemplate.exchange("http://www.gpsprogramys.co.in/com.gps.quiz/android/v1/program/add", HttpMethod.POST, requestEntity,String.class);

String output=response.getBody();