EJB3.0 Entity beans ID generator

June 13th, 2007

A quick tip, I got an error while deploying EJB3.0 entity beans on JBoss AS 4.0.4

I used an ID Generator as follow

@TableGenerator(name=”PK_GENERATOR”,
table=”PK_GENERATOR_TABLE”,
pkColumnName=”PRIMARY_KEY_COLUMN”,
valueColumnName=”VALUE_COLUMN”,
pkColumnValue=”ID”,
allocationSize=1)

and my entity contains an ID

@Id
@GeneratedValue (strategy=GenerationType.TABLE, generator=”PK_GENERATOR”)
@Column(name=”ID”, nullable = false)
private Integer Id;

If the id was not the first attribute declared in the class, the entity will not be deployed ! it is a bit strange to have a certain order for the attribute ….. I am recording it!!

AJAX DWR Singleton Creator

April 13th, 2007

In one of my messages in the DWR mailing list, I asked about how to use a singleton class in DWR, they kindly refered to http://getahead.org/dwr/server/dwrxml/creators/scripted the solution is to use BSF (Bean Scripting Framework) to initialize the class in dwr.xml, you should download & use the jar of BSF. I didn’t like both things (writing java code in the xml file and using another jar in my project). After few weeks, I got some Spring knowledge and noticed that it is easy in Spring to define singleton beans
<bean id="singleton" class="example.LegacySingleton" factory-method="getInstance"></bean>

last weekend, I went through DWR source code trying to implement the same thing to be used in my project. First I got the DWR source and added a new Creator for singleton in the dwr.xml I added this declaration
<creator id="singleton" class="org.directwebremoting.create.SingletonCreator"></creator>
The class implementation was easy with some Reflection staff, I will pass the function name which will initialize the object to the creator class, and I will use reflection to invoke this method and return the returned object.

Method method = clazz.getMethod(factoryMethod, null);
return method.invoke(new SingletonCreator(), null);

After that I made a simple singleton class “UserService”

package org.egjug.dwr;
/**
* @author Ahmed Hashim [hashim at egjug dot org]
*/
public class UserService
{
private static UserService userService = null;
public static UserService getInstance(){
if(userService == null){
userService = new UserService();
}
return userService;
}
/**
* private constructor
*/
private UserService()
{
System.out.println("Congratulation!");
}
/**
* A function to test the singleton class.
* */
public String helloWorld(String name){
return "Hello "+name;
}
}

The definition in the dwr.xml will be easy and clear

<create creator="singleton" javascript="userServiceSingleton">
<param name="class" value="org.egjug.dwr.UserService"></param>
<param name="factoryMethod" value="getInstance"></param>
</create>

This will be added to DWR2 http://getahead.org/blog/joe/2007/04/11/new_dwr_release_2_0_rc4.html

Tips to save client’s bandwidth

March 20th, 2007

In this post, I will write about the client/server bandwidth saving. In some countries, the cost of the Internet is based on the bandwidth consumption, you pay for the number of MB’s you have used as traffic, so, if there is a website which contains pages with large size, you will consume the client bandwidth! Also the request will take long time because of the large size of the page. People always talking about saving server bandwidth which is good, but it is important too to save the client’s bandwidth.
How can I save the client’s bandwidth?

  1. Don’t use images instead of text. Write the text and use CSS and javascript to add styles and effects for the text. For example, if you want to make a link to your homepage, some people use graphics package to write the word ‘Home’ and add effects, background color, borders..etc. All this staff can be done by CSS and JavaScript with a great feature “you can change the text without need to use any graphics package”. So, it is very important point to replace images with text as much as possible.
  2. Don’t use background image if it is blank, else use CSS background color.
  3. Don’t use a big image as background, try to make a small on and repeat is using CSS.
  4. Don’t write HTML comments in your code, instead, write server side comments in JSP, PHP …etc code.

    HTML comments <!-- comments -->
    JSP comments <%--comments --%>
    <?php
    //comments
    ?>
  5. Don’t copy-past from any word processor. The word processor like Microsoft Word add extra not-standard code, check this bulk of code

    <p class="MsoNormal" dir="ltr" style="text-align: left; unicode-bidi: embed"><span style="font-size: 10pt; color: black">Test
    the Microsoft Words HTML code!</span><span dir="rtl" lang="AR-SA"><o:p></o:p></span>
    I want just to write a statement “Test the Microsoft Words HTML code!” without any styles but the word add intelligent code :)
  6. Don’t make inline CSS, move it to a file. Don’t repeat the styles and reuse those in the common CSS. For example, you will repeat the same style for every item in a list like that

    <ul>
    <li style="color:#fffaaa;font-size:20;">1</li>
    <li style="color:#fffaaa;font-size:20;">2</li>
    <li style="color:#fffaaa;font-size:20;">3</li>
    <li style="color:#fffaaa;font-size:20;">4</li>
    </ul>
    While you can make

    .listItemStyle
    {
    color:#fffaaa;
    font-size:20;
    }

    and the list will be

    <ul>
    <li class="listItemStyle">1</li>
    <li class="listItemStyle">2</li>
    <li class="listItemStyle">3</li>
    <li class="listItemStyle">4</li>
    </ul>

    This will keep your code clean and easy to use. The code will be reusable and easy to maintain.
  7. Don’t make inline Javascript, move it to a file. This will promote reusability and maintainability.
  8. Use client side validatoin with JavaScript before submitting the data to the server. So, if there is an error in the data, you will not submit and back again.
  9. Use AJAX to send partial requests to the server. For example, if you have 2 dropdown, one for the country and another for the city and want to load the cities of the countries choose by the user, no need to submit the complete form, just send request with the country and use the returned data from the server to update the DOM of the page.
  10. Use JavaScript and CSS compressor to compress the javascript and css files, it will be sent to the client, so try to minimize the size as much as possible.
    The CSS compressor can reduce the size of the CSS files. You can use the DOJO compressor or any other javascript compressor.
  11. Use valid XHTML code to make sure that your code is correct.
  12. Use compression in the webserver/application server used in your application, this will compress the request/response and will save both client and servers’s bandwidth. This may have a performance impact. An example for tomcat configuration:

    <Connector port="8080" maxHttpHeaderSize="8192"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    connectionTimeout="20000" disableUploadTimeout="true"
    compression="no"
    />

    You will need to add to this four attributes:
    compression=”force”
    compressionMinSize=”2048″
    noCompressionUserAgents=”gozilla, traviata”
    compressableMimeType=”text/html,text/xml”
    Notice that there is a list of compressible MIME types. Basically:
    * compression=”no” means nothing gets compressed.
    * compression=”yes” means only the compressible MIME types get compressed.
    * compression=”force” means everything gets compressed (assuming the client accepts gzip and the response is bigger than compressionMinSize)You can test your application compression http://www.port80software.com/products/httpzip/compresscheck
  13. Use the ZipOutputStream as a resonse output stream if you will return to the user a big plain text file. This will compress the file on the server and send it, the client’s browser will extract it.

    String encoding = request.getHeader("Accept-Encoding");
    OutputStream out = null;
    if (encoding != null && encoding.indexOf("gzip") != -1) {
    response.setHeader("Content-Encoding", "gzip");
    out = new GZIPOutputStream(response.getOutputStream());
    }
    else if (encoding != null && encoding.indexOf("compress") != -1) {
    response.setHeader("Content-Encoding", "compress");
    out = new ZipOutputStream(response.getOutputStream());
    }
    else if (encoding != null && encoding.indexOf("deflate") != -1) {
    response.setHeader("Content-Encoding", "deflate");
    out = new DeflaterOutputStream(response.getOutputStream(), new Deflater(
    Deflater.BEST_COMPRESSION, false));
    }
    else {
    out = response.getOutputStream();
    }
    out.write(".....");
  14. Optimize your resources (images, flash).

This will result in save the client/server bandwidth and develop more fast web application.

References:

http://www.cssdrive.com/index.php/main/csscompressor/
http://dojotoolkit.org/docs/compressor_system.html
http://javascriptcompressor.com/
http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/ZipOutputStream.html
http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
http://www.codinghorror.com/blog/archives/000059.html
http://tomcat.apache.org/tomcat-5.5-doc/config/http.html
http://fmarcia.info/jsmin/test.html

Volunteer Activities Membership type

March 10th, 2007

For every volunteer activity, there are several types of people

  • Those who spend time, money and everything to get things done. As a result, they are the most beneficial of this activity.
  • Others who would like to join and contribute but don’t know how.
  • And others who would like to contribute but don’t have time.
  • Others who have time, want to contribute and know how to contribute, but finally do nothing :)
  • Hidden persons who always monitor the progress of the activities and get benefits but you will never ever know about them. If you are waiting for “Thank you” you will never get it form them .
  • Persons who get benefits from this activity and always not happy from the activity, complains, defending the volunteers and asking for better service and more efforts. If you are working in a volunteer activity, ignore this kind of people or be political :)
  • Others who don’t care. This is usual, so nothing wrong in that because not all people will be interested in what you are doing.
  • Some people who will overdo and say to you “WOW you are a great man, Well DONE !!. Are you who did that!! AMAZING”. If you are working in a volunteer activity, don’t listen too much to this staff.

I think the one can learn a lot from working in volunteer activities, the people understanding is a great experience!

Compare String to a literal.. coding style

March 8th, 2007

I saw many times code written by geeks, comparing String to literals in this style

public boolean compareUser(String name)
{
if("Ahmed Hashim".equals(name))
{
//do staff here
return true;
}
return false;
}

what is the difference between this and the normal code style?

public boolean compareUser(String name)
{
if(name.equals("Ahmed Hashim"))
{
//do staff here
return true;
}
return false;
}

You will miss the difference if you call both versions of the function like this


compareUser(null);

I think you got it, passing null will not need check in the first version because you are not accessing the “.equals” method inside the passed object, while the 2nd version will cause NullPointerException! :)

Windows Vista code –exclusive–

March 8th, 2007

/******
* (c) 2007 Misrocoft Corp.
* All rights reserved
**********/
#include
class WindowsVista extends WindowsXP implements Nothing
{
boolean beta = true;
WindowsVista( )
{
checkIfHardwareIsCompatible( );
/** Ok. The idiot seems to have some high end hardware.
* Lets make his life miserable
*/
runInternetExplorer7();
}

void checkIfHardwareIsCompatible( )
{
/*
* Lets make sure that half the world cannot run this OS while
* we fix all the bugs
*/
if((installedRam < 2GB) && (processorSpeed < 4GHz))
{
MessageBox(” Your System does not seem to be capable of running zero err..
aero glass and the like. Please upgrade the hardware and try again.”);
WaitTillPoorGuyReadsTheMessage( );
bsod(); // Blue Screen of Death http://en.wikipedia.org/wiki/Blue_Screen_of_Death
}
}

void runInternetExplorer 7()
{
IE7 ie7 = new IE7();
ie7.featureSet = firefox_features
+ safari_features
+ opera_features + lot_of_bugs;
ie7.run();
WaitWhileThePoorGuy LooksAtTheNewInt erface();
bsod();
}

/**
* return true when product is stable.
*/
boolean isReadyForRelease( )
{
int lastReportedNumberO fBugs = 3457888E+08
int totalNoOfNewFeature s = 600;
boolean readyForRelease = false;
sendFeatureSetToMar ketingGuys( );
while (marketingGuysAreAt It)
{
Thread fixBugsWhileInBeta = new fixBugsWhileInBeta( );
fixBugsWhileInBeta.assignProgrammer (oneBug);
fixBugsWhileInBeta.start();
if(programmersAreNotSufficient)
{
hireFromXBOXDivision();
}
if(aMonthHasPassed)
{
announce(”Windows Vista Consumer Version Will be delayed by one more
month”);
dropAFewFeatures( );
totalNoOfNewFeatures = totalNoOfNewFeatures - 10;
}

/** Boss strictly told me that we should have no more than * 7000 bugs
* when we ship the item
*/
if(lastReportedNumberOfBugs- - == 7000)
return true;
}
}

int main(void)
{
WindowsVista vista = new WindowsVista( );
vista.runWindowsXP( );
return plentyOfMoneyforBilly;
}
}

Load Message Resources from Struts Action

March 7th, 2007

Sometime, you will need to read some text from the resource files in your application from the Struts Action class. The easier way which most developers are using is to open the resource file using the java.util.ResourceBundle class, which will open the file and read its content.

PropertyResourceBundle properties=(PropertyResourceBundle)ResourceBundle.getBundle(propertyFileName);

This will open the file for every request to your action! I am sure that it is very bad from the performance point.

Struts provide a methods in the Action class to get the locale and the resources

getLocale(request) and getResources(request)

For some reason, getResources() didn’t work with me.

I didn’t think about the first solution because I am sure that the resources are loaded in the application and must be stored somewhere, so, lets use. And here is the code

MessageResources resources = (MessageResources) getServlet().getServletContext().getAttribute(bundle);
message = resources.getMessage(locale, key);

I hope that this can help somebody to tune the struts web application performance.

Discussing Arab Programmers: Roles and Future Prospects

February 20th, 2007

I have received this email from Islam Online Technology section team

Although software development and the programming community in Egypt and the Arab World have been around for more than two decades yet little seems to come out of the region by way of brand-name software products. Hundreds of software houses are opening across the region with only a few strong ones emerging as viable subcontractors to major software houses especially in the US . More graduates are coming out of newly established computer science departments in Arab universities with the cream of the software developers community finding better offers in silicon valley than at home. What is the role of Arab programmers in the international software development market, and what future lies for Arab programmers in the region? Can Arab economies launch on the virtual wave of the digital age?

Join us with your questions on Monday, February 19, 2007 from 14:00 to 15:30 GMT to discuss with Mr. Ahmed Adel, Developer and Platforms Manager at Microsoft Egypt , the Information Technology (IT) landscape in the Arab world.

A graduate of the faculty of Communications and Computer Engineering, Cairo University , and holder of a Masters degree in Computer Science from the University of Louisville, Kentucky, Adel started his career working 10 years for IBM. As the Development Manager in the Technology Development Center , Adel oversaw the execution of large scale, multi-disciplinary digital solutions for IBM’s offshore software services. After IBM, Adel joined the Egyptian IT conglomerate Raya Holding in 2001 where he was initially responsible for the establishment of a world-class development team in AIN, a Raya venture into the eCommerce space. For five years he held the position of General Manager for Raya Software. In November 2005, Ahmed moved to Microsoft Egypt to establish the Developer and Platforms division which is responsible for all activities related to software developers as students, customers, and participants in the software developers community at large. The Developer and Platforms division organizes a number of events and programs in Egypt including the .Net University , Imagine Cup and the annual Middle East Developers Conference last held 4-7 February, 2007.

You can send in your question in advance by e-mailing to ScienceTech@islam-online.net .

Open Source Software Presentation

February 18th, 2007

Yesterday, I made a presentation about Open Source Software in FCI-CU on the Connect 2 Success event. The number of attendees around 80, the seminar room was full and I found all students interested to know more about OSS.

The presentation is available, you can download it.

If you have attended the presentation, please give me your feedback.

Apache commons fileupload.. always lowercase file name

February 7th, 2007

Just as a reference for me and other poeple, a defect discovered while working with apache file upload, all files uploaded to the server are with lowercase file name. It is really annoying! I did a search and got a short answer from this site, which links to apache SVN. If any one want to solve it, rebuild the apache commons fileupload again.