final PortfolioSearchRequest request = new PortfolioSearchRequest();
request.setName(getPortfolioName(portfolio));
request.setVisibility(visibility); // Any existing match needs to be at least as visible
final PortfolioSearchResult result = _portfolios.search(request);
final ManageablePortfolio manageablePortfolio = createManageablePortfolio(portfolio);
PortfolioDocument document;
if (updateMatchingName) {
document = result.getFirstDocument();
// TODO why did this assume document will never be null? is that valid or have I broken something?
if (document != null) {
final ManageablePortfolio resultPortfolio = document.getPortfolio();
if (nodesEqual(manageablePortfolio.getRootNode(), resultPortfolio.getRootNode())) {
s_logger.debug("Found existing match at {}", document.getUniqueId());
return document.getUniqueId();
}
}
} else {
document = null;
for (PortfolioDocument resultDocument : result.getDocuments()) {
final ManageablePortfolio resultPortfolio = resultDocument.getPortfolio();
if (manageablePortfolio.getName().equals(resultPortfolio.getName()) && nodesEqual(manageablePortfolio.getRootNode(), resultPortfolio.getRootNode())) {
s_logger.debug("Found existing match at {}", resultDocument.getUniqueId());
return resultDocument.getUniqueId();
}
}
}
if (document == null) {
s_logger.debug("Adding to master");
document = new PortfolioDocument(manageablePortfolio);
document.setVisibility(visibility);
document = _portfolios.add(document);
} else {
s_logger.debug("Updating {} within master", document.getUniqueId());
// Retain existing visibility
document.setPortfolio(manageablePortfolio);
document = _portfolios.update(document);
}
s_logger.info("Portfolio '{}' saved as {}", manageablePortfolio.getName(), document.getUniqueId());
return document.getUniqueId();
}