Monday, January 21, 2008

JSON and HashMap

DWR is used for easy 'AJAX for JAVA' and is employed to call Java methods from Javascript (version 2.0 + supports reverse-AJAX too).

Working on the ShopprStream(earlier known as WEB122) has helped me get acquainted with many facets of web-development.


Now I have a Java method that returns a generic HashMap object ;
For this example lets consider that the key is of type String
And the elements are instances of the class CustomClass with name (of type String) as instance variable

The DWR call will return a JSON object. This is how we can access the dat
a


for (var key in hashMap)
{
//if not using Firebug, comment out console.log statements

//'key' is the key in the HashMap
console.log("key : "+ key);

//this will give the no. of elements stored corresponding to the 'key'
console.log("hashMap[key].length: "+ hashMap[key].length);

//Access individual elements corresponding to the 'key'
for(var i=0; i<hashMap[key].length; i++)
{
console.log("hashMap[key][i].name: " + hashMap[key][i].name);
}
}

If the HashMap contains custom objects, make sure it has a corresponding converter entry in the dwr.xml file


for example, if my class is called CustomClass, then write as

<convert converter="bean" match="com.pramati.web122.imsupport.ContactDetail"/>

Here, abc.xyz is the package structure

If object returned is hashmap, then values can be accessed as:
hasMap[key]

If object returned is hashmap, then values can be accessed as:
hasMap[key][0],
hasMap[key][1], hasMap[key][2] . . . . .

Thursday, January 17, 2008

Helpful JavaScripts

To bring focus to a text box / button or any other element

just add this javascript in the HTML code:

<script type="text/javascript">
document.getElementById("elementId").focus();
</script>
where
elementId the id of the element on which the focus is to be set

for example, the following code will bring focus to the textbox that has the id email
<input type="text" id="email" />
<script type="text/javascript">
document.getElementById("email").focus();
</script>

Wednesday, December 5, 2007

Fake Mail

One can send mails using JAVA Mail API. It is fairly simple to use this library to send mails.

First download the JAVA Mail API, and add mail.jar to your classpath
Then download, JAF API, and add activation.jar to your classpath

Following is the simple code:

Java Class: TestMail.java
import java.io.*;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import java.net.InetAddress;

class TestMail
{
public static void main(String args[])
{
try
{
//from address
String from = "fromaddress@somecompany.com";

//receipents of the mail
String to = "toaddress@someothercompany.com";

/*
*If there are multiple
*recepients, then email ids
*should be stored in a String
*with a space in between them.
*eg: String to = "id1@comp1.com id2@comp2.com id3@comp3.com"
*/

//subject of the mail
String subject = "Test Mail Subject";

//e-mail content
String text = "This is a test email";

/*SMTP host
*SMTP host should be correct
*for this program to work.
*Also, some SMTP servers
*are configured to allow
*messages to be sent from
*one or a few doamins
*/
String mailhost = "mail.somecompany.com";

//mailer
String mailer = "testmailer";

Properties props = System.getProperties();

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

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

//construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("X-Mailer", mailer);
msg.setSentDate(new Date());

//send the mail
Transport.send(msg);

System.out.println("\nMail was sent successfully.");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

WARNING:
When full headers are viewed by the recepeint for a mail sent by this program, it mite have an indication that there is something fishy about how the mail was sent !!


Happy Spamming !!!

Tuesday, December 4, 2007

JavaScript NULL

For JavaScript:

If you want to test whether a String object is NULL , then the following may FAIL

if(someString == "")

if(someString == "null")


The CORRECT way to test would be:

if(someString == null)


---------------------------------------------------------
Resources:

http://lists.evolt.org/archive/Week-of-Mon-20050214/169524.html

Monday, December 3, 2007

Post HTML codes in blogs

If you post articles with html tags on blogspot, it will most probably give an error message as:

ERROR
"Your HTML cannot be accepted: Tag is not allowed: "

The way to get around this is to convert all the mark-ups (eg: '<' , '>') into character-entities (eg: '&lt;' for '<' ; '&gt;' for '>')

One can use online applications that perform this conversion stuff:

http://www.stanford.edu/~bsuter/js/convert.html

If formatting has to be retained, then just enclose the code inside '<pre>' and '</pre>' tags.

Web Browser Compatibility !!!!

Developing on a web application is not easy if you intend to have the product compatible with all the available browsers in the universe for some new browser or its clone comes to life everyday.

This article is about how can one know which browser is being used by the end-user and how one can customize the code in accordance the same, be it IE or Mozilla Firefox or Safari or blah blah blaaaaaaaaaaaah !!!

The end-user browser can be determined by using navigator.appname

The following code illustrates the same:


<html>
<head>
<script type="text/javascript">
function navigatorName()
{
alert(navigator.appName);
}
</script>
</head>

<body onload="navigatorName()">
<div id="browserContents">
</div>
</body>
</html>


When the page gets loaded, the onload feature will call the javascript function navigatorName() which will display the alert box with the name of the browser as the message.

Now, inside the function navigatorName, we can write the logic that would make our code browser specific


<html>
<head>
<script type="text/javascript">
function navigatorName()
{
if(navigator.appName == "Netscape")
{
document.getElementById("browserContents").innerHTML = "Netscape";
}
else if(navigator.appName == "Microsoft Internet Explorer")
{
document.getElementById("browserContents").innerHTML = "MS IE";
}
else
{
document.getElementById("browserContents").innerHTML = "Some Browser";
}
}
</script>
</head>

<body onload="navigatorName()">
<div id="browserContents">
loading . . .
</div>
</body>
</html>

Here, when the body part of the page has been loaded, the browser calls the function navigatorName(). This function checks the browser being used, and in accordance to that, replaces the contents of the div with id browserContents appropriate contents by making use of the function document.getElementById("browserContents").innerHTML.

Sunday, December 2, 2007

Derby

I had a project work in which I needed to port an existing web-application running on MySQL toDerby. The SQL and datatypes of both are fairly same with minor variations (like syntax for triggers), though Derby does NOT support a few features like 'limit'.

TIPS:

If you are using embedded derby, remember, only ONE connection can be made to the database at a time. If applications running on different JVM's try to access the same database resource at the same time, then except the first one, none will be able to get access. So, go for Network server, if you have any such requirements.

----------------------------------------------

Username & Password

While creating the derby database, if username and password were not specified, and the application you are using requires one, then use the following if it doesn't accept blank/null fields

username: app
password: app

----------------------------------------------

Derby Network Server (for Windows)

Goto
%DERBY_INSTALL%\frameworks\NetworkServer\bin
and type "startNetworkServer.bat"

This will start the server and by default it will listen on port 1527

example:

In my machine Derby is installed in
C:\Program Files\Apache Software Foundation

So, value of the DERBY_INSTALL variable is "C:\Program Files\Apache Software Foundation\db-derby-10.2.1.6-bin"

So, the command "cd %DERBY_INSTALL%\frameworks\NetworkServer\bin"
opens up the following:
C:\Program Files\Apache Software Foundation\db-derby-10.2.1.6-bin\frameworks\Net
workServer\bin>

Now entering "startNetworkServer.bat" starts the server on port 1527

Remember, your derby database files must be located in the
"C:\> cd %DERBY_INSTALL%\frameworks\NetworkServer\bin" directory,
if you are run the server following the aforesaid.

From the program through which you wish access the database, give the following path of the database as:

"jdbc:derby://localhost:1527/dbname"

where 'dbname' is the name of the database.

If the database is located in some other folder, say D:/dbfolder, then modify the above as follows:

"jdbc:derby://localhost:1527/D:/dbfolder/dbname"

----------------------------------------------

Resources: