idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
2,400
|
public RuntimeManager build ( KnowledgeRuntimeManagerType type , String identifier ) { final RuntimeManager runtimeManager ; final RuntimeEnvironment runtimeEnvironment = _runtimeEnvironmentBuilder . build ( ) ; final RemoteManifest remoteManifest = RemoteManifest . removeFromEnvironment ( runtimeEnvironment . getEnvironment ( ) ) ; if ( remoteManifest != null ) { runtimeManager = new RemoteRuntimeManager ( remoteManifest . buildConfiguration ( ) , identifier ) ; } else { switch ( type ) { case SINGLETON : runtimeManager = _runtimeManagerFactory . newSingletonRuntimeManager ( runtimeEnvironment , identifier ) ; break ; case PER_REQUEST : runtimeManager = _runtimeManagerFactory . newPerRequestRuntimeManager ( runtimeEnvironment , identifier ) ; break ; case PER_PROCESS_INSTANCE : runtimeManager = _runtimeManagerFactory . newPerProcessInstanceRuntimeManager ( runtimeEnvironment , identifier ) ; break ; default : runtimeManager = null ; break ; } } return runtimeManager ; }
|
Builds a RuntimeManager .
|
2,401
|
protected ChannelsModel toChannelsModel ( Channel [ ] channelAnnotations , KnowledgeNamespace knowledgeNamespace , ComponentModel componentModel , SwitchYardNamespace switchyardNamespace ) { if ( channelAnnotations == null || channelAnnotations . length == 0 ) { return null ; } ChannelsModel channelsModel = new V1ChannelsModel ( knowledgeNamespace . uri ( ) ) ; for ( Channel channelAnnotation : channelAnnotations ) { ChannelModel channelModel = new V1ChannelModel ( knowledgeNamespace . uri ( ) ) ; Class < ? extends org . kie . api . runtime . Channel > clazz = channelAnnotation . value ( ) ; if ( Channel . UndefinedChannel . class . isAssignableFrom ( clazz ) ) { clazz = SwitchYardServiceChannel . class ; } channelModel . setClazz ( clazz ) ; String name = channelAnnotation . name ( ) ; if ( UNDEFINED . equals ( name ) ) { if ( SwitchYardServiceChannel . class . isAssignableFrom ( clazz ) ) { name = SwitchYardServiceChannel . SERVICE ; } } if ( UNDEFINED . equals ( name ) ) { name = clazz . getSimpleName ( ) ; } channelModel . setName ( name ) ; String operation = channelAnnotation . operation ( ) ; if ( ! UNDEFINED . equals ( operation ) ) { channelModel . setOperation ( operation ) ; } String reference = channelAnnotation . reference ( ) ; if ( ! UNDEFINED . equals ( reference ) ) { channelModel . setReference ( reference ) ; ComponentReferenceModel componentReferenceModel = new V1ComponentReferenceModel ( switchyardNamespace . uri ( ) ) ; componentReferenceModel . setName ( reference ) ; Class < ? > interfaze = channelAnnotation . interfaze ( ) ; if ( ! Channel . UndefinedInterface . class . isAssignableFrom ( interfaze ) ) { InterfaceModel interfaceModel = new V1InterfaceModel ( InterfaceModel . JAVA ) ; interfaceModel . setInterface ( interfaze . getName ( ) ) ; componentReferenceModel . setInterface ( interfaceModel ) ; componentModel . addReference ( componentReferenceModel ) ; } } channelsModel . addChannel ( channelModel ) ; } return channelsModel ; }
|
Converts channel annotations to a channels model .
|
2,402
|
protected ContainerModel toContainerModel ( Container containerAnnotation , KnowledgeNamespace knowledgeNamespace ) { if ( containerAnnotation == null ) { return null ; } ContainerModel containerModel = new V1ContainerModel ( knowledgeNamespace . uri ( ) ) ; String baseName = containerAnnotation . baseName ( ) ; if ( ! UNDEFINED . equals ( baseName ) ) { containerModel . setBaseName ( baseName ) ; } String releaseId = containerAnnotation . releaseId ( ) ; if ( ! UNDEFINED . equals ( releaseId ) ) { containerModel . setReleaseId ( releaseId ) ; } boolean scan = containerAnnotation . scan ( ) ; if ( scan ) { containerModel . setScan ( scan ) ; } long scanInterval = containerAnnotation . scanInterval ( ) ; if ( scanInterval > 0 ) { containerModel . setScanInterval ( Long . valueOf ( scanInterval ) ) ; } String sessionName = containerAnnotation . sessionName ( ) ; if ( ! UNDEFINED . equals ( sessionName ) ) { containerModel . setSessionName ( sessionName ) ; } return containerModel ; }
|
Converts container annotation to container model
|
2,403
|
protected ListenersModel toListenersModel ( Listener [ ] listenerAnnotations , KnowledgeNamespace knowledgeNamespace ) { if ( listenerAnnotations == null || listenerAnnotations . length == 0 ) { return null ; } ListenersModel listenersModel = new V1ListenersModel ( knowledgeNamespace . uri ( ) ) ; for ( Listener listenerAnnotation : listenerAnnotations ) { ListenerModel listenerModel = new V1ListenerModel ( knowledgeNamespace . uri ( ) ) ; listenerModel . setClazz ( listenerAnnotation . value ( ) ) ; listenersModel . addListener ( listenerModel ) ; } return listenersModel ; }
|
Converts listener annotations to listeners model .
|
2,404
|
protected LoggersModel toLoggersModel ( Logger [ ] loggerAnnotations , KnowledgeNamespace knowledgeNamespace ) { if ( loggerAnnotations == null || loggerAnnotations . length == 0 ) { return null ; } LoggersModel loggersModel = new V1LoggersModel ( knowledgeNamespace . uri ( ) ) ; for ( Logger loggerAnnotation : loggerAnnotations ) { LoggerModel loggerModel = new V1LoggerModel ( knowledgeNamespace . uri ( ) ) ; int interval = loggerAnnotation . interval ( ) ; if ( interval > - 1 ) { loggerModel . setInterval ( interval ) ; } String log = loggerAnnotation . log ( ) ; if ( ! UNDEFINED . equals ( log ) ) { loggerModel . setLog ( log ) ; } LoggerType loggerType = loggerAnnotation . type ( ) ; if ( ! LoggerType . THREADED_FILE . equals ( loggerType ) ) { loggerModel . setType ( loggerType ) ; } loggersModel . addLogger ( loggerModel ) ; } return loggersModel ; }
|
Converts logger annotations to loggers model .
|
2,405
|
protected ManifestModel toManifestModel ( Manifest [ ] manifestAnnotations , KnowledgeNamespace knowledgeNamespace ) { if ( manifestAnnotations == null || manifestAnnotations . length == 0 ) { return null ; } Manifest manifestAnnotation = manifestAnnotations [ 0 ] ; ManifestModel manifestModel = new V1ManifestModel ( knowledgeNamespace . uri ( ) ) ; Container [ ] container = manifestAnnotation . container ( ) ; if ( container != null && container . length > 0 ) { manifestModel . setContainer ( toContainerModel ( container [ 0 ] , knowledgeNamespace ) ) ; } manifestModel . setResources ( toResourcesModel ( manifestAnnotation . resources ( ) , knowledgeNamespace ) ) ; return manifestModel ; }
|
Converts manifest annotations to manifest model .
|
2,406
|
protected GlobalsModel toGlobalsModel ( Global [ ] globals , KnowledgeNamespace knowledgeNamespace ) { GlobalsModel globalsModel = null ; if ( globals != null ) { for ( Global global : globals ) { if ( global != null ) { GlobalModel globalModel = new V1GlobalModel ( knowledgeNamespace . uri ( ) ) ; String from = global . from ( ) ; if ( ! UNDEFINED . equals ( from ) ) { globalModel . setFrom ( from ) ; } String to = global . to ( ) ; if ( ! UNDEFINED . equals ( to ) ) { globalModel . setTo ( to ) ; } if ( globalsModel == null ) { globalsModel = new V1GlobalsModel ( knowledgeNamespace . uri ( ) ) ; } globalsModel . addGlobal ( globalModel ) ; } } } return globalsModel ; }
|
Converts globals to mappings model .
|
2,407
|
protected InputsModel toInputsModel ( Input [ ] inputs , KnowledgeNamespace knowledgeNamespace ) { InputsModel inputsModel = null ; if ( inputs != null ) { for ( Input input : inputs ) { if ( input != null ) { InputModel inputModel = new V1InputModel ( knowledgeNamespace . uri ( ) ) ; String from = input . from ( ) ; if ( ! UNDEFINED . equals ( from ) ) { inputModel . setFrom ( from ) ; } String to = input . to ( ) ; if ( ! UNDEFINED . equals ( to ) ) { inputModel . setTo ( to ) ; } if ( inputsModel == null ) { inputsModel = new V1InputsModel ( knowledgeNamespace . uri ( ) ) ; } inputsModel . addInput ( inputModel ) ; } } } return inputsModel ; }
|
Converts inputs to mappings model .
|
2,408
|
protected OutputsModel toOutputsModel ( Output [ ] outputs , KnowledgeNamespace knowledgeNamespace ) { OutputsModel outputsModel = null ; if ( outputs != null ) { for ( Output output : outputs ) { if ( output != null ) { OutputModel outputModel = new V1OutputModel ( knowledgeNamespace . uri ( ) ) ; String from = output . from ( ) ; if ( ! UNDEFINED . equals ( from ) ) { outputModel . setFrom ( from ) ; } String to = output . to ( ) ; if ( ! UNDEFINED . equals ( to ) ) { outputModel . setTo ( to ) ; } if ( outputsModel == null ) { outputsModel = new V1OutputsModel ( knowledgeNamespace . uri ( ) ) ; } outputsModel . addOutput ( outputModel ) ; } } } return outputsModel ; }
|
Converts outputs to mappings model .
|
2,409
|
protected FaultsModel toFaultsModel ( Fault [ ] faults , KnowledgeNamespace knowledgeNamespace ) { FaultsModel faultsModel = null ; if ( faults != null ) { for ( Fault fault : faults ) { if ( fault != null ) { FaultModel faultModel = new V1FaultModel ( knowledgeNamespace . uri ( ) ) ; String from = fault . from ( ) ; if ( ! UNDEFINED . equals ( from ) ) { faultModel . setFrom ( from ) ; } String to = fault . to ( ) ; if ( ! UNDEFINED . equals ( to ) ) { faultModel . setTo ( to ) ; } if ( faultsModel == null ) { faultsModel = new V1FaultsModel ( knowledgeNamespace . uri ( ) ) ; } faultsModel . addFault ( faultModel ) ; } } } return faultsModel ; }
|
Converts faults to mappings model .
|
2,410
|
protected PropertiesModel toPropertiesModel ( Property [ ] propertyAnnotations , KnowledgeNamespace knowledgeNamespace ) { if ( propertyAnnotations == null || propertyAnnotations . length == 0 ) { return null ; } PropertiesModel propertiesModel = new V1PropertiesModel ( knowledgeNamespace . uri ( ) ) ; for ( Property propertyAnnotation : propertyAnnotations ) { PropertyModel propertyModel = new V1PropertyModel ( knowledgeNamespace . uri ( ) ) ; String name = propertyAnnotation . name ( ) ; if ( ! UNDEFINED . equals ( name ) ) { propertyModel . setName ( name ) ; } String value = propertyAnnotation . value ( ) ; if ( ! UNDEFINED . equals ( value ) ) { propertyModel . setValue ( value ) ; } propertiesModel . addProperty ( propertyModel ) ; } return propertiesModel ; }
|
Converts property annotations to properties model .
|
2,411
|
protected ResourcesModel toResourcesModel ( Resource [ ] resourceAnnotations , KnowledgeNamespace knowledgeNamespace ) { if ( resourceAnnotations == null || resourceAnnotations . length == 0 ) { return null ; } ResourcesModel resourcesModel = new V1ResourcesModel ( knowledgeNamespace . uri ( ) ) ; for ( Resource resourceAnnotation : resourceAnnotations ) { ResourceModel resourceModel = new V1ResourceModel ( knowledgeNamespace . uri ( ) ) ; String location = resourceAnnotation . location ( ) ; if ( ! UNDEFINED . equals ( location ) ) { resourceModel . setLocation ( location ) ; } String type = resourceAnnotation . type ( ) ; if ( ! UNDEFINED . equals ( type ) ) { resourceModel . setType ( ResourceType . valueOf ( type ) ) ; } ResourceDetailModel resourceDetailModel = toResourceDetailModel ( resourceAnnotation . detail ( ) , knowledgeNamespace ) ; if ( resourceDetailModel != null ) { resourceModel . setDetail ( resourceDetailModel ) ; } resourcesModel . addResource ( resourceModel ) ; } return resourcesModel ; }
|
Converts resource annotations to resources model .
|
2,412
|
public List < ExpressionMapping > getInputOnlyExpressionMappings ( ) { List < ExpressionMapping > list = new LinkedList < ExpressionMapping > ( ) ; for ( ExpressionMapping em : _inputExpressionMappings ) { if ( em . getOutput ( ) == null ) { list . add ( em ) ; } } return list ; }
|
Gets the input - only expression mappings .
|
2,413
|
public Map < String , ExpressionMapping > getInputOutputExpressionMappings ( ) { Map < String , ExpressionMapping > map = new LinkedHashMap < String , ExpressionMapping > ( ) ; for ( ExpressionMapping em : _inputExpressionMappings ) { String output = em . getOutput ( ) ; if ( output != null ) { if ( map . containsKey ( output ) ) { throw new IllegalArgumentException ( "duplicate input/output variable [" + output + "] not allowed" ) ; } else { map . put ( output , em ) ; } } } return map ; }
|
Gets the input - output expression mappings .
|
2,414
|
protected static < T extends Manifest > T removeFromEnvironment ( Environment environment , Class < T > type ) { String identifier = type . getName ( ) ; Object manifest = environment . get ( identifier ) ; if ( manifest != null ) { environment . set ( identifier , null ) ; } return type . cast ( manifest ) ; }
|
Removes and returns the Manifest from the Environment .
|
2,415
|
public Expression getFromExpression ( ) { if ( _fromExpression == null && _from != null ) { _fromExpression = ExpressionFactory . INSTANCE . create ( _from , null , _propertyResolver ) ; } return _fromExpression ; }
|
Gets the from expression .
|
2,416
|
public Expression getToExpression ( ) { if ( _toExpression == null && _to != null ) { _toExpression = ExpressionFactory . INSTANCE . create ( _to , null , _propertyResolver ) ; } return _toExpression ; }
|
Gets the to expression .
|
2,417
|
public final void addConnections ( final int max ) throws Exception { if ( connections . size ( ) < maxConnections ) { for ( int i = 1 ; i < max ; i ++ ) { addNewConnection ( ) ; } } }
|
Adds a number of new connections to this session .
|
2,418
|
public final void close ( ) throws IOException { LOGGER . info ( "Closing was requested." ) ; for ( Connection c : connections ) { c . close ( ) ; } connections . clear ( ) ; factory . closedSession ( this ) ; executor . shutdown ( ) ; }
|
Closes this session instances with all opened connections .
|
2,419
|
private final Future < Void > executeTask ( final ITask task ) throws TaskExecutionException { if ( task instanceof IOTask ) { final Future < Void > returnVal = executor . submit ( ( IOTask ) task ) ; return returnVal ; } else { try { task . call ( ) ; } catch ( final Exception exc ) { throw new TaskExecutionException ( new ExecutionException ( exc ) ) ; } return null ; } }
|
This methods appends the given task to the end of the taskQueue and set the calling thread is sleep state .
|
2,420
|
public final void finishedTask ( final ITask ftask ) { try { taskBalancer . releaseConnection ( outstandingTasks . get ( ftask ) ) ; } catch ( NoSuchConnectionException e ) { e . printStackTrace ( ) ; } outstandingTasks . remove ( ftask ) ; LOGGER . debug ( "Finished a " + ftask + " for the session " + targetName ) ; }
|
removes Task from outstandingTasks .
|
2,421
|
public final void restartTask ( final ITask task ) throws ExecutionException { try { if ( task != null ) { if ( task instanceof IOTask ) { executor . submit ( ( IOTask ) task ) ; } else { task . call ( ) ; } taskBalancer . releaseConnection ( outstandingTasks . get ( task ) ) ; outstandingTasks . remove ( task ) ; } LOGGER . debug ( "Restarted a Task out of the outstandingTasks Queue" ) ; } catch ( Exception e ) { throw new ExecutionException ( e ) ; } }
|
restarts a Task from outstandingTasks .
|
2,422
|
public final void addOutstandingTask ( final Connection connection , final ITask task ) { outstandingTasks . put ( task , connection ) ; LOGGER . debug ( "Added a Task to the outstandingTasks Queue" ) ; }
|
Adds a Task to the outstandingTasks Hashmap .
|
2,423
|
public boolean execute ( ) throws DigestException , IOException , InterruptedException , InternetSCSIException , SettingsException { running = true ; while ( running ) { ProtocolDataUnit pdu = connection . receivePdu ( ) ; BasicHeaderSegment bhs = pdu . getBasicHeaderSegment ( ) ; switch ( bhs . getOpCode ( ) ) { case SCSI_COMMAND : if ( connection . getTargetSession ( ) . isNormalSession ( ) ) { final SCSICommandParser parser = ( SCSICommandParser ) bhs . getParser ( ) ; ScsiOperationCode scsiOpCode = ScsiOperationCode . valueOf ( parser . getCDB ( ) . get ( 0 ) ) ; LOGGER . debug ( "scsiOpCode = " + scsiOpCode ) ; if ( scsiOpCode != null ) { switch ( scsiOpCode ) { case TEST_UNIT_READY : stage = new TestUnitReadyStage ( this ) ; break ; case REQUEST_SENSE : stage = new RequestSenseStage ( this ) ; break ; case FORMAT_UNIT : stage = new FormatUnitStage ( this ) ; break ; case INQUIRY : stage = new InquiryStage ( this ) ; break ; case MODE_SELECT_6 : stage = null ; scsiOpCode = null ; break ; case MODE_SENSE_6 : stage = new ModeSenseStage ( this ) ; if ( ! ( ( ModeSenseStage ) stage ) . canHandle ( pdu ) ) { stage = null ; scsiOpCode = null ; } break ; case SEND_DIAGNOSTIC : stage = new SendDiagnosticStage ( this ) ; break ; case READ_CAPACITY_10 : case READ_CAPACITY_16 : stage = new ReadCapacityStage ( this ) ; break ; case WRITE_6 : case WRITE_10 : stage = new WriteStage ( this ) ; break ; case READ_6 : case READ_10 : stage = new ReadStage ( this ) ; break ; case REPORT_LUNS : stage = new ReportLunsStage ( this ) ; break ; default : scsiOpCode = null ; } } if ( scsiOpCode == null ) { LOGGER . error ( "Unsupported SCSI OpCode 0x" + Integer . toHexString ( parser . getCDB ( ) . get ( 0 ) & 255 ) + " in SCSI Command PDU." ) ; stage = new UnsupportedOpCodeStage ( this ) ; } } else { throw new InternetSCSIException ( "received SCSI command in discovery session" ) ; } break ; case SCSI_TM_REQUEST : stage = new TMStage ( this ) ; break ; case NOP_OUT : stage = new PingStage ( this ) ; break ; case TEXT_REQUEST : stage = new TextNegotiationStage ( this ) ; break ; case LOGOUT_REQUEST : stage = new LogoutStage ( this ) ; running = false ; break ; default : LOGGER . error ( "Received unsupported opcode for " + pdu . getBasicHeaderSegment ( ) . getOpCode ( ) ) ; stage = new UnsupportedOpCodeStage ( this ) ; } stage . execute ( pdu ) ; } return false ; }
|
Starts the full feature phase .
|
2,424
|
public final void closeSession ( final String targetName ) throws NoSuchSessionException , TaskExecutionException { getSession ( targetName ) . logout ( ) ; sessions . remove ( targetName ) ; LOGGER . info ( "Closed the session to the iSCSI Target '" + targetName + "'." ) ; }
|
Closes all opened connections within this session to the given target .
|
2,425
|
public final synchronized void flush ( ) throws Exception { List < Long > sortedKeys = new ArrayList < Long > ( buffer . keySet ( ) ) ; Collections . sort ( sortedKeys ) ; while ( sortedKeys . size ( ) > 0 ) { long firstKey = sortedKeys . get ( 0 ) ; int firstDataLength = buffer . get ( firstKey ) . length ; int i = 1 ; while ( i < sortedKeys . size ( ) && sortedKeys . get ( i ) == sortedKeys . get ( i - 1 ) + ( firstDataLength / getBlockSize ( ) ) ) { i ++ ; } byte [ ] data = new byte [ firstDataLength * i ] ; for ( int j = 0 ; j < i ; j ++ ) { System . arraycopy ( buffer . get ( sortedKeys . get ( j ) ) , 0 , data , j * firstDataLength , firstDataLength ) ; } device . write ( firstKey , data ) ; if ( sortedKeys . size ( ) != 1 ) { sortedKeys = sortedKeys . subList ( i , sortedKeys . size ( ) ) ; } else { sortedKeys . clear ( ) ; } } buffer . clear ( ) ; }
|
Flush the buffer to the target .
|
2,426
|
public void read ( byte [ ] bytes , long storageIndex ) throws IOException { long filePos = storageIndex / mFileSize ; int storageOffset = ( int ) ( storageIndex % mFileSize ) ; byte [ ] cachedBytes = mCache . getIfPresent ( filePos ) ; File fileAtPos = new File ( mBaseDir + File . separator + filePos ) ; if ( ! fileAtPos . exists ( ) ) { fileAtPos . createNewFile ( ) ; cachedBytes = new byte [ mFileSize ] ; Files . write ( fileAtPos . toPath ( ) , cachedBytes ) ; } else if ( cachedBytes == null ) { cachedBytes = Files . readAllBytes ( fileAtPos . toPath ( ) ) ; mCache . put ( ( int ) filePos , cachedBytes ) ; } if ( ( storageOffset + bytes . length ) > mFileSize ) { System . arraycopy ( cachedBytes , storageOffset , bytes , 0 , mFileSize - storageOffset ) ; byte [ ] nextStep = new byte [ bytes . length - ( mFileSize - storageOffset ) ] ; read ( nextStep , storageIndex + ( mFileSize - storageOffset ) ) ; System . arraycopy ( nextStep , 0 , bytes , mFileSize - storageOffset , nextStep . length ) ; } else { System . arraycopy ( cachedBytes , storageOffset , bytes , 0 , bytes . length ) ; } }
|
Reading bytes from file
|
2,427
|
final int serialize ( final ByteBuffer dst , final int offset ) throws InternetSCSIException { dst . position ( offset ) ; if ( dst . remaining ( ) < BHS_FIXED_SIZE ) { throw new IllegalArgumentException ( "Destination array is too small." ) ; } int line = 0 ; if ( immediateFlag ) { line |= IMMEDIATE_FLAG_MASK ; } line |= operationCode . value ( ) << Constants . THREE_BYTES_SHIFT ; if ( finalFlag ) { line |= FINAL_FLAG_MASK ; } dst . putInt ( line ) ; dst . putInt ( dataSegmentLength | ( totalAHSLength << Constants . THREE_BYTES_SHIFT ) ) ; dst . putInt ( BYTES_16_19 , initiatorTaskTag ) ; parser . serializeBasicHeaderSegment ( dst , offset ) ; return BHS_FIXED_SIZE ; }
|
This method serializes the informations of this BHS object to the byte representation defined by the iSCSI Standard .
|
2,428
|
final int deserialize ( final ProtocolDataUnit protocolDataUnit , final ByteBuffer src ) throws InternetSCSIException { if ( src . remaining ( ) < BHS_FIXED_SIZE ) { throw new InternetSCSIException ( "This Protocol Data Unit does not contain" + " an valid Basic Header Segment." ) ; } final int firstLine = src . getInt ( ) ; immediateFlag = Utils . isBitSet ( firstLine & IMMEDIATE_FLAG_MASK ) ; final int code = ( firstLine & OPERATION_CODE_MASK ) >> Constants . THREE_BYTES_SHIFT ; operationCode = OperationCode . valueOf ( ( byte ) code ) ; finalFlag = Utils . isBitSet ( firstLine & FINAL_FLAG_MASK ) ; totalAHSLength = src . get ( ) ; dataSegmentLength = Utils . getUnsignedInt ( src . get ( ) ) << Constants . TWO_BYTES_SHIFT ; dataSegmentLength += Utils . getUnsignedInt ( src . get ( ) ) << Constants . ONE_BYTE_SHIFT ; dataSegmentLength += Utils . getUnsignedInt ( src . get ( ) ) ; initiatorTaskTag = src . getInt ( BYTES_16_19 ) ; parser = MessageParserFactory . getParser ( protocolDataUnit , operationCode ) ; src . rewind ( ) ; parser . deserializeBasicHeaderSegment ( src ) ; return BHS_FIXED_SIZE ; }
|
Extract from the given Protocol Data Unit the BHS . After an successful extraction this methods and setreturns the right message parser object for this kind of message .
|
2,429
|
final void setOperationCode ( final ProtocolDataUnit protocolDataUnit , final OperationCode initOperationCode ) { operationCode = initOperationCode ; parser = MessageParserFactory . getParser ( protocolDataUnit , initOperationCode ) ; }
|
Set a new operation code for this BHS object .
|
2,430
|
final void clear ( ) { immediateFlag = false ; operationCode = OperationCode . LOGIN_REQUEST ; finalFlag = false ; totalAHSLength = 0x00 ; dataSegmentLength = 0x00000000 ; initiatorTaskTag = 0x00000000 ; parser = null ; }
|
Clears all the stored content of this BasicHeaderSegment object .
|
2,431
|
final int serialize ( final ByteBuffer dst , final int offset ) throws InternetSCSIException { dst . position ( offset ) ; if ( dst . remaining ( ) < length ) { throw new IllegalArgumentException ( "Destination array is too small." ) ; } dst . putShort ( length ) ; dst . put ( type . value ( ) ) ; dst . put ( specificField . get ( ) ) ; while ( specificField . hasRemaining ( ) ) { dst . putInt ( specificField . getInt ( ) ) ; } return length + FIX_SIZE_OVERHEAD ; }
|
This method serializes the informations of this AHS object to the byte representation defined by the iSCSI Standard .
|
2,432
|
final void deserialize ( final ByteBuffer pdu , final int offset ) throws InternetSCSIException { pdu . position ( offset ) ; length = pdu . getShort ( ) ; type = AdditionalHeaderSegmentType . valueOf ( pdu . get ( ) ) ; specificField = ByteBuffer . allocate ( length ) ; specificField . put ( pdu . get ( ) ) ; while ( specificField . hasRemaining ( ) ) { specificField . putInt ( pdu . getInt ( ) ) ; } checkIntegrity ( ) ; }
|
Extract the informations given by the int array to this Additional Header Segment object .
|
2,433
|
private final void checkIntegrity ( ) throws InternetSCSIException { switch ( type ) { case EXTENDED_CDB : case EXPECTED_BIDIRECTIONAL_READ_DATA_LENGTH : break ; default : throw new InternetSCSIException ( "AHS Package is not valid." ) ; } specificField . rewind ( ) ; Utils . isReserved ( specificField . get ( ) ) ; switch ( type ) { case EXTENDED_CDB : break ; case EXPECTED_BIDIRECTIONAL_READ_DATA_LENGTH : Utils . isExpected ( specificField . limit ( ) , EXPECTED_BIDIRECTIONAL_SPECIFIC_FIELD_LENGTH ) ; Utils . isExpected ( length , EXPECTED_BIDIRECTIONAL_LENGTH ) ; break ; default : throw new InternetSCSIException ( "Unknown additional header segment type." ) ; } specificField . rewind ( ) ; }
|
This method checks the integrity of the this Additional Header Segment object to garantee a valid specification .
|
2,434
|
private final void serializeCommonFields ( final ByteBuffer byteBuffer , final int index ) { byteBuffer . position ( index ) ; byte b = 0 ; if ( senseKeySpecificDataValid ) b = BitManip . getByteWithBitSet ( b , 7 , true ) ; byteBuffer . put ( b ) ; }
|
Serializes the fields common to all sense - key - specific data .
|
2,435
|
private final void serializeCommonFields ( final ByteBuffer byteBuffer , final int index ) { byteBuffer . position ( index ) ; byteBuffer . put ( descriptorType . getValue ( ) ) ; byteBuffer . put ( ( byte ) additionalLength ) ; }
|
Serializes the fields common to all sense data descriptors .
|
2,436
|
@ SuppressWarnings ( "unchecked" ) public CDB decode ( ByteBuffer input ) throws IOException { byte [ ] opcode = new byte [ 1 ] ; input . duplicate ( ) . get ( opcode ) ; DataInputStream in = new DataInputStream ( new ByteArrayInputStream ( opcode ) ) ; int operationCode = in . readUnsignedByte ( ) ; if ( ! _cdbs . containsKey ( operationCode ) ) { throw new IOException ( String . format ( "Could not create new cdb with unsupported operation code: %x" , operationCode ) ) ; } try { CDB cdb = _cdbs . get ( operationCode ) . newInstance ( ) ; cdb . decode ( null , input ) ; return cdb ; } catch ( InstantiationException e ) { throw new IOException ( "Could not create new cdb parser: " + e . getMessage ( ) ) ; } catch ( IllegalAccessException e ) { throw new IOException ( "Could not create new cdb parser: " + e . getMessage ( ) ) ; } }
|
Used by iSCSI transport layer to decode CDB data off the wire .
|
2,437
|
private static final ByteBuffer createReadWriteMessage ( final byte opCode , final int logicalBlockAddress , final short transferLength ) { ByteBuffer cdb = ByteBuffer . allocate ( DEFAULT_CDB_LENGTH ) ; cdb . put ( opCode ) ; cdb . position ( LOGICAL_BLOCK_ADDRESS_OFFSET ) ; cdb . putInt ( logicalBlockAddress ) ; cdb . position ( TRANSFER_LENGTH_OFFSET ) ; cdb . putShort ( transferLength ) ; cdb . rewind ( ) ; return cdb ; }
|
Creates the Command Descriptor Block for a given Operation Message .
|
2,438
|
public static final ByteBuffer createReadCapacityMessage ( ) { ByteBuffer cdb = ByteBuffer . allocate ( DEFAULT_CDB_LENGTH ) ; cdb . put ( READ_CAPACITY_OP_CODE ) ; cdb . rewind ( ) ; return cdb ; }
|
Creates the Command Descriptor Block for a Read Capacity Message .
|
2,439
|
public static void main ( final String [ ] args ) throws Exception { WhiskasDemo demo = new WhiskasDemo ( ) ; demo . setUp ( ) ; while ( true ) { demo . sequentialRead ( ) ; demo . randomRead ( ) ; } }
|
Main method to start the demo .
|
2,440
|
public void stop ( ) { this . running = false ; for ( TargetSession session : sessions ) { if ( ! session . getConnection ( ) . stop ( ) ) { this . running = true ; LOGGER . error ( "Unable to stop session for " + session . getTargetName ( ) ) ; } } }
|
Stop this target server
|
2,441
|
public final long serialize ( ) throws InternetSCSIException { checkIntegrity ( ) ; long isid = 0 ; int firstLine = c ; firstLine |= b << Constants . ONE_BYTE_SHIFT ; firstLine |= a << Constants . THREE_BYTES_SHIFT ; firstLine &= 0x00ffffff ; firstLine |= t . value ( ) << T_FIELD_SHIFT ; isid = Utils . getUnsignedLong ( firstLine ) << Constants . FOUR_BYTES_SHIFT ; isid |= Utils . getUnsignedLong ( d ) << Constants . TWO_BYTES_SHIFT ; return isid ; }
|
Serializes this ISID object ot its byte representation .
|
2,442
|
final void deserialize ( long isid ) throws InternetSCSIException { int line = ( int ) ( isid >>> Constants . FOUR_BYTES_SHIFT ) ; t = Format . valueOf ( ( byte ) ( line >>> T_FIELD_SHIFT ) ) ; a = ( byte ) ( ( line & A_FIELD_FLAG_MASK ) >>> Constants . THREE_BYTES_SHIFT ) ; b = ( short ) ( ( line & Constants . MIDDLE_TWO_BYTES_SHIFT ) >>> Constants . ONE_BYTE_SHIFT ) ; c = ( byte ) ( line & Constants . FOURTH_BYTE_MASK ) ; line = ( int ) ( isid & Constants . LAST_FOUR_BYTES_MASK ) ; d = ( short ) ( ( line & Constants . FIRST_TWO_BYTES_MASK ) >>> Constants . TWO_BYTES_SHIFT ) ; checkIntegrity ( ) ; }
|
Parses a given ISID in this ISID obejct .
|
2,443
|
protected final void checkIntegrity ( ) throws InternetSCSIException { String exceptionMessage = "" ; switch ( t ) { case OUI_FORMAT : break ; case IANA_ENTERPRISE_NUMBER : break ; case RANDOM : break ; case RESERVED : if ( a != 0 && b != 0 && c != 0 && d != 0 ) { exceptionMessage = "This ISID is not valid. All" ; } break ; default : exceptionMessage = "This format is not supported." ; } if ( exceptionMessage . length ( ) > 0 ) { throw new InternetSCSIException ( exceptionMessage ) ; } else { } }
|
This method checks if all fields are valid . In these cases an exception will be thrown .
|
2,444
|
public final ByteBuffer serialize ( ) throws InternetSCSIException , IOException { basicHeaderSegment . getParser ( ) . checkIntegrity ( ) ; final ByteBuffer pdu = ByteBuffer . allocate ( calcSize ( ) ) ; int offset = 0 ; offset += basicHeaderSegment . serialize ( pdu , offset ) ; if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "Serialized Basic Header Segment:\n" + toString ( ) ) ; } offset += serializeAdditionalHeaderSegments ( pdu , offset ) ; if ( basicHeaderSegment . getParser ( ) . canHaveDigests ( ) ) { offset += serializeDigest ( pdu , headerDigest ) ; } offset += serializeDataSegment ( pdu , offset ) ; if ( basicHeaderSegment . getParser ( ) . canHaveDigests ( ) ) { offset += serializeDigest ( pdu , dataDigest ) ; } return ( ByteBuffer ) pdu . rewind ( ) ; }
|
Serialize all informations of this PDU object to its byte representation .
|
2,445
|
private final int serializeAdditionalHeaderSegments ( final ByteBuffer dst , final int offset ) throws InternetSCSIException { int off = offset ; for ( AdditionalHeaderSegment ahs : additionalHeaderSegments ) { off += ahs . serialize ( dst , off ) ; } return off - offset ; }
|
Serialize all the contained additional header segments to the destination array starting from the given offset .
|
2,446
|
public final void clear ( ) { basicHeaderSegment . clear ( ) ; headerDigest . reset ( ) ; additionalHeaderSegments . clear ( ) ; dataSegment . clear ( ) ; dataSegment . flip ( ) ; dataDigest . reset ( ) ; }
|
Clears all stored content of this ProtocolDataUnit object .
|
2,447
|
public final void setDataSegment ( final IDataSegmentChunk chunk ) { if ( chunk == null ) { throw new NullPointerException ( ) ; } dataSegment = ByteBuffer . allocate ( chunk . getTotalLength ( ) ) ; dataSegment . put ( chunk . getData ( ) ) ; basicHeaderSegment . setDataSegmentLength ( chunk . getLength ( ) ) ; }
|
Sets a new data segment in this PDU .
|
2,448
|
private short getPageLength ( ) { short pageLength = 0 ; for ( int i = 0 ; i < identificationDescriptors . length ; ++ i ) { pageLength += identificationDescriptors [ i ] . size ( ) ; } return pageLength ; }
|
Returns the combined length of all contained IDENTIFICATION DESCRIPTORs .
|
2,449
|
public final void setCommandDescriptorBlock ( final ByteBuffer newCDB ) { if ( newCDB . limit ( ) - newCDB . position ( ) > CDB_SIZE ) { throw new IllegalArgumentException ( "Buffer cannot be longer than 16 bytes, because AHS-support is not implemented." ) ; } commandDescriptorBlock = newCDB ; }
|
Sets the new Command Descriptor Block .
|
2,450
|
private static synchronized boolean createStorageVolume ( final File pToCreate , final long pLength ) throws IOException { FileOutputStream outStream = null ; try { if ( pToCreate . exists ( ) ) { if ( ! pToCreate . delete ( ) ) { LOGGER . debug ( "Removal of old storage " + pToCreate . toString ( ) + " unsucessful." ) ; return false ; } LOGGER . debug ( "Removal of old storage " + pToCreate . toString ( ) + " sucessful." ) ; } final File parent = pToCreate . getCanonicalFile ( ) . getParentFile ( ) ; if ( ! parent . exists ( ) && ! parent . mkdirs ( ) ) { throw new FileNotFoundException ( "Unable to create directory: " + parent . getAbsolutePath ( ) ) ; } pToCreate . createNewFile ( ) ; outStream = new FileOutputStream ( pToCreate ) ; final FileChannel fcout = outStream . getChannel ( ) ; fcout . position ( pLength ) ; outStream . write ( 26 ) ; fcout . force ( true ) ; LOGGER . debug ( "Creation of storage " + pToCreate . toString ( ) + " sucessful." ) ; return true ; } catch ( IOException e ) { LOGGER . error ( "Exception creating storage volume " + pToCreate . getAbsolutePath ( ) + ": " + e . getMessage ( ) , e ) ; throw e ; } finally { if ( outStream != null ) { try { outStream . close ( ) ; } catch ( IOException e ) { LOGGER . error ( "Exception closing storage volume: " + e . getMessage ( ) , e ) ; } } } }
|
Creating a new file if not existing at the path defined in the config . Note that it is advised to create the file beforehand .
|
2,451
|
public static boolean recursiveDelete ( final File pFile ) { if ( pFile . isDirectory ( ) ) { for ( final File child : pFile . listFiles ( ) ) { if ( ! recursiveDelete ( child ) ) { return false ; } } } return pFile . delete ( ) ; }
|
Deleting a storage recursive . Used for deleting a databases
|
2,452
|
public final void add ( final OperationalTextKey textKey , final String value ) { final String s = textKey . value ( ) + KEY_VALUE_DELIMITER + value + PAIR_DELIMITER ; resizeBuffer ( s . length ( ) , true ) ; dataBuffer . put ( s . getBytes ( ) ) ; isDirty = true ; }
|
Add a given operation text keys with the given value to the key value pairs .
|
2,453
|
public static final int getReponseCodeFor ( final ErrorType errorType , final SenseDataFormat senseDataFormat ) { if ( senseDataFormat == SenseDataFormat . FIXED ) { if ( errorType == ErrorType . CURRENT ) return 0x70 ; else return 0x71 ; } else { if ( errorType == ErrorType . CURRENT ) return 0x72 ; else return 0x73 ; } }
|
Returns the proper response code for the given error type and sense data format .
|
2,454
|
public Collection < ModePage > get ( boolean subPages ) { List < ModePage > value = new LinkedList < ModePage > ( ) ; for ( Map < Integer , ModePage > pagelist : pages . values ( ) ) { for ( ModePage page : pagelist . values ( ) ) { if ( page . getSubPageCode ( ) == 0x00 ) { value . add ( page ) ; } else if ( subPages ) { value . add ( page ) ; } } } return value ; }
|
Returns all mode pages .
|
2,455
|
public Collection < ModePage > get ( byte pageCode ) { if ( this . contains ( pageCode ) ) return this . pages . get ( pageCode ) . values ( ) ; else return null ; }
|
Returns all mode pages with the given page code .
|
2,456
|
public final int [ ] getTable ( final int offset ) { final int [ ] table = new int [ SIZE_OF_TABLE ] ; long numberToCalculate ; for ( int number = 0 ; number < table . length ; number ++ ) { numberToCalculate = Integer . reverseBytes ( Integer . reverse ( number ) ) ; table [ number ] = calculateCRC32 ( numberToCalculate << offset ) ; } return table ; }
|
Returns all remainders of the polynomial division for the given offset .
|
2,457
|
final void deserializeBasicHeaderSegment ( final ByteBuffer pdu ) throws InternetSCSIException { deserializeBytes1to3 ( pdu . getInt ( ) & FIRST_SPECIFIC_FIELD_MASK ) ; pdu . position ( BasicHeaderSegment . BYTES_8_11 ) ; deserializeBytes8to11 ( pdu . getInt ( ) ) ; deserializeBytes12to15 ( pdu . getInt ( ) ) ; pdu . position ( BasicHeaderSegment . BYTES_20_23 ) ; deserializeBytes20to23 ( pdu . getInt ( ) ) ; deserializeBytes24to27 ( pdu . getInt ( ) ) ; deserializeBytes28to31 ( pdu . getInt ( ) ) ; deserializeBytes32to35 ( pdu . getInt ( ) ) ; deserializeBytes36to39 ( pdu . getInt ( ) ) ; deserializeBytes40to43 ( pdu . getInt ( ) ) ; deserializeBytes44to47 ( pdu . getInt ( ) ) ; }
|
This method defines the order of the parsing process of the operation code specific fields and check their integtity .
|
2,458
|
final void serializeBasicHeaderSegment ( final ByteBuffer dst , final int offset ) throws InternetSCSIException { dst . position ( offset ) ; dst . putInt ( offset , dst . getInt ( ) | serializeBytes1to3 ( ) ) ; dst . position ( offset + BasicHeaderSegment . BYTES_8_11 ) ; dst . putInt ( serializeBytes8to11 ( ) ) ; dst . putInt ( serializeBytes12to15 ( ) ) ; dst . position ( offset + BasicHeaderSegment . BYTES_20_23 ) ; dst . putInt ( serializeBytes20to23 ( ) ) ; dst . putInt ( serializeBytes24to27 ( ) ) ; dst . putInt ( serializeBytes28to31 ( ) ) ; dst . putInt ( serializeBytes32to35 ( ) ) ; dst . putInt ( serializeBytes36to39 ( ) ) ; dst . putInt ( serializeBytes40to43 ( ) ) ; dst . putInt ( serializeBytes44to47 ( ) ) ; }
|
This method serializes the whole BHS to its byte representation .
|
2,459
|
public final String getSetting ( final String targetName , final int connectionID , final OperationalTextKey textKey ) throws OperationalTextKeyException { try { final SessionConfiguration sc ; synchronized ( sessionConfigs ) { sc = sessionConfigs . get ( targetName ) ; synchronized ( sc ) { if ( sc != null ) { String value = sc . getSetting ( connectionID , textKey ) ; if ( value != null ) { return value ; } } } } } catch ( OperationalTextKeyException e ) { } final SettingEntry se ; synchronized ( globalConfig ) { se = globalConfig . get ( textKey ) ; synchronized ( se ) { if ( se != null ) { return se . getValue ( ) ; } } } throw new OperationalTextKeyException ( "No OperationalTextKey entry found for key: " + textKey . value ( ) ) ; }
|
Returns the value of a single parameter instead of all values .
|
2,460
|
public final String getSessionSetting ( final String targetName , final OperationalTextKey textKey ) throws OperationalTextKeyException { return getSetting ( targetName , - 1 , textKey ) ; }
|
Returns the value of a single parameter . It can only return session and global parameters .
|
2,461
|
public final void update ( final String targetName , final int connectionID , final SettingsMap response ) throws NoSuchSessionException { final SessionConfiguration sc ; synchronized ( sessionConfigs ) { sc = sessionConfigs . get ( targetName ) ; synchronized ( sc ) { if ( sc == null ) { throw new NoSuchSessionException ( "A session with the ID '" + targetName + "' does not exist." ) ; } synchronized ( response ) { SettingEntry se ; for ( Map . Entry < OperationalTextKey , String > e : response . entrySet ( ) ) { synchronized ( globalConfig ) { se = globalConfig . get ( e . getKey ( ) ) ; if ( se == null ) { if ( LOGGER . isWarnEnabled ( ) ) { LOGGER . warn ( "This key " + e . getKey ( ) + " is not in the globalConfig." ) ; } continue ; } synchronized ( se ) { if ( se . getScope ( ) . compareTo ( VALUE_SCOPE_SESSION ) == 0 ) { sc . updateSessionSetting ( e . getKey ( ) , e . getValue ( ) , se . getResult ( ) ) ; } else if ( se . getScope ( ) . compareTo ( VALUE_SCOPE_CONNECTION ) == 0 ) { sc . updateConnectionSetting ( connectionID , e . getKey ( ) , e . getValue ( ) , se . getResult ( ) ) ; } } } } } } } }
|
Updates the stored settings of a connection with these values from the response of the iSCSI Target .
|
2,462
|
private final void parseSettings ( final Element root ) { if ( root == null ) { throw new NullPointerException ( ) ; } clear ( ) ; parseGlobalSettings ( root ) ; parseTargetSpecificSettings ( root ) ; }
|
Parses all settings form the main configuration file .
|
2,463
|
private final void parseGlobalSettings ( final Element root ) { final NodeList globalConfiguration = root . getElementsByTagName ( ELEMENT_GLOBAL ) ; final ResultFunctionFactory resultFunctionFactory = new ResultFunctionFactory ( ) ; Node parameter ; NodeList parameters ; NamedNodeMap attributes ; SettingEntry key ; for ( int i = 0 ; i < globalConfiguration . getLength ( ) ; i ++ ) { parameters = globalConfiguration . item ( i ) . getChildNodes ( ) ; for ( int j = 0 ; j < parameters . getLength ( ) ; j ++ ) { parameter = parameters . item ( j ) ; if ( parameter . getNodeType ( ) == Node . ELEMENT_NODE ) { attributes = parameter . getAttributes ( ) ; key = new SettingEntry ( ) ; key . setScope ( attributes . getNamedItem ( ATTRIBUTE_SCOPE ) . getNodeValue ( ) ) ; key . setResult ( resultFunctionFactory . create ( attributes . getNamedItem ( ATTRIBUTE_RESULT ) . getNodeValue ( ) ) ) ; key . setValue ( parameter . getTextContent ( ) ) ; synchronized ( globalConfig ) { globalConfig . put ( OperationalTextKey . valueOfEx ( parameter . getNodeName ( ) ) , key ) ; } } } } }
|
Parses all global settings form the main configuration file .
|
2,464
|
private final void parseTargetSpecificSettings ( final Element root ) { final NodeList targets = root . getElementsByTagName ( ELEMENT_TARGET ) ; Node target ; Node parameter ; NodeList parameters ; try { for ( int i = 0 ; i < targets . getLength ( ) ; i ++ ) { target = targets . item ( i ) ; parameters = target . getChildNodes ( ) ; SessionConfiguration sc = new SessionConfiguration ( ) ; sc . setAddress ( target . getAttributes ( ) . getNamedItem ( ATTRIBUTE_ADDRESS ) . getNodeValue ( ) , Integer . parseInt ( target . getAttributes ( ) . getNamedItem ( ATTRIBUTE_PORT ) . getNodeValue ( ) ) ) ; for ( int j = 0 ; j < parameters . getLength ( ) ; j ++ ) { parameter = parameters . item ( j ) ; if ( parameter . getNodeType ( ) == Node . ELEMENT_NODE ) { sc . addSessionSetting ( OperationalTextKey . valueOfEx ( parameter . getNodeName ( ) ) , parameter . getTextContent ( ) ) ; } } synchronized ( sessionConfigs ) { sessionConfigs . put ( target . getAttributes ( ) . getNamedItem ( ATTRIBUTE_ID ) . getNodeValue ( ) , sc ) ; } } } catch ( UnknownHostException e ) { if ( LOGGER . isErrorEnabled ( ) ) { LOGGER . error ( "The given host is not reachable: " + e . getLocalizedMessage ( ) ) ; } } }
|
Parses all target - specific settings form the main configuration file .
|
2,465
|
public static String byteBufferToString ( final ByteBuffer buffer ) { if ( buffer == null ) return "null" ; final int numberOfBytes = buffer . limit ( ) ; final StringBuilder sb = new StringBuilder ( ) ; buffer . position ( 0 ) ; int value ; for ( int i = 1 ; i <= numberOfBytes ; ++ i ) { sb . append ( "0x" ) ; value = 255 & buffer . get ( ) ; if ( value < 16 ) sb . append ( "0" ) ; sb . append ( Integer . toHexString ( value ) ) ; if ( i % BYTES_PER_LINE == 0 ) sb . append ( "\n" ) ; else sb . append ( " " ) ; } return sb . toString ( ) ; }
|
Returns a string containing the buffered values in the defined format .
|
2,466
|
public boolean execute ( ProtocolDataUnit pdu ) throws IOException , InterruptedException , InternetSCSIException , DigestException , SettingsException { final ConnectionSettingsNegotiator negotiator = connection . getConnectionSettingsNegotiator ( ) ; while ( ! negotiator . beginNegotiation ( ) ) { } boolean loginSuccessful = true ; try { BasicHeaderSegment bhs = pdu . getBasicHeaderSegment ( ) ; LoginRequestParser parser = ( LoginRequestParser ) bhs . getParser ( ) ; LoginStage nextStageNumber ; if ( parser . getCurrentStageNumber ( ) == LoginStage . SECURITY_NEGOTIATION ) { stage = new SecurityNegotiationStage ( this ) ; stage . execute ( pdu ) ; nextStageNumber = stage . getNextStageNumber ( ) ; if ( nextStageNumber != null ) authenticated = true ; else { loginSuccessful = false ; return false ; } if ( nextStageNumber == LoginStage . LOGIN_OPERATIONAL_NEGOTIATION ) { pdu = connection . receivePdu ( ) ; bhs = pdu . getBasicHeaderSegment ( ) ; parser = ( LoginRequestParser ) bhs . getParser ( ) ; } else if ( nextStageNumber == LoginStage . FULL_FEATURE_PHASE ) { return true ; } else { loginSuccessful = false ; return false ; } } if ( parser != null && authenticated && parser . getCurrentStageNumber ( ) == LoginStage . LOGIN_OPERATIONAL_NEGOTIATION ) { stage = new LoginOperationalParameterNegotiationStage ( this ) ; stage . execute ( pdu ) ; nextStageNumber = stage . getNextStageNumber ( ) ; if ( nextStageNumber == LoginStage . FULL_FEATURE_PHASE ) return true ; } loginSuccessful = false ; return false ; } catch ( DigestException e ) { loginSuccessful = false ; throw e ; } catch ( IOException e ) { loginSuccessful = false ; throw e ; } catch ( InterruptedException e ) { loginSuccessful = false ; throw e ; } catch ( InternetSCSIException e ) { loginSuccessful = false ; throw e ; } catch ( SettingsException e ) { loginSuccessful = false ; throw e ; } finally { negotiator . finishNegotiation ( loginSuccessful ) ; } }
|
Starts the login phase .
|
2,467
|
public int drainTo ( Collection < ? super Task > c ) { if ( c == this ) throw new IllegalArgumentException ( "cannot drain task set into itself" ) ; if ( c == null ) throw new NullPointerException ( "target collection must not be null" ) ; int count = 0 ; while ( true ) { try { Task t = this . poll ( 0 , TimeUnit . SECONDS ) ; if ( t == null ) break ; else c . add ( t ) ; } catch ( InterruptedException e ) { break ; } } return count ; }
|
Removes all available elements from this task set . Any tasks that are blocked will not be removed . Will cease draining if the thread is interrupted .
|
2,468
|
private static final void indent ( final StringBuilder sb , final int indent ) { for ( int i = 0 ; i < indent ; i ++ ) { sb . append ( LOG_OUT_INDENT ) ; } }
|
Appends to a given StringBuilder the given indents depending on the indent level .
|
2,469
|
public TaskServiceResponse abortTaskSet ( Nexus nexus ) { try { this . taskSet . abort ( nexus ) ; return TaskServiceResponse . FUNCTION_COMPLETE ; } catch ( InterruptedException e ) { return TaskServiceResponse . SERVICE_DELIVERY_OR_TARGET_FAILURE ; } catch ( IllegalArgumentException e ) { throw e ; } }
|
is simply attempting to remove a task from the scheduler
|
2,470
|
boolean checkIntegrity ( ) { if ( headerType == null ) return false ; if ( headerType == HeaderType . MODE_PARAMETER_HEADER_6 && longLba ) return false ; return true ; }
|
This method is used for checking that all required members are initialized and their respective values compatible with each other .
|
2,471
|
public final void update ( final SettingsMap response ) throws NoSuchSessionException { configuration . update ( referenceSession . getTargetName ( ) , connectionID , response ) ; }
|
Updates all entries of the given response key - values with the stored settings of this instance .
|
2,472
|
public final void nextState ( final IState newState ) throws InternetSCSIException { this . state = newState ; if ( this . state != null ) { do { this . state . execute ( ) ; LOGGER . info ( "State is following: " + this . state . nextStateFollowing ( ) ) ; } while ( this . state . nextStateFollowing ( ) ) ; } }
|
Switch to the new state . Start point of the state pattern . All states are computed one after another .
|
2,473
|
public final void send ( final ProtocolDataUnit protocolDataUnit ) throws InternetSCSIException { try { senderReceiver . sendOverWire ( protocolDataUnit ) ; } catch ( IOException e ) { throw new InternetSCSIException ( e ) ; } catch ( InterruptedException e ) { throw new InternetSCSIException ( e ) ; } }
|
Enqueue this protocol data unit to the end of the sending queue .
|
2,474
|
public final void send ( final Queue < ProtocolDataUnit > protocolDataUnits ) throws InternetSCSIException { for ( final ProtocolDataUnit unit : protocolDataUnits ) { send ( unit ) ; } }
|
Enqueue all protocol data units to the end of the sending queue .
|
2,475
|
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private final void processQueue ( ) { SoftValue < V > softValue ; while ( ( softValue = ( SoftValue ) queue . poll ( ) ) != null ) { internalMap . remove ( softValue . key ) ; } }
|
Remove garbage collected soft values with the help of the reference queue .
|
2,476
|
private static final int base64ValueOf ( final char c ) { if ( 'A' <= c && c <= 'Z' ) return c - 'A' ; if ( 'a' <= c && c <= 'z' ) return c - 'a' + 26 ; if ( '0' <= c && c <= '9' ) return c - '0' + 52 ; if ( c == '+' ) return 62 ; if ( c == '/' ) return 63 ; throw new NumberFormatException ( ) ; }
|
Returns a character s value in Base64
|
2,477
|
protected final void sendRejectPdu ( final LoginStatus errorStatus ) throws InterruptedException , IOException , InternetSCSIException { final ProtocolDataUnit rejectPDU = TargetPduFactory . createLoginResponsePdu ( false , false , stageNumber , stageNumber , session . getInitiatorSessionID ( ) , session . getTargetSessionIdentifyingHandle ( ) , initiatorTaskTag , errorStatus , ByteBuffer . allocate ( 0 ) ) ; connection . sendPdu ( rejectPDU ) ; }
|
Sends a Login Response PDU informing the initiator that an error has occurred and that the connection must be closed .
|
2,478
|
public final String get ( final OperationalTextKey textKey ) { if ( textKey == null ) { throw new NullPointerException ( ) ; } return settingsMap . get ( textKey ) ; }
|
Returns the value of the given parameter which is not parsed .
|
2,479
|
public final ByteBuffer asByteBuffer ( ) { final StringBuilder sb = new StringBuilder ( ) ; for ( Map . Entry < OperationalTextKey , String > e : settingsMap . entrySet ( ) ) { sb . append ( e . getKey ( ) . value ( ) ) ; sb . append ( KEY_VALUE_DELIMITER ) ; sb . append ( e . getValue ( ) ) ; sb . append ( PAIR_DELIMITER ) ; } return ByteBuffer . wrap ( sb . toString ( ) . getBytes ( ) ) ; }
|
Returns a buffer of the serialized key - value pairs which are contained in this instance .
|
2,480
|
public void initialize ( ) throws IOException , NotInitializedException { logger . debug ( "Initialising TCPTransportClient. Origin address is [{}] and destination address is [{}]" , origAddress , destAddress ) ; if ( destAddress == null ) { throw new NotInitializedException ( "Destination address is not set" ) ; } socketChannel = SelectorProvider . provider ( ) . openSocketChannel ( ) ; try { if ( origAddress != null ) { socketChannel . socket ( ) . bind ( origAddress ) ; } socketChannel . connect ( destAddress ) ; socketChannel . configureBlocking ( BLOCKING_IO ) ; getParent ( ) . onConnected ( ) ; } catch ( IOException e ) { if ( origAddress != null ) { socketChannel . socket ( ) . close ( ) ; } socketChannel . close ( ) ; throw e ; } }
|
Network init socket
|
2,481
|
public void run ( ) { int sleepTime = 250 ; logger . debug ( "Sleeping for {}ms before starting transport so that listeners can all be added and ready for messages" , sleepTime ) ; try { Thread . sleep ( sleepTime ) ; } catch ( InterruptedException e ) { } logger . debug ( "Finished sleeping for {}ms. By now, MutablePeerTableImpl should have added its listener" , sleepTime ) ; logger . debug ( "Transport is started. Socket is [{}]" , socketDescription ) ; Selector selector = null ; try { selector = Selector . open ( ) ; socketChannel . register ( selector , SelectionKey . OP_READ ) ; while ( ! stop ) { selector . select ( SELECT_TIMEOUT ) ; Iterator < SelectionKey > it = selector . selectedKeys ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { SelectionKey selKey = it . next ( ) ; it . remove ( ) ; if ( selKey . isValid ( ) && selKey . isReadable ( ) ) { SocketChannel sChannel = ( SocketChannel ) selKey . channel ( ) ; int dataLength = sChannel . read ( buffer ) ; logger . debug ( "Just read [{}] bytes on [{}]" , dataLength , socketDescription ) ; if ( dataLength == - 1 ) { stop = true ; break ; } buffer . flip ( ) ; byte [ ] data = new byte [ buffer . limit ( ) ] ; buffer . get ( data ) ; append ( data ) ; buffer . clear ( ) ; } } } } catch ( ClosedByInterruptException e ) { logger . error ( "Transport exception " , e ) ; } catch ( AsynchronousCloseException e ) { logger . error ( "Transport is closed" ) ; } catch ( Throwable e ) { logger . error ( "Transport exception " , e ) ; } finally { try { clearBuffer ( ) ; if ( selector != null ) { selector . close ( ) ; } if ( socketChannel != null && socketChannel . isOpen ( ) ) { socketChannel . close ( ) ; } getParent ( ) . onDisconnect ( ) ; } catch ( Exception e ) { logger . error ( "Error" , e ) ; } stop = false ; logger . info ( "Read thread is stopped for socket [{}]" , socketDescription ) ; } }
|
PCB added logging
|
2,482
|
private void append ( byte [ ] data ) { if ( storage . position ( ) + data . length >= storage . capacity ( ) ) { ByteBuffer tmp = ByteBuffer . allocate ( storage . limit ( ) + data . length * 2 ) ; byte [ ] tmpData = new byte [ storage . position ( ) ] ; storage . flip ( ) ; storage . get ( tmpData ) ; tmp . put ( tmpData ) ; storage = tmp ; logger . warn ( "Increase storage size. Current size is {}" , storage . array ( ) . length ) ; } try { storage . put ( data ) ; } catch ( BufferOverflowException boe ) { logger . error ( "Buffer overflow occured" , boe ) ; } boolean messageReceived ; do { messageReceived = seekMessage ( ) ; } while ( messageReceived ) ; }
|
Adds data to storage
|
2,483
|
private String makeRoutingKey ( Message message ) { String sessionId = message . getSessionId ( ) ; return new StringBuilder ( sessionId != null ? sessionId : "null" ) . append ( message . getEndToEndIdentifier ( ) ) . append ( message . getHopByHopIdentifier ( ) ) . toString ( ) ; }
|
PCB - Made better routing algorithm that should not grow all the time
|
2,484
|
public void appendElements ( ExtensionPoint ... elements ) { List < ExtensionPoint > rc = new ArrayList < ExtensionPoint > ( ) ; rc . addAll ( Arrays . asList ( this . elements ) ) ; rc . addAll ( Arrays . asList ( elements ) ) ; this . elements = rc . toArray ( new ExtensionPoint [ 0 ] ) ; }
|
Append extension point entries
|
2,485
|
protected long getNumConnections ( IPeer peer ) { if ( peer == null ) { return 0 ; } IStatistic stats = peer . getStatistic ( ) ; if ( ! stats . isEnabled ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Statistics for peer are disabled. Please enable statistics in client config" ) ; } return 0 ; } String uri = peer . getUri ( ) == null ? "local" : peer . getUri ( ) . toString ( ) ; long requests = getRecord ( IStatisticRecord . Counters . AppGenRequestPerSecond . name ( ) + '.' + uri , stats ) + getRecord ( IStatisticRecord . Counters . NetGenRequestPerSecond . name ( ) + '.' + uri , stats ) ; long connections = Math . max ( 0 , requests ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Active connections for {}: {}" , peer , connections ) ; } return connections ; }
|
Since num connections is not available determine throughput by reading statistics and assume the load of the peer
|
2,486
|
private Configuration getConfigByName ( String name ) { if ( config != null ) { for ( Configuration c : config ) { if ( c != null && c . getStringValue ( Parameters . ConcurrentEntityName . ordinal ( ) , "" ) . equals ( name ) ) { return c ; } } } return null ; }
|
fetch configuration for executor
|
2,487
|
public long nextLong ( ) { Delta d = ranges . get ( ) ; if ( d . start <= d . stop ) { mutex . lock ( ) ; value = d . update ( value ) ; mutex . unlock ( ) ; } return d . start ++ ; }
|
Return next uid as long
|
2,488
|
public static InetAddress InetAddressByIPv4 ( String address ) { StringTokenizer addressTokens = new StringTokenizer ( address , "." ) ; byte [ ] bytes ; if ( addressTokens . countTokens ( ) == 4 ) { bytes = new byte [ ] { getByBytes ( addressTokens ) , getByBytes ( addressTokens ) , getByBytes ( addressTokens ) , getByBytes ( addressTokens ) } ; } else { return null ; } try { return InetAddress . getByAddress ( bytes ) ; } catch ( UnknownHostException e ) { return null ; } }
|
Convert defined string to IPv4 object instance
|
2,489
|
public static InetAddress InetAddressByIPv6 ( String address ) { StringTokenizer addressTokens = new StringTokenizer ( address , ":" ) ; byte [ ] bytes = new byte [ 16 ] ; if ( addressTokens . countTokens ( ) == 8 ) { int count = 0 ; while ( addressTokens . hasMoreTokens ( ) ) { int word = Integer . parseInt ( addressTokens . nextToken ( ) , 16 ) ; bytes [ count * 2 ] = ( byte ) ( ( word >> 8 ) & 0xff ) ; bytes [ count * 2 + 1 ] = ( byte ) ( word & 0xff ) ; count ++ ; } } else { return null ; } try { return InetAddress . getByAddress ( bytes ) ; } catch ( UnknownHostException e ) { return null ; } }
|
Convert defined string to IPv6 object instance
|
2,490
|
private void initStack ( ) { if ( log . isInfoEnabled ( ) ) { log . info ( "Initializing Stack..." ) ; } InputStream is = null ; try { dictionary . parseDictionary ( this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( dictionaryFile ) ) ; log . info ( "AVP Dictionary successfully parsed." ) ; this . stack = new StackImpl ( ) ; is = this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( configFile ) ; Configuration config = new XMLConfiguration ( is ) ; factory = stack . init ( config ) ; if ( log . isInfoEnabled ( ) ) { log . info ( "Stack Configuration successfully loaded." ) ; } Set < org . jdiameter . api . ApplicationId > appIds = stack . getMetaData ( ) . getLocalPeer ( ) . getCommonApplications ( ) ; log . info ( "Diameter Stack :: Supporting " + appIds . size ( ) + " applications." ) ; for ( org . jdiameter . api . ApplicationId x : appIds ) { log . info ( "Diameter Stack :: Common :: " + x ) ; } is . close ( ) ; Network network = stack . unwrap ( Network . class ) ; network . addNetworkReqListener ( new NetworkReqListener ( ) { public Answer processRequest ( Request request ) { return null ; } } , this . authAppId ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; if ( this . stack != null ) { this . stack . destroy ( ) ; } if ( is != null ) { try { is . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } return ; } MetaData metaData = stack . getMetaData ( ) ; if ( metaData . getStackType ( ) != StackType . TYPE_SERVER || metaData . getMinorVersion ( ) <= 0 ) { stack . destroy ( ) ; if ( log . isEnabledFor ( org . apache . log4j . Level . ERROR ) ) { log . error ( "Incorrect driver" ) ; } return ; } try { if ( log . isInfoEnabled ( ) ) { log . info ( "Starting stack" ) ; } stack . start ( ) ; if ( log . isInfoEnabled ( ) ) { log . info ( "Stack is running." ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; stack . destroy ( ) ; return ; } if ( log . isInfoEnabled ( ) ) { log . info ( "Stack initialization successfully completed." ) ; } }
|
boolean telling if we finished our interaction
|
2,491
|
private void printAvpsAux ( AvpSet avpSet , int level ) throws AvpDataException { String prefix = " " . substring ( 0 , level * 2 ) ; for ( Avp avp : avpSet ) { AvpRepresentation avpRep = AvpDictionary . INSTANCE . getAvp ( avp . getCode ( ) , avp . getVendorId ( ) ) ; if ( avpRep != null && avpRep . getType ( ) . equals ( "Grouped" ) ) { log . info ( prefix + "<avp name=\"" + avpRep . getName ( ) + "\" code=\"" + avp . getCode ( ) + "\" vendor=\"" + avp . getVendorId ( ) + "\">" ) ; printAvpsAux ( avp . getGrouped ( ) , level + 1 ) ; log . info ( prefix + "</avp>" ) ; } else if ( avpRep != null ) { String value = "" ; if ( avpRep . getType ( ) . equals ( "Integer32" ) ) value = String . valueOf ( avp . getInteger32 ( ) ) ; else if ( avpRep . getType ( ) . equals ( "Integer64" ) || avpRep . getType ( ) . equals ( "Unsigned64" ) ) value = String . valueOf ( avp . getInteger64 ( ) ) ; else if ( avpRep . getType ( ) . equals ( "Unsigned32" ) ) value = String . valueOf ( avp . getUnsigned32 ( ) ) ; else if ( avpRep . getType ( ) . equals ( "Float32" ) ) value = String . valueOf ( avp . getFloat32 ( ) ) ; else value = new String ( avp . getOctetString ( ) , StandardCharsets . UTF_8 ) ; log . info ( prefix + "<avp name=\"" + avpRep . getName ( ) + "\" code=\"" + avp . getCode ( ) + "\" vendor=\"" + avp . getVendorId ( ) + "\" value=\"" + value + "\" />" ) ; } } }
|
Prints the AVPs present in an AvpSet with a specified tab level
|
2,492
|
public void start ( ) throws InterruptedException { logger . debug ( "Staring client TLSTransportClient {} " , socketDescription ) ; if ( isConnected ( ) ) { logger . debug ( "Already connected TLSTransportClient {} " , socketDescription ) ; return ; } workerGroup = new NioEventLoopGroup ( ) ; Bootstrap bootstrap = new Bootstrap ( ) ; bootstrap . group ( workerGroup ) . channel ( NioSocketChannel . class ) . handler ( new ChannelInitializer < SocketChannel > ( ) { protected void initChannel ( SocketChannel channel ) throws Exception { ChannelPipeline pipeline = channel . pipeline ( ) ; pipeline . addLast ( "decoder" , new DiameterMessageDecoder ( parentConnection , parser ) ) ; pipeline . addLast ( "msgHandler" , new DiameterMessageHandler ( parentConnection , false ) ) ; pipeline . addLast ( "startTlsInitiator" , new StartTlsInitiator ( config , TLSTransportClient . this ) ) ; pipeline . addLast ( "encoder" , new DiameterMessageEncoder ( parser ) ) ; pipeline . addLast ( "inbandWriter" , new InbandSecurityHandler ( ) ) ; } } ) ; this . channel = bootstrap . remoteAddress ( destAddress ) . connect ( ) . sync ( ) . channel ( ) ; parentConnection . onConnected ( ) ; logger . debug ( "Started TLS Transport on Socket {}" , socketDescription ) ; }
|
only client side
|
2,493
|
public static synchronized Enumeration < Stack > getStacks ( ) { List < Stack > result = new CopyOnWriteArrayList < Stack > ( ) ; if ( ! initialized ) { initialize ( ) ; } ClassLoader callerCL = ClassLoader . getSystemClassLoader ( ) ; for ( StackInfo di : stacks ) { if ( getCallerClass ( callerCL , di . stackClassName ) != di . stackClass ) { println ( new StringBuilder ( ) . append ( " skipping: " ) . append ( di ) . toString ( ) ) ; continue ; } result . add ( di . stack ) ; } return Collections . enumeration ( result ) ; }
|
Retrieves an Enumeration with all of the currently loaded Diameter stacks to which the current caller has access .
|
2,494
|
public static void addOriginAvps ( Message m , MetaData md ) { AvpSet set = m . getAvps ( ) ; if ( set . getAvp ( Avp . ORIGIN_HOST ) == null ) { m . getAvps ( ) . addAvp ( Avp . ORIGIN_HOST , md . getLocalPeer ( ) . getUri ( ) . getFQDN ( ) , true , false , true ) ; } if ( set . getAvp ( Avp . ORIGIN_REALM ) == null ) { m . getAvps ( ) . addAvp ( Avp . ORIGIN_REALM , md . getLocalPeer ( ) . getRealmName ( ) , true , false , true ) ; } }
|
Used to set origin previously done in MessageParser .
|
2,495
|
public RiakObject setVTag ( String vtag ) { if ( vtag != null && vtag . isEmpty ( ) ) { throw new IllegalArgumentException ( "vtag can not be zero length" ) ; } this . vtag = vtag ; return this ; }
|
Set the version tag for this RiakObject
|
2,496
|
public boolean removeNode ( RiakNode node ) { stateCheck ( State . CREATED , State . RUNNING , State . QUEUING ) ; boolean removed = false ; try { nodeListLock . writeLock ( ) . lock ( ) ; removed = nodeList . remove ( node ) ; for ( NodeStateListener listener : stateListeners ) { node . removeStateListener ( listener ) ; } } finally { nodeListLock . writeLock ( ) . unlock ( ) ; } nodeManager . removeNode ( node ) ; return removed ; }
|
Removes the provided node from the cluster .
|
2,497
|
public List < RiakNode > getNodes ( ) { stateCheck ( State . CREATED , State . RUNNING , State . SHUTTING_DOWN , State . QUEUING ) ; try { nodeListLock . readLock ( ) . lock ( ) ; return new ArrayList < > ( nodeList ) ; } finally { nodeListLock . readLock ( ) . unlock ( ) ; } }
|
Returns a copy of the list of nodes in this cluster .
|
2,498
|
private boolean keepProperty ( BeanPropertyWriter beanPropertyWriter ) { if ( beanPropertyWriter . getAnnotation ( JsonProperty . class ) != null ) { return true ; } for ( Class < ? extends Annotation > annotation : RIAK_ANNOTATIONS ) { if ( beanPropertyWriter . getAnnotation ( annotation ) != null ) { return false ; } } return true ; }
|
Checks if the property has any of the Riak annotations on it or the Jackson JsonProperty annotation .
|
2,499
|
public static RiakClient newClient ( InetSocketAddress ... addresses ) throws UnknownHostException { final List < String > remoteAddresses = new ArrayList < > ( addresses . length ) ; for ( InetSocketAddress addy : addresses ) { remoteAddresses . add ( String . format ( "%s:%s" , addy . getHostName ( ) , addy . getPort ( ) ) ) ; } return newClient ( createDefaultNodeBuilder ( ) , remoteAddresses ) ; }
|
Static factory method to create a new client instance . This method produces a client connected to the supplied addresses .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.