Archive for category Java
Mac OS and Java Me SDK 3.0
Sun have released not too long ago a Java ME SDK 3.0 that finally brings an official Wireless Toolkit Emulator to the Mac platform.
I have been dealing with SUN software for a while now and I was not expecting this to be a smooth ride. Those who’d dealt with the WTK on Windows/Linux platform are well aware of the limitations of these emulators. What I was not prepared for was to get so much clutter that would just not work more than a couple of times.
First impression: this wtk looks like the most polished emulator ever released by Sun.
Sadly, after using the thing for a few days I discovered that the old habits had not changed:
- there is no menu entry to run an existing jad/jar pair. You have to right click on an emulator instance and then run it…
- you cannot set-up a project starting from a jad/jar pair. There used to be an option to do this back in wtk 2.2…
- after running a couple of apps the whole thing crashes an burns
- when closing down the wtk a process is left lingering. Run this in a terminal: ps aux | grep device-manager.app
- switching the verbose mode when launching the emulator kills the whole thing dead!
- they bundled ant 1.7.1 with the distro although ant is built in Mac OS
- Permgen errors are thrown if you try to launch the app too often. LOL
Here’s what happened when I created a new project and tried to run it:
*** Error ***
Failed to connect to device 0!
Reason:
Emulator 0 terminated while waiting for it to register!
The same thing happens with Emulator 1 and 2 and 3 and 4 and 5 and 6 and … you get the picture.
Googling did return lots of forum posts, but hardly any answers…
So after wasting more than 2 hours on this issue I did the unthinkable: rebooted my mac! To my surprise the miracle happened during the reboot: I was finally able to run the project again.
Needless to say I am very disappointed but not surprised by the quality of this, early access, Java ME SDK.
Cheers…
Jersey and Websphere 6.1
If you landed on this page it probably means that you’ve attempted to deploy a Jersey RESTful web service in IBM’s Websphere app server.
First of all: what were you thinking?!?
Secondly: it probably wasn’t your decision and you just need to make it work and move on. That was our case anyway…
So rather than bore you to death with how we ended up debugging the JVM and discovering that a java.lang.TypeNotPresentException is thrown when calling class.isAnnotationPresent from within the cores (com.ibm.oti.reflect.AnnotationHelper.getAnnotation) of the IBM J9 JVM rather than a plain true / false, I will just give you a bullet list of the things that need to happen to keep Websphere happy.
- Get your versions right! Jersey 1.0.3 and Websphere AS 6.1.0.25 (including 6.1.0.25 Fix Pack for Web Services) (Getting here is a blog post in itself and I will not do it here)
- Make sure that the enterprise app that contains your Jersey resources uses “Classes loaded with parent class loader first” and “Single class loader for application” (That is in your application’s “Class loading and update detection” section.)
- In your web xml configure the Jersey servlet to search for resources using ClassNames rather than packages. Basically make sure your web.xml looks similar to what I have below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name> <param-value>com.sun.jersey.api.core.ClassNamesResourceConfig</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.classnames</param-name> <param-value> net.tmro.MyRESTfulResource </param-value> </init-param> <load-on-startup>10</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/json/*</url-pattern> </servlet-mapping> |
- Okay, some clarification: the reason ClassNamesResourceConfig is used rather than PackagesResourceConfig is that when the packages are browsed for the actual @Path annotated classes an actual jar browsing is done which throws and swallows a nasty SecurityException… I invite you (more like dare you) to try using ClasspathResourceConfig and let me know if it works.
Now go ahead and give this a try… don’t forget to let me know if it worked or failed for you… Good luck!
Cheers….
JATA – Java Application Terminal Alignment
The Sun JavaOne conference is now in progress and one of the interesting things that have been announced so far is the JATA.
Together with France Telecom and Orange, Motorola, Nokia, Sony Ericsson and Vodafone, Sun announced the Java Application Terminal Alignment (JATA), which they promised would reduce the number of tests application developers would need to go through to ensure their applications run on different networks and handsets.
Also promised are a publisher ID digital certificate to authenticate a person and application, and R&D signing for developers to test their applications.
I am looking forward to learning more about it… in the mean time there is always j2mepolish
Jersey 1.0.2 JSON and JAXB
In a previous post I explained how to unit test JAX-RS. Let’s now have a look at a more complex example: implementing RESTful webservices using Jersey 1.0.2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <servlet> <servlet-name>My Jersey Web Application</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name> <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>net.tmro.demo.json;your.packages;separated.by.semicolons</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>My Jersey Web Application</servlet-name> <url-pattern>/webappjson/*</url-pattern> </servlet-mapping> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package net.tmro.demo.json; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path(“/myresource”) public class MyResource { public MyResource() { } @GET @Produces(value=MediaType.APPLICATION_JSON) @Path(“/getsomething”) public MyComplexObject getSomething(@QueryParam(“idOfSomething”) String id) { //your complex object can expose primitive data types, objects as well as collections. //you are not required to do anything fancy as long as you implement return new MyComplexObject(id); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package net.tmro.demo.json; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.*; import javax.ws.rs.ext.*; import com.sun.jersey.spi.resource.Singleton; import net.sf.json.JSONSerializer; @Provider @Singleton public class MyEntityProvider implements MessageBodyWriter<object> { //the json serializer used to write out objects to the output stream private final JSONSerializer serializer = new JSONSerializer(); public long getSize(final Object t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return -1; } public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE); } public void writeTo(final Object t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<string, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write(serializer.toJSON(t).toString().getBytes()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package net.tmro.demo.json; @XmlRootElement public class MyComplexObject extends AnotherObject { //fields: primitive data types, objects and collections. everything gets serialized unless //marked as transient public MyComplexObject(String id){ [..] } //getters and setters } |
The Java Store – Project Vector
Posted by Nick in Java, The Wonderful Internet on May 25, 2009
Unit Test JAX-RS using Java 6 and JUnit 4
Today I was amazed to discover that Unit testing JAX-RS resources with JUnit 4 and Java 6 is insanely easy.
Have a look at the example below and then read the description underneath if things are not clear enough already.
import static org.junit.Assert.*;
import java.io.*;
import java.net.*;
import javax.ws.rs.*;
import org.junit.*;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
@Path("/hellotest")
public class MyResourceTest {
private static final String LOCALHOST = "http://localhost:9998/";
private static HttpServer server;
@GET
@Produces("text/plain")
public String testSystem(){
return "Hello. This is a test";
}
@BeforeClass
public static void setUp() throws Exception{
System.out.println("Creating server");
server = HttpServerFactory.create(LOCALHOST);
System.out.println("Starting server");
server.start();
System.out.println("HTTP server started");
System.out.println("Running tests...");
testResourceAtUrl(new URL(LOCALHOST + "hellotest"));
}
private static String testResourceAtUrl(URL url) throws Exception {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String firstLineOfText = reader.readLine();//you can also read the whole thing and then test
System.out.println("Read: " + firstLineOfText);
System.out.println("System was initialized correctly. About to run actual tests...");
connection.disconnect();
return firstLineOfText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
throw new Exception("could not establish connection to " + url.toExternalForm());
}
@Test
public void testMyMethod() throws Exception {
String activationText = testResourceAtUrl(new URL(LOCALHOST + "myresource"));
//TODO test here
}
/**
* Destroy the server
*/
@AfterClass
public static void tearDown() throws IOException{
System.out.println("Stopping server");
server.stop(0);
System.out.println("Server stopped");
}
}
So here’s what the code above means:
1. @Path(”/hellotest”) The unit test itself is set up as a resource so when the tests are run we can check that the system is working by consuming the resource defined by testSystem()
2. Java 6 allows us to set up a HTTP server very easily using HttpServerFactory.create(LOCALHOST) This way we simply go ahead and send HTTP requests without having to worry about 3rd party libs and setting up mock HTTP servers.
3. testResourceAtUrl(new URL(LOCALHOST + “hellotest”)) does the hard work: it requests the resource from the location that we specify in the method call.
4. put your actual test data in the placeholder
Of course this is a simplified test, and it is meant just to show you how easy it is to test your RESTful webservices. How would you make this better?
Cheers…
Objective C – A translation from Java
Posted by Nick in Apple, Java, Objective C, Tutorial on September 30, 2008
Hello Objective C (objc) from a (mainly) Java developer. I’d love to welcome you into my portfolio of programming languages but hey, what’s with that slang, that weird terminology?!
In this blog post I will try to provide you with a translation, a dictionary or an index of terms that are used by objc programmers. If I have the time I will even keep it up to date…
I hope I am not breaking any NDAs by posting this, I am sure I will be told if I do…
Let’s not waste any time and jump straight in:
| Java |
Objective C |
What the?! |
| - | id | Just remember: everything is an id. Any object, any … anything. |
| Class (concept) (defined by a class) .class Files use .java extension. |
Class (concept) (defined by an interface and an implementation, see class structure below) class method Interface files use the .h extension, implementation files use the .m extension. |
Wanna know the class? do a [myObject class] |
| Interface | Protocol Files use the .h extension. |
One adopts a protocol rather than implement an interface. |
| this, super | self, super | Easy. |
| null | nil | lol |
| Field | Property (and instance variable) | One declares an instance variable (optional), then declares the @Property and finally specifies how it is implemented (@synthesize, @dynamic). Easy as. |
| Call / Invoke myObject.init() |
Send Message [myObject init] or myObject.init() (quite unconventional though) |
That is how one uses a type’s methods. This gets more complicated, look up Selectors in the context of sending messages. |
| Subclass class A extends BaseClass |
Subclass, Category, Extension @implementation A : BaseClass (CategoryOMG ) |
You see, things are not as simply as you thought. A class can not only be extended but also When defining a category you must import the class’s interface file. |
| abstract | - | N/A |
| public, protected, private | same | After specifying @public (or another) you can just list all the instance variables that have the same visibility. No need to do it for each variable. Cool eh?
One mention goes to package which cares about how many bits your platform has. google for this (search box available above) |
| static method, non-static method static void doSmth(){} void printName(){} |
class method, instance method + (void) doSmth; - (void) printName; |
That is just the method declaration in the objc column. The implementation uses brackets after the method name to group the method’s code, just like Java. |
| public void setOrigin(int x, int y); | - (void) setX:(int)x andY:(int)y;
Default return type is id. |
AndY is just a label for the second argument. Note that the colons and the labels are part of the method name. |
| Object | NSObject | This isn’t necessarily the Class that everything extends from. There is also NSProxy and you can also write your own. Feeling brave already? |
| toString() | description | The NSObject implementation returns the name & address of the object. Sounds familiar? |
| import | #import | One can reference just the class not include the whole thing. See comment below. |
| Class structure: import java.lang.*; class MyClass extends BaseClass implements Comma,Separated,List,OfInterfaces { //method definitions |
A class requires an Interface and an Implementation.
#import “BaseClass.h” @interface MyClass : BaseClass <Protocol1, Protocol2> //method declarations //and then don’t forget the implementation #import “MyClass.h” @implementation MyClass |
Too much can be said and surely you will be asking me questions anyway.
Still: @Class is used when no instances are created / used in your implementation but rather parameter names are of that particular type. Is is simply a low-weight #import. |
| Interface
interface A extends AnotherInterface, YetAnotherInterface{ |
Protocol Specified using @Protocol @Protocol A <AnotherProtocol, YetAnotherProtocol> //required by default @optional @end |
So much better…
Can incorporate another protocol just like Interfaces can extend other interfaces.
Methods are @required (by default) or @optional. Use these to group the mandatory and the optional methods or your You can declare objects that adopt a protocol: And last, you can forward reference a protocol: |
| MyClass myObject = new MyClass(); | MyClass *myObject = [[MyClass alloc] init];
or for non static typing: |
These are virtually equivalent. I suggest you use static typing if you want your compiler to be able to tell you if some method does not exist in the type that you are using, for example. |
| object’s fields initialization { [...] } and for static fields /* Honestly, when did you last use this rather than a constructor with arguments? */ |
- init - initWithBlah - init… and for Class initialization + (void) initialize; |
NSObject’s init returns self. Therefore all classes should define an init method to initialize their instance variables.
The runtime will call initialize before using a class object. I am a little bit confused myself but I believe them. |
| java.lang java.util etc | NS, CG, CF | NS = NextStep CG = Core Graphics CF = Core Foundation unless I am wrong of course. |
| instanceof | Defined in NSObject:
isMemberOfClass – actual class |
Cool!
Responds to selector means that the method exists in the class passed as argument while conforms to protocol means that ALL the methods in the protocol. I suspect that a YES response is returned if the methods defined by the protocol exist in the type passed as argument even if the type does not conform to the protocol. |
| synchronized | @synchronized() | No synchronized keyword for methods. A mutex is required. Self is a possible candidate, another good one can be _cmd as long as the method name is unique. Who is _cmd? Google in the search box above. |
| Exception | NSException
@try; @catch; @finally and @throw are the keywords. |
You can throw other objects, not necessarily part of the NSException inheritance tree.
Once an exception is caught it can be re-thrown by using @throw without having to specify the argument. |
| !!!
Invoking non-existent methods. Say they have been deprecated and removed from the API. |
forwarding
- (void) forwardInvocation: (NSInvocation *) theInvocation { Here’s what just happened: a method that does not exist on our “self” was called and the runtime forwarded the call to the method I wrote above. It could’ve freaked out but it didn’t, it kept its calm and got my kudos. The original Note: the NSObject’s forwardInvocation doesn’t do much. Soz. |
This is so cool, it should be a mandatory feature in all modern programming languages.
Can replace @deprecated, multiple inheritance (I can almost hear your cry), surrogate objects, proxies, delegates and more. It is up to you to confuse the crap out of all those that try to steal your job. Piece of advice: consider overriding respondsToSelector, isKindOfClass, etc to make it look like your surrogate objects actually belong in the type hierarchy. That will simply make you irreplaceable. |
| Remoting | RPC | Remote Messaging
Type qualifiers: Example: |
Normally all these qualifiers are to be used in the protocol that defines the remote messaging, not in the classes that you implement. They are implementation guidelines more than anything.
New to pointers? Then trust me: out and inout only make sense for pointers. |
| @deprecated | @interface SadClass - sadmethod __attribute__((deprecated)); @end |
|
| Spring Framework, Log4j, Maven, Axis, Acegi | LOL, ROFL, ZOMG | I just thought it would be funny |
My conclusion: objc is too powerful for its own good. God have mercy of all those who end up stuck in teams that have bad developers. Just stop and imagine someone abusing Categories and Extensions, what a disaster that project can become. Let me know when that happens though, I may have the right medicine
Do you want to study objc in depth? Well if you have an apple dev account then you already know where to find it. Otherwise try this wikibook.
Cheers…
p.s. special thanks go to my surgeon (who is truly awesome btw) who provided me with the time and the painkillers required to read the objc documentation
Google Android confirmed for 4th Quarter
Since then, we’ve been working with our Open Handset Alliance partners to incorporate much of that feedback, and finish the first devices. Since those devices are shipping in the fourth quarter, the platform is now converging on a final “Android 1.0″ version.
The 0.9 SDK brings about a ton of new stuff:
- The new Home screen is included, along with a ton of UI changes for 1.0.
- Some new applications are also included: an Alarm Clock, Calculator, Camera, Music player, Picture viewer, and Messaging (for SMS/MMS conversations.)
- Several new development tools were added, such as a graphical preview for XML layouts for users of Eclipse, and a tool for constructing 9-patch images.
- The source of the now-obsolete version from the M5 early-look SDK.
- A number of new APIs are fleshed out and improved, and others are now close to their final forms for 1.0.
- Tons of bugs were fixed, of course. (If you had problems with the MediaPlayer, try it now!)
So Google are trying to win back the developers after the terrible SDK mishap, when only the top 50 developers (Android Developer Challenge) were granted access to the “new” SDK while the rest of the community was left out in the dark. I wonder if it won’t be too late now that the iPhone is about to be rolled out in 21 new countries (22nd August).
UPDATE: The new SDK unfortunately no longer includes a number of APIs such as GTalkService (for security reasons), and the Bluetooth API. Quote: Due to significant API changes in the upstream open-source project and due to the timeline of getting certain Bluetooth profile implementations certified, a comprehensive Bluetooth API will not be possible or present in Android 1.0
Cheers…
Java ME on Windows Mobile
First of all, let me just say this: if one is using a Windows Mobile device, why would they need a J2ME / JavaME application? Unless maybe it’s a game…
Windows Mobile devices don’t always come with JVMs, which only makes it hard for both developers and users. The problem is that there are not too many options out there. Not free at least. Here are the implementations that I am aware of:
- IBM Websphere Everyplace Micro Environment (former J9)
- CrE-ME
- Jeode (discontinued) in favour of the more expensive Jbed
- Jbed
- JBlend
- JV-Lite2 Wireless Edition
As a developer one can probably only hope to get IBM’s implementation or CrE-ME, as the other ones are mostly sold to device manufacturers. I know it hurts to pay money for a Java ME implementation but if you google long enough you’ll find some free versions on some forums.
The other problems that I’ve found with these implementations is that you can’t get too fancy with your applications. Sometimes the SSL certificates are not available to these JVMs, other times if the application is served as a stream from some server the JVM (AMS) won’t install it. Other JVMs will read the URL and name the application after whatever follows the last forward slash “/”. Problems everywhere.
So why does SUN not step up and provide an implementation to help the Java ME developers out there? There is no official JVM for the iPhone, no JVM for the Android platform… Is SUN giving up on the Java ME platform?
Windows Mobile (CE) and Java have been on the market for a long time, yet they have not worked together and other platforms have stepped up and conquered the developers’ hearts. I really cannot see an iPhone developer switching to Java ME. I can imagine though lots of Java ME developers really looking forward to moving the Apple’s platform. And all this right before Google realease some final version of the hyped Android platform.
What do you think?
Cheers…
PostgreSQL + Named Queries = Headache
I am no DBA guy. No doubt about that. I would be even more frustrated if I were one. Today I stumbled upon another PostgreSQL issue but this time around I decided to share my anger with you.
Problem: Imagine that you need to write a query that returns the values that match a condition or null if nothing is matched. In other words you are trying to do a coalesce. So your query would be something like Select * from EMPLOYEE where :empNoParameter IS NULL or :empNoParameter = EMP_NO. Normally you’d rewrite this as: Select * from EMPLOYEE where EMP_NO = COALESCE(:empNoParameter, EMP_NO) because COALESCE will return the first non-null value that it finds … Now the problem is that in EJBQL or the new Java Persistence Query Language there is no Coalesce function. Damn. So you have to write in the first style. The problem is that, in PostgreSQL (8.3), you will get a org.postgresql.util.PSQLException: ERROR: operator does not exist: character
varying = bytea or something similar to that.
Solution: The query was Select * from EMPLOYEE where :empNoParameter IS NULL or :empNoParameter = EMP_NO and it failed; that happened because when the PostgreSQL JDBC driver first encountered the empNoParameter named parameter it had no clue what type it was because empNoParameter IS NULL does not really reveal the type. So the driver just assigned some default type to the param. Which would be okay if you didn’t need to do some other comparison later on with the same parameter. So when you come across :empNoParameter the second time around it will have the type it was given initially and will only work as intended if the EMP_NO is indeed of that type. Which in most cases will not be. So here is the solution: swap the tests around: Select * from EMPLOYEE where :empNoParameter = EMP_NO OR :empNoParameter IS NULL. Now the named query will work because the JDBC driver will be able to identify :empNoParameter’s type from the first test it has to make.
Rant: Why don’t you do a look ahead you silly PostgreSQL driver? Eh? Why don’t you?
Note: This is my guess as I have not studied the JDBC driver code. I know it worked in more than one scenario though so hopefully it will work for you too…
Cheers…

Recent Comments