target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void propertyBridge() { PropertyBridgeWriteContext context = new SessionBasedBridgeOperationContext( sessionContext ); assertThat( context.extension( HibernateOrmExtension.get() ) ).isSameAs( sessionContext ); } | public static HibernateOrmExtension get() { return INSTANCE; } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } |
@Test public void valueBridge() { ValueBridgeToIndexedValueContext toIndexedValueContext = new ValueBridgeToIndexedValueContextImpl( mappingContext ); assertThat( toIndexedValueContext.extension( HibernateOrmExtension.get() ) ).isSameAs( mappingContext ); ValueBridgeFromIndexedValueContext fromIndexedValueContext = new SessionBasedBridgeOperationContext( sessionContext ); assertThat( fromIndexedValueContext.extension( HibernateOrmExtension.get() ) ).isSameAs( sessionContext ); } | public static HibernateOrmExtension get() { return INSTANCE; } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } |
@Test public void toIndexValueConverter() { ToDocumentFieldValueConvertContext context = new ToDocumentFieldValueConvertContextImpl( mappingContext ); assertThat( context.extension( HibernateOrmExtension.get() ) ).isSameAs( mappingContext ); } | public static HibernateOrmExtension get() { return INSTANCE; } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } |
@Test public void fromIndexValueConverter() { FromDocumentFieldValueConvertContext context = new FromDocumentFieldValueConvertContextImpl( sessionContext ); assertThat( context.extension( HibernateOrmExtension.get() ) ).isSameAs( sessionContext ); } | public static HibernateOrmExtension get() { return INSTANCE; } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } | HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>,
IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>,
RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>,
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContextExtension<HibernateOrmSessionContext>,
TypeBridgeWriteContextExtension<HibernateOrmSessionContext>,
PropertyBridgeWriteContextExtension<HibernateOrmSessionContext>,
ValueBridgeToIndexedValueContextExtension<HibernateOrmMappingContext>,
ValueBridgeFromIndexedValueContextExtension<HibernateOrmSessionContext>,
ToDocumentFieldValueConvertContextExtension<HibernateOrmMappingContext>,
FromDocumentFieldValueConvertContextExtension<HibernateOrmSessionContext> { public static HibernateOrmExtension get() { return INSTANCE; } private HibernateOrmExtension(); static HibernateOrmExtension get(); @Override Optional<HibernateOrmMappingContext> extendOptional(IdentifierBridgeToDocumentIdentifierContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(IdentifierBridgeFromDocumentIdentifierContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(RoutingBridgeRouteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(
org.hibernate.search.mapper.pojo.bridge.runtime.RoutingKeyBridgeToRoutingKeyContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(TypeBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmSessionContext> extendOptional(PropertyBridgeWriteContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ValueBridgeToIndexedValueContext original,
BridgeMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(ValueBridgeFromIndexedValueContext original,
BridgeSessionContext sessionContext); @Override Optional<HibernateOrmMappingContext> extendOptional(ToDocumentFieldValueConvertContext original,
BackendMappingContext mappingContext); @Override Optional<HibernateOrmSessionContext> extendOptional(FromDocumentFieldValueConvertContext original,
BackendSessionContext sessionContext); } |
@Test public void resolve_withoutBeanConfigurer() { when( serviceResolverMock.loadJavaServices( BeanConfigurer.class ) ) .thenReturn( Collections.emptyList() ); when( configurationSourceMock.get( EngineSpiSettings.Radicals.BEAN_CONFIGURERS ) ) .thenReturn( Optional.empty() ); BeanResolver beanResolver = new ConfiguredBeanResolver( serviceResolverMock, beanProviderMock, configurationSourceMock ); verifyNoOtherInteractionsAndReset(); BeanHolder<Type1> type1BeanHolder = BeanHolder.of( new Type1() ); BeanHolder<Type2> type2BeanHolder = BeanHolder.of( new Type2() ); BeanHolder<Type3> type3BeanHolder1 = BeanHolder.of( new Type3() ); BeanHolder<Type3> type3BeanHolder2 = BeanHolder.of( new Type3() ); when( beanProviderMock.forType( Type1.class ) ).thenReturn( type1BeanHolder ); assertThat( beanResolver.resolve( Type1.class ) ).isSameAs( type1BeanHolder ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forType( Type1.class ) ).thenReturn( type1BeanHolder ); assertThat( beanResolver.resolve( BeanReference.of( Type1.class ) ) ).isSameAs( type1BeanHolder ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forTypeAndName( Type2.class, "someName" ) ).thenReturn( type2BeanHolder ); assertThat( beanResolver.resolve( Type2.class, "someName" ) ).isSameAs( type2BeanHolder ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forTypeAndName( Type2.class, "someName" ) ).thenReturn( type2BeanHolder ); assertThat( beanResolver.resolve( BeanReference.of( Type2.class, "someName" ) ) ).isSameAs( type2BeanHolder ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forType( Type3.class ) ).thenReturn( type3BeanHolder1 ); when( beanProviderMock.forTypeAndName( Type3.class, "someOtherName" ) ).thenReturn( type3BeanHolder2 ); BeanHolder<List<Type3>> beans = beanResolver.resolve( Arrays.asList( BeanReference.of( Type3.class ), BeanReference.of( Type3.class, "someOtherName" ) ) ); verifyNoOtherInteractionsAndReset(); assertThat( beans.get() ) .containsExactly( type3BeanHolder1.get(), type3BeanHolder2.get() ); } | @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } |
@Test public void resolve_withBeanConfigurer() { BeanReference<Type1> beanReference1Mock = beanReferenceMock(); BeanReference<Type2> beanReference2Mock = beanReferenceMock(); BeanReference<Type3> beanReference3Mock = beanReferenceMock(); BeanReference<Type3> beanReference4Mock = beanReferenceMock(); BeanConfigurer beanConfigurer1 = context -> { context.define( Type1.class, beanReference1Mock ); context.define( Type2.class, "someName", beanReference2Mock ); context.define( Type3.class, "someOtherName1", beanReference3Mock ); }; BeanConfigurer beanConfigurer2 = context -> { context.define( Type3.class, "someOtherName2", beanReference4Mock ); }; when( serviceResolverMock.loadJavaServices( BeanConfigurer.class ) ) .thenReturn( Collections.singletonList( beanConfigurer1 ) ); when( configurationSourceMock.get( EngineSpiSettings.Radicals.BEAN_CONFIGURERS ) ) .thenReturn( (Optional) Optional.of( Collections.singletonList( beanConfigurer2 ) ) ); BeanResolver beanResolver = new ConfiguredBeanResolver( serviceResolverMock, beanProviderMock, configurationSourceMock ); verifyNoOtherInteractionsAndReset(); BeanHolder<Type1> type1BeanHolder = BeanHolder.of( new Type1() ); BeanHolder<Type2> type2BeanHolder = BeanHolder.of( new Type2() ); BeanHolder<Type3> type3BeanHolder1 = BeanHolder.of( new Type3() ); BeanHolder<Type3> type3BeanHolder2 = BeanHolder.of( new Type3() ); when( beanProviderMock.forType( Type1.class ) ) .thenThrow( new SearchException( "cannot find Type1" ) ); when( beanReference1Mock.resolve( any() ) ).thenReturn( type1BeanHolder ); assertThat( beanResolver.resolve( Type1.class ) ).isSameAs( type1BeanHolder ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forTypeAndName( Type2.class, "someName" ) ) .thenThrow( new SearchException( "cannot find Type2#someName" ) ); when( beanReference2Mock.resolve( any() ) ).thenReturn( type2BeanHolder ); assertThat( beanResolver.resolve( Type2.class, "someName" ) ).isSameAs( type2BeanHolder ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forTypeAndName( Type3.class, "someOtherName1" ) ) .thenThrow( new SearchException( "cannot find Type3#someOtherName" ) ); when( beanProviderMock.forTypeAndName( Type3.class, "someOtherName2" ) ) .thenThrow( new SearchException( "cannot find Type3#someOtherName2" ) ); when( beanReference3Mock.resolve( any() ) ).thenReturn( type3BeanHolder1 ); when( beanReference4Mock.resolve( any() ) ).thenReturn( type3BeanHolder2 ); BeanHolder<List<Type3>> beans = beanResolver.resolve( Arrays.asList( BeanReference.of( Type3.class, "someOtherName1" ), BeanReference.of( Type3.class, "someOtherName2" ) ) ); verifyNoOtherInteractionsAndReset(); assertThat( beans.get() ) .containsExactly( type3BeanHolder1.get(), type3BeanHolder2.get() ); } | @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } |
@Test public void resolve_noBean() { when( serviceResolverMock.loadJavaServices( BeanConfigurer.class ) ) .thenReturn( Collections.emptyList() ); when( configurationSourceMock.get( EngineSpiSettings.Radicals.BEAN_CONFIGURERS ) ) .thenReturn( (Optional) Optional.empty() ); BeanResolver beanResolver = new ConfiguredBeanResolver( serviceResolverMock, beanProviderMock, configurationSourceMock ); verifyNoOtherInteractionsAndReset(); SearchException providerType1NotFound = new SearchException( "cannot find Type1" ); when( beanProviderMock.forType( Type1.class ) ).thenThrow( providerType1NotFound ); assertThatThrownBy( () -> beanResolver.resolve( Type1.class ) ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Cannot resolve bean reference to type '" + Type1.class.getName() + "'", " cannot find Type1" ) .hasCauseReference( providerType1NotFound ); verifyNoOtherInteractionsAndReset(); SearchException providerType2NotFound = new SearchException( "cannot find Type2#someName" ); when( beanProviderMock.forTypeAndName( Type2.class, "someName" ) ) .thenThrow( providerType2NotFound ); assertThatThrownBy( () -> beanResolver.resolve( Type2.class, "someName" ) ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Cannot resolve bean reference to type '" + Type2.class.getName() + "' and name 'someName'", "cannot find Type2#someName" ) .hasCauseReference( providerType2NotFound ); verifyNoOtherInteractionsAndReset(); } | @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } |
@Test public void javaIOCloseable() { Throwable mainException = new Exception(); IOException exception1 = new IOException(); RuntimeException exception2 = new IllegalStateException(); @SuppressWarnings("resource") Closeable closeable = () -> { throw exception1; }; new SuppressingCloser( mainException ) .push( closeable ) .push( ignored -> { throw exception2; }, new Object() ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ); } | public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); } |
@Test public void resolve_withBeanConfigurer_providerFailure() { BeanReference<Type1> beanReference1Mock = beanReferenceMock(); BeanReference<Type1> beanReference2Mock = beanReferenceMock(); BeanConfigurer beanConfigurer1 = context -> { context.define( Type1.class, beanReference1Mock ); }; BeanConfigurer beanConfigurer2 = context -> { context.define( Type1.class, "someName", beanReference2Mock ); }; when( serviceResolverMock.loadJavaServices( BeanConfigurer.class ) ) .thenReturn( Collections.singletonList( beanConfigurer1 ) ); when( configurationSourceMock.get( EngineSpiSettings.Radicals.BEAN_CONFIGURERS ) ) .thenReturn( (Optional) Optional.of( Collections.singletonList( beanConfigurer2 ) ) ); BeanResolver beanResolver = new ConfiguredBeanResolver( serviceResolverMock, beanProviderMock, configurationSourceMock ); verifyNoOtherInteractionsAndReset(); RuntimeException providerFailure = new RuntimeException( "internal failure in provider" ); when( beanProviderMock.forType( Type1.class ) ).thenThrow( providerFailure ); assertThatThrownBy( () -> beanResolver.resolve( Type1.class ) ).isSameAs( providerFailure ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forTypeAndName( Type2.class, "someName" ) ).thenThrow( providerFailure ); assertThatThrownBy( () -> beanResolver.resolve( Type2.class, "someName" ) ) .isSameAs( providerFailure ); verifyNoOtherInteractionsAndReset(); } | @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } |
@Test public void resolve_withBeanConfigurer_noProviderBean_configuredBeanFailure() { BeanReference<Type1> beanReference1Mock = beanReferenceMock(); BeanReference<Type2> beanReference2Mock = beanReferenceMock(); BeanConfigurer beanConfigurer1 = context -> { context.define( Type1.class, beanReference1Mock ); }; BeanConfigurer beanConfigurer2 = context -> { context.define( Type2.class, "someName", beanReference2Mock ); }; when( serviceResolverMock.loadJavaServices( BeanConfigurer.class ) ) .thenReturn( Collections.singletonList( beanConfigurer1 ) ); when( configurationSourceMock.get( EngineSpiSettings.Radicals.BEAN_CONFIGURERS ) ) .thenReturn( (Optional) Optional.of( Collections.singletonList( beanConfigurer2 ) ) ); BeanResolver beanResolver = new ConfiguredBeanResolver( serviceResolverMock, beanProviderMock, configurationSourceMock ); verifyNoOtherInteractionsAndReset(); SearchException providerType1NotFound = new SearchException( "cannot find Type1" ); RuntimeException configuredBeanType1Failed = new RuntimeException( "configured bean failed for Type1" ); when( beanProviderMock.forType( Type1.class ) ).thenThrow( providerType1NotFound ); when( beanReference1Mock.resolve( any() ) ).thenThrow( configuredBeanType1Failed ); assertThatThrownBy( () -> beanResolver.resolve( Type1.class ) ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Cannot resolve bean reference to type '" + Type1.class.getName() + "'", "cannot find Type1", "configured bean failed for Type1" ) .hasCauseReference( providerType1NotFound ) .hasSuppressedException( configuredBeanType1Failed ); verifyNoOtherInteractionsAndReset(); SearchException providerType2NotFound = new SearchException( "provider cannot find Type2#someName" ); RuntimeException configuredBeanType2Failed = new RuntimeException( "configured bean failed for Type2#someName" ); when( beanProviderMock.forTypeAndName( Type2.class, "someName" ) ) .thenThrow( providerType2NotFound ); when( beanReference2Mock.resolve( any() ) ).thenThrow( configuredBeanType2Failed ); assertThatThrownBy( () -> beanResolver.resolve( Type2.class, "someName" ) ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Cannot resolve bean reference to type '" + Type2.class.getName() + "' and name 'someName'", "provider cannot find Type2#someName", "configured bean failed for Type2#someName" ) .hasCauseReference( providerType2NotFound ) .hasSuppressedException( configuredBeanType2Failed ); verifyNoOtherInteractionsAndReset(); } | @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } |
@Test public void resolve_withBeanConfigurer_multipleBeans() { BeanReference<Type1> beanReference1Mock = beanReferenceMock(); BeanReference<Type1> beanReference2Mock = beanReferenceMock(); BeanConfigurer beanConfigurer1 = context -> { context.define( Type1.class, beanReference1Mock ); }; BeanConfigurer beanConfigurer2 = context -> { context.define( Type1.class, "someName", beanReference2Mock ); }; when( serviceResolverMock.loadJavaServices( BeanConfigurer.class ) ) .thenReturn( Collections.singletonList( beanConfigurer1 ) ); when( configurationSourceMock.get( EngineSpiSettings.Radicals.BEAN_CONFIGURERS ) ) .thenReturn( (Optional) Optional.of( Collections.singletonList( beanConfigurer2 ) ) ); BeanResolver beanResolver = new ConfiguredBeanResolver( serviceResolverMock, beanProviderMock, configurationSourceMock ); verifyNoOtherInteractionsAndReset(); when( beanProviderMock.forType( Type1.class ) ) .thenThrow( new SearchException( "cannot find Type1" ) ); assertThatThrownBy( () -> beanResolver.resolve( Type1.class ) ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Cannot resolve bean reference to type '" + Type1.class.getName() + "'", "cannot find Type1", "Multiple beans registered for type '" + Type1.class.getName() + "'" ); verifyNoOtherInteractionsAndReset(); } | @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } | ConfiguredBeanResolver implements BeanResolver { @Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } } ConfiguredBeanResolver(ServiceResolver serviceResolver, BeanProvider beanProvider,
ConfigurationPropertySource configurationPropertySource); @Override BeanHolder<T> resolve(Class<T> typeReference); @Override BeanHolder<T> resolve(Class<T> typeReference, String nameReference); @Override List<BeanReference<T>> allConfiguredForRole(Class<T> role); @Override Map<String, BeanReference<T>> namedConfiguredForRole(Class<T> role); } |
@Test public void backendKey() { assertThat( BackendSettings.backendKey( "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.foo.bar" ); assertThat( BackendSettings.backendKey( "myBackend", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.myBackend.foo.bar" ); assertThat( BackendSettings.backendKey( null, "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.foo.bar" ); } | public static String backendKey(String radical) { return join( ".", EngineSettings.BACKEND, radical ); } | BackendSettings { public static String backendKey(String radical) { return join( ".", EngineSettings.BACKEND, radical ); } } | BackendSettings { public static String backendKey(String radical) { return join( ".", EngineSettings.BACKEND, radical ); } private BackendSettings(); } | BackendSettings { public static String backendKey(String radical) { return join( ".", EngineSettings.BACKEND, radical ); } private BackendSettings(); static String backendKey(String radical); static String backendKey(String backendName, String radical); } | BackendSettings { public static String backendKey(String radical) { return join( ".", EngineSettings.BACKEND, radical ); } private BackendSettings(); static String backendKey(String radical); static String backendKey(String backendName, String radical); static final String TYPE; @Deprecated
static final String INDEX_DEFAULTS; static final String INDEXES; } |
@Test public void indexKey() { assertThat( IndexSettings.indexKey( "indexName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.indexes.indexName.foo.bar" ); assertThat( IndexSettings.indexKey( "backendName", "indexName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.backendName.indexes.indexName.foo.bar" ); assertThat( IndexSettings.indexKey( null, "indexName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.indexes.indexName.foo.bar" ); } | public static String indexKey(String indexName, String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEXES, indexName, radical ); } | IndexSettings { public static String indexKey(String indexName, String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEXES, indexName, radical ); } } | IndexSettings { public static String indexKey(String indexName, String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEXES, indexName, radical ); } private IndexSettings(); } | IndexSettings { public static String indexKey(String indexName, String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEXES, indexName, radical ); } private IndexSettings(); @Deprecated static String indexDefaultsKey(String radical); static String indexKey(String indexName, String radical); @Deprecated static String indexDefaultsKey(String backendName, String radical); static String indexKey(String backendName, String indexName, String radical); } | IndexSettings { public static String indexKey(String indexName, String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEXES, indexName, radical ); } private IndexSettings(); @Deprecated static String indexDefaultsKey(String radical); static String indexKey(String indexName, String radical); @Deprecated static String indexDefaultsKey(String backendName, String radical); static String indexKey(String backendName, String indexName, String radical); } |
@Test @SuppressWarnings("deprecation") public void indexDefaultsKey() { assertThat( IndexSettings.indexDefaultsKey( "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.index_defaults.foo.bar" ); assertThat( IndexSettings.indexDefaultsKey( "backendName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.backendName.index_defaults.foo.bar" ); assertThat( IndexSettings.indexDefaultsKey( null, "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.index_defaults.foo.bar" ); } | @Deprecated public static String indexDefaultsKey(String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEX_DEFAULTS, radical ); } | IndexSettings { @Deprecated public static String indexDefaultsKey(String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEX_DEFAULTS, radical ); } } | IndexSettings { @Deprecated public static String indexDefaultsKey(String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEX_DEFAULTS, radical ); } private IndexSettings(); } | IndexSettings { @Deprecated public static String indexDefaultsKey(String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEX_DEFAULTS, radical ); } private IndexSettings(); @Deprecated static String indexDefaultsKey(String radical); static String indexKey(String indexName, String radical); @Deprecated static String indexDefaultsKey(String backendName, String radical); static String indexKey(String backendName, String indexName, String radical); } | IndexSettings { @Deprecated public static String indexDefaultsKey(String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEX_DEFAULTS, radical ); } private IndexSettings(); @Deprecated static String indexDefaultsKey(String radical); static String indexKey(String indexName, String radical); @Deprecated static String indexDefaultsKey(String backendName, String radical); static String indexKey(String backendName, String indexName, String radical); } |
@Test public void parseGeoPoint() { GeoPoint geoPoint = ParseUtils.parseGeoPoint( "12.123, -24.234" ); assertThat( geoPoint ).isEqualTo( GeoPoint.of( 12.123, -24.234 ) ); geoPoint = ParseUtils.parseGeoPoint( "12.123,-24.234" ); assertThat( geoPoint ).isEqualTo( GeoPoint.of( 12.123, -24.234 ) ); geoPoint = ParseUtils.parseGeoPoint( "12.123, -24.234" ); assertThat( geoPoint ).isEqualTo( GeoPoint.of( 12.123, -24.234 ) ); assertThatThrownBy( () -> ParseUtils.parseGeoPoint( "12.123#-24.234" ) ) .hasMessage( "HSEARCH000564: Unable to parse the provided geo-point value: '12.123#-24.234'. The expected format is latitude, longitude." ); assertThatThrownBy( () -> ParseUtils.parseGeoPoint( "12.123" ) ) .hasMessage( "HSEARCH000564: Unable to parse the provided geo-point value: '12.123'. The expected format is latitude, longitude." ); } | public static GeoPoint parseGeoPoint(String value) { String[] split = value.split( GEO_POINT_SEPARATOR ); if ( split.length != 2 ) { throw log.unableToParseGeoPoint( value ); } try { return GeoPoint.of( Double.parseDouble( split[0] ), Double.parseDouble( split[1] ) ); } catch (NumberFormatException e) { throw log.unableToParseGeoPoint( value ); } } | ParseUtils { public static GeoPoint parseGeoPoint(String value) { String[] split = value.split( GEO_POINT_SEPARATOR ); if ( split.length != 2 ) { throw log.unableToParseGeoPoint( value ); } try { return GeoPoint.of( Double.parseDouble( split[0] ), Double.parseDouble( split[1] ) ); } catch (NumberFormatException e) { throw log.unableToParseGeoPoint( value ); } } } | ParseUtils { public static GeoPoint parseGeoPoint(String value) { String[] split = value.split( GEO_POINT_SEPARATOR ); if ( split.length != 2 ) { throw log.unableToParseGeoPoint( value ); } try { return GeoPoint.of( Double.parseDouble( split[0] ), Double.parseDouble( split[1] ) ); } catch (NumberFormatException e) { throw log.unableToParseGeoPoint( value ); } } private ParseUtils(); } | ParseUtils { public static GeoPoint parseGeoPoint(String value) { String[] split = value.split( GEO_POINT_SEPARATOR ); if ( split.length != 2 ) { throw log.unableToParseGeoPoint( value ); } try { return GeoPoint.of( Double.parseDouble( split[0] ), Double.parseDouble( split[1] ) ); } catch (NumberFormatException e) { throw log.unableToParseGeoPoint( value ); } } private ParseUtils(); static String parseString(String value); static Instant parseInstant(String value); static LocalDate parseLocalDate(String value); static LocalDateTime parseLocalDateTime(String value); static LocalTime parseLocalTime(String value); static OffsetDateTime parseOffsetDateTime(String value); static OffsetTime parseOffsetTime(String value); static ZonedDateTime parseZonedDateTime(String value); static Year parseYear(String value); static YearMonth parseYearMonth(String value); static MonthDay parseMonthDay(String value); static ZoneOffset parseZoneOffset(String value); static Period parsePeriod(String value); static Duration parseDuration(String value); static GeoPoint parseGeoPoint(String value); } | ParseUtils { public static GeoPoint parseGeoPoint(String value) { String[] split = value.split( GEO_POINT_SEPARATOR ); if ( split.length != 2 ) { throw log.unableToParseGeoPoint( value ); } try { return GeoPoint.of( Double.parseDouble( split[0] ), Double.parseDouble( split[1] ) ); } catch (NumberFormatException e) { throw log.unableToParseGeoPoint( value ); } } private ParseUtils(); static String parseString(String value); static Instant parseInstant(String value); static LocalDate parseLocalDate(String value); static LocalDateTime parseLocalDateTime(String value); static LocalTime parseLocalTime(String value); static OffsetDateTime parseOffsetDateTime(String value); static OffsetTime parseOffsetTime(String value); static ZonedDateTime parseZonedDateTime(String value); static Year parseYear(String value); static YearMonth parseYearMonth(String value); static MonthDay parseMonthDay(String value); static ZoneOffset parseZoneOffset(String value); static Period parsePeriod(String value); static Duration parseDuration(String value); static GeoPoint parseGeoPoint(String value); } |
@Test public void genericContext_runtimeException() { RuntimeException runtimeException = new SimulatedRuntimeException(); logged.expectEvent( Level.ERROR, sameInstance( runtimeException ), "failure handler threw an exception" ); doThrow( runtimeException ).when( failureHandlerMock ).handle( any( FailureContext.class ) ); wrapper.handle( FailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); } | @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } |
@Test public void genericContext_error() { Error error = new SimulatedError(); logged.expectEvent( Level.ERROR, sameInstance( error ), "failure handler threw an exception" ); doThrow( error ).when( failureHandlerMock ).handle( any( FailureContext.class ) ); wrapper.handle( FailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); } | @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } |
@Test public void entityIndexingContext_runtimeException() { RuntimeException runtimeException = new SimulatedRuntimeException(); logged.expectEvent( Level.ERROR, sameInstance( runtimeException ), "failure handler threw an exception" ); doThrow( runtimeException ).when( failureHandlerMock ).handle( any( EntityIndexingFailureContext.class ) ); wrapper.handle( EntityIndexingFailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); } | @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } |
@Test public void autoCloseable() { Throwable mainException = new Exception(); Exception exception1 = new Exception(); RuntimeException exception2 = new IllegalStateException(); @SuppressWarnings("resource") AutoCloseable closeable = () -> { throw exception1; }; new SuppressingCloser( mainException ) .push( closeable ) .push( ignored -> { throw exception2; }, new Object() ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ); } | public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); } |
@Test public void entityIndexingContext_error() { Error error = new SimulatedError(); logged.expectEvent( Level.ERROR, sameInstance( error ), "failure handler threw an exception" ); doThrow( error ).when( failureHandlerMock ).handle( any( EntityIndexingFailureContext.class ) ); wrapper.handle( EntityIndexingFailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); } | @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } | FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); } |
@Test public void error_missingBackendType_nullType() { String keyPrefix = "somePrefix."; ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass( Throwable.class ); when( configurationSourceMock.get( "default_backend" ) ) .thenReturn( (Optional) Optional.empty() ); IndexManagerBuildingStateHolder holder = new IndexManagerBuildingStateHolder( beanResolverMock, configurationSourceMock, rootBuildContextMock ); verifyNoOtherBackendInteractionsAndReset(); when( configurationSourceMock.get( "backend.type" ) ) .thenReturn( Optional.empty() ); when( beanResolverMock.namedConfiguredForRole( BackendFactory.class ) ) .thenReturn( Collections.emptyMap() ); when( configurationSourceMock.resolve( "backend.type" ) ) .thenReturn( Optional.of( keyPrefix + "backend.type" ) ); when( rootBuildContextMock.getFailureCollector() ) .thenReturn( rootFailureCollectorMock ); when( rootFailureCollectorMock.withContext( EventContexts.defaultBackend() ) ) .thenReturn( backendFailureCollectorMock ); holder.createBackends( CollectionHelper.asSet( Optional.empty() ) ); verify( backendFailureCollectorMock ).add( throwableCaptor.capture() ); verifyNoOtherBackendInteractionsAndReset(); assertThat( throwableCaptor.getValue() ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Configuration property 'somePrefix.backend.type' is not set, and no backend was found in the classpath", "Did you forget to add the desired backend to your project's dependencies?" ); } | void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } IndexManagerBuildingStateHolder(BeanResolver beanResolver, ConfigurationPropertySource propertySource,
RootBuildContext rootBuildContext); } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } IndexManagerBuildingStateHolder(BeanResolver beanResolver, ConfigurationPropertySource propertySource,
RootBuildContext rootBuildContext); } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } IndexManagerBuildingStateHolder(BeanResolver beanResolver, ConfigurationPropertySource propertySource,
RootBuildContext rootBuildContext); } |
@Test public void error_missingBackendType_emptyType() { String keyPrefix = "somePrefix."; ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass( Throwable.class ); when( configurationSourceMock.get( "default_backend" ) ) .thenReturn( (Optional) Optional.empty() ); IndexManagerBuildingStateHolder holder = new IndexManagerBuildingStateHolder( beanResolverMock, configurationSourceMock, rootBuildContextMock ); verifyNoOtherBackendInteractionsAndReset(); when( configurationSourceMock.get( "backend.type" ) ) .thenReturn( (Optional) Optional.of( "" ) ); when( beanResolverMock.namedConfiguredForRole( BackendFactory.class ) ) .thenReturn( Collections.emptyMap() ); when( configurationSourceMock.resolve( "backend.type" ) ) .thenReturn( Optional.of( keyPrefix + "backend.type" ) ); when( rootBuildContextMock.getFailureCollector() ) .thenReturn( rootFailureCollectorMock ); when( rootFailureCollectorMock.withContext( EventContexts.defaultBackend() ) ) .thenReturn( backendFailureCollectorMock ); holder.createBackends( CollectionHelper.asSet( Optional.empty() ) ); verify( backendFailureCollectorMock ).add( throwableCaptor.capture() ); verifyNoOtherBackendInteractionsAndReset(); assertThat( throwableCaptor.getValue() ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Configuration property 'somePrefix.backend.type' is not set, and no backend was found in the classpath", "Did you forget to add the desired backend to your project's dependencies?" ); } | void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } IndexManagerBuildingStateHolder(BeanResolver beanResolver, ConfigurationPropertySource propertySource,
RootBuildContext rootBuildContext); } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } IndexManagerBuildingStateHolder(BeanResolver beanResolver, ConfigurationPropertySource propertySource,
RootBuildContext rootBuildContext); } | IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } IndexManagerBuildingStateHolder(BeanResolver beanResolver, ConfigurationPropertySource propertySource,
RootBuildContext rootBuildContext); } |
@Test public void simple_batchEndsImmediately() throws InterruptedException { createAndStartExecutor( 2, true ); StubWork work1Mock = workMock( 1 ); CompletableFuture<Object> batch1Future = CompletableFuture.completedFuture( null ); when( processorMock.endBatch() ).thenReturn( (CompletableFuture) batch1Future ); executor.submit( work1Mock ); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).beginBatch(); inOrder.verify( work1Mock ).submitTo( processorMock ); inOrder.verify( processorMock ).endBatch(); inOrder.verify( processorMock ).complete(); } ); checkPostExecution(); } | public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } |
@Test public void simple_batchEndsLater_someAdditionalWorkBeforeComplete() throws InterruptedException { createAndStartExecutor( 2, true ); StubWork work1Mock = workMock( 1 ); CompletableFuture<Object> batch1Future = new CompletableFuture<>(); when( processorMock.endBatch() ).thenReturn( (CompletableFuture) batch1Future ); executor.submit( work1Mock ); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).beginBatch(); inOrder.verify( work1Mock ).submitTo( processorMock ); inOrder.verify( processorMock ).endBatch(); } ); StubCompletionListener completionListenerAfterSubmit1 = addPendingCompletionListener(); StubWork work2Mock = workMock( 2 ); StubWork work3Mock = workMock( 3 ); executor.submit( work2Mock ); executor.submit( work3Mock ); verifyAsynchronouslyAndReset( inOrder -> { } ); StubCompletionListener completionListenerAfterSubmit2 = addPendingCompletionListener(); CompletableFuture<Object> batch2Future = new CompletableFuture<>(); when( processorMock.endBatch() ).thenReturn( (CompletableFuture) batch2Future ); batch1Future.complete( null ); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).beginBatch(); inOrder.verify( work2Mock ).submitTo( processorMock ); inOrder.verify( work3Mock ).submitTo( processorMock ); inOrder.verify( processorMock ).endBatch(); } ); batch2Future.complete( null ); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).complete(); verify( completionListenerAfterSubmit1 ).onComplete(); verify( completionListenerAfterSubmit2 ).onComplete(); } ); checkPostExecution(); } | public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } |
@Test public void simple_batchEndsLater_noAdditionalWork() throws InterruptedException { createAndStartExecutor( 2, true ); StubWork work1Mock = workMock( 1 ); CompletableFuture<Object> batch1Future = new CompletableFuture<>(); when( processorMock.endBatch() ).thenReturn( (CompletableFuture) batch1Future ); executor.submit( work1Mock ); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).beginBatch(); inOrder.verify( work1Mock ).submitTo( processorMock ); inOrder.verify( processorMock ).endBatch(); } ); StubCompletionListener completionListenerAfterSubmit = addPendingCompletionListener(); batch1Future.complete( null ); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).complete(); inOrder.verify( completionListenerAfterSubmit ).onComplete(); } ); checkPostExecution(); } | public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } |
@Test public void beginBatchFailure() throws InterruptedException { createAndStartExecutor( 4, true ); SimulatedFailure simulatedFailure = new SimulatedFailure(); Runnable unblockExecutorSwitch = blockExecutor(); StubWork work1Mock = workMock( 1 ); executor.submit( work1Mock ); verifyAsynchronouslyAndReset( inOrder -> { } ); StubCompletionListener completionListenerAfterSubmit = addPendingCompletionListener(); ArgumentCaptor<FailureContext> failureContextCaptor = ArgumentCaptor.forClass( FailureContext.class ); doThrow( simulatedFailure ).when( processorMock ).beginBatch(); unblockExecutorSwitch.run(); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).beginBatch(); inOrder.verify( failureHandlerMock ).handle( failureContextCaptor.capture() ); inOrder.verify( processorMock ).complete(); inOrder.verify( completionListenerAfterSubmit ).onComplete(); } ); FailureContext failureContext = failureContextCaptor.getValue(); assertThat( failureContext.throwable() ) .isSameAs( simulatedFailure ); assertThat( failureContext.failingOperation() ).asString() .contains( "Executing task '" + NAME + "'" ); checkPostExecution(); } | public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } |
@Test public void submitFailure() throws InterruptedException { createAndStartExecutor( 4, true ); SimulatedFailure simulatedFailure = new SimulatedFailure(); Runnable unblockExecutorSwitch = blockExecutor(); StubWork work1Mock = workMock( 1 ); StubWork work2Mock = workMock( 2 ); StubWork work3Mock = workMock( 3 ); executor.submit( work1Mock ); executor.submit( work2Mock ); executor.submit( work3Mock ); verifyAsynchronouslyAndReset( inOrder -> { } ); StubCompletionListener completionListenerAfterSubmit = addPendingCompletionListener(); CompletableFuture<Object> batch1Future = CompletableFuture.completedFuture( null ); doThrow( simulatedFailure ).when( work2Mock ).submitTo( processorMock ); when( processorMock.endBatch() ).thenReturn( (CompletableFuture) batch1Future ); unblockExecutorSwitch.run(); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).beginBatch(); inOrder.verify( work1Mock ).submitTo( processorMock ); inOrder.verify( work2Mock ).submitTo( processorMock ); inOrder.verify( work2Mock ).markAsFailed( simulatedFailure ); inOrder.verify( work3Mock ).submitTo( processorMock ); inOrder.verify( processorMock ).endBatch(); inOrder.verify( processorMock ).complete(); inOrder.verify( completionListenerAfterSubmit ).onComplete(); } ); checkPostExecution(); } | public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } |
@Test public void endBatchFailure() throws InterruptedException { createAndStartExecutor( 4, true ); SimulatedFailure simulatedFailure = new SimulatedFailure(); Runnable unblockExecutorSwitch = blockExecutor(); StubWork work1Mock = workMock( 1 ); StubWork work2Mock = workMock( 2 ); executor.submit( work1Mock ); executor.submit( work2Mock ); verifyAsynchronouslyAndReset( inOrder -> { } ); StubCompletionListener completionListenerAfterSubmit = addPendingCompletionListener(); ArgumentCaptor<FailureContext> failureContextCaptor = ArgumentCaptor.forClass( FailureContext.class ); doThrow( simulatedFailure ).when( processorMock ).endBatch(); unblockExecutorSwitch.run(); verifyAsynchronouslyAndReset( inOrder -> { inOrder.verify( processorMock ).beginBatch(); inOrder.verify( work1Mock ).submitTo( processorMock ); inOrder.verify( work2Mock ).submitTo( processorMock ); inOrder.verify( processorMock ).endBatch(); inOrder.verify( failureHandlerMock ).handle( failureContextCaptor.capture() ); inOrder.verify( processorMock ).complete(); inOrder.verify( completionListenerAfterSubmit ).onComplete(); } ); FailureContext failureContext = failureContextCaptor.getValue(); assertThat( failureContext.throwable() ) .isSameAs( simulatedFailure ); assertThat( failureContext.failingOperation() ).asString() .contains( "Executing task '" + NAME + "'" ); checkPostExecution(); } | public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } | BatchingExecutor { public void submit(BatchedWork<? super P> work) throws InterruptedException { if ( processingTask == null ) { throw new AssertionFailure( "Attempt to submit a work to executor '" + name + "', which is stopped" + " There is probably a bug in Hibernate Search, please report it." ); } workQueue.put( work ); processingTask.ensureScheduled(); } BatchingExecutor(String name,
P processor, int maxTasksPerBatch, boolean fair,
FailureHandler failureHandler); @Override String toString(); synchronized void start(ExecutorService executorService); synchronized void stop(); void submit(BatchedWork<? super P> work); CompletableFuture<?> completion(); } |
@Test public void success() { Long work1Result = 42L; Long work2Result = 41L; Long work3Result = 43L; ArgumentCaptor<CompletableFuture<Long>> work1FutureCaptor = futureCaptor(); ArgumentCaptor<CompletableFuture<Long>> work2FutureCaptor = futureCaptor(); ArgumentCaptor<CompletableFuture<Long>> work3FutureCaptor = futureCaptor(); CompletableFuture<IndexIndexingPlanExecutionReport<StubEntityReference>> planExecutionFuture; LuceneIndexIndexingPlanExecution<StubEntityReference> execution = new LuceneIndexIndexingPlanExecution<>( orchestratorMock, entityReferenceFactoryMock, commitStrategy, refreshStrategy, workMocks( 3 ) ); verifyNoOtherOrchestratorInteractionsAndReset(); planExecutionFuture = execution.execute(); verify( orchestratorMock ).submit( work1FutureCaptor.capture(), eq( workMocks.get( 0 ) ) ); verify( orchestratorMock ).submit( work2FutureCaptor.capture(), eq( workMocks.get( 1 ) ) ); verify( orchestratorMock ).submit( work3FutureCaptor.capture(), eq( workMocks.get( 2 ) ) ); verifyNoOtherOrchestratorInteractionsAndReset(); assertThatFuture( planExecutionFuture ).isPending(); work2FutureCaptor.getValue().complete( work2Result ); verifyNoOtherOrchestratorInteractionsAndReset(); assertThatFuture( planExecutionFuture ).isPending(); work1FutureCaptor.getValue().complete( work1Result ); verifyNoOtherOrchestratorInteractionsAndReset(); assertThatFuture( planExecutionFuture ).isPending(); work3FutureCaptor.getValue().complete( work3Result ); if ( DocumentCommitStrategy.FORCE.equals( commitStrategy ) ) { verify( orchestratorMock ).forceCommitInCurrentThread(); } if ( DocumentRefreshStrategy.FORCE.equals( refreshStrategy ) ) { verify( orchestratorMock ).forceRefreshInCurrentThread(); } verifyNoOtherOrchestratorInteractionsAndReset(); assertThatFuture( planExecutionFuture ).isSuccessful( report -> { assertThat( report ).isNotNull(); assertSoftly( softly -> { softly.assertThat( report.throwable() ).isEmpty(); softly.assertThat( report.failingEntityReferences() ).isEmpty(); } ); } ); } | CompletableFuture<IndexIndexingPlanExecutionReport<R>> execute() { CompletableFuture<IndexIndexingPlanExecutionReport<R>> reportFuture = CompletableFuture.allOf( futures ) .handle( (result, throwable) -> onAllWorksFinished() ); for ( int i = 0; i < works.size(); i++ ) { CompletableFuture<Long> future = futures[i]; SingleDocumentIndexingWork work = works.get( i ); orchestrator.submit( future, work ); } return reportFuture; } | LuceneIndexIndexingPlanExecution { CompletableFuture<IndexIndexingPlanExecutionReport<R>> execute() { CompletableFuture<IndexIndexingPlanExecutionReport<R>> reportFuture = CompletableFuture.allOf( futures ) .handle( (result, throwable) -> onAllWorksFinished() ); for ( int i = 0; i < works.size(); i++ ) { CompletableFuture<Long> future = futures[i]; SingleDocumentIndexingWork work = works.get( i ); orchestrator.submit( future, work ); } return reportFuture; } } | LuceneIndexIndexingPlanExecution { CompletableFuture<IndexIndexingPlanExecutionReport<R>> execute() { CompletableFuture<IndexIndexingPlanExecutionReport<R>> reportFuture = CompletableFuture.allOf( futures ) .handle( (result, throwable) -> onAllWorksFinished() ); for ( int i = 0; i < works.size(); i++ ) { CompletableFuture<Long> future = futures[i]; SingleDocumentIndexingWork work = works.get( i ); orchestrator.submit( future, work ); } return reportFuture; } LuceneIndexIndexingPlanExecution(LuceneSerialWorkOrchestrator orchestrator,
EntityReferenceFactory<R> entityReferenceFactory,
DocumentCommitStrategy commitStrategy,
DocumentRefreshStrategy refreshStrategy,
List<SingleDocumentIndexingWork> works); } | LuceneIndexIndexingPlanExecution { CompletableFuture<IndexIndexingPlanExecutionReport<R>> execute() { CompletableFuture<IndexIndexingPlanExecutionReport<R>> reportFuture = CompletableFuture.allOf( futures ) .handle( (result, throwable) -> onAllWorksFinished() ); for ( int i = 0; i < works.size(); i++ ) { CompletableFuture<Long> future = futures[i]; SingleDocumentIndexingWork work = works.get( i ); orchestrator.submit( future, work ); } return reportFuture; } LuceneIndexIndexingPlanExecution(LuceneSerialWorkOrchestrator orchestrator,
EntityReferenceFactory<R> entityReferenceFactory,
DocumentCommitStrategy commitStrategy,
DocumentRefreshStrategy refreshStrategy,
List<SingleDocumentIndexingWork> works); } | LuceneIndexIndexingPlanExecution { CompletableFuture<IndexIndexingPlanExecutionReport<R>> execute() { CompletableFuture<IndexIndexingPlanExecutionReport<R>> reportFuture = CompletableFuture.allOf( futures ) .handle( (result, throwable) -> onAllWorksFinished() ); for ( int i = 0; i < works.size(); i++ ) { CompletableFuture<Long> future = futures[i]; SingleDocumentIndexingWork work = works.get( i ); orchestrator.submit( future, work ); } return reportFuture; } LuceneIndexIndexingPlanExecution(LuceneSerialWorkOrchestrator orchestrator,
EntityReferenceFactory<R> entityReferenceFactory,
DocumentCommitStrategy commitStrategy,
DocumentRefreshStrategy refreshStrategy,
List<SingleDocumentIndexingWork> works); } |
@Test public void runtimeException() { Throwable mainException = new Exception(); RuntimeException exception1 = new RuntimeException(); RuntimeException exception2 = new IllegalStateException(); RuntimeException exception3 = new UnsupportedOperationException(); new SuppressingCloser( mainException ) .push( ignored -> { throw exception1; }, new Object() ) .push( ignored -> { throw exception2; }, new Object() ) .push( ignored -> { throw exception3; }, new Object() ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ) .hasSuppressedException( exception3 ); } | public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); } | SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); } |
@Test public void testIterator() { Schema sample = AvroSchemaGeneratorTest.getSampleSchema(); boolean baseSeen = false, recursiveSeen = false, compositeSeen = false, arraySeen = false, mapSeen = false; for (Schema schema : new AvroSchemaIterator(sample)) { if (schema.getName().equals("SampleBaseType")) { baseSeen = true; } if (schema.getName().equals("SampleRecursiveType")) { recursiveSeen = true; } if (schema.getName().equals("SampleCompositeType")) { compositeSeen = true; } } assertTrue(baseSeen); assertTrue(recursiveSeen); assertTrue(compositeSeen); } | @Override public Iterator<Schema> iterator() { return this; } | AvroSchemaIterator implements Iterable<Schema>,
Iterator<Schema> { @Override public Iterator<Schema> iterator() { return this; } } | AvroSchemaIterator implements Iterable<Schema>,
Iterator<Schema> { @Override public Iterator<Schema> iterator() { return this; } AvroSchemaIterator(Schema rootSchema); } | AvroSchemaIterator implements Iterable<Schema>,
Iterator<Schema> { @Override public Iterator<Schema> iterator() { return this; } AvroSchemaIterator(Schema rootSchema); @Override Iterator<Schema> iterator(); @Override boolean hasNext(); @Override Schema next(); } | AvroSchemaIterator implements Iterable<Schema>,
Iterator<Schema> { @Override public Iterator<Schema> iterator() { return this; } AvroSchemaIterator(Schema rootSchema); @Override Iterator<Schema> iterator(); @Override boolean hasNext(); @Override Schema next(); } |
@Test public void testParseCompositeKey() { final CompositeKey key = CompositeKey.parseCompositeKey("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"); assertThat(key.getObjectType(), is(equalTo("abc"))); assertThat(key.getAttributes(), hasSize(4)); assertThat(key.getAttributes(), contains("def", "ghi", "jkl", "mno")); assertThat(key.toString(), is(equalTo("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"))); } | public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; } |
@Test(expected = CompositeKeyFormatException.class) public void testParseCompositeKeyInvalidObjectType() { CompositeKey.parseCompositeKey("ab\udbff\udfffc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"); } | public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; } |
@Test(expected = CompositeKeyFormatException.class) public void testParseCompositeKeyInvalidAttribute() { CompositeKey.parseCompositeKey("abc\u0000def\u0000ghi\u0000jk\udbff\udfffl\u0000mno\u0000"); } | public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); } | CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; } |
@Test public void addOrgs() { final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(null); ep.addOrgs(RoleType.RoleTypePeer, "Org1"); final byte[] epBytes = ep.policy(); assertThat(epBytes, is(not(nullValue()))); assertTrue(epBytes.length > 0); final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray(); assertArrayEquals(expectedEPBytes, epBytes); } | @Override public void addOrgs(final RoleType role, final String... organizations) { MSPRoleType mspRole; if (RoleType.RoleTypeMember.equals(role)) { mspRole = MSPRoleType.MEMBER; } else { mspRole = MSPRoleType.PEER; } for (final String neworg : organizations) { orgs.put(neworg, mspRole); } } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void addOrgs(final RoleType role, final String... organizations) { MSPRoleType mspRole; if (RoleType.RoleTypeMember.equals(role)) { mspRole = MSPRoleType.MEMBER; } else { mspRole = MSPRoleType.PEER; } for (final String neworg : organizations) { orgs.put(neworg, mspRole); } } } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void addOrgs(final RoleType role, final String... organizations) { MSPRoleType mspRole; if (RoleType.RoleTypeMember.equals(role)) { mspRole = MSPRoleType.MEMBER; } else { mspRole = MSPRoleType.PEER; } for (final String neworg : organizations) { orgs.put(neworg, mspRole); } } StateBasedEndorsementImpl(final byte[] ep); } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void addOrgs(final RoleType role, final String... organizations) { MSPRoleType mspRole; if (RoleType.RoleTypeMember.equals(role)) { mspRole = MSPRoleType.MEMBER; } else { mspRole = MSPRoleType.PEER; } for (final String neworg : organizations) { orgs.put(neworg, mspRole); } } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void addOrgs(final RoleType role, final String... organizations) { MSPRoleType mspRole; if (RoleType.RoleTypeMember.equals(role)) { mspRole = MSPRoleType.MEMBER; } else { mspRole = MSPRoleType.PEER; } for (final String neworg : organizations) { orgs.put(neworg, mspRole); } } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); } |
@Test public void delOrgs() { final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray(); final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes); final List<String> listOrgs = ep.listOrgs(); assertThat(listOrgs, is(not(nullValue()))); assertThat(listOrgs, contains("Org1")); assertThat(listOrgs, hasSize(1)); ep.addOrgs(RoleType.RoleTypeMember, "Org2"); ep.delOrgs("Org1"); final byte[] epBytes = ep.policy(); assertThat(epBytes, is(not(nullValue()))); assertTrue(epBytes.length > 0); final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org2", MSPRoleType.MEMBER).toByteString().toByteArray(); assertArrayEquals(expectedEPBytes, epBytes); } | @Override public void delOrgs(final String... organizations) { for (final String delorg : organizations) { orgs.remove(delorg); } } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void delOrgs(final String... organizations) { for (final String delorg : organizations) { orgs.remove(delorg); } } } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void delOrgs(final String... organizations) { for (final String delorg : organizations) { orgs.remove(delorg); } } StateBasedEndorsementImpl(final byte[] ep); } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void delOrgs(final String... organizations) { for (final String delorg : organizations) { orgs.remove(delorg); } } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void delOrgs(final String... organizations) { for (final String delorg : organizations) { orgs.remove(delorg); } } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); } |
@Test public void listOrgs() { final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray(); final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes); final List<String> listOrgs = ep.listOrgs(); assertThat(listOrgs, is(not(nullValue()))); assertThat(listOrgs, hasSize(1)); assertThat(listOrgs, contains("Org1")); } | @Override public List<String> listOrgs() { final List<String> res = new ArrayList<>(); res.addAll(orgs.keySet()); return res; } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public List<String> listOrgs() { final List<String> res = new ArrayList<>(); res.addAll(orgs.keySet()); return res; } } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public List<String> listOrgs() { final List<String> res = new ArrayList<>(); res.addAll(orgs.keySet()); return res; } StateBasedEndorsementImpl(final byte[] ep); } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public List<String> listOrgs() { final List<String> res = new ArrayList<>(); res.addAll(orgs.keySet()); return res; } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); } | StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public List<String> listOrgs() { final List<String> res = new ArrayList<>(); res.addAll(orgs.keySet()); return res; } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); } |
@Test public void getInstance() { assertNotNull(StateBasedEndorsementFactory.getInstance()); assertTrue(StateBasedEndorsementFactory.getInstance() instanceof StateBasedEndorsementFactory); } | public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); } return instance; } | StateBasedEndorsementFactory { public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); } return instance; } } | StateBasedEndorsementFactory { public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); } return instance; } } | StateBasedEndorsementFactory { public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); } return instance; } static synchronized StateBasedEndorsementFactory getInstance(); StateBasedEndorsement newStateBasedEndorsement(final byte[] ep); } | StateBasedEndorsementFactory { public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); } return instance; } static synchronized StateBasedEndorsementFactory getInstance(); StateBasedEndorsement newStateBasedEndorsement(final byte[] ep); } |
@Test public void newStateBasedEndorsement() { assertNotNull(StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {})); thrown.expect(IllegalArgumentException.class); StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {0}); } | public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) { return new StateBasedEndorsementImpl(ep); } | StateBasedEndorsementFactory { public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) { return new StateBasedEndorsementImpl(ep); } } | StateBasedEndorsementFactory { public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) { return new StateBasedEndorsementImpl(ep); } } | StateBasedEndorsementFactory { public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) { return new StateBasedEndorsementImpl(ep); } static synchronized StateBasedEndorsementFactory getInstance(); StateBasedEndorsement newStateBasedEndorsement(final byte[] ep); } | StateBasedEndorsementFactory { public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) { return new StateBasedEndorsementImpl(ep); } static synchronized StateBasedEndorsementFactory getInstance(); StateBasedEndorsement newStateBasedEndorsement(final byte[] ep); } |
@Test public void testKeyValueImpl() { new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); } | KeyValueImpl(final KV kv) { this.key = kv.getKey(); this.value = kv.getValue(); } | KeyValueImpl implements KeyValue { KeyValueImpl(final KV kv) { this.key = kv.getKey(); this.value = kv.getValue(); } } | KeyValueImpl implements KeyValue { KeyValueImpl(final KV kv) { this.key = kv.getKey(); this.value = kv.getValue(); } KeyValueImpl(final KV kv); } | KeyValueImpl implements KeyValue { KeyValueImpl(final KV kv) { this.key = kv.getKey(); this.value = kv.getValue(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyValueImpl implements KeyValue { KeyValueImpl(final KV kv) { this.key = kv.getKey(); this.value = kv.getValue(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testGetKey() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getKey(), is(equalTo("key"))); } | @Override public String getKey() { return key; } | KeyValueImpl implements KeyValue { @Override public String getKey() { return key; } } | KeyValueImpl implements KeyValue { @Override public String getKey() { return key; } KeyValueImpl(final KV kv); } | KeyValueImpl implements KeyValue { @Override public String getKey() { return key; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyValueImpl implements KeyValue { @Override public String getKey() { return key; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void assetDelete() { MyAssetContract contract = new MyAssetContract(); Context ctx = mock(Context.class); ChaincodeStub stub = mock(ChaincodeStub.class); when(ctx.getStub()).thenReturn(stub); when(stub.getState("10001")).thenReturn(null); Exception thrown = assertThrows(RuntimeException.class, () -> { contract.deleteMyAsset(ctx, "10001"); }); assertEquals(thrown.getMessage(), "The asset 10001 does not exist"); } | @Transaction() public void deleteMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } ctx.getStub().delState(myAssetId); } | MyAssetContract implements ContractInterface { @Transaction() public void deleteMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } ctx.getStub().delState(myAssetId); } } | MyAssetContract implements ContractInterface { @Transaction() public void deleteMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } ctx.getStub().delState(myAssetId); } MyAssetContract(); } | MyAssetContract implements ContractInterface { @Transaction() public void deleteMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } ctx.getStub().delState(myAssetId); } MyAssetContract(); @Transaction() boolean myAssetExists(Context ctx, String myAssetId); @Transaction() void createMyAsset(Context ctx, String myAssetId, String value); @Transaction() MyAsset readMyAsset(Context ctx, String myAssetId); @Transaction() void updateMyAsset(Context ctx, String myAssetId, String newValue); @Transaction() void deleteMyAsset(Context ctx, String myAssetId); } | MyAssetContract implements ContractInterface { @Transaction() public void deleteMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } ctx.getStub().delState(myAssetId); } MyAssetContract(); @Transaction() boolean myAssetExists(Context ctx, String myAssetId); @Transaction() void createMyAsset(Context ctx, String myAssetId, String value); @Transaction() MyAsset readMyAsset(Context ctx, String myAssetId); @Transaction() void updateMyAsset(Context ctx, String myAssetId, String newValue); @Transaction() void deleteMyAsset(Context ctx, String myAssetId); } |
@Test public void testGetValue() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getValue(), is(equalTo("value".getBytes(UTF_8)))); } | @Override public byte[] getValue() { return value.toByteArray(); } | KeyValueImpl implements KeyValue { @Override public byte[] getValue() { return value.toByteArray(); } } | KeyValueImpl implements KeyValue { @Override public byte[] getValue() { return value.toByteArray(); } KeyValueImpl(final KV kv); } | KeyValueImpl implements KeyValue { @Override public byte[] getValue() { return value.toByteArray(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyValueImpl implements KeyValue { @Override public byte[] getValue() { return value.toByteArray(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testGetStringValue() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getStringValue(), is(equalTo("value"))); } | @Override public String getStringValue() { return value.toStringUtf8(); } | KeyValueImpl implements KeyValue { @Override public String getStringValue() { return value.toStringUtf8(); } } | KeyValueImpl implements KeyValue { @Override public String getStringValue() { return value.toStringUtf8(); } KeyValueImpl(final KV kv); } | KeyValueImpl implements KeyValue { @Override public String getStringValue() { return value.toStringUtf8(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyValueImpl implements KeyValue { @Override public String getStringValue() { return value.toStringUtf8(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testHashCode() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .build()); int expectedHashCode = 31; expectedHashCode = expectedHashCode + "".hashCode(); expectedHashCode = expectedHashCode * 31 + ByteString.copyFromUtf8("").hashCode(); assertEquals("Wrong hashcode", expectedHashCode, kv.hashCode()); } | @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } | KeyValueImpl implements KeyValue { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } } | KeyValueImpl implements KeyValue { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyValueImpl(final KV kv); } | KeyValueImpl implements KeyValue { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyValueImpl implements KeyValue { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testEquals() { final KeyValueImpl kv1 = new KeyValueImpl(KV.newBuilder() .setKey("a") .setValue(ByteString.copyFromUtf8("valueA")) .build()); final KeyValueImpl kv2 = new KeyValueImpl(KV.newBuilder() .setKey("a") .setValue(ByteString.copyFromUtf8("valueB")) .build()); final KeyValueImpl kv3 = new KeyValueImpl(KV.newBuilder() .setKey("b") .setValue(ByteString.copyFromUtf8("valueA")) .build()); final KeyValueImpl kv4 = new KeyValueImpl(KV.newBuilder() .setKey("a") .setValue(ByteString.copyFromUtf8("valueA")) .build()); assertFalse(kv1.equals(kv2)); assertFalse(kv1.equals(kv3)); assertTrue(kv1.equals(kv4)); } | @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyValueImpl other = (KeyValueImpl) obj; if (!key.equals(other.key)) { return false; } if (!value.equals(other.value)) { return false; } return true; } | KeyValueImpl implements KeyValue { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyValueImpl other = (KeyValueImpl) obj; if (!key.equals(other.key)) { return false; } if (!value.equals(other.value)) { return false; } return true; } } | KeyValueImpl implements KeyValue { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyValueImpl other = (KeyValueImpl) obj; if (!key.equals(other.key)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyValueImpl(final KV kv); } | KeyValueImpl implements KeyValue { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyValueImpl other = (KeyValueImpl) obj; if (!key.equals(other.key)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyValueImpl implements KeyValue { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyValueImpl other = (KeyValueImpl) obj; if (!key.equals(other.key)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void register() throws UnsupportedEncodingException { itm.register(); } | public InvocationTaskManager register() { logger.info(() -> "Registering new chaincode " + this.chaincodeId); chaincode.setState(ChaincodeBase.CCState.CREATED); this.outgoingMessage.accept(ChaincodeMessageFactory.newRegisterChaincodeMessage(this.chaincodeId)); return this; } | InvocationTaskManager { public InvocationTaskManager register() { logger.info(() -> "Registering new chaincode " + this.chaincodeId); chaincode.setState(ChaincodeBase.CCState.CREATED); this.outgoingMessage.accept(ChaincodeMessageFactory.newRegisterChaincodeMessage(this.chaincodeId)); return this; } } | InvocationTaskManager { public InvocationTaskManager register() { logger.info(() -> "Registering new chaincode " + this.chaincodeId); chaincode.setState(ChaincodeBase.CCState.CREATED); this.outgoingMessage.accept(ChaincodeMessageFactory.newRegisterChaincodeMessage(this.chaincodeId)); return this; } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); } | InvocationTaskManager { public InvocationTaskManager register() { logger.info(() -> "Registering new chaincode " + this.chaincodeId); chaincode.setState(ChaincodeBase.CCState.CREATED); this.outgoingMessage.accept(ChaincodeMessageFactory.newRegisterChaincodeMessage(this.chaincodeId)); return this; } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } | InvocationTaskManager { public InvocationTaskManager register() { logger.info(() -> "Registering new chaincode " + this.chaincodeId); chaincode.setState(ChaincodeBase.CCState.CREATED); this.outgoingMessage.accept(ChaincodeMessageFactory.newRegisterChaincodeMessage(this.chaincodeId)); return this; } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } |
@Test public void onMessageTestTx() throws UnsupportedEncodingException { final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.READY); itm.onChaincodeMessage(msg); } | public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } |
@Test public void onWrongCreatedState() throws UnsupportedEncodingException { perfLogger.setLevel(Level.ALL); final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.CREATED); itm.onChaincodeMessage(msg); } | public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } |
@Test public void onWrongEstablishedState() throws UnsupportedEncodingException { final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.ESTABLISHED); itm.onChaincodeMessage(msg); } | public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } |
@Test public void onErrorResponse() throws UnsupportedEncodingException { final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.ERROR, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.READY); itm.onChaincodeMessage(msg); } | public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } | InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); } |
@Test void testNewGetPrivateDataHashEventMessage() { ChaincodeMessageFactory.newGetPrivateDataHashEventMessage(channelId, txId, collection, key); } | protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } |
@Test public void assetRead() { MyAssetContract contract = new MyAssetContract(); Context ctx = mock(Context.class); ChaincodeStub stub = mock(ChaincodeStub.class); when(ctx.getStub()).thenReturn(stub); MyAsset asset = new MyAsset(); asset.setValue("Valuable"); String json = asset.toJSONString(); when(stub.getState("10001")).thenReturn(json.getBytes(StandardCharsets.UTF_8)); MyAsset returnedAsset = contract.readMyAsset(ctx, "10001"); assertEquals(returnedAsset.getValue(), asset.getValue()); } | @Transaction() public MyAsset readMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } MyAsset newAsset = MyAsset.fromJSONString(new String(ctx.getStub().getState(myAssetId),UTF_8)); return newAsset; } | MyAssetContract implements ContractInterface { @Transaction() public MyAsset readMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } MyAsset newAsset = MyAsset.fromJSONString(new String(ctx.getStub().getState(myAssetId),UTF_8)); return newAsset; } } | MyAssetContract implements ContractInterface { @Transaction() public MyAsset readMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } MyAsset newAsset = MyAsset.fromJSONString(new String(ctx.getStub().getState(myAssetId),UTF_8)); return newAsset; } MyAssetContract(); } | MyAssetContract implements ContractInterface { @Transaction() public MyAsset readMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } MyAsset newAsset = MyAsset.fromJSONString(new String(ctx.getStub().getState(myAssetId),UTF_8)); return newAsset; } MyAssetContract(); @Transaction() boolean myAssetExists(Context ctx, String myAssetId); @Transaction() void createMyAsset(Context ctx, String myAssetId, String value); @Transaction() MyAsset readMyAsset(Context ctx, String myAssetId); @Transaction() void updateMyAsset(Context ctx, String myAssetId, String newValue); @Transaction() void deleteMyAsset(Context ctx, String myAssetId); } | MyAssetContract implements ContractInterface { @Transaction() public MyAsset readMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } MyAsset newAsset = MyAsset.fromJSONString(new String(ctx.getStub().getState(myAssetId),UTF_8)); return newAsset; } MyAssetContract(); @Transaction() boolean myAssetExists(Context ctx, String myAssetId); @Transaction() void createMyAsset(Context ctx, String myAssetId, String value); @Transaction() MyAsset readMyAsset(Context ctx, String myAssetId); @Transaction() void updateMyAsset(Context ctx, String myAssetId, String newValue); @Transaction() void deleteMyAsset(Context ctx, String myAssetId); } |
@Test void testNewGetStateEventMessage() { ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, collection, key); } | protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } |
@Test void testNewGetStateMetadataEventMessage() { ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, collection, key); } | protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } |
@Test void testNewPutStateEventMessage() { ChaincodeMessageFactory.newPutStateEventMessage(channelId, txId, collection, key, value); } | protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key, final ByteString value) { return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString()); } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key, final ByteString value) { return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString()); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key, final ByteString value) { return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key, final ByteString value) { return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key, final ByteString value) { return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString()); } private ChaincodeMessageFactory(); } |
@Test void testNewPutStateMetadataEventMessage() { ChaincodeMessageFactory.newPutStateMetadataEventMessage(channelId, txId, collection, key, metakey, value); } | protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key, final String metakey, final ByteString value) { return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key) .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString()); } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key, final String metakey, final ByteString value) { return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key) .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString()); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key, final String metakey, final ByteString value) { return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key) .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key, final String metakey, final ByteString value) { return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key) .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key, final String metakey, final ByteString value) { return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key) .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString()); } private ChaincodeMessageFactory(); } |
@Test void testNewDeleteStateEventMessage() { ChaincodeMessageFactory.newDeleteStateEventMessage(channelId, txId, collection, key); } | protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } | ChaincodeMessageFactory { protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); } |
@Test void testNewErrorEventMessage() { ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, message); ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, throwable); ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, message, event); } | protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } | ChaincodeMessageFactory { protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } private ChaincodeMessageFactory(); } |
@Test void testNewCompletedEventMessage() { ChaincodeMessageFactory.newCompletedEventMessage(channelId, txId, response, event); } | protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) { final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); return message; } | ChaincodeMessageFactory { protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) { final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); return message; } } | ChaincodeMessageFactory { protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) { final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); return message; } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) { final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); return message; } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) { final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); return message; } private ChaincodeMessageFactory(); } |
@Test void testNewInvokeChaincodeMessage() { ChaincodeMessageFactory.newInvokeChaincodeMessage(channelId, txId, payload); } | protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null); } | ChaincodeMessageFactory { protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null); } private ChaincodeMessageFactory(); } |
@Test void testNewRegisterChaincodeMessage() { ChaincodeMessageFactory.newRegisterChaincodeMessage(chaincodeId); } | protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); } private ChaincodeMessageFactory(); } |
@Test void testNewEventMessageTypeStringStringByteString() { ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload); ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload, event); } | protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) { return newEventMessage(type, channelId, txId, payload, null); } | ChaincodeMessageFactory { protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) { return newEventMessage(type, channelId, txId, payload, null); } } | ChaincodeMessageFactory { protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) { return newEventMessage(type, channelId, txId, payload, null); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) { return newEventMessage(type, channelId, txId, payload, null); } private ChaincodeMessageFactory(); } | ChaincodeMessageFactory { protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) { return newEventMessage(type, channelId, txId, payload, null); } private ChaincodeMessageFactory(); } |
@Test public void testKeyModificationImpl() { new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setTxId("txid") .setValue(ByteString.copyFromUtf8("value")) .setTimestamp(Timestamp.newBuilder() .setSeconds(1234567890) .setNanos(123456789)) .setIsDelete(true) .build()); } | KeyModificationImpl(final KvQueryResult.KeyModification km) { this.txId = km.getTxId(); this.value = km.getValue(); this.timestamp = Instant.ofEpochSecond(km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); this.deleted = km.getIsDelete(); } | KeyModificationImpl implements KeyModification { KeyModificationImpl(final KvQueryResult.KeyModification km) { this.txId = km.getTxId(); this.value = km.getValue(); this.timestamp = Instant.ofEpochSecond(km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); this.deleted = km.getIsDelete(); } } | KeyModificationImpl implements KeyModification { KeyModificationImpl(final KvQueryResult.KeyModification km) { this.txId = km.getTxId(); this.value = km.getValue(); this.timestamp = Instant.ofEpochSecond(km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); this.deleted = km.getIsDelete(); } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { KeyModificationImpl(final KvQueryResult.KeyModification km) { this.txId = km.getTxId(); this.value = km.getValue(); this.timestamp = Instant.ofEpochSecond(km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); this.deleted = km.getIsDelete(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { KeyModificationImpl(final KvQueryResult.KeyModification km) { this.txId = km.getTxId(); this.value = km.getValue(); this.timestamp = Instant.ofEpochSecond(km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); this.deleted = km.getIsDelete(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testGetTxId() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setTxId("txid") .build()); assertThat(km.getTxId(), is(equalTo("txid"))); } | @Override public String getTxId() { return txId; } | KeyModificationImpl implements KeyModification { @Override public String getTxId() { return txId; } } | KeyModificationImpl implements KeyModification { @Override public String getTxId() { return txId; } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { @Override public String getTxId() { return txId; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { @Override public String getTxId() { return txId; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testGetValue() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(km.getValue(), is(equalTo("value".getBytes(UTF_8)))); } | @Override public byte[] getValue() { return value.toByteArray(); } | KeyModificationImpl implements KeyModification { @Override public byte[] getValue() { return value.toByteArray(); } } | KeyModificationImpl implements KeyModification { @Override public byte[] getValue() { return value.toByteArray(); } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { @Override public byte[] getValue() { return value.toByteArray(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { @Override public byte[] getValue() { return value.toByteArray(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testGetStringValue() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(km.getStringValue(), is(equalTo("value"))); } | @Override public String getStringValue() { return value.toStringUtf8(); } | KeyModificationImpl implements KeyModification { @Override public String getStringValue() { return value.toStringUtf8(); } } | KeyModificationImpl implements KeyModification { @Override public String getStringValue() { return value.toStringUtf8(); } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { @Override public String getStringValue() { return value.toStringUtf8(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { @Override public String getStringValue() { return value.toStringUtf8(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testGetTimestamp() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setTimestamp(Timestamp.newBuilder() .setSeconds(1234567890L) .setNanos(123456789)) .build()); assertThat(km.getTimestamp(), hasProperty("epochSecond", equalTo(1234567890L))); assertThat(km.getTimestamp(), hasProperty("nano", equalTo(123456789))); } | @Override public java.time.Instant getTimestamp() { return timestamp; } | KeyModificationImpl implements KeyModification { @Override public java.time.Instant getTimestamp() { return timestamp; } } | KeyModificationImpl implements KeyModification { @Override public java.time.Instant getTimestamp() { return timestamp; } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { @Override public java.time.Instant getTimestamp() { return timestamp; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { @Override public java.time.Instant getTimestamp() { return timestamp; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testIsDeleted() { Stream.of(true, false) .forEach(b -> { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(b) .build()); assertThat(km.isDeleted(), is(b)); }); } | @Override public boolean isDeleted() { return deleted; } | KeyModificationImpl implements KeyModification { @Override public boolean isDeleted() { return deleted; } } | KeyModificationImpl implements KeyModification { @Override public boolean isDeleted() { return deleted; } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { @Override public boolean isDeleted() { return deleted; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { @Override public boolean isDeleted() { return deleted; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testHashCode() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(false) .build()); int expectedHashCode = 31; expectedHashCode = expectedHashCode + 1237; expectedHashCode = expectedHashCode * 31 + Instant.EPOCH.hashCode(); expectedHashCode = expectedHashCode * 31 + "".hashCode(); expectedHashCode = expectedHashCode * 31 + ByteString.copyFromUtf8("").hashCode(); assertEquals("Wrong hash code", expectedHashCode, km.hashCode()); } | @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (deleted ? 1231 : 1237); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + ((txId == null) ? 0 : txId.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } | KeyModificationImpl implements KeyModification { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (deleted ? 1231 : 1237); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + ((txId == null) ? 0 : txId.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } } | KeyModificationImpl implements KeyModification { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (deleted ? 1231 : 1237); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + ((txId == null) ? 0 : txId.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (deleted ? 1231 : 1237); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + ((txId == null) ? 0 : txId.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (deleted ? 1231 : 1237); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + ((txId == null) ? 0 : txId.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void testEquals() { final KeyModification km1 = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(false) .build()); final KeyModification km2 = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(true) .build()); final KeyModification km3 = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(false) .build()); assertFalse(km1.equals(km2)); assertTrue(km1.equals(km3)); } | @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyModificationImpl other = (KeyModificationImpl) obj; if (deleted != other.deleted) { return false; } if (!timestamp.equals(other.timestamp)) { return false; } if (!txId.equals(other.txId)) { return false; } if (!value.equals(other.value)) { return false; } return true; } | KeyModificationImpl implements KeyModification { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyModificationImpl other = (KeyModificationImpl) obj; if (deleted != other.deleted) { return false; } if (!timestamp.equals(other.timestamp)) { return false; } if (!txId.equals(other.txId)) { return false; } if (!value.equals(other.value)) { return false; } return true; } } | KeyModificationImpl implements KeyModification { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyModificationImpl other = (KeyModificationImpl) obj; if (deleted != other.deleted) { return false; } if (!timestamp.equals(other.timestamp)) { return false; } if (!txId.equals(other.txId)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyModificationImpl(final KvQueryResult.KeyModification km); } | KeyModificationImpl implements KeyModification { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyModificationImpl other = (KeyModificationImpl) obj; if (deleted != other.deleted) { return false; } if (!timestamp.equals(other.timestamp)) { return false; } if (!txId.equals(other.txId)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } | KeyModificationImpl implements KeyModification { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyModificationImpl other = (KeyModificationImpl) obj; if (deleted != other.deleted) { return false; } if (!timestamp.equals(other.timestamp)) { return false; } if (!txId.equals(other.txId)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); } |
@Test public void getMetadata() { final QueryResultsIteratorWithMetadataImpl<Integer> testIter = new QueryResultsIteratorWithMetadataImpl<>(null, "", "", prepareQueryResponse().toByteString(), queryResultBytesToKv); assertThat(testIter.getMetadata().getBookmark(), is("asdf")); assertThat(testIter.getMetadata().getFetchedRecordsCount(), is(2)); } | @Override public ChaincodeShim.QueryResponseMetadata getMetadata() { return metadata; } | QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl<T> implements QueryResultsIteratorWithMetadata<T> { @Override public ChaincodeShim.QueryResponseMetadata getMetadata() { return metadata; } } | QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl<T> implements QueryResultsIteratorWithMetadata<T> { @Override public ChaincodeShim.QueryResponseMetadata getMetadata() { return metadata; } QueryResultsIteratorWithMetadataImpl(final ChaincodeInvocationTask handler, final String channelId, final String txId,
final ByteString responseBuffer, final Function<QueryResultBytes, T> mapper); } | QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl<T> implements QueryResultsIteratorWithMetadata<T> { @Override public ChaincodeShim.QueryResponseMetadata getMetadata() { return metadata; } QueryResultsIteratorWithMetadataImpl(final ChaincodeInvocationTask handler, final String channelId, final String txId,
final ByteString responseBuffer, final Function<QueryResultBytes, T> mapper); @Override ChaincodeShim.QueryResponseMetadata getMetadata(); } | QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl<T> implements QueryResultsIteratorWithMetadata<T> { @Override public ChaincodeShim.QueryResponseMetadata getMetadata() { return metadata; } QueryResultsIteratorWithMetadataImpl(final ChaincodeInvocationTask handler, final String channelId, final String txId,
final ByteString responseBuffer, final Function<QueryResultBytes, T> mapper); @Override ChaincodeShim.QueryResponseMetadata getMetadata(); } |
@Test public void testNewSuccessResponseEmpty() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse(); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertNull("Response message in not null", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); } | @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void logger() { Logger.getLogger(LoggerTest.class); Logger.getLogger(LoggerTest.class.getName()); } | protected Logger(final String name) { super(name, null); this.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); } | Logger extends java.util.logging.Logger { protected Logger(final String name) { super(name, null); this.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); } } | Logger extends java.util.logging.Logger { protected Logger(final String name) { super(name, null); this.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); } protected Logger(final String name); } | Logger extends java.util.logging.Logger { protected Logger(final String name) { super(name, null); this.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); } protected Logger(final String name); static Logger getLogger(final String name); void debug(final Supplier<String> msgSupplier); void debug(final String msg); static Logger getLogger(final Class<?> class1); void error(final String message); void error(final Supplier<String> msgSupplier); String formatError(final Throwable throwable); } | Logger extends java.util.logging.Logger { protected Logger(final String name) { super(name, null); this.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); } protected Logger(final String name); static Logger getLogger(final String name); void debug(final Supplier<String> msgSupplier); void debug(final String msg); static Logger getLogger(final Class<?> class1); void error(final String message); void error(final Supplier<String> msgSupplier); String formatError(final Throwable throwable); } |
@Test public void testNewSuccessResponseWithMessage() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple message"); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); } | @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewSuccessResponseWithPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertNull("Response message in not null", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); } | @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewSuccessResponseWithMessageAndPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple message", "Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); } | @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewErrorResponseEmpty() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertNull("Response message in not null", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); } | @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewErrorResponseWithMessage() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple message"); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); } | @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewErrorResponseWithPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertNull("Response message in not null", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); } | @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewErrorResponseWithMessageAndPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple message", "Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); } | @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewErrorResponseWithException() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(new Exception("Simple exception")); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message is not correct", "Unexpected error", response.getMessage()); assertNull("Response payload is not null", response.getPayload()); } | @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testNewErrorResponseWithChaincodeException() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(new ChaincodeException("Chaincode exception")); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message is not correct", "Chaincode exception", response.getMessage()); assertNull("Response payload is not null", response.getPayload()); } | @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testUnsetOptionId() { final ChaincodeBase cb = new EmptyChaincode(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(Matchers.containsString("The chaincode id must be specified")); cb.validateOptions(); } | protected final void validateOptions() { if (this.id == null) { throw new IllegalArgumentException(format( "The chaincode id must be specified using either the -i or --i command line options or the %s environment variable.", CORE_CHAINCODE_ID_NAME)); } if (this.tlsEnabled) { if (tlsClientCertPath == null) { throw new IllegalArgumentException( format("Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); } if (tlsClientKeyPath == null) { throw new IllegalArgumentException( format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); } if (tlsClientRootCertPath == null) { throw new IllegalArgumentException( format("Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); } } } | ChaincodeBase implements Chaincode { protected final void validateOptions() { if (this.id == null) { throw new IllegalArgumentException(format( "The chaincode id must be specified using either the -i or --i command line options or the %s environment variable.", CORE_CHAINCODE_ID_NAME)); } if (this.tlsEnabled) { if (tlsClientCertPath == null) { throw new IllegalArgumentException( format("Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); } if (tlsClientKeyPath == null) { throw new IllegalArgumentException( format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); } if (tlsClientRootCertPath == null) { throw new IllegalArgumentException( format("Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); } } } } | ChaincodeBase implements Chaincode { protected final void validateOptions() { if (this.id == null) { throw new IllegalArgumentException(format( "The chaincode id must be specified using either the -i or --i command line options or the %s environment variable.", CORE_CHAINCODE_ID_NAME)); } if (this.tlsEnabled) { if (tlsClientCertPath == null) { throw new IllegalArgumentException( format("Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); } if (tlsClientKeyPath == null) { throw new IllegalArgumentException( format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); } if (tlsClientRootCertPath == null) { throw new IllegalArgumentException( format("Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); } } } } | ChaincodeBase implements Chaincode { protected final void validateOptions() { if (this.id == null) { throw new IllegalArgumentException(format( "The chaincode id must be specified using either the -i or --i command line options or the %s environment variable.", CORE_CHAINCODE_ID_NAME)); } if (this.tlsEnabled) { if (tlsClientCertPath == null) { throw new IllegalArgumentException( format("Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); } if (tlsClientKeyPath == null) { throw new IllegalArgumentException( format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); } if (tlsClientRootCertPath == null) { throw new IllegalArgumentException( format("Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); } } } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { protected final void validateOptions() { if (this.id == null) { throw new IllegalArgumentException(format( "The chaincode id must be specified using either the -i or --i command line options or the %s environment variable.", CORE_CHAINCODE_ID_NAME)); } if (this.tlsEnabled) { if (tlsClientCertPath == null) { throw new IllegalArgumentException( format("Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); } if (tlsClientKeyPath == null) { throw new IllegalArgumentException( format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); } if (tlsClientRootCertPath == null) { throw new IllegalArgumentException( format("Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); } } } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testValidateSimpleKeys() { CompositeKey.validateSimpleKeys("abc", "def", "ghi"); } | public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; } |
@Test @Ignore public void testNewChannelBuilder() throws Exception { final ChaincodeBase cb = new EmptyChaincode(); environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc"); environmentVariables.set("CORE_PEER_ADDRESS", "localhost:7052"); environmentVariables.set("CORE_PEER_TLS_ENABLED", "true"); environmentVariables.set("CORE_PEER_TLS_ROOTCERT_FILE", "src/test/resources/ca.crt"); environmentVariables.set("CORE_TLS_CLIENT_KEY_PATH", "src/test/resources/client.key.enc"); environmentVariables.set("CORE_TLS_CLIENT_CERT_PATH", "src/test/resources/client.crt.enc"); cb.processEnvironmentOptions(); cb.validateOptions(); assertTrue("Not correct builder", cb.newChannelBuilder() instanceof ManagedChannelBuilder); } | @SuppressWarnings("deprecation") final ManagedChannelBuilder<?> newChannelBuilder() throws IOException { final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); LOGGER.info("Configuring channel connection to peer."); if (tlsEnabled) { builder.negotiationType(NegotiationType.TLS); builder.sslContext(createSSLContext()); } else { builder.usePlaintext(); } return builder; } | ChaincodeBase implements Chaincode { @SuppressWarnings("deprecation") final ManagedChannelBuilder<?> newChannelBuilder() throws IOException { final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); LOGGER.info("Configuring channel connection to peer."); if (tlsEnabled) { builder.negotiationType(NegotiationType.TLS); builder.sslContext(createSSLContext()); } else { builder.usePlaintext(); } return builder; } } | ChaincodeBase implements Chaincode { @SuppressWarnings("deprecation") final ManagedChannelBuilder<?> newChannelBuilder() throws IOException { final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); LOGGER.info("Configuring channel connection to peer."); if (tlsEnabled) { builder.negotiationType(NegotiationType.TLS); builder.sslContext(createSSLContext()); } else { builder.usePlaintext(); } return builder; } } | ChaincodeBase implements Chaincode { @SuppressWarnings("deprecation") final ManagedChannelBuilder<?> newChannelBuilder() throws IOException { final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); LOGGER.info("Configuring channel connection to peer."); if (tlsEnabled) { builder.negotiationType(NegotiationType.TLS); builder.sslContext(createSSLContext()); } else { builder.usePlaintext(); } return builder; } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { @SuppressWarnings("deprecation") final ManagedChannelBuilder<?> newChannelBuilder() throws IOException { final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); LOGGER.info("Configuring channel connection to peer."); if (tlsEnabled) { builder.negotiationType(NegotiationType.TLS); builder.sslContext(createSSLContext()); } else { builder.usePlaintext(); } return builder; } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void testInitializeLogging() { final ChaincodeBase cb = new EmptyChaincode(); cb.processEnvironmentOptions(); cb.initializeLogging(); assertEquals("Wrong log level for org.hyperledger.fabric.shim ", Level.INFO, Logger.getLogger("org.hyperledger.fabric.shim").getLevel()); assertEquals("Wrong log level for " + cb.getClass().getPackage().getName(), Level.INFO, Logger.getLogger(cb.getClass().getPackage().getName()).getLevel()); setLogLevelForChaincode(environmentVariables, cb, "WRONG", "WRONG"); assertEquals("Wrong log level for org.hyperledger.fabric.shim ", Level.INFO, Logger.getLogger("org.hyperledger.fabric.shim").getLevel()); assertEquals("Wrong log level for " + cb.getClass().getPackage().getName(), Level.INFO, Logger.getLogger(cb.getClass().getPackage().getName()).getLevel()); setLogLevelForChaincode(environmentVariables, cb, "DEBUG", "NOTICE"); assertEquals("Wrong log level for org.hyperledger.fabric.shim ", Level.FINEST, Logger.getLogger("org.hyperledger.fabric.shim").getLevel()); assertEquals("Wrong log level for " + cb.getClass().getPackage().getName(), Level.CONFIG, Logger.getLogger(cb.getClass().getPackage().getName()).getLevel()); setLogLevelForChaincode(environmentVariables, cb, "INFO", "WARNING"); assertEquals("Wrong log level for org.hyperledger.fabric.shim ", Level.INFO, Logger.getLogger("org.hyperledger.fabric.shim").getLevel()); assertEquals("Wrong log level for " + cb.getClass().getPackage().getName(), Level.WARNING, Logger.getLogger(cb.getClass().getPackage().getName()).getLevel()); setLogLevelForChaincode(environmentVariables, cb, "CRITICAL", "ERROR"); assertEquals("Wrong log level for org.hyperledger.fabric.shim ", Level.SEVERE, Logger.getLogger("org.hyperledger.fabric.shim").getLevel()); assertEquals("Wrong log level for " + cb.getClass().getPackage().getName(), Level.SEVERE, Logger.getLogger(cb.getClass().getPackage().getName()).getLevel()); } | protected final void initializeLogging() { System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"); final Logger rootLogger = Logger.getLogger(""); for (final java.util.logging.Handler handler : rootLogger.getHandlers()) { handler.setLevel(ALL); handler.setFormatter(new SimpleFormatter() { @Override public synchronized String format(final LogRecord record) { return super.format(record).replaceFirst(".*SEVERE\\s*\\S*\\s*\\S*", "\u001B[1;31m$0\u001B[0m") .replaceFirst(".*WARNING\\s*\\S*\\s*\\S*", "\u001B[1;33m$0\u001B[0m") .replaceFirst(".*CONFIG\\s*\\S*\\s*\\S*", "\u001B[35m$0\u001B[0m") .replaceFirst(".*FINE\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINER\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINEST\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m"); } }); } final LogManager logManager = LogManager.getLogManager(); final Formatter f = new Formatter() { private final Date dat = new Date(); private final String format = "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"; @Override public String format(final LogRecord record) { dat.setTime(record.getMillis()); String source; if (record.getSourceClassName() != null) { source = record.getSourceClassName(); if (record.getSourceMethodName() != null) { source += " " + record.getSourceMethodName(); } } else { source = record.getLoggerName(); } final String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); } return String.format(format, dat, source, record.getLoggerName(), record.getLevel(), message, throwable); } }; rootLogger.info("Updated all handlers the format"); final Level chaincodeLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_LEVEL)); final Package chaincodePackage = this.getClass().getPackage(); if (chaincodePackage != null) { Logger.getLogger(chaincodePackage.getName()).setLevel(chaincodeLogLevel); } else { Logger.getLogger("").setLevel(chaincodeLogLevel); } final Level shimLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_SHIM)); Logger.getLogger(ChaincodeBase.class.getPackage().getName()).setLevel(shimLogLevel); Logger.getLogger(ContractRouter.class.getPackage().getName()).setLevel(chaincodeLogLevel); final List<?> loggers = Collections.list(LogManager.getLogManager().getLoggerNames()); loggers.forEach(x -> { final Logger l = LogManager.getLogManager().getLogger((String) x); }); } | ChaincodeBase implements Chaincode { protected final void initializeLogging() { System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"); final Logger rootLogger = Logger.getLogger(""); for (final java.util.logging.Handler handler : rootLogger.getHandlers()) { handler.setLevel(ALL); handler.setFormatter(new SimpleFormatter() { @Override public synchronized String format(final LogRecord record) { return super.format(record).replaceFirst(".*SEVERE\\s*\\S*\\s*\\S*", "\u001B[1;31m$0\u001B[0m") .replaceFirst(".*WARNING\\s*\\S*\\s*\\S*", "\u001B[1;33m$0\u001B[0m") .replaceFirst(".*CONFIG\\s*\\S*\\s*\\S*", "\u001B[35m$0\u001B[0m") .replaceFirst(".*FINE\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINER\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINEST\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m"); } }); } final LogManager logManager = LogManager.getLogManager(); final Formatter f = new Formatter() { private final Date dat = new Date(); private final String format = "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"; @Override public String format(final LogRecord record) { dat.setTime(record.getMillis()); String source; if (record.getSourceClassName() != null) { source = record.getSourceClassName(); if (record.getSourceMethodName() != null) { source += " " + record.getSourceMethodName(); } } else { source = record.getLoggerName(); } final String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); } return String.format(format, dat, source, record.getLoggerName(), record.getLevel(), message, throwable); } }; rootLogger.info("Updated all handlers the format"); final Level chaincodeLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_LEVEL)); final Package chaincodePackage = this.getClass().getPackage(); if (chaincodePackage != null) { Logger.getLogger(chaincodePackage.getName()).setLevel(chaincodeLogLevel); } else { Logger.getLogger("").setLevel(chaincodeLogLevel); } final Level shimLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_SHIM)); Logger.getLogger(ChaincodeBase.class.getPackage().getName()).setLevel(shimLogLevel); Logger.getLogger(ContractRouter.class.getPackage().getName()).setLevel(chaincodeLogLevel); final List<?> loggers = Collections.list(LogManager.getLogManager().getLoggerNames()); loggers.forEach(x -> { final Logger l = LogManager.getLogManager().getLogger((String) x); }); } } | ChaincodeBase implements Chaincode { protected final void initializeLogging() { System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"); final Logger rootLogger = Logger.getLogger(""); for (final java.util.logging.Handler handler : rootLogger.getHandlers()) { handler.setLevel(ALL); handler.setFormatter(new SimpleFormatter() { @Override public synchronized String format(final LogRecord record) { return super.format(record).replaceFirst(".*SEVERE\\s*\\S*\\s*\\S*", "\u001B[1;31m$0\u001B[0m") .replaceFirst(".*WARNING\\s*\\S*\\s*\\S*", "\u001B[1;33m$0\u001B[0m") .replaceFirst(".*CONFIG\\s*\\S*\\s*\\S*", "\u001B[35m$0\u001B[0m") .replaceFirst(".*FINE\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINER\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINEST\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m"); } }); } final LogManager logManager = LogManager.getLogManager(); final Formatter f = new Formatter() { private final Date dat = new Date(); private final String format = "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"; @Override public String format(final LogRecord record) { dat.setTime(record.getMillis()); String source; if (record.getSourceClassName() != null) { source = record.getSourceClassName(); if (record.getSourceMethodName() != null) { source += " " + record.getSourceMethodName(); } } else { source = record.getLoggerName(); } final String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); } return String.format(format, dat, source, record.getLoggerName(), record.getLevel(), message, throwable); } }; rootLogger.info("Updated all handlers the format"); final Level chaincodeLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_LEVEL)); final Package chaincodePackage = this.getClass().getPackage(); if (chaincodePackage != null) { Logger.getLogger(chaincodePackage.getName()).setLevel(chaincodeLogLevel); } else { Logger.getLogger("").setLevel(chaincodeLogLevel); } final Level shimLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_SHIM)); Logger.getLogger(ChaincodeBase.class.getPackage().getName()).setLevel(shimLogLevel); Logger.getLogger(ContractRouter.class.getPackage().getName()).setLevel(chaincodeLogLevel); final List<?> loggers = Collections.list(LogManager.getLogManager().getLoggerNames()); loggers.forEach(x -> { final Logger l = LogManager.getLogManager().getLogger((String) x); }); } } | ChaincodeBase implements Chaincode { protected final void initializeLogging() { System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"); final Logger rootLogger = Logger.getLogger(""); for (final java.util.logging.Handler handler : rootLogger.getHandlers()) { handler.setLevel(ALL); handler.setFormatter(new SimpleFormatter() { @Override public synchronized String format(final LogRecord record) { return super.format(record).replaceFirst(".*SEVERE\\s*\\S*\\s*\\S*", "\u001B[1;31m$0\u001B[0m") .replaceFirst(".*WARNING\\s*\\S*\\s*\\S*", "\u001B[1;33m$0\u001B[0m") .replaceFirst(".*CONFIG\\s*\\S*\\s*\\S*", "\u001B[35m$0\u001B[0m") .replaceFirst(".*FINE\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINER\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINEST\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m"); } }); } final LogManager logManager = LogManager.getLogManager(); final Formatter f = new Formatter() { private final Date dat = new Date(); private final String format = "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"; @Override public String format(final LogRecord record) { dat.setTime(record.getMillis()); String source; if (record.getSourceClassName() != null) { source = record.getSourceClassName(); if (record.getSourceMethodName() != null) { source += " " + record.getSourceMethodName(); } } else { source = record.getLoggerName(); } final String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); } return String.format(format, dat, source, record.getLoggerName(), record.getLevel(), message, throwable); } }; rootLogger.info("Updated all handlers the format"); final Level chaincodeLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_LEVEL)); final Package chaincodePackage = this.getClass().getPackage(); if (chaincodePackage != null) { Logger.getLogger(chaincodePackage.getName()).setLevel(chaincodeLogLevel); } else { Logger.getLogger("").setLevel(chaincodeLogLevel); } final Level shimLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_SHIM)); Logger.getLogger(ChaincodeBase.class.getPackage().getName()).setLevel(shimLogLevel); Logger.getLogger(ContractRouter.class.getPackage().getName()).setLevel(chaincodeLogLevel); final List<?> loggers = Collections.list(LogManager.getLogManager().getLoggerNames()); loggers.forEach(x -> { final Logger l = LogManager.getLogManager().getLogger((String) x); }); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); } | ChaincodeBase implements Chaincode { protected final void initializeLogging() { System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"); final Logger rootLogger = Logger.getLogger(""); for (final java.util.logging.Handler handler : rootLogger.getHandlers()) { handler.setLevel(ALL); handler.setFormatter(new SimpleFormatter() { @Override public synchronized String format(final LogRecord record) { return super.format(record).replaceFirst(".*SEVERE\\s*\\S*\\s*\\S*", "\u001B[1;31m$0\u001B[0m") .replaceFirst(".*WARNING\\s*\\S*\\s*\\S*", "\u001B[1;33m$0\u001B[0m") .replaceFirst(".*CONFIG\\s*\\S*\\s*\\S*", "\u001B[35m$0\u001B[0m") .replaceFirst(".*FINE\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINER\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m") .replaceFirst(".*FINEST\\s*\\S*\\s*\\S*", "\u001B[36m$0\u001B[0m"); } }); } final LogManager logManager = LogManager.getLogManager(); final Formatter f = new Formatter() { private final Date dat = new Date(); private final String format = "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"; @Override public String format(final LogRecord record) { dat.setTime(record.getMillis()); String source; if (record.getSourceClassName() != null) { source = record.getSourceClassName(); if (record.getSourceMethodName() != null) { source += " " + record.getSourceMethodName(); } } else { source = record.getLoggerName(); } final String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); } return String.format(format, dat, source, record.getLoggerName(), record.getLevel(), message, throwable); } }; rootLogger.info("Updated all handlers the format"); final Level chaincodeLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_LEVEL)); final Package chaincodePackage = this.getClass().getPackage(); if (chaincodePackage != null) { Logger.getLogger(chaincodePackage.getName()).setLevel(chaincodeLogLevel); } else { Logger.getLogger("").setLevel(chaincodeLogLevel); } final Level shimLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_SHIM)); Logger.getLogger(ChaincodeBase.class.getPackage().getName()).setLevel(shimLogLevel); Logger.getLogger(ContractRouter.class.getPackage().getName()).setLevel(chaincodeLogLevel); final List<?> loggers = Collections.list(LogManager.getLogManager().getLoggerNames()); loggers.forEach(x -> { final Logger l = LogManager.getLogManager().getLogger((String) x); }); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; } |
@Test public void getInstance() { final ContextFactory f1 = ContextFactory.getInstance(); final ContextFactory f2 = ContextFactory.getInstance(); assertThat(f1, sameInstance(f2)); } | public static synchronized ContextFactory getInstance() { if (cf == null) { cf = new ContextFactory(); } return cf; } | ContextFactory { public static synchronized ContextFactory getInstance() { if (cf == null) { cf = new ContextFactory(); } return cf; } } | ContextFactory { public static synchronized ContextFactory getInstance() { if (cf == null) { cf = new ContextFactory(); } return cf; } } | ContextFactory { public static synchronized ContextFactory getInstance() { if (cf == null) { cf = new ContextFactory(); } return cf; } static synchronized ContextFactory getInstance(); Context createContext(final ChaincodeStub stub); } | ContextFactory { public static synchronized ContextFactory getInstance() { if (cf == null) { cf = new ContextFactory(); } return cf; } static synchronized ContextFactory getInstance(); Context createContext(final ChaincodeStub stub); } |
@Test public void createContext() { final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); final Context ctx = ContextFactory.getInstance().createContext(stub); assertThat(stub.getArgs(), is(equalTo(ctx.getStub().getArgs()))); assertThat(stub.getStringArgs(), is(equalTo(ctx.getStub().getStringArgs()))); assertThat(stub.getFunction(), is(equalTo(ctx.getStub().getFunction()))); assertThat(stub.getParameters(), is(equalTo(ctx.getStub().getParameters()))); assertThat(stub.getTxId(), is(equalTo(ctx.getStub().getTxId()))); assertThat(stub.getChannelId(), is(equalTo(ctx.getStub().getChannelId()))); assertThat(stub.invokeChaincode("cc", Collections.emptyList(), "ch0"), is(equalTo(ctx.getStub().invokeChaincode("cc", Collections.emptyList(), "ch0")))); assertThat(stub.getState("a"), is(equalTo(ctx.getStub().getState("a")))); ctx.getStub().putState("b", "sdfg".getBytes()); assertThat(stub.getStringState("b"), is(equalTo(ctx.getStub().getStringState("b")))); assertThat(ctx.clientIdentity.getMSPID(), is(equalTo("testMSPID"))); assertThat(ctx.clientIdentity.getId(), is(equalTo( "x509::CN=admin, OU=Fabric, O=Hyperledger, ST=North Carolina," + " C=US::CN=example.com, OU=WWW, O=Internet Widgets, L=San Francisco, ST=California, C=US"))); } | public Context createContext(final ChaincodeStub stub) { final Context newContext = new Context(stub); return newContext; } | ContextFactory { public Context createContext(final ChaincodeStub stub) { final Context newContext = new Context(stub); return newContext; } } | ContextFactory { public Context createContext(final ChaincodeStub stub) { final Context newContext = new Context(stub); return newContext; } } | ContextFactory { public Context createContext(final ChaincodeStub stub) { final Context newContext = new Context(stub); return newContext; } static synchronized ContextFactory getInstance(); Context createContext(final ChaincodeStub stub); } | ContextFactory { public Context createContext(final ChaincodeStub stub) { final Context newContext = new Context(stub); return newContext; } static synchronized ContextFactory getInstance(); Context createContext(final ChaincodeStub stub); } |
@Test public void getInstance() { final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); final Context context1 = new Context(stub); final Context context2 = new Context(stub); assertThat(context1.getStub(), sameInstance(context2.getStub())); } | public ChaincodeStub getStub() { return this.stub; } | Context { public ChaincodeStub getStub() { return this.stub; } } | Context { public ChaincodeStub getStub() { return this.stub; } Context(final ChaincodeStub stub); } | Context { public ChaincodeStub getStub() { return this.stub; } Context(final ChaincodeStub stub); ChaincodeStub getStub(); ClientIdentity getClientIdentity(); } | Context { public ChaincodeStub getStub() { return this.stub; } Context(final ChaincodeStub stub); ChaincodeStub getStub(); ClientIdentity getClientIdentity(); } |
@Test public void getSetClientIdentity() { final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); final Context context = ContextFactory.getInstance().createContext(stub); assertThat(context.getClientIdentity(), sameInstance(context.clientIdentity)); } | public ClientIdentity getClientIdentity() { return this.clientIdentity; } | Context { public ClientIdentity getClientIdentity() { return this.clientIdentity; } } | Context { public ClientIdentity getClientIdentity() { return this.clientIdentity; } Context(final ChaincodeStub stub); } | Context { public ClientIdentity getClientIdentity() { return this.clientIdentity; } Context(final ChaincodeStub stub); ChaincodeStub getStub(); ClientIdentity getClientIdentity(); } | Context { public ClientIdentity getClientIdentity() { return this.clientIdentity; } Context(final ChaincodeStub stub); ChaincodeStub getStub(); ClientIdentity getClientIdentity(); } |
@Test public void testCreateAndScan() { final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"}); r.findAllContracts(); final ChaincodeStub s = new ChaincodeStubNaiveImpl(); final List<String> args = new ArrayList<>(); args.add("samplecontract:t1"); args.add("asdf"); ((ChaincodeStubNaiveImpl) s).setStringArgs(args); final InvocationRequest request = ExecutionFactory.getInstance().createRequest(s); assertThat(request.getNamespace(), is(equalTo(SampleContract.class.getAnnotation(Contract.class).name()))); assertThat(request.getMethod(), is(equalTo("t1"))); assertThat(request.getRequestName(), is(equalTo("samplecontract:t1"))); assertThat(request.getArgs(), is(contains(s.getArgs().get(1)))); } | protected void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } | ContractRouter extends ChaincodeBase { protected void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } } | ContractRouter extends ChaincodeBase { protected void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } ContractRouter(final String[] args); } | ContractRouter extends ChaincodeBase { protected void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } ContractRouter(final String[] args); @Override Response invoke(final ChaincodeStub stub); @Override Response init(final ChaincodeStub stub); static void main(final String[] args); } | ContractRouter extends ChaincodeBase { protected void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } ContractRouter(final String[] args); @Override Response invoke(final ChaincodeStub stub); @Override Response init(final ChaincodeStub stub); static void main(final String[] args); } |
@Test public void testInit() { final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"}); r.findAllContracts(); final ChaincodeStub s = new ChaincodeStubNaiveImpl(); final List<String> args = new ArrayList<>(); args.add("samplecontract:t1"); args.add("asdf"); ((ChaincodeStubNaiveImpl) s).setStringArgs(args); SampleContract.setBeforeInvoked(0); SampleContract.setAfterInvoked(0); SampleContract.setDoWorkInvoked(0); SampleContract.setT1Invoked(0); final Chaincode.Response response = r.init(s); assertThat(response, is(notNullValue())); assertThat(response.getStatus(), is(Chaincode.Response.Status.SUCCESS)); assertThat(response.getMessage(), is(nullValue())); assertThat(response.getStringPayload(), is(equalTo("asdf"))); assertThat(SampleContract.getBeforeInvoked(), is(1)); assertThat(SampleContract.getAfterInvoked(), is(1)); assertThat(SampleContract.getDoWorkInvoked(), is(1)); assertThat(SampleContract.getT1Invoked(), is(1)); } | @Override public Response init(final ChaincodeStub stub) { return processRequest(stub); } | ContractRouter extends ChaincodeBase { @Override public Response init(final ChaincodeStub stub) { return processRequest(stub); } } | ContractRouter extends ChaincodeBase { @Override public Response init(final ChaincodeStub stub) { return processRequest(stub); } ContractRouter(final String[] args); } | ContractRouter extends ChaincodeBase { @Override public Response init(final ChaincodeStub stub) { return processRequest(stub); } ContractRouter(final String[] args); @Override Response invoke(final ChaincodeStub stub); @Override Response init(final ChaincodeStub stub); static void main(final String[] args); } | ContractRouter extends ChaincodeBase { @Override public Response init(final ChaincodeStub stub) { return processRequest(stub); } ContractRouter(final String[] args); @Override Response invoke(final ChaincodeStub stub); @Override Response init(final ChaincodeStub stub); static void main(final String[] args); } |
@Test public void putIfNotNull() { final TypeSchema ts = new TypeSchema(); System.out.println("Key - value"); ts.putIfNotNull("Key", "value"); System.out.println("Key - null"); final String nullstr = null; ts.putIfNotNull("Key", nullstr); assertThat(ts.get("Key"), equalTo("value")); System.out.println("Key - <empty>"); ts.putIfNotNull("Key", ""); assertThat(ts.get("Key"), equalTo("value")); } | String putIfNotNull(final String key, final String value) { return (String) this.putInternal(key, value); } | TypeSchema extends HashMap<String, Object> { String putIfNotNull(final String key, final String value) { return (String) this.putInternal(key, value); } } | TypeSchema extends HashMap<String, Object> { String putIfNotNull(final String key, final String value) { return (String) this.putInternal(key, value); } TypeSchema(); } | TypeSchema extends HashMap<String, Object> { String putIfNotNull(final String key, final String value) { return (String) this.putInternal(key, value); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } | TypeSchema extends HashMap<String, Object> { String putIfNotNull(final String key, final String value) { return (String) this.putInternal(key, value); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } |
@Test public void getType() { final TypeSchema ts = new TypeSchema(); ts.put("type", "MyType"); assertThat(ts.getType(), equalTo("MyType")); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getType(), equalTo("MyType")); } | public String getType() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("type"); } return (String) this.get("type"); } | TypeSchema extends HashMap<String, Object> { public String getType() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("type"); } return (String) this.get("type"); } } | TypeSchema extends HashMap<String, Object> { public String getType() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("type"); } return (String) this.get("type"); } TypeSchema(); } | TypeSchema extends HashMap<String, Object> { public String getType() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("type"); } return (String) this.get("type"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } | TypeSchema extends HashMap<String, Object> { public String getType() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("type"); } return (String) this.get("type"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } |
@Test(expected = CompositeKeyFormatException.class) public void testValidateSimpleKeysException() throws Exception { CompositeKey.validateSimpleKeys("\u0000abc"); } | public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); } | CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; } |
@Test public void getFormat() { final TypeSchema ts = new TypeSchema(); ts.put("format", "MyFormat"); assertThat(ts.getFormat(), equalTo("MyFormat")); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getFormat(), equalTo("MyFormat")); } | public String getFormat() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("format"); } return (String) this.get("format"); } | TypeSchema extends HashMap<String, Object> { public String getFormat() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("format"); } return (String) this.get("format"); } } | TypeSchema extends HashMap<String, Object> { public String getFormat() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("format"); } return (String) this.get("format"); } TypeSchema(); } | TypeSchema extends HashMap<String, Object> { public String getFormat() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("format"); } return (String) this.get("format"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } | TypeSchema extends HashMap<String, Object> { public String getFormat() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("format"); } return (String) this.get("format"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } |
@Test public void getRef() { final TypeSchema ts = new TypeSchema(); ts.put("$ref", "#/ref/to/MyType"); assertThat(ts.getRef(), equalTo("#/ref/to/MyType")); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getRef(), equalTo("#/ref/to/MyType")); } | public String getRef() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("$ref"); } return (String) this.get("$ref"); } | TypeSchema extends HashMap<String, Object> { public String getRef() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("$ref"); } return (String) this.get("$ref"); } } | TypeSchema extends HashMap<String, Object> { public String getRef() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("$ref"); } return (String) this.get("$ref"); } TypeSchema(); } | TypeSchema extends HashMap<String, Object> { public String getRef() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("$ref"); } return (String) this.get("$ref"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } | TypeSchema extends HashMap<String, Object> { public String getRef() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("$ref"); } return (String) this.get("$ref"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } |
@Test public void getItems() { final TypeSchema ts1 = new TypeSchema(); final TypeSchema ts = new TypeSchema(); ts.put("items", ts1); assertThat(ts.getItems(), equalTo(ts1)); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getItems(), equalTo(ts1)); } | public TypeSchema getItems() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (TypeSchema) intermediateMap.get("items"); } return (TypeSchema) this.get("items"); } | TypeSchema extends HashMap<String, Object> { public TypeSchema getItems() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (TypeSchema) intermediateMap.get("items"); } return (TypeSchema) this.get("items"); } } | TypeSchema extends HashMap<String, Object> { public TypeSchema getItems() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (TypeSchema) intermediateMap.get("items"); } return (TypeSchema) this.get("items"); } TypeSchema(); } | TypeSchema extends HashMap<String, Object> { public TypeSchema getItems() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (TypeSchema) intermediateMap.get("items"); } return (TypeSchema) this.get("items"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } | TypeSchema extends HashMap<String, Object> { public TypeSchema getItems() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (TypeSchema) intermediateMap.get("items"); } return (TypeSchema) this.get("items"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } |
@Test public void getTypeClass() { final TypeSchema ts = new TypeSchema(); ts.put("type", "string"); final TypeRegistry mockRegistry = new TypeRegistryImpl(); assertThat(ts.getTypeClass(mockRegistry), equalTo(String.class)); ts.put("type", "integer"); ts.put("format", "int8"); assertThat(ts.getTypeClass(mockRegistry), equalTo(byte.class)); ts.put("type", "integer"); ts.put("format", "int16"); assertThat(ts.getTypeClass(mockRegistry), equalTo(short.class)); ts.put("type", "integer"); ts.put("format", "int32"); assertThat(ts.getTypeClass(mockRegistry), equalTo(int.class)); ts.put("type", "integer"); ts.put("format", "int64"); assertThat(ts.getTypeClass(mockRegistry), equalTo(long.class)); ts.put("type", "number"); ts.put("format", "double"); assertThat(ts.getTypeClass(mockRegistry), equalTo(double.class)); ts.put("type", "number"); ts.put("format", "float"); assertThat(ts.getTypeClass(mockRegistry), equalTo(float.class)); ts.put("type", "boolean"); assertThat(ts.getTypeClass(mockRegistry), equalTo(boolean.class)); ts.put("type", null); ts.put("$ref", "#/ref/to/MyType"); mockRegistry.addDataType(MyType.class); assertThat(ts.getTypeClass(mockRegistry), equalTo(MyType.class)); final TypeSchema array = new TypeSchema(); array.put("type", "array"); array.put("items", ts); assertThat(array.getTypeClass(mockRegistry), equalTo(MyType[].class)); } | public Class<?> getTypeClass(final TypeRegistry typeRegistry) { Class<?> clz = null; String type = getType(); if (type == null) { type = "object"; } if (type.contentEquals("string")) { final String format = getFormat(); if (format != null && format.contentEquals("uint16")) { clz = char.class; } else { clz = String.class; } } else if (type.contentEquals("integer")) { final String format = getFormat(); switch (format) { case "int8": clz = byte.class; break; case "int16": clz = short.class; break; case "int32": clz = int.class; break; case "int64": clz = long.class; break; default: throw new RuntimeException("Unknown format for integer of " + format); } } else if (type.contentEquals("number")) { final String format = getFormat(); switch (format) { case "double": clz = double.class; break; case "float": clz = float.class; break; default: throw new RuntimeException("Unknown format for number of " + format); } } else if (type.contentEquals("boolean")) { clz = boolean.class; } else if (type.contentEquals("object")) { final String ref = this.getRef(); final String format = ref.substring(ref.lastIndexOf("/") + 1); clz = typeRegistry.getDataType(format).getTypeClass(); } else if (type.contentEquals("array")) { final TypeSchema typdef = this.getItems(); final Class<?> arrayType = typdef.getTypeClass(typeRegistry); clz = Array.newInstance(arrayType, 0).getClass(); } return clz; } | TypeSchema extends HashMap<String, Object> { public Class<?> getTypeClass(final TypeRegistry typeRegistry) { Class<?> clz = null; String type = getType(); if (type == null) { type = "object"; } if (type.contentEquals("string")) { final String format = getFormat(); if (format != null && format.contentEquals("uint16")) { clz = char.class; } else { clz = String.class; } } else if (type.contentEquals("integer")) { final String format = getFormat(); switch (format) { case "int8": clz = byte.class; break; case "int16": clz = short.class; break; case "int32": clz = int.class; break; case "int64": clz = long.class; break; default: throw new RuntimeException("Unknown format for integer of " + format); } } else if (type.contentEquals("number")) { final String format = getFormat(); switch (format) { case "double": clz = double.class; break; case "float": clz = float.class; break; default: throw new RuntimeException("Unknown format for number of " + format); } } else if (type.contentEquals("boolean")) { clz = boolean.class; } else if (type.contentEquals("object")) { final String ref = this.getRef(); final String format = ref.substring(ref.lastIndexOf("/") + 1); clz = typeRegistry.getDataType(format).getTypeClass(); } else if (type.contentEquals("array")) { final TypeSchema typdef = this.getItems(); final Class<?> arrayType = typdef.getTypeClass(typeRegistry); clz = Array.newInstance(arrayType, 0).getClass(); } return clz; } } | TypeSchema extends HashMap<String, Object> { public Class<?> getTypeClass(final TypeRegistry typeRegistry) { Class<?> clz = null; String type = getType(); if (type == null) { type = "object"; } if (type.contentEquals("string")) { final String format = getFormat(); if (format != null && format.contentEquals("uint16")) { clz = char.class; } else { clz = String.class; } } else if (type.contentEquals("integer")) { final String format = getFormat(); switch (format) { case "int8": clz = byte.class; break; case "int16": clz = short.class; break; case "int32": clz = int.class; break; case "int64": clz = long.class; break; default: throw new RuntimeException("Unknown format for integer of " + format); } } else if (type.contentEquals("number")) { final String format = getFormat(); switch (format) { case "double": clz = double.class; break; case "float": clz = float.class; break; default: throw new RuntimeException("Unknown format for number of " + format); } } else if (type.contentEquals("boolean")) { clz = boolean.class; } else if (type.contentEquals("object")) { final String ref = this.getRef(); final String format = ref.substring(ref.lastIndexOf("/") + 1); clz = typeRegistry.getDataType(format).getTypeClass(); } else if (type.contentEquals("array")) { final TypeSchema typdef = this.getItems(); final Class<?> arrayType = typdef.getTypeClass(typeRegistry); clz = Array.newInstance(arrayType, 0).getClass(); } return clz; } TypeSchema(); } | TypeSchema extends HashMap<String, Object> { public Class<?> getTypeClass(final TypeRegistry typeRegistry) { Class<?> clz = null; String type = getType(); if (type == null) { type = "object"; } if (type.contentEquals("string")) { final String format = getFormat(); if (format != null && format.contentEquals("uint16")) { clz = char.class; } else { clz = String.class; } } else if (type.contentEquals("integer")) { final String format = getFormat(); switch (format) { case "int8": clz = byte.class; break; case "int16": clz = short.class; break; case "int32": clz = int.class; break; case "int64": clz = long.class; break; default: throw new RuntimeException("Unknown format for integer of " + format); } } else if (type.contentEquals("number")) { final String format = getFormat(); switch (format) { case "double": clz = double.class; break; case "float": clz = float.class; break; default: throw new RuntimeException("Unknown format for number of " + format); } } else if (type.contentEquals("boolean")) { clz = boolean.class; } else if (type.contentEquals("object")) { final String ref = this.getRef(); final String format = ref.substring(ref.lastIndexOf("/") + 1); clz = typeRegistry.getDataType(format).getTypeClass(); } else if (type.contentEquals("array")) { final TypeSchema typdef = this.getItems(); final Class<?> arrayType = typdef.getTypeClass(typeRegistry); clz = Array.newInstance(arrayType, 0).getClass(); } return clz; } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } | TypeSchema extends HashMap<String, Object> { public Class<?> getTypeClass(final TypeRegistry typeRegistry) { Class<?> clz = null; String type = getType(); if (type == null) { type = "object"; } if (type.contentEquals("string")) { final String format = getFormat(); if (format != null && format.contentEquals("uint16")) { clz = char.class; } else { clz = String.class; } } else if (type.contentEquals("integer")) { final String format = getFormat(); switch (format) { case "int8": clz = byte.class; break; case "int16": clz = short.class; break; case "int32": clz = int.class; break; case "int64": clz = long.class; break; default: throw new RuntimeException("Unknown format for integer of " + format); } } else if (type.contentEquals("number")) { final String format = getFormat(); switch (format) { case "double": clz = double.class; break; case "float": clz = float.class; break; default: throw new RuntimeException("Unknown format for number of " + format); } } else if (type.contentEquals("boolean")) { clz = boolean.class; } else if (type.contentEquals("object")) { final String ref = this.getRef(); final String format = ref.substring(ref.lastIndexOf("/") + 1); clz = typeRegistry.getDataType(format).getTypeClass(); } else if (type.contentEquals("array")) { final TypeSchema typdef = this.getItems(); final Class<?> arrayType = typdef.getTypeClass(typeRegistry); clz = Array.newInstance(arrayType, 0).getClass(); } return clz; } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.