Thursday, 17 October 2013

factorial program in java

/*
Java Factorial Using Recursion Example
This Java example shows how to generate factorial of a given number
using recursive function.
*/
import java.io.IOException;
import java.util.Scanner;
public class JavaFactorialUsingRecursion {
public static void main(String args[]) throws NumberFormatException, IOException{
System.out.println("Enter the number: ");
//get input from the user
Scanner scan=new Scanner(System.in);
int a = scan.nextInt();
//call the recursive function to generate factorial
int result= fact(a);
System.out.println("Factorial of the number is: " + result);
}
static int fact(int b)
{
if(b <= 1)
//if the number is 1 then return 1
return 1;
else
//else call the same function with the value - 1
return b * fact(b-1);
}
}


Enter the number:
5

Factorial of the number is: 120

Wednesday, 16 October 2013

sending email using spring mvc

Required Jars:

commons-fileupload-1.2.2.jar
commons-io-2.3.jar
commons-logging-1.1.1.jar
mail.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-context-support-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
spring-web-3.2.0.RELEASE.jar
spring-webmvc-3.2.0.RELEASE.jar

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SendingMail</display-name>
<servlet>
<servlet-name>SpringController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>EmailForm.jsp</welcome-file>
</welcome-file-list>
</web-app>


spring-mvc.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.karthik.spring" />

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="xxxx@gmail.com" />
<property name="password" value="xxxx" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->

</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">Error</prop>
</props>
</property>
</bean>
</beans>

SendEmailWithAttachment Controller:

package com.karthik.spring;

import java.io.IOException;
import java.io.InputStream;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping("/sendEmail.do")
public class SendEmailWithAttachment {
@Autowired
private JavaMailSender mailSender;

@RequestMapping(method = RequestMethod.POST)
public String sendEmail(HttpServletRequest request,
final @RequestParam CommonsMultipartFile attachFile) {

// reads form input
final String emailTo = request.getParameter("mailTo");
final String subject = request.getParameter("subject");
final String yourmailid = request.getParameter("yourmail");
final String message = request.getParameter("message");

// for logging
System.out.println("emailTo: " + emailTo);
System.out.println("subject: " + subject);
System.out.println("Your mail id is: "+yourmailid);
System.out.println("message: " + message);
System.out.println("attachFile: " + attachFile.getOriginalFilename());

mailSender.send(new MimeMessagePreparator() {

@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper messageHelper = new MimeMessageHelper(
mimeMessage, true, "UTF-8");
messageHelper.setTo(emailTo);
messageHelper.setSubject(subject);
messageHelper.setReplyTo(yourmailid);
messageHelper.setText(message);
// determines if there is an upload file, attach it to the e-mail
String attachName = attachFile.getOriginalFilename();
if (!attachFile.equals("")) {

messageHelper.addAttachment(attachName, new InputStreamSource() {
@Override
public InputStream getInputStream() throws IOException {
return attachFile.getInputStream();
}
});
}
}

});

return "Result";
}
}


EmailForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC - Email</title>
</head>
<body>
<center>
<h1>Send e-mail with attachment</h1>
<form method="post" action="sendEmail.do" enctype="multipart/form-data">
<table border="0" width="80%">
<tr>
<td>Email To:</td>
<td><input type="text" name="mailTo" size="45" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" size="45" /></td>
</tr>
<tr>
<td>Your mail ID:</td>
<td><input type="text" name="yourmail" size="45" /></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea cols="50" rows="10" name="message"></textarea></td>
</tr>
<tr>
<td>Attach file:</td>
<td><input type="file" name="attachFile" size="60" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Send E-mail" />
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

Error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
</head>
<body>
<center>
<h2>Sorry,the email was not sent because of the following error</h2>
<h3>${exception.message}</h3>
</center>
</body>
</html>


Result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Send mail Result</title>
</head>
<body>
<center>
<h2>Success</h2>
</center>
</body>

</html>

Hibernate Required jars

http://sourceforge.net/projects/hibernate/files/hibernate4/

E:\Java\hibernate-distribution-3.6.10.Final\hibernate3.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\required\antlr-2.7.6.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\required\commons-collections-3.1.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\required\dom4j-1.6.1.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\required\javassist-3.12.0.GA.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\required\jta-1.1.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\required\slf4j-api-1.6.1.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\jpa\hibernate-jpa-2.0-api-1.0.1.Final.jar
E:\Java\hibernate-distribution-3.6.10.Final\lib\bytecode\javassist\javassist-3.12.0.GA.jar

Monday, 27 May 2013

interface in java

An interface in the Java Programming language is an abstract type that is used to specify an interface(in the generic sense of the term) that classes must implement.
Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final).
An interface never contain method definitions.
Interfaces cannot be instantiated, but rather are implemented.
A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface.
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object(the root class of the Java type system); multiple classes of classes is not allowed.
A Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
Example:

Program:
interface B {
}
interface C extends B {
}
interface D extends B, C {
}
interface E {
}
class Simple implements B, C, D {
}
public class A {
public static void main(String[] args) {
}
}
Which is not possible in interface?
We cant implement an interface with interface
interface B {
}
interface C implements B {
}
CTE--->Compile Time Error

CTE:Syntax error on token "implements", extends expected

interface B {
public void study(){
}
}
CTE:Abstract methods do not specify a body
Remove method body

Program:
interface B {
public void study();
}

class Simple implements B {

@Override
public void study() {
System.out.println("Hai i am the impl for study method in interface B");
}
}
public class A {
public static void main(String[] args) {
B b=new B();
}
}
Cannot instantiate the type B

Program:
interface B {
public void study();
}
class Simple implements B {
}
public class A {
public static void main(String[] args) {
Simple s = new Simple();
s.study();
}
}
--->the type Simple must implement the inherited abstract method B.study()
Solution:
interface B {
public void study();
}
class Simple implements B {
@Override
public void study() {
System.out.println("Hai i am in impl for study method in interface B");
}
}
public class A {
public static void main(String[] args) {
Simple s = new Simple();
s.study();
}
}
O/P:Hai i am in impl for study method in interface B

Major Points in interface:
possible:
interface extends interface
interface extends interface1,interface2
class implements interface
class implements interface1,interface2
interface B {
}
interface C extends B {
}
interface D extends B, C {
}
interface E {
}
class Sam implements B{
}
class Simple implements B,C{
}
public class A {
public static void main(String[] args) {
}

}