Sunday, July 29, 2007

Primary Key vs. Unique Key

There are two differences between Primary key and Unique Key:

  • First and a trivial difference is that Unique Key would permit null value (one null value per cloum in the unique key constraint), while Primary key would not allow for null value.
  • Second and the major difference that you should know is that the Unique Key indexes are non-clustered while Primary key is clustered index. This difference has following corollaries

    • There could be only one PK per table emanating from the fact that there could be only one clustered index on a table.
    • The PK affects how the data is physically stored but a unique key doesn't.
Now the question is what is a clustered index and why there can be only one clustered index on a table. Clustered index is a index with leaf node containing actual data and not pointer to the actual data while for Unique Key index, leaf node contains pointer to the actual data storage.

HTTP Head method

HTTP HEAD request is similar to HTTP GET request except that the Server will not send and response body in response to the request. e.g. if you make a HEAD request to resource /image/test.jpg, server will send only the response status to the client (200 if the image exists) the actual image will not be transmitted to the client. This is useful in cases where you are referring an external resource and not sure if a resource exists on server or not. Or you want to know if you have access to certain resource on server, or ever if you just want to know when the resource on the server was last modified.

The HEAD request can be very useful specially with AJAX calls.

Reversing words in a String

This I think is by far most popular string Interview question, be it on Java/C/C++ or C#
Question : Write procedure to reverse the words in a String, assume words are separated by blank-spaces e.g. given a string "Writing and debugging software", the output of the procedure should be "software debugging and Writing"

Here is the code which i had written recently in Java, i think the code and algorithm is self-explanatory, but if you need help understanding the code please let me know.

If you have a big string and don't like the idea of O(n) space complexity and want to do it in O(1) space, than instead of putting words in word and to_ret arrays, you just store the array indexes and as soon as you find a blank space shift the original array up by the last word length and add the word to appropriate position in the string. This is just a hint i'll leave the implementation to you.. I can send you the code, if needed.


public class Reverse {
public static String reverse(String str) {
char[] chars = str.toCharArray();
char[] to_ret = new char[chars.length];
char[] word = new char[chars.length];
int l = 0;
int last = chars.length - 1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ' ') {
for (; l > 0; l--) {
to_ret[last] = word[l - 1];
last--;
}
to_ret[last] = ' ';
last--;
l = 0;
} else {
word[l] = chars[i];
l++;
}
}
//add the last word if any
if (l != 0) {
for (; l > 0; l--) {
to_ret[last] = word[l - 1];
last--;
}
}
return new String(to_ret);
}

public static void main(String[] args) {
String str = "This is a beautiful World";
System.out.println(str);
System.out.println(reverse(str));
}
}

Printing session attributes and request attributes in JSP for debugging

I generally like to use following JSP which I call req_session_attribute_printer.jsp for debugging purpose. I just include this jsp, where ever i want to debug, i have found this very useful over time for simple debugging.


<%--
req_session_attribute_printer.jsp
Author:<a href="mailto:get.anurag at gmail do com">Anurag Kumar Jain</a>
Date: July 25, 2007
--%>
<%@ page language="java" contentType="text/html; "%>
<script type="text/javascript">
function showHideAttributes(spanId){
if(document.getElementById(spanId).style.display=='block'){
document.getElementById(spanId).style.display='none';
}else if(document.getElementById(spanId).style.display=='none'){
document.getElementById(spanId).style.display='block';

}
}
</script>
<a href="#" onclick="showHideAttributes('debugSpan')"> Attributes</a>
<span id='debugSpan' style='display:none'>
Session Attributes:
<% java.util.Enumeration salist = session.getAttributeNames();
while(salist.hasMoreElements()){
String name=(String)salist.nextElement();
Object value = session.getAttribute(name);%>
<%=" "+name+"="+value %>
<% }%>
Request Attributes:
<% java.util.Enumeration ralist = request.getAttributeNames();
while(ralist.hasMoreElements()){
String name=(String)ralist.nextElement();
Object value = session.getAttribute(name);%>
<%=" "+name+"="+value %>
<% }%>
</span>



This is specially very helpful for debugging in environments other than dev, where you have less control.

IE Caching issue with AJAX HTTP GET request

There is one very annoying issue with IE using AJAX when you use a HTTP-GET request (I haven't faced this problem with HTTP-POST request). I tried following but nothing seemed to work:

response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server


So we need to fool IE to consider the request as new request everytime, and you can fool IE by adding current timestamp at the end of your url. You can do following in your Javascript code:

url= url+"?currDate="+ new Date(); if your url is simple like /test/something.do
OR
url= url+"&currDate="+ new Date(); if your url contains request parameters and looks something like /test/something.do?id=1234

Hibernate Reverse engineering tool

May time you want to reverse engineer the Hibernate definitions from already existing scheme. Hibernate tools with Ecliplse plutgin is a very useful for this purpose, more information here on hibernate.org.

Creating your own ajax loading image

I found this useful for creating images for my AJAX loading ICONs http://www.ajaxload.info/

Enabling Expression Language (EL) in JSP

You can do it in two ways:

  • Enable it for whole application : Put following in web.xml

    <jsp-config>
    <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <el-ignored>false</el-ignored>
    </jsp-property-group>
    </jsp-config>

  • Enable it for just one JSP page : put following at top of your JSP Page
    <%@ page isELIgnored="false" %>
Make sure when you use the first option you use 2.4 schema or above. i. e. your root tag in web .xml looks something like this.

< web-app id="WebApp" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

make sure you are using Jasper jars for JSP 2.0 or above.

Saturday, July 28, 2007

AndroMDA: Generating create/drop schema script with Maven 2

First of all I would recommend anyone who is using the anroMDA for first time to read
${application_root}/readme.txt file carefully. This helps understanding the generated schema.

If you read readme.txt, you will notice two tasks

  • mvn -f core/pom.xml andromdapp:schema -Dtasks=create --> generates the DDL create code and subsequently tells the database to create the schema for the entities

  • mvn -f core/pom.xml andromdapp:schema -Dtasks=drop --> generates the DDL drop code and subsequently tells the database to drop the schema for the entities

  • mvn -f core/pom.xml andromdapp:schema -Dtasks=drop,create
But wait, these target don't seem to work for me if i use maven-2 (mvn) with AndroMDA 3.2.
add following to the plugin configuration in core/pom.xml
<executescripts>false</executescripts>
<tasks>create</tasks>
<tasks>drop</tasks>
and now when you run the above targets, the create and drop DDLs are generated in the path specified by createOutputPath and dropOutputPath property.

The default location for generated scripts is ${application_root}/app/target/

Remote and Local EJB with AndroMDA

@andromda.ejb.viewType "both" isn't supported, that's the reason. If you want to use remote at all, then set it to "remote", most application servers (like JBoss) treat remote interfaces as local when they're in the same JVM anyway.

Understanding Java Security and permission

This is a must read for any java programmer, combined with this article on JavaWorld