Jira web-resource plugin to drag and drop subtasks

Today I’ve been making a simple plugin for Jira, to allow drag and drop reordering of subtasks. As standard, a list of subtasks comes with links to move the items one position up or down – tedious if you want to move a long way!

Getting up and running with the Atlassian plugin SDK is really straightforward.

The plugin contains only a web-resource with the JavaScript I want to run. I’m not particularly familiar with jQuery, so it may be a little hacky or non-optimal, but it works!

A couple of useful things I learnt:

Jira provides some very specific contexts to determine which pages will include the resource. In my case, the web-resource definition in my atlassian-plugin.xml contains the line:

<context>jira.view.issue</context>

You can see all the web-resource contexts here: Web Resource plugin module contexts.

Because the list of subtasks could contain issues hidden to the current user, I parsed the new position for the sub task from the links which already exist for moving the subtasks up and down, rather than just using the row index.

You can see the source here: https://github.com/anorakgirl/subtask-dragger

Or you can download a jar here: subtask-dragger-0.1.jar. DISCLAIMER: This is just a demo, use at your own risk!

maven release, git and the parent pom

Some strange maven behaviour took up some of my time today.

A lot of our projects have some common settings, so we have a ‘parent pom’ artifact.  I’ve been trying to tidy up our release procedure, and wanted to use the maven release plugin.

I thought I could be clever and define the scm settings in the parent pom like this:

 

 
<scm>
   <developerConnection>scm:git:https://our-repo-url/${repo.name}.git</developerConnection>
</scm>
 

All projects using this parent would then just have to define a “repo.name” property in the pom.

However, it didn’t work! when running maven release, maven was attempting to push to ‘https://our-repo-url/${repo.name}.git/artifactId” i.e. it was appending the artifactId to the scm url. Needless to say, the push failed, and the maven release failed.

After some googling I found that same problem is encountered when trying to release a single module of a multi module project (For example see http://stackoverflow.com/questions/6727450/releasing-a-multi-module-maven-project-with-git)

I guess the maven release plugin is trying to be clever, and perhaps this behaviour makes more sense in an SVN world.

To fix the problem, I defined an “scm.root” variable in the parent pom, and defined the scm connection for individual projects as below:

<scm>
   <developerConnection>${scm.root}/reponame.git</developerConnection>
</scm>

Updating from a list in Grails

This week I had the pleasure of attending both Groovy and Grails courses at Skills Matter in London. The courses were taught by Dierk König, a committer to both Groovy and Grails, and the author of Groovy in Action. He’s very knowledgeable and the courses were really interesting – I would have liked more time for advanced grails topics, but I guess you can’t fit it all in to two days!

During the course I asked for help with one of my pet grails problems – the best way to update multiple records at once from a list view. For example, you might have a set of records with a check box field, and want to tick/un-tick for several rows and then save all with a single click. We didn’t quite get it working in class, but I got some helpful advice which meant I was able to finish it off on the train home.

The domain class is nothing special:

class Person {
 String firstName
 String lastName
 boolean available
}

My PersonController looks like this (I’ve left the scaffolding in, so you get all the standard pages too):

class PersonController {
   static scaffold = true
   def multiEdit = {
      List<Person> list = Person.list()
      [personInstanceList: list]
   }

    def multiSave = { MultiplePersonCommand command ->
     command.people.each { p ->
     Person person = Person.get(p.id)
     person.properties = p.properties
     person.save()
   }
   redirect action: list
 }
}
class SinglePersonCommand {
 Integer id
 boolean available
}
class MultiplePersonCommand {
 List<SinglePersonCommand> people = [].withDefault({ new SinglePersonCommand() } )
}

The important thing here is the use of Command objects. I’ve defined these in the same class as the Controller but they could be in a separate file. The really important tip is the use of `withDefault` on the list in the MultiplePersonCommand. When the binding takes place, we can’t guarantee what order it will be in. For example it might try to bind the second list item before the first. This would cause an error without the `withDefault` method.

And finally, multiEdit.gsp looks like this:

<g:form action="multiSave">
 <g:each var="person" in="${personInstanceList}" status="i">
     <div id="person${i}">
     <g:hiddenField name='people[${i}].id' value='$person.id'/>
     <g:fieldValue bean="${person}" field="firstName"/>
     <g:checkBox name='people[${i}].available' value='1' checked="${person.available}"/>
   </div>
 </g:each>
 </div>
<g:submitButton name="action" />
</g:form>

The important thing here is the use of the $i variable in square brackets on the fields in question. This means that the params that come back to the Controller will effectively contain people[0].id, people[0].available, people[1].id, people[1].available and so on. Grails is clever enough to bind all the people[0] values to the first SinglePersonCommand in the people list inside the MultiplePersonCommand, and so on. Then I can access this list and copy across the values to People objects and save them.

I hope this is useful to someone. I’m looking forward to spending some time on Groovy and Grails development, so hopefully more here soon!

 

maven, junit, cobertura and BeanCreationException

I have a set of junit tests for my project. When I run them with mvn test they run fine and pass.

However, when I ran them with mvn cobertura:cobertura, they failed with the following error:

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'com.anorakgirl.MyTest': Autowiring of fields failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.anorakgirl.MyService com.anorakgirl.MyTest.myService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.anorakgirl.MyService] is defined:
Unsatisfied dependency of type [class com.anorakgirl.MyService]:
expected at least 1 matching bean

After some googling, this is the problem. The ServiceObject was annotated with @Autowire. Spring autowires by type. I have only one class of type ‘com.anorakgirl.MyService’. So when run with junit this works fine. However, cobertura changes the type of the MyService class during Instrumentation, so Spring no longer recognises it as type MyService, and so cannot Autowire.

There are two possible answers:

The easy answer (what I did)

In your test application context add the line:

<aop:config proxy-target-class="true"/>

The other answer (what I read about)

Make sure the classes that you want to autowire all implement interfaces. Then autowire the interface rather than the implementation. The Cobertura class will still implement the same interface and therefore can still be autowired.

I didn’t try this as the service classes do not have interfaces and I haven’t time to add them!

Developing a Plone Product Part 2

Next I want to add a Portlet which will display any items of the new content type which are in the current folder.

Creating a Plone Portlet

First step seems easy:

cd src/anorakgirl.mycontent
paster addcontent portlet

and then answer the easy questions. This creates a some files in the portlets folder of the product. However, when I restart Plone, I get this error:

ZopeXMLConfigurationError: File 
"c:\plone\src\anorakgirl.mycontent\anorakgirl\mycontent\portlets\configure.zcml", line 12.2-21.8]
ImportError: cannot import name QuotesPortletMessageFactory

I fixed this by commenting out the line below from portlets/mycontentportlet.py – who knows if this matters!

#from anorakgirl.mycontent.portlets import MyContentPortletMessageFactory as _

Plone now restarts, and I can add the MyContentPortlet via ‘Manage Portlets’. However, it doesn’t do anything yet.

To make it show the first ‘MyContent’ item from the current folder, I modified portlets/mycontentportlet.py as follows. Please note that this code is shamelessly copied from Professional Plone Development by Martin Aspeli.

from zope import schema
from zope.component import getMultiAdapter
from zope.formlib import form
from zope.interface import implements
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Acquisition import aq_inner
from Products.CMFCore.interfaces import ICatalogTool
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName

from anorakgirl.mycontent.interfaces import IMyContent

#from anorakgirl.mycontent.portlets import MyContentPortletMessageFactory as _

class IMyContentPortlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

class Assignment(base.Assignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(IMyContentPortlet)

    def __init__(self):
        pass

    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return "MyContent Portlet"

class Renderer(base.Renderer):
	"""Portlet renderer.

	This is registered in configure.zcml. The referenced page template is
	rendered, and the implicit variable 'view' will refer to an instance
	of this class. Other methods can be added and referenced in the template.
	"""

	render = ViewPageTemplateFile('mycontentportlet.pt')

	@property
	def available(self):
		return len(self._data()) > 0

	def mycontent_list(self):
		for brain in self._data():
			mycontent = brain.getObject()

			yield dict(title=mycontent.title,
				description=mycontent.description,
				author=mycontent.author,
				details=mycontent.details)

	@memoize
	def _data(self):
		context = aq_inner(self.context)
		limit = 1
		query = dict(object_provides = IMyContent.__identifier__)
		if self.context.isPrincipiaFolderish:
			query['path'] = '/'.join(context.getPhysicalPath())

		if not self.context.isPrincipiaFolderish:
			parent = context.aq_parent
			query['path'] = '/'.join(parent.getPhysicalPath())
		catalog = getToolByName(context, 'portal_catalog')
		results = catalog(query)
		mycontents = []

		mycontents = results[:limit]
		return mycontents

# NOTE: If this portlet does not have any configurable parameters, you can
# inherit from NullAddForm and remove the form_fields variable.

class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(IMyContentPortlet)

    def create(self, data):
        return Assignment(**data)

# NOTE: IF this portlet does not have any configurable parameters, you can
# remove this class definition and delete the editview attribute from the
# <plone:portlet /> registration in configure.zcml

class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(IMyContentPortlet)

Really all that I changed from the paster generated content was the imports and the Render method.

I also amended the template file mycontentportlet.pt to show the data returned by the Render method:

<dl class="portlet portletMyContentPortlet"
    i18n:domain="anorakgirl.mycontent.portlets">
    <dd class="portletItem odd">

        <div tal:define="items view/mycontent_list">
             <ul>
                 <li tal:repeat="item items">
                 <span tal:content="item/details"/>
                 <br/><b tal:content="item/author"></b></li>
             </ul>
            </div>
    </dd>
</dl>

Because paster amended the xml files in the profiles folder ( to register the new portlet) not only do you need to restart Plone, you need to reinstall the product to get the Portlet to show up. I’m doing this using the Setup > Add-on products page, but this may not be the best way?

You should now be able to add the Portlet using Manage Portlets. If you add it at the root, and the rest of the site is set to inherit parent portlets, then the portlet should show up in any folder in which you add a ‘MyContent’ item.

    Developing a Plone product part 1

    I have to say, I am used to being able to pick up a new tool or environment and start digging behind the scenes without becoming too bewildered, but Plone has not been like that at all. I am very impressed at the front end, but there’s always something extra required. Python is new to me, and I am struggling with the terminology and so on.

    So, I am going to record my progress in creating a Plone product. I am currently using Plone 3.2.2, developing on Windows but will be deploying on Linux.

    Useful things I learned so far

    #Run plone in the foreground, so that you can see the output and restart easily

    C:\Plone>bin\plonectl.exe fg

    #If you change a .py or .zcml file, you need to restart Plone to see your changes

    #Changes to .pt files should show up immediately in foreground mode

    #Changes to .xml files mean the product must be uninstalled and reinstalled  (I think via the front end Setup > Add-on products page is fine)

    My planned product

    I want the site users (Editors/Contributers) to be able to add content into the right hand column, without giving them Manager rights. My plan is this:

    1. Create a new content type for this content.  This will simply have a few custom fields, and should not appear in navigation by default (this tutorial).

    2. Create a portlet which displays any items of the new content type in the current folder. The portlet will be added at root level and carry through the site, so users simply add the new right hand content where they want it. If the users want specific right hand content for a single page, they would put the page in its own folder. (see next tutorial)

    Getting Started

    I am using paster to create the skeleton of my product. This creates a directory structure with all the required files. It is easiest if paster is in your path.  So, in the src directory:

    paster create -t archetype anorakgirl.mycontent

    And answer the questions that follow:

    Enter title (The title of the project) ['Plone Example']: Anorakgirl MyContent Project
    Enter namespace_package (Namespace package (like plone)) ['plone']: anorakgirl
    Enter package (The package contained namespace package (like example)) ['example']: mycontent
    ...

    Use paster to add the actual contentype

    cd anorakgirl.mycontent
    paster addcontent contenttype

    Then use paster again to add some fields to the content type.

    paster addcontent atschema

    Again answer the questions. The module name in this case will be mycontent. Repeat the above to add whatever fields you need. Note that you get Title and Description for free, so don’t add those.

    You’ve now done enough to see the product in action. So

    Adding the product to the build environment

    Add the following lines to buildout.cfg

    [buildout]
    ...
    develop =
       src/anorakgirl.mycontent
    [instance]
    ...
    eggs =  
       ...
       anorakgirl.mycontent
    zcml =
       ...
       anorakgirl.mycontent

    Run buildout.

    Start plone (in foreground mode).

    Login as an Administrator. Go to Site Setup > Add-on Products. The product should be listed under products to install. Install it.

    Your new content type should appear on the Add New menu. The edit form should have all the fields you added. The standard view won’t be very pretty but that’s a job for another tutorial…

    Next Time: creating a Plone portlet to display the new Content Type…

    Compiling mnogosearch with MySQL support & PHP extension on 64bit Centos5

    We just got a new dedicated server, running Centos 5.  I’ve just been moving some php websites which use the mnogosearch extension, and finally cracked it.

    The main problem I was getting was:

    /usr/bin/ld: cannot find -lmysqlclient

    Here is a rough outline of what I had to do:

    Install Mysql development

    1. yum install mysql-devel

    Download & build mnogosearch

    1. wget http://www.mnogosearch.org/Download/mnogosearch-3.3.8.tar.gz
    2. edit “configure” script so that MYSQL_LIBDIR=/usr/lib64/mysql
    3. install.pl choosing appropriate options (I chose yes for build shared libraries)
    4. make
    5. make install

    Build PHP extension

    1. cd mnogosearch-3.3.8/php
    2. follow instructions in  README file here
    3. service httpd restart

    (I tried to get it working with PostgreSQL support too, but kept getting “/usr/bin/ld: cannot find -lpq”. The fix for setting the library path in the configure file didn’t seem to work in this case, but I didn’t try too hard.)

    Tomcat Error listenerStart

    I’m sure I’m not the only one who has battled with this startup error:

    4985 [main] ERROR org.apache.catalina.core.StandardContext  – Error listenerStart
    4985 [main] ERROR org.apache.catalina.core.StandardContext  – Context [/mycontext] startup failed due to previous errors

    The problem is getting the real cause of the problem to appear in the log. I’ve had this problem various times in the past (must be repeating the same mistakes). Today’s answer was simple:

    1. Remove log4j.jar from myapp/WEB-INF/lib (it is already in Tomcat/common/lib)
    2. Restart app.
    3. Debug using the reams of useful error messages which suddenly appear in the output.

    Dynarch DHTML Calendar IE7 positioning problem

    My husband wants me to post this, in case it helps anyone to find the patch…

    We’ve both used the Dynarch DHTML Calendar in projects over the years. And had been quietly ignoring the fact it has problems in Internet Explorer 7. The calendar displays in the wrong position when you are in Standards Compliance Mode (using a proper doctype).

    Well… there’s a patch, here:
    http://sourceforge.net/tracker/index.php?func=detail&aid=1679433&group_id=75569&atid=544287

    So there you go.

    Spring Security: Method Level Security with JSF so far…

    My personal Gotcha’s in case they are of use to anyone else:

    1. Ensure you have compatible versions of Spring and Spring Security. I am using Sping Security 2.0.4 and Spring 2.5.6. Originally my Spring was a slightly older version (2.5) and I got the following error:

    java.lang.NoSuchMethodError:
    org.springframework.aop.config.AopNamespaceUtils.registerAutoProxyCreatorIfNecessary

    I fixed this by upgrading to the latest Spring. I think the problem was resolved in Spring 2.5.2 and relates to this bug: http://jira.springframework.org/browse/SPR-4459

    2. Make sure the methods you are securing are actually in Spring Managed beans, doh! My @Secured annoration was being ignored entirely, and it took me ages to realise why – some of my beans are still in faces config files, so Spring has no way of knowing about them. Moving the beans into the Spring configuration fixed the problem straight away.