idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
25,300 | public static String buildSecretFromJwk ( final String json ) { CommonHelper . assertNotBlank ( "json" , json ) ; try { final OctetSequenceKey octetSequenceKey = OctetSequenceKey . parse ( json ) ; return new String ( octetSequenceKey . toByteArray ( ) , "UTF-8" ) ; } catch ( final UnsupportedEncodingException | ParseException e ) { throw new TechnicalException ( e ) ; } } | Build the secret from the JWK JSON . |
25,301 | public static KeyPair buildRSAKeyPairFromJwk ( final String json ) { CommonHelper . assertNotBlank ( "json" , json ) ; try { final RSAKey rsaKey = RSAKey . parse ( json ) ; return rsaKey . toKeyPair ( ) ; } catch ( final JOSEException | ParseException e ) { throw new TechnicalException ( e ) ; } } | Build the RSA key pair from the JWK JSON . |
25,302 | public static KeyPair buildECKeyPairFromJwk ( final String json ) { CommonHelper . assertNotBlank ( "json" , json ) ; try { final ECKey ecKey = ECKey . parse ( json ) ; return ecKey . toKeyPair ( ) ; } catch ( final JOSEException | ParseException e ) { throw new TechnicalException ( e ) ; } } | Build the EC key pair from the JWK JSON . |
25,303 | public static boolean isTypedIdOf ( final String id , final Class < ? extends CommonProfile > clazz ) { if ( id != null && clazz != null ) { return id . startsWith ( clazz . getName ( ) + CommonProfile . SEPARATOR ) ; } return false ; } | Indicate if the user identifier matches this kind of profile . |
25,304 | public static CommonProfile restoreOrBuildProfile ( final ProfileDefinition < ? extends CommonProfile > profileDefinition , final String typedId , final Map < String , Object > profileAttributes , final Map < String , Object > authenticationAttributes , final Object ... parameters ) { if ( CommonHelper . isBlank ( typedId ) ) { return null ; } logger . info ( "Building user profile based on typedId: {}" , typedId ) ; final CommonProfile profile ; if ( typedId . contains ( CommonProfile . SEPARATOR ) ) { final String className = CommonHelper . substringBefore ( typedId , CommonProfile . SEPARATOR ) ; try { profile = buildUserProfileByClassCompleteName ( className ) ; } catch ( final TechnicalException e ) { logger . error ( "Cannot build instance for class name: {}" , className , e ) ; return null ; } profile . addAttributes ( profileAttributes ) ; profile . addAuthenticationAttributes ( authenticationAttributes ) ; } else { profile = profileDefinition . newProfile ( parameters ) ; profileDefinition . convertAndAdd ( profile , profileAttributes , authenticationAttributes ) ; } profile . setId ( ProfileHelper . sanitizeIdentifier ( profile , typedId ) ) ; return profile ; } | Restore or build a profile . |
25,305 | public static CommonProfile buildUserProfileByClassCompleteName ( final String completeName ) { try { final Constructor < ? extends CommonProfile > constructor = CommonHelper . getConstructor ( completeName ) ; return constructor . newInstance ( ) ; } catch ( final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e ) { throw new TechnicalException ( e ) ; } } | Build a profile by its class name . |
25,306 | public static < U extends UserProfile > List < U > flatIntoAProfileList ( final Map < String , U > profiles ) { return new ArrayList < > ( profiles . values ( ) ) ; } | Flat the map of profiles into a list of profiles . |
25,307 | public static String sanitizeIdentifier ( final BasicUserProfile profile , final Object id ) { if ( id != null ) { String sId = id . toString ( ) ; if ( profile != null ) { final String type = profile . getClass ( ) . getName ( ) + BasicUserProfile . SEPARATOR ; if ( sId . startsWith ( type ) ) { sId = sId . substring ( type . length ( ) ) ; } } return sId ; } return null ; } | Sanitize into a string identifier . |
25,308 | public PathMatcher excludeRegex ( final String regex ) { CommonHelper . assertNotBlank ( "regex" , regex ) ; logger . warn ( "Excluding paths with regexes is an advanced feature: be careful when defining your regular expression " + "to avoid any security issues!" ) ; if ( ! regex . startsWith ( "^" ) || ! regex . endsWith ( "$" ) ) { throw new TechnicalException ( "Your regular expression: '" + regex + "' must start with a ^ and end with a $ " + "to define a full path matching" ) ; } excludedPatterns . add ( Pattern . compile ( regex ) ) ; return this ; } | Any path matching this regex will be excluded . |
25,309 | boolean matches ( final String path ) { logger . debug ( "path to match: {}" , path ) ; if ( excludedPaths . contains ( path ) ) { return false ; } for ( Pattern pattern : excludedPatterns ) { if ( pattern . matcher ( path ) . matches ( ) ) { return false ; } } return true ; } | Returns true if a path should be authenticated false to skip authentication . |
25,310 | protected R handleException ( final Exception e , final HttpActionAdapter < R , C > httpActionAdapter , final C context ) { if ( httpActionAdapter == null || context == null ) { throw runtimeException ( e ) ; } else if ( e instanceof HttpAction ) { final HttpAction action = ( HttpAction ) e ; logger . debug ( "extra HTTP action required in security: {}" , action . getCode ( ) ) ; return httpActionAdapter . adapt ( action , context ) ; } else { if ( CommonHelper . isNotBlank ( errorUrl ) ) { final HttpAction action = RedirectionActionHelper . buildRedirectUrlAction ( context , errorUrl ) ; return httpActionAdapter . adapt ( action , context ) ; } else { throw runtimeException ( e ) ; } } } | Handle exceptions . |
25,311 | protected RuntimeException runtimeException ( final Exception exception ) { if ( exception instanceof RuntimeException ) { throw ( RuntimeException ) exception ; } else { throw new RuntimeException ( exception ) ; } } | Wrap an Exception into a RuntimeException . |
25,312 | public static boolean urisEqualAfterPortNormalization ( final URI uri1 , final URI uri2 ) { if ( uri1 == null && uri2 == null ) { return true ; } if ( uri1 == null || uri2 == null ) { return false ; } try { URI normalizedUri1 = normalizePortNumbersInUri ( uri1 ) ; URI normalizedUri2 = normalizePortNumbersInUri ( uri2 ) ; boolean eq = normalizedUri1 . equals ( normalizedUri2 ) ; return eq ; } catch ( URISyntaxException use ) { logger . error ( "Cannot compare 2 URIs." , use ) ; return false ; } } | Compares two URIs for equality ignoring default port numbers for selected protocols . |
25,313 | private static URI normalizePortNumbersInUri ( final URI uri ) throws URISyntaxException { int port = uri . getPort ( ) ; final String scheme = uri . getScheme ( ) ; if ( SCHEME_HTTP . equals ( scheme ) && port == DEFAULT_HTTP_PORT ) { port = - 1 ; } if ( SCHEME_HTTPS . equals ( scheme ) && port == DEFAULT_HTTPS_PORT ) { port = - 1 ; } final URI result = new URI ( scheme , uri . getUserInfo ( ) , uri . getHost ( ) , port , uri . getPath ( ) , uri . getQuery ( ) , uri . getFragment ( ) ) ; return result ; } | Normalizes a URI . If it contains the default port for the used scheme the method replaces the port with default . |
25,314 | protected URI getEndpointURL ( MessageContext < SAMLObject > messageContext ) throws MessageEncodingException { try { return SAMLBindingSupport . getEndpointURL ( messageContext ) ; } catch ( BindingException e ) { throw new MessageEncodingException ( "Could not obtain message endpoint URL" , e ) ; } } | Gets the response URL from the message context . |
25,315 | public String generate ( final Map < String , Object > claims ) { final JWTClaimsSet . Builder builder = new JWTClaimsSet . Builder ( ) ; for ( final Map . Entry < String , Object > entry : claims . entrySet ( ) ) { builder . claim ( entry . getKey ( ) , entry . getValue ( ) ) ; } if ( this . expirationTime != null ) { builder . expirationTime ( this . expirationTime ) ; } return internalGenerate ( builder . build ( ) ) ; } | Generate a JWT from a map of claims . |
25,316 | protected String internalGenerate ( final JWTClaimsSet claimsSet ) { JWT jwt ; if ( signatureConfiguration == null ) { jwt = new PlainJWT ( claimsSet ) ; } else { jwt = signatureConfiguration . sign ( claimsSet ) ; } if ( encryptionConfiguration != null ) { return encryptionConfiguration . encrypt ( jwt ) ; } else { return jwt . serialize ( ) ; } } | Generate a JWT from a claims set . |
25,317 | public static String buildHttpErrorMessage ( final HttpURLConnection connection ) throws IOException { final StringBuilder messageBuilder = new StringBuilder ( "(" ) . append ( connection . getResponseCode ( ) ) . append ( ")" ) ; if ( connection . getResponseMessage ( ) != null ) { messageBuilder . append ( " " ) ; messageBuilder . append ( connection . getResponseMessage ( ) ) ; } try ( final InputStreamReader isr = new InputStreamReader ( connection . getErrorStream ( ) , StandardCharsets . UTF_8 ) ; BufferedReader br = new BufferedReader ( isr ) ) { String output ; messageBuilder . append ( "[" ) ; while ( ( output = br . readLine ( ) ) != null ) { messageBuilder . append ( output ) ; } messageBuilder . append ( "]" ) ; } finally { connection . disconnect ( ) ; } return messageBuilder . toString ( ) ; } | Build error message from connection in case of failure |
25,318 | protected void computeInitialFeasibleSolution ( ) { for ( int j = 0 ; j < dim ; j ++ ) { labelByJob [ j ] = Double . POSITIVE_INFINITY ; } for ( int w = 0 ; w < dim ; w ++ ) { for ( int j = 0 ; j < dim ; j ++ ) { if ( costMatrix [ w ] [ j ] < labelByJob [ j ] ) { labelByJob [ j ] = costMatrix [ w ] [ j ] ; } } } } | Compute an initial feasible solution by assigning zero labels to the workers and by assigning to each job a label equal to the minimum cost among its incident edges . |
25,319 | public int [ ] execute ( ) { reduce ( ) ; computeInitialFeasibleSolution ( ) ; greedyMatch ( ) ; int w = fetchUnmatchedWorker ( ) ; while ( w < dim ) { initializePhase ( w ) ; executePhase ( ) ; w = fetchUnmatchedWorker ( ) ; } int [ ] result = Arrays . copyOf ( matchJobByWorker , rows ) ; for ( w = 0 ; w < result . length ; w ++ ) { if ( result [ w ] >= cols ) { result [ w ] = - 1 ; } } return result ; } | Execute the algorithm . |
25,320 | protected void greedyMatch ( ) { for ( int w = 0 ; w < dim ; w ++ ) { for ( int j = 0 ; j < dim ; j ++ ) { if ( matchJobByWorker [ w ] == - 1 && matchWorkerByJob [ j ] == - 1 && costMatrix [ w ] [ j ] - labelByWorker [ w ] - labelByJob [ j ] == 0 ) { match ( w , j ) ; } } } } | Find a valid matching by greedily selecting among zero - cost matchings . This is a heuristic to jump - start the augmentation algorithm . |
25,321 | protected void initializePhase ( int w ) { Arrays . fill ( committedWorkers , false ) ; Arrays . fill ( parentWorkerByCommittedJob , - 1 ) ; committedWorkers [ w ] = true ; for ( int j = 0 ; j < dim ; j ++ ) { minSlackValueByJob [ j ] = costMatrix [ w ] [ j ] - labelByWorker [ w ] - labelByJob [ j ] ; minSlackWorkerByJob [ j ] = w ; } } | Initialize the next phase of the algorithm by clearing the committed workers and jobs sets and by initializing the slack arrays to the values corresponding to the specified root worker . |
25,322 | protected void reduce ( ) { for ( int w = 0 ; w < dim ; w ++ ) { double min = Double . POSITIVE_INFINITY ; for ( int j = 0 ; j < dim ; j ++ ) { if ( costMatrix [ w ] [ j ] < min ) { min = costMatrix [ w ] [ j ] ; } } for ( int j = 0 ; j < dim ; j ++ ) { costMatrix [ w ] [ j ] -= min ; } } double [ ] min = new double [ dim ] ; for ( int j = 0 ; j < dim ; j ++ ) { min [ j ] = Double . POSITIVE_INFINITY ; } for ( int w = 0 ; w < dim ; w ++ ) { for ( int j = 0 ; j < dim ; j ++ ) { if ( costMatrix [ w ] [ j ] < min [ j ] ) { min [ j ] = costMatrix [ w ] [ j ] ; } } } for ( int w = 0 ; w < dim ; w ++ ) { for ( int j = 0 ; j < dim ; j ++ ) { costMatrix [ w ] [ j ] -= min [ j ] ; } } } | Reduce the cost matrix by subtracting the smallest element of each row from all elements of the row as well as the smallest element of each column from all elements of the column . Note that an optimal assignment for a reduced cost matrix is optimal for the original cost matrix . |
25,323 | protected void updateLabeling ( double slack ) { for ( int w = 0 ; w < dim ; w ++ ) { if ( committedWorkers [ w ] ) { labelByWorker [ w ] += slack ; } } for ( int j = 0 ; j < dim ; j ++ ) { if ( parentWorkerByCommittedJob [ j ] != - 1 ) { labelByJob [ j ] -= slack ; } else { minSlackValueByJob [ j ] -= slack ; } } } | Update labels with the specified slack by adding the slack value for committed workers and by subtracting the slack value for committed jobs . In addition update the minimum slack values appropriately . |
25,324 | public static List < ITree > preOrder ( ITree tree ) { List < ITree > trees = new ArrayList < > ( ) ; preOrder ( tree , trees ) ; return trees ; } | Returns a list of every subtrees and the tree ordered using a pre - order . |
25,325 | public static List < ITree > postOrder ( ITree tree ) { List < ITree > trees = new ArrayList < > ( ) ; postOrder ( tree , trees ) ; return trees ; } | Returns a list of every subtrees and the tree ordered using a post - order . |
25,326 | public Object set ( String key , Object value ) { int idx = keys . indexOf ( key ) ; if ( idx == - 1 ) { keys . add ( key ) ; values . add ( value ) ; return null ; } return values . set ( idx , value ) ; } | set metadata key with value and returns the previous value This method won t remove if value == null |
25,327 | protected void beforeMarkup ( ) { int soFar = stack [ depth ] ; if ( ( soFar & WROTE_DATA ) == 0 && ( depth > 0 || soFar != 0 ) ) { try { writeNewLine ( depth ) ; if ( depth > 0 && getIndent ( ) . length ( ) > 0 ) { afterMarkup ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } | Prepare to write markup by writing a new line and indentation . |
25,328 | protected void beforeStartElement ( ) { beforeMarkup ( ) ; if ( stack . length <= depth + 1 ) { int [ ] newStack = new int [ stack . length * 2 ] ; System . arraycopy ( stack , 0 , newStack , 0 , stack . length ) ; stack = newStack ; } stack [ depth + 1 ] = 0 ; } | Prepare to start an element by allocating stack space . |
25,329 | protected void writeNewLine ( int indentation ) throws XMLStreamException { final int newLineLength = getNewLine ( ) . length ( ) ; final int prefixLength = newLineLength + ( getIndent ( ) . length ( ) * indentation ) ; if ( prefixLength > 0 ) { if ( linePrefix == null ) { linePrefix = ( getNewLine ( ) + getIndent ( ) ) . toCharArray ( ) ; } while ( prefixLength > linePrefix . length ) { char [ ] newPrefix = new char [ newLineLength + ( ( linePrefix . length - newLineLength ) * 2 ) ] ; System . arraycopy ( linePrefix , 0 , newPrefix , 0 , linePrefix . length ) ; System . arraycopy ( linePrefix , newLineLength , newPrefix , linePrefix . length , linePrefix . length - newLineLength ) ; linePrefix = newPrefix ; } out . writeCharacters ( linePrefix , 0 , prefixLength ) ; } } | Write a line separator followed by indentation . |
25,330 | public Object getMetadata ( ITree node , String key ) { Object metadata ; if ( node == null || ( metadata = node . getMetadata ( key ) ) == null ) return getMetadata ( key ) ; return metadata ; } | Get a local metadata if available . Otherwise get a global metadata . There is no way to know if the metadata is really null or does not exists . |
25,331 | public Object setMetadata ( String key , Object value ) { return metadata . put ( key , value ) ; } | Store a global metadata . |
25,332 | public Object setMetadata ( ITree node , String key , Object value ) { if ( node == null ) return setMetadata ( key , value ) ; else { Object res = node . setMetadata ( key , value ) ; if ( res == null ) return getMetadata ( key ) ; return res ; } } | Store a local metadata |
25,333 | public static List < int [ ] > longestCommonSubsequence ( String s0 , String s1 ) { int [ ] [ ] lengths = new int [ s0 . length ( ) + 1 ] [ s1 . length ( ) + 1 ] ; for ( int i = 0 ; i < s0 . length ( ) ; i ++ ) for ( int j = 0 ; j < s1 . length ( ) ; j ++ ) if ( s0 . charAt ( i ) == ( s1 . charAt ( j ) ) ) lengths [ i + 1 ] [ j + 1 ] = lengths [ i ] [ j ] + 1 ; else lengths [ i + 1 ] [ j + 1 ] = Math . max ( lengths [ i + 1 ] [ j ] , lengths [ i ] [ j + 1 ] ) ; return extractIndexes ( lengths , s0 . length ( ) , s1 . length ( ) ) ; } | Returns the longest common subsequence between two strings . |
25,334 | public static List < int [ ] > hunks ( String s0 , String s1 ) { List < int [ ] > lcs = longestCommonSubsequence ( s0 , s1 ) ; List < int [ ] > hunks = new ArrayList < int [ ] > ( ) ; int inf0 = - 1 ; int inf1 = - 1 ; int last0 = - 1 ; int last1 = - 1 ; for ( int i = 0 ; i < lcs . size ( ) ; i ++ ) { int [ ] match = lcs . get ( i ) ; if ( inf0 == - 1 || inf1 == - 1 ) { inf0 = match [ 0 ] ; inf1 = match [ 1 ] ; } else if ( last0 + 1 != match [ 0 ] || last1 + 1 != match [ 1 ] ) { hunks . add ( new int [ ] { inf0 , last0 + 1 , inf1 , last1 + 1 } ) ; inf0 = match [ 0 ] ; inf1 = match [ 1 ] ; } else if ( i == lcs . size ( ) - 1 ) { hunks . add ( new int [ ] { inf0 , match [ 0 ] + 1 , inf1 , match [ 1 ] + 1 } ) ; break ; } last0 = match [ 0 ] ; last1 = match [ 1 ] ; } return hunks ; } | Returns the hunks of the longest common subsequence between s1 and s2 . |
25,335 | public static String longestCommonSequence ( String s1 , String s2 ) { int start = 0 ; int max = 0 ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { for ( int j = 0 ; j < s2 . length ( ) ; j ++ ) { int x = 0 ; while ( s1 . charAt ( i + x ) == s2 . charAt ( j + x ) ) { x ++ ; if ( ( ( i + x ) >= s1 . length ( ) ) || ( ( j + x ) >= s2 . length ( ) ) ) break ; } if ( x > max ) { max = x ; start = i ; } } } return s1 . substring ( start , ( start + max ) ) ; } | Returns the longest common sequence between two strings as a string . |
25,336 | public static List < int [ ] > longestCommonSubsequenceWithTypeAndLabel ( List < ITree > s0 , List < ITree > s1 ) { int [ ] [ ] lengths = new int [ s0 . size ( ) + 1 ] [ s1 . size ( ) + 1 ] ; for ( int i = 0 ; i < s0 . size ( ) ; i ++ ) for ( int j = 0 ; j < s1 . size ( ) ; j ++ ) if ( s0 . get ( i ) . hasSameTypeAndLabel ( s1 . get ( j ) ) ) lengths [ i + 1 ] [ j + 1 ] = lengths [ i ] [ j ] + 1 ; else lengths [ i + 1 ] [ j + 1 ] = Math . max ( lengths [ i + 1 ] [ j ] , lengths [ i ] [ j + 1 ] ) ; return extractIndexes ( lengths , s0 . size ( ) , s1 . size ( ) ) ; } | Returns the longest common subsequence between the two list of nodes . This version use type and label to ensure equality . |
25,337 | public static List < int [ ] > longestCommonSubsequenceWithIsomorphism ( List < ITree > s0 , List < ITree > s1 ) { int [ ] [ ] lengths = new int [ s0 . size ( ) + 1 ] [ s1 . size ( ) + 1 ] ; for ( int i = 0 ; i < s0 . size ( ) ; i ++ ) for ( int j = 0 ; j < s1 . size ( ) ; j ++ ) if ( s0 . get ( i ) . isIsomorphicTo ( s1 . get ( j ) ) ) lengths [ i + 1 ] [ j + 1 ] = lengths [ i ] [ j ] + 1 ; else lengths [ i + 1 ] [ j + 1 ] = Math . max ( lengths [ i + 1 ] [ j ] , lengths [ i ] [ j + 1 ] ) ; return extractIndexes ( lengths , s0 . size ( ) , s1 . size ( ) ) ; } | Returns the longest common subsequence between the two list of nodes . This version use isomorphism to ensure equality . |
25,338 | public int positionFor ( int line , int column ) { if ( lines . size ( ) < line ) return - 1 ; return lines . get ( line - 1 ) + column - 1 ; } | Line and column starts at 1 |
25,339 | private double spfL ( InfoTree it1 , InfoTree it2 ) { int fPostorder = it1 . getCurrentNode ( ) ; int gPostorder = it2 . getCurrentNode ( ) ; int minKR = it2 . info [ POST2_MIN_KR ] [ gPostorder ] ; int [ ] kr = it2 . info [ KR ] ; if ( minKR > - 1 ) { for ( int j = minKR ; kr [ j ] < gPostorder ; j ++ ) { treeEditDist ( it1 , it2 , fPostorder , kr [ j ] ) ; } } treeEditDist ( it1 , it2 , fPostorder , gPostorder ) ; return it1 . isSwitched ( ) ? delta [ gPostorder ] [ fPostorder ] + deltaBit [ gPostorder ] [ fPostorder ] * costMatch : delta [ fPostorder ] [ gPostorder ] + deltaBit [ fPostorder ] [ gPostorder ] * costMatch ; } | Single - path function for the left - most path based on Zhang and Shasha algorithm . |
25,340 | private double spfR ( InfoTree it1 , InfoTree it2 ) { int fReversedPostorder = it1 . getSize ( ) - 1 - it1 . info [ POST2_PRE ] [ it1 . getCurrentNode ( ) ] ; int gReversedPostorder = it2 . getSize ( ) - 1 - it2 . info [ POST2_PRE ] [ it2 . getCurrentNode ( ) ] ; int minRKR = it2 . info [ RPOST2_MIN_RKR ] [ gReversedPostorder ] ; int [ ] rkr = it2 . info [ RKR ] ; if ( minRKR > - 1 ) for ( int j = minRKR ; rkr [ j ] < gReversedPostorder ; j ++ ) treeEditDistRev ( it1 , it2 , fReversedPostorder , rkr [ j ] ) ; treeEditDistRev ( it1 , it2 , fReversedPostorder , gReversedPostorder ) ; return it1 . isSwitched ( ) ? delta [ it2 . getCurrentNode ( ) ] [ it1 . getCurrentNode ( ) ] + deltaBit [ it2 . getCurrentNode ( ) ] [ it1 . getCurrentNode ( ) ] * costMatch : delta [ it1 . getCurrentNode ( ) ] [ it2 . getCurrentNode ( ) ] + deltaBit [ it1 . getCurrentNode ( ) ] [ it2 . getCurrentNode ( ) ] * costMatch ; } | Single - path function for right - most path based on symmetric version of Zhang and Shasha algorithm . |
25,341 | public final int addChild ( Task < E > child ) { int index = addChildToTask ( child ) ; if ( tree != null && tree . listeners != null ) tree . notifyChildAdded ( this , index ) ; return index ; } | This method will add a child to the list of this task s children |
25,342 | public boolean checkGuard ( Task < E > control ) { if ( guard == null ) return true ; if ( ! guard . checkGuard ( control ) ) return false ; guard . setControl ( control . tree . guardEvaluator ) ; guard . start ( ) ; guard . run ( ) ; switch ( guard . getStatus ( ) ) { case SUCCEEDED : return true ; case FAILED : return false ; default : throw new IllegalStateException ( "Illegal guard status '" + guard . getStatus ( ) + "'. Guards must either succeed or fail in one step." ) ; } } | Checks the guard of this task . |
25,343 | public final void cancel ( ) { cancelRunningChildren ( 0 ) ; Status previousStatus = status ; status = Status . CANCELLED ; if ( tree . listeners != null && tree . listeners . size > 0 ) tree . notifyStatusUpdated ( this , previousStatus ) ; end ( ) ; } | Terminates this task and all its running children . This method MUST be called only if this task is running . |
25,344 | protected void cancelRunningChildren ( int startIndex ) { for ( int i = startIndex , n = getChildCount ( ) ; i < n ; i ++ ) { Task < E > child = getChild ( i ) ; if ( child . status == Status . RUNNING ) child . cancel ( ) ; } } | Terminates the running children of this task starting from the specified index up to the end . |
25,345 | public void resetTask ( ) { if ( status == Status . RUNNING ) cancel ( ) ; for ( int i = 0 , n = getChildCount ( ) ; i < n ; i ++ ) { getChild ( i ) . resetTask ( ) ; } status = Status . FRESH ; tree = null ; control = null ; } | Resets this task to make it restart from scratch on next run . |
25,346 | public static int mulAndCheck ( int x , int y ) throws ArithmeticException { long m = ( ( long ) x ) * ( ( long ) y ) ; if ( m < Integer . MIN_VALUE || m > Integer . MAX_VALUE ) { throw new ArithmeticException ( ) ; } return ( int ) m ; } | Multiply two integers checking for overflow . |
25,347 | protected Pool < BehaviorTree > getPool ( final String treeReference ) { Pool < BehaviorTree > treePool = pools . get ( treeReference ) ; if ( treePool == null ) { treePool = new Pool < BehaviorTree > ( ) { protected BehaviorTree newObject ( ) { return newBehaviorTree ( treeReference ) ; } } ; pools . put ( treeReference , treePool ) ; } return treePool ; } | retrieve pool by tree reference create it if not already exists . |
25,348 | public void clear ( String treeReference ) { Pool < BehaviorTree > treePool = pools . get ( treeReference ) ; if ( treePool != null ) { treePool . clear ( ) ; } } | Clear pool for a tree reference . |
25,349 | public void clear ( ) { for ( Entry < String , Pool < BehaviorTree > > entry : pools . entries ( ) ) { entry . value . clear ( ) ; } pools . clear ( ) ; } | clear all pools . |
25,350 | protected SteeringAcceleration < T > reachOrientation ( SteeringAcceleration < T > steering , float targetOrientation ) { float rotation = ArithmeticUtils . wrapAngleAroundZero ( targetOrientation - owner . getOrientation ( ) ) ; float rotationSize = rotation < 0f ? - rotation : rotation ; if ( rotationSize <= alignTolerance ) return steering . setZero ( ) ; Limiter actualLimiter = getActualLimiter ( ) ; float targetRotation = actualLimiter . getMaxAngularSpeed ( ) ; if ( rotationSize <= decelerationRadius ) targetRotation *= rotationSize / decelerationRadius ; targetRotation *= rotation / rotationSize ; steering . angular = ( targetRotation - owner . getAngularVelocity ( ) ) / timeToTarget ; float angularAcceleration = steering . angular < 0f ? - steering . angular : steering . angular ; if ( angularAcceleration > actualLimiter . getMaxAngularAcceleration ( ) ) steering . angular *= actualLimiter . getMaxAngularAcceleration ( ) / angularAcceleration ; steering . linear . setZero ( ) ; return steering ; } | Produces a steering that tries to align the owner to the target orientation . This method is called by subclasses that want to align to a certain orientation . |
25,351 | private Steerable < T > calculateTarget ( ) { this . jumpTarget . position = jumpDescriptor . takeoffPosition ; this . airborneTime = calculateAirborneTimeAndVelocity ( jumpTarget . linearVelocity , jumpDescriptor , getActualLimiter ( ) . getMaxLinearSpeed ( ) ) ; this . isJumpAchievable = airborneTime >= 0 ; return jumpTarget ; } | Works out the trajectory calculation . |
25,352 | public Jump < T > setJumpDescriptor ( JumpDescriptor < T > jumpDescriptor ) { this . jumpDescriptor = jumpDescriptor ; this . target = null ; this . isJumpAchievable = false ; return this ; } | Sets the jump descriptor to use . |
25,353 | public void run ( long timeToRun ) { frame ++ ; runList . size = 0 ; for ( int i = 0 ; i < schedulableRecords . size ; i ++ ) { SchedulableRecord record = schedulableRecords . get ( i ) ; if ( ( frame + record . phase ) % record . frequency == 0 ) runList . add ( record ) ; } long lastTime = TimeUtils . nanoTime ( ) ; int numToRun = runList . size ; for ( int i = 0 ; i < numToRun ; i ++ ) { long currentTime = TimeUtils . nanoTime ( ) ; timeToRun -= currentTime - lastTime ; long availableTime = timeToRun / ( numToRun - i ) ; runList . get ( i ) . schedulable . run ( availableTime ) ; lastTime = currentTime ; } } | Executes scheduled tasks based on their frequency and phase . This method must be called once per frame . |
25,354 | public Collision < T > set ( Collision < T > collision ) { this . point . set ( collision . point ) ; this . normal . set ( collision . normal ) ; return this ; } | Sets this collision from the given collision . |
25,355 | public Collision < T > set ( T point , T normal ) { this . point . set ( point ) ; this . normal . set ( normal ) ; return this ; } | Sets this collision from the given point and normal . |
25,356 | protected BehaviorTree < ? > retrieveArchetypeTree ( String treeReference ) { BehaviorTree < ? > archetypeTree = repository . get ( treeReference ) ; if ( archetypeTree == null ) { archetypeTree = parser . parse ( resolver . resolve ( treeReference ) , null ) ; registerArchetypeTree ( treeReference , archetypeTree ) ; } return archetypeTree ; } | Retrieves the archetype tree from the library . If the library doesn t contain the archetype tree it is loaded and added to the library . |
25,357 | public void disposeBehaviorTree ( String treeReference , BehaviorTree < ? > behaviorTree ) { if ( Task . TASK_CLONER != null ) { Task . TASK_CLONER . freeTask ( behaviorTree ) ; } } | Dispose behavior tree obtain by this library . |
25,358 | public boolean execute ( PathFinderRequest < N > request ) { request . executionFrames ++ ; while ( true ) { if ( DEBUG ) GdxAI . getLogger ( ) . debug ( TAG , "------" ) ; if ( request . status == PathFinderRequest . SEARCH_NEW ) { long currentTime = TimeUtils . nanoTime ( ) ; timeToRun -= currentTime - lastTime ; if ( timeToRun <= timeTolerance ) return false ; if ( DEBUG ) GdxAI . getLogger ( ) . debug ( TAG , "search begin" ) ; if ( ! request . initializeSearch ( timeToRun ) ) return false ; request . changeStatus ( PathFinderRequest . SEARCH_INITIALIZED ) ; lastTime = currentTime ; } if ( request . status == PathFinderRequest . SEARCH_INITIALIZED ) { long currentTime = TimeUtils . nanoTime ( ) ; timeToRun -= currentTime - lastTime ; if ( timeToRun <= timeTolerance ) return false ; if ( DEBUG ) GdxAI . getLogger ( ) . debug ( TAG , "search path" ) ; if ( ! request . search ( pathFinder , timeToRun ) ) return false ; request . changeStatus ( PathFinderRequest . SEARCH_DONE ) ; lastTime = currentTime ; } if ( request . status == PathFinderRequest . SEARCH_DONE ) { long currentTime = TimeUtils . nanoTime ( ) ; timeToRun -= currentTime - lastTime ; if ( timeToRun <= timeTolerance ) return false ; if ( DEBUG ) GdxAI . getLogger ( ) . debug ( TAG , "search end" ) ; if ( ! request . finalizeSearch ( timeToRun ) ) return false ; request . changeStatus ( PathFinderRequest . SEARCH_FINALIZED ) ; if ( server != null ) { MessageDispatcher dispatcher = request . dispatcher != null ? request . dispatcher : MessageManager . getInstance ( ) ; dispatcher . dispatchMessage ( server , request . client , request . responseMessageCode , request ) ; } lastTime = currentTime ; if ( request . statusChanged && request . status == PathFinderRequest . SEARCH_NEW ) { if ( DEBUG ) GdxAI . getLogger ( ) . debug ( TAG , "search renew" ) ; continue ; } } return true ; } } | Executes the given pathfinding request resuming it if needed . |
25,359 | public boolean revertToPreviousState ( ) { if ( stateStack . size == 0 ) { return false ; } S previousState = stateStack . pop ( ) ; changeState ( previousState , false ) ; return true ; } | Changes the Change state back to the previous state . That is the high - most state on the internal stack of previous states . |
25,360 | public FollowPath < T , P > setPath ( Path < T , P > path ) { this . path = path ; return this ; } | Sets the path followed by this behavior . |
25,361 | public int smoothPath ( SmoothableGraphPath < N , V > path ) { int inputPathLength = path . getCount ( ) ; if ( inputPathLength <= 2 ) return 0 ; if ( this . ray == null ) { V vec = path . getNodePosition ( 0 ) ; this . ray = new Ray < V > ( vec . cpy ( ) , vec . cpy ( ) ) ; } int outputIndex = 1 ; int inputIndex = 2 ; while ( inputIndex < inputPathLength ) { ray . start . set ( path . getNodePosition ( outputIndex - 1 ) ) ; ray . end . set ( path . getNodePosition ( inputIndex ) ) ; boolean collides = raycastCollisionDetector . collides ( ray ) ; if ( collides ) { path . swapNodes ( outputIndex , inputIndex - 1 ) ; outputIndex ++ ; } inputIndex ++ ; } path . swapNodes ( outputIndex , inputIndex - 1 ) ; path . truncatePath ( outputIndex + 1 ) ; return inputIndex - outputIndex - 1 ; } | Smoothes the given path in place . |
25,362 | public boolean smoothPath ( PathSmootherRequest < N , V > request , long timeToRun ) { long lastTime = TimeUtils . nanoTime ( ) ; SmoothableGraphPath < N , V > path = request . path ; int inputPathLength = path . getCount ( ) ; if ( inputPathLength <= 2 ) return true ; if ( request . isNew ) { request . isNew = false ; if ( this . ray == null ) { V vec = request . path . getNodePosition ( 0 ) ; this . ray = new Ray < V > ( vec . cpy ( ) , vec . cpy ( ) ) ; } request . outputIndex = 1 ; request . inputIndex = 2 ; } while ( request . inputIndex < inputPathLength ) { long currentTime = TimeUtils . nanoTime ( ) ; timeToRun -= currentTime - lastTime ; if ( timeToRun <= PathFinderQueue . TIME_TOLERANCE ) return false ; ray . start . set ( path . getNodePosition ( request . outputIndex - 1 ) ) ; ray . end . set ( path . getNodePosition ( request . inputIndex ) ) ; boolean collided = raycastCollisionDetector . collides ( ray ) ; if ( collided ) { path . swapNodes ( request . outputIndex , request . inputIndex - 1 ) ; request . outputIndex ++ ; } request . inputIndex ++ ; lastTime = currentTime ; } path . swapNodes ( request . outputIndex , request . inputIndex - 1 ) ; path . truncatePath ( request . outputIndex + 1 ) ; return true ; } | Smoothes in place the path specified by the given request possibly over multiple consecutive frames . |
25,363 | public Ray < T > set ( Ray < T > ray ) { start . set ( ray . start ) ; end . set ( ray . end ) ; return this ; } | Sets this ray from the given ray . |
25,364 | public Ray < T > set ( T start , T end ) { this . start . set ( start ) ; this . end . set ( end ) ; return this ; } | Sets this Ray from the given start and end points . |
25,365 | public void remove ( SteeringBehavior < T > behavior ) { for ( int i = 0 ; i < list . size ; i ++ ) { if ( list . get ( i ) . behavior == behavior ) { list . removeIndex ( i ) ; return ; } } } | Removes a steering behavior from the list . |
25,366 | public SteeringAcceleration < T > add ( SteeringAcceleration < T > steering ) { linear . add ( steering . linear ) ; angular += steering . angular ; return this ; } | Adds the given steering acceleration to this steering acceleration . |
25,367 | public SteeringAcceleration < T > mulAdd ( SteeringAcceleration < T > steering , float scalar ) { linear . mulAdd ( steering . linear , scalar ) ; angular += steering . angular * scalar ; return this ; } | First scale a supplied steering acceleration then add it to this steering acceleration . |
25,368 | public void addListener ( Telegraph listener , int msg ) { Array < Telegraph > listeners = msgListeners . get ( msg ) ; if ( listeners == null ) { listeners = new Array < Telegraph > ( false , 16 ) ; msgListeners . put ( msg , listeners ) ; } listeners . add ( listener ) ; Array < TelegramProvider > providers = msgProviders . get ( msg ) ; if ( providers != null ) { for ( int i = 0 , n = providers . size ; i < n ; i ++ ) { TelegramProvider provider = providers . get ( i ) ; Object info = provider . provideMessageInfo ( msg , listener ) ; if ( info != null ) { Telegraph sender = ClassReflection . isInstance ( Telegraph . class , provider ) ? ( Telegraph ) provider : null ; dispatchMessage ( 0 , sender , listener , msg , info , false ) ; } } } } | Registers a listener for the specified message code . Messages without an explicit receiver are broadcasted to all its registered listeners . |
25,369 | public SteeringAcceleration < T > calculateSteering ( SteeringAcceleration < T > steering ) { return isEnabled ( ) ? calculateRealSteering ( steering ) : steering . setZero ( ) ; } | If this behavior is enabled calculates the steering acceleration and writes it to the given steering output . If it is disabled the steering output is set to zero . |
25,370 | public void updateSlotAssignments ( ) { slotAssignmentStrategy . updateSlotAssignments ( slotAssignments ) ; pattern . setNumberOfSlots ( slotAssignmentStrategy . calculateNumberOfSlots ( slotAssignments ) ) ; if ( motionModerator != null ) motionModerator . calculateDriftOffset ( driftOffset , slotAssignments , pattern ) ; } | Updates the assignment of members to slots |
25,371 | public boolean changePattern ( FormationPattern < T > pattern ) { int occupiedSlots = slotAssignments . size ; if ( pattern . supportsSlots ( occupiedSlots ) ) { setPattern ( pattern ) ; updateSlotAssignments ( ) ; return true ; } return false ; } | Changes the pattern of this formation and updates slot assignments if the number of member is supported by the given pattern . |
25,372 | public boolean addMember ( FormationMember < T > member ) { int occupiedSlots = slotAssignments . size ; if ( pattern . supportsSlots ( occupiedSlots + 1 ) ) { slotAssignments . add ( new SlotAssignment < T > ( member , occupiedSlots ) ) ; updateSlotAssignments ( ) ; return true ; } return false ; } | Adds a new member to the first available slot and updates slot assignments if the number of member is supported by the current pattern . |
25,373 | public void removeMember ( FormationMember < T > member ) { int slot = findMemberSlot ( member ) ; if ( slot >= 0 ) { slotAssignmentStrategy . removeSlotAssignment ( slotAssignments , slot ) ; updateSlotAssignments ( ) ; } } | Removes a member from its slot and updates slot assignments . |
25,374 | public void updateSlots ( ) { Location < T > anchor = getAnchorPoint ( ) ; positionOffset . set ( anchor . getPosition ( ) ) ; float orientationOffset = anchor . getOrientation ( ) ; if ( motionModerator != null ) { positionOffset . sub ( driftOffset . getPosition ( ) ) ; orientationOffset -= driftOffset . getOrientation ( ) ; } orientationMatrix . idt ( ) . rotateRad ( anchor . getOrientation ( ) ) ; for ( int i = 0 ; i < slotAssignments . size ; i ++ ) { SlotAssignment < T > slotAssignment = slotAssignments . get ( i ) ; Location < T > relativeLoc = slotAssignment . member . getTargetLocation ( ) ; pattern . calculateSlotLocation ( relativeLoc , slotAssignment . slotNumber ) ; T relativeLocPosition = relativeLoc . getPosition ( ) ; if ( relativeLocPosition instanceof Vector2 ) ( ( Vector2 ) relativeLocPosition ) . mul ( orientationMatrix ) ; else if ( relativeLocPosition instanceof Vector3 ) ( ( Vector3 ) relativeLocPosition ) . mul ( orientationMatrix ) ; relativeLocPosition . add ( positionOffset ) ; relativeLoc . setOrientation ( relativeLoc . getOrientation ( ) + orientationOffset ) ; } if ( motionModerator != null ) { motionModerator . updateAnchorPoint ( anchor ) ; } } | Writes new slot locations to each member |
25,375 | private static boolean containsFloatingPointCharacters ( String value ) { for ( int i = 0 , n = value . length ( ) ; i < n ; i ++ ) { switch ( value . charAt ( i ) ) { case '.' : case 'E' : case 'e' : return true ; } } return false ; } | line 315 BehaviorTreeReader . rl |
25,376 | public boolean handleMessage ( Telegram telegram ) { if ( currentState != null && currentState . onMessage ( owner , telegram ) ) { return true ; } if ( globalState != null && globalState . onMessage ( owner , telegram ) ) { return true ; } return false ; } | Handles received telegrams . The telegram is first routed to the current state . If the current state does not deal with the message it s routed to the global state s message handler . |
25,377 | public boolean store ( T item ) { if ( size == items . length ) { if ( ! resizable ) return false ; resize ( Math . max ( 8 , ( int ) ( items . length * 1.75f ) ) ) ; } size ++ ; items [ tail ++ ] = item ; if ( tail == items . length ) tail = 0 ; return true ; } | Adds the given item to the tail of this circular buffer . |
25,378 | public void clear ( ) { final T [ ] items = this . items ; if ( tail > head ) { int i = head , n = tail ; do { items [ i ++ ] = null ; } while ( i < n ) ; } else if ( size > 0 ) { for ( int i = head , n = items . length ; i < n ; i ++ ) items [ i ] = null ; for ( int i = 0 , n = tail ; i < n ; i ++ ) items [ i ] = null ; } this . head = 0 ; this . tail = 0 ; this . size = 0 ; } | Removes all items from this circular buffer . |
25,379 | protected void resize ( int newCapacity ) { @ SuppressWarnings ( "unchecked" ) T [ ] newItems = ( T [ ] ) ArrayReflection . newInstance ( items . getClass ( ) . getComponentType ( ) , newCapacity ) ; if ( tail > head ) { System . arraycopy ( items , head , newItems , 0 , size ) ; } else if ( size > 0 ) { System . arraycopy ( items , head , newItems , 0 , items . length - head ) ; System . arraycopy ( items , 0 , newItems , items . length - head , tail ) ; } head = 0 ; tail = size ; items = newItems ; } | Creates a new backing array with the specified capacity containing the current items . |
25,380 | protected int addChildToTask ( Task < E > child ) { if ( this . rootTask != null ) throw new IllegalStateException ( "A behavior tree cannot have more than one root task" ) ; this . rootTask = child ; return 0 ; } | This method will add a child namely the root to this behavior tree . |
25,381 | public Location < T > calculateDriftOffset ( Location < T > centerOfMass , Array < SlotAssignment < T > > slotAssignments , FormationPattern < T > pattern ) { centerOfMass . getPosition ( ) . setZero ( ) ; float centerOfMassOrientation = 0 ; if ( tempLocation == null ) tempLocation = centerOfMass . newLocation ( ) ; T centerOfMassPos = centerOfMass . getPosition ( ) ; T tempLocationPos = tempLocation . getPosition ( ) ; float numberOfAssignments = slotAssignments . size ; for ( int i = 0 ; i < numberOfAssignments ; i ++ ) { pattern . calculateSlotLocation ( tempLocation , slotAssignments . get ( i ) . slotNumber ) ; centerOfMassPos . add ( tempLocationPos ) ; centerOfMassOrientation += tempLocation . getOrientation ( ) ; } centerOfMassPos . scl ( 1f / numberOfAssignments ) ; centerOfMassOrientation /= numberOfAssignments ; centerOfMass . setOrientation ( centerOfMassOrientation ) ; return centerOfMass ; } | Calculates the drift offset when members are in the given set of slots for the specified pattern . |
25,382 | static CliReceivedCommand consumeCommandLineInput ( ParseResult providedCommand , @ SuppressWarnings ( "SameParameterValue" ) Iterable < CliDeclaredOptionSpec > declaredOptions ) { assumeTrue ( providedCommand . hasSubcommand ( ) , "Command was empty, expected one of: " + Arrays . toString ( CliCommandType . values ( ) ) ) ; final ParseResult mailCommand = providedCommand . subcommand ( ) ; final CliCommandType matchedCommand = CliCommandType . valueOf ( mailCommand . commandSpec ( ) . name ( ) ) ; final Map < CliDeclaredOptionSpec , OptionSpec > matchedOptionsInOrderProvision = matchProvidedOptions ( declaredOptions , mailCommand . matchedOptions ( ) ) ; logParsedInput ( matchedCommand , matchedOptionsInOrderProvision ) ; List < CliReceivedOptionData > receivedOptions = new ArrayList < > ( ) ; for ( Entry < CliDeclaredOptionSpec , OptionSpec > cliOption : matchedOptionsInOrderProvision . entrySet ( ) ) { final Method sourceMethod = cliOption . getKey ( ) . getSourceMethod ( ) ; final int mandatoryParameters = MiscUtil . countMandatoryParameters ( sourceMethod ) ; final List < String > providedStringValues = cliOption . getValue ( ) . getValue ( ) ; assumeTrue ( providedStringValues . size ( ) >= mandatoryParameters , format ( "provided %s arguments, but need at least %s" , providedStringValues . size ( ) , mandatoryParameters ) ) ; assumeTrue ( providedStringValues . size ( ) <= sourceMethod . getParameterTypes ( ) . length , format ( "provided %s arguments, but need at most %s" , providedStringValues . size ( ) , sourceMethod . getParameterTypes ( ) . length ) ) ; receivedOptions . add ( new CliReceivedOptionData ( cliOption . getKey ( ) , convertProvidedOptionValues ( providedStringValues , sourceMethod ) ) ) ; LOGGER . debug ( "\tconverted option values: {}" , getLast ( receivedOptions ) . getProvidedOptionValues ( ) ) ; } return new CliReceivedCommand ( matchedCommand , receivedOptions ) ; } | we reach here when terminal input was value and no help was requested |
25,383 | public static String encodeText ( final String name ) { if ( name == null ) { return null ; } try { return MimeUtility . encodeText ( name ) ; } catch ( final UnsupportedEncodingException e ) { throw new IllegalArgumentException ( e . getMessage ( ) , e ) ; } } | To make sure email clients can interpret text properly we need to encode some values according to RFC - 2047 . |
25,384 | public static ParsedMimeMessageComponents parseMimeMessage ( final MimeMessage mimeMessage ) { final ParsedMimeMessageComponents parsedComponents = new ParsedMimeMessageComponents ( ) ; parsedComponents . messageId = parseMessageId ( mimeMessage ) ; parsedComponents . subject = parseSubject ( mimeMessage ) ; parsedComponents . toAddresses . addAll ( parseToAddresses ( mimeMessage ) ) ; parsedComponents . ccAddresses . addAll ( parseCcAddresses ( mimeMessage ) ) ; parsedComponents . bccAddresses . addAll ( parseBccAddresses ( mimeMessage ) ) ; parsedComponents . fromAddress = parseFromAddress ( mimeMessage ) ; parsedComponents . replyToAddresses = parseReplyToAddresses ( mimeMessage ) ; parseMimePartTree ( mimeMessage , parsedComponents ) ; moveInvalidEmbeddedResourcesToAttachments ( parsedComponents ) ; return parsedComponents ; } | Extracts the content of a MimeMessage recursively . |
25,385 | @ SuppressWarnings ( "WeakerAccess" ) public static boolean isMimeType ( final MimePart part , final String mimeType ) { try { final ContentType contentType = new ContentType ( retrieveDataHandler ( part ) . getContentType ( ) ) ; return contentType . match ( mimeType ) ; } catch ( final ParseException ex ) { return retrieveContentType ( part ) . equalsIgnoreCase ( mimeType ) ; } } | Checks whether the MimePart contains an object of the given mime type . |
25,386 | private static DataSource createDataSource ( final MimePart part ) { final DataHandler dataHandler = retrieveDataHandler ( part ) ; final DataSource dataSource = dataHandler . getDataSource ( ) ; final String contentType = parseBaseMimeType ( dataSource . getContentType ( ) ) ; final byte [ ] content = readContent ( retrieveInputStream ( dataSource ) ) ; final ByteArrayDataSource result = new ByteArrayDataSource ( content , contentType ) ; final String dataSourceName = parseDataSourceName ( part , dataSource ) ; result . setName ( dataSourceName ) ; return result ; } | Parses the MimePart to create a DataSource . |
25,387 | public static Map < Property , Object > loadProperties ( final String filename , final boolean addProperties ) { final InputStream input = ConfigLoader . class . getClassLoader ( ) . getResourceAsStream ( filename ) ; if ( input != null ) { return loadProperties ( input , addProperties ) ; } LOGGER . debug ( "Property file not found on classpath, skipping config file" ) ; return new HashMap < > ( ) ; } | Loads properties from property file on the classpath if provided . Calling this method only has effect on new Email and Mailer instances after this . |
25,388 | public static Map < Property , Object > loadProperties ( final Properties properties , final boolean addProperties ) { if ( ! addProperties ) { RESOLVED_PROPERTIES . clear ( ) ; } RESOLVED_PROPERTIES . putAll ( readProperties ( properties ) ) ; return unmodifiableMap ( RESOLVED_PROPERTIES ) ; } | Loads properties from another properties source in case you want to provide your own list . |
25,389 | static String determineResourceName ( final AttachmentResource attachmentResource , final boolean includeExtension ) { final String datasourceName = attachmentResource . getDataSource ( ) . getName ( ) ; String resourceName ; if ( ! valueNullOrEmpty ( attachmentResource . getName ( ) ) ) { resourceName = attachmentResource . getName ( ) ; } else if ( ! valueNullOrEmpty ( datasourceName ) ) { resourceName = datasourceName ; } else { resourceName = "resource" + UUID . randomUUID ( ) ; } if ( includeExtension && ! valueNullOrEmpty ( datasourceName ) ) { @ SuppressWarnings ( "UnnecessaryLocalVariable" ) final String possibleFilename = datasourceName ; if ( ! resourceName . contains ( "." ) && possibleFilename . contains ( "." ) ) { final String extension = possibleFilename . substring ( possibleFilename . lastIndexOf ( "." ) ) ; if ( ! resourceName . endsWith ( extension ) ) { resourceName += extension ; } } } else if ( ! includeExtension && resourceName . contains ( "." ) && resourceName . equals ( datasourceName ) ) { final String extension = resourceName . substring ( resourceName . lastIndexOf ( "." ) ) ; resourceName = resourceName . replace ( extension , "" ) ; } return resourceName ; } | Determines the right resource name and optionally attaches the correct extension to the name . |
25,390 | public String getEncoding ( ) { return ( this . dataSource instanceof EncodingAware ) ? ( ( EncodingAware ) this . dataSource ) . getEncoding ( ) : null ; } | Optimization to help Java Mail determine encoding for attachments . |
25,391 | static AsyncResponse executeAsync ( final String processName , final Runnable operation ) { return executeAsync ( newSingleThreadExecutor ( ) , processName , operation , true ) ; } | Executes using a single - execution ExecutorService which shutdown immediately after the thread finishes . |
25,392 | static AsyncResponse executeAsync ( final ExecutorService executorService , final String processName , final Runnable operation ) { return executeAsync ( executorService , processName , operation , false ) ; } | Executes using a the given ExecutorService which is left running after the thread finishes running . |
25,393 | private synchronized void checkShutDownRunningProcesses ( ) { smtpRequestsPhaser . arriveAndDeregister ( ) ; LOGGER . trace ( "SMTP request threads left: {}" , smtpRequestsPhaser . getUnarrivedParties ( ) ) ; if ( smtpRequestsPhaser . getUnarrivedParties ( ) == 0 ) { LOGGER . trace ( "all threads have finished processing" ) ; if ( needsAuthenticatedProxy ( ) && proxyServer . isRunning ( ) && ! proxyServer . isStopping ( ) ) { LOGGER . trace ( "stopping proxy bridge..." ) ; proxyServer . stop ( ) ; } if ( executor != null ) { executor . shutdown ( ) ; } } } | We need to keep a count of running threads in case a proxyserver is running or a connection pool needs to be shut down . |
25,394 | public boolean isNewSession ( ) { Session session = handlerInput . getRequestEnvelope ( ) . getSession ( ) ; if ( session == null ) { throw new IllegalArgumentException ( "The provided request doesn't contain a session" ) ; } return session . getNew ( ) ; } | Returns whether the request is a new session . |
25,395 | protected ResponseEnvelope invoke ( UnmarshalledRequest < RequestEnvelope > unmarshalledRequest , Object context ) { RequestEnvelope requestEnvelope = unmarshalledRequest . getUnmarshalledRequest ( ) ; JsonNode requestEnvelopeJson = unmarshalledRequest . getRequestJson ( ) ; if ( skillId != null && ! requestEnvelope . getContext ( ) . getSystem ( ) . getApplication ( ) . getApplicationId ( ) . equals ( skillId ) ) { throw new AskSdkException ( "AlexaSkill ID verification failed." ) ; } ServiceClientFactory serviceClientFactory = apiClient != null ? ServiceClientFactory . builder ( ) . withDefaultApiConfiguration ( getApiConfiguration ( requestEnvelope ) ) . build ( ) : null ; HandlerInput handlerInput = HandlerInput . builder ( ) . withRequestEnvelope ( requestEnvelope ) . withPersistenceAdapter ( persistenceAdapter ) . withContext ( context ) . withRequestEnvelopeJson ( requestEnvelopeJson ) . withServiceClientFactory ( serviceClientFactory ) . withTemplateFactory ( templateFactory ) . build ( ) ; Optional < Response > response = requestDispatcher . dispatch ( handlerInput ) ; return ResponseEnvelope . builder ( ) . withResponse ( response != null ? response . orElse ( null ) : null ) . withSessionAttributes ( requestEnvelope . getSession ( ) != null ? handlerInput . getAttributesManager ( ) . getSessionAttributes ( ) : null ) . withVersion ( SdkConstants . FORMAT_VERSION ) . withUserAgent ( UserAgentUtils . getUserAgent ( customUserAgent ) ) . build ( ) ; } | Invokes the dispatcher to handler the request envelope and construct the handler input |
25,396 | private X509Certificate retrieveAndVerifyCertificateChain ( final String signingCertificateChainUrl ) throws CertificateException { try ( InputStream in = proxy != null ? getAndVerifySigningCertificateChainUrl ( signingCertificateChainUrl ) . openConnection ( proxy ) . getInputStream ( ) : getAndVerifySigningCertificateChainUrl ( signingCertificateChainUrl ) . openConnection ( ) . getInputStream ( ) ) { CertificateFactory certificateFactory = CertificateFactory . getInstance ( ServletConstants . SIGNATURE_CERTIFICATE_TYPE ) ; @ SuppressWarnings ( "unchecked" ) Collection < X509Certificate > certificateChain = ( Collection < X509Certificate > ) certificateFactory . generateCertificates ( in ) ; X509Certificate signingCertificate = certificateChain . iterator ( ) . next ( ) ; signingCertificate . checkValidity ( ) ; TrustManagerFactory trustManagerFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustManagerFactory . init ( ( KeyStore ) null ) ; X509TrustManager x509TrustManager = null ; for ( TrustManager trustManager : trustManagerFactory . getTrustManagers ( ) ) { if ( trustManager instanceof X509TrustManager ) { x509TrustManager = ( X509TrustManager ) trustManager ; } } if ( x509TrustManager == null ) { throw new IllegalStateException ( "No X509 TrustManager available. Unable to check certificate chain" ) ; } else { x509TrustManager . checkServerTrusted ( certificateChain . toArray ( new X509Certificate [ certificateChain . size ( ) ] ) , ServletConstants . SIGNATURE_TYPE ) ; } if ( ! subjectAlernativeNameListContainsEchoSdkDomainName ( signingCertificate . getSubjectAlternativeNames ( ) ) ) { throw new CertificateException ( "The provided certificate is not valid for the Echo SDK" ) ; } return signingCertificate ; } catch ( KeyStoreException | IOException | NoSuchAlgorithmException ex ) { throw new CertificateException ( "Unable to verify certificate at URL: " + signingCertificateChainUrl , ex ) ; } } | Retrieves the certificate from the specified URL and confirms that the certificate is valid . |
25,397 | public static < T extends Request > Predicate < HandlerInput > requestType ( Class < T > requestType ) { return i -> requestType . isInstance ( i . getRequestEnvelope ( ) . getRequest ( ) ) ; } | Returns a predicate that returns to true if the incoming request is an instance of the given request class . |
25,398 | public String next ( ) { if ( hasNext ( ) ) { if ( enumerationSize == NULL_LOCALE_ENUMERATION_SIZE ) { cursor ++ ; return templateName ; } final String language = matcher . group ( 1 ) ; final String country = matcher . group ( 2 ) ; switch ( cursor ) { case 0 : cursor ++ ; return templateName + FILE_SEPARATOR + language + FILE_SEPARATOR + country ; case 1 : cursor ++ ; return templateName + FILE_SEPARATOR + language + UNDERSCORE + country ; case 2 : cursor ++ ; return templateName + FILE_SEPARATOR + language ; case 3 : cursor ++ ; return templateName + UNDERSCORE + language + UNDERSCORE + country ; case 4 : cursor ++ ; return templateName + UNDERSCORE + language ; case 5 : cursor ++ ; return templateName ; } } String message = "No next available template name combination." ; LOGGER . error ( message ) ; throw new IllegalStateException ( message ) ; } | Generate the next combination of template name and return . |
25,399 | public void setSessionAttributes ( Map < String , Object > sessionAttributes ) { if ( requestEnvelope . getSession ( ) == null ) { throw new IllegalStateException ( "Attempting to set session attributes for out of session request" ) ; } this . sessionAttributes = sessionAttributes ; } | Sets session attributes replacing any existing attributes already present in the session . An exception is thrown if this method is called while processing an out of session request . Use this method when bulk replacing attributes is desired . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.