method2testcases
stringlengths 118
6.63k
|
---|
### Question:
Elements implements Constraint { public Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ) { this.unions = unions; this.exclusion = exclusion; } Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); }### Answer:
@Test public void doTest() throws Exception { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); DefinedType type = factory.types().define( "MyInt", factory.types().builtin( "INTEGER" ), null ); module.validate(); ConstraintTemplate e = factory.constraints().elements( constraint, except ); boolean actual = ConstraintTestUtils.checkConstraint( e, factory.values().integer( 1 ), type, module.createScope() ); Assert.assertEquals( title + ": failed", expectedResult, actual ); } |
### Question:
ElementSetSpec implements Constraint { public ElementSetSpec( List<Constraint> unions ) { this.unions = new ArrayList<>( unions ); } ElementSetSpec( List<Constraint> unions ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); }### Answer:
@Test public void doTest() { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); DefinedType type = factory.types().define( "MyInt", factory.types().builtin( "INTEGER" ), null ); ConstraintTemplate specs = unions == null ? factory.constraints().elementSetSpec( exclusion ) : factory.constraints().elementSetSpec( unions ); boolean actual = ConstraintTestUtils.checkConstraint( specs, factory.values().integer( 1 ), type, module.createScope() ); Assert.assertEquals( title + ": failed", expectedResult, actual ); } |
### Question:
TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; }### Answer:
@Test public void testUTCParse() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmss" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); }
@Test public void testUTCParseMinutes() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmm" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); }
@Test public void testUTCParseCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.ofHours( 4 ) ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmssZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); }
@Test public void testUTCParseMinutesCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.ofHours( 4 ) ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } |
### Question:
NullBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) { assert context.getType().getFamily() == Family.NULL; assert context.getLength() == 0; return NullValue.INSTANCE; } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_length() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.NULL.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new NullBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 1, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new NullBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 0, false ) ); fail( "Must fail" ); } } |
### Question:
TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; }### Answer:
@Test public void testFormatInstant000() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ).withNano( 0 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "200001010100Z", result ); }
@Test public void testFormatInstant00() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ) .withNano( 880000000 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "20000101010000.88Z", result ); }
@Test public void testFormatInstant0() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ) .withNano( 800000000 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "20000101010000.8Z", result ); } |
### Question:
NRxUtils { public static String toCanonicalNR3( String value ) { if( "-Infinity".equals( value ) || "Infinity".equals( value ) || "NaN".equals( value ) ) return value; if( !FORMAT_PATTERN.matcher( value ).matches() ) throw new IllegalArgumentException(); value = value.toUpperCase(); String mantisStr; String exponentStr; int expIndex = value.indexOf( 'E' ); if( expIndex == -1 ) { mantisStr = value; exponentStr = "0"; } else { mantisStr = value.substring( 0, expIndex ).trim(); exponentStr = value.substring( expIndex + 1 ).trim(); } int scale; String actualMantis; int dotIndex = mantisStr.indexOf( '.' ); if( dotIndex == -1 ) { scale = 0; actualMantis = mantisStr; } else { scale = mantisStr.length() - dotIndex - 1; String fracture = mantisStr.substring( dotIndex + 1 ); if( isAllZeros( fracture ) ) { scale -= fracture.length(); fracture = ""; } actualMantis = mantisStr.substring( 0, dotIndex ) + fracture; } return formatInt( actualMantis ) + ".E" + formatExponent( scale, exponentStr ); } private NRxUtils(); static String toCanonicalNR3( String value ); }### Answer:
@Test public void testValues() throws Exception { assertEquals( "Not equal", "1.E-1", NRxUtils.toCanonicalNR3( "0.01E1" ) ); assertEquals( "Not equal", "+0.E1", NRxUtils.toCanonicalNR3( "0.00000E1" ) ); assertEquals( "Not equal", "12312.E+0", NRxUtils.toCanonicalNR3( "12312" ) ); assertEquals( "Not equal", "12312123121231212312123121212.E-1231212312123121231212316", NRxUtils.toCanonicalNR3( "1231212312123121231212312.1212E-1231212312123121231212312" ) ); } |
### Question:
RefUtils { public static void assertTypeRef( String name ) { if( !isTypeRef( name ) ) throw new IllegalArgumentException( "Not a type reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void testNotTypeRef() { RefUtils.assertTypeRef( "a" ); } |
### Question:
DefaultBerReader extends AbstractBerReader { @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override public byte read() throws IOException { int read = is.read(); if( read != -1 ) position++; return (byte)read; } DefaultBerReader( InputStream is, ValueFactory valueFactory ); @Override int position(); @Override void skip( int amount ); @Override void skipToEoc(); @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override byte read(); @Override int read( byte[] buffer ); @Override void close(); }### Answer:
@Test public void writeHugeReal() throws Exception { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); Scope scope = module.createScope(); ConstraintTemplate constraintTemplate = factory.constraints().valueRange( new RealValueFloat( 0.0f ), false, null, false ); Type tagged = factory.types().constrained( constraintTemplate, UniversalType.REAL.ref() ); Type defined = factory.types().define( "MyReal", tagged, null ); module.validate(); Value expected = new RealValueBig( new BigDecimal( BigInteger.valueOf( 34645 ).pow( 16663 ) ) ); byte[] result = InputUtils.writeValue( scope, defined, expected ); try( ByteArrayInputStream is = new ByteArrayInputStream( result ); AbstractBerReader reader = new DefaultBerReader( is, new CoreValueFactory() ) ) { Value value = reader.read( scope, defined ); Assert.assertEquals( "Values are not equal", expected, value ); } }
@Test public void testHugeTagNumber() throws Exception { TypeFactory factory = new CoreTypeFactory(); Module module = factory.dummyModule(); Scope scope = module.createScope(); Type tagged = factory.tagged( TagEncoding.application( 2048 ), UniversalType.INTEGER.ref() ); Type defined = factory.define( "MyTagged", tagged, null ); module.validate(); Value expected = new IntegerValueInt( 0 ); byte[] result = InputUtils.writeValue( scope, defined, expected ); try( ByteArrayInputStream is = new ByteArrayInputStream( result ); AbstractBerReader reader = new DefaultBerReader( is, new CoreValueFactory() ) ) { Value value = reader.read( scope, defined ); Assert.assertEquals( "Values are not equal", expected, value ); } } |
### Question:
RefUtils { public static void assertValueRef( String name ) { if( !isValueRef( name ) ) throw new IllegalArgumentException( "Not a value reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void testNotValueRef() { RefUtils.assertValueRef( "A" ); } |
### Question:
RefUtils { public static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ) throws ResolutionException { if( component.getDefaultValue() == null ) return false; resolve = toBasicValue( scope, resolve ); Value value = toBasicValue( scope, component.getDefaultValue() ); return resolve.isEqualTo( value ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); }### Answer:
@Test public void testSameAsDefault() throws Exception { MyIntegerValue value = new MyIntegerValue(); assertTrue( "Must be true", RefUtils.isSameAsDefaultValue( new MyScope(), new MyAbstractComponentType( value ), value ) ); } |
### Question:
HexUtils { @SuppressWarnings( "MagicNumber" ) public static String toHexString( byte[] array ) { if( ArrayUtils.isEmpty( array ) ) return ""; StringBuilder sb = new StringBuilder(); for( byte value : array ) { if( ( value & 0xF0 ) == 0 ) sb.append( '0' ); sb.append( Integer.toHexString( value & 0xFF ).toUpperCase() ); } return sb.toString(); } private HexUtils(); @SuppressWarnings( "MagicNumber" ) static String toHexString( byte[] array ); }### Answer:
@Test public void testConversion() throws Exception { assertEquals( "Is not equal", "0A", HexUtils.toHexString( new byte[]{0x0A} ) ); assertEquals( "Is not equal", "0A0A", HexUtils.toHexString( new byte[]{0x0A, 0x0A} ) ); assertEquals( "Is not equal", "", HexUtils.toHexString( new byte[]{} ) ); } |
### Question:
CollectionUtils { @NotNull public static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ) { Collection<Long> values = new HashSet<>(); Long maxValue = 0L; for( Ref<Value> valueRef : valueList ) { NamedValue value = (NamedValue)valueRef; if( value.getReferenceKind() != Kind.INTEGER || !value.toIntegerValue().isLong() ) throw new IllegalStateException(); Long longValue = value.toIntegerValue().asLong(); values.add( longValue ); maxValue = Math.max( maxValue, longValue ); } if( desiredSize > -1 ) { if( maxValue > ( desiredSize - 1 ) ) throw new IllegalArgumentException( "Unable to truncate data. Desired size is smaller than expected: current = " + ( maxValue + 1 ) + " desired = " + desiredSize ); maxValue = (long)desiredSize - 1; } StringBuilder sb = new StringBuilder(); sb.append( '\'' ); for( long value = 0; value <= maxValue; value++ ) sb.append( values.contains( value ) ? '1' : '0' ); sb.append( "'B" ); return sb.toString(); } private CollectionUtils(); @NotNull static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ); }### Answer:
@Test public void testConversion() throws Exception { IntegerValue value = new MyIntegerValue(); MyScope scope = new MyScope(); MyNamedValue namedValue = new MyNamedValue( (IntegerValue)RefUtils.toBasicValue( scope, value ) ); String result = CollectionUtils.convertToBString( Collections.singletonList( namedValue ), 4 ); assertEquals( "Is not equals", "'0100'B", result ); assertEquals( "Must be equal", value, RefUtils.toBasicValue( scope, namedValue ) ); } |
### Question:
TemplateParameter implements Comparable<TemplateParameter> { public String getName() { if( reference instanceof TypeNameRef ) return ( (TypeNameRef)reference ).getName(); if( reference instanceof ValueNameRef ) return ( (ValueNameRef)reference ).getName(); throw new IllegalStateException(); } TemplateParameter( int index, @NotNull Ref<?> reference, @Nullable Ref<Type> governor ); int getIndex(); String getName(); @SuppressWarnings( "unchecked" ) Ref<T> getReference(); @Nullable Ref<Type> getGovernor(); boolean isTypeRef(); boolean isValueRef(); @SuppressWarnings( "unchecked" ) @Override boolean equals( Object obj ); @Override int hashCode(); @Override String toString(); @Override int compareTo( @NotNull TemplateParameter o ); }### Answer:
@Test( expected = IllegalStateException.class ) public void testIllegalRef() throws Exception { TemplateParameter parameter = new TemplateParameter( 0, scope -> { throw new UnsupportedOperationException(); }, null ); parameter.getName(); fail( "Must fail" ); } |
### Question:
Template { public Template() { this( false ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); }### Answer:
@Test public void testTemplate() throws Exception { Template template = new Template(); assertEquals( "Parameter count must be 0", 0, template.getParameterCount() ); template.addParameter( new TemplateParameter( 0, new TypeNameRef( "A" ), null ) ); assertEquals( "Parameter count must be 1", 1, template.getParameterCount() ); assertNotNull( "Must not be null", template.getParameter( 0 ) ); assertNotNull( "Must not be null", template.getParameter( "A" ) ); assertFalse( "Must not be instance", template.isInstance() ); } |
### Question:
Template { @Nullable public TemplateParameter getParameter( @NotNull String name ) { return parameterMap.get( name ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void testIllegalIndexGet() throws Exception { Template template = new Template(); template.getParameter( 1 ); fail( "Must fail" ); } |
### Question:
EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); @Override int getPriority(); @Override boolean isSupportedFor( Type type ); @SuppressWarnings( "unchecked" ) @Override TypeMapper mapType( Type type, TypeMetadata metadata ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void testDuplicateFail() throws Exception { mapperFactory.mapType( Values.class, null ); fail( "Must fail" ); }
@Test( expected = IllegalArgumentException.class ) public void testUnsupportedType() throws Exception { mapperFactory.mapType( Integer.class, null ); fail( "Must fail!" ); }
@Test( expected = IllegalStateException.class ) public void testNoEnumConstantsFail() throws Exception { mapperFactory.mapType( ValuesEmpty.class, null ); fail( "Must fail" ); }
@Test( expected = IllegalStateException.class ) public void testIllegalIndexes() throws Exception { mapperFactory.mapType( IllegalEnum.class, null ); fail( "Must fail" ); }
@Test( expected = IllegalStateException.class ) public void testIllegalIndexes2() throws Exception { mapperFactory.mapType( IllegalEnum2.class, null ); fail( "Must fail" ); } |
### Question:
Introspector { @NotNull public JavaType introspect( Type type ) { if( typeMap.containsKey( type.getTypeName() ) ) return typeMap.get( type.getTypeName() ); if( type instanceof Class<?> ) return forClass( (Class<?>)type ); if( type instanceof ParameterizedType ) return forParameterized( (ParameterizedType)type ); if( type instanceof TypeVariable<?> ) { JavaType javaType = new JavaType( type ); typeMap.put( type.getTypeName(), javaType ); return javaType; } throw new UnsupportedOperationException(); } @NotNull JavaType introspect( Type type ); }### Answer:
@Test public void testIntrospection() throws Exception { Introspector introspector = new Introspector(); JavaType type = introspector.introspect( Element.class ); int k = 0; } |
### Question:
RealTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( isFloat() && isAssignableToFloat( value ) ) return factory.real( (Float)value ); if( isDouble() && isAssignableToDouble( value ) ) return factory.real( (Double)value ); if( isBigDecimal() && Objects.equals( value.getClass(), BigDecimal.class ) ) return factory.real( (BigDecimal)value ); throw new IllegalArgumentException( "Unable to convert value: " + value ); } RealTypeMapper( Class<?> realClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new RealTypeMapper( double.class, REAL ); mapper.toAsn1( FACTORY, true ); fail( "Must fail" ); } |
### Question:
RealTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.REAL ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); RealValue rv = value.toRealValue(); if( isFloat() ) return rv.asFloat(); if( isDouble() ) return rv.asDouble(); if( isBigDecimal() ) return rv.asBigDecimal(); throw new UnsupportedOperationException(); } RealTypeMapper( Class<?> realClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new RealTypeMapper( double.class, REAL ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
### Question:
StringTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !javaType.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); return factory.cString( (String)value ); } StringTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new StringTypeMapper( String.class, UTF8_STRING ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); } |
### Question:
StringTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.C_STRING ) throw new IllegalArgumentException( "Unable to convert value of kind: " + value.getKind() ); return value.toStringValue().asString(); } StringTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new StringTypeMapper( String.class, UTF8_STRING ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
### Question:
IntegerTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( isByte() && isAssignableToByte( value ) ) return factory.integer( (Byte)value ); if( isShort() && isAssignableToShort( value ) ) return factory.integer( (Short)value ); if( isInteger() && isAssignableToInt( value ) ) return factory.integer( (Integer)value ); if( isLong() && isAssignableToLong( value ) ) return factory.integer( (Long)value ); if( isBigInteger() && Objects.equals( value.getClass(), BigInteger.class ) ) return factory.integer( (BigInteger)value ); throw new IllegalArgumentException( "Unable to convert value: " + value ); } IntegerTypeMapper( Class<?> integerClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new IntegerTypeMapper( Long.class, INTEGER ); mapper.toAsn1( FACTORY, true ); fail( "Must fail" ); } |
### Question:
IntegerTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.INTEGER ) throw new IllegalArgumentException( "Unable to convert to integer value of kind: " + value.getKind() ); IntegerValue iv = value.toIntegerValue(); if( isByte() ) return (byte)iv.asInt(); if( isShort() ) return (short)iv.asInt(); if( isInteger() ) return iv.asInt(); if( isLong() ) return iv.asLong(); if( isBigInteger() ) return iv.asBigInteger(); throw new UnsupportedOperationException(); } IntegerTypeMapper( Class<?> integerClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new IntegerTypeMapper( Long.class, INTEGER ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
### Question:
ByteArrayTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !byte[].class.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); byte[] array = (byte[])value; return factory.byteArrayValue( array.length * 8, array ); } ByteArrayTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new ByteArrayTypeMapper( byte[].class, OCTET_STRING ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); } |
### Question:
BitStringBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.BIT_STRING; assert !context.getTag().isConstructed(); if( context.getLength() == 0 ) return context.getValueFactory().emptyByteArray(); byte unusedBits = context.read(); if( unusedBits < 0 || unusedBits > 7 ) throw new IllegalValueException( "Unused bits must be in range: [0,7]" ); if( context.getLength() == -1 ) return OctetStringBerDecoder.readByteArrayValueIndefinite( context.getReader(), unusedBits ); return OctetStringBerDecoder.readByteArrayValue( context.getReader(), context.getLength() - 1, unusedBits ); } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new BitStringBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } |
### Question:
ByteArrayTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.BYTE_ARRAY ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); return value.toByteArrayValue().asByteArray(); } ByteArrayTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new ByteArrayTypeMapper( byte[].class, OCTET_STRING ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
### Question:
DateTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !javaType.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); if( isDate() ) return factory.timeValue( ( (Date)value ).toInstant() ); if( isInstant() ) return factory.timeValue( (Instant)value ); throw new UnsupportedOperationException(); } DateTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new DateTypeMapper( Instant.class, G_TIME ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); } |
### Question:
DateTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.TIME ) throw new IllegalArgumentException( "Unable to convert values of kind: " + value.getKind() ); Instant instant = value.toDateValue().asInstant(); if( isInstant() ) return instant; if( isDate() ) return Date.from( instant ); throw new UnsupportedOperationException(); } DateTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new DateTypeMapper( Instant.class, G_TIME ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
### Question:
BooleanTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !isBooleanClass( value ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); if( Boolean.TRUE.equals( value ) ) return BooleanValue.TRUE; if( Boolean.FALSE.equals( value ) ) return BooleanValue.FALSE; throw new UnsupportedOperationException(); } BooleanTypeMapper( Class<?> booleanClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test public void toAsn1() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); assertEquals( "Not equals", BooleanValue.TRUE, mapper.toAsn1( FACTORY, true ) ); assertEquals( "Not equals", BooleanValue.FALSE, mapper.toAsn1( FACTORY, false ) ); }
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); } |
### Question:
BooleanTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.BOOLEAN ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); if( Objects.equals( value, BooleanValue.TRUE ) ) return Boolean.TRUE; if( Objects.equals( value, BooleanValue.FALSE ) ) return Boolean.FALSE; throw new UnsupportedOperationException(); } BooleanTypeMapper( Class<?> booleanClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }### Answer:
@Test public void toJava() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); assertEquals( "Not equals", Boolean.TRUE, mapper.toJava( BooleanValue.TRUE ) ); assertEquals( "Not equals", Boolean.FALSE, mapper.toJava( BooleanValue.FALSE ) ); }
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); mapper.toJava( FACTORY.integer( 1 ) ); fail( "Must fail" ); } |
### Question:
GeneralizedTimeBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.GENERALIZED_TIME; assert context.getValue().getKind() == Kind.TIME; Instant instant = context.getValue().toDateValue().asInstant(); boolean optimize = context.getRules() != BerRules.DER; String content = TimeUtils.formatInstant( instant, TimeUtils.GENERALIZED_TIME_FORMAT, optimize ); byte[] bytes = content.getBytes( TimeUtils.CHARSET ); context.writeHeader( TAG, bytes.length ); context.write( bytes ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testWrite_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.GENERALIZED_TIME.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseGeneralizedTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.DER ); new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 15 ); verify( writer ).write( new byte[]{0x32, 0x30, 0x31, 0x37, 0x30, 0x36, 0x30, 0x31, 0x31, 0x31, 0x35, 0x37, 0x30, 0x30, 0x5A} ); verifyNoMoreInteractions( writer ); } }
@Test public void testWrite_Ber() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.GENERALIZED_TIME.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseGeneralizedTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.BER ); new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 13 ); verify( writer ).write( new byte[]{0x32, 0x30, 0x31, 0x37, 0x30, 0x36, 0x30, 0x31, 0x31, 0x31, 0x35, 0x37, 0x5A} ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseGeneralizedTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.GENERALIZED_TIME.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
StringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.RESTRICTED_STRING; assert context.getValue().getKind() == Kind.C_STRING; Type type = context.getType(); while( !( type instanceof StringType ) ) { assert type != null; type = type.getSibling(); } Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); byte[] bytes = context.getValue().toStringValue().asString().getBytes( ( (StringType)type ).getCharset() ); context.writeHeader( tag, bytes.length ); context.write( bytes ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testEncode_0() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTF8_STRING.ref().resolve( scope ); Value value = new StringValueImpl( "A" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new StringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( new byte[]{65} ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new StringValueImpl( "Value" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new StringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTF8_STRING.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new StringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
ObjectIDBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.OID; assert context.getLength() > 0; List<Ref<Value>> list = new ArrayList<>(); int length = context.getLength(); while( length > 0 ) length = readObjectIDItem( context.getReader(), length, list ); ObjectIdentifierValue objectIdentifierValue = context.getValueFactory().objectIdentifier( list ); return context.getType().optimize( context.getScope(), objectIdentifierValue ); } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new ObjectIDBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } |
### Question:
BooleanBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException { assert context.getType().getFamily() == Family.BOOLEAN; assert context.getLength() == 1; byte content = context.read(); return content == BerUtils.BOOLEAN_FALSE ? BooleanValue.FALSE : BooleanValue.TRUE; } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new BooleanBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 1, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testDecode_fail_length() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new BooleanBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 2, false ) ); fail( "Must fail" ); } } |
### Question:
BooleanBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.BOOLEAN; assert context.getValue().getKind() == Kind.BOOLEAN; context.writeHeader( TAG, 1 ); boolean value = context.getValue().toBooleanValue().asBoolean(); context.write( value ? BerUtils.BOOLEAN_TRUE : BerUtils.BOOLEAN_FALSE ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testEncode_true() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( BerUtils.BOOLEAN_TRUE ); verifyNoMoreInteractions( writer ); } }
@Test public void testEncode_false() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); Value value = BooleanValue.FALSE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( BerUtils.BOOLEAN_FALSE ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); Value value = NullValue.INSTANCE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
OctetStringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.OCTET_STRING; assert context.getValue().getKind() == Kind.BYTE_ARRAY; byte[] bytes = context.getValue().toByteArrayValue().asByteArray(); int length = bytes == null ? 0 : bytes.length; context.writeHeader( TAG, length ); context.write( bytes ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testEncode_Empty() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OCTET_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromHexString( "''H" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 0 ); verifyNoMoreInteractions( writer ); } }
@Test public void testEncode_AF() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OCTET_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromHexString( "'AF'H" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( new byte[]{(byte)0xAF} ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromHexString( "'AF'H" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OCTET_STRING.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
OctetStringBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.OCTET_STRING; assert !context.getTag().isConstructed(); if( context.getLength() == -1 ) return readByteArrayValueIndefinite( context.getReader(), 0 ); if( context.getLength() == 0 ) return context.getValueFactory().emptyByteArray(); return readByteArrayValue( context.getReader(), context.getLength(), 0 ); } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new OctetStringBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } |
### Question:
RealBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException { assert context.getType().getFamily() == Family.REAL; assert !context.getTag().isConstructed(); if( context.getLength() == 0 ) return context.getValueFactory().rZero(); byte first = context.read(); if( first == 0 ) return context.getValueFactory().rZero(); if( ( first & BerUtils.BYTE_SIGN_MASK ) != 0 ) return readBinary( context.getReader(), first, context.getLength() ); switch( first ) { case BerUtils.REAL_ISO_6093_NR1: case BerUtils.REAL_ISO_6093_NR2: case BerUtils.REAL_ISO_6093_NR3: return context.getValueFactory().real( readString( context.getReader(), context.getLength() - 1 ) ); case BerUtils.REAL_NEGATIVE_INF: return context.getValueFactory().rNegativeInfinity(); case BerUtils.REAL_POSITIVE_INF: return context.getValueFactory().rPositiveInfinity(); case BerUtils.REAL_NAN: return context.getValueFactory().rNan(); case BerUtils.REAL_MINUS_ZERO: return context.getValueFactory().rNegativeZero(); default: throw new IllegalStateException( String.format( "Illegal real configuration byte: %02X", first ) ); } } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new RealBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } |
### Question:
IntegerBerEncoder implements BerEncoder { static void writeLong( @NotNull AbstractBerWriter os, long value, @Nullable Tag tag, boolean writeHeader ) throws IOException { if( tag == null && writeHeader ) throw new IOException( "Unable to write header: tag is unavailable." ); int size = calculateByteCount( value ); if( writeHeader ) os.writeHeader( tag, size ); for( int i = size - 1; i >= 0; i-- ) os.write( getByteByIndex( value, i ) ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testWriteLong_0() throws Exception { try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { IntegerBerEncoder.writeLong( writer, 0L, null, false ); verify( writer ).write( 0 ); verifyNoMoreInteractions( writer ); } }
@Test public void testWriteLong_minus_1() throws Exception { try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { IntegerBerEncoder.writeLong( writer, -1L, null, false ); verify( writer ).write( -1 ); verifyNoMoreInteractions( writer ); } }
@Test public void testWriteLong_256() throws Exception { try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { IntegerBerEncoder.writeLong( writer, 256L, null, false ); verify( writer ).write( 1 ); verify( writer ).write( 0 ); verifyNoMoreInteractions( writer ); } }
@Test public void testWriteLong_300000() throws Exception { try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { IntegerBerEncoder.writeLong( writer, 300000L, null, false ); verify( writer ).write( (byte)0x04 ); verify( writer ).write( (byte)0x93 ); verify( writer ).write( (byte)0xE0 ); verifyNoMoreInteractions( writer ); } }
@Test( expected = IOException.class ) public void testWriteLong_fail() throws Exception { try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { IntegerBerEncoder.writeLong( writer, 0L, null, true ); fail( "This method must fail." ); } } |
### Question:
IntegerBerEncoder implements BerEncoder { static byte[] toByteArray( long value ) { int size = calculateByteCount( value ); byte[] result = new byte[size]; for( int i = size - 1, position = 0; i >= 0; i--, position++ ) result[position] = getByteByIndex( value, i ); return result; } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testToByteArray_0() throws Exception { byte[] array = IntegerBerEncoder.toByteArray( 0L ); Assert.assertEquals( "Illegal array size", 1, array.length ); Assert.assertArrayEquals( "Arrays are different", new byte[]{0}, array ); }
@Test public void testToByteArray_minus_1() throws Exception { byte[] array = IntegerBerEncoder.toByteArray( -1L ); Assert.assertEquals( "Illegal array size", 1, array.length ); Assert.assertArrayEquals( "Arrays are different", new byte[]{-1}, array ); }
@Test public void testToByteArray_256() throws Exception { byte[] array = IntegerBerEncoder.toByteArray( 256L ); Assert.assertEquals( "Illegal array size", 2, array.length ); Assert.assertArrayEquals( "Arrays are different", new byte[]{1, 0}, array ); }
@Test public void testToByteArray_300000() throws Exception { byte[] array = IntegerBerEncoder.toByteArray( 300000L ); Assert.assertEquals( "Illegal array size", 3, array.length ); Assert.assertArrayEquals( "Arrays are different", new byte[]{0x04, (byte)0x93, (byte)0xE0}, array ); } |
### Question:
IntegerBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException { assert context.getType().getFamily() == Family.INTEGER; assert context.getLength() >= 0; return readInteger( context.getReader(), context.getLength() ); } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.REAL.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new IntegerBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } |
### Question:
IntegerBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.INTEGER; assert context.getValue().getKind() == Kind.INTEGER; writeLong( context.getWriter(), context.getValue().toIntegerValue().asLong(), TAG, context.isWriteHeader() ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testEncode_0() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new IntegerValueInt( 0 ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new IntegerBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( 0 ); verifyNoMoreInteractions( writer ); } }
@Test public void testEncode_minus_1() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new IntegerValueInt( -1 ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new IntegerBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( -1 ); verifyNoMoreInteractions( writer ); } }
@Test public void testEncode_256() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new IntegerValueInt( 256 ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new IntegerBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 2 ); verify( writer ).write( 1 ); verify( writer ).write( 0 ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.REAL.ref().resolve( scope ); Value value = new IntegerValueInt( 256 ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new IntegerBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new RealValueFloat( 0.0f ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new IntegerBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); fail( "Must fail" ); } } |
### Question:
ObjectIDBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.OID; assert context.getValue().getKind() == Kind.OID; if( !context.isWriteHeader() ) writeObjectIDImpl( context.getWriter(), context.getValue().toObjectIdentifierValue() ); else if( context.isBufferingAvailable() ) { context.startBuffer( -1 ); writeObjectIDImpl( context.getWriter(), context.getValue().toObjectIdentifierValue() ); context.stopBuffer( TAG ); } else throw new Asn1Exception( "Buffering is required for ObjectIdentifier" ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testEncode_NoHeader() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OBJECT_IDENTIFIER.ref().resolve( scope ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new ObjectIDBerEncoder().encode( new WriterContext( writer, scope, type, OPTIMIZED_OID_VALUE, false ) ); verify( writer, times( 2 ) ).write( 0 ); verify( writer ).write( 1 ); verify( writer ).write( (byte)0x82 ); verifyNoMoreInteractions( writer ); } }
@Test public void testEncode_Buffered() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OBJECT_IDENTIFIER.ref().resolve( scope ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.isBufferingAvailable() ).thenReturn( true ); new ObjectIDBerEncoder().encode( new WriterContext( writer, scope, type, OPTIMIZED_OID_VALUE, true ) ); verify( writer ).isBufferingAvailable(); verify( writer ).startBuffer( -1 ); verify( writer, times( 2 ) ).write( 0 ); verify( writer ).write( 1 ); verify( writer ).write( (byte)0x82 ); verify( writer ).stopBuffer( TAG ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new ObjectIDBerEncoder().encode( new WriterContext( writer, scope, type, OPTIMIZED_OID_VALUE, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OBJECT_IDENTIFIER.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new ObjectIDBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
StringBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.RESTRICTED_STRING; Type type = context.getType(); while( !( type instanceof StringType ) ) { assert type != null; type = type.getSibling(); } byte[] content = BerDecoderUtils.readString( context.getReader(), context.getLength() ); return context.getValueFactory().cString( new String( content, ( (StringType)type ).getCharset() ) ); } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test public void testDecode() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTF8_STRING.ref().resolve( scope ); Value value = new StringValueImpl( "Example" ); byte[] result = InputUtils.writeValue( scope, type, value ); int totalWritten = result.length - 2; byte[] noHeader = new byte[totalWritten]; System.arraycopy( result, 2, noHeader, 0, noHeader.length ); try( AbstractBerReader reader = mock( AbstractBerReader.class ) ) { ValueFactory factory = mock( ValueFactory.class ); when( reader.getValueFactory() ).thenReturn( factory ); when( reader.read( any() ) ).then( invocationOnMock -> { System.arraycopy( result, 2, invocationOnMock.getArguments()[0], 0, totalWritten ); return totalWritten; } ); Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new StringBerDecoder().decode( new ReaderContext( reader, scope, type, tag, totalWritten, false ) ); verify( reader ).getValueFactory(); verify( reader ).read( any( byte[].class ) ); verifyNoMoreInteractions( reader ); } }
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new StringBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } |
### Question:
NullBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.NULL; assert context.getValue().getKind() == Kind.NULL; context.writeHeader( TAG, 0 ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testEncode_value_no_header() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.NULL.ref().resolve( scope ); Value value = NullValue.INSTANCE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new NullBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); verifyNoMoreInteractions( writer ); } }
@Test public void testEncode_value_with_header() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.NULL.ref().resolve( scope ); Value value = NullValue.INSTANCE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new NullBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 0 ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = NullValue.INSTANCE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new NullBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.NULL.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new NullBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
UTCTimeBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.UTC_TIME; assert context.getValue().getKind() == Kind.TIME; String content = TimeUtils.formatInstant( context.getValue().toDateValue().asInstant(), TimeUtils.UTC_TIME_FORMAT, context.getRules() != BerRules.DER ); byte[] bytes = content.getBytes( TimeUtils.CHARSET ); context.writeHeader( TAG, bytes.length ); context.write( bytes ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testWrite_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTC_TIME.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseUTCTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.DER ); new UTCTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 13 ); verify( writer ).write( new byte[]{0x31, 0x37, 0x30, 0x36, 0x30, 0x31, 0x31, 0x31, 0x35, 0x37, 0x30, 0x30, 0x5A} ); verifyNoMoreInteractions( writer ); } }
@Test public void testWrite_Ber() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTC_TIME.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseUTCTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.BER ); new UTCTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 11 ); verify( writer ).write( new byte[]{0x31, 0x37, 0x30, 0x36, 0x30, 0x31, 0x31, 0x31, 0x35, 0x37, 0x5A} ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseUTCTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new UTCTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTC_TIME.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new UTCTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
EnumeratedBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.ENUMERATED; assert context.getValue().getKind() == Kind.NAME && context.getValue().toNamedValue().getReferenceKind() == Kind.INTEGER; IntegerBerEncoder.writeLong( context.getWriter(), context.getValue().toIntegerValue().asLong(), TAG, context.isWriteHeader() ); } @Override void encode( @NotNull WriterContext context ); }### Answer:
@Test public void testEncode_0() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Enumerated type = new EnumeratedType(); type.addItem( ItemKind.PRIMARY, "a", new IntegerValueInt( 0 ) ); type.validate( scope ); Value value = type.optimize( scope, new IntegerValueInt( 0 ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new EnumeratedBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( 0 ); verifyNoMoreInteractions( writer ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new NamedValueImpl( "abc", new IntegerValueInt( 0 ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new EnumeratedBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
@Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Enumerated type = new EnumeratedType(); type.addItem( ItemKind.PRIMARY, "a", new IntegerValueInt( 0 ) ); type.validate( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new EnumeratedBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } |
### Question:
GroupSyntaxObject implements SyntaxObject { @Override public String getText() { throw new UnsupportedOperationException(); } @Override Kind getKind(); @Override String getText(); void addObject( SyntaxObject object ); List<SyntaxObject> getObjects(); }### Answer:
@Test( expected = UnsupportedOperationException.class ) public void testGetTextFail() { new GroupSyntaxObject().getText(); Assert.fail( "Exception was not thrown" ); } |
### Question:
GroupSyntaxObject implements SyntaxObject { public void addObject( SyntaxObject object ) { objects.add( object ); } @Override Kind getKind(); @Override String getText(); void addObject( SyntaxObject object ); List<SyntaxObject> getObjects(); }### Answer:
@Test public void testAddObject() { GroupSyntaxObject group = new GroupSyntaxObject(); Assert.assertEquals( "Kind is not GROUP", Kind.GROUP, group.getKind() ); Assert.assertTrue( "Collection is not empty", group.getObjects().isEmpty() ); group.addObject( new SimpleSyntaxObject( Kind.KEYWORD, "VALUE" ) ); Assert.assertEquals( "Collection is not empty", 1, group.getObjects().size() ); } |
### Question:
FileQueueService { public QueueFile getQueueFile() { return this.queueFile; } @Autowired FileQueueService(@Value("${modum.tokenapp.email.queue-file-path}") String queueFilePath,
@Autowired ObjectMapper objectMapper); FileQueueService(String queueFilePath); FileQueueService(); QueueFile getQueueFile(); ObjectMapper getObjectMapper(); synchronized void addConfirmationEmail(Investor investor, URI confirmationEmaiLink); synchronized void addSummaryEmail(Investor investor); synchronized Optional<Email> peekEmail(); synchronized void addEmail(Email email); }### Answer:
@Test public void testFileQueue() throws IOException { FileQueueService fileQueueService = new FileQueueService(getTempFilePath()); fileQueueService.getQueueFile().add("test".getBytes()); assertThat(fileQueueService.getQueueFile().peek(), is("test".getBytes())); }
@Test public void testFileQueueRecovering() throws IOException { String tempFile = getTempFilePath(); FileQueueService fileQueueService1 = new FileQueueService(tempFile); fileQueueService1.getQueueFile().add("test".getBytes()); FileQueueService fileQueueService2 = new FileQueueService(tempFile); assertThat(fileQueueService2.getQueueFile().peek(), is("test".getBytes())); } |
### Question:
SendEmailTask { public SendEmailTask() { } SendEmailTask(); @Scheduled(initialDelay = 10000, fixedRateString = "${modum.tokenapp.email.send-email-interval}") void sendEmail(); }### Answer:
@Test public void testSendEmailTask() throws IOException, URISyntaxException { FileQueueService fileQueueService = new FileQueueService(getTempFilePath(), objectMapper); fileQueueService.addConfirmationEmail(new Investor().setEmail(INVESTOR_EMAIL), new URI(CONFIRMATION_EMAIL_URI)); Email email = fileQueueService.peekEmail().get(); assertThat(email.getInvestor().getEmail(), is(INVESTOR_EMAIL)); assertThat(email.getConfirmationEmaiLink().toASCIIString(), is(CONFIRMATION_EMAIL_URI)); } |
### Question:
Etherscan { public BigInteger getBalance(String address) throws IOException { String s = "https: "?module=account" + "&action=balance" + "&address=" + address + "&tag=latest" + "&apikey="+apiKey; HttpHeaders headers = new HttpHeaders(); headers.set("User-Agent", options.getUserAgent()); ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); ObjectMapper objectMapper = new ObjectMapper(); ReturnSingleValue retVal = objectMapper.readValue(res.getBody(), ReturnSingleValue.class); return new BigInteger(retVal.result); } BigInteger getBalance(String address); List<Triple<Date,Long,Long>> getTxEth(String address); BigInteger get20Balances(String... contract); BigInteger get20Balances(List<String> contract); long getCurrentBlockNr(); BigInteger getBalances(List<String> contract); }### Answer:
@Test public void testConnect1() throws IOException { String balance = etherscan.getBalance("0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae").toString(); System.out.println("balance: "+balance); } |
### Question:
Etherscan { public BigInteger get20Balances(String... contract) throws IOException { return get20Balances(Arrays.asList(contract)); } BigInteger getBalance(String address); List<Triple<Date,Long,Long>> getTxEth(String address); BigInteger get20Balances(String... contract); BigInteger get20Balances(List<String> contract); long getCurrentBlockNr(); BigInteger getBalances(List<String> contract); }### Answer:
@Test public void testConnect2() throws IOException { String balance = etherscan.get20Balances("0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae", "0x25d96310cd6694d88b9c6803be09511597c0a630").toString(); System.out.println("balance: "+balance); } |
### Question:
Etherscan { public long getCurrentBlockNr() throws IOException { String s = "https: "?module=proxy" + "&action=eth_blockNumber" + "&apikey="+apiKey; HttpHeaders headers = new HttpHeaders(); headers.set("User-Agent", options.getUserAgent()); ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); ObjectMapper objectMapper = new ObjectMapper(); ReturnBlock retVal = objectMapper.readValue(res.getBody(), ReturnBlock.class); return Long.parseLong(retVal.result.substring(2), 16); } BigInteger getBalance(String address); List<Triple<Date,Long,Long>> getTxEth(String address); BigInteger get20Balances(String... contract); BigInteger get20Balances(List<String> contract); long getCurrentBlockNr(); BigInteger getBalances(List<String> contract); }### Answer:
@Test public void testBlockNr() throws IOException { long bl1 = blockr.getCurrentBlockNr(); long bl2 = etherscan.getCurrentBlockNr(); System.out.println("ret: "+bl1 +"/"+bl2); } |
### Question:
BerIdentifier { public int encode(BerByteArrayOutputStream berOStream) throws IOException { for (int i = (identifier.length - 1); i >= 0; i--) { berOStream.write(identifier[i]); } return identifier.length; } BerIdentifier(int identifierClass, int primitive, int tagNumber); BerIdentifier(); int encode(BerByteArrayOutputStream berOStream); int decode(InputStream iStream); int decodeAndCheck(InputStream iStream); boolean equals(int identifierClass, int primitive, int tagNumber); boolean equals(BerIdentifier berIdentifier); @Override String toString(); static final int UNIVERSAL_CLASS; static final int APPLICATION_CLASS; static final int CONTEXT_CLASS; static final int PRIVATE_CLASS; static final int PRIMITIVE; static final int CONSTRUCTED; static final int BOOLEAN_TAG; static final int INTEGER_TAG; static final int BIT_STRING_TAG; static final int OCTET_STRING_TAG; static final int NULL_TAG; static final int OBJECT_IDENTIFIER_TAG; static final int REAL_TAG; static final int ENUMERATED_TAG; static final int UTF8_STRING_TAG; static final int NUMERIC_STRING_TAG; static final int PRINTABLE_STRING_TAG; static final int TELETEX_STRING_TAG; static final int VIDEOTEX_STRING_TAG; static final int IA5_STRING_TAG; static final int GENERALIZED_TIME_TAG; static final int GRAPHIC_STRING_TAG; static final int VISIBLE_STRING_TAG; static final int GENERAL_STRING_TAG; static final int UNIVERSAL_STRING_TAG; static final int BMP_STRING_TAG; public byte[] identifier; public int identifierClass; public int primitive; public int tagNumber; }### Answer:
@Test public void twoByteEncoding() throws IOException { BerByteArrayOutputStream berBAOStream = new BerByteArrayOutputStream(50); BerIdentifier berIdentifier = new BerIdentifier(BerIdentifier.APPLICATION_CLASS, BerIdentifier.PRIMITIVE, 31); int length = berIdentifier.encode(berBAOStream); Assert.assertEquals(2, length); byte[] expectedBytes = new byte[] { 0x5f, 0x1f }; Assert.assertArrayEquals(expectedBytes, berBAOStream.getArray()); } |
### Question:
BerInteger { public int decode(InputStream iStream, boolean explicit) throws IOException { int codeLength = 0; if (explicit) { codeLength += id.decodeAndCheck(iStream); } BerLength length = new BerLength(); codeLength += length.decode(iStream); if (length.val < 1 || length.val > 8) { throw new IOException("Decoded length of BerInteger is not correct"); } byte[] byteCode = new byte[length.val]; if (iStream.read(byteCode, 0, length.val) < length.val) { throw new IOException("Error Decoding BerInteger"); } codeLength += length.val; val = (byteCode[0] & 0x80) == 0x80 ? -1 : 0; for (int i = 0; i < length.val; i++) { val <<= 8; val |= byteCode[i] & 0xff; } return codeLength; } BerInteger(); BerInteger(byte[] code); BerInteger(long val); int encode(BerByteArrayOutputStream berOStream, boolean explicit); int decode(InputStream iStream, boolean explicit); void encodeAndSave(int encodingSizeGuess); final static BerIdentifier identifier; public BerIdentifier id; public byte[] code; public long val; }### Answer:
@Test public void explicitDecoding() throws IOException { byte[] byteCode = new byte[] { 0x02, 0x01, 0x33 }; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerInteger asn1Integer = new BerInteger(); asn1Integer.decode(berInputStream, true); Assert.assertEquals(51, asn1Integer.val); }
@Test public void explicitDecoding2() throws IOException { byte[] byteCode = new byte[] { 0x02, 0x02, 0x15, (byte) 0xb3 }; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerInteger asn1Integer = new BerInteger(); asn1Integer.decode(berInputStream, true); Assert.assertEquals(5555, asn1Integer.val); }
@Test public void explicitDecoding3() throws IOException { byte[] byteCode = new byte[] { 0x02, 0x01, (byte) 0xc0 }; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerInteger asn1Integer = new BerInteger(); asn1Integer.decode(berInputStream, true); Assert.assertEquals(-64, asn1Integer.val); }
@Test public void explicitDecoding4() throws IOException { byte[] byteCode = new byte[] { 0x02, 0x02, (byte) 0xff, 0x01 }; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerInteger asn1Integer = new BerInteger(); asn1Integer.decode(berInputStream, true); Assert.assertEquals(-255, asn1Integer.val); } |
### Question:
BerOctetString { public int encode(BerByteArrayOutputStream berOStream, boolean explicit) throws IOException { berOStream.write(octetString); int codeLength = octetString.length; codeLength += BerLength.encodeLength(berOStream, codeLength); if (explicit) { codeLength += id.encode(berOStream); } return codeLength; } BerOctetString(); BerOctetString(byte[] octetString); int encode(BerByteArrayOutputStream berOStream, boolean explicit); int decode(InputStream iStream, boolean explicit); @Override String toString(); final static BerIdentifier identifier; public byte[] octetString; }### Answer:
@Test public void explicitEncoding() throws IOException { BerByteArrayOutputStream berStream = new BerByteArrayOutputStream(50); byte[] byteArray = new byte[] { 0x01, 0x02, 0x03 }; BerOctetString asn1OctetString = new BerOctetString(byteArray); int length = asn1OctetString.encode(berStream, true); Assert.assertEquals(5, length); byte[] expectedBytes = new byte[] { 0x04, 0x03, 0x01, 0x02, 0x03 }; Assert.assertArrayEquals(expectedBytes, berStream.getArray()); } |
### Question:
BerOctetString { public int decode(InputStream iStream, boolean explicit) throws IOException { int codeLength = 0; if (explicit) { codeLength += id.decodeAndCheck(iStream); } BerLength length = new BerLength(); codeLength += length.decode(iStream); octetString = new byte[length.val]; if (length.val != 0) { if (iStream.read(octetString, 0, length.val) < length.val) { throw new IOException("Error Decoding BerOctetString"); } codeLength += length.val; } return codeLength; } BerOctetString(); BerOctetString(byte[] octetString); int encode(BerByteArrayOutputStream berOStream, boolean explicit); int decode(InputStream iStream, boolean explicit); @Override String toString(); final static BerIdentifier identifier; public byte[] octetString; }### Answer:
@Test public void explicitDecoding() throws IOException { byte[] byteCode = new byte[] { 0x04, 0x00 }; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerOctetString asn1OctetString = new BerOctetString(); asn1OctetString.decode(berInputStream, true); Assert.assertEquals(0, asn1OctetString.octetString.length); } |
### Question:
BerObjectIdentifier { public int encode(BerByteArrayOutputStream berOStream, boolean explicit) throws IOException { int codeLength; if (code != null) { codeLength = code.length; for (int i = code.length - 1; i >= 0; i--) { berOStream.write(code[i]); } } else { int firstSubidentifier = 40 * objectIdentifierComponents[0] + objectIdentifierComponents[1]; int subidentifier; codeLength = 0; for (int i = (objectIdentifierComponents.length - 1); i > 0; i--) { if (i == 1) { subidentifier = firstSubidentifier; } else { subidentifier = objectIdentifierComponents[i]; } int subIDLength = 1; while (subidentifier > (Math.pow(2, (7 * subIDLength)) - 1)) { subIDLength++; } berOStream.write(subidentifier & 0x7f); for (int j = 1; j <= (subIDLength - 1); j++) { berOStream.write(((subidentifier >> (7 * j)) & 0xff) | 0x80); } codeLength += subIDLength; } codeLength += BerLength.encodeLength(berOStream, codeLength); } if (explicit) { codeLength += id.encode(berOStream); } return codeLength; } BerObjectIdentifier(); BerObjectIdentifier(byte[] code); BerObjectIdentifier(int[] objectIdentifierComponents); int encode(BerByteArrayOutputStream berOStream, boolean explicit); int decode(InputStream iStream, boolean explicit); @Override String toString(); final static BerIdentifier identifier; public byte[] code; public int[] objectIdentifierComponents; }### Answer:
@Test public void explicitEncoding() throws IOException { BerByteArrayOutputStream berBAOStream = new BerByteArrayOutputStream(50); BerObjectIdentifier oi = new BerObjectIdentifier(objectIdentifierComponents); int length = oi.encode(berBAOStream, true); Assert.assertEquals(7, length); Assert.assertArrayEquals(expectedBytes, berBAOStream.getArray()); } |
### Question:
BerLength { public static int encodeLength(BerByteArrayOutputStream berOStream, int length) throws IOException { if (length <= 127) { berOStream.write((byte) length); return 1; } else { int numLengthBytes = 1; while (((int) (Math.pow(2, 8 * numLengthBytes) - 1)) < length) { numLengthBytes++; } for (int i = 0; i < numLengthBytes; i++) { berOStream.write((length >> 8 * i) & 0xff); } berOStream.write(0x80 | numLengthBytes); return 1 + numLengthBytes; } } BerLength(); int decode(InputStream iStream); static int encodeLength(BerByteArrayOutputStream berOStream, int length); public int val; }### Answer:
@Test public void encodeLength() throws IOException { BerByteArrayOutputStream berOStream = new BerByteArrayOutputStream(50); int codedLength = BerLength.encodeLength(berOStream, 128); Assert.assertEquals(2, codedLength); byte[] expectedBytes = new byte[] { (byte) 0x81, (byte) 128 }; Assert.assertArrayEquals(expectedBytes, berOStream.getArray()); }
@Test public void encodeLength2() throws IOException { BerByteArrayOutputStream berOStream = new BerByteArrayOutputStream(50); int codedLength = BerLength.encodeLength(berOStream, 128); Assert.assertEquals(2, codedLength); byte[] expectedBytes = new byte[] { (byte) 0x81, (byte) 128 }; Assert.assertArrayEquals(expectedBytes, berOStream.getArray()); } |
### Question:
BerObjectIdentifier { public int decode(InputStream iStream, boolean explicit) throws IOException { int codeLength = 0; if (explicit) { codeLength += id.decodeAndCheck(iStream); } BerLength length = new BerLength(); codeLength += length.decode(iStream); if (length.val == 0) { objectIdentifierComponents = new int[0]; return codeLength; } byte[] byteCode = new byte[length.val]; if (iStream.read(byteCode, 0, length.val) == -1) { throw new IOException("Error Decoding BerObjectIdentifier"); } codeLength += length.val; List<Integer> objectIdentifierComponentsList = new ArrayList<Integer>(); int subIDEndIndex = 0; while ((byteCode[subIDEndIndex] & 0x80) == 0x80) { if (subIDEndIndex >= (length.val - 1)) { throw new IOException("Invalid Object Identifier"); } subIDEndIndex++; } int subidentifier = 0; for (int i = 0; i <= subIDEndIndex; i++) { subidentifier |= (byteCode[i] << ((subIDEndIndex - i) * 7)); } if (subidentifier < 40) { objectIdentifierComponentsList.add(0); objectIdentifierComponentsList.add(subidentifier); } else if (subidentifier < 80) { objectIdentifierComponentsList.add(1); objectIdentifierComponentsList.add(subidentifier - 40); } else { objectIdentifierComponentsList.add(2); objectIdentifierComponentsList.add(subidentifier - 80); } subIDEndIndex++; while (subIDEndIndex < length.val) { int subIDStartIndex = subIDEndIndex; while ((byteCode[subIDEndIndex] & 0x80) == 0x80) { if (subIDEndIndex == (length.val - 1)) { throw new IOException("Invalid Object Identifier"); } subIDEndIndex++; } subidentifier = 0; for (int j = subIDStartIndex; j <= subIDEndIndex; j++) { subidentifier |= ((byteCode[j] & 0x7f) << ((subIDEndIndex - j) * 7)); } objectIdentifierComponentsList.add(subidentifier); subIDEndIndex++; } objectIdentifierComponents = new int[objectIdentifierComponentsList.size()]; for (int i = 0; i < objectIdentifierComponentsList.size(); i++) { objectIdentifierComponents[i] = objectIdentifierComponentsList.get(i); } return codeLength; } BerObjectIdentifier(); BerObjectIdentifier(byte[] code); BerObjectIdentifier(int[] objectIdentifierComponents); int encode(BerByteArrayOutputStream berOStream, boolean explicit); int decode(InputStream iStream, boolean explicit); @Override String toString(); final static BerIdentifier identifier; public byte[] code; public int[] objectIdentifierComponents; }### Answer:
@Test public void explicitDecoding() throws IOException { ByteArrayInputStream berInputStream = new ByteArrayInputStream(expectedBytes); BerObjectIdentifier oi = new BerObjectIdentifier(); oi.decode(berInputStream, true); Assert.assertArrayEquals(objectIdentifierComponents, oi.objectIdentifierComponents); ByteArrayInputStream berInputStream2 = new ByteArrayInputStream(expectedBytes2); BerObjectIdentifier oi2 = new BerObjectIdentifier(); oi2.decode(berInputStream2, true); } |
### Question:
BerLength { public int decode(InputStream iStream) throws IOException { val = iStream.read(); int length = 1; if ((val & 0x80) != 0) { int lengthLength = val & 0x7f; if (lengthLength == 0) { val = -1; return 1; } if (lengthLength > 4) { throw new IOException("Length is out of bound!"); } val = 0; byte[] byteCode = new byte[lengthLength]; if (iStream.read(byteCode, 0, lengthLength) == -1) { throw new IOException("Error Decoding ASN1Integer"); } length += lengthLength; for (int i = 0; i < lengthLength; i++) { val |= (byteCode[i] & 0xff) << (8 * (lengthLength - i - 1)); } } return length; } BerLength(); int decode(InputStream iStream); static int encodeLength(BerByteArrayOutputStream berOStream, int length); public int val; }### Answer:
@Test public void explicitDecoding() throws IOException { byte[] byteCode = new byte[] { (byte) 0x81, (byte) 128 }; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerLength berLength = new BerLength(); berLength.decode(berInputStream); Assert.assertEquals(128, berLength.val); } |
### Question:
Functions { public static <T> List<T> myFilter(List<T> list, MyPredicate<T> myPredicate) { ArrayList<T> result = new ArrayList<>(); for (T t : list) { if (myPredicate.test(t)) result.add(t); } return result; } static List<T> myFilter(List<T> list, MyPredicate<T> myPredicate); static List<R> myMap(List<T> list, MyFunction<T, R> myFunction); static List<R> myFlatMap(List<T> list, MyFunction<T, List<R>> myFunction); static void myForEach(List<T> list, MyConsumer<T> myConsumer); static List<T> myGenerate(MySupplier<T> supplier, int count); }### Answer:
@Test public void testMyFilter() { List<Integer> numbers = Arrays.asList(4, 5, 7, 8, 10, 11, 14, 15); List<Integer> result = Functions.myFilter(numbers, item -> item % 2 == 0); assertEquals(Arrays.asList(4, 8, 10, 14), result); }
@Test public void testClosuresAvoidRepeats() { List<String> names = Arrays.asList("Foo", "Ramen", "Naan", "Ravioli"); System.out.println(Functions.myFilter(names, stringHasSizeOf(4))); System.out.println(Functions.myFilter(names, stringHasSizeOf(2))); } |
### Question:
Functions { public static <T> List<T> myGenerate(MySupplier<T> supplier, int count) { List<T> result = new ArrayList<>(); for (int i = 0; i < count; i++) { result.add(supplier.get()); } return result; } static List<T> myFilter(List<T> list, MyPredicate<T> myPredicate); static List<R> myMap(List<T> list, MyFunction<T, R> myFunction); static List<R> myFlatMap(List<T> list, MyFunction<T, List<R>> myFunction); static void myForEach(List<T> list, MyConsumer<T> myConsumer); static List<T> myGenerate(MySupplier<T> supplier, int count); }### Answer:
@Test public void testMyGenerate() { List<LocalDateTime> localDateTimes = Functions.myGenerate(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { } return LocalDateTime.now(); }, 10); System.out.println(localDateTimes); } |
### Question:
Functions { public static <T, R> List<R> myMap(List<T> list, MyFunction<T, R> myFunction) { ArrayList<R> result = new ArrayList<>(); for (T t : list) { result.add(myFunction.apply(t)); } return result; } static List<T> myFilter(List<T> list, MyPredicate<T> myPredicate); static List<R> myMap(List<T> list, MyFunction<T, R> myFunction); static List<R> myFlatMap(List<T> list, MyFunction<T, List<R>> myFunction); static void myForEach(List<T> list, MyConsumer<T> myConsumer); static List<T> myGenerate(MySupplier<T> supplier, int count); }### Answer:
@Test public void testMyMap() { List<Integer> numbers = Arrays.asList(4, 5, 7, 8); List<Integer> mapped = Functions.myMap(numbers, t -> t + 2); assertEquals(Arrays.asList(6, 7, 9, 10), mapped); }
@Test public void testMethodReferenceAStaticMethod() { List<Integer> numbers = Arrays.asList(2, 4, 5, 1, 9, 15, 19, 21, 33, 78, 93, 10); System.out.println(Functions.myMap(numbers, Math::abs)); }
@Test public void testMethodReferenceAContainingType() { List<String> words = Arrays.asList("One", "Two", "Three", "Four"); List<Integer> result = Functions.myMap(words, String::length); System.out.println(result); }
@Test public void testMethodReferenceAContainingTypeTrickQuestion() { List<Integer> numbers = Arrays.asList(2, 4, 5, 1, 9, 15, 19, 21, 33, 78, 93, 10); System.out.println(Functions.myMap(numbers, Object::toString)); }
@Test public void testTwoOrMoreItemsInALambda() { List<Integer> numbers = Arrays.asList(2, 4, 5, 1, 9, 15, 19, 21, 33, 78, 93, 10); System.out.println(Functions.myMap(numbers, x -> { int y = 100; int z = 10; return y + z + x; })); }
@Test public void testMethodReferenceAnInstance() { List<Integer> numbers = Arrays.asList(2, 4, 5, 1, 9, 15, 19, 21, 33, 78, 93, 10); TaxRate taxRate2016 = new TaxRate(2016, .085); System.out.println(Functions.myMap(numbers, taxRate2016::apply)); }
@Test public void testMethodReferenceANewType() { List<Integer> numbers = Arrays.asList(2, 4, 5, 1, 9, 15, 19, 21, 33, 78, 93, 10); System.out.println(Functions.myMap(numbers, Double::new)); } |
### Question:
Functions { public static <T, R> List<R> myFlatMap(List<T> list, MyFunction<T, List<R>> myFunction) { ArrayList<R> result = new ArrayList<>(); for (T t : list) { List<R> application = myFunction.apply(t); result.addAll(application); } return result; } static List<T> myFilter(List<T> list, MyPredicate<T> myPredicate); static List<R> myMap(List<T> list, MyFunction<T, R> myFunction); static List<R> myFlatMap(List<T> list, MyFunction<T, List<R>> myFunction); static void myForEach(List<T> list, MyConsumer<T> myConsumer); static List<T> myGenerate(MySupplier<T> supplier, int count); }### Answer:
@Test public void testMyFlatMap() { List<Integer> numbers = Arrays.asList(4, 5, 7, 8); List<Integer> mapped = Functions.myFlatMap(numbers, t -> List.of(t - 1, t, t + 1)); assertEquals(Arrays.asList(3, 4, 5, 4, 5, 6, 6, 7, 8, 7, 8, 9), mapped); } |
### Question:
Functions { public static <T> void myForEach(List<T> list, MyConsumer<T> myConsumer) { for (T t : list) { myConsumer.accept(t); } } static List<T> myFilter(List<T> list, MyPredicate<T> myPredicate); static List<R> myMap(List<T> list, MyFunction<T, R> myFunction); static List<R> myFlatMap(List<T> list, MyFunction<T, List<R>> myFunction); static void myForEach(List<T> list, MyConsumer<T> myConsumer); static List<T> myGenerate(MySupplier<T> supplier, int count); }### Answer:
@Test public void testMyForEach() { List<Integer> numbers = Arrays.asList(4, 5, 7, 8); Functions.myForEach(numbers, new MyConsumer<Integer>() { @Override public void accept(Integer x) { System.out.println(x); } }); } |
### Question:
WeChatUtils { public static String joinPath(final String firstPath, final String secondPath) { Validate.notEmpty(firstPath); Validate.notEmpty(secondPath); final String tmp1 = firstPath.endsWith("/") ? firstPath.substring(0, firstPath.length() - 1) : firstPath; final String tmp2 = secondPath.startsWith("/") ? (tmp1 + secondPath) : (tmp1 + "/" + secondPath); return tmp2.endsWith("/") ? tmp2.substring(0, tmp2.length() - 1) : tmp2; } private WeChatUtils(); @NotNull static String uuid32(); static String joinPath(final String firstPath, final String secondPath); static String urlEncode(final String urlStr); }### Answer:
@Test public void joinPath() { assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("http: } |
### Question:
WeChatPayRestTemplateClient implements WeChatPayClient { @Override public UnifiedOrderResponse unifiedOrder( final UnifiedOrderRequest request) throws WeChatPayException { Objects.requireNonNull(request); return postForEntity( WeChatPayClient.UNIFIED_ORDER_PATH, request, UnifiedOrderResponse.class) .getBody(); } WeChatPayRestTemplateClient(
final RestTemplate restTemplate, final WeChatPayProperties weChatPayProperties); @Override UnifiedOrderResponse unifiedOrder(
final UnifiedOrderRequest request); @Override OrderQueryResponse orderQuery(
final OrderQueryRequest request); @Override CloseOrderResponse closeOrder(
final CloseOrderRequest request); @Override RefundResponse refund(
final RefundRequest request); @Override RefundQueryResponse refundQuery(
final RefundQueryRequest request); }### Answer:
@Test public void unifiedOrder() { stubFor(post(urlEqualTo(WeChatPayClient.UNIFIED_ORDER_PATH)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", MediaType.APPLICATION_XML_VALUE) .withBody("<xml><return_code>SUCCESS</return_code><result_code>SUCCESS</result_code></xml>"))); WeChatPayConfigurator.DEFAULT.setMchKey("key"); final UnifiedOrderRequest request = UnifiedOrderRequest.createWithNative("body", "outTradeNo", 100); final UnifiedOrderResponse unifiedOrderResponse = this.weChatPayClient.unifiedOrder(request); assertThat(unifiedOrderResponse) .hasReturnCode("SUCCESS") .hasResultCode("SUCCESS"); } |
### Question:
WeChatPayRestTemplateClient implements WeChatPayClient { @Override public OrderQueryResponse orderQuery( final OrderQueryRequest request) throws WeChatPayException { Objects.requireNonNull(request); return postForEntity( WeChatPayClient.ORDER_QUERY_PATH, request, OrderQueryResponse.class) .getBody(); } WeChatPayRestTemplateClient(
final RestTemplate restTemplate, final WeChatPayProperties weChatPayProperties); @Override UnifiedOrderResponse unifiedOrder(
final UnifiedOrderRequest request); @Override OrderQueryResponse orderQuery(
final OrderQueryRequest request); @Override CloseOrderResponse closeOrder(
final CloseOrderRequest request); @Override RefundResponse refund(
final RefundRequest request); @Override RefundQueryResponse refundQuery(
final RefundQueryRequest request); }### Answer:
@Test public void orderQuery() { } |
### Question:
WeChatMpController { @GetMapping(path = "${wechat.mp.authorize-code-path:" + WeChatMpProperties.AUTHORIZE_CODE_PATH + '}') public void authorizeCode( @RequestParam("code") final String code) { final WeChatMpAccessTokenResponse accessTokenResponse = this.weChatMpClient.accessToken(code); if (accessTokenResponse.isSuccessful()) { this.publisher.publishEvent(new WeChatMpAuthenticationSuccessEvent(accessTokenResponse)); } else { throw new WeChatMpAuthenticationException(String.format("errcode: %s, errmsg: %s", accessTokenResponse.getErrCode(), accessTokenResponse.getErrMsg())); } } WeChatMpController(
@NotNull final WeChatMpProperties weChatMpProperties,
@NotNull final WeChatMpClient weChatMpClient,
@NotNull final ApplicationEventPublisher publisher); @GetMapping(path = "${wechat.mp.authorize-path:" + WeChatMpProperties.AUTHORIZE_PATH + "}") RedirectView authorize(@RequestParam("redirect") final String redirect); @GetMapping(path = "${wechat.mp.authorize-code-path:" + WeChatMpProperties.AUTHORIZE_CODE_PATH + '}') void authorizeCode(
@RequestParam("code") final String code); }### Answer:
@Test public void authorizeCode() throws Exception { final WeChatMpAccessTokenResponse accessTokenResponse = new WeChatMpAccessTokenResponse(); accessTokenResponse.setErrCode("0"); given(this.weChatMpClient.accessToken("code")).willReturn(accessTokenResponse); this.mvc.perform(get(WeChatMpProperties.AUTHORIZE_CODE_PATH) .param("code", "code") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } |
### Question:
WeChatMpAutoConfiguration { @Bean @ConditionalOnMissingBean public WeChatMpController weChatMpController(final WeChatMpClient weChatMpClient, final ApplicationEventPublisher publisher) { return new WeChatMpController(this.weChatMpProperties, weChatMpClient, publisher); } WeChatMpAutoConfiguration(final WeChatMpProperties weChatMpProperties); @Bean @ConditionalOnMissingBean WeChatMpController weChatMpController(final WeChatMpClient weChatMpClient,
final ApplicationEventPublisher publisher); @Bean @ConditionalOnMissingBean WeChatMpClient weChatMpClient(
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired(required = false) final RestTemplateBuilder restTemplateBuilder); }### Answer:
@Test public void weChatMpController() throws Exception { ClassPool.getDefault().makeClass("cn.javaer.wechat.spring.boot.starter.mp.ConditionalOnClassTrigger").toClass(); try (AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext()) { context.register(WeChatMpAutoConfiguration.class); context.refresh(); context.getBean(WeChatMpController.class); } } |
### Question:
WeChatPayUtils { @NotNull public static String generateSign( @NotNull final BasePayRequest request, @NotNull final String mchKey) { return generateSign(signParamsFrom(request), mchKey); } @NotNull static String generateSign(
@NotNull final BasePayRequest request, @NotNull final String mchKey); @NotNull static String generateSign(
@NotNull final BasePayResponse response, @NotNull final String mchKey); @NotNull static String generateSign(
@NotNull final SortedMap<String, String> params, @NotNull final String mchKey); static void checkSuccessful(@NotNull final BasePayResponse response); static void checkSign(@NotNull final BasePayResponse response, @NotNull final String mchKey); static boolean isSuccessful(@NotNull final BasePayResponse response, @NotNull final String mchKey); static Map<String, T> beansMapFrom(
@NotNull final SortedMap<String, String> params,
@NotNull final Map<String, BiConsumer<String, T>> mapping,
@NotNull final Supplier<T> newT); static List<T> beansFrom(
@NotNull final SortedMap<String, String> params,
@NotNull final Map<String, BiConsumer<String, T>> mapping,
@NotNull final Supplier<T> newT); static List<Coupon> couponsFrom(final SortedMap<String, String> params); }### Answer:
@Test public void sign() { final UnifiedOrderResponse response = new UnifiedOrderResponse(); response.setReturnCode("SUCCESS"); response.setReturnMsg("OK"); response.setAppid("wx2421b1c4370ec43b"); response.setMchId("10000100"); response.setNonceStr("IITRi8Iabbblz1Jc"); response.setResultCode("SUCCESS"); response.setPrepayId("wx201411101639507cbf6ffd8b0779950874"); response.setTradeType("JSAPI"); response.beforeSign(); assertEquals("BC884153761883FE608EA956BD05A6F5", WeChatPayUtils.generateSign(response, "key")); }
@Test public void sign4Cache() throws Exception { final UnifiedOrderResponse response = new UnifiedOrderResponse(); response.setReturnCode("SUCCESS"); response.setReturnMsg("OK"); response.setAppid("wx2421b1c4370ec43b"); response.setMchId("10000100"); response.setNonceStr("IITRi8Iabbblz1Jc"); response.setResultCode("SUCCESS"); response.setPrepayId("wx201411101639507cbf6ffd8b0779950874"); response.setTradeType("JSAPI"); WeChatPayUtils.generateSign(response, "key"); assertEquals("BC884153761883FE608EA956BD05A6F5", WeChatPayUtils.generateSign(response, "key")); final Field field = WeChatPayUtils.class.getDeclaredField("CACHE_FOR_SIGN"); field.setAccessible(true); @SuppressWarnings("unchecked") final Map<Class, List<Field>> cache = (Map<Class, List<Field>>) field.get(null); assertThat(cache).hasSize(1); } |
### Question:
WeChatPayUtils { public static <T> Map<String, T> beansMapFrom( @NotNull final SortedMap<String, String> params, @NotNull final Map<String, BiConsumer<String, T>> mapping, @NotNull final Supplier<T> newT) { final Map<String, T> rtMap = new HashMap<>(); for (final Map.Entry<String, String> entry : params.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (null == value || value.isEmpty()) { continue; } for (final Map.Entry<String, BiConsumer<String, T>> mappingEntry : mapping.entrySet()) { final String keyStart = mappingEntry.getKey(); if (key.matches(keyStart + "\\d+")) { final String rtKey = key.substring(keyStart.length()); final T t = rtMap.computeIfAbsent(rtKey, k -> newT.get()); mappingEntry.getValue().accept(value, t); } } } return rtMap; } @NotNull static String generateSign(
@NotNull final BasePayRequest request, @NotNull final String mchKey); @NotNull static String generateSign(
@NotNull final BasePayResponse response, @NotNull final String mchKey); @NotNull static String generateSign(
@NotNull final SortedMap<String, String> params, @NotNull final String mchKey); static void checkSuccessful(@NotNull final BasePayResponse response); static void checkSign(@NotNull final BasePayResponse response, @NotNull final String mchKey); static boolean isSuccessful(@NotNull final BasePayResponse response, @NotNull final String mchKey); static Map<String, T> beansMapFrom(
@NotNull final SortedMap<String, String> params,
@NotNull final Map<String, BiConsumer<String, T>> mapping,
@NotNull final Supplier<T> newT); static List<T> beansFrom(
@NotNull final SortedMap<String, String> params,
@NotNull final Map<String, BiConsumer<String, T>> mapping,
@NotNull final Supplier<T> newT); static List<Coupon> couponsFrom(final SortedMap<String, String> params); }### Answer:
@Test public void beansMapFrom() { final SortedMap<String, String> params = new TreeMap<>(); params.put("coupon_refund_id_0", "BC884153761883FE608EA956BD05A6F5"); params.put("coupon_type_0", "CASH"); params.put("coupon_refund_fee_0", "100"); params.put("coupon_refund_id_1", "16BE80B8FD1044069950ADAEDEB812C5"); params.put("coupon_type_1", "NO_CASH"); params.put("coupon_refund_fee_1", "1"); final Map<String, BiConsumer<String, Coupon>> mapping = new HashMap<>(3); mapping.put("coupon_refund_id_", (val, coupon) -> coupon.setId(val)); mapping.put("coupon_type_", (val, coupon) -> coupon.setType(Coupon.Type.valueOf(val))); mapping.put("coupon_refund_fee_", (val, coupon) -> coupon.setFee(Integer.valueOf(val))); final Map<String, Coupon> couponMap = WeChatPayUtils.beansMapFrom( params, mapping, Coupon::new); assertThat(couponMap) .containsOnlyKeys("0", "1"); assertThat(couponMap.get("0")) .hasId("BC884153761883FE608EA956BD05A6F5") .hasType(Coupon.Type.CASH) .hasFee(100); assertThat(couponMap.get("1")) .hasId("16BE80B8FD1044069950ADAEDEB812C5") .hasType(Coupon.Type.NO_CASH) .hasFee(1); } |
### Question:
NotifyResult extends BasePayResponse { @Override public void beforeSign() { if (null == this.coupons && null != this.otherParams) { this.coupons = WeChatPayUtils.couponsFrom(this.otherParams); } } @Override void beforeSign(); }### Answer:
@Test public void testParse() { final String xml = WeChatTestUtils.readClassPathFileToUTFString("/WeChatPayNotifyResult.xml", this.getClass()); final NotifyResult notifyResult = WeChatTestUtils.jaxbUnmarshal(xml, NotifyResult.class); assertThat(notifyResult) .hasAppid("wx2421b1c4370ec43b") .hasAttach("支付测试") .hasBankType("CFT") .hasFeeType("CNY") .hasIsSubscribe("Y") .hasMchId("10000100") .hasNonceStr("5d2b6c2a8db53831f7eda20af46e531c") .hasOpenid("oUpF8uMEb4qRXf22hE3X68TekukE") .hasOutTradeNo("1409811653") .hasResultCode("SUCCESS") .hasReturnCode("SUCCESS") .hasSign("B552ED6B279343CB493C5DD0D78AB241") .hasSubMchId("10000100") .hasTimeEnd("20140903131540") .hasTotalFee(1) .hasCouponFee(10) .hasCouponCount(1) .hasTradeType("JSAPI") .hasTransactionId("1004400740201409030005092168"); notifyResult.beforeSign(); assertThat(notifyResult.getCoupons()) .hasSize(5) .extracting("id", "type", "fee") .containsOnly( tuple("coupon_id_0", Coupon.Type.CASH, 0), tuple("coupon_id_1", Coupon.Type.CASH, 1), tuple("coupon_id_2", Coupon.Type.CASH, 2), tuple("coupon_id_3", Coupon.Type.NO_CASH, 3), tuple("coupon_id_4", Coupon.Type.CASH, 4) ); } |
### Question:
RefundQueryResponse extends BasePayResponse { @Override public void beforeSign() { if (null == this.refunds && null != this.otherParams) { final Map<String, Refund> refundsMap = WeChatPayUtils.beansMapFrom(this.otherParams, createRefundMapping(), Refund::new); initCoupons(refundsMap); this.refunds = new ArrayList<>(refundsMap.values()); } } @Override void beforeSign(); }### Answer:
@Test public void beforeSign() { final String xmlStr = WeChatTestUtils.readClassPathFileToUTFString("/WeChatPayRefundQueryResponse.xml", this.getClass()); final RefundQueryResponse response = WeChatTestUtils.jaxbUnmarshal(xmlStr, RefundQueryResponse.class); assertThat(response) .hasReturnCode("SUCCESS") .hasResultCode("SUCCESS") .hasAppid("appid") .hasMchId("mch_id") .hasNonceStr("4EDCA0A0220F466D95C524FA3FE3C100") .hasTotalRefundCount(36) .hasTransactionId("transaction_id") .hasOutTradeNo("out_trade_no") .hasTotalFee(100) .hasCashFee(90) .hasRefundCount(21); response.beforeSign(); assertThat(response.getOtherParams()) .containsEntry("out_refund_no_0", "out_refund_no_0") .containsEntry("refund_id_0", "refund_id_0") .containsEntry("refund_channel_0", "ORIGINAL") .containsEntry("refund_fee_0", "10") .containsEntry("settlement_refund_fee_0", "8") .containsEntry("coupon_refund_fee_0", "20") .containsEntry("coupon_refund_count_0", "3") .containsEntry("refund_status_0", "SUCCESS") .containsEntry("refund_account_0", "REFUND_SOURCE_RECHARGE_FUNDS") .containsEntry("refund_recv_accout_0", "招商银行信用卡0403") .containsEntry("refund_success_time_0", "2016-07-25 15:26:26") .containsEntry("coupon_refund_id_0_0", "BE2F2D9E4D9848E2963BF39A8DE0A2CD") .containsEntry("coupon_type_0_0", "CASH") .containsEntry("coupon_refund_fee_0_0", "2") .containsEntry("coupon_refund_id_0_1", "2DC61D51BE6C4CEA9FAA7E41893B2D97") .containsEntry("coupon_type_0_1", "CASH") .containsEntry("coupon_refund_fee_0_1", "3") .containsEntry("coupon_refund_id_1_0", "FCBA60A940224716A77D06EF202A57AD") .containsEntry("coupon_type_1_0", "NO_CASH") .containsEntry("coupon_refund_fee_1_0", "5") .containsEntry("coupon_refund_id_1_1", "E9D17A8E767847299B038836A5CE34D9") .containsEntry("coupon_type_1_1", "CASH") .containsEntry("coupon_refund_fee_1_1", "3") ; final String generateSign = WeChatPayUtils.generateSign(response, "key"); assertThat(response).hasSign(generateSign); WeChatPayConfigurator.DEFAULT.setMchKey("key"); response.checkSignAndSuccessful(); } |
### Question:
WeChatMpResponse { @JsonAnySetter protected void setOtherProperties(final String name, final String value) { this.otherProperties.put(name, value); } boolean isSuccessful(); }### Answer:
@Test public void setOtherProperties() throws Exception { final ObjectMapper mapper = new ObjectMapper(); final Demo demo = mapper.readValue("{\"errcode\":\"d1\",\"any1\":\"any1\",\"any2\":\"any2\"}", Demo.class); Assert.assertEquals("d1", demo.getErrCode()); Assert.assertEquals("any1", demo.getOtherProperties().get("any1")); Assert.assertEquals("any2", demo.getOtherProperties().get("any2")); } |
### Question:
WeChatMpUtils { public static String generateAuthorizeUrl( @NotNull final String appId, @NotNull final String redirectUri, @NotNull final AuthorizeScope scope, @NotNull final String state) { return "https: + "&redirect_uri=" + WeChatUtils.urlEncode(redirectUri) + "&response_type=code&scope=" + scope.getScope() + "&state=" + state + "#wechat_redirect"; } static String generateAuthorizeUrl(
@NotNull final String appId,
@NotNull final String redirectUri,
@NotNull final AuthorizeScope scope,
@NotNull final String state); static String generateAuthorizeUrl(
@NotNull final String appId,
@NotNull final String redirectUri,
@NotNull final AuthorizeScope scope); static void checkResponseBody(final WeChatMpResponse response); }### Answer:
@Test public void generateAuthorizeUrl() { final String authorizeUrl = WeChatMpUtils.generateAuthorizeUrl( "wx520c15f417810387", "https: AuthorizeScope.BASE, "123"); final String expected = "https: assertEquals(expected, authorizeUrl); }
@Test public void generateAuthorizeUrlNoState() { final String authorizeUrl = WeChatMpUtils.generateAuthorizeUrl("wx520c15f417810387", "https: AuthorizeScope.BASE); final String expected = "https: assertEquals(expected, authorizeUrl); } |
### Question:
WeChatPayAutoConfiguration { @Bean @ConditionalOnMissingBean public WeChatPayClient weChatPayClient( @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Autowired(required = false) RestTemplate restTemplate) { if (null == restTemplate) { restTemplate = new RestTemplate(); } return new WeChatPayRestTemplateClient(restTemplate, this.weChatPayProperties); } WeChatPayAutoConfiguration(final WeChatPayProperties weChatPayProperties); @Bean @ConditionalOnMissingBean WeChatPayClient weChatPayClient(
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired(required = false) RestTemplate restTemplate); @Bean @ConditionalOnMissingBean WeChatPayService weChatPayService(
final WeChatPayClient weChatPayClient, final ApplicationEventPublisher publisher); @Bean @ConditionalOnMissingBean WeChatPayController weChatPayController(final ApplicationEventPublisher publisher); }### Answer:
@Test public void weChatPayClient() throws Exception { ClassPool.getDefault().makeClass("cn.javaer.wechat.spring.boot.starter.pay.ConditionalOnClassTrigger").toClass(); try (AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext()) { context.register(WeChatPayAutoConfiguration.class); context.refresh(); context.getBean(WeChatPayClient.class); } } |
### Question:
BerLength implements Serializable { public static int encodeLength(OutputStream reverseOS, int length) throws IOException { if (length <= 127) { reverseOS.write(length); return 1; } if (length <= 255) { reverseOS.write(length); reverseOS.write(0x81); return 2; } if (length <= 65535) { reverseOS.write(length); reverseOS.write(length >> 8); reverseOS.write(0x82); return 3; } if (length <= 16777215) { reverseOS.write(length); reverseOS.write(length >> 8); reverseOS.write(length >> 16); reverseOS.write(0x83); return 4; } int numLengthBytes = 1; while (((int) (Math.pow(2, 8 * numLengthBytes) - 1)) < length) { numLengthBytes++; } for (int i = 0; i < numLengthBytes; i++) { reverseOS.write(length >> (8 * i)); } reverseOS.write(0x80 | numLengthBytes); return 1 + numLengthBytes; } BerLength(); static int encodeLength(OutputStream reverseOS, int length); static int readEocByte(InputStream is); int decode(InputStream is); int readEocIfIndefinite(InputStream is); public int val; }### Answer:
@Test public void encodeLength() throws IOException { ReverseByteArrayOutputStream os = new ReverseByteArrayOutputStream(50); int codedLength = BerLength.encodeLength(os, 128); assertEquals(2, codedLength); byte[] expectedBytes = new byte[] {(byte) 0x81, (byte) 128}; assertArrayEquals(expectedBytes, os.getArray()); }
@Test public void encodeLength2() throws IOException { ReverseByteArrayOutputStream os = new ReverseByteArrayOutputStream(50); int codedLength = BerLength.encodeLength(os, 128); assertEquals(2, codedLength); byte[] expectedBytes = new byte[] {(byte) 0x81, (byte) 128}; assertArrayEquals(expectedBytes, os.getArray()); }
@Test public void encodeLength3() throws IOException { ReverseByteArrayOutputStream os = new ReverseByteArrayOutputStream(50); int codedLength = BerLength.encodeLength(os, 65536); assertEquals(4, codedLength); byte[] expectedBytes = new byte[] {(byte) 0x83, 1, 0, 0}; assertArrayEquals(expectedBytes, os.getArray()); }
@Test public void encodeLength4() throws IOException { ReverseByteArrayOutputStream os = new ReverseByteArrayOutputStream(50); int codedLength = BerLength.encodeLength(os, 256); assertEquals(3, codedLength); byte[] expectedBytes = new byte[] {(byte) 0x82, 1, 0}; assertArrayEquals(expectedBytes, os.getArray()); }
@Test public void encodeLength5() throws IOException { ReverseByteArrayOutputStream os = new ReverseByteArrayOutputStream(50); int codedLength = BerLength.encodeLength(os, 16777216); assertEquals(5, codedLength); byte[] expectedBytes = new byte[] {(byte) 0x84, 1, 0, 0, 0}; assertArrayEquals(expectedBytes, os.getArray()); } |
### Question:
BerOctetString implements Serializable, BerType { @Override public int encode(OutputStream reverseOS) throws IOException { return encode(reverseOS, true); } BerOctetString(); BerOctetString(byte[] value); @Override int encode(OutputStream reverseOS); int encode(OutputStream reverseOS, boolean withTag); @Override int decode(InputStream is); int decode(InputStream is, boolean withTag); @Override String toString(); static final BerTag tag; public byte[] value; }### Answer:
@Test public void explicitEncoding() throws IOException { ReverseByteArrayOutputStream berStream = new ReverseByteArrayOutputStream(50); byte[] byteArray = new byte[] {0x01, 0x02, 0x03}; BerOctetString asn1OctetString = new BerOctetString(byteArray); int length = asn1OctetString.encode(berStream, true); assertEquals(5, length); byte[] expectedBytes = new byte[] {0x04, 0x03, 0x01, 0x02, 0x03}; assertArrayEquals(expectedBytes, berStream.getArray()); } |
### Question:
BerOctetString implements Serializable, BerType { @Override public int decode(InputStream is) throws IOException { return decode(is, true); } BerOctetString(); BerOctetString(byte[] value); @Override int encode(OutputStream reverseOS); int encode(OutputStream reverseOS, boolean withTag); @Override int decode(InputStream is); int decode(InputStream is, boolean withTag); @Override String toString(); static final BerTag tag; public byte[] value; }### Answer:
@Test public void explicitDecoding() throws IOException { byte[] byteCode = new byte[] {0x04, 0x00}; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerOctetString asn1OctetString = new BerOctetString(); asn1OctetString.decode(berInputStream, true); assertEquals(0, asn1OctetString.value.length); } |
### Question:
BerOctetString implements Serializable, BerType { @Override public String toString() { return HexString.fromBytes(value); } BerOctetString(); BerOctetString(byte[] value); @Override int encode(OutputStream reverseOS); int encode(OutputStream reverseOS, boolean withTag); @Override int decode(InputStream is); int decode(InputStream is, boolean withTag); @Override String toString(); static final BerTag tag; public byte[] value; }### Answer:
@Test public void toStringTest() { BerOctetString octetString = new BerOctetString(new byte[] {1, 2, (byte) 0xa0}); assertEquals("0102A0", octetString.toString()); } |
### Question:
BerObjectIdentifier implements Serializable, BerType { @Override public int encode(OutputStream reverseOS) throws IOException { return encode(reverseOS, true); } BerObjectIdentifier(); BerObjectIdentifier(byte[] code); BerObjectIdentifier(int[] value); @Override int encode(OutputStream reverseOS); int encode(OutputStream reverseOS, boolean withTag); @Override int decode(InputStream is); int decode(InputStream is, boolean withTag); @Override String toString(); static final BerTag tag; public int[] value; }### Answer:
@Test public void explicitEncoding() throws IOException { ReverseByteArrayOutputStream berBAOStream = new ReverseByteArrayOutputStream(50); BerObjectIdentifier oi = new BerObjectIdentifier(objectIdentifierComponents); int length = oi.encode(berBAOStream, true); assertEquals(7, length); assertArrayEquals(expectedBytes, berBAOStream.getArray()); } |
### Question:
BerObjectIdentifier implements Serializable, BerType { @Override public int decode(InputStream is) throws IOException { return decode(is, true); } BerObjectIdentifier(); BerObjectIdentifier(byte[] code); BerObjectIdentifier(int[] value); @Override int encode(OutputStream reverseOS); int encode(OutputStream reverseOS, boolean withTag); @Override int decode(InputStream is); int decode(InputStream is, boolean withTag); @Override String toString(); static final BerTag tag; public int[] value; }### Answer:
@Test public void explicitDecoding() throws IOException { ByteArrayInputStream berInputStream = new ByteArrayInputStream(expectedBytes); BerObjectIdentifier oi = new BerObjectIdentifier(); oi.decode(berInputStream, true); assertArrayEquals(objectIdentifierComponents, oi.value); ByteArrayInputStream berInputStream2 = new ByteArrayInputStream(expectedBytes2); BerObjectIdentifier oi2 = new BerObjectIdentifier(); oi2.decode(berInputStream2, true); } |
### Question:
BerGeneralizedTime extends BerVisibleString { @Override public int encode(OutputStream reverseOS, boolean withTag) throws IOException { int codeLength = super.encode(reverseOS, false); if (withTag) { codeLength += tag.encode(reverseOS); } return codeLength; } BerGeneralizedTime(); BerGeneralizedTime(byte[] value); BerGeneralizedTime(String valueAsString); @Override int encode(OutputStream reverseOS, boolean withTag); @Override int decode(InputStream is, boolean withTag); Calendar asCalendar(); Date asDate(); static final BerTag tag; }### Answer:
@Test public void explicitEncoding() throws IOException { ReverseByteArrayOutputStream berStream = new ReverseByteArrayOutputStream(50); byte[] byteArray = new byte[] {0x01, 0x02, 0x03}; BerGeneralizedTime berGeneralizedTime = new BerGeneralizedTime(byteArray); int length = berGeneralizedTime.encode(berStream, true); assertEquals(5, length); byte[] expectedBytes = new byte[] {24, 0x03, 0x01, 0x02, 0x03}; assertArrayEquals(expectedBytes, berStream.getArray()); } |
### Question:
BerBitString implements Serializable, BerType { @Override public String toString() { StringBuilder sb = new StringBuilder(); for (boolean bit : getValueAsBooleans()) { if (bit) { sb.append('1'); } else { sb.append('0'); } } return sb.toString(); } BerBitString(); BerBitString(byte[] value, int numBits); BerBitString(boolean[] value); BerBitString(byte[] code); boolean[] getValueAsBooleans(); @Override int encode(OutputStream reverseOS); int encode(OutputStream reverseOS, boolean withTag); @Override int decode(InputStream is); int decode(InputStream is, boolean withTag); @Override String toString(); static final BerTag tag; public byte[] value; public int numBits; }### Answer:
@Test public void toStringTest() { BerBitString bitString = new BerBitString(new byte[] {1, 2, 7}, 23); assertEquals("00000001000000100000011", bitString.toString()); }
@Test public void toString2Test() { BerBitString bitString = new BerBitString( new boolean[] { false, false, false, false, false, false, false, true, false, false, false, false, false, false, true, false, false, false, false, false, false, true, true }); assertEquals("00000001000000100000011", bitString.toString()); } |
### Question:
BerLength implements Serializable { public int decode(InputStream is) throws IOException { val = is.read(); if (val < 128) { if (val == -1) { throw new EOFException("Unexpected end of input stream."); } return 1; } int lengthLength = val & 0x7f; if (lengthLength == 0) { val = -1; return 1; } if (lengthLength > 4) { throw new IOException("Length is out of bounds: " + lengthLength); } val = 0; for (int i = 0; i < lengthLength; i++) { int nextByte = is.read(); if (nextByte == -1) { throw new EOFException("Unexpected end of input stream."); } val |= nextByte << (8 * (lengthLength - i - 1)); } return lengthLength + 1; } BerLength(); static int encodeLength(OutputStream reverseOS, int length); static int readEocByte(InputStream is); int decode(InputStream is); int readEocIfIndefinite(InputStream is); public int val; }### Answer:
@Test public void explicitDecoding() throws IOException { byte[] byteCode = new byte[] {(byte) 0x81, (byte) 128}; ByteArrayInputStream berInputStream = new ByteArrayInputStream(byteCode); BerLength berLength = new BerLength(); berLength.decode(berInputStream); assertEquals(128, berLength.val); } |
### Question:
PrimaryMetaStore extends AbstractMetaStore { @Override public FederationType getFederationType() { return FederationType.PRIMARY; } PrimaryMetaStore(); PrimaryMetaStore(
String name,
String remoteMetaStoreUris,
AccessControlType accessControlType,
String... writableDatabaseWhitelist); PrimaryMetaStore(
String name,
String remoteMetaStoreUris,
AccessControlType accessControlType,
List<String> writableDatabaseWhitelist); @Override FederationType getFederationType(); @NotNull @Override String getDatabasePrefix(); }### Answer:
@Test public void testFederationType() { assertThat(metaStore.getFederationType(), is(FederationType.PRIMARY)); } |
### Question:
MetaStoreMappingDecorator implements MetaStoreMapping { @Override public String getMetastoreMappingName() { return metaStoreMapping.getMetastoreMappingName(); } MetaStoreMappingDecorator(MetaStoreMapping metaStoreMapping); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override void close(); @Override Iface getClient(); @Override String getDatabasePrefix(); @Override String getMetastoreMappingName(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override long getLatency(); }### Answer:
@Test public void getMetastoreMappingName() throws Exception { when(metaStoreMapping.getMetastoreMappingName()).thenReturn("Name"); String result = decorator.getMetastoreMappingName(); assertThat(result, is("Name")); } |
### Question:
MetaStoreMappingDecorator implements MetaStoreMapping { @Override public boolean isAvailable() { return metaStoreMapping.isAvailable(); } MetaStoreMappingDecorator(MetaStoreMapping metaStoreMapping); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override void close(); @Override Iface getClient(); @Override String getDatabasePrefix(); @Override String getMetastoreMappingName(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override long getLatency(); }### Answer:
@Test public void isAvailable() throws Exception { when(metaStoreMapping.isAvailable()).thenReturn(true); boolean result = decorator.isAvailable(); assertThat(result, is(true)); } |
### Question:
MetaStoreMappingDecorator implements MetaStoreMapping { @Override public String transformInboundDatabaseName(String databaseName) { return metaStoreMapping.transformInboundDatabaseName(databaseName); } MetaStoreMappingDecorator(MetaStoreMapping metaStoreMapping); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override void close(); @Override Iface getClient(); @Override String getDatabasePrefix(); @Override String getMetastoreMappingName(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override long getLatency(); }### Answer:
@Test public void transformInboundDatabaseName() throws Exception { when(metaStoreMapping.transformInboundDatabaseName("db")).thenReturn("trans_db"); String result = decorator.transformInboundDatabaseName("db"); assertThat(result, is("trans_db")); } |
### Question:
MetaStoreMappingDecorator implements MetaStoreMapping { @Override public String transformOutboundDatabaseName(String databaseName) { return metaStoreMapping.transformOutboundDatabaseName(databaseName); } MetaStoreMappingDecorator(MetaStoreMapping metaStoreMapping); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override void close(); @Override Iface getClient(); @Override String getDatabasePrefix(); @Override String getMetastoreMappingName(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override long getLatency(); }### Answer:
@Test public void transformOutboundDatabaseName() throws Exception { when(metaStoreMapping.transformOutboundDatabaseName("db")).thenReturn("trans_db"); String result = decorator.transformOutboundDatabaseName("db"); assertThat(result, is("trans_db")); } |
### Question:
MetaStoreMappingDecorator implements MetaStoreMapping { @Override public Database transformOutboundDatabase(Database database) { return metaStoreMapping.transformOutboundDatabase(database); } MetaStoreMappingDecorator(MetaStoreMapping metaStoreMapping); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override void close(); @Override Iface getClient(); @Override String getDatabasePrefix(); @Override String getMetastoreMappingName(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override long getLatency(); }### Answer:
@Test public void transformOutboundDatabase() throws Exception { Database database = new Database(); database.setName("a"); Database expected = new Database(); expected.setName("b"); when(metaStoreMapping.transformOutboundDatabase(database)).thenReturn(expected); Database result = decorator.transformOutboundDatabase(database); assertThat(result, is(expected)); } |
### Question:
MetaStoreMappingImpl implements MetaStoreMapping { @Override public String transformOutboundDatabaseName(String databaseName) { return databaseName.toLowerCase(Locale.ROOT); } MetaStoreMappingImpl(
String databasePrefix,
String name,
CloseableThriftHiveMetastoreIface client,
AccessControlHandler accessControlHandler,
ConnectionType connectionType,
long latency); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override ThriftHiveMetastore.Iface getClient(); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override String getDatabasePrefix(); @Override void close(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override String getMetastoreMappingName(); @Override long getLatency(); }### Answer:
@Test public void transformOutboundDatabaseName() { assertThat(metaStoreMapping.transformOutboundDatabaseName("My_Database"), is("my_database")); } |
### Question:
MetaStoreMappingImpl implements MetaStoreMapping { @Override public Database transformOutboundDatabase(Database database) { database.setName(transformOutboundDatabaseName(database.getName())); return database; } MetaStoreMappingImpl(
String databasePrefix,
String name,
CloseableThriftHiveMetastoreIface client,
AccessControlHandler accessControlHandler,
ConnectionType connectionType,
long latency); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override ThriftHiveMetastore.Iface getClient(); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override String getDatabasePrefix(); @Override void close(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override String getMetastoreMappingName(); @Override long getLatency(); }### Answer:
@Test public void transformOutboundDatabase() { when(database.getName()).thenReturn("My_Database"); Database outboundDatabase = metaStoreMapping.transformOutboundDatabase(database); assertThat(outboundDatabase, is(sameInstance(database))); verify(outboundDatabase).setName("my_database"); } |
### Question:
MetaStoreMappingImpl implements MetaStoreMapping { @Override public String transformInboundDatabaseName(String databaseName) { return databaseName.toLowerCase(Locale.ROOT); } MetaStoreMappingImpl(
String databasePrefix,
String name,
CloseableThriftHiveMetastoreIface client,
AccessControlHandler accessControlHandler,
ConnectionType connectionType,
long latency); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override ThriftHiveMetastore.Iface getClient(); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override String getDatabasePrefix(); @Override void close(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override String getMetastoreMappingName(); @Override long getLatency(); }### Answer:
@Test public void transformInboundDatabaseName() { assertThat(metaStoreMapping.transformInboundDatabaseName("My_Database"), is("my_database")); }
@Test public void transformInboundDatabaseNameWithoutPrefixReturnsDatabase() { assertThat(metaStoreMapping.transformInboundDatabaseName("no_prefix_My_Database"), is("no_prefix_my_database")); } |
### Question:
MetaStoreMappingImpl implements MetaStoreMapping { @Override public String getDatabasePrefix() { return databasePrefix; } MetaStoreMappingImpl(
String databasePrefix,
String name,
CloseableThriftHiveMetastoreIface client,
AccessControlHandler accessControlHandler,
ConnectionType connectionType,
long latency); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override ThriftHiveMetastore.Iface getClient(); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override String getDatabasePrefix(); @Override void close(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override String getMetastoreMappingName(); @Override long getLatency(); }### Answer:
@Test public void getDatabasePrefix() { assertThat(metaStoreMapping.getDatabasePrefix(), is(DATABASE_PREFIX)); } |
### Question:
AbstractMetaStore { public static FederatedMetaStore newFederatedInstance(String name, String remoteMetaStoreUris) { return new FederatedMetaStore(name, remoteMetaStoreUris); } AbstractMetaStore(); AbstractMetaStore(String name, String remoteMetaStoreUris, AccessControlType accessControlType); AbstractMetaStore(
String name,
String remoteMetaStoreUris,
AccessControlType accessControlType,
List<String> writableDatabaseWhitelist); static FederatedMetaStore newFederatedInstance(String name, String remoteMetaStoreUris); static PrimaryMetaStore newPrimaryInstance(
String name,
String remoteMetaStoreUris,
AccessControlType accessControlType); static PrimaryMetaStore newPrimaryInstance(String name, String remoteMetaStoreUris); String getDatabasePrefix(); void setDatabasePrefix(String databasePrefix); String getName(); void setName(String name); String getRemoteMetaStoreUris(); void setRemoteMetaStoreUris(String remoteMetaStoreUris); MetastoreTunnel getMetastoreTunnel(); void setMetastoreTunnel(MetastoreTunnel metastoreTunnel); ConnectionType getConnectionType(); abstract FederationType getFederationType(); AccessControlType getAccessControlType(); void setAccessControlType(AccessControlType accessControlType); List<String> getWritableDatabaseWhiteList(); void setWritableDatabaseWhiteList(List<String> writableDatabaseWhitelist); long getLatency(); void setLatency(long latency); List<String> getMappedDatabases(); void setMappedDatabases(List<String> mappedDatabases); Map<String, String> getDatabaseNameMapping(); void setDatabaseNameMapping(Map<String, String> databaseNameMapping); @Transient HashBiMap<String, String> getDatabaseNameBiMapping(); @Transient MetaStoreStatus getStatus(); @Transient void setStatus(MetaStoreStatus status); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void newFederatedInstance() { FederatedMetaStore federatedMetaStore = AbstractMetaStore.newFederatedInstance(name, remoteMetaStoreUri); assertThat(federatedMetaStore.getName(), is(name)); assertThat(federatedMetaStore.getRemoteMetaStoreUris(), is(remoteMetaStoreUri)); } |
### Question:
MetaStoreMappingImpl implements MetaStoreMapping { @Override public String getMetastoreMappingName() { return name; } MetaStoreMappingImpl(
String databasePrefix,
String name,
CloseableThriftHiveMetastoreIface client,
AccessControlHandler accessControlHandler,
ConnectionType connectionType,
long latency); @Override String transformOutboundDatabaseName(String databaseName); @Override List<String> transformOutboundDatabaseNameMultiple(String databaseName); @Override ThriftHiveMetastore.Iface getClient(); @Override Database transformOutboundDatabase(Database database); @Override String transformInboundDatabaseName(String databaseName); @Override String getDatabasePrefix(); @Override void close(); @Override boolean isAvailable(); @Override MetaStoreMapping checkWritePermissions(String databaseName); @Override void createDatabase(Database database); @Override String getMetastoreMappingName(); @Override long getLatency(); }### Answer:
@Test public void getMetastoreMappingNameSameAsPrefix() { assertThat(metaStoreMapping.getMetastoreMappingName(), is(NAME)); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.