src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ElasticsearchIndexIndexingPlanExecution { CompletableFuture<IndexIndexingPlanExecutionReport<R>> execute() { CompletableFuture<IndexIndexingPlanExecutionReport<R>> reportFuture = CompletableFuture.allOf( futures ) .handle( (result, throwable) -> onAllWorksFinished() ); for ( int i = 0; i < works.size(); i++ ) { Complet...
@Test public void success() { ArgumentCaptor<CompletableFuture<Void>> work1FutureCaptor = futureCaptor(); ArgumentCaptor<CompletableFuture<Void>> work2FutureCaptor = futureCaptor(); ArgumentCaptor<CompletableFuture<Void>> work3FutureCaptor = futureCaptor(); CompletableFuture<IndexIndexingPlanExecutionReport<StubEntityR...
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public long getContentLength() { this.contentLengthWasProvided = true; return this.contentLength; } GsonHttpEntity(Gson gson, List<JsonObject> bodyParts); @Override boolean isRepeatable(); @Override boolean isChunked(); @Override long getContent...
@Test public void initialContentLength() { assumeTrue( expectedContentLength < 1024 ); assertThat( gsonEntity.getContentLength() ).isEqualTo( expectedContentLength ); } @Test public void produceContent_noPushBack() throws IOException { int pushBackPeriod = Integer.MAX_VALUE; for ( int i = 0; i < 2; i++ ) { assertThat( ...
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public Header getContentType() { return CONTENT_TYPE; } GsonHttpEntity(Gson gson, List<JsonObject> bodyParts); @Override boolean isRepeatable(); @Override boolean isChunked(); @Override long getContentLength(); @Override Header getContentType();...
@Test public void contentType() { Header contentType = gsonEntity.getContentType(); assertThat( contentType.getName() ).isEqualTo( "Content-Type" ); assertThat( contentType.getValue() ).isEqualTo( "application/json; charset=UTF-8" ); }
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public void writeTo(OutputStream out) throws IOException { CountingOutputStream countingStream = new CountingOutputStream( out ); Writer writer = new OutputStreamWriter( countingStream, CHARSET ); for ( JsonObject bodyPart : bodyParts ) { gson.t...
@Test public void writeTo() throws IOException { for ( int i = 0; i < 2; i++ ) { assertThat( doWriteTo( gsonEntity ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } }
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public InputStream getContent() { return new HttpAsyncContentProducerInputStream( this, BYTE_BUFFER_PAGE_SIZE ); } GsonHttpEntity(Gson gson, List<JsonObject> bodyParts); @Override boolean isRepeatable(); @Override boolean isChunked(); @Override ...
@Test public void getContent() throws IOException { for ( int i = 0; i < 2; i++ ) { assertThat( doGetContent( gsonEntity ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } }
SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser pushAll(AutoCloseable ... closeables) { return pushAll( AutoCloseable::close, closeables ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoClose...
@Test public void iterable() throws IOException { Throwable mainException = new Exception(); IOException exception1 = new IOException(); RuntimeException exception2 = new IllegalStateException(); IOException exception3 = new IOException(); RuntimeException exception4 = new UnsupportedOperationException(); List<Closeabl...
SerializationUtil { public static int parseIntegerParameter(String key, String value) { try { return Integer.parseInt( value ); } catch (NumberFormatException e) { throw log.unableToParseJobParameter( key, value, e ); } } private SerializationUtil(); static String serialize(Object object); static Object deserialize(St...
@Test public void deserializeInt_fromInt() throws Exception { int i = SerializationUtil.parseIntegerParameter( "My parameter", "1" ); assertThat( i ).isEqualTo( 1 ); } @Test public void deserializeInt_fromDouble() throws Exception { thrown.expect( SearchException.class ); thrown.expectMessage( "HSEARCH500029: Unable to...
SerializationUtil { public static Integer parseIntegerParameterOptional(String key, String value, Integer defaultValue) { if ( value == null ) { return defaultValue; } else { return parseIntegerParameter( key, value ); } } private SerializationUtil(); static String serialize(Object object); static Object deserialize(S...
@Test public void deserializeInt_defaultValue() throws Exception { int i = SerializationUtil.parseIntegerParameterOptional( "My parameter", null, 1 ); assertThat( i ).isEqualTo( 1 ); }
SerializationUtil { public static boolean parseBooleanParameterOptional(String key, String value, boolean defaultValue) { if ( value == null ) { return defaultValue; } if ( "true".equalsIgnoreCase( value ) ) { return true; } if ( "false".equalsIgnoreCase( value ) ) { return false; } throw log.unableToParseJobParameter(...
@Test public void deserializeBoolean_fromLowerCase() throws Exception { boolean t = SerializationUtil.parseBooleanParameterOptional( "My parameter 1", "true", false ); boolean f = SerializationUtil.parseBooleanParameterOptional( "My parameter 2", "false", true ); assertThat( t ).isTrue(); assertThat( f ).isFalse(); } @...
SimpleGlobPattern { public boolean matches(String candidate) { return matches( candidate, 0 ); } private SimpleGlobPattern(); static SimpleGlobPattern compile(String patternString); boolean matches(String candidate); SimpleGlobPattern prependLiteral(String literal); SimpleGlobPattern prependMany(); Optional<String> to...
@Test public void matches() { assertSoftly( softly -> { for ( String candidate : expectedMatching ) { softly.assertThat( pattern.matches( candidate ) ) .as( "'" + patternString + "' matches '" + candidate + "'" ) .isTrue(); } for ( String candidate : expectedNonMatching ) { softly.assertThat( pattern.matches( candidate...
ValidationUtil { public static void validateEntityTypes( EntityManagerFactoryRegistry emfRegistry, String entityManagerFactoryScope, String entityManagerFactoryReference, String serializedEntityTypes) { EntityManagerFactory emf = JobContextUtil.getEntityManagerFactory( emfRegistry, entityManagerFactoryScope, entityMana...
@Test public void validateEntityTypes_whenAllTypesAreAvailableInEMF() throws Exception { String serializedEntityTypes = Stream .of( Company.class, Person.class ) .map( Class::getName ) .collect( Collectors.joining( "," ) ); ValidationUtil.validateEntityTypes( null, EMF_SCOPE, PERSISTENCE_UNIT_NAME, serializedEntityType...
ValidationUtil { public static void validatePositive(String parameterName, int parameterValue) { if ( parameterValue <= 0 ) { throw log.negativeValueOrZero( parameterName, parameterValue ); } } private ValidationUtil(); static void validateCheckpointInterval(int checkpointInterval, int rowsPerPartition); static void v...
@Test(expected = SearchException.class) public void validatePositive_valueIsNegative() throws Exception { ValidationUtil.validatePositive( "MyParameter", -1 ); } @Test(expected = SearchException.class) public void validatePositive_valueIsZero() throws Exception { ValidationUtil.validatePositive( "MyParameter", 0 ); } @...
ValidationUtil { public static void validateCheckpointInterval(int checkpointInterval, int rowsPerPartition) { if ( checkpointInterval > rowsPerPartition ) { throw log.illegalCheckpointInterval( checkpointInterval, rowsPerPartition ); } } private ValidationUtil(); static void validateCheckpointInterval(int checkpointI...
@Test public void validateCheckpointInterval_lessThanRowsPerPartition() throws Exception { ValidationUtil.validateCheckpointInterval( 99, 100 ); } @Test public void validateCheckpointInterval_equalToRowsPerPartition() { ValidationUtil.validateCheckpointInterval( 100, 100 ); } @Test(expected = SearchException.class) pub...
SimpleGlobPattern { public abstract String toPatternString(); private SimpleGlobPattern(); static SimpleGlobPattern compile(String patternString); boolean matches(String candidate); SimpleGlobPattern prependLiteral(String literal); SimpleGlobPattern prependMany(); Optional<String> toLiteral(); abstract String toPatter...
@Test public void toPatternString() { assertThat( pattern.toPatternString() ).isEqualTo( expectedToPatternString ); }
ValidationUtil { public static void validateSessionClearInterval(int sessionClearInterval, int checkpointInterval) { if ( sessionClearInterval > checkpointInterval ) { throw log.illegalSessionClearInterval( sessionClearInterval, checkpointInterval ); } } private ValidationUtil(); static void validateCheckpointInterval...
@Test public void validateSessionClearInterval_lessThanCheckpointInterval() throws Exception { ValidationUtil.validateSessionClearInterval( 99, 100 ); } @Test public void validateSessionClearInterval_equalToCheckpointInterval() { ValidationUtil.validateSessionClearInterval( 100, 100 ); } @Test(expected = SearchExceptio...
PartitionMapper implements javax.batch.api.partition.PartitionMapper { @Override public PartitionPlan mapPartitions() throws Exception { JobContextData jobData = (JobContextData) jobContext.getTransientUserData(); emf = jobData.getEntityManagerFactory(); try ( StatelessSession ss = PersistenceUtil.openStatelessSession(...
@Test public void testMapPartitions() throws Exception { JobContextData jobData = new JobContextData(); jobData.setEntityManagerFactory( emf ); jobData.setCustomQueryCriteria( new HashSet<>() ); jobData.setEntityTypeDescriptors( Arrays.asList( JobTestUtil.createSimpleEntityTypeDescriptor( emf, Company.class ), JobTestU...
TypePatternMatcherFactory { public TypePatternMatcher createExactRawTypeMatcher(Class<?> exactTypeToMatch) { PojoRawTypeModel<?> exactTypeToMatchModel = introspector.typeModel( exactTypeToMatch ); return new ExactRawTypeMatcher( exactTypeToMatchModel ); } TypePatternMatcherFactory(PojoBootstrapIntrospector introspector...
@Test public void exactType() { PojoRawTypeModel typeToMatchMock = mock( PojoRawTypeModel.class ); PojoGenericTypeModel typeToInspectMock = mock( PojoGenericTypeModel.class ); PojoRawTypeModel typeToInspectRawTypeMock = mock( PojoRawTypeModel.class ); when( introspectorMock.typeModel( String.class ) ) .thenReturn( type...
TypePatternMatcherFactory { public ExtractingTypePatternMatcher createExtractingMatcher(Type typePattern, Type typeToExtract) { if ( typePattern instanceof TypeVariable ) { throw new UnsupportedOperationException( "Matching a type variable is not supported" ); } else if ( typePattern instanceof WildcardType ) { throw n...
@Test public void wildcardType() { assertThatThrownBy( () -> factory.createExtractingMatcher( new WildcardTypeCapture<Of<?>>() { }.getType(), String.class ) ) .isInstanceOf( UnsupportedOperationException.class ); } @Test public <T> void typeVariable() { Type type = new TypeCapture<T>() { }.getType(); assertThatThrownBy...
SimpleGlobPattern { public Optional<String> toLiteral() { return Optional.empty(); } private SimpleGlobPattern(); static SimpleGlobPattern compile(String patternString); boolean matches(String candidate); SimpleGlobPattern prependLiteral(String literal); SimpleGlobPattern prependMany(); Optional<String> toLiteral(); a...
@Test public void toLiteral() { assertThat( pattern.toLiteral() ).isEqualTo( expectedToLiteral ); }
CancellableExecutionCompletableFuture extends CompletableFuture<T> { @Override public boolean cancel(boolean mayInterruptIfRunning) { super.cancel( mayInterruptIfRunning ); return future.cancel( mayInterruptIfRunning ); } CancellableExecutionCompletableFuture(Runnable runnable, ExecutorService executor); @Override bool...
@Test public void runnable_cancel() throws InterruptedException { AtomicBoolean started = new AtomicBoolean( false ); AtomicBoolean finished = new AtomicBoolean( false ); CompletableFuture<Void> future = new CancellableExecutionCompletableFuture<>( () -> { started.set( true ); try { Thread.sleep( Long.MAX_VALUE ); } ca...
PojoModelPath { public static PojoModelPathPropertyNode ofProperty(String propertyName) { return new PojoModelPathPropertyNode( null, propertyName ); } PojoModelPath(); static Builder builder(); static PojoModelPathPropertyNode ofProperty(String propertyName); static PojoModelPathValueNode ofValue(String propertyName);...
@Test public void ofProperty() { assertThat( PojoModelPath.ofProperty( "foo" ) ) .satisfies( isPath( "foo" ) ); assertThatThrownBy( () -> PojoModelPath.ofProperty( null ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.ofProperty( "" ) ) .isInstanceOf( IllegalArgumentException...
Closer extends AbstractCloser<Closer<E>, E> implements AutoCloseable { public <E2 extends Exception> Closer<E2> split() { return new Closer<>( state ); } Closer(); private Closer(CloseableState state); Closer<E2> split(); @Override void close(); }
@Test public void split() { MyException1 exception1 = new MyException1(); MyException2 exception2 = new MyException2(); IOException exception3 = new IOException(); assertThatThrownBy( () -> { try ( Closer<IOException> closer1 = new Closer<>(); Closer<MyException1> closer2 = closer1.split(); Closer<MyException2> closer3...
PojoModelPath { public static PojoModelPathValueNode ofValue(String propertyName) { return ofValue( propertyName, ContainerExtractorPath.defaultExtractors() ); } PojoModelPath(); static Builder builder(); static PojoModelPathPropertyNode ofProperty(String propertyName); static PojoModelPathValueNode ofValue(String prop...
@Test public void ofValue_property() { assertThat( PojoModelPath.ofValue( "foo" ) ) .satisfies( isPath( "foo", ContainerExtractorPath.defaultExtractors() ) ); assertThatThrownBy( () -> PojoModelPath.ofValue( null ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.ofValue( "" ) ...
PojoModelPath { public static PojoModelPathValueNode parse(String dotSeparatedPath) { Contracts.assertNotNullNorEmpty( dotSeparatedPath, "dotSeparatedPath" ); Builder builder = builder(); for ( String propertyName : DOT_PATTERN.split( dotSeparatedPath, -1 ) ) { builder.property( propertyName ).valueWithDefaultExtractor...
@Test public void parse() { assertThat( PojoModelPath.parse( "foo" ) ) .satisfies( isPath( "foo", ContainerExtractorPath.defaultExtractors() ) ); assertThat( PojoModelPath.parse( "foo.bar" ) ) .satisfies( isPath( "foo", ContainerExtractorPath.defaultExtractors(), "bar", ContainerExtractorPath.defaultExtractors() ) ); a...
PojoModelPath { public static Builder builder() { return new Builder(); } PojoModelPath(); static Builder builder(); static PojoModelPathPropertyNode ofProperty(String propertyName); static PojoModelPathValueNode ofValue(String propertyName); static PojoModelPathValueNode ofValue(String propertyName, ContainerExtractor...
@Test public void builder() { PojoModelPath.Builder builder = PojoModelPath.builder(); builder.property( "foo" ).value( BuiltinContainerExtractors.COLLECTION ) .property( "bar" ).valueWithoutExtractors() .property( "fubar" ).valueWithDefaultExtractors() .property( "other" ).value( BuiltinContainerExtractors.MAP_KEY ) ....
HibernateOrmExtension implements IdentifierBridgeToDocumentIdentifierContextExtension<HibernateOrmMappingContext>, IdentifierBridgeFromDocumentIdentifierContextExtension<HibernateOrmSessionContext>, RoutingBridgeRouteContextExtension<HibernateOrmSessionContext>, org.hibernate.search.mapper.pojo.bridge.runti...
@Test public void identifierBridge() { IdentifierBridgeToDocumentIdentifierContext toDocumentContext = new IdentifierBridgeToDocumentIdentifierContextImpl( mappingContext ); assertThat( toDocumentContext.extension( HibernateOrmExtension.get() ) ).isSameAs( mappingContext ); IdentifierBridgeFromDocumentIdentifierContext...
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 ); } ...
@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 ConfiguredB...
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_...
@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"...
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); @De...
@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" );...
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); @Depr...
@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.i...
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) { th...
@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.pa...
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); @Overrid...
@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 )...
IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildSt...
@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 = ...
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( wor...
@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 ); execut...
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 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 = tru...
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); re...
@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...
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)...
@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...
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...
@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();...
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... ...
@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()...
StateBasedEndorsementFactory { public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); } return instance; } static synchronized StateBasedEndorsementFactory getInstance(); StateBasedEndorsement newStateBasedEndorsement(final byte[] ...
@Test public void getInstance() { assertNotNull(StateBasedEndorsementFactory.getInstance()); assertTrue(StateBasedEndorsementFactory.getInstance() instanceof StateBasedEndorsementFactory); }
StateBasedEndorsementFactory { public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) { return new StateBasedEndorsementImpl(ep); } 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}); }
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 testKeyValueImpl() { new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); }
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 testGetKey() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getKey(), is(equalTo("key"))); }
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(); @Transact...
@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, () -> { cont...
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 testGetValue() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getValue(), is(equalTo("value".getBytes(UTF_8)))); }
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 testGetStringValue() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getStringValue(), is(equalTo("value"))); }
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 ...
@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.ha...
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(o...
@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 KeyV...
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; } InvocationTaskManage...
@Test public void register() throws UnsupportedEncodingException { itm.register(); }
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...
@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.setS...
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().toByteS...
@Test void testNewGetPrivateDataHashEventMessage() { ChaincodeMessageFactory.newGetPrivateDataHashEventMessage(channelId, txId, collection, key); }
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...
@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("10...
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 C...
@Test void testNewGetStateEventMessage() { ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, collection, key); }
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().toBy...
@Test void testNewGetStateMetadataEventMessage() { ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, collection, key); }
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(valu...
@Test void testNewPutStateEventMessage() { ChaincodeMessageFactory.newPutStateEventMessage(channelId, txId, collection, key, value); }
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().setC...
@Test void testNewPutStateMetadataEventMessage() { ChaincodeMessageFactory.newPutStateMetadataEventMessage(channelId, txId, collection, key, metakey, value); }
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...
@Test void testNewDeleteStateEventMessage() { ChaincodeMessageFactory.newDeleteStateEventMessage(channelId, txId, collection, key); }
ChaincodeMessageFactory { protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } private ChaincodeMessageFactory(); }
@Test void testNewErrorEventMessage() { ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, message); ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, throwable); ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, message, event); }
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); ...
@Test void testNewCompletedEventMessage() { ChaincodeMessageFactory.newCompletedEventMessage(channelId, txId, response, event); }
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 testNewInvokeChaincodeMessage() { ChaincodeMessageFactory.newInvokeChaincodeMessage(channelId, txId, payload); }
ChaincodeMessageFactory { protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); } private ChaincodeMessageFactory(); }
@Test void testNewRegisterChaincodeMessage() { ChaincodeMessageFactory.newRegisterChaincodeMessage(chaincodeId); }
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 void testNewEventMessageTypeStringStringByteString() { ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload); ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload, event); }
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(); } KeyModificationImp...
@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 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 isDel...
@Test public void testGetTxId() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setTxId("txid") .build()); assertThat(km.getTxId(), is(equalTo("txid"))); }
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(); @Overri...
@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)))); }
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(); ...
@Test public void testGetStringValue() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(km.getStringValue(), is(equalTo("value"))); }
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(); @O...
@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(...
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...
@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)); }); }
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...
@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 = e...
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) { retur...
@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 KeyM...
QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl<T> implements QueryResultsIteratorWithMetadata<T> { @Override public ChaincodeShim.QueryResponseMetadata getMetadata() { return metadata; } QueryResultsIteratorWithMetadataImpl(final ChaincodeInvocationTask handler, final String channelId, final Stri...
@Test public void getMetadata() { final QueryResultsIteratorWithMetadataImpl<Integer> testIter = new QueryResultsIteratorWithMetadataImpl<>(null, "", "", prepareQueryResponse().toByteString(), queryResultBytesToKv); assertThat(testIter.getMetadata().getBookmark(), is("asdf")); assertThat(testIter.getMetadata().getFetch...
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 sta...
@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 nul...
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(...
@Test public void logger() { Logger.getLogger(LoggerTest.class); Logger.getLogger(LoggerTest.class.getName()); }
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(f...
@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 ...
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 (tls...
@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(); }
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 objectT...
@Test public void testValidateSimpleKeys() { CompositeKey.validateSimpleKeys("abc", "def", "ghi"); } @Test(expected = CompositeKeyFormatException.class) public void testValidateSimpleKeysException() throws Exception { CompositeKey.validateSimpleKeys("\u0000abc"); }
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(...
@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...
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(...
@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 "...
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 getInstance() { final ContextFactory f1 = ContextFactory.getInstance(); final ContextFactory f2 = ContextFactory.getInstance(); assertThat(f1, sameInstance(f2)); }
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 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(st...
Context { public ChaincodeStub getStub() { return this.stub; } Context(final ChaincodeStub stub); ChaincodeStub getStub(); ClientIdentity getClientIdentity(); }
@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())); }
Context { public ClientIdentity getClientIdentity() { return this.clientIdentity; } 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)); }
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 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"); ((Chaincod...
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 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"); ((ChaincodeStubNaiv...
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 t...
@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>");...
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 getR...
@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")); }
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(); Strin...
@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")); }
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 getRe...
@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")); }
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...
@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)); }
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")) {...
@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), ...
TypeSchema extends HashMap<String, Object> { public void validate(final JSONObject obj) { final JSONObject toValidate = new JSONObject(); toValidate.put("prop", obj); JSONObject schemaJSON; if (this.containsKey("schema")) { schemaJSON = new JSONObject((Map) this.get("schema")); } else { schemaJSON = new JSONObject(this...
@Test public void validate() { final TypeSchema ts = TypeSchema.typeConvert(org.hyperledger.fabric.contract.MyType.class); final DataTypeDefinition dtd = new DataTypeDefinitionImpl(org.hyperledger.fabric.contract.MyType.class); MetadataBuilder.addComponent(dtd); final JSONObject json = new JSONObject(); ts.validate(jso...
MetadataBuilder { public static String getMetadata() { return metadata().toString(); } private MetadataBuilder(); static void validate(); static void initialize(final RoutingRegistry registry, final TypeRegistry typeRegistry); static void addComponent(final DataTypeDefinition datatype); @SuppressWarnings("serial") sta...
@Test public void systemContract() { final SystemContract system = new SystemContract(); final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); system.getMetadata(new Context(stub)); }
JSONTransactionSerializer implements SerializerInterface { @Override public byte[] toBuffer(final Object value, final TypeSchema ts) { logger.debug(() -> "Schema to convert is " + ts); byte[] buffer = null; if (value != null) { final String type = ts.getType(); if (type != null) { switch (type) { case "array": final JS...
@Test public void toBuffer() { final TypeRegistry tr = TypeRegistry.getRegistry(); tr.addDataType(MyType.class); MetadataBuilder.addComponent(tr.getDataType("MyType")); final JSONTransactionSerializer serializer = new JSONTransactionSerializer(); byte[] bytes = serializer.toBuffer("hello world", TypeSchema.typeConvert(...
JSONTransactionSerializer implements SerializerInterface { @Override public Object fromBuffer(final byte[] buffer, final TypeSchema ts) { try { final String stringData = new String(buffer, StandardCharsets.UTF_8); Object value = null; value = convert(stringData, ts); return value; } catch (InstantiationException | Ille...
@Test public void fromBufferObject() { final byte[] buffer = "[{\"value\":\"hello\"},{\"value\":\"world\"}]".getBytes(StandardCharsets.UTF_8); final TypeRegistry tr = TypeRegistry.getRegistry(); tr.addDataType(MyType.class); MetadataBuilder.addComponent(tr.getDataType("MyType")); final JSONTransactionSerializer seriali...
CompositeKey { public String getObjectType() { return objectType; } 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 parseCompos...
@Test public void testGetObjectType() { final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno")); assertThat(key.getObjectType(), is(equalTo("abc"))); }
Logging { private static Level mapLevel(final String level) { if (level != null) { switch (level.toUpperCase().trim()) { case "ERROR": case "CRITICAL": return Level.SEVERE; case "WARNING": return Level.WARNING; case "INFO": return Level.INFO; case "NOTICE": return Level.CONFIG; case "DEBUG": return Level.FINEST; defaul...
@Test public void testMapLevel() { assertEquals("Error maps", Level.SEVERE, proxyMapLevel("ERROR")); assertEquals("Critical maps", Level.SEVERE, proxyMapLevel("critical")); assertEquals("Warn maps", Level.WARNING, proxyMapLevel("WARNING")); assertEquals("Info maps", Level.INFO, proxyMapLevel("INFO")); assertEquals("Con...
Logging { public static String formatError(final Throwable throwable) { if (throwable == null) { return null; } final StringWriter buffer = new StringWriter(); buffer.append(throwable.getMessage()).append(System.lineSeparator()); throwable.printStackTrace(new PrintWriter(buffer)); final Throwable cause = throwable.getC...
@Test public void testFormatError() { final Exception e1 = new Exception("Computer says no"); assertThat(Logging.formatError(e1), containsString("Computer says no")); final NullPointerException npe1 = new NullPointerException("Nothing here"); npe1.initCause(e1); assertThat(Logging.formatError(npe1), containsString("Com...
Logging { public static void setLogLevel(final String newLevel) { final Level l = mapLevel(newLevel); final LogManager logManager = LogManager.getLogManager(); final ArrayList<String> allLoggers = Collections.list(logManager.getLoggerNames()); allLoggers.add("org.hyperledger"); allLoggers.stream().filter(name -> name.s...
@Test public void testSetLogLevel() { final java.util.logging.Logger l = java.util.logging.Logger.getLogger("org.hyperledger.fabric.test"); final java.util.logging.Logger another = java.util.logging.Logger.getLogger("acme.wibble"); final Level anotherLevel = another.getLevel(); Logging.setLogLevel("debug"); assertThat(...
CompositeKey { public List<String> getAttributes() { return attributes; } 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 parse...
@Test public void testGetAttributes() { final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno")); assertThat(key.getObjectType(), is(equalTo("abc"))); assertThat(key.getAttributes(), hasSize(4)); assertThat(key.getAttributes(), contains("def", "ghi", "jkl", "mno")); }
CompositeKey { @Override public String toString() { return compositeKey; } 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 pars...
@Test public void testToString() { final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno")); assertThat(key.toString(), is(equalTo("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"))); }