1. Make sure Karaf features http, jetty and war are installed.
  2. Make sure http service is enabled in file etc/org.ops4j.pax.web.cfg. E.g. org.osgi.service.http.port=8080
  3. Deploy a blueprint bundle, exposing your servlet. My context.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

  <bean id="myServlet" class="org.whatever.MyServlet" />

  <service ref="myServlet" interface="javax.servlet.Servlet">
    <service-properties>
      <entry key="urlPatterns" value="/myServlet" />
    </service-properties>
  </service>
</blueprint>

Now you should have your Servlet available on http://localhost:8080/myServlet.

Others might say it’s dangerous due to a high risk of injuries, etc., but for me it was a very pleasant experience. I had four weeks for my preparation: did 13 runs, 2 of them were more than 10 km long.

I did my first half-marathon at a relaxed, easy pace; finished with 1:51:28 (Update: real calculated time is 1:50:12). No injuries, no problems, just had a very good time :)

I have started thinking about doing a full marathon, will probably require_a_bit_more_preparation…

If you forgot to run Vim with sudo and don’t have permissions to save a file, you can use a little trick from within Vim:

:w ! sudo tee % 

Write buffer [w] to external (system) command [!], the command is [sudo tee] and argument for tee is current filename [%]. Usually you would also redirect tee output somewhere (since it splits standard input by writing into argument file and standard output), in our case it could be tee % > /dev/null, but I don’t think it’s necessary here.

Probably a known thing, but anyway, love it, so just wanted to share…

Tonight I’ve played a bit with JDK 7 small language changes. I find some of them quite handy.

The new stuff:

I’ve always missed this one – strings in switch:

String string = "foo";

switch (string) {
    case "foo":
        System.out.println("bar");
        break;
}

Readability counts; underscores in numeric literals and nice binary literals (I personally think that the underscores in number literals look a bit ugly/hacky/unclean):

long l = 1111_2222_3333_4444L; // I is card number
double d = 0_0; // I is cute, 1337h4x0r style!
byte b = 0b00101010; // I is binary

System.out.println(l); // 1111222233334444
System.out.println(d); // 0.0
System.out.println(b); // 42

Less code for generics, meet the Diamond operator:

List<String> list1 = new ArrayList<String>(); // Pre JRE 7
List<String> list2 = new ArrayList<>(); // Diamonds are forever

Multi-catch:

try {
    // Uuuuu scary stuff here...
} catch (Exception|Error e) {
    // http://ns.c2.com/cgi/wiki?PokemonExceptionHandling 
}

No tedious resource closing in finally block, less code and it looks much cleaner:

/**
 * AutoCloseable will close the resource when it's not needed.
 * 
 * @see http://download.java.net/jdk7/docs/api/java/lang/AutoCloseable.html
 * 
 * @param file
 * @return
 * @throws IOException 
 */
public static String readFirstLine(String file) throws IOException {    
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        return reader.readLine();
    }
}

Simplified varargs method invocation – haven’t checked this improvement yet.

On the side note – Ubuntu 11.04 and Unity are awesome on my Eee netbook, I’ve been checking Unity during development and I honestly thought it will not be ready for the release.

Today a colleague of mine was having a problem with running a JPQL query which for some reason failed with a rather cryptic exception.

The code looked something like:

String query = "select s from SomeEntity e "
        + "join e.something s "
        + "where something "
        + variable == null ? "and something" : "and other";
System.out.println(query); // What is the output?

Even experienced developers were puzzled by this and we had a good laugh after the mystery was unsolved :)

Operator Precedence

From Surely You’re Joking, Mr. Feynman! (Adventures of a Curious Character) – an awesome bio of an awesome Physicist:

I sit down at the desk, and the psychiatrist starts looking through my papers. “Hello, Dick!” he says in a cheerful voice. “Where do you work?”

I’m thinking, “Who does he think he is, calling me by my first name?” and I say coldly, “Schenectady.”

“Who do you work for, Dick?” says the psychiatrist, smiling again.

“General Electric.”

“Do you like your work, Dick?” he says, with that same big smile on his face.

“So‑so.” I just wasn’t going to have anything to do with him.

Three nice questions, and then the fourth one is completely different. “Do you think people talk about you?” he asks, in a low, serious tone.

I light up and say, “Sure! When I go home, my mother often tells me how she was telling her friends about me.” He isn’t listening to the explanation; instead, he’s writing something down on my paper.

Then again, in a low, serious tone, he says, “Do you think people stare at you?”

I’m all ready to say no, when he says, “For instance, do you think any of the boys waiting on the benches are staring at you now?”

While I had been waiting to talk to the psychiatrist, I had noticed there were about twelve guys on the benches waiting for the three psychiatrists, and they’ve got nothing else to look at, so I divide twelve by three–that makes four each–but I’m conservative, so I say, “Yeah, maybe two of them are looking at us.”

He says, “Well just turn around and look”–and he’s not even bothering to look himself!

So I turn around, and sure enough, two guys are looking. So I point to them and I say, “Yeah–there’s that guy, and that guy over there looking at us.” Of course, when I’m turned around and pointing like that, other guys start to look at us, so I say, “Now him, and those two over there‑and now the whole bunch.” He still doesn’t look up to check. He’s busy writing more things on my paper.

Then he says, “Do you ever hear voices in your head?”

“Very rarely,” and I’m about to describe the two occasions on which it happened when he says, “Do you talk to yourself?”

“Yeah, sometimes when I’m shaving, or thinking; once in a while.” He’s writing down more stuff.

“I see you have a deceased wife–do you talk to her ?”

This question really annoyed me, but I contained myself and said, “Sometimes, when I go up on a mountain and I’m thinking about her.”

More writing. Then he asks, “Is anyone in your family in a mental institution?”

“Yeah, I have an aunt in an insane asylum.”

“Why do you call it an insane asylum?” he says, resentfully. “Why don’t you call it a mental institution?”

“I thought it was the same thing.”

“Just what do you think insanity is?” he says, angrily.

“It’s a strange and peculiar disease in human beings,” I say honestly.

“There’s nothing any more strange or peculiar about it than appendicitis!” he retorts.

“I don’t think so. In appendicitis we understand the causes better, and something about the mechanism of it, whereas with insanity it’s much more complicated and mysterious.” I won’t go through the whole debate; the point is that I meant insanity is physiologically peculiar, and he thought I meant it was socially peculiar.

Up until this time, although I had been unfriendly to the psychiatrist, I had nevertheless been honest in everything I said. But when he asked me to put out my hands, I couldn’t resist pulling a trick a guy in the “bloodsucking line” had told me about. I figured nobody was ever going to get a chance to do this, and as long as I was halfway under water, I would do it. So I put out my hands with one palm up and the other one down.

The psychiatrist doesn’t notice. He says, “Turn them over.”

I turn them over. The one that was up goes down, and the one that was down goes up, and he still doesn’t notice, because he’s always looking very closely at one hand to see if it is shaking. So the trick had no effect.

Finally, at the end of all these questions, he becomes friendly again. He lights up and says, “I see you have a Ph.D., Dick. Where did you study?”

“MIT and Princeton. And where did you study!”

“Yale and London. And what did you study, Dick?”

“Physics. And what did you study?”

“Medicine.”

“And this is medicine ?”

“Well, yes. What do you think it is? You go and sit down over there and wait a few minutes!”

So I sit on the bench again, and one of the other guys waiting sidles up to me and says, “Gee! You were in there twenty‑five minutes! The other guys were in there only five minutes!”

“Yeah.”

“Hey,” he says. “You wanna know how to fool the psychiatrist? All you have to do is pick your nails, like this.”

“Then why don’t you pick your nails like that?”

“Oh,” he says, “I wanna get in the army!”

“You wanna fool the psychiatrist?” I say. “You just tell him that!”

After a while I was called over to a different desk to see another psychiatrist. While the first psychiatrist had been rather young and innocent‑looking, this one was gray‑haired and distinguished‑looking–obviously the superior psychiatrist. I figure all of this is now going to get straightened out, but no matter what happens, I’m not going to become friendly.

The new psychiatrist looks at my papers, puts a big smile on his face, and says, “Hello, Dick. I see you worked at Los Alamos during the war.”

“Yeah.”

“There used to be a boys’ school there, didn’t there?”

“That’s right.”

“Were there a lot of buildings in the school?”

“Only a few.”

Three questions–same technique‑and the next question is completely different. “You said you hear voices in your head. Describe that, please.”

“It happens very rarely, when I’ve been paying attention to a person with a foreign accent. As I’m falling asleep I can hear his voice very clearly. The first time it happened was while I was a student at MIT. I could hear old Professor Vallarta say, ‘Dee‑a dee‑a electric field‑a.’ And the other time was in Chicago during the war, when Professor Teller was explaining to me how the bomb worked. Since I’m interested in all kinds of phenomena, I wondered how I could hear these voices with accents so precisely, when I couldn’t imitate them that well … Doesn’t everybody have something like that happen once in a while?”

The psychiatrist put his hand over his face, and I could see through his fingers a little smile (he wouldn’t answer the question).

Then the psychiatrist checked into something else. “You said that you talk to your deceased wife. What do you say to her?”

I got angry. I figure it’s none of his damn business, and I say, “I tell her I love her, if it’s all right with you!”

After some more bitter exchanges he says, “Do you believe in the supernormal?”

I say, “I don’t know what the ‘supernormal’ is.”

“What? You, a Ph.D. in physics, don’t know what the supernormal is?”

“That’s right.”

“It’s what Sir Oliver Lodge and his school believe in.”

That’s not much of a clue, but I knew it. “You mean the supernatural .”

“You can call it that if you want.”

“All right, I will.”

“Do you believe in mental telepathy?”

“No. Do you?”

“Well, I’m keeping an open mind.”

“What? You, a psychiatrist, keeping an open mind ? Ha!” It went on like this for quite a while.

Then at some point near the end he says, “How much do you value life?”

“Sixty‑four.”

“Why did you say ‘sixty‑four’?”

“How are you supposed to measure the value of life?”

“No! I mean, why did you say ‘sixty‑four,’ and not ‘seventy‑three,’ for instance?”

“If I had said ‘seventy‑three,’ you would have asked me the same question!”

The psychiatrist finished with three friendly questions, just as the other psychiatrist had done, handed me my papers, and I went off to the next booth.

While I’m waiting in the line, I look at the paper which has the summary of all the tests I’ve taken so far. And just for the hell of it I show my paper to the guy next to me, and I ask him in a rather stupid‑sounding voice, “Hey! What did you get in ‘Psychiatric’? Oh! You got an ‘N.’ I got an ‘N’ in everything else, but I got a ‘D’ in ‘Psychiatric.’ What does that mean?” I knew what it meant: “N” is normal, “D” is deficient.

The guy pats me on the shoulder and says, “Buddy, it’s perfectly all right. It doesn’t mean anything. Don’t worry about it!” Then he walks way over to the other corner of the room, frightened: It’s a lunatic!

I started looking at the papers the psychiatrists had written, and it looked pretty serious! The first guy wrote:

Thinks people talk about him.

Thinks people stare at him.

Auditory hypnogogic hallucinations.

Talks to self.

Talks to deceased wife.

Maternal aunt in mental institution.

Very peculiar stare. (I knew what that was–that was when I said, “And this is medicine ?”)

With Hibernate and generic DAO it has now become a common practice to figure out the class of generic type at runtime (please note that the code is a bit simplified):

import java.lang.reflect.ParameterizedType;

// It's not marked as abstract, probably better name would be GenericDao...
public class AbstractDao<T> {

    private Class<T> elementClass;

    @SuppressWarnings("unchecked")
    public AbstractDao() {
        elementClass =
                (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                        .getActualTypeArguments()[0];
    }

    public Class<T> getElementClass() {
        return elementClass;
    }
    ...
}

Then we can do things like:

public class ConcreteDao extends AbstractDao<SomeEntity> {
}

ConcreteDao dao = new ConcreteDao();

This approach is very nice, since we don’t have to pass an entity class during initialization. But it has some limitations, one of which is that it won’t work if we try to initialize it directly, e.g.:

// java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
AbstractDao<SomeEntity> dao = new AbstractDao<SomeEntity>();

Due to type erasure it is not possible to figure out the generic type for stand alone generic class, e.g. AbstractDao. This can be done only for superclass. In this case the superclass is Object, so sorry, no go.
For this case we can add a remedy – another constructor with a Class parameter, then we can initialize the class like this:

AbstractDao<SomeEntity> dao = new AbstractDao<SomeEntity>(SomeEntity.class);

Also since we are trying to getGenericSuperclass, this code will work only with single inheritance, multiple inheritance won’t work:

public class ConcreteDao extends AbstractDao<SomeEntity> {
}
class SpecializedDao extends ConcreteDao {
}

SpecilizedDao dao = new SpecializedDao(); // no go, since constructor tries to read generic info from ConcreteDao

After some thinking I’ve made it a little bit more flexible (but in a somewhat hacky way):

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class AbstractDao<T> {

    private Class<T> elementClass;

    public AbstractDao(final Class<T> clazz) {
        elementClass = clazz;
    }

    @SuppressWarnings("unchecked")
    protected AbstractDao() {
        Class<?> cl = getClass();

        if (Object.class.getSimpleName().equals(cl.getSuperclass().getSimpleName())) {
            throw new IllegalArgumentException(
                    "Default constructor does not support direct instantiation");
        }

        while (!AbstractDao.class.getSimpleName().equals(cl.getSuperclass().getSimpleName())) {
            // case of multiple inheritance, we are trying to get the first available generic info
            if (cl.getGenericSuperclass() instanceof ParameterizedType) {
                break;
            }
            cl = cl.getSuperclass();
        }

        if (cl.getGenericSuperclass() instanceof ParameterizedType) {
            elementClass =
                    (Class<T>) ((ParameterizedType) cl.getGenericSuperclass())
                            .getActualTypeArguments()[0];
        }
    }

    public Class<T> getElementClass() {
        return elementClass;
    }
    ...
}

Now we can do things like:

public class ConcreteDao extends AbstractDao<SomeEntity> {
}
class SpecializedDao extends ConcreteDao {
}

SpecilizedDao dao = new SpecializedDao();
Follow

Get every new post delivered to your Inbox.