/** * Gets the best descriptive name. * * @return the best descriptive name, not null */ public String getBestName() { Security security = getTarget(); ObjectId objectId = getObjectId(); ExternalIdBundle bundle = getExternalId(); if (security != null) { // Try to retrieve the security's assigned name String name = security.getName(); if (StringUtils.isNotBlank(name)) { return name; } bundle = security.getExternalIdBundle(); } if (bundle != null && bundle.size() > 0) { if (bundle.getValue(ExternalSchemes.BLOOMBERG_TICKER) != null) { return bundle.getValue(ExternalSchemes.BLOOMBERG_TICKER); } else if (bundle.getValue(ExternalSchemes.RIC) != null) { return bundle.getValue(ExternalSchemes.RIC); } else if (bundle.getValue(ExternalSchemes.ACTIVFEED_TICKER) != null) { return bundle.getValue(ExternalSchemes.ACTIVFEED_TICKER); } else { return bundle.getExternalIds().iterator().next().getValue(); } } if (objectId != null) { return objectId.toString(); } return ""; }
@Override public PortfolioDocument add(PortfolioDocument document) { ArgumentChecker.notNull(document, "document"); ArgumentChecker.notNull(document.getPortfolio(), "document.portfolio"); final ObjectId objectId = _objectIdSupplier.get(); final UniqueId uniqueId = objectId.atVersion(""); final Instant now = Instant.now(); final PortfolioDocument clonedDoc = clonePortfolioDocument(document); setDocumentId(document, clonedDoc, uniqueId); setVersionTimes(document, clonedDoc, now, null, now, null); _store.put(objectId, clonedDoc); storeNodes( clonedDoc.getPortfolio().getRootNode(), document.getPortfolio().getRootNode(), uniqueId, null); _changeManager.entityChanged( ChangeType.ADDED, objectId, document.getVersionFromInstant(), document.getVersionToInstant(), now); updateCaches(null, clonedDoc); return document; }
@Override public synchronized YieldCurveDefinitionDocument get( ObjectIdentifiable objectIdable, VersionCorrection versionCorrection) { ArgumentChecker.notNull(objectIdable, "objectIdable"); ObjectId objectId = objectIdable.getObjectId(); if (!getUniqueIdScheme().equals(objectId.getScheme())) { throw new DataNotFoundException( "Scheme '" + objectId.getScheme() + "' not valid for '" + getUniqueIdScheme() + "'"); } final int i = objectId.getValue().indexOf('_'); if (i <= 0) { throw new DataNotFoundException( "Identifier '" + objectId.getValue() + "' not valid for '" + getUniqueIdScheme() + "'"); } final String name = objectId.getValue().substring(0, i); final String iso = objectId.getValue().substring(i + 1); final Currency currency; try { currency = Currency.of(iso); } catch (IllegalArgumentException e) { throw new DataNotFoundException( "Identifier '" + objectId.getValue() + "' not valid for '" + getUniqueIdScheme() + "'", e); } final TreeMap<Instant, YieldCurveDefinition> definitions = _definitions.get(Pair.of(currency, name)); if (definitions == null) { throw new DataNotFoundException("Curve definition not found"); } final YieldCurveDefinition definition = definitions.lastEntry().getValue(); if (definition == null) { throw new DataNotFoundException("Curve definition not found"); } return new YieldCurveDefinitionDocument(objectId.atLatestVersion(), definition); }
@Test public void test_search_userIds() { UserSearchRequest request = new UserSearchRequest(); request.addObjectId(ObjectId.of("DbUsr", "101")); request.addObjectId(ObjectId.of("DbUsr", "201")); request.addObjectId(ObjectId.of("DbUsr", "9999")); UserSearchResult test = _usrMaster.search(request); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert202(test.getDocuments().get(1)); }
@GET @Path("exchanges/{exchangeId}") public Response get( @PathParam("exchangeId") String idStr, @QueryParam("version") String version, @QueryParam("versionAsOf") String versionAsOf, @QueryParam("correctedTo") String correctedTo) { final ObjectId objectId = ObjectId.parse(idStr); if (version != null) { final Exchange result = getExchangeSource().getExchange(objectId.atVersion(version)); return responseOkFudge(result); } else { final VersionCorrection vc = VersionCorrection.parse(versionAsOf, correctedTo); Exchange result = getExchangeSource().getExchange(objectId, vc); return responseOkFudge(result); } }
/** * Updates an existing time-series in the master. If the time series provided has overlaps with * the existing time series, the old versions of intersecting points will be corrected to the new * ones. After that, points later than the existing latest point of the time series will be * appended. * * @param description a description of the time-series for display purposes, not null * @param dataSource the data source, not null * @param dataProvider the data provider, not null * @param dataField the data field, not null * @param observationTime the descriptive observation time key, e.g. LONDON_CLOSE, not null * @param oId the unique identifier of the time-series to be updated, not null * @param timeSeries the time-series, not null * @return the unique identifier of the time-series */ public UniqueId writeTimeSeries( String description, String dataSource, String dataProvider, String dataField, String observationTime, ObjectId oId, LocalDateDoubleTimeSeries timeSeries) { UniqueId uId = oId.atLatestVersion(); ManageableHistoricalTimeSeries existingManageableTs = _htsMaster.getTimeSeries(uId); LocalDateDoubleTimeSeries existingTs = existingManageableTs.getTimeSeries(); if (existingTs.isEmpty()) { uId = _htsMaster.updateTimeSeriesDataPoints(oId, timeSeries); s_logger.debug( "Updating time series " + oId + "[" + dataField + "] with all as currently emtpy)"); } else { // There is a non-empty matching time-series already in the master so update it to reflect the // new time-series // 1: 'correct' any differences in the subseries already present LocalDateDoubleTimeSeries tsIntersection = timeSeries.subSeries( existingTs.getEarliestTime(), true, existingTs.getLatestTime(), true); if (!tsIntersection.equals(existingTs)) { s_logger.debug( "Correcting time series " + oId + "[" + dataField + "] from " + existingTs.getEarliestTime() + " to " + existingTs.getLatestTime()); uId = _htsMaster.correctTimeSeriesDataPoints(oId, tsIntersection); } // 2: 'update' the time-series to add any new, later points if (existingTs.getLatestTime().isBefore(timeSeries.getLatestTime())) { LocalDateDoubleTimeSeries newSeries = timeSeries.subSeries( existingTs.getLatestTime(), false, timeSeries.getLatestTime(), true); if (newSeries.size() > 0) { s_logger.debug( "Updating time series " + oId + "[" + dataField + "] from " + newSeries.getEarliestTime() + " to " + newSeries.getLatestTime()); uId = _htsMaster.updateTimeSeriesDataPoints(oId, newSeries); } } } return uId; }
// ------------------------------------------------------------------------- @Test public void test_searchPositionHistoric_documents() { ObjectId oid = ObjectId.of("DbPos", "221"); PositionHistoryRequest request = new PositionHistoryRequest(oid); PositionHistoryResult test = _posMaster.history(request); assertEquals(2, test.getDocuments().size()); assert222(test.getDocuments().get(0)); assert221(test.getDocuments().get(1)); }
// ------------------------------------------------------------------------- @Test public void test_history_documents() { ObjectId oid = ObjectId.of("DbSec", "201"); SecurityHistoryRequest request = new SecurityHistoryRequest(oid); SecurityHistoryResult test = _secMaster.history(request); assertEquals(2, test.getDocuments().size()); assert202(test.getDocuments().get(0)); assert201(test.getDocuments().get(1)); }
public void test() { ManageableTrade obj = new ManageableTrade(); obj.setUniqueId(UniqueId.of("U", "1")); obj.setQuantity(BigDecimal.ONE); obj.setSecurityLink(new ManageableSecurityLink(ExternalId.of("A", "B"))); obj.getSecurityLink().setObjectId(ObjectId.of("O", "1")); obj.setTradeDate(LocalDate.of(2011, 6, 1)); obj.setCounterpartyExternalId(ExternalId.of("C", "D")); testFudgeMessage(obj); }
@Test public void test_searchPositionHistoric_documentCountWhenMultipleSecuritiesAndMultipleTrades() { ObjectId oid = ObjectId.of("DbPos", "123"); PositionHistoryRequest request = new PositionHistoryRequest(oid); PositionHistoryResult test = _posMaster.history(request); assertEquals(1, test.getPaging().getTotalItems()); assertEquals(1, test.getDocuments().size()); assert123(test.getDocuments().get(0)); }
// ------------------------------------------------------------------------- @Test public void test_history_versionsTo_preFirst() { ObjectId oid = ObjectId.of("DbSec", "201"); SecurityHistoryRequest request = new SecurityHistoryRequest(oid); request.setVersionsToInstant(_version1Instant.minusSeconds(5)); SecurityHistoryResult test = _secMaster.history(request); assertEquals(0, test.getPaging().getTotalItems()); assertEquals(0, test.getDocuments().size()); }
// ------------------------------------------------------------------------- @Test public void test_searchPositionHistoric_versionsTo_preFirst() { ObjectId oid = ObjectId.of("DbPos", "221"); PositionHistoryRequest request = new PositionHistoryRequest(oid); request.setVersionsToInstant(_version1Instant.minusSeconds(5)); PositionHistoryResult test = _posMaster.history(request); assertEquals(0, test.getPaging().getTotalItems()); assertEquals(0, test.getDocuments().size()); }
@Test public void test_history_documentCountWhenMultipleSecuritys() { ObjectId oid = ObjectId.of("DbSec", "102"); SecurityHistoryRequest request = new SecurityHistoryRequest(oid); SecurityHistoryResult test = _secMaster.history(request); assertEquals(1, test.getPaging().getTotalItems()); assertEquals(1, test.getDocuments().size()); assert102(test.getDocuments().get(0)); }
// ------------------------------------------------------------------------- @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 test_searchPositionHistoric_versionsFrom_postSecond() { ObjectId oid = ObjectId.of("DbPos", "221"); PositionHistoryRequest request = new PositionHistoryRequest(oid); request.setVersionsFromInstant(_version2Instant.plusSeconds(5)); PositionHistoryResult test = _posMaster.history(request); assertEquals(1, test.getPaging().getTotalItems()); assertEquals(1, test.getDocuments().size()); assert222(test.getDocuments().get(0)); }
@Test public void test_history_versionsFrom_postSecond() { ObjectId oid = ObjectId.of("DbSec", "201"); SecurityHistoryRequest request = new SecurityHistoryRequest(oid); request.setVersionsFromInstant(_version2Instant.plusSeconds(5)); SecurityHistoryResult test = _secMaster.history(request); assertEquals(1, test.getPaging().getTotalItems()); assertEquals(1, test.getDocuments().size()); assert202(test.getDocuments().get(0)); }
/** * Parses an {@code ObjectId} from a formatted scheme and value. * * <p>This parses the identifier from the form produced by {@code toString()} which is {@code * <SCHEME>~<VALUE>}. * * @param str the object identifier to parse, not null * @return the object identifier, not null * @throws IllegalArgumentException if the identifier cannot be parsed */ @FromString public static ObjectId parse(String str) { ArgumentChecker.notEmpty(str, "str"); if (str.contains("~") == false) { str = StringUtils.replace(str, "::", "~"); // leniently parse old data } String[] split = StringUtils.splitByWholeSeparatorPreserveAllTokens(str, "~"); switch (split.length) { case 2: return ObjectId.of(split[0], split[1]); } throw new IllegalArgumentException("Invalid identifier format: " + str); }
private void storeNodes( final ManageablePortfolioNode clonedNode, final ManageablePortfolioNode origNode, final UniqueId portfolioId, final UniqueId parentNodeId) { final ObjectId objectId = _objectIdSupplier.get(); final UniqueId uniqueId = objectId.atVersion(""); clonedNode.setUniqueId(uniqueId); origNode.setUniqueId(uniqueId); clonedNode.setParentNodeId(parentNodeId); origNode.setParentNodeId(parentNodeId); clonedNode.setPortfolioId(portfolioId); origNode.setPortfolioId(portfolioId); _storeNodes.put(objectId, clonedNode); for (int i = 0; i < clonedNode.getChildNodes().size(); i++) { storeNodes( clonedNode.getChildNodes().get(i), origNode.getChildNodes().get(i), portfolioId, uniqueId); } }
// ------------------------------------------------------------------------- @Test public void test_history_noInstants() { ObjectId oid = ObjectId.of("DbSec", "201"); SecurityHistoryRequest request = new SecurityHistoryRequest(oid); SecurityHistoryResult test = _secMaster.history(request); assertEquals(PagingRequest.ALL, test.getPaging().getRequest()); assertEquals(2, test.getPaging().getTotalItems()); assertEquals(2, test.getDocuments().size()); assert202(test.getDocuments().get(0)); assert201(test.getDocuments().get(1)); }
// ------------------------------------------------------------------------- @Test public void test_searchPositionHistoric_noInstants_pageOne() { ObjectId oid = ObjectId.of("DbPos", "221"); PositionHistoryRequest request = new PositionHistoryRequest(oid); request.setPagingRequest(PagingRequest.ofPage(1, 1)); PositionHistoryResult test = _posMaster.history(request); assertEquals(1, test.getPaging().getFirstItemOneBased()); assertEquals(1, test.getPaging().getPagingSize()); assertEquals(2, test.getPaging().getTotalItems()); assertEquals(1, test.getDocuments().size()); assert222(test.getDocuments().get(0)); }
// ------------------------------------------------------------------------- @Test public void test_history_noInstants_pageOne() { ObjectId oid = ObjectId.of("DbSec", "201"); PagingRequest pr = PagingRequest.ofPage(1, 1); SecurityHistoryRequest request = new SecurityHistoryRequest(oid); request.setPagingRequest(pr); SecurityHistoryResult test = _secMaster.history(request); assertEquals(pr, test.getPaging().getRequest()); assertEquals(2, test.getPaging().getTotalItems()); assertEquals(1, test.getDocuments().size()); assert202(test.getDocuments().get(0)); }
@SuppressWarnings("deprecation") public void testTrade_withPremium() { SimpleTrade trade = new SimpleTrade(); trade.setUniqueId(UniqueId.of("A", "B")); trade.setQuantity(BigDecimal.valueOf(12.34d)); trade.setSecurityLink(new SimpleSecurityLink(ObjectId.of("E", "F"))); trade.setCounterparty(new SimpleCounterparty(ExternalId.of("G", "H"))); trade.setTradeDate(LocalDate.of(2011, 1, 5)); trade.setTradeTime(OffsetTime.parse("14:30+02:00")); // set premium trade.setPremium(100.00); trade.setPremiumCurrency(Currency.USD); trade.setPremiumDate(LocalDate.of(2011, 1, 6)); trade.setPremiumTime(OffsetTime.parse("15:30+02:00")); assertEncodeDecodeCycle(Trade.class, trade); }
/** * Returns the version history of a market data snapshot. * * @param snapshotId An snapshot {@link ObjectId} * @return JSON array of the snapshot's history * <pre> * [{"uniqueId": "DbSnp~12345~2", * "correctionFrom": "2012-05-23T10:54:10.124293Z", * "correctionTo": null, * "versionFrom": "2012-05-23T10:54:10.124293Z", * "versionTo": null}] * </pre> */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("{snapshotId}") public String getMarketDataSnapshotHistory(@PathParam("snapshotId") String snapshotId) { ObjectId id = ObjectId.parse(snapshotId); MarketDataSnapshotHistoryResult result = _snapshotMaster.history(new MarketDataSnapshotHistoryRequest(id)); List<MarketDataSnapshotDocument> documents = result.getDocuments(); List<Map<String, Object>> json = Lists.newArrayListWithCapacity(documents.size()); for (MarketDataSnapshotDocument document : documents) { Map<String, Object> map = Maps.newHashMapWithExpectedSize(5); map.put("uniqueId", document.getUniqueId()); map.put("versionFrom", document.getVersionFromInstant()); map.put("versionTo", document.getVersionToInstant()); map.put("correctionFrom", document.getCorrectionFromInstant()); map.put("correctionTo", document.getCorrectionToInstant()); json.add(map); } return new JSONArray(json).toString(); }
/** * Returns a copy of this identifier with the specified scheme. * * @param scheme the new scheme of the identifier, not empty, not null * @return an {@link ObjectId} based on this identifier with the specified scheme, not null */ public ObjectId withScheme(final String scheme) { return ObjectId.of(scheme, _value); }
/** Test {@link MasterExchangeSource}. */ @Test(groups = TestGroup.UNIT) public class MasterExchangeSourceTest { private static final ObjectId OID = ObjectId.of("A", "B"); private static final UniqueId UID = UniqueId.of("A", "B", "V"); private static final ExternalId ID = ExternalId.of("C", "D"); private static final ExternalIdBundle BUNDLE = ExternalIdBundle.of(ID); private static final Instant NOW = Instant.now(); private static final VersionCorrection VC = VersionCorrection.of(NOW.minusSeconds(2), NOW.minusSeconds(1)); @Test(expectedExceptions = IllegalArgumentException.class) public void test_constructor_1arg_nullMaster() throws Exception { new MasterExchangeSource(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_constructor_2arg_nullMaster() throws Exception { new MasterExchangeSource(null, null); } // ------------------------------------------------------------------------- public void test_getExchange_UniqueId_noOverride_found() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); ExchangeDocument doc = new ExchangeDocument(example()); when(mock.get(UID)).thenReturn(doc); MasterExchangeSource test = new MasterExchangeSource(mock); Exchange testResult = test.get(UID); verify(mock, times(1)).get(UID); assertEquals(example(), testResult); } public void test_getExchange_UniqueId_found() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); ExchangeDocument doc = new ExchangeDocument(example()); when(mock.get(OID, VC)).thenReturn(doc); MasterExchangeSource test = new MasterExchangeSource(mock, VC); Exchange testResult = test.get(UID); verify(mock, times(1)).get(OID, VC); assertEquals(example(), testResult); } @Test(expectedExceptions = DataNotFoundException.class) public void test_getExchange_UniqueId_notFound() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); when(mock.get(OID, VC)).thenThrow(new DataNotFoundException("")); MasterExchangeSource test = new MasterExchangeSource(mock, VC); try { test.get(UID); } finally { verify(mock, times(1)).get(OID, VC); } } // ------------------------------------------------------------------------- public void test_getExchange_ObjectId_found() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); ExchangeDocument doc = new ExchangeDocument(example()); when(mock.get(OID, VC)).thenReturn(doc); MasterExchangeSource test = new MasterExchangeSource(mock, VC); Exchange testResult = test.get(OID, VC); verify(mock, times(1)).get(OID, VC); assertEquals(example(), testResult); } @Test(expectedExceptions = DataNotFoundException.class) public void test_getExchange_ObjectId_notFound() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); when(mock.get(OID, VC)).thenThrow(new DataNotFoundException("")); MasterExchangeSource test = new MasterExchangeSource(mock, VC); try { test.get(OID, VC); } finally { verify(mock, times(1)).get(OID, VC); } } // ------------------------------------------------------------------------- public void test_getSingleExchange_ExternalId_found() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); ExchangeSearchRequest request = new ExchangeSearchRequest(ID); request.setPagingRequest(PagingRequest.ONE); request.setPagingRequest(PagingRequest.ONE); request.setVersionCorrection(VC); ExchangeSearchResult result = new ExchangeSearchResult(); result.getDocuments().add(new ExchangeDocument(example())); when(mock.search(request)).thenReturn(result); MasterExchangeSource test = new MasterExchangeSource(mock, VC); Exchange testResult = test.getSingle(ID); verify(mock, times(1)).search(request); assertEquals(example(), testResult); } public void test_getSingleExchange_ExternalId_notFound() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); ExchangeSearchRequest request = new ExchangeSearchRequest(ID); request.setPagingRequest(PagingRequest.ONE); request.setPagingRequest(PagingRequest.ONE); request.setVersionCorrection(VC); ExchangeSearchResult result = new ExchangeSearchResult(); when(mock.search(request)).thenReturn(result); MasterExchangeSource test = new MasterExchangeSource(mock, VC); Exchange testResult = test.getSingle(ID); verify(mock, times(1)).search(request); assertEquals(null, testResult); } // ------------------------------------------------------------------------- public void test_getSingleExchange_ExternalIdBundle_found() throws Exception { ExchangeMaster mock = mock(ExchangeMaster.class); ExchangeSearchRequest request = new ExchangeSearchRequest(BUNDLE); request.setPagingRequest(PagingRequest.ONE); request.setVersionCorrection(VC); ExchangeSearchResult result = new ExchangeSearchResult(); result.getDocuments().add(new ExchangeDocument(example())); when(mock.search(request)).thenReturn(result); MasterExchangeSource test = new MasterExchangeSource(mock, VC); Exchange testResult = test.getSingle(BUNDLE); verify(mock, times(1)).search(request); assertEquals(example(), testResult); } // ------------------------------------------------------------------------- protected ManageableExchange example() { ManageableExchange exchange = new ManageableExchange(); exchange.setUniqueId(UID); exchange.setName("NYSE"); exchange.setRegionIdBundle(ExternalIdBundle.of(ExternalSchemes.countryRegionId(Country.US))); return exchange; } }
/** * Returns a copy of this identifier with the specified value. * * @param value the new value of the identifier, not empty, not null * @return an {@link ObjectId} based on this identifier with the specified value, not null */ public ObjectId withValue(final String value) { return ObjectId.of(_scheme, value); }
@Override public Security get(ObjectId objectId, VersionCorrection versionCorrection) { ArgumentChecker.notNull(objectId, "objectId"); ArgumentChecker.notNull(versionCorrection, "versionCorrection"); return _delegator.chooseDelegate(objectId.getScheme()).get(objectId, versionCorrection); }
@Override public ObjectId getObjectId() { return ObjectId.of(BatchMaster.BATCH_IDENTIFIER_SCHEME, Long.toString(getId())); }
@Test(expectedExceptions = IllegalArgumentException.class) public void test_search_userIds_badSchemeValidOid() { UserSearchRequest request = new UserSearchRequest(); request.addObjectId(ObjectId.of("Rubbish", "120")); _usrMaster.search(request); }
public void testGetSecurity_byObjectId() { final SecuritySource underlying = Mockito.mock(SecuritySource.class); final SecuritySource coalescing = new CoalescingSecuritySource(underlying); coalescing.get(ObjectId.of("Test", "Test"), VersionCorrection.LATEST); Mockito.verify(underlying).get(ObjectId.of("Test", "Test"), VersionCorrection.LATEST); }