@Override
  public PortfolioSearchResult search(PortfolioSearchRequest request) {
    ArgumentChecker.notNull(request, "request");
    Collection<PortfolioDocument> docsToCheck = null;

    if ((request.getName() != null) && !RegexUtils.containsWildcard(request.getName())) {
      docsToCheck = _portfoliosByName.get(request.getName());
    } else {
      docsToCheck = _store.values();
    }
    if (docsToCheck == null) {
      docsToCheck = Collections.emptySet();
    }

    final List<PortfolioDocument> list = new ArrayList<PortfolioDocument>();
    for (PortfolioDocument doc : docsToCheck) {
      if (request.matches(doc)) {
        PortfolioDocument docToAdd = isCloneResults() ? clonePortfolioDocument(doc) : doc;
        list.add(docToAdd);
      }
    }
    final PortfolioSearchResult result = new PortfolioSearchResult();
    result.setPaging(Paging.of(request.getPagingRequest(), list));
    result.getDocuments().addAll(request.getPagingRequest().select(list));
    return result;
  }
  /**
   * Stores the portfolio.
   *
   * @param portfolio the portfolio, not null
   */
  private void storePortfolio(final ManageablePortfolio portfolio) {
    final PortfolioMaster portfolioMaster = getToolContext().getPortfolioMaster();

    final PortfolioSearchRequest req = new PortfolioSearchRequest();
    req.setName(portfolio.getName());
    final PortfolioSearchResult result = portfolioMaster.search(req);
    switch (result.getDocuments().size()) {
      case 0:
        s_logger.info("Creating new portfolio");
        portfolioMaster.add(new PortfolioDocument(portfolio));
        break;
      case 1:
        final UniqueId previousId = result.getDocuments().get(0).getUniqueId();
        s_logger.info("Updating portfolio {}", previousId);
        portfolio.setUniqueId(previousId);
        final PortfolioDocument document = new PortfolioDocument(portfolio);
        document.setUniqueId(previousId);
        portfolioMaster.update(document);
        break;
      default:
        throw new OpenGammaRuntimeException("Multiple portfolios matching " + req);
    }
  }