idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
13,700
protected Plugin parsePluginString ( String pluginString , String field ) throws MojoExecutionException { if ( pluginString != null ) { String [ ] pluginStrings = pluginString . split ( ":" ) ; if ( pluginStrings . length == 2 ) { Plugin plugin = new Plugin ( ) ; plugin . setGroupId ( StringUtils . strip ( pluginStrings [ 0 ] ) ) ; plugin . setArtifactId ( StringUtils . strip ( pluginStrings [ 1 ] ) ) ; return plugin ; } else { throw new MojoExecutionException ( "Invalid " + field + " string: " + pluginString ) ; } } else { throw new MojoExecutionException ( "Invalid " + field + " string: " + pluginString ) ; } }
Helper method to parse and inject a Plugin .
13,701
public Set < Plugin > getProfilePlugins ( MavenProject project ) { Set < Plugin > result = new HashSet < Plugin > ( ) ; @ SuppressWarnings ( "unchecked" ) List < Profile > profiles = project . getActiveProfiles ( ) ; if ( profiles != null && ! profiles . isEmpty ( ) ) { for ( Profile p : profiles ) { BuildBase b = p . getBuild ( ) ; if ( b != null ) { @ SuppressWarnings ( "unchecked" ) List < Plugin > plugins = b . getPlugins ( ) ; if ( plugins != null ) { result . addAll ( plugins ) ; } } } } return result ; }
Finds the plugins that are listed in active profiles .
13,702
protected Plugin findCurrentPlugin ( Plugin plugin , MavenProject project ) { Plugin found = null ; try { Model model = project . getModel ( ) ; @ SuppressWarnings ( "unchecked" ) Map < String , Plugin > plugins = model . getBuild ( ) . getPluginsAsMap ( ) ; found = plugins . get ( plugin . getKey ( ) ) ; } catch ( NullPointerException e ) { } if ( found == null ) { found = resolvePlugin ( plugin , project ) ; } return found ; }
Given a plugin this will retrieve the matching plugin artifact from the model .
13,703
protected Plugin resolvePlugin ( Plugin plugin , MavenProject project ) { @ SuppressWarnings ( "unchecked" ) List < ArtifactRepository > pluginRepositories = project . getPluginArtifactRepositories ( ) ; Artifact artifact = factory . createPluginArtifact ( plugin . getGroupId ( ) , plugin . getArtifactId ( ) , VersionRange . createFromVersion ( "LATEST" ) ) ; try { this . resolver . resolve ( artifact , pluginRepositories , this . local ) ; plugin . setVersion ( artifact . getVersion ( ) ) ; } catch ( ArtifactResolutionException e ) { } catch ( ArtifactNotFoundException e ) { } return plugin ; }
Resolve plugin .
13,704
protected Set < Plugin > getBoundPlugins ( LifecycleExecutor life , MavenProject project , String thePhases ) throws PluginNotFoundException , LifecycleExecutionException , IllegalAccessException { Set < Plugin > allPlugins = new HashSet < Plugin > ( ) ; String [ ] lifecyclePhases = thePhases . split ( "," ) ; for ( int i = 0 ; i < lifecyclePhases . length ; i ++ ) { String lifecyclePhase = lifecyclePhases [ i ] ; if ( StringUtils . isNotEmpty ( lifecyclePhase ) ) { try { Lifecycle lifecycle = getLifecycleForPhase ( lifecyclePhase ) ; allPlugins . addAll ( getAllPlugins ( project , lifecycle ) ) ; } catch ( BuildFailureException e ) { } } } return allPlugins ; }
Gets the plugins that are bound to the defined phases . This does not find plugins bound in the pom to a phase later than the plugin is executing .
13,705
protected boolean hasValidVersionSpecified ( EnforcerRuleHelper helper , Plugin source , List < PluginWrapper > pluginWrappers ) { boolean found = false ; boolean status = false ; for ( PluginWrapper plugin : pluginWrappers ) { if ( source . getArtifactId ( ) . equals ( plugin . getArtifactId ( ) ) && source . getGroupId ( ) . equals ( plugin . getGroupId ( ) ) ) { found = true ; String version = plugin . getVersion ( ) ; try { version = ( String ) helper . evaluate ( version ) ; } catch ( ExpressionEvaluationException e ) { return false ; } if ( StringUtils . isNotEmpty ( version ) && ! StringUtils . isWhitespace ( version ) ) { if ( banRelease && version . equals ( "RELEASE" ) ) { return false ; } if ( banLatest && version . equals ( "LATEST" ) ) { return false ; } if ( banSnapshots && isSnapshot ( version ) ) { return false ; } status = true ; if ( ! banRelease && ! banLatest && ! banSnapshots ) { break ; } } } } if ( ! found ) { log . debug ( "plugin " + source . getGroupId ( ) + ":" + source . getArtifactId ( ) + " not found" ) ; } return status ; }
Checks for valid version specified .
13,706
protected boolean isSnapshot ( String baseVersion ) { if ( banTimestamps ) { return Artifact . VERSION_FILE_PATTERN . matcher ( baseVersion ) . matches ( ) || baseVersion . endsWith ( Artifact . SNAPSHOT_VERSION ) ; } else { return baseVersion . endsWith ( Artifact . SNAPSHOT_VERSION ) ; } }
Checks if is snapshot .
13,707
@ SuppressWarnings ( "unchecked" ) private Set < Plugin > getAllPlugins ( MavenProject project , Lifecycle lifecycle ) throws PluginNotFoundException , LifecycleExecutionException { log . debug ( "RequirePluginVersions.getAllPlugins:" ) ; Set < Plugin > plugins = new HashSet < Plugin > ( ) ; Map mappings = findMappingsForLifecycle ( project , lifecycle ) ; Iterator iter = mappings . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Entry entry = ( Entry ) iter . next ( ) ; log . debug ( " lifecycleMapping = " + entry . getKey ( ) ) ; String pluginsForLifecycle = ( String ) entry . getValue ( ) ; log . debug ( " plugins = " + pluginsForLifecycle ) ; if ( StringUtils . isNotEmpty ( pluginsForLifecycle ) ) { String pluginList [ ] = pluginsForLifecycle . split ( "," ) ; for ( String plugin : pluginList ) { plugin = StringUtils . strip ( plugin ) ; log . debug ( " plugin = " + plugin ) ; String tokens [ ] = plugin . split ( ":" ) ; log . debug ( " GAV = " + Arrays . asList ( tokens ) ) ; Plugin p = new Plugin ( ) ; p . setGroupId ( tokens [ 0 ] ) ; p . setArtifactId ( tokens [ 1 ] ) ; plugins . add ( p ) ; } } } List < String > mojos = findOptionalMojosForLifecycle ( project , lifecycle ) ; for ( String value : mojos ) { String tokens [ ] = value . split ( ":" ) ; Plugin plugin = new Plugin ( ) ; plugin . setGroupId ( tokens [ 0 ] ) ; plugin . setArtifactId ( tokens [ 1 ] ) ; plugins . add ( plugin ) ; } plugins . addAll ( project . getBuildPlugins ( ) ) ; return plugins ; }
Gets the all plugins .
13,708
public Map < String , Lifecycle > getPhaseToLifecycleMap ( ) throws LifecycleExecutionException { if ( phaseToLifecycleMap == null ) { phaseToLifecycleMap = new HashMap < String , Lifecycle > ( ) ; for ( Lifecycle lifecycle : lifecycles ) { @ SuppressWarnings ( "unchecked" ) List < String > phases = lifecycle . getPhases ( ) ; for ( String phase : phases ) { if ( phaseToLifecycleMap . containsKey ( phase ) ) { Lifecycle prevLifecycle = ( Lifecycle ) phaseToLifecycleMap . get ( phase ) ; throw new LifecycleExecutionException ( "Phase '" + phase + "' is defined in more than one lifecycle: '" + lifecycle . getId ( ) + "' and '" + prevLifecycle . getId ( ) + "'" ) ; } else { phaseToLifecycleMap . put ( phase , lifecycle ) ; } } } } return phaseToLifecycleMap ; }
Gets the phase to lifecycle map .
13,709
private Lifecycle getLifecycleForPhase ( String phase ) throws BuildFailureException , LifecycleExecutionException { Lifecycle lifecycle = ( Lifecycle ) getPhaseToLifecycleMap ( ) . get ( phase ) ; if ( lifecycle == null ) { throw new BuildFailureException ( "Unable to find lifecycle for phase '" + phase + "'" ) ; } return lifecycle ; }
Gets the lifecycle for phase .
13,710
private Map findMappingsForLifecycle ( MavenProject project , Lifecycle lifecycle ) throws LifecycleExecutionException , PluginNotFoundException { String packaging = project . getPackaging ( ) ; Map mappings = null ; LifecycleMapping m = ( LifecycleMapping ) findExtension ( project , LifecycleMapping . ROLE , packaging , session . getSettings ( ) , session . getLocalRepository ( ) ) ; if ( m != null ) { mappings = m . getPhases ( lifecycle . getId ( ) ) ; } Map defaultMappings = lifecycle . getDefaultPhases ( ) ; if ( mappings == null ) { try { m = ( LifecycleMapping ) session . lookup ( LifecycleMapping . ROLE , packaging ) ; mappings = m . getPhases ( lifecycle . getId ( ) ) ; } catch ( ComponentLookupException e ) { if ( defaultMappings == null ) { throw new LifecycleExecutionException ( "Cannot find lifecycle mapping for packaging: \'" + packaging + "\'." , e ) ; } } } if ( mappings == null ) { if ( defaultMappings == null ) { throw new LifecycleExecutionException ( "Cannot find lifecycle mapping for packaging: \'" + packaging + "\', and there is no default" ) ; } else { mappings = defaultMappings ; } } return mappings ; }
Find mappings for lifecycle .
13,711
@ SuppressWarnings ( "unchecked" ) private List < String > findOptionalMojosForLifecycle ( MavenProject project , Lifecycle lifecycle ) throws LifecycleExecutionException , PluginNotFoundException { String packaging = project . getPackaging ( ) ; List < String > optionalMojos = null ; LifecycleMapping m = ( LifecycleMapping ) findExtension ( project , LifecycleMapping . ROLE , packaging , session . getSettings ( ) , session . getLocalRepository ( ) ) ; if ( m != null ) { optionalMojos = m . getOptionalMojos ( lifecycle . getId ( ) ) ; } if ( optionalMojos == null ) { try { m = ( LifecycleMapping ) session . lookup ( LifecycleMapping . ROLE , packaging ) ; optionalMojos = m . getOptionalMojos ( lifecycle . getId ( ) ) ; } catch ( ComponentLookupException e ) { log . debug ( "Error looking up lifecycle mapping to retrieve optional mojos. Lifecycle ID: " + lifecycle . getId ( ) + ". Error: " + e . getMessage ( ) , e ) ; } } if ( optionalMojos == null ) { optionalMojos = Collections . emptyList ( ) ; } return optionalMojos ; }
Find optional mojos for lifecycle .
13,712
private Object findExtension ( MavenProject project , String role , String roleHint , Settings settings , ArtifactRepository localRepository ) throws LifecycleExecutionException , PluginNotFoundException { Object pluginComponent = null ; @ SuppressWarnings ( "unchecked" ) List < Plugin > buildPlugins = project . getBuildPlugins ( ) ; for ( Plugin plugin : buildPlugins ) { if ( plugin . isExtensions ( ) ) { verifyPlugin ( plugin , project , settings , localRepository ) ; try { pluginComponent = pluginManager . getPluginComponent ( plugin , role , roleHint ) ; if ( pluginComponent != null ) { break ; } } catch ( ComponentLookupException e ) { log . debug ( "Unable to find the lifecycle component in the extension" , e ) ; } catch ( PluginManagerException e ) { throw new LifecycleExecutionException ( "Error getting extensions from the plugin '" + plugin . getKey ( ) + "': " + e . getMessage ( ) , e ) ; } } } return pluginComponent ; }
Find extension .
13,713
private PluginDescriptor verifyPlugin ( Plugin plugin , MavenProject project , Settings settings , ArtifactRepository localRepository ) throws LifecycleExecutionException , PluginNotFoundException { PluginDescriptor pluginDescriptor ; try { pluginDescriptor = pluginManager . verifyPlugin ( plugin , project , settings , localRepository ) ; } catch ( PluginManagerException e ) { throw new LifecycleExecutionException ( "Internal error in the plugin manager getting plugin '" + plugin . getKey ( ) + "': " + e . getMessage ( ) , e ) ; } catch ( PluginVersionResolutionException e ) { throw new LifecycleExecutionException ( e . getMessage ( ) , e ) ; } catch ( InvalidVersionSpecificationException e ) { throw new LifecycleExecutionException ( e . getMessage ( ) , e ) ; } catch ( InvalidPluginException e ) { throw new LifecycleExecutionException ( e . getMessage ( ) , e ) ; } catch ( ArtifactNotFoundException e ) { throw new LifecycleExecutionException ( e . getMessage ( ) , e ) ; } catch ( ArtifactResolutionException e ) { throw new LifecycleExecutionException ( e . getMessage ( ) , e ) ; } catch ( PluginVersionNotFoundException e ) { throw new LifecycleExecutionException ( e . getMessage ( ) , e ) ; } return pluginDescriptor ; }
Verify plugin .
13,714
protected List < PluginWrapper > getAllPluginEntries ( MavenProject project ) throws ArtifactResolutionException , ArtifactNotFoundException , IOException , XmlPullParserException { List < PluginWrapper > plugins = new ArrayList < PluginWrapper > ( ) ; String pomName = null ; try { pomName = project . getFile ( ) . getName ( ) ; } catch ( Exception e ) { pomName = "pom.xml" ; } List < Model > models = utils . getModelsRecursively ( project . getGroupId ( ) , project . getArtifactId ( ) , project . getVersion ( ) , new File ( project . getBasedir ( ) , pomName ) ) ; for ( Model model : models ) { try { List < Plugin > modelPlugins = model . getBuild ( ) . getPlugins ( ) ; plugins . addAll ( PluginWrapper . addAll ( utils . resolvePlugins ( modelPlugins ) , model . getId ( ) + ".build.plugins" ) ) ; } catch ( NullPointerException e ) { } try { List < ReportPlugin > modelReportPlugins = model . getReporting ( ) . getPlugins ( ) ; plugins . addAll ( PluginWrapper . addAll ( utils . resolveReportPlugins ( modelReportPlugins ) , model . getId ( ) + ".reporting" ) ) ; } catch ( NullPointerException e ) { } try { List < Plugin > modelPlugins = model . getBuild ( ) . getPluginManagement ( ) . getPlugins ( ) ; plugins . addAll ( PluginWrapper . addAll ( utils . resolvePlugins ( modelPlugins ) , model . getId ( ) + ".build.pluginManagement.plugins" ) ) ; } catch ( NullPointerException e ) { } @ SuppressWarnings ( "unchecked" ) List < Profile > profiles = model . getProfiles ( ) ; for ( Profile profile : profiles ) { try { List < Plugin > modelPlugins = profile . getBuild ( ) . getPlugins ( ) ; plugins . addAll ( PluginWrapper . addAll ( utils . resolvePlugins ( modelPlugins ) , model . getId ( ) + ".profiles.profile[" + profile . getId ( ) + "].build.plugins" ) ) ; } catch ( NullPointerException e ) { } try { List < ReportPlugin > modelReportPlugins = profile . getReporting ( ) . getPlugins ( ) ; plugins . addAll ( PluginWrapper . addAll ( utils . resolveReportPlugins ( modelReportPlugins ) , model . getId ( ) + "profile[" + profile . getId ( ) + "].reporting.plugins" ) ) ; } catch ( NullPointerException e ) { } try { List < Plugin > modelPlugins = profile . getBuild ( ) . getPluginManagement ( ) . getPlugins ( ) ; plugins . addAll ( PluginWrapper . addAll ( utils . resolvePlugins ( modelPlugins ) , model . getId ( ) + "profile[" + profile . getId ( ) + "].build.pluginManagement.plugins" ) ) ; } catch ( NullPointerException e ) { } } } return plugins ; }
Gets all plugin entries in build . plugins build . pluginManagement . plugins profile . build . plugins reporting and profile . reporting in this project and all parents
13,715
protected void init ( String directory , InfoLocationOptions option ) { if ( this . valOption ( ) == null ) { this . errors . addError ( "constructor(init) - no validation option set" ) ; return ; } try { if ( directory != null ) { switch ( option ) { case FILESYSTEM_ONLY : if ( this . tryFS ( directory ) == false ) { if ( this . tryCP ( directory ) == false ) { this . errors . addError ( "constructor(init) - could not find directory <" + directory + ">, tried file system" ) ; } } break ; case CLASSPATH_ONLY : if ( this . tryCP ( directory ) == false ) { if ( this . tryCP ( directory ) == false ) { this . errors . addError ( "constructor(init) - could not find directory <" + directory + ">>, tried using class path" ) ; } } break ; case TRY_FS_THEN_CLASSPATH : if ( this . tryFS ( directory ) == false ) { this . errors . clearErrorMessages ( ) ; ; if ( this . tryCP ( directory ) == false ) { this . errors . addError ( "constructor(init) - could not find directory <" + directory + ">, tried file system then using class path" ) ; } } break ; case TRY_CLASSPATH_THEN_FS : if ( this . tryCP ( directory ) == false ) { this . errors . clearErrorMessages ( ) ; ; if ( this . tryFS ( directory ) == false ) { this . errors . addError ( "constructor(init) - could not find directory <" + directory + ">, tried using class path then file system" ) ; } } break ; default : this . errors . addError ( "constructor(init) - unknown location option <" + option + "> for directories" ) ; } } } catch ( Exception ex ) { this . errors . addError ( "init() - catched unpredicted exception: " + ex . getMessage ( ) ) ; } }
Initialize the directory info object with any parameters presented by the constructors .
13,716
protected final boolean tryFS ( String directory ) { String path = directory ; File file = new File ( path ) ; if ( this . testDirectory ( file ) == true ) { try { this . url = file . toURI ( ) . toURL ( ) ; this . file = file ; this . fullDirectoryName = FilenameUtils . getPath ( file . getAbsolutePath ( ) ) ; this . setRootPath = directory ; return true ; } catch ( MalformedURLException e ) { this . errors . addError ( "init() - malformed URL for file with name " + this . file . getAbsolutePath ( ) + " and message: " + e . getMessage ( ) ) ; } } return false ; }
Try to locate a directory in the file system .
13,717
protected final boolean tryCP ( String directory ) { String [ ] cp = StringUtils . split ( System . getProperty ( "java.class.path" ) , File . pathSeparatorChar ) ; for ( String s : cp ) { if ( ! StringUtils . endsWith ( s , ".jar" ) && ! StringUtils . startsWith ( s , "/" ) ) { String path = s + File . separator + directory ; File file = new File ( path ) ; if ( this . testDirectory ( file ) == true ) { try { this . url = file . toURI ( ) . toURL ( ) ; this . file = file ; this . fullDirectoryName = FilenameUtils . getPath ( file . getAbsolutePath ( ) ) ; this . setRootPath = directory ; return true ; } catch ( MalformedURLException e ) { this . errors . addError ( "init() - malformed URL for file with name " + this . file . getAbsolutePath ( ) + " and message: " + e . getMessage ( ) ) ; } } } } return false ; }
Try to locate a directory using any directory given in the class path as set - root .
13,718
public Operation getOperation ( String id ) { for ( Iterator < Operation > it = operations . iterator ( ) ; it . hasNext ( ) ; ) { Operation oper = it . next ( ) ; if ( oper . getId ( ) . compareTo ( id ) == 0 ) { return oper ; } } return null ; }
Returns the operation of the given id or a new default operation . If no operation was found null is returned .
13,719
public Operations getOperationsFor ( final PMContext ctx , Object instance , Operation operation ) throws PMException { final Operations result = new Operations ( ) ; final List < Operation > r = new ArrayList < Operation > ( ) ; if ( operation != null ) { for ( Operation op : getOperations ( ) ) { if ( op . isDisplayed ( operation . getId ( ) ) && op . isEnabled ( ) && ! op . equals ( operation ) ) { if ( op . getCondition ( ) == null || op . getCondition ( ) . check ( ctx , instance , op , operation . getId ( ) ) ) { if ( instance != null || OperationScope . GENERAL . is ( op . getScope ( ) ) || OperationScope . SELECTED . is ( op . getScope ( ) ) ) { r . add ( op ) ; } } } } } result . setOperations ( r ) ; return result ; }
Returns the Operations for a given operation . That is the operations that are different to the given one enabled and visible in it .
13,720
public Operations getOperationsForScope ( OperationScope ... scopes ) { final Operations result = new Operations ( ) ; final List < Operation > r = new ArrayList < Operation > ( ) ; if ( getOperations ( ) != null ) { for ( Operation op : getOperations ( ) ) { if ( op . getScope ( ) != null ) { String s = op . getScope ( ) . trim ( ) ; for ( int i = 0 ; i < scopes . length ; i ++ ) { OperationScope scope = scopes [ i ] ; if ( scope . is ( s ) ) { r . add ( op ) ; break ; } } } } result . setOperations ( r ) ; } return result ; }
Returns an Operations object for the given scope
13,721
public boolean incrementToken ( ) throws IOException { if ( ! input . incrementToken ( ) ) { return false ; } final String t = myTermAttribute . toString ( ) ; if ( t != null && t . length ( ) != 0 ) { try { myTermAttribute . setEmpty ( ) . append ( ISO639Converter . convert ( t ) ) ; } catch ( final IllegalArgumentException details ) { if ( LOGGER . isWarnEnabled ( ) ) { LOGGER . warn ( details . getMessage ( ) , details ) ; } } } return true ; }
Increments and processes tokens in the ISO - 639 code stream .
13,722
public static < T > PowerSet < T > getPowerSet ( Set < T > hashSet ) { Validate . notNull ( hashSet ) ; if ( hashSet . isEmpty ( ) ) throw new IllegalArgumentException ( "set size 0" ) ; HashList < T > hashList = new HashList < > ( hashSet ) ; PowerSet < T > result = new PowerSet < > ( hashList . size ( ) ) ; for ( int i = 0 ; i < Math . pow ( 2 , hashList . size ( ) ) ; i ++ ) { int setSize = Integer . bitCount ( i ) ; HashSet < T > newList = new HashSet < > ( setSize ) ; result . get ( setSize ) . add ( newList ) ; for ( int j = 0 ; j < hashList . size ( ) ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) { newList . add ( hashList . get ( j ) ) ; } } } return result ; }
Generates a new Powerset out of the given set .
13,723
public static < T > Set < T > union ( Collection < Set < T > > sets ) { Set < T > result = new HashSet < > ( ) ; if ( sets . isEmpty ( ) ) { return result ; } Iterator < Set < T > > iter = sets . iterator ( ) ; result . addAll ( iter . next ( ) ) ; if ( sets . size ( ) == 1 ) { return result ; } while ( iter . hasNext ( ) ) { result . addAll ( iter . next ( ) ) ; } return result ; }
Determines the union of a collection of sets .
13,724
public static boolean existPairwiseIntersections ( Collection < Set < String > > sets ) { List < List < Set < String > > > setPairs = ListUtils . getKElementaryLists ( new ArrayList < Set < String > > ( sets ) , 2 ) ; for ( Iterator < List < Set < String > > > iter = setPairs . iterator ( ) ; iter . hasNext ( ) ; ) { Set < String > intersection = SetUtils . intersection ( iter . next ( ) ) ; if ( ! intersection . isEmpty ( ) ) { return true ; } } return false ; }
Checks if any two of the given sets intersect .
13,725
private RedBlackTreeNode < Key , Value > put ( RedBlackTreeNode < Key , Value > h , Key key , Value value ) { if ( h == null ) return new RedBlackTreeNode < > ( key , value , RED , 1 ) ; int cmp = key . compareTo ( h . getKey ( ) ) ; if ( cmp < 0 ) h . setLeft ( put ( h . getLeft ( ) , key , value ) ) ; else if ( cmp > 0 ) h . setRight ( put ( h . getRight ( ) , key , value ) ) ; else h . setValue ( value ) ; if ( isRed ( h . getRight ( ) ) && ! isRed ( h . getLeft ( ) ) ) h = rotateLeft ( h ) ; if ( isRed ( h . getLeft ( ) ) && isRed ( h . getLeft ( ) . getLeft ( ) ) ) h = rotateRight ( h ) ; if ( isRed ( h . getLeft ( ) ) && isRed ( h . getRight ( ) ) ) flipColors ( h ) ; h . setSize ( size ( h . getLeft ( ) ) + size ( h . getRight ( ) ) + 1 ) ; return h ; }
insert the key - value pair in the subtree rooted at h
13,726
public void deleteMax ( ) { if ( isEmpty ( ) ) throw new NoSuchElementException ( "BST underflow" ) ; if ( ! isRed ( root . getLeft ( ) ) && ! isRed ( root . getRight ( ) ) ) root . setColor ( RED ) ; root = deleteMax ( root ) ; if ( ! isEmpty ( ) ) { root . setParent ( null ) ; root . setColor ( BLACK ) ; } }
Removes the largest key and associated value from the symbol table .
13,727
private RedBlackTreeNode < Key , Value > delete ( RedBlackTreeNode < Key , Value > h , Key key ) { if ( key . compareTo ( h . getKey ( ) ) < 0 ) { if ( ! isRed ( h . getLeft ( ) ) && ! isRed ( h . getLeft ( ) . getLeft ( ) ) ) h = moveRedLeft ( h ) ; h . setLeft ( delete ( h . getLeft ( ) , key ) ) ; } else { if ( isRed ( h . getLeft ( ) ) ) h = rotateRight ( h ) ; if ( key . compareTo ( h . getKey ( ) ) == 0 && ( h . getRight ( ) == null ) ) return null ; if ( ! isRed ( h . getRight ( ) ) && ! isRed ( h . getRight ( ) . getLeft ( ) ) ) h = moveRedRight ( h ) ; if ( key . compareTo ( h . getKey ( ) ) == 0 ) { RedBlackTreeNode < Key , Value > x = min ( h . getRight ( ) ) ; h . setKey ( x . getKey ( ) ) ; h . setValue ( x . getValue ( ) ) ; h . setRight ( deleteMin ( h . getRight ( ) ) ) ; } else h . setRight ( delete ( h . getRight ( ) , key ) ) ; } return balance ( h ) ; }
delete the key - value pair with the given key rooted at h
13,728
private RedBlackTreeNode < Key , Value > max ( RedBlackTreeNode < Key , Value > x ) { if ( x . getRight ( ) == null ) return x ; else return max ( x . getRight ( ) ) ; }
the largest key in the subtree rooted at x ; null if no such key
13,729
public Key select ( int k ) { if ( k < 0 || k >= size ( root ) ) throw new IllegalArgumentException ( ) ; RedBlackTreeNode < Key , Value > x = select ( root , k ) ; return x . getKey ( ) ; }
Return the kth smallest key in the symbol table .
13,730
private RedBlackTreeNode < Key , Value > select ( RedBlackTreeNode < Key , Value > x , int k ) { int t = size ( x . getLeft ( ) ) ; if ( t > k ) return select ( x . getLeft ( ) , k ) ; else if ( t < k ) return select ( x . getRight ( ) , k - t - 1 ) ; else return x ; }
the key of rank k in the subtree rooted at x
13,731
private int rank ( Key key , RedBlackTreeNode < Key , Value > x ) { if ( x == null ) return 0 ; int cmp = key . compareTo ( x . getKey ( ) ) ; if ( cmp < 0 ) return rank ( key , x . getLeft ( ) ) ; else if ( cmp > 0 ) return 1 + size ( x . getLeft ( ) ) + rank ( key , x . getRight ( ) ) ; else return size ( x . getLeft ( ) ) ; }
number of keys less than key in the subtree rooted at x
13,732
private void keys ( RedBlackTreeNode < Key , Value > x , Queue < Key > queue , Key lo , Key hi ) { if ( x == null ) return ; int cmplo = lo . compareTo ( x . getKey ( ) ) ; int cmphi = hi . compareTo ( x . getKey ( ) ) ; if ( cmplo < 0 ) keys ( x . getLeft ( ) , queue , lo , hi ) ; if ( cmplo <= 0 && cmphi >= 0 ) queue . offer ( x . getKey ( ) ) ; if ( cmphi > 0 ) keys ( x . getRight ( ) , queue , lo , hi ) ; }
to the queue
13,733
public int size ( Key low , Key high ) { if ( low . compareTo ( high ) > 0 ) return 0 ; if ( contains ( high ) ) return rank ( high ) - rank ( low ) + 1 ; else return rank ( high ) - rank ( low ) ; }
Returns the number of keys in the symbol table in the given range .
13,734
public void add ( ILocalizableString name , Object object ) { objects . add ( new Pair < > ( name , object ) ) ; }
Add an object .
13,735
public void doneOnSubTasksDone ( ) { if ( jp != null ) return ; synchronized ( tasks ) { jp = new JoinPoint < > ( ) ; for ( SubTask task : tasks ) jp . addToJoinDoNotCancel ( task . getProgress ( ) . getSynch ( ) ) ; } jp . listenInline ( new Runnable ( ) { public void run ( ) { if ( jp . hasError ( ) ) error ( jp . getError ( ) ) ; else done ( ) ; } } ) ; jp . start ( ) ; }
Automatically call the done or error method of this WorkProgress once all current sub - tasks are done .
13,736
public static int cs_tdfs ( int j , int k , int [ ] head , int head_offset , int [ ] next , int next_offset , int [ ] post , int post_offset , int [ ] stack , int stack_offset ) { int i , p , top = 0 ; if ( head == null || next == null || post == null || stack == null ) return ( - 1 ) ; stack [ stack_offset + 0 ] = j ; while ( top >= 0 ) { p = stack [ stack_offset + top ] ; i = head [ head_offset + p ] ; if ( i == - 1 ) { top -- ; post [ post_offset + ( k ++ ) ] = p ; } else { head [ head_offset + p ] = next [ next_offset + i ] ; stack [ stack_offset + ( ++ top ) ] = i ; } } return ( k ) ; }
Depth - first search and postorder of a tree rooted at node j
13,737
public static File getExecutionPath ( ) throws OSException { try { return new File ( OSUtils . class . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) . toURI ( ) . getPath ( ) ) ; } catch ( URISyntaxException ex ) { throw new OSException ( ex ) ; } }
Returns the execution path to the direcory of the current Java application .
13,738
public void runCommand ( String [ ] command , GenericHandler < BufferedReader > inputHandler , GenericHandler < BufferedReader > errorHandler ) throws OSException { Validate . notNull ( command ) ; try { Process p = Runtime . getRuntime ( ) . exec ( command ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( p . getInputStream ( ) ) ) ; BufferedReader err = new BufferedReader ( new InputStreamReader ( p . getErrorStream ( ) ) ) ; if ( inputHandler != null ) { inputHandler . handle ( in ) ; } if ( errorHandler != null ) { errorHandler . handle ( err ) ; } in . close ( ) ; p . waitFor ( ) ; p . exitValue ( ) ; } catch ( Exception ex ) { throw new OSException ( ex . getMessage ( ) , ex ) ; } }
Runs a command on the operating system .
13,739
protected static String sanitizeFileExtension ( String fileTypeExtension ) throws OSException { String newFileTypeExtension = fileTypeExtension . replaceAll ( "\\s+" , "" ) ; newFileTypeExtension = newFileTypeExtension . toLowerCase ( ) ; String [ ] splittedFileExtension = newFileTypeExtension . split ( "\\." ) ; if ( newFileTypeExtension . length ( ) == 0 || splittedFileExtension . length == 0 ) { throw new OSException ( "The given file extension \"" + fileTypeExtension + "\" is too short." ) ; } newFileTypeExtension = "." + splittedFileExtension [ splittedFileExtension . length - 1 ] ; return newFileTypeExtension ; }
Sanitizes file extension such that it can be used in the Windows Registry .
13,740
public String getProperty ( Property property , String defaultValue ) { String value = null ; List < String > systemProps = property . getSystemPropertyNames ( ) ; if ( systemProps != null ) { for ( String sp : systemProps ) { value = System . getProperty ( sp ) ; if ( value != null ) { break ; } } } if ( value == null ) { List < String > envVars = property . getEnvironmentVariableNames ( ) ; if ( envVars != null ) { for ( String ev : envVars ) { value = System . getenv ( ev ) ; if ( value != null ) { break ; } } } } if ( value == null && property . getPropertyName ( ) != null ) { value = implementationConfiguration . get ( property . getPropertyName ( ) ) ; } return value == null ? defaultValue : value ; }
Returns the value of the property .
13,741
public Configuration prefixedWith ( String ... prefixes ) { if ( prefixes == null || prefixes . length == 0 ) { return this ; } Map < String , String > filteredConfig = implementationConfiguration . entrySet ( ) . stream ( ) . filter ( e -> Arrays . stream ( prefixes ) . anyMatch ( p -> e . getKey ( ) . startsWith ( p ) ) ) . collect ( toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; return new Configuration ( feedIdStrategy , resultFilter , filteredConfig ) ; }
Filters out all the configuration entries whose keys don t start with any of the white - listed prefixes
13,742
private < T extends Property > Map < String , String > getOverriddenImplementationConfiguration ( Collection < T > overridableProperties ) { Map < String , String > ret = new HashMap < > ( ) ; overridableProperties . forEach ( p -> { String val = getProperty ( p , null ) ; if ( val != null ) { ret . put ( p . getPropertyName ( ) , val ) ; } } ) ; implementationConfiguration . forEach ( ret :: putIfAbsent ) ; return ret ; }
this hoop is needed so that we can type - check the T through the stream manipulations
13,743
static public X509Certificate duplicate ( X509Certificate cert ) { X500Principal prince = cert . getSubjectX500Principal ( ) ; log . info ( "Principal={}." , prince . getName ( ) ) ; KeyPairGenerator kpg ; try { kpg = KeyPairGenerator . getInstance ( "RSA" ) ; } catch ( NoSuchAlgorithmException e1 ) { throw new UnsupportedOperationException ( "OGTE TODO!" , e1 ) ; } KeyPair keyPair = kpg . generateKeyPair ( ) ; AlgorithmId alg ; try { alg = new AlgorithmId ( new ObjectIdentifier ( cert . getSigAlgOID ( ) ) ) ; } catch ( IOException e1 ) { throw new UnsupportedOperationException ( "OGTE TODO!" , e1 ) ; } X509CertInfo info = new X509CertInfo ( ) ; try { info . set ( X509CertInfo . SUBJECT , new CertificateSubjectName ( new X500Name ( prince . getName ( ) ) ) ) ; info . set ( X509CertInfo . KEY , new CertificateX509Key ( keyPair . getPublic ( ) ) ) ; info . set ( X509CertInfo . VALIDITY , new CertificateValidity ( cert . getNotBefore ( ) , cert . getNotAfter ( ) ) ) ; info . set ( X509CertInfo . ISSUER , new CertificateIssuerName ( new X500Name ( prince . getName ( ) ) ) ) ; info . set ( X509CertInfo . ALGORITHM_ID , new CertificateAlgorithmId ( alg ) ) ; info . set ( X509CertInfo . SERIAL_NUMBER , new CertificateSerialNumber ( cert . getSerialNumber ( ) ) ) ; info . set ( X509CertInfo . VERSION , new CertificateVersion ( cert . getVersion ( ) - 1 ) ) ; } catch ( CertificateException | IOException e ) { throw new UnsupportedOperationException ( "OGTE TODO!" , e ) ; } log . info ( "Cert info={}." , info ) ; X509CertImpl newCert = new X509CertImpl ( info ) ; try { newCert . sign ( keyPair . getPrivate ( ) , alg . getName ( ) ) ; } catch ( InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException e ) { throw new UnsupportedOperationException ( "OGTE TODO!" , e ) ; } log . info ( "Returning new cert={}." , newCert ) ; return newCert ; }
Create a self - signed certificate that duplicates as many of the given cert s fields as possible .
13,744
private static void initialize ( ) { double lFlen = 1.0f / ( double ) SPLINE_LUTLEN ; double lScale = ( double ) SPLINE_QUANTSCALE ; for ( int i = 0 ; i < SPLINE_LUTLEN ; i ++ ) { double lX = ( ( double ) i ) * lFlen ; int lIdx = i << 2 ; double lCm1 = Math . floor ( 0.5 + lScale * ( - 0.5 * lX * lX * lX + 1.0 * lX * lX - 0.5 * lX ) ) ; double lC0 = Math . floor ( 0.5 + lScale * ( 1.5 * lX * lX * lX - 2.5 * lX * lX + 1.0 ) ) ; double lC1 = Math . floor ( 0.5 + lScale * ( - 1.5 * lX * lX * lX + 2.0 * lX * lX + 0.5 * lX ) ) ; double lC2 = Math . floor ( 0.5 + lScale * ( 0.5 * lX * lX * lX - 0.5 * lX * lX ) ) ; lut [ lIdx + 0 ] = ( int ) ( ( lCm1 < - lScale ) ? - lScale : ( ( lCm1 > lScale ) ? lScale : lCm1 ) ) ; lut [ lIdx + 1 ] = ( int ) ( ( lC0 < - lScale ) ? - lScale : ( ( lC0 > lScale ) ? lScale : lC0 ) ) ; lut [ lIdx + 2 ] = ( int ) ( ( lC1 < - lScale ) ? - lScale : ( ( lC1 > lScale ) ? lScale : lC1 ) ) ; lut [ lIdx + 3 ] = ( int ) ( ( lC2 < - lScale ) ? - lScale : ( ( lC2 > lScale ) ? lScale : lC2 ) ) ; int lSum = lut [ lIdx + 0 ] + lut [ lIdx + 1 ] + lut [ lIdx + 2 ] + lut [ lIdx + 3 ] ; if ( lSum != SPLINE_QUANTSCALE ) { int lMax = lIdx ; if ( lut [ lIdx + 1 ] > lut [ lMax ] ) lMax = lIdx + 1 ; if ( lut [ lIdx + 2 ] > lut [ lMax ] ) lMax = lIdx + 2 ; if ( lut [ lIdx + 3 ] > lut [ lMax ] ) lMax = lIdx + 3 ; lut [ lMax ] += ( SPLINE_QUANTSCALE - lSum ) ; } } }
Init the static params
13,745
public void free ( byte [ ] array ) { int len = array . length ; synchronized ( arraysBySize ) { if ( totalSize + len > maxTotalSize ) return ; Node < ArraysBySize > node = arraysBySize . get ( len ) ; if ( node == null ) { ArraysBySize arrays = new ArraysBySize ( ) ; arrays . arrays = new TurnArray < > ( len >= 128 * 1024 ? maxBuffersBySizeAbove128KB : maxBuffersBySizeUnder128KB ) ; arrays . arrays . add ( array ) ; arrays . lastCachedTime = System . currentTimeMillis ( ) ; arraysBySize . add ( len , arrays ) ; totalSize += len ; return ; } ArraysBySize arrays = node . getElement ( ) ; arrays . lastCachedTime = System . currentTimeMillis ( ) ; if ( arrays . arrays . isFull ( ) ) return ; totalSize += len ; arrays . arrays . add ( array ) ; } }
Put an array in the cache .
13,746
int getIndexOf ( final V value ) { Validate . notNull ( value , "Value required" ) ; Validate . validState ( getSize ( ) > 0 , "No data" ) ; return getData ( ) . indexOf ( value ) ; }
Returns the index of the first occurrence of the specified value in this controller or - 1 if this controller does not contain the value .
13,747
public V findChachedValueOf ( K key ) { for ( V value : selection ) { if ( getKeyOf ( value ) . equals ( key ) ) { return value ; } } for ( V value : getData ( ) ) { if ( getKeyOf ( value ) . equals ( key ) ) { return value ; } } return null ; }
Find value in cached data .
13,748
public void setSorting ( List < SortProperty > newSorting ) { Validate . notNull ( newSorting , "Sorting required" ) ; if ( ! sorting . equals ( newSorting ) ) { sorting . clear ( ) ; sorting . addAll ( newSorting ) ; selectionIndex = - 1 ; clearCache ( ) ; } }
Sets sorting does nothing if sorting will not change . Clears the cache but does not notify observers for data changes .
13,749
public PublishedEvent findByTransactionIdAndSequence ( final UUID transactionId , final int sequence ) { return repositoryService . uniqueMatch ( new QueryDefault < > ( PublishedEvent . class , "findByTransactionIdAndSequence" , "transactionId" , transactionId , "sequence" , sequence ) ) ; }
region > findByTransactionIdAndSequence
13,750
public List < PublishedEvent > findByTargetAndFromAndTo ( final Object publishedObject , final LocalDate from , final LocalDate to ) { final Bookmark bookmark = bookmarkService . bookmarkFor ( publishedObject ) ; return findByTargetAndFromAndTo ( bookmark , from , to ) ; }
region > findByTargetAndFromAndTo
13,751
public static String getOptionValue ( String [ ] args , String optionName ) { String opt = "-" + optionName + "=" ; for ( String arg : args ) { if ( arg . startsWith ( opt ) ) return arg . substring ( opt . length ( ) ) ; } return null ; }
Search for an argument - &lt ; option&gt ; = &lt ; value&gt ; where option is the given option name and return the value .
13,752
public boolean registerFileExtension ( String mimeTypeName , String fileTypeExtension , String application ) throws OSException { throw new UnsupportedOperationException ( "Not supported." ) ; }
Registers a new file extension .
13,753
public static TemporaryFiles get ( Application app ) { TemporaryFiles instance = app . getInstance ( TemporaryFiles . class ) ; if ( instance == null ) { File dir = null ; String path = app . getProperty ( Application . PROPERTY_TMP_DIRECTORY ) ; if ( path != null ) { dir = new File ( path ) ; if ( ! dir . exists ( ) ) if ( ! dir . mkdirs ( ) ) dir = null ; } if ( dir == null ) { path = app . getProperty ( "java.io.tmpdir" ) ; if ( path != null ) { dir = new File ( path ) ; if ( ! dir . exists ( ) ) if ( ! dir . mkdirs ( ) ) dir = null ; } } instance = new TemporaryFiles ( dir ) ; } return instance ; }
Get the instance for the given application .
13,754
public void setTemporaryDirectory ( File dir ) throws IOException { if ( dir != null ) { if ( ! dir . exists ( ) || ! dir . isDirectory ( ) ) if ( ! dir . mkdirs ( ) ) throw new IOException ( "Unable to create temporary directory: " + dir . getAbsolutePath ( ) ) ; } tempDir = dir ; }
Set the directory into which create temporary files .
13,755
public String getIdHash ( ) { if ( CurrentExecution_Type . featOkTst && ( ( CurrentExecution_Type ) jcasType ) . casFeat_idHash == null ) jcasType . jcas . throwFeatMissing ( "idHash" , "edu.cmu.lti.oaqa.framework.types.CurrentExecution" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( CurrentExecution_Type ) jcasType ) . casFeatCode_idHash ) ; }
getter for idHash - gets
13,756
public void setIdHash ( String v ) { if ( CurrentExecution_Type . featOkTst && ( ( CurrentExecution_Type ) jcasType ) . casFeat_idHash == null ) jcasType . jcas . throwFeatMissing ( "idHash" , "edu.cmu.lti.oaqa.framework.types.CurrentExecution" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( CurrentExecution_Type ) jcasType ) . casFeatCode_idHash , v ) ; }
setter for idHash - sets
13,757
private void validateArtifactInformation ( ) throws MojoExecutionException { Model model = generateModel ( ) ; ModelValidationResult result = modelValidator . validate ( model ) ; if ( result . getMessageCount ( ) > 0 ) { throw new MojoExecutionException ( "The artifact information is incomplete or not valid:\n" + result . render ( " " ) ) ; } }
Validates the user - supplied artifact information .
13,758
private Model generateModel ( ) { Model model = new Model ( ) ; model . setModelVersion ( "4.0.0" ) ; model . setGroupId ( groupId ) ; model . setArtifactId ( artifactId ) ; model . setVersion ( version ) ; model . setPackaging ( packaging ) ; model . setDescription ( "POM was created from specialsource-maven-plugin" ) ; return model ; }
Generates a minimal model from the user - supplied artifact information .
13,759
protected void installChecksums ( Collection metadataFiles ) throws MojoExecutionException { for ( Iterator it = metadataFiles . iterator ( ) ; it . hasNext ( ) ; ) { File metadataFile = ( File ) it . next ( ) ; installChecksums ( metadataFile ) ; } }
Installs the checksums for the specified metadata files .
13,760
private void installChecksum ( File originalFile , File installedFile , Digester digester , String ext ) throws MojoExecutionException { String checksum ; getLog ( ) . debug ( "Calculating " + digester . getAlgorithm ( ) + " checksum for " + originalFile ) ; try { checksum = digester . calc ( originalFile ) ; } catch ( DigesterException e ) { throw new MojoExecutionException ( "Failed to calculate " + digester . getAlgorithm ( ) + " checksum for " + originalFile , e ) ; } File checksumFile = new File ( installedFile . getAbsolutePath ( ) + ext ) ; getLog ( ) . debug ( "Installing checksum to " + checksumFile ) ; try { checksumFile . getParentFile ( ) . mkdirs ( ) ; FileUtils . fileWrite ( checksumFile . getAbsolutePath ( ) , "UTF-8" , checksum ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Failed to install checksum to " + checksumFile , e ) ; } }
Installs a checksum for the specified file .
13,761
public TSIGRecord generate ( Message m , byte [ ] b , int error , TSIGRecord old ) { Date timeSigned ; if ( error != Rcode . BADTIME ) timeSigned = new Date ( ) ; else timeSigned = old . getTimeSigned ( ) ; int fudge ; HMAC hmac = null ; if ( error == Rcode . NOERROR || error == Rcode . BADTIME ) hmac = new HMAC ( digest , digestBlockLength , key ) ; fudge = Options . intValue ( "tsigfudge" ) ; if ( fudge < 0 || fudge > 0x7FFF ) fudge = FUDGE ; if ( old != null ) { DNSOutput out = new DNSOutput ( ) ; out . writeU16 ( old . getSignature ( ) . length ) ; if ( hmac != null ) { hmac . update ( out . toByteArray ( ) ) ; hmac . update ( old . getSignature ( ) ) ; } } if ( hmac != null ) hmac . update ( b ) ; DNSOutput out = new DNSOutput ( ) ; name . toWireCanonical ( out ) ; out . writeU16 ( DClass . ANY ) ; out . writeU32 ( 0 ) ; alg . toWireCanonical ( out ) ; long time = timeSigned . getTime ( ) / 1000 ; int timeHigh = ( int ) ( time >> 32 ) ; long timeLow = ( time & 0xFFFFFFFFL ) ; out . writeU16 ( timeHigh ) ; out . writeU32 ( timeLow ) ; out . writeU16 ( fudge ) ; out . writeU16 ( error ) ; out . writeU16 ( 0 ) ; if ( hmac != null ) hmac . update ( out . toByteArray ( ) ) ; byte [ ] signature ; if ( hmac != null ) signature = hmac . sign ( ) ; else signature = new byte [ 0 ] ; byte [ ] other = null ; if ( error == Rcode . BADTIME ) { out = new DNSOutput ( ) ; time = new Date ( ) . getTime ( ) / 1000 ; timeHigh = ( int ) ( time >> 32 ) ; timeLow = ( time & 0xFFFFFFFFL ) ; out . writeU16 ( timeHigh ) ; out . writeU32 ( timeLow ) ; other = out . toByteArray ( ) ; } return ( new TSIGRecord ( name , DClass . ANY , 0 , alg , timeSigned , fudge , signature , m . getHeader ( ) . getID ( ) , error , other ) ) ; }
Generates a TSIG record with a specific error for a message that has been rendered .
13,762
public static String of ( Entity . Blueprint entity , CanonicalPath entityPath ) { return ComputeHash . of ( InventoryStructure . of ( entity ) . build ( ) , entityPath , false , true , false ) . getContentHash ( ) ; }
The entity path is currently only required for resources which base their content hash on the resource type path which can be specified using a relative or canonical path in the blueprint . For the content hash to be consistent we need to convert to just a single representation of the path .
13,763
public static String normalizeJDKVersion ( String theJdkVersion ) { theJdkVersion = theJdkVersion . replaceAll ( "_|-" , "." ) ; String tokenArray [ ] = StringUtils . split ( theJdkVersion , "." ) ; List < String > tokens = Arrays . asList ( tokenArray ) ; StringBuffer buffer = new StringBuffer ( theJdkVersion . length ( ) ) ; Iterator < String > iter = tokens . iterator ( ) ; for ( int i = 0 ; i < tokens . size ( ) && i < 4 ; i ++ ) { String section = ( String ) iter . next ( ) ; section = section . replaceAll ( "[^0-9]" , "" ) ; if ( StringUtils . isNotEmpty ( section ) ) { buffer . append ( Integer . parseInt ( section ) ) ; if ( i != 2 ) { buffer . append ( '.' ) ; } else { buffer . append ( '-' ) ; } } } String version = buffer . toString ( ) ; version = StringUtils . stripEnd ( version , "-" ) ; return StringUtils . stripEnd ( version , "." ) ; }
Converts a jdk string from 1 . 5 . 0 - 11b12 to a single 3 digit version like 1 . 5 . 0 - 11
13,764
public void fire ( ) { ArrayList < Runnable > listeners ; synchronized ( this ) { if ( this . listeners == null ) return ; listeners = new ArrayList < > ( this . listeners ) ; } for ( int i = 0 ; i < listeners . size ( ) ; ++ i ) listeners . get ( i ) . run ( ) ; }
Fire this event or in other words call the listeners .
13,765
public byte [ ] createSingleByteArray ( ) { byte [ ] buf = new byte [ totalSize ] ; int pos = 0 ; for ( Triple < byte [ ] , Integer , Integer > t : buffers ) { System . arraycopy ( t . getValue1 ( ) , t . getValue2 ( ) . intValue ( ) , buf , pos , t . getValue3 ( ) . intValue ( ) ) ; pos += t . getValue3 ( ) . intValue ( ) ; } return buf ; }
Merge the byte arrays of this class into a single one and return it .
13,766
public synchronized void addBuffer ( byte [ ] buf , int off , int len ) { if ( copyBuffers ) { byte [ ] b = new byte [ len ] ; System . arraycopy ( buf , off , b , 0 , len ) ; buf = b ; off = 0 ; } buffers . add ( new Triple < > ( buf , Integer . valueOf ( off ) , Integer . valueOf ( len ) ) ) ; totalSize += len ; }
Append the given buffer .
13,767
public static String resolve ( String value , Map < String , String > properties ) { do { int i = value . indexOf ( "${" ) ; if ( i < 0 ) return value ; int j = value . indexOf ( '}' , i + 2 ) ; if ( j < 0 ) return value ; String name = value . substring ( i + 2 , j ) ; String val = properties . get ( name ) ; if ( val == null ) val = "" ; value = value . substring ( 0 , i ) + val + value . substring ( j + 1 ) ; } while ( true ) ; }
Resolve the given value with the given properties .
13,768
public Result < T > put ( T service ) { check ( service ) ; ServiceType serviceType = service . resolveServiceType ( ) ; T previous = null ; lock ( ) ; try { ServiceType existingServiceType = keysToServiceTypes . get ( service . getKey ( ) ) ; if ( existingServiceType != null && ! existingServiceType . equals ( serviceType ) ) throw new ServiceLocationException ( "Invalid registration of service " + service . getKey ( ) + ": already registered under service type " + existingServiceType + ", cannot be registered also under service type " + serviceType , SLPError . INVALID_REGISTRATION ) ; keysToServiceTypes . put ( service . getKey ( ) , serviceType ) ; previous = keysToServiceInfos . put ( service . getKey ( ) , service ) ; service . setRegistered ( true ) ; if ( previous != null ) previous . setRegistered ( false ) ; } finally { unlock ( ) ; } notifyServiceAdded ( previous , service ) ; return new Result < T > ( previous , service ) ; }
Adds the given service to this cache replacing an eventually existing entry .
13,769
public Result < T > addAttributes ( ServiceInfo . Key key , Attributes attributes ) { T previous = null ; T current = null ; lock ( ) ; try { previous = get ( key ) ; if ( previous == null ) throw new ServiceLocationException ( "Could not find service to update " + key , SLPError . INVALID_UPDATE ) ; current = ( T ) previous . addAttributes ( attributes ) ; keysToServiceInfos . put ( current . getKey ( ) , current ) ; current . setRegistered ( true ) ; previous . setRegistered ( false ) ; } finally { unlock ( ) ; } notifyServiceUpdated ( previous , current ) ; return new Result < T > ( previous , current ) ; }
Updates an existing ServiceInfo identified by the given Key adding the given attributes .
13,770
public List < T > purge ( ) { List < T > result = new ArrayList < T > ( ) ; long now = System . currentTimeMillis ( ) ; lock ( ) ; try { for ( T serviceInfo : getServiceInfos ( ) ) { if ( serviceInfo . isExpiredAsOf ( now ) ) { T purged = remove ( serviceInfo . getKey ( ) ) . getPrevious ( ) ; if ( purged != null ) result . add ( purged ) ; } } return result ; } finally { unlock ( ) ; } }
Purges from this cache entries whose registration time plus their lifetime is less than the current time ; that is entries that should have been renewed but for some reason they have not been .
13,771
private static Filter [ ] filters ( QueryFragment ... fragments ) { Filter [ ] ret = new Filter [ fragments . length ] ; for ( int i = 0 ; i < fragments . length ; ++ i ) { ret [ i ] = fragments [ i ] . getFilter ( ) ; } return ret ; }
Converts the list of applicators to the list of filters .
13,772
public Builder branch ( ) { if ( fragments . isEmpty ( ) ) { fragments . add ( new PathFragment ( new NoopFilter ( ) ) ) ; } Builder child = new Builder ( ) ; child . parent = this ; children . add ( child ) ; return child ; }
Creates a new branch in the tree and returns a builder of that branch .
13,773
public Builder done ( ) { if ( done ) { return parent ; } this . tree . fragments = fragments . toArray ( new QueryFragment [ fragments . size ( ) ] ) ; if ( parent != null ) { parent . tree . subTrees . add ( this . tree ) ; parent . children . remove ( this ) ; } new ArrayList < > ( children ) . forEach ( Query . Builder :: done ) ; done = true ; return parent ; }
Concludes the work on a branch and returns a builder of the parent node if any .
13,774
public static OffsetDateTime parseDateTime ( String date ) throws ParseException { return DATE_TIME_OPTIONAL_OFFSET . withZone ( ZoneOffset . UTC ) . parse ( date , OffsetDateTime :: from ) ; }
Parse an XSD dateTime .
13,775
public static String sanitize ( String s ) { if ( s != null ) { StringBuilder b = new StringBuilder ( s . length ( ) ) ; for ( int i = 0 , count = s . length ( ) ; i < count ; i ++ ) { char c = s . charAt ( i ) ; switch ( c ) { case '<' : b . append ( "&lt;" ) ; break ; case '>' : b . append ( "&gt;" ) ; break ; case '\'' : b . append ( "&#39;" ) ; break ; case '"' : b . append ( "&quot;" ) ; break ; case '&' : b . append ( "&amp;" ) ; break ; default : b . append ( c ) ; } } return b . toString ( ) ; } return "" ; }
Converts all sensitive characters to its HTML entity equivalent .
13,776
public double doubleValue ( String name ) { String s = childValue ( name ) ; if ( s != null ) { return Double . parseDouble ( s ) ; } throw new IllegalArgumentException ( this + ": content: " + name ) ; }
Returns a double value of the supplied child or throws an exception if missing .
13,777
public final void setValue ( Object value ) { if ( value instanceof Date ) { content = formatDateTime ( ( Date ) value ) ; } else if ( value != null ) { content = value . toString ( ) ; } else { content = null ; } }
Sets or clears the content of this element .
13,778
public static byte updateBlock ( byte [ ] data , int len , byte crc ) { for ( int i = 0 ; i < len ; i ++ ) crc = CRC8_TABLE [ crc ^ data [ i ] ] ; return crc ; }
Update the CRC value with data from a byte array .
13,779
public static byte calc ( byte [ ] data , int len ) { byte crc = 0 ; for ( int i = 0 ; i < len ; i ++ ) crc = CRC8_TABLE [ ( crc ^ data [ i ] ) & 0xff ] ; return crc ; }
Calculate the CRC value with data from a byte array .
13,780
public int writeSampleData ( final byte [ ] newSampleData , final int offset , int length ) { synchronized ( lock ) { System . arraycopy ( newSampleData , offset , resultSampleBuffer , 0 , length ) ; int anzSamples = writeIntoFloatArrayBuffer ( length ) ; if ( dspEnabled ) { anzSamples = callEffects ( sampleBuffer , currentWritePosition , anzSamples ) ; length = readFromFloatArrayBuffer ( anzSamples ) ; } currentWritePosition = ( currentWritePosition + anzSamples ) % sampleBufferSize ; return length ; } }
This method will write the sample data to the dsp buffer It will convert all sampledata to a stereo or mono float of 1 . 0< = x< = - 1 . 0
13,781
private static String getFormat ( Map < ? , ? > map , int keyPrecision , int valuePrecision ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( '{' ) ; int mappings = map . keySet ( ) . size ( ) ; int c = 0 ; for ( Object key : map . keySet ( ) ) { c ++ ; builder . append ( FormatUtils . getIndexedFormat ( c , FormatUtils . getFormat ( key , keyPrecision ) . substring ( 1 ) ) ) ; builder . append ( VALUE_MAPPING ) ; builder . append ( FormatUtils . getIndexedFormat ( mappings + c , FormatUtils . getFormat ( map . get ( key ) , valuePrecision ) . substring ( 1 ) ) ) ; if ( c < mappings ) builder . append ( VALUE_SEPARATION ) ; } builder . append ( '}' ) ; return builder . toString ( ) ; }
Returns a format - String that can be used to generate a String representation of a map using the String . format method .
13,782
public synchronized Value get ( Key key , CloseableListenable user ) { Data < Value > data = map . get ( key ) ; if ( data == null ) return null ; data . users . add ( user ) ; if ( user != null ) user . addCloseListener ( new Listener < CloseableListenable > ( ) { public void fire ( CloseableListenable event ) { event . removeCloseListener ( this ) ; free ( data . value , event ) ; } } ) ; return data . value ; }
Return the cached data corresponding to the given key or null if it does not exist . The given user is added as using the cached data . Once closed the user is automatically removed from the list of users .
13,783
public synchronized void free ( Value value , CloseableListenable user ) { Data < Value > data = values . get ( value ) ; if ( data == null ) return ; data . lastUsage = System . currentTimeMillis ( ) ; data . users . remove ( user ) ; }
Signal that the given cached data is not anymore used by the given user .
13,784
public synchronized void put ( Key key , Value value , CloseableListenable firstUser ) { if ( map . containsKey ( key ) ) throw new IllegalStateException ( "Cannot put a value in Cache with an existing key: " + key ) ; if ( values . containsKey ( value ) ) throw new IllegalStateException ( "Cannot put 2 times the same value in Cache: " + value ) ; Data < Value > data = new Data < Value > ( ) ; data . value = value ; data . lastUsage = System . currentTimeMillis ( ) ; data . users . add ( firstUser ) ; map . put ( key , data ) ; values . put ( value , data ) ; }
Add the given data to this cache and add the given first user to it .
13,785
@ SuppressWarnings ( "unchecked" ) public < Input , Output > Output adapt ( Input input , Class < Output > outputType ) throws Exception { Class < ? > inputType = input . getClass ( ) ; Adapter a = findAdapter ( input , inputType , outputType ) ; if ( a == null ) return null ; return ( Output ) a . adapt ( input ) ; }
Find an adapter that can adapt the given input into the given output type and adapt it or return null if no available adapter can be found .
13,786
public boolean canAdapt ( Object input , Class < ? > outputType ) { Class < ? > inputType = input . getClass ( ) ; Adapter a = findAdapter ( input , inputType , outputType ) ; return a != null ; }
Return true if an adapter can be found to adapt the given input into the given output type .
13,787
@ SuppressWarnings ( "unchecked" ) public < Input , Output > Adapter < Input , Output > findAdapter ( Object in , Class < Input > input , Class < Output > output ) { ArrayList < Adapter > acceptInput = new ArrayList < > ( ) ; ArrayList < Adapter > matching = new ArrayList < > ( ) ; for ( Adapter a : adapters ) { if ( ! a . getInputType ( ) . isAssignableFrom ( input ) ) continue ; if ( ! a . canAdapt ( in ) ) continue ; acceptInput . add ( a ) ; if ( output . equals ( a . getOutputType ( ) ) ) return a ; if ( output . isAssignableFrom ( a . getOutputType ( ) ) ) matching . add ( a ) ; } if ( acceptInput . isEmpty ( ) ) return null ; if ( matching . size ( ) == 1 ) return matching . get ( 0 ) ; if ( ! matching . isEmpty ( ) ) return getBest ( matching ) ; LinkedList < LinkedList < Adapter > > paths = findPathsTo ( input , acceptInput , output ) ; LinkedList < Adapter > best = null ; while ( ! paths . isEmpty ( ) ) { LinkedList < Adapter > path = paths . removeFirst ( ) ; if ( best != null && best . size ( ) <= path . size ( ) ) continue ; Object o = in ; boolean valid = true ; int i = 0 ; for ( Adapter a : path ) { if ( ! a . canAdapt ( o ) ) { valid = false ; break ; } if ( i == path . size ( ) - 1 ) break ; i ++ ; try { o = a . adapt ( o ) ; } catch ( Exception e ) { valid = false ; break ; } } if ( valid ) best = path ; } if ( best == null ) return null ; return new LinkedAdapter ( best ) ; }
Search for an adapter .
13,788
public final void unblock ( ) { if ( Threading . debugSynchronization ) ThreadingDebugHelper . unblocked ( this ) ; ArrayList < Runnable > listeners ; synchronized ( this ) { if ( unblocked ) return ; unblocked = true ; if ( listenersInline == null ) { this . notifyAll ( ) ; return ; } listeners = listenersInline ; listenersInline = new ArrayList < > ( 2 ) ; } Logger log = LCCore . getApplication ( ) . getLoggerFactory ( ) . getLogger ( SynchronizationPoint . class ) ; while ( true ) { if ( ! log . debug ( ) ) for ( int i = 0 ; i < listeners . size ( ) ; ++ i ) try { listeners . get ( i ) . run ( ) ; } catch ( Throwable t ) { log . error ( "Exception thrown by an inline listener of SynchronizationPoint" , t ) ; } else for ( int i = 0 ; i < listeners . size ( ) ; ++ i ) { long start = System . nanoTime ( ) ; try { listeners . get ( i ) . run ( ) ; } catch ( Throwable t ) { log . error ( "Exception thrown by an inline listener of SynchronizationPoint" , t ) ; } long time = System . nanoTime ( ) - start ; if ( time > 1000000 ) log . debug ( "Listener took " + ( time / 1000000.0d ) + "ms: " + listeners . get ( i ) ) ; } synchronized ( this ) { if ( listenersInline . isEmpty ( ) ) { listenersInline = null ; listeners = null ; this . notifyAll ( ) ; break ; } listeners . clear ( ) ; ArrayList < Runnable > tmp = listeners ; listeners = listenersInline ; listenersInline = tmp ; } } }
Unblock this synchronization point without error .
13,789
public void stop ( ) { AsyncWork < Integer , IOException > currentRead = readTask ; if ( currentRead != null && ! currentRead . isUnblocked ( ) ) { currentRead . cancel ( new CancelException ( "SimpleBufferedReadable.stop" ) ) ; currentRead . block ( 0 ) ; } }
Stop any pending read and block until they are cancelled or done .
13,790
public final Map < String , Set < String > > getExtensionMimeMap ( ) throws OSException { initializeMimeExtensionArrays ( ) ; return Collections . unmodifiableMap ( extensionMime ) ; }
Creates a map with file extensions as keys pointing on sets of MIME types associated with them .
13,791
public Map < String , Set < String > > getMimeApps ( ) throws OSException { if ( mimeApps == null ) { mimeApps = new HashMap < > ( ) ; for ( String path : MIME_APPS_LISTS ) { File mimeAppListFile = new File ( path ) ; if ( mimeAppListFile . exists ( ) && mimeAppListFile . isFile ( ) && mimeAppListFile . canRead ( ) ) { try ( BufferedReader br = new BufferedReader ( new FileReader ( mimeAppListFile ) ) ) { for ( String line ; ( line = br . readLine ( ) ) != null ; ) { String mimeType = null ; Set < String > apps = new HashSet < > ( ) ; Matcher extMatcher = MIME_TYPE_APPS_PATTERN . matcher ( line ) ; while ( extMatcher . find ( ) ) { if ( extMatcher . group ( 1 ) != null ) { mimeType = extMatcher . group ( 1 ) ; } if ( extMatcher . group ( 2 ) != null ) { apps . add ( extMatcher . group ( 2 ) ) ; } } if ( mimeType != null && apps . size ( ) > 0 ) { mimeApps . put ( mimeType , apps ) ; } } } catch ( IOException e ) { throw new OSException ( e ) ; } } } } return Collections . unmodifiableMap ( mimeApps ) ; }
Creates a map of MIME types pointing on the associated application .
13,792
public final Map < String , Set < String > > getMimeExtensionMap ( ) throws OSException { initializeMimeExtensionArrays ( ) ; return Collections . unmodifiableMap ( mimeExtension ) ; }
Creates a map with MIME types as keys pointing on sets of associated file extensions .
13,793
protected BE getSingle ( Query query , SegmentType entityType ) { return inTx ( tx -> Util . getSingle ( tx , query , entityType ) ) ; }
A helper method to retrieve a single result from the query or throw an exception if the query yields no results .
13,794
public static PropertiesSettings from ( File file ) throws IOException { FileInputStream stream = new FileInputStream ( file ) ; return from ( stream ) ; }
Creates a new PropertiesSettings from the given properties file .
13,795
public static PropertiesSettings from ( String resource ) throws IOException { return from ( resource , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; }
Creates a new PropertiesSettings from the given resource in the classpath of the context ClassLoader .
13,796
public static PropertiesSettings from ( String resource , ClassLoader classLoader ) throws IOException { URL url = classLoader . getResource ( resource ) ; return from ( url ) ; }
Creates a new PropertiesSettings from the given resource in the classpath of the given ClassLoader .
13,797
public static PropertiesSettings from ( URL url ) throws IOException { InputStream stream = null ; try { stream = url . openStream ( ) ; return from ( stream ) ; } finally { if ( stream != null ) stream . close ( ) ; } }
Creates a new PropertiesSettings from the given URL .
13,798
public static PropertiesSettings from ( InputStream stream ) throws IOException { Properties properties = new Properties ( ) ; properties . load ( stream ) ; return from ( properties ) ; }
Creates a new PropertiesSettings from the given input stream
13,799
public static XElement parseXML ( File file ) throws XMLStreamException { try ( InputStream in = new FileInputStream ( file ) ) { return parseXML ( in ) ; } catch ( IOException ex ) { throw new XMLStreamException ( ex ) ; } }
Parse an XML from the given local file .