idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
28,700 | public ByteBuffer sliceAsByteBuffer ( int index , int length ) { if ( hasArray ( ) ) { return ByteBuffer . wrap ( ( byte [ ] ) base , ( int ) ( ( address - ARRAY_BYTE_BASE_OFFSET ) + index ) , length ) ; } else { assert ( ! isUniversalBuffer ) ; return DirectBufferAccess . newByteBuffer ( address , index , length , reference ) ; } } | Create a ByteBuffer view of the range [ index index + length ) of this memory |
28,701 | public byte [ ] toByteArray ( ) { byte [ ] b = new byte [ size ( ) ] ; unsafe . copyMemory ( base , address , b , ARRAY_BYTE_BASE_OFFSET , size ( ) ) ; return b ; } | Get a copy of this buffer |
28,702 | public void copyTo ( int index , MessageBuffer dst , int offset , int length ) { unsafe . copyMemory ( base , address + index , dst . base , dst . address + offset , length ) ; } | Copy this buffer contents to another MessageBuffer |
28,703 | public JsonFormat . Value findFormat ( Annotated ann ) { JsonFormat . Value precedenceFormat = super . findFormat ( ann ) ; if ( precedenceFormat != null ) { return precedenceFormat ; } return ARRAY_FORMAT ; } | Defines array format for serialized entities with ObjectMapper without actually including the schema |
28,704 | public Boolean findIgnoreUnknownProperties ( AnnotatedClass ac ) { final Boolean precedenceIgnoreUnknownProperties = super . findIgnoreUnknownProperties ( ac ) ; if ( precedenceIgnoreUnknownProperties != null ) { return precedenceIgnoreUnknownProperties ; } return true ; } | Defines that unknown properties will be ignored and won t fail the un - marshalling process . Happens in case of de - serialization of a payload that contains more properties than the actual value type |
28,705 | public OutputStream reset ( OutputStream out ) throws IOException { OutputStream old = this . out ; this . out = out ; return old ; } | Reset Stream . This method doesn t close the old stream . |
28,706 | public InputStream reset ( InputStream in ) throws IOException { InputStream old = this . in ; this . in = in ; return old ; } | Reset Stream . This method doesn t close the old resource . |
28,707 | public WritableByteChannel reset ( WritableByteChannel channel ) throws IOException { WritableByteChannel old = this . channel ; this . channel = channel ; return old ; } | Reset channel . This method doesn t close the old channel . |
28,708 | public ReadableByteChannel reset ( ReadableByteChannel channel ) throws IOException { ReadableByteChannel old = this . channel ; this . channel = channel ; return old ; } | Reset channel . This method doesn t close the old resource . |
28,709 | private MessageBuffer getNextBuffer ( ) throws IOException { MessageBuffer next = in . next ( ) ; if ( next == null ) { throw new MessageInsufficientBufferException ( ) ; } assert ( buffer != null ) ; totalReadBytes += buffer . size ( ) ; return next ; } | Get the next buffer without changing the position |
28,710 | public MessageFormat getNextFormat ( ) throws IOException { if ( ! ensureBuffer ( ) ) { throw new MessageInsufficientBufferException ( ) ; } byte b = buffer . getByte ( position ) ; return MessageFormat . valueOf ( b ) ; } | Returns format of the next value . |
28,711 | private byte readByte ( ) throws IOException { if ( buffer . size ( ) > position ) { byte b = buffer . getByte ( position ) ; position ++ ; return b ; } else { nextBuffer ( ) ; if ( buffer . size ( ) > 0 ) { byte b = buffer . getByte ( 0 ) ; position = 1 ; return b ; } return readByte ( ) ; } } | Read a byte value at the cursor and proceed the cursor . |
28,712 | public void skipValue ( int count ) throws IOException { while ( count > 0 ) { byte b = readByte ( ) ; MessageFormat f = MessageFormat . valueOf ( b ) ; switch ( f ) { case POSFIXINT : case NEGFIXINT : case BOOLEAN : case NIL : break ; case FIXMAP : { int mapLen = b & 0x0f ; count += mapLen * 2 ; break ; } case FIXARRAY : { int arrayLen = b & 0x0f ; count += arrayLen ; break ; } case FIXSTR : { int strLen = b & 0x1f ; skipPayload ( strLen ) ; break ; } case INT8 : case UINT8 : skipPayload ( 1 ) ; break ; case INT16 : case UINT16 : skipPayload ( 2 ) ; break ; case INT32 : case UINT32 : case FLOAT32 : skipPayload ( 4 ) ; break ; case INT64 : case UINT64 : case FLOAT64 : skipPayload ( 8 ) ; break ; case BIN8 : case STR8 : skipPayload ( readNextLength8 ( ) ) ; break ; case BIN16 : case STR16 : skipPayload ( readNextLength16 ( ) ) ; break ; case BIN32 : case STR32 : skipPayload ( readNextLength32 ( ) ) ; break ; case FIXEXT1 : skipPayload ( 2 ) ; break ; case FIXEXT2 : skipPayload ( 3 ) ; break ; case FIXEXT4 : skipPayload ( 5 ) ; break ; case FIXEXT8 : skipPayload ( 9 ) ; break ; case FIXEXT16 : skipPayload ( 17 ) ; break ; case EXT8 : skipPayload ( readNextLength8 ( ) + 1 ) ; break ; case EXT16 : skipPayload ( readNextLength16 ( ) + 1 ) ; break ; case EXT32 : skipPayload ( readNextLength32 ( ) + 1 ) ; break ; case ARRAY16 : count += readNextLength16 ( ) ; break ; case ARRAY32 : count += readNextLength32 ( ) ; break ; case MAP16 : count += readNextLength16 ( ) * 2 ; break ; case MAP32 : count += readNextLength32 ( ) * 2 ; break ; case NEVER_USED : throw new MessageNeverUsedFormatException ( "Encountered 0xC1 \"NEVER_USED\" byte" ) ; } count -- ; } } | Skip next values then move the cursor at the end of the value |
28,713 | private static MessagePackException unexpected ( String expected , byte b ) { MessageFormat format = MessageFormat . valueOf ( b ) ; if ( format == MessageFormat . NEVER_USED ) { return new MessageNeverUsedFormatException ( String . format ( "Expected %s, but encountered 0xC1 \"NEVER_USED\" byte" , expected ) ) ; } else { String name = format . getValueType ( ) . name ( ) ; String typeName = name . substring ( 0 , 1 ) + name . substring ( 1 ) . toLowerCase ( ) ; return new MessageTypeException ( String . format ( "Expected %s, but got %s (%02x)" , expected , typeName , b ) ) ; } } | Create an exception for the case when an unexpected byte value is read |
28,714 | public boolean tryUnpackNil ( ) throws IOException { if ( ! ensureBuffer ( ) ) { throw new MessageInsufficientBufferException ( ) ; } byte b = buffer . getByte ( position ) ; if ( b == Code . NIL ) { readByte ( ) ; return true ; } return false ; } | Peeks a Nil byte and reads it if next byte is a nil value . |
28,715 | public boolean unpackBoolean ( ) throws IOException { byte b = readByte ( ) ; if ( b == Code . FALSE ) { return false ; } else if ( b == Code . TRUE ) { return true ; } throw unexpected ( "boolean" , b ) ; } | Reads true or false . |
28,716 | public short unpackShort ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixInt ( b ) ) { return ( short ) b ; } switch ( b ) { case Code . UINT8 : byte u8 = readByte ( ) ; return ( short ) ( u8 & 0xff ) ; case Code . UINT16 : short u16 = readShort ( ) ; if ( u16 < ( short ) 0 ) { throw overflowU16 ( u16 ) ; } return u16 ; case Code . UINT32 : int u32 = readInt ( ) ; if ( u32 < 0 || u32 > Short . MAX_VALUE ) { throw overflowU32 ( u32 ) ; } return ( short ) u32 ; case Code . UINT64 : long u64 = readLong ( ) ; if ( u64 < 0L || u64 > Short . MAX_VALUE ) { throw overflowU64 ( u64 ) ; } return ( short ) u64 ; case Code . INT8 : byte i8 = readByte ( ) ; return ( short ) i8 ; case Code . INT16 : short i16 = readShort ( ) ; return i16 ; case Code . INT32 : int i32 = readInt ( ) ; if ( i32 < Short . MIN_VALUE || i32 > Short . MAX_VALUE ) { throw overflowI32 ( i32 ) ; } return ( short ) i32 ; case Code . INT64 : long i64 = readLong ( ) ; if ( i64 < Short . MIN_VALUE || i64 > Short . MAX_VALUE ) { throw overflowI64 ( i64 ) ; } return ( short ) i64 ; } throw unexpected ( "Integer" , b ) ; } | Reads a short . |
28,717 | public long unpackLong ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixInt ( b ) ) { return ( long ) b ; } switch ( b ) { case Code . UINT8 : byte u8 = readByte ( ) ; return ( long ) ( u8 & 0xff ) ; case Code . UINT16 : short u16 = readShort ( ) ; return ( long ) ( u16 & 0xffff ) ; case Code . UINT32 : int u32 = readInt ( ) ; if ( u32 < 0 ) { return ( long ) ( u32 & 0x7fffffff ) + 0x80000000L ; } else { return ( long ) u32 ; } case Code . UINT64 : long u64 = readLong ( ) ; if ( u64 < 0L ) { throw overflowU64 ( u64 ) ; } return u64 ; case Code . INT8 : byte i8 = readByte ( ) ; return ( long ) i8 ; case Code . INT16 : short i16 = readShort ( ) ; return ( long ) i16 ; case Code . INT32 : int i32 = readInt ( ) ; return ( long ) i32 ; case Code . INT64 : long i64 = readLong ( ) ; return i64 ; } throw unexpected ( "Integer" , b ) ; } | Reads a long . |
28,718 | public BigInteger unpackBigInteger ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixInt ( b ) ) { return BigInteger . valueOf ( ( long ) b ) ; } switch ( b ) { case Code . UINT8 : byte u8 = readByte ( ) ; return BigInteger . valueOf ( ( long ) ( u8 & 0xff ) ) ; case Code . UINT16 : short u16 = readShort ( ) ; return BigInteger . valueOf ( ( long ) ( u16 & 0xffff ) ) ; case Code . UINT32 : int u32 = readInt ( ) ; if ( u32 < 0 ) { return BigInteger . valueOf ( ( long ) ( u32 & 0x7fffffff ) + 0x80000000L ) ; } else { return BigInteger . valueOf ( ( long ) u32 ) ; } case Code . UINT64 : long u64 = readLong ( ) ; if ( u64 < 0L ) { BigInteger bi = BigInteger . valueOf ( u64 + Long . MAX_VALUE + 1L ) . setBit ( 63 ) ; return bi ; } else { return BigInteger . valueOf ( u64 ) ; } case Code . INT8 : byte i8 = readByte ( ) ; return BigInteger . valueOf ( ( long ) i8 ) ; case Code . INT16 : short i16 = readShort ( ) ; return BigInteger . valueOf ( ( long ) i16 ) ; case Code . INT32 : int i32 = readInt ( ) ; return BigInteger . valueOf ( ( long ) i32 ) ; case Code . INT64 : long i64 = readLong ( ) ; return BigInteger . valueOf ( i64 ) ; } throw unexpected ( "Integer" , b ) ; } | Reads a BigInteger . |
28,719 | public float unpackFloat ( ) throws IOException { byte b = readByte ( ) ; switch ( b ) { case Code . FLOAT32 : float fv = readFloat ( ) ; return fv ; case Code . FLOAT64 : double dv = readDouble ( ) ; return ( float ) dv ; } throw unexpected ( "Float" , b ) ; } | Reads a float . |
28,720 | public int unpackArrayHeader ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixedArray ( b ) ) { return b & 0x0f ; } switch ( b ) { case Code . ARRAY16 : { int len = readNextLength16 ( ) ; return len ; } case Code . ARRAY32 : { int len = readNextLength32 ( ) ; return len ; } } throw unexpected ( "Array" , b ) ; } | Reads header of an array . |
28,721 | public int unpackMapHeader ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixedMap ( b ) ) { return b & 0x0f ; } switch ( b ) { case Code . MAP16 : { int len = readNextLength16 ( ) ; return len ; } case Code . MAP32 : { int len = readNextLength32 ( ) ; return len ; } } throw unexpected ( "Map" , b ) ; } | Reads header of a map . |
28,722 | public int unpackBinaryHeader ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixedRaw ( b ) ) { return b & 0x1f ; } int len = tryReadBinaryHeader ( b ) ; if ( len >= 0 ) { return len ; } if ( allowReadingStringAsBinary ) { len = tryReadStringHeader ( b ) ; if ( len >= 0 ) { return len ; } } throw unexpected ( "Binary" , b ) ; } | Reads header of a binary . |
28,723 | public MessageBuffer readPayloadAsReference ( int length ) throws IOException { int bufferRemaining = buffer . size ( ) - position ; if ( bufferRemaining >= length ) { MessageBuffer slice = buffer . slice ( position , length ) ; position += length ; return slice ; } MessageBuffer dst = MessageBuffer . allocate ( length ) ; readPayload ( dst , 0 , length ) ; return dst ; } | Reads payload bytes of binary extension or raw string types as a reference to internal buffer . |
28,724 | public MessageBuffer reset ( MessageBuffer buf ) { MessageBuffer old = this . buffer ; this . buffer = buf ; if ( buf == null ) { isEmpty = true ; } else { isEmpty = false ; } return old ; } | Reset buffer . This method returns the old buffer . |
28,725 | public ModbusRequest buildDiagnostics ( DiagnosticsSubFunctionCode subFunctionCode , int serverAddress , int data ) throws ModbusNumberException { DiagnosticsRequest request = new DiagnosticsRequest ( ) ; request . setServerAddress ( serverAddress ) ; request . setSubFunctionCode ( subFunctionCode ) ; request . setSubFunctionData ( data ) ; return request ; } | The function uses a sub - function code field in the query to define the type of test to be performed . The server echoes both the function code and sub - function code in a normal response . Some of the diagnostics cause data to be returned from the remote device in the data field of a normal response . |
28,726 | synchronized public ModbusResponse processRequest ( ModbusRequest request ) throws ModbusProtocolException , ModbusIOException { try { sendRequest ( request ) ; if ( request . getServerAddress ( ) != Modbus . BROADCAST_ID ) { do { try { ModbusResponse msg = ( ModbusResponse ) readResponse ( request ) ; request . validateResponse ( msg ) ; if ( msg . getModbusExceptionCode ( ) != ModbusExceptionCode . ACKNOWLEDGE ) { if ( msg . isException ( ) ) throw new ModbusProtocolException ( msg . getModbusExceptionCode ( ) ) ; return msg ; } } catch ( ModbusNumberException mne ) { Modbus . log ( ) . warning ( mne . getLocalizedMessage ( ) ) ; } } while ( System . currentTimeMillis ( ) - requestTime < getConnection ( ) . getReadTimeout ( ) ) ; throw new ModbusIOException ( "Response timeout." ) ; } else { broadcastResponse . setFunction ( request . getFunction ( ) ) ; return broadcastResponse ; } } catch ( ModbusIOException mioe ) { disconnect ( ) ; throw mioe ; } } | this function allows you to process your own ModbusRequest . Each request class has a compliant response class for instance ReadHoldingRegistersRequest and ReadHoldingRegistersResponse . If you process an instance of ReadHoldingRegistersRequest this function exactly either returns a ReadHoldingRegistersResponse instance or throws an exception . |
28,727 | public void setResponseTimeout ( int timeout ) { try { getConnection ( ) . setReadTimeout ( timeout ) ; } catch ( Exception e ) { Modbus . log ( ) . warning ( e . getLocalizedMessage ( ) ) ; } } | ModbusMaster will block for only this amount of time . If the timeout expires a ModbusTransportException is raised though the ModbusMaster is still valid . |
28,728 | final public int [ ] readHoldingRegisters ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadHoldingRegisters ( serverAddress , startAddress , quantity ) ; ReadHoldingRegistersResponse response = ( ReadHoldingRegistersResponse ) processRequest ( request ) ; return response . getRegisters ( ) ; } | This function code is used to read the contents of a contiguous block of holding registers in a remote device . The Request PDU specifies the starting register address and the number of registers . In the PDU Registers are addressed starting at zero . Therefore registers numbered 1 - 16 are addressed as 0 - 15 . |
28,729 | final public int [ ] readInputRegisters ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadInputRegisters ( serverAddress , startAddress , quantity ) ; ReadHoldingRegistersResponse response = ( ReadInputRegistersResponse ) processRequest ( request ) ; return response . getRegisters ( ) ; } | This function code is used to read from 1 to 125 contiguous input registers in a remote device . The Request PDU specifies the starting register address and the number of registers . In the PDU Registers are addressed starting at zero . Therefore input registers numbered 1 - 16 are addressed as 0 - 15 . |
28,730 | final synchronized public boolean [ ] readCoils ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadCoils ( serverAddress , startAddress , quantity ) ; ReadCoilsResponse response = ( ReadCoilsResponse ) processRequest ( request ) ; return response . getCoils ( ) ; } | This function code is used to read from 1 to 2000 contiguous status of coils in a remote device . The Request PDU specifies the starting address i . e . the address of the first coil specified and the number of coils . In the PDU Coils are addressed starting at zero . Therefore coils numbered 1 - 16 are addressed as 0 - 15 . If the returned output quantity is not a multiple of eight the remaining coils in the final boolean array will be padded with FALSE . |
28,731 | final public boolean [ ] readDiscreteInputs ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadDiscreteInputs ( serverAddress , startAddress , quantity ) ; ReadDiscreteInputsResponse response = ( ReadDiscreteInputsResponse ) processRequest ( request ) ; return response . getCoils ( ) ; } | This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device . The Request PDU specifies the starting address i . e . the address of the first input specified and the number of inputs . In the PDU Discrete Inputs are addressed starting at zero . Therefore Discrete inputs numbered 1 - 16 are addressed as 0 - 15 . If the returned input quantity is not a multiple of eight the remaining inputs in the final boolean array will be padded with FALSE . |
28,732 | final public void writeSingleRegister ( int serverAddress , int startAddress , int register ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { processRequest ( ModbusRequestBuilder . getInstance ( ) . buildWriteSingleRegister ( serverAddress , startAddress , register ) ) ; } | This function code is used to write a single holding register in a remote device . The Request PDU specifies the address of the register to be written . Registers are addressed starting at zero . Therefore register numbered 1 is addressed as 0 . |
28,733 | final public int [ ] readWriteMultipleRegisters ( int serverAddress , int readAddress , int readQuantity , int writeAddress , int [ ] registers ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadWriteMultipleRegisters ( serverAddress , readAddress , readQuantity , writeAddress , registers ) ; ReadWriteMultipleRegistersResponse response = ( ReadWriteMultipleRegistersResponse ) processRequest ( request ) ; return response . getRegisters ( ) ; } | This function code performs a combination of one read operation and one write operation in a single MODBUS transaction . The write operation is performed before the read . Holding registers are addressed starting at zero . Therefore holding registers 1 - 16 are addressed in the PDU as 0 - 15 . The request specifies the starting address and number of holding registers to be read as well as the starting address number of holding registers and the data to be written . |
28,734 | final public ModbusFileRecord [ ] readFileRecord ( int serverAddress , ModbusFileRecord [ ] records ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadFileRecord ( serverAddress , records ) ; ReadFileRecordResponse response = ( ReadFileRecordResponse ) processRequest ( request ) ; return response . getFileRecords ( ) ; } | This function code is used to perform a file record read . A file is an organization of records . Each file contains 10000 records addressed 0000 to 9999 decimal or 0X0000 to 0X270F . For example record 12 is addressed as 12 . The function can read multiple groups of references . |
28,735 | final public void writeFileRecord ( int serverAddress , ModbusFileRecord record ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { processRequest ( ModbusRequestBuilder . getInstance ( ) . buildWriteFileRecord ( serverAddress , record ) ) ; } | This function code is used to perform a file record write . All Request Data Lengths are provided in terms of number of bytes and all Record Lengths are provided in terms of the number of 16 - bit words . A file is an organization of records . Each file contains 10000 records addressed 0000 to 9999 decimal or 0X0000 to 0X270F . For example record 12 is addressed as 12 . The function can write multiple groups of references . |
28,736 | static public void setLogLevel ( LogLevel level ) { logLevel = level ; log . setLevel ( level . value ( ) ) ; for ( Handler handler : log . getHandlers ( ) ) { handler . setLevel ( level . value ( ) ) ; } } | changes the log level for all loggers used |
28,737 | static public boolean checkServerAddress ( int serverAddress ) { switch ( serverAddress ) { case 0x00 : return true ; case 0xFF : return true ; default : return ! ( serverAddress < Modbus . MIN_SERVER_ADDRESS || serverAddress > Modbus . MAX_SERVER_ADDRESS ) ; } } | validates address of server |
28,738 | public int readShortBE ( ) throws IOException { int h = read ( ) ; int l = read ( ) ; if ( - 1 == h || - 1 == l ) return - 1 ; return DataUtils . toShort ( h , l ) ; } | read two bytes in Big Endian Byte Order |
28,739 | public int readShortLE ( ) throws IOException { int l = read ( ) ; int h = read ( ) ; if ( - 1 == h || - 1 == l ) return - 1 ; return DataUtils . toShort ( h , l ) ; } | read two bytes in Little Endian Byte Order |
28,740 | public Future < AuthenticationResult > acquireToken ( final String resource , final UserAssertion userAssertion , final ClientCredential credential , final AuthenticationCallback callback ) { this . validateOnBehalfOfRequestInput ( resource , userAssertion , credential , true ) ; final ClientAuthentication clientAuth = new ClientSecretPost ( new ClientID ( credential . getClientId ( ) ) , new Secret ( credential . getClientSecret ( ) ) ) ; return acquireTokenOnBehalfOf ( resource , userAssertion , clientAuth , callback ) ; } | Acquires an access token from the authority on behalf of a user . It requires using a user token previously received . |
28,741 | public Future < AuthenticationResult > acquireToken ( final String resource , final UserAssertion userAssertion , final AsymmetricKeyCredential credential , final AuthenticationCallback callback ) { this . validateOnBehalfOfRequestInput ( resource , userAssertion , credential , true ) ; ClientAssertion clientAssertion = JwtHelper . buildJwt ( credential , this . authenticationAuthority . getSelfSignedJwtAudience ( ) ) ; final ClientAuthentication clientAuth = createClientAuthFromClientAssertion ( clientAssertion ) ; return acquireTokenOnBehalfOf ( resource , userAssertion , clientAuth , callback ) ; } | Acquires an access token from the authority on behalf of a user . It requires using a user token previously received . Uses certificate to authenticate client . |
28,742 | public Future < DeviceCode > acquireDeviceCode ( final String clientId , final String resource , final AuthenticationCallback < DeviceCode > callback ) { validateDeviceCodeRequestInput ( clientId , resource ) ; return service . submit ( new AcquireDeviceCodeCallable ( this , clientId , resource , callback ) ) ; } | Acquires a device code from the authority |
28,743 | public Future < AuthenticationResult > acquireTokenByDeviceCode ( final DeviceCode deviceCode , final AuthenticationCallback callback ) throws AuthenticationException { final ClientAuthentication clientAuth = new ClientAuthenticationPost ( ClientAuthenticationMethod . NONE , new ClientID ( deviceCode . getClientId ( ) ) ) ; this . validateDeviceCodeRequestInput ( deviceCode , clientAuth , deviceCode . getResource ( ) ) ; final AdalDeviceCodeAuthorizationGrant deviceCodeGrant = new AdalDeviceCodeAuthorizationGrant ( deviceCode , deviceCode . getResource ( ) ) ; return this . acquireToken ( deviceCodeGrant , clientAuth , callback ) ; } | Acquires security token from the authority using an device code previously received . |
28,744 | public Future < AuthenticationResult > acquireTokenByRefreshToken ( final String refreshToken , final String clientId , final String resource , final AuthenticationCallback callback ) { final ClientAuthentication clientAuth = new ClientAuthenticationPost ( ClientAuthenticationMethod . NONE , new ClientID ( clientId ) ) ; final AdalOAuthAuthorizationGrant authGrant = new AdalOAuthAuthorizationGrant ( new RefreshTokenGrant ( new RefreshToken ( refreshToken ) ) , resource ) ; return this . acquireToken ( authGrant , clientAuth , callback ) ; } | Acquires a security token from the authority using a Refresh Token previously received . This method is suitable for the daemon OAuth2 flow when a client secret is not possible . |
28,745 | public Map < String , List < String > > toParameters ( ) { final Map < String , List < String > > outParams = new LinkedHashMap < > ( ) ; outParams . put ( "resource" , Collections . singletonList ( resource ) ) ; outParams . put ( "grant_type" , Collections . singletonList ( GRANT_TYPE ) ) ; outParams . put ( "code" , Collections . singletonList ( deviceCode . getDeviceCode ( ) ) ) ; return outParams ; } | Converts the device code grant to a map of HTTP paramters . |
28,746 | public static JSONObject processBadRespStr ( int responseCode , String responseMsg ) throws JSONException { JSONObject response = new JSONObject ( ) ; response . put ( "responseCode" , responseCode ) ; if ( responseMsg . equalsIgnoreCase ( "" ) ) { response . put ( "responseMsg" , "" ) ; } else { JSONObject errorObject = new JSONObject ( responseMsg ) . optJSONObject ( "odata.error" ) ; String errorCode = errorObject . optString ( "code" ) ; String errorMsg = errorObject . optJSONObject ( "message" ) . optString ( "value" ) ; response . put ( "responseCode" , responseCode ) ; response . put ( "errorCode" , errorCode ) ; response . put ( "errorMsg" , errorMsg ) ; } return response ; } | for good response |
28,747 | static ClientAssertion buildJwt ( final AsymmetricKeyCredential credential , final String jwtAudience ) throws AuthenticationException { if ( credential == null ) { throw new IllegalArgumentException ( "credential is null" ) ; } final long time = System . currentTimeMillis ( ) ; final JWTClaimsSet claimsSet = new JWTClaimsSet . Builder ( ) . audience ( Collections . singletonList ( jwtAudience ) ) . issuer ( credential . getClientId ( ) ) . jwtID ( UUID . randomUUID ( ) . toString ( ) ) . notBeforeTime ( new Date ( time ) ) . expirationTime ( new Date ( time + AuthenticationConstants . AAD_JWT_TOKEN_LIFETIME_SECONDS * 1000 ) ) . subject ( credential . getClientId ( ) ) . build ( ) ; SignedJWT jwt ; try { JWSHeader . Builder builder = new Builder ( JWSAlgorithm . RS256 ) ; List < Base64 > certs = new ArrayList < Base64 > ( ) ; certs . add ( new Base64 ( credential . getPublicCertificate ( ) ) ) ; builder . x509CertChain ( certs ) ; builder . x509CertThumbprint ( new Base64URL ( credential . getPublicCertificateHash ( ) ) ) ; jwt = new SignedJWT ( builder . build ( ) , claimsSet ) ; final RSASSASigner signer = new RSASSASigner ( credential . getKey ( ) ) ; jwt . sign ( signer ) ; } catch ( final Exception e ) { throw new AuthenticationException ( e ) ; } return new ClientAssertion ( jwt . serialize ( ) ) ; } | Builds JWT object . |
28,748 | public static JSONArray fetchDirectoryObjectJSONArray ( JSONObject jsonObject ) throws Exception { JSONArray jsonArray = new JSONArray ( ) ; jsonArray = jsonObject . optJSONObject ( "responseMsg" ) . optJSONArray ( "value" ) ; return jsonArray ; } | This method parses an JSON Array out of a collection of JSON Objects within a string . |
28,749 | public static JSONObject fetchDirectoryObjectJSONObject ( JSONObject jsonObject ) throws Exception { JSONObject jObj = new JSONObject ( ) ; jObj = jsonObject . optJSONObject ( "responseMsg" ) ; return jObj ; } | This method parses an JSON Object out of a collection of JSON Objects within a string |
28,750 | public static String fetchNextSkiptoken ( JSONObject jsonObject ) throws Exception { String skipToken = "" ; skipToken = jsonObject . optJSONObject ( "responseMsg" ) . optString ( "odata.nextLink" ) ; if ( ! skipToken . equalsIgnoreCase ( "" ) ) { int index = skipToken . indexOf ( "$skiptoken=" ) + ( new String ( "$skiptoken=" ) ) . length ( ) ; skipToken = skipToken . substring ( index ) ; } return skipToken ; } | This method parses the skip token from a json formatted string . |
28,751 | public static String createJSONString ( HttpServletRequest request , String controller ) throws Exception { JSONObject obj = new JSONObject ( ) ; try { Field [ ] allFields = Class . forName ( "com.microsoft.windowsazure.activedirectory.sdk.graph.models." + controller ) . getDeclaredFields ( ) ; String [ ] allFieldStr = new String [ allFields . length ] ; for ( int i = 0 ; i < allFields . length ; i ++ ) { allFieldStr [ i ] = allFields [ i ] . getName ( ) ; } List < String > allFieldStringList = Arrays . asList ( allFieldStr ) ; Enumeration < String > fields = request . getParameterNames ( ) ; while ( fields . hasMoreElements ( ) ) { String fieldName = fields . nextElement ( ) ; String param = request . getParameter ( fieldName ) ; if ( allFieldStringList . contains ( fieldName ) ) { if ( param == null || param . length ( ) == 0 ) { if ( ! fieldName . equalsIgnoreCase ( "password" ) ) { obj . put ( fieldName , JSONObject . NULL ) ; } } else { if ( fieldName . equalsIgnoreCase ( "password" ) ) { obj . put ( "passwordProfile" , new JSONObject ( "{\"password\": \"" + param + "\"}" ) ) ; } else { obj . put ( fieldName , param ) ; } } } } } catch ( JSONException e ) { e . printStackTrace ( ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; } return obj . toString ( ) ; } | This method would create a string consisting of a JSON document with all the necessary elements set from the HttpServletRequest request . |
28,752 | public static < T > void convertJSONObjectToDirectoryObject ( JSONObject jsonObject , T destObject ) throws Exception { Field [ ] fieldList = destObject . getClass ( ) . getDeclaredFields ( ) ; for ( int i = 0 ; i < fieldList . length ; i ++ ) { if ( fieldList [ i ] . getType ( ) . equals ( String . class ) ) { destObject . getClass ( ) . getMethod ( String . format ( "set%s" , WordUtils . capitalize ( fieldList [ i ] . getName ( ) ) ) , new Class [ ] { String . class } ) . invoke ( destObject , new Object [ ] { jsonObject . optString ( fieldList [ i ] . getName ( ) ) } ) ; } } } | This is a generic method that copies the simple attribute values from an argument jsonObject to an argument generic object . |
28,753 | public String getPublicCertificateHash ( ) throws CertificateEncodingException , NoSuchAlgorithmException { return Base64 . encodeBase64String ( AsymmetricKeyCredential . getHash ( this . publicCertificate . getEncoded ( ) ) ) ; } | Base64 encoded hash of the the public certificate . |
28,754 | public boolean isDeviceCodeError ( ) { ErrorObject errorObject = getErrorObject ( ) ; if ( errorObject == null ) { return false ; } String code = errorObject . getCode ( ) ; if ( code == null ) { return false ; } switch ( code ) { case "authorization_pending" : case "slow_down" : case "access_denied" : case "code_expired" : return true ; default : return false ; } } | Checks if is a device code error . |
28,755 | private StateData validateState ( HttpSession session , String state ) throws Exception { if ( StringUtils . isNotEmpty ( state ) ) { StateData stateDataInSession = removeStateFromSession ( session , state ) ; if ( stateDataInSession != null ) { return stateDataInSession ; } } throw new Exception ( FAILED_TO_VALIDATE_MESSAGE + "could not validate state" ) ; } | make sure that state is stored in the session delete it from session - should be used only once |
28,756 | public String getLdapEncoded ( ) { if ( components . size ( ) == 0 ) { throw new IndexOutOfBoundsException ( "No components in Rdn." ) ; } StringBuffer sb = new StringBuffer ( DEFAULT_BUFFER_SIZE ) ; for ( Iterator iter = components . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { LdapRdnComponent component = ( LdapRdnComponent ) iter . next ( ) ; sb . append ( component . encodeLdap ( ) ) ; if ( iter . hasNext ( ) ) { sb . append ( "+" ) ; } } return sb . toString ( ) ; } | Get a properly rfc2253 - encoded String representation of this LdapRdn . |
28,757 | public String encodeUrl ( ) { StringBuffer sb = new StringBuffer ( DEFAULT_BUFFER_SIZE ) ; for ( Iterator iter = components . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { LdapRdnComponent component = ( LdapRdnComponent ) iter . next ( ) ; sb . append ( component . encodeUrl ( ) ) ; if ( iter . hasNext ( ) ) { sb . append ( "+" ) ; } } return sb . toString ( ) ; } | Get a String representation of this LdapRdn for use in urls . |
28,758 | public int compareTo ( Object obj ) { LdapRdn that = ( LdapRdn ) obj ; if ( this . components . size ( ) != that . components . size ( ) ) { return this . components . size ( ) - that . components . size ( ) ; } Set < Map . Entry < String , LdapRdnComponent > > theseEntries = this . components . entrySet ( ) ; for ( Map . Entry < String , LdapRdnComponent > oneEntry : theseEntries ) { LdapRdnComponent thatEntry = that . components . get ( oneEntry . getKey ( ) ) ; if ( thatEntry == null ) { return - 1 ; } int compared = oneEntry . getValue ( ) . compareTo ( thatEntry ) ; if ( compared != 0 ) { return compared ; } } return 0 ; } | Compare this LdapRdn to another object . |
28,759 | public LdapRdn immutableLdapRdn ( ) { Map < String , LdapRdnComponent > mapWithImmutableRdns = new LinkedHashMap < String , LdapRdnComponent > ( components . size ( ) ) ; for ( Iterator iterator = components . values ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { LdapRdnComponent rdnComponent = ( LdapRdnComponent ) iterator . next ( ) ; mapWithImmutableRdns . put ( rdnComponent . getKey ( ) , rdnComponent . immutableLdapRdnComponent ( ) ) ; } Map < String , LdapRdnComponent > unmodifiableMapOfImmutableRdns = Collections . unmodifiableMap ( mapWithImmutableRdns ) ; LdapRdn immutableRdn = new LdapRdn ( ) ; immutableRdn . components = unmodifiableMapOfImmutableRdns ; return immutableRdn ; } | Create an immutable copy of this instance . It will not be possible to add or remove components or modify the keys and values of these components . |
28,760 | void doCloseConnection ( DirContext context , ContextSource contextSource ) throws javax . naming . NamingException { DirContextHolder transactionContextHolder = ( DirContextHolder ) TransactionSynchronizationManager . getResource ( contextSource ) ; if ( transactionContextHolder == null || transactionContextHolder . getCtx ( ) != context ) { log . debug ( "Closing context" ) ; context . close ( ) ; } else { log . debug ( "Leaving transactional context open" ) ; } } | Close the supplied context but only if it is not associated with the current transaction . |
28,761 | protected String encodeLdap ( ) { StringBuffer buff = new StringBuffer ( key . length ( ) + value . length ( ) * 2 ) ; buff . append ( key ) ; buff . append ( '=' ) ; buff . append ( LdapEncoder . nameEncode ( value ) ) ; return buff . toString ( ) ; } | Encode key and value to ldap . |
28,762 | public String encodeUrl ( ) { try { URI valueUri = new URI ( null , null , value , null ) ; return key + "=" + valueUri . toString ( ) ; } catch ( URISyntaxException e ) { return key + "=" + "value" ; } } | Get a String representation of this instance for use in URLs . |
28,763 | public int compareTo ( Object obj ) { LdapRdnComponent that = ( LdapRdnComponent ) obj ; int keyCompare = this . key . toLowerCase ( ) . compareTo ( that . key . toLowerCase ( ) ) ; if ( keyCompare == 0 ) { return this . value . toLowerCase ( ) . compareTo ( that . value . toLowerCase ( ) ) ; } else { return keyCompare ; } } | Compare this instance to the supplied object . |
28,764 | public static void collectAttributeValues ( Attributes attributes , String name , Collection < Object > collection ) { collectAttributeValues ( attributes , name , collection , Object . class ) ; } | Collect all the values of a the specified attribute from the supplied Attributes . |
28,765 | public static < T > void collectAttributeValues ( Attributes attributes , String name , Collection < T > collection , Class < T > clazz ) { Assert . notNull ( attributes , "Attributes must not be null" ) ; Assert . hasText ( name , "Name must not be empty" ) ; Assert . notNull ( collection , "Collection must not be null" ) ; Attribute attribute = attributes . get ( name ) ; if ( attribute == null ) { throw new NoSuchAttributeException ( "No attribute with name '" + name + "'" ) ; } iterateAttributeValues ( attribute , new CollectingAttributeValueCallbackHandler < T > ( collection , clazz ) ) ; } | Collect all the values of a the specified attribute from the supplied Attributes as the specified class . |
28,766 | public static void iterateAttributeValues ( Attribute attribute , AttributeValueCallbackHandler callbackHandler ) { Assert . notNull ( attribute , "Attribute must not be null" ) ; Assert . notNull ( callbackHandler , "callbackHandler must not be null" ) ; if ( attribute instanceof Iterable ) { int i = 0 ; for ( Object obj : ( Iterable ) attribute ) { handleAttributeValue ( attribute . getID ( ) , obj , i , callbackHandler ) ; i ++ ; } } else { for ( int i = 0 ; i < attribute . size ( ) ; i ++ ) { try { handleAttributeValue ( attribute . getID ( ) , attribute . get ( i ) , i , callbackHandler ) ; } catch ( javax . naming . NamingException e ) { throw convertLdapException ( e ) ; } } } } | Iterate through all the values of the specified Attribute calling back to the specified callbackHandler . |
28,767 | public static LdapName newLdapName ( String distinguishedName ) { Assert . notNull ( distinguishedName , "distinguishedName must not be null" ) ; try { return new LdapName ( distinguishedName ) ; } catch ( InvalidNameException e ) { throw convertLdapException ( e ) ; } } | Construct a new LdapName instance from the supplied distinguished name string . |
28,768 | public static Rdn getRdn ( Name name , String key ) { Assert . notNull ( name , "name must not be null" ) ; Assert . hasText ( key , "key must not be blank" ) ; LdapName ldapName = returnOrConstructLdapNameFromName ( name ) ; List < Rdn > rdns = ldapName . getRdns ( ) ; for ( Rdn rdn : rdns ) { NamingEnumeration < String > ids = rdn . toAttributes ( ) . getIDs ( ) ; while ( ids . hasMoreElements ( ) ) { String id = ids . nextElement ( ) ; if ( key . equalsIgnoreCase ( id ) ) { return rdn ; } } } throw new NoSuchElementException ( "No Rdn with the requested key: '" + key + "'" ) ; } | Find the Rdn with the requested key in the supplied Name . |
28,769 | public static Object getValue ( Name name , String key ) { NamingEnumeration < ? extends Attribute > allAttributes = getRdn ( name , key ) . toAttributes ( ) . getAll ( ) ; while ( allAttributes . hasMoreElements ( ) ) { Attribute oneAttribute = allAttributes . nextElement ( ) ; if ( key . equalsIgnoreCase ( oneAttribute . getID ( ) ) ) { try { return oneAttribute . get ( ) ; } catch ( javax . naming . NamingException e ) { throw convertLdapException ( e ) ; } } } throw new NoSuchElementException ( "No Rdn with the requested key: '" + key + "'" ) ; } | Get the value of the Rdn with the requested key in the supplied Name . |
28,770 | public static Object getValue ( Name name , int index ) { Assert . notNull ( name , "name must not be null" ) ; LdapName ldapName = returnOrConstructLdapNameFromName ( name ) ; Rdn rdn = ldapName . getRdn ( index ) ; if ( rdn . size ( ) > 1 ) { LOGGER . warn ( "Rdn at position " + index + " of dn '" + name + "' is multi-value - returned value is not to be trusted. " + "Consider using name-based getValue method instead" ) ; } return rdn . getValue ( ) ; } | Get the value of the Rdn at the requested index in the supplied Name . |
28,771 | public static String getStringValue ( Name name , String key ) { return ( String ) getValue ( name , key ) ; } | Get the value of the Rdn with the requested key in the supplied Name as a String . |
28,772 | static byte [ ] numberToBytes ( String number , int length , boolean bigEndian ) { BigInteger bi = new BigInteger ( number ) ; byte [ ] bytes = bi . toByteArray ( ) ; int remaining = length - bytes . length ; if ( remaining < 0 ) { bytes = Arrays . copyOfRange ( bytes , - remaining , bytes . length ) ; } else { byte [ ] fill = new byte [ remaining ] ; bytes = addAll ( fill , bytes ) ; } if ( ! bigEndian ) { reverse ( bytes ) ; } return bytes ; } | Converts the given number to a binary representation of the specified length and endian - ness . |
28,773 | static String toHexString ( final byte b ) { String hexString = Integer . toHexString ( b & 0xFF ) ; if ( hexString . length ( ) % 2 != 0 ) { hexString = "0" + hexString ; } return hexString ; } | Converts a byte into its hexadecimal representation padding with a leading zero to get an even number of characters . |
28,774 | static String toHexString ( final byte [ ] b ) { StringBuffer sb = new StringBuffer ( "{" ) ; for ( int i = 0 ; i < b . length ; i ++ ) { sb . append ( toHexString ( b [ i ] ) ) ; if ( i < b . length - 1 ) { sb . append ( "," ) ; } } sb . append ( "}" ) ; return sb . toString ( ) ; } | Converts a byte array into its hexadecimal representation padding each with a leading zero to get an even number of characters . |
28,775 | public Context getInnermostDelegateContext ( ) { final Context delegateContext = this . getDelegateContext ( ) ; if ( delegateContext instanceof DelegatingContext ) { return ( ( DelegatingContext ) delegateContext ) . getInnermostDelegateContext ( ) ; } return delegateContext ; } | Recursivley inspect delegates until a non - delegating context is found . |
28,776 | public boolean isSatisfiedBy ( LdapAttributes record ) throws NamingException { if ( record != null ) { LdapName dn = record . getName ( ) ; if ( dn != null ) { if ( record . get ( "objectClass" ) != null ) { Rdn rdn = dn . getRdn ( dn . size ( ) - 1 ) ; if ( record . get ( rdn . getType ( ) ) != null ) { Object object = record . get ( rdn . getType ( ) ) . get ( ) ; if ( object instanceof String ) { String value = ( String ) object ; if ( ( ( String ) rdn . getValue ( ) ) . equalsIgnoreCase ( value ) ) { return true ; } } else if ( object instanceof byte [ ] ) { String rdnValue = LdapEncoder . printBase64Binary ( ( ( String ) rdn . getValue ( ) ) . getBytes ( ) ) ; String attributeValue = LdapEncoder . printBase64Binary ( ( byte [ ] ) object ) ; if ( rdnValue . equals ( attributeValue ) ) return true ; } } } } } } | Determines if the policy is satisfied by the supplied LdapAttributes object . |
28,777 | public void destroy ( ) { try { ctx . close ( ) ; } catch ( javax . naming . NamingException e ) { LOG . warn ( "Error when closing" , e ) ; } } | Destroy method that allows the target DirContext to be cleaned up when the SingleContextSource is not going to be used any more . |
28,778 | protected final void parse ( String path ) { DnParser parser = DefaultDnParserFactory . createDnParser ( unmangleCompositeName ( path ) ) ; DistinguishedName dn ; try { dn = parser . dn ( ) ; } catch ( ParseException e ) { throw new BadLdapGrammarException ( "Failed to parse DN" , e ) ; } catch ( TokenMgrError e ) { throw new BadLdapGrammarException ( "Failed to parse DN" , e ) ; } this . names = dn . names ; } | Parse the supplied String and make this instance represent the corresponding distinguished name . |
28,779 | public String toUrl ( ) { StringBuffer buffer = new StringBuffer ( DEFAULT_BUFFER_SIZE ) ; for ( int i = names . size ( ) - 1 ; i >= 0 ; i -- ) { LdapRdn n = ( LdapRdn ) names . get ( i ) ; buffer . append ( n . encodeUrl ( ) ) ; if ( i > 0 ) { buffer . append ( "," ) ; } } return buffer . toString ( ) ; } | Builds a complete LDAP path ldap and url encoded . Separates only with . |
28,780 | public int compareTo ( Object obj ) { DistinguishedName that = ( DistinguishedName ) obj ; ListComparator comparator = new ListComparator ( ) ; return comparator . compare ( this . names , that . names ) ; } | Compare this instance to another object . Note that the comparison is done in order of significance so the most significant Rdn is compared first then the second and so on . |
28,781 | public DistinguishedName immutableDistinguishedName ( ) { List listWithImmutableRdns = new ArrayList ( names . size ( ) ) ; for ( Iterator iterator = names . iterator ( ) ; iterator . hasNext ( ) ; ) { LdapRdn rdn = ( LdapRdn ) iterator . next ( ) ; listWithImmutableRdns . add ( rdn . immutableLdapRdn ( ) ) ; } return new DistinguishedName ( Collections . unmodifiableList ( listWithImmutableRdns ) ) ; } | Return an immutable copy of this instance . It will not be possible to add or remove any Rdns to or from the returned instance and the respective Rdns will also be immutable in turn . |
28,782 | private boolean processAttributeAnnotation ( Field field ) { syntax = "" ; isBinary = false ; name = new CaseIgnoreString ( field . getName ( ) ) ; boolean foundAnnotation = false ; Attribute attribute = field . getAnnotation ( Attribute . class ) ; List < String > attrList = new ArrayList < String > ( ) ; if ( attribute != null ) { foundAnnotation = true ; String localAttributeName = attribute . name ( ) ; if ( localAttributeName != null && localAttributeName . length ( ) > 0 ) { name = new CaseIgnoreString ( localAttributeName ) ; attrList . add ( localAttributeName ) ; } syntax = attribute . syntax ( ) ; isBinary = attribute . type ( ) == Attribute . Type . BINARY ; isReadOnly = attribute . readonly ( ) ; } attributes = attrList . toArray ( new String [ attrList . size ( ) ] ) ; isObjectClass = name . equals ( OBJECT_CLASS_ATTRIBUTE_CI ) ; return foundAnnotation ; } | syntax isBinary isObjectClass and name . |
28,783 | private static Map < String , String > readSyntaxMap ( File syntaxMapFile ) throws IOException { Map < String , String > result = new HashMap < String , String > ( ) ; BufferedReader reader = null ; try { reader = new BufferedReader ( new FileReader ( syntaxMapFile ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { String trimmed = line . trim ( ) ; if ( trimmed . length ( ) > 0 ) { if ( trimmed . charAt ( 0 ) != '#' ) { String [ ] parts = trimmed . split ( "," ) ; if ( parts . length != 2 ) { throw new IOException ( String . format ( "Failed to parse line \"%1$s\"" , trimmed ) ) ; } String partOne = parts [ 0 ] . trim ( ) ; String partTwo = parts [ 1 ] . trim ( ) ; if ( partOne . length ( ) == 0 || partTwo . length ( ) == 0 ) { throw new IOException ( String . format ( "Failed to parse line \"%1$s\"" , trimmed ) ) ; } result . put ( partOne , partTwo ) ; } } } } finally { if ( reader != null ) { reader . close ( ) ; } } return result ; } | Read mappings of LDAP syntaxes to Java classes . |
28,784 | private static ObjectSchema readSchema ( String url , String user , String pass , SyntaxToJavaClass syntaxToJavaClass , Set < String > binarySet , Set < String > objectClasses ) throws NamingException , ClassNotFoundException { Hashtable < String , String > env = new Hashtable < String , String > ( ) ; env . put ( Context . PROVIDER_URL , url ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; if ( user != null ) { env . put ( Context . SECURITY_PRINCIPAL , user ) ; } if ( pass != null ) { env . put ( Context . SECURITY_CREDENTIALS , pass ) ; } DirContext context = new InitialDirContext ( env ) ; DirContext schemaContext = context . getSchema ( "" ) ; SchemaReader reader = new SchemaReader ( schemaContext , syntaxToJavaClass , binarySet ) ; ObjectSchema schema = reader . getObjectSchema ( objectClasses ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( String . format ( "Schema - %1$s" , schema . toString ( ) ) ) ; } return schema ; } | Bind to the directory read and process the schema |
28,785 | private static void createCode ( String packageName , String className , ObjectSchema schema , Set < SyntaxToJavaClass . ClassInfo > imports , File outputFile ) throws IOException , TemplateException { Configuration freeMarkerConfiguration = new Configuration ( ) ; freeMarkerConfiguration . setClassForTemplateLoading ( DEFAULT_LOADER_CLASS , "" ) ; freeMarkerConfiguration . setObjectWrapper ( new DefaultObjectWrapper ( ) ) ; Map < String , Object > model = new HashMap < String , Object > ( ) ; model . put ( "package" , packageName ) ; model . put ( "class" , className ) ; model . put ( "schema" , schema ) ; model . put ( "imports" , imports ) ; Template template = freeMarkerConfiguration . getTemplate ( TEMPLATE_FILE ) ; if ( LOG . isDebugEnabled ( ) ) { Writer out = new OutputStreamWriter ( System . out ) ; template . process ( model , out ) ; out . flush ( ) ; } LOG . debug ( String . format ( "Writing java to: %1$s" , outputFile . getAbsolutePath ( ) ) ) ; FileOutputStream outputStream = new FileOutputStream ( outputFile ) ; Writer out = new OutputStreamWriter ( outputStream ) ; template . process ( model , out ) ; out . flush ( ) ; out . close ( ) ; } | Create the Java |
28,786 | private static File makeOutputFile ( String outputDir , String packageName , String className ) throws IOException { Pattern pattern = Pattern . compile ( "\\." ) ; Matcher matcher = pattern . matcher ( packageName ) ; String sepToUse = File . separator ; if ( sepToUse . equals ( "\\" ) ) { sepToUse = "\\\\" ; } String directoryPath = outputDir + File . separator + matcher . replaceAll ( sepToUse ) ; File directory = new File ( directoryPath ) ; File outputFile = new File ( directory , className + ".java" ) ; LOG . debug ( String . format ( "Attempting to create output file at %1$s" , outputFile . getAbsolutePath ( ) ) ) ; try { directory . mkdirs ( ) ; outputFile . createNewFile ( ) ; } catch ( SecurityException se ) { throw new IOException ( String . format ( "Can't write to output file %1$s" , outputFile . getAbsoluteFile ( ) ) , se ) ; } catch ( IOException ioe ) { throw new IOException ( String . format ( "Can't write to output file %1$s" , outputFile . getAbsoluteFile ( ) ) , ioe ) ; } return outputFile ; } | Create the output file for the generated code along with all intervening directories |
28,787 | public ObjectSchema getObjectSchema ( Set < String > objectClasses ) throws NamingException , ClassNotFoundException { ObjectSchema result = new ObjectSchema ( ) ; createObjectClass ( objectClasses , schemaContext , result ) ; return result ; } | Get the object schema for the given object classes |
28,788 | private void createObjectClass ( Set < String > objectClasses , DirContext schemaContext , ObjectSchema schema ) throws NamingException , ClassNotFoundException { Set < String > supList = new HashSet < String > ( ) ; for ( String objectClass : objectClasses ) { schema . addObjectClass ( objectClass ) ; Attributes attributes = schemaContext . getAttributes ( "ClassDefinition/" + objectClass ) ; NamingEnumeration < ? extends Attribute > valuesEnumeration = attributes . getAll ( ) ; while ( valuesEnumeration . hasMoreElements ( ) ) { Attribute currentAttribute = valuesEnumeration . nextElement ( ) ; String currentId = currentAttribute . getID ( ) . toUpperCase ( ) ; SchemaAttributeType type = getSchemaAttributeType ( currentId ) ; NamingEnumeration < ? > currentValues = currentAttribute . getAll ( ) ; while ( currentValues . hasMoreElements ( ) ) { String currentValue = ( String ) currentValues . nextElement ( ) ; switch ( type ) { case SUP : String lowerCased = currentValue . toLowerCase ( ) ; if ( ! schema . getObjectClass ( ) . contains ( lowerCased ) ) { supList . add ( lowerCased ) ; } break ; case MUST : schema . addMust ( createAttributeSchema ( currentValue , schemaContext ) ) ; break ; case MAY : schema . addMay ( createAttributeSchema ( currentValue , schemaContext ) ) ; break ; default : } } } createObjectClass ( supList , schemaContext , schema ) ; } } | Recursively extract schema from the directory and process it |
28,789 | private void closeContext ( DirContext ctx ) { if ( ctx != null ) { try { ctx . close ( ) ; } catch ( Exception e ) { LOG . debug ( "Exception closing context" , e ) ; } } } | Close the context and swallow any exceptions . |
28,790 | protected DirContext createContext ( Hashtable < String , Object > environment ) { DirContext ctx = null ; try { ctx = getDirContextInstance ( environment ) ; if ( LOG . isInfoEnabled ( ) ) { Hashtable < ? , ? > ctxEnv = ctx . getEnvironment ( ) ; String ldapUrl = ( String ) ctxEnv . get ( Context . PROVIDER_URL ) ; LOG . debug ( "Got Ldap context on server '" + ldapUrl + "'" ) ; } return ctx ; } catch ( NamingException e ) { closeContext ( ctx ) ; throw LdapUtils . convertLdapException ( e ) ; } } | Create a DirContext using the supplied environment . |
28,791 | public void afterPropertiesSet ( ) { if ( ObjectUtils . isEmpty ( urls ) ) { throw new IllegalArgumentException ( "At least one server url must be set" ) ; } if ( authenticationSource == null ) { LOG . debug ( "AuthenticationSource not set - " + "using default implementation" ) ; if ( ! StringUtils . hasText ( userDn ) ) { LOG . info ( "Property 'userDn' not set - " + "anonymous context will be used for read-write operations" ) ; anonymousReadOnly = true ; } else if ( ! StringUtils . hasText ( password ) ) { LOG . info ( "Property 'password' not set - " + "blank password will be used" ) ; } authenticationSource = new SimpleAuthenticationSource ( ) ; } if ( cacheEnvironmentProperties ) { anonymousEnv = setupAnonymousEnv ( ) ; } } | Checks that all necessary data is set and that there is no compatibility issues after which the instance is initialized . Note that you need to call this method explicitly after setting all desired properties if using the class outside of a Spring Context . |
28,792 | public void setBaseEnvironmentProperties ( Map < String , Object > baseEnvironmentProperties ) { this . baseEnv = new Hashtable < String , Object > ( baseEnvironmentProperties ) ; } | If any custom environment properties are needed these can be set using this method . |
28,793 | public LdapNameBuilder add ( Name name ) { Assert . notNull ( name , "name must not be null" ) ; try { ldapName . addAll ( ldapName . size ( ) , name ) ; return this ; } catch ( InvalidNameException e ) { throw new org . springframework . ldap . InvalidNameException ( e ) ; } } | Append the specified name to the currently built LdapName . |
28,794 | public LdapNameBuilder add ( String name ) { Assert . notNull ( name , "name must not be null" ) ; return add ( LdapUtils . newLdapName ( name ) ) ; } | Append the LdapName represented by the specified string to the currently built LdapName . |
28,795 | protected void deleteRecursively ( DirContext ctx , Name name ) { NamingEnumeration enumeration = null ; try { enumeration = ctx . listBindings ( name ) ; while ( enumeration . hasMore ( ) ) { Binding binding = ( Binding ) enumeration . next ( ) ; LdapName childName = LdapUtils . newLdapName ( binding . getName ( ) ) ; childName . addAll ( 0 , name ) ; deleteRecursively ( ctx , childName ) ; } ctx . unbind ( name ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Entry " + name + " deleted" ) ; } } catch ( javax . naming . NamingException e ) { throw LdapUtils . convertLdapException ( e ) ; } finally { try { enumeration . close ( ) ; } catch ( Exception e ) { } } } | Delete all subcontexts including the current one recursively . |
28,796 | private void assureReturnObjFlagSet ( SearchControls controls ) { Assert . notNull ( controls , "controls must not be null" ) ; if ( ! controls . getReturningObjFlag ( ) ) { LOG . debug ( "The returnObjFlag of supplied SearchControls is not set" + " but a ContextMapper is used - setting flag to true" ) ; controls . setReturningObjFlag ( true ) ; } } | Make sure the returnObjFlag is set in the supplied SearchControls . Set it and log if it s not set . |
28,797 | public DirContext getInnermostDelegateDirContext ( ) { final DirContext delegateDirContext = this . getDelegateDirContext ( ) ; if ( delegateDirContext instanceof DelegatingDirContext ) { return ( ( DelegatingDirContext ) delegateDirContext ) . getInnermostDelegateDirContext ( ) ; } return delegateDirContext ; } | Recursivley inspect delegates until a non - delegating dir context is found . |
28,798 | public static Name getFirstArgumentAsName ( Object [ ] args ) { Assert . notEmpty ( args ) ; Object firstArg = args [ 0 ] ; return getArgumentAsName ( firstArg ) ; } | Get the first parameter in the argument list as a Name . |
28,799 | public static Name getArgumentAsName ( Object arg ) { if ( arg instanceof String ) { return LdapUtils . newLdapName ( ( String ) arg ) ; } else if ( arg instanceof Name ) { return ( Name ) arg ; } else { throw new IllegalArgumentException ( "First argument needs to be a Name or a String representation thereof" ) ; } } | Get the argument as a Name . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.