/*
* (non-Javadoc)
* @see org.apache.james.mailbox.store.mail.MessageMapper#save(org.apache.james.mailbox.store.mail.model.Mailbox, org.apache.james.mailbox.store.mail.model.MailboxMembership)
*/
public long add(Mailbox<String> mailbox, Message<String> message) throws MailboxException {
final JCRMessage membership = (JCRMessage) message;
try {
Node messageNode = null;
if (membership.isPersistent()) {
messageNode = getSession().getNodeByIdentifier(membership.getId());
}
if (messageNode == null) {
Date date = message.getInternalDate();
if (date == null) {
date = new Date();
}
// extracte the date from the message to create node structure
// later
Calendar cal = Calendar.getInstance();
cal.setTime(date);
final String year = convertIntToString(cal.get(Calendar.YEAR));
final String month = convertIntToString(cal.get(Calendar.MONTH) + 1);
final String day = convertIntToString(cal.get(Calendar.DAY_OF_MONTH));
final String hour = convertIntToString(cal.get(Calendar.HOUR_OF_DAY));
final String min = convertIntToString(cal.get(Calendar.MINUTE));
Node mailboxNode = getSession().getNodeByIdentifier(mailbox.getMailboxId());
Node node = mailboxNode;
if (scaleType > MESSAGE_SCALE_NONE) {
// we lock the whole mailbox with all its childs while
// adding the folder structure for the date
if (scaleType >= MESSAGE_SCALE_YEAR) {
node = JcrUtils.getOrAddFolder(node, year);
if (scaleType >= MESSAGE_SCALE_MONTH) {
node = JcrUtils.getOrAddFolder(node, month);
if (scaleType >= MESSAGE_SCALE_DAY) {
node = JcrUtils.getOrAddFolder(node, day);
if (scaleType >= MESSAGE_SCALE_HOUR) {
node = JcrUtils.getOrAddFolder(node, hour);
if (scaleType >= MESSAGE_SCALE_MINUTE) {
node = JcrUtils.getOrAddFolder(node, min);
}
}
}
}
}
}
long uid = membership.getUid();
messageNode = mailboxNode.addNode(String.valueOf(uid), "nt:file");
messageNode.addMixin("jamesMailbox:message");
try {
membership.merge(messageNode);
messageNode.setProperty(JCRMessage.UID_PROPERTY, uid);
} catch (IOException e) {
throw new RepositoryException("Unable to merge message in to tree", e);
}
return uid;
} else {
membership.merge(messageNode);
return membership.getUid();
}
} catch (RepositoryException e) {
throw new MailboxException("Unable to save message " + message + " in mailbox " + mailbox, e);
} catch (IOException e) {
throw new MailboxException("Unable to save message " + message + " in mailbox " + mailbox, e);