<commit_before>/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.web.analytics;

import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.Instant;

import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.opengamma.core.change.ChangeEvent;
import com.opengamma.core.change.ChangeType;
import com.opengamma.core.position.Portfolio;
import com.opengamma.core.position.Position;
import com.opengamma.core.position.Trade;
import com.opengamma.core.position.impl.PortfolioMapper;
import com.opengamma.engine.ComputationTargetResolver;
import com.opengamma.engine.view.ViewResultModel;
import com.opengamma.engine.view.compilation.CompiledViewDefinition;
import com.opengamma.engine.view.cycle.ViewCycle;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.web.analytics.blotter.BlotterColumnMapper;

/**
 * Default implementation of {@link AnalyticsView}. This class isn't meant to be thread safe. A thread calling any
 * method that mutates the state must have an exclusive lock. The get methods can safely be called by multiple
 * concurrent threads.
 * @see LockingAnalyticsView
 * @see com.opengamma.web.analytics Package concurrency notes
 */
/* package */ class SimpleAnalyticsView implements AnalyticsView {

  private static final Logger s_logger = LoggerFactory.getLogger(SimpleAnalyticsView.class);

  private final ResultsCache _cache = new ResultsCache();
  private final ComputationTargetResolver _targetResolver;
  private final String _viewId;
  private final ViewportListener _viewportListener;
  private final VersionCorrection _versionCorrection;
  private final Supplier<Portfolio> _portfolioSupplier;
  private final PortfolioEntityExtractor _portfolioEntityExtractor;

  private PortfolioAnalyticsGrid _portfolioGrid;
  private MainAnalyticsGrid _primitivesGrid;
  private CompiledViewDefinition _compiledViewDefinition;

  /**
   * @param viewId ID of the view
   * @param portoflioCallbackId ID that is passed to the listener when the structure of the portfolio grid changes.
   * This class makes no assumptions about its value
   * @param primitivesCallbackId ID that is passed to the listener when the structure of the primitives grid changes.
 * This class makes no assumptions about its value
   * @param targetResolver For looking up calculation targets by specification
   * @param viewportListener Notified when any viewport is created, updated or deleted
   * @param blotterColumnMapper For populating the blotter columns with details for each different security type
   * @param portfolioSupplier Supplies an up to date version of the portfolio
   * @param showBlotterColumns Whether the blotter columns should be shown in the portfolio analytics grid
   */
  /* package */ SimpleAnalyticsView(Portfolio portfolio,
                                    VersionCorrection versionCorrection,
                                    String viewId,
                                    String portoflioCallbackId,
                                    String primitivesCallbackId,
                                    ComputationTargetResolver targetResolver,
                                    ViewportListener viewportListener,
                                    BlotterColumnMapper blotterColumnMapper,
                                    Supplier<Portfolio> portfolioSupplier,
                                    PortfolioEntityExtractor portfolioEntityExtractor,
                                    boolean showBlotterColumns) {
    ArgumentChecker.notEmpty(viewId, "viewId");
    ArgumentChecker.notEmpty(portoflioCallbackId, "portoflioGridId");
    ArgumentChecker.notEmpty(primitivesCallbackId, "primitivesGridId");
    ArgumentChecker.notNull(targetResolver, "targetResolver");
    ArgumentChecker.notNull(viewportListener, "viewportListener");
    ArgumentChecker.notNull(blotterColumnMapper, "blotterColumnMappings");
    ArgumentChecker.notNull(versionCorrection, "versionCorrection");
    ArgumentChecker.notNull(portfolioSupplier, "portfolioSupplier");
    ArgumentChecker.notNull(portfolioEntityExtractor, "portfolioEntityExtractor");
    _versionCorrection = versionCorrection;
    _viewId = viewId;
    _targetResolver = targetResolver;
    _portfolioSupplier = portfolioSupplier;
    _portfolioEntityExtractor = portfolioEntityExtractor;
    List<UniqueIdentifiable> entities;
    if (portfolio != null) {
      entities = PortfolioMapper.flatMap(portfolio.getRootNode(), _portfolioEntityExtractor);
    } else {
      entities = Collections.emptyList();
    }
    _cache.put(entities);
    if (showBlotterColumns) {
      _portfolioGrid = PortfolioAnalyticsGrid.forBlotter(portoflioCallbackId,
                                                         portfolio,
                                                         targetResolver,
                                                         viewportListener,
                                                         blotterColumnMapper);
    } else {
      _portfolioGrid = PortfolioAnalyticsGrid.forAnalytics(portoflioCallbackId,
                                                           portfolio,
                                                           targetResolver,
                                                           viewportListener);
    }
    _primitivesGrid = PrimitivesAnalyticsGrid.empty(primitivesCallbackId);
    _viewportListener = viewportListener;
  }

  @Override
  public List<String> updateColumns(CompiledViewDefinition compiledViewDefinition) {
    _compiledViewDefinition = compiledViewDefinition;
    // TODO this loses all dependency graphs. new grid needs to rebuild graphs from old grid. need stable IDs to do that
    Portfolio portfolio = compiledViewDefinition.getPortfolio();
    _portfolioGrid = _portfolioGrid.withUpdatedColumns(_compiledViewDefinition).withUpdatedRows(portfolio);
    _primitivesGrid = new PrimitivesAnalyticsGrid(_compiledViewDefinition,
                                                  _primitivesGrid.getCallbackId(),
                                                  _targetResolver,
                                                  _viewportListener);
    return getGridIds();
  }

  private List<String> getGridIds() {
    List<String> gridIds = Lists.newArrayList();
    gridIds.add(_portfolioGrid.getCallbackId());
    gridIds.add(_primitivesGrid.getCallbackId());
    gridIds.addAll(_portfolioGrid.getDependencyGraphCallbackIds());
    gridIds.addAll(_primitivesGrid.getDependencyGraphCallbackIds());
    return gridIds;
  }

  @Override
  public List<String> updateResults(ViewResultModel results, ViewCycle viewCycle) {
    _cache.put(results);
    List<String> updatedIds = Lists.newArrayList();
    updatedIds.addAll(_portfolioGrid.updateResults(_cache, viewCycle));
    updatedIds.addAll(_primitivesGrid.updateResults(_cache, viewCycle));
    return updatedIds;
  }

  private MainAnalyticsGrid getGrid(GridType gridType) {<commit_msg>[PLAT-3106] Temporary rollback of change to grid building<commit_after>/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.web.analytics;

import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.Instant;

import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.opengamma.core.change.ChangeEvent;
import com.opengamma.core.change.ChangeType;
import com.opengamma.core.position.Portfolio;
import com.opengamma.core.position.Position;
import com.opengamma.core.position.Trade;
import com.opengamma.core.position.impl.PortfolioMapper;
import com.opengamma.engine.ComputationTargetResolver;
import com.opengamma.engine.view.ViewResultModel;
import com.opengamma.engine.view.compilation.CompiledViewDefinition;
import com.opengamma.engine.view.cycle.ViewCycle;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.web.analytics.blotter.BlotterColumnMapper;

/**
 * Default implementation of {@link AnalyticsView}. This class isn't meant to be thread safe. A thread calling any
 * method that mutates the state must have an exclusive lock. The get methods can safely be called by multiple
 * concurrent threads.
 * @see LockingAnalyticsView
 * @see com.opengamma.web.analytics Package concurrency notes
 */
/* package */ class SimpleAnalyticsView implements AnalyticsView {

  private static final Logger s_logger = LoggerFactory.getLogger(SimpleAnalyticsView.class);

  private final ResultsCache _cache = new ResultsCache();
  private final ComputationTargetResolver _targetResolver;
  private final String _viewId;
  private final ViewportListener _viewportListener;
  private final VersionCorrection _versionCorrection;
  private final Supplier<Portfolio> _portfolioSupplier;
  private final PortfolioEntityExtractor _portfolioEntityExtractor;

  private PortfolioAnalyticsGrid _portfolioGrid;
  private MainAnalyticsGrid _primitivesGrid;
  private CompiledViewDefinition _compiledViewDefinition;

  /**
   * @param viewId ID of the view
   * @param portoflioCallbackId ID that is passed to the listener when the structure of the portfolio grid changes.
   * This class makes no assumptions about its value
   * @param primitivesCallbackId ID that is passed to the listener when the structure of the primitives grid changes.
 * This class makes no assumptions about its value
   * @param targetResolver For looking up calculation targets by specification
   * @param viewportListener Notified when any viewport is created, updated or deleted
   * @param blotterColumnMapper For populating the blotter columns with details for each different security type
   * @param portfolioSupplier Supplies an up to date version of the portfolio
   * @param showBlotterColumns Whether the blotter columns should be shown in the portfolio analytics grid
   */
  /* package */ SimpleAnalyticsView(Portfolio portfolio,
                                    VersionCorrection versionCorrection,
                                    String viewId,
                                    String portoflioCallbackId,
                                    String primitivesCallbackId,
                                    ComputationTargetResolver targetResolver,
                                    ViewportListener viewportListener,
                                    BlotterColumnMapper blotterColumnMapper,
                                    Supplier<Portfolio> portfolioSupplier,
                                    PortfolioEntityExtractor portfolioEntityExtractor,
                                    boolean showBlotterColumns) {
    ArgumentChecker.notEmpty(viewId, "viewId");
    ArgumentChecker.notEmpty(portoflioCallbackId, "portoflioGridId");
    ArgumentChecker.notEmpty(primitivesCallbackId, "primitivesGridId");
    ArgumentChecker.notNull(targetResolver, "targetResolver");
    ArgumentChecker.notNull(viewportListener, "viewportListener");
    ArgumentChecker.notNull(blotterColumnMapper, "blotterColumnMappings");
    ArgumentChecker.notNull(versionCorrection, "versionCorrection");
    ArgumentChecker.notNull(portfolioSupplier, "portfolioSupplier");
    ArgumentChecker.notNull(portfolioEntityExtractor, "portfolioEntityExtractor");
    _versionCorrection = versionCorrection;
    _viewId = viewId;
    _targetResolver = targetResolver;
    _portfolioSupplier = portfolioSupplier;
    _portfolioEntityExtractor = portfolioEntityExtractor;
    List<UniqueIdentifiable> entities;
    if (portfolio != null) {
      entities = PortfolioMapper.flatMap(portfolio.getRootNode(), _portfolioEntityExtractor);
    } else {
      entities = Collections.emptyList();
    }
    _cache.put(entities);
    if (showBlotterColumns) {
      _portfolioGrid = PortfolioAnalyticsGrid.forBlotter(portoflioCallbackId,
                                                         portfolio,
                                                         targetResolver,
                                                         viewportListener,
                                                         blotterColumnMapper);
    } else {
      _portfolioGrid = PortfolioAnalyticsGrid.forAnalytics(portoflioCallbackId,
                                                           portfolio,
                                                           targetResolver,
                                                           viewportListener);
    }
    _primitivesGrid = PrimitivesAnalyticsGrid.empty(primitivesCallbackId);
    _viewportListener = viewportListener;
  }

  @Override
  public List<String> updateColumns(CompiledViewDefinition compiledViewDefinition) {
    _compiledViewDefinition = compiledViewDefinition;
    // TODO this loses all dependency graphs. new grid needs to rebuild graphs from old grid. need stable IDs to do that
    Portfolio portfolio = compiledViewDefinition.getPortfolio();
    _portfolioGrid = _portfolioGrid.withUpdatedColumns(_compiledViewDefinition);
    //_portfolioGrid = _portfolioGrid.withUpdatedColumns(_compiledViewDefinition).withUpdatedRows(portfolio);
    _primitivesGrid = new PrimitivesAnalyticsGrid(_compiledViewDefinition,
                                                  _primitivesGrid.getCallbackId(),
                                                  _targetResolver,
                                                  _viewportListener);
    return getGridIds();
  }

  private List<String> getGridIds() {
    List<String> gridIds = Lists.newArrayList();
    gridIds.add(_portfolioGrid.getCallbackId());
    gridIds.add(_primitivesGrid.getCallbackId());
    gridIds.addAll(_portfolioGrid.getDependencyGraphCallbackIds());
    gridIds.addAll(_primitivesGrid.getDependencyGraphCallbackIds());
    return gridIds;
  }

  @Override
  public List<String> updateResults(ViewResultModel results, ViewCycle viewCycle) {
    _cache.put(results);
    List<String> updatedIds = Lists.newArrayList();
    updatedIds.addAll(_portfolioGrid.updateResults(_cache, viewCycle));
    updatedIds.addAll(_primitivesGrid.updateResults(_cache, viewCycle));
    return updatedIds;
  }

  private MainAnalyticsGrid getGrid(GridType gridType) {
{'fraction_non_alphanumeric': 0.06468235134585396, 'fraction_numerical': 0.0010848193097837142, 'mean_word_length': 2.970390309555855, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 60, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2374309', 'n_tokens_mistral': 3624, 'n_tokens_neox': 3535, 'n_words': 873}