Wednesday, December 24, 2014

Convert Excel to XML in JEXCEL API

package com.relaytemplate.data;

import java.io.*;

import jxl.*;
import jxl.demo.XML;
import jxl.read.biff.BiffException;

import java.util.*;

import java.sql.*;

public class ExceltoXML{


// public void readExcelFile() {
public static void main(String args[]) throws BiffException, IOException{
File f = new File("TestConsolidated.xml");
OutputStream os = (OutputStream) new FileOutputStream(f);
String encoding = "UTF8";
OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
String filename = "relaytemplate.xls";
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook w = Workbook.getWorkbook(new File(filename), ws);
try {
XML myxml=new XML(w,os,filename, false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Wednesday, December 10, 2014

Spring JDBC Template- To get back the inserted values using Keyholder

public List insert(final Action action){
final String insertIntoSql ="INSERT INTO MIPUSER_ACTIONS(IACTIONID, SACTIONNAME) VALUES (nextval('SEQ_MIPUSER_ACTIONS'),?)";
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {           

                @Override
                public PreparedStatement createPreparedStatement(Connection connection)
                        throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(insertIntoSql.toString(), Statement.RETURN_GENERATED_KEYS);
                    ps.setString(1, action.getAction_name());
                    return ps;
                }
            }, holder);

KeyHolder newPersonId = holder;
System.out.println(newPersonId.getKeyList());
System.out.println(newPersonId.getKeys());
return newPersonId.getKeyList();
 }

Sunday, May 4, 2014

SpringMailService Utility Class

// This class contains  overloaded methods and has demonstrated all the features of spring mail inclusing velocity integration.
package com.packt.mailservice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessagePreparator;
import javax.mail.Message;
import java.util.Map;
import java.util.HashMap;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSenderService {
@Autowired
private VelocityEngine velocityEngine;
@Autowired
private MailSender mailSender;
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private SimpleMailMessage configured_message;
public void sendmail(String from, String to, String subject, String body) throws MailException{
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(from);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
public void sendmail(String from, String []to, String subject, String body) throws MailException{
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
public void sendmime_mail(final String from, final String to, final String subject, final String body) throws MailException{
MimeMessagePreparator message = new MimeMessagePreparator() {
               public void prepare(MimeMessage mimeMessage) throws Exception {
              message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
              message.setFrom(new InternetAddress(from));
              message.setSubject(subject);
              message.setText(msg);
            }

public void prepare(MimeMessage arg0) throws Exception {
// TODO Auto-generated method stub

}

    };
    mailSender.send(message);
}
public void sendmail(String from, String []to, String subject, String body,FileSystemResource file,String filename) throws MailException{
       MimeMessage mimemessage = mailSender.createMimeMessage();
       MimeMessageHelper mimemessagehelper = new MimeMessageHelper(message, true);
       mimemessagehelper.setFrom(from);
       mimemessagehelper.setTo(to);
       mimemessagehelper.setSubject(subject);
       mimemessagehelper.setText(msg);
       mimemessagehelper.addAttachment(filename, file);//image will be sent by this name
       mailSender.send(message);
     
}
public void sendmail(String message) throws MailException{
SimpleMailMessage message=new SimpleMailMessage(configured_message);
        mailSender.send(message);
     
}
public void sendmail(final Customer customer){
MimeMessagePreparator preparator = new MimeMessagePreparator() {
     public void prepare(MimeMessage mimeMessage)
          throws Exception {
       MimeMessageHelper message =
                             new MimeMessageHelper(mimeMessage);
       message.setTo(user.getEmailAddress());
           message.setFrom("webmaster@csonth.gov.uk"); // could be parameterized...
           Map model = new HashMap();
           model.put("customer", customer);
           String text = VelocityEngineUtils.mergeTemplateIntoString(
              velocityEngine, "com/packt/velocity/templates/orderconfirmation.vm", model);
           message.setText(text, true);
        }
     };
     this.mailSender.send(preparator);
  }
}

Tuesday, July 2, 2013

Multilevel Inheritance in java with public variables and parameterized Constructor

This is a demonstration of Multi-level inheritance in java using parameterised constructor
package com.inheritance;

public class Class1 {
public int a;
public int b;
public Class1(int a, int b) {
super();
this.a = a;
this.b = b;
System.out.println("I am super class called first--->"+(a+b));
System.out.println(a+b);
}
}
---------------------------------------------
package com.inheritance;
public class Class2 extends Class1 {
public int c;
public Class2(int a, int b, int c) {
super(a, b);
this.c=c;
System.out.println("I am the second level subclass--->" +a%c);
}

}
--------------------------------------------------------------
package com.inheritance;

public class Class3 extends Class2 {
public int d;
public Class3(int a, int b,int c, int d) {
super(a, b, c);
this.d=d;
System.out.println("I am thrid level subclass extends second level class-->"+a*b*c*d);
// TODO Auto-generated constructor stub
}
public static void main(String args[]){
Class3 class3=new Class3(1, 2, 3, 4);
}
}
--------------------------------------------
output:
I am super class called first--->3
3
I am the second level subclass--->1
I am thrid level subclass extends second level class-->24

Wednesday, June 26, 2013

Can a Class implement two interfaces with the same method signature

I created two interfaces with same method signature.
You can actually implement the method only once.

package com.anjana;
public interface Interface2 {
public String printme();
}
package com.anjana;
public interface Interface1 {
public String printme();
}
package com.anjana;

public class Employee implements Interface1,Interface2,Interface3{
@Override
public String printme() {
return "Hello";
}

public static void main(String args[]){
Interface1 emp1=new Employee();
emp1.printme();
System.out.println(emp1.printme());
Interface2 emp2=new Employee();
System.out.println(emp2.printme());
}
This will be misleading if you have to do some operations based on the returned value.

Thursday, May 30, 2013

Example:Immutable Class

Immutable class is thread safe
Imuutable class objects cannot be modified
Examples :
  • Integer
  • String
package com.demo.immutable;
//make ur class final
public final class MyImmutable {
 //make ur instance variables final
    final String s="Anjana";
    private String s2=null;
//access the private via constructors--to modify
    public MyImmutable(String s2) {
        super();
        this.s2 = s2;
    }
    public static void main(String args[]){
        MyImmutable  myimmutable=new MyImmutable("dff");
    }
}
 

Friday, September 7, 2012

CXF RESTFUL Service - Example jax-rs

CXF frame work  supports restful web services.
It is provided in the following ways:
  1. JAX_RS
  2. JAX_WS ProviderDispatch
  3. HtppBinding
Below is the example of RESTFUL service which gives an xml response.The data is pulled form  the database.I have also integrated  spring-jdbc with cxf.

check the response after running the application at-http://localhost:8086/cxf-jaxrs-poc/myservice/users
Port number can change based on availability.

Lets start with the configurations-cxf.xml:

 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xmlns:jaxrs="http://cxf.apache.org/jaxrs"  
   xsi:schemaLocation="  
 http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans.xsd  
 http://cxf.apache.org/jaxrs  
 http://cxf.apache.org/schemas/jaxrs.xsd"  
   default-lazy-init="false">  
   <jaxrs:server id="myService" address="/">  
     <jaxrs:serviceBeans>  
       <ref bean="serviceImpl" />  
     </jaxrs:serviceBeans>  
     <jaxrs:extensionMappings>  
       <entry key="xml" value="application/xml" />  
     </jaxrs:extensionMappings>  
   </jaxrs:server>  
   <bean id="serviceImpl" class="service.ServiceImpl" />  
   <bean id="MySqlDatasource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">  
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>  
     <property name="url" value="jdbc:mysql://localhost:3306/emp"/>  
     <property name="username" value="root"/>  
     <property name="password" value="prdc123"/>  
   </bean>  
   <bean id="userDAO" class="dao.UserDAOImpl">  
           <property name="dataSource" ref="MySqlDatasource"/>  
      </bean>  
 </beans>  

web.xml configuration- add cxf servlet-and spring context listners
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
   <display-name>cxf-jaxrs-poc</display-name>  
   <description>cxf-jaxrs-poc</description>  
 <!--   <context-param> -->  
 <!--     <param-name>webAppRootKey</param-name> -->  
 <!--     <param-value>cxf.rest.example.root</param-value> -->  
 <!--   </context-param> -->  
   <context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>/WEB-INF/cxf.xml</param-value>  
   </context-param>  
   <listener>  
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
   </listener>  
   <servlet>  
     <servlet-name>CXFServlet</servlet-name>  
     <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
     <load-on-startup>1</load-on-startup>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>CXFServlet</servlet-name>  
     <url-pattern>/*</url-pattern>  
   </servlet-mapping>  
 </web-app> 

Service Defn Interface
 package service;  
 import javax.ws.rs.core.Response;  
 import pojo.User;  
 import pojo.UserCollection;  
 public interface ServiceDefn {  
   public abstract UserCollection getUsers();  
   public abstract User getUser(Integer id);  
   public abstract Response getBadRequest();  
 }  

service impl class-- define restful service path,prepares the data for response
 package service;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 import java.util.Iterator;  
 import java.util.List;  
 import java.util.Map;  
 import javax.ws.rs.DELETE;  
 import javax.ws.rs.GET;  
 import javax.ws.rs.POST;  
 import javax.ws.rs.PUT;  
 import javax.ws.rs.Path;  
 import javax.ws.rs.PathParam;  
 import javax.ws.rs.Produces;  
 import javax.ws.rs.core.Response;  
 import javax.ws.rs.core.Response.Status;  
 import dao.Manager;  
 import pojo.User;  
 import pojo.UserCollection;  
 @Path("/myservice/")  
 @Produces("application/xml")  
 public class ServiceImpl implements ServiceDefn {  
   private static Map<Integer, User> users = new HashMap<Integer, User>();  
   private static Manager m;  
   Integer currentId = 3;  
   static {  
 //    users.put(1, new User(1, "foo","Manager"));  
 //    users.put(2, new User(2, "bar","SE"));  
 //    users.put(3, new User(3, "baz","CTO"));  
        List l=new ArrayList();       
         m=new Manager();  
         l=m.view();  
        Iterator itr=l.iterator();  
        int i=0;  
        while(itr.hasNext()){  
             users.put(i++, (User) itr.next());  
        }  
   }  
   public ServiceImpl() {  
   }  
   @GET  
   @Path("/users")  
   public UserCollection getUsers() {  
        System.out.println(users.values());  
     return new UserCollection(users.values());  
   }  
   @GET  
   @Path("/user/{id}")  
   public User getUser(@PathParam("id") Integer id) {  
     return users.get(id);  
   }  
   @GET  
   @Path("/users/bad")  
   public Response getBadRequest() {  
     return Response.status(Status.BAD_REQUEST).build();  
   }  
   @PUT  
   @Path("/users/")  
   public Response updateUsers(User user) {  
     System.out.println("----invoking updateCustomer, Customer name is: " + user.getName());  
     User c = users.get(user.getId());  
     Response r;  
     if (c != null) {  
          users.put(user.getId(), user);  
       r = Response.ok().build();  
     } else {  
       r = Response.notModified().build();  
     }  
     return r;  
   }  
   @POST  
   @Path("/users/")  
   public Response addUsers(User user) {  
     System.out.println("----invoking addCustomer, Customer name is: " + user.getName());  
     user.setId(++currentId);  
     users.put(user.getId(), user);  
     return Response.ok(user).build();  
   }  
   @DELETE  
   @Path("/user/{id}/")  
   public Response deleteUser(@PathParam("id") String id) {  
     System.out.println("----invoking deleteCustomer, Customer id is: " + id);  
     Integer idNumber = Integer.parseInt(id);  
     User c = users.get(idNumber);  
     Response r;  
     if (c != null) {  
       r = Response.ok().build();  
       users.remove(idNumber);  
     } else {  
       r = Response.notModified().build();  
     }  
     return r;  
   }  
 }  

Users COllection
 package pojo;  
 import java.util.Collection;  
 import javax.xml.bind.annotation.XmlElement;  
 import javax.xml.bind.annotation.XmlElementWrapper;  
 import javax.xml.bind.annotation.XmlRootElement;  
 @XmlRootElement  
 public class UserCollection {  
   private Collection<User> users;  
   public UserCollection() {  
   }  
   public UserCollection(Collection<User> users) {  
     this.users = users;  
   }  
   @XmlElement(name="user")  
   @XmlElementWrapper(name="users")  
   public Collection<User> getUsers() {  
     return users;  
   }  
 }  

User
 package pojo;  
 import javax.xml.bind.annotation.XmlRootElement;  
 @XmlRootElement(name = "user")  
 public class User {  
   private Integer id;  
   private String name;  
   private String designation;  
      public String getDesignation() {  
           return designation;  
      }  
      public void setDesignation(String designation) {  
           this.designation = designation;  
      }  
      public User() {  
   }  
   public User(Integer id, String name,String designation) {  
     this.id = id;  
     this.name = name;  
     this.designation=designation;  
   }  
   public User(String name,String designation) {  
     this.id = id;  
     this.name = name;  
     this.designation=designation;  
   }  
   public Integer getId() {  
     return id;  
   }  
   public void setId(Integer id) {  
     this.id = id;  
   }  
   public void setName(String name) {  
     this.name = name;  
   }  
   public String getName() {  
     return name;  
   }  
   @Override  
      public String toString() {  
           return "User [id=" + id + ", name=" + name + ", designation="  
                     + designation + "]";  
      }  
 }