Different ways to Iterate ArrayList- Example

package com.pretech;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListLoop {
	public static void main(String[] args) {
		List<String> weekdays = new ArrayList<String>();
		weekdays.add("Monday");
		weekdays.add("Tuesday");
		weekdays.add("Wednesday");
		System.out.println("ITERATE USING FOR LOOP");
		for (int num = 0; num < weekdays.size(); num++) {
			System.out.println(weekdays.get(num));
		}
		System.out.println("ITERATE USING ADVANCED FOR LOOP");
		for (String str : weekdays) {
			System.out.println(str);
		}
		
		System.out.println("ITERATE USING util.Iterator");
		Iterator<String> i = weekdays.iterator();
		while (i.hasNext()) {
			System.out.println(i.next());
		}
		
		
		System.out.println("ITERATE USING WHILE LOOP");
		int num = 0;
		while (weekdays.size() > num) {
			System.out.println(weekdays.get(num));
			num++;
		}
	}
}

Output



ITERATE USING FOR LOOP
Monday
Tuesday
Wednesday
ITERATE USING ADVANCED FOR LOOP
Monday
Tuesday
Wednesday
ITERATE USING util.Iterator
Monday
Tuesday
Wednesday
ITERATE USING WHILE LOOP
Monday
Tuesday
Wednesday


ClassNotFoundException v/s NoClassDefFoundError

ClassNotFoundException

ClassNotFoundException Thrown when an application tries to load in a class through its name as String. (When Dynamic loading).
Here is one simple example to throw class not found Exception

public class ClassNotFoundTest {
	public static void main(String[] args) {
		try {
				ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
				String className = "testclass";
				Class<?> myClass = myClassLoader.loadClass(className);
				System.out.println("Successfully loaded"+myClass.getSimpleName());	
			}
			catch (ClassNotFoundException  e) {
				System.out.println("Exception message   "+e);
			}
	}
}


Exception message   java.lang.ClassNotFoundException: testclass



NoClassDefFoundError


NoClassDefFoundError Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

How to call Stored Procedure using Spring StoredProcedure?

In the previous example we used org.springframework.jdbc.core.simple.SimpleJdbcCall to call stored procedures. In this example we will see how to use org.springframework.jdbc.object.StoredProcedure to call stored procedures.

1. Database setup

For this example we will use one simple customer table and one stored procedure. Run below sql script to set up data in MySql
 
--
-- Create schema customerdb
--
 
CREATE DATABASE IF NOT EXISTS customerdb;
USE customerdb;
 
--
-- Definition of table `customer`
--
 
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `address` VARCHAR(45) NOT NULL,
  `phone` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;
 
--
-- Definition of procedure `customerDetails`
--
 
DROP PROCEDURE IF EXISTS `customerDetails`;
 
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `customerDetails`( IN id INT,  OUT firstname VARCHAR(255))
BEGIN
 SELECT name INTO firstname
   FROM customer
   WHERE id = id;
END $$
DELIMITER ;
 

2. Create class which extends spring Stored Procedure Class

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.object.StoredProcedure;
 
public class StoredProcedureCall extends StoredProcedure {
 public StoredProcedureCall(JdbcTemplate jdbcTemplate, String spName) {
  super(jdbcTemplate, spName);
  setFunction(false);
 
 }
}

 

3. Create a class for Data base operation (CustomerDataService.java)

import java.sql.Types;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;

public class CustomerDataService {
    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 List<?> selectAllCustomerDetails() {
        List<?> customerList = template.queryForList("select * from customer");
        return customerList;
    }

    public void callStoredProcedure() {
        StoredProcedureCall storedProcedureCall = new StoredProcedureCall(template, "customerDetails");

        SqlParameter idparam = new SqlParameter("id", Types.INTEGER);
        SqlOutParameter outParam = new SqlOutParameter("firstname", Types.VARCHAR);

        SqlParameter[] paramArray = { idparam, outParam };

        storedProcedureCall.setParameters(paramArray);
        storedProcedureCall.compile();

        // Call stored procedure
        Map storedProcResult = storedProcedureCall.execute(1);
        System.out.println(storedProcResult);
    }
}

4. Create spring configuration (SpringConfig.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
  <property name="url" value="jdbc:mysql://localhost:3306/customerDB"></property>
  <property name="username" value="root"></property>
  <property name="password" value="root"></property>
 </bean>
  <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
     <constructor-arg>
        <ref bean="dataSource"/>
     </constructor-arg>    
     </bean>
    <bean id="customerDataService" class="com.pretech.jdbc.CustomerDataService">
       <property name="template">
       <ref bean="jdbctemplate"/>
    </property>
</bean>
</beans>

5. Create a test class (CustomerMaster.java)

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class CustomerMaster {

    public static void main(String[] args) {
        Resource resource = new ClassPathResource("SpringConfig.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        CustomerDataService customerDataService = (CustomerDataService) factory.getBean("customerDataService");

        // inserting data

        customerDataService.insertCustomerDetails(1, "VINOD", "BANGALORE", "90909090");
        // selecting data
        System.out.println("Customer Details" + customerDataService.selectAllCustomerDetails());

        // Calling stored procedure

        customerDataService.callStoredProcedure();

    }

}

6. Run it

After running the CustomerMaster we will get below output.
 
Record inserted successfully
Customer Details[{id=1, name=VINOD, address=BANGALORE, phone=90909090}]
{#update-count-1=1, firstname=VINOD}
 

How to call Stored Procedure using Spring SimpleJdbcCall ?

In this example we will see how to call stored procedure using org.springframework.jdbc.core.simple.SimpleJdbcCall

1. Database setup

For this example we will use one simple customer table and one stored procedure. Run below sql script to set up data in MySql
 
--
-- Create schema customerdb
--
 
CREATE DATABASE IF NOT EXISTS customerdb;
USE customerdb;
 
--
-- Definition of table `customer`
--
 
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `address` VARCHAR(45) NOT NULL,
  `phone` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;
 
--
-- Definition of procedure `customerDetails`
--
 
DROP PROCEDURE IF EXISTS `customerDetails`;
 
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `customerDetails`( IN id INT,  OUT firstname VARCHAR(255))
BEGIN
 SELECT name INTO firstname
   FROM customer
   WHERE id = id;
END $$
DELIMITER ; 

2. Create a class for Data base operation (CustomerDataService.java)

Note: During the callStoredProcedure method we are using the Spring SimpleJdbcCall

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;

public class CustomerDataService {
    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 List<?> selectAllCustomerDetails() {
        List<?> customerList = template.queryForList("select * from customer");
        return customerList;
    }

    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);
    }

}

3. Create spring configuration (SpringConfig.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
  <property name="url" value="jdbc:mysql://localhost:3306/customerDB"></property>
  <property name="username" value="root"></property>
  <property name="password" value="root"></property>
 </bean>
  <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
     <constructor-arg>
        <ref bean="dataSource"/>
     </constructor-arg>    
     </bean>
    <bean id="customerDataService" class="com.pretech.jdbc.CustomerDataService">
       <property name="template">
       <ref bean="jdbctemplate"/>
    </property>
</bean>
</beans>

4. Create a test class (CustomerMaster.java)

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class CustomerMaster {

    public static void main(String[] args) {
        Resource resource = new ClassPathResource("SpringConfig.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        CustomerDataService customerDataService = (CustomerDataService) factory.getBean("customerDataService");

        // inserting data

        customerDataService.insertCustomerDetails(1, "VINOD", "BANGALORE", "90909090");
        // selecting data
        System.out.println("Customer Details" + customerDataService.selectAllCustomerDetails());

        // Calling stored procedure

        customerDataService.callStoredProcedure();

    }

}

5. Run it

After running the CustomerMaster we will get below output.
 
Record inserted successfully
Customer Details[{id=1, name=VINOD, address=BANGALORE, phone=90909090}]
{#update-count-1=1, firstname=VINOD}
 

How to create Procedure in MySql?

1.Create a database and procedure

CREATE DATABASE `pretech`
DELIMITER $$
DROP PROCEDURE IF EXISTS `pretech`.`Helloworld` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `Helloworld`()
BEGIN
 Select 'HELLO WORLD';
END $$
DELIMITER ;

2. Run it

CALL Helloworld()

3.Call procedure



image


Serializing Objects to byte array using Apache SerializationUtils

1. Add below dependency

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.3</version>
		</dependency>

2. Example

package com.pretech;
import org.apache.commons.lang.SerializationUtils;
public class SerializationExample {
	public static void main(String[] args) {
		byte name[] = SerializationUtils.serialize("Test");
		String deserilazed = (String) SerializationUtils.deserialize(name);
		System.out.println(deserilazed);
	}
}

3. Output



Test


Camel Jetty Component Example

The jetty component provides HTTP-based endpoints for consuming and producing HTTP requests. Here is one simple example to expose a jetty end point and serving the http request from REST client.

1. Create Maven project with below dependencies.

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <version>2.12.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. Create a Simple Route to expose Jetty endpoint.

package com.vinod.test;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class CamelJettyExample {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyCamelJettyBuilder());
        main.run(args);
    }
}

class MyCamelJettyBuilder extends RouteBuilder {
    public void configure() {
        from("jetty:http://localhost:8181/mytestservice").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                String message = exchange.getIn().getBody(String.class);
                System.out.println("Hello Mr :" + message);
                exchange.getOut().setBody("Hello world Mr " + message);
            }
        });
    }
}

3. Run it
Run the application and hit the service
http://localhost:8181/mytestservice


4. Done !! Download application
https://github.com/kkvinodkumaran/camel

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts