Hi.
I’m currently writing a Confluence plugin which provides an API for receiving files and attaching these files to a page. The plugin runs with administrator privileges and so the default user/creator in that case for generated pages or attachments is always ‘anonymous’. I’m able to manually change the user of a plugin generated page via ConfluenceEntityObject::setCreator ()
, but I cannot change the user of an attachment uploaded via the same plugin. There does not seem to be an API call for that.
Principle:
ConfluenceUser user = ...
// Creating the page. Setting the user is possible here
Page page = templatePage.copyLatestVersion ();
page.setCreator (user);
// Attaching data to the page. There does not seem a way to set a user for the generated attachment.
AttachmentResource attachment = new InputStreamAttachmentResource (new ByteArrayInputStream (data), name, format, data.length, comment);
fileUploadManager.storeResource (attachment, page);
Is there a way to set the user for the attachment here, too ?
Thank you in advance !
Hi @FrankBlankenburg ,
As you mention, Confluence sets the attachment creator to the current user upon saving with attachment.setCreator(AuthenticatedUserThreadLocal.get());
.
It is possible to override the Attachment creator, although this is not recommended and is using deprecated API. We can update most fields through AttachmentService
but not the creator
, hence we have to use AttachmentManager
and the DAO
directly.
Confluence provides the AttachmentManager
API to retrieve the Attachment
object which is a ConfluenceEntityObject
.
So you should be able to do something like:
Attachment attachment = attachmentManager.getAttachment(...)
attachment.setCreator(...)
attachmentDao.updateAttachment(attachment)
I haven’t tested the above pseudocode, but let me know how it goes, if it doesn’t work for you I’ll look into it further.
Regards,
Alex
2 Likes
Hi Alex,
yes, this solves the problem ! With one small addendum: The ‘updateAttachment ()’ call must be executed in an explicit transaction, otherwise a spring exception is thrown. The complete code which works fine is:
/*
* Set creator (user) the given attachment belongs to
*
* The default user associated with an attachment is 'anonymous', because the plugin runs in
* an admin context.
*/
void setAttachmentCreator (Page page, String attachment_name, ConfluenceUser user) throws Exception
{
Attachment attachment = attachmentManager.getAttachment (page, attachment_name);
if (attachment == null)
throw new ConnectException (Response.Status.BAD_REQUEST, "Attachment '" + attachment_name + "' cannot be found.");
attachment.setCreator (user);
Object res = transactionTemplate.execute (new TransactionCallback () {
@Override
public Object doInTransaction () {
attachmentManager.getAttachmentDao ().updateAttachment (attachment);
return null;
}
});
}
Thank you very much,
Frank
EDIT: Code indentation corrected