Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, April 9, 2010

ODBC System DSN List Using Java

/**
* OdbcSystemDSNListUtil.java
*/
package odbc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

/**
* @author Nimish
* Apr 9, 2010
*/
public class OdbcSystemDSNListUtil {

public static Set getODBCSystemDNS() {
String PERSONAL_FOLDER_CMD ="HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBC.INI";
String []command = new String[] {"reg","query",PERSONAL_FOLDER_CMD};
Set dsnList = new HashSet();
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
String dsn = "";
while((dsn=stream.readLine())!=null){
if(dsn.indexOf(PERSONAL_FOLDER_CMD+"\\") != -1)
dsnList.add(dsn.substring(dsn.lastIndexOf("\\")+1));
}

} catch (IOException e) {
e.printStackTrace();
}
return dsnList;
}

public static void main(String[] args) {
Set dsnList = getODBCSystemDNS();
for(String dsn:dsnList) {
System.out.println("dsn name: "+ dsn);
}
}
}

Windows Tasklist using Java

package test.process;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ProcessManager {
public static void main(String[] args) {
List testList = ProcessManager.getTaskList();
for(Task task:testList){
System.out.println(task.getImageName()+" : "+task.getMemoryUsage());
}
}

public static List getTaskList(){
List tasklist = new ArrayList();
try {
String []command = new String[] {"tasklist","/fo","csv","/nh"};
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader
(new InputStreamReader(process.getInputStream()));
String line ="";
while ((line = input.readLine()) != null) {
if(!line.equals("")) {
line = line.replaceAll("\"","");
Task task = new Task();
String[] taskAttributes = null;
try {
taskAttributes = line.split(",");
} catch (RuntimeException e) {
e.printStackTrace();
}
task.setImageName(taskAttributes[0]==null?"":taskAttributes[0]);
task.setProcessID(taskAttributes[1]==null?"":taskAttributes[1]);
task.setSessionName(taskAttributes[2]==null?"":taskAttributes[2]);
task.setSessionNumber(taskAttributes[3]==null?"":taskAttributes[3]);
try {
task.setMemoryUsage(taskAttributes[4]==null?"":taskAttributes[4]+taskAttributes[5]==null?"":taskAttributes[5]);
} catch (RuntimeException e) {
task.setMemoryUsage(taskAttributes[4]==null?"":taskAttributes[4]);
}
tasklist.add(task);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return tasklist;
}
}

Saturday, February 20, 2010

Way2SMS Source Exposed

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Vector;

public class SMS {
public static void send(String uid, String pwd, String phone, String msg)
throws IOException {
if ((uid == null) || (uid.length() == 0)) {
throw new IllegalArgumentException("User ID should be present.");
}
uid = URLEncoder.encode(uid, "UTF-8");

if ((pwd == null) || (pwd.length() == 0)) {
throw new IllegalArgumentException("Password should be present.");
}
pwd = URLEncoder.encode(pwd, "UTF-8");

if ((phone == null) || (phone.length() == 0)) {
throw new IllegalArgumentException(
"At least one phone number should be present.");
}
if ((msg == null) || (msg.length() == 0)) {
throw new IllegalArgumentException("SMS message should be present.");
}
msg = URLEncoder.encode(msg, "UTF-8");

Vector numbers = new Vector();

if (phone.indexOf(59) >= 0) {
String[] pharr = phone.split(";");
for (String t : pharr)
try {
numbers.add(Long.valueOf(t));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(
"Give proper phone numbers.");
}
} else {
try {
numbers.add(Long.valueOf(phone));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Give proper phone numbers.");
}
}

if (numbers.size() == 0) {
throw new IllegalArgumentException(
"At least one proper phone number should be present to send SMS.");
}
String temp = "";
String content = "username=" + uid + "&password=" + pwd;
URL u = new URL("http://wwwa.way2sms.com/auth.cl");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setDoOutput(true);
uc
.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
uc.setRequestProperty("Content-Length", String
.valueOf(content.length()));
uc.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestProperty("Referer", "http://wwwg.way2sms.com//entry.jsp");
uc.setRequestMethod("POST");
uc.setInstanceFollowRedirects(false);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(uc
.getOutputStream()), true);
pw.print(content);
pw.flush();
pw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(uc
.getInputStream()));
while ((temp = br.readLine()) != null) {
System.out.println(temp);
}
String cookie = uc.getHeaderField("Set-Cookie");

u = null;
uc = null;
for (Iterator localIterator = numbers.iterator(); localIterator
.hasNext();) {
long num = ((Long) localIterator.next()).longValue();

content = "custid=undefined&HiddenAction=instantsms&Action=custfrom450000&login=&pass=&MobNo="
+ num
+ "&textArea="
+ msg;
u = new URL("http://wwwa.way2sms.com/FirstServletsms?custid=");
uc = (HttpURLConnection) u.openConnection();
uc.setDoOutput(true);
uc
.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
uc.setRequestProperty("Content-Length", String.valueOf(content
.getBytes().length));
uc.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestProperty("Cookie", cookie);
uc.setRequestMethod("POST");
uc.setInstanceFollowRedirects(false);
pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()),
true);
pw.print(content);
pw.flush();
pw.close();
br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ((temp = br.readLine()) != null)
;
br.close();
u = null;
uc = null;
}

u = new URL("http://wwwa.way2sms.com/jsp/logout.jsp");
uc = (HttpURLConnection) u.openConnection();
uc
.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestProperty("Cookie", cookie);
uc.setRequestMethod("GET");
uc.setInstanceFollowRedirects(false);
br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ((temp = br.readLine()) != null)
;
br.close();
u = null;
uc = null;
}
}

best web hosting plan providers-cochin/kerala

cellphone application developers Kerala/India

Monday, December 7, 2009

send SMS using way2sms updated by sujith and joji

// Send SMS to each of the phone numbers
u = null; uc = null;
for (long num : numbers)
{
content = "HiddenAction=instantsms&login=&pass=&custid=undefined&MobNo=" + num + "&textArea=" + msg;


change this content part in previous post by

content = "custid=undefined&HiddenAction=instantsms&Action=custfrom50000&login=&pass=&MobNo=" + phone + "&textArea=" + msg+"&qlogin1=Gmail+Id&qpass1=******&gincheck=on&ylogin1=Yahoo+Id&ypass1=******&yincheck=on";

cellphone application providers cochin kerala

economic web hosting web development plans kerala cochin

Monday, September 14, 2009

Send Email from Java program using apache commons email

This api allows you to send email from your java progra. You can download the API from the folowing site
Download


Here I am giving you a sample code which lets you to send email fromyuor system

SimpleEmail email = new SimpleEmail();
email.setHostName("localhost");
try {
email.addTo("nimishth@gmail.com","Nimish T");
email.setFrom("admin@localhost");
email.setSubject("test");
email.setMsg("test message");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}

first of all you have to include the downloaded library into u'r class path
after that write a java class and create an instarnce of SimpleEmail
then you have to set the set the host name, from address and to address
after that just add the message you want to send and and set a subject for the
perticular instance of the SimpleEmail class. here after you can call the sen method
which will send the email to the to address you have specified here its nimishth@gmail.com

If u want to send the mail using oter hservice providers such as gmail or oters
u have to change the the host name by the smtp address of the service provider you want to use
but there need authentication also
ie
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
try {
email.addTo("nimishth@gmail.com","Nimish T");
email.setFrom("your email address");
email.setAuthentication("yoru email address", "your password");
email.setTLS(true);
//465 or 587 which is the port number here
email.setSmtpPort(587);
email.setSubject("Test");
email.setMsg("test");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}

You will get more details about the mail such as attachment, html mail etc from
User Guide

Tuesday, August 25, 2009

Send Mail Using JAVA MAIL API

The JavaMail API is a set of abstract APIs that model a mail system. The API provides a platform independent and protocol independent framework to build Java technology based email client applications. The JavaMail API provides facilities for reading and sending email. Service providers implement particular protocols. Several service providers are included with the JavaMail API package; others are available separately. The JavaMail API is implemented as a Java optional package that can be used on JDK 1.4 and later on any operating system. The JavaMail API is also a required part of the Java Platform, Enterprise Edition (Java EE).
You can download Java Mail API from http://java.sun.com/products/javamail/downloads/

An Example program for sending mail using JAVA Mail
------------------------------------------------------------------
Before run the example code please goes through steps given below

1. download java mail API. and add to Classpath
2. Create one Gmail Account ( in this example we use google mail server as server)
3. edit the code "USERNAME = new gmail id" and PASSWORD = "password of new gmail id";
4. edit formAddress and to address.

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendMail {

public static final String MAIL_SERVER = "smtp.gmail.com";
public static final String USERNAME = "servermail@gmail.com";
public static final String PASSWORD = "password";

public static void main(String[] args) {
try {
fromAddress = "fromaddress@gmail.com";
String toAddress = "toaddress@gmail.com";
String subject = "This is a test Message";
String message = "Hello Hows u?";

Properties properties = System.getProperties();
properties.put("mail.smtps.host", MAIL_SERVER);
properties.put("mail.smtps.auth", "true");

Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(fromAddress));
msg.addRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
msg.setText(message);

Transport tr = session.getTransport("smtps");
tr.connect(MAIL_SERVER, USERNAME, PASSWORD);
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
} catch (AddressException ex) {
System.out.println(ex.getMessage());
} catch (MessagingException ex) {
System.out.println(ex.getMessage());
}
}
}

webdevelopers webhosting application development-IT solutions Cochin Kerala

Wednesday, July 15, 2009

way2sms API

Send free sms from your application using java api.
You have to create an account in way2sms
Implementaion details are alredy published in codeglobe
Try it at your own risk
Download



source

Yahoo Astrology API Java

Impelmentaion details are in codeglobe.blogspot.com
Download

Tuesday, July 14, 2009

Get mobile directories/roots using J2ME

//try this code

Enumeration roots = FileSystemRegistry.listRoots();
while(roots.hasMoreElements()){
//here you can do your actions on the roots-
//use 'roots.nextElement()' to get the root/directory
//for eg you can add these directories into a choice group.
//To get the string value of the diectory use
//'String=roots.nextElement().toString();'
}

java cellphone software developers cochin

website hosting development cochin kerala

Monday, July 13, 2009

Get your horo scope

It's a small program which can be used for display horoscope in u'r web site or application try this

package sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Astrology {

/**
* This method will return your horoscope according to the date passed as argument
* @param date DD-MM-YYYY the date of birth
* @return : string
* @throws Exception Invalid Date format
*/
public static String getYourHoroscope(String date) throws Exception{
Pattern datePattern = Pattern.compile("(\\d{2})-(\\d{2})-(\\d{4})");
Matcher dateMatcher = datePattern.matcher(date);
if(!dateMatcher.matches())
throw new Exception("Invalid date format");
String yourHoroscope="";
Hashtable horoscope=new Hashtable();
horoscope=getHoroscope();
int day=0,month=0;
day=Integer.parseInt(dateMatcher.group(1));
month=Integer.parseInt(dateMatcher.group(2));
System.out.println("month:"+month);
System.out.println("day:"+day);
if(((month==12)&&(day>=21))||((month==1)&&(day<=19))){
yourHoroscope=horoscope.get("capricon");
} else if(((month==1)&&(day>=20))||((month==2)&&(day<=18))){
yourHoroscope=horoscope.get("aquarius");
} else if(((month==2)&&(day>=19))||((month==3)&&(day<=20))){
yourHoroscope=horoscope.get("pisces");
} else if(((month==3)&&(day>=21))||((month==4)&&(day<=19))){
yourHoroscope=horoscope.get("arius");
} else if(((month==4)&&(day>=20))||((month==5)&&(day<=20))){
yourHoroscope=horoscope.get("taurus");
} else if(((month==5)&&(day>=21))||((month==6)&&(day<=21))){
yourHoroscope=horoscope.get("gemini");
} else if(((month==6)&&(day>=22))||((month==7)&&(day<=22))){
yourHoroscope=horoscope.get("cancer");
} else if(((month==7)&&(day>=23))||((month==8)&&(day<=22))){
yourHoroscope=horoscope.get("leo");
} else if(((month==8)&&(day>=23))||((month==9)&&(day<=22))){
yourHoroscope=horoscope.get("virgo");
} else if(((month==9)&&(day>=23))||((month==10)&&(day<=22))){
yourHoroscope=horoscope.get("libra");
} else if(((month==10)&&(day>=23))||((month==11)&&(day<=21))){
yourHoroscope=horoscope.get("scorpio");
} else if(((month==11)&&(day>=22))||((month==12)&&(day<=21))){
yourHoroscope=horoscope.get("sagittarius");
}
return yourHoroscope;
}

/**
* This method used to collect horoscope from the web site
* @return return a hash table
*/
public static Hashtable getHoroscope(){
URL url=null;
Hashtable horoscope=new Hashtable();
try {
url = new URL("http","192.168.0.6",3128,"http://www.sxmsms.com/horoscope.aspx");
HttpURLConnection uc=null;
uc = (HttpURLConnection) url.openConnection();
BufferedReader br=null;
br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String temp="";
StringBuffer data=new StringBuffer();
while ( (temp = br.readLine()) != null ) {
data.append(temp);
}
String content=data.toString();
int startIndex=0;
int endIndex=0;
if(content.indexOf("
startIndex=content.indexOf("
content=content.substring(startIndex);
endIndex=content.indexOf("
");
content=content.substring(0,endIndex);
content=content.substring(content.indexOf("")+8,content.lastIndexOf("")+4);
}
String []strs=content.split("");
String key="";
String msg="";
for(int i=0;i key=strs[i].substring(0,strs[i].indexOf("
")).toLowerCase();
msg=strs[i].substring(strs[i].indexOf("SMS\">")+5,strs[i].lastIndexOf(""));
horoscope.put(key, msg);
}
} catch (Exception e) {
e.printStackTrace();
}
return horoscope;
}


public static void main(String[] args)throws Exception {
System.out.println(getYourHoroscope("10-09-1983"));
}
}

Saturday, May 9, 2009

Simple Program to parse a csv file

//Simple program to parse the csv file in Java
package util;
import java.io.*;

public class CsvFileAction {
public static void main(String args[]){
String fName = "//root//mycsv.csv";
String thisLine;
int count=0;
try{
FileInputStream fis = new FileInputStream(fName);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
int i=0;
while ((thisLine = br.readLine()) != null)
{
String strar[] = thisLine.split(",");
for(int j=0;j {
System.out.println(strar[j]);
}
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}

MAC Address onLinux PC from Java Application

package util;
import java.io.*;

public class SystemAttributes {
public String getMacAddress()throws Exception{
String retStr="";
Runtime rt=Runtime.getRuntime();
Process proc=rt.exec("ifconfig");
BufferedReader br=new BufferedReader(new InputStreamReader(proc.getInputStream()));
retStr=br.readLine();
retStr=retStr.substring(retStr.indexOf("HWaddr")+7);
return retStr;
}

public static void main(String args[])throws Exception{
System.out.print(new SystemAttributes().getMacAddress());
}
}

Send Java Mail

download the
activation.jar
mail.jar files and put it into u'r lib
/**
* SendApp.java
* Created on Mar 12, 2009 6:08:04 AM
*/
package mail;
import java.util.Date;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendApp {

/**
* Using this function u can send mail
* @param smtpHost: u have to specify u'r smtp host here
* @param smtpPort: the smtp port number for gmail its 587
* @param from: from address
* @param urPassword: password of the sender for authentication
* @param to: to address
* @param subject: subject of the mail
* @param content: the message content
* @throws AddressException
* @throws MessagingException
*/
public static void send(String smtpHost, int smtpPort,
String from, String urPassword,String to,
String subject, String content)
throws AddressException, MessagingException {

// Create a mail session
java.util.Properties props = new java.util.Properties();
props=System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtps.auth", "true");
Session session=Session.getInstance(props,null);
session.setDebug(true);

// Construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
msg.setSentDate(new Date());
Transport tr = null;
tr = session.getTransport("smtp");
tr.connect(smtpHost,smtpPort,from, urPassword);
tr.sendMessage(msg, msg.getAllRecipients());

}

public static void main(String[] args) throws Exception {
// Send a test message
String smtpHost="smtp.gmail.com";
int smtpPort=587;
String from="test@testmail.com";
String urPasswd="testpass";
String to="test@gmail.com";
String subject="Tested and working fine";
String message="Hello, \n\n How are you ?";
send(smtpHost, smtpPort,from,urPasswd,to,subject,message );
}
}

send SMS using u'y wey2sms account (Java)

This program help you to send sms using way2sms account

Its not written by by me I have just modified it


smsconfig.properties
user=way2sms username
password=way2sms password
proxy_enabled=true/false
proxy_host=if true ip of the proxy
proxy_port=port number of proxy
protocol=http

/**
* SMSConfig.java
* Created on Mar 11, 2009 6:36:23 AM
*/
package sms;

import java.util.ResourceBundle;

/**
* @author Nimish T
*
*/
public class SMSConfig {

/**
*
*/
public SMSConfig() {
// TODO Auto-generated constructor stub
}
private static ResourceBundle resourceBundle;
public static String USERNAME;
public static String PASSWORD;
public static boolean PROXY;
public static String PROXY_HOST;
public static int PROXY_PORT;
public static String PROTOCOL;
static {
try {
resourceBundle=ResourceBundle.getBundle("sms.smsconfig");
init();
} catch (Exception e) {
//e.getMessage();
e.printStackTrace();
}
}
private static void init(){
USERNAME=resourceBundle.getString("user");
PASSWORD=resourceBundle.getString("password");
PROXY=Boolean.valueOf(resourceBundle.getString("proxy_enabled"));
if(PROXY){
PROXY_HOST=resourceBundle.getString("proxy_host");
PROXY_PORT=Integer.parseInt(resourceBundle.getString("proxy_port"));
PROTOCOL=resourceBundle.getString("protocol");
}

}
}



/**
* SMS.java
* Created on Mar 10, 2009 7:37:35 PM
*/
package sms;

/**
* @author Nimish T
*
*/

import java.io.*;
import java.net.*;
import java.util.Vector;

public class SMS
{
public static void send(String uid, String pwd, String phone, String msg) throws IOException {

if (uid == null || 0 == uid.length())
throw new IllegalArgumentException("User ID should be present.");
else
uid = URLEncoder.encode(uid, "UTF-8");

if (pwd == null || 0 == pwd.length())
throw new IllegalArgumentException("Password should be present.");
else
pwd = URLEncoder.encode(pwd, "UTF-8");

if (phone == null || 0 == phone.length())
throw new IllegalArgumentException("At least one phone number should be present.");

if (msg == null || 0 == msg.length())
throw new IllegalArgumentException("SMS message should be present.");
else
msg = URLEncoder.encode(msg, "UTF-8");

Vector numbers = new Vector();
String pharr[];
if (phone.indexOf(';') >= 0) {
pharr = phone.split(";");
for (String t : pharr) {
try
{
numbers.add(Long.valueOf(t));
}
catch (NumberFormatException ex)
{
throw new IllegalArgumentException("Give proper phone numbers.");
}
}
} else {
try
{
numbers.add(Long.valueOf(phone));
}
catch (NumberFormatException ex)
{
throw new IllegalArgumentException("Give proper phone numbers.");
}
}

if (0 == numbers.size())
throw new IllegalArgumentException("At least one proper phone number should be present to send SMS.");

/*==================================================================*/

// Login
String temp = "";
String content = "username=" + uid + "&password=" + pwd + "&q=Deepika%20Padukone%20Photo%20Gallery";
URL u=null;
if(SMSConfig.PROXY){
u = new URL(SMSConfig.PROTOCOL,SMSConfig.PROXY_HOST,SMSConfig.PROXY_PORT,"http://wwwd.way2sms.com/auth.cl");
} else {
u = new URL("http://wwwd.way2sms.com/auth.cl");
}
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
uc.setRequestProperty("Content-Length", String.valueOf(content.length()));
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestMethod("POST");
uc.setInstanceFollowRedirects(false); // very important line :)
PrintWriter pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true);
pw.print(content);
pw.flush();
pw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ( (temp = br.readLine()) != null ) {}
String cookie = uc.getHeaderField("Set-Cookie");

// Send SMS to each of the phone numbers
u = null; uc = null;
for (long num : numbers)
{
content = "HiddenAction=instantsms&login=&pass=&custid=undefined&MobNo=" + num + "&textArea=" + msg;
if(SMSConfig.PROXY){
u = new URL(SMSConfig.PROTOCOL,SMSConfig.PROXY_HOST,SMSConfig.PROXY_PORT,"http://wwwd.way2sms.com/FirstServletsms?custid=");
} else {
u = new URL("http://wwwd.way2sms.com/FirstServletsms?custid=");
}
uc = (HttpURLConnection) u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
uc.setRequestProperty("Content-Length", String.valueOf(content.length()));
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestProperty("Cookie", cookie);
uc.setRequestMethod("POST");
uc.setInstanceFollowRedirects(false);
pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true);
pw.print(content);
pw.flush();
pw.close();
br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ( (temp = br.readLine()) != null ) {}
br.close();
u = null;
uc = null;
}

// Logout
if(SMSConfig.PROXY){
u = new URL(SMSConfig.PROTOCOL,SMSConfig.PROXY_HOST,SMSConfig.PROXY_PORT,"http://wwwd.way2sms.com/jsp/logout.jsp");
} else {
u = new URL("http://wwwd.way2sms.com/jsp/logout.jsp");
}
uc = (HttpURLConnection) u.openConnection();
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestProperty("Cookie", cookie);
uc.setRequestMethod("GET");
uc.setInstanceFollowRedirects(false);
br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ( (temp = br.readLine()) != null ) {}
br.close();
u = null;
uc = null;
}
}


//Mail send example
public class SMSSender{
public static void main(String a[]){
SMS.send(SMSConfig.USERNAME, SMSConfig.PASSWORD, "9496340776", "My First SMS");
}
}



cellphone application developers cochin kerala
website hosting development kochi kerala

CurrencyConverter API

/*
* Copyright (c) 2007 Thomas Knierim
* http://www.thomasknierim.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package etudes;

import java.net.*;
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.text.*;
import java.util.*;

/**
* CurrencyConverter provides an API for accessing the European Central Bank's
* (ECB) foreign exchange rates. The published ECB rates contain exchange rates
* for approx. 35 of the world's major currencies. They are updated daily at
* 14:15 CET. These rates use EUR as reference currency and are specified with a
* precision of 1/10000 of the currency unit (one hundredth cent). See:
*
* http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
*
* The convert() method performs currency conversions using either double values
* or 64-bit long integer values. Long values are preferred in order to avoid
* problems associated with floating point arithmetics. A local cache file is
* used for storing exchange rates to reduce network latency. The cache file is
* updated automatically when new exchange rates become available. It is
* created/updated the first time a call to convert() is made.
*
* @version 1.0 2008-16-02
* @author Thomas Knierim
*
*/
public final class CurrencyConverter {

/** singleton instance */
private static CurrencyConverter instance = null;

/** URL for XML file containing EGB's daily exchange rates */
private final String ecbRatesURL = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";

/** local cache file */
transient private File cacheFile = null;

/** name of local cache file */
private String cacheFileName = null;

/** exchange rate collection */
private HashMap fxRates = new HashMap(40);

/** publishing date */
private Date referenceDate = null;

/** internal error message */
private String lastError = null;

/** singleton without subclassing */
private CurrencyConverter() {}

/**
* Returns a singleton instance of CurrencyConverter.
* @return CurrencyConverter instance
*/
public static CurrencyConverter getInstance() {
if (instance == null)
instance = new CurrencyConverter();
return instance;
}

/**
* Converts a double precision floating point value from one currency to
* another. Example: convert(29.95, "USD", "EUR") - converts $29.95 US Dollars
* to Euro.
*
* @param amount
* Amount of money (in source currency) to be converted.
* @param fromCurrency
* Three letter ISO 4217 currency code of source currency.
* @param toCurrency
* Three letter ISO 4217 currency code of target currency.
* @return Amount in target currency
* @throws IOException
* If cache file cannot be read/written or if URL cannot be
* opened.
* @throws ParseException
* If an error occurs while parsing the XML cache file.
* @throws IllegalArgumentException
* If a wrong (non-existing) currency argument was supplied.
*/
public double convert(double amount, String fromCurrency, String toCurrency)
throws IOException, ParseException, IllegalArgumentException {
if (checkCurrencyArgs(fromCurrency, toCurrency)) {
amount *= fxRates.get(toCurrency);
amount /= fxRates.get(fromCurrency);
}
return amount;
}

/**
* Converts a long value from one currency to another. Internally long
* values represent monetary amounts in 1/10000 of the currency unit, e.g.
* the long value 975573l represents 97.5573 (precision = four digits after
* comma). Using long values instead of floating point numbers prevents
* imprecision / calculation errors resulting from floating point
* arithmetics.
*
* @param amount
* Amount of money (in source currency) to be converted.
* @param fromCurrency
* Three letter ISO 4217 currency code of source currency.
* @param toCurrency
* Three letter ISO 4217 currency code of target currency.
* @return Amount in target currency
* @throws IOException
* If cache file cannot be read/written or if URL cannot be
* opened.
* @throws ParseException
* If an error occurs while parsing the XML cache file.
* @throws IllegalArgumentException
* If a wrong (non-existing) currency argument was supplied.
*/
public long convert(long amount, String fromCurrency, String toCurrency)
throws IOException, ParseException, IllegalArgumentException {
if (checkCurrencyArgs(fromCurrency, toCurrency)) {
amount *= fxRates.get(toCurrency);
amount /= fxRates.get(fromCurrency);
}
return amount;
}

/**
* Check whether currency arguments are valid and not equal.
*
* @param fromCurrency
* ISO 4217 source currency code.
* @param toCurrency
* ISO 4217 target currency code.
* @return true if both currency arguments are not equal.
* @throws IOException
* If cache file cannot be read/written or if URL cannot be
* opened.
* @throws ParseException
* If an error occurs while parsing the XML cache file.
* @throws IllegalArgumentException
* If a wrong (non-existing) currency argument was supplied.
*/
private boolean checkCurrencyArgs(String fromCurrency, String toCurrency)
throws IOException, ParseException, IllegalArgumentException {
update();
if (!fxRates.containsKey(fromCurrency))
throw new IllegalArgumentException(fromCurrency
+ " currency is not available.");
if (!fxRates.containsKey(toCurrency))
throw new IllegalArgumentException(toCurrency
+ " currency is not available.");
return (!fromCurrency.equals(toCurrency));
}

/**
* Check whether the exchange rate for a given currency is available.
*
* @param currency
* Three letter ISO 4217 currency code of source currency.
* @return True if exchange rate exists, false otherwise.
*/
public boolean isAvailable(String currency) {
return (fxRates.containsKey(currency));
}

/**
* Returns currencies for which exchange rates are available.
*
* @return String array with ISO 4217 currency codes.
* @throws IOException
* If cache file cannot be read/written or if URL cannot be
* opened.
* @throws ParseException
* If an error occurs while parsing the XML cache file.
*/
public String[] getCurrencies() throws IOException, ParseException {
if (fxRates.isEmpty())
update();
String[] currencies = fxRates.keySet().toArray(
new String[fxRates.size()]);
return currencies;
}

/**
* Get the reference date for the exchange rates as a Java Date. The time
* part is always 14:15 Central European Time (CET).
*
* @return Date for which currency exchange rates are valid, or null if the
* data structure has not yet been initialised.
*
*/
public Date getReferenceDate() {
return referenceDate;
}

/**
* Get the name of the fully qualified path name of the XML cache file. By
* default this is a file named "ExchangeRates.xml" located in the system's
* temporary file directory. The cache file can be shared by multiple
* threads/applications.
*
* @return Path name of the XML cache file.
*/
public String getCacheFileName() {
return cacheFileName;
}

/**
* Set the location where the XML cache file should be stored.
*
* @param cacheFileName
* @see #getCacheFileName() Fully qualified path name of the XML cache file.
*/
public void setCacheFileName(String cacheFileName) {
this.cacheFileName = cacheFileName;
}

/**
* Delete XML cache file and reset internal data structure. Calling
* clearCache() before the convert() method forces a fresh download of the
* currency exchange rates.
*/
public void clearCache() {
initCacheFile();
cacheFile.delete();
cacheFile = null;
referenceDate = null;
}

/**
* Check whether cache is initialised and up-to-date. If not, re-download
* cache file and parse data into internal data structure.
*
* @throws IOException
* If cache file cannot be read/written or if URL cannot be
* opened.
* @throws ParseException
* If an error occurs while parsing the XML cache file.
*/
private void update() throws IOException, ParseException {
if (referenceDate == null) {
initCacheFile();
if (!cacheFile.exists()) {
refreshCacheFile();
}
parse();
}
if (cacheIsExpired()) {
refreshCacheFile();
parse();
}
}

/**
* Initialises cache file member variable if not already initialised.
*/
private void initCacheFile() {
if (cacheFile == null) {
if (cacheFileName == null || cacheFileName.equals(""))
cacheFileName = System.getProperty("java.io.tmpdir")
+ "ExchangeRates.xml";
cacheFile = new File(cacheFileName);
}
}

/**
* Checks whether XML cache file needs to be updated. The cache file is up
* to date for 24 hours after the reference date (plus a certain tolerance).
* On weekends, it is 72 hours because no rates are published during
* weekends.
*
* @return true if cache file needs to be updated, false otherwise.
*/
private boolean cacheIsExpired() {
final int tolerance = 12;
if (referenceDate == null)
return true;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long hoursOld = (cal.getTimeInMillis() - referenceDate.getTime())
/ (1000 * 60 * 60);
int hoursValid = 24 + tolerance;
cal.setTime(referenceDate);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
hoursValid = 72;
else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
hoursValid = 48; // hypothetical... rates are never published on
// Saturdays
if (hoursOld > hoursValid)
return true;
return false;
}

/**
* (Re-) download the XML cache file and store it in a temporary location.
*
* @throws IOException
* If (1) URL cannot be opened, or (2) if cache file cannot
* be opened, or (3) if a read/write error occurs.
*/
private void refreshCacheFile() throws IOException {
lastError = null;
initCacheFile();
InputStreamReader in;
FileWriter out;
try {
URL ecbRates = new URL(ecbRatesURL);
in = new InputStreamReader(ecbRates.openStream());
out = new FileWriter(cacheFile);
try {
int c;
while ((c = in.read()) != -1)
out.write(c);
} catch (IOException e) {
lastError = "Read/Write Error: " + e.getMessage();
} finally {
out.flush();
out.close();
in.close();
}
} catch (IOException e) {
lastError = "Connection/Open Error: " + e.getMessage();
}
if (lastError != null) {
throw new IOException(lastError);
}
}

/**
* Convert a numeric string to a long value with a precision of four digits
* after the decimal point without rounding. E.g. "123.456789" becomes
* 1234567l.
*
* @param str
* Positive numeric string expression.
* @return Value representing 1/10000th of a currency unit.
* @throws NumberFormatException
* If "str" argument is not numeric.
*/
private long stringToLong(String str) throws NumberFormatException {
int decimalPoint = str.indexOf('.');
String wholePart = "";
String fractionPart = "";
if (decimalPoint > -1) {
if (decimalPoint > 0)
wholePart = str.substring(0, decimalPoint);
fractionPart = str.substring(decimalPoint + 1);
String padString = "0000";
int padLength = 4 - fractionPart.length();
if (padLength > 0)
fractionPart += padString.substring(0, padLength);
else if (padLength < 0)
fractionPart = fractionPart.substring(0, 4);
} else {
wholePart = str;
fractionPart = "0000";
}
return (Long.parseLong(wholePart + fractionPart));
}

/**
* Parse XML cache file and create internal data structures containing
* exchange rates and reference dates.
*
* @throws ParseException
* If XML file cannot be parsed.
*/
private void parse() throws ParseException {
try {
FileReader input = new FileReader(cacheFile);
XMLReader saxReader = XMLReaderFactory.createXMLReader();
DefaultHandler handler = new DefaultHandler() {
public void startElement(String uri, String localName,
String qName, Attributes attributes) {
if (localName.equals("Cube")) {
String date = attributes.getValue("time");
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(
"yyyy-MM-dd HH:mm z");
try {
referenceDate = df.parse(date + " 14:15 CET");
} catch (ParseException e) {
lastError = "Cannot parse reference date: "
+ date;
}
}
String currency = attributes.getValue("currency");
String rate = attributes.getValue("rate");
if (currency != null && rate != null) {
try {
fxRates.put(currency, stringToLong(rate));
} catch (Exception e) {
lastError = "Cannot parse exchange rate: "
+ rate + ". " + e.getMessage();
}
}
}
}
};
lastError = null;
fxRates.clear();
fxRates.put("EUR", 10000L);
saxReader.setContentHandler(handler);
saxReader.setErrorHandler(handler);
saxReader.parse(new InputSource(input));
input.close();
} catch (Exception e) {
lastError = "Parser error: " + e.getMessage();
}
if (lastError != null) {
throw new ParseException(lastError, 0);
}
}

}

Friday, May 8, 2009

MailSend Java

mailconfig.properties
sentprotocol=smtp
senthost=pop.gmail.com
sentport=995
senderid=your email id
senderpassword=your password
receiveprotocol=pop
receivehost=smtp.gmail.com
receiveport=587
receiverid=receiver mail id
receiverpassword=receiver password
folder=inbox
savedir=/root/tmp
debug=true

MailConfig.java
package mail;

import java.util.ResourceBundle;
public class MailConfig
{
public static ResourceBundle resourceBundle;
public static String SEND_PROTOCOL;
public static String SEND_HOST;
public static String SEND_PORT;
public static String SENDER_ID;
public static String SENDER_PASSWORD;
public static String RECEIVE_PROTOCOL;
public static String RECEIVE_HOST;
public static String RECEIVE_PORT;
public static String RECEIVER_ID;
public static String RECEIVER_PASSWORD;
public static String FOLDER;
public static String SAVE_DIR;
public static String DEBUG;

static{
try{
resourceBundle=ResourceBundle.getBundle("mail.mailconfig");
init();
}catch(Exception ex){
ex.getMessage();
}
init();
}

/**
* this method initialize the mail configuration variables
*
*/
public static void init()
{
SEND_PROTOCOL=resourceBundle.getString("sentprotocol");
SEND_HOST=resourceBundle.getString("senthost");
SEND_PORT=resourceBundle.getString("sentport");
SENDER_ID=resourceBundle.getString("senderid");
SENDER_PASSWORD=resourceBundle.getString("senderpassword");
RECEIVE_PROTOCOL=resourceBundle.getString("receiveprotocol");
RECEIVE_HOST=resourceBundle.getString("receivehost");
RECEIVE_PORT=resourceBundle.getString("receiveport");
RECEIVER_ID=resourceBundle.getString("receiverid");
RECEIVER_PASSWORD=resourceBundle.getString("receiverpassword");
FOLDER=resourceBundle.getString("folder");
SAVE_DIR=resourceBundle.getString("savedir");
DEBUG=resourceBundle.getString("debug");
}
}

MailSender.java
package mail;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.Date;
public class MailSender
{
private String strProtocol;
private String strHost;
private int nPort;
private String strFrom;
private String strPassword;
private Properties prop;
private boolean debug;
private Transport tr = null;
private Session session;


public MailSender()
{
strProtocol=MailConfig.SEND_PROTOCOL;
strHost=MailConfig.SEND_HOST;
nPort=Integer.parseInt(MailConfig.SEND_PORT);
strFrom=MailConfig.SENDER_ID;
strPassword=MailConfig.SENDER_PASSWORD;
debug=Boolean.parseBoolean(MailConfig.DEBUG);
init();
}

public void init()
{
prop=System.getProperties();
prop.put("mail.smtp.host", strHost);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtps.auth", "true");
session=Session.getInstance(prop,null);
if(debug){
session.setDebug(debug);
}
}

/**
* This method send mail to specified mail address from the
* mail address specified in the property file.
* @param subject subject of the mail to be send
* @param to to address of the mail
* @param message the content of the mail
* @return true if the mail sent successfully otherwise false.
*/
public boolean sendMessage(String subject,String to,String message){
boolean status=sendMessage(subject,to,"",message);
return status;
}

/**
* This Method send message to specified mail address form the
* mail address specified specified in the property file.
* @param subject of the mail to be send
* @param to to address of the mail.
* @param cc copy to
* @param message message content
* @return true if the message sent successfully.
*/
public boolean sendMessage(String subject,String to,String cc,String message)
{
try {
Message msg=new MimeMessage(session);
Address[] toAddress=InternetAddress.parse(to,false);
Address[] ccAddress=InternetAddress.parse(cc,false);

if(strFrom!=null){
msg.setFrom(new InternetAddress(strFrom));
}
msg.setRecipients(Message.RecipientType.TO,toAddress);
if(!cc.equals(""))
msg.setRecipients(Message.RecipientType.CC,ccAddress);
msg.setSubject(subject);
msg.setText(message);
msg.setHeader("X-Mailer","msgsend");
msg.setSentDate(new Date());
tr = session.getTransport(strProtocol);
tr.connect(strHost,nPort,strFrom, strPassword);
tr.sendMessage(msg, msg.getAllRecipients());
return true;
}
catch(Exception ex) {
ex.printStackTrace();
}
return false;
}

public static void main(String arsg[])
{
MailSender mailsender=new MailSender();
boolean st=mailsender.sendMessage("test","nimishth@gmail.com","test mail");
System.out.print(st);
}
}

Wednesday, April 22, 2009

Convert Object To Byte Array Using JAVA

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectToByte {

public byte[] convert(Object obj) throws IOException {
ObjectOutputStream os = null;

ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
os.flush();
os.writeObject(obj);
os.flush();
byte[] sendBuf = byteStream.toByteArray();
os.close();
return sendBuf;

}
}

Saturday, April 18, 2009

Play Audio File using java

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class AudioPlayer extends Thread {

private static final int EXTERNAL_BUFFER_SIZE = 128000;
private SourceDataLine line = null;
private String strFilename;
boolean play = true;

public AudioPlayer(String strFilename) {
this.strFilename = strFilename;
}

public void startPlaying() {
play = true;
start();
}

public void stopPlaying() {
play = false;
line.drain();
line.close();

}

public void run() {
File soundFile = new File(strFilename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e) {

e.printStackTrace();
System.exit(1);
}
AudioFormat audioFormat = audioInputStream.getFormat();

DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try {
line = (SourceDataLine) AudioSystem.getLine(info);


line.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
line.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1 && play) {
try {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
int nBytesWritten = line.write(abData, 0, nBytesRead);
}
}
line.drain();
line.close();
}
}

Saturday, March 21, 2009

Read/write BLOB from/to MySQL in Java

This post shows you how to insert an image into MySQL database through Java

Step 1 : Open MySQL client
Step 2 : Execute the following query

CREATE TABLE IF NOT EXISTS `image` (
IMG blob,
IMG_ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`IMG_ID`)
)

Source code
-----------


import java.awt.event.ActionEvent;
import java.sql.*;
import java.awt.Graphics;

import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;



/**
*
* @author mustaq
*/
public class ImagePanel extends JPanel implements ActionListener {


JButton browse;
Connection con = null;

public ImagePanel() {
con = this.getConnection();
browse = new JButton("Browse");
browse.addActionListener(this);
this.add(browse);
}
public Connection getConnection() {
try {
// Creating connection to DB
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/image";
Connection c = DriverManager.getConnection(url,"root","");
return c;
}
catch(Exception ex) {
System.out.println(ex.getMessage());
return null;
}

}
public void imageWrite(File file) {
try {

FileInputStream io = new FileInputStream(file);
String query = "insert into image(IMG) values(?)";
java.sql.PreparedStatement stmt = con.prepareStatement(query);
stmt.setBinaryStream(1, (InputStream)io,(int)file.length());
stmt.executeUpdate();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
public BufferedImage getImageById(int id) {
String query = "select IMG from image where IMG_ID = ?";
BufferedImage buffimg = null;
try {
PreparedStatement stmt = con.prepareStatement(query);
stmt.setInt(1,id);
ResultSet result = stmt.executeQuery();
result.next();
InputStream img = result.getBinaryStream(1); // reading image as InputStream
buffimg= ImageIO.read(img); // decoding the inputstream as BufferedImage

}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
return buffimg;
}
@Override
public void paint(Graphics g) {

BufferedImage img = this.getImageById(5) ; // pass valid IMG_ID
if(img != null)
g.drawImage(img, 70, 20, this);

}
public static void main(String[] args) {
JFrame frame = new JFrame("ImagePanel Demo");
ImagePanel imgPanel = new ImagePanel();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(imgPanel);


}
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
File file = null;
if(returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile(); // path to image
this.imageWrite(file); // inserting image into database
JOptionPane.showMessageDialog(this, "Image inserted.", "ImageDemo", JOptionPane.PLAIN_MESSAGE);
this.repaint();

}
}

}

LinkWithin

Related Posts with Thumbnails