Ashik’s IT Thoughts

August 11, 2011

Removing an element from a Collection while iterating over it

Filed under: Uncategorized — Tags: — ashikuzzaman @ 5:59 pm

Can you remove an element from a collection while iterating over it? Answer: No, you can’t.

What kind of error will you get in Java if you make an attempt? Compile time or Runtime? Answer: Runtime.

The details of the exception will be as below. Check this along with a sample program that I wrote. You can try to compile and run it yourself to see the result.

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)


package com.salesforce.test;

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

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

public List counts = new ArrayList();

public RemoveListTest() {
counts.add(0);
counts.add(1);
counts.add(2);
counts.add(3);
counts.add(4);
counts.add(5);
counts.add(6);
counts.add(7);
counts.add(8);
counts.add(9);
counts.add(10);
counts.add(11);
counts.add(12);
counts.add(13);
counts.add(14);
}

public static void main(String[] args) {
System.out.println("\nRemoveListTest starts.....\n");
RemoveListTest rlt = new RemoveListTest();
List results = new ArrayList();
for(Integer count : rlt.counts) {
System.out.println("count before removing = " + count);
if(count % 3 == 1) {
results.add(count);
// rlt.counts.remove(count); // you will get runtime error if you uncomment it
}
}

for(Integer result : results) {
System.out.println("result = " + result);
rlt.counts.remove(result);
}
for(Integer count : rlt.counts) {
System.out.println("count after removing = " + count);
}

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

Advertisements

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.

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.


September 1, 2009

Title Revision from Software Engineer to Senior Member of Technical Staff

Filed under: IT, Official — Tags: , , , , , , , , , , — ashikuzzaman @ 6:42 pm

Recently I got a title revision in Salesforce.com as a Senior Member of Technical Staff (SMTS) although without any salary hike. When I joined Salesforce at November 5, 2007 I was assigned the title of Software Engineer. My grade was already high within the Software Engineer title holders at that time falling a little short of the next title Senior Software Engineer. In IT we had the hierarchy like – Associate Software Engineer > Software Engineer > Senior Software Engineer > Lead Software Engineer > Principal Engineer. But in R&D which is a bigger team in Salesforce, the similar titles were Associate Member of Technical Staff (AMTS), Member of Technical Staff (MTS), Senior Member of Technical Staff (SMTS), Lead Member of Technical Staff (LMTS) and Principle Member of Technical Staff (PMTS). So in a recent alignment initiative between R&D and IT team, management decided to follow the conventions of R&D team for both of these groups. This resulted in converting out Software Engineers to MTS. Only for my case in AppStore team, I was levelled as SMTS although my earlier title was Software Engineer. This means I am still eligible for my next level promotion to Lead Member of Technical Staff as per our Merit Increase Process. Let’s see how things go.

April 17, 2008

JMS

Filed under: Uncategorized — Tags: , — ashikuzzaman @ 12:30 pm

Background
I, Nitol and Paul are 3 developers who worked at the early times of our career as java developers in a project named SPRINTRE in Bangladesh almost 6 years back. Coincidentally, we all 3 are now in USA. I and Nitol in California and are now neighbours and Paul just came to USA few weeks back and interviewing for openings in New York area. This is a part of a technical discussion going amongst us in JMS that Nitol sent. I am keeping it here finding valuable for reference.
Excerpt From Nitol’s Email
JMS is not mandatory thing, it’s a tool. If it properly used, then it can be useful. It helps to modularize code, improves maintainability …
Scenario
I’m going to describe one scenario from project Spintre, you remember right :). When a Purchase Order is approved, it should be saved in the PO table also it should save one record in accounts in proper cost center. How did we implemented it, we had accounts service call in PO module. Means we made PO module dependent on accounts module. Suppose we had a ActivityTracking module, which saves all user activity. How did we implemented it? We would have implemented it by calling activity tracking service. Suppose we have to include notification service also, when ever a PO is approved, purchase officer wants a email in his email box.
Without using JMS
accountService.save(amount, costcenter);
activityTrackingService(userObj, PoModuleIdentifier, ActivityApprove ..);
{
look for who want’s notification, get the email address and send the email.
}
How do you like this code implementation? How is the impression of a User who just clicked on the Approve button and waiting for so many thing to happen.
Those all service can be asynchronous, those activity don’t need to be real time. Now how we can use JMS here
when PO is saved, code block using JMS is
With JMS
{
Event event  = new Event(po number, date, Module, ActivityType, user ……)
jmsPublisher.publish(event);
}
Done, clean implementation. But now we can write sevaral Subscriber
AccountModuleSubscriber {
receive(Message obj) {
Event event = (Event) obj;
// save it to correct cost center
}
}
ActivityTracker {
receive(Message obj) {

Event event = (Event) obj;
// save it log table
}

}

So, by using JMS you basically improved the application performance, It’s using idle time .. Jms broker will manage these different thread ..
2. I user ActiveMQ. I heard it became a apache project now.
Commercial Weblogic JMS is expensive. Basically all the EJB server has JMS support, Jboss, webspheare ….
3. JMS is a technology, a messaging architechture. It is scalable, if it is used properly. Means if design is good, then it’s scalable .. if design is bad, no meaning of using JMS.
4. You yourself can implement by using thread. But why to re-invent the wheel. JMS gives support of message persistent, redelivery, durability, thread pool .. so many support. Why not use those.
You can also make code moduler by using Observable-Observer pattern, but that is synchronous. You can use thread then, you’ve to maintain them ..
5. JMS is nice technology. Messaging technology is old, java implemented that near 2000. There are big server’s available for messging/message broker from long time back, like IBM MQSeries. Microsoft has there MS MQ implementation into windows may from 10-15 years ago. It’s a proven technology.
My informations can be wrong, anyway I hope it will help.

January 30, 2008

Rounding problem in Java for float, double types

Filed under: Uncategorized — Tags: , , , , — ashikuzzaman @ 3:28 pm

Here is a sample java program that I wrote. It shows that for all of Double, double, Float, float you can’t rely on default rounding operation of java/jvm. I think even JVM to JVM implementation (sun windows jvm vs ibm linux jvm for example) the output may vary. Can someone confirm it?

public class DoubleAndFloatIssue {

public static void main(String[] args) {

Float f1 = new Float(7.0004443556783244696789123456789f);
float f2 = 7.0004443556783244696789123456789f;

Double d1 = new Double(7.0004443556783244696789123456789);
double d2 = 7.0004443556783244696789123456789;

System.out.println(“Float f1 = ” + f1);
System.out.println(“float f2 = ” + f2);

System.out.println(“Double d1 = ” + d1);
System.out.println(“double d2 = ” + d2);

f1 = f1/7;
f2 = f2/7;

d1 = d1/7;
d2 = d2/7;

System.out.println(“Float f1/7 = ” + f1);
System.out.println(“float f2/7 = ” + f2);

System.out.println(“Double d1/7 = ” + d1);
System.out.println(“double d2/7 = ” + d2);

f1 = f1*7;
f2 = f2*7;

d1 = d1*7;
d2 = d2*7;

System.out.println(“Float (f1/7)*7 = ” + f1);
System.out.println(“float (f2/7)*7 = ” + f2);

System.out.println(“Double (d1/7)*7 = ” + d1);
System.out.println(“double (d2/7)*7 = ” + d2);

}

}

The output of the program is as below:

Float f1 = 7.0004444
float f2 = 7.0004444
Double d1 = 7.000444355678325
double d2 = 7.000444355678325
Float f1/7 = 1.0000635
float f2/7 = 1.0000635
Double d1/7 = 1.0000634793826177
double d2/7 = 1.0000634793826177
Float (f1/7)*7 = 7.000445
float (f2/7)*7 = 7.000445
Double (d1/7)*7 = 7.000444355678324
double (d2/7)*7 = 7.000444355678324

Create a free website or blog at WordPress.com.