method2testcases
stringlengths
118
6.63k
### Question: ServiceContext { public synchronized boolean isAvailable() { Service service = this.service; return service != null && !CollectionValues.isNullOrEmpty(service.getInstances()); } ServiceContext(DiscoveryConfig discoveryConfig); DiscoveryConfig getDiscoveryConfig(); synchronized Service newService(); synchronized void setService(Service service); synchronized boolean deleteInstance(Instance instance); synchronized boolean updateInstance(Instance instance); synchronized boolean addInstance(Instance instance); synchronized boolean isAvailable(); synchronized Set<ServiceChangeListener> getListeners(); synchronized void addListener(final ServiceChangeListener listener); ServiceChangeEvent newServiceChangeEvent(final String changeType); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object other); }### Answer: @Test public void testIsAvailable() { ServiceContext context = new ServiceContext(_discoveryConfig); Assert.assertFalse(context.isAvailable()); Instance instance = Instances.newInstance(_serviceId); Assert.assertTrue(context.addInstance(instance)); Assert.assertEquals(1, context.newService().getInstances().size()); Assert.assertTrue(context.isAvailable()); Assert.assertTrue(context.deleteInstance(instance)); Assert.assertFalse(context.isAvailable()); }
### Question: GroupDao { protected void insertOrUpdate(final GroupModel... groups) { insertOrUpdate(Lists.newArrayList(groups)); } private GroupDao(); List<GroupModel> query(); List<GroupModel> select(GroupModel filter); List<GroupModel> select(List<Long> groupIds); static final GroupDao INSTANCE; }### Answer: @Test public void testInsertOrUpdate() { GroupModel group = newGroup(); groupDao.insertOrUpdate(group); assertGroup(group, query(group)); groupDao.insertOrUpdate(group); assertGroup(group, query(group)); }
### Question: GroupDao { protected void delete(final Long... ids) { delete(Lists.newArrayList(ids)); } private GroupDao(); List<GroupModel> query(); List<GroupModel> select(GroupModel filter); List<GroupModel> select(List<Long> groupIds); static final GroupDao INSTANCE; }### Answer: @Test public void testDelete() { GroupModel group = newGroup(); groupDao.insertOrUpdate(group); GroupModel copy1 = query(group); groupDao.delete(copy1.getId()); Assert.assertNull(query(group, 0)); groupDao.insertOrUpdate(group); GroupModel copy2 = query(group); Assert.assertEquals(copy1.getId(), copy2.getId()); assertGroup(copy1, copy2); }
### Question: GroupDao { public List<GroupModel> select(GroupModel filter) { ValueCheckers.notNull(filter, "filter"); Map<String, String> conditions = Maps.newHashMap(); conditions.put("id=?", filter.getId() == null ? null : Long.toString(filter.getId())); conditions.put("service_id=?", filter.getServiceId()); conditions.put("region_id=?", filter.getRegionId()); conditions.put("zone_id=?", filter.getZoneId()); conditions.put("name=?", filter.getName()); conditions.put("app_id=?", filter.getAppId()); conditions.put("status=?", filter.getStatus()); Set<String> removed = Sets.newHashSet(); for (String key : conditions.keySet()) { if (StringValues.isNullOrWhitespace(conditions.get(key))) { removed.add(key); } } conditions.keySet().removeAll(removed); return query(Joiner.on(" and ").join(conditions.keySet()), Lists.newArrayList(conditions.values())); } private GroupDao(); List<GroupModel> query(); List<GroupModel> select(GroupModel filter); List<GroupModel> select(List<Long> groupIds); static final GroupDao INSTANCE; }### Answer: @Test public void testSelect() { GroupModel group = newGroup(); groupDao.insertOrUpdate(group); GroupModel filter = new GroupModel(); filter.setServiceId(group.getServiceId()); filter.setName(group.getName()); GroupModel newGroup = groupDao.select(filter).get(0); assertGroup(group, newGroup); assertGroup(group, groupDao.select(Lists.newArrayList(newGroup.getId())).get(0)); }
### Question: ServiceInstanceLogDao { protected void insert(final ServiceInstanceLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private ServiceInstanceLogDao(); List<ServiceInstanceLog> select(ServiceInstanceLogModel filter); List<ServiceInstanceLog> query(final String condition, final List<Object> args); static final ServiceInstanceLogDao INSTANCE; }### Answer: @Test public void testInsert() { final ServiceInstanceLogModel log1 = newModel(); final ServiceInstanceLogModel log2 = newModel(); final List<ServiceInstanceLogModel> logs = Lists.newArrayList(log1, log2); serviceInstanceLogDao.insert(log1, log2); for (final ServiceInstanceLogModel log : logs) { final List<ServiceInstanceLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertLog(log, logModels.get(0)); } }
### Question: GroupTagDao { public List<GroupTagModel> query() { return DataConfig.jdbcTemplate().query("select group_id, tag, value from service_group_tag", new RowMapper<GroupTagModel>() { @Override public GroupTagModel mapRow(ResultSet rs, int i) throws SQLException { GroupTagModel tag = new GroupTagModel(); tag.setGroupId(rs.getLong(1)); tag.setTag(rs.getString(2)); tag.setValue(rs.getString(3)); return tag; } }); } private GroupTagDao(); List<GroupTagModel> query(); void delete(GroupTagModel filter); void insertOrUpdate(GroupTagModel... models); void insertOrUpdate(final List<GroupTagModel> models); static final GroupTagDao INSTANCE; }### Answer: @Test public void testQuery() throws Exception { groupTagDao.insertOrUpdate(newGroupTag()); groupTagDao.insertOrUpdate(newGroupTag()); Assert.assertTrue(groupTagDao.query().size() >= 2); }
### Question: GroupTagDao { public void delete(GroupTagModel filter) { ValueCheckers.notNull(filter, "filter"); final Map<String, String> conditions = Maps.newHashMap(); conditions.put("group_id=?", filter.getGroupId() == null ? null : Long.toString(filter.getGroupId())); conditions.put("tag=?", filter.getTag()); conditions.put("value=?", filter.getValue()); Set<String> removed = Sets.newHashSet(); for (String key : conditions.keySet()) { if (StringValues.isNullOrWhitespace(conditions.get(key))) { removed.add(key); } } conditions.keySet().removeAll(removed); if (conditions.size() == 0) { throw new IllegalStateException("forbidden operation."); } String sql = "delete from service_group_tag where " + Joiner.on(" and ").join(conditions.keySet()); DataConfig.jdbcTemplate().update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { List<String> args = Lists.newArrayList(conditions.values()); for (int i = 0; i < args.size(); i++) { ps.setString(i + 1, args.get(i)); } } }); } private GroupTagDao(); List<GroupTagModel> query(); void delete(GroupTagModel filter); void insertOrUpdate(GroupTagModel... models); void insertOrUpdate(final List<GroupTagModel> models); static final GroupTagDao INSTANCE; }### Answer: @Test public void testDelete() throws Exception { GroupTagModel groupTag = newGroupTag(); groupTagDao.insertOrUpdate(groupTag); assertGroupOperation(groupTag, query(groupTag)); groupTagDao.delete(groupTag); Assert.assertNull(query(groupTag)); }
### Question: GroupTagDao { public void insertOrUpdate(GroupTagModel... models) { insertOrUpdate(Lists.newArrayList(models)); } private GroupTagDao(); List<GroupTagModel> query(); void delete(GroupTagModel filter); void insertOrUpdate(GroupTagModel... models); void insertOrUpdate(final List<GroupTagModel> models); static final GroupTagDao INSTANCE; }### Answer: @Test public void testInsertOrUpdate() throws Exception { GroupTagModel GroupTag = newGroupTag(); groupTagDao.insertOrUpdate(GroupTag); groupTagDao.insertOrUpdate(GroupTag); assertGroupOperation(GroupTag, query(GroupTag)); }
### Question: GroupTagLogDao { public void insert(final GroupTagLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private GroupTagLogDao(); List<GroupTagLog> query(final String condition, final Object... args); void insert(final GroupTagLogModel... logs); void insert(final List<GroupTagLogModel> logs); static final GroupTagLogDao INSTANCE; }### Answer: @Test public void testInsert() { final GroupTagLogModel log1 = newModel(); final GroupTagLogModel log2 = newModel(); final List<GroupTagLogModel> logs = Lists.newArrayList(log1, log2); groupTagLogDao.insert(log1, log2); for (final GroupTagLogModel log : logs) { final List<GroupTagLog> ls = query(log); Assert.assertTrue(ls.size() == 1); assertLog(log, ls.get(0)); } Assert.assertTrue(groupTagLogDao.query("create_time >= DATE_SUB(now(), INTERVAL ? MINUTE)", "2").size() >= logs.size()); Assert.assertTrue(groupTagLogDao.query("create_time > now()").size() == 0); Assert.assertTrue(groupTagLogDao.query("create_time <= now()").size() >= logs.size()); }
### Question: RouteRuleDao { protected void insertOrUpdate(RouteRuleModel... models) { insertOrUpdate(Lists.newArrayList(models)); } List<RouteRuleModel> query(); List<RouteRuleModel> select(RouteRuleModel filter); List<RouteRuleModel> select(List<Long> groupIds); static final RouteRuleDao INSTANCE; }### Answer: @Test public void testInsertOrUpdate() { RouteRuleModel routeRule = newRouteRule(); routeRuleDao.insertOrUpdate(routeRule); assertRouteRule(routeRule, query(routeRule)); routeRuleDao.insertOrUpdate(routeRule); assertRouteRule(routeRule, query(routeRule)); }
### Question: RouteRuleDao { protected void delete(final Long... ids) { delete(Lists.newArrayList(ids)); } List<RouteRuleModel> query(); List<RouteRuleModel> select(RouteRuleModel filter); List<RouteRuleModel> select(List<Long> groupIds); static final RouteRuleDao INSTANCE; }### Answer: @Test public void testDelete() { RouteRuleModel routeRule = newRouteRule(); routeRuleDao.insertOrUpdate(routeRule); RouteRuleModel copy1 = query(routeRule); routeRuleDao.delete(copy1.getId()); Assert.assertNull(query(routeRule, 0)); routeRuleDao.insertOrUpdate(routeRule); RouteRuleModel copy2 = query(routeRule); Assert.assertEquals(copy1.getId(), copy2.getId()); assertRouteRule(copy1, copy2); }
### Question: DiscoveryClientImpl implements DiscoveryClient { @Override public Service getService(final DiscoveryConfig discoveryConfig) { DiscoveryConfigChecker.DEFAULT.check(discoveryConfig, "discoveryConfig"); return serviceRepository.getService(discoveryConfig); } DiscoveryClientImpl(final String clientId, final ArtemisClientManagerConfig managerConfig); @Override Service getService(final DiscoveryConfig discoveryConfig); @Override void registerServiceChangeListener(final DiscoveryConfig discoveryConfig, final ServiceChangeListener listener); }### Answer: @Test public void testGetService() { final String serviceId = ArtemisClientConstants.RegistryService.Net.serviceKey; final DiscoveryConfig discoveryConfig = new DiscoveryConfig(serviceId); final Service service = _discoveryClientImpl.getService(discoveryConfig); Assert.assertEquals(serviceId, service.getServiceId()); Assert.assertNotNull(service.getInstances()); Assert.assertTrue(service.getInstances().size() >= 0); }
### Question: RouteRuleDao { public List<RouteRuleModel> select(RouteRuleModel filter) { ValueCheckers.notNull(filter, "filter"); Map<String, String> conditions = Maps.newHashMap(); conditions.put("id=?", filter.getId() == null ? null : Long.toString(filter.getId())); conditions.put("service_id=?", filter.getServiceId()); conditions.put("name=?", filter.getName()); conditions.put("status=?", filter.getStatus()); Set<String> removed = Sets.newHashSet(); for (String key : conditions.keySet()) { if (StringValues.isNullOrWhitespace(conditions.get(key))) { removed.add(key); } } conditions.keySet().removeAll(removed); return query(Joiner.on(" and ").join(conditions.keySet()), Lists.newArrayList(conditions.values())); } List<RouteRuleModel> query(); List<RouteRuleModel> select(RouteRuleModel filter); List<RouteRuleModel> select(List<Long> groupIds); static final RouteRuleDao INSTANCE; }### Answer: @Test public void testSelect() { RouteRuleModel routeRule = newRouteRule(); routeRuleDao.insertOrUpdate(routeRule); RouteRuleModel filter = new RouteRuleModel(); filter.setName(routeRule.getName()); filter.setServiceId(routeRule.getServiceId()); Assert.assertEquals(1, routeRuleDao.select(filter).size()); Assert.assertEquals(1, routeRuleDao.select(Lists.newArrayList(routeRuleDao.select(filter).get(0).getId())).size()); }
### Question: ServiceInstanceDao { public List<ServiceInstanceModel> query() { final String sql = "SELECT service_id, instance_id, ip, machine_name, metadata, port, protocol, region_id, zone_id, healthy_check_url, url, group_id from service_instance"; return DataConfig.jdbcTemplate().query(sql, new RowMapper<ServiceInstanceModel>() { @Override public ServiceInstanceModel mapRow(final ResultSet rs, final int rowNum) throws SQLException { ServiceInstanceModel serviceInstance = new ServiceInstanceModel(); serviceInstance.setServiceId(rs.getString(1)); serviceInstance.setInstanceId(rs.getString(2)); serviceInstance.setIp(rs.getString(3)); serviceInstance.setMachineName(rs.getString(4)); serviceInstance.setMetadata(rs.getString(5)); serviceInstance.setPort(rs.getInt(6)); serviceInstance.setProtocol(rs.getString(7)); serviceInstance.setRegionId(rs.getString(8)); serviceInstance.setZoneId(rs.getString(9)); serviceInstance.setHealthCheckUrl(rs.getString(10)); serviceInstance.setUrl(rs.getString(11)); serviceInstance.setGroupId(rs.getString(12)); return serviceInstance; } }); } private ServiceInstanceDao(); List<ServiceInstanceModel> query(); List<ServiceInstanceModel> select(ServiceInstanceModel filter); List<ServiceInstanceModel> select(List<Long> groupIds); static final ServiceInstanceDao INSTANCE; }### Answer: @Test public void testQuery() throws Exception { serviceInstanceDao.insertOrUpdate(newServiceInstance()); serviceInstanceDao.insertOrUpdate(newServiceInstance()); Assert.assertTrue(serviceInstanceDao.query().size() >= 2); }
### Question: ServiceInstanceDao { protected void delete(final Long... ids) { delete(Lists.newArrayList(ids)); } private ServiceInstanceDao(); List<ServiceInstanceModel> query(); List<ServiceInstanceModel> select(ServiceInstanceModel filter); List<ServiceInstanceModel> select(List<Long> groupIds); static final ServiceInstanceDao INSTANCE; }### Answer: @Test public void testDelete() throws Exception { ServiceInstanceModel serviceInstance = newServiceInstance(); serviceInstanceDao.insertOrUpdate(serviceInstance); ServiceInstanceModel newServiceInstance = query(serviceInstance); assertServiceInstance(serviceInstance, query(serviceInstance)); serviceInstanceDao.delete(newServiceInstance.getId()); Assert.assertNull(query(serviceInstance, 0)); }
### Question: ServiceInstanceDao { protected void deleteByFilters(final List<ServiceInstanceModel> filters) { checkInsertOrUpdateArgument(filters); DataConfig.jdbcTemplate().batchUpdate("delete from service_instance where service_id = ? and instance_id=?", new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return filters.size(); } @Override public void setValues(final PreparedStatement ps, final int i) throws SQLException { final ServiceInstanceModel filter = filters.get(i); ps.setString(1, filter.getServiceId()); ps.setString(2, filter.getInstanceId()); } }); } private ServiceInstanceDao(); List<ServiceInstanceModel> query(); List<ServiceInstanceModel> select(ServiceInstanceModel filter); List<ServiceInstanceModel> select(List<Long> groupIds); static final ServiceInstanceDao INSTANCE; }### Answer: @Test public void testDeleteByFilters() throws Exception { ServiceInstanceModel serviceInstance1 = newServiceInstance(); ServiceInstanceModel serviceInstance2 = newServiceInstance(); serviceInstanceDao.insertOrUpdate(serviceInstance1, serviceInstance2); query(serviceInstance1, 1); query(serviceInstance2, 1); serviceInstanceDao.deleteByFilters(Lists.newArrayList(serviceInstance1, serviceInstance2)); query(serviceInstance1, 0); query(serviceInstance2, 0); }
### Question: ServiceInstanceDao { protected void insertOrUpdate(final ServiceInstanceModel... groupInstances) { insertOrUpdate(Lists.newArrayList(groupInstances)); } private ServiceInstanceDao(); List<ServiceInstanceModel> query(); List<ServiceInstanceModel> select(ServiceInstanceModel filter); List<ServiceInstanceModel> select(List<Long> groupIds); static final ServiceInstanceDao INSTANCE; }### Answer: @Test public void testInsertOrUpdate() throws Exception { ServiceInstanceModel serviceInstance = newServiceInstance(); serviceInstanceDao.insertOrUpdate(serviceInstance); serviceInstanceDao.insertOrUpdate(serviceInstance); assertServiceInstance(serviceInstance, query(serviceInstance)); }
### Question: BusinessDao { @Transactional public void operationGroupOperation(OperationContext operationContext, GroupModel group, boolean isOperationComplete) { checkOperationContextArgument(operationContext); List<GroupOperationModel> groupOperation = Lists .newArrayList(new GroupOperationModel(groupDao.generateGroup(group).getId(), operationContext.getOperation())); if (isOperationComplete) { deleteGroupOperation(operationContext, groupOperation); } else { insertOrUpdateGroupOperation(operationContext, groupOperation); } } @Transactional void createServiceRouteRules(OperationContext operationContext, final String serviceId, List<RouteRuleInfo> routeRuleInfos); @Transactional void activateServiceRouteRules(OperationContext operationContext, final String serviceId, List<RouteRuleInfo> routeRuleInfos); @Transactional void operationGroupOperation(OperationContext operationContext, GroupModel group, boolean isOperationComplete); RouteRuleModel generateRouteRule(RouteRuleModel routeRuleModel); GroupModel generateGroup(GroupModel groupModel); @Transactional void updateGroupInstance(OperationContext operationContext, Long groupId, Set<String> instanceIds); void deleteGroupOperation(OperationContext operationContext, List<GroupOperationModel> groupOperations); void insertOrUpdateGroupOperation(OperationContext operationContext, List<GroupOperationModel> groupOperations); void deleteGroups(OperationContext operationContext, List<Long> groupIds); void insertOrUpdateGroups(OperationContext operationContext, List<GroupModel> groups); void insertGroups(OperationContext operationContext, List<GroupModel> groups); void deleteRouteRules(OperationContext operationContext, List<Long> routeRuleIds); void insertOrUpdateRouteRules(OperationContext operationContext, List<RouteRuleModel> routeRules); void insertRouteRules(OperationContext operationContext, List<RouteRuleModel> routeRules); void deleteRouteRuleGroups(OperationContext operationContext, List<Long> ids); void insertOrUpdateRouteRuleGroups(OperationContext operationContext, List<RouteRuleGroupModel> routeRuleGroups); void releaseRouteRuleGroups(OperationContext operationContext, List<RouteRuleGroupModel> routeRuleGroups); void publishRouteRuleGroups(OperationContext operationContext, List<RouteRuleGroupModel> routeRuleGroups); void deleteGroupInstances(OperationContext operationContext, List<Long> groupInstanceIds); void deleteGroupInstancesByFilter(OperationContext operationContext, List<GroupInstanceModel> groupInstances); void insertGroupInstances(OperationContext operationContext, List<GroupInstanceModel> groupInstanceModels); void deleteServiceInstances(OperationContext operationContext, List<Long> serviceInstanceIds); void deleteServiceInstancesByFilter(OperationContext operationContext, List<ServiceInstanceModel> serviceInstances); void insertServiceInstances(OperationContext operationContext, List<ServiceInstanceModel> serviceInstanceModels); static final BusinessDao INSTANCE; }### Answer: @Test public void testOperateGroupOperation() { GroupModel group = newGroup(); OperationContext operationContext = newOperationContext(); businessDao.operationGroupOperation(operationContext, group, false); GroupModel newGroup = query(group, 1); List<GroupOperationModel> operationModels = groupOperationDao.query("group_id=?", Lists.newArrayList(Long.toString(newGroup.getId()))); Assert.assertEquals(1, operationModels.size()); Assert.assertEquals(operationContext.getOperation(), operationModels.get(0).getOperation()); List<GroupOperationLog> logs = groupOperationLogDao .select(new GroupOperationLogModel(newGroup.getId(), operationContext.getOperation(), operationContext.getOperatorId()), false); Assert.assertEquals(1, logs.size()); Assert.assertEquals(operationContext.getOperation(), logs.get(0).getOperation()); Assert.assertEquals(operationContext.getToken(), logs.get(0).getToken()); businessDao.operationGroupOperation(operationContext, group, true); operationModels = groupOperationDao.query("group_id=?", Lists.newArrayList(Long.toString(newGroup.getId()))); Assert.assertEquals(0, operationModels.size()); logs = groupOperationLogDao.select(new GroupOperationLogModel(newGroup.getId(), operationContext.getOperation(), operationContext.getOperatorId()), true); Assert.assertEquals(1, logs.size()); Assert.assertEquals(operationContext.getOperation(), logs.get(0).getOperation()); Assert.assertEquals(operationContext.getToken(), logs.get(0).getToken()); }
### Question: BusinessDao { public void insertOrUpdateRouteRuleGroups(OperationContext operationContext, List<RouteRuleGroupModel> routeRuleGroups) { checkOperationContextArgument(operationContext); routeRuleGroupDao.insertOrUpdate(routeRuleGroups); routeRuleGroupLogDao.insert(RouteRuleGroups.newRouteRuleGroupLogs(operationContext, routeRuleGroups)); } @Transactional void createServiceRouteRules(OperationContext operationContext, final String serviceId, List<RouteRuleInfo> routeRuleInfos); @Transactional void activateServiceRouteRules(OperationContext operationContext, final String serviceId, List<RouteRuleInfo> routeRuleInfos); @Transactional void operationGroupOperation(OperationContext operationContext, GroupModel group, boolean isOperationComplete); RouteRuleModel generateRouteRule(RouteRuleModel routeRuleModel); GroupModel generateGroup(GroupModel groupModel); @Transactional void updateGroupInstance(OperationContext operationContext, Long groupId, Set<String> instanceIds); void deleteGroupOperation(OperationContext operationContext, List<GroupOperationModel> groupOperations); void insertOrUpdateGroupOperation(OperationContext operationContext, List<GroupOperationModel> groupOperations); void deleteGroups(OperationContext operationContext, List<Long> groupIds); void insertOrUpdateGroups(OperationContext operationContext, List<GroupModel> groups); void insertGroups(OperationContext operationContext, List<GroupModel> groups); void deleteRouteRules(OperationContext operationContext, List<Long> routeRuleIds); void insertOrUpdateRouteRules(OperationContext operationContext, List<RouteRuleModel> routeRules); void insertRouteRules(OperationContext operationContext, List<RouteRuleModel> routeRules); void deleteRouteRuleGroups(OperationContext operationContext, List<Long> ids); void insertOrUpdateRouteRuleGroups(OperationContext operationContext, List<RouteRuleGroupModel> routeRuleGroups); void releaseRouteRuleGroups(OperationContext operationContext, List<RouteRuleGroupModel> routeRuleGroups); void publishRouteRuleGroups(OperationContext operationContext, List<RouteRuleGroupModel> routeRuleGroups); void deleteGroupInstances(OperationContext operationContext, List<Long> groupInstanceIds); void deleteGroupInstancesByFilter(OperationContext operationContext, List<GroupInstanceModel> groupInstances); void insertGroupInstances(OperationContext operationContext, List<GroupInstanceModel> groupInstanceModels); void deleteServiceInstances(OperationContext operationContext, List<Long> serviceInstanceIds); void deleteServiceInstancesByFilter(OperationContext operationContext, List<ServiceInstanceModel> serviceInstances); void insertServiceInstances(OperationContext operationContext, List<ServiceInstanceModel> serviceInstanceModels); static final BusinessDao INSTANCE; }### Answer: @Test public void testInsertOrUpdateRouteRuleGroups() { businessDao.insertOrUpdateRouteRuleGroups(newOperationContext(), Lists.newArrayList(newRouteRuleGroup())); }
### Question: GroupOperationDao { public List<GroupOperationModel> query() { return DataConfig.jdbcTemplate().query("select group_id, operation from service_group_operation", new RowMapper<GroupOperationModel>() { @Override public GroupOperationModel mapRow(ResultSet rs, int i) throws SQLException { GroupOperationModel groupOperation = new GroupOperationModel(); groupOperation.setGroupId(rs.getLong(1)); groupOperation.setOperation(rs.getString(2)); return groupOperation; } }); } private GroupOperationDao(); List<GroupOperationModel> query(); static final GroupOperationDao INSTANCE; }### Answer: @Test public void testQuery() throws Exception { groupOperationDao.insertOrUpdate(newGroupOperation()); groupOperationDao.insertOrUpdate(newGroupOperation()); Assert.assertTrue(groupOperationDao.query().size() >= 2); }
### Question: GroupOperationDao { protected void delete(GroupOperationModel groupOperation) { delete(Lists.newArrayList(groupOperation)); } private GroupOperationDao(); List<GroupOperationModel> query(); static final GroupOperationDao INSTANCE; }### Answer: @Test public void testDelete() throws Exception { GroupOperationModel groupOperation = newGroupOperation(); groupOperationDao.insertOrUpdate(groupOperation); assertGroupOperation(groupOperation, query(groupOperation)); groupOperationDao.delete(groupOperation); Assert.assertNull(query(groupOperation)); }
### Question: DiscoveryClientImpl implements DiscoveryClient { @Override public void registerServiceChangeListener(final DiscoveryConfig discoveryConfig, final ServiceChangeListener listener) { DiscoveryConfigChecker.DEFAULT.check(discoveryConfig, "discoveryConfig"); NullArgumentChecker.DEFAULT.check(listener, "listener"); serviceRepository.registerServiceChangeListener(discoveryConfig, listener); } DiscoveryClientImpl(final String clientId, final ArtemisClientManagerConfig managerConfig); @Override Service getService(final DiscoveryConfig discoveryConfig); @Override void registerServiceChangeListener(final DiscoveryConfig discoveryConfig, final ServiceChangeListener listener); }### Answer: @Test public void registerServiceChangeListener() { final Map<String, DefaultServiceChangeListener> registerServices = Maps.newHashMap(); final String serviceId = Services.newServiceId(); registerServices.put("framework.soa.v1.registryservice", new DefaultServiceChangeListener()); registerServices.put("framework.soa.testservice.v2.testservice", new DefaultServiceChangeListener()); registerServices.put("framework.soa.test.v1.testportal", new DefaultServiceChangeListener()); registerServices.put(serviceId, new DefaultServiceChangeListener()); for (final Map.Entry<String, DefaultServiceChangeListener> entry : registerServices.entrySet()) { final DiscoveryConfig discoveryConfig = new DiscoveryConfig(entry.getKey()); _discoveryClientImpl.registerServiceChangeListener(discoveryConfig, entry.getValue()); } for (final Map.Entry<String, DefaultServiceChangeListener> entry : registerServices.entrySet()) { final List<ServiceChangeEvent> serviceChangeEvents = entry.getValue().getServiceChangeEvents(); Assert.assertEquals(0, serviceChangeEvents.size()); } }
### Question: GroupOperationDao { protected void insertOrUpdate(GroupOperationModel... operationModels) { insertOrUpdate(Lists.newArrayList(operationModels)); } private GroupOperationDao(); List<GroupOperationModel> query(); static final GroupOperationDao INSTANCE; }### Answer: @Test public void testInsertOrUpdate() throws Exception { GroupOperationModel groupOperation = newGroupOperation(); groupOperationDao.insertOrUpdate(groupOperation); groupOperationDao.insertOrUpdate(groupOperation); assertGroupOperation(groupOperation, query(groupOperation)); }
### Question: GroupInstanceDao { protected void delete(final Long... ids) { delete(Lists.newArrayList(ids)); } private GroupInstanceDao(); List<GroupInstanceModel> query(); List<GroupInstanceModel> select(GroupInstanceModel filter); List<GroupInstanceModel> select(List<Long> groupIds); static final GroupInstanceDao INSTANCE; }### Answer: @Test public void testDelete() { GroupInstanceModel groupInstance = newGroupInstance(); groupInstanceDao.insert(groupInstance); GroupInstanceModel copy1 = query(groupInstance); groupInstanceDao.delete(copy1.getId()); Assert.assertNull(query(groupInstance, 0)); }
### Question: GroupInstanceDao { protected void deleteByFilters(final List<GroupInstanceModel> filters){ checkInsertOrUpdateArgument(filters); DataConfig.jdbcTemplate().batchUpdate("delete from service_group_instance where group_id = ? and instance_id=?", new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return filters.size(); } @Override public void setValues(final PreparedStatement ps, final int i) throws SQLException { final GroupInstanceModel filter = filters.get(i); ps.setLong(1, filter.getGroupId()); ps.setString(2, filter.getInstanceId()); } }); } private GroupInstanceDao(); List<GroupInstanceModel> query(); List<GroupInstanceModel> select(GroupInstanceModel filter); List<GroupInstanceModel> select(List<Long> groupIds); static final GroupInstanceDao INSTANCE; }### Answer: @Test public void testDeleteByFilters() { GroupInstanceModel groupInstance1 = newGroupInstance(); GroupInstanceModel groupInstance2 = newGroupInstance(); groupInstanceDao.insert(groupInstance1, groupInstance2); query(groupInstance1, 1); query(groupInstance2, 1); groupInstanceDao.deleteByFilters(Lists.newArrayList(groupInstance1, groupInstance2)); query(groupInstance1, 0); query(groupInstance2, 0); }
### Question: GroupInstanceDao { public List<GroupInstanceModel> select(GroupInstanceModel filter) { ValueCheckers.notNull(filter, "filter"); Map<String, String> conditions = Maps.newHashMap(); conditions.put("id=?", filter.getId() == null ? null : Long.toString(filter.getId())); conditions.put("group_id=?", filter.getGroupId() == null ? null : Long.toString(filter.getGroupId())); conditions.put("instance_id=?", filter.getInstanceId()); Set<String> removed = Sets.newHashSet(); for (String key : conditions.keySet()) { if (StringValues.isNullOrWhitespace(conditions.get(key))) { removed.add(key); } } conditions.keySet().removeAll(removed); return query(Joiner.on(" and ").join(conditions.keySet()), Lists.newArrayList(conditions.values())); } private GroupInstanceDao(); List<GroupInstanceModel> query(); List<GroupInstanceModel> select(GroupInstanceModel filter); List<GroupInstanceModel> select(List<Long> groupIds); static final GroupInstanceDao INSTANCE; }### Answer: @Test public void testSelect() { GroupInstanceModel groupInstance = newGroupInstance(); groupInstanceDao.insert(groupInstance); GroupInstanceModel filter = new GroupInstanceModel(); filter.setGroupId(groupInstance.getGroupId()); filter.setInstanceId(groupInstance.getInstanceId()); assertGroupInstance(groupInstance, groupInstanceDao.select(filter).get(0)); }
### Question: RouteRuleGroupDao { protected void insertOrUpdate(final RouteRuleGroupModel... models) { insertOrUpdate(Lists.newArrayList(models)); } List<RouteRuleGroupModel> query(); RouteRuleGroupModel generateGroup(RouteRuleGroupModel routeRuleGroup); List<RouteRuleGroupModel> select(RouteRuleGroupModel filter); List<RouteRuleGroupModel> select(List<Long> groupIds); static final RouteRuleGroupDao INSTANCE; }### Answer: @Test public void testInsertOrUpdate() { for (RouteRuleGroupModel routeRuleGroup : newRouteRuleGroups()) { routeRuleGroupDao.insertOrUpdate(routeRuleGroup); assertRouteRuleGroup(routeRuleGroup, query(routeRuleGroup)); routeRuleGroup.setUnreleasedWeight(null); routeRuleGroupDao.insertOrUpdate(routeRuleGroup); assertRouteRuleGroup(routeRuleGroup, query(routeRuleGroup)); } }
### Question: RouteRuleGroupDao { protected void insert(final RouteRuleGroupModel... models) { insert(Lists.newArrayList(models)); } List<RouteRuleGroupModel> query(); RouteRuleGroupModel generateGroup(RouteRuleGroupModel routeRuleGroup); List<RouteRuleGroupModel> select(RouteRuleGroupModel filter); List<RouteRuleGroupModel> select(List<Long> groupIds); static final RouteRuleGroupDao INSTANCE; }### Answer: @Test public void testInsert() { for (RouteRuleGroupModel routeRuleGroup : newRouteRuleGroups()) { routeRuleGroupDao.insert(routeRuleGroup); assertRouteRuleGroup(routeRuleGroup, query(routeRuleGroup)); routeRuleGroup.setUnreleasedWeight(null); routeRuleGroupDao.insert(routeRuleGroup); assertRouteRuleGroup(routeRuleGroup, query(routeRuleGroup)); } }
### Question: RouteRuleGroupDao { protected void delete(final Long... ids) { delete(Lists.newArrayList(ids)); } List<RouteRuleGroupModel> query(); RouteRuleGroupModel generateGroup(RouteRuleGroupModel routeRuleGroup); List<RouteRuleGroupModel> select(RouteRuleGroupModel filter); List<RouteRuleGroupModel> select(List<Long> groupIds); static final RouteRuleGroupDao INSTANCE; }### Answer: @Test public void testDelete() { for (RouteRuleGroupModel routeRuleGroup : newRouteRuleGroups()) { routeRuleGroupDao.insertOrUpdate(routeRuleGroup); RouteRuleGroupModel copy = query(routeRuleGroup); routeRuleGroupDao.delete(copy.getId()); Assert.assertNull(query(routeRuleGroup, 0)); } }
### Question: RouteRuleGroupDao { public List<RouteRuleGroupModel> select(RouteRuleGroupModel filter) { ValueCheckers.notNull(filter, "filter"); Map<String, Long> conditions = Maps.newHashMap(); conditions.put("id=?", filter.getId()); conditions.put("route_rule_id=?", filter.getRouteRuleId()); conditions.put("group_id=?", filter.getGroupId()); Set<String> removed = Sets.newHashSet(); for (String key : conditions.keySet()) { if (conditions.get(key) == null) { removed.add(key); } } conditions.keySet().removeAll(removed); return query(Joiner.on(" and ").join(conditions.keySet()), Lists.newArrayList(conditions.values())); } List<RouteRuleGroupModel> query(); RouteRuleGroupModel generateGroup(RouteRuleGroupModel routeRuleGroup); List<RouteRuleGroupModel> select(RouteRuleGroupModel filter); List<RouteRuleGroupModel> select(List<Long> groupIds); static final RouteRuleGroupDao INSTANCE; }### Answer: @Test public void testSelect() { for (RouteRuleGroupModel routeRuleGroup : newRouteRuleGroups()) { routeRuleGroupDao.insertOrUpdate(routeRuleGroup); RouteRuleGroupModel filter = new RouteRuleGroupModel(); filter.setGroupId(routeRuleGroup.getGroupId()); Assert.assertEquals(1, routeRuleGroupDao.select(filter).size()); Assert.assertEquals(1, routeRuleGroupDao.select(Lists.newArrayList(routeRuleGroupDao.select(filter).get(0).getId())).size()); } }
### Question: RouteRuleGroupDao { protected void release(final List<RouteRuleGroupModel> models) { checkReleaseArgument(models); DataConfig.jdbcTemplate().batchUpdate("update service_route_rule_group set weight = unreleased_weight where route_rule_id=? and group_id=?", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { RouteRuleGroupModel model = models.get(i); ps.setLong(1, model.getRouteRuleId()); ps.setLong(2, model.getGroupId()); } @Override public int getBatchSize() { return models.size(); } }); } List<RouteRuleGroupModel> query(); RouteRuleGroupModel generateGroup(RouteRuleGroupModel routeRuleGroup); List<RouteRuleGroupModel> select(RouteRuleGroupModel filter); List<RouteRuleGroupModel> select(List<Long> groupIds); static final RouteRuleGroupDao INSTANCE; }### Answer: @Test public void testRelease() { for (RouteRuleGroupModel routeRuleGroup : newRouteRuleGroups()) { routeRuleGroupDao.insertOrUpdate(routeRuleGroup); RouteRuleGroupModel valueBeforeReleased = query(routeRuleGroup); assertRouteRuleGroup(routeRuleGroup, valueBeforeReleased); if (routeRuleGroup.getUnreleasedWeight() != null) { Assert.assertNull(valueBeforeReleased.getWeight()); Assert.assertNotEquals(routeRuleGroup.getUnreleasedWeight(), valueBeforeReleased.getWeight()); } else { Assert.assertEquals(routeRuleGroup.getUnreleasedWeight(), valueBeforeReleased.getWeight()); } routeRuleGroupDao.release(Lists.newArrayList(valueBeforeReleased)); RouteRuleGroupModel valueAfterReleased = query(routeRuleGroup); assertRouteRuleGroup(routeRuleGroup, valueAfterReleased); Assert.assertEquals(routeRuleGroup.getUnreleasedWeight(), valueAfterReleased.getWeight()); } }
### Question: RouteRuleGroupDao { protected void publish(final RouteRuleGroupModel... models) { publish(Lists.newArrayList(models)); } List<RouteRuleGroupModel> query(); RouteRuleGroupModel generateGroup(RouteRuleGroupModel routeRuleGroup); List<RouteRuleGroupModel> select(RouteRuleGroupModel filter); List<RouteRuleGroupModel> select(List<Long> groupIds); static final RouteRuleGroupDao INSTANCE; }### Answer: @Test public void testPublish() { for (RouteRuleGroupModel routeRuleGroup : newRouteRuleGroups()) { routeRuleGroupDao.publish(routeRuleGroup); RouteRuleGroupModel published = query(routeRuleGroup); Assert.assertEquals(routeRuleGroup.getRouteRuleId(), published.getRouteRuleId()); Assert.assertEquals(routeRuleGroup.getGroupId(), published.getGroupId()); Assert.assertEquals(null, published.getUnreleasedWeight()); Assert.assertEquals(routeRuleGroup.getWeight(), published.getWeight()); } }
### Question: ArtemisDiscoveryHttpClient extends ArtemisHttpClient { public Service getService(final DiscoveryConfig discoveryConfig) { Preconditions.checkArgument(discoveryConfig != null, "discoveryConfig"); final List<Service> services = getServices(Lists.newArrayList(discoveryConfig)); if (services.size() > 0) { return services.get(0); } throw new RuntimeException("not found any service by discoveryConfig:" + discoveryConfig); } ArtemisDiscoveryHttpClient(final ArtemisClientConfig config); Service getService(final DiscoveryConfig discoveryConfig); List<Service> getServices(final List<DiscoveryConfig> discoveryConfigs); }### Answer: @Test public void testGetService_ShouldReturnEmptyInstances() { Assert.assertTrue(CollectionUtils.isEmpty(_client.getService(Services.newDiscoverConfig()).getInstances())); } @Test public void testGetService_ShouldReturnIntances() throws Exception { final Service service = _client.getService(new DiscoveryConfig(ArtemisClientConstants.RegistryService.Net.serviceKey)); Assert.assertNotNull(service); Assert.assertTrue(service.getInstances().size() > 0); }
### Question: GroupOperationLogDao { public void insert(final GroupOperationLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private GroupOperationLogDao(); List<GroupOperationLog> select(GroupOperationLogModel filter, Boolean complete); List<GroupOperationLog> query(final String condition, final List<Object> args); void insert(final GroupOperationLogModel... logs); void insert(final List<GroupOperationLogModel> logs); static final GroupOperationLogDao INSTANCE; }### Answer: @Test public void testInsert() { final GroupOperationLogModel log1 = newModel(); final GroupOperationLogModel log2 = newModel(); log1.setComplete(true); log2.setComplete(true); final List<GroupOperationLogModel> logs = Lists.newArrayList(log1, log2); groupOperationLogDao.insert(log1, log2); for (final GroupOperationLogModel log : logs) { final List<GroupOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertLog(log, logModels.get(0)); } log1.setComplete(false); log2.setComplete(false); groupOperationLogDao.insert(log1, log2); for (final GroupOperationLogModel log : logs) { final List<GroupOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertLog(log, logModels.get(0)); } }
### Question: RouteRuleGroupLogDao { public void insert(final RouteRuleGroupLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private RouteRuleGroupLogDao(); List<RouteRuleGroupLog> select(RouteRuleGroupLogModel filter); List<RouteRuleGroupLog> query(final String condition, final List<Object> args); void insert(final RouteRuleGroupLogModel... logs); void insert(final List<RouteRuleGroupLogModel> logs); static final RouteRuleGroupLogDao INSTANCE; }### Answer: @Test public void testInsert() { final RouteRuleGroupLogModel log1 = newModel(); final RouteRuleGroupLogModel log2 = newModel(); final List<RouteRuleGroupLogModel> logs = Lists.newArrayList(log1, log2); routeRuleGroupLogDao.insert(log1, log2); for (final RouteRuleGroupLogModel log : logs) { final List<RouteRuleGroupLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertLog(log, logModels.get(0)); } }
### Question: GroupInstanceLogDao { protected void insert(final GroupInstanceLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private GroupInstanceLogDao(); List<GroupInstanceLog> select(GroupInstanceLogModel filter); List<GroupInstanceLog> query(final String condition, final List<Object> args); static final GroupInstanceLogDao INSTANCE; }### Answer: @Test public void testInsert() { final GroupInstanceLogModel log1 = newModel(); final GroupInstanceLogModel log2 = newModel(); final List<GroupInstanceLogModel> logs = Lists.newArrayList(log1, log2); groupInstanceLogDao.insert(log1, log2); for (final GroupInstanceLogModel log : logs) { final List<GroupInstanceLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertLog(log, logModels.get(0)); } }
### Question: GroupLogDao { public void insert(final GroupLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private GroupLogDao(); List<GroupLog> select(GroupLogModel filter); List<GroupLog> query(final String condition, final List<Object> args); void insert(final GroupLogModel... logs); void insert(final List<GroupLogModel> logs); static final GroupLogDao INSTANCE; }### Answer: @Test public void testInsert() { final GroupLogModel log1 = newModel(); final GroupLogModel log2 = newModel(); final List<GroupLogModel> logs = Lists.newArrayList(log1, log2); groupLogDao.insert(log1, log2); for (final GroupLogModel log : logs) { final List<GroupLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertLog(log, logModels.get(0)); } }
### Question: ZoneOperationLogDao { public void insert(final ZoneOperationLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private ZoneOperationLogDao(); List<ZoneOperationLog> select(ZoneOperationLogModel filter, Boolean complete); List<ZoneOperationLog> query(final String condition, final List<String> args); void insert(final ZoneOperationLogModel... logs); void insert(final List<ZoneOperationLogModel> logs); static final ZoneOperationLogDao INSTANCE; }### Answer: @Test public void testInsert() { final ZoneOperationLogModel log1 = newZoneOperationLogModel(); final ZoneOperationLogModel log2 = newZoneOperationLogModel(); log1.setComplete(true); log2.setComplete(true); final List<ZoneOperationLogModel> logs = Lists.newArrayList(log1, log2); zoneOperationLogDao.insert(log1, log2); for (final ZoneOperationLogModel log : logs) { final List<ZoneOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertZoneOperationLog(log, logModels.get(0)); } log1.setComplete(false); log2.setComplete(false); zoneOperationLogDao.insert(log1, log2); for (final ZoneOperationLogModel log : logs) { final List<ZoneOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertZoneOperationLog(log, logModels.get(0)); } }
### Question: ZoneOperationDao { public void insertOrUpdate(ZoneOperationModel... operationModels) { insertOrUpdate(Lists.newArrayList(operationModels)); } private ZoneOperationDao(); List<ZoneOperationModel> query(); void delete(final ZoneOperationModel... zoneOperations); void delete(final List<ZoneOperationModel> zoneOperations); void insertOrUpdate(ZoneOperationModel... operationModels); void insertOrUpdate(final List<ZoneOperationModel> models); List<ZoneOperationModel> select(ZoneOperationModel filter); static final ZoneOperationDao INSTANCE; }### Answer: @Test public void testInsertOrUpdate() { ZoneOperationModel zone = newZoneOperation(); zoneOperationDao.insertOrUpdate(zone); assertZoneOperation(zone, query(zone)); zoneOperationDao.insertOrUpdate(zone); assertZoneOperation(zone, query(zone)); }
### Question: ZoneOperationDao { public void delete(final ZoneOperationModel... zoneOperations) { delete(Lists.newArrayList(zoneOperations)); } private ZoneOperationDao(); List<ZoneOperationModel> query(); void delete(final ZoneOperationModel... zoneOperations); void delete(final List<ZoneOperationModel> zoneOperations); void insertOrUpdate(ZoneOperationModel... operationModels); void insertOrUpdate(final List<ZoneOperationModel> models); List<ZoneOperationModel> select(ZoneOperationModel filter); static final ZoneOperationDao INSTANCE; }### Answer: @Test public void testDelete() { ZoneOperationModel zone = newZoneOperation(); zoneOperationDao.insertOrUpdate(zone); ZoneOperationModel copy1 = query(zone); zoneOperationDao.delete(zone); Assert.assertNull(query(zone, 0)); zoneOperationDao.insertOrUpdate(zone); ZoneOperationModel copy2 = query(zone); assertZoneOperation(copy1, copy2); }
### Question: ZoneOperationDao { public List<ZoneOperationModel> select(ZoneOperationModel filter) { ValueCheckers.notNull(filter, "filter"); Map<String, String> conditions = Maps.newHashMap(); conditions.put("id=?", filter.getId() == null ? null : Long.toString(filter.getId())); conditions.put("service_id=?", filter.getServiceId()); conditions.put("region_id=?", filter.getRegionId()); conditions.put("zone_id=?", filter.getZoneId()); conditions.put("operation=?", filter.getOperation()); Set<String> removed = Sets.newHashSet(); for (String key : conditions.keySet()) { if (StringValues.isNullOrWhitespace(conditions.get(key))) { removed.add(key); } } conditions.keySet().removeAll(removed); return query(Joiner.on(" and ").join(conditions.keySet()), Lists.newArrayList(conditions.values())); } private ZoneOperationDao(); List<ZoneOperationModel> query(); void delete(final ZoneOperationModel... zoneOperations); void delete(final List<ZoneOperationModel> zoneOperations); void insertOrUpdate(ZoneOperationModel... operationModels); void insertOrUpdate(final List<ZoneOperationModel> models); List<ZoneOperationModel> select(ZoneOperationModel filter); static final ZoneOperationDao INSTANCE; }### Answer: @Test public void testSelect() { ZoneOperationModel zone = newZoneOperation(); zoneOperationDao.insertOrUpdate(zone); ZoneOperationModel filter = new ZoneOperationModel(); filter.setServiceId(zone.getServiceId()); filter.setZoneId(zone.getZoneId()); assertZoneOperation(zone, zoneOperationDao.select(filter).get(0)); }
### Question: SearchTree { public V get(List<K> cascadingFactors) { if (CollectionValues.isNullOrEmpty(cascadingFactors)) { return value; } List<K> factors = Lists.newArrayList(cascadingFactors); SearchTree<K, V> g = children.get(factors.remove(0)); if (g == null) { return defaultChildrenValue; } return g.get(factors); } V getValue(); void setValue(V value); V getDefaultChildrenValue(); void setDefaultChildrenValue(V defaultChildrenValue); V get(List<K> cascadingFactors); V first(List<K> cascadingFactors); void add(List<K> cascadingFactors, V value); void put(K childKey, SearchTree<K, V> searchTree); }### Answer: @Test public void testGet() throws Exception { Assert.assertNull(tree.get(null)); Assert.assertNull(tree.get(new ArrayList<String>())); Assert.assertEquals("key1", tree.get(key1)); Assert.assertEquals(null, tree.get(key2)); Assert.assertEquals("key3", tree.get(key3)); Assert.assertEquals(null, tree.get(key4)); Assert.assertEquals("key5", tree.get(key5)); Assert.assertEquals(null, tree.get(key6)); Assert.assertEquals("key7", tree.get(key7)); Assert.assertEquals(null, tree.get(key8)); }
### Question: SearchTree { public void add(List<K> cascadingFactors, V value) { if (CollectionValues.isNullOrEmpty(cascadingFactors)) { this.value = value; return; } List<K> factors = Lists.newArrayList(cascadingFactors); K factor = factors.remove(0); ValueCheckers.notNull(factor, "factor"); SearchTree<K, V> child = children.get(factor); if (child == null) { child = new SearchTree<>(); children.put(factor, child); } child.add(factors, value); } V getValue(); void setValue(V value); V getDefaultChildrenValue(); void setDefaultChildrenValue(V defaultChildrenValue); V get(List<K> cascadingFactors); V first(List<K> cascadingFactors); void add(List<K> cascadingFactors, V value); void put(K childKey, SearchTree<K, V> searchTree); }### Answer: @Test public void testAdd() throws Exception { SearchTree<String,String> tree = new SearchTree<>(); tree.add(null, null); }
### Question: SearchTree { public V first(List<K> cascadingFactors) { if (value != null || CollectionValues.isNullOrEmpty(cascadingFactors)) { return value; } List<K> factors = Lists.newArrayList(cascadingFactors); SearchTree<K, V> g = children.get(factors.remove(0)); if (g == null) { return defaultChildrenValue; } return g.first(factors); } V getValue(); void setValue(V value); V getDefaultChildrenValue(); void setDefaultChildrenValue(V defaultChildrenValue); V get(List<K> cascadingFactors); V first(List<K> cascadingFactors); void add(List<K> cascadingFactors, V value); void put(K childKey, SearchTree<K, V> searchTree); }### Answer: @Test public void testFirst() throws Exception { Assert.assertNull(tree.first(null)); Assert.assertNull(tree.first(new ArrayList<String>())); Assert.assertEquals("key1", tree.first(key1)); Assert.assertEquals("key1", tree.first(key2)); Assert.assertEquals("key1", tree.first(key3)); Assert.assertEquals("key1", tree.first(key4)); Assert.assertEquals("key5", tree.first(key5)); Assert.assertEquals("key1", tree.first(key6)); Assert.assertEquals("key1", tree.first(key7)); Assert.assertEquals("key1", tree.first(key8)); }
### Question: ServiceGroups { public static int fixWeight(Integer weight) { if (weight == null || weight < MIN_WEIGHT_VALUE) { return DEFAULT_WEIGHT_VALUE; } if (weight > MAX_WEIGHT_VALUE) { return MAX_WEIGHT_VALUE; } return weight; } private ServiceGroups(); static int fixWeight(Integer weight); static boolean isDefaultGroupId(String groupId); static boolean isGroupCanaryInstance(String groupKey, Instance instance); static boolean isLocalZone(ServiceGroup serviceGroup); static final String DEFAULT_GROUP_ID; static final int MAX_WEIGHT_VALUE; static final int MIN_WEIGHT_VALUE; static final int DEFAULT_WEIGHT_VALUE; }### Answer: @Test public void testFixWeight() { Assert.assertEquals(ServiceGroups.DEFAULT_WEIGHT_VALUE, ServiceGroups.fixWeight(null)); Assert.assertEquals(ServiceGroups.MIN_WEIGHT_VALUE, ServiceGroups.fixWeight(ServiceGroups.MIN_WEIGHT_VALUE)); Assert.assertEquals(ServiceGroups.MAX_WEIGHT_VALUE, ServiceGroups.fixWeight(ServiceGroups.MAX_WEIGHT_VALUE)); Assert.assertEquals(ServiceGroups.MIN_WEIGHT_VALUE + 1, ServiceGroups.fixWeight(ServiceGroups.MIN_WEIGHT_VALUE + 1)); Assert.assertEquals(ServiceGroups.MAX_WEIGHT_VALUE - 1, ServiceGroups.fixWeight(ServiceGroups.MAX_WEIGHT_VALUE - 1)); Assert.assertEquals(ServiceGroups.DEFAULT_WEIGHT_VALUE, ServiceGroups.fixWeight(ServiceGroups.MIN_WEIGHT_VALUE - 1)); Assert.assertEquals(ServiceGroups.MAX_WEIGHT_VALUE, ServiceGroups.fixWeight(ServiceGroups.MAX_WEIGHT_VALUE + 1)); }
### Question: ArtemisDiscoveryHttpClient extends ArtemisHttpClient { public List<Service> getServices(final List<DiscoveryConfig> discoveryConfigs) { Preconditions.checkArgument(!CollectionUtils.isEmpty(discoveryConfigs), "discoveryConfigs should not be null or empty"); final LookupRequest request = new LookupRequest(discoveryConfigs, DeploymentConfig.regionId(), DeploymentConfig.zoneId()); final LookupResponse response = this.request(RestPaths.DISCOVERY_LOOKUP_FULL_PATH, request, LookupResponse.class); ResponseStatus status = response.getResponseStatus(); logEvent(status, "discovery", "lookup"); if (ResponseStatusUtil.isSuccess(status)) return response.getServices(); throw new RuntimeException("lookup services failed. " + status); } ArtemisDiscoveryHttpClient(final ArtemisClientConfig config); Service getService(final DiscoveryConfig discoveryConfig); List<Service> getServices(final List<DiscoveryConfig> discoveryConfigs); }### Answer: @Test public void testGetServices() { final String serviceId = Services.newServiceId(); final List<String> serviceIds = Lists.newArrayList(serviceId, ArtemisClientConstants.RegistryService.Net.serviceKey); final List<DiscoveryConfig> discoveryConfigs = Lists.newArrayList(new DiscoveryConfig(serviceId), new DiscoveryConfig(ArtemisClientConstants.RegistryService.Net.serviceKey)); final List<Service> services = _client.getServices(discoveryConfigs); Assert.assertEquals(discoveryConfigs.size(), services.size()); for (final Service service : services) { Assert.assertTrue(serviceIds.contains(service.getServiceId())); if (ArtemisClientConstants.RegistryService.Net.serviceKey .equals(service.getServiceId())) { Assert.assertTrue(service.getInstances().size() > 0); } else { Assert.assertTrue((service.getInstances() == null) || (service.getInstances().size() == 0)); } } }
### Question: ServiceDiscovery { protected void reload(DiscoveryConfig... configs) { reload(Lists.newArrayList(configs)); } ServiceDiscovery(final ServiceRepository serviceRepository, final ArtemisClientConfig config); void registerDiscoveryConfig(DiscoveryConfig config); Service getService(DiscoveryConfig config); }### Answer: @Test public void testReload() throws Exception { final ServiceRepository serviceRepository = new ServiceRepository(ArtemisClientConstants.DiscoveryClientConfig); final List<Service> services = Lists.newArrayList(); Assert.assertEquals(0, services.size()); Set<String> serviceKeys = Sets.newHashSet(ArtemisClientConstants.RegistryService.Net.serviceKey, ArtemisClientConstants.RegistryService.Java.serviceKey); Map<String, ServiceChangeListener> serviceChangeListeners = Maps.newHashMap(); for (String serviceKey : serviceKeys) { DefaultServiceChangeListener listener = new DefaultServiceChangeListener(); DiscoveryConfig discoveryConfig = new DiscoveryConfig(serviceKey); serviceChangeListeners.put(serviceKey, listener); serviceRepository.registerServiceChangeListener(discoveryConfig, listener); serviceRepository.serviceDiscovery.reload(discoveryConfig); Assert.assertTrue(listener.getServiceChangeEvents().size() >= 1); for (ServiceChangeEvent event : listener.getServiceChangeEvents()) { Assert.assertEquals(InstanceChange.ChangeType.RELOAD, event.changeType()); Assert.assertEquals(serviceKey, event.changedService().getServiceId()); } } }
### Question: BtpRuntimeException extends RuntimeException { public BtpError toBtpError(long requestId) { return toBtpError(requestId, new BtpSubProtocols()); } BtpRuntimeException(); BtpRuntimeException(BtpErrorCode code, String message); BtpRuntimeException(BtpErrorCode code, String message, Throwable cause); BtpRuntimeException(Throwable cause); BtpErrorCode getCode(); Instant getTriggeredAt(); BtpError toBtpError(long requestId); BtpError toBtpError(long requestId, BtpSubProtocols subProtocols); }### Answer: @Test public void toBtpError() { final BtpRuntimeException exception = new BtpRuntimeException(BtpErrorCode.F00_NotAcceptedError, ERROR_MESSAGE); final BtpError error = exception.toBtpError(REQUEST_ID); assertThat(error.getErrorCode()).isEqualTo(BtpErrorCode.F00_NotAcceptedError); assertThat(error.getTriggeredAt()).isEqualTo(exception.getTriggeredAt()); assertThat(error.getErrorData().length).isEqualTo(0); }
### Question: IlpOverHttpLink extends AbstractLink<IlpOverHttpLinkSettings> implements Link<IlpOverHttpLinkSettings> { public void testConnection() { try { final Request okHttpRequest = this.constructSendPacketRequest(UNFULFILLABLE_PACKET); try (Response response = okHttpClient.newCall(okHttpRequest).execute()) { if (response.isSuccessful()) { boolean responseHasOctetStreamContentType = response.headers(CONTENT_TYPE).stream() .findFirst() .filter(OCTET_STREAM_STRING::equals) .isPresent(); if (responseHasOctetStreamContentType) { logger.info("Remote peer-link supports ILP-over-HTTP. url={} responseHeaders={}", outgoingUrl, response ); } else { logger.warn("Remote peer-link supports ILP-over-HTTP but uses wrong ContentType. url={} " + "response={}", outgoingUrl, response ); } } else { if (response.code() == 406 || response.code() == 415) { throw new LinkException( String.format("Remote peer-link DOES NOT support ILP-over-HTTP. url=%s response=%s", outgoingUrl, response ), getLinkId() ); } else { throw new LinkException( String.format("Unable to connect to ILP-over-HTTP. url=%s response=%s", outgoingUrl, response ), getLinkId() ); } } } } catch (IOException e) { throw new LinkException(e.getMessage(), e, getLinkId()); } } IlpOverHttpLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final HttpUrl outgoingUrl, final OkHttpClient okHttpClient, final ObjectMapper objectMapper, final CodecContext ilpCodecContext, final BearerTokenSupplier bearerTokenSupplier ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); void testConnection(); @Override String toString(); HttpUrl getOutgoingUrl(); static final String LINK_TYPE_STRING; static final LinkType LINK_TYPE; }### Answer: @Test public void testConnectionThrowsUnexpected() throws Exception { Call call = mock(Call.class); when(httpClientMock.newCall(any())).thenReturn(call); when(call.execute()).thenThrow(new IOException("hey a penny")); expectedException.expect(LinkException.class); expectedException.expectMessage("hey a penny"); link.testConnection(); } @Test public void testConnection() throws Exception { mockCall(200); link.testConnection(); } @Test public void testConnectionFailsOn406() throws Exception { mockCall(406); expectedException.expect(LinkException.class); expectedException.expectMessage("Remote peer-link DOES NOT support ILP-over-HTTP. " + "url=https: + "response=Response{" + "protocol=h2, " + "code=406, " + "message=stop asking me to set stuff, " + "url=https: + "}"); link.testConnection(); } @Test public void testConnectionFailsOn415() throws Exception { mockCall(415); expectedException.expect(LinkException.class); expectedException.expectMessage("Remote peer-link DOES NOT support ILP-over-HTTP. " + "url=https: + "response=Response{" + "protocol=h2, " + "code=415, " + "message=stop asking me to set stuff, " + "url=https: + "}"); link.testConnection(); } @Test public void testConnectionFailsOnOther() throws Exception { mockCall(422); expectedException.expect(LinkException.class); expectedException.expectMessage("Unable to connect to ILP-over-HTTP. " + "url=https: + "response=Response{" + "protocol=h2, " + "code=422, " + "message=stop asking me to set stuff, " + "url=https: + "}"); link.testConnection(); }
### Question: LinkSettingsUtils { public static Map<String, Object> flattenSettings(Map<String, Object> settings) { return flattenSettings("", settings); } static Map<String, Object> flattenSettings(Map<String, Object> settings); static Optional<IlpOverHttpLinkSettings.AuthType> getIncomingAuthType(Map<String, Object> customSettings); static Optional<IlpOverHttpLinkSettings.AuthType> getOutgoingAuthType(Map<String, Object> customSettings); static void validate(AuthenticatedLinkSettings linkSettings); }### Answer: @Test public void flattenSettingsAlreadyFlattened() { assertThat(LinkSettingsUtils.flattenSettings(flattenedSettings)).isEqualTo(flattenedSettings); } @Test public void flattenSettings() { Map<String, Object> grandsonSettings = ImmutableMap.of("name", "fizz", "age", 15); Map<String, Object> grandDaughterSettings = ImmutableMap.of("name", "buzz", "age", 20); Map<String, Object> sonSettings = ImmutableMap.of("name", "bar", "age", 50, "grandson", grandsonSettings, "granddaughter", grandDaughterSettings); Map<String, Object> parentSettings = ImmutableMap.of("name", "foo", "age", 100, "son", sonSettings); Map<String, Object> settings = ImmutableMap.of("parent", parentSettings); assertThat(LinkSettingsUtils.flattenSettings(settings)).isEqualTo(flattenedSettings); }
### Question: LinkSettingsUtils { public static Optional<IlpOverHttpLinkSettings.AuthType> getIncomingAuthType(Map<String, Object> customSettings) { return Optional.ofNullable(flattenSettings(customSettings).get(IncomingLinkSettings.HTTP_INCOMING_AUTH_TYPE)) .map(Object::toString) .map(String::toUpperCase) .map(IlpOverHttpLinkSettings.AuthType::valueOf); } static Map<String, Object> flattenSettings(Map<String, Object> settings); static Optional<IlpOverHttpLinkSettings.AuthType> getIncomingAuthType(Map<String, Object> customSettings); static Optional<IlpOverHttpLinkSettings.AuthType> getOutgoingAuthType(Map<String, Object> customSettings); static void validate(AuthenticatedLinkSettings linkSettings); }### Answer: @Test public void getIncomingAuthTypeWithSimple() { assertThat(LinkSettingsUtils.getIncomingAuthType(AbstractHttpLinkSettingsTest.customSettingsSimpleFlat())) .isEqualTo(Optional.of(IlpOverHttpLinkSettings.AuthType.SIMPLE)); assertThat(LinkSettingsUtils.getIncomingAuthType(AbstractHttpLinkSettingsTest.customSettingsSimpleHierarchical())) .isEqualTo(Optional.of(IlpOverHttpLinkSettings.AuthType.SIMPLE)); } @Test public void getIncomingAuthTypeWithJwtHs256() { IlpOverHttpLinkSettings.AuthType authType = IlpOverHttpLinkSettings.AuthType.JWT_HS_256; assertThat( LinkSettingsUtils.getIncomingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtFlat(authType))) .isEqualTo(Optional.of(authType)); assertThat( LinkSettingsUtils.getIncomingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtHierarchical(authType))) .isEqualTo(Optional.of(authType)); } @Test public void getIncomingAuthTypeWithJwtRs256() { IlpOverHttpLinkSettings.AuthType authType = IlpOverHttpLinkSettings.AuthType.JWT_RS_256; assertThat( LinkSettingsUtils.getIncomingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtFlat(authType))) .isEqualTo(Optional.of(authType)); assertThat( LinkSettingsUtils.getIncomingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtHierarchical(authType))) .isEqualTo(Optional.of(authType)); }
### Question: LinkSettingsUtils { public static Optional<IlpOverHttpLinkSettings.AuthType> getOutgoingAuthType(Map<String, Object> customSettings) { return Optional.ofNullable(flattenSettings(customSettings).get(OutgoingLinkSettings.HTTP_OUTGOING_AUTH_TYPE)) .map(Object::toString) .map(String::toUpperCase) .map(IlpOverHttpLinkSettings.AuthType::valueOf); } static Map<String, Object> flattenSettings(Map<String, Object> settings); static Optional<IlpOverHttpLinkSettings.AuthType> getIncomingAuthType(Map<String, Object> customSettings); static Optional<IlpOverHttpLinkSettings.AuthType> getOutgoingAuthType(Map<String, Object> customSettings); static void validate(AuthenticatedLinkSettings linkSettings); }### Answer: @Test public void getOutgoingAuthTypeWithSimple() { assertThat(LinkSettingsUtils.getOutgoingAuthType(AbstractHttpLinkSettingsTest.customSettingsSimpleFlat())) .isEqualTo(Optional.of(IlpOverHttpLinkSettings.AuthType.SIMPLE)); assertThat(LinkSettingsUtils.getOutgoingAuthType(AbstractHttpLinkSettingsTest.customSettingsSimpleHierarchical())) .isEqualTo(Optional.of(IlpOverHttpLinkSettings.AuthType.SIMPLE)); } @Test public void getOutgoingAuthTypeWithJwtHs256() { IlpOverHttpLinkSettings.AuthType authType = IlpOverHttpLinkSettings.AuthType.JWT_HS_256; assertThat( LinkSettingsUtils.getOutgoingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtFlat(authType))) .isEqualTo(Optional.of(authType)); assertThat( LinkSettingsUtils.getOutgoingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtHierarchical(authType))) .isEqualTo(Optional.of(authType)); } @Test public void getOutgoingAuthTypeWithJwtRs256() { IlpOverHttpLinkSettings.AuthType authType = IlpOverHttpLinkSettings.AuthType.JWT_RS_256; assertThat( LinkSettingsUtils.getOutgoingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtFlat(authType))) .isEqualTo(Optional.of(authType)); assertThat( LinkSettingsUtils.getOutgoingAuthType(AbstractHttpLinkSettingsTest.customSettingsJwtHierarchical(authType))) .isEqualTo(Optional.of(authType)); }
### Question: JwtHs256BearerTokenSupplier implements BearerTokenSupplier { @Override public String get() { try { return this.ilpOverHttpAuthTokens.get(outgoingLinkSettings.jwtAuthSettings().get().tokenSubject()); } catch (ExecutionException e) { throw new RuntimeException(e); } } JwtHs256BearerTokenSupplier( final SharedSecretBytesSupplier sharedSecretBytesSupplier, final OutgoingLinkSettings outgoingLinkSettings ); @Override String get(); }### Answer: @Test public void checkCaching() { OutgoingLinkSettings linkSettings = createOutgoingSettings(Duration.ofMinutes(5)); JwtHs256BearerTokenSupplier tokenSupplier = new JwtHs256BearerTokenSupplier(secretBytesSupplier, linkSettings); tokenSupplier.get(); tokenSupplier.get(); verify(secretBytesSupplier).get(); } @Test public void checkCachingWithCachingDisabled() { OutgoingLinkSettings linkSettings = createOutgoingSettings(Duration.ofMinutes(0)); JwtHs256BearerTokenSupplier tokenSupplier = new JwtHs256BearerTokenSupplier(secretBytesSupplier, linkSettings); tokenSupplier.get(); tokenSupplier.get(); verify(secretBytesSupplier, times(2)).get(); } @Test public void checkCacheExpiry() throws Exception { OutgoingLinkSettings linkSettings = createOutgoingSettings(Duration.ofMillis(2)); JwtHs256BearerTokenSupplier tokenSupplier = new JwtHs256BearerTokenSupplier(secretBytesSupplier, linkSettings); tokenSupplier.get(); Thread.sleep(3); tokenSupplier.get(); verify(secretBytesSupplier, times(2)).get(); }
### Question: AsnIldcpResponsePacketDataCodec extends AsnSequenceCodec<IldcpResponsePacket> { @Override public IldcpResponsePacket decode() { final IldcpResponse ildcpResponse; try { ildcpResponse = IldcpCodecContextFactory.oer() .read(IldcpResponse.class, new ByteArrayInputStream(getValueAt(1))); } catch (IOException e) { throw new IldcpCodecException(e.getMessage(), e); } return IldcpResponsePacket.builder() .fulfillment(getValueAt(0)) .ildcpResponse(ildcpResponse) .build(); } AsnIldcpResponsePacketDataCodec(); @Override IldcpResponsePacket decode(); @Override void encode(IldcpResponsePacket value); }### Answer: @Test public void decode() throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); IldcpCodecContextFactory.oer().write(packet, os); final IldcpResponsePacket actual = IldcpCodecContextFactory.oer() .read(IldcpResponsePacket.class, new ByteArrayInputStream(os.toByteArray())); assertThat(actual).isEqualTo(packet); }
### Question: DateUtils { public static Instant now() { return Instant.now().truncatedTo(ChronoUnit.MILLIS); } static Instant now(); }### Answer: @Test public void now() { for (int i = 0; i < 100; i++) { long micros = DateUtils.now().get(ChronoField.MICRO_OF_SECOND); assertThat(micros % 1000).isEqualTo(0); } }
### Question: InterledgerRustNodeClient { public RustNodeAccount createAccount(RustNodeAccount rustNodeAccount) throws IOException { return execute(requestBuilder() .url(baseUrl.newBuilder().addPathSegment("accounts").build()) .post(RequestBody.create(objectMapper.writeValueAsString(rustNodeAccount), JSON)) .build(), RustNodeAccount.class); } @Deprecated InterledgerRustNodeClient(OkHttpClient okHttpClient, String authToken, String baseUrl); InterledgerRustNodeClient( final OkHttpClient okHttpClient, final String authToken, final HttpUrl baseUrl ); RustNodeAccount createAccount(RustNodeAccount rustNodeAccount); BigDecimal getBalance(String accountName); static final MediaType JSON; }### Answer: @Test public void createAccount() throws IOException, URISyntaxException { String testClient = "testClient"; String accountBody = "{\"ilp_address\":\"test.xpring-dev.rs1." + testClient + "\"," + "\"username\":\"" + testClient + "\"," + "\"asset_code\":\"XRP\"," + "\"asset_scale\":6," + "\"max_packet_amount\":10000000," + "\"min_balance\":-100000000," + "\"ilp_over_http_incoming_token\":\"passwordin\"," + "\"ilp_over_http_outgoing_token\":\"passwordout\"," + "\"http_endpoint\":\"https: + "\"btp_uri\":\"btp+ws: + "\"routing_relation\":\"Peer\"," + "\"round_trip_time\":500}"; stubFor(post(urlEqualTo("/accounts")) .withHeader("Authorization", equalTo("Bearer passwordin")) .willReturn(aResponse() .withStatus(200) .withBody(accountBody) )); client.createAccount(RustNodeAccount.builder() .ilpAddress(InterledgerAddress.of("test.xpring-dev.rs1").with(testClient)) .username(testClient) .assetCode("XRP") .assetScale(6) .minBalance(new BigInteger("-100000000")) .maxPacketAmount(new BigInteger("10000000")) .httpIncomingToken("passwordin") .httpOutgoingToken("passwordout") .httpEndpoint(new URI("https: .btpUri(new URI("btp+ws: .roundTripTime(new BigInteger("500")) .routingRelation(RustNodeAccount.RoutingRelation.PEER) .build() ); verify(postRequestedFor(urlMatching("/accounts")) .withRequestBody(equalTo(accountBody))); }
### Question: InterledgerRustNodeClient { public BigDecimal getBalance(String accountName) throws SpspClientException { return execute(requestBuilder() .url( baseUrl.newBuilder().addPathSegment("accounts").addPathSegment(accountName).addPathSegment("balance").build() ) .get() .build(), BalanceResponse.class) .getBalance(); } @Deprecated InterledgerRustNodeClient(OkHttpClient okHttpClient, String authToken, String baseUrl); InterledgerRustNodeClient( final OkHttpClient okHttpClient, final String authToken, final HttpUrl baseUrl ); RustNodeAccount createAccount(RustNodeAccount rustNodeAccount); BigDecimal getBalance(String accountName); static final MediaType JSON; }### Answer: @Test public void getBalance() { String bigBalance = "12345678901234567890.11111"; String testClient = "testClient"; stubFor(get(urlEqualTo("/accounts/" + testClient + "/balance")) .withHeader("Authorization", equalTo("Bearer passwordin")) .willReturn(aResponse() .withStatus(200) .withBody("{\"balance\":\"" + bigBalance + "\"}") )); BigDecimal response = client.getBalance(testClient); assertThat(response).isEqualTo(new BigDecimal(bigBalance)); }
### Question: SimpleSpspClient implements SpspClient { @Override public StreamConnectionDetails getStreamConnectionDetails(final PaymentPointer paymentPointer) throws InvalidReceiverClientException { Objects.requireNonNull(paymentPointer); return getStreamConnectionDetails(paymentPointerResolver.resolveHttpUrl(paymentPointer)); } SimpleSpspClient(); SimpleSpspClient( final OkHttpClient httpClient, final PaymentPointerResolver paymentPointerResolver, final ObjectMapper objectMapper ); @Override StreamConnectionDetails getStreamConnectionDetails(final PaymentPointer paymentPointer); @Override StreamConnectionDetails getStreamConnectionDetails(final HttpUrl spspUrl); }### Answer: @Test public void getStreamConnectionDetailsFromPaymentPointer() { String testClient = "testClient"; String sharedSecret = "Nf9wCXI1OZLM/QIWdZZ2Q39limh6+Yxhm/FB1bUpZLA="; String wiremockIlpAddress = "test.wiremock"; stubFor(get(urlEqualTo("/" + testClient)) .withHeader("Accept", equalTo(SpspClient.APPLICATION_SPSP4_JSON_VALUE)) .willReturn(aResponse() .withStatus(200) .withBody("{\"destination_account\":\"" + wiremockIlpAddress + "." + testClient + "\"," + "\"shared_secret\":\"" + sharedSecret + "\"}") )); StreamConnectionDetails response = client.getStreamConnectionDetails(paymentPointer(testClient)); assertThat(response) .isEqualTo(StreamConnectionDetails.builder() .destinationAddress(InterledgerAddress.of(wiremockIlpAddress + "." + testClient)) .sharedSecret(SharedSecret.of(sharedSecret)) .build()); } @Test public void getStreamConnectionDetailsFromUrl() { String testClient = "testClient"; String sharedSecret = "Nf9wCXI1OZLM/QIWdZZ2Q39limh6+Yxhm/FB1bUpZLA="; String wiremockIlpAddress = "test.wiremock"; stubFor(get(urlEqualTo("/" + testClient)) .withHeader("Accept", equalTo(SpspClient.APPLICATION_SPSP4_JSON_VALUE)) .willReturn(aResponse() .withStatus(200) .withBody("{\"destination_account\":\"" + wiremockIlpAddress + "." + testClient + "\"," + "\"shared_secret\":\"" + sharedSecret + "\"}") )); HttpUrl url = HttpUrl.parse(wireMockRule.baseUrl() + "/" + testClient); StreamConnectionDetails response = client.getStreamConnectionDetails(url); assertThat(response) .isEqualTo(StreamConnectionDetails.builder() .destinationAddress(InterledgerAddress.of(wiremockIlpAddress + "." + testClient)) .sharedSecret(SharedSecret.of(sharedSecret)) .build()); } @Test(expected = InvalidReceiverClientException.class) public void getStreamConnectionDetails404ThrowsInvalidReceiver() { String testClient = "testClient"; stubFor(get(urlEqualTo("/" + testClient)) .withHeader("Accept", equalTo(SpspClient.APPLICATION_SPSP4_JSON_VALUE)) .willReturn(aResponse() .withStatus(404) )); client.getStreamConnectionDetails(paymentPointer(testClient)); } @Test(expected = SpspClientException.class) public void getStreamConnectionDetails500ThrowsSpspClientException() { String testClient = "testClient"; stubFor(get(urlEqualTo("/" + testClient)) .withHeader("Accept", equalTo(SpspClient.APPLICATION_SPSP4_JSON_VALUE)) .willReturn(aResponse() .withStatus(503) )); client.getStreamConnectionDetails(paymentPointer(testClient)); }
### Question: IldcpResponsePacketMapper { public final T map(final InterledgerResponsePacket responsePacket) { Objects.requireNonNull(responsePacket); if (InterledgerFulfillPacket.class.isAssignableFrom(responsePacket.getClass())) { return mapFulfillPacket((IldcpResponsePacket) responsePacket); } else if (InterledgerRejectPacket.class.isAssignableFrom(responsePacket.getClass())) { return mapRejectPacket((InterledgerRejectPacket) responsePacket); } else { throw new RuntimeException( String.format("Unsupported IldcpResponsePacket Type: %s", responsePacket.getClass())); } } final T map(final InterledgerResponsePacket responsePacket); }### Answer: @Test public void mapFulfill() { ResponseWrapper wrapper = new ResponseWrapperMapper().map(fulfillPacket); assertThat(wrapper.get()).isEqualTo(fulfillPacket); } @Test public void mapReject() { ResponseWrapper wrapper = new ResponseWrapperMapper().map(rejectPacket); assertThat(wrapper.get()).isEqualTo(rejectPacket); } @Test public void cannotMap() { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Unsupported IldcpResponsePacket Type: " + "class org.interledger.ildcp.InterledgerShampooPacketBuilder$ImmutableInterledgerShampooPacket"); new ResponseWrapperMapper().map(shampooPacket); }
### Question: AsnIldcpPacketCodec extends AsnSequenceCodec<T> { protected void onTypeIdChanged(int typeId) { switch (typeId) { case IldcpPacketTypes.REQUEST: setCodecAt(1, new AsnOpenTypeCodec<>(new AsnIldcpRequestPacketDataCodec())); return; case IldcpPacketTypes.RESPONSE: setCodecAt(1, new AsnOpenTypeCodec<>(new AsnIldcpResponsePacketDataCodec())); return; default: throw new CodecException(format("Unknown IL-DCP packet type code: %s", typeId)); } } AsnIldcpPacketCodec(); @Override T decode(); @Override void encode(T value); }### Answer: @Test(expected = CodecException.class) public void onTypeIdChangedToUnsupported() { try { codec.onTypeIdChanged((short) 50); Assert.fail(); } catch (CodecException e) { assertThat(e.getMessage()).isEqualTo("Unknown IL-DCP packet type code: 50"); throw e; } }
### Question: IldcpResponsePacketHandler { public final void handle(final InterledgerResponsePacket responsePacket) { Objects.requireNonNull(responsePacket); if (IldcpResponsePacket.class.isAssignableFrom(responsePacket.getClass())) { handleIldcpResponsePacket((IldcpResponsePacket) responsePacket); } else if (InterledgerRejectPacket.class.isAssignableFrom(responsePacket.getClass())) { handleIldcpErrorPacket((InterledgerRejectPacket) responsePacket); } else { throw new RuntimeException( String.format("Unsupported IldcpResponsePacket Type: %s", responsePacket.getClass())); } } final void handle(final InterledgerResponsePacket responsePacket); }### Answer: @Test(expected = NullPointerException.class) public void handleNullPacket() { new IldcpResponsePacketHandler() { @Override protected void handleIldcpResponsePacket(IldcpResponsePacket ildcpResponsePacket) { throw new RuntimeException("Should not fulfill!"); } @Override protected void handleIldcpErrorPacket(InterledgerRejectPacket ildcpErrorPacket) { throw new RuntimeException("Should not reject!"); } }.handle(null); fail("cannot handle null packet"); } @Test public void handleFulfillPacket() { new IldcpResponsePacketHandler() { @Override protected void handleIldcpResponsePacket(IldcpResponsePacket ildcpResponsePacket) { assertThat(ildcpResponsePacket).isEqualTo(fulfillPacket); } @Override protected void handleIldcpErrorPacket(InterledgerRejectPacket ildcpErrorPacket) { fail("Cannot handle fulfill packets"); throw new RuntimeException("Should not reject!"); } }.handle(fulfillPacket); } @Test public void handleRejectPacket() { new IldcpResponsePacketHandler() { @Override protected void handleIldcpResponsePacket(IldcpResponsePacket ildcpResponsePacket) { fail("Cannot handle reject packet"); throw new RuntimeException("Should not fulfill!"); } @Override protected void handleIldcpErrorPacket(InterledgerRejectPacket ildcpErrorPacket) { assertThat(ildcpErrorPacket.getCode()).isEqualTo(InterledgerErrorCode.T00_INTERNAL_ERROR); } }.handle(rejectPacket); } @Test public void handleExpiredPacket() { new IldcpResponsePacketHandler() { @Override protected void handleIldcpResponsePacket(IldcpResponsePacket ildcpResponsePacket) { fail("Cannot handle expired packet"); throw new RuntimeException("Should not fulfill!"); } @Override protected void handleIldcpErrorPacket(InterledgerRejectPacket ildcpErrorPacket) { assertThat(ildcpErrorPacket.getCode()).isEqualTo(InterledgerErrorCode.R00_TRANSFER_TIMED_OUT); } }.handle(expiredPacket); } @Test public void fallthrough() { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Unsupported IldcpResponsePacket Type: " + "class org.interledger.ildcp.InterledgerShampooPacketBuilder$ImmutableInterledgerShampooPacket"); new IldcpResponsePacketHandler() { @Override protected void handleIldcpResponsePacket(IldcpResponsePacket ildcpResponsePacket) { } @Override protected void handleIldcpErrorPacket(InterledgerRejectPacket ildcpErrorPacket) { } }.handle(shampooPacket); }
### Question: AimdCongestionController implements CongestionController { @Override public boolean hasInFlight() { return is(this.amountInFlight.get()).greaterThan(UnsignedLong.ZERO); } AimdCongestionController(); AimdCongestionController( final UnsignedLong startAmount, final UnsignedLong increaseAmount, final BigDecimal decreaseFactor, final CodecContext streamCodecContext ); @Override UnsignedLong getMaxAmount(); @Override void prepare(final UnsignedLong amount); @Override void fulfill(final UnsignedLong prepareAmount); @Override void reject(final UnsignedLong prepareAmount, final InterledgerRejectPacket rejectPacket); @Override CongestionState getCongestionState(); void setCongestionState(final CongestionState congestionState); @Override Optional<UnsignedLong> getMaxPacketAmount(); void setMaxPacketAmount(final UnsignedLong maxPacketAmount); void setMaxPacketAmount(final Optional<UnsignedLong> maxPacketAmount); @Override boolean hasInFlight(); }### Answer: @Test public void hasInFlight() { controller.prepare(UnsignedLong.ONE); assertThat(controller.hasInFlight()).isTrue(); }
### Question: AsnIldcpRequestPacketDataCodec extends AsnSequenceCodec<IldcpRequestPacket> { @Override public void encode(IldcpRequestPacket value) { setValueAt(0, value.getAmount()); setValueAt(1, value.getExpiresAt()); setValueAt(2, value.getExecutionCondition()); setValueAt(3, value.getDestination()); setValueAt(4, value.getData()); } AsnIldcpRequestPacketDataCodec(); @Override IldcpRequestPacket decode(); @Override void encode(IldcpRequestPacket value); }### Answer: @Test public void encode() { codec.encode(packet); assertThat((UnsignedLong) codec.getValueAt(0)).isEqualTo(UnsignedLong.ZERO); assertThat((Instant) codec.getValueAt(1)).isEqualTo(NOW); assertThat((InterledgerCondition) codec.getValueAt(2)) .isEqualTo(IldcpRequestPacket.EXECUTION_CONDITION); assertThat((InterledgerAddress) codec.getValueAt(3)).isEqualTo(IldcpRequestPacket.PEER_DOT_CONFIG); assertThat((byte[]) codec.getValueAt(4)).isEqualTo(new byte[0]); }
### Question: StreamConnectionManager { public StreamConnection openConnection(final StreamConnectionId streamConnectionId) { Objects.requireNonNull(streamConnectionId); return connections.computeIfAbsent(streamConnectionId, StreamConnection::new); } StreamConnection openConnection(final StreamConnectionId streamConnectionId); Optional<StreamConnection> closeConnection(final StreamConnectionId streamConnectionId); }### Answer: @Test public void openConnection() { StreamConnectionId streamConnectionId = StreamConnectionId.of("foo"); final StreamConnection streamConnection = streamConnectionManager .openConnection(streamConnectionId); assertThat(streamConnectionManager.openConnection(streamConnectionId)).isEqualTo(streamConnection); assertThat(streamConnectionManager.openConnection(streamConnectionId)).isEqualTo(streamConnection); }
### Question: StreamConnectionManager { public Optional<StreamConnection> closeConnection(final StreamConnectionId streamConnectionId) { Objects.requireNonNull(streamConnectionId); return Optional.ofNullable(connections.get(streamConnectionId)) .map(connectionToClose -> { connectionToClose.closeConnection(); return connectionToClose; }); } StreamConnection openConnection(final StreamConnectionId streamConnectionId); Optional<StreamConnection> closeConnection(final StreamConnectionId streamConnectionId); }### Answer: @Test public void closeConnection() { StreamConnectionId streamConnectionId = StreamConnectionId.of("foo"); final StreamConnection streamConnection = streamConnectionManager .openConnection(streamConnectionId); assertThat(streamConnectionManager.closeConnection(streamConnectionId)).get().isEqualTo(streamConnection); assertThat(streamConnectionManager.closeConnection(streamConnectionId)).get().isEqualTo(streamConnection); }
### Question: AsnIldcpRequestPacketDataCodec extends AsnSequenceCodec<IldcpRequestPacket> { @Override public IldcpRequestPacket decode() { return IldcpRequestPacket.builder() .amount(getValueAt(0)) .expiresAt(getValueAt(1)) .build(); } AsnIldcpRequestPacketDataCodec(); @Override IldcpRequestPacket decode(); @Override void encode(IldcpRequestPacket value); }### Answer: @Test public void decode() throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); IldcpCodecContextFactory.oer().write(packet, os); final IldcpRequestPacket actual = IldcpCodecContextFactory.oer() .read(IldcpRequestPacket.class, new ByteArrayInputStream(os.toByteArray())); assertThat(actual).isEqualTo(packet); }
### Question: AesGcmStreamEncryptionService implements StreamEncryptionService { @VisibleForTesting byte[] encryptWithIv(final SharedSecret sharedSecret, final byte[] plainText, final byte[] iv) throws EncryptionException { Objects.requireNonNull(sharedSecret); Objects.requireNonNull(plainText); Objects.requireNonNull(iv); if (this.encryptionMode == EncryptionMode.ENCRYPT_NON_STANDARD) { return this.nonStandardModeEncryptWithIv(sharedSecret, plainText, iv); } else { return this.standardModeEncryptWithIv(sharedSecret, plainText, iv); } } AesGcmStreamEncryptionService(); AesGcmStreamEncryptionService(final EncryptionMode encryptionMode); @Override byte[] encrypt(final SharedSecret sharedSecret, final byte[] plainText); @Override byte[] decrypt(final SharedSecret sharedSecret, final byte[] cipherMessage); }### Answer: @Test public void testEncryptToSameRustJs() { byte[] encryptedValue = streamEncryptionService.encryptWithIv(SHARED_SECRET, PLAINTEXT, NONCE_IV); assertThat(encryptedValue).isEqualTo(CIPHERTEXT); }
### Question: AesGcmStreamEncryptionService implements StreamEncryptionService { @Override public byte[] decrypt(final SharedSecret sharedSecret, final byte[] cipherMessage) { Objects.requireNonNull(sharedSecret); Objects.requireNonNull(cipherMessage); if (this.encryptionMode == EncryptionMode.ENCRYPT_NON_STANDARD) { try { return this.nonStandardModeDecrypt(sharedSecret, cipherMessage); } catch (EncryptionException e) { logger.warn( "Unable to decrypt payload in {} mode. Attempting {} mode as a fallback.", EncryptionMode.ENCRYPT_NON_STANDARD, EncryptionMode.ENCRYPT_STANDARD, e ); return this.standardModeDecrypt(sharedSecret, cipherMessage); } } else { try { return this.standardModeDecrypt(sharedSecret, cipherMessage); } catch (EncryptionException e) { logger.warn( "Unable to decrypt payload in {} mode. Attempting {} mode as a fallback.", EncryptionMode.ENCRYPT_STANDARD, EncryptionMode.ENCRYPT_NON_STANDARD, e ); return this.nonStandardModeDecrypt(sharedSecret, cipherMessage); } } } AesGcmStreamEncryptionService(); AesGcmStreamEncryptionService(final EncryptionMode encryptionMode); @Override byte[] encrypt(final SharedSecret sharedSecret, final byte[] plainText); @Override byte[] decrypt(final SharedSecret sharedSecret, final byte[] cipherMessage); }### Answer: @Test public void testDecryptToSameAsRustJs() { byte[] decryptedValue = streamEncryptionService.decrypt(SHARED_SECRET, CIPHERTEXT); assertThat(decryptedValue).isEqualTo(PLAINTEXT); } @Test public void testDecryptToSameAsRustJsInStandardMode() { this.streamEncryptionService = new AesGcmStreamEncryptionService(EncryptionMode.ENCRYPT_STANDARD); byte[] decryptedValue = streamEncryptionService.decrypt(SHARED_SECRET, CIPHERTEXT); assertThat(decryptedValue).isEqualTo(PLAINTEXT); }
### Question: StreamConnection implements Closeable { public StreamConnectionId getStreamConnectionId() { return streamConnectionId; } StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret); StreamConnection(final StreamConnectionId streamConnectionId); UnsignedLong nextSequence(); Instant getCreationDateTime(); void transitionConnectionState(); StreamConnectionState getConnectionState(); StreamConnectionId getStreamConnectionId(); void closeConnection(); boolean isClosed(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override void close(); static final UnsignedLong MAX_FRAMES_PER_CONNECTION; }### Answer: @Test public void testConstructorWithAddressAndSecret() { streamConnection = new StreamConnection(InterledgerAddress.of("example.foo"), SharedSecret.of(new byte[32])); assertThat(streamConnection.getStreamConnectionId()) .isEqualTo(StreamConnectionId.of("246307596a10c1ba057f56cd6d588ed0d11cf3f8817c937265e93950af53751f")); } @Test public void testStreamConnectionId() { StreamConnectionId streamConnectionId = StreamConnectionId.of("foo"); assertThat(new StreamConnection(streamConnectionId).getStreamConnectionId()).isEqualTo(streamConnectionId); }
### Question: StreamConnection implements Closeable { public UnsignedLong nextSequence() throws StreamConnectionClosedException { final UnsignedLong nextSequence = sequence.getAndUpdate(currentSequence -> currentSequence.plus(UnsignedLong.ONE)); if (sequenceIsSafeForSingleSharedSecret(nextSequence)) { return nextSequence; } else { this.closeConnection(); throw new StreamConnectionClosedException(streamConnectionId); } } StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret); StreamConnection(final StreamConnectionId streamConnectionId); UnsignedLong nextSequence(); Instant getCreationDateTime(); void transitionConnectionState(); StreamConnectionState getConnectionState(); StreamConnectionId getStreamConnectionId(); void closeConnection(); boolean isClosed(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override void close(); static final UnsignedLong MAX_FRAMES_PER_CONNECTION; }### Answer: @Test public void nextSequence() throws StreamConnectionClosedException { assertThat(streamConnection.nextSequence()).isEqualTo(UnsignedLong.ONE); assertThat(streamConnection.nextSequence()).isEqualTo(UnsignedLong.valueOf(2L)); assertThat(streamConnection.nextSequence()).isEqualTo(UnsignedLong.valueOf(3L)); assertThat(streamConnection.nextSequence()).isEqualTo(UnsignedLong.valueOf(4L)); } @Test public void nextSequenceMultiThreaded() throws StreamConnectionClosedException { final List<CompletableFuture<UnsignedLong>> allFutures = Lists.newArrayList(); final int numRepetitions = 50000; final ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < numRepetitions; i++) { allFutures.add( CompletableFuture.supplyAsync(() -> { try { UnsignedLong sequence = streamConnection.nextSequence(); return sequence; } catch (StreamConnectionClosedException e) { throw new RuntimeException(e); } }, executorService) ); } CompletableFuture.allOf(allFutures.toArray(new CompletableFuture[0])).join(); assertThat(streamConnection.nextSequence().longValue()).isEqualTo(numRepetitions + 1); }
### Question: StreamConnection implements Closeable { public void transitionConnectionState() { this.connectionState.updateAndGet(streamConnectionState -> { switch (streamConnectionState) { case AVAILABLE: { return StreamConnectionState.OPEN; } case OPEN: case CLOSED: default: { return StreamConnectionState.CLOSED; } } }); } StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret); StreamConnection(final StreamConnectionId streamConnectionId); UnsignedLong nextSequence(); Instant getCreationDateTime(); void transitionConnectionState(); StreamConnectionState getConnectionState(); StreamConnectionId getStreamConnectionId(); void closeConnection(); boolean isClosed(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override void close(); static final UnsignedLong MAX_FRAMES_PER_CONNECTION; }### Answer: @Test public void transitionConnectionState() { assertThat(streamConnection.isClosed()).isFalse(); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.AVAILABLE); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.AVAILABLE); streamConnection.transitionConnectionState(); assertThat(streamConnection.isClosed()).isFalse(); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.OPEN); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.OPEN); streamConnection.transitionConnectionState(); assertThat(streamConnection.isClosed()).isTrue(); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.CLOSED); assertThat(streamConnection.isClosed()).isTrue(); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.CLOSED); streamConnection.transitionConnectionState(); streamConnection.transitionConnectionState(); streamConnection.transitionConnectionState(); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.CLOSED); assertThat(streamConnection.getConnectionState()).isEqualTo(StreamConnectionState.CLOSED); assertThat(streamConnection.isClosed()).isTrue(); }
### Question: StreamConnection implements Closeable { public Instant getCreationDateTime() { return creationDateTime; } StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret); StreamConnection(final StreamConnectionId streamConnectionId); UnsignedLong nextSequence(); Instant getCreationDateTime(); void transitionConnectionState(); StreamConnectionState getConnectionState(); StreamConnectionId getStreamConnectionId(); void closeConnection(); boolean isClosed(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override void close(); static final UnsignedLong MAX_FRAMES_PER_CONNECTION; }### Answer: @Test public void getCreationDateTime() { assertThat(streamConnection.getCreationDateTime()).isNotNull(); assertThat(streamConnection.getCreationDateTime()).isBefore(DateUtils.now().plusSeconds(1)); }
### Question: StreamConnection implements Closeable { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } StreamConnection that = (StreamConnection) obj; return streamConnectionId.equals(that.streamConnectionId); } StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret); StreamConnection(final StreamConnectionId streamConnectionId); UnsignedLong nextSequence(); Instant getCreationDateTime(); void transitionConnectionState(); StreamConnectionState getConnectionState(); StreamConnectionId getStreamConnectionId(); void closeConnection(); boolean isClosed(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override void close(); static final UnsignedLong MAX_FRAMES_PER_CONNECTION; }### Answer: @Test public void testEquals() { assertThat(streamConnection.equals(null)).isFalse(); assertThat(streamConnection.equals(streamConnection)).isTrue(); StreamConnection identicalStreamConnection = new StreamConnection(StreamConnectionId.of("foo")); assertThat(streamConnection.equals(identicalStreamConnection)).isTrue(); assertThat(identicalStreamConnection.equals(streamConnection)).isTrue(); StreamConnection nonIdenticalStreamConnection = new StreamConnection(StreamConnectionId.of("foo1")); assertThat(streamConnection.equals(nonIdenticalStreamConnection)).isFalse(); assertThat(nonIdenticalStreamConnection.equals(streamConnection)).isFalse(); }
### Question: OerLengthSerializer { public static int readLength(final InputStream inputStream) throws IOException { Objects.requireNonNull(inputStream); final int length; int initialLengthPrefixOctet = inputStream.read(); if (initialLengthPrefixOctet >= 0 && initialLengthPrefixOctet < 128) { length = initialLengthPrefixOctet; } else { final int lengthOfLength = initialLengthPrefixOctet & 0x7F; byte[] ba = new byte[lengthOfLength]; int read = inputStream.read(ba, 0, lengthOfLength); if (read != lengthOfLength) { throw new IOException("Unable to read " + lengthOfLength + " bytes from stream, only read " + read); } length = toInt(ba); } return length > 0 ? length : 0; } static int readLength(final InputStream inputStream); static void writeLength(final int length, final OutputStream outputStream); }### Answer: @Test public void read() throws Exception { final ByteArrayInputStream inputStream = new ByteArrayInputStream(this.asn1OerBytes); final int actualPayloadLength = OerLengthSerializer.readLength(inputStream); assertThat(actualPayloadLength).isEqualTo(expectedPayloadLength); } @Test public void readLengthWithCorrectPrefixButNegativeNumber() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(3); for (int i = 0; i < 3; i++) { outputStream.write(-1); } ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); assertThat(OerLengthSerializer.readLength(inputStream)).isEqualTo(3); } @Test public void readMultiByteLengthWithNegativeValue() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(-127); outputStream.write(0x80); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); assertThat(OerLengthSerializer.readLength(inputStream)).isEqualTo(128); } @Test public void readMultiByteLengthWith1Byte() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(-127); outputStream.write(2); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); assertThat(OerLengthSerializer.readLength(inputStream)).isEqualTo(2); } @Test public void readMultiByteLengthWithMaxBytes() throws IOException { expectedException.expect(CodecException.class); expectedException.expectMessage("This method only supports arrays up to length 4!"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(-1); for (int i = 0; i < 127; i++) { outputStream.write(-1); } ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); OerLengthSerializer.readLength(inputStream); }
### Question: StreamConnection implements Closeable { @Override public int hashCode() { return streamConnectionId.hashCode(); } StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret); StreamConnection(final StreamConnectionId streamConnectionId); UnsignedLong nextSequence(); Instant getCreationDateTime(); void transitionConnectionState(); StreamConnectionState getConnectionState(); StreamConnectionId getStreamConnectionId(); void closeConnection(); boolean isClosed(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override void close(); static final UnsignedLong MAX_FRAMES_PER_CONNECTION; }### Answer: @Test public void testHashCode() { StreamConnection identicalStreamConnection = new StreamConnection(StreamConnectionId.of("foo")); assertThat(streamConnection.hashCode()).isEqualTo(identicalStreamConnection.hashCode()); StreamConnection nonIdenticalStreamConnection = new StreamConnection(StreamConnectionId.of("foo1")); assertThat(streamConnection.hashCode()).isNotEqualTo(nonIdenticalStreamConnection.hashCode()); }
### Question: StreamConnection implements Closeable { @Override public String toString() { return new StringJoiner(", ", StreamConnection.class.getSimpleName() + "[", "]") .add("creationDateTime=" + creationDateTime) .add("streamConnectionId=" + streamConnectionId) .add("sequence=" + sequence) .add("connectionState=" + connectionState) .toString(); } StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret); StreamConnection(final StreamConnectionId streamConnectionId); UnsignedLong nextSequence(); Instant getCreationDateTime(); void transitionConnectionState(); StreamConnectionState getConnectionState(); StreamConnectionId getStreamConnectionId(); void closeConnection(); boolean isClosed(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); @Override void close(); static final UnsignedLong MAX_FRAMES_PER_CONNECTION; }### Answer: @Test public void testToString() { final String matchingSerializedRegex = "StreamConnection\\[" + "creationDateTime=[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.\\d+Z, " + "streamConnectionId=\\S+ sequence=\\d+, connectionState=[A-Z]+]"; final String serializedStreamConnection = streamConnection.toString(); assertThat(serializedStreamConnection.matches(matchingSerializedRegex)).isTrue(); }
### Question: StreamUtils { public static InterledgerFulfillment generatedFulfillableFulfillment( final SharedSecret sharedSecret, final byte[] data ) { Objects.requireNonNull(sharedSecret); Objects.requireNonNull(data); final SecretKey secretKey = new SecretKeySpec(sharedSecret.key(), HMAC_SHA256_ALG_NAME); final byte[] hmacKey = Hashing.hmacSha256(secretKey).hashBytes(ILP_STREAM_FULFILLMENT).asBytes(); final SecretKey hmacSecretKey = new SecretKeySpec(hmacKey, HMAC_SHA256_ALG_NAME); final byte[] fulfillmentBytes = Hashing.hmacSha256(hmacSecretKey).hashBytes(data).asBytes(); return InterledgerFulfillment.of(fulfillmentBytes); } static InterledgerCondition unfulfillableCondition(); static InterledgerFulfillment generatedFulfillableFulfillment( final SharedSecret sharedSecret, final byte[] data ); static UnsignedLong min(final UnsignedLong value1, final UnsignedLong value2); static UnsignedLong max(final UnsignedLong value1, final UnsignedLong value2); }### Answer: @Test public void generatedFulfillableFulfillment() { InterledgerFulfillment fulfillment = StreamUtils.generatedFulfillableFulfillment(SHARED_SECRET, DATA); assertThat(fulfillment.getPreimage()).isEqualTo(FULFILLMENT); assertThat(fulfillment).isEqualTo(InterledgerFulfillment.of(FULFILLMENT)); }
### Question: StreamUtils { public static UnsignedLong min(final UnsignedLong value1, final UnsignedLong value2) { Objects.requireNonNull(value1); Objects.requireNonNull(value2); if (is(value1).lessThan(value2)) { return value1; } else { return value2; } } static InterledgerCondition unfulfillableCondition(); static InterledgerFulfillment generatedFulfillableFulfillment( final SharedSecret sharedSecret, final byte[] data ); static UnsignedLong min(final UnsignedLong value1, final UnsignedLong value2); static UnsignedLong max(final UnsignedLong value1, final UnsignedLong value2); }### Answer: @Test(expected = NullPointerException.class) public void minWithNullFirst() { try { StreamUtils.min(null, UnsignedLong.ONE); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isNull(); throw e; } } @Test(expected = NullPointerException.class) public void minWithNullSecond() { try { StreamUtils.min(UnsignedLong.ONE, null); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isNull(); throw e; } } @Test public void minTests() { assertThat(StreamUtils.min(UnsignedLong.ZERO, UnsignedLong.ZERO)).isEqualTo(UnsignedLong.ZERO); assertThat(StreamUtils.min(UnsignedLong.ONE, UnsignedLong.ZERO)).isEqualTo(UnsignedLong.ZERO); assertThat(StreamUtils.min(UnsignedLong.ZERO, UnsignedLong.ONE)).isEqualTo(UnsignedLong.ZERO); assertThat(StreamUtils.min(UnsignedLong.MAX_VALUE, UnsignedLong.ZERO)).isEqualTo(UnsignedLong.ZERO); assertThat(StreamUtils.min(UnsignedLong.ZERO, UnsignedLong.MAX_VALUE)).isEqualTo(UnsignedLong.ZERO); assertThat(StreamUtils.min(UnsignedLong.ONE, UnsignedLong.MAX_VALUE)).isEqualTo(UnsignedLong.ONE); assertThat(StreamUtils.min(UnsignedLong.MAX_VALUE, UnsignedLong.ONE)).isEqualTo(UnsignedLong.ONE); }
### Question: StreamUtils { public static UnsignedLong max(final UnsignedLong value1, final UnsignedLong value2) { Objects.requireNonNull(value1); Objects.requireNonNull(value2); if (is(value1).greaterThan(value2)) { return value1; } else { return value2; } } static InterledgerCondition unfulfillableCondition(); static InterledgerFulfillment generatedFulfillableFulfillment( final SharedSecret sharedSecret, final byte[] data ); static UnsignedLong min(final UnsignedLong value1, final UnsignedLong value2); static UnsignedLong max(final UnsignedLong value1, final UnsignedLong value2); }### Answer: @Test public void maxTests() { assertThat(StreamUtils.max(UnsignedLong.ZERO, UnsignedLong.ZERO)).isEqualTo(UnsignedLong.ZERO); assertThat(StreamUtils.max(UnsignedLong.ONE, UnsignedLong.ZERO)).isEqualTo(UnsignedLong.ONE); assertThat(StreamUtils.max(UnsignedLong.ZERO, UnsignedLong.ONE)).isEqualTo(UnsignedLong.ONE); assertThat(StreamUtils.max(UnsignedLong.MAX_VALUE, UnsignedLong.ZERO)).isEqualTo(UnsignedLong.MAX_VALUE); assertThat(StreamUtils.max(UnsignedLong.ZERO, UnsignedLong.MAX_VALUE)).isEqualTo(UnsignedLong.MAX_VALUE); assertThat(StreamUtils.max(UnsignedLong.ONE, UnsignedLong.MAX_VALUE)).isEqualTo(UnsignedLong.MAX_VALUE); assertThat(StreamUtils.max(UnsignedLong.MAX_VALUE, UnsignedLong.ONE)).isEqualTo(UnsignedLong.MAX_VALUE); }
### Question: StreamUtils { public static InterledgerCondition unfulfillableCondition() { return InterledgerCondition.of(Random.randBytes(32)); } static InterledgerCondition unfulfillableCondition(); static InterledgerFulfillment generatedFulfillableFulfillment( final SharedSecret sharedSecret, final byte[] data ); static UnsignedLong min(final UnsignedLong value1, final UnsignedLong value2); static UnsignedLong max(final UnsignedLong value1, final UnsignedLong value2); }### Answer: @Test public void unfulfillableCondition() { assertThat(StreamUtils.unfulfillableCondition()).isNotNull(); assertThat(StreamUtils.unfulfillableCondition()).isNotEqualTo(InterledgerCondition.of(new byte[32])); }
### Question: NoOpExchangeRateCalculator implements ExchangeRateCalculator { @Override public UnsignedLong calculateMinAmountToAccept( final UnsignedLong sendAmount, final Denomination sendAmountDenomination ) { Objects.requireNonNull(sendAmount); Objects.requireNonNull(sendAmountDenomination); return UnsignedLong.ZERO; } @Override UnsignedLong calculateAmountToSend(UnsignedLong amountToSend, Denomination amountToSendDenomination, Denomination receiverDenomination); @Override UnsignedLong calculateMinAmountToAccept( final UnsignedLong sendAmount, final Denomination sendAmountDenomination ); }### Answer: @Test public void calculateMinAmountToAcceptInReceiverAmountMode() { ExchangeRateCalculator calc = new NoOpExchangeRateCalculator(); assertThat(calc.calculateMinAmountToAccept(UnsignedLong.ONE, Denominations.USD, Denominations.EUR)) .isEqualTo(UnsignedLong.ZERO); } @Test public void calculateMinAmountToAcceptInSenderAmountMode() { ExchangeRateCalculator calc = new NoOpExchangeRateCalculator(); assertThat(calc.calculateMinAmountToAccept(UnsignedLong.ONE, Denominations.USD)) .isEqualTo(UnsignedLong.ZERO); }
### Question: OerLengthSerializer { public static void writeLength(final int length, final OutputStream outputStream) throws IOException { Objects.requireNonNull(outputStream); if (length <= 0) { outputStream.write(0); } else { if (length >= 0 && length < 128) { outputStream.write(length); } else { if (length <= 127) { outputStream.write(length); } else if (length <= 255) { outputStream.write(128 + 1); outputStream.write(length); } else if (length <= 65535) { outputStream.write(128 + 2); outputStream.write((length >> 8)); outputStream.write(length); } else if (length <= 16777215) { outputStream.write(128 + 3); outputStream.write((length >> 16)); outputStream.write((length >> 8)); outputStream.write(length); } else { outputStream.write(128 + 4); outputStream.write((length >> 24)); outputStream.write((length >> 16)); outputStream.write((length >> 8)); outputStream.write(length); } } } } static int readLength(final InputStream inputStream); static void writeLength(final int length, final OutputStream outputStream); }### Answer: @Test public void write() throws Exception { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OerLengthSerializer.writeLength(expectedPayloadLength, outputStream); assertThat(this.asn1OerBytes).isEqualTo(outputStream.toByteArray()); } @Test public void writeNegativeLength() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OerLengthSerializer.writeLength(Integer.MIN_VALUE, outputStream); assertThat(BaseEncoding.base16().decode("00")).isEqualTo(outputStream.toByteArray()); outputStream = new ByteArrayOutputStream(); OerLengthSerializer.writeLength(-1, outputStream); assertThat(BaseEncoding.base16().decode("00")).isEqualTo(outputStream.toByteArray()); }
### Question: StatelessStreamReceiver implements StreamReceiver { @Override public StreamConnectionDetails setupStream(final InterledgerAddress receiverAddress) { Objects.requireNonNull(receiverAddress); return streamConnectionGenerator.generateConnectionDetails(serverSecretSupplier, receiverAddress); } StatelessStreamReceiver( final ServerSecretSupplier serverSecretSupplier, final StreamConnectionGenerator streamConnectionGenerator, final StreamEncryptionService streamEncryptionService, final CodecContext streamCodecContext ); @Override StreamConnectionDetails setupStream(final InterledgerAddress receiverAddress); @Override InterledgerResponsePacket receiveMoney( final InterledgerPreparePacket preparePacket, final InterledgerAddress receiverAddress, final Denomination denomination ); }### Answer: @Test public void setupStream() { StreamConnectionGenerator streamConnectionGenerator = mock(StreamConnectionGenerator.class); this.streamReceiver = new StatelessStreamReceiver( serverSecretSupplier, streamConnectionGenerator, streamEncryptionService, StreamCodecContextFactory.oer() ); InterledgerAddress receiverAddress = InterledgerAddress.of("example.receiver"); streamReceiver.setupStream(receiverAddress); Mockito.verify(streamConnectionGenerator).generateConnectionDetails(Mockito.any(), eq(receiverAddress)); }
### Question: AsnInterledgerAddressPrefixCodec extends AsnIA5StringBasedObjectCodec<InterledgerAddressPrefix> { @Override public InterledgerAddressPrefix decode() { return InterledgerAddressPrefix.of(getCharString()); } AsnInterledgerAddressPrefixCodec(); @Override InterledgerAddressPrefix decode(); @Override void encode(InterledgerAddressPrefix value); }### Answer: @Test public void decode() { assertThat(codec.decode()).isEqualTo(InterledgerAddressPrefix.of(G)); }
### Question: AsnOctetStringBasedObjectCodec extends AsnPrimitiveCodec<T> { public final void setBytes(byte[] bytes) { Objects.requireNonNull(bytes); validateSize(bytes); this.bytes = bytes; this.onValueChangedEvent(); } AsnOctetStringBasedObjectCodec(AsnSizeConstraint sizeConstraintInOctets); AsnOctetStringBasedObjectCodec(int fixedSizeConstraint); AsnOctetStringBasedObjectCodec(int minSize, int maxSize); final byte[] getBytes(); final void setBytes(byte[] bytes); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test(expected = CodecException.class) public void setBytesTooBig() { final AsnOctetStringBasedObjectCodec codec = createCodec(new AsnSizeConstraint(0, 1)); final byte[] bytes = new byte[2]; try { codec.setBytes(bytes); } catch (CodecException e) { assertThat(e.getMessage()).isEqualTo("Invalid octet string length. Expected < 1, got 2"); throw e; } } @Test(expected = CodecException.class) public void setBytesTooBigForFixedSize() { final AsnOctetStringBasedObjectCodec codec = createCodec(new AsnSizeConstraint(1, 1)); final byte[] bytes = new byte[2]; try { codec.setBytes(bytes); } catch (CodecException e) { assertThat(e.getMessage()).isEqualTo("Invalid octet string length. Expected < 1, got 2"); throw e; } } @Test(expected = CodecException.class) public void setBytesTooSmall() { final AsnOctetStringBasedObjectCodec codec = createCodec(new AsnSizeConstraint(1, 2)); final byte[] bytes = new byte[0]; try { codec.setBytes(bytes); } catch (CodecException e) { assertThat(e.getMessage()).isEqualTo("Invalid octet string length. Expected > 1, got 0"); throw e; } } @Test(expected = CodecException.class) public void setBytesTooSmallForFixedSize() { final AsnOctetStringBasedObjectCodec codec = createCodec(new AsnSizeConstraint(1, 1)); final byte[] bytes = new byte[0]; try { codec.setBytes(bytes); } catch (CodecException e) { assertThat(e.getMessage()).isEqualTo("Invalid octet string length. Expected > 1, got 0"); throw e; } }
### Question: AsnSequenceOfSequenceCodec extends AsnObjectCodecBase<L> { public AsnSequenceCodec<T> getCodecAt(final int index) { Objects.requireNonNull(codecs); final AsnSequenceCodec<T> subCodec; if (codecs.size() == 0 || codecs.size() <= index) { subCodec = subCodecSupplier.get(); codecs.add(index, subCodec); } else { subCodec = codecs.get(index); } return subCodec; } AsnSequenceOfSequenceCodec( final Supplier<L> listConstructor, final Supplier<AsnSequenceCodec<T>> subCodecSupplier ); int size(); AsnSequenceCodec<T> getCodecAt(final int index); @Override L decode(); @Override void encode(final L values); }### Answer: @Test public void getCodecAtNegativeIndex() { expectedException.expect(IndexOutOfBoundsException.class); codec.getCodecAt(-1); } @Test public void getCodecAtWithRandomAccess() { expectedException.expect(IndexOutOfBoundsException.class); codec.getCodecAt(100); }
### Question: AsnSequenceOfSequenceCodec extends AsnObjectCodecBase<L> { @Override public void encode(final L values) { Objects.requireNonNull(values); this.codecs = new ArrayList<>(CODECS_ARRAY_INITIAL_CAPACITY); for (T value : values) { AsnSequenceCodec<T> codec = subCodecSupplier.get(); codec.encode(value); this.codecs.add(codec); } } AsnSequenceOfSequenceCodec( final Supplier<L> listConstructor, final Supplier<AsnSequenceCodec<T>> subCodecSupplier ); int size(); AsnSequenceCodec<T> getCodecAt(final int index); @Override L decode(); @Override void encode(final L values); }### Answer: @Test public void testEncodeWithNullCodecsList() { expectedException.expect(NullPointerException.class); codec.encode(null); }
### Question: AsnUintCodecUL extends AsnOctetStringBasedObjectCodec<UnsignedLong> { @Override public UnsignedLong decode() { try { return UnsignedLong.valueOf(new BigInteger(1, getBytes())); } catch (Exception e) { if (defaultValue.isPresent()) { logger.warn( "Variable Unsigned Integer was too big for VarUInt: {}. Returning UnsignedLong.Max", Base64.getEncoder().encodeToString(getBytes()) ); return defaultValue.get(); } else { throw e; } } } AsnUintCodecUL(); AsnUintCodecUL(final UnsignedLong defaultValue); @Override UnsignedLong decode(); @Override void encode(final UnsignedLong value); }### Answer: @Test public void decode() { codec = new AsnUintCodecUL(); codec.setBytes(new byte[]{1}); assertThat(codec.decode()).isEqualTo(UnsignedLong.ONE); } @Test public void decodeValueTooLarge() { codec = new AsnUintCodecUL(UnsignedLong.ONE); byte[] bytes = new BigInteger("18446744073709551616").toByteArray(); codec.setBytes(bytes); assertThat(codec.decode()).isEqualTo(UnsignedLong.ONE); }
### Question: AsnInterledgerAddressPrefixCodec extends AsnIA5StringBasedObjectCodec<InterledgerAddressPrefix> { @Override public void encode(InterledgerAddressPrefix value) { setCharString(value.getValue()); } AsnInterledgerAddressPrefixCodec(); @Override InterledgerAddressPrefix decode(); @Override void encode(InterledgerAddressPrefix value); }### Answer: @Test public void encode() { codec.encode(InterledgerAddressPrefix.of(G)); assertThat(codec.getCharString()).isEqualTo(G); }
### Question: AsnUintCodecUL extends AsnOctetStringBasedObjectCodec<UnsignedLong> { @Override public void encode(final UnsignedLong value) { byte[] bytes = value.bigIntegerValue().toByteArray(); if (bytes[0] == 0x00 && bytes.length > 1) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(bytes, 1, bytes.length - 1); setBytes(baos.toByteArray()); return; } setBytes(bytes); } AsnUintCodecUL(); AsnUintCodecUL(final UnsignedLong defaultValue); @Override UnsignedLong decode(); @Override void encode(final UnsignedLong value); }### Answer: @Test public void encode() { codec = new AsnUintCodecUL(); codec.encode(UnsignedLong.ONE); assertThat(codec.getBytes()).isEqualTo(new byte[] {1}); }
### Question: AsnUintCodec extends AsnOctetStringBasedObjectCodec<BigInteger> { @Override public void encode(final BigInteger value) { if (value.compareTo(BigInteger.ZERO) < 0) { throw new IllegalArgumentException("value must be positive or zero"); } byte[] bytes = value.toByteArray(); if (bytes[0] == 0x00 && bytes.length > 1) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(bytes, 1, bytes.length - 1); setBytes(baos.toByteArray()); return; } setBytes(bytes); } AsnUintCodec(); @Override BigInteger decode(); @Override void encode(final BigInteger value); }### Answer: @Test(expected = IllegalArgumentException.class) public void encodeNegative() { try { codec.encode(BigInteger.valueOf(-1L)); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("value must be positive or zero"); throw e; } } @Test public void encode() { codec.encode(expectedUint); assertThat(codec.getBytes()).isEqualTo(this.expectedEncodedBytes); }
### Question: AsnUintCodec extends AsnOctetStringBasedObjectCodec<BigInteger> { @Override public BigInteger decode() { return new BigInteger(1, getBytes()); } AsnUintCodec(); @Override BigInteger decode(); @Override void encode(final BigInteger value); }### Answer: @Test public void decode() { codec.setBytes(this.expectedEncodedBytes); assertThat(codec.decode()).isEqualTo(this.expectedUint); }
### Question: AsnSizeConstraint { public boolean isFixedSize() { return max != 0 && max == min; } AsnSizeConstraint(int fixedSize); AsnSizeConstraint(int min, int max); boolean isUnconstrained(); boolean isFixedSize(); int getMax(); int getMin(); @Override boolean equals(Object obj); @Override int hashCode(); static final AsnSizeConstraint UNCONSTRAINED; }### Answer: @Test public void isFixedSize() { final AsnSizeConstraint constraint = new AsnSizeConstraint(1); assertThat(constraint.isUnconstrained()).isFalse(); assertThat(constraint.isFixedSize()).isTrue(); assertThat(constraint.getMin()).isEqualTo(1); assertThat(constraint.getMax()).isEqualTo(1); }
### Question: AsnSizeConstraint { @Override public int hashCode() { int result = min; result = 31 * result + max; return result; } AsnSizeConstraint(int fixedSize); AsnSizeConstraint(int min, int max); boolean isUnconstrained(); boolean isFixedSize(); int getMax(); int getMin(); @Override boolean equals(Object obj); @Override int hashCode(); static final AsnSizeConstraint UNCONSTRAINED; }### Answer: @Test public void equalsHashCode() { assertThat(AsnSizeConstraint.UNCONSTRAINED).isEqualTo(AsnSizeConstraint.UNCONSTRAINED); assertThat(AsnSizeConstraint.UNCONSTRAINED).isNotEqualTo(new AsnSizeConstraint(1)); assertThat(AsnSizeConstraint.UNCONSTRAINED.hashCode()).isEqualTo(AsnSizeConstraint.UNCONSTRAINED.hashCode()); assertThat(AsnSizeConstraint.UNCONSTRAINED.hashCode()).isNotEqualTo(new AsnSizeConstraint(1).hashCode()); }
### Question: PacketRejector { public InterledgerRejectPacket reject( final LinkId rejectingLinkId, final InterledgerPreparePacket preparePacket, final InterledgerErrorCode errorCode, final String errorMessage ) { Objects.requireNonNull(rejectingLinkId, "rejectingLinkId must not be null"); Objects.requireNonNull(preparePacket, "preparePacket must not be null"); Objects.requireNonNull(errorCode, "errorCode must not be null"); Objects.requireNonNull(errorMessage, "errorMessage must not be null"); final InterledgerRejectPacket rejectPacket = InterledgerRejectPacket.builder() .triggeredBy(operatorAddressSupplier.get()) .code(errorCode) .message(errorMessage) .build(); logger.debug( "Rejecting inside linkId={}: PreparePacket={} RejectPacket={}", rejectingLinkId, preparePacket, rejectPacket ); return rejectPacket; } PacketRejector(final Supplier<InterledgerAddress> operatorAddressSupplier); InterledgerRejectPacket reject( final LinkId rejectingLinkId, final InterledgerPreparePacket preparePacket, final InterledgerErrorCode errorCode, final String errorMessage ); }### Answer: @Test(expected = NullPointerException.class) public void nullLinkId() { try { packetRejector.reject(null, PREPARE_PACKET, InterledgerErrorCode.T02_PEER_BUSY, ""); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("rejectingLinkId must not be null"); throw e; } } @Test(expected = NullPointerException.class) public void nullPreparePacket() { try { packetRejector.reject(LINK_ID, null, InterledgerErrorCode.T02_PEER_BUSY, ""); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("preparePacket must not be null"); throw e; } } @Test(expected = NullPointerException.class) public void nullErrorCode() { try { packetRejector.reject(LINK_ID, PREPARE_PACKET, null, ""); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("errorCode must not be null"); throw e; } } @Test(expected = NullPointerException.class) public void nullErrorMessage() { try { packetRejector.reject(LINK_ID, PREPARE_PACKET, InterledgerErrorCode.T02_PEER_BUSY, null); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("errorMessage must not be null"); throw e; } } @Test public void testReject() { InterledgerRejectPacket reject = packetRejector .reject(LINK_ID, PREPARE_PACKET, InterledgerErrorCode.T02_PEER_BUSY, "the error"); assertThat(reject.getCode()).isEqualTo(InterledgerErrorCode.T02_PEER_BUSY); assertThat(reject.getTriggeredBy().get()).isEqualTo(OPERATOR_ADDRESS); assertThat(reject.getMessage()).isEqualTo("the error"); assertThat(reject.getData().length).isEqualTo(0); }
### Question: AsnInterledgerAddressCodec extends AsnIA5StringBasedObjectCodec<InterledgerAddress> { @Override public InterledgerAddress decode() { return Optional.ofNullable(getCharString()) .filter(charString -> !"".equals(charString)) .map(InterledgerAddress::of) .orElse(null); } AsnInterledgerAddressCodec(); @Override InterledgerAddress decode(); @Override void encode(InterledgerAddress value); }### Answer: @Test public void decode() { assertThat(codec.decode()).isEqualTo(InterledgerAddress.of(G_FOO)); }
### Question: LinkException extends RuntimeException { public LinkId getLinkId() { return linkId; } LinkException(LinkId linkId); LinkException(String message, LinkId linkId); LinkException(String message, Throwable cause, LinkId linkId); LinkException(Throwable cause, LinkId linkId); LinkException( String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, LinkId linkId ); LinkId getLinkId(); @Override String toString(); }### Answer: @Test public void getLinkId() { assertThat(new LinkException(LinkId.of("foo")).getLinkId().value()).isEqualTo("foo"); }
### Question: LinkException extends RuntimeException { @Override public String toString() { String linkIdMessage = "LinkId=" + getLinkId(); String className = getClass().getName(); String message = getLocalizedMessage() == null ? linkIdMessage : getLocalizedMessage() + " " + linkIdMessage; return (className + ": " + message); } LinkException(LinkId linkId); LinkException(String message, LinkId linkId); LinkException(String message, Throwable cause, LinkId linkId); LinkException(Throwable cause, LinkId linkId); LinkException( String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, LinkId linkId ); LinkId getLinkId(); @Override String toString(); }### Answer: @Test public void testToStringWithNullMessage() { assertThat(new LinkException(LinkId.of("foo")).toString()) .isEqualTo("org.interledger.link.exceptions.LinkException: LinkId=LinkId(foo)"); } @Test public void testToString() { assertThat(new LinkException("hello", LinkId.of("foo")).toString()) .isEqualTo("org.interledger.link.exceptions.LinkException: hello LinkId=LinkId(foo)"); }
### Question: PingLoopbackLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public void registerLinkHandler(LinkHandler ilpDataHandler) throws LinkHandlerAlreadyRegisteredException { throw new RuntimeException( "PingLoopback links never have incoming data, and thus should not have a registered DataHandler." ); } PingLoopbackLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override void registerLinkHandler(LinkHandler ilpDataHandler); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override String toString(); static final String LINK_TYPE_STRING; static final LinkType LINK_TYPE; static final InterledgerFulfillment PING_PROTOCOL_FULFILLMENT; static final InterledgerCondition PING_PROTOCOL_CONDITION; }### Answer: @Test(expected = RuntimeException.class) public void registerLinkHandler() { try { link.registerLinkHandler(incomingPreparePacket -> null); } catch (Exception e) { assertThat(e.getMessage()).isEqualTo( "PingLoopback links never have incoming data, and thus should not have a registered DataHandler."); throw e; } }
### Question: PingLoopbackLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket) { Objects.requireNonNull(preparePacket, "preparePacket must not be null!"); if (preparePacket.getExecutionCondition().equals(PING_PROTOCOL_CONDITION)) { return InterledgerFulfillPacket.builder() .fulfillment(PING_PROTOCOL_FULFILLMENT) .data(preparePacket.getData()) .build(); } else { final InterledgerRejectPacket rejectPacket = InterledgerRejectPacket.builder() .triggeredBy(getOperatorAddressSupplier().get()) .code(InterledgerErrorCode.F00_BAD_REQUEST) .message("Invalid Ping Protocol Condition") .build(); logger.warn( "Rejecting Unidirectional Ping packet: PreparePacket={} RejectPacket={}", preparePacket, rejectPacket ); return rejectPacket; } } PingLoopbackLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override void registerLinkHandler(LinkHandler ilpDataHandler); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override String toString(); static final String LINK_TYPE_STRING; static final LinkType LINK_TYPE; static final InterledgerFulfillment PING_PROTOCOL_FULFILLMENT; static final InterledgerCondition PING_PROTOCOL_CONDITION; }### Answer: @Test(expected = NullPointerException.class) public void sendPacketWithNull() { try { link.sendPacket(null); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("preparePacket must not be null!"); throw e; } } @Test public void sendPacketWithInvalidCondition() { final InterledgerPreparePacket preparePacket = InterledgerPreparePacket.builder() .amount(UnsignedLong.valueOf(10L)) .executionCondition(InterledgerCondition.of(new byte[32])) .destination(OPERATOR_ADDRESS) .expiresAt(DateUtils.now()) .build(); link.sendPacket(preparePacket).handle(fulfillPacket -> { logger.error("InterledgerFulfillPacket: {}", fulfillPacket); fail("Expected a Reject!"); }, rejectPacket -> { assertThat(rejectPacket.getCode()).isEqualTo(InterledgerErrorCode.F00_BAD_REQUEST); assertThat(rejectPacket.getTriggeredBy().isPresent()).isEqualTo(true); assertThat(rejectPacket.getTriggeredBy()).isEqualTo(EXPECTED_REJECT_PACKET.getTriggeredBy()); } ); } @Test public void sendPacketWithInvalidAddress() { final InterledgerPreparePacket preparePacket = InterledgerPreparePacket.builder() .amount(UnsignedLong.valueOf(10L)) .executionCondition(PING_PROTOCOL_CONDITION) .destination(InterledgerAddress.of("example.foo")) .expiresAt(DateUtils.now()) .build(); link.sendPacket(preparePacket).handle( fulfillPacket -> assertThat(fulfillPacket.getFulfillment()).isEqualTo(PING_PROTOCOL_FULFILLMENT), rejectPacket -> { logger.error("InterledgerRejectPacket: {}", rejectPacket); fail("Expected a Fulfill!"); } ); } @Test public void sendPacket() { final InterledgerPreparePacket preparePacket = InterledgerPreparePacket.builder() .amount(UnsignedLong.valueOf(10L)) .executionCondition(PING_PROTOCOL_CONDITION) .destination(OPERATOR_ADDRESS) .expiresAt(DateUtils.now()) .build(); link.sendPacket(preparePacket).handle( fulfillPacket -> assertThat(fulfillPacket.getFulfillment()).isEqualTo(PING_PROTOCOL_FULFILLMENT), rejectPacket -> { logger.error("InterledgerRejectPacket: {}", rejectPacket); fail("Expected a Fulfill!"); } ); }