Educating the world

Our blog has over 10,000 readers a month

Active Spring transaction synchronization or active JTA

January 30th, 2012

During Spring development I got this exception, but there was almost no reference to what caused it. So after a lot of searching I found out the cause and thought I’d blog it for others struggling with the same problem.

java.lang.IllegalStateException: Active Spring transaction synchronization or active JTA transaction with specified [javax.transaction.TransactionManager] required
 at org.springframework.jdbc.support.lob.LobCreatorUtils.registerTransactionSynchronization(LobCreatorUtils.java:79)
 at org.springframework.orm.hibernate3.support.AbstractLobType.nullSafeSet(AbstractLobType.java:185)
 at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:146)
 at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:1997)
 at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:1974)
 at org.hibernate.persister.entity.AbstractEntityPersister$3.bindValues(AbstractEntityPersister.java:2152)
 at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:32)
 at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
 at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
 at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
 at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
 at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
 at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
 at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:94)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
 at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
 at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
 at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
 at org.springframework.orm.hibernate3.HibernateTemplate$16.doInHibernate(HibernateTemplate.java:696)
 at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:373)
 at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:693)
 at uk.co.bigsoft.Manager.thumbs.ClipThumbnailManagerDaoHibernate.setClipThumbnail(ClipThumbnailManagerDaoHibernate.java:66)
 at uk.co.bigsoft.Manager.thumbs.ClipThumbnailManager.setClipThumbnail(ClipThumbnailManager.java:25)
 at uk.co.bigsoft.Manager.corba.ThumbnailReader.newThumbnail(ThumbnailReader.java:106)
 at uk.co.bigsoft.corba_2_3.ThumbnailListenerPOATie.newThumbnail(ThumbnailListenerPOATie.java:53)
 at uk.co.bigsoft.corba_2_3.ThumbnailListenerPOA._invoke(ThumbnailListenerPOA.java:50)
 at org.jacorb.poa.RequestProcessor.invokeOperation(RequestProcessor.java:299)
 at org.jacorb.poa.RequestProcessor.process(RequestProcessor.java:602)
 at org.jacorb.poa.RequestProcessor.run(RequestProcessor.java:745)

In order to add large binary objects to a hibernate persistent store (database), the action must be part of a transaction.

In the springframework you must have several beans set up. The first is a datasource bean. This describes how to talk to the database; what language to use, and how to access it.

XML

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/myDb"/>
  <property name="username" value="myUsername"/>
  <property name="password" value="myPassword"/>
</bean>

The default behaviour of the DriverManagerDataSource is to use database transactions if possible. However you need a transaction manager inside the spring application to manage the transaction as a whole; i.e. there may be more transactional units other than a database transaction that need to be tied together, such as a Java Message Queue Transaction. It is this overall Transaction manager that controls whether a particular transaction is committed or rolled back.

Spring provides a factory for creating (or reusing already existing) transaction objects depending on the code we are currently running through.

XML

<bean id="jotm" class="org.springframework.transaction.jta.JotmFactoryBean" />

The transaction manager organises the rules of how one transaction interacts with another, for example we don’t want to fail a larger transaction because a smaller unit of work fails - we would want to retry the smaller transaction several times before failing the larger transaction. The transaction manager manages this.

XML

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
  <property name="userTransaction">
    <ref local="jotm" />
  </property>
</bean>

We would like to use annotations in our code so we will need to tell the xml engine how to understand <tx : ??> namespace tags.

XML

&lt;beans
    xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    "&gt;

Next we set the transaction manager to use when we use transaction annotations in our code.

XML

&lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;

Large binary objects need to run inside a transaction because they may have several stages that need to be completed before we can continue. If one of the stages fails, we need to be sure that the system will be able to clean up after us. Spring enforces this as a requirement.

We need a bean to manage the handling of a Large Object (LOB). Spring’s job is to abstract away the complexities of handling 3rd party APIs. Different databases handle LOBs in different ways so we need a LOB handler to take care of them for us:

XML

&lt;bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"/&gt;

We are going to use Hibernate as our object persistence store, so we need a session factory to get our Hibernate sessions. The Session Factory needs to know how to talk to the database and how to handle LOBs. We’ll use a bean for that.

XML

&lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;
  &lt;property name="dataSource" ref="dataSource" /&gt;
  &lt;property name="lobHandler" ref="defaultLobHandler"/&gt;
  &lt;!-- other properties --&gt;
&lt;/bean&gt;

Note:
Unfortunately I wrote this ages ago but never finished it and never published it. I don’t work in this area any more and don’t have the will power to get back into Spring. So I publish it uncompleted with just a reference to what I was going to put in it. Maybe the first part will give help to some one looking for the meaning of the exception.

TODO:
show an hbm mapping for the database
show a pojo using input stream
show doa using @Transaction
without @Transactional you get the error.

Direct and indirect discourse

January 27th, 2012

The last couple of lessons have centred around dialogue.

We had also been discussing how the descriptive text surrounding the dialogue can change everything. I tried to create the same scenario with the same characters but couldn’t quite manage it. The original idea was to have 2 passages which present a different view of the same situation and alter the readers perspective by altering the flowering around the dialogue.

I was going to link direct and indirect discourse to Wikipedia but surprisingly their definitions didn’t seem to fall in line with what teacher said. In fact I couldn’t find a good explanation of what direct and indirect discourse was from Google’s first page. So I provide these passages for you as examples. Can you spot which is direct discourse and which is indirect discourse?

First timer

Professor James Monroe slowed the car to a stop. There was almost nobody around. Shadows hid the space between the pavement and the factory doorways. Street lamps flickered and buzzed. The council hadn’t been here for a while.
A woman approached James’ passenger window and tapped on the glass with her ring.
“What do you want?", she asked in a quiet but bold voice.
This was James’ first time down Loose Lover’s Court. Trying to hide inside the car he said sheepishly, “Not really sure, what do you do?".
The woman listed the standard services with prices for each.
“We can talk about any specialist requests you might have, but we can do that later.”
James took a moment to think. Sweat was running down the sides of his waist. He felt so far out of his comfort zone that he started to shake. The woman leaned in through the window and with a comforting voice said, “Don’t worry, I’ll look after you, it’ll be all right. We don’t have to do anything you’re not comfortable with; we can just talk if you like.”
James looked visibly relieved. “Okay” he said.

Just starting

Jane Bishop was sitting behind her desk looking around her new office. The broom cupboard she had when she was a lecturer was pitifully small compared to a professor’s office.
There was a gentle knocking at the door. “What do you want?” she shouted.
The door opened a jar and a young man stuck his head around.
“Not really sure, what do you do?", he said with a nervous voice that kept cutting out.
Jane had gone to a lot of trouble to get her name and job title embossed on her office door and was about to launch into a diatribe about students walking around with their eyes closed when she noticed a guide dog sniffing at his heals. She took a breath and explained her new position with obvious glee which was clearly lost on John. She when on to explain which philosophy courses they ran at the college and finished with “We can talk about any specialist requests you might have, but we can do that later.”
John seemed at ease, but Jane felt guilty about what she almost said. She re-assured him with “Don’t worry, I’ll look after you, it’ll be all right. We don’t have to do anything you’re not comfortable with; we can just talk if you like.”
“Okay", said John, pleased that he wouldn’t have to do any writing.

I include my first attempt at the “Just starting” story but I had to bin it half way through because I felt like I had got myself into a pickle.

Second story first draft

Professor James was absently starring out of the window of his new office when there was a knock on his door. Before he could say anything the door flew open and his latest project walked in. Maria was a prostitute from the east end of town. She was on her third strike and has been told to co-operate or it was jail.
“What do you want?” she snapped impatiently. She didn’t want to be there, but for her there was no choice.
James didn’t know who the police would be sending, he only knew the area of town they’d be from.
“Not really sure, what do you do?".
She explained that she’d been busted last week for solicitation and possession. James explained that he was writing a book about the underworld and he’d needed her help.

I tried to think of situations that would allow the man to say “We can talk about any specialist..” but struggled so I started again.

Teacher and class comments
First timer

  1. Easier to visualise.
  2. Good use of indirect discourse which maintained the pace of the story.
  3. Story showed her sensitivity.
  4. Good use of “Showing” when talking about Monroe sweating.

Just starting

  1. Difficult to follow.
  2. Very quickly the story reveals lots of facts about the Professor: happy, new job, etc.
  3. Clever plot twist making John blind, no one expected that.

Both stories

  1. Introduced people early.
  2. Most of the class enjoyed the Just starting better.
  3. The tension was palpable.

Second story first draft

  1. “Latest project” liked that, good twist.
  2. Didn’t need to say she was a prostitute because it would be referred to later in the passage.

Writing can change the world

January 25th, 2012

This phrase was thought up by Stephen Fry. He enlisted the help of the engraver Graham Short to write it on the side of a fountain pen which would be auctioned in aid of English Pen the body that represents imprisoned writers around the world:

Waggled in the right way this inky little stick can change the world.

Creating a MySQL user under Plesk

January 24th, 2012

Plesk has a comprehensive web interface but every now and again you just want to get at the nuts and bolts. Avoiding the Plesk interface will allow you to do batches of tasks or automated work.

This article shows us how to create a database, add a user and set up their permissions. I’ve always found MySQL’s permission and grant structure unnecessarily complicated so in this example we are just going to give the users all the default permissions.

First up create the database. Under Plesk you can call the database anything you like, but I’ve adopted the naming convention <domain>_<usage>. This gives me several advantages:

  1. It groups the databases together in the file system so it is easier to find what you are looking for.
  2. Avoids name clashes.
  3. If you create a database outside Plesk it is not managed, which means it won’t get deleted when you delete the domain. All MySQL database files are owned by MySQL so it’s difficult to see which domain a particular database instance belongs to. Not any more!
  4. Your system looks like there is order!

First up is to create a database for example.com and we are going to use it for the world’s best blogging software B2evolution.

mysqladmin -uadmin -p`cat /etc/psa/.psa.shadow` create example_com_b2evolution

There’s no need to enter our password on the command line because Plesk stores it in a file.
The database creation time is almost instant.
Next up, we need to enter the MySQL command line.

mysql -uadmin -p`cat /etc/psa/.psa.shadow`

Strictly speaking you can create database instances from inside MySQL using the following command.

CREATE DATABASE example_com_b2evolution;

I prefer to do it externally though, partly because after the database has been created you can enter the MySQL command prompt straight into that clean database but mostly because soon after creating the database I do an import which is another external command.

The only people accessing the database will be my web server on the localhost. Users can have access to database, tables, DDL commands, functions, store procedures and triggers. In reality though, in almost all cases you just want one user who can access everything in one database instance and that’s it. I’ve been using MySQL for 15 years and never had to give a user a single table, select only permission! Enough babbling, MySQL says you have to create a floating user first then assign permissions to them. If I was going to go completely anal I would insist on having a separate user for each application and add table level permissions for that user to access just those tables, but generally speaking it’s not worth the hassle. Domain specific administrators want to be able to log in and check their databases, they don’t want to keep switching users to administer different applications in the same database. You’ll find in fact that you’ll need a database user for some operations like repairing or optimising tables.

From the MySQL command prompt:

CREATE USER david;

Now that we have a user we’ll assign them some rights. This statement says “Give david access to all the tables in the example_com_b2evolution database, but only when he logs in from the localhost. You can set different permissions for when I log in from home or whether I login from work! I don’t like the idea that my security level changes depending on where I’m logging in from. It just feels wrong. I always thought it would be better and cleaner to have a separate user as it can lead to confusion.

GRANT ALL ON example_com_b2evolution.* TO david@localhost;

Finally we must set a password for our user. A side effect of having floating users and host name restrictions is that you can have a different password depending on where you log in from. This seems even wronger!

SET PASSWORD FOR david@localhost=PASSWORD(’!,DaViD54890′);

I have experimented with this in the past and it was a pain in the arse! There were all sorts of peculiar behaviours and I seemed to spend most of my time trying to figure out why you could log in from hostB with userA but not with userB.

The internet is one big soapbox

January 16th, 2012

The Internet’s content can be split into many pieces, but it can be characterised into just 2 (well 3 if you count all the porn!): what people know and what people think.

What people know is simple; it includes all the journals, academic papers, research, medical journals, technical specifications and documentation. All of these sources are considered true (at the time of writing). What people think is also simple. These are (but not limited to) blogs, forums, comments sections, Facebook and Twitter.

But wait… is it really that simple? No. If you know my mate Switfy, he talks like it’s true but he has no idea and is generally just making it up. So at the end of one of his explanations we have to ask: “Is that true or Swifty-True?". The Internet is still run by people and everybody lies. In some cases they may not know they are telling untruths they could just be mistaken.

There are many places devoted to collecting peoples opinion. Sites like YouGov ask people how they are feeling about their lives, their aspirations and how they feel about the current state of the country. It also conducts market research.

There are several examples of mistaken truths in action. The UK press reported recently a story about Nadine Dorries M.P. and her blog. She had been keeping a diary reassuring constituents about how hard she was working but caused outrage when it was discovered that about 70% of it was untrue. Another ongoing example is that of Wikipedia. It’s content is generated by people, most of the pages are written by the experts in that field, but a lot of them are not. Wikipedia has started requiring citations to back up each statement made. This reduces the number of vague or inaccurate claims but they can still be indexed, searched and referenced.

Every couple of months I get a scaremongering chain email from one of my friends who seems not to be able to tell the difference between a genuine email and a hoax or spam email. They tend to read the subject of “Let stop baby rabbits being used in underwater mining” think this is terrible and send it to everyone they know. Most of them believe that because they “think” they know who sent the message they automatically trust the contents of the email. Some are not so obvious, for example the Marks & Spencer Voucher Giveaway Hoax is one such email I tend to get a lot around Christmas time. It shows that in some cases the original recipient has not even read the email before passing it along. If you read the email it says that someone will give you £100 for passing the email to 8 friends. In fact they are doing the spammer’s job for them.

Spammers are lazy. They just cut and paste the email which makes it really easy to lookup at Google. Copy one sentence from the middle of the email and paste it into Google. You will always come up with a hit because you are highly unlikely to be the first person who is targeted and most of the circulars are reused from a couple of years ago.

You, as an Internet user, must decide for yourself what is true and what is false. Often there is just opinion which is very subjective and dressed up as truth. Often there is someone trying to con you. In fact, it’s just like life.