Android presentation, prezi and general impression

This is my first post without any code, but I just had to express myself :)

Today I had my first non-JavaSvet presentation (for those who don’t know JavaSvet is the first serbian Java user group). It was organized by the great people in SEE ICT organization. I wasn’t the only speaker,  a friend of mine Vladan Petrović  was in it as well, and he made this awesome presentation in prezi (I’ve helped with the content, not that much with the overall design). You can find the presentation here.

Photo by Vladimir Trkulja

I must say that I am pretty impressed how fast it was to make a presentation, and how effective it looks like. I saw that some people in the audience were impressed. And also, this was my first time presenting something that is inside a browser, and not powerpoint/open(libre)office. So it was all pretty new for me.

The goal was to first explain android basics, and later give them some small exercises that they can work on. We decided to test them with a little bit of tic-tac-toe. We’ve showed all the basics with this little example that I have made (github link). In case you need it, you can find there some basic examples of activities, services, broadcast receivers and content provider. Basically all-in-one example. It’s a small, but functional mp3 player (actual song isn’t hosted @ github). To make things more geeky, I’ve selected Paranoid Android by Radiohead (OK Computer album), cool eh?

The thing that totally blew me away was that when I got back home, I’ve already had some facebook invites, and tweets, that people continued working on the example as their first project.

I would be the luckiest man if any of those guys keep on working, and if they can make some cash out of it, that would be more than amazing. So thumbs up for everybody :)

UPDATE: Great guys from start it uploaded the video to youtube.

Advertisement

JavaMail, Spring and Google apps mail

Whoa, second post in one day :)

In my application I want to use spring’s mail sender with my google apps account. I was getting:

org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first

After a little bit of help form my dear friend, I found out that all you need to do is:

<bean id="javaMailSender">
   <property name="host" value="${mailer.host}"/>
   <property name="username" value="${mailer.user}"/>
   <property name="password" value="${mailer.pass}"/>

   <property name="defaultEncoding" value="${mailer.encoding}"/>

   <property name="javaMailProperties">
      <props>
         <prop key="mail.smtp.auth">true</prop>
         <prop key="mail.smtp.starttls.enable">true</prop>
      </props>
   </property>
</bean>

Take a look at the javaMailProperties element. Yup. That’s all you need to add to your configuration xml.

Spring Security, OpenId and special characters

I wanted to enable open id login with spring security 3.0.7. I’ve used google as a open id provider.
Setup was pretty easy, everything by the book. I’ve tried with couple of accounts and everything was ok.

But when I tried to use my “official” google account, I’ve ran into a problem. My account couldn’t pass the verification. In log files I’ve found this:

Verification failed for: [http://somedomain] reason: null

Reason null. Whoa, too much information :)

Googling didn’t help much, until I’ve realized that the problem was in encoding. Yup, all accounts worked except mine… and I have the letter ć in my surname. I guess the same problem would be with umlauts and similar.

The easiest fix was to add just one attribute to the Connector element in server.xml tomcat configuration. The magical attribute is:

URIEncoding="UTF-8"

Hibernate Audit logging – the easy way!

Let’s say you are working on an application where users are constantly adding/changing  new content. You will most likely have to keep a record what’s going on. For example you want to make a wiki-like software, it is crucial to keep a log who added/updated/deleted wiki entries.

If you need that functionality, and you are using Hibernate, then you are one happy coder! Enter ENVERS! As the good people at jboss site say: Easy Entity Auditing.

Here is what you need to do make your entities auditable:

  1. Download latest hibernate with envers bundled (I’m using 3.6.0.Final) and add it to your classpath
  2. Add envers event listeners to your session factory (I’m using spring in my project, so here is a part of my spring.xml):
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
       <!-- Envers - Auditlogging -->
       <property name="eventListeners">
          <map>
             <entry key="post-insert"><ref local="enversListener" /></entry>
             <entry key="post-update"><ref local="enversListener" /></entry>
             <entry key="post-delete"><ref local="enversListener" /></entry>
             <entry key="pre-collection-update"><ref local="enversListener" /></entry>
             <entry key="pre-collection-remove"><ref local="enversListener" /></entry>
             <entry key="post-collection-recreate"><ref local="enversListener" /></entry>
          </map>
       </property>
    </bean>
    <bean id="enversListener" class="org.hibernate.envers.event.AuditEventListener" />
    
  3. Annotate your class with @Audited. If you don’t want to keep track of all properties, just annotate the fields you need with the same @Audited.

And that is it :)

After completing all the three steps you will see new table called revinfo (that keeps all the revisions information, you can change it’s name, prefix/suffix, check out the docs) and <entity>_aud (log for the specified entity).

I had a problem that <entity>_aud didn’t have all the required fields, even with hibernate.hbm2ddl.auto set to update. Adam Warski (great guy that create Envers, thanks man!)  gave somebody a great tip in jboss forum, that helped me. I’ve just added @Audited for my getters and everything worked smoothly.

One thing I needed more is to keep track WHO made the changes. Here is a nice tutorial how to do that. To keep it short:

  1. Extend DefaultRevisionEntity and annotate it with @RevisionEntity
    @RevisionEntity(PectopahRevisionListener.class)
    public class PectopahRevisionEntity extends DefaultRevisionEntity {
    	private String username;
    
    	public String getUsername() { return username; }
    	public void setUsername(String username) { this.username = username; }
    }
    
  2. Create your own RevisionListener
    public class PectopahRevisionListener implements RevisionListener {
        @Autowired
        private UserService userService;
        @Override
        public void newRevision(Object revisionEntity) {
               PectopahRevisionEntity pectopahRevisionEntity = (PectopahRevisionEntity) revisionEntity;
               User user =  userDetails.getCurrentUser();
               pectopahRevisionEntity.setUsername(user.getUsername());
            }
        }
    }
    
  3. In case you are using hbm.xml files (like me), add the following:
    <hibernate-mapping package="...your package...">
    	<class name="PectopahRevisionEntity" table="revinfo">
            <id name="id" type="int">
    			<column name="rev" not-null="true"/>
    			<generator class="native"/>
    		</id>
            <property name="timestamp" type="long" column="timestamp" />
    		<property name="username" type="string" not-null="true"/>
    	</class>
    </hibernate-mapping>

    (here you could rename table’s name and/or fields).

Simple as that. There is also a simple mechanism how to retrieve info from audit log, but I’ll maybe cover that some other time, it’s almost 1am :)

It makes me really happy to find great tools like this one. Easy to setup, clean and simple API, and yeah it does the job!

Lucene’s Field options (Store and Index), aka RTFM :)

To make a long story short, if you want to make a field act as a database primary key (so you could update/delete a document), create a field with this parameters:

document.add(new Field("id", object.getId(), Store.YES, Index.NOT_ANALYZED));

This was a big RTFM moment for me. I’ve lost a lot of time with this one, and it was really simple. So I guess you are wondering why I didn’t check this :) Well in another project, it was Index.NO instead of Index.NOT_ANALYZED, and I thought that was ok, and checked EVERYTHING else, except that line you see above this text.

So, let’s read the manual together, first the Store options

  • Store.YES – Value is stored in index, so it can be retrieved by an IndexReader.
  • Store.NO – Not stored :)

Now the Index options:

  • Index.No – not indexed, so not searchable (… and in my case, if you don’t index the “ID” field, than it can’t be searchable, which means it can’t be deleted and/or updated)
  • Index.ANALYZED – Field will be indexed, and it will be analyzed (saved as tokens that will be searchable)
  • Index.NOT_ANALYZED – Field will be indexed but in it’s original form (good for things that should be searchable in original form, ID anybody? :))

So, if I got everything right, here are some good combinations:

Store.YES + Index.ANALYZED = In index and analyzed, good for not so big content, such as a title and some short intro text (first few lines you see in a blog, before you go to that post)

Store.NO + Index.ANALYZED = Not stored in index, but analyzed and searchable, so pretty good for big text (content)

Store.YES + Index.NOT_ANALYZED = Stored in index in it’s original form, great for IDs :)

If I got something wrong, feel free to point that out (in comments or hate mail), also if you got lucene tips, please share :D

@Embeddable with hbm.xml

At work we are using hibernate with annotations. So in some places we use the @Embeddable & @Embedded annotation. What do they do? They are both standard annotations, @Embeddable means “this class will not have it’s own table, and it will be embedded in some other’s class table”, and @Embedded means “embed this field to my table”.

That’s all good, but I’ve returned to my old project (klopaj.com), and what do we have there? hbm.xml files. I confess, I’ve first started using hibernate annotations, and then hbm files, so I’m not a hbm guru (nor annotations, but I know a bit more :)). So, to do the same thing with hbm.xml:


<class name="Poi"...>
...
<component name="geoPoint" access="field" class="GeoPoint">
<property name="latitude" type="double" />
<property name="longitude" type="double"  />
...
</component>

Simple as that, now my Poi table has two additional columns “latitude” and “longitude”, but my Poi class has a reference to GeoPoint instance. :)
But still, I like the annotation solutions prettier, but this one is working as planned.

Introducing the “Toink” sessions

I’ve very pleased to announce something that I want to do in a very long time. I’ve heard a million times “this framework is much better than <insert name> framework”, “it’s cool, but to difficult to setup” ,”too many XMLs” etc.

So what will I do? Simple, try to test all the frameworks as much as I can on a very simple application. The mystery application name is “Toink”, so there’s the name “Toink Session”! And yeah, the name doesn’t mean anything, it’s windows default sound when something goes wrong :)

Every framework will use the same backend (core) that has been implemented in Hibernate + Guice combination. And I’ll with test to see how simple it is to setup some framework, use a “legacy” code, and try to use the old POJO objects. Maybe I will do some performance tests as well, because all the frameworks will you the same core.

All the code, examples, bugs and wiki will be @ code.google.com/p/toink. I still don’t know how often will I post here, but as soon as some framework is done, I’ll post it here.

Ready or now, here we go! The first framework will be Apache Wicket!

I would like to hear your thoughts and ideas in the comments :)

The Unbearable Lightness of Java – jodd

I was amazed when I first read about this library.  It’s almost unbelievable what is packed in less than 850KB. Without further ado, let me represent jodd!

jodd logo

As the author said himself:

Jodd = tools + ioc + mvc + db + aop + tx < 850KB

There are two main parts, one is the general utility library, and the second being a set of lightweightapplication frameworks.

  1. How many times you had to deal with date in java? You can still feel the pain? Here is the cure JDateTime. Ever had a need to copy entire bean? Use BeanUtil. Sending email is your thing? Yup, jodd has that covered. Auto-populating forms? Checked. Also there are StringUtil, Printf, special JSP tag library and bunch more. Very useful from time to time.
  2. Second part is interesting as well. There is a slick MVC framework named Madvoc (I’ve used it in one of my projects, simple as hell), Petite (DI container, no XMLs :)), DB access layer and more.

Check it up yourself at www.jodd.org. Documentation is great and there are planty of examples to get you started (much better than my examples anyway)

Also there you can find “Uphea“, application built on jodd framework.

Sonar – open source software quality tool

Wow, I don’t know how did I miss this awesome tool. Just go to http://www.sonarsource.org/ download it and install it. It will help you keep your code much cleaner and with less bugs (I didn’t say bugless :))

Installation is easy, UI is simple enough, a lot of features (different metrics, time machine, unit tests etc)… And one of the great things I love about it there is a Sonar plugin for Hudson, and you can find it http://wiki.hudson-ci.org/display/HUDSON/Sonar+Plugin. With that plugin you could analyze your code with every night build, compare it to the previous, see if you have any improvements.

Oh yeah, one more thing, it’s maven ready. And if you are not using Java, there is a PHP, Flex, .NET, Groovy… plugins, check it out here http://docs.codehaus.org/display/SONAR/Sonar+Plugin+Library

Wicket, Hibernate and filters (web.xml)

I guess everybody read about Open Session In View. So, as the jboss guys said there, we need something like SessionRequest filter. No problem with that. I’ve used almost the same code in my application, but I had issues with it.

What happend? Well, sometimes after saving something wicket would block, wait a minute and throw a “After 1 minute the Pagemap null is still locked by:” exception. I’ve read alot about that, but couldn’t find any solution!

Luckly, I found one mailing list, where somebody said that SessionRequest should be defined before WicketFilter (I’ve lost the link, but when I find it, I’ll post it).  Here is how my web.xml looks like now and it worked!

<filter>
 <filter-name>SessionRequestFilter</filter-name>
 <filter-class>com.vuknikolic.SessionRequestFilter</filter-class>
 </filter>
 <filter-mapping>
 <filter-name>SessionRequestFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

<filter>
 <filter-name>wicket.patientportal</filter-name>
 <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
 <init-param>
 <param-name>applicationClassName</param-name>
 <param-value>com.vuknikolic.WicketApplication</param-value>
 </init-param>
 </filter>
 

UPDATE: I need to find some plugin for posting source code…

UPDATE 2: Found one source code highlighter, yay!