Ejemplo n.º 1
0
 @Test
 public void testGetSecurityByBundleVersionCorrection() {
   final FudgeMsgEnvelope fme =
       getSecuritySourceResource()
           .getSecurity(
               Arrays.asList("d1~v1"), Instant.now().toString(), Instant.now().toString());
   checkSecurityMessage(fme);
 }
 @Override
 public synchronized void remove(ObjectIdentifiable objectIdentifiable) {
   ArgumentChecker.notNull(objectIdentifiable, "objectIdentifiable");
   if (!getUniqueIdScheme().equals(objectIdentifiable.getObjectId().getScheme())) {
     throw new DataNotFoundException(
         "Scheme '"
             + objectIdentifiable.getObjectId().getScheme()
             + "' not valid for '"
             + getUniqueIdScheme()
             + "'");
   }
   final int i = objectIdentifiable.getObjectId().getValue().indexOf('_');
   if (i <= 0) {
     throw new DataNotFoundException(
         "Identifier '"
             + objectIdentifiable.getObjectId().getValue()
             + "' not valid for '"
             + getUniqueIdScheme()
             + "'");
   }
   final String name = objectIdentifiable.getObjectId().getValue().substring(0, i);
   final String iso = objectIdentifiable.getObjectId().getValue().substring(i + 1);
   final Currency currency;
   try {
     currency = Currency.of(iso);
   } catch (IllegalArgumentException e) {
     throw new DataNotFoundException(
         "Identifier '"
             + objectIdentifiable.getObjectId().getValue()
             + "' not valid for '"
             + getUniqueIdScheme()
             + "'",
         e);
   }
   final Pair<Currency, String> key = Pair.of(currency, name);
   if (_sourceVersionCorrection.getVersionAsOf() != null) {
     final TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key);
     if (value == null) {
       throw new DataNotFoundException("Curve definition not found");
     }
     // Don't need to keep the old values before the one needed by "versionAsOfInstant"
     final Instant oldestNeeded = value.floorKey(_sourceVersionCorrection.getVersionAsOf());
     if (oldestNeeded != null) {
       value.headMap(oldestNeeded).clear();
     }
     // Store a null to indicate the delete
     value.put(Instant.now(), null);
   } else {
     if (_definitions.remove(key) == null) {
       throw new DataNotFoundException("Curve definition not found");
     }
   }
   changeManager()
       .entityChanged(
           ChangeType.REMOVED, objectIdentifiable.getObjectId(), null, null, Instant.now());
 }
 @Override
 public synchronized YieldCurveDefinitionDocument update(YieldCurveDefinitionDocument document) {
   ArgumentChecker.notNull(document, "document");
   ArgumentChecker.notNull(document.getYieldCurveDefinition(), "document.yieldCurveDefinition");
   final Currency currency = document.getYieldCurveDefinition().getCurrency();
   final String name = document.getYieldCurveDefinition().getName();
   final UniqueId uid = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode());
   if (!uid.equals(document.getUniqueId())) {
     throw new IllegalArgumentException("Invalid unique identifier");
   }
   final Pair<Currency, String> key = Pair.of(currency, name);
   final TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key);
   if (value == null) {
     throw new DataNotFoundException("UID '" + uid + "' not found");
   }
   if (_sourceVersionCorrection.getVersionAsOf() != null) {
     // Don't need to keep the old values before the one needed by "versionAsOfInstant"
     final Instant oldestNeeded = value.floorKey(_sourceVersionCorrection.getVersionAsOf());
     value.headMap(oldestNeeded).clear();
   } else {
     // Don't need any old values
     value.clear();
   }
   Instant now = Instant.now();
   value.put(now, document.getYieldCurveDefinition());
   document.setUniqueId(uid);
   changeManager().entityChanged(ChangeType.CHANGED, uid.getObjectId(), null, null, now);
   return document;
 }
 // -------------------------------------------------------------------------
 @Override
 public synchronized YieldCurveDefinitionDocument add(YieldCurveDefinitionDocument document) {
   ArgumentChecker.notNull(document, "document");
   ArgumentChecker.notNull(document.getYieldCurveDefinition(), "document.yieldCurveDefinition");
   final Currency currency = document.getYieldCurveDefinition().getCurrency();
   final String name = document.getYieldCurveDefinition().getName();
   final Pair<Currency, String> key = Pair.of(currency, name);
   if (_definitions.containsKey(key)) {
     throw new IllegalArgumentException("Duplicate definition");
   }
   final TreeMap<Instant, YieldCurveDefinition> value =
       new TreeMap<Instant, YieldCurveDefinition>();
   Instant now = Instant.now();
   value.put(now, document.getYieldCurveDefinition());
   _definitions.put(key, value);
   final UniqueId uid = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode());
   document.setUniqueId(uid);
   changeManager()
       .entityChanged(
           ChangeType.ADDED,
           document.getObjectId(),
           document.getVersionFromInstant(),
           document.getVersionToInstant(),
           now);
   return document;
 }
  @Test
  public void testCycleSimpleGraph() {
    ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
    env.init();
    CompiledViewDefinitionWithGraphsImpl compiledViewDefinition =
        env.compileViewDefinition(Instant.now(), VersionCorrection.LATEST);
    DependencyGraph graph =
        compiledViewDefinition.getDependencyGraph(
            ViewProcessorTestEnvironment.TEST_CALC_CONFIG_NAME);
    DependencyGraph cycledGraph = cycleObject(DependencyGraph.class, graph);

    assertEquals(
        graph.getCalculationConfigurationName(), cycledGraph.getCalculationConfigurationName());
    assertEquals(graph.getAllComputationTargets(), cycledGraph.getAllComputationTargets());
    assertEquals(graph.getOutputSpecifications(), cycledGraph.getOutputSpecifications());
    assertEquals(graph.getSize(), cycledGraph.getSize());
    assertEquals(
        graph.getTerminalOutputSpecifications(), cycledGraph.getTerminalOutputSpecifications());

    for (DependencyNode node : graph.getDependencyNodes()) {
      boolean isRoot = graph.getRootNodes().contains(node);
      for (ValueSpecification spec : node.getOutputValues()) {
        DependencyNode equivalentNode = cycledGraph.getNodeProducing(spec);
        assertEquals(isRoot, cycledGraph.getRootNodes().contains(equivalentNode));
        assertEquals(node.getInputValues(), equivalentNode.getInputValues());
        assertEquals(node.getOutputValues(), equivalentNode.getOutputValues());
        assertEquals(node.getTerminalOutputValues(), equivalentNode.getTerminalOutputValues());
      }
    }
  }
 private VersionCorrection getResolvedVersionCorrection() {
   VersionCorrection versionCorrection = getExecutionOptions().getVersionCorrection();
   if (!versionCorrection.containsLatest()) {
     return versionCorrection;
   }
   return versionCorrection.withLatestFixed(Instant.now());
 }
Ejemplo n.º 7
0
  private static class SynchronousInMemoryLKVSnapshot extends AbstractMarketDataSnapshot {

    private final Map<ValueRequirement, Object> _snapshot;
    private final Instant _snapshotTime = Instant.now();

    public SynchronousInMemoryLKVSnapshot(Map<ValueRequirement, Object> snapshot) {
      _snapshot = snapshot;
    }

    @Override
    public UniqueId getUniqueId() {
      return UniqueId.of(
          MARKET_DATA_SNAPSHOT_ID_SCHEME, "SynchronousInMemoryLKVSnapshot:" + getSnapshotTime());
    }

    @Override
    public Instant getSnapshotTimeIndication() {
      return _snapshotTime;
    }

    @Override
    public Instant getSnapshotTime() {
      return _snapshotTime;
    }

    @Override
    public Object query(ValueRequirement requirement) {
      return _snapshot.get(requirement);
    }
  }
  @Override
  public List<UniqueId> replaceAllVersions(
      ObjectIdentifiable objectIdentifiable,
      List<YieldCurveDefinitionDocument> replacementDocuments) {
    ArgumentChecker.notNull(replacementDocuments, "replacementDocuments");
    ArgumentChecker.notNull(objectIdentifiable, "objectIdentifiable");

    final Instant now = Instant.now();

    for (YieldCurveDefinitionDocument replacementDocument : replacementDocuments) {
      ArgumentChecker.notNull(replacementDocument, "document");
      ArgumentChecker.notNull(
          replacementDocument.getYieldCurveDefinition(), "document.yieldCurveDefinition");
      final Currency currency = replacementDocument.getYieldCurveDefinition().getCurrency();
      final String name = replacementDocument.getYieldCurveDefinition().getName();
      final UniqueId id = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode());
      ArgumentChecker.isTrue(id.equals(objectIdentifiable), "Invalid object identifier");
    }

    YieldCurveDefinitionDocument storedDocument = get(objectIdentifiable, null);
    if (storedDocument == null) {
      throw new DataNotFoundException("Document not found: " + objectIdentifiable);
    }
    final Currency currency = storedDocument.getYieldCurveDefinition().getCurrency();
    final String name = storedDocument.getYieldCurveDefinition().getName();
    Pair<Currency, String> key = Pair.of(currency, name);

    final TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key);
    if (value == null) {
      throw new DataNotFoundException("OID '" + objectIdentifiable + "' not found");
    }
    value.clear();

    List<YieldCurveDefinitionDocument> orderedReplacementDocuments =
        MasterUtils.adjustVersionInstants(now, null, null, replacementDocuments);

    final Instant lowestVersionFrom = orderedReplacementDocuments.get(0).getVersionFromInstant();

    ArgumentChecker.notNull(
        lowestVersionFrom, "You must define version from of the first document");

    for (YieldCurveDefinitionDocument replacementDocument : orderedReplacementDocuments) {
      value.put(
          replacementDocument.getVersionFromInstant(),
          replacementDocument.getYieldCurveDefinition());
      changeManager()
          .entityChanged(ChangeType.CHANGED, replacementDocument.getObjectId(), null, null, now);
    }
    return MasterUtils.mapToUniqueIDs(orderedReplacementDocuments);
  }
Ejemplo n.º 9
0
 private void shutdownStaleViewClients() {
   Instant timeoutBefore = Instant.now().minus(VIEW_CLIENT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
   Iterator<DataViewClientResource> clientIterator = _createdViewClients.values().iterator();
   while (clientIterator.hasNext()) {
     DataViewClientResource clientResource = clientIterator.next();
     if (clientResource.getViewClient().getState() == ViewClientState.TERMINATED) {
       clientIterator.remove();
       continue;
     }
     if (clientResource.getLastAccessed().isBefore(timeoutBefore)) {
       clientIterator.remove();
       clientResource
           .shutdown(); // PLAT-1213: must shutdown the rest interface in order to stop the
                        // publishing
     }
   }
 }
 @Override
 public synchronized YieldCurveDefinitionDocument addOrUpdate(
     YieldCurveDefinitionDocument document) {
   ArgumentChecker.notNull(document, "document");
   ArgumentChecker.notNull(document.getYieldCurveDefinition(), "document.yieldCurveDefinition");
   final Currency currency = document.getYieldCurveDefinition().getCurrency();
   final String name = document.getYieldCurveDefinition().getName();
   final Pair<Currency, String> key = Pair.of(currency, name);
   TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key);
   final UniqueId uid = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode());
   Instant now = Instant.now();
   if (value != null) {
     if (_sourceVersionCorrection.getVersionAsOf() != null) {
       // Don't need to keep the old values before the one needed by "versionAsOfInstant"
       final Instant oldestNeeded = value.floorKey(_sourceVersionCorrection.getVersionAsOf());
       if (oldestNeeded != null) {
         value.headMap(oldestNeeded).clear();
       }
     } else {
       // Don't need any old values
       value.clear();
     }
     value.put(now, document.getYieldCurveDefinition());
     changeManager().entityChanged(ChangeType.CHANGED, uid.getObjectId(), null, null, now);
   } else {
     value = new TreeMap<Instant, YieldCurveDefinition>();
     value.put(now, document.getYieldCurveDefinition());
     _definitions.put(key, value);
     changeManager()
         .entityChanged(
             ChangeType.ADDED,
             uid.getObjectId(),
             document.getVersionFromInstant(),
             document.getVersionToInstant(),
             now);
   }
   document.setUniqueId(uid);
   return document;
 }
Ejemplo n.º 11
0
  @Test
  public void test_update_nameChangeNullValue() {
    Instant now = Instant.now(_cfgMaster.getTimeSource());

    UniqueId uniqueId = UniqueId.of("DbCfg", "101", "0");
    ConfigDocument<ExternalId> base = _cfgMaster.get(uniqueId, ExternalId.class);
    ConfigDocument<ExternalId> input = new ConfigDocument<ExternalId>(ExternalId.class);
    input.setUniqueId(uniqueId);
    input.setName("NewName");
    input.setValue(null); // name change only

    ConfigDocument<ExternalId> updated = _cfgMaster.update(input);
    assertEquals(false, base.getUniqueId().equals(updated.getUniqueId()));
    assertEquals("NewName", updated.getName()); // name changed
    assertEquals(base.getValue(), updated.getValue()); // value unchanged

    ConfigDocument<ExternalId> old = _cfgMaster.get(uniqueId, ExternalId.class);
    assertEquals(base.getUniqueId(), old.getUniqueId());
    assertEquals(now, old.getVersionToInstant()); // old version ended
    assertEquals(base.getName(), old.getName());
    assertEquals(base.getValue(), old.getValue());
  }
  @Test
  public void test_remove_removed() {
    Instant now = Instant.now(_secMaster.getTimeSource());

    UniqueId uniqueId = UniqueId.of("DbSec", "101", "0");
    _secMaster.remove(uniqueId);
    SecurityDocument test = _secMaster.get(uniqueId);

    assertEquals(uniqueId, test.getUniqueId());
    assertEquals(_version1Instant, test.getVersionFromInstant());
    assertEquals(now, test.getVersionToInstant());
    assertEquals(_version1Instant, test.getCorrectionFromInstant());
    assertEquals(null, test.getCorrectionToInstant());
    ManageableSecurity security = test.getSecurity();
    assertNotNull(security);
    assertEquals(uniqueId, security.getUniqueId());
    assertEquals("TestSecurity101", security.getName());
    assertEquals("EQUITY", security.getSecurityType());
    assertEquals(
        ExternalIdBundle.of(
            ExternalId.of("A", "B"), ExternalId.of("C", "D"), ExternalId.of("E", "F")),
        security.getIdentifiers());
  }
Ejemplo n.º 13
0
  @Test
  public void test_update_getUpdateGet() {
    Instant now = Instant.now(_cfgMaster.getTimeSource());

    UniqueId uniqueId = UniqueId.of("DbCfg", "101", "0");
    ConfigDocument<ExternalId> base = _cfgMaster.get(uniqueId, ExternalId.class);
    ConfigDocument<ExternalId> input = new ConfigDocument<ExternalId>(ExternalId.class);
    input.setUniqueId(uniqueId);
    input.setName("NewName");
    input.setValue(ExternalId.of("A", "B"));

    ConfigDocument<ExternalId> updated = _cfgMaster.update(input);
    assertEquals(false, base.getUniqueId().equals(updated.getUniqueId()));
    assertEquals(now, updated.getVersionFromInstant());
    assertEquals(null, updated.getVersionToInstant());
    assertEquals(now, updated.getCorrectionFromInstant());
    assertEquals(null, updated.getCorrectionToInstant());
    assertEquals("NewName", updated.getName());
    assertEquals(ExternalId.of("A", "B"), updated.getValue());

    ConfigDocument<ExternalId> old = _cfgMaster.get(uniqueId, ExternalId.class);
    assertEquals(base.getUniqueId(), old.getUniqueId());
    assertEquals(base.getVersionFromInstant(), old.getVersionFromInstant());
    assertEquals(now, old.getVersionToInstant()); // old version ended
    assertEquals(base.getCorrectionFromInstant(), old.getCorrectionFromInstant());
    assertEquals(base.getCorrectionToInstant(), old.getCorrectionToInstant());
    assertEquals(base.getName(), old.getName());
    assertEquals(base.getValue(), old.getValue());

    ConfigHistoryRequest<ExternalId> search =
        new ConfigHistoryRequest<ExternalId>(base.getUniqueId(), null, now);
    search.setType(ExternalId.class);

    ConfigHistoryResult<ExternalId> searchResult = _cfgMaster.history(search);
    assertEquals(2, searchResult.getDocuments().size());
  }
Ejemplo n.º 14
0
 private static CalculationJobSpecification createJobSpecification() {
   return new CalculationJobSpecification(
       UniqueId.of("Cycle", "1"), "Default", Instant.now(), JobIdSource.getId());
 }
  public void testCompileFunction() {
    final InMemoryFunctionRepository functions = new InMemoryFunctionRepository();
    final MockFunction alwaysValid = new MockFunction("always valid", null, null);
    final MockFunction validUntil = new MockFunction("valid until", null, 30L);
    final MockFunction validFrom = new MockFunction("valid from", 30L, null);
    final MockFunction validWithin = new MockFunction("valid within", 30L, 30L);
    functions.addFunction(alwaysValid);
    functions.addFunction(validUntil);
    functions.addFunction(validFrom);
    functions.addFunction(validWithin);
    final CachingFunctionRepositoryCompiler compiler = new CachingFunctionRepositoryCompiler();
    final CompiledFunctionService context =
        new CompiledFunctionService(functions, compiler, new FunctionCompilationContext());
    final Instant timestamp = Instant.now();

    // Everything compiled once
    final CompiledFunctionRepository compiledFunctionsNow =
        context.compileFunctionRepository(timestamp);
    assertSame(
        alwaysValid,
        compiledFunctionsNow.getDefinition(alwaysValid.getUniqueId()).getFunctionDefinition());
    assertSame(
        validUntil,
        compiledFunctionsNow.getDefinition(validUntil.getUniqueId()).getFunctionDefinition());
    assertSame(
        validFrom,
        compiledFunctionsNow.getDefinition(validFrom.getUniqueId()).getFunctionDefinition());
    assertSame(
        validWithin,
        compiledFunctionsNow.getDefinition(validWithin.getUniqueId()).getFunctionDefinition());
    assertEquals(1, alwaysValid._compileCount.get());
    assertEquals(1, validUntil._compileCount.get());
    assertEquals(1, validFrom._compileCount.get());
    assertEquals(1, validWithin._compileCount.get());

    // All previously compiled ones still valid, so should use the "previous" cache
    final CompiledFunctionRepository compiledFunctionsAheadWithin =
        context.compileFunctionRepository(timestamp.plusMillis(29L));
    assertSame(compiledFunctionsNow, compiledFunctionsAheadWithin);
    assertEquals(1, alwaysValid._compileCount.get());
    assertEquals(1, validUntil._compileCount.get());
    assertEquals(1, validFrom._compileCount.get());
    assertEquals(1, validWithin._compileCount.get());

    // All previously compiled ones still valid, so should use the "previous" cache
    final CompiledFunctionRepository compiledFunctionsAheadLimit =
        context.compileFunctionRepository(timestamp.plusMillis(30L));
    assertSame(compiledFunctionsNow, compiledFunctionsAheadLimit);
    assertEquals(1, alwaysValid._compileCount.get());
    assertEquals(1, validUntil._compileCount.get());
    assertEquals(1, validFrom._compileCount.get());
    assertEquals(1, validWithin._compileCount.get());

    // Some functions to be recompiled, others from the "previous" cache
    final CompiledFunctionRepository compiledFunctionsAheadBeyond =
        context.compileFunctionRepository(timestamp.plusMillis(31L));
    assertNotSame(compiledFunctionsNow, compiledFunctionsAheadBeyond);
    assertSame(
        compiledFunctionsNow.getDefinition(alwaysValid.getUniqueId()),
        compiledFunctionsAheadBeyond.getDefinition(alwaysValid.getUniqueId()));
    assertNotSame(
        compiledFunctionsNow.getDefinition(validUntil.getUniqueId()),
        compiledFunctionsAheadBeyond.getDefinition(validUntil.getUniqueId()));
    assertSame(
        compiledFunctionsNow.getDefinition(validFrom.getUniqueId()),
        compiledFunctionsAheadBeyond.getDefinition(validFrom.getUniqueId()));
    assertNotSame(
        compiledFunctionsNow.getDefinition(validWithin.getUniqueId()),
        compiledFunctionsAheadBeyond.getDefinition(validWithin.getUniqueId()));
    assertEquals(1, alwaysValid._compileCount.get());
    assertEquals(2, validUntil._compileCount.get());
    assertEquals(1, validFrom._compileCount.get());
    assertEquals(2, validWithin._compileCount.get());

    // All previously compiled functions, so should use the "ahead" cache
    final CompiledFunctionRepository compiledFunctionsBeforeWithin =
        context.compileFunctionRepository(timestamp.minusMillis(30L));
    assertSame(compiledFunctionsNow, compiledFunctionsBeforeWithin);
    assertEquals(1, alwaysValid._compileCount.get());
    assertEquals(2, validUntil._compileCount.get());
    assertEquals(1, validFrom._compileCount.get());
    assertEquals(2, validWithin._compileCount.get());

    // Some functions to be recompiled, others from the "ahead" cache
    final CompiledFunctionRepository compiledFunctionsBeforeBeyond =
        context.compileFunctionRepository(timestamp.minusMillis(31L));
    assertNotSame(compiledFunctionsNow, compiledFunctionsBeforeBeyond);
    assertSame(
        compiledFunctionsNow.getDefinition(alwaysValid.getUniqueId()),
        compiledFunctionsBeforeBeyond.getDefinition(alwaysValid.getUniqueId()));
    assertSame(
        compiledFunctionsNow.getDefinition(validUntil.getUniqueId()),
        compiledFunctionsBeforeBeyond.getDefinition(validUntil.getUniqueId()));
    assertNotSame(
        compiledFunctionsNow.getDefinition(validFrom.getUniqueId()),
        compiledFunctionsBeforeBeyond.getDefinition(validFrom.getUniqueId()));
    assertNotSame(
        compiledFunctionsNow.getDefinition(validWithin.getUniqueId()),
        compiledFunctionsBeforeBeyond.getDefinition(validWithin.getUniqueId()));
    assertEquals(1, alwaysValid._compileCount.get());
    assertEquals(2, validUntil._compileCount.get());
    assertEquals(2, validFrom._compileCount.get());
    assertEquals(3, validWithin._compileCount.get());
  }
  private void init() throws Exception {
    super.setUp();
    ConfigurableApplicationContext context = DbMasterTestUtils.getContext(getDatabaseType());
    _secMaster = (DbSecurityMaster) context.getBean(getDatabaseType() + "DbSecurityMaster");

    //    id bigint not null,
    //    oid bigint not null,
    //    ver_from_instant timestamp not null,
    //    ver_to_instant timestamp not null,
    //    corr_from_instant timestamp not null,
    //    corr_to_instant timestamp not null,
    //    name varchar(255) not null,
    //    sec_type varchar(255) not null,
    Instant now = Instant.now();
    _secMaster.setTimeSource(TimeSource.fixed(now));
    _version1Instant = now.minusSeconds(100);
    _version2Instant = now.minusSeconds(50);
    s_logger.debug("test data now:   {}", _version1Instant);
    s_logger.debug("test data later: {}", _version2Instant);
    final SimpleJdbcTemplate template = _secMaster.getDbConnector().getJdbcTemplate();
    template.update(
        "INSERT INTO sec_security VALUES (?,?,?,?,?, ?,?,?,?)",
        101,
        101,
        toSqlTimestamp(_version1Instant),
        MAX_SQL_TIMESTAMP,
        toSqlTimestamp(_version1Instant),
        MAX_SQL_TIMESTAMP,
        "TestSecurity101",
        "EQUITY",
        "D");
    template.update(
        "INSERT INTO sec_security VALUES (?,?,?,?,?, ?,?,?,?)",
        102,
        102,
        toSqlTimestamp(_version1Instant),
        MAX_SQL_TIMESTAMP,
        toSqlTimestamp(_version1Instant),
        MAX_SQL_TIMESTAMP,
        "TestSecurity102",
        "EQUITY",
        "D");
    template.update(
        "INSERT INTO sec_security VALUES (?,?,?,?,?, ?,?,?,?)",
        201,
        201,
        toSqlTimestamp(_version1Instant),
        toSqlTimestamp(_version2Instant),
        toSqlTimestamp(_version1Instant),
        MAX_SQL_TIMESTAMP,
        "TestSecurity201",
        "EQUITY",
        "D");
    template.update(
        "INSERT INTO sec_security VALUES (?,?,?,?,?, ?,?,?,?)",
        202,
        201,
        toSqlTimestamp(_version2Instant),
        MAX_SQL_TIMESTAMP,
        toSqlTimestamp(_version2Instant),
        MAX_SQL_TIMESTAMP,
        "TestSecurity202",
        "EQUITY",
        "D");
    _totalSecurities = 3;
    //  id bigint not null,
    //  key_scheme varchar(255) not null,
    //  key_value varchar(255) not null,
    template.update("INSERT INTO sec_idkey VALUES (?,?,?)", 1, "A", "B");
    template.update("INSERT INTO sec_idkey VALUES (?,?,?)", 2, "C", "D");
    template.update("INSERT INTO sec_idkey VALUES (?,?,?)", 3, "E", "F");
    template.update("INSERT INTO sec_idkey VALUES (?,?,?)", 4, "G", "HI");
    //  security_id bigint not null,
    //  idkey_id bigint not null,
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 101, 1);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 101, 2);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 101, 3);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 102, 1);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 102, 2);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 102, 4);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 201, 2);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 201, 3);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 202, 2);
    template.update("INSERT INTO sec_security2idkey VALUES (?,?)", 202, 3);
  }
Ejemplo n.º 17
0
/** Test. */
public class DataConfigSourceResourceTest {

  private static final ObjectId OID = ObjectId.of("Test", "A");
  private static final UniqueId UID = OID.atVersion("B");
  private static final VersionCorrection VC =
      VersionCorrection.LATEST.withLatestFixed(Instant.now());
  private static final String NAME = "name";
  private ConfigSource _underlying;
  private UriInfo _uriInfo;
  private DataConfigSourceResource _resource;

  @BeforeMethod
  public void setUp() {
    _underlying = mock(ConfigSource.class);
    _uriInfo = mock(UriInfo.class);
    when(_uriInfo.getBaseUri()).thenReturn(URI.create("testhost"));
    _resource = new DataConfigSourceResource(_underlying);
  }

  // -------------------------------------------------------------------------
  @Test
  public void testGetConfigByUid() {
    final SimpleExchange target = new SimpleExchange();
    target.setName("Test");

    when(_underlying.getConfig(eq(SimpleExchange.class), eq(UID))).thenReturn(target);

    Response test =
        _resource.get(OID.toString(), SimpleExchange.class.getName(), UID.getVersion(), "", "");
    assertEquals(Status.OK.getStatusCode(), test.getStatus());
    assertSame(target, test.getEntity());
  }

  @Test
  public void testGetConfigByOid() {
    final SimpleExchange target = new SimpleExchange();
    target.setName("Test");

    when(_underlying.getConfig(eq(SimpleExchange.class), eq(OID), eq(VC))).thenReturn(target);

    Response test =
        _resource.get(
            OID.toString(),
            SimpleExchange.class.getName(),
            null,
            VC.getVersionAsOfString(),
            VC.getCorrectedToString());
    assertEquals(Status.OK.getStatusCode(), test.getStatus());
    assertSame(target, test.getEntity());
  }

  @SuppressWarnings({"rawtypes", "unchecked"})
  @Test
  public void testSearch() {
    final SimpleExchange target = new SimpleExchange();
    target.setName("Test");
    Collection targetColl = ImmutableList.of(target);

    when(_underlying.getConfigs(eq(SimpleExchange.class), eq(NAME), eq(VC))).thenReturn(targetColl);

    Response test =
        _resource.search(
            SimpleExchange.class.getName(),
            VC.getVersionAsOfString(),
            VC.getCorrectedToString(),
            NAME);
    assertEquals(Status.OK.getStatusCode(), test.getStatus());
    assertEquals(FudgeListWrapper.of(targetColl), test.getEntity());
  }
}
  @Override
  public List<UniqueId> replaceVersions(
      ObjectIdentifiable objectIdentifiable,
      List<YieldCurveDefinitionDocument> replacementDocuments) {
    ArgumentChecker.notNull(replacementDocuments, "replacementDocuments");
    ArgumentChecker.notNull(objectIdentifiable, "objectIdentifiable");

    final Instant now = Instant.now();

    for (YieldCurveDefinitionDocument replacementDocument : replacementDocuments) {
      ArgumentChecker.notNull(replacementDocument, "document");
      ArgumentChecker.notNull(
          replacementDocument.getYieldCurveDefinition(), "document.yieldCurveDefinition");
      final Currency currency = replacementDocument.getYieldCurveDefinition().getCurrency();
      final String name = replacementDocument.getYieldCurveDefinition().getName();
      final UniqueId id = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode());
      ArgumentChecker.isTrue(id.equals(objectIdentifiable), "Invalid object identifier");
    }

    YieldCurveDefinitionDocument storedDocument = get(objectIdentifiable, null);
    if (storedDocument == null) {
      throw new DataNotFoundException("Document not found: " + objectIdentifiable);
    }
    final Currency currency = storedDocument.getYieldCurveDefinition().getCurrency();
    final String name = storedDocument.getYieldCurveDefinition().getName();
    Pair<Currency, String> key = Pair.of(currency, name);

    final TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key);
    if (value == null) {
      throw new DataNotFoundException("OID '" + objectIdentifiable + "' not found");
    }
    if (_sourceVersionCorrection.getVersionAsOf() != null) {
      // Don't need to keep the old values before the one needed by "versionAsOfInstant"
      final Instant oldestNeeded = value.floorKey(_sourceVersionCorrection.getVersionAsOf());
      value.headMap(oldestNeeded).clear();
    } else {
      // Don't need any old values
      value.clear();
    }

    Instant lowestCurrentVersionFrom = value.firstKey();

    List<YieldCurveDefinitionDocument> orderedReplacementDocuments =
        MasterUtils.adjustVersionInstants(
            now, lowestCurrentVersionFrom, null, replacementDocuments);

    final Instant lowestVersionFrom = orderedReplacementDocuments.get(0).getVersionFromInstant();
    final Instant highestVersionTo =
        orderedReplacementDocuments
            .get(orderedReplacementDocuments.size() - 1)
            .getVersionToInstant();

    if (orderedReplacementDocuments.size() > 0) {
      value.subMap(lowestVersionFrom, true, highestVersionTo, false).clear();
    }

    for (YieldCurveDefinitionDocument replacementDocument : orderedReplacementDocuments) {
      value.put(
          replacementDocument.getVersionFromInstant(),
          replacementDocument.getYieldCurveDefinition());
      changeManager()
          .entityChanged(ChangeType.CHANGED, replacementDocument.getObjectId(), null, null, now);
    }
    return MasterUtils.mapToUniqueIDs(orderedReplacementDocuments);
  }