Java J2ME JSP J2EE Servlet Android

Captcha with java

A simple CAPTCHA generating java class


import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Captcha {
public static Color TEXT_COLOR = Color.white;
public static Color CIRCLE_COLOR = new Color(160,160,160);
public static int NUMBER_OF_CHARACTERS = 6;
public static Color BACKGROUND_COLOR = Color.red;
public static String SESSION_NAME = "captchaText";

public void buildCapcha(HttpServletRequest request, HttpServletResponse response){
response.setContentType("image/jpg");

try {
Color textColor = TEXT_COLOR;
Color circleColor = CIRCLE_COLOR;
Font textFont = new Font("Arial", Font.PLAIN, 24);
int charsToPrint = NUMBER_OF_CHARACTERS;
int width = request.getParameter("width") != null ? Integer.parseInt(request.getParameter("width")) : 150;
int height = request.getParameter("height") != null ? Integer.parseInt(request.getParameter("height")) : 80;
int circlesToDraw = 4;
float horizMargin = 20.0f;
float imageQuality = 0.95f; // max is 1.0 (this is for jpeg)
double rotationRange = 0.7; // this is radians
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics2D g = (Graphics2D) bufferedImage.getGraphics();

//Draw an oval
g.setColor(BACKGROUND_COLOR);
g.fillRect(0, 0, width, height);

// lets make some noisey circles
g.setColor(circleColor);
for ( int i = 0; i < circlesToDraw; i++ ) {
int circleRadius = (int) (Math.random() * height / 2.0);
int circleX = (int) (Math.random() * width - circleRadius);
int circleY = (int) (Math.random() * height - circleRadius);
g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
}

g.setColor(textColor);
g.setFont(textFont);

FontMetrics fontMetrics = g.getFontMetrics();
int maxAdvance = fontMetrics.getMaxAdvance();
int fontHeight = fontMetrics.getHeight();

// i removed 1 and l and i because there are confusing to users...
// Z, z, and N also get confusing when rotated
// 0, O, and o are also confusing...
// lowercase G looks a lot like a 9 so i killed it
// this should ideally be done for every language...
// i like controlling the characters though because it helps prevent confusion
String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy23456789";
char[] chars = elegibleChars.toCharArray();

float spaceForLetters = -horizMargin * 2 + width;
float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);

StringBuffer finalString = new StringBuffer();

for ( int i = 0; i < charsToPrint; i++ ) {
double randomValue = Math.random();
int randomIndex = (int) Math.round(randomValue * (chars.length - 1));
char characterToShow = chars[randomIndex];
System.out.println(characterToShow);
finalString.append(characterToShow);

// this is a separate canvas used for the character so that
// we can rotate it independently

int charWidth = fontMetrics.charWidth(characterToShow);
int charDim = Math.max(maxAdvance, fontHeight);
int halfCharDim = (int) (charDim / 2);

BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
Graphics2D charGraphics = charImage.createGraphics();
charGraphics.translate(halfCharDim, halfCharDim);
double angle = (Math.random() - 0.5) * rotationRange;
charGraphics.transform(AffineTransform.getRotateInstance(angle));
charGraphics.translate(-halfCharDim,-halfCharDim);
charGraphics.setColor(textColor);
charGraphics.setFont(textFont);

int charX = (int) (0.5 * charDim - 0.5 * charWidth);
charGraphics.drawString("" + characterToShow, charX,
(int) ((charDim - fontMetrics.getAscent())
/ 2 + fontMetrics.getAscent()));

float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
int y = (int) ((height - charDim) / 2);
//System.out.println("x=" + x + " height=" + height + " charDim=" + charDim + " y=" + y + " advance=" + maxAdvance + " fontHeight=" + fontHeight + " ascent=" + fontMetrics.getAscent());
g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);

charGraphics.dispose();
}

//Write the image as a jpg
Iterator iter = ImageIO.getImageWritersByFormatName("JPG");
if( iter.hasNext() ) {
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(imageQuality);
writer.setOutput(ImageIO.createImageOutputStream(response.getOutputStream()));
IIOImage imageIO = new IIOImage(bufferedImage, null, null);
writer.write(null, imageIO, iwp);
} else {
throw new RuntimeException("no encoder found for jsp");
}

// let's stick the final string in the session
request.getSession().setAttribute(SESSION_NAME, finalString.toString());

g.dispose();
} catch (IOException ioe) {
throw new RuntimeException("Unable to build image" , ioe);
}
}

}

Sending email using SSL connection : Java

This is a demo class to send email using SSL connection with email server..



import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

import java.util.Date;
import java.util.Properties;


public class SimpleSSLMail {

private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT = 465;
private static final String SMTP_AUTH_USER = "abc@gmail.com";
private static final String SMTP_AUTH_PWD = "1234567";

public static void main(String[] args) throws Exception{
new SimpleSSLMail().test();
}

public void test() throws Exception{
Properties props = new Properties();

props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", SMTP_HOST_NAME);
props.put("mail.smtps.auth", "true");
// props.put("mail.smtps.quitwait", "false");

Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing SMTP-SSL");
message.setContent("This is a test", "text/plain");

message.setFrom(new InternetAddress("sharifhome@smile.com.bd"));
message = attachment(message,"This is a test", "D:\\user.txt");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("sharifruet@smile.com.bd"));

transport.connect
(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
MimeMessage attachment(MimeMessage msg, String text, String file) throws MessagingException{
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(text);

// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();

// attach the file to the message
FileDataSource fds = new FileDataSource(file);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());

// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);

// add the Multipart to the message
msg.setContent(mp);

// set the Date: header
msg.setSentDate(new Date());
return msg;
}
}

A Java class to get Bangla Calendar from Gregorian Calendar : Java

Here is a class that can be used as Gregorian to Bangla Calendar conversion..



import java.util.Calendar;

public class BanglaCalendar {
public static int BAISAKH = 1;
public static int JAISTHA = 2;
public static int ASARH = 3;
public static int SRABAN = 4;
public static int VADRA = 5;
public static int ASHWIN = 6;
public static int KARTIK = 7;
public static int AGRAHAYAN = 8;
public static int POUSH = 9;
public static int MAGHH = 10;
public static int FALGUN = 11;
public static int CHAITRA = 12;

Calendar calendar = null;
int day;
int month;
int year;
public BanglaCalendar(Calendar cal){
this.calendar = cal;
process();
}

public int getDay(){
return day;
}
public int getMonth(){
return month;
}
public int getYear(){
return year;
}
private void process(){
int ddd = calendar.get(Calendar.DAY_OF_YEAR);
year = calendar.get(Calendar.YEAR);
if(isLeapYear(year)){
year = year-593;
if(ddd<115)
year--;
if(ddd>=115 && ddd<=145){
month = BAISAKH;
day = ddd - 114;
}
else if(ddd>=146 && ddd<=176){
month = JAISTHA;
day = ddd - 145;
}
else if(ddd>=177 && ddd<=207){
month = ASARH;
day = ddd - 176;
}
else if(ddd>=208 && ddd<=238){
month = SRABAN;
day = ddd - 207;
}
else if(ddd>=239 && ddd<=269){
month = VADRA;
day = ddd - 238;
}
else if(ddd>=270 && ddd<=299){
month = ASHWIN;
day = ddd - 269;
}
else if(ddd>=300 && ddd<=329){
month = KARTIK;
day = ddd - 299;
}
else if(ddd>=330 && ddd<=359){
month = AGRAHAYAN;
day = ddd - 329;
}
else if(ddd>=360 && ddd<=23){
month = POUSH;
day = ddd - 359;
}
else if(ddd>=24 && ddd<=53){
month = MAGHH;
day = ddd - 23;
}
else if(ddd>=54 && ddd<=84){
month = FALGUN;
day = ddd - 53;
}
else if(ddd>=85 && ddd<=114){
month = CHAITRA;
day = ddd - 84;
}
}else{
year = year-593;
if(ddd<114)
year--;
if(ddd>=114 && ddd<=144){
month = BAISAKH;
day = ddd - 113;
}
else if(ddd>=145 && ddd<=175){
month = JAISTHA;
day = ddd - 144;
}
else if(ddd>=176 && ddd<=206){
month = ASARH;
day = ddd - 175;
}
else if(ddd>=207 && ddd<=237){
month = SRABAN;
day = ddd - 206;
}
else if(ddd>=238 && ddd<=268){
month = VADRA;
day = ddd - 237;
}
else if(ddd>=269 && ddd<=298){
month = ASHWIN;
day = ddd - 268;
}
else if(ddd>=299 && ddd<=328){
month = KARTIK;
day = ddd - 298;
}
else if(ddd>=329 && ddd<=358){
month = AGRAHAYAN;
day = ddd - 328;
}
else if(ddd>=359 && ddd<=23){
month = POUSH;
day = ddd - 358;
}
else if(ddd>=24 && ddd<=53){
month = MAGHH;
day = ddd - 24;
}
else if(ddd>=54 && ddd<=83){
month = FALGUN;
day = ddd - 53;
}
else if(ddd>=84 && ddd<=113){
month = CHAITRA;
day = ddd - 83;
}
}
}
public static void main(String args[]){
BanglaCalendar bc = new BanglaCalendar(Calendar.getInstance());
System.out.println(bc.getDay());
System.out.println(bc.getMonth());
System.out.println(bc.getYear());
}

/**
* Is the given year a year year in the SPAWAR Calendar?
* @param yyyy the year
* @return true if the year is a leap year
*/
public static final boolean isLeapYear ( int yyyy )
{
if ( yyyy < 0 ) return( yyyy + 1 ) % 4 == 0;
if ( yyyy < 1582 ) return yyyy % 4 == 0;
if ( yyyy % 4 != 0 ) return false;
if ( yyyy % 100 != 0 ) return true;
if ( yyyy % 400 != 0 ) return false;
if ( yyyy % 3200 != 0 ) return true;
return false;
}

}

Simple JDBC Connection: Java

Here is an example to Connect to Oracle database using jdbc driver. In the same way we can connect with any database with appropriate JDBC driver for that database

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Connector {
private String user = "scott";
private String password = "tiget";
private String connectionString = "jdbc:oracle:thin:@localhost:1521:orcl";
private String driverClass = "oracle.jdbc.driver.OracleDriver";

public Connector(){
}
public Connection connect(){
Connection connn = null;
try {
Class.forName(driverClass).newInstance();
connn = DriverManager.getConnection( connectionString, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
return connn;
}
}

HTTP / URL Reading: Java

We can read url HTTP request in the following way efficiently.


public static String readURL(URL url) throws MalformedURLException, IOException{
String str= "";
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
str += inputLine+"\n";
in.close();
return str;
}

Send email: Java

Java has a separate package for email that is java mail api. We can use this api to send and receive emails using java. Here is a java method to send email using java mail api.

public static void sendMail(String from, String to, String subject,
String textBody, String htmlBody, String host)
throws AddressException, MessagingException {
Properties props = System.getProperties();

props.put("mail.smtp.host", host);

Session session = Session.getInstance(props, null);

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setText(textBody);

message.setContent(htmlBody, "text/html");

Transport.send(message);
}

I think it'll help you. If you have any question on java email just add as comment. I'll try to answer..