method2testcases
stringlengths 118
6.63k
|
---|
### Question:
CsnFactory { public Csn newInstance() { int tmpChangeCount; synchronized ( lock ) { long newTimestamp = System.currentTimeMillis(); if ( lastTimestamp == newTimestamp ) { changeCount++; } else { lastTimestamp = newTimestamp; changeCount = 0; } tmpChangeCount = changeCount; } return new Csn( lastTimestamp, tmpChangeCount, replicaId, 0 ); } CsnFactory( int replicaId ); Csn newInstance(); Csn newInstance( long timestamp, int changeCount ); Csn newPurgeCsn( long expirationDate ); void setReplicaId( int replicaId ); }### Answer:
@Test public void testUnique() { int replicaId = 001; CsnFactory defaultCSNFactory = new CsnFactory( replicaId ); Csn[] csns = new Csn[NUM_GENERATES]; for ( int i = 0; i < NUM_GENERATES; i++ ) { csns[i] = defaultCSNFactory.newInstance(); } for ( int i = 0; i < NUM_GENERATES; i++ ) { for ( int j = i + 1; j < NUM_GENERATES; j++ ) { assertFalse( csns[i].equals( csns[j] ) ); } } } |
### Question:
Csn implements Comparable<Csn> { public Csn( long timestamp, int changeCount, int replicaId, int operationNumber ) { this.timestamp = timestamp; this.replicaId = replicaId; this.operationNumber = operationNumber; this.changeCount = changeCount; sdf.setTimeZone( UTC_TIME_ZONE ); } Csn( long timestamp, int changeCount, int replicaId, int operationNumber ); Csn( String value ); Csn( byte[] value ); static boolean isValid( String value ); byte[] getBytes(); long getTimestamp(); int getChangeCount(); int getReplicaId(); int getOperationNumber(); @Override String toString(); @Override int hashCode(); @Override boolean equals( Object o ); @Override int compareTo( Csn csn ); }### Answer:
@Test public void testCSN() { synchronized ( SDF ) { long ts = System.currentTimeMillis(); Csn csn = new Csn( SDF.format( new Date( ts ) ) + "#123456#abc#654321" ); assertEquals( ts / 1000, csn.getTimestamp() / 1000 ); assertEquals( 1193046, csn.getChangeCount() ); assertEquals( 6636321, csn.getOperationNumber() ); assertEquals( 2748, csn.getReplicaId() ); } } |
### Question:
CsnComparator extends LdapComparator<Object> { @Override public int compare( Object csnObj1, Object csnObj2 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_13745_COMPARING_CSN, csnObj1, csnObj2 ) ); } if ( csnObj1 == csnObj2 ) { return 0; } if ( csnObj1 == null ) { return -1; } if ( csnObj2 == null ) { return 1; } String csnStr1; String csnStr2; if ( csnObj1 instanceof Value ) { csnStr1 = ( ( Value ) csnObj1 ).getString(); } else { csnStr1 = csnObj1.toString(); } if ( csnObj2 instanceof Value ) { csnStr2 = ( ( Value ) csnObj2 ).getString(); } else { csnStr2 = csnObj2.toString(); } return csnStr1.compareTo( csnStr2 ); } CsnComparator( String oid ); @Override int compare( Object csnObj1, Object csnObj2 ); }### Answer:
@Test public void testNullCSNs() { assertEquals( 0, comparator.compare( null, null ) ); Csn csn2 = new Csn( System.currentTimeMillis(), 1, 1, 1 ); assertEquals( -1, comparator.compare( null, csn2.toString() ) ); assertEquals( 1, comparator.compare( csn2.toString(), null ) ); }
@Test public void testEqualsCSNs() { long t0 = System.currentTimeMillis(); Csn csn1 = new Csn( t0, 0, 0, 0 ); Csn csn2 = new Csn( t0, 0, 0, 0 ); assertEquals( 0, comparator.compare( csn1.toString(), csn2.toString() ) ); }
@Test public void testDifferentTimeStampCSNs() { long t0 = System.currentTimeMillis(); long t1 = System.currentTimeMillis() + 1000; Csn csn1 = new Csn( t0, 0, 0, 0 ); Csn csn2 = new Csn( t1, 0, 0, 0 ); assertEquals( -1, comparator.compare( csn1.toString(), csn2.toString() ) ); assertEquals( 1, comparator.compare( csn2.toString(), csn1.toString() ) ); }
@Test public void testDifferentChangeCountCSNs() { long t0 = System.currentTimeMillis(); Csn csn1 = new Csn( t0, 0, 0, 0 ); Csn csn2 = new Csn( t0, 1, 0, 0 ); assertEquals( -1, comparator.compare( csn1.toString(), csn2.toString() ) ); assertEquals( 1, comparator.compare( csn2.toString(), csn1.toString() ) ); }
@Test public void testDifferentReplicaIdCSNs() { long t0 = System.currentTimeMillis(); Csn csn1 = new Csn( t0, 0, 0, 0 ); Csn csn2 = new Csn( t0, 0, 1, 0 ); assertEquals( -1, comparator.compare( csn1.toString(), csn2.toString() ) ); assertEquals( 1, comparator.compare( csn2.toString(), csn1.toString() ) ); }
@Test public void testDifferentOperationNumberCSNs() { long t0 = System.currentTimeMillis(); Csn csn1 = new Csn( t0, 0, 0, 0 ); Csn csn2 = new Csn( t0, 0, 0, 1 ); assertEquals( -1, comparator.compare( csn1.toString(), csn2.toString() ) ); assertEquals( 1, comparator.compare( csn2.toString(), csn1.toString() ) ); } |
### Question:
IntegerComparator extends LdapComparator<Object> implements Serializable { @Override public int compare( Object v1, Object v2 ) { if ( v1 == null ) { if ( v2 == null ) { return 0; } else { return -1; } } else if ( v2 == null ) { return 1; } if ( v1 instanceof String ) { return compare( ( String ) v1, ( String ) v2 ); } else if ( v1 instanceof Value ) { return compare( ( ( Value ) v1 ).getString(), ( ( Value ) v2 ).getString() ); } else { return Long.compare( ( Long ) v1, ( Long ) v2 ); } } IntegerComparator( String oid ); @Override int compare( Object v1, Object v2 ); }### Answer:
@Test public void testNullIntegers() { assertEquals( 0, comparator.compare( null, null ) ); String int1 = "1"; assertEquals( -1, comparator.compare( ( String ) null, int1 ) ); assertEquals( 1, comparator.compare( int1, ( String ) null ) ); }
@Test public void testBigIntegerValues() { assertEquals( -1, comparator.compare( null, "1000000000000000000000000" ) ); assertEquals( 1, comparator.compare( "1000000000000000000000000", null ) ); assertEquals( 0, comparator.compare( "1000000000000000000000000", "1000000000000000000000000" ) ); long t0 = System.currentTimeMillis(); for ( int i = 0; i < 10000000; i++ ) { assertEquals( -1, comparator.compare( "9223372036854775805", "9223372036854775806" ) ); } long t1 = System.currentTimeMillis(); System.out.println( "Delta = " + ( t1 - t0 ) ); assertEquals( 1, comparator.compare( "1000000000000000000000001", "1000000000000000000000000" ) ); } |
### Question:
CsnSidComparator extends LdapComparator<String> { public int compare( String sidStr1, String sidStr2 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_13744_COMPARING_CSN_SID, sidStr1, sidStr2 ) ); } if ( sidStr1 == null ) { return ( sidStr2 == null ) ? 0 : -1; } if ( sidStr2 == null ) { return 1; } int sid1 = 0; int sid2; try { sid1 = Integer.parseInt( sidStr1, 16 ); } catch ( NumberFormatException nfe ) { return -1; } try { sid2 = Integer.parseInt( sidStr2, 16 ); } catch ( NumberFormatException nfe ) { return 1; } if ( sid1 > sid2 ) { return 1; } else if ( sid2 > sid1 ) { return -1; } return 0; } CsnSidComparator( String oid ); int compare( String sidStr1, String sidStr2 ); }### Answer:
@Test public void testNullSids() { assertEquals( 0, comparator.compare( null, null ) ); assertEquals( -1, comparator.compare( null, "000" ) ); assertEquals( 1, comparator.compare( "000", null ) ); }
@Test public void testEqualsSids() { assertEquals( 0, comparator.compare( "000", "000" ) ); assertEquals( 0, comparator.compare( "000", "0" ) ); assertEquals( 0, comparator.compare( "fff", "fff" ) ); }
@Test public void testDifferentSids() { assertEquals( -1, comparator.compare( "123", "456" ) ); assertEquals( 1, comparator.compare( "FFF", "000" ) ); assertEquals( 1, comparator.compare( "FFF", "GGG" ) ); } |
### Question:
BitStringComparator extends LdapComparator<String> { public int compare( String bs1, String bs2 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_13743_COMPARING_BITSTRING, bs1, bs2 ) ); } if ( bs1 == bs2 ) { return 0; } if ( ( bs1 == null ) || ( bs2 == null ) ) { return bs1 == null ? -1 : 1; } char[] array1 = bs1.toCharArray(); char[] array2 = bs2.toCharArray(); int pos1 = bs1.indexOf( '1' ); int pos2 = bs2.indexOf( '1' ); if ( pos1 == -1 ) { if ( pos2 == -1 ) { return 0; } else { return -1; } } else if ( pos2 == -1 ) { return 1; } int length1 = array1.length - pos1; int length2 = array2.length - pos2; if ( length1 == length2 ) { for ( int i = 0; i < length1; i++ ) { int i1 = i + pos1; int i2 = i + pos2; if ( array1[i1] < array2[i2] ) { return -1; } else if ( array1[i1] > array2[i2] ) { return 1; } } return 0; } if ( length1 < length2 ) { return -1; } else { return 1; } } BitStringComparator( String oid ); int compare( String bs1, String bs2 ); }### Answer:
@Test public void testNullBitString() { assertEquals( 0, comparator.compare( null, null ) ); assertEquals( -1, comparator.compare( null, "0101B" ) ); assertEquals( -1, comparator.compare( null, "000B" ) ); assertEquals( 1, comparator.compare( "0101B", null ) ); assertEquals( 1, comparator.compare( "111B", null ) ); }
@Test public void testBitStringsEquals() { assertEquals( 0, comparator.compare( "0B", "0B" ) ); assertEquals( 0, comparator.compare( "1B", "1B" ) ); assertEquals( 0, comparator.compare( "101010B", "101010B" ) ); assertEquals( 0, comparator.compare( "00000101010B", "00101010B" ) ); }
@Test public void testBitStringsNotEquals() { assertEquals( -1, comparator.compare( "0B", "1B" ) ); assertEquals( 1, comparator.compare( "1B", "0B" ) ); assertEquals( 1, comparator.compare( "101110B", "101010B" ) ); assertEquals( -1, comparator.compare( "00000101010B", "00111010B" ) ); } |
### Question:
ByteArrayComparator extends LdapComparator<byte[]> { public int compare( byte[] b1, byte[] b2 ) { return Strings.compare( b1, b2 ); } ByteArrayComparator( String oid ); int compare( byte[] b1, byte[] b2 ); }### Answer:
@Test public void testBothNull() { assertEquals( 0, new ByteArrayComparator( null ).compare( null, null ) ); }
@Test public void testB2Null() { assertEquals( 1, new ByteArrayComparator( null ).compare( new byte[0], null ) ); }
@Test public void testB1Null() { assertEquals( -1, new ByteArrayComparator( null ).compare( null, new byte[0] ) ); }
@Test public void testBothEmpty() { assertEquals( 0, new ByteArrayComparator( null ).compare( new byte[0], new byte[0] ) ); }
@Test public void testBothEqualLengthOne() { assertEquals( 0, new ByteArrayComparator( null ).compare( new byte[1], new byte[1] ) ); }
@Test public void testBothEqualLengthTen() { assertEquals( 0, new ByteArrayComparator( null ).compare( new byte[10], new byte[10] ) ); }
@Test public void testB1PrefixOfB2() { byte[] b1 = new byte[] { 0, 1, 2 }; byte[] b2 = new byte[] { 0, 1, 2, 3 }; assertEquals( -1, new ByteArrayComparator( null ).compare( b1, b2 ) ); }
@Test public void testB2PrefixOfB1() { byte[] b1 = new byte[] { 0, 1, 2, 3 }; byte[] b2 = new byte[] { 0, 1, 2 }; assertEquals( 1, new ByteArrayComparator( null ).compare( b1, b2 ) ); }
@Test public void testB1GreaterThanB2() { byte[] b1 = new byte[] { 0, 5 }; byte[] b2 = new byte[] { 0, 1, 2 }; assertEquals( 1, new ByteArrayComparator( null ).compare( b1, b2 ) ); }
@Test public void testB1GreaterThanB2SameLength() { byte[] b1 = new byte[] { 0, 5 }; byte[] b2 = new byte[] { 0, 1 }; assertEquals( 1, new ByteArrayComparator( null ).compare( b1, b2 ) ); }
@Test public void testB2GreaterThanB1() { byte[] b1 = new byte[] { 0, 1, 2 }; byte[] b2 = new byte[] { 0, 5 }; assertEquals( -1, new ByteArrayComparator( null ).compare( b1, b2 ) ); }
@Test public void testB2GreaterThanB1SameLength() { byte[] b1 = new byte[] { 0, 1 }; byte[] b2 = new byte[] { 0, 5 }; assertEquals( -1, new ByteArrayComparator( null ).compare( b1, b2 ) ); } |
### Question:
ObjectIdentifierFirstComponentComparator extends LdapComparator<String> { public int compare( String s1, String s2 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_13748_COMPARING_OBJECT_IDENTIFIER_FIRST_COMPONENT, s1, s2 ) ); } if ( s1 == null ) { return ( s2 == null ) ? 0 : -1; } if ( s2 == null ) { return -1; } if ( s1.equals( s2 ) ) { return 0; } String oid1 = getNumericOid( s1 ); if ( oid1 == null ) { return -1; } String oid2 = getNumericOid( s2 ); if ( oid2 == null ) { return -1; } if ( oid1.equals( oid2 ) ) { return 0; } else { return -1; } } ObjectIdentifierFirstComponentComparator( String oid ); int compare( String s1, String s2 ); }### Answer:
@Test public void testNullObjectIdentifiers() { assertEquals( 0, comparator.compare( null, null ) ); String c2 = "( 1.1 FQCN org.apache.directory.SimpleComparator BYTECODE ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== )"; assertEquals( -1, comparator.compare( null, c2 ) ); assertEquals( -1, comparator.compare( c2, null ) ); }
@Test public void testEqualsObjectIdentifiers() { String c1 = "( 1.1 FQCN org.apache.directory.SimpleComparator BYTECODE ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== )"; String c2 = "( 1.1 fqcn org.apache.directory.SimpleComparator bytecode ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== )"; assertEquals( 0, comparator.compare( c1, c2 ) ); String c3 = "( 1.1 FQCN org.apache.directory.SimpleComparator BYTECODE ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== X-SCHEMA 'system' )"; String c4 = "( 1.1 fqcn org.apache.directory.SimpleComparator bytecode ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== )"; assertEquals( 0, comparator.compare( c3, c4 ) ); }
@Test public void testDifferentObjectIdentifiers() { String c1 = "( 1.1 FQCN org.apache.directory.SimpleComparator BYTECODE ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== )"; String c2 = "( 1.2 fqcn org.apache.directory.SimpleComparator bytecode ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== )"; assertEquals( -1, comparator.compare( c1, c2 ) ); String c3 = "( 1.1 FQCN org.apache.directory.SimpleComparator BYTECODE ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== X-SCHEMA 'system' )"; String c4 = "( 1.1.1 fqcn org.apache.directory.SimpleComparator bytecode ABCDEFGHIJKLMNOPQRSTUVWXYZ+/abcdefghijklmnopqrstuvwxyz0123456789==== )"; assertNotSame( 0, comparator.compare( c3, c4 ) ); } |
### Question:
GeneralizedTime implements Comparable<GeneralizedTime> { @Override public int compareTo( GeneralizedTime other ) { return calendar.compareTo( other.calendar ); } GeneralizedTime( Date date ); GeneralizedTime( Calendar calendar ); GeneralizedTime( long timeInMillis ); GeneralizedTime( String generalizedTime ); String toGeneralizedTime(); String toGeneralizedTimeWithoutFraction(); String toGeneralizedTime( Format format, FractionDelimiter fractionDelimiter, int fractionLength,
TimeZoneFormat timeZoneFormat ); Calendar getCalendar(); @Override String toString(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override int compareTo( GeneralizedTime other ); long getTime(); Date getDate(); int getYear(); int getMonth(); int getDay(); int getHour(); int getMinutes(); int getSeconds(); int getFraction(); static Date getDate( String zuluTime ); }### Answer:
@Test public void testCompareTo() throws ParseException { String gt1 = "20080102121313,999Z"; GeneralizedTime generalizedTime1 = new GeneralizedTime( gt1 ); String gt2 = "20080102121314Z"; GeneralizedTime generalizedTime2 = new GeneralizedTime( gt2 ); String gt3 = "20080102121314,001Z"; GeneralizedTime generalizedTime3 = new GeneralizedTime( gt3 ); assertTrue( generalizedTime1.compareTo( generalizedTime2 ) < 0 ); assertTrue( generalizedTime1.compareTo( generalizedTime3 ) < 0 ); assertTrue( generalizedTime2.compareTo( generalizedTime3 ) < 0 ); assertTrue( generalizedTime2.compareTo( generalizedTime1 ) > 0 ); assertTrue( generalizedTime3.compareTo( generalizedTime1 ) > 0 ); assertTrue( generalizedTime3.compareTo( generalizedTime2 ) > 0 ); assertTrue( generalizedTime1.compareTo( generalizedTime1 ) == 0 ); assertTrue( generalizedTime2.compareTo( generalizedTime2 ) == 0 ); assertTrue( generalizedTime3.compareTo( generalizedTime3 ) == 0 ); } |
### Question:
WordComparator extends LdapComparator<String> { public int compare( String value, String assertion ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_13749_COMPARING_STRING, value, assertion ) ); } if ( value == assertion ) { return 0; } if ( ( value == null ) || ( assertion == null ) ) { return ( assertion == null ) ? 1 : -1; } String trimmedAssertion = Strings.trim( assertion ); int pos = value.indexOf( trimmedAssertion ); if ( pos != -1 ) { int assertionLength = trimmedAssertion.length(); if ( assertionLength == value.length() ) { return 0; } if ( pos == 0 ) { char after = value.charAt( assertionLength ); if ( !Character.isLetterOrDigit( after ) ) { return 0; } else { return -1; } } if ( pos + assertionLength == value.length() ) { char before = value.charAt( value.length() - assertionLength - 1 ); if ( !Character.isLetterOrDigit( before ) ) { return 0; } else { return -1; } } char before = value.charAt( value.length() - assertionLength ); char after = value.charAt( assertionLength ); if ( Character.isLetterOrDigit( after ) ) { return -1; } if ( !Character.isLetterOrDigit( before ) ) { return -1; } return 0; } return -1; } WordComparator( String oid ); int compare( String value, String assertion ); }### Answer:
@Test public void testNullWordss() { assertEquals( 0, comparator.compare( null, null ) ); assertEquals( -1, comparator.compare( null, " abc " ) ); assertEquals( 1, comparator.compare( " abc def ghi ", null ) ); }
@Test public void testEqualsWords() { assertEquals( 0, comparator.compare( "abc", "abc" ) ); assertEquals( 0, comparator.compare( "abc", " abc " ) ); assertEquals( 0, comparator.compare( "abc def ghi", "def" ) ); assertEquals( 0, comparator.compare( "abc def ghi", " def " ) ); assertEquals( 0, comparator.compare( "abc def ghi", "abc" ) ); assertEquals( 0, comparator.compare( "abc def ghi", "ghi" ) ); }
@Test public void testNotEqualsWords() { assertEquals( -1, comparator.compare( "abc", "" ) ); assertEquals( -1, comparator.compare( "abc", "ab" ) ); assertEquals( -1, comparator.compare( "abc", " ab " ) ); assertEquals( -1, comparator.compare( "abc def ghi", "dkf" ) ); assertEquals( -1, comparator.compare( "abc def ghi", " dkf " ) ); assertEquals( -1, comparator.compare( "abc def ghi", "hi" ) ); assertEquals( -1, comparator.compare( "abc def ghi", "e" ) ); } |
### Question:
BooleanComparator extends LdapComparator<String> { public int compare( String b1, String b2 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_13752_COMPARING_BOOLEAN, b1, b2 ) ); } if ( b1 == b2 ) { return 0; } if ( ( b1 == null ) || ( b2 == null ) ) { return b1 == null ? -1 : 1; } boolean boolean1 = Boolean.parseBoolean( b1 ); boolean boolean2 = Boolean.parseBoolean( b2 ); if ( boolean1 == boolean2 ) { return 0; } return boolean1 ? 1 : -1; } BooleanComparator( String oid ); int compare( String b1, String b2 ); }### Answer:
@Test public void testNullBooleans() { assertEquals( 0, comparator.compare( null, null ) ); assertEquals( -1, comparator.compare( null, "TRUE" ) ); assertEquals( -1, comparator.compare( null, "FALSE" ) ); assertEquals( 1, comparator.compare( "TRUE", null ) ); assertEquals( 1, comparator.compare( "FALSE", null ) ); }
@Test public void testBooleans() { assertEquals( 0, comparator.compare( "TRUE", "TRUE" ) ); assertEquals( 0, comparator.compare( "FALSE", "FALSE" ) ); assertEquals( -1, comparator.compare( "FALSE", "TRUE" ) ); assertEquals( 1, comparator.compare( "TRUE", "FALSE" ) ); String b1 = "TRUE"; String b2 = "true"; assertEquals( 0, comparator.compare( b1, Strings.upperCase( b2 ) ) ); } |
### Question:
TelephoneNumberComparator extends LdapComparator<String> { public int compare( String telephoneNumber1, String telephoneNumber2 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_13750_COMPARING_TELEPHONE_NUMBER, telephoneNumber1, telephoneNumber2 ) ); } if ( telephoneNumber1 == null ) { return ( telephoneNumber2 == null ) ? 0 : -1; } if ( telephoneNumber2 == null ) { return 1; } String strippedTelephoneNumber1 = strip( telephoneNumber1 ); String strippedTelephoneNumber2 = strip( telephoneNumber2 ); return strippedTelephoneNumber1.compareToIgnoreCase( strippedTelephoneNumber2 ); } TelephoneNumberComparator( String oid ); int compare( String telephoneNumber1, String telephoneNumber2 ); }### Answer:
@Test public void testNullTelephoneNumbers() { String tel1 = null; String tel2 = null; assertEquals( 0, comparator.compare( tel1, tel2 ) ); tel2 = "abc"; assertEquals( -1, comparator.compare( tel1, tel2 ) ); String tel3 = null; assertEquals( 1, comparator.compare( tel2, tel3 ) ); }
@Test public void testEmptyTelephoneNumbers() { String tel1 = ""; String tel2 = ""; assertEquals( 0, comparator.compare( tel1, tel2 ) ); tel2 = "abc"; assertTrue( comparator.compare( tel1, tel2 ) < 0 ); String tel3 = ""; assertTrue( comparator.compare( tel2, tel3 ) > 0 ); }
@Test public void testSimpleTelephoneNumbers() { String tel1 = "01 02 03 04 05"; String tel2 = "01 02 03 04 05"; assertEquals( 0, comparator.compare( tel1, tel2 ) ); tel2 = "0102030405"; assertEquals( 0, comparator.compare( tel1, tel2 ) ); }
@Test public void testComplexTelephoneNumbers() { String tel1 = " + 33 1 01-02-03-04-05 "; String tel2 = "+3310102030405"; assertEquals( 0, comparator.compare( tel1, tel2 ) ); tel1 = "1-801-555-1212"; tel2 = "18015551212"; assertEquals( 0, comparator.compare( tel1, tel2 ) ); assertEquals( 0, comparator.compare( "1 801 555 1212", tel1 ) ); assertEquals( 0, comparator.compare( "1 801 555 1212", tel2 ) ); } |
### Question:
GeneralizedTime implements Comparable<GeneralizedTime> { @Override public boolean equals( Object obj ) { if ( obj instanceof GeneralizedTime ) { GeneralizedTime other = ( GeneralizedTime ) obj; return calendar.equals( other.calendar ); } else { return false; } } GeneralizedTime( Date date ); GeneralizedTime( Calendar calendar ); GeneralizedTime( long timeInMillis ); GeneralizedTime( String generalizedTime ); String toGeneralizedTime(); String toGeneralizedTimeWithoutFraction(); String toGeneralizedTime( Format format, FractionDelimiter fractionDelimiter, int fractionLength,
TimeZoneFormat timeZoneFormat ); Calendar getCalendar(); @Override String toString(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override int compareTo( GeneralizedTime other ); long getTime(); Date getDate(); int getYear(); int getMonth(); int getDay(); int getHour(); int getMinutes(); int getSeconds(); int getFraction(); static Date getDate( String zuluTime ); }### Answer:
@Test public void testEquals() throws ParseException { String gt1 = "20080102121314Z"; GeneralizedTime generalizedTime1 = new GeneralizedTime( gt1 ); String gt2 = "20080102121314Z"; GeneralizedTime generalizedTime2 = new GeneralizedTime( gt2 ); String gt3 = "20080102121314,001Z"; GeneralizedTime generalizedTime3 = new GeneralizedTime( gt3 ); assertTrue( generalizedTime1.equals( generalizedTime2 ) ); assertFalse( generalizedTime1.equals( generalizedTime3 ) ); assertFalse( generalizedTime1.equals( null ) ); } |
### Question:
NameForm extends AbstractSchemaObject { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } NameForm( String oid ); String getStructuralObjectClassOid(); ObjectClass getStructuralObjectClass(); void setStructuralObjectClassOid( String structuralObjectClassOid ); void setStructuralObjectClass( ObjectClass structuralObjectClass ); List<String> getMustAttributeTypeOids(); List<AttributeType> getMustAttributeTypes(); void setMustAttributeTypeOids( List<String> mustAttributeTypeOids ); void setMustAttributeTypes( List<AttributeType> mustAttributeTypes ); void addMustAttributeTypeOids( String oid ); void addMustAttributeTypes( AttributeType attributeType ); List<String> getMayAttributeTypeOids(); List<AttributeType> getMayAttributeTypes(); void setMayAttributeTypeOids( List<String> mayAttributeTypeOids ); void setMayAttributeTypes( List<AttributeType> mayAttributeTypes ); void addMayAttributeTypeOids( String oid ); void addMayAttributeTypes( AttributeType attributeType ); @Override String toString(); @Override NameForm copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = nameForm.toString(); assertNotNull( string ); assertTrue( string.startsWith( "nameform (" ) ); assertTrue( string.contains( " NAME " ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tOC" ) ); assertTrue( string.contains( "\n\tMUST" ) ); assertTrue( string.contains( "\n\tMAY" ) ); } |
### Question:
MatchingRule extends AbstractSchemaObject { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } MatchingRule( String oid ); LdapSyntax getSyntax(); void setSyntax( LdapSyntax ldapSyntax ); String getSyntaxOid(); void setSyntaxOid( String oid ); LdapComparator<? super Object> getLdapComparator(); @SuppressWarnings("unchecked") void setLdapComparator( LdapComparator<?> ldapComparator ); Normalizer getNormalizer(); void setNormalizer( Normalizer normalizer ); @Override String toString(); @Override MatchingRule copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = matchingRule.toString(); assertNotNull( string ); assertTrue( string.startsWith( "matchingrule (" ) ); assertTrue( string.contains( " NAME " ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tSYNTAX " ) ); } |
### Question:
LdapSyntax extends AbstractSchemaObject { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } LdapSyntax( String oid ); LdapSyntax( String oid, String description ); LdapSyntax( String oid, String description, boolean isHumanReadable ); boolean isHumanReadable(); void setHumanReadable( boolean humanReadable ); SyntaxChecker getSyntaxChecker(); void setSyntaxChecker( SyntaxChecker syntaxChecker ); void updateSyntaxChecker( SyntaxChecker newSyntaxChecker ); @Override String toString(); @Override LdapSyntax copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = ldapSyntax.toString(); assertNotNull( string ); assertTrue( string.startsWith( "ldapsyntax (" ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tX-NOT-HUMAN-READABLE " ) ); } |
### Question:
GeneralizedTime implements Comparable<GeneralizedTime> { public Date getDate() { return calendar.getTime(); } GeneralizedTime( Date date ); GeneralizedTime( Calendar calendar ); GeneralizedTime( long timeInMillis ); GeneralizedTime( String generalizedTime ); String toGeneralizedTime(); String toGeneralizedTimeWithoutFraction(); String toGeneralizedTime( Format format, FractionDelimiter fractionDelimiter, int fractionLength,
TimeZoneFormat timeZoneFormat ); Calendar getCalendar(); @Override String toString(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override int compareTo( GeneralizedTime other ); long getTime(); Date getDate(); int getYear(); int getMonth(); int getDay(); int getHour(); int getMinutes(); int getSeconds(); int getFraction(); static Date getDate( String zuluTime ); }### Answer:
@Test public void fractionCloseToOne() throws ParseException { GeneralizedTime close = new GeneralizedTime( "20000101000000.9994Z" ); assertThat( close.getDate(), is( equalTo( format.parse( "01/01/2000 00:00:00.999 GMT" ) ) ) ); GeneralizedTime closer = new GeneralizedTime( "20000101000000.9995Z" ); assertThat( closer.getDate(), is( equalTo( format.parse( "01/01/2000 00:00:00.999 GMT" ) ) ) ); GeneralizedTime larger = new GeneralizedTime( "20000101000000.9Z" ); assertThat( larger.getDate(), is( equalTo( format.parse( "01/01/2000 00:00:00.900 GMT" ) ) ) ); } |
### Question:
MethodUtils { public static Method getAssignmentCompatibleMethod( Class<?> clazz, String candidateMethodName, Class<?>[] candidateParameterTypes ) throws NoSuchMethodException { if ( LOG.isDebugEnabled() ) { StringBuilder buf = new StringBuilder(); buf.append( "call to getAssignmentCompatibleMethod(): \n\tclazz = " ); buf.append( clazz.getName() ); buf.append( "\n\tcandidateMethodName = " ); buf.append( candidateMethodName ); buf.append( "\n\tcandidateParameterTypes = " ); for ( Class<?> argClass : candidateParameterTypes ) { buf.append( "\n\t\t" ); buf.append( argClass.getName() ); } if ( LOG.isDebugEnabled() ) { LOG.debug( buf.toString() ); } } try { Method exactMethod = clazz.getMethod( candidateMethodName, candidateParameterTypes ); if ( exactMethod != null ) { return exactMethod; } } catch ( Exception e ) { if ( LOG.isInfoEnabled() ) { LOG.info( I18n.msg( I18n.MSG_17009_NO_EXACT_MATCH, candidateMethodName, e ) ); } } Method[] methods = clazz.getMethods(); for ( int mx = 0; mx < methods.length; mx++ ) { if ( !candidateMethodName.equals( methods[mx].getName() ) ) { continue; } Class<?>[] parameterTypes = methods[mx].getParameterTypes(); if ( parameterTypes.length != candidateParameterTypes.length ) { continue; } for ( int px = 0; px < parameterTypes.length; px++ ) { if ( !parameterTypes[px].isAssignableFrom( candidateParameterTypes[px] ) ) { break; } } return methods[mx]; } throw new NoSuchMethodException( clazz.getName() + "." + candidateMethodName + "(" + Arrays.toString( candidateParameterTypes ) + ")" ); } private MethodUtils(); static Method getAssignmentCompatibleMethod( Class<?> clazz,
String candidateMethodName,
Class<?>[] candidateParameterTypes
); }### Answer:
@Test public void testSameBehaviourOfStandardGetMethod() { Method m1 = null; Method m2 = null; try { m1 = TestClass.class.getMethod( "methodA", new Class[] { String.class } ); } catch ( SecurityException e ) { e.printStackTrace(); } catch ( NoSuchMethodException e ) { e.printStackTrace(); } try { m2 = MethodUtils.getAssignmentCompatibleMethod( TestClass.class, "methodA", new Class[] { String.class } ); } catch ( NoSuchMethodException e ) { e.printStackTrace(); } assertEquals( m1, m2 ); }
@Test public void testNewBehaviourOfAssignmentCompatibleGetMethod() { Method m2 = null; try { TestClass.class.getMethod( "methodB", new Class[] { ArrayList.class } ); fail( "We should not have come here." ); } catch ( SecurityException e ) { e.printStackTrace(); } catch ( NoSuchMethodException e ) { assertNotNull( e ); } try { m2 = MethodUtils.getAssignmentCompatibleMethod( TestClass.class, "methodB", new Class[] { ArrayList.class } ); } catch ( NoSuchMethodException e ) { e.printStackTrace(); } assertNotNull( m2 ); } |
### Question:
SchemaUtils { static StringBuilder renderQDescrs( StringBuilder buf, List<String> qdescrs ) { if ( ( qdescrs == null ) || qdescrs.isEmpty() ) { return buf; } if ( qdescrs.size() == 1 ) { buf.append( '\'' ).append( qdescrs.get( 0 ) ).append( '\'' ); } else { buf.append( "( " ); for ( String qdescr : qdescrs ) { buf.append( '\'' ).append( qdescr ).append( "' " ); } buf.append( ")" ); } return buf; } private SchemaUtils(); static Entry getTargetEntry( List<? extends Modification> mods, Entry entry ); static StringBuilder render( StringBuilder buf, List<String> qdescrs ); static StringBuilder render( ObjectClass[] ocs ); static StringBuilder render( StringBuilder buf, ObjectClass[] ocs ); static StringBuilder render( AttributeType[] ats ); static StringBuilder render( StringBuilder buf, AttributeType[] ats ); static StringBuilder render( Map<String, List<String>> extensions ); static String render( LoadableSchemaObject description ); static String stripOptions( String attributeId ); static Set<String> getOptions( String attributeId ); static byte[] uuidToBytes( UUID uuid ); static boolean isAttributeNameValid( String attributeName ); }### Answer:
@Test public void testRenderQdescrs() { assertEquals( "", SchemaUtils.renderQDescrs( new StringBuilder(), ( List<String> ) null ).toString() ); assertEquals( "", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] {} ) ).toString() ); assertEquals( "'name1'", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] { "name1" } ) ).toString() ); assertEquals( "( 'name1' 'name2' )", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] { "name1", "name2" } ) ).toString() ); assertEquals( "( 'name1' 'name2' 'name3' )", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] { "name1", "name2", "name3" } ) ).toString() ); assertEquals( "", SchemaUtils.renderQDescrs( new StringBuilder(), ( List<String> ) null ).toString() ); assertEquals( "", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] {} ) ).toString() ); assertEquals( "'name1'", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] { "name1" } ) ).toString() ); assertEquals( "( 'name1' 'name2' )", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] { "name1", "name2" } ) ).toString() ); assertEquals( "( 'name1' 'name2' 'name3' )", SchemaUtils.renderQDescrs( new StringBuilder(), Arrays.asList( new String[] { "name1", "name2", "name3" } ) ).toString() ); } |
### Question:
SchemaUtils { public static boolean isAttributeNameValid( String attributeName ) { if ( Strings.isEmpty( attributeName ) ) { return false; } boolean descr; boolean zero = false; boolean dot = false; char c = attributeName.charAt( 0 ); if ( ( ( c >= 'a' ) && ( c <= 'z' ) ) || ( ( c >= 'A' ) && ( c <= 'Z' ) ) ) { descr = true; } else if ( ( c >= '0' ) && ( c <= '9' ) ) { descr = false; zero = c == '0'; } else { return false; } for ( int i = 1; i < attributeName.length(); i++ ) { c = attributeName.charAt( i ); if ( descr ) { if ( ( ( c < 'a' ) || ( c > 'z' ) ) && ( ( c < 'A' ) || ( c > 'Z' ) ) && ( ( c < '0' ) || ( c > '9' ) ) && ( c != '-' ) && ( c != '_' ) ) { return false; } } else { if ( c == '.' ) { if ( dot ) { return false; } dot = true; zero = false; } else if ( ( c >= '0' ) && ( c <= '9' ) ) { dot = false; if ( zero ) { return false; } else if ( c == '0' ) { zero = true; } } else { return false; } } } return true; } private SchemaUtils(); static Entry getTargetEntry( List<? extends Modification> mods, Entry entry ); static StringBuilder render( StringBuilder buf, List<String> qdescrs ); static StringBuilder render( ObjectClass[] ocs ); static StringBuilder render( StringBuilder buf, ObjectClass[] ocs ); static StringBuilder render( AttributeType[] ats ); static StringBuilder render( StringBuilder buf, AttributeType[] ats ); static StringBuilder render( Map<String, List<String>> extensions ); static String render( LoadableSchemaObject description ); static String stripOptions( String attributeId ); static Set<String> getOptions( String attributeId ); static byte[] uuidToBytes( UUID uuid ); static boolean isAttributeNameValid( String attributeName ); }### Answer:
@Test public void testIsAttributeNameValid() { assertFalse( SchemaUtils.isAttributeNameValid( null ) ); assertFalse( SchemaUtils.isAttributeNameValid( "" ) ); assertFalse( SchemaUtils.isAttributeNameValid( " " ) ); assertTrue( SchemaUtils.isAttributeNameValid( "a" ) ); assertTrue( SchemaUtils.isAttributeNameValid( "ObjectClass-text_test123" ) ); assertFalse( SchemaUtils.isAttributeNameValid( "-text_test123" ) ); assertFalse( SchemaUtils.isAttributeNameValid( "text_te&st123" ) ); assertFalse( SchemaUtils.isAttributeNameValid( "text_te st123" ) ); assertTrue( SchemaUtils.isAttributeNameValid( "0" ) ); assertTrue( SchemaUtils.isAttributeNameValid( "0" ) ); assertFalse( SchemaUtils.isAttributeNameValid( "00.1.2.3" ) ); assertFalse( SchemaUtils.isAttributeNameValid( "0.1.2..3" ) ); assertFalse( SchemaUtils.isAttributeNameValid( "0.01.2.3" ) ); } |
### Question:
SchemaObjectSorter { public static Iterable<AttributeType> hierarchicalOrdered( List<AttributeType> attributeTypes ) { return new SchemaObjectIterable<>( attributeTypes, new ReferenceCallback<AttributeType>() { @Override public Collection<String> getSuperiorOids( AttributeType at ) { return Collections.singleton( at.getSuperiorOid() ); } } ); } private SchemaObjectSorter(); static Iterable<AttributeType> hierarchicalOrdered( List<AttributeType> attributeTypes ); static Iterable<ObjectClass> sortObjectClasses( List<ObjectClass> objectClasses ); }### Answer:
@Test public void testSortAttributeTypesAlreadySorted() { List<AttributeType> attributeTypes = new ArrayList<AttributeType>(); addAttributeType( attributeTypes, "1.1.1", "att1", null ); addAttributeType( attributeTypes, "1.1.2", "att2", "att1" ); addAttributeType( attributeTypes, "1.1.3", "att3", "att2" ); addAttributeType( attributeTypes, "1.1.4", "att4", "att3" ); addAttributeType( attributeTypes, "1.1.5", "att5", "att1" ); addAttributeType( attributeTypes, "1.1.6", "att6", null ); addAttributeType( attributeTypes, "1.1.7", "att7", "other" ); Iterable<AttributeType> sorted = SchemaObjectSorter.hierarchicalOrdered( attributeTypes ); assertHierarchicalOrderAT( sorted ); }
@Test public void testSortAttributeTypesShuffled() { List<String> oids = Arrays.asList( "1.1.1", "1.1.2", "1.1.3", "1.1.4", "1.1.5", "1.1.6", "1.1.7" ); for ( int i = 0; i < 1000; i++ ) { Collections.shuffle( oids ); Iterator<String> oidIterator = oids.iterator(); List<AttributeType> attributeTypes = new ArrayList<AttributeType>(); addAttributeType( attributeTypes, oidIterator.next(), "att1", null ); addAttributeType( attributeTypes, oidIterator.next(), "aTT2", "att1" ); addAttributeType( attributeTypes, oidIterator.next(), "att3", "att2" ); addAttributeType( attributeTypes, oidIterator.next(), "att4", "atT3" ); addAttributeType( attributeTypes, oidIterator.next(), "att5", "aTt1" ); addAttributeType( attributeTypes, oidIterator.next(), "att6", null ); addAttributeType( attributeTypes, oidIterator.next(), "att7", "other" ); Iterable<AttributeType> sorted = SchemaObjectSorter.hierarchicalOrdered( attributeTypes ); assertHierarchicalOrderAT( sorted ); } }
@Test public void testSortAttributeTypesLoop() { List<AttributeType> attributeTypes = new ArrayList<AttributeType>(); addAttributeType( attributeTypes, "1.1.1", "att1", "att4" ); addAttributeType( attributeTypes, "1.1.2", "att2", "att1" ); addAttributeType( attributeTypes, "1.1.3", "att3", "att2" ); addAttributeType( attributeTypes, "1.1.4", "att4", "att3" ); Iterable<AttributeType> sorted = SchemaObjectSorter.hierarchicalOrdered( attributeTypes ); assertThrows( IllegalStateException.class, () -> { sorted.iterator().next(); } ); } |
### Question:
SchemaObjectSorter { public static Iterable<ObjectClass> sortObjectClasses( List<ObjectClass> objectClasses ) { return new SchemaObjectIterable<>( objectClasses, new ReferenceCallback<ObjectClass>() { @Override public Collection<String> getSuperiorOids( ObjectClass oc ) { return oc.getSuperiorOids(); } } ); } private SchemaObjectSorter(); static Iterable<AttributeType> hierarchicalOrdered( List<AttributeType> attributeTypes ); static Iterable<ObjectClass> sortObjectClasses( List<ObjectClass> objectClasses ); }### Answer:
@Test public void testSortObjectClassesAlreadySorted() { List<ObjectClass> objectClasses = new ArrayList<ObjectClass>(); addObjectClass( objectClasses, "1.2.1", "oc1" ); addObjectClass( objectClasses, "1.2.2", "OC2", "oc1" ); addObjectClass( objectClasses, "1.2.3", "oc3", "oC2" ); addObjectClass( objectClasses, "1.2.4", "oc4" ); addObjectClass( objectClasses, "1.2.5", "oc5", "Oc2", "oC4" ); addObjectClass( objectClasses, "1.2.6", "oc6", "other" ); Iterable<ObjectClass> sorted = SchemaObjectSorter.sortObjectClasses( objectClasses ); assertHierarchicalOrderOC( sorted ); }
@Test public void testSortObjectClassesShuffled() { List<String> oids = Arrays.asList( "1.1.1", "1.1.2", "1.1.3", "1.1.4", "1.1.5", "1.1.6" ); for ( int i = 0; i < 1000; i++ ) { Collections.shuffle( oids ); Iterator<String> oidIterator = oids.iterator(); List<ObjectClass> objectClasses = new ArrayList<ObjectClass>(); addObjectClass( objectClasses, oidIterator.next(), "oc1" ); addObjectClass( objectClasses, oidIterator.next(), "OC2", "oc1" ); addObjectClass( objectClasses, oidIterator.next(), "oc3", "Oc2" ); addObjectClass( objectClasses, oidIterator.next(), "oc4" ); addObjectClass( objectClasses, oidIterator.next(), "oc5", "oC2", "OC4" ); addObjectClass( objectClasses, oidIterator.next(), "oc6", "other" ); Iterable<ObjectClass> sorted = SchemaObjectSorter.sortObjectClasses( objectClasses ); assertHierarchicalOrderOC( sorted ); } }
@Test public void testSortObjectClassesLoop() { List<ObjectClass> objectClasses = new ArrayList<ObjectClass>(); addObjectClass( objectClasses, "1.2.1", "oc1", "oc3" ); addObjectClass( objectClasses, "1.2.2", "oc2", "oc1" ); addObjectClass( objectClasses, "1.2.3", "oc3", "oc2" ); Iterable<ObjectClass> sorted = SchemaObjectSorter.sortObjectClasses( objectClasses ); assertThrows( IllegalStateException.class, () -> { sorted.iterator().next(); } ); } |
### Question:
ObjectClass extends AbstractSchemaObject { @Override public boolean equals( Object o ) { if ( !super.equals( o ) ) { return false; } if ( !( o instanceof ObjectClass ) ) { return false; } ObjectClass that = ( ObjectClass ) o; if ( objectClassType != that.objectClassType ) { return false; } if ( superiorOids.size() != that.superiorOids.size() ) { return false; } for ( String oid : superiorOids ) { if ( !that.superiorOids.contains( oid ) ) { return false; } } for ( String oid : that.superiorOids ) { if ( !superiorOids.contains( oid ) ) { return false; } } if ( superiors.size() != that.superiors.size() ) { return false; } for ( ObjectClass superior : superiors ) { if ( !that.superiors.contains( superior ) ) { return false; } } for ( ObjectClass superior : that.superiors ) { if ( !superiors.contains( superior ) ) { return false; } } if ( mayAttributeTypeOids.size() != that.mayAttributeTypeOids.size() ) { return false; } for ( String oid : mayAttributeTypeOids ) { if ( !that.mayAttributeTypeOids.contains( oid ) ) { return false; } } for ( String oid : that.mayAttributeTypeOids ) { if ( !mayAttributeTypeOids.contains( oid ) ) { return false; } } if ( mayAttributeTypes.size() != that.mayAttributeTypes.size() ) { return false; } for ( AttributeType oid : mayAttributeTypes ) { if ( !that.mayAttributeTypes.contains( oid ) ) { return false; } } for ( AttributeType oid : that.mayAttributeTypes ) { if ( !mayAttributeTypes.contains( oid ) ) { return false; } } if ( mustAttributeTypeOids.size() != that.mustAttributeTypeOids.size() ) { return false; } for ( String oid : mustAttributeTypeOids ) { if ( !that.mustAttributeTypeOids.contains( oid ) ) { return false; } } for ( String oid : that.mustAttributeTypeOids ) { if ( !mustAttributeTypeOids.contains( oid ) ) { return false; } } if ( mustAttributeTypes.size() != that.mustAttributeTypes.size() ) { return false; } for ( AttributeType oid : mustAttributeTypes ) { if ( !that.mustAttributeTypes.contains( oid ) ) { return false; } } for ( AttributeType oid : that.mustAttributeTypes ) { if ( !mustAttributeTypes.contains( oid ) ) { return false; } } return true; } ObjectClass( String oid ); List<String> getMayAttributeTypeOids(); List<AttributeType> getMayAttributeTypes(); void addMayAttributeTypeOids( String... oids ); void addMayAttributeTypes( AttributeType... attributeTypes ); void setMayAttributeTypeOids( List<String> mayAttributeTypeOids ); void setMayAttributeTypes( List<AttributeType> mayAttributeTypes ); List<String> getMustAttributeTypeOids(); List<AttributeType> getMustAttributeTypes(); void addMustAttributeTypeOids( String... oids ); void addMustAttributeTypes( AttributeType... attributeTypes ); void setMustAttributeTypeOids( List<String> mustAttributeTypeOids ); void setMustAttributeTypes( List<AttributeType> mustAttributeTypes ); List<ObjectClass> getSuperiors(); List<String> getSuperiorOids(); void addSuperiorOids( String... oids ); void addSuperior( ObjectClass... objectClasses ); void setSuperiors( List<ObjectClass> superiors ); void setSuperiorOids( List<String> superiorOids ); ObjectClassTypeEnum getType(); void setType( ObjectClassTypeEnum objectClassType ); boolean isStructural(); boolean isAbstract(); boolean isAuxiliary(); @Override String toString(); @Override ObjectClass copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testEqualsNull() throws Exception { assertFalse( objectClassA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( objectClassA.equals( objectClassC ) ); assertFalse( objectClassC.equals( objectClassA ) ); } |
### Question:
ObjectClass extends AbstractSchemaObject { @Override public int hashCode() { int hash = h; hash = hash * 17 + objectClassType.getValue(); int tempHash = 0; for ( String oid : superiorOids ) { tempHash += oid.hashCode(); } hash = hash * 17 + tempHash; tempHash = 0; for ( String may : mayAttributeTypeOids ) { tempHash += may.hashCode(); } hash = hash * 17 + tempHash; tempHash = 0; for ( String must : mustAttributeTypeOids ) { tempHash += must.hashCode(); } hash = hash * 17 + tempHash; return hash; } ObjectClass( String oid ); List<String> getMayAttributeTypeOids(); List<AttributeType> getMayAttributeTypes(); void addMayAttributeTypeOids( String... oids ); void addMayAttributeTypes( AttributeType... attributeTypes ); void setMayAttributeTypeOids( List<String> mayAttributeTypeOids ); void setMayAttributeTypes( List<AttributeType> mayAttributeTypes ); List<String> getMustAttributeTypeOids(); List<AttributeType> getMustAttributeTypes(); void addMustAttributeTypeOids( String... oids ); void addMustAttributeTypes( AttributeType... attributeTypes ); void setMustAttributeTypeOids( List<String> mustAttributeTypeOids ); void setMustAttributeTypes( List<AttributeType> mustAttributeTypes ); List<ObjectClass> getSuperiors(); List<String> getSuperiorOids(); void addSuperiorOids( String... oids ); void addSuperior( ObjectClass... objectClasses ); void setSuperiors( List<ObjectClass> superiors ); void setSuperiorOids( List<String> superiorOids ); ObjectClassTypeEnum getType(); void setType( ObjectClassTypeEnum objectClassType ); boolean isStructural(); boolean isAbstract(); boolean isAuxiliary(); @Override String toString(); @Override ObjectClass copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testHashCodeReflexive() throws Exception { assertEquals( objectClassA.hashCode(), objectClassA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( objectClassA.hashCode(), objectClassACopy.hashCode() ); assertEquals( objectClassACopy.hashCode(), objectClassA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( objectClassA.hashCode(), objectClassACopy.hashCode() ); assertEquals( objectClassACopy.hashCode(), objectClassB.hashCode() ); assertEquals( objectClassA.hashCode(), objectClassB.hashCode() ); } |
### Question:
ObjectClass extends AbstractSchemaObject { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } ObjectClass( String oid ); List<String> getMayAttributeTypeOids(); List<AttributeType> getMayAttributeTypes(); void addMayAttributeTypeOids( String... oids ); void addMayAttributeTypes( AttributeType... attributeTypes ); void setMayAttributeTypeOids( List<String> mayAttributeTypeOids ); void setMayAttributeTypes( List<AttributeType> mayAttributeTypes ); List<String> getMustAttributeTypeOids(); List<AttributeType> getMustAttributeTypes(); void addMustAttributeTypeOids( String... oids ); void addMustAttributeTypes( AttributeType... attributeTypes ); void setMustAttributeTypeOids( List<String> mustAttributeTypeOids ); void setMustAttributeTypes( List<AttributeType> mustAttributeTypes ); List<ObjectClass> getSuperiors(); List<String> getSuperiorOids(); void addSuperiorOids( String... oids ); void addSuperior( ObjectClass... objectClasses ); void setSuperiors( List<ObjectClass> superiors ); void setSuperiorOids( List<String> superiorOids ); ObjectClassTypeEnum getType(); void setType( ObjectClassTypeEnum objectClassType ); boolean isStructural(); boolean isAbstract(); boolean isAuxiliary(); @Override String toString(); @Override ObjectClass copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = objectClass.toString(); assertNotNull( string ); assertTrue( string.startsWith( "objectclass (" ) ); assertTrue( string.contains( " NAME " ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tSUP " ) ); assertTrue( string.contains( "\n\tSTRUCTURAL" ) ); assertTrue( string.contains( "\n\tMUST" ) ); assertTrue( string.contains( "\n\tMAY" ) ); assertTrue( string.endsWith( " )" ) ); } |
### Question:
OidRegistry implements Iterable<T> { public OidRegistry<T> copy() { OidRegistry<T> copy = new OidRegistry<>(); copy.byOid = new HashMap<>(); return copy; } boolean contains( String oid ); String getPrimaryName( String oid ); T getSchemaObject( String oid ); List<String> getNameSet( String oid ); Iterator<String> iteratorOids(); @Override Iterator<T> iterator(); boolean isRelaxed(); boolean isStrict(); void setRelaxed(); void setStrict(); SchemaErrorHandler getErrorHandler(); void setErrorHandler( SchemaErrorHandler errorHandler ); void register( T schemaObject ); void unregister( String oid ); OidRegistry<T> copy(); int size(); void clear(); @Override String toString(); }### Answer:
@Test public void testCopy() throws Exception { } |
### Question:
AttributeType extends AbstractSchemaObject implements Cloneable { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } AttributeType( String oid ); boolean isSingleValued(); void setSingleValued( boolean singleValued ); boolean isUserModifiable(); void setUserModifiable( boolean userModifiable ); boolean isCollective(); void setCollective( boolean collective ); boolean isRelaxed(); void setRelaxed( boolean isRelaxed ); UsageEnum getUsage(); void setUsage( UsageEnum usage ); long getSyntaxLength(); void setSyntaxLength( long length ); AttributeType getSuperior(); String getSuperiorOid(); void setSuperior( AttributeType superior ); void setSuperior( String newSuperiorOid ); void setSuperiorOid( String superiorOid ); String getSuperiorName(); LdapSyntax getSyntax(); void setSyntax( LdapSyntax syntax ); String getSyntaxName(); String getSyntaxOid(); void setSyntaxOid( String syntaxOid ); MatchingRule getEquality(); void setEquality( MatchingRule equality ); String getEqualityOid(); void setEqualityOid( String equalityOid ); String getEqualityName(); MatchingRule getOrdering(); void setOrdering( MatchingRule ordering ); String getOrderingName(); String getOrderingOid(); void setOrderingOid( String orderingOid ); MatchingRule getSubstring(); void setSubstring( MatchingRule substring ); String getSubstringName(); String getSubstringOid(); void setSubstringOid( String substrOid ); boolean isUser(); boolean isOperational(); boolean isAncestorOf( AttributeType descendant ); boolean isHR(); boolean isDescendantOf( AttributeType ancestor ); @Override String toString(); @Override AttributeType copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = attributeType.toString(); assertNotNull( string ); assertTrue( string.startsWith( "attributetype (" ) ); assertTrue( string.contains( " NAME " ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tSUP " ) ); assertTrue( string.contains( "\n\tUSAGE" ) ); } |
### Question:
DitStructureRule extends AbstractSchemaObject { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } DitStructureRule( int ruleId ); String getForm(); void setForm( String form ); int getRuleId(); void setRuleId( int ruleId ); List<Integer> getSuperRules(); void setSuperRules( List<Integer> superRules ); void addSuperRule( Integer superRule ); @Override String getOid(); @Override String toString(); @Override DitStructureRule copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = ditStructureRule.toString(); assertNotNull( string ); assertTrue( string.startsWith( "ditstructurerule (" ) ); assertTrue( string.contains( " NAME " ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tFORM " ) ); assertTrue( string.contains( "\n\tSUP" ) ); } |
### Question:
NumericNormalizer extends Normalizer implements PreparedNormalizer { public Value normalize( Value value ) throws LdapException { String normalized = normalize( value.getString() ); return new Value( normalized ); } NumericNormalizer(); Value normalize( Value value ); @Override String normalize( String value ); @Override String normalize( String value, PrepareString.AssertionType assertionType ); }### Answer:
@Test public void testNumericNormalizerNull() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( null, normalizer.normalize( ( String ) null ) ); }
@Test public void testNumericNormalizerEmpty() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "", normalizer.normalize( "" ) ); }
@Test public void testNumericNormalizerOneSpace() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "", normalizer.normalize( " " ) ); }
@Test public void testNumericNormalizerTwoSpaces() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "", normalizer.normalize( " " ) ); }
@Test public void testNumericNormalizerNSpaces() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "", normalizer.normalize( " " ) ); }
@Test public void testInsignifiantSpacesStringOneChar() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "1", normalizer.normalize( "1" ) ); }
@Test public void testInsignifiantSpacesStringTwoChars() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "11", normalizer.normalize( "11" ) ); }
@Test public void testInsignifiantSpacesStringNChars() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "123456", normalizer.normalize( "123456" ) ); }
@Test public void testInsignifiantNumericCharsSpaces() throws LdapException { Normalizer normalizer = new NumericNormalizer(); assertEquals( "1", normalizer.normalize( " 1" ) ); assertEquals( "1", normalizer.normalize( "1 " ) ); assertEquals( "1", normalizer.normalize( " 1 " ) ); assertEquals( "11", normalizer.normalize( "1 1" ) ); assertEquals( "11", normalizer.normalize( " 1 1" ) ); assertEquals( "11", normalizer.normalize( "1 1 " ) ); assertEquals( "11", normalizer.normalize( "1 1" ) ); assertEquals( "11", normalizer.normalize( " 1 1 " ) ); assertEquals( "123456789", normalizer.normalize( " 123 456 789 " ) ); } |
### Question:
BooleanNormalizer extends Normalizer { @Override public String normalize( String value ) throws LdapInvalidDnException { if ( value == null ) { return null; } return Strings.upperCase( value.trim() ); } BooleanNormalizer(); @Override String normalize( String value ); @Override String normalize( String value, PrepareString.AssertionType assertionType ); }### Answer:
@Test public void testNormalizeNullValue() throws Exception { assertNull( normalizer.normalize( null ) ); }
@Test public void testNormalizeNonNullValue() throws Exception { assertEquals( "TRUE", normalizer.normalize( "true" ) ); assertEquals( "ABC", normalizer.normalize( "aBc" ) ); assertEquals( "FALSE", normalizer.normalize( "falsE" ) ); }
@Test public void testNormalizeValueWithSpaces() throws Exception { assertEquals( "TRUE", normalizer.normalize( " tRuE " ) ); } |
### Question:
SyntaxChecker extends LoadableSchemaObject { @Override public boolean equals( Object o ) { if ( !super.equals( o ) ) { return false; } return o instanceof SyntaxChecker; } protected SyntaxChecker( String oid ); protected SyntaxChecker(); boolean isValidSyntax( Object value ); void setSchemaManager( SchemaManager schemaManager ); @Override boolean equals( Object o ); @Override String toString(); static final long serialVersionUID; }### Answer:
@Test public void testEqualsNull() throws Exception { assertFalse( objectClassA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( objectClassA.equals( objectClassC ) ); assertFalse( objectClassC.equals( objectClassA ) ); } |
### Question:
PrepareString { public static String normalize( String value ) { if ( !Normalizer.isNormalized( value, Normalizer.Form.NFKC ) ) { return Normalizer.normalize( value, Normalizer.Form.NFKC ); } else { return value; } } private PrepareString(); static String transcode( byte[] bytes ); static String normalize( String value ); static String mapCaseSensitive( String unicode ); static void checkProhibited( char[] value ); static String insignificantNumericStringHandling( char[] source ); static String insignificantTelephoneNumberStringHandling( char[] source ); static String insignificantSpacesStringValue( char[] origin ); static String insignificantSpacesStringInitial( char[] origin ); static String insignificantSpacesStringAny( char[] origin ); static String insignificantSpacesStringFinal( char[] origin ); static String mapIgnoreCase( String unicode ); static final boolean CASE_SENSITIVE; static final boolean IGNORE_CASE; }### Answer:
@Test public void testEscapeBackSlash() throws IOException { String result = PrepareString.normalize( "C:\\a\\b\\c" ); System.out.println( result ); } |
### Question:
DitContentRule extends AbstractSchemaObject { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } DitContentRule( String oid ); List<String> getAuxObjectClassOids(); void addAuxObjectClassOidOids( String oid ); void addAuxObjectClasses( ObjectClass objectClass ); void setAuxObjectClassOids( List<String> auxObjectClassOids ); void setAuxObjectClasses( List<ObjectClass> auxObjectClasses ); List<ObjectClass> getAuxObjectClasses(); List<String> getMayAttributeTypeOids(); void addMayAttributeTypeOids( String oid ); void addMayAttributeTypes( AttributeType attributeType ); void setMayAttributeTypeOids( List<String> mayAttributeTypeOids ); void setMayAttributeTypes( List<AttributeType> mayAttributeTypes ); List<AttributeType> getMayAttributeTypes(); List<String> getMustAttributeTypeOids(); void addMustAttributeTypeOids( String oid ); void addMustAttributeTypes( AttributeType attributeType ); void setMustAttributeTypeOids( List<String> mustAttributeTypeOids ); void setMustAttributeTypes( List<AttributeType> mustAttributeTypes ); List<AttributeType> getMustAttributeTypes(); List<String> getNotAttributeTypeOids(); void addNotAttributeTypeOids( String oid ); void addNotAttributeTypes( AttributeType attributeType ); void setNotAttributeTypeOids( List<String> notAttributeTypeOids ); void setNotAttributeTypes( List<AttributeType> notAttributeTypes ); List<AttributeType> getNotAttributeTypes(); @Override String toString(); @Override DitContentRule copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = ditContentRule.toString(); assertNotNull( string ); assertTrue( string.startsWith( "ditcontentrule (" ) ); assertTrue( string.contains( " NAME " ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tAUX " ) ); assertTrue( string.contains( "\n\tMUST" ) ); assertTrue( string.contains( "\n\tMAY" ) ); assertTrue( string.contains( "\n\tNOT" ) ); } |
### Question:
MatchingRuleUse extends AbstractSchemaObject { @Override public String toString() { return SchemaObjectRenderer.OPEN_LDAP_SCHEMA_RENDERER.render( this ); } MatchingRuleUse( String oid ); List<String> getApplicableAttributeOids(); List<AttributeType> getApplicableAttributes(); void setApplicableAttributeOids( List<String> applicableAttributeOids ); void setApplicableAttributes( List<AttributeType> applicableAttributes ); void addApplicableAttributeOids( String oid ); void addApplicableAttribute( AttributeType attributeType ); @Override String toString(); @Override MatchingRuleUse copy(); @Override int hashCode(); @Override boolean equals( Object o ); @Override void clear(); static final long serialVersionUID; }### Answer:
@Test public void testToString() throws Exception { String string = matchingRuleUse.toString(); assertNotNull( string ); assertTrue( string.startsWith( "matchingruleuse (" ) ); assertTrue( string.contains( " NAME " ) ); assertTrue( string.contains( "\n\tDESC " ) ); assertTrue( string.contains( "\n\tAPPLIES " ) ); } |
### Question:
Ava implements Externalizable, Cloneable, Comparable<Ava> { public String getName() { return upName; } Ava(); Ava( SchemaManager schemaManager ); Ava( SchemaManager schemaManager, Ava ava ); Ava( String upType, byte[] upValue ); Ava( SchemaManager schemaManager, String upType, byte[] upValue ); Ava( SchemaManager schemaManager, String upType, String upName, byte[] upValue ); Ava( String upType, String upValue ); Ava( SchemaManager schemaManager, String upType, String upValue ); Ava( SchemaManager schemaManager, String upType, String upName, String upValue ); Ava( String upType, String normType, Value value, String upName ); Ava( AttributeType attributeType, String upType, String normType, Value value, String upName ); Ava( SchemaManager schemaManager, String upType, String normType, Value value ); String getNormType(); String getType(); Value getValue(); String getName(); String getEscaped(); @Override Ava clone(); @Override int hashCode(); @Override boolean equals( Object obj ); int serialize( byte[] buffer, int pos ); int deserialize( byte[] buffer, int pos ); @Override void writeExternal( ObjectOutput out ); @Override void readExternal( ObjectInput in ); boolean isSchemaAware(); AttributeType getAttributeType(); @Override int compareTo( Ava that ); @Override String toString(); }### Answer:
@Test public void testNormalize() throws LdapException { Ava atav = new Ava( schemaManager, " A ", "a" ); assertEquals( " A =a", atav.getName() ); } |
### Question:
Rdn implements Cloneable, Externalizable, Iterable<Ava>, Comparable<Rdn> { @Override public String toString() { return upName == null ? "" : upName; } Rdn(); Rdn( SchemaManager schemaManager ); Rdn( SchemaManager schemaManager, String rdn ); Rdn( String rdn ); Rdn( SchemaManager schemaManager, String upType, String upValue ); Rdn( String upType, String upValue ); Rdn( SchemaManager schemaManager, Ava... avas ); Rdn( Ava... avas ); Rdn( Rdn rdn ); Rdn( SchemaManager schemaManager, Rdn rdn ); Object getValue( String type ); Ava getAva( String type ); @Override Iterator<Ava> iterator(); @Override Rdn clone(); String getName(); String getNormName(); Ava getAva(); Ava getAva( int pos ); String getType(); String getNormType(); String getValue(); @Override boolean equals( Object that ); int size(); static Object unescapeValue( String value ); static String escapeValue( String value ); String getEscaped(); static String escapeValue( byte[] attrValue ); boolean isSchemaAware(); static boolean isValid( String dn ); static boolean isValid( SchemaManager schemaManager, String dn ); @Override int hashCode(); int serialize( byte[] buffer, int pos ); int deserialize( byte[] buffer, int pos ); @Override void writeExternal( ObjectOutput out ); @Override void readExternal( ObjectInput in ); @Override int compareTo( Rdn otherRdn ); @Override String toString(); static final Rdn EMPTY_RDN; static final int UNDEFINED; static final int SUPERIOR; static final int INFERIOR; static final int EQUAL; }### Answer:
@Test public void testRdnNull() { assertEquals( "", new Rdn().toString() ); }
@Test public void testRdnEmpty() throws LdapException { assertEquals( "", new Rdn( "" ).toString() ); } |
### Question:
Rdn implements Cloneable, Externalizable, Iterable<Ava>, Comparable<Rdn> { public Object getValue( String type ) throws LdapInvalidDnException { String normalizedType = Strings.lowerCaseAscii( Strings.trim( type ) ); if ( schemaManager != null ) { AttributeType attributeType = schemaManager.getAttributeType( normalizedType ); if ( attributeType != null ) { normalizedType = attributeType.getOid(); } } switch ( nbAvas ) { case 0: return ""; case 1: if ( ava.getNormType().equals( normalizedType ) ) { if ( ava.getValue() != null ) { return ava.getValue().getString(); } else { return null; } } return ""; default: List<Ava> avaList = avaTypes.get( normalizedType ); if ( avaList != null ) { for ( Ava elem : avaList ) { if ( elem.getNormType().equals( normalizedType ) ) { if ( elem.getValue() != null ) { return elem.getValue().getString(); } else { return null; } } } return null; } return null; } } Rdn(); Rdn( SchemaManager schemaManager ); Rdn( SchemaManager schemaManager, String rdn ); Rdn( String rdn ); Rdn( SchemaManager schemaManager, String upType, String upValue ); Rdn( String upType, String upValue ); Rdn( SchemaManager schemaManager, Ava... avas ); Rdn( Ava... avas ); Rdn( Rdn rdn ); Rdn( SchemaManager schemaManager, Rdn rdn ); Object getValue( String type ); Ava getAva( String type ); @Override Iterator<Ava> iterator(); @Override Rdn clone(); String getName(); String getNormName(); Ava getAva(); Ava getAva( int pos ); String getType(); String getNormType(); String getValue(); @Override boolean equals( Object that ); int size(); static Object unescapeValue( String value ); static String escapeValue( String value ); String getEscaped(); static String escapeValue( byte[] attrValue ); boolean isSchemaAware(); static boolean isValid( String dn ); static boolean isValid( SchemaManager schemaManager, String dn ); @Override int hashCode(); int serialize( byte[] buffer, int pos ); int deserialize( byte[] buffer, int pos ); @Override void writeExternal( ObjectOutput out ); @Override void readExternal( ObjectInput in ); @Override int compareTo( Rdn otherRdn ); @Override String toString(); static final Rdn EMPTY_RDN; static final int UNDEFINED; static final int SUPERIOR; static final int INFERIOR; static final int EQUAL; }### Answer:
@Test public void testRdnCompositeMultivaluedAttribute() throws LdapException { Rdn rdn = new Rdn( "a =b+c=d + e=f + g =h + i =j " ); assertEquals( "b", rdn.getValue( "a" ) ); assertEquals( "d", rdn.getValue( "c" ) ); assertEquals( "f", rdn.getValue( " E " ) ); assertEquals( "h", rdn.getValue( "g" ) ); assertEquals( "j", rdn.getValue( "i" ) ); }
@Test public void testGetValue() throws LdapException { Rdn rdn = new Rdn( " a = b + b = f + g = h + c = d " ); assertEquals( "b", rdn.getValue() ); } |
### Question:
Oid { public static boolean isOid( String oidString ) { try { Oid.fromString( oidString ); return true; } catch ( DecoderException e ) { return false; } } private Oid( String oidString, byte[] oidBytes ); @Override boolean equals( Object other ); static Oid fromBytes( byte[] oidBytes ); static Oid fromString( String oidString ); int getEncodedLength(); @Override int hashCode(); static boolean isOid( String oidString ); byte[] toBytes(); @Override String toString(); void writeBytesTo( ByteBuffer buffer ); void writeBytesTo( OutputStream outputStream ); }### Answer:
@Test public void testNewOidStringBad() { assertFalse( Oid.isOid( "0" ) ); assertFalse( Oid.isOid( "1" ) ); assertFalse( Oid.isOid( "0." ) ); assertFalse( Oid.isOid( "1." ) ); assertFalse( Oid.isOid( "2." ) ); assertFalse( Oid.isOid( "2." ) ); assertFalse( Oid.isOid( "." ) ); assertFalse( Oid.isOid( "0.1.2." ) ); assertFalse( Oid.isOid( "3.1" ) ); assertFalse( Oid.isOid( "0..1" ) ); assertFalse( Oid.isOid( "0..12" ) ); assertFalse( Oid.isOid( "0.a.2" ) ); assertFalse( Oid.isOid( "0.40" ) ); assertFalse( Oid.isOid( "0.51" ) ); assertFalse( Oid.isOid( "0.01" ) ); assertFalse( Oid.isOid( "0.123456" ) ); assertFalse( Oid.isOid( "1.123456" ) ); } |
### Question:
Rdn implements Cloneable, Externalizable, Iterable<Ava>, Comparable<Rdn> { public String getType() { switch ( nbAvas ) { case 0: return null; case 1: return ava.getType(); default: return avas.get( 0 ).getType(); } } Rdn(); Rdn( SchemaManager schemaManager ); Rdn( SchemaManager schemaManager, String rdn ); Rdn( String rdn ); Rdn( SchemaManager schemaManager, String upType, String upValue ); Rdn( String upType, String upValue ); Rdn( SchemaManager schemaManager, Ava... avas ); Rdn( Ava... avas ); Rdn( Rdn rdn ); Rdn( SchemaManager schemaManager, Rdn rdn ); Object getValue( String type ); Ava getAva( String type ); @Override Iterator<Ava> iterator(); @Override Rdn clone(); String getName(); String getNormName(); Ava getAva(); Ava getAva( int pos ); String getType(); String getNormType(); String getValue(); @Override boolean equals( Object that ); int size(); static Object unescapeValue( String value ); static String escapeValue( String value ); String getEscaped(); static String escapeValue( byte[] attrValue ); boolean isSchemaAware(); static boolean isValid( String dn ); static boolean isValid( SchemaManager schemaManager, String dn ); @Override int hashCode(); int serialize( byte[] buffer, int pos ); int deserialize( byte[] buffer, int pos ); @Override void writeExternal( ObjectOutput out ); @Override void readExternal( ObjectInput in ); @Override int compareTo( Rdn otherRdn ); @Override String toString(); static final Rdn EMPTY_RDN; static final int UNDEFINED; static final int SUPERIOR; static final int INFERIOR; static final int EQUAL; }### Answer:
@Test public void testGetType() throws LdapException { Rdn rdn = new Rdn( " a = b + b = f + g = h + c = d " ); assertEquals( "a", rdn.getNormType() ); } |
### Question:
Rdn implements Cloneable, Externalizable, Iterable<Ava>, Comparable<Rdn> { public int size() { return nbAvas; } Rdn(); Rdn( SchemaManager schemaManager ); Rdn( SchemaManager schemaManager, String rdn ); Rdn( String rdn ); Rdn( SchemaManager schemaManager, String upType, String upValue ); Rdn( String upType, String upValue ); Rdn( SchemaManager schemaManager, Ava... avas ); Rdn( Ava... avas ); Rdn( Rdn rdn ); Rdn( SchemaManager schemaManager, Rdn rdn ); Object getValue( String type ); Ava getAva( String type ); @Override Iterator<Ava> iterator(); @Override Rdn clone(); String getName(); String getNormName(); Ava getAva(); Ava getAva( int pos ); String getType(); String getNormType(); String getValue(); @Override boolean equals( Object that ); int size(); static Object unescapeValue( String value ); static String escapeValue( String value ); String getEscaped(); static String escapeValue( byte[] attrValue ); boolean isSchemaAware(); static boolean isValid( String dn ); static boolean isValid( SchemaManager schemaManager, String dn ); @Override int hashCode(); int serialize( byte[] buffer, int pos ); int deserialize( byte[] buffer, int pos ); @Override void writeExternal( ObjectOutput out ); @Override void readExternal( ObjectInput in ); @Override int compareTo( Rdn otherRdn ); @Override String toString(); static final Rdn EMPTY_RDN; static final int UNDEFINED; static final int SUPERIOR; static final int INFERIOR; static final int EQUAL; }### Answer:
@Test public void testGetSize() throws LdapException { Rdn rdn = new Rdn( " a = b + b = f + g = h + c = d " ); assertEquals( 4, rdn.size() ); }
@Test public void testGetSize0() { Rdn rdn = new Rdn(); assertEquals( 0, rdn.size() ); } |
### Question:
Rdn implements Cloneable, Externalizable, Iterable<Ava>, Comparable<Rdn> { @Override public Iterator<Ava> iterator() { if ( nbAvas < 2 ) { return new Iterator<Ava>() { private boolean hasMoreElement = nbAvas == 1; @Override public boolean hasNext() { return hasMoreElement; } @Override public Ava next() { Ava obj = ava; hasMoreElement = false; return obj; } @Override public void remove() { } }; } else { return avas.iterator(); } } Rdn(); Rdn( SchemaManager schemaManager ); Rdn( SchemaManager schemaManager, String rdn ); Rdn( String rdn ); Rdn( SchemaManager schemaManager, String upType, String upValue ); Rdn( String upType, String upValue ); Rdn( SchemaManager schemaManager, Ava... avas ); Rdn( Ava... avas ); Rdn( Rdn rdn ); Rdn( SchemaManager schemaManager, Rdn rdn ); Object getValue( String type ); Ava getAva( String type ); @Override Iterator<Ava> iterator(); @Override Rdn clone(); String getName(); String getNormName(); Ava getAva(); Ava getAva( int pos ); String getType(); String getNormType(); String getValue(); @Override boolean equals( Object that ); int size(); static Object unescapeValue( String value ); static String escapeValue( String value ); String getEscaped(); static String escapeValue( byte[] attrValue ); boolean isSchemaAware(); static boolean isValid( String dn ); static boolean isValid( SchemaManager schemaManager, String dn ); @Override int hashCode(); int serialize( byte[] buffer, int pos ); int deserialize( byte[] buffer, int pos ); @Override void writeExternal( ObjectOutput out ); @Override void readExternal( ObjectInput in ); @Override int compareTo( Rdn otherRdn ); @Override String toString(); static final Rdn EMPTY_RDN; static final int UNDEFINED; static final int SUPERIOR; static final int INFERIOR; static final int EQUAL; }### Answer:
@Test public void testMultiValuedIterator() throws LdapException { Rdn rdn = new Rdn( "cn=Kate Bush+sn=Bush" ); Iterator<Ava> iterator = rdn.iterator(); assertNotNull( iterator ); assertTrue( iterator.hasNext() ); assertNotNull( iterator.next() ); assertTrue( iterator.hasNext() ); assertNotNull( iterator.next() ); assertFalse( iterator.hasNext() ); }
@Test public void testSingleValuedIterator() throws LdapException { Rdn rdn = new Rdn( "cn=Kate Bush" ); Iterator<Ava> iterator = rdn.iterator(); assertNotNull( iterator ); assertTrue( iterator.hasNext() ); assertNotNull( iterator.next() ); assertFalse( iterator.hasNext() ); }
@Test public void testEmptyIterator() { Rdn rdn = new Rdn(); Iterator<Ava> iterator = rdn.iterator(); assertNotNull( iterator ); assertFalse( iterator.hasNext() ); }
@Test public void testIterator() throws LdapException { Rdn rdn = new Rdn( "cn=John + sn=Doe" ); String[] expected = new String[] { "cn=John ", " sn=Doe" }; int i = 0; for ( Ava ava : rdn ) { assertEquals( expected[i], ava.getName() ); i++; } } |
### Question:
OsgiUtils { public static Set<File> getClasspathCandidates( FileFilter filter ) { Set<File> candidates = new HashSet<>(); String separator = System.getProperty( "path.separator" ); String[] cpElements = System.getProperty( "java.class.path" ).split( separator ); for ( String element : cpElements ) { File candidate = new File( element ); if ( candidate.isFile() ) { if ( filter != null && filter.accept( candidate ) ) { candidates.add( candidate ); if ( LOG.isInfoEnabled() ) { LOG.info( I18n.msg( I18n.MSG_17003_ACCEPTED_CANDIDATE_WITH_FILTER, candidate.toString() ) ); } } else if ( filter == null && candidate.getName().endsWith( ".jar" ) ) { candidates.add( candidate ); if ( LOG.isInfoEnabled() ) { LOG.info( I18n.msg( I18n.MSG_17004_ACCEPTED_CANDIDATE_NO_FILTER, candidate.toString() ) ); } } else { if ( LOG.isInfoEnabled() ) { LOG.info( I18n.msg( I18n.MSG_17005_REJECTING_CANDIDATE, candidate.toString() ) ); } } } } return candidates; } private OsgiUtils(); static Set<String> getAllBundleExports( FileFilter filter, Set<String> pkgs ); static Set<String> splitIntoPackages( String exports, Set<String> pkgs ); static Set<File> getClasspathCandidates( FileFilter filter ); static String getBundleExports( File bundle ); }### Answer:
@Test public void testGetClasspathCandidates() { Set<File> candidates = OsgiUtils.getClasspathCandidates( REJECTION_FILTER ); assertEquals( 0, candidates.size(), "Should have no results with REJECTION_FILTER" ); candidates = OsgiUtils.getClasspathCandidates( ONLY_ONE_FILTER ); assertEquals( 1, candidates.size(), "Should have one result with ONLY_ONE_FILTER" ); candidates = OsgiUtils.getClasspathCandidates( JUNIT_SLF4J_FILTER ); assertTrue( candidates.size() >= 4, "Should have at least 4 results with JUNIT_SLF4J_FILTER" ); candidates = OsgiUtils.getClasspathCandidates( null ); assertTrue( candidates.size() >= 4, "Should have at least 4 results with no filter" ); } |
### Question:
LdifRevertor { public static LdifEntry reverseAdd( Dn dn ) { LdifEntry entry = new LdifEntry(); entry.setChangeType( ChangeType.Delete ); entry.setDn( dn ); return entry; } private LdifRevertor(); static LdifEntry reverseAdd( Dn dn ); static LdifEntry reverseDel( Dn dn, Entry deletedEntry ); static LdifEntry reverseModify( Dn dn, List<Modification> forwardModifications, Entry modifiedEntry ); static LdifEntry reverseMove( Dn newSuperiorDn, Dn modifiedDn ); static List<LdifEntry> reverseRename( Entry entry, Rdn newRdn, boolean deleteOldRdn ); static List<LdifEntry> reverseMoveAndRename( Entry entry, Dn newSuperior, Rdn newRdn, boolean deleteOldRdn ); static final boolean DELETE_OLD_RDN; static final boolean KEEP_OLD_RDN; }### Answer:
@Test public void testReverseAdd() throws LdapInvalidDnException { Dn dn = new Dn( "dc=apache, dc=com" ); LdifEntry reversed = LdifRevertor.reverseAdd( dn ); assertNotNull( reversed ); assertEquals( dn.getName(), reversed.getDn().getName() ); assertEquals( ChangeType.Delete, reversed.getChangeType() ); assertNull( reversed.getEntry() ); }
@Test public void testReverseAddBase64DN() throws LdapException { Dn dn = new Dn( "dc=Emmanuel L\u00c9charny" ); LdifEntry reversed = LdifRevertor.reverseAdd( dn ); assertNotNull( reversed ); assertEquals( dn.getName(), reversed.getDn().getName() ); assertEquals( ChangeType.Delete, reversed.getChangeType() ); assertNull( reversed.getEntry() ); } |
### Question:
LdifRevertor { public static LdifEntry reverseDel( Dn dn, Entry deletedEntry ) throws LdapException { LdifEntry entry = new LdifEntry(); entry.setDn( dn ); entry.setChangeType( ChangeType.Add ); for ( Attribute attribute : deletedEntry ) { entry.addAttribute( attribute ); } return entry; } private LdifRevertor(); static LdifEntry reverseAdd( Dn dn ); static LdifEntry reverseDel( Dn dn, Entry deletedEntry ); static LdifEntry reverseModify( Dn dn, List<Modification> forwardModifications, Entry modifiedEntry ); static LdifEntry reverseMove( Dn newSuperiorDn, Dn modifiedDn ); static List<LdifEntry> reverseRename( Entry entry, Rdn newRdn, boolean deleteOldRdn ); static List<LdifEntry> reverseMoveAndRename( Entry entry, Dn newSuperior, Rdn newRdn, boolean deleteOldRdn ); static final boolean DELETE_OLD_RDN; static final boolean KEEP_OLD_RDN; }### Answer:
@Test public void testReverseDel() throws LdapException { Dn dn = new Dn( "dc=apache, dc=com" ); Entry deletedEntry = new DefaultEntry( dn , "objectClass: top", "objectClass: person", "cn: test", "sn: apache", "dc: apache" ); LdifEntry reversed = LdifRevertor.reverseDel( dn, deletedEntry ); assertNotNull( reversed ); assertEquals( dn.getName(), reversed.getDn().getName() ); assertEquals( ChangeType.Add, reversed.getChangeType() ); assertNotNull( reversed.getEntry() ); assertEquals( deletedEntry, reversed.getEntry() ); } |
### Question:
OsgiUtils { public static Set<String> getAllBundleExports( FileFilter filter, Set<String> pkgs ) { if ( pkgs == null ) { pkgs = new HashSet<>(); } Set<File> candidates = getClasspathCandidates( filter ); for ( File candidate : candidates ) { String exports = getBundleExports( candidate ); if ( exports == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_17000_NO_EXPORT_FOUND, candidate ) ); } continue; } if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_17001_PROCESSING_EXPORTS, candidate, exports ) ); } splitIntoPackages( exports, pkgs ); } return pkgs; } private OsgiUtils(); static Set<String> getAllBundleExports( FileFilter filter, Set<String> pkgs ); static Set<String> splitIntoPackages( String exports, Set<String> pkgs ); static Set<File> getClasspathCandidates( FileFilter filter ); static String getBundleExports( File bundle ); }### Answer:
@Test public void testGetAllBundleExports() { OsgiUtils.getAllBundleExports( null, null ); } |
### Question:
LdifRevertor { public static LdifEntry reverseMove( Dn newSuperiorDn, Dn modifiedDn ) throws LdapException { LdifEntry entry = new LdifEntry(); Dn currentParent; Rdn currentRdn; Dn newDn; if ( newSuperiorDn == null ) { throw new IllegalArgumentException( I18n.err( I18n.ERR_13466_NEW_SUPERIOR_DN_NULL ) ); } if ( modifiedDn == null ) { throw new IllegalArgumentException( I18n.err( I18n.ERR_13467_NULL_MODIFIED_DN ) ); } if ( modifiedDn.size() == 0 ) { throw new IllegalArgumentException( I18n.err( I18n.ERR_13468_DONT_MOVE_ROOTDSE ) ); } currentParent = modifiedDn; currentRdn = currentParent.getRdn(); currentParent = currentParent.getParent(); newDn = newSuperiorDn; newDn = newDn.add( modifiedDn.getRdn() ); entry.setChangeType( ChangeType.ModDn ); entry.setDn( newDn ); entry.setNewRdn( currentRdn.getName() ); entry.setNewSuperior( currentParent.getName() ); entry.setDeleteOldRdn( false ); return entry; } private LdifRevertor(); static LdifEntry reverseAdd( Dn dn ); static LdifEntry reverseDel( Dn dn, Entry deletedEntry ); static LdifEntry reverseModify( Dn dn, List<Modification> forwardModifications, Entry modifiedEntry ); static LdifEntry reverseMove( Dn newSuperiorDn, Dn modifiedDn ); static List<LdifEntry> reverseRename( Entry entry, Rdn newRdn, boolean deleteOldRdn ); static List<LdifEntry> reverseMoveAndRename( Entry entry, Dn newSuperior, Rdn newRdn, boolean deleteOldRdn ); static final boolean DELETE_OLD_RDN; static final boolean KEEP_OLD_RDN; }### Answer:
@Test public void testReverseModifyDNMove() throws LdapException { Dn dn = new Dn( "cn=john doe, dc=example, dc=com" ); Dn newSuperior = new Dn( "ou=system" ); Rdn rdn = new Rdn( "cn=john doe" ); LdifEntry reversed = LdifRevertor.reverseMove( newSuperior, dn ); assertNotNull( reversed ); assertEquals( "cn=john doe,ou=system", reversed.getDn().getName() ); assertEquals( ChangeType.ModDn, reversed.getChangeType() ); assertFalse( reversed.isDeleteOldRdn() ); assertEquals( rdn.getName(), reversed.getNewRdn() ); assertEquals( "dc=example, dc=com", Strings.trim( reversed.getNewSuperior() ) ); assertNull( reversed.getEntry() ); } |
### Question:
Unicode { public static char bytesToChar( byte[] bytes ) { return bytesToChar( bytes, 0 ); } private Unicode(); static int countBytesPerChar( byte[] bytes, int pos ); static char bytesToChar( byte[] bytes ); static char bytesToChar( byte[] bytes, int pos ); static int countNbBytesPerChar( char car ); static int countBytes( char[] chars ); static int countChars( byte[] bytes ); static byte[] charToBytes( char car ); static boolean isUnicodeSubset( String str, int pos ); static boolean isUnicodeSubset( char c ); static boolean isUnicodeSubset( byte b ); static void writeUTF( ObjectOutput objectOutput, String str ); static String readUTF( ObjectInput objectInput ); }### Answer:
@Test public void testOneByteChar() { char res = Unicode.bytesToChar( new byte[] { 0x30 } ); assertEquals( '0', res ); }
@Test public void testOneByteChar00() { char res = Unicode.bytesToChar( new byte[] { 0x00 } ); assertEquals( 0x00, res ); }
@Test public void testOneByteChar7F() { char res = Unicode.bytesToChar( new byte[] { 0x7F } ); assertEquals( 0x7F, res ); }
@Test public void testTwoBytesChar() { char res = Unicode.bytesToChar( new byte[] { ( byte ) 0xCE, ( byte ) 0x91 } ); assertEquals( 0x0391, res ); }
@Test public void testThreeBytesChar() { char res = Unicode.bytesToChar( new byte[] { ( byte ) 0xE2, ( byte ) 0x89, ( byte ) 0xA2 } ); assertEquals( 0x2262, res ); } |
### Question:
BitString { public boolean getBit( int pos ) { if ( pos > nbBits ) { throw new IndexOutOfBoundsException( I18n.err( I18n.ERR_00002_CANNOT_FIND_BIT, pos, nbBits ) ); } int posBytes = pos >>> 3; int bitNumber = 7 - pos % 8; byte mask = ( byte ) ( 1 << bitNumber ); int res = bytes[posBytes] & mask; return res != 0; } BitString( int length ); BitString( byte[] bytes ); void setData( byte[] data ); byte[] getData(); byte getUnusedBits(); void setBit( int pos ); void clearBit( int pos ); boolean getBit( int pos ); int size(); @Override String toString(); static final BitString EMPTY_STRING; }### Answer:
@Test public void testSingleBitBitString() throws DecoderException { BitString bitString = new BitString( new byte[] { 0x07, ( byte ) 0x80 } ); assertEquals( true, bitString.getBit( 0 ) ); } |
### Question:
LdifUtils { public static Attributes createJndiAttributes( Object... avas ) throws LdapException { StringBuilder sb = new StringBuilder(); int pos = 0; boolean valueExpected = false; for ( Object ava : avas ) { if ( !valueExpected ) { if ( !( ava instanceof String ) ) { throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_13233_ATTRIBUTE_ID_MUST_BE_A_STRING, pos + 1 ) ); } String attribute = ( String ) ava; sb.append( attribute ); if ( attribute.indexOf( ':' ) != -1 ) { sb.append( '\n' ); } else { valueExpected = true; } } else { if ( ava instanceof String ) { sb.append( ": " ).append( ( String ) ava ).append( '\n' ); } else if ( ava instanceof byte[] ) { sb.append( ":: " ); sb.append( new String( Base64.encode( ( byte[] ) ava ) ) ); sb.append( '\n' ); } else { throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_13234_ATTRIBUTE_VAL_STRING_OR_BYTE, pos + 1 ) ); } valueExpected = false; } } if ( valueExpected ) { throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n .err( I18n.ERR_13234_ATTRIBUTE_VAL_STRING_OR_BYTE ) ); } try ( LdifAttributesReader reader = new LdifAttributesReader() ) { return AttributeUtils.toAttributes( reader.parseEntry( sb.toString() ) ); } catch ( IOException ioe ) { throw new LdapLdifException( ioe.getMessage(), ioe ); } } private LdifUtils(); static boolean isLDIFSafe( String str ); static String convertToLdif( Attributes attrs ); static String convertToLdif( Attributes attrs, int length ); static String convertToLdif( Attributes attrs, Dn dn, int length ); static String convertToLdif( Attributes attrs, Dn dn ); static String convertToLdif( Entry entry ); static String convertToLdif( Entry entry, boolean includeVersionInfo ); static String convertAttributesToLdif( Entry entry ); static Attributes getJndiAttributesFromLdif( String ldif ); static String convertToLdif( Entry entry, int length ); static String convertAttributesToLdif( Entry entry, int length ); static String convertToLdif( LdifEntry entry ); static String convertToLdif( LdifEntry entry, int length ); static String convertToLdif( Attribute attr ); static String convertToLdif( Attribute attr, int length ); static String stripLineToNChars( String str, int nbChars ); static Attributes createJndiAttributes( Object... avas ); }### Answer:
@Test public void testCreateAttributesVarargs() throws LdapException, LdapLdifException, NamingException { String mOid = "m-oid: 1.2.3.4"; String description = "description"; Attributes attrs = LdifUtils.createJndiAttributes( "objectClass: top", "objectClass: metaTop", "objectClass: metaSyntax", mOid, "m-description", description ); assertEquals( "top", attrs.get( "objectClass" ).get( 0 ) ); assertEquals( "metaTop", attrs.get( "objectClass" ).get( 1 ) ); assertEquals( "metaSyntax", attrs.get( "objectClass" ).get( 2 ) ); assertEquals( "1.2.3.4", attrs.get( "m-oid" ).get() ); assertEquals( "description", attrs.get( "m-description" ).get() ); try { LdifUtils.createJndiAttributes( "objectClass", "top", "objectClass" ); fail(); } catch ( LdapInvalidAttributeValueException iave ) { assertTrue( true ); } } |
### Question:
Unicode { public static byte[] charToBytes( char car ) { if ( car <= 0x007F ) { byte[] bytes = new byte[1]; bytes[0] = ( byte ) car; return bytes; } else if ( car <= 0x07FF ) { byte[] bytes = new byte[2]; bytes[0] = ( byte ) ( 0x00C0 + ( ( car & 0x07C0 ) >> 6 ) ); bytes[1] = ( byte ) ( 0x0080 + ( car & 0x3F ) ); return bytes; } else { byte[] bytes = new byte[3]; bytes[0] = ( byte ) ( 0x00E0 + ( ( car & 0xF000 ) >> 12 ) ); bytes[1] = ( byte ) ( 0x0080 + ( ( car & 0x0FC0 ) >> 6 ) ); bytes[2] = ( byte ) ( 0x0080 + ( car & 0x3F ) ); return bytes; } } private Unicode(); static int countBytesPerChar( byte[] bytes, int pos ); static char bytesToChar( byte[] bytes ); static char bytesToChar( byte[] bytes, int pos ); static int countNbBytesPerChar( char car ); static int countBytes( char[] chars ); static int countChars( byte[] bytes ); static byte[] charToBytes( char car ); static boolean isUnicodeSubset( String str, int pos ); static boolean isUnicodeSubset( char c ); static boolean isUnicodeSubset( byte b ); static void writeUTF( ObjectOutput objectOutput, String str ); static String readUTF( ObjectInput objectInput ); }### Answer:
@Test public void testcharToBytesOne() { assertEquals( "0x00 ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x0000 ) ) ); assertEquals( "0x61 ", Strings.dumpBytes( Unicode.charToBytes( 'a' ) ) ); assertEquals( "0x7F ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x007F ) ) ); }
@Test public void testcharToBytesTwo() { assertEquals( "0xC2 0x80 ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x0080 ) ) ); assertEquals( "0xC3 0xBF ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x00FF ) ) ); assertEquals( "0xC4 0x80 ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x0100 ) ) ); assertEquals( "0xDF 0xBF ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x07FF ) ) ); }
@Test public void testcharToBytesThree() { assertEquals( "0xE0 0xA0 0x80 ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x0800 ) ) ); assertEquals( "0xE0 0xBF 0xBF ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x0FFF ) ) ); assertEquals( "0xE1 0x80 0x80 ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0x1000 ) ) ); assertEquals( "0xEF 0xBF 0xBF ", Strings.dumpBytes( Unicode.charToBytes( ( char ) 0xFFFF ) ) ); } |
### Question:
LdapConnectionConfig { public void setTrustManagers( TrustManager... trustManagers ) { if ( ( trustManagers == null ) || ( trustManagers.length == 0 ) || ( trustManagers.length == 1 && trustManagers[0] == null ) ) { throw new IllegalArgumentException( "TrustManagers must not be null or empty" ); } this.trustManagers = trustManagers; } LdapConnectionConfig(); boolean isUseSsl(); void setUseSsl( boolean useSsl ); int getLdapPort(); void setLdapPort( int ldapPort ); String getLdapHost(); void setLdapHost( String ldapHost ); String getName(); void setName( String name ); String getCredentials(); void setCredentials( String credentials ); int getDefaultLdapPort(); int getDefaultLdapsPort(); String getDefaultLdapHost(); long getDefaultTimeout(); long getTimeout(); void setTimeout( long timeout ); int getSupportedLdapVersion(); TrustManager[] getTrustManagers(); void setTrustManagers( TrustManager... trustManagers ); String getSslProtocol(); void setSslProtocol( String sslProtocol ); KeyManager[] getKeyManagers(); void setKeyManagers( KeyManager[] keyManagers ); SecureRandom getSecureRandom(); void setSecureRandom( SecureRandom secureRandom ); String[] getEnabledCipherSuites(); void setEnabledCipherSuites( String[] enabledCipherSuites ); String[] getEnabledProtocols(); void setEnabledProtocols( String... enabledProtocols ); BinaryAttributeDetector getBinaryAttributeDetector(); void setBinaryAttributeDetector( BinaryAttributeDetector binaryAttributeDetector ); boolean isUseTls(); void setUseTls( boolean useTls ); LdapApiService getLdapApiService(); void setLdapApiService( LdapApiService ldapApiService ); static final int DEFAULT_LDAP_PORT; static final int DEFAULT_LDAPS_PORT; static final String DEFAULT_LDAP_HOST; static final int LDAP_V3; static final long DEFAULT_TIMEOUT; static final String DEFAULT_SSL_PROTOCOL; }### Answer:
@Test public void testNullTrustManagers() { LdapConnectionConfig config = new LdapConnectionConfig(); Assertions.assertThrows(IllegalArgumentException.class, () -> { config.setTrustManagers((TrustManager)null); }); }
@Test public void testNullTrustManagers2() { LdapConnectionConfig config = new LdapConnectionConfig(); Assertions.assertThrows(IllegalArgumentException.class, () -> { config.setTrustManagers(null); }); } |
### Question:
UnaryFilter extends AbstractFilter { public static UnaryFilter not() { return new UnaryFilter(); } private UnaryFilter(); static UnaryFilter not(); static UnaryFilter not( Filter filter ); @Override StringBuilder build( StringBuilder builder ); }### Answer:
@Test public void testNot() { AttributeDescriptionFilter attributeFilter = AttributeDescriptionFilter.present( "objectClass" ); assertEquals( "(!" + attributeFilter.build().toString() + ")", UnaryFilter.not( attributeFilter ).build().toString() ); AttributeValueAssertionFilter attributeValueAssertionFilter = AttributeValueAssertionFilter.equal( "objectClass", "person" ); assertEquals( "(!" + attributeValueAssertionFilter.build().toString() + ")", UnaryFilter.not( attributeValueAssertionFilter ).build().toString() ); } |
### Question:
SetOfFiltersFilter extends AbstractFilter { public static SetOfFiltersFilter and( Filter... filters ) { return new SetOfFiltersFilter( FilterOperator.AND ).addAll( filters ); } private SetOfFiltersFilter( FilterOperator operator ); SetOfFiltersFilter add( Filter filter ); SetOfFiltersFilter addAll( Filter... filters ); SetOfFiltersFilter addAll( List<Filter> filters ); static SetOfFiltersFilter and( Filter... filters ); static SetOfFiltersFilter or( Filter... filters ); @Override StringBuilder build( StringBuilder builder ); }### Answer:
@Test public void testAnd() { AttributeDescriptionFilter attributeFilter = AttributeDescriptionFilter.present( "objectClass" ); AttributeValueAssertionFilter attributeValueAssertionFilter = AttributeValueAssertionFilter.equal( "objectClass", "person" ); String expected = expected( FilterOperator.AND, attributeFilter, attributeValueAssertionFilter ); assertEquals( expected, SetOfFiltersFilter.and( attributeFilter, attributeValueAssertionFilter ) .build().toString() ); assertEquals( expected, SetOfFiltersFilter.and() .add( attributeFilter ) .add( attributeValueAssertionFilter ) .build().toString() ); assertEquals( expected, SetOfFiltersFilter.and() .addAll( attributeFilter, attributeValueAssertionFilter ) .build().toString() ); assertEquals( expected, SetOfFiltersFilter.and() .addAll( Arrays.asList( ( Filter ) attributeFilter, ( Filter ) attributeValueAssertionFilter ) ) .build().toString() ); } |
### Question:
SetOfFiltersFilter extends AbstractFilter { public static SetOfFiltersFilter or( Filter... filters ) { return new SetOfFiltersFilter( FilterOperator.OR ).addAll( filters ); } private SetOfFiltersFilter( FilterOperator operator ); SetOfFiltersFilter add( Filter filter ); SetOfFiltersFilter addAll( Filter... filters ); SetOfFiltersFilter addAll( List<Filter> filters ); static SetOfFiltersFilter and( Filter... filters ); static SetOfFiltersFilter or( Filter... filters ); @Override StringBuilder build( StringBuilder builder ); }### Answer:
@Test public void testOr() { AttributeDescriptionFilter attributeFilter = AttributeDescriptionFilter.present( "objectClass" ); AttributeValueAssertionFilter attributeValueAssertionFilter = AttributeValueAssertionFilter.equal( "objectClass", "person" ); String expected = expected( FilterOperator.OR, attributeFilter, attributeValueAssertionFilter ); assertEquals( expected, SetOfFiltersFilter.or( attributeFilter, attributeValueAssertionFilter ) .build().toString() ); assertEquals( expected, SetOfFiltersFilter.or() .add( attributeFilter ) .add( attributeValueAssertionFilter ) .build().toString() ); assertEquals( expected, SetOfFiltersFilter.or() .addAll( attributeFilter, attributeValueAssertionFilter ) .build().toString() ); assertEquals( expected, SetOfFiltersFilter.or() .addAll( Arrays.asList( ( Filter ) attributeFilter, ( Filter ) attributeValueAssertionFilter ) ) .build().toString() ); } |
### Question:
FilterBuilder { public static MatchingRuleAssertionFilterBuilder extensible( String value ) { return new MatchingRuleAssertionFilterBuilder( null, value ); } FilterBuilder( Filter filter ); static FilterBuilder and( FilterBuilder... filters ); static FilterBuilder approximatelyEqual( String attribute, String value ); static FilterBuilder equal( String attribute, String value ); static MatchingRuleAssertionFilterBuilder extensible( String value ); static MatchingRuleAssertionFilterBuilder extensible( String attribute, String value ); static FilterBuilder greaterThanOrEqual( String attribute, String value ); static FilterBuilder lessThanOrEqual( String attribute, String value ); static FilterBuilder not( FilterBuilder builder ); static FilterBuilder or( FilterBuilder... builders ); static FilterBuilder present( String attribute ); static FilterBuilder startsWith( String attribute, String... parts ); static FilterBuilder endsWith( String attribute, String... parts ); static FilterBuilder contains( String attribute, String... parts ); static FilterBuilder substring( String attribute, String... parts ); @Override String toString(); }### Answer:
@Test public void testExtensible() { assertEquals( "(cn:caseExactMatch:=Fred Flintstone)", extensible( "cn", "Fred Flintstone" ) .setMatchingRule( "caseExactMatch" ).toString() ); } |
### Question:
FilterBuilder { FilterBuilder( Filter filter ) { this.filter = filter; } FilterBuilder( Filter filter ); static FilterBuilder and( FilterBuilder... filters ); static FilterBuilder approximatelyEqual( String attribute, String value ); static FilterBuilder equal( String attribute, String value ); static MatchingRuleAssertionFilterBuilder extensible( String value ); static MatchingRuleAssertionFilterBuilder extensible( String attribute, String value ); static FilterBuilder greaterThanOrEqual( String attribute, String value ); static FilterBuilder lessThanOrEqual( String attribute, String value ); static FilterBuilder not( FilterBuilder builder ); static FilterBuilder or( FilterBuilder... builders ); static FilterBuilder present( String attribute ); static FilterBuilder startsWith( String attribute, String... parts ); static FilterBuilder endsWith( String attribute, String... parts ); static FilterBuilder contains( String attribute, String... parts ); static FilterBuilder substring( String attribute, String... parts ); @Override String toString(); }### Answer:
@Test public void testFilterBuilder() { assertEquals( "(cn=Babs Jensen)", equal( "cn", "Babs Jensen" ).toString() ); assertEquals( "(!(cn=Tim Howes))", not( equal( "cn", "Tim Howes" ) ).toString() ); assertEquals( "(&(objectClass=Person)(|(sn=Jensen)(cn=Babs J\\2A)))", and( equal( "objectClass", "Person" ), or( equal( "sn", "Jensen" ), equal( "cn", "Babs J*" ) ) ).toString() ); assertEquals( "(o=univ\\2Aof\\2Amich\\2A)", equal( "o", "univ*of*mich*" ).toString() ); } |
### Question:
MatchingRuleAssertionFilter extends AbstractFilter { public static MatchingRuleAssertionFilter extensible( String value ) { return new MatchingRuleAssertionFilter( null, value, FilterOperator.EXTENSIBLE_EQUAL ); } MatchingRuleAssertionFilter( String attribute, String value,
FilterOperator operator ); static MatchingRuleAssertionFilter extensible( String value ); static MatchingRuleAssertionFilter extensible( String attribute, String value ); MatchingRuleAssertionFilter setMatchingRule( String matchingRule ); MatchingRuleAssertionFilter useDnAttributes(); @Override StringBuilder build( StringBuilder builder ); }### Answer:
@Test public void testExtensible() { assertEquals( "(cn:caseExactMatch:=Fred Flintstone)", extensible( "cn", "Fred Flintstone" ) .setMatchingRule( "caseExactMatch" ).toString() ); assertEquals( "(cn:=Betty Rubble)", extensible( "cn", "Betty Rubble" ).toString() ); assertEquals( "(sn:dn:2.4.6.8.10:=Barney Rubble)", extensible( "sn", "Barney Rubble" ) .useDnAttributes() .setMatchingRule( "2.4.6.8.10" ).toString() ); assertEquals( "(o:dn:=Ace Industry)", extensible( "o", "Ace Industry" ) .useDnAttributes().toString() ); assertEquals( "(:1.2.3:=Wilma Flintstone)", extensible( "Wilma Flintstone" ) .setMatchingRule( "1.2.3" ).toString() ); assertEquals( "(:dn:2.4.6.8.10:=Dino)", extensible( "Dino" ) .useDnAttributes() .setMatchingRule( "2.4.6.8.10" ).toString() ); } |
### Question:
AttributeDescriptionFilter extends AbstractFilter { public static AttributeDescriptionFilter present( String attribute ) { return new AttributeDescriptionFilter( attribute ); } private AttributeDescriptionFilter( String attribute ); static AttributeDescriptionFilter present( String attribute ); @Override StringBuilder build( StringBuilder builder ); }### Answer:
@Test public void testPresent() { assertEquals( "(objectClass=*)", AttributeDescriptionFilter.present( "objectClass" ).build().toString() ); assertEquals( "(uid=*)", AttributeDescriptionFilter.present( "uid" ).build().toString() ); assertEquals( "(userPassword=*)", AttributeDescriptionFilter.present( "userPassword" ).build().toString() ); assertEquals( "(cn=*)", AttributeDescriptionFilter.present( "cn" ).build().toString() ); } |
### Question:
JarLdifSchemaLoader extends AbstractSchemaLoader { public JarLdifSchemaLoader() throws IOException, LdapException { initializeSchemas(); } JarLdifSchemaLoader(); @Override List<Entry> loadComparators( Schema... schemas ); @Override List<Entry> loadSyntaxCheckers( Schema... schemas ); @Override List<Entry> loadNormalizers( Schema... schemas ); @Override List<Entry> loadMatchingRules( Schema... schemas ); @Override List<Entry> loadSyntaxes( Schema... schemas ); @Override List<Entry> loadAttributeTypes( Schema... schemas ); @Override List<Entry> loadMatchingRuleUses( Schema... schemas ); @Override List<Entry> loadNameForms( Schema... schemas ); @Override List<Entry> loadDitContentRules( Schema... schemas ); @Override List<Entry> loadDitStructureRules( Schema... schemas ); @Override List<Entry> loadObjectClasses( Schema... schemas ); }### Answer:
@Test public void testJarLdifSchemaLoader() throws Exception { JarLdifSchemaLoader loader = new JarLdifSchemaLoader(); SchemaManager sm = new DefaultSchemaManager( loader ); sm.loadWithDeps( "system" ); assertTrue( sm.getRegistries().getAttributeTypeRegistry().contains( "cn" ) ); assertFalse( sm.getRegistries().getAttributeTypeRegistry().contains( "m-aux" ) ); sm.loadWithDeps( "apachemeta" ); assertTrue( sm.getRegistries().getAttributeTypeRegistry().contains( "m-aux" ) ); } |
### Question:
Hex { public static String decodeHexString( String str ) throws InvalidNameException { if ( str == null || str.length() == 0 ) { throw new InvalidNameException( I18n.err( I18n.ERR_17037_MUST_START_WITH_SHARP ) ); } char[] chars = str.toCharArray(); if ( chars[0] != '#' ) { throw new InvalidNameException( I18n.err( I18n.ERR_17038_MUST_START_WITH_ESC_SHARP, str ) ); } byte[] decoded = new byte[( chars.length - 1 ) >> 1]; for ( int ii = 1, jj = 0; ii < chars.length; ii += 2, jj++ ) { int ch = ( HEX_VALUE[chars[ii]] << 4 ) + ( HEX_VALUE[chars[ii + 1]] & 0xff ); decoded[jj] = ( byte ) ch; } return Strings.utf8ToString( decoded ); } private Hex(); static byte getHexValue( char high, char low ); static byte getHexValue( byte high, byte low ); static byte getHexValue( char c ); static String decodeHexString( String str ); static byte[] convertEscapedHex( String str ); static char[] encodeHex( byte[] data ); }### Answer:
@Test public void testDecodeHexString() throws Exception { try { assertEquals( "", Hex.decodeHexString( "" ) ); fail( "should not get here" ); } catch ( NamingException e ) { } assertEquals( "", Hex.decodeHexString( "#" ) ); assertEquals( "F", Hex.decodeHexString( "#46" ) ); try { assertEquals( "F", Hex.decodeHexString( "46" ) ); fail( "should not get here" ); } catch ( NamingException e ) { } assertEquals( "Ferry", Hex.decodeHexString( "#4665727279" ) ); } |
### Question:
DnNode { public synchronized DnNode<N> add( Dn dn ) throws LdapException { return add( dn, null ); } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testAddNullDNNoElem() throws LdapException { DnNode<Dn> tree = new DnNode<Dn>(); assertThrows( LdapUnwillingToPerformException.class, () -> { tree.add( null ); } ); }
@Test public void testAdd2EqualDNsNoElem() throws LdapException { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn1 = new Dn( "dc=b,dc=a" ); Dn dn2 = new Dn( "dc=b,dc=a" ); tree.add( dn1 ); assertThrows( LdapUnwillingToPerformException.class, () -> { tree.add( dn2 ); } ); }
@Test public void testAddNullDN() throws LdapException { DnNode<Dn> tree = new DnNode<Dn>(); assertThrows( LdapUnwillingToPerformException.class, () -> { tree.add( ( Dn ) null, null ); } ); }
@Test public void testAdd2EqualDNs() throws LdapException { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn1 = new Dn( "dc=b,dc=a" ); Dn dn2 = new Dn( "dc=b,dc=a" ); tree.add( dn1, dn1 ); assertThrows( LdapUnwillingToPerformException.class, () -> { tree.add( dn2, dn2 ); } ); } |
### Question:
DnNode { public synchronized boolean hasChildren() { return ( children != null ) && children.size() != 0; } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testHasChildren() throws Exception { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn1 = new Dn( "dc=b,dc=a" ); tree.add( dn1 ); assertTrue( tree.hasChildren() ); Map<String, DnNode<Dn>> children = tree.getChildren(); assertNotNull( children ); DnNode<Dn> child = children.get( new Rdn( "dc=a" ).getNormName() ); assertTrue( child.hasChildren() ); children = child.getChildren(); child = children.get( new Rdn( "dc=b" ).getNormName() ); assertFalse( child.hasChildren() ); } |
### Question:
Asn1Buffer2 { public void put( byte b ) { if ( pos == size ) { extend(); } currentBuffer.buffer[size - pos - 1] = b; pos++; } Asn1Buffer2(); int getPos(); void put( byte b ); void put( byte[] bytes ); byte[] getBytes(); int getSize(); void clear(); @Override String toString(); }### Answer:
@Test @Disabled public void testBytesPerf() { long t0 = System.currentTimeMillis(); for ( int j = 0; j < 1000; j++ ) { Asn1Buffer buffer = new Asn1Buffer(); for ( int i = 0; i < 409600; i++ ) { buffer.put( new byte[] { 0x01, ( byte ) i } ); } } long t1 = System.currentTimeMillis(); System.out.println( "Delta: " + ( t1 - t0 ) ); } |
### Question:
DnNode { public synchronized boolean isLeaf() { return !hasChildren(); } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testIsLeaf() throws Exception { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn = new Dn( "dc=c,dc=b,dc=a" ); tree.add( dn ); assertFalse( tree.isLeaf() ); DnNode<Dn> child = tree.getChild( new Rdn( "dc=a" ) ); assertFalse( child.isLeaf() ); child = child.getChild( new Rdn( "dc=b" ) ); assertFalse( child.isLeaf() ); child = child.getChild( new Rdn( "dc=c" ) ); assertTrue( child.isLeaf() ); } |
### Question:
DnNode { public synchronized N getElement() { return nodeElement; } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testGetElement() throws Exception { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn = new Dn( "dc=c,dc=b,dc=a" ); tree.add( dn, dn ); assertNull( tree.getElement() ); DnNode<Dn> child = tree.getChild( new Rdn( "dc=a" ) ); assertNull( child.getElement() ); child = child.getChild( new Rdn( "dc=b" ) ); assertNull( child.getElement() ); child = child.getChild( new Rdn( "dc=c" ) ); assertEquals( dn, child.getElement() ); } |
### Question:
DnNode { public synchronized boolean hasElement() { return nodeElement != null; } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testHasElement() throws Exception { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn = new Dn( "dc=c,dc=b,dc=a" ); tree.add( dn, dn ); assertFalse( tree.hasElement() ); DnNode<Dn> child = tree.getChild( new Rdn( "dc=a" ) ); assertFalse( child.hasElement() ); child = child.getChild( new Rdn( "dc=b" ) ); assertFalse( child.hasElement() ); child = child.getChild( new Rdn( "dc=c" ) ); assertTrue( child.hasElement() ); } |
### Question:
DnNode { public synchronized int size() { int size = 1; if ( children.size() != 0 ) { for ( DnNode<N> node : children.values() ) { size += node.size(); } } return size; } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testSize() throws LdapException { DnNode<Dn> tree = new DnNode<Dn>(); assertEquals( 1, tree.size() ); tree.add( new Dn( "dc=b,dc=a" ) ); assertEquals( 3, tree.size() ); tree.add( new Dn( "dc=f,dc=a" ) ); assertEquals( 4, tree.size() ); tree.add( new Dn( "dc=a,dc=f,dc=a" ) ); assertEquals( 5, tree.size() ); tree.add( new Dn( "dc=b,dc=f,dc=a" ) ); assertEquals( 6, tree.size() ); tree.add( new Dn( "dc=z,dc=t" ) ); assertEquals( 8, tree.size() ); } |
### Question:
DnNode { public synchronized DnNode<N> getParent() { return parent; } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testGetParent() throws Exception { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn = new Dn( "dc=c,dc=b,dc=a" ); tree.add( dn, dn ); assertNull( tree.getParent() ); DnNode<Dn> child = tree.getChild( new Rdn( "dc=a" ) ); assertEquals( tree, child.getParent() ); DnNode<Dn> child1 = child.getChild( new Rdn( "dc=b" ) ); assertEquals( child, child1.getParent() ); child = child1.getChild( new Rdn( "dc=c" ) ); assertEquals( child1, child.getParent() ); } |
### Question:
DnNode { public synchronized boolean hasParent() { return parent != null; } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testHasParent() throws Exception { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn = new Dn( "dc=c,dc=b,dc=a" ); tree.add( dn, dn ); assertFalse( tree.hasParent() ); DnNode<Dn> child = tree.getChild( new Rdn( "dc=a" ) ); assertTrue( child.hasParent() ); DnNode<Dn> child1 = child.getChild( new Rdn( "dc=b" ) ); assertTrue( child1.hasParent() ); child = child1.getChild( new Rdn( "dc=c" ) ); assertTrue( child.hasParent() ); } |
### Question:
DnNode { public synchronized boolean contains( Rdn rdn ) { return children.containsKey( rdn.getNormName() ); } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testContains() throws Exception { DnNode<Dn> tree = new DnNode<Dn>(); Dn dn = new Dn( "dc=c,dc=b,dc=a" ); tree.add( dn, dn ); Rdn rdnA = new Rdn( "dc=a" ); Rdn rdnB = new Rdn( "dc=b" ); Rdn rdnC = new Rdn( "dc=c" ); assertTrue( tree.contains( rdnA ) ); assertFalse( tree.contains( rdnB ) ); assertFalse( tree.contains( rdnC ) ); DnNode<Dn> child = tree.getChild( rdnA ); assertFalse( child.contains( rdnA ) ); assertTrue( child.contains( rdnB ) ); assertFalse( child.contains( rdnC ) ); child = child.getChild( rdnB ); assertFalse( child.contains( rdnA ) ); assertFalse( child.contains( rdnB ) ); assertTrue( child.contains( rdnC ) ); } |
### Question:
DnNode { public synchronized boolean hasParentElement( Dn dn ) { List<Rdn> rdns = dn.getRdns(); DnNode<N> currentNode = this; boolean hasElement = false; for ( int i = rdns.size() - 1; i >= 0; i-- ) { Rdn rdn = rdns.get( i ); if ( currentNode.hasChildren() ) { currentNode = currentNode.children.get( rdn.getNormName() ); if ( currentNode == null ) { break; } if ( currentNode.hasElement() ) { hasElement = true; } parent = currentNode; } else { break; } } return hasElement; } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testHasParentElement() throws Exception { DnNode<Dn> dnLookupTree = new DnNode<Dn>(); Dn dn1 = new Dn( "dc=directory,dc=apache,dc=org" ); Dn dn2 = new Dn( "dc=mina,dc=apache,dc=org" ); Dn dn3 = new Dn( "dc=test,dc=com" ); Dn dn4 = new Dn( "dc=acme,dc=com" ); Dn dn5 = new Dn( "dc=acme,c=us,dc=com" ); Dn dn6 = new Dn( "dc=empty" ); Dn org = new Dn( "dc=org" ); dnLookupTree.add( dn1, dn1 ); dnLookupTree.add( dn2, dn2 ); dnLookupTree.add( dn3, dn3 ); dnLookupTree.add( dn4, dn4 ); dnLookupTree.add( dn5 ); dnLookupTree.add( dn6, dn6 ); dnLookupTree.add( org, org ); assertTrue( dnLookupTree.hasParentElement( new Dn( "dc=apache,dc=org" ) ) ); assertTrue( dnLookupTree.hasDescendantElement( org ) ); assertFalse( dnLookupTree.hasDescendantElement( new Dn( "c=us,dc=com" ) ) ); Dn dn7 = new Dn( "dc=elem,dc=mina,dc=apache,dc=org" ); dnLookupTree.add( dn7, dn7 ); List<Dn> dns = dnLookupTree.getDescendantElements( org ); assertNotNull( dns ); assertEquals( 2, dns.size() ); assertTrue( dns.contains( dn1 ) ); assertTrue( dns.contains( dn2 ) ); dns = dnLookupTree.getDescendantElements( dn6 ); assertEquals( 0, dns.size() ); } |
### Question:
DnNode { public synchronized void rename( Rdn newRdn ) throws LdapException { Dn temp = nodeDn.getParent(); temp = temp.add( newRdn ); Rdn oldRdn = nodeRdn; nodeRdn = temp.getRdn(); nodeDn = temp; if ( parent != null ) { parent.children.remove( oldRdn.getNormName() ); parent.children.put( nodeRdn.getNormName(), this ); } updateAfterModDn( nodeDn ); } DnNode(); DnNode( N element ); DnNode( Dn dn, N element ); synchronized boolean isLeaf(); synchronized boolean isLeaf( Dn dn ); synchronized int size(); synchronized N getElement(); synchronized N getElement( Dn dn ); synchronized boolean hasElement(); synchronized boolean hasElement( Dn dn ); synchronized boolean hasDescendantElement( Dn dn ); synchronized List<N> getDescendantElements( Dn dn ); synchronized boolean hasChildren(); synchronized boolean hasChildren( Dn dn ); synchronized Map<String, DnNode<N>> getChildren(); synchronized DnNode<N> getParent(); synchronized boolean hasParent(); synchronized boolean hasParent( Dn dn ); synchronized DnNode<N> add( Dn dn ); synchronized DnNode<N> add( Dn dn, N element ); synchronized void remove( Dn dn ); synchronized boolean contains( Rdn rdn ); synchronized DnNode<N> getChild( Rdn rdn ); synchronized Rdn getRdn(); synchronized DnNode<N> getNode( Dn dn ); synchronized boolean hasParentElement( Dn dn ); synchronized DnNode<N> getParentWithElement( Dn dn ); synchronized DnNode<N> getParentWithElement(); synchronized void rename( Rdn newRdn ); synchronized void move( Dn newParent ); @Override String toString(); synchronized Dn getDn(); }### Answer:
@Test public void testRename() throws Exception { DnNode<Dn> rootNode = new DnNode<Dn>(); Dn dn = new Dn( "dc=directory,dc=apache,dc=org" ); rootNode.add( dn ); Rdn childRdn = new Rdn( "dc=org" ); DnNode<Dn> child = rootNode.getChild( childRdn ); assertNotNull( child ); Rdn newChildRdn = new Rdn( "dc=neworg" ); child.rename( newChildRdn ); assertNull( rootNode.getChild( childRdn ) ); assertEquals( new Dn( "dc=neworg" ), child.getDn() ); DnNode<Dn> child2 = child.getChild( new Rdn( "dc=apache" ) ); assertEquals( new Dn( "dc=apache,dc=neworg" ), child2.getDn() ); assertEquals( new Dn( "dc=directory,dc=apache,dc=neworg" ), child2.getChild( new Rdn( "dc=directory" ) ) .getDn() ); assertNotNull( rootNode.getChild( newChildRdn ) ); } |
### Question:
MaxValueCountItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( MaxValueCountElem item : items ) { if ( item != null ) { hash = hash * 17 + item.hashCode(); } else { hash = hash * 17 + 37; } } } return hash; } MaxValueCountItem( Set<MaxValueCountElem> items ); Iterator<MaxValueCountElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testHashCodeReflexive() throws Exception { assertEquals( maxValueCountItemA.hashCode(), maxValueCountItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( maxValueCountItemA.hashCode(), maxValueCountItemACopy.hashCode() ); assertEquals( maxValueCountItemACopy.hashCode(), maxValueCountItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( maxValueCountItemA.hashCode(), maxValueCountItemACopy.hashCode() ); assertEquals( maxValueCountItemACopy.hashCode(), maxValueCountItemB.hashCode() ); assertEquals( maxValueCountItemA.hashCode(), maxValueCountItemB.hashCode() ); } |
### Question:
SpringCloudFunctionInvoker implements FunctionInvoker, Closeable { @Override public Optional<OutputEvent> tryInvoke(InvocationContext ctx, InputEvent evt) { SpringCloudMethod method = loader.getFunction(); Object[] userFunctionParams = coerceParameters(ctx, method, evt); Object result = tryInvoke(method, userFunctionParams); return coerceReturnValue(ctx, method, result); } SpringCloudFunctionInvoker(SpringCloudFunctionLoader loader); SpringCloudFunctionInvoker(Class<?> configClass); @Override Optional<OutputEvent> tryInvoke(InvocationContext ctx, InputEvent evt); @Override void close(); }### Answer:
@Test public void invokesFunctionWithFluxOfMultipleItems() { SpringCloudFunction fnWrapper = new SpringCloudFunction(x -> x, new SimpleFunctionInspector()); Object result = invoker.tryInvoke(fnWrapper, new Object[]{ Arrays.asList("hello", "world") }); assertThat(result).isInstanceOf(List.class); assertThat((List) result).containsSequence("hello", "world"); }
@Test public void invokesFunctionWithEmptyFlux() { SpringCloudFunction fnWrapper = new SpringCloudFunction(x -> x, new SimpleFunctionInspector()); Object result = invoker.tryInvoke(fnWrapper, new Object[0]); assertThat(result).isNull(); }
@Test public void invokesFunctionWithFluxOfSingleItem() { SpringCloudFunction fnWrapper = new SpringCloudFunction(x -> x, new SimpleFunctionInspector()); Object result = invoker.tryInvoke(fnWrapper, new Object[]{ "hello" }); assertThat(result).isInstanceOf(String.class); assertThat(result).isEqualTo("hello"); } |
### Question:
RemoteFlowApiClient implements CompleterClient { @Override public CompletionId supply(FlowId flowId, Serializable supplier, CodeLocation codeLocation) { return addStageWithClosure(APIModel.CompletionOperation.SUPPLY, flowId, supplier, codeLocation, Collections.emptyList()); } RemoteFlowApiClient(String apiUrlBase, BlobStoreClient blobClient, HttpClient httpClient); @Override FlowId createFlow(String functionId); @Override CompletionId supply(FlowId flowId, Serializable supplier, CodeLocation codeLocation); @Override CompletionId thenApply(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId thenCompose(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId whenComplete(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId thenAccept(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId thenRun(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId acceptEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation); @Override CompletionId applyToEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation); @Override CompletionId thenAcceptBoth(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation); @Override CompletionId createCompletion(FlowId flowId, CodeLocation codeLocation); @Override CompletionId invokeFunction(FlowId flowId, String functionId, byte[] data, HttpMethod method, Headers headers, CodeLocation codeLocation); @Override CompletionId completedValue(FlowId flowId, boolean success, Object value, CodeLocation codeLocation); @Override CompletionId allOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation); @Override CompletionId handle(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId exceptionally(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId exceptionallyCompose(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation); @Override CompletionId thenCombine(FlowId flowId, CompletionId completionId, Serializable fn, CompletionId alternate, CodeLocation codeLocation); @Override boolean complete(FlowId flowId, CompletionId completionId, Object value, CodeLocation codeLocation); @Override boolean completeExceptionally(FlowId flowId, CompletionId completionId, Throwable value, CodeLocation codeLocation); @Override CompletionId anyOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation); @Override CompletionId delay(FlowId flowId, long l, CodeLocation codeLocation); @Override Object waitForCompletion(FlowId flowId, CompletionId id, ClassLoader ignored, long timeout, TimeUnit unit); @Override Object waitForCompletion(FlowId flowId, CompletionId id, ClassLoader ignored); void commit(FlowId flowId); @Override void addTerminationHook(FlowId flowId, Serializable code, CodeLocation codeLocation); static final String CONTENT_TYPE_HEADER; static final String CONTENT_TYPE_JAVA_OBJECT; static final String CONTENT_TYPE_OCTET_STREAM; }### Answer:
@Test public void supply() throws Exception { String contentType = "application/java-serialized-object"; String testBlobId = "BLOBID"; BlobResponse blobResponse = makeBlobResponse(lambdaBytes, contentType, testBlobId); when(blobStoreClient.writeBlob(testFlowId, lambdaBytes, contentType)).thenReturn(blobResponse); HttpClient.HttpResponse response = responseWithAddStageResponse(testFlowId, testStageId); when(mockHttpClient.execute(requestContainingAddStageRequest(blobResponse.blobId, Collections.emptyList()))).thenReturn(response); CompletionId completionId = completerClient.supply(new FlowId(testFlowId), serializableLambda, codeLocation); assertNotNull(completionId); assertEquals(completionId.getId(), testStageId); } |
### Question:
Headers implements Serializable { public static String canonicalKey(String key) { if (!headerName.matcher(key).matches()) { return key; } String parts[] = key.split("-", -1); for (int i = 0; i < parts.length; i++) { String p = parts[i]; if (p.length() > 0) { parts[i] = p.substring(0, 1).toUpperCase() + p.substring(1).toLowerCase(); } } return String.join("-", parts); } private Headers(Map<String, List<String>> headersIn); Map getAll(); static String canonicalKey(String key); static Headers fromMap(Map<String, String> headers); static Headers fromMultiHeaderMap(Map<String, List<String>> headers); static Headers emptyHeaders(); Headers setHeaders(Map<String, List<String>> vals); Headers addHeader(String key, String v1, String... vs); Headers setHeader(String key, String v1, String... vs); Headers setHeader(String key, Collection<String> vs); Headers removeHeader(String key); Optional<String> get(String key); Collection<String> keys(); Map<String, List<String>> asMap(); List<String> getAllValues(String key); int hashCode(); boolean equals(Object other); @Override String toString(); }### Answer:
@Test public void shouldCanonicalizeHeaders(){ for (String[] v : new String[][] { {"",""}, {"a","A"}, {"fn-ID-","Fn-Id-"}, {"myHeader-VaLue","Myheader-Value"}, {" Not a Header "," Not a Header "}, {"-","-"}, {"--","--"}, {"a-","A-"}, {"-a","-A"} }){ assertThat(Headers.canonicalKey(v[0])).isEqualTo(v[1]); } } |
### Question:
InputHandler { Map<String, InterceptorInstance> resolveInputInterceptors(String algorithmClassName) { Map<String,InterceptorInstance> result = new HashMap<String, InterceptorInstance>(); Class<?> clazz; try { clazz = Class.forName(algorithmClassName, false, getClass().getClassLoader()); } catch (ClassNotFoundException e) { LOGGER.warn("Could not find class {}", algorithmClassName); return result; } DataInputInterceptorImplementations annotation = clazz.getAnnotation(DataInputInterceptors.DataInputInterceptorImplementations.class); if (annotation != null) { Class<?> interceptorClazz; try { interceptorClazz = Class.forName(annotation.value()); } catch (ClassNotFoundException e) { LOGGER.warn("Could not find class "+ annotation.value(), e); return result; } if (DataInputInterceptors.class.isAssignableFrom(interceptorClazz)) { DataInputInterceptors instance; try { instance = (DataInputInterceptors) interceptorClazz.newInstance(); } catch (InstantiationException e) { LOGGER.warn("Could not instantiate class "+ interceptorClazz, e); return result; } catch (IllegalAccessException e) { LOGGER.warn("Could not access class "+ interceptorClazz, e); return result; } return instance.getInterceptors(); } } return result; } private InputHandler(Builder builder); Map<String, List<IData>> getParsedInputData(); }### Answer:
@Test public void testInputHandlerResolveInputInterceptors() throws ExceptionReport, XmlException, IOException { System.out.println("Testing testInputHandlerResolveInputInterceptors..."); InputHandler instance = new InputHandler.Builder(simpleBufferAlgorithmInputArray, "org.n52.wps.server.algorithm.SimpleBufferAlgorithm").build(); Map<String, InterceptorInstance> resolveInputInterceptors = instance.resolveInputInterceptors("org.n52.wps.server.algorithm.SimpleBufferAlgorithm"); assertThat(resolveInputInterceptors.size(), equalTo(0)); instance = new InputHandler.Builder(dummyTestClassAlgorithmInputArray, "org.n52.wps.server.algorithm.test.DummyTestClass").build(); resolveInputInterceptors = instance.resolveInputInterceptors("org.n52.wps.server.algorithm.SimpleBufferAlgorithm"); assertThat(resolveInputInterceptors.size(), equalTo(0)); } |
### Question:
ExecutionContext { public List<OutputDefinitionType> getOutputs() { return this.outputDefinitionTypes; } ExecutionContext(); ExecutionContext(OutputDefinitionType output); ExecutionContext(List< ? extends OutputDefinitionType> outputs); String getTempDirectoryPath(); List<OutputDefinitionType> getOutputs(); }### Answer:
@Test public void testConstructor() { ExecutionContext ec; ec = new ExecutionContext((OutputDefinitionType)null); assertNotNull(ec.getOutputs()); assertEquals(0, ec.getOutputs().size()); ec = new ExecutionContext(Arrays.asList(new OutputDefinitionType[0])); assertNotNull(ec.getOutputs()); assertEquals(0, ec.getOutputs().size()); ec = new ExecutionContext(Arrays.asList(new OutputDefinitionType[1])); assertNotNull(ec.getOutputs()); assertEquals(1, ec.getOutputs().size()); ec = new ExecutionContext((List<OutputDefinitionType>)null); assertNotNull(ec.getOutputs()); assertEquals(0, ec.getOutputs().size()); ec = new ExecutionContext(OutputDefinitionType.Factory.newInstance()); assertNotNull(ec.getOutputs()); assertEquals(1, ec.getOutputs().size()); ec = new ExecutionContext(); assertNotNull(ec.getOutputs()); assertEquals(0, ec.getOutputs().size()); } |
### Question:
InputHandler { InputDescriptionType getInputReferenceDescriptionType(String inputId) { for (InputDescriptionType tempDesc : this.processDesc.getDataInputs().getInputArray()) { if (inputId.equals(tempDesc.getIdentifier().getStringValue())) { return tempDesc; } } return null; } private InputHandler(Builder builder); Map<String, List<IData>> getParsedInputData(); }### Answer:
@Test public void testInputHandlerResolveInputDescriptionTypes() throws ExceptionReport, XmlException, IOException { System.out.println("Testing testInputHandlerResolveInputDescriptionTypes..."); InputHandler instance = new InputHandler.Builder(simpleBufferAlgorithmInputArray, "org.n52.wps.server.algorithm.SimpleBufferAlgorithm").build(); InputDescriptionType idt = instance.getInputReferenceDescriptionType("data"); assertThat(idt, is(notNullValue())); assertThat(idt.getMaxOccurs().intValue(), equalTo(1)); assertThat(idt.getMinOccurs().intValue(), equalTo(1)); instance = new InputHandler.Builder(dummyTestClassAlgorithmInputArray, "org.n52.wps.server.algorithm.test.DummyTestClass").build(); idt = instance.getInputReferenceDescriptionType("BBOXInputData"); assertThat(idt, is(notNullValue())); assertThat(idt.getMaxOccurs().intValue(), equalTo(1)); assertThat(idt.getMinOccurs().intValue(), equalTo(0)); } |
### Question:
ExecuteRequest extends Request implements IObserver { public void updateStatusError(String errorMessage) { StatusType status = StatusType.Factory.newInstance(); net.opengis.ows.x11.ExceptionReportDocument.ExceptionReport excRep = status .addNewProcessFailed().addNewExceptionReport(); excRep.setVersion("1.0.0"); ExceptionType excType = excRep.addNewException(); excType.addNewExceptionText().setStringValue(errorMessage); excType.setExceptionCode(ExceptionReport.NO_APPLICABLE_CODE); updateStatus(status); } ExecuteRequest(Document doc); ExecuteRequest(CaseInsensitiveMap ciMap); void getKVPDataInputs(); boolean validate(); Response call(); String getAlgorithmIdentifier(); Execute getExecute(); Map<String, IData> getAttachedResult(); boolean isStoreResponse(); boolean isQuickStatus(); ExecuteResponseBuilder getExecuteResponseBuilder(); boolean isRawData(); void update(ISubject subject); void updateStatusAccepted(); void updateStatusStarted(); void updateStatusSuccess(); void updateStatusError(String errorMessage); }### Answer:
@Test public void testUpdateStatusError() throws ExceptionReport, XmlException, IOException, SAXException, ParserConfigurationException { FileInputStream fis = new FileInputStream(new File("src/test/resources/LRDTCCorruptInputResponseDocStatusTrue.xml")); Document doc = fac.newDocumentBuilder().parse(fis); ExecuteRequest request = new ExecuteRequest(doc); String exceptionText = "TestError"; request.updateStatusError(exceptionText); File response = DatabaseFactory.getDatabase().lookupResponseAsFile(request.getUniqueId().toString()); ExecuteResponseDocument responseDoc = ExecuteResponseDocument.Factory.parse(response); StatusType statusType = responseDoc.getExecuteResponse().getStatus(); assertTrue(validateExecuteResponse(responseDoc)); assertTrue(statusType.isSetProcessFailed()); assertTrue(statusType.getProcessFailed().getExceptionReport().getExceptionArray(0).getExceptionTextArray(0).equals(exceptionText)); } |
### Question:
OutputDataItem extends ResponseData { public void updateResponseForLiteralData(ExecuteResponseDocument res, String dataTypeReference){ OutputDataType output = prepareOutput(res); String processValue = BasicXMLTypeFactory.getStringRepresentation(dataTypeReference, obj); LiteralDataType literalData = output.addNewData().addNewLiteralData(); if (dataTypeReference != null) { literalData.setDataType(dataTypeReference); } literalData.setStringValue(processValue); if(obj instanceof AbstractLiteralDataBinding){ String uom = ((AbstractLiteralDataBinding)obj).getUnitOfMeasurement(); if(uom != null && !uom.equals("")){ literalData.setUom(uom); } } } OutputDataItem(IData obj, String id, String schema, String encoding,
String mimeType, LanguageStringType title, String algorithmIdentifier, ProcessDescriptionType description); void updateResponseForInlineComplexData(ExecuteResponseDocument res); void updateResponseForLiteralData(ExecuteResponseDocument res, String dataTypeReference); void updateResponseAsReference(ExecuteResponseDocument res, String reqID, String mimeType); void updateResponseForBBOXData(ExecuteResponseDocument res, IBBOXData bbox); }### Answer:
@Test public void testUpdateResponseForLiteralData() { for (ILiteralData literalData : literalDataList) { try { testLiteralOutput(literalData); } catch (Exception e) { System.out.println("Test failed for " + literalData.getClass() + " " + e); } mockupResponseDocument.getExecuteResponse().getProcessOutputs() .removeOutput(0); } } |
### Question:
RawData extends ResponseData { public InputStream getAsStream() throws ExceptionReport { try { if(obj instanceof ILiteralData){ return new ByteArrayInputStream(String.valueOf(obj.getPayload()).getBytes(Charsets.UTF_8)); } if(obj instanceof IBBOXData){ IBBOXData bbox = (IBBOXData) obj; StringBuilder builder = new StringBuilder(); builder.append("<wps:BoundingBoxData"); appendAttr(builder, "xmlns:ows", XMLBeansHelper.NS_OWS_1_1); appendAttr(builder, "xmlns:wps", XMLBeansHelper.NS_WPS_1_0_0); if (bbox.getCRS() != null) { appendAttr(builder, "crs", escape(bbox.getCRS())); } appendAttr(builder, "dimensions", bbox.getDimension()); builder.append(">"); builder.append("\n\t"); builder.append("<ows:LowerCorner>"); SPACE_JOINER.appendTo(builder, Doubles.asList(bbox.getLowerCorner())); builder.append("</ows:LowerCorner>"); builder.append("\n\t"); builder.append("<ows:UpperCorner>"); SPACE_JOINER.appendTo(builder, Doubles.asList(bbox.getUpperCorner())); builder.append("</ows:UpperCorner>"); builder.append("\n"); builder.append("</wps:BoundingBoxData>"); return new ByteArrayInputStream(builder.toString().getBytes(Charsets.UTF_8)); } if(encoding == null || "".equals(encoding) || encoding.equalsIgnoreCase(IOHandler.DEFAULT_ENCODING)){ return generator.generateStream(obj, mimeType, schema); } else if(encoding.equalsIgnoreCase(IOHandler.ENCODING_BASE64)){ return generator.generateBase64Stream(obj, mimeType, schema); } } catch (IOException e) { throw new ExceptionReport("Error while generating Complex Data out of the process result", ExceptionReport.NO_APPLICABLE_CODE, e); } throw new ExceptionReport("Could not determine encoding. Use default (=not set) or base64", ExceptionReport.NO_APPLICABLE_CODE); } RawData(IData obj, String id, String schema, String encoding,
String mimeType, String algorithmIdentifier,
ProcessDescriptionType description); InputStream getAsStream(); static final Joiner SPACE_JOINER; }### Answer:
@Test public void testBBoxRawDataOutputCRS(){ IData envelope = new BoundingBoxData( new double[] { 46, 102 }, new double[] { 47, 103 }, "EPSG:4326"); InputStream is; try { RawData bboxRawData = new RawData(envelope, "BBOXOutputData", null, null, null, identifier, processDescription); is = bboxRawData.getAsStream(); XmlObject bboxXMLObject = XmlObject.Factory.parse(is); assertTrue(bboxXMLObject != null); assertTrue(bboxXMLObject.getDomNode().getFirstChild().getNodeName().equals("wps:BoundingBoxData")); } catch (Exception e) { fail(e.getMessage()); } }
@Test public void testBBoxRawDataOutput(){ IData envelope = new BoundingBoxData( new double[] { 46, 102 }, new double[] { 47, 103 }, null); InputStream is; try { RawData bboxRawData = new RawData(envelope, "BBOXOutputData", null, null, null, identifier, processDescription); is = bboxRawData.getAsStream(); XmlObject bboxXMLObject = XmlObject.Factory.parse(is); assertTrue(bboxXMLObject != null); assertTrue(bboxXMLObject.getDomNode().getFirstChild().getNodeName().equals("wps:BoundingBoxData")); } catch (Exception e) { fail(e.getMessage()); } } |
### Question:
MainViewModel extends AndroidViewModel { void init() { rmConnector.connect(getApplication()); rmConnector.setOnDataReceiveListener(event -> receiveColourMessage(event)); rmConnector.setOnPeerChangedListener(event -> liveDataPeerChangedEvent.postValue(event)); rmConnector.setOnConnectSuccessListener(meshId -> liveDataMyMeshId.setValue(meshId)); } MainViewModel(@NonNull Application application); void setRightMeshConnector(RightMeshConnector rmConnector); }### Answer:
@Test public void init_isCalled() { spyViewModel.init(); verify(rightMeshConnector).setOnConnectSuccessListener(any()); verify(rightMeshConnector).setOnPeerChangedListener(any()); verify(rightMeshConnector).setOnDataReceiveListener(any()); verify(spyViewModel).init(); } |
### Question:
MainViewModel extends AndroidViewModel { void toRightMeshWalletActivty() { try { rmConnector.toRightMeshWalletActivty(); } catch (RightMeshException e) { Log.e(TAG, e.toString()); } } MainViewModel(@NonNull Application application); void setRightMeshConnector(RightMeshConnector rmConnector); }### Answer:
@Test public void toRightMeshWalletActivty_isCalled() throws RightMeshException { spyViewModel.toRightMeshWalletActivty(); verify(rightMeshConnector).toRightMeshWalletActivty(); verify(spyViewModel).toRightMeshWalletActivty(); } |
### Question:
MainViewModel extends AndroidViewModel { void sendColorMsg(MeshId targetMeshId, Colour msgColor) { try { if (targetMeshId != null) { String payload = targetMeshId.toString() + ":" + msgColor.toString(); rmConnector.sendDataReliable(targetMeshId, payload); } } catch (RightMeshException.RightMeshServiceDisconnectedException sde) { Log.e(TAG, "Service disconnected while sending data, with message: " + sde.getMessage()); liveDataNotification.setValue(sde.getMessage()); } catch (RightMeshRuntimeException.RightMeshLicenseException le) { Log.e(TAG, le.getMessage()); liveDataNotification.setValue(le.getMessage()); } catch (RightMeshException rme) { Log.e(TAG, "Unable to find next hop to peer, with message: " + rme.getMessage()); liveDataNotification.setValue(rme.getMessage()); } } MainViewModel(@NonNull Application application); void setRightMeshConnector(RightMeshConnector rmConnector); }### Answer:
@Test public void sendColorMsg_nullTargetMeshId() throws RightMeshException { MeshId targetId = null; Colour msgColor = Colour.RED; String payload = String.valueOf(targetId) + ":" + msgColor; spyViewModel.sendColorMsg(targetId, msgColor); verify(rightMeshConnector, never()).sendDataReliable(targetId, payload); verify(spyViewModel).sendColorMsg(targetId, msgColor); }
@Test public void sendColorMsg_targetMeshId() throws RightMeshException { MeshId targetId = mockMeshId; Colour msgColor = Colour.RED; String payload = String.valueOf(targetId) + ":" + msgColor; spyViewModel.sendColorMsg(targetId, msgColor); verify(rightMeshConnector).sendDataReliable(targetId, payload); verify(spyViewModel).sendColorMsg(targetId, msgColor); } |
### Question:
MainViewModel extends AndroidViewModel { @Override protected void onCleared() { try { rmConnector.stop(); } catch (RightMeshException.RightMeshServiceDisconnectedException e) { Log.e(TAG, "Service disconnected before stopping AndroidMeshManager with message" + e.getMessage()); } } MainViewModel(@NonNull Application application); void setRightMeshConnector(RightMeshConnector rmConnector); }### Answer:
@Test public void onCleared_isCalled() throws RightMeshException { spyViewModel.onCleared(); verify(rightMeshConnector).stop(); verify(spyViewModel).onCleared(); } |
### Question:
RightMeshConnector implements MeshStateListener { @Override public void meshStateChanged(MeshId meshId, int state) { if (state == SUCCESS) { try { androidMeshManager.bind(meshPort); if (connectSuccessListener != null) { connectSuccessListener.onConnectSuccess(meshId); } androidMeshManager.on(DATA_RECEIVED, event -> { if (dataReceiveListener != null) { dataReceiveListener.onDataReceive(event); } }); androidMeshManager.on(PEER_CHANGED, event -> { if (peerchangedListener != null) { peerchangedListener.onPeerChange(event); } }); } catch (RightMeshException.RightMeshServiceDisconnectedException sde) { Log.e(TAG, "Service disconnected while binding, with message: " + sde.getMessage()); } catch (RightMeshException rme) { Log.e(TAG, "MeshPort already bound, with message: " + rme.getMessage()); } } } RightMeshConnector(int meshPort); void connect(Context context); @Override void meshStateChanged(MeshId meshId, int state); void stop(); void setOnDataReceiveListener(OnDataReceiveListener listener); void setOnPeerChangedListener(OnPeerChangedListener listener); void setOnConnectSuccessListener(OnConnectSuccessListener listener); void toRightMeshWalletActivty(); void sendDataReliable(MeshId targetMeshId, String payload); void setAndroidMeshManager(AndroidMeshManager androidMeshManager); }### Answer:
@Test public void meshStateChanged_successEvent() throws RightMeshException, ClassNotFoundException { spyRightMeshConnector.meshStateChanged(meshId, MeshStateListener.SUCCESS); verify(androidMeshManager).bind(MESH_PORT); verify(spyRightMeshConnector).meshStateChanged(meshId, MeshStateListener.SUCCESS); } |
### Question:
RightMeshConnector implements MeshStateListener { public void stop() throws RightMeshException.RightMeshServiceDisconnectedException { androidMeshManager.stop(); } RightMeshConnector(int meshPort); void connect(Context context); @Override void meshStateChanged(MeshId meshId, int state); void stop(); void setOnDataReceiveListener(OnDataReceiveListener listener); void setOnPeerChangedListener(OnPeerChangedListener listener); void setOnConnectSuccessListener(OnConnectSuccessListener listener); void toRightMeshWalletActivty(); void sendDataReliable(MeshId targetMeshId, String payload); void setAndroidMeshManager(AndroidMeshManager androidMeshManager); }### Answer:
@Test public void stop_isCalled() throws RightMeshException.RightMeshServiceDisconnectedException { spyRightMeshConnector.stop(); verify(androidMeshManager).stop(); verify(spyRightMeshConnector).stop(); } |
### Question:
RightMeshConnector implements MeshStateListener { public void toRightMeshWalletActivty() throws RightMeshException { this.androidMeshManager.showSettingsActivity(); } RightMeshConnector(int meshPort); void connect(Context context); @Override void meshStateChanged(MeshId meshId, int state); void stop(); void setOnDataReceiveListener(OnDataReceiveListener listener); void setOnPeerChangedListener(OnPeerChangedListener listener); void setOnConnectSuccessListener(OnConnectSuccessListener listener); void toRightMeshWalletActivty(); void sendDataReliable(MeshId targetMeshId, String payload); void setAndroidMeshManager(AndroidMeshManager androidMeshManager); }### Answer:
@Test public void toRightMeshWalletActivty_isCalled() throws RightMeshException { spyRightMeshConnector.toRightMeshWalletActivty(); verify(androidMeshManager).showSettingsActivity(); verify(spyRightMeshConnector).toRightMeshWalletActivty(); } |
### Question:
RightMeshConnector implements MeshStateListener { public void sendDataReliable(MeshId targetMeshId, String payload) throws RightMeshException, RightMeshException.RightMeshServiceDisconnectedException { androidMeshManager.sendDataReliable(androidMeshManager.getNextHopPeer(targetMeshId), meshPort, payload.getBytes(Charset.forName("UTF-8"))); } RightMeshConnector(int meshPort); void connect(Context context); @Override void meshStateChanged(MeshId meshId, int state); void stop(); void setOnDataReceiveListener(OnDataReceiveListener listener); void setOnPeerChangedListener(OnPeerChangedListener listener); void setOnConnectSuccessListener(OnConnectSuccessListener listener); void toRightMeshWalletActivty(); void sendDataReliable(MeshId targetMeshId, String payload); void setAndroidMeshManager(AndroidMeshManager androidMeshManager); }### Answer:
@Test public void sendDataReliable_isCalled() throws RightMeshException { String payload = "abc"; spyRightMeshConnector.sendDataReliable(meshId, payload); verify(spyRightMeshConnector).sendDataReliable(any(), eq(payload)); } |
### Question:
ParseBoolean { public int parse() { String expression = " if(" + _input + "){" + "returnValue = VALUEA;" + "}" + " else { returnValue = VALUEB; }"; expression = expression.replaceAll("0", " false " ); expression = expression.replaceAll("1", " true " ); expression = expression.replaceAll("\\*", " && " ); expression = expression.replaceAll("\\+", " || " ); expression = expression.replace("VALUEA", " \"1\" " ); expression = expression.replace("VALUEB", " \"0\" " ); System.out.println(expression); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js"); Object result = null; try { result = engine.eval(expression); } catch (ScriptException e) { } return result == null ? 0 :Integer.parseInt(result.toString()); } ParseBoolean(String input); int parse(); }### Answer:
@Test public void test1() { String input = "(1+0*1)"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",1, testResults ); }
@Test public void test2() { String input = "(!0)"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",1, testResults ); }
@Test public void test3() { String input = "0"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",0, testResults ); }
@Test public void test4() { String input = "0 * 1 * 1"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",0, testResults ); }
@Test public void test5() { String input = "(1+0)"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",1, testResults ); }
@Test public void test6() { String input = "!0 * 0 + 1"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",1, testResults ); }
@Test public void test7() { String input = "(0+1) * (1+0)"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",1, testResults ); }
@Test public void test8() { String input = "((0+0+(1+!1+!(0 + !(0*1+0*1*1+1*0)+1)+0*1)+1*0*0)+0*1)"; ParseBoolean tester = new ParseBoolean(input); int testResults = tester.parse(); assertEquals("Result",1, testResults ); } |
### Question:
ParseBooleanOriginal { public int process() { _input = _input.replaceAll(" ", ""); _input = _input.replaceAll("!1", "0"); _input = _input.replaceAll("!0", "1"); Matcher m = p.matcher(_input); if(m.find()) { _input = _input.substring(1,_input.length()-1); } Matcher m1 = p1.matcher(_input); Matcher m2 = p2.matcher(_input); if(m1.find() || m2.find()) { return 1; } Matcher m4 = p4.matcher(_input); String foundInnerLogic; String parsed; while (m4.find()) { foundInnerLogic = m4.group(); if(foundInnerLogic != null){ parsed = parseInnerLogic(foundInnerLogic); String matched = foundInnerLogic; _input = _input.replace(matched, parsed); _input = _input.replace("!0", "1"); _input = _input.replace("!1", "0"); m4 = p4.matcher(_input); } } _input = parseInnerLogic(_input); return Integer.parseInt(_input); } ParseBooleanOriginal(String input); int process(); static void main(String[] args); }### Answer:
@Test public void test3() { String input = "0"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",0, testResults ); }
@Test public void test4() { String input = "0 * 1 * 1"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",0, testResults ); }
@Test public void test5() { String input = "(1+0)"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",1, testResults ); }
@Test public void test6() { String input = "!0 * 0 + 1"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",1, testResults ); }
@Test public void test7() { String input = "(0+1) * (1+0)"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",1, testResults ); }
@Test public void test8() { String input = "((0+0+(1+!1+!(0 + !(0*1+0*1*1+1*0)+1)+0*1)+1*0*0)+0*1)"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",1, testResults ); }
@Test public void test1() { String input = "(1+0*1)"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",1, testResults ); }
@Test public void test2() { String input = "(!0)"; ParseBooleanOriginal tester = new ParseBooleanOriginal(input); int testResults = tester.process(); assertEquals("Result",1, testResults ); } |
### Question:
SecretSantaFinder { public Map<String, String> pair() { List<Family> families = new ArrayList<Family>(); if(2*maxFamilyMembers > totalNames){ return null; } for(String key: familyMembers.keySet()) { families.add(familyMembers.get(key)) ; } Collections.sort(families); List<String> receiveList = new ArrayList<String>(totalNames); List<String> sendList = new ArrayList<String>(totalNames); List<String> largestFamilyMembers = new ArrayList<String>(); Map<String, String> secretList = new HashMap<String,String>(); for(int i=0;i < families.size();i++) { List<String> names = families.get(i).members; receiveList.addAll(names); if(i== 0) { largestFamilyMembers = names; } else { sendList.addAll(names); } } sendList.addAll(largestFamilyMembers); for(int i=0;i < sendList.size();i++) { secretList.put(sendList.get(i), receiveList.get(i)); } return secretList; } SecretSantaFinder(String[] lists); Map<String, String> pair(); static void main(String[] args); }### Answer:
@Test public void testTooManyInAFamily() { String names = "A Smith, B Smith, C Smith, D Andersen, E Andersen"; String[] nameList = names.split(","); SecretSantaFinder ssf = new SecretSantaFinder(nameList); assertEquals(ssf.pair(), null); }
@Test public void testUnique() { String names = "A Smith, B Smith, C Smith, D Andersen, E Andersen,F Andersen, G Jackson"; String[] nameList = names.split(","); SecretSantaFinder ssf = new SecretSantaFinder(nameList); Map<String,String> pairs = ssf.pair(); assertEquals(pairs.size(), 7); for(String key: pairs.keySet()) { assertFalse(key.equals(pairs.get(key))); String[] giver = key.split(" "); String[] receiver = pairs.get(key).split(" "); assertFalse(giver[1].equals(receiver[1])); } } |
### Question:
CyclicWordsKata { public List<List<String>> process() { List<List<String>> processed = new ArrayList<List<String>>(); Map<Integer,List<String>> buckets ; List<List<String>> returnArray ; buckets = separateInputBySize(_input); if(buckets == null) return processed; for(int size: buckets.keySet()) { List<String> elements = buckets.get(size); System.out.println("size " + size); while(elements != null && elements.size() > 0) { returnArray = processSameSizeArray(elements); elements = returnArray.get(1) ; processed.add(returnArray.get(0)); } } return processed; } CyclicWordsKata(String[] input); List<List<String>> process(); Map<Integer,List<String>> separateInputBySize(String[] input); String joinStringArray(List<String> arrayList, String connector); static void main(String[] args); }### Answer:
@Test public void testOneCyclicPair() { String[] input = {"abc","acb", "cab"}; CyclicWordsKata tester = new CyclicWordsKata(input); List<List<String>> results = tester.process(); assertEquals("Result", 2, results.size()); }
@Test public void testNull() { String[] input = null; CyclicWordsKata tester = new CyclicWordsKata(input); List<List<String>> results = tester.process(); assertNull("results", results); } |
### Question:
ParseRomanNumerals { public String parse() { String returnValue = ""; String prefix = ""; String suffix = ""; while(_input/1000 > 0 ) { int current = _input/1000; int toBeParsed = _input%1000; returnValue = prefix + parseUnder1000(toBeParsed) + suffix + returnValue; _input = current; prefix += "("; suffix += ")"; } returnValue = prefix + parseUnder1000(_input) + suffix + returnValue; returnValue = returnValue.replaceAll("\\(I\\)", "M"); returnValue = returnValue.replaceAll("\\(II\\)", "MM"); returnValue = returnValue.replaceAll("\\(III\\)", "MMM"); return returnValue; } ParseRomanNumerals(int input); String parse(); static void main(String[] args); }### Answer:
@Test public void test1() { int input = 1879; ParseRomanNumerals tester = new ParseRomanNumerals(input); String testResults = tester.parse(); assertEquals("Result","MDCCCLXXIX", testResults ); }
@Test public void test2() { int input = 1; ParseRomanNumerals tester = new ParseRomanNumerals(input); String testResults = tester.parse(); assertEquals("Result","I", testResults ); }
@Test public void test3() { int input = 2010; ParseRomanNumerals tester = new ParseRomanNumerals(input); String testResults = tester.parse(); assertEquals("Result","MMX", testResults ); }
@Test public void test4() { int input = 47; ParseRomanNumerals tester = new ParseRomanNumerals(input); String testResults = tester.parse(); assertEquals("Result","XLVII", testResults ); }
@Test public void test5() { int input = 3888; ParseRomanNumerals tester = new ParseRomanNumerals(input); String testResults = tester.parse(); assertEquals("Result","MMMDCCCLXXXVIII", testResults ); } |
### Question:
StateMachine { public String execute(String input) { String startState = entryState; for(int i = 0; i < input.length();i++){ char event = input.charAt(i) ; if(_symbols.indexOf(event) < 0) { return null; } String key = startState + "_" + event; if (endStates.containsKey(key)) { startState = endStates.get(key); } } if (states.containsKey(startState)) { return states.get(startState); } return null; } StateMachine(String symbols, String statesIn, String transitions); String execute(String input); static void main(String[] args); }### Answer:
@Test public void test1 () { StateMachine fsm = new StateMachine("0,1", "EVEN:pass,ODD:fail,BAD:fail", "EVEN:ODD:1,ODD:EVEN:1,ODD:BAD:0"); assertEquals("pass", fsm.execute("00110")); assertEquals("fail", fsm.execute("00111")); assertEquals("fail", fsm.execute("001110000110011")); assertEquals("fail", null,fsm.execute("0011100001130011")); } |
### Question:
ShellMode { public static ShellMode from(String... arguments) { if (runInBatchMode(arguments)) { return new BatchMode(extractCommand(arguments)); } return new InteractiveMode(); } static String usage(); static ShellMode from(String... arguments); static ShellMode batch(String command); static ShellMode interactive(); abstract void start(); @Override final boolean equals(Object object); @Override abstract String toString(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void illegalFlagsShouldBeDetected() { ShellMode mode = ShellMode.from("--interactive --foo"); } |
### Question:
Script extends ShellCommand implements Iterable<ShellCommand> { public Script(List<ShellCommand> commands) { this.commands = new ArrayList<ShellCommand>(commands); } Script(List<ShellCommand> commands); @Override void execute(ShellCommandHandler handler); Iterator<ShellCommand> iterator(); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void toFileShouldCreateANonEmptyFile() throws FileNotFoundException { final ShellCommand script = script(history(), version(), exit()); final String destination = "test.txt"; script.toFile(destination); File file = new File(destination); assertThat("no file generated!", file.exists()); assertThat("empty file generated!", file.length(), is(greaterThan(0L))); file.delete(); }
@Test public void generatedScriptsShouldBeReadble() throws Exception { final String destination = "test.txt"; final ShellCommand script = script(history(), version(), exit()); try { script.toFile(destination); final ShellCommand script2 = fromFile(destination); assertThat("Different files", script2, is(equalTo(script))); } catch (Exception e) { throw e; } finally { File file = new File(destination); file.delete(); } } |
### Question:
AuthResource { public TempTokenResponse temporaryAuthToken(String scope) throws StorageException, UnsupportedEncodingException { if (Strings.isNullOrEmpty(scope)) { scope = "all"; } String tempToken = sessionManager.storeNewTempToken(); String xanauthURL = "xanauth: + URLEncoder.encode(scope, "UTF-8"); TempTokenResponse tempTokenResponse = new TempTokenResponse(); tempTokenResponse.xanauth = xanauthURL; tempTokenResponse.token = tempToken; return tempTokenResponse; } AuthResource(SessionManager sessionManager, ObjectMapper mapper, String host); SessionResponse getSessionToken(String header64, String claim64, String sig64); TempTokenResponse temporaryAuthToken(String scope); }### Answer:
@Test public void temporaryAuthToken() throws Exception { SessionManager mockManager = mock(SessionManager.class); when(mockManager.storeNewTempToken()).thenReturn("dummyToken"); AuthResource resource = new AuthResource(mockManager, null, "localhost"); TempTokenResponse response = resource.temporaryAuthToken("doc"); assertNotNull(response.token); assertEquals("xanauth: } |
### Question:
RopeUtils { public static <T extends StreamElement> long addWeightsOfRightLeaningChildNodes(Node<T> x) { if (x == null || x.right == null) { return 0; } return x.right.weight + addWeightsOfRightLeaningChildNodes(x.right); } static long addWeightsOfRightLeaningChildNodes(Node<T> x); static long addWeightsOfRightLeaningParentNodes(Node<T> child); static void adjustWeightOfLeftLeaningParents(Node<T> startNode, long weight); static long characterCount(Node<T> x); static void collectLeafNodes(Node<T> x, Queue<Node<T>> queue); static Node<T> concat(List<Node<T>> orphans); static Node<T> concat(Node<T> left, Node<T> right); static void cutLeftNode(Node<T> x, List<Node<T>> orphans); static void cutRightNode(Node<T> x, List<Node<T>> orphans); static Node<T> findRoot(Node<T> child); static Node<T> findSearchNode(Node<T> x, long weight, Node<T> root); static NodeIndex<T> index(long characterPosition, Node<T> x, long disp); static boolean intersects(long start, long end, long start2, long end2); static Node<T> rebalance(Node<T> x); }### Answer:
@Test public void addWeightsOfRightLeaningChildNodesNoChildren() throws Exception { Node<InvariantSpan> x = new Node<>(new InvariantSpan(1, 1, documentHash)); assertEquals(0, RopeUtils.addWeightsOfRightLeaningChildNodes(x)); }
@Test public void addWeightsOfRightLeaningChildNodesNullNode() throws Exception { assertEquals(0, RopeUtils.addWeightsOfRightLeaningChildNodes(null)); }
@Test public void addWeightsOfRightLeaningChildNodesSimple() throws Exception { Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash)); Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(0).right(right).build(); assertEquals(10, RopeUtils.addWeightsOfRightLeaningChildNodes(x)); }
@Test public void addWeightsOfRightLeaningChildNodesChained() throws Exception { Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash)); Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(1, 20, documentHash)); right.right = right2; Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(0).right(right).build(); assertEquals(30, RopeUtils.addWeightsOfRightLeaningChildNodes(x)); }
@Test public void addWeightsOfRightLeaningChildNodesLeftOnly() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash)); Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(1).left(left).build(); assertEquals(0, RopeUtils.addWeightsOfRightLeaningChildNodes(x)); } |
Subsets and Splits