Wednesday, October 30, 2013

JUnit + Eclipse + Maven = fun

Given:

/src/test/java/com/helloworld/a.xml with body <src_test_java/>
/src/test/resources/com/helloworld/a.xml with body <src_test_resources/>
/src/main/java/com/helloworld/a.xml with body <src_main_java/>
/src/main/resources/com/helloworld/a.xml with body <src_main_resources/>

Run the following JUnit(NOT under /src/test/java/com/helloworld/) in Eclipse configured by Maven with Eclipse plugin (mvn eclipse:eclipse):

A: this.getClass().getResource("a.xml”);
B: this.getClass().getResource("/com/helloworld/a.xml");
C: this.getClass().getResourceAsStream("a.xml");
D: this.getClass().getResourceAsStream("/com/helloworld/a.xml");
E: this.getClass().getClassLoader().getResource("a.xml");
F: this.getClass().getClassLoader().getResource("/com/helloworld/a.xml");
G: this.getClass().getClassLoader().getResourceAsStream("a.xml");
H: this.getClass().getClassLoader().getResourceAsStream("/com/helloworld/a.xml");

What should the result look like?

Answer:
A: empty string
B: <src_test_resources/>
C: empty string
D: <src_test_resources/>
E: null
F: null
G: null
H: null

Tuesday, February 12, 2013

java.lang.Long.intValue() or casting long to int

Problem:

public static void main(String args[]) {
Long l = Long.MAX_VALUE;
System.out.println(l.longValue());
System.out.println(l.intValue());
System.out.println("---------------\n");
Long l2 = Long.valueOf(Integer.MAX_VALUE);
System.out.println(l2.longValue());
System.out.println(l2.intValue());
System.out.println("---------------\n");
Long l3 = Long.valueOf(Integer.MAX_VALUE) + 1;
System.out.println(l3.longValue());
System.out.println(l3.intValue());
System.out.println("---------------\n");
Long l4 = Long.valueOf(Integer.MAX_VALUE) + 2;
System.out.println(l4.longValue());
System.out.println(l4.intValue());
System.out.println("---------------\n");
Long l5 = Long.valueOf(Integer.MAX_VALUE) + Integer.MAX_VALUE;
System.out.println(l5.longValue());
System.out.println(l5.intValue());
System.out.println("---------------\n");
Long l6 = Long.valueOf(Integer.MAX_VALUE) + Integer.MAX_VALUE + 1;
System.out.println(l6.longValue());
System.out.println(l6.intValue());
System.out.println("---------------\n");
Long l7 = Long.valueOf(Integer.MAX_VALUE) + Integer.MAX_VALUE + 2;
System.out.println(l7.longValue());
System.out.println(l7.intValue());
System.out.println("---------------\n");
}




9223372036854775807
-1
---------------

2147483647
2147483647
---------------

2147483648
-2147483648
---------------

2147483649
-2147483647
---------------

4294967294
-2
---------------

4294967295
-1
---------------

4294967296
0
---------------




Solution:

use one of the suggested methods mentioned at this thread:

http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java

Thursday, February 7, 2013

Use autoboxing/unboxing cautiously

Problem:


public static void main(String args[]) {
Long long1 = Long.valueOf(123L);
Long long2 = new Long("123");
Long long3 = Long.parseLong("123");
long long4 = Long.valueOf(123L);
long long5 = new Long("123");
long long6 = Long.parseLong("123");

System.out.println("long1==long2:"+ (long1==long2));
System.out.println("long1==long3:"+ (long1==long3));
System.out.println("long1==long4:"+ (long1==long4));
System.out.println("long1==long5:"+ (long1==long5));
System.out.println("long1==long6:"+ (long1==long6));
System.out.println("long2==long3:"+ (long2==long3));
System.out.println("long2==long4:"+ (long2==long4));
System.out.println("long2==long5:"+ (long2==long5));
System.out.println("long2==long6:"+ (long2==long6));
System.out.println("long3==long4:"+ (long3==long4));
System.out.println("long3==long5:"+ (long3==long5));
System.out.println("long3==long6:"+ (long3==long6));
System.out.println("long4==long5:"+ (long4==long5));
System.out.println("long4==long6:"+ (long4==long6));

System.out.println("long5==long6:"+ (long5==long6));
}

long1==long2:false
long1==long3:true
long1==long4:true
long1==long5:true
long1==long6:true
long2==long3:false
long2==long4:true
long2==long5:true
long2==long6:true
long3==long4:true
long3==long5:true
long3==long6:true
long4==long5:true
long4==long6:true
long5==long6:true

Solution: If you don't know the origin of the Long object, you may want to check if it is null AND longObject.longValue() for value comparison.

Tuesday, September 4, 2012

Invoking parent private method by reflection


public class SuperClass {
boolean superField = true;
private void superMethod(boolean superField) {
System.out.println("superMethod() called - param:" + superField);
}
}






import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SubClass extends SuperClass {
public static void main(String args[]) {
SubClass subClassInstance = new SubClass();
try {
Method declaredMethod = SuperClass.class.getDeclaredMethod("superMethod", boolean.class);
declaredMethod.setAccessible(true);
declaredMethod.invoke((SuperClass)subClassInstance, new Object[] {false}); //I remember that there was a situation this explicit cast is required
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
}
}



Friday, March 30, 2012

MapQuest Android MapView vs Google Android MapView

Problem: Cannot align the MapView properly in MapQuest.


Solution: Do your own bit-wise OR!!!


Google Android MapView LayoutParams:


int a = MapView.LayoutParams.BOTTOM_CENTER; //81

int b = MapView.LayoutParams.BOTTOM; //80

int c = MapView.LayoutParams.CENTER_HORIZONTAL; //1

int d = MapView.LayoutParams.BOTTOM | MapView.LayoutParams.CENTER_HORIZONTAL; // 81

it makes sense, doesn't it?



How about MapQuest Android MapView LayoutParams?

int a = MapView.LayoutParams.BOTTOM_CENTER; //35

int b = MapView.LayoutParams.BOTTOM; //32

int c = MapView.LayoutParams.CENTER_HORIZONTAL; //1

int d = MapView.LayoutParams.BOTTOM | MapView.LayoutParams.CENTER_HORIZONTAL; // 33

hmmm...something doesn't seem right here...

Thursday, June 30, 2011

eclipse replace multiple lines


Problem: Hibernate Tools DAO generation generates SeeionFactory with getter via JNDI

private final SessionFactory sessionFactory = getSessionFactory();


protected SessionFactory getSessionFactory() {

try {

return (SessionFactory) new InitialContext()

.lookup("SessionFactory");

} catch (Exception e) {

log.error("Could not locate SessionFactory in JNDI", e);

throw new IllegalStateException(

"Could not locate SessionFactory in JNDI");

}

}


while I need the regular java bean getter setter without JNDI context

private SessionFactory sessionFactory;


public SessionFactory getSessionFactory() {

return sessionFactory;

}


public void setSessionFactory(SessionFactory sessionFactory) {

this.sessionFactory = sessionFactory;

}


Solution: use Eclipse search+replace function, on the GUI, looks like it supports only 1 single line replacement, in fact it isn't, but multiple lines cannot be entered at the search field using the keyboard's Enter key, it requires using copy+paste


Tuesday, June 14, 2011

java.net.BindException: Permission denied on Mac OSX

problem:
running any java app that listens to a port

Caused by: java.net.BindException: Permission denied

at java.net.PlainSocketImpl.socketBind(Native Method)

at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:383)

at java.net.ServerSocket.bind(ServerSocket.java:328)

at java.net.ServerSocket.(ServerSocket.java:194)

at javax.net.DefaultServerSocketFactory.createServerSocket(ServerSocketFactory.java:170)

at org.apache.activemq.transport.tcp.TcpTransportServer.bind(TcpTransportServer.java:135)

... 44 more


solution:
1. use sudo
or
2. listen to a port that is outside of 0 to 1023

Thursday, June 9, 2011

Hibernate + PostgreSQL + Table Partitioning

Problem: using Hibernate to insert a new entry into a partitioned table on PostgreSQL would get the following exception:


2011-06-08 16:37:07,725 ERROR [org.hibernate.event.def.AbstractFlushingEventListener] -

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1


Solution:

use a @SQLInsert(sql = "insert into table (col_1, col_2) values (?, ?)", check=ResultCheckStyle.NONE)


more solutions provided here:

http://www.redhat.com/f/pdf/jbw/jmlodgenski_940_scaling_hibernate.pdf

Wednesday, June 8, 2011

Hibernate (Annotation) + PostgreSQL + Sequence Generator

Problem: The java class generated by Hibernate Code Generator does not know anything about the sequence defined on PostgreSQL.

Solution: use the combination of @javax.persistence.GeneratedValue & @org.hibernate.annotation.GenericGenerator

@Id

@Column(name = "id", unique = true, nullable = false, insertable=false)

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "IdSeqGeneratorName")

@org.hibernate.annotations.GenericGenerator(name = "IdSeqGeneratorName", strategy = "sequence", parameters = { @Parameter(name = "sequence", value = "the_postgres_seq") })

public long getId() {

return this.id;

}



or

@Id

@Column(name = "id", unique = true, nullable = false, insertable=false)

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tcp_audit_seq_name")

@SequenceGenerator(name = "tcp_audit_seq_name", sequenceName = "tcp_audit_seq", allocationSize = 1)

public long getId() {

return this.id;

}

Monday, November 15, 2010

Waiting for changelog lock.... at SpringSource Tool Suite 2.5.1

problem: Starting up tc Server hangs at "Initializing Spring root WebApplicationContext" and "Waiting for changelog lock...."

solution: Downgrade from STS 2.5.1 to 2.5.0. Unfortunately I don't have time to pinpoint exactly what causes the problem, but at least I can keep writing code.

Friday, November 12, 2010

problem:


using Quartz + Spring + PostreSQL


55028 [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_QuartzSchedulerThread] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource

55029 [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_QuartzSchedulerThread] ERROR org.quartz.core.ErrorLogger - An error occured while scanning for the next trigger to fire.

org.quartz.JobPersistenceException: Couldn't acquire next trigger: Couldn't retrieve trigger: Bad value for type long : [See nested exception: org.quartz.JobPersistenceException: Couldn't retrieve trigger: Bad value for type long : [See nested exception: org.postgresql.util.PSQLException: Bad value for type long : ]]

at org.quartz.impl.jdbcjobstore.JobStoreSupport.acquireNextTrigger(JobStoreSupport.java:2789)

at org.quartz.impl.jdbcjobstore.JobStoreSupport$36.execute(JobStoreSupport.java:2732)

at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3763)

at org.quartz.impl.jdbcjobstore.JobStoreSupport.acquireNextTrigger(JobStoreSupport.java:2728)

at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:264)

Caused by: org.quartz.JobPersistenceException: Couldn't retrieve trigger: Bad value for type long : [See nested exception: org.postgresql.util.PSQLException: Bad value for type long : ]

at org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger(JobStoreSupport.java:1571)

at org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger(JobStoreSupport.java:1547)

at org.quartz.impl.jdbcjobstore.JobStoreSupport.acquireNextTrigger(JobStoreSupport.java:2767)

... 4 more

Caused by: org.postgresql.util.PSQLException: Bad value for type long :

at org.postgresql.jdbc2.AbstractJdbc2ResultSet.toLong(AbstractJdbc2ResultSet.java:2736)

at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getLong(AbstractJdbc2ResultSet.java:2032)

at org.postgresql.jdbc2.Jdbc2ResultSet.getBlob(Jdbc2ResultSet.java:52)

at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getBlob(AbstractJdbc2ResultSet.java:337)

at org.apache.commons.dbcp.DelegatingResultSet.getBlob(DelegatingResultSet.java:565)

at org.apache.commons.dbcp.DelegatingResultSet.getBlob(DelegatingResultSet.java:565)

at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.getObjectFromBlob(StdJDBCDelegate.java:3462)

at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.selectTrigger(StdJDBCDelegate.java:2132)

at org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger(JobStoreSupport.java:1553)

... 6 more


Solution:

Use the PostgresSQL driver delegate class


Replace:


org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate


with


org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate

Wednesday, November 10, 2010

Configure memory settings of SpringSource Tool Suite (STS) on Mac OSX

springsource.2.5.0.RELEASE/sts-2.5.0.RELEASE/STS.app/Contents/MacOS/STS.ini

-startup
../../../plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
../../../plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.1.R36x_v20100810
-product
com.springsource.sts.ide
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms768m
-Xmx2048m
-XX:MaxPermSize=512m
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts

Wednesday, October 27, 2010

Using SpringSource Tool Suite (STS) Template

1. Go to New -> Other


2. Under SpringSource Tool Suite -> Spring Template Project

3. enter Project name, top-level package

4. choose the type of project needed


5. download the template if it is executed for the first time

6. project skeleton generated


7. basic definition of Hibernate related beans

Friday, May 7, 2010

thumbs116x116.dat reader

I know this is very ugly, and I wished that I have time to improve it.

If anyone can beautify it, please send me a copy, thanks.


public static Bitmap readThumbsAlternative(byte[] search, String szSearch) {
// file:///SDCard/BlackBerry/pictures/image.jpg
szSearch = szSearch.substring(szSearch.lastIndexOf('/')+1,szSearch.length());
// convert the search string to bytes for easier comparison
byte[] searchtmp = szSearch.getBytes();
int lastbyte = 0;
int endIndex = 0;
for (int x = 0; x < search.length; x++) {
boolean found = false;
// For the length of searchtmp trying to find a match in the byte file
// we could also have converted search to String [new String(search)]
// and have done an index of however I prefer direct byte access as lookups tend to be faster
for (int y = 0; y < searchtmp.length; y++) {
if (search[x + y] == searchtmp[y]) {
lastbyte = x + y + 1;
found = true;
} else {
found = false;
break;
}
}
if (found) {
for (int y = lastbyte; y < search.length; y++) {
byte first = search[y];
byte second = (y < search.length - 1) ? search[y + 1] : search[y];
String firstS = Integer.toString((first & 0xff) + 0x100, 16).substring(1);
String secondS = Integer.toString((second & 0xff) + 0x100, 16).substring(1);
if (firstS.equals("ff") && secondS.equals("d9")) {
endIndex = y + 1;
break;
}
}
if (endIndex>0) {
break;
}
}
}
if (lastbyte > 0 && endIndex > 0) {
byte[] b = new byte[lastbyte + endIndex];
int counter = 0;
for (int i = lastbyte; i <= endIndex; i++) {
b[counter] = search[i];
counter++;
}
EncodedImage ei = EncodedImage.createEncodedImage(b, 0, b.length);
Bitmap bt = ei.getBitmap();
return bt;
}
return _loadingImage;
}

Thursday, May 6, 2010

reading BBThumbs.dat thumbnail

Problem: Need a way to select images from the device, but takes forever to generate thumbnail at runtime.

Solution: Read the thumbnail generated by BlackBerry's image browser.

Here are the files of the thumbnails:
for newer OS:
1. file:///SDCard/BlackBerry/system/media/thumbs116x116.dat
2. file:///store/appdata/rim/media/thumbs116x116.dat

or thumbs480x360.dat if you want bigger thumbnails
*** I didn't need to use the .key file, if anyone knows what does the .key file do, would you please let me know?

read the file as EXIFs by stripping the data FFD8XXXX...XXXXFFD9

www.media.mit.edu/pia/Research/deepview/exif.html



for older OS:
3. file:///SDCard/BlackBerry/pictures/BBThumbs.dat
4. file:///store/home/user/pictures/BBThumbs.dat

read the file as PNGs by using the code snippet from

supportforums.blackberry.com/t5/Java-Development/Thumbnails-work-around/m-p/343870

Monday, February 22, 2010

BlackBerry API - SMS - DatagramConnection.send() hangs/freezes

Problem:


public void SendSMS(String input){
try {
DatagramConnection dgConn;
dgConn = (DatagramConnection)Connector.open("sms://15195555555");
byte[] data = input.getBytes();
Datagram dg = dgConn.newDatagram(dgConn.getMaximumLength());
dg.setData(data, 0, data.length);
dgConn.send(dg); <------ hangs right here!!!! and no Throwable was ever thrown!!!
} catch (Throwable t) {
t.printStackTrace();
}
}


Solution:
Check the length of the message, in my case, it hangs when the message is >160 in length.

Thursday, December 24, 2009

Server Tomcat v6.0 Server at localhost was unable to start within 45 seconds. What if the server requires more time?

Problem: Debugging a web app on Tomcat within Eclipse that takes more than 45 seconds to start-up, which prompts the following message:

Server Tomcat v6.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

Solution: I'm not sure where the server editor is located, but changing the start-timeout="45" in workspace\.metadata\.plugins\org.eclipse.wst.server.core\server.xml would help, make sure restart eclipse after the change.

Monday, August 31, 2009

VMWare connects at 10Mbps

Problem: After the weekend, my VMWare's XP(AMD PCNET Family PCI Ethernet Adapter) connects to the network at 10Mbps, while it was connecting at 1Gbps before the weekend.


Solution: Check the VMWare's MAC address, let your administrator know if the address has been updated. Secondly, reinstall/repair VMWare Tools.