Sunday, January 8, 2012
Flipping an Image
Making a Certain Color Transparent
Making an Image Translucent
Saving Image
Creating and Using your own Image in Java
Drawing an Image on the Screen using Graphics2D
Using Blocking Queues
package com.oreilly.tiger.ch10;
import java.io.PrintStream;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
public class Producer extends Thread {
private BlockingQueue q;
private PrintStream out;
public Producer(BlockingQueue q, PrintStream out) {
setName("Producer");
this.q = q;
this.out = out;
}
public void run( ) {
try {
while (true) {
q.put(produce( ));
}
} catch (InterruptedException e) {
out.printf("%s interrupted: %s", getName( ), e.getMessage( ));
}
}
private String produce( ) {
while (true) {
double r = Math.random( );
// Only goes forward 1/10 of the time
if ((r*100) < 10) {
String s = String.format("Inserted at %tc", new Date( ));
return s;
}
}
}
}
Loading an Image
ScrollPane with image
Handling Uncaught Exceptions in Threads
Normally a Java thread (represented by any class that extends java.lang.Thread) stops when its
run( ) method completes. In an abnormal case, such as when something goes wrong, the thread can
terminate by throwing an exception. This exception trickles up the thread's ThreadGroup hierarchy,
and if it gets to the root ThreadGroup, the default behavior is to print out the thread's name,
exception name, exception message, and exception stack trace.
To get around this behavior (at least in Java 1.4 and earlier), you've got to insert your own code into
the ThreadGroup hierarchy, handle the exception, and prevent delegation back to the root
ThreadGroup. While this is certainly possible, you'll have to define your own subclass of
ThreadGroup, make sure any Threads you create are assigned to that group, and generally do a lot
of coding that has very little to do with the task at hand—actually handling the uncaught exception.
Tiger simplifies all this dramatically, and lets you define uncaught exception handling on a per-Thread basis.
Example:
package com.oreilly.tiger.ch10;
public class BubbleSortThread extends Thread {
private int[] numbers;
public BubbleSortThread(int[] numbers) {
setName("Simple Thread");
setUncaughtExceptionHandler(
new SimpleThreadExceptionHandler( ));
this.numbers = numbers;
}
public void run( ) {
int index = numbers.length;
boolean finished = false;
while (!finished) {
index--;
finished = true;
for (int i=0; i<5; i++)="" {="" create="" error="" condition="" if="" (numbers[i+1]="" <="" 0)="" throw="" new="" illegalargumentexception(="" "cannot="" pass="" negative="" numbers="" into="" this="" thread!");="" }="" (numbers[i]=""> numbers[i+1]) {
// swap
int temp = numbers[i];
numbers[i] = numbers[i+1];
numbers[i+1] = temp;
finished = false;
}
}
}
}
}
class SimpleThreadExceptionHandler implements
Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.err.printf("%s: %s at line %d of %s%n",
t.getName( ),
e.toString( ),
e.getStackTrace( )[0].getLineNumber( ),
e.getStackTrace( )[0].getFileName( ));
}
}
How to Write a Tree Selection Listener
Creating a Data Model
How to Load Children Lazily
Dynamically Changing a Tree
Customizing a Tree's Display
How to respond to a tree node selection
How to Create Trees
How to take single snapshots from a webcam
Enabling Multiple Selections in a JFileChooser Dialog
How to Make Dialogs
How to Use Tool Tips
How to Use File Choosers
STL(standard template library)
The Standard Template Libraries (STL's) are a set of C++ template classes to provide common programming data structures
and functions such as doubly linked lists (list), paired arrays (map), expandable arrays (vector), large string storage
and manipulation (rope), etc. The STL library is available from the STL home page. This is also your best detailed
reference for all of the STL class functions available.
STL can be categorized into the following groupings:
Container classes:
Sequences:
vector: (this tutorial) Dynamic array of variables, struct or objects. Insert data at the end.
(also see the YoLinux.com tutorial on using and STL list and boost ptr_list to manage pointers.)
deque: Array which supports insertion/removal of elements at beginning or end of array
list: (this tutorial) Linked list of variables, struct or objects. Insert/remove anywhere.
Associative Containers:
set (duplicate data not allowed in set), multiset (duplication allowed): Collection of ordered data in a balanced binary tree structure. Fast search.
map (unique keys), multimap (duplicate keys allowed): Associative key-value pair held in balanced binary tree structure.
Container adapters:
stack LIFO
queue FIFO
priority_queue returns element with highest priority.
String:
string: Character strings and manipulation
rope: String storage and manipulation
bitset: Contains a more intuitive method of storing and manipulating bits.
Operations/Utilities:
iterator: (examples in this tutorial) STL class to represent position in an STL container. An iterator is declared to be associated with a single container class type.
algorithm: Routines to find, count, sort, search, ... elements in container classes
auto_ptr: Class to manage memory pointers and avoid memory leaks.
Running Codes
http://en.wikipedia.org/wiki/Standard_Template_Library
Cone in Java 3d Programming
capped cone centered at the origin with its central axis aligned along the Y−axis. The center of the Cone is
defined to be the center of its bounding box (rather than its centroid). If the GENERATE_TEXTURE_COORDS
flag is set, the texture coordinates are generated so that the texture gets mapped onto the Cone similarly to a
Cylinder, except without a top cap.
Cone consists of the following Shape3D objects:
ALIGN="JUSTIFY">int BODY = 0; •
"JUSTIFY">int CAP = 1;
The geometry for the Cone consists of a Cylinder tapering from the supplied radius at one end to zero
radius at the other end. A disk is created using the same number of divisions as the Cylinder and aligned to
close the open end of the Cylinder.
Running Codes
|
+−−javax.media.j3d.SceneGraphObject
|
+−−javax.media.j3d.Node
|
+−−javax.media.j3d.Group
|
+−−com.sun.j3d.utils.geometry.Primitive
public Cone(float radius, float height, int primflags,
int xdivision, int ydivision, Appearance ap) |
+−−com.sun.j3d.utils.geometry.Cone
Labels: Advanced, JavaSE 0 comments
Box in Java 3d Programming
capped cone centered at the origin with its central axis aligned along the Y−axis. The center of the Cone is
defined to be the center of its bounding box (rather than its centroid). If the GENERATE_TEXTURE_COORDS
flag is set, the texture coordinates are generated so that the texture gets mapped onto the Cone similarly to a
Cylinder, except without a top cap.
Cone consists of the following Shape3D objects:
ALIGN="JUSTIFY">int BODY = 0; •
"JUSTIFY">int CAP = 1;
The geometry for the Cone consists of a Cylinder tapering from the supplied radius at one end to zero
radius at the other end. A disk is created using the same number of divisions as the Cylinder and aligned to
close the open end of the Cylinder.
Running Codes
|
+−−javax.media.j3d.SceneGraphObject
|
+−−javax.media.j3d.Node
|
+−−javax.media.j3d.Group
|
+−−com.sun.j3d.utils.geometry.Primitive
public Cone(float radius, float height, int primflags,
int xdivision, int ydivision, Appearance ap) |
+−−com.sun.j3d.utils.geometry.Cone
Labels: Advanced, JavaSE 0 comments
Saturday, January 7, 2012
Thread Synchronizing in Java Threading
Thread Synchronization
Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
The Producer/Consumer example
To introduce systematically the Java threads synchronization techniques consider the Producer/Consumer example, proposed in http://www.cs.technion.ac.il/~assaf/publications/parjava.doc.gz. We modified this example to facilitate the practical experimentation of the analyzed synchronization ideas.
The example consists of a class MyData0 that stores an integer value and of two threads of the classes Producer and Consumer. The Producer writes in an infinite loop consecutive integer values into the MyData0 object and the Consumer reads in an infinite loop these values. The Producer and Consumer threads are created and initialized in the ProducerConsumerDriver class.
The task is to synchronize the Producer and the Consumer so that the values will not be lost when the Producer performs two consecutive writings, and the values will not be duplicated when the Consumer will performs to consecutive readings.
Consider first the first Version of this example without any synchronization:
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } } public class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); } } }
Main Program
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
Labels: Advanced, JavaSE, Thread 0 comments
Thread DeadLock in Java
What is a deadlock?
We say that a set of processes or threads is deadlocked when each thread is waiting for an event that only another process in the set can cause. Another way to illustrate a deadlock is to build a directed graph whose vertices are threads or processes and whose edges represent the "is-waiting-for" relation. If this graph contains a cycle, the system is deadlocked. Unless the system is designed to recover from deadlocks, a deadlock causes the program or system to hang.
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here's an example.
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
Labels: Advanced, JavaSE, Thread 0 comments
JavaEE What is,Why we need it
General APIs
The Java EE APIs includes several technologies that extend the functionality of the base Java SE APIs.
Java EE 6 Platform Packages
Java EE 5 Platform Packages
javax.faces.*
This package defines the root of the JavaServer Faces (JSF) API. JSF is a technology for constructing user interfaces out of components
javax.faces.component.*
This package defines the component part of the JavaServer Faces (JSF) API. Since JSF is primarily component oriented, this is one of the core packages. The package overview contains a UML diagram of the component hierarchy.
javax.servlet.*
The servlet specification defines a set of APIs to service mainly HTTP requests. It includes the JavaServer Pages specification.
javax.enterprise.inject.*
These packages define the injection annotations for the contexts and Dependency Injection (CDI) API.
javax.enterprise.context.*
These packages define the context annotations and interfaces for the Contexts and Dependency Injection (CDI) API.
javax.ejb.*
The Enterprise JavaBean (EJB) specification defines a set of lightweight APIs that an object container (the EJB container) will support in order to provide transactions (using JTA), remote procedure calls (using RMI or RMI-IIOP), concurrency control, dependency injection and access control for business objects. This package contains the Enterprise JavaBeans classes and interfaces that define the contracts between the enterprise bean and its clients and between the enterprise bean and the ejb container.
javax.validation
This package contains the annotations and interfaces for the declarative validation support offered by the Bean Validation API. Bean Validation provides a unified way to provide constraints on beans (e.g. JPA model classes) that can be enforced cross-layer. In Java EE, JPA honors bean validation constraints in the persistence layer, while JSF does so in the view layer.
javax.persistence
This package contains the classes and interfaces that define the contracts between a persistence provider and the managed classes and the clients of the Java Persistence API (JPA).
javax.transaction
This package provides the Java Transaction API (JTA) API that contains the interfaces to interact with the transaction support offered by Java EE. Even though this API abstracts from the really low-level details, it is itself also considered somewhat low-level and the average application developer in Java EE is assumed to be relying on transparent handling of transactions by the higher level EJB abstractions.
javax.jms.*
This package defines the Java Message Service (JMS) API. The JMS API provides a common way for Java programs to create, send, receive and read an enterprise messaging system's messages.
javax.resource.*
This package defines the Java EE Connector Architecture (JCA) API. Java EE Connector Architecture (JCA) is a Java-based technology solution for connecting application servers and enterprise information systems (EIS) as part of enterprise application integration (EAI) solutions. This is a low-level API aimed at vendors that the average application developer typically does not come in contact with.
Labels: Basic, JavaEE 0 comments
Multithreading in Java
Introduction
So far you have learned about a single thread. Lets us know about the concept of multithreading and learn the implementation of it. But before that, lets be aware from the multitasking.
Multitasking :
Multitasking allow to execute more than one tasks at the same time, a task being a program. In multitasking only one CPU is involved but it can switches from one program to another program so quickly that's why it gives the appearance of executing all of the programs at the same time. Multitasking allow processes (i.e. programs) to run concurrently on the program. For Example running the spreadsheet program and you are working with word processor also.
Multitasking is running heavyweight processes by a single OS.
Multithreading :
Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system
In the multithreading concept, several multiple lightweight processes are run in a single process/task or program by a single processor. For Example, When you use a word processor you perform a many different tasks such as printing, spell checking and so on. Multithreaded software treats each process as a separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time.
For example, look at the diagram shown as:
In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread.
Advantages of multithreading over multitasking :
Reduces the computation time.
Improves performance of an application.
Threads share the same address space so it saves the memory.
Context switching between threads is usually less expensive than between processes.
Cost of communication between threads is relatively low.
Different states implementing Multiple-Threads are:
As we have seen different states that may be occur with the single thread. A running thread can enter to any non-runnable state, depending on the circumstances. A thread cannot enters directly to the running state from non-runnable state, firstly it goes to runnable state. Now lets understand the some non-runnable states which may be occur handling the multithreads.
Sleeping ? On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread.
static void sleep(long millisecond) throws InterruptedException
Waiting for Notification ? A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread.
final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException
Blocked on I/O ? The thread waits for completion of blocking operation. A thread can enter on this state because of waiting I/O resource. In that case the thread sends back to runnable state after availability of resources.
Blocked for joint completion ? The thread can come on this state because of waiting the completion of another thread.
Blocked for lock acquisition ? The thread can come on this state because of waiting to acquire the lock of an object.
Labels: Advanced, JavaSE, Thread 0 comments
Threading & Process, Simple Example of Threading
Process
A process is an instance of a computer program that is executed sequentially. It is a collection of instructions which are executed simultaneously at the rum time. Thus several processes may be associated with the same program. For example, to check the spelling is a single process in the Word Processor program and you can also use other processes like printing, formatting, drawing, etc. associated with this program.
Thread
A thread is a lightweight process which exist within a program and executed to perform a special task. Several threads of execution may be associated with a single process. Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process.
In Java Programming language, thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete. It exists in a common memory space and can share both data and code of a program. Threading concept is very important in Java through which we can increase the speed of any application. You can see diagram shown below in which a thread is executed along with its several operations with in a single process.
Threading Example
private int countDown = 5;
private static int threadCount = 0;
public SimpleThread() {
super("" + ++threadCount); // Store the thread name
start();
}
public String toString() {
return "#" + getName() + ": " + countDown;
}
public void run() {
while(true) {
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
for(int i = 0; i < 5; i++) new SimpleThread(); } } ///
Labels: Basic, JavaSE, Thread 0 comments
Netbeans warns you about sleep() and not about join() in Java Threading
if i put a thread to sleep in a loop, netbeans gives me a caution saying Invoking Thread.sleep in loop can cause performance problems. However, if i were to replace the sleep with join, no such caution is given. Both versions compile and work fine tho. My code is below (check the last few lines for "Thread.sleep() vs t.join()").
//Display a message, preceded by the name of the current thread
static void threadMessage(String message) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
try {
for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message threadMessage(importantInfo[i]); } } catch (InterruptedException e) { threadMessage("I wasn't done!"); } } } public static void main(String args[]) throws InterruptedException { //Delay, in milliseconds before we interrupt MessageLoop //thread (default one hour). long patience = 1000 * 60 * 60; //If command line argument present, gives patience in seconds. if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
}
threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
//loop until MessageLoop thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
//Wait maximum of 1 second for MessageLoop thread to
//finish.
/*******LOOK HERE**********************/
Thread.sleep(1000);//issues caution unlike t.join(1000)
/**************************************/
if (((System.currentTimeMillis() - startTime) > patience) &&
t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
//Shouldn't be long now -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
}
}
Its Because::
There is a difference between join() and sleep(). join() will wait until the timeout expires or the thread finishes. sleep() will just wait for the specified amount of time unless interrupted. So it is perfectly possible for join() to return much faster than the specified time.
The reason why Netbeans warns you about sleep() and not about join() is precisely that difference. join() waits for something meaningful while sleep() just sits there doing nothing. If you aren't waiting for something, then why would you want to wait at all? It is rarely meaningful, hence the warning.
Labels: Advanced, JavaSE, Thread 0 comments
Send Mail through Java
Send a mail in java is easy and deesnt require any fuss.
The JavaMail API is not part of core Java SE, but an optional extension. In addition, it is required in Java Enterprise Edition. The JavaMail packages can be accessed in two ways :
by placing j2ee.jar in the classpath
or, by placing both mail.jar and activation.jar in the classpath
The javax.mail API uses a properties file for reading server names and related configuration. These settings will override any system defaults. Alternatively, the configuration can be set directly in code, using the JavaMail API.
The foillowing code can help u guys::
An email configuration file (to run the example, substitute valid values for the uncommented items) :
# If a value for an item is not provided, then
# system defaults will be used. These items can
# also be set in code.
# Host whose mail services will be used
# (Default value : localhost)
mail.host=mail.blah.com
# Return address to appear on emails
# (Default value : username@host)
mail.from=webmaster@blah.net
# Other possible items include:
# mail.user=
# mail.store.protocol=
# mail.transport.protocol=
# mail.smtp.host=
# mail.smtp.user=
# mail.debug=
A class which uses this file to send an email :
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
* Simple demonstration of using the javax.mail API.
*
* Run from the command line. Please edit the implementation
* to use correct email addresses and host name.
*/
public final class Emailer {
public static void main( String... aArguments ){
Emailer emailer = new Emailer();
//the domains of these email addresses should be valid,
//or the example will fail:
emailer.sendEmail(
"fromblah@blah.com", "toblah@blah.com",
"Testing 1-2-3", "blah blah blah"
);
}
/**
* Send a single email.
*/
public void sendEmail(
String aFromEmailAddr, String aToEmailAddr,
String aSubject, String aBody
){
//Here, no Authenticator argument is used (it is null).
//Authenticators are used to prompt the user for user
//name and password.
Session session = Session.getDefaultInstance( fMailServerConfig, null );
MimeMessage message = new MimeMessage( session );
try {
//the "from" address may be set in code, or set in the
//config file under "mail.from" ; here, the latter style is used
//message.setFrom( new InternetAddress(aFromEmailAddr) );
message.addRecipient(
Message.RecipientType.TO, new InternetAddress(aToEmailAddr)
);
message.setSubject( aSubject );
message.setText( aBody );
Transport.send( message );
}
catch (MessagingException ex){
System.err.println("Cannot send email. " + ex);
}
}
/**
* Allows the config to be refreshed at runtime, instead of
* requiring a restart.
*/
public static void refreshConfig() {
fMailServerConfig.clear();
fetchConfig();
}
// PRIVATE //
private static Properties fMailServerConfig = new Properties();
static {
fetchConfig();
}
/**
* Open a specific text file containing mail server
* parameters, and populate a corresponding Properties object.
*/
private static void fetchConfig() {
InputStream input = null;
try {
//If possible, one should try to avoid hard-coding a path in this
//manner; in a web application, one should place such a file in
//WEB-INF, and access it using ServletContext.getResourceAsStream.
//Another alternative is Class.getResourceAsStream.
//This file contains the javax.mail config properties mentioned above.
input = new FileInputStream( "C:\\Temp\\MyMailServer.txt" );
fMailServerConfig.load( input );
}
catch ( IOException ex ){
System.err.println("Cannot open and load mail server properties file.");
}
finally {
try {
if ( input != null ) input.close();
}
catch ( IOException ex ){
System.err.println( "Cannot close mail server properties file." );
}
}
}
}
Labels: Basic, JavaSE, Mail 0 comments
Select Query of MySql in Java
For any Select query in java write::
{
boolean having=false;
String query="SELECT * FROM userinfo WHERE username='"+username+"'"+"AND password='"+pass_word+"';";
try
{
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery(query);
having=rs.next();
rs.close();
stmt.close();
}
catch (Exception e)
{
errmsg ="Cannot connect to database server/*/*/*/*"+e.getMessage();
JOptionPane.showMessageDialog(null,errmsg, "Error msg", JOptionPane.ERROR_MESSAGE);
}
return having;
}
Labels: Basic, Database, JavaSE 0 comments
Insert or NonExecutable Query of MySql in java
For queries like insert or delete or Update use these codes in java for MySql::
{
try {
Statement s3 = conn.createStatement();
s3.execute("insert into logged_in(user_id,logged_ip,logged_now) values('"+user_id+"','"+ip+"','yes')");
s3.close ();
return true;
}
catch(Exception e){
String err = "Cannot connect to database server: "+e.getMessage();
JOptionPane.showMessageDialog(null,"Please click logout before exiting", "Information", JOptionPane.INFORMATION_MESSAGE);
return false;
}
}
Labels: Basic, Database, JavaSE 0 comments
Connect to MySql with Java
First install the Mysql/Java connector in ur pc or add the dll files needed found here
MySql/J connector
final static String password = "";
final static String url = "jdbc:mysql://192.168.60.93/java";// String url = "jdbc:mySubprotocol:myDataSource"; ?
Statement stmt;
Connection conn=null;
for creating connection use the following codes which is easy:
{
try
{
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
errmsg ="Cannot connect to database server"+e.getMessage();
JOptionPane.showMessageDialog(null,errmsg, "Error msg", JOptionPane.ERROR_MESSAGE);
}
}
Labels: Basic, Database, JavaSE 0 comments
Send Attachments/files in Mail Java
The JavaMail FAQ can be found at the official java site here:
http://java.sun.com/products/javamail/FAQ.html
Q: How do I send a message with an attachment?
A: A message with attachments is represented as a MIME multipart message where the first part is the main body of the message and the other parts are the attachments. There are numerous examples showing how to construct such a message in the demo programs included in the JavaMail download package. To attach a file use the attachFile method of MimeBodyPart.
Q: How do I read a message with an attachment and save the attachment?
A: As described above, a message with an attachment is represented in MIME as a multipart message. In the simple case, the results of the Message object's getContent method will be a MimeMultipart object. The first body part of the multipart object wil be the main text of the message. The other body parts will be attachments. The msgshow.java demo program shows how to traverse all the multipart objects in a message and extract the data of each of the body parts. The getDisposition method will give you a hint as to whether the body part should be displayed inline or should be considered an attachment (but note that not all mailers provide this information). So to save the contents of a body part in a file, use the saveFile method of MimeBodyPart.
BodyPart bodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(yourFile);
bodyPart.setDataHandler(new DataHandler(source);
bodyPart.setFileName("MyFile.ext");
bodyPart.setDisposition(Part.ATTACHMENT);
// Then add to your message:
messageContent.addBodyPart(bodyPart);
Labels: JavaSE, Mail 0 comments
Java UDP Network Codes
Sending/Receiving Datagram Packets via UDP
The following are related to sending and receiving datagram packets via UDP.
1.DatagramPacket
2.DatagramSocket
DatagramPacket represents a datagram packet. Datagram packets are used for connectionless delivery and
normally include destination address and port information. DatagramSocket is a socket used for sending
and receiving datagram packets over a network via UDP. A DatagramPacket is sent from a DatagramSocketby
calling the send(...) method of DatagramSocket with DatagramPacket as the argument:
send(DatagramPacket dp). receive(DatagramPacket dp) is use for receiving aDatagramPacket.
(The MulticastSocket class may be used for sending/receiving aDatagramPacket to a mulitcast group. It is
a subclass of DatagramSocket that adds functionality for multicasting.)
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
UDP CLIENT PROGRAM
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Labels: Basic, JavaSE, Networking 0 comments
TCP Server side Code Java Part 1
Client Side Program
import java.lang.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class client
{
Public static void main(String args[])
{
Socket sock=null;
DataInputStream dis=null;
PrintStream ps=null;
System.out.println(" Trying to connect");
try
{
// to get the ip address of the server by the name
InetAddress ip =InetAddress.getByName
("Hari.calsoftlabs.com");
// Connecting to the port 1025 declared
in the Serverclass
// Creates a socket with the server
bind to it.
sock= new Socket(ip,Server.PORT);
ps= new PrintStream(sock.getOutputStream());
ps.println(" Hi from client");
DataInputStream is = new
DataInputStream(sock.getInputStream());
System.out.println(is.readLine());
}
0catch(SocketException e)
{
System.out.println("SocketException " + e);
}
catch(IOException e)
{
System.out.println("IOException " + e);
}
// Finally closing the socket from
the client side
finally
{
try
{
sock.close();
}
catch(IOException ie)
{
System.out.println(" Close Error :" +
ie.getMessage());
}
}
}
}
Labels: Basic, Networking, TCP 0 comments
TCP Server side Code Java Part 1
MAKING TCP CONNECTION
These classes are related to making normal TCP connections:
1.ServerSocket
2.Socket
ServerSocket represents the socket on a server that waits and listens for requests for service from a
client.Socket represents the endpoints for communication between a server and a client. When a server
gets a request for service, it creates a Socket for communication with the client and continues to listen
for other requests on the ServerSocket. The client also creates a Socket for communication with the
server.
Simple Server Client Messaging Using TCP
Server Side Program
// Import Java Packages
import java.net.*;
import java.lang.*;
import java.io.*;
public class Server{
//port number should be more than 1024
public static final int PORT = 1025;
public static void main( String args[])
{
ServerSocket sersock = null;
Socket sock = null;
System.out.println(" Wait !! ");
try
{
// Initialising the ServerSocket
sersock = new ServerSocket(PORT);
// Gives the Server Details Machine name,Port number
System.out.println("Server Started :"+sersock);
try
{
/* makes a socket connection to particular client after
which two way communication take place */
sock = sersock.accept();
System.out.println("Client Connected :"+ sock);
// Receive message from client i.e Request from client
DataInputStream ins = new DataInputStream(sock.getInputStream());
// Send message to the client i.e Response
PrintStream ios = new PrintStream(sock.getOutputStream());
ios.println("Hello from server");
ios.close();
// Close the Socket connection
sock.close();
}
catch(SocketException se)
{
System.out.println("Server Socket
problem "+se.getMessage());
}
catch(Exception e)
{
System.out.println("Couldn't start "
+ e.getMessage()) ;
}
// Usage of some methods in Socket class
System.out.println(" Connection from : " +
sock.getInetAddress());
}
}
Labels: Basic, Networking, TCP 0 comments
