Asterisk is a PBX
Asterisk is a Private Branch Exchange (PBX). A PBX can be thought of as a private
phone switchboard, connecting to one or more telephones on one side, and usually
connecting to one or more telephone lines on the other. This is usually more cost
effective than leasing a telephone line for each telephone needed in a business.
Welcome to CodeGlobe. CodeGlobe provides free source code, tutorials and latest useful technology news.
Tuesday, May 26, 2009
online Exchange Rate (PHP)
$us_price = '100';
$ticker= 'CADUSD=X';
$open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$ticker&f=sl1d1t1c1ohgv&e=.csv", "r");
$exchange_rate = fread($open, 2000);
fclose($open);
$exchange_rate = str_replace("\"", "", $exchange_rate);
$exchange_rate = explode(",", $exchange_rate);
$ca_price = ($us_price/$exchange_rate[1]);
$price = number_format ($ca_price, 2);
echo "$us_price US dollars = \$$price Canadian dollars";
?>
PHP Proxy example for Yahoo! Web services. (Permission denied XmlHttpRequest- Cross site Ajax Request)
// PHP Proxy example for Yahoo! Web services.
// Responds to both HTTP GET and POST requests
//
// Author: Jason Levitt
// December 7th, 2005
//
// Allowed hostname (api.local and api.travel are also possible here)
define ('HOSTNAME', 'http://search.yahooapis.com/');
// Get the REST call path from the AJAX application
// Is it a POST or a GET?
$path = ($_POST['yws_path']) ? $_POST['yws_path'] : $_GET['yws_path'];
$url = HOSTNAME.$path;
// Open the Curl session
$session = curl_init($url);
// If it's a POST, put the POST data in the body
if ($_POST['yws_path']) {
$postvars = '';
while ($element = current($_POST)) {
$postvars .= key($_POST).'='.$element.'&';
next($_POST);
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
}
// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Make the call
$xml = curl_exec($session);
// The web service returns XML. Set the Content-Type appropriately
header("Content-Type: text/xml");
echo $xml;
curl_close($session);
?>
// Responds to both HTTP GET and POST requests
//
// Author: Jason Levitt
// December 7th, 2005
//
// Allowed hostname (api.local and api.travel are also possible here)
define ('HOSTNAME', 'http://search.yahooapis.com/');
// Get the REST call path from the AJAX application
// Is it a POST or a GET?
$path = ($_POST['yws_path']) ? $_POST['yws_path'] : $_GET['yws_path'];
$url = HOSTNAME.$path;
// Open the Curl session
$session = curl_init($url);
// If it's a POST, put the POST data in the body
if ($_POST['yws_path']) {
$postvars = '';
while ($element = current($_POST)) {
$postvars .= key($_POST).'='.$element.'&';
next($_POST);
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
}
// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Make the call
$xml = curl_exec($session);
// The web service returns XML. Set the Content-Type appropriately
header("Content-Type: text/xml");
echo $xml;
curl_close($session);
?>
Wednesday, May 20, 2009
Try this in Turbo c
#include
#include
#include
#include
int c=261.5,cb=277,d=293,db=311,e=329,f=349.5,fb=370,g=392,gb=415,a=440,ab=446,b=497,x=0;
void stanzal()
{
sound(f);delay(450+x);nosound();delay(50+x);sound(f);delay(250+x);sound(e);
delay(250+x);
sound(d);delay(250+x);sound(e);delay(500+x);sound(cb);delay(250+x);
sound(d);delay(250+x);nosound();delay(250+x);sound(d);delay(1500+x);
}
void main()
{
while(kbhit()==0)
{
stanzal();
sound(a/2);delay(250+x);sound(b/2);delay(250+x);
sound(d);delay(500+x);sound(e);delay(250+x);sound(fb);
delay(500+x);sound(g);delay(250+x);sound(fb);delay(500+x);
sound(g);delay(250+x);sound(fb);delay(250+x);nosound();
delay(250+x);sound(fb);delay(250+x);sound(e);delay(250+x);
sound(g);delay(250+x);sound(fb);delay(250+x);sound(e);
delay(250+x);sound(d);delay(250+x);
stanzal();
sound(fb);delay(250+x);sound(g);delay(250+x);sound(a);
delay(250+x);nosound();delay(250+x);
sound(a);delay(200+x);nosound();delay(50+x);sound(a);
delay(500+x);sound(fb);delay(250+x);
sound(g);delay(250+x);sound(b);delay(250+x);sound(a);
delay(1500+x);
sound(fb);delay(250+x);sound(g);delay(250+x);sound(a);delay(250+x);
nosound();delay(250+x);sound(g);delay(250+x);
sound(g);delay(250+x);sound(f);delay(500+x);sound(e);
delay(250+x);
sound(d);delay(250+x);nosound();delay(250+x);sound(d);delay(250+x);
sound(cb);delay(250+x);
sound(d);delay(250+x);sound(cb);delay(250+x);sound(b/2);delay(250+x);
sound(a/2);delay(250+x);nosound();
}
getch();
}
#include
#include
#include
int c=261.5,cb=277,d=293,db=311,e=329,f=349.5,fb=370,g=392,gb=415,a=440,ab=446,b=497,x=0;
void stanzal()
{
sound(f);delay(450+x);nosound();delay(50+x);sound(f);delay(250+x);sound(e);
delay(250+x);
sound(d);delay(250+x);sound(e);delay(500+x);sound(cb);delay(250+x);
sound(d);delay(250+x);nosound();delay(250+x);sound(d);delay(1500+x);
}
void main()
{
while(kbhit()==0)
{
stanzal();
sound(a/2);delay(250+x);sound(b/2);delay(250+x);
sound(d);delay(500+x);sound(e);delay(250+x);sound(fb);
delay(500+x);sound(g);delay(250+x);sound(fb);delay(500+x);
sound(g);delay(250+x);sound(fb);delay(250+x);nosound();
delay(250+x);sound(fb);delay(250+x);sound(e);delay(250+x);
sound(g);delay(250+x);sound(fb);delay(250+x);sound(e);
delay(250+x);sound(d);delay(250+x);
stanzal();
sound(fb);delay(250+x);sound(g);delay(250+x);sound(a);
delay(250+x);nosound();delay(250+x);
sound(a);delay(200+x);nosound();delay(50+x);sound(a);
delay(500+x);sound(fb);delay(250+x);
sound(g);delay(250+x);sound(b);delay(250+x);sound(a);
delay(1500+x);
sound(fb);delay(250+x);sound(g);delay(250+x);sound(a);delay(250+x);
nosound();delay(250+x);sound(g);delay(250+x);
sound(g);delay(250+x);sound(f);delay(500+x);sound(e);
delay(250+x);
sound(d);delay(250+x);nosound();delay(250+x);sound(d);delay(250+x);
sound(cb);delay(250+x);
sound(d);delay(250+x);sound(cb);delay(250+x);sound(b/2);delay(250+x);
sound(a/2);delay(250+x);nosound();
}
getch();
}
Tuesday, May 19, 2009
Try it in Turbo c
#include
#include
float main(void)
{
float A,Bb,D,G,F;
A = 440;
G = 780;
Bb = 461;
D = 586;
F = 687;
sound(G);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(500);
nosound();
sound(2*D);
delay(500);
nosound();
sound(2*A);
delay(250);
nosound();
sound(2*Bb);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(500);
nosound();
sound(2*A);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
//end 1
sound(G);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(500);
nosound();
sound(2*D);
delay(500);
nosound();
sound(2*A);
delay(250);
nosound();
sound(2*Bb);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(500);
nosound();
sound(2*A);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
//end 2
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
return 0;
}
#include
float main(void)
{
float A,Bb,D,G,F;
A = 440;
G = 780;
Bb = 461;
D = 586;
F = 687;
sound(G);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(500);
nosound();
sound(2*D);
delay(500);
nosound();
sound(2*A);
delay(250);
nosound();
sound(2*Bb);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(500);
nosound();
sound(2*A);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
//end 1
sound(G);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(500);
nosound();
sound(2*D);
delay(500);
nosound();
sound(2*A);
delay(250);
nosound();
sound(2*Bb);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(500);
nosound();
sound(2*A);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
//end 2
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
return 0;
}
Proxy server in Java
import java.net.* ;
import java.io.* ;
import java.lang.* ;
import java.util.* ;
class proxy {
public static void main(String args[]) throws IOException{
//parse arguments from command line
int localport = -1;
int remoteport = -1;
String remotehost = null;
boolean error = false;
int i = 0;
Integer parselocalport = new Integer(args);
Integer parseremoteport = new Integer(args[i+2]);
Socket incoming, outgoing = null;
ServerSocket Server = null;
try
{
localport = parselocalport.parseInt(args, 10);
remotehost = args[i+1];
remoteport = parseremoteport.parseInt(args[i+2], 10);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage() + "\n");
error = true;
}
// Check for valid local and remote port, hostname not null
System.out.println("Checking: Port" + localport + " to " + remotehost + " Port " + remoteport);
if(localport <= 0){
System.err.println("Error: Invalid Local Port Specification " + "\n");
error = true;
}
if(remoteport <=0){
System.err.println("Error: Invalid Remote Port Specification " + "\n");
error = true;
}
if(remotehost == null){
System.err.println("Error: Invalid Remote Host Specification " + "\n");
error = true;
}
//If any errors so far, exit program
if(error)
System.exit(-1);
//Test and create a listening socket at proxy
try{
Server = new ServerSocket(localport);
}
catch(IOException e) {
e.printStackTrace();
}
//Loop to listen for incoming connection, and accept if there is one
while(true)
{
try{
incoming = Server.accept();
//Create the 2 threads for the incoming and outgoing traffic of proxy server
outgoing = new Socket(remotehost, remoteport);
proxyThread thread1 = new proxyThread(incoming, outgoing);
thread1.start();
proxyThread thread2 = new proxyThread(outgoing, incoming);
thread2.start();
}
catch (UnknownHostException e) {
//Test and make connection to remote host
System.err.println("Error: Unknown Host " + remotehost);
System.exit(-1);
}
catch(IOException e){
System.exit(-2);//continue;
}
/* catch (IOException e) {
System.err.println("Error: Couldn't Initiate I/O connection for " + remotehost);
System.exit(-1);
}
*/
}
}
}
import java.net.* ;
import java.io.* ;
import java.lang.* ;
import java.util.* ;
class proxyThread extends Thread {
Socket incoming, outgoing;
//Thread constructor
proxyThread(Socket in, Socket out){
incoming = in;
outgoing = out;
}
//Overwritten run() method of thread -- does the data transfers
public void run(){
byte[] buffer = new byte[60];
int numberRead = 0;
OutputStream ToClient;
InputStream FromClient;
try{
ToClient = outgoing.getOutputStream();
FromClient = incoming.getInputStream();
while( true){
numberRead = FromClient.read(buffer, 0, 50);
System.out.println("read " + numberRead);
//buffer[numberRead] = buffer[0] = (byte)'+';
if(numberRead == -1){
incoming.close();
outgoing.close();
}
ToClient.write(buffer, 0, numberRead);
}
}
catch(IOException e) {}
catch(ArrayIndexOutOfBoundsException e) {}
}
}
usage
java proxy 9999 192.168.0.1 7068
import java.io.* ;
import java.lang.* ;
import java.util.* ;
class proxy {
public static void main(String args[]) throws IOException{
//parse arguments from command line
int localport = -1;
int remoteport = -1;
String remotehost = null;
boolean error = false;
int i = 0;
Integer parselocalport = new Integer(args);
Integer parseremoteport = new Integer(args[i+2]);
Socket incoming, outgoing = null;
ServerSocket Server = null;
try
{
localport = parselocalport.parseInt(args, 10);
remotehost = args[i+1];
remoteport = parseremoteport.parseInt(args[i+2], 10);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage() + "\n");
error = true;
}
// Check for valid local and remote port, hostname not null
System.out.println("Checking: Port" + localport + " to " + remotehost + " Port " + remoteport);
if(localport <= 0){
System.err.println("Error: Invalid Local Port Specification " + "\n");
error = true;
}
if(remoteport <=0){
System.err.println("Error: Invalid Remote Port Specification " + "\n");
error = true;
}
if(remotehost == null){
System.err.println("Error: Invalid Remote Host Specification " + "\n");
error = true;
}
//If any errors so far, exit program
if(error)
System.exit(-1);
//Test and create a listening socket at proxy
try{
Server = new ServerSocket(localport);
}
catch(IOException e) {
e.printStackTrace();
}
//Loop to listen for incoming connection, and accept if there is one
while(true)
{
try{
incoming = Server.accept();
//Create the 2 threads for the incoming and outgoing traffic of proxy server
outgoing = new Socket(remotehost, remoteport);
proxyThread thread1 = new proxyThread(incoming, outgoing);
thread1.start();
proxyThread thread2 = new proxyThread(outgoing, incoming);
thread2.start();
}
catch (UnknownHostException e) {
//Test and make connection to remote host
System.err.println("Error: Unknown Host " + remotehost);
System.exit(-1);
}
catch(IOException e){
System.exit(-2);//continue;
}
/* catch (IOException e) {
System.err.println("Error: Couldn't Initiate I/O connection for " + remotehost);
System.exit(-1);
}
*/
}
}
}
import java.net.* ;
import java.io.* ;
import java.lang.* ;
import java.util.* ;
class proxyThread extends Thread {
Socket incoming, outgoing;
//Thread constructor
proxyThread(Socket in, Socket out){
incoming = in;
outgoing = out;
}
//Overwritten run() method of thread -- does the data transfers
public void run(){
byte[] buffer = new byte[60];
int numberRead = 0;
OutputStream ToClient;
InputStream FromClient;
try{
ToClient = outgoing.getOutputStream();
FromClient = incoming.getInputStream();
while( true){
numberRead = FromClient.read(buffer, 0, 50);
System.out.println("read " + numberRead);
//buffer[numberRead] = buffer[0] = (byte)'+';
if(numberRead == -1){
incoming.close();
outgoing.close();
}
ToClient.write(buffer, 0, numberRead);
}
}
catch(IOException e) {}
catch(ArrayIndexOutOfBoundsException e) {}
}
}
usage
java proxy 9999 192.168.0.1 7068
Saturday, May 9, 2009
Random Number generator
public static String generateLongNumber(int digit)
{
Random random = new Random();
String convert = "0";
BigInteger bigGen;
BigInteger bigComp = BigInteger.valueOf(-1L);
Long generated = random.nextLong();
bigGen = BigInteger.valueOf(generated);
convert = String.valueOf(generated);
if(generated < 0) {
convert = String.valueOf(bigGen.multiply(bigComp));
}
if((convert.length() > digit )) {
convert = convert.substring(0,digit);
generated = Long.parseLong(convert);
} else if((convert.length() < digit )) {
generateLongNumber(digit);
}
return generated.toString();
}
{
Random random = new Random();
String convert = "0";
BigInteger bigGen;
BigInteger bigComp = BigInteger.valueOf(-1L);
Long generated = random.nextLong();
bigGen = BigInteger.valueOf(generated);
convert = String.valueOf(generated);
if(generated < 0) {
convert = String.valueOf(bigGen.multiply(bigComp));
}
if((convert.length() > digit )) {
convert = convert.substring(0,digit);
generated = Long.parseLong(convert);
} else if((convert.length() < digit )) {
generateLongNumber(digit);
}
return generated.toString();
}
Hashing
This method will give u the out put according to the input string and the algorithm
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Method getHashText.
* @param plainText
* @param algorithm The algorithm to use like MD2, MD5, SHA-1, etc.
* @return String
* @throws NoSuchAlgorithmException
*/
public static String getHashText(String plainText, String algorithm)
throws NoSuchAlgorithmException {
MessageDigest mdAlgorithm = MessageDigest.getInstance(algorithm);
mdAlgorithm.update(plainText.getBytes());
byte[] digest = mdAlgorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
plainText = Integer.toHexString(0xFF & digest[i]);
if (plainText.length() < 2) {
plainText = "0" + plainText;
}
hexString.append(plainText);
}
return hexString.toString();
}
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Method getHashText.
* @param plainText
* @param algorithm The algorithm to use like MD2, MD5, SHA-1, etc.
* @return String
* @throws NoSuchAlgorithmException
*/
public static String getHashText(String plainText, String algorithm)
throws NoSuchAlgorithmException {
MessageDigest mdAlgorithm = MessageDigest.getInstance(algorithm);
mdAlgorithm.update(plainText.getBytes());
byte[] digest = mdAlgorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
plainText = Integer.toHexString(0xFF & digest[i]);
if (plainText.length() < 2) {
plainText = "0" + plainText;
}
hexString.append(plainText);
}
return hexString.toString();
}
Dojo FileUpload
While uploading file from dojo it always not giving proper response that's why U cant give a message
such as file uploaded succeessfully or bot this issue can be solved by just return the string with in a html textarea tag ie
PrintWrite pw=responsequest.getWriter();
//code to upload file using the Api such as common file upload or jsp smart
String message = "";
if(fileuploaded){
message="";
}else{
message="";
}
out.println(message);
Then u will get the response what u have specified in this textarea
such as file uploaded succeessfully or bot this issue can be solved by just return the string with in a html textarea tag ie
PrintWrite pw=responsequest.getWriter();
//code to upload file using the Api such as common file upload or jsp smart
String message = "";
if(fileuploaded){
message="";
}else{
message="";
}
out.println(message);
Then u will get the response what u have specified in this textarea
Servlet Listener Java
web.xml
TestNew
listener.TestListener
package listener;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Servlet implementation class for Servlet: TestListener
*
*/
public class TestListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent sev){
Timer timer=new Timer(true);
timer.scheduleAtFixedRate(new Task(),0,1000);
}
public void contextDestroyed(ServletContextEvent scv){
}
class Task extends TimerTask{
public void run(){
System.out.println("Hello");
}
}
}
TestNew
package listener;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Servlet implementation class for Servlet: TestListener
*
*/
public class TestListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent sev){
Timer timer=new Timer(true);
timer.scheduleAtFixedRate(new Task(),0,1000);
}
public void contextDestroyed(ServletContextEvent scv){
}
class Task extends TimerTask{
public void run(){
System.out.println("Hello");
}
}
}
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();
}
}
}
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());
}
}
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 );
}
}
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
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
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");
}
}
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);
}
}
}
* 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
/** 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);
}
}
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);
}
}
Subscribe to:
Posts (Atom)