Saturday, August 27, 2011

to solve javascript disable browser

If you use javascript code for your application, you should not depend fully on it for various important checking. Beside it, server side checking also should be implemented. Because, if javascript of the web browser is disabled then, all checking will be stopped with it.

But, there is an another option of the disabling problem of javascript. There is a tag <NOSCRIPT>, which is use when javascript is not found in the browser. And message can be showed inside this <NOSCRIPT> tag. Beside showing message it can also be used to hide a page element from the page. An example of code snap of using <NOSCRIPT> tag. <NOSCRIPT> tag should be used inside <HEAD> tag

Code Example of NOSCRIPT


<noscript >
<style type="text/css">
.pagecontainer {display:none;}
</style>
<div style="color: red; text-decoration: blink;font-size: xx-large" align="center">
This page uses Javascript. Your browser either doesn't support Javascript or you have it turned off.
To see this page as it is meant to appear please use a Javascript enabled browser
</div>
</noscript>

Friday, August 26, 2011

javamail: to access mail through java

The JavaMail API is a set of abstract APIs that model a mail system.The JavaMail API provides facilities for reading and sending email. Service providers implement particular protocols. Several service providers are included with the JavaMail API package; others are available separately.


Download Javamail



If a web-based email services provide POP3 or IMAP access, JavaMail can probably be used to access it.


IMAP:IMAP stands for Internet Message Access Protocol. It is a method of accessing electronic mail messages stored on a (possibly shared) mail server. In other words, it permits a "client" email program to access remote message stores as if they were local.


SMTP
SMTP stands for Simple Mail Transfer Protocol. It is used to transfer RFC822-style messages between different mail hosts as well as to submit new messages to a host for delivery. SMTP is in very wide use (it originated in 1982).



MIME
MIME and RFC822 are the standards for describing email messages that are sent across the Internet. The javax.mail.internet subpackage (which is part of the JavaMail APIs) provides a complete implementation of these two packages. MIME is specified by the following RFCs: RFC2045, RFC2046, RFC2047.




POP3

POP3 stands for Post Office Protocol version 3. POP3 is a very limited protocol for accessing a single mailbox. It is much less capable than IMAP. POP3 is very widely used and is defined by RFC1939.


To use javamail with your project, Unzip the distribution zip file and edit your CLASSPATH environment variable to include the mail.jar file that was included with the JavaMail API distribution.

At contect of Netbeans, javamail can be addred asfollowing steps:
Q: How do I add the JavaMail library to my NetBeans Java Project?
A: Use the Library Manager to create a library and add a reference to that library to your project.

1. Inside Netbeans, open the Library Manager (Tools > Libraries from the main menu bar).
2. Select
3. Enter a library name, e.g., "JavaMail", and hit . Do not check server library.
4. Make sure the new library is selected under "Libraries" on the left.
5. Select the "Classpath" tab on the right and choose
6. Using the file browser, select mail.jar from your JavaMail installation (e.g. .../javamail-1.4.3/mail.jar), and hit to accept.
7. Select the "Javadoc" tab and choose
8. Using the file browser, select the folder where the JavaMail javadoc index files are (e.g. .../javamail-1.4.3/docs/javadocs"), and hit to accept.
9. If you downloaded the JavaMail source code, you can set the source code reference on the "Sources" tab. This can be helpful for debugging. Using the file browser, select the source root for the JavaMail sources (".../javamail-1.4.3/mail/src/main/java" for 1.4.3) and hit to accept.

Note: If you are using JDK 1.5.0 or earlier you will need to add the JavaBeans Activation Framework library as well. You can create a separate library in a manner similar to the above, or just add activation.jar (and javadoc/source references if desired) to this library definition.

Now add a reference to this library to your project.

1. Open your project in NetBeans and make sure the "Projects" tab is visible.
2. Right click your project in the project explorer and select "Properties"
3. In the Properties dialog, select "Libraries" in the tree on the left and make sure the "Compile" tab is selected.
4. Click
5. Locate and select the library you created above and click "Add Library". It should be added to the list of compile-time libraries.
6. Click "OK" and you're done.



The JavaMail API package does not include any mail servers. To use the JavaMail API package, you'll need to have access to an IMAP or POP3 mail server (for reading mail) and/or an SMTP mail server (for sending mail). These mail servers are usually provided by your Internet Service Provider or are a part of your organization's networking infrastructure.



JavaMail 1.4 is capable of sending and reading messages using Gmail. All that's required is to properly configure JavaMail. I'll illustrate the proper configuration using the demo programs that come with JavaMail - msgshow.java and smtpsend.java.

Let's assume your Gmail username is "user@gmail.com" and your password is "passwd".

To read mail from your Gmail Inbox, invoke msgshow as follows:

java msgshow -D -T pop3s -H pop.gmail.com -U user -P passwd


By reading the msgshow.java source code, you can see how these command line arguments are used in the JavaMail API. You should first try using msgshow as shown above, and once that's working move on to writing and configuring your own program to use Gmail. The following code fragment shows a simple way to incorporate the needed configuration in your application:

String host = "pop.gmail.com;
String username = "user";
String password = "passwd";
// ...
Store store = session.getStore("pop3s");
store.connect(host, username, password);



To connect to Gmail using the IMAP protocol instead of the POP3 protocol, simply change the host name "pop.gmail.com" to "imap.gmail.com" and change the protocol name "pop3s" to "imaps" in the above instructions.

To send a message through Gmail, invoke smtpsend as follows:

java -Dmail.smtps.host=smtp.gmail.com -Dmail.smtps.auth=true
smtpsend -d -S -M smtp.gmail.com -U user -P passwd -A user@gmail.com


(Note that I split the command over two lines for display, but you should type it on one line.)

A bug in older versions of the smtpsend command causes it to set the incorrect properties when using the -S (SSL) option, so we work around that bug by setting them on the command line. The smtpsend program uses the System properties when creating the JavaMail Session, so the properties set on the command line will be available to the JavaMail Session.

The smtpsend program will prompt for a subject and message body text. End the message body with ^D on UNIX or ^Z on Windows.

Again, you can read the smtpsend.java source code to see how the command line arguments are used in the JavaMail API. The following code fragment shows a simple way to incorporate the needed configuration in your application:


    String host = "smtp.gmail.com;

String username = "user";
String password = "passwd";
Properties props = new Properties();
props.put("mail.smtps.auth", "true");
// ...
MimeMessage msg = new MimeMessage(session);
// set the message content here
Transport t = session.getTransport("smtps");
try {
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}









Thursday, August 25, 2011

In JSP, Rendering a dropdrownlist on the basis of another dropdownlist's selection value

Its a little bit difficult to change a drop down list on basis of another selected value of drop down list in jsp. To do so, we need to use help from ajax. And the specific function of the ajax file is called onchange event of the (decision maker) drop down list.


onchange="loadDDLfirst()"

The loadDDLfirst() file is written in a javascript file(i.e, name of the javascript file is ajaxjs.js)




//////////////---Code of ajaxjs.js----///////////////////////
var xmlhttp;

var nm;
function loadDDLfirst()
{

/*To save the name of the District*/

var w = document...selectedIndex;
var selected_text = document...options[w].text;
document..selected_District.value=selected_text;

/////-----------------------------/////
var districtID;
parameterValue = document.getElementById("ddlFirst").value;

xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}

//////////////---End of code of ajaxjs.js----///////////////////////


/* Actually the drop down list is generated at another webpage consisting on the dropdown list. And each time a random no. is added with the url to make identity of the request*/
url ="<webpageurl>?=" + parameterValue + "&idn=" + Math.random() * 100;
xmlhttp.onreadystatechange=getValues;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function getValues()
{
if (xmlhttp.readyState==4)
{
document.getElementById("load_ddl2ND").innerHTML=xmlhttp.responseText;
}
}


load_ddl2ND is the id of the form element where the webpageurl.jsp page will be showed. The webpageurl.jsp contains the code to create the dropdownlist.


<%
///Code to load simple dropdownlist as in normal jsp
%>



Sunday, August 14, 2011

show Image from database in jsp


We can provide a servlet as the source of the image. ans in the servlet we need to some little cook. This code may help you in the regards.

/*
* This Method Returns the right MIME type for a particular format
*


* @param String format ex: xml or HTML etc.
* @return String MIMEtype
*/
private String getMimeType(String format)
{
if(format.equalsIgnoreCase("pdf")) //check the out type
return "application/pdf";
else if(format.equalsIgnoreCase("audio_basic"))
return "audio/basic";
else if(format.equalsIgnoreCase("audio_wav"))
return "audio/wav";
else if(format.equalsIgnoreCase("image_gif"))
return "image/gif";
else if(format.equalsIgnoreCase("image_jpeg"))
return "image/jpeg";
else if(format.equalsIgnoreCase("image_bmp"))
return "image/bmp";
else if(format.equalsIgnoreCase("image_x-png"))
return "image/x-png";
else if(format.equalsIgnoreCase("msdownload"))
return "application/x-msdownload";
else if(format.equalsIgnoreCase("video_avi"))
return "video/avi";
else if(format.equalsIgnoreCase("video_mpeg"))
return "video/mpeg";
else if(format.equalsIgnoreCase("html"))
return "text/html";
else if(format.equalsIgnoreCase("xml"))
return "text/xml";
else
return null;
}

Step Two
Get the reference to the right OutPutStream. Use ServletOutPutStream, where as for character data you'd use PrintWriter, the java.io class that prints objects to a text-output stream. This following snippet is for binary data:


ServletOutputStream sOutStream = response.getOutputStream();

Step Three
Create BufferedInputStream from the InputStream:


BufferedInputStream bis = null;
InputStream in = urlc.getInputStream();
bis = new BufferedInputStream(in);




Step Four
Create BufferedOutPutStream with a new ServletOutPutStream to which you can write:


BufferedOutputStream bos = null;
bos = new BufferedOutputStream(sOutStream);

Step Five
Read in to the bytes array from BufferedInputStream:


byte[] buff = new byte[length];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}

Step Six
Write on to BufferedOutPutStream from the bytes array, which in turn streams to the client. Use the streamBinaryData() method for binary data streaming:


/*
* This Method Handles streaming Binary data
*


* @param String urlstr ex: http;//localhost/test.pdf etc.
* @param String format ex: pdf or audio_wav or msdocuments etc.
* @param ServletOutputStream outstr
* @param HttpServletResponse resp
*/
private void streamBinaryData(String urlstr,String format,
ServletOutputStream outstr, HttpServletResponse resp)
{
String ErrorStr = null;
try{
//find the right MIME type and set it as contenttype
resp.setContentType(getMimeType(format));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
URL url = new URL(urlstr);
URLConnection urlc= url.openConnection();
int length = urlc.getContentLength();
resp.setContentLength(length);
// Use Buffered Stream for reading/writing.
InputStream in = urlc.getInputStream();
bis = new BufferedInputStream(in);
bos = new BufferedOutputStream(outstr);
byte[] buff = new byte[length];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
ErrorStr = "Error Streaming the Data";
outstr.print(ErrorStr);
} finally {
if( bis != null ) {
bis.close();
}
if( bos != null ) {
bos.close();
}
if( outstr != null ) {
outstr.flush();
outstr.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}

N.B In the up coming post, i will try to note a complete sequence to show image from database.

Friday, August 12, 2011

Servlet Life cycle




* The servlet is initialized by calling the init () method.
* The servlet calls service() method to process a client's request.
* The servlet is terminated by calling the destroy() method.
* Finally, servlet is garbage collected by the garbage collector of the JVM.



The life cycle of a servlet can be categorized into four parts:

1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute of web.xml file. If the attribute has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.



2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {
// Initialization code...
}



3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.

The service() method :

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}

The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.



4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.