idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
39,200
public static String objectToString ( Object value ) { if ( value == null ) { return null ; } if ( value instanceof String ) { return ( String ) value ; } if ( value instanceof String [ ] ) { return StringUtils . join ( encodeString ( ( String [ ] ) value ) , ARRAY_DELIMITER ) ; } else if ( value instanceof Integer ) { return Integer . toString ( ( Integer ) value ) ; } else if ( value instanceof Long ) { return Long . toString ( ( Long ) value ) ; } else if ( value instanceof Double ) { return Double . toString ( ( Double ) value ) ; } else if ( value instanceof Boolean ) { return Boolean . toString ( ( Boolean ) value ) ; } else if ( value instanceof Map ) { Map < ? , ? > map = ( Map < ? , ? > ) value ; StringBuilder stringValue = new StringBuilder ( ) ; Map . Entry < ? , ? > [ ] entries = Iterators . toArray ( map . entrySet ( ) . iterator ( ) , Map . Entry . class ) ; for ( int i = 0 ; i < entries . length ; i ++ ) { Map . Entry < ? , ? > entry = entries [ i ] ; String entryKey = encodeString ( Objects . toString ( entry . getKey ( ) , "" ) ) ; String entryValue = encodeString ( Objects . toString ( entry . getValue ( ) , "" ) ) ; stringValue . append ( entryKey ) . append ( KEY_VALUE_DELIMITER ) . append ( entryValue ) ; if ( i < entries . length - 1 ) { stringValue . append ( ARRAY_DELIMITER ) ; } } return stringValue . toString ( ) ; } throw new IllegalArgumentException ( "Unsupported type: " + value . getClass ( ) . getName ( ) ) ; }
Converts a typed value to it s string representation .
39,201
public ParameterBuilder < T > defaultOsgiConfigProperty ( String value ) { if ( value == null || ! OSGI_CONFIG_PROPERTY_PATTERN . matcher ( value ) . matches ( ) ) { throw new IllegalArgumentException ( "Invalid value: " + value ) ; } this . defaultOsgiConfigProperty = value ; return this ; }
References OSGi configuration property which is checked for default value if this parameter is not set in any configuration .
39,202
public ParameterBuilder < T > properties ( Map < String , Object > map ) { if ( map == null ) { throw new IllegalArgumentException ( "Map argument must not be null." ) ; } this . properties . putAll ( map ) ; return this ; }
Further properties for documentation and configuration of behavior in configuration editor .
39,203
public ParameterBuilder < T > property ( String key , Object value ) { if ( key == null ) { throw new IllegalArgumentException ( "Key argument must not be null." ) ; } this . properties . put ( key , value ) ; return this ; }
Further property for documentation and configuration of behavior in configuration editor .
39,204
@ SuppressWarnings ( "unchecked" ) public synchronized < T > Evaluator < T > createEvaluator ( String source , ClassType projection , String [ ] names , Type [ ] types , Class < ? > [ ] classes , Map < String , Object > constants ) { try { final String id = toId ( source , projection . getJavaClass ( ) , types , constants . values ( ) ) ; Method method = cache . get ( id ) ; if ( method == null ) { Class < ? > clazz ; try { clazz = loader . loadClass ( id ) ; } catch ( ClassNotFoundException e ) { compile ( source , projection , names , types , id , constants ) ; clazz = loader . loadClass ( id ) ; } method = findEvalMethod ( clazz ) ; cache . put ( id , method ) ; } return new MethodEvaluator < T > ( method , constants , ( Class ) projection . getJavaClass ( ) ) ; } catch ( ClassNotFoundException e ) { throw new CodegenException ( e ) ; } catch ( SecurityException e ) { throw new CodegenException ( e ) ; } catch ( IOException e ) { throw new CodegenException ( e ) ; } }
Create a new Evaluator instance
39,205
public void cleanQueueJob ( ) { try { Set < Long > ids = queueCleanerService . getFinishedExecStateIds ( ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "Will clean from queue the next Exec state ids amount:" + ids . size ( ) ) ; Set < Long > execIds = new HashSet < > ( ) ; for ( Long id : ids ) { execIds . add ( id ) ; if ( execIds . size ( ) >= QUEUE_BULK_SIZE ) { queueCleanerService . cleanFinishedSteps ( execIds ) ; execIds . clear ( ) ; } } if ( execIds . size ( ) > 0 ) { queueCleanerService . cleanFinishedSteps ( execIds ) ; } } catch ( Exception e ) { logger . error ( "Can't run queue cleaner job." , e ) ; } }
Job that will handle the cleaning of queue table .
39,206
public void joinFinishedSplitsJob ( ) { try { if ( logger . isDebugEnabled ( ) ) logger . debug ( "SplitJoinJob woke up at " + new Date ( ) ) ; StopWatch stopWatch = new StopWatch ( ) ; stopWatch . start ( ) ; boolean moreToJoin = true ; for ( int i = 0 ; i < SPLIT_JOIN_ITERATIONS && moreToJoin ; i ++ ) { int joinedSplits = splitJoinService . joinFinishedSplits ( SPLIT_JOIN_BULK_SIZE ) ; moreToJoin = ( joinedSplits == SPLIT_JOIN_BULK_SIZE ) ; } stopWatch . stop ( ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "finished SplitJoinJob in " + stopWatch ) ; } catch ( Exception ex ) { logger . error ( "SplitJoinJob failed" , ex ) ; } }
Job that will handle the joining of finished branches .
39,207
public void executionRecoveryJob ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "ExecutionRecoveryJob woke up at " + new Date ( ) ) ; } try { executionRecoveryService . doRecovery ( ) ; } catch ( Exception e ) { logger . error ( "Can't run queue recovery job." , e ) ; } }
Job to execute the recovery check .
39,208
private void cancelPausedRun ( ExecutionState executionStateToCancel ) { final List < ExecutionState > branches = executionStateService . readByExecutionId ( executionStateToCancel . getExecutionId ( ) ) ; if ( branches . size ( ) > 1 ) { for ( ExecutionState branch : branches ) { if ( ! EMPTY_BRANCH . equals ( branch . getBranchId ( ) ) ) { returnCanceledRunToQueue ( branch ) ; executionStateService . deleteExecutionState ( branch . getExecutionId ( ) , branch . getBranchId ( ) ) ; } } executionStateToCancel . setStatus ( ExecutionStatus . PENDING_CANCEL ) ; } else { returnCanceledRunToQueue ( executionStateToCancel ) ; } }
If it doesn t - just cancel it straight away - extract the Run Object set its context accordingly and put into the queue .
39,209
private boolean isBranch ( Execution execution ) { return execution != null && ! StringUtils . isEmpty ( execution . getSystemContext ( ) . getBranchId ( ) ) ; }
Returns true when the execution is a branch with the new branch mechanism It will return true for executions of parallel multi - instance sub - flows and non blocking
39,210
public void doRecovery ( ) { try { synchronized ( this ) { executorService . shutdownNow ( ) ; threadPoolVersion ++ ; logger . warn ( "Worker is in doRecovery(). Cleaning state and cancelling running tasks. It may take up to 30 seconds..." ) ; } boolean finished = executorService . awaitTermination ( 30 , TimeUnit . SECONDS ) ; if ( finished ) { logger . warn ( "Worker succeeded to cancel running tasks during doRecovery()." ) ; } else { logger . warn ( "Not all running tasks responded to cancel." ) ; } } catch ( InterruptedException ex ) { } mapOfRunningTasks . clear ( ) ; executorService = new ThreadPoolExecutor ( numberOfThreads , numberOfThreads , Long . MAX_VALUE , TimeUnit . NANOSECONDS , inBuffer , new WorkerThreadFactory ( ( threadPoolVersion ) + "_WorkerExecutionThread" ) ) ; }
Must clean the buffer that holds Runnables that wait for execution and also drop all the executions that currently run
39,211
public PythonExecutionResult exec ( String script , Map < String , Serializable > callArguments ) { checkValidInterpreter ( ) ; initInterpreter ( ) ; prepareInterpreterContext ( callArguments ) ; Exception originException = null ; for ( int i = 0 ; i < RETRIES_NUMBER_ON_THREADED_ISSUE ; i ++ ) { try { return exec ( script ) ; } catch ( Exception e ) { if ( ! isThreadsRelatedModuleIssue ( e ) ) { throw new RuntimeException ( "Error executing python script: " + e , e ) ; } if ( originException == null ) { originException = e ; } } } throw new RuntimeException ( "Error executing python script: " + originException , originException ) ; }
we need this method to be synchronized so we will not have multiple scripts run in parallel on the same context
39,212
public String escapeLikeExpression ( String likeExpression ) { String normalizeLikeExpression = likeExpression ; if ( likeExpression != null && ! likeExpression . isEmpty ( ) ) { normalizeLikeExpression = normalizeLikeExpression . replace ( ESCAPE_CHAR , DOUBLE_ESCAPE_CHAR ) ; for ( String charToEscape : currentSpecialCharsSet ) { normalizeLikeExpression = normalizeLikeExpression . replace ( charToEscape , ESCAPE_CHAR + charToEscape ) ; } } return normalizeLikeExpression ; }
Escaping like expressions so wildcards will not be evaluated . The HQL query should have the ESCAPE_EXPRESSION in it s suffix for this to work!!!
39,213
public Pair < Integer , Integer > getMinSizeAndSizeOfInBuffer ( int executionThreadsCount ) { int defaultMinInBufferSize = Math . max ( 1 , executionThreadsCount / 5 ) ; int minInBufferSizeLocal = getInteger ( WORKER_INBUFFER_MIN_SIZE , defaultMinInBufferSize ) ; int minInBufferSize = ( minInBufferSizeLocal > 0 ) ? minInBufferSizeLocal : defaultMinInBufferSize ; int defaultNewInBufferSize = ( executionThreadsCount == 1 ) ? 2 : ( ( 3 * executionThreadsCount ) / 2 ) ; int newInBufferSizeLocal = getInteger ( WORKER_INBUFFER_SIZE , defaultNewInBufferSize ) ; int newInBufferSize = ( newInBufferSizeLocal > minInBufferSize ) ? newInBufferSizeLocal : defaultNewInBufferSize ; if ( newInBufferSize <= minInBufferSize ) { throw new IllegalStateException ( format ( "Value of property \"%s\" must be greater than the value of property \"%s\"." , WORKER_INBUFFER_SIZE , WORKER_INBUFFER_MIN_SIZE ) ) ; } return new ImmutablePair < > ( minInBufferSize , newInBufferSize ) ; }
10 percent of Xmx
39,214
private boolean isExecutionPaused ( Execution nextStepExecution ) { if ( nextStepExecution == null ) { executionMessage . setStatus ( ExecStatus . FINISHED ) ; executionMessage . incMsgSeqId ( ) ; executionMessage . setPayload ( null ) ; try { outBuffer . put ( executionMessage ) ; } catch ( InterruptedException e ) { logger . warn ( "Thread was interrupted! Exiting the execution... " , e ) ; } return true ; } else { return false ; } }
If execution was paused it sends the current step with status FINISHED and that is all ...
39,215
private ExecutionMessage createTerminatedExecutionMessage ( Execution nextStepExecution ) { Payload payload = converter . createPayload ( nextStepExecution ) ; ExecutionMessage finalMessage = ( ExecutionMessage ) executionMessage . clone ( ) ; finalMessage . setStatus ( ExecStatus . TERMINATED ) ; finalMessage . incMsgSeqId ( ) ; finalMessage . setPayload ( payload ) ; return finalMessage ; }
Creates termination execution message base on current execution message
39,216
private ExecutionMessage createPendingExecutionMessage ( Execution nextStepExecution ) { String groupName = nextStepExecution . getGroupName ( ) ; if ( groupName == null ) { groupName = WorkerNode . DEFAULT_WORKER_GROUPS [ 0 ] ; } return new ExecutionMessage ( ExecutionMessage . EMPTY_EXEC_STATE_ID , ExecutionMessage . EMPTY_WORKER , groupName , executionMessage . getMsgId ( ) , ExecStatus . PENDING , converter . createPayload ( nextStepExecution ) , 0 ) . setWorkerKey ( executionMessage . getWorkerKey ( ) ) ; }
Creates pending execution message for the next step base on current execution message
39,217
private ExecutionMessage createInProgressExecutionMessage ( Execution nextStepExecution ) { String groupName = nextStepExecution . getGroupName ( ) ; if ( groupName == null ) { groupName = WorkerNode . DEFAULT_WORKER_GROUPS [ 0 ] ; } Long id = queueStateIdGeneratorService . generateStateId ( ) ; return new ExecutionMessage ( id , executionMessage . getWorkerId ( ) , groupName , executionMessage . getMsgId ( ) , ExecStatus . IN_PROGRESS , nextStepExecution , converter . createPayload ( nextStepExecution ) , 0 ) . setWorkerKey ( executionMessage . getWorkerKey ( ) ) ; }
Creates InProgress execution message for the next step base on current execution message - used for short cut!
39,218
public void setFinishedChildBranchesData ( ArrayList < EndBranchDataContainer > data ) { Validate . isTrue ( ! contextMap . containsKey ( ExecutionParametersConsts . FINISHED_CHILD_BRANCHES_DATA ) , "not allowed to overwrite finished branches data" ) ; contextMap . put ( ExecutionParametersConsts . FINISHED_CHILD_BRANCHES_DATA , data ) ; }
setter for the finished child brunches data
39,219
public void setBranchId ( String brunchId ) { Validate . isTrue ( StringUtils . isEmpty ( getBranchId ( ) ) , "not allowed to overwrite branch id" ) ; contextMap . put ( BRANCH_ID , brunchId ) ; }
setter for the brunch id of the current Execution
39,220
public void setSplitId ( String splitId ) { Validate . isTrue ( StringUtils . isEmpty ( getSplitId ( ) ) , "not allowed to overwrite split id" ) ; contextMap . put ( NEW_SPLIT_ID , splitId ) ; }
set teh split id
39,221
public void addEvent ( String eventType , Serializable eventData ) { @ SuppressWarnings ( "unchecked" ) Queue < ScoreEvent > eventsQueue = getFromMap ( SCORE_EVENTS_QUEUE ) ; if ( eventsQueue == null ) { eventsQueue = new ArrayDeque < > ( ) ; contextMap . put ( SCORE_EVENTS_QUEUE , ( ArrayDeque ) eventsQueue ) ; } eventsQueue . add ( new ScoreEvent ( eventType , getLanguageName ( ) , eventData , getMetaData ( ) ) ) ; }
add event - for score to fire
39,222
public void addBranch ( Long startPosition , String flowUuid , Map < String , Serializable > context ) { Map < String , Long > runningPlansIds = getFromMap ( RUNNING_PLANS_MAP ) ; Long runningPlanId = runningPlansIds . get ( flowUuid ) ; addBranch ( startPosition , runningPlanId , context , new ExecutionRuntimeServices ( this ) ) ; }
add brunch - means you want to split your execution
39,223
protected boolean handlePausedFlow ( Execution execution ) throws InterruptedException { String branchId = execution . getSystemContext ( ) . getBranchId ( ) ; PauseReason reason = findPauseReason ( execution . getExecutionId ( ) , branchId ) ; if ( reason != null ) { pauseFlow ( reason , execution ) ; return true ; } return false ; }
check if the execution should be Paused and pause it if needed
39,224
private boolean handlePausedFlowAfterStep ( Execution execution ) throws InterruptedException { String branchId = execution . getSystemContext ( ) . getBranchId ( ) ; PauseReason reason = null ; ExecutionSummary execSummary = pauseService . readPausedExecution ( execution . getExecutionId ( ) , branchId ) ; if ( execSummary != null && execSummary . getStatus ( ) . equals ( ExecutionStatus . PENDING_PAUSE ) ) { reason = execSummary . getPauseReason ( ) ; } if ( reason != null ) { pauseFlow ( reason , execution ) ; return true ; } return false ; }
no need to check if paused - because this is called after the step when the Pause flag exists in the context
39,225
private Set < String > extractAndRemoveUpToLimit ( Set < String > source , int limit ) { Set < String > result = new HashSet < > ( ) ; Iterator < String > iterator = source . iterator ( ) ; while ( iterator . hasNext ( ) && result . size ( ) < limit ) { result . add ( iterator . next ( ) ) ; iterator . remove ( ) ; } return result ; }
Extracts items from source in the ammount set in limit and also removes them from source
39,226
public static String getTypeName ( Class < ? extends Tag < ? > > clazz ) { return TagType . getByTagClass ( clazz ) . getTypeName ( ) ; }
Gets the type name of a tag .
39,227
public void writeTag ( Tag < ? > tag ) throws IOException { String name = tag . getName ( ) ; byte [ ] nameBytes = name . getBytes ( NBTConstants . CHARSET . name ( ) ) ; os . writeByte ( tag . getType ( ) . getId ( ) ) ; os . writeShort ( nameBytes . length ) ; os . write ( nameBytes ) ; if ( tag . getType ( ) == TagType . TAG_END ) { throw new IOException ( "Named TAG_End not permitted." ) ; } writeTagPayload ( tag ) ; }
Writes a tag .
39,228
private void writeTagPayload ( Tag < ? > tag ) throws IOException { switch ( tag . getType ( ) ) { case TAG_END : writeEndTagPayload ( ( EndTag ) tag ) ; break ; case TAG_BYTE : writeByteTagPayload ( ( ByteTag ) tag ) ; break ; case TAG_SHORT : writeShortTagPayload ( ( ShortTag ) tag ) ; break ; case TAG_INT : writeIntTagPayload ( ( IntTag ) tag ) ; break ; case TAG_LONG : writeLongTagPayload ( ( LongTag ) tag ) ; break ; case TAG_FLOAT : writeFloatTagPayload ( ( FloatTag ) tag ) ; break ; case TAG_DOUBLE : writeDoubleTagPayload ( ( DoubleTag ) tag ) ; break ; case TAG_BYTE_ARRAY : writeByteArrayTagPayload ( ( ByteArrayTag ) tag ) ; break ; case TAG_STRING : writeStringTagPayload ( ( StringTag ) tag ) ; break ; case TAG_LIST : writeListTagPayload ( ( ListTag < ? > ) tag ) ; break ; case TAG_COMPOUND : writeCompoundTagPayload ( ( CompoundTag ) tag ) ; break ; case TAG_INT_ARRAY : writeIntArrayTagPayload ( ( IntArrayTag ) tag ) ; break ; case TAG_SHORT_ARRAY : writeShortArrayTagPayload ( ( ShortArrayTag ) tag ) ; break ; default : throw new IOException ( "Invalid tag type: " + tag . getType ( ) + "." ) ; } }
Writes tag payload .
39,229
public T load ( CompoundTag tag ) { Tag subTag = tag . getValue ( ) . get ( key ) ; if ( subTag == null ) { return ( value = defaultValue ) ; } return ( value = field . getValue ( subTag ) ) ; }
Get this field from a CompoundTag
39,230
public static < T > FieldValue < T > from ( String name , Field < T > field , T defaultValue ) { return new FieldValue < T > ( name , field , defaultValue ) ; }
So generic info doesn t have to be duplicated
39,231
public static < T > T getTagValue ( Tag < ? > t , Class < ? extends T > clazz ) { Object o = toTagValue ( t ) ; if ( o == null ) { return null ; } try { return clazz . cast ( o ) ; } catch ( ClassCastException e ) { return null ; } }
Takes in an NBT tag sanely checks null status and then returns it value . This method will return null if the value cannot be cast to the given class .
39,232
public static < T , U extends T > T toTagValue ( Tag < ? > t , Class < ? extends T > clazz , U defaultValue ) { Object o = toTagValue ( t ) ; if ( o == null ) { return defaultValue ; } try { T value = clazz . cast ( o ) ; return value ; } catch ( ClassCastException e ) { return defaultValue ; } }
Takes in an NBT tag sanely checks null status and then returns it value . This method will return null if the value cannot be cast to the default value .
39,233
public static < T extends Tag < ? > > T checkTagCast ( Tag < ? > tag , Class < T > type ) throws IllegalArgumentException { if ( tag == null ) { throw new IllegalArgumentException ( "Expected tag of type " + type . getName ( ) + ", was null" ) ; } else if ( ! type . isInstance ( tag ) ) { throw new IllegalArgumentException ( "Expected tag to be a " + type . getName ( ) + ", was a " + tag . getClass ( ) . getName ( ) ) ; } return type . cast ( tag ) ; }
Checks that a tag is not null and of the required type
39,234
public X509Certificate [ ] getCertificates ( ) { if ( this . certSubjectDNMap == null ) { return null ; } Collection certs = this . certSubjectDNMap . values ( ) ; return ( X509Certificate [ ] ) certs . toArray ( new X509Certificate [ certs . size ( ) ] ) ; }
so moved some things over to there
39,235
public SigningPolicy [ ] getSigningPolicies ( ) { if ( this . policyDNMap == null ) { return null ; } Collection values = this . policyDNMap . values ( ) ; return ( SigningPolicy [ ] ) this . policyDNMap . values ( ) . toArray ( new SigningPolicy [ values . size ( ) ] ) ; }
Returns all signing policies
39,236
public SigningPolicy getSigningPolicy ( String subject ) { if ( this . policyDNMap == null ) { return null ; } return ( SigningPolicy ) this . policyDNMap . get ( subject ) ; }
Returns signing policy associated with the given CA subject .
39,237
private ByteBuffer sslDataWrap ( ByteBuffer inBBuff , ByteBuffer outBBuff ) throws GSSException { try { if ( sslEngine . getHandshakeStatus ( ) != SSLEngineResult . HandshakeStatus . NOT_HANDSHAKING ) { throw new Exception ( "SSLEngine handshaking needed! " + "HandshakeStatus: " + sslEngine . getHandshakeStatus ( ) . toString ( ) ) ; } int iter = 0 ; do { logger . debug ( "PROCESSING DATA (WRAP) " + ++ iter + ": " + inBBuff . remaining ( ) ) ; SSLEngineResult result = sslEngine . wrap ( inBBuff , outBBuff ) ; if ( result . getHandshakeStatus ( ) == SSLEngineResult . HandshakeStatus . NEED_TASK ) { runDelegatedTasks ( sslEngine ) ; continue ; } if ( result . getStatus ( ) == SSLEngineResult . Status . BUFFER_OVERFLOW ) { int pktSize = sslEngine . getSession ( ) . getPacketBufferSize ( ) ; ByteBuffer b = ByteBuffer . allocate ( pktSize + outBBuff . position ( ) ) ; outBBuff . flip ( ) ; b . put ( outBBuff ) ; outBBuff = b ; continue ; } else if ( result . getStatus ( ) == SSLEngineResult . Status . BUFFER_UNDERFLOW ) { throw new GlobusGSSException ( GSSException . FAILURE , new Exception ( "Unexpected BUFFER_UNDERFLOW;" + " Handshaking status: " + sslEngine . getHandshakeStatus ( ) ) ) ; } if ( result . getStatus ( ) != SSLEngineResult . Status . OK ) { throw new GlobusGSSException ( GSSException . FAILURE , GlobusGSSException . TOKEN_FAIL , result . getStatus ( ) . toString ( ) ) ; } } while ( inBBuff . hasRemaining ( ) ) ; return outBBuff ; } catch ( Exception e ) { throw new GlobusGSSException ( GSSException . FAILURE , e ) ; } }
Meant for non - handshake processing
39,238
private ByteBuffer sslDataUnwrap ( ByteBuffer inBBuff , ByteBuffer outBBuff ) throws GSSException { try { int iter = 0 ; if ( sslEngine . getHandshakeStatus ( ) != SSLEngineResult . HandshakeStatus . NOT_HANDSHAKING ) { throw new Exception ( "SSLEngine handshaking needed! " + "HandshakeStatus: " + sslEngine . getHandshakeStatus ( ) . toString ( ) ) ; } do { logger . debug ( "PROCESSING DATA (UNWRAP) " + ++ iter + ": " + inBBuff . remaining ( ) ) ; SSLEngineResult result = sslEngine . unwrap ( inBBuff , outBBuff ) ; if ( result . getHandshakeStatus ( ) == SSLEngineResult . HandshakeStatus . NEED_TASK ) { runDelegatedTasks ( sslEngine ) ; continue ; } if ( result . getStatus ( ) == SSLEngineResult . Status . BUFFER_OVERFLOW ) { int appSize = sslEngine . getSession ( ) . getApplicationBufferSize ( ) ; ByteBuffer b = ByteBuffer . allocate ( appSize + outBBuff . position ( ) ) ; outBBuff . flip ( ) ; b . put ( outBBuff ) ; outBBuff = b ; continue ; } else if ( result . getStatus ( ) == SSLEngineResult . Status . BUFFER_UNDERFLOW ) { break ; } else if ( result . getStatus ( ) == SSLEngineResult . Status . CLOSED ) { throw new ClosedGSSException ( ) ; } if ( result . getStatus ( ) != SSLEngineResult . Status . OK ) { throw new GlobusGSSException ( GSSException . FAILURE , GlobusGSSException . TOKEN_FAIL , result . getStatus ( ) . toString ( ) ) ; } } while ( inBBuff . hasRemaining ( ) ) ; return outBBuff ; } catch ( IllegalArgumentException e ) { throw new GlobusGSSException ( GSSException . DEFECTIVE_TOKEN , e ) ; } catch ( SSLException e ) { if ( e . toString ( ) . endsWith ( "bad record MAC" ) ) throw new GlobusGSSException ( GSSException . BAD_MIC , e ) ; else if ( e . toString ( ) . endsWith ( "ciphertext sanity check failed" ) ) throw new GlobusGSSException ( GSSException . DEFECTIVE_TOKEN , e ) ; else throw new GlobusGSSException ( GSSException . FAILURE , e ) ; } catch ( GSSException e ) { throw e ; } catch ( Exception e ) { throw new GlobusGSSException ( GSSException . FAILURE , e ) ; } }
Not all in inBBuff might be consumed by this method!!!
39,239
public byte [ ] wrap ( byte [ ] inBuf , int off , int len , MessageProp prop ) throws GSSException { checkContext ( ) ; logger . debug ( "enter wrap" ) ; byte [ ] token = null ; boolean doGSIWrap = false ; if ( prop != null ) { if ( prop . getQOP ( ) != 0 && prop . getQOP ( ) != GSSConstants . GSI_BIG ) { throw new GSSException ( GSSException . BAD_QOP ) ; } doGSIWrap = ( ! prop . getPrivacy ( ) && prop . getQOP ( ) == GSSConstants . GSI_BIG ) ; } if ( doGSIWrap ) { throw new GSSException ( GSSException . UNAVAILABLE ) ; } else { token = wrap ( inBuf , off , len ) ; if ( prop != null ) { prop . setPrivacy ( this . encryption ) ; prop . setQOP ( 0 ) ; } } logger . debug ( "exit wrap" ) ; return token ; }
Wraps a message for integrity and protection . A regular SSL - wrapped token is returned .
39,240
public byte [ ] initDelegation ( GSSCredential credential , Oid mechanism , int lifetime , byte [ ] buf , int off , int len ) throws GSSException { logger . debug ( "Enter initDelegation: " + delegationState ) ; if ( mechanism != null && ! mechanism . equals ( getMech ( ) ) ) { throw new GSSException ( GSSException . BAD_MECH ) ; } if ( this . gssMode != GSIConstants . MODE_SSL && buf != null && len > 0 ) { buf = unwrap ( buf , off , len ) ; off = 0 ; len = buf . length ; } byte [ ] token = null ; switch ( delegationState ) { case DELEGATION_START : this . delegationFinished = false ; token = DELEGATION_TOKEN ; this . delegationState = DELEGATION_SIGN_CERT ; break ; case DELEGATION_SIGN_CERT : if ( credential == null ) { GSSManager manager = new GlobusGSSManagerImpl ( ) ; credential = manager . createCredential ( GSSCredential . INITIATE_AND_ACCEPT ) ; } if ( ! ( credential instanceof GlobusGSSCredentialImpl ) ) { throw new GSSException ( GSSException . DEFECTIVE_CREDENTIAL ) ; } X509Credential cred = ( ( GlobusGSSCredentialImpl ) credential ) . getX509Credential ( ) ; X509Certificate [ ] chain = cred . getCertificateChain ( ) ; int time = ( lifetime == GSSCredential . DEFAULT_LIFETIME ) ? - 1 : lifetime ; ByteArrayInputStream inData = null ; ByteArrayOutputStream out = null ; try { inData = new ByteArrayInputStream ( buf , off , len ) ; X509Certificate cert = this . certFactory . createCertificate ( inData , chain [ 0 ] , cred . getPrivateKey ( ) , time , BouncyCastleCertProcessingFactory . decideProxyType ( chain [ 0 ] , this . delegationType ) ) ; out = new ByteArrayOutputStream ( ) ; out . write ( cert . getEncoded ( ) ) ; for ( int i = 0 ; i < chain . length ; i ++ ) { out . write ( chain [ i ] . getEncoded ( ) ) ; } token = out . toByteArray ( ) ; } catch ( Exception e ) { throw new GlobusGSSException ( GSSException . FAILURE , e ) ; } finally { if ( inData != null ) { try { inData . close ( ) ; } catch ( Exception e ) { logger . warn ( "Unable to close stream." ) ; } } if ( out != null ) { try { out . close ( ) ; } catch ( Exception e ) { logger . warn ( "Unable to close stream." ) ; } } } this . delegationState = DELEGATION_START ; this . delegationFinished = true ; break ; default : throw new GSSException ( GSSException . FAILURE ) ; } logger . debug ( "Exit initDelegation" ) ; if ( this . gssMode != GSIConstants . MODE_SSL && token != null ) { return wrap ( token , 0 , token . length ) ; } else { return token ; } }
Initiate the delegation of a credential .
39,241
public static void installSecureRandomProvider ( ) { CoGProperties props = CoGProperties . getDefault ( ) ; String providerName = props . getSecureRandomProvider ( ) ; try { Class providerClass = Class . forName ( providerName ) ; Security . insertProviderAt ( ( Provider ) providerClass . newInstance ( ) , 1 ) ; } catch ( Exception e ) { logger . debug ( "Unable to install PRNG. Using default PRNG." , e ) ; } }
Installs SecureRandom provider . This function is automatically called when this class is loaded .
39,242
public static int getCAPathConstraint ( TBSCertificateStructure crt ) throws IOException { X509Extensions extensions = crt . getExtensions ( ) ; if ( extensions == null ) { return - 1 ; } X509Extension proxyExtension = extensions . getExtension ( X509Extension . basicConstraints ) ; if ( proxyExtension != null ) { BasicConstraints basicExt = getBasicConstraints ( proxyExtension ) ; if ( basicExt . isCA ( ) ) { BigInteger pathLen = basicExt . getPathLenConstraint ( ) ; return ( pathLen == null ) ? Integer . MAX_VALUE : pathLen . intValue ( ) ; } else { return - 1 ; } } return - 1 ; }
Return CA Path constraint
39,243
public static KeyPair generateKeyPair ( String algorithm , int bits ) throws GeneralSecurityException { KeyPairGenerator generator = null ; if ( provider == null ) { generator = KeyPairGenerator . getInstance ( algorithm ) ; } else { generator = KeyPairGenerator . getInstance ( algorithm , provider ) ; } generator . initialize ( bits ) ; return generator . generateKeyPair ( ) ; }
Generates a key pair of given algorithm and strength .
39,244
public static TBSCertificateStructure getTBSCertificateStructure ( X509Certificate cert ) throws CertificateEncodingException , IOException { ASN1Primitive obj = toASN1Primitive ( cert . getTBSCertificate ( ) ) ; return TBSCertificateStructure . getInstance ( obj ) ; }
Extracts the TBS certificate from the given certificate .
39,245
public static CertPath getCertPath ( X509Certificate [ ] certs ) throws CertificateException { CertificateFactory factory = CertificateFactory . getInstance ( "X.509" ) ; return factory . generateCertPath ( Arrays . asList ( certs ) ) ; }
JGLOBUS - 91
39,246
protected X509Credential createObject ( GlobusResource certSource , GlobusResource keySource ) throws ResourceStoreException { InputStream certIns ; InputStream keyIns ; try { certIns = certSource . getInputStream ( ) ; keyIns = keySource . getInputStream ( ) ; return new X509Credential ( certIns , keyIns ) ; } catch ( FileNotFoundException e ) { throw new ResourceStoreException ( e ) ; } catch ( CredentialException e ) { throw new ResourceStoreException ( e ) ; } catch ( IOException ioe ) { throw new ResourceStoreException ( ioe ) ; } }
for creation of credential from a file
39,247
public HostPort setPassive ( int port , int queue ) throws IOException { if ( serverSocket == null ) { ServerSocketFactory factory = ServerSocketFactory . getDefault ( ) ; serverSocket = factory . createServerSocket ( port , queue ) ; } session . serverMode = Session . SERVER_PASSIVE ; String address = Util . getLocalHostAddress ( ) ; int localPort = serverSocket . getLocalPort ( ) ; if ( remoteControlChannel . isIPv6 ( ) ) { String version = HostPort6 . getIPAddressVersion ( address ) ; session . serverAddress = new HostPort6 ( version , address , localPort ) ; } else { session . serverAddress = new HostPort ( address , localPort ) ; } logger . debug ( "started passive server at port " + session . serverAddress . getPort ( ) ) ; return session . serverAddress ; }
Start the local server
39,248
public void setActive ( HostPort hp ) throws UnknownHostException , ClientException , IOException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "hostport: " + hp . getHost ( ) + " " + hp . getPort ( ) ) ; } session . serverMode = Session . SERVER_ACTIVE ; this . remoteServerAddress = hp ; }
Asynchronous ; return before completion . Connect to the remote server . Any exception that would occure will not be thrown but returned through the local control channel .
39,249
public static void exceptionToControlChannel ( Throwable e , String msg , BasicServerControlChannel control ) { java . io . StringWriter writer = new java . io . StringWriter ( ) ; e . printStackTrace ( new java . io . PrintWriter ( writer ) ) ; String stack = writer . toString ( ) ; LocalReply reply = new LocalReply ( 451 , msg + "\n" + e . toString ( ) + "\n" + stack ) ; control . write ( reply ) ; }
Convert the exception to a negative 451 reply and pipe it to the provided control channel .
39,250
public void store ( DataSink sink ) { try { localControlChannel . resetReplyCount ( ) ; TransferContext context = createTransferContext ( ) ; if ( session . serverMode == Session . SERVER_PASSIVE ) { runTask ( createPassiveConnectTask ( sink , context ) ) ; } else { runTask ( createActiveConnectTask ( sink , context ) ) ; } } catch ( Exception e ) { exceptionToControlChannel ( e , "ocurred during store()" ) ; } }
Asynchronous ; return before completion . Start the incoming transfer and store the file to the supplied data sink . Any exception that would occure will not be thrown but returned through the local control channel .
39,251
public void retrieve ( DataSource source ) { try { localControlChannel . resetReplyCount ( ) ; TransferContext context = createTransferContext ( ) ; if ( session . serverMode == Session . SERVER_PASSIVE ) { runTask ( createPassiveConnectTask ( source , context ) ) ; } else { runTask ( createActiveConnectTask ( source , context ) ) ; } } catch ( Exception e ) { exceptionToControlChannel ( e , "ocurred during retrieve()" ) ; } }
Asynchronous ; return before completion . Start the outgoing transfer reading the data from the supplied data source . Any exception that would occure will not be thrown but returned through the local control channel .
39,252
private synchronized void runTask ( Task task ) { if ( taskThread == null ) { taskThread = new TaskThread ( ) ; } taskThread . runTask ( task ) ; }
Use this as an interface to the local manager thread . This submits the task to the thread queue . The thread will perform it when it s ready with other waiting tasks .
39,253
private PassiveConnectTask createPassiveConnectTask ( DataSource source , TransferContext context ) { return new PassiveConnectTask ( serverSocket , source , localControlChannel , session , dataChannelFactory , context ) ; }
use these methods to create tasks
39,254
public void close ( ) throws IOException { try { this . context . dispose ( ) ; } catch ( GSSException e ) { throw new ChainedIOException ( "dispose failed." , e ) ; } finally { this . socket . close ( ) ; } }
Disposes of the context and closes the connection
39,255
public static byte [ ] readSslMessage ( InputStream in ) throws IOException { byte [ ] header = new byte [ 5 ] ; readFully ( in , header , 0 , header . length ) ; int length ; if ( isSSLv3Packet ( header ) ) length = toShort ( header [ 3 ] , header [ 4 ] ) ; else if ( isSSLv2HelloPacket ( header ) ) length = ( ( ( header [ 0 ] & 0x7f ) << 8 ) | ( header [ 1 ] & 0xff ) ) - 3 ; else { throw new IOException ( "Invalid SSL header" ) ; } byte [ ] inToken = new byte [ header . length + length ] ; System . arraycopy ( header , 0 , inToken , 0 , header . length ) ; readFully ( in , inToken , header . length , length ) ; return inToken ; }
Reads an entire SSL message from the specified input stream .
39,256
public static void writeInt ( int v , byte [ ] buf , int off ) { buf [ off ] = ( byte ) ( ( v >>> 24 ) & 0xFF ) ; buf [ off + 1 ] = ( byte ) ( ( v >>> 16 ) & 0xFF ) ; buf [ off + 2 ] = ( byte ) ( ( v >>> 8 ) & 0xFF ) ; buf [ off + 3 ] = ( byte ) ( ( v >>> 0 ) & 0xFF ) ; }
Converts the specified int value into 4 bytes . The bytes are put into the specified byte array at a given offset location .
39,257
public void shutdown ( ) { accept = false ; try { _server . close ( ) ; } catch ( Exception e ) { } SocketFactory factory = SocketFactory . getDefault ( ) ; Socket s = null ; try { s = factory . createSocket ( InetAddress . getLocalHost ( ) , getPort ( ) ) ; s . getInputStream ( ) ; } catch ( Exception e ) { } finally { if ( s != null ) { try { s . close ( ) ; } catch ( Exception e ) { } } } serverThread = null ; _server = null ; }
Stops the server but does not stop all the client threads
39,258
public Binding evaluate ( Map symbolTable ) throws RslEvaluationException { String strValue = _value . evaluate ( symbolTable ) ; return new Binding ( getName ( ) , new Value ( strValue ) ) ; }
Evaluates the variable definition with the specified symbol table .
39,259
public String toRSL ( boolean explicitConcat ) { StringBuffer buf = new StringBuffer ( ) ; toRSL ( buf , explicitConcat ) ; return buf . toString ( ) ; }
Returns a RSL representation of this variable definition .
39,260
public void toRSL ( StringBuffer buf , boolean explicitConcat ) { buf . append ( "(" ) ; buf . append ( getName ( ) ) ; buf . append ( " " ) ; getValue ( ) . toRSL ( buf , explicitConcat ) ; buf . append ( ")" ) ; }
Produces a RSL representation of this variable definition .
39,261
public static void setTimeout ( Stub stub , int timeout ) { if ( stub instanceof org . apache . axis . client . Stub ) { ( ( org . apache . axis . client . Stub ) stub ) . setTimeout ( timeout ) ; } }
Sets connection timeout .
39,262
public static void setHTTPVersion ( Stub stub , boolean http10 ) { stub . _setProperty ( MessageContext . HTTP_TRANSPORT_VERSION , ( http10 ) ? HTTPConstants . HEADER_PROTOCOL_V10 : HTTPConstants . HEADER_PROTOCOL_V11 ) ; }
Sets on option on the stub to control what HTTP protocol version should be used .
39,263
public GlobusResource getResource ( String location ) { GlobusResource returnResource ; URL resourceURL ; if ( location . startsWith ( "classpath:" ) ) { resourceURL = getClass ( ) . getClassLoader ( ) . getResource ( location . replaceFirst ( "classpath:/" , "" ) ) ; returnResource = new GlobusResource ( resourceURL . getPath ( ) ) ; } else if ( location . startsWith ( "file:" ) ) { returnResource = new GlobusResource ( location . replaceFirst ( "file:" , "" ) ) ; } else returnResource = new GlobusResource ( location ) ; return returnResource ; }
This method takes a location string and returns a GlobusResource of the corresponding location . This method does not accept any patterns for the location string .
39,264
public GlobusResource [ ] getResources ( String locationPattern ) { Vector < GlobusResource > pathsMatchingLocationPattern = new Vector < GlobusResource > ( ) ; String mainPath = "" ; if ( locationPattern . startsWith ( "classpath:" ) ) { String pathUntilWildcard = getPathUntilWildcard ( locationPattern . replaceFirst ( "classpath:/" , "" ) , false ) ; URL resourceURL = getClass ( ) . getClassLoader ( ) . getResource ( pathUntilWildcard ) ; this . mainClassPath = resourceURL . getPath ( ) ; this . locationPattern = Pattern . compile ( antToRegexConverter ( locationPattern . replaceFirst ( "classpath:/" , "" ) . replaceFirst ( pathUntilWildcard , "" ) ) ) ; parseDirectoryStructure ( new File ( this . mainClassPath ) , pathsMatchingLocationPattern ) ; } else if ( locationPattern . startsWith ( "file:" ) ) { if ( ( locationPattern . replaceFirst ( "file:" , "" ) . compareTo ( getPathUntilWildcard ( locationPattern . replaceFirst ( "file:" , "" ) , true ) ) ) == 0 ) { pathsMatchingLocationPattern . add ( new GlobusResource ( locationPattern . replaceFirst ( "file:" , "" ) ) ) ; } else { try { URL resourceURL = new File ( getPathUntilWildcard ( locationPattern . replaceFirst ( "file:" , "" ) , true ) ) . toURL ( ) ; mainPath = resourceURL . getPath ( ) ; this . locationPattern = Pattern . compile ( antToRegexConverter ( locationPattern . replaceFirst ( "file:" , "" ) ) ) ; parseDirectoryStructure ( new File ( mainPath ) , pathsMatchingLocationPattern ) ; } catch ( MalformedURLException ex ) { } } } else { mainPath = getPathUntilWildcard ( locationPattern , true ) ; this . locationPattern = Pattern . compile ( antToRegexConverter ( locationPattern ) ) ; parseDirectoryStructure ( new File ( mainPath ) , pathsMatchingLocationPattern ) ; } return pathsMatchingLocationPattern . toArray ( new GlobusResource [ 0 ] ) ; }
Finds all the resources that match the Ant - Style locationPattern
39,265
private void parseFilesInDirectory ( File currentDirectory , Vector < GlobusResource > pathsMatchingLocationPattern ) { File [ ] directoryContents = null ; if ( currentDirectory . isDirectory ( ) ) { directoryContents = currentDirectory . listFiles ( ) ; } else { directoryContents = new File [ 1 ] ; directoryContents [ 0 ] = currentDirectory ; } String absolutePath = null ; Matcher locationPatternMatcher = null ; if ( directoryContents != null ) { for ( File currentFile : directoryContents ) { if ( currentFile . isFile ( ) ) { absolutePath = currentFile . getAbsolutePath ( ) ; locationPatternMatcher = locationPattern . matcher ( absolutePath ) ; if ( locationPatternMatcher . find ( ) ) { pathsMatchingLocationPattern . add ( new GlobusResource ( absolutePath ) ) ; } } } } }
Compares every file s Absolute Path against the locationPattern if they match a GlobusResource is created with the file s Absolute Path and added to pathsMatchingLocationPattern .
39,266
private void closeOutgoingSockets ( ) throws ClientException { SocketOperator op = new SocketOperator ( ) { public void operate ( SocketBox sb ) throws Exception { if ( ( ( ManagedSocketBox ) sb ) . isReusable ( ) ) { Socket s = sb . getSocket ( ) ; if ( s != null ) { EBlockImageDCWriter . close ( new DataOutputStream ( s . getOutputStream ( ) ) ) ; } } } } ; try { socketPool . applyToAll ( op ) ; } catch ( IOException e ) { } catch ( Exception e ) { ClientException ce = new ClientException ( ClientException . SOCKET_OP_FAILED ) ; ce . setRootCause ( e ) ; throw ce ; } }
All sockets opened when this server was active should send a special EBlock header before closing .
39,267
public void store ( DataSink sink ) { try { localControlChannel . resetReplyCount ( ) ; if ( session . transferMode != GridFTPSession . MODE_EBLOCK ) { EBlockParallelTransferContext context = ( EBlockParallelTransferContext ) createTransferContext ( ) ; context . setEodsTotal ( 0 ) ; if ( session . serverMode == Session . SERVER_PASSIVE ) { transferThreadManager . passiveConnect ( sink , context , 1 , serverSocket ) ; } else { transferThreadManager . startTransfer ( sink , context , 1 , ManagedSocketBox . NON_REUSABLE ) ; } } else if ( session . serverMode != GridFTPSession . SERVER_EPAS && session . serverMode != GridFTPSession . SERVER_PASSIVE ) { exceptionToControlChannel ( new DataChannelException ( DataChannelException . BAD_SERVER_MODE ) , "refusing to store with active mode" ) ; } else { EBlockParallelTransferContext context = ( EBlockParallelTransferContext ) createTransferContext ( ) ; int willReuseConnections = socketPool . countFree ( ) ; int needNewConnections = 0 ; if ( gSession . parallel > willReuseConnections ) { needNewConnections = gSession . parallel - willReuseConnections ; } logger . debug ( "will reuse " + willReuseConnections + " connections and start " + needNewConnections + " new ones." ) ; transferThreadManager . startTransfer ( sink , context , willReuseConnections , ManagedSocketBox . REUSABLE ) ; if ( needNewConnections > 0 ) { transferThreadManager . passiveConnect ( sink , context , needNewConnections , serverSocket ) ; } } } catch ( Exception e ) { exceptionToControlChannel ( e , "ocurred during store()" ) ; } }
Store the data from the data channel to the data sink . Does not block . If operation fails exception might be thrown via local control channel .
39,268
public void retrieve ( DataSource source ) { try { localControlChannel . resetReplyCount ( ) ; if ( session . transferMode != GridFTPSession . MODE_EBLOCK ) { EBlockParallelTransferContext context = ( EBlockParallelTransferContext ) createTransferContext ( ) ; context . setEodsTotal ( 0 ) ; logger . debug ( "starting outgoing transfer without mode E" ) ; if ( session . serverMode == Session . SERVER_PASSIVE ) { transferThreadManager . passiveConnect ( source , context , serverSocket ) ; } else { transferThreadManager . startTransfer ( source , context , 1 , ManagedSocketBox . NON_REUSABLE ) ; } return ; } else if ( session . serverMode == Session . SERVER_ACTIVE ) { EBlockParallelTransferContext context = ( EBlockParallelTransferContext ) createTransferContext ( ) ; int total = gSession . parallel ; context . setEodsTotal ( total ) ; int free = socketPool . countFree ( ) ; int willReuseConnections = ( total > free ) ? free : total ; int willCloseConnections = ( free > total ) ? free - total : 0 ; int needNewConnections = ( total > free ) ? total - free : 0 ; logger . debug ( "will reuse " + willReuseConnections + " connections, start " + needNewConnections + " new ones, and close " + willCloseConnections ) ; if ( needNewConnections > 0 ) { transferThreadManager . activeConnect ( this . remoteServerAddress , needNewConnections ) ; } if ( willCloseConnections > 0 ) { transferThreadManager . activeClose ( context , willCloseConnections ) ; } transferThreadManager . startTransfer ( source , context , willReuseConnections + needNewConnections , ManagedSocketBox . REUSABLE ) ; } else if ( session . serverMode == GridFTPSession . SERVER_EACT ) { if ( stripeRetrContextManager == null ) { throw new IllegalStateException ( ) ; } int stripes = stripeRetrContextManager . getStripes ( ) ; for ( int stripe = 0 ; stripe < stripes ; stripe ++ ) { EBlockParallelTransferContext context = stripeRetrContextManager . getStripeContext ( stripe ) ; context . setEodsTotal ( gSession . parallel ) ; transferThreadManager . startTransfer ( source , context , gSession . parallel , ManagedSocketBox . REUSABLE ) ; } } else { throw new DataChannelException ( DataChannelException . BAD_SERVER_MODE ) ; } } catch ( Exception e ) { exceptionToControlChannel ( e , "ocurred during retrieve()" ) ; } }
Retrieve the data from the data source and write to the data channel . This method does not block . If operation fails exception might be thrown via local control channel .
39,269
public static Socket authenticate ( Socket simpleSocket , boolean isClientSocket , GSSCredential credential , int protection , DataChannelAuthentication dcau ) throws Exception { GSSContext gssContext = null ; GSSManager manager = ExtendedGSSManager . getInstance ( ) ; if ( isClientSocket ) { gssContext = manager . createContext ( null , GSSConstants . MECH_OID , credential , GSSContext . DEFAULT_LIFETIME ) ; } else { gssContext = manager . createContext ( credential ) ; } if ( protection != GridFTPSession . PROTECTION_CLEAR ) { ( ( ExtendedGSSContext ) gssContext ) . setOption ( GSSConstants . GSS_MODE , GSIConstants . MODE_SSL ) ; } gssContext . requestConf ( protection == GridFTPSession . PROTECTION_PRIVATE ) ; logger . debug ( "Creating secure socket" ) ; GssSocketFactory factory = GssSocketFactory . getDefault ( ) ; GssSocket secureSocket = ( GssSocket ) factory . createSocket ( simpleSocket , null , 0 , gssContext ) ; secureSocket . setUseClientMode ( isClientSocket ) ; if ( dcau == null ) { secureSocket . setAuthorization ( null ) ; } else if ( dcau == DataChannelAuthentication . SELF ) { secureSocket . setAuthorization ( SelfAuthorization . getInstance ( ) ) ; } else if ( dcau == DataChannelAuthentication . NONE ) { } else if ( dcau instanceof DataChannelAuthentication ) { secureSocket . setAuthorization ( new IdentityAuthorization ( dcau . toFtpCmdArgument ( ) ) ) ; } secureSocket . getOutputStream ( ) . flush ( ) ; if ( protection == GridFTPSession . PROTECTION_SAFE || protection == GridFTPSession . PROTECTION_PRIVATE ) { logger . debug ( "Data channel protection: on" ) ; return secureSocket ; } else { logger . debug ( "Data channel protection: off" ) ; return simpleSocket ; } }
authenticate socket . if protection on return authenticated socket wrapped over the original simpleSocket else return original socket .
39,270
public void addUrlCopyListener ( UrlCopyListener listener ) { if ( listeners == null ) listeners = new LinkedList ( ) ; listeners . add ( listener ) ; }
Adds url copy listener .
39,271
public void setSourceUrl ( GlobusURL source ) throws UrlCopyException { if ( source == null ) { throw new IllegalArgumentException ( "Source url cannot be null" ) ; } checkUrl ( source ) ; srcUrl = source ; }
Sets source url .
39,272
public void setDestinationUrl ( GlobusURL dest ) throws UrlCopyException { if ( dest == null ) { throw new IllegalArgumentException ( "Desitination url cannot be null" ) ; } checkUrl ( dest ) ; dstUrl = dest ; }
Sets destination url .
39,273
protected GlobusInputStream getInputStream ( ) throws Exception { GlobusInputStream in = null ; String fromP = srcUrl . getProtocol ( ) ; String fromFile = srcUrl . getPath ( ) ; if ( fromP . equalsIgnoreCase ( "file" ) ) { fromFile = URLDecoder . decode ( fromFile ) ; in = new GlobusFileInputStream ( fromFile ) ; } else if ( fromP . equalsIgnoreCase ( "ftp" ) ) { fromFile = URLDecoder . decode ( fromFile ) ; in = new FTPInputStream ( srcUrl . getHost ( ) , srcUrl . getPort ( ) , srcUrl . getUser ( ) , srcUrl . getPwd ( ) , fromFile ) ; } else if ( fromP . equalsIgnoreCase ( "gsiftp" ) || fromP . equalsIgnoreCase ( "gridftp" ) ) { Authorization auth = getSourceAuthorization ( ) ; if ( auth == null ) { auth = HostAuthorization . getInstance ( ) ; } fromFile = URLDecoder . decode ( fromFile ) ; in = new GridFTPInputStream ( getSourceCredentials ( ) , auth , srcUrl . getHost ( ) , srcUrl . getPort ( ) , fromFile , getDCAU ( ) ) ; } else if ( fromP . equalsIgnoreCase ( "https" ) ) { Authorization auth = getSourceAuthorization ( ) ; if ( auth == null ) { auth = SelfAuthorization . getInstance ( ) ; } in = new GassInputStream ( getSourceCredentials ( ) , auth , srcUrl . getHost ( ) , srcUrl . getPort ( ) , fromFile ) ; } else if ( fromP . equalsIgnoreCase ( "http" ) ) { in = new HTTPInputStream ( srcUrl . getHost ( ) , srcUrl . getPort ( ) , fromFile ) ; } else { throw new Exception ( "Source protocol: " + fromP + " not supported!" ) ; } return in ; }
Returns input stream based on the source url
39,274
protected GlobusOutputStream getOutputStream ( long size ) throws Exception { GlobusOutputStream out = null ; String toP = dstUrl . getProtocol ( ) ; String toFile = dstUrl . getPath ( ) ; if ( toP . equalsIgnoreCase ( "file" ) ) { toFile = URLDecoder . decode ( toFile ) ; out = new GlobusFileOutputStream ( toFile , appendMode ) ; } else if ( toP . equalsIgnoreCase ( "ftp" ) ) { toFile = URLDecoder . decode ( toFile ) ; out = new FTPOutputStream ( dstUrl . getHost ( ) , dstUrl . getPort ( ) , dstUrl . getUser ( ) , dstUrl . getPwd ( ) , toFile , appendMode ) ; } else if ( toP . equalsIgnoreCase ( "gsiftp" ) || toP . equalsIgnoreCase ( "gridftp" ) ) { Authorization auth = getDestinationAuthorization ( ) ; if ( auth == null ) { auth = HostAuthorization . getInstance ( ) ; } toFile = URLDecoder . decode ( toFile ) ; out = new GridFTPOutputStream ( getDestinationCredentials ( ) , auth , dstUrl . getHost ( ) , dstUrl . getPort ( ) , toFile , appendMode , getDCAU ( ) , ( disableAllo ? - 1 : size ) ) ; } else if ( toP . equalsIgnoreCase ( "https" ) ) { Authorization auth = getDestinationAuthorization ( ) ; if ( auth == null ) { auth = SelfAuthorization . getInstance ( ) ; } out = new GassOutputStream ( getDestinationCredentials ( ) , auth , dstUrl . getHost ( ) , dstUrl . getPort ( ) , toFile , size , appendMode ) ; } else if ( toP . equalsIgnoreCase ( "http" ) ) { out = new HTTPOutputStream ( dstUrl . getHost ( ) , dstUrl . getPort ( ) , toFile , size , appendMode ) ; } else { throw new Exception ( "Destination protocol: " + toP + " not supported!" ) ; } return out ; }
Returns output stream based on the destination url .
39,275
private boolean transfer ( long total , GlobusInputStream in , GlobusOutputStream out ) throws IOException { byte [ ] buffer = new byte [ bufferSize ] ; int bytes = 0 ; long totalBytes = total ; long transferedBytes = 0 ; if ( total == - 1 ) { while ( ( bytes = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , bytes ) ; out . flush ( ) ; if ( listeners != null ) { transferedBytes += bytes ; fireUrlTransferProgressEvent ( totalBytes , transferedBytes ) ; } if ( isCanceled ( ) ) return false ; } } else { while ( total != 0 ) { bytes = bufferSize ; if ( total < bufferSize ) bytes = ( int ) total ; bytes = in . read ( buffer ) ; out . write ( buffer , 0 , bytes ) ; out . flush ( ) ; total -= bytes ; if ( listeners != null ) { transferedBytes += bytes ; fireUrlTransferProgressEvent ( totalBytes , transferedBytes ) ; } if ( isCanceled ( ) ) return false ; } } return true ; }
This function performs the actual transfer .
39,276
private void thirdPartyTransfer ( ) throws UrlCopyException { logger . debug ( "Trying third party transfer..." ) ; FTPClient srcFTP = null ; FTPClient dstFTP = null ; try { srcFTP = createFTPConnection ( srcUrl , true ) ; dstFTP = createFTPConnection ( dstUrl , false ) ; negotiateDCAU ( srcFTP , dstFTP ) ; srcFTP . setType ( Session . TYPE_IMAGE ) ; dstFTP . setType ( Session . TYPE_IMAGE ) ; if ( listeners != null ) { fireUrlTransferProgressEvent ( - 1 , - 1 ) ; } if ( this . sourceOffset == 0 && this . destinationOffset == 0 && this . sourceLength == Long . MAX_VALUE ) { srcFTP . setMode ( Session . MODE_STREAM ) ; dstFTP . setMode ( Session . MODE_STREAM ) ; srcFTP . transfer ( srcUrl . getPath ( ) , dstFTP , dstUrl . getPath ( ) , false , null ) ; } else if ( srcFTP instanceof GridFTPClient && dstFTP instanceof GridFTPClient ) { GridFTPClient srcGridFTP = ( GridFTPClient ) srcFTP ; GridFTPClient dstGridFTP = ( GridFTPClient ) dstFTP ; srcGridFTP . setMode ( GridFTPSession . MODE_EBLOCK ) ; dstGridFTP . setMode ( GridFTPSession . MODE_EBLOCK ) ; srcGridFTP . extendedTransfer ( srcUrl . getPath ( ) , this . sourceOffset , this . sourceLength , dstGridFTP , dstUrl . getPath ( ) , this . destinationOffset , null ) ; } else { throw new UrlCopyException ( "Partial 3rd party transfers not supported " + "by FTP client. Use GridFTP for both source and destination." ) ; } } catch ( Exception e ) { throw new UrlCopyException ( "UrlCopy third party transfer failed." , e ) ; } finally { if ( srcFTP != null ) { try { srcFTP . close ( ) ; } catch ( Exception ee ) { } } if ( dstFTP != null ) { try { dstFTP . close ( ) ; } catch ( Exception ee ) { } } } }
This performs thrid party transfer only if source and destination urls are ftp urls .
39,277
public String evaluate ( Map symbolTable ) throws RslEvaluationException { String var = null ; if ( symbolTable != null ) { var = ( String ) symbolTable . get ( value ) ; } if ( var == null && defValue != null ) { var = defValue . evaluate ( symbolTable ) ; } if ( var == null ) { throw new RslEvaluationException ( "Variable '" + value + "' not defined." ) ; } if ( concatValue == null ) { return var ; } else { return var + concatValue . evaluate ( symbolTable ) ; } }
Evaluates the variable reference with the specified symbol table . The value of the reference is first looked up in the symbol table . If not found then the default value is used . If the default value is not specified the reference is evaluated to an empty string .
39,278
public void toRSL ( StringBuffer buf , boolean explicitConcat ) { buf . append ( "$(" ) ; buf . append ( value ) ; if ( defValue != null ) { buf . append ( " " ) ; defValue . toRSL ( buf , explicitConcat ) ; } buf . append ( ")" ) ; if ( concatValue == null ) return ; if ( explicitConcat ) buf . append ( " # " ) ; concatValue . toRSL ( buf , explicitConcat ) ; }
Produces a RSL representation of this variable reference .
39,279
public void checkClientTrusted ( X509Certificate [ ] x509Certificates , String authType ) throws CertificateException { CertPath certPath = CertificateUtil . getCertPath ( x509Certificates ) ; try { this . result = this . validator . engineValidate ( certPath , parameters ) ; } catch ( CertPathValidatorException exception ) { throw new CertificateException ( "Path validation failed: " + exception . getMessage ( ) , exception ) ; } catch ( InvalidAlgorithmParameterException exception ) { throw new CertificateException ( "Path validation failed: " + exception . getMessage ( ) , exception ) ; } }
Test if the client is trusted based on the certificate chain . Does not currently support anonymous clients .
39,280
public X509Certificate [ ] getAcceptedIssuers ( ) { try { Collection < X509Certificate > trusted = CertificateLoadUtil . getTrustedCertificates ( this . parameters . getTrustStore ( ) , null ) ; return trusted . toArray ( new X509Certificate [ trusted . size ( ) ] ) ; } catch ( KeyStoreException e ) { logger . warn ( "Unable to load trusted Certificates. Authentication will fail." , e ) ; return new X509Certificate [ ] { } ; } }
Get the collection of trusted certificate issuers .
39,281
private static byte [ ] getDecodedPEMObject ( BufferedReader reader ) throws IOException { String line ; StringBuffer buf = new StringBuffer ( ) ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . indexOf ( "--END" ) != - 1 ) { return Base64 . decode ( buf . toString ( ) . getBytes ( ) ) ; } else { buf . append ( line ) ; } } throw new EOFException ( "Missing PEM end footer" ) ; }
Reads Base64 encoded data from the stream and returns its decoded value . The reading continues until the END string is found in the data . Otherwise returns null .
39,282
public void saveCertificateChain ( OutputStream out ) throws IOException , CertificateEncodingException { CertificateIOUtil . writeCertificate ( out , this . certChain [ 0 ] ) ; for ( int i = 1 ; i < this . certChain . length ; i ++ ) { if ( this . certChain [ i ] . getSubjectDN ( ) . equals ( certChain [ i ] . getIssuerDN ( ) ) ) { continue ; } CertificateIOUtil . writeCertificate ( out , this . certChain [ i ] ) ; } out . flush ( ) ; }
COMMENT Used to be key cert cert cert ... which is wrong afaik . must be cert key cert cert ...
39,283
public int getCertNum ( ) { for ( int i = this . certChain . length - 1 ; i >= 0 ; i -- ) { if ( ! this . certChain [ i ] . getSubjectDN ( ) . equals ( this . certChain [ i ] . getIssuerDN ( ) ) ) { return i + 1 ; } } return this . certChain . length ; }
Returns the number of certificates in the credential without the self - signed certificates .
39,284
public long getTimeLeft ( ) { Date earliestTime = null ; for ( int i = 0 ; i < this . certChain . length ; i ++ ) { Date time = this . certChain [ i ] . getNotAfter ( ) ; if ( earliestTime == null || time . before ( earliestTime ) ) { earliestTime = time ; } } long diff = ( earliestTime . getTime ( ) - System . currentTimeMillis ( ) ) / 1000 ; return ( diff < 0 ) ? 0 : diff ; }
Returns time left of this credential . The time left of the credential is based on the certificate with the shortest validity time .
39,285
public X509Certificate getIdentityCertificate ( ) { try { return BouncyCastleUtil . getIdentityCertificate ( this . certChain ) ; } catch ( CertificateException e ) { logger . debug ( "Error getting certificate identity." , e ) ; return null ; } }
Returns the identity certificate of this credential . The identity certificate is the first certificate in the chain that is not an impersonation proxy certificate .
39,286
public int getPathConstraint ( ) { int pathLength = Integer . MAX_VALUE ; try { for ( int i = 0 ; i < this . certChain . length ; i ++ ) { int length = BouncyCastleUtil . getProxyPathConstraint ( this . certChain [ i ] ) ; if ( length == - 1 ) { length = Integer . MAX_VALUE ; } if ( length < pathLength ) { pathLength = length ; } } } catch ( Exception e ) { logger . warn ( "Error retrieving path length." , e ) ; pathLength = - 1 ; } return pathLength ; }
Returns the path length constraint . The shortest length in the chain of certificates is returned as the credential s path length .
39,287
private ServerSocket createServerSocket ( int backlog , InetAddress binAddr ) throws IOException { ServerSocket server = null ; int port = 0 ; while ( true ) { port = this . portRange . getFreePort ( port ) ; try { server = new PrServerSocket ( port , backlog , binAddr ) ; this . portRange . setUsed ( port ) ; return server ; } catch ( IOException e ) { port ++ ; } } }
Tries to find first available port within the port range specified . If it finds a free port it first checks if the port is not used by any other server . If it is it keeps looking for a next available port . If none found it throws an exception . If the port is available the server instance is returned .
39,288
protected void checkGridFTPSupport ( ) throws IOException , ServerException { FeatureList fl = getFeatureList ( ) ; if ( ! ( fl . contains ( FeatureList . PARALLEL ) && fl . contains ( FeatureList . ESTO ) && fl . contains ( FeatureList . ERET ) && fl . contains ( FeatureList . SIZE ) ) ) { throw new ServerException ( ServerException . UNSUPPORTED_FEATURE ) ; } }
assure that the server supports extended transfer features ; throw exception if not
39,289
public void get ( String remoteFileName , File localFile ) throws IOException , ClientException , ServerException { if ( gSession . transferMode == GridFTPSession . MODE_EBLOCK ) { DataSink sink = new FileRandomIO ( new RandomAccessFile ( localFile , "rw" ) ) ; get ( remoteFileName , sink , null ) ; } else { super . get ( remoteFileName , localFile ) ; } }
basic compatibility API
39,290
public void setChecksum ( ChecksumAlgorithm algorithm , String value ) throws IOException , ServerException { String arguments = algorithm . toFtpCmdArgument ( ) + " " + value ; Command cmd = new Command ( "SCKS" , arguments ) ; try { controlChannel . execute ( cmd ) ; } catch ( UnexpectedReplyCodeException urce ) { throw ServerException . embedUnexpectedReplyCodeException ( urce ) ; } catch ( FTPReplyParseException rpe ) { throw ServerException . embedFTPReplyParseException ( rpe ) ; } }
Sets the checksum values ahead of the transfer
39,291
public String checksum ( ChecksumAlgorithm algorithm , long offset , long length , String file ) throws IOException , ServerException { String arguments = algorithm . toFtpCmdArgument ( ) + " " + String . valueOf ( offset ) + " " + String . valueOf ( length ) + " " + file ; Command cmd = new Command ( "CKSM" , arguments ) ; Reply reply = null ; try { reply = controlChannel . execute ( cmd ) ; return reply . getMessage ( ) ; } catch ( UnexpectedReplyCodeException urce ) { throw ServerException . embedUnexpectedReplyCodeException ( urce ) ; } catch ( FTPReplyParseException rpe ) { throw ServerException . embedFTPReplyParseException ( rpe ) ; } }
Computes and returns a checksum of a file . transferred .
39,292
public void changeGroup ( String group , String file ) throws IOException , ServerException { String arguments = group + " " + file ; Command cmd = new Command ( "SITE CHGRP" , arguments ) ; try { controlChannel . execute ( cmd ) ; } catch ( UnexpectedReplyCodeException urce ) { throw ServerException . embedUnexpectedReplyCodeException ( urce ) ; } catch ( FTPReplyParseException rpe ) { throw ServerException . embedFTPReplyParseException ( rpe ) ; } }
Change the Unix group membership of a file .
39,293
public void changeModificationTime ( int year , int month , int day , int hour , int min , int sec , String file ) throws IOException , ServerException { DecimalFormat df2 = new DecimalFormat ( "00" ) ; DecimalFormat df4 = new DecimalFormat ( "0000" ) ; String arguments = df4 . format ( year ) + df2 . format ( month ) + df2 . format ( day ) + df2 . format ( hour ) + df2 . format ( min ) + df2 . format ( sec ) + " " + file ; Command cmd = new Command ( "SITE UTIME" , arguments ) ; try { controlChannel . execute ( cmd ) ; } catch ( UnexpectedReplyCodeException urce ) { throw ServerException . embedUnexpectedReplyCodeException ( urce ) ; } catch ( FTPReplyParseException rpe ) { throw ServerException . embedFTPReplyParseException ( rpe ) ; } }
Change the modification time of a file .
39,294
public void createSymbolicLink ( String link_target , String link_name ) throws IOException , ServerException { String arguments = link_target . replaceAll ( " " , "%20" ) + " " + link_name ; Command cmd = new Command ( "SITE SYMLINK" , arguments ) ; try { controlChannel . execute ( cmd ) ; } catch ( UnexpectedReplyCodeException urce ) { throw ServerException . embedUnexpectedReplyCodeException ( urce ) ; } catch ( FTPReplyParseException rpe ) { throw ServerException . embedFTPReplyParseException ( rpe ) ; } }
Create a symbolic link on the FTP server .
39,295
public void setOid ( String oid ) { if ( oid == null ) { throw new IllegalArgumentException ( i18n . getMessage ( "oidNull" ) ) ; } this . oid = oid ; }
Sets the oid of this extension .
39,296
public void addListener ( GramJobListener listener ) { if ( listeners == null ) listeners = new Vector ( ) ; listeners . addElement ( listener ) ; }
Add a listener to the GramJob . The listener will be notified whenever the status of the GramJob changes .
39,297
protected void setStatus ( int status ) { if ( this . status == status ) return ; this . status = status ; if ( listeners == null ) return ; int size = listeners . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { GramJobListener listener = ( GramJobListener ) listeners . elementAt ( i ) ; listener . statusChanged ( this ) ; } }
Sets the status of the job . User should not call this function .
39,298
public void request ( String contact , boolean batch ) throws GramException , GSSException { Gram . request ( contact , this , batch ) ; }
Submits a job to the specified gatekeeper either as an interactive or batch job . Performs limited delegation .
39,299
public int signal ( int signal , String arg ) throws GramException , GSSException { return Gram . jobSignal ( this , signal , arg ) ; }
Sends a signal command to the job .