Help needed with BlueprintPageCreateEvent listener
Asked by steve-killelay:

Hi,

I've been puzzling over this for a couple of days now and cannot seem to figure out why this is not working.

I've been using [this tutorial](https://developer.atlassian.com/server/confluence/write-an-advanced-blueprint-plugin/?) to write a custom collection of templates into a single blueprint. Not-with-standing the age of this tutorial and that it's not entirely up-to-date for the latest SDK; I've pretty much got everything I need sorted, so I'm confident the pom and atlassian-plugin.xml are well structured.

My only issue is that I cannot get the listener to fire on the BlueprintPageCreateEvent.

Here's the framework of my listener -

```
package com.itg.plugins.confluence.iso.impl;

import com.atlassian.confluence.plugins.createcontent.api.events.BlueprintPageCreateEvent;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.plugin.ModuleCompleteKey;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.confluence.pages.Page;
import com.atlassian.confluence.pages.PageManager;
import com.atlassian.confluence.spaces.Space;
import com.atlassian.confluence.spaces.SpaceManager;
import com.atlassian.confluence.spaces.SpacesQuery;
import java.util.List;



public class IsoDocumentTemplateListener {
 private static final ModuleCompleteKey MY_BLUEPRINT_KEY = new ModuleCompleteKey("com.itg.plugins.confluence.iso", "iso-documentation");
 private static final Logger log = LoggerFactory.getLogger(IsoDocumentTemplateListener.class);
 private SpaceManager manager;
 private SpacesQuery query;

 
 public IsoDocumentTemplateListener(EventPublisher eventPublisher) {
 eventPublisher.register(this);
 }

 @EventListener
 public void onBlueprintCreateEvent(BlueprintPageCreateEvent event){

 ModuleCompleteKey moduleCompleteKey = event.getBlueprintKey();

 if (MY_BLUEPRINT_KEY.equals(moduleCompleteKey)){
 //Do stuff here!


 
 }
 }
}???
```

I'm using atlas SDK v6.3.7, building to confluence version 6.0.2 and JRE 1.8 (64 bit).

Any help you can provide would be welcome


Answers:
author: Hasnae
body: Hei there

You need to ensure your event listener is treated as a component; there are two ways you can achieve this :

* update your **atlassian-plugin.xml** with a component definition

```
<component 
      name="My event listener" 
      class="my.event.listener.ClassImpl"
      key="myEventListener" application="confluence"
/>
```

* rely on the atlassian spring annotations

```
@Component
public class SampleEventListener implements InitializingBean, DisposableBean {

    private final EventPublisher eventPublisher;

    @Autowired
    public SampleEventListener(@ComponentImport final EventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    @EventListener
    public void onBlueprintCreateEvent(final BlueprintPageCreateEvent event){
        final ContentBlueprint blueprint = event.getBlueprint();
        System.out.println(blueprint);
    }

    @Override
    public void destroy() {
        this.eventPublisher.unregister(this);
    }

    @Override
    public void afterPropertiesSet() {
        this.eventPublisher.register(this);
    }
}
```

Also to reduce side effects on confluence, you need to ensure that your event listener is unregistered when the application needs it to. So the common practice within Confluence teams is to implement the **InitializingBean** and **DisposableBean**interfaces for event listeners.

Doing so will ensure events are captured by your event listener

You can find a sample implementation on this repo <https://bitbucket.org/viqueen/confluence-community/commits/5ba8c641101333ad5af07adfa0fed6ff31ab7f75>

Hopefully this helps you :)

![Screen Shot 2018-03-01 at 17.19.03.png](https://community.atlassian.com/t5/image/serverpage/image-id/16116iAD20176C47CEE70D/image-dimensions/487x381?v=v2 "Screen Shot 2018-03-01 at 17.19.03.png")

comments: author: steve-killelay
body: Hi [Hasnae](https://community.atlassian.com/t5/user/viewprofilepage/user-id/767294),

Thanks for taking the time to reply.

I followed your guidance to the letter and went down the spring annotations route, but I'm still not having any joy with this :(

The onBlueprintCreateEvent just doesn't fire, there's nothing in the debug log to suggest where I need to look to resolve this.

tbh I'm having trouble consolidating the multitude of solutions and answers I've seen on this forum (and the wider net) that span the many different versions of Confluence, hence probably overlooking something obvious to those with a little more experience that myself.

I've uploaded my plugin here <https://github.com/st-even-ak/iso-docs/> would appreciate your (or anyones) feedback.


author: Hasnae
body: Hei [@steve-killelay](/t5/user/viewprofilepage/user-id/1185996)

I looked through your code, and you are actually using the wrong **Component** annotation : **org.osgi.service.component.annotations.Component**

You need to use **org.springframework.stereotype.Component**instead.

In order to be able to resolve the dependency supplying that class, you need to add the following to your plugin pom file

```
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.atlassian.confluence</groupId>
            <artifactId>confluence-plugins-platform-pom</artifactId>
            <version>${confluence.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
```

This is how we manage dependencies across most of Confluence plugins.

And voila , I attached a debugger and have been able to step through the event listener

![Screen Shot 2018-03-04 at 08.24.48.png](https://community.atlassian.com/t5/image/serverpage/image-id/16296i44A9CAB5CBA73D6A/image-size/large?v=v2&px=999 "Screen Shot 2018-03-04 at 08.24.48.png")

I have just opened a pull request with the fix <https://github.com/st-even-ak/iso-docs/pull/1/commits>

Happy coding


author: steve-killelay
body: Thank you so much [Hasnae](https://community.atlassian.com/t5/user/viewprofilepage/user-id/767294), This is working now!


author: Maximilian
body: Hey [@Hasnae](/t5/user/viewprofilepage/user-id/767294) i've got the same problem steve had. The BlueprintPageCreateEvent is not fired. I followed your instructions but it doesn't work.

```
@Component
public class MyEventListener implements InitializingBean, DisposableBean? {

?? ?private static final Logger log = LoggerFactory.getLogger(MyEventListener.class);
?? ?
?? ?private final EventPublisher eventPublisher;
?? ?
?? ?@Autowired
?? ?public MyEventListener(@ComponentImport EventPublisher eventPublisher) {
?? ??? ?this.eventPublisher = eventPublisher;
?? ?}
?? ?
?? ?@EventListener
?? ?public void onBlueprintCreateEvent(BlueprintPageCreateEvent event) {
?? ??? ?final ContentBlueprint blueprint = event.getBlueprint();
?? ??? ?log.warn("WARN: Listener fired");
?? ?}?? ?
?? ? 
?? ?@Override
?? ?public void afterPropertiesSet() throws Exception {
?? ??? ?this.eventPublisher.register(this);
?? ?}
?? ?
?? ?@Override
??? public void destroy() throws Exception {
??????? this.eventPublisher.unregister(this);
??? }
} 
```

**Any other events like PageCreateEvent are fired**

..Any idea what i am doing wrong?


author: steve-killelay
body: Hi [Max](https://community.atlassian.com/t5/user/viewprofilepage/user-id/1194441),

Have you checked which Component you're using for annotations ? I found that eclipse defaulted to **org.osgi.service.component.annotations.Component** but you need **org.springframework.stereotype.Component**

Also on Hasnae advice I added a file called mvnvm.properties to the top level folder with with the maven version in (for me this was "mvn_version=3.5.2")

This repo might help <https://github.com/st-even-ak/iso-docs> it fairly basic but compiles and works


author: Maximilian
body: Hey [@steve-killelay](/t5/user/viewprofilepage/user-id/1185996),

i found the problem.

I am trying to trigger the BlueprintPageCreateEvent for a page created from my space blueprint. The only event triggered is the PageCreateEvent. Unfortunately this event provides no information to let me know that the page was created from my space blueprint..

<https://jira.atlassian.com/browse/CONFSERVER-44186>

Seems like there is no way to check if the page was created from a specific space blueprint :/


author: Maximilian
body: Ok found another event that provides all information i need:

```
import com.atlassian.confluence.plugins.createcontent.api.events.SpaceBlueprintCreateEvent;
```

and the Listener:

```
?@EventListener
?? ?public void onSpaceBlueprintCreateEvent(SpaceBlueprintCreateEvent event) {?? ??? ?
?? ??? ?final String blueprintKey = event.getSpaceBlueprint().getModuleCompleteKey();
?? ??? ?
?? ??? ?if(PLUGIN_KEY.equals(blueprintKey)) {
?? ??? ??? ?log.info("INFO: Space Blueprint created!");? ??? ??? ?
?? ??? ?}
?? ?}
```


author: iamgoingtosneeze
body: Hi - I'm getting really really confused with all of the stuff I am reading in the internet about the simple task of how to add labels to my page when in my space blueprint.

Please can somebody provide a complete event listener for doing this? The reason I am putting it on this thread is i think that i in order to put labels on my pages i have to get it on the space page create event. I think then i can inspect the event to get the page. But how do i get the page's page manager. to add the label to the page?


author: steve-killelay
body: Hi [@iamgoingtosneeze](/t5/user/viewprofilepage/user-id/1387387),

Here's an abridge version of my Listener Class. I've removed the parts superfluous to your query for brevity. Note this is based on a BlueprintPageCreateEvent not a PageCreateEvent so you might need to change the signature to hook into the correct event otherwise the approach should be pretty similar. Hope this helps.

```

@Component
public class TemplateListener implements InitializingBean, DisposableBean {

private static final Logger LOGGER = getLogger(TemplateListener.class);
 public static final ModuleCompleteKey BLUEPRINT_KEY = new ModuleCompleteKey("com.itg.plugins.confluence.document-blueprints:document-blueprint");
 private final EventPublisher eventPublisher;
 private final UserAccessor userAccessor;
 private final LocaleManager localeManager;
 private final ApplicationProperties applicationProperties;
 private final EditorFormatService editorFormatService;
 private final I18NBeanFactory i18NBeanFactory;
 private final AttachmentManager attachmentManager;
 private final PageManager pageManager;
 private final LabelManager labelManager;

private final BlueprintProviderImpl serviceProvider;

@Autowired
 public TemplateListener(@ComponentImport final EventPublisher eventPublisher,
 @ComponentImport final ApplicationProperties applicationProperties,
 @ComponentImport final PageManager pageManager,
 @ComponentImport final UserAccessor userAccessor,
 @ComponentImport final LocaleManager localeManager,
 @ComponentImport final EditorFormatService editorFormatService,
 @ComponentImport final I18NBeanFactory i18NBeanFactory,
 @ComponentImport final AttachmentManager attachmentManager,
 @ComponentImport final LabelManager labelManager
 ) {
 eventPublisher.register(this);
 this.eventPublisher = eventPublisher;
 this.applicationProperties = applicationProperties;
 this.pageManager = pageManager;
 this.userAccessor = userAccessor;
 this.localeManager = localeManager;
 this.editorFormatService = editorFormatService;
 this.i18NBeanFactory = i18NBeanFactory;
 this.attachmentManager = attachmentManager;
 this.labelManager = labelManager;

this.serviceProvider = new BlueprintProviderImpl(this.applicationProperties, this.userAccessor, this.localeManager);
 }


 @EventListener
 public void onBlueprintCreateEvent(BlueprintPageCreateEvent event) {

if (BLUEPRINT_KEY.equals(event.getBlueprintKey())) {

// do something

/**
 * manage the labels on the page
 */
 try {
 /**
 * remove blueprint created labels
 */
 this.labelManager.removeAllLabels(event.getPage());

List<String> labels;
 labels = asList(event.getContext().get("varLabels").toString().trim().split(";"));

labels.stream().filter((label) -> (label.hashCode() > 0)).forEachOrdered((label) -> {
 addLabel(event.getPage(), label);
 });
 } catch (Exception e) {
 LOGGER.warn("some message to log", e);
 }
 }
 }

private void addLabel(ContentEntityObject page, String label) {

this.labelManager.addLabel(page, new Label(label.trim().replace(" ", "-").toLowerCase(), GLOBAL.toString(), serviceProvider.getCurrentUser()));
 }
}
```


author: iamgoingtosneeze
body: Thank you so much for taking the time to supply this. I'm trying it now. Been fiddling around for days ...


author: iamgoingtosneeze
body: I'm getting closer. It seems i need the pagecreate event.

My issue now is this .... i can create programatically but i cannot create manually...

I immediately get an error "This page is taking longer to load than usual. Give it a few moments, then try refreshing. Still having issues? Contact your Confluence admin."

And it spins.

Is there something I have to pass on?

All i have in my event is this:

@EventListener public void pageCreateEvent(PageCreateEvent event) { System.out.println("oh my create ") ; System.out.println(event.getPage().getTitle()) ; System.out.println(event.toString()); System.out.println("END"); }  

Thanks in advance.


author: iamgoingtosneeze
body: don't worry.my sychrony server was down. sorted. Now i just need to find out how to get the space name!


author: steve-killelay
body: Hi [@iamgoingtosneeze](/t5/user/viewprofilepage/user-id/1387387),

was just about to say look at synchrony...

Re the space name, the space key should be set as an entry in the context map --\> event.getContext().get("spacekey") \[i think\], you should be able to use com.atlassian.confluence.spaces.Space to get the properties of that space


author: iamgoingtosneeze
body: I've still fiddling around with this. I think for space blueprints you have to actually use the pagecreateevent. There is a SpaceBlueprintCreateEvent but you don't seem to be able to do getPage from it and it appears not be documented anywhere.

What I cannot find out though is the import. I think that I need this import import com.atlassian.confluence.event.events.content.page.PageCreateEvent;  

but I get this error.

\[ERROR\] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project customerspacebp: Compilation failure\[ERROR\] /C:/confluence_dev/customerspacebp/src/main/java/com/abinitio/confluence/customerspacebp/impl/AbEventListener.java:\[2,53\] cannot find symbol\[ERROR\] symbol: class page  
\[ERROR\] location: package com.atlassian.confluence.event.events.content  
\[ERROR\] -\> \[Help 1\]

I wonder if i need something in my POM but I just cannot find the info out there.

Would anybody be able to help?

Thanks,


Tags: atl-dev

developer