Ashik’s IT Thoughts

November 20, 2015

Working with Fixed Map – Unmodifiable or Immutable?

Filed under: Java — ashikuzzaman @ 2:18 pm

We often have to work with a defined collection of values in our programs. Maps are one way of holding those defined values and retrieving those by names when we need to use. One easy way of reusing those predefined values have been using static maps in a class so that we don’t instantiate those same values again and again every time we use it. That’s a very basic and minimal thing to start with for any program.

But as your system goes bigger and you start sharing code among many team members and many modules of your system, and as performance issues become more important than anything else, and on top of it if you are working on multi-threaded environments – you know you have to play the game at a higher level than this.

We recently hit a relevant bug around using static hashmap that led me to refactor and restructure a similar basic code to a more sophisticated fixed collection. I learnt that the use case for a completely fixed map is not well understood and clear to everyone. At the end of the analysis and refactoring what I came up with can be simplified to a small program that I developed for my readers here.

Please look at my public github repository for the source code while I walk you through it – https://github.com/ashikuzzaman/javashare

There are two major ways of generating a fixed map other than writing your own collection data structure. First option is what comes with Java Standard Edition – an API to make any collection unmodifiable that gives you a read-only view of a modifiable collection. For Map it is Collections.unmodifiableMap(map).

Second option to make a map fixed we get from Google’s Guava library – Immutable collections. For Map, it is ImmutableMap which can be used instead of HashMap that we use more often in simple java programs. It makes sure once you build the map, you can no more add, update or remove any entry from it. While both of these give you a simplistic fixed size map, they have important behavioral difference. Additionally, none of them can guarantee you a truly fixed map where not only entries can’t be manipulated but each value for each entry also can’t be manipulated either. Let’s see where the gap is with them and how we can overcome the gap.

In FixedMap.java, FixedContentMap.java and FixedMapRunner.java from the above project, we are working with a modifiable map, an unmodifiable map (that wraps around the modifiable map) and an immutable map (that picks the values of the modifiable map to build itself). Both unmodifiable map and immutable map, once built, will not allow you to add any new element, remove any existing element or update any element with a new value using their own references. But we can add any number of elements to modifiable map even after the other 2 maps are built out of it. And that’s where the difference between unmodifiable map and immutable map becomes evident. Look at the program output for first 4 print statements and see where unmodifiable map falls short. While immutable map wont change in size even if you add new entry to the modifiable map out of which it was built, the unmodifiable map will increase in size as long as you are using a different entry point (other than the reference variable of unmodifiable map itself) to the modifiable map to add new elements. So clearly, Immutable map has an edge over Unmodifiable map when it comes to working with fixed maps.

fixedmaprunner

However, the next 4 print statements (5 to 8) show the shortcomings of both unmodfiable and immutable maps. When you say the map is immutable, you are only making sure no add, delete or update happens at an element level, more precisely, using the key of the element. But nothing is stopping you from adding a new element inside the values of a map, if the value itself is a collection. So in our case each map element values are individual set of Strings. So nothing is stopping the program to add values inside those Strings using the unmodifiable or immutable map references. This is the result of famous copy by value and copy by reference debate of Object Oriented Programming. And hence you see new values got added for “animals” as part of #7 and #8 prints. So despite Immutable map doing a better job than Unmodifiable map, I call it a fake fixed map. A true fixed map, better if I coin a term fixed content map, needs to ensure that even the individual values for each element is untouchable (i.e. read only).

To achieve that we extend FixedContentMap from FixedMap (because all fixed content map is a fixed map but some fixed maps may be fake fixed maps!). We just build the values in fixed content map as immutable sets. So now if anyone wants to change the value of the fixed content map, including the contents of any element – they will face a java.lang.UnsupportedOperationException as is evident when you run the program (you won’t see print statement #12 ever getting executed).

So my conclusion is, if used correctly, Google’s Guava library will allow you to work with truly fixed content collections in Java.

May 11, 2015

My First Java Code Commit to GitHub

Filed under: IT, Java — ashikuzzaman @ 11:46 am

My First Java Code Commit to GitHub. For now I have started with a simple class and will keep adding more classes as I get time –  ListPerformanceTestSimple.java

https://github.com/ashikuzzaman/javaapichecks

I had to do some trial and error before finally all the setups worked in my Ubuntu box. You can save the trial and error time if you follow the steps below that I performed –

1. Register a github account – https://github.com/

2. create a repository – look at top right + sign after you log in.

3. setup authentication from github to git. You can read through this article if you need some help or simply execute the commands that I typed below in sequence – https://help.github.com/articles/set-up-git/#next-steps-authenticating-with-github-from-git or http://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository
3a. $ git config –global user.name “ashikuzzaman”
3b. $ git config –global user.email “ashikuzzaman@gmail.com
3c. $ git config –global core.editor gedit
3d. $ git config –list
3e. $ git log

4. Clone your repository in your local workspace –  $ git clone https://github.com/ashikuzzaman/javaapichecks.git

5. Add a new .java file, locally compile and run. For example, javac -d . ListPerformanceTestSimple.java

6. $ git add ListPerformanceTestSimple.java

7. $ git status

8. $ git commit -m “my first commit from command line to github”

9. $ git push origin master

November 25, 2011

Finding Union and Intersection of 2 Large Lists

Filed under: IT, Java — ashikuzzaman @ 10:15 am

One of my colleague who works on performance tracking and tuning of applications asked for some helped around how to find the union and intersection of large lists. He works mostly on Python and Perl. Being a Java guy, I prepared a sample program for him to do this allowing to determine the size of the lists by himself. He was happy to get the program and once I explained him a bit about the retailAll(), addAll() and removeAll() API of Java and how I used those to determine the union and intersection, it was very clear to him. I am giving that program here in case it helps you as a reference implementation.


package com.salesforce.test;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;

/**
* To compiple: javac -d . ListPerformanceTest.java
* To run: java com.salesforce.test.ListPerformanceTest
*
* @author ashik
*/
public class ListPerformanceTest {

private int LOOP_COUNT = 50000;
private List firstList;
private List secondList;

public ListPerformanceTest() {
firstList = new ArrayList();
secondList = new ArrayList();
for(int i = 0; i < LOOP_COUNT; i++) {
if(i % 3 != 0 || i % 5 != 0) {
firstList.add("ashik - " + i);
}
if(i % 9 != 0) {
secondList.add("ashik - " + i);
}
}
}

public static void main(String[] args) {
System.out.println("\nListPerformanceTest starts.....\n");
ListPerformanceTest perf = new ListPerformanceTest();
List intersection = new ArrayList();
List union = new ArrayList();

Date d1 = new Date(System.currentTimeMillis());
System.out.println("d1 = " + d1);
for(String value : perf.firstList) {
System.out.println("value for firstList = " + value);
}
Date d2 = new Date(System.currentTimeMillis());
System.out.println("d2 = " + d2);
for(String value : perf.secondList) {
System.out.println("value for secondList = " + value);
}
Date d3 = new Date(System.currentTimeMillis());
System.out.println("d3 = " + d3);

System.out.println("perf.firstList.size() = " + perf.firstList.size() + " and perf.secondList.size() = " + perf.secondList.size());

if(perf.firstList.size() >= perf.secondList.size()) {
intersection.addAll(perf.firstList);
intersection.retainAll(perf.secondList);
} else {
intersection.addAll(perf.secondList);
intersection.retainAll(perf.firstList);
}
Date d4 = new Date(System.currentTimeMillis());
System.out.println("d4 = " + d4);
System.out.println("intersection.size() = " + intersection.size());

if(perf.firstList.size() >= perf.secondList.size()) {
union.addAll(perf.firstList);
union.removeAll(perf.secondList);
union.addAll(perf.secondList);
} else {
union.addAll(perf.secondList);
union.removeAll(perf.firstList);
union.addAll(perf.firstList);
}
Date d5 = new Date(System.currentTimeMillis());
System.out.println("d5 = " + d5);
System.out.println("union.size() = " + union.size());

System.out.println("\nListPerformanceTest ends.....\n");
}

}

The significant part from the output when you run the program is given below.

d3 = Fri Nov 25 10:03:36 PST 2011
perf.firstList.size() = 46666 and perf.secondList.size() = 44444
d4 = Fri Nov 25 10:03:55 PST 2011
intersection.size() = 42222
d5 = Fri Nov 25 10:04:14 PST 2011
union.size() = 48888

December 19, 2010

Small Java Program To Convert Unicode Character Filled Sentences To Native or UTF-8 Character Filled Sentences

Filed under: IT, Java, Official — ashikuzzaman @ 12:58 pm

My colleague John asked for a tool from me last week so that he can finish the translations / localization works that he was doing. To solve it in a lazy way, I did some google around a bit but couldn’t figure out any easy tool that will convert Unicode characters \uxxxx to native locales. There are plenty of tools available to convert natives to UTF-8 and even the below simple command works in java for native to utf-8 :

native2ascii.exe -encoding UTF-8 your-input-file-name.properties your-output-file-name.properties

So what I have done is just written a small java program that will help you to achieve the reverse of it i.e. converting from unicode to native / utf-8. Here are the steps you will need to perform.

package com.salesforce.test;

import java.io.*;

/**
* To compile: javac -d . SfdcUnicodeToNativeConverter.java
* To run: java com.salesforce.test.SfdcUnicodeToNativeConverter
*
* @author ashik
*/
public class SfdcUnicodeToNativeConverter {

private static String fileName = "output.properties";

private static String sentenceToConvert = "cmgt_configurator/Sfdc_common_summary_32=\u304a\u652f\u6255\u3044\u60c5\u5831\u306e\u5165\u529b";

/*
\u304a\u652f\u6255\u3044\u60c5\u5831\u306e\u5165\u529b
\u304a\u652f\u6255\u3044\u6761\u4ef6 & \u5951\u7d04\u671f\u9593\u306e\u7de8\u96c6
\u6b64\u8ba2\u5355\u7684\u603b\u4f63\u91d1+
\u82e5\u8981\u7e7c\u7e8c\u7d50\u5e33\uff0c\u60a8\u5fc5\u9808\u8a73\u95b1\u8b80\u4e26\u63a5\u53d7\u4ee5\u4e0b\u6240\u5217\u6bcf\u500b\u7522\u54c1\u7684\u689d\u6b3e\u3002
*/
public static void writeOutput(String str, String fileName) {
System.out.println("Unicode to Native Conversion Starts...");
try {
FileOutputStream fos = new FileOutputStream(fileName);
Writer out = new OutputStreamWriter(fos, "UTF8");
out.write(str);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Unicode to Native Conversion Successful!");
}

public static void main(String[] args) {
writeOutput(sentenceToConvert, fileName);
}

}

1. Make sure sure you have JDK installed in your system. Set the environment variable JAVA_HOME in to point to JDK (alternatively there is a shorter way that I can show you).
2. Copy the source java file from the following network location into your machine – \\moorea\departments\AppStore\Comergent\Programs\SfdcUnicodeToNativeConverter.java
3. Open the source file in TextPad or Crimson Editor and replace the value for the variable sentenceToConvert to the actual sentence that you are trying to translate / convert.
4. Compile the java file that I wrote using the command javac -d . SfdcUnicodeToNativeConverter.java
5. Run the program to generate the output file using the command java com.salesforce.test.SfdcUnicodeToNativeConverter
6. A new file named output.properties should be generated in the same folder from where you ran the program.
7. Open this file with Altova Xml Spy or Notepad with UTF-8 Encoding to preserve the file format correctly. You may see some characters that look like junk. Don’t worry, those are not junks.
8. Copy the content from the file in Xml Spy or Notepad and paste those into a new MS Excel Spreadsheet. Now you should see the native characters properly. You can use those for translation purposes I your models.

I have tried to write down the steps above clearly as you will need to perform those repeatedly for each line of translations for each locale. Being a little innovative, you can use the steps above for multi-line translations as well by adding proper \n” + ” to hold many properties / values in the sentenceToConvert variables.

March 15, 2010

Convert Http URL to Https URL – A Short Sample Code

Filed under: Java, Web — Tags: , , , , — ashikuzzaman @ 7:31 pm

Here is an example of how you convert an Http URL to a secured URL (Https). Here I am assuming the URL will be fully standard i.e. even the default port 80 will be written after colon as :80 and same for default https port :443.


package com.google.test;

/**

* To compiple: javac -d . ConvertHttpToHttps.java

* To run: java com.google.test.ConvertHttpToHttps

*

* @author ashik

*/
public final class ConvertHttpToHttps {

private static String url = "http://configure.google.com:80/AppStore/en/US/enterpriseMgr/AppStore";

public static void main (String[] args) {
System.out.println("url before replacing = " + url);
System.out.println("url after replacing = " + convert(url));
}

public static String convert(String url) {
StringBuffer result = new StringBuffer();
if(url.startsWith("http://")) {
String strColon = url.substring(7);
result.append("https://");
int colonIndex = strColon.indexOf(":");
String portNumber = strColon.substring(0, colonIndex);
result.append(portNumber);
result.append(":443" + strColon.substring(colonIndex+3));
}
return result.toString();
}

}

March 13, 2010

Replacing $ in a String in Java

Filed under: Java — Tags: , , , , , , — ashikuzzaman @ 3:25 am

I faced an issue in my project where we read a password for an admin user first from a file which has a dummy or wrong password written in it. Then I read the password from database and replace the dummy password with the real password that I get from Database. So the code was something very simple like this (this is actually different from original).


String myXmlDoc = readALargeXmlAsString();
String realPassword = readFromDatabase();
String password = myXmlDoc.replaceAll("dummyPassword", realPassword);

All on a sudden we found that this replacement started failing after the password of that admin user was changed recently. Here is the exception log.

Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
at java.util.regex.Matcher.appendReplacement(Matcher.java:706)
at java.util.regex.Matcher.replaceAll(Matcher.java:806)
at java.lang.String.replaceAll(String.java:2000)
at com.salesforce.test.StringReplaceTest.main(StringReplaceTest.java:34)

So I figured out from the log that it’s actually the replaceAll() pattern matching method that is causing the failure when you have $ in your replacement string (not in the pattern itself). So as per the first code example, if you had a $ character as one of the characters for realPassword, then it would throw the exception above. While the solution was to use a different admin for now who doesn’t have a password containing $ sign, I sat down to investigate it in detail and write a long term solution.

First I reproduced the issue in 3 different ways. Here is a code that will tell you depending on where you are putting the $ sign, the exception stack trace will be different. I give you the code and the compile and run instructions so that you can test it yourself.

package com.salesforce.test;

/**
* To compile: javac -d . StringReplaceTest.java
* To run: java com.salesforce.test.StringReplaceTest
* or, java com.salesforce.test.StringReplaceTest start
* or, java com.salesforce.test.StringReplaceTest middle
* or, java com.salesforce.test.StringReplaceTest end
* @authot ashik
*/
public class StringReplaceTest {

public static void main(String[] args) {

System.out.println("\nStringReplaceTest starts.....\n");

String firstStr = "I am a Java programmer working in USA. Chess is my hobby and here in USA lot of people play chess.";

System.out.println("firstStr before replacing = " + firstStr);

String positionPOfDollarSign = "";
if(args.length > 0) {
positionPOfDollarSign = args[0];
}
String secondStr = "";
if("start".equalsIgnoreCase(positionPOfDollarSign)) {
secondStr = firstStr.replaceAll("USA", "$PUT_A_VALUE123"); // illegal group reference
} else if("middle".equalsIgnoreCase(positionPOfDollarSign)) {
secondStr = firstStr.replaceAll("USA", "PUT_A_VALUE$123"); // String index out of range: 15
} else if("end".equalsIgnoreCase(positionPOfDollarSign)) {
secondStr = firstStr.replaceAll("USA", "PUT_A_VALUE123$"); // java.lang.IndexOutOfBoundsException: No group 1
} else {
secondStr = firstStr.replaceAll("USA", "PUT_A_VALUE123"); // no error
}

System.out.println("\nsecondStr after replacing firstStr = " + secondStr);

System.out.println("\nStringReplaceTest ends.....\n");
}

}

Developing the fix was a little tricky as replacing the $ and \ characters (these 2 are what makes trouble) using regular methods like Spring.split() or StringTokenizer class doesn’t work as those itself can’t process $ correctly. So I had to do my search and replace based on the String.indexOf() and String.substring(). Here is my fix and I would like to know your feedback on this. Please note that Apache StringUtils will be a very good resource to use here instead of trying to write the algorithm yourself.


package com.google.test;

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* To compiple: javac -d . SfdcReplaceSubstring3.java
* To run: java com.google.test.SfdcReplaceSubstring3
*
* @author ashik
*/
public final class SfdcReplaceSubstring3 {

// private static String firstStr = "I am a Java programmer and a $Chess$ player working in USA. $Chess$ is my hobby and here in USA lot of people play $Chess$. USA had a great Chess player named Bobby Fischer.";

private static String firstStr = "Java, Apex, $Chess$ and Oracle - which one do you like? I guess Chess. If not $Chess$ then what else?";

private static String patternToSearch = "$Chess$";

private static String[] replacementStrFromDB = { null, "", " ", "PUT_A_VALUE123",
"PUT#A^VALUE!123?a+b/c>d", "PUT$A$VALUE123", "$PUT_A_VALUE123",
"PUT_A_$VALUE123", "PUT_A_VALUE123$", "PUT_A_VALUE$123",
"PUT_A_VALUE123$", "\\$PUT_A_VALUE123", "\\\\$PUT_A_VALUE123",
"\\PUT_A_VALUE123", "\\\\PUT_A_VALUE123", "\\PUT_A_VALUE$123",
"\\\\PUT_A_VALUE$123", "\\PUT_A_VALUE123$", "\\\\PUT_A_VALUE123$",
"$PUT_A_VALUE$123$" };

public static void main(String[] args) {
System.out.println("\nfirstStr before replacing = " + firstStr);
System.out.println("\npatternToSearch = " + patternToSearch);
// System.out.println("Direct replacement: " +
// matcher.replaceAll("PUT\\$A\\$VALUE123"));
for (int i = 0; i < replacementStrFromDB.length; i++)
try {
System.out.println("\nExecuted test#"
+ (i + 1)
+ ": "
+ "firstStr after replacing with "
+ replacementStrFromDB[i]
+ " = "
+ replace(firstStr, patternToSearch,
replacementStrFromDB[i]));
} catch (Exception e) {
System.out.println("\nExecuted test#" + (i + 1) + ": "
+ "Exception while replacing firstStr with "
+ replacementStrFromDB[i] + " = " + e.getMessage());
}
}

public static String replace(String text, String searchString,
String replacement) {
int start = 0;
int end = text.indexOf(searchString, start);
if (end == -1) {
return text;
}
int replLength = searchString.length();
StringBuilder buf = new StringBuilder();
while (end != -1) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}

}

Update: This post attracted the attention of my friend Nitol wwith whom I have worked early in my career. He suggested to use Apache StringUtils for problems like this. Special thanks to him. It reminds me how many Apache open source libraries I have used earlier when I was in Bangladesh and after coming to USA, I don’t get time to sync up myself with the latest open source changes and often try to solve problems that has already been solved by numerous people (re-inventing the wheel). I will keep my eye on it from now on and allow myself to be a little lazy programmmer.

November 4, 2009

How To Unescape HTML in Java

Filed under: IT, Java — Tags: — ashikuzzaman @ 7:46 pm

I was writing an Html unescape algorithm in Java today. What I came out with is the one below. There is a problem in the algorithm below that eats up some space or characters for some corner cases. Can you figure out what the problem is?

I wrote the class in a way so that you can compile and run it in command prompt and can see the output right away. You can do some trial and error and figure out the issue in the algorithm below.

package com.salesforce.test;

import java.util.*;

/**
* To compiple: javac -d . StringUtils.java
* To run: java com.salesforce.test.StringUtils
*
* @authot ashik
*/
public class StringUtils {

private StringUtils() {}

/**
* the characters to unescape
*/
public static HashMap htmlEntities = new HashMap();
static {
htmlEntities.put("<","<"); htmlEntities.put("<",""); htmlEntities.put(">",">");
htmlEntities.put("'","\'"); htmlEntities.put("'","\'");
htmlEntities.put(""","\""); htmlEntities.put(""","\"");
htmlEntities.put("&","&"); htmlEntities.put("&","&");
htmlEntities.put(" "," "); htmlEntities.put(" "," ");
}

public static final String unescapeHTML(String source, int start){
int i,j;

i = source.indexOf("&", start);
if (i > -1) {
j = source.indexOf(";" ,i);
if (j > i) {
String entityToLookFor = source.substring(i , j + 1);
System.out.println("source = " + source + ", entityToLookFor = " + entityToLookFor + ", i = " + i + " and j = " + j);
if(entityToLookFor.lastIndexOf("&") > entityToLookFor.indexOf("&")) {
i = entityToLookFor.lastIndexOf("&") + 1;
System.out.println("Before source = " + source + ", entityToLookFor = " + entityToLookFor + ", i = " + i + " and j = " + j);
entityToLookFor = entityToLookFor.substring(entityToLookFor.lastIndexOf("&"));
System.out.println("After source = " + source + ", entityToLookFor = " + entityToLookFor + ", i = " + i + " and j = " + j);
}
String value = (String)htmlEntities.get(entityToLookFor);
if (value != null) {
source = new StringBuffer().append(source.substring(0 , i)).append(value).append(source.substring(j + 1)).toString();
return unescapeHTML(source, i + 1); // recursive call
}
}
}
return source;
}

public static void main(String args[]) throws Exception {
// to see accented character to the console
java.io.PrintStream ps = new java.io.PrintStream(System.out, true, "Cp850");

ps.println("Finally: Ashik's Quote <Test Ok = " + unescapeHTML("Ashik's Quote <Test Ok", 0));
ps.println("-----------");
ps.println("Finally: M& M > 5 = " + unescapeHTML("M& M > 5", 0));
ps.println("-----------");
ps.println("Finally: M & M > 5 = " + unescapeHTML("M & M > 5", 0));
ps.println("-----------");
ps.println("Finally: M &M > 5 = " + unescapeHTML("M &M > 5", 0));
ps.println("-----------");
ps.println("Finally: M& M> 5 = " + unescapeHTML("M& M> 5", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Apos\'trophie & "quote" is <present>", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Please check for empty space in Order Review tab.", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Also check for Billing Information & Subscription Information & Order Review tabs.", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("It's difficult to check today's capitalization strategy for all tabs.", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Remember that 12 is > 9 is > 4", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Similarly 8 is < 10 is < 15", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Shakespeare said,"To be or not to be that is the question."", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Think & think about New York's <best pizza> as the \"ultimate\" pizza!", 0));
ps.println("-----------");
ps.println("Also: \n-->" + unescapeHTML("Apos'trophie & "quote" is <present>", 0));
ps.println("-----------");
}

}

September 16, 2009

My Thoughts On SCJP Java 6 Exam

Filed under: IT, Java — Tags: , , , , , , , , , , — ashikuzzaman @ 6:07 am

Recently I have been thinking about the industry standard technology certifications, particularly around Java/JEE technologies. I am not exactly sure how valuable the technology certifications are when you are already an experienced veteran in the industry. But I can guess that it will give an impression to your upper management to accommodate you for the next level (higher level than where you are) or while switching jobs will justify you to apply for a higher title than you are in now.

Once I am successfully done with my hiking in Half Dome of Yosemite a few weeks later, I will be focusing on the Sun Certified Java Programmer (SCJP) exam on Java 6 platform. Although in my current project we use Java 5, we will be moving to Java 6 sooner or later as some other teams as well as the core platform team in Salesforce uses Java 6. Also it makes sense to get certified on the latest version of Java so that it can around your neck for a longer period of time in your career. I already talked to my manager and he was convinced that it’s relevant to my work and career development plan.

While looking for the best resources, I always refer to my favorite site JavaRanch. Even without looking much into all the books it was evidently clear that there are 2 outstanding study guides for this exam – Kathy Sierra and Bert Bates SCJP 6 Study Guide and Khalid Mughal and Rolf Rusmussen’s A Programmer’s Guide to Java Certification. Kathy&Bert book is targeted very much at making you pass the certification. But the strong points of Khalid&Rolf books is that it’s more thorough, details and explained subjects outside of the exam objectives if that should be useful to a programmer. So Khalid’s book should be better at teaching you Java. But I would recommend the K&B if you are already an experienced java programmer and just want to squeeze through the exam. I am thinking of reading the K&B first and then, time permitting, go through Khalid Mughal.

One place that every SCJP aspirants should frequently visit is the SCJP forum of JavaRanch. Try using only a text editor, even if Notepad and command prompt. Don’t copy paste codes, just type it yourself to see how you are introducing the compile and runtime errors. Here are the exam details and objectives. While looking for free mock exams for SCJP 6, I found the followings good at initial look.

One place that every SCJP aspirants should frequently visit is the SCJP forum of JavaRanch. Try using only a text editor, even if Notepad and command prompt. Don’t copy paste codes, just type it yourself to see how you are introducing the compile and runtime errors.

If you plan to buy a commercial mock exam, JQPlus from Enthuware is best amongst them – although I think you won’t need to spend $28 for this as K&B book already has some mock exams.

Last 2 weeks were one of my most extensive work hours spent in office. I was going early in the morning and coming back at midnight. Good that Shusmita was understanding enough towards my deadline in office and didn’t complain much. For this I had to skip hiking last week so that I can help her in preparation for the iftari and dinner invitations at our house.

One good news, Pearl Law Group applied for my PERM process on behalf of Salesforce.com in EB-2 Category, the day before yesterday. I hope all the paper processing happens very smoothly and fast for me.


April 7, 2009

Bowling with Friends

Filed under: Community, Java — ashikuzzaman @ 2:05 am

Last week I went to bowling with my friends in Fremont and we enjoyed it a lot. I paid on behalf of them for the game so that everyone else pay me back later. Despite their repeated query to know how much they should pay me, I was too busy the whole last week to calculate that. Right now, having a little relax time, so I downloaded JDK 6 in my new laptop from office and wrote the small java program to calculate it. Compile and run the program to know how much I owe to each of them.

/**
* To compile: javac -d . BowlingCost.java
* To run: java BowlingCost
*/

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class BowlingCost {
public static final double shoeRent = 4.0;
public static final double perGame = 4.25;
private static int male = 5;
private static int female = 4;
private static Map payersMaritalStatus = new HashMap();
public BowlingCost() {
payersMaritalStatus.put("Shahriar", Boolean.TRUE);
payersMaritalStatus.put("Ezaz", Boolean.TRUE);
payersMaritalStatus.put("Hasinur", Boolean.TRUE);
payersMaritalStatus.put("Nitol", Boolean.FALSE);
payersMaritalStatus.put("Ashik", Boolean.TRUE);
}
public static void main(String []args) {
BowlingCost cost = new BowlingCost();
System.out.println("Total Cost of Bowling = " + calculateTotal() + " dollars.\n");
displayPaymentAmounts();
System.out.println("\nThank you! It was a pleasure playing bowling with you guys!!");
}
private static double calculateTotal() {
return perGame * (male * 3 + female * 1) + shoeRent * (male + female);
}
private static void displayPaymentAmounts() {
Iterator it = payersMaritalStatus.keySet().iterator();
String payerName = null;
boolean isMarried = false;
while(it.hasNext()) {
payerName = (String) it.next();
isMarried = ((Boolean) payersMaritalStatus.get(payerName)).booleanValue();
if(isMarried) {
System.out.println(payerName + " should pay " + (perGame * (3 + 1) + shoeRent * (1 + 1)) + " dollars.");
} else {
System.out.println(payerName + " should pay " + (perGame * 3 + shoeRent * 1) + " dollars.");
}
}
}
}

If you don’t want to run the program in command line or opening your favorite IDE, then you can use the following online java compiler to copy paste the code there (select Java SE 1.4 class from the drop down box at the bottom).

http://www.zamples.com/JspExplorer/index.jsp?format=jdk16cl

Here is the output if you run the program:

Total Cost of Bowling = 116.75 dollars.

Ezaz should pay 25.0 dollars.
Ashik should pay 25.0 dollars.
Hasinur should pay 25.0 dollars.
Shahriar should pay 25.0 dollars.
Nitol should pay 16.75 dollars.

Thank you! It was a pleasure playing bowling with you guys!!

February 27, 2007

Developing Simple Chess Board With Swing in Java SE 6

Filed under: Java — ashikuzzaman @ 4:44 pm

My first professional java project as a software developer was to build a client/server application using Java 2, Swing, RMI and Oracle database. Around 5 years back, it was a small team of 3 developers one project manager and one architect. At that time we used Forte For Java was facsinated how easily I could drag and drop swing components in a palette to build my GUI instead of the AWT way I learnt and taught my students during my Java Teaching career. However, immediately after finishing first few modules, we understood the problems of JFC/Swing components in Java 1.2 . They were so slow that a novice user could identify that and compare with a Visual Basic or C++ GUI application. We had hard time working with JTree and JTable components. But since then Java has crossed JDK 1.3, JDK 1.4 (a major improvement compared to other versions), Java SE 5 and now Java SE 6. While I am working with SWTand Java SE 5in one of my projects in office, I may get into a parallal project on Swing soon. So I thaught to prepare the same chess board using Swing and Java SE 6 and finally came up with this entry. You may compare this with the one that I prototypes using SWT as a practice. To my understanding while both SWT and Swing has its own places, Swing would be a better choice for my next java GUI development due to its intuitive, easy to use API. You dont any java IDE for the program I am going to show you today. However, for advanced GUI design purpose my favorite would be Netbeans 5.5 and as I want to continue using MyEclipse where most of my java projects are configured, I downloaded Matisse4MyEclipse in it.

 

Get tight and follow the steps!

  1. Make sure you have Java installed. I installed Java SE 6 in C:\programs\java\jdk_6
  2. Install Ant 1.6.5 altough you may use command prompt if you dont want to use Ant.
  3. Create project directory at c:\workspace\SwingBoard
  4. Create SwingBoard class under package name com.chess4you.board. Here is the source code for this class.
    /** SwingBoard.java **/
    package com.chess4you.board;import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;

    /**
    * A simple chess board using Swing
    *
    * @author Ashik Uzzaman
    * @link https://ashikuzzaman.wordpress.com
    */
    public class SwingBoard extends JFrame {

    public static final int NUMBER_OF_ROWS = 8;
    public static final int NUMBER_OF_FILES = 8;
    public static JLabel square;
    public static JPanel squarePanel = new JPanel();
    public static JPanel squaresPanel = new JPanel();

    private static void createSquares() {
    LayoutManager layout = new GridLayout(NUMBER_OF_ROWS, NUMBER_OF_FILES);
    squaresPanel.setLayout(layout);
    for(int i=NUMBER_OF_ROWS; i>0; i–) {
    for(int j=1; j<=NUMBER_OF_FILES; j++) {
    squarePanel = new JPanel();
    square = new JLabel (“r” + i + “:c” + j);
    squarePanel.add(square);
    squarePanel.setBackground(getColor(i, j));
    square.setForeground(new Color(0, 0, 250));
    squarePanel.setToolTipText(“Row ” + i + ” and Column ” + j);
    squaresPanel.add(squarePanel);
    }
    }
    }

    private static Color getColor(int x, int y)
    {
    if((x+y) % 2 == 0)
    return new Color(255, 255, 255);
    else
    return new Color(0, 0, 0);
    }
    public SwingBoard() {
    initComponents();
    }

    private void initComponents() {

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    int boardSize = 0;
    int width = dim.width;
    int height = dim.height;
    if(width >= height) {
    boardSize = height / 2;
    } else {
    boardSize = width / 2;
    }
    createSquares();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle(“Swing Chess Board”);
    setIconImage(new ImageIcon(“board.jpg”).getImage());
    getContentPane().add(squaresPanel, BorderLayout.CENTER);
    setVisible(true);
    Dimension preferredSize = new Dimension();
    preferredSize.width = boardSize;
    preferredSize.height = boardSize;
    setPreferredSize(preferredSize);
    setBounds(boardSize / 4, boardSize / 4, boardSize, boardSize);
    pack();
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new SwingBoard();
    }
    });
    }
    }

  5. Create javase6.bat file inside your project directory. The content of this file actually sets path and classpath required for java.
    ## Simple batch file for Java classpath settings
    SET JAVA_HOME=C:\programs\java\jdk_6
    SET ANT_HOME=C:\programs\java\apache-ant-1.6.5
    SET PATH=%PATH%;%JAVA_HOME%\bin;%ANT_HOME%\bin
    SET PROJECT_HOME=C:\workspace\SwingBoard
    SET CLASSPATH=%CLASSPATH%;.;%JAVA_HOME%\lib\tools.jar
    Title “JDK 6”
    cd %PROJECT_HOME%
    cmd
  6. If you use Ant, create build.xml file in your project directory with following contents.
    <?xml version=”1.0″ encoding=”ISO-8859-1″?>
    <project name=”SwingBoard” default=”run” basedir=”.”>
    <description>
    Swing Application build and execution file
    </description><property name=”main.class” value=”com.chess4you.board.SwingBoard”/>
    <property name=”src” location=”.”/>
    <property name=”build” location=”.”/><target name=”compile”>
    <javac srcdir=”${src}” destdir=”${build}” />
    </target>

    <target name=”run” depends=”compile”>
    <java classname=”${main.class}” fork=”true” failonerror=”true” />
    </target>
    </project>

  7. Copy a small icon for a chess board in your project directory and name it board.jpg that is used in our code. You may download the icon that I used from http://farm1.static.flickr.com/160/391341494_669254c2c6_s.jpg
  8. To compile from command prompt, double click javase6.bat file and issue the following command: javac com/chess4you/board/SwingBoard.java
  9. To run from command prompt, issue the following command: java com.chess4you.board.SwingBoard
  10. To compile using Ant, issue the following command: ant compile
  11. To run using Ant, issue the following command: ant run
Older Posts »

Blog at WordPress.com.