idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
9,500
protected < T > T processInjectionPoint ( final Member injectionTarget , final Class < T > injectionType , final GrpcClient annotation ) { final List < ClientInterceptor > interceptors = interceptorsFromAnnotation ( annotation ) ; final String name = annotation . value ( ) ; final Channel channel ; try { channel = getChannelFactory ( ) . createChannel ( name , interceptors ) ; if ( channel == null ) { throw new IllegalStateException ( "Channel factory created a null channel for " + name ) ; } } catch ( final RuntimeException e ) { throw new IllegalStateException ( "Failed to create channel: " + name , e ) ; } final T value = valueForMember ( name , injectionTarget , injectionType , channel ) ; if ( value == null ) { throw new IllegalStateException ( "Injection value is null unexpectedly for " + name + " at " + injectionTarget ) ; } return value ; }
Processes the given injection point and computes the appropriate value for the injection .
9,501
protected < T > T valueForMember ( final String name , final Member injectionTarget , final Class < T > injectionType , final Channel channel ) throws BeansException { if ( Channel . class . equals ( injectionType ) ) { return injectionType . cast ( channel ) ; } else if ( AbstractStub . class . isAssignableFrom ( injectionType ) ) { try { @ SuppressWarnings ( "unchecked" ) final Class < ? extends AbstractStub < ? > > stubClass = ( Class < ? extends AbstractStub < ? > > ) injectionType . asSubclass ( AbstractStub . class ) ; final Constructor < ? extends AbstractStub < ? > > constructor = ReflectionUtils . accessibleConstructor ( stubClass , Channel . class ) ; AbstractStub < ? > stub = constructor . newInstance ( channel ) ; for ( final StubTransformer stubTransformer : getStubTransformers ( ) ) { stub = stubTransformer . transform ( name , stub ) ; } return injectionType . cast ( stub ) ; } catch ( final NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new BeanInstantiationException ( injectionType , "Failed to create gRPC client for : " + injectionTarget , e ) ; } } else { throw new InvalidPropertyException ( injectionTarget . getDeclaringClass ( ) , injectionTarget . getName ( ) , "Unsupported type " + injectionType . getName ( ) ) ; } }
Creates the instance to be injected for the given member .
9,502
private AccessPredicateConfigAttribute find ( final Collection < ConfigAttribute > attributes ) { for ( final ConfigAttribute attribute : attributes ) { if ( attribute instanceof AccessPredicateConfigAttribute ) { return ( AccessPredicateConfigAttribute ) attribute ; } } return null ; }
Finds the first AccessPredicateConfigAttribute in the given collection .
9,503
@ EventListener ( HeartbeatEvent . class ) public void heartbeat ( final HeartbeatEvent event ) { if ( this . monitor . update ( event . getValue ( ) ) ) { for ( final DiscoveryClientNameResolver discoveryClientNameResolver : this . discoveryClientNameResolvers ) { discoveryClientNameResolver . refresh ( ) ; } } }
Triggers a refresh of the registered name resolvers .
9,504
public static Map < String , Object > mapPropertyValues ( final List < Property > list , final PropertyResolver resolver ) { final Map < String , Object > inputConfig = new HashMap < String , Object > ( ) ; for ( final Property property : list ) { final Object value = resolver . resolvePropertyValue ( property . getName ( ) , property . getScope ( ) ) ; if ( null == value ) { continue ; } inputConfig . put ( property . getName ( ) , value ) ; } return inputConfig ; }
Return All property values for the input property set mapped by name to value .
9,505
public static StepExecutionItem createPluginNodeStepItem ( final String type , final Map configuration , final boolean keepgoingOnSuccess , final StepExecutionItem handler , final String label , final List < PluginConfiguration > filterConfigurations ) { return new PluginNodeStepExecutionItemImpl ( type , configuration , keepgoingOnSuccess , handler , label , filterConfigurations ) ; }
Create a workflow execution item for a plugin node step .
9,506
public static int comp ( Integer v1 , String s1 , Integer v2 , String s2 ) { if ( v1 != null && v2 != null ) { return v1 . compareTo ( v2 ) ; } else if ( v1 != null ) { return 1 ; } else if ( v2 != null ) { return - 1 ; } else if ( null == s1 && null == s2 ) { return 0 ; } else if ( null == s1 ) { return - 1 ; } else if ( null == s2 ) { return 1 ; } else { return s1 . compareTo ( s2 ) ; } }
Compares two version strings and their parsed integer values if available . Returns - 1 0 or 1 if value 1 is less than equal to or greater than value 2 respectively . Compares integers if both are available otherwise compares non - integer as less than integer . if no integers are available comparse strings and treats null strings as less than non - null strings .
9,507
public static VersionCompare forString ( final String value ) { VersionCompare vers = new VersionCompare ( ) ; if ( null == value || "" . equals ( value ) ) { return vers ; } String [ ] parr1 = value . split ( "-" , 2 ) ; String [ ] v1arr = parr1 [ 0 ] . split ( "\\." , 3 ) ; if ( v1arr . length > 0 ) { vers . majString = v1arr [ 0 ] ; try { vers . maj = Integer . parseInt ( vers . majString ) ; } catch ( NumberFormatException e ) { } } if ( v1arr . length > 1 ) { vers . minString = v1arr [ 1 ] ; try { vers . min = Integer . parseInt ( vers . minString ) ; } catch ( NumberFormatException e ) { } } if ( v1arr . length > 2 ) { vers . patchString = v1arr [ 2 ] ; try { vers . patch = Integer . parseInt ( vers . patchString ) ; } catch ( NumberFormatException e ) { } } if ( parr1 . length > 1 ) { vers . tag = parr1 [ 1 ] ; } return vers ; }
Return a VersionCompare for the string
9,508
public UserInfo getUserInfo ( String username ) throws Exception { DirContext dir = context ( ) ; ArrayList roleList = new ArrayList ( getUserRoles ( username ) ) ; String credentials = getUserCredentials ( username ) ; return new UserInfo ( username , Credential . getCredential ( credentials ) , roleList ) ; }
Get the UserInfo for a specified username
9,509
public void initialize ( Subject subject , CallbackHandler callbackHandler , Map sharedState , Map options ) { super . initialize ( subject , callbackHandler , sharedState , options ) ; Properties props = loadProperties ( ( String ) options . get ( "file" ) ) ; initWithProps ( props ) ; }
Read contents of the configured property file .
9,510
private Collection getUserRoles ( String userName ) throws NamingException { log . debug ( "Obtaining roles for userName: " + userName ) ; String filter = "(" + roleMemberRDN + "=" + userNameRDN + "=" + userName + "," + userBase + ")" ; NamingEnumeration roleResults = this . search ( roleBase , filter , new String [ ] { roleMemberRDN } ) ; ArrayList results = new ArrayList ( ) ; while ( roleResults != null && roleResults . hasMore ( ) ) { SearchResult roleResult = ( SearchResult ) roleResults . next ( ) ; String roleResultName = roleResult . getName ( ) ; if ( "" . equals ( roleResultName ) ) { continue ; } String roleResultValue = ( roleResultName . split ( "=" ) ) [ 1 ] ; results . add ( roleResultValue ) ; } return results ; }
Get the collection of role names for the user
9,511
private Map getUsers ( ) throws NamingException { String filter = "(" + roleNameRDN + "=*)" ; HashMap users = new HashMap ( ) ; NamingEnumeration results = this . search ( roleBase , filter , new String [ ] { roleMemberRDN } ) ; while ( results != null && results . hasMore ( ) ) { SearchResult roleResult = ( SearchResult ) results . next ( ) ; String roleResultName = roleResult . getName ( ) ; if ( "" . equals ( roleResultName ) ) { continue ; } String roleResultValue = ( roleResultName . split ( "=" ) ) [ 1 ] ; Attributes roleAttrs = roleResult . getAttributes ( ) ; Attribute roleAttr = roleAttrs . get ( roleMemberRDN ) ; NamingEnumeration valueEnum = roleAttr . getAll ( ) ; while ( valueEnum != null && valueEnum . hasMore ( ) ) { String value = ( String ) valueEnum . next ( ) ; String name ; if ( value . endsWith ( "," + userBase ) ) { name = value . substring ( 0 , value . length ( ) - userBase . length ( ) - 1 ) ; name = name . split ( "=" ) [ 1 ] ; } else { log . debug ( "found unrecognized DN: " + value ) ; continue ; } if ( users . containsKey ( name ) ) { HashSet roles = ( HashSet ) users . get ( name ) ; roles . add ( roleResultValue ) ; } else { HashSet roles = new HashSet ( ) ; roles . add ( roleResultValue ) ; users . put ( name , roles ) ; } } } return users ; }
Return a Map of usernames to role sets .
9,512
private NamingEnumeration search ( String base , String filter , String [ ] returnAttrs ) throws NamingException { SearchControls constraints = new SearchControls ( ) ; constraints . setSearchScope ( SearchControls . SUBTREE_SCOPE ) ; constraints . setReturningAttributes ( returnAttrs ) ; DirContext dirContext = context ( ) ; return dirContext . search ( base , filter , constraints ) ; }
search using search base filter and declared return attributes
9,513
public int read ( final Reader reader ) throws IOException { final int c = reader . read ( cbuf ) ; if ( c > 0 ) { addData ( cbuf , 0 , c ) ; } return c ; }
Read some chars from a reader and return the number of characters read
9,514
public void addData ( final char [ ] data , final int off , final int size ) { if ( size < 1 ) { return ; } final String str = new String ( data , off , size ) ; if ( str . contains ( "\n" ) ) { final String [ ] lines = str . split ( "\\r?\\n" , - 1 ) ; for ( int i = 0 ; i < lines . length - 1 ; i ++ ) { appendString ( lines [ i ] , true ) ; } if ( lines . length > 0 ) { final String last = lines [ lines . length - 1 ] ; if ( "" . equals ( last ) ) { } else { appendString ( last , false ) ; } } } else if ( str . contains ( "\r" ) ) { final String [ ] lines = str . split ( "\\r" , - 1 ) ; for ( int i = 0 ; i < lines . length - 2 ; i ++ ) { appendString ( lines [ i ] , true ) ; } if ( lines . length >= 2 ) { final String last2 = lines [ lines . length - 2 ] ; final String last = lines [ lines . length - 1 ] ; if ( ! "" . equals ( last ) ) { appendString ( last2 , true ) ; appendString ( last , false ) ; } else { appendString ( last2 + "\r" , false ) ; } } } else { appendString ( str , false ) ; } }
Add character data to the buffer
9,515
public synchronized < T > T load ( final PluggableService < T > service , final String providerName ) throws ProviderLoaderException { if ( ! ( service instanceof ScriptPluginProviderLoadable ) ) { return null ; } ScriptPluginProviderLoadable < T > loader = ( ScriptPluginProviderLoadable < T > ) service ; final ProviderIdent ident = new ProviderIdent ( service . getName ( ) , providerName ) ; if ( null == pluginProviderDefs . get ( ident ) ) { final PluginMeta pluginMeta ; try { pluginMeta = getPluginMeta ( ) ; } catch ( IOException e ) { throw new ProviderLoaderException ( e , service . getName ( ) , providerName ) ; } if ( null == pluginMeta ) { throw new ProviderLoaderException ( "Unable to load plugin metadata for file: " + file , service . getName ( ) , providerName ) ; } for ( final ProviderDef pluginDef : pluginMeta . getPluginDefs ( ) ) { if ( matchesProvider ( ident , pluginDef ) ) { final ScriptPluginProvider provider ; try { provider = getPlugin ( pluginMeta , file , pluginDef , ident ) ; } catch ( PluginException e ) { throw new ProviderLoaderException ( e , service . getName ( ) , providerName ) ; } pluginProviderDefs . put ( ident , provider ) ; break ; } } } final ScriptPluginProvider scriptPluginProvider = pluginProviderDefs . get ( ident ) ; try { getResourceLoader ( ) . listResources ( ) ; } catch ( IOException iex ) { throw new ProviderLoaderException ( iex , service . getName ( ) , providerName ) ; } catch ( PluginException e ) { throw new ProviderLoaderException ( e , service . getName ( ) , providerName ) ; } if ( null != scriptPluginProvider ) { try { return loader . createScriptProviderInstance ( scriptPluginProvider ) ; } catch ( PluginException e ) { throw new ProviderLoaderException ( e , service . getName ( ) , providerName ) ; } } return null ; }
Load a provider instance for the service by name
9,516
private PluginMeta getPluginMeta ( ) throws IOException { if ( null != metadata ) { return metadata ; } metadata = loadMeta ( file ) ; metadata . setId ( PluginUtils . generateShaIdFromName ( metadata . getName ( ) ) ) ; dateLoaded = new Date ( ) ; return metadata ; }
Get the plugin metadata loading from the file if necessary
9,517
private ScriptPluginProvider getPlugin ( final PluginMeta pluginMeta , final File file , final ProviderDef pluginDef , final ProviderIdent ident ) throws ProviderLoaderException , PluginException { if ( null == fileExpandedDir ) { final File dir ; try { dir = expandScriptPlugin ( file ) ; } catch ( IOException e ) { throw new ProviderLoaderException ( e , ident . getService ( ) , ident . getProviderName ( ) ) ; } fileExpandedDir = dir ; if ( pluginDef . getPluginType ( ) . equals ( "script" ) ) { final File script = new File ( fileExpandedDir , pluginDef . getScriptFile ( ) ) ; try { ScriptfileUtils . setExecutePermissions ( script ) ; } catch ( IOException e ) { log . warn ( "Unable to set executable bit for script file: " + script + ": " + e . getMessage ( ) ) ; } } debug ( "expanded plugin dir! " + fileExpandedDir ) ; } else { debug ( "expanded plugin dir: " + fileExpandedDir ) ; } if ( pluginDef . getPluginType ( ) . equals ( "script" ) ) { final File script = new File ( fileExpandedDir , pluginDef . getScriptFile ( ) ) ; if ( ! script . exists ( ) || ! script . isFile ( ) ) { throw new PluginException ( "Script file was not found: " + script . getAbsolutePath ( ) ) ; } } return new ScriptPluginProviderImpl ( pluginMeta , pluginDef , file , fileExpandedDir ) ; }
Get the ScriptPluginProvider definition from the file for the given provider def and ident
9,518
private boolean matchesProvider ( final ProviderIdent ident , final ProviderDef pluginDef ) { return ident . getService ( ) . equals ( pluginDef . getService ( ) ) && ident . getProviderName ( ) . equals ( pluginDef . getName ( ) ) ; }
Return true if the ident matches the provider def metadata
9,519
public synchronized boolean isLoaderFor ( final ProviderIdent ident ) { final PluginMeta pluginMeta ; try { pluginMeta = getPluginMeta ( ) ; } catch ( IOException e ) { log . warn ( "Unable to load file meta: " + e . getMessage ( ) ) ; return false ; } if ( null == pluginMeta ) { return false ; } for ( final ProviderDef pluginDef : pluginMeta . getPluginDefs ( ) ) { if ( matchesProvider ( ident , pluginDef ) ) { return true ; } } return false ; }
Return true if the plugin file can loade a provider for the ident
9,520
static PluginMeta loadMeta ( final File jar ) throws IOException { FileInputStream fileInputStream = new FileInputStream ( jar ) ; try { final ZipInputStream zipinput = new ZipInputStream ( fileInputStream ) ; final PluginMeta metadata = ScriptPluginProviderLoader . loadMeta ( jar , zipinput ) ; return metadata ; } finally { fileInputStream . close ( ) ; } }
Get plugin metadatat from a zip file
9,521
static PluginMeta loadMeta ( final File jar , final ZipInputStream zipinput ) throws IOException { final String basename = basename ( jar ) ; PluginMeta metadata = null ; boolean topfound = false ; boolean found = false ; boolean dirfound = false ; boolean resfound = false ; ZipEntry nextEntry = zipinput . getNextEntry ( ) ; Set < String > paths = new HashSet < > ( ) ; while ( null != nextEntry ) { paths . add ( nextEntry . getName ( ) ) ; if ( ! found && ! nextEntry . isDirectory ( ) && nextEntry . getName ( ) . equals ( basename + "/plugin.yaml" ) ) { try { metadata = loadMetadataYaml ( zipinput ) ; found = true ; } catch ( Throwable e ) { log . error ( "Error parsing metadata file plugin.yaml: " + e . getMessage ( ) , e ) ; } } nextEntry = zipinput . getNextEntry ( ) ; } if ( ! found || metadata == null ) { log . error ( "Plugin not loaded: Found no " + basename + "/plugin.yaml within: " + jar . getAbsolutePath ( ) ) ; } String resdir = null != metadata ? getResourcesBasePath ( metadata ) : null ; for ( String path : paths ) { if ( ! topfound && path . startsWith ( basename + "/" ) ) { topfound = true ; } if ( ! dirfound && ( path . startsWith ( basename + "/contents/" ) || path . equals ( basename + "/contents" ) ) ) { dirfound = true ; } if ( ! resfound && resdir != null && ( path . startsWith ( basename + "/" + resdir + "/" ) || path . equals ( basename + "/" + resdir ) ) ) { resfound = true ; } } if ( ! topfound ) { log . error ( "Plugin not loaded: Found no " + basename + "/ dir within file: " + jar . getAbsolutePath ( ) ) ; } if ( ! dirfound && ! resfound ) { log . error ( "Plugin not loaded: Found no " + basename + "/contents or " + basename + "/" + resdir + " dir within: " + jar . getAbsolutePath ( ) ) ; } if ( found && ( dirfound || resfound ) ) { return metadata ; } return null ; }
Load plugin metadata for a file and zip inputstream
9,522
static PluginMeta loadMetadataYaml ( final InputStream stream ) { final Yaml yaml = new Yaml ( ) ; return yaml . loadAs ( stream , PluginMeta . class ) ; }
return loaded yaml plugin metadata from the stream
9,523
static PluginValidation validatePluginMeta ( final PluginMeta pluginList , final File file ) { PluginValidation . State state = PluginValidation . State . VALID ; if ( pluginList == null ) { return PluginValidation . builder ( ) . message ( "No metadata" ) . state ( PluginValidation . State . INVALID ) . build ( ) ; } List < String > messages = new ArrayList < > ( ) ; if ( null == pluginList . getName ( ) ) { messages . add ( "'name' not found in metadata" ) ; state = PluginValidation . State . INVALID ; } if ( null == pluginList . getVersion ( ) ) { messages . add ( "'version' not found in metadata" ) ; state = PluginValidation . State . INVALID ; } if ( null == pluginList . getRundeckPluginVersion ( ) ) { messages . add ( "'rundeckPluginVersion' not found in metadata" ) ; state = PluginValidation . State . INVALID ; } else if ( ! SUPPORTED_PLUGIN_VERSIONS . contains ( pluginList . getRundeckPluginVersion ( ) ) ) { messages . add ( "'rundeckPluginVersion': \"" + pluginList . getRundeckPluginVersion ( ) + "\" is not supported" ) ; state = PluginValidation . State . INVALID ; } if ( pluginList . getRundeckPluginVersion ( ) . equals ( VERSION_2_0 ) ) { List < String > validationErrors = new ArrayList < > ( ) ; PluginValidation . State hostCompatState = PluginMetadataValidator . validateTargetHostCompatibility ( validationErrors , pluginList . getTargetHostCompatibility ( ) ) ; PluginValidation . State versCompatState = PluginMetadataValidator . validateRundeckCompatibility ( validationErrors , pluginList . getRundeckCompatibilityVersion ( ) ) ; messages . addAll ( validationErrors ) ; state = state . or ( hostCompatState ) . or ( versCompatState ) ; } final List < ProviderDef > pluginDefs = pluginList . getPluginDefs ( ) ; for ( final ProviderDef pluginDef : pluginDefs ) { try { validateProviderDef ( pluginDef ) ; } catch ( PluginException e ) { messages . add ( e . getMessage ( ) ) ; state = PluginValidation . State . INVALID ; } } return PluginValidation . builder ( ) . state ( state ) . messages ( messages ) . build ( ) ; }
Return true if loaded metadata about the plugin file is valid .
9,524
private File expandScriptPlugin ( final File file ) throws IOException { if ( ! cachedir . exists ( ) ) { if ( ! cachedir . mkdirs ( ) ) { log . warn ( "Unable to create cache dir: " + cachedir . getAbsolutePath ( ) ) ; } } final File jardir = getFileCacheDir ( ) ; if ( ! jardir . exists ( ) ) { if ( ! jardir . mkdir ( ) ) { log . warn ( "Unable to create cache dir for plugin: " + jardir . getAbsolutePath ( ) ) ; } } final String prefix = getFileBasename ( ) + "/contents" ; debug ( "Expand zip " + file . getAbsolutePath ( ) + " to dir: " + jardir + ", prefix: " + prefix ) ; ZipUtil . extractZip ( file . getAbsolutePath ( ) , jardir , prefix , prefix + "/" ) ; return jardir ; }
Expand zip file into plugin cache dir
9,525
private synchronized boolean removeScriptPluginCache ( ) { if ( null != fileExpandedDir && fileExpandedDir . exists ( ) ) { debug ( "removeScriptPluginCache: " + fileExpandedDir ) ; return FileUtils . deleteDir ( fileExpandedDir ) ; } return true ; }
Remove any cache dir for the file
9,526
private static String basename ( final File file ) { final String name = file . getName ( ) ; if ( name . contains ( "." ) ) { return name . substring ( 0 , name . lastIndexOf ( "." ) ) ; } return name ; }
Get basename of a file
9,527
private static void validateProviderDef ( final ProviderDef pluginDef ) throws PluginException { if ( null == pluginDef . getPluginType ( ) || "" . equals ( pluginDef . getPluginType ( ) ) ) { throw new PluginException ( "Script plugin missing plugin-type" ) ; } if ( "script" . equals ( pluginDef . getPluginType ( ) ) ) { validateScriptProviderDef ( pluginDef ) ; } else if ( "ui" . equals ( pluginDef . getPluginType ( ) ) ) { validateUIProviderDef ( pluginDef ) ; } else { throw new PluginException ( "Script plugin has invalid plugin-type: " + pluginDef . getPluginType ( ) ) ; } }
Validate provider def
9,528
static String getVersionForFile ( final File file ) { try { final PluginMeta pluginMeta = loadMeta ( file ) ; return pluginMeta . getVersion ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return null ; }
Return the version string metadata value for the plugin file or null if it is not available or could not loaded
9,529
private String expandMessage ( final BuildEvent event , final String message ) { final HashMap < String , String > data = new HashMap < String , String > ( ) ; final String user = retrieveUserName ( event ) ; if ( null != user ) { data . put ( "user" , user ) ; } final String node = retrieveNodeName ( event ) ; if ( null != node ) { data . put ( "node" , node ) ; } data . put ( "level" , logLevelToString ( event . getPriority ( ) ) ) ; if ( null != formatter ) { return formatter . reformat ( data , message ) ; } else { return message ; } }
Process string specified by the framework . log . dispatch . console . format property replacing any well known tokens with values from the event .
9,530
public static String logLevelToString ( final int level ) { String logLevel ; switch ( level ) { case Project . MSG_DEBUG : logLevel = "DEBUG" ; break ; case Project . MSG_VERBOSE : logLevel = "VERBOSE" ; break ; case Project . MSG_INFO : logLevel = "INFO" ; break ; case Project . MSG_WARN : logLevel = "WARN" ; break ; case Project . MSG_ERR : logLevel = "ERROR" ; break ; default : logLevel = "UNKNOWN" ; break ; } return logLevel ; }
Returns a string representing the specified log level
9,531
public static void buildFieldProperties ( final Class < ? > aClass , final DescriptionBuilder builder ) { for ( final Field field : collectClassFields ( aClass ) ) { final PluginProperty annotation = field . getAnnotation ( PluginProperty . class ) ; if ( null == annotation ) { continue ; } final Property pbuild = propertyFromField ( field , annotation ) ; if ( null == pbuild ) { continue ; } builder . property ( pbuild ) ; } }
Add properties based on introspection of a class
9,532
public static Map < String , Object > configureProperties ( final PropertyResolver resolver , final Object object ) { return configureProperties ( resolver , buildDescription ( object , DescriptionBuilder . builder ( ) ) , object , PropertyScope . InstanceOnly ) ; }
Set field values on a plugin object by using annotated field values to create a Description and setting field values to resolved property values . Any resolved properties that are not mapped to a field will be included in the return result .
9,533
public static Map < String , Object > configureProperties ( final PropertyResolver resolver , final Description description , final Object object , PropertyScope defaultScope ) { Map < String , Object > inputConfig = mapDescribedProperties ( resolver , description , defaultScope ) ; if ( object instanceof Configurable ) { Configurable configObject = ( Configurable ) object ; Properties configuration = new Properties ( ) ; configuration . putAll ( inputConfig ) ; try { configObject . configure ( configuration ) ; } catch ( ConfigurationException e ) { } } else { inputConfig = configureObjectFieldsWithProperties ( object , description . getProperties ( ) , inputConfig ) ; } return inputConfig ; }
Set field values on a plugin object by using a Description and setting field values to resolved property values . Any resolved properties that are not mapped to a field will be included in the return result .
9,534
public static Map < String , Object > configureObjectFieldsWithProperties ( final Object object , final Map < String , Object > inputConfig ) { return configureObjectFieldsWithProperties ( object , buildFieldProperties ( object ) , inputConfig ) ; }
Set field values on an object using introspection and input values for those properties
9,535
public static Map < String , Object > configureObjectFieldsWithProperties ( final Object object , final List < Property > properties , final Map < String , Object > inputConfig ) { HashMap < String , Object > modified = new HashMap < > ( inputConfig ) ; for ( final Property property : properties ) { if ( null != modified . get ( property . getName ( ) ) ) { if ( setValueForProperty ( property , modified . get ( property . getName ( ) ) , object ) ) { modified . remove ( property . getName ( ) ) ; } } } return modified ; }
Set field values on an object given a list of properties and input values for those properties
9,536
public static Map < String , Object > mapDescribedProperties ( final PropertyResolver resolver , final Description description ) { return mapDescribedProperties ( resolver , description , null ) ; }
Retrieve the Description s Properties mapped to resolved values given the resolver using InsanceOnly default scope .
9,537
public static PropertyLookup create ( final File propfile , final Map defaults , final IPropertyLookup defaultsLookup ) { return new PropertyLookup ( propfile , defaults , defaultsLookup ) ; }
Calls base constructor feeding defaults from Map and IPropertyLookup params
9,538
public String getProperty ( final String key ) { if ( hasProperty ( key ) ) { return properties . getProperty ( key ) ; } else { throw new PropertyLookupException ( "property not found: " + key ) ; } }
Get the property per specified key
9,539
public static Properties fetchProperties ( final File propFile ) { final Properties properties = new Properties ( ) ; try { FileInputStream fis = new FileInputStream ( propFile ) ; try { properties . load ( fis ) ; } finally { if ( null != fis ) { fis . close ( ) ; } } } catch ( IOException e ) { throw new PropertyLookupException ( "failed loading properties from file: " + propFile , e ) ; } return properties ; }
given a file reads in its properties
9,540
protected Properties difference ( final Map map ) { final Properties difference = new Properties ( ) ; for ( final Object o : map . entrySet ( ) ) { final Map . Entry entry = ( Map . Entry ) o ; final String key = ( String ) entry . getKey ( ) ; final String val = ( String ) entry . getValue ( ) ; if ( ! properties . containsKey ( key ) ) { difference . setProperty ( key , val ) ; } } return difference ; }
Reads map of input properties and returns a collection of those that are unique to that input set .
9,541
public static boolean hasProperty ( final String propKey , final File propFile ) { if ( null == propKey ) throw new IllegalArgumentException ( "propKey param was null" ) ; if ( null == propFile ) throw new IllegalArgumentException ( "propFile param was null" ) ; if ( propFile . exists ( ) ) { final Properties p = new Properties ( ) ; try { FileInputStream fis = new FileInputStream ( propFile ) ; try { p . load ( fis ) ; } finally { if ( null != fis ) { fis . close ( ) ; } } return p . containsKey ( propKey ) ; } catch ( IOException e ) { return false ; } } else { return false ; } }
Reads propFile and then checks if specified key exists .
9,542
public static Properties expand ( final Map properties ) { final Properties expandedProperties = new Properties ( ) ; for ( final Object o : properties . entrySet ( ) ) { final Map . Entry entry = ( Map . Entry ) o ; final String key = ( String ) entry . getKey ( ) ; final String keyValue = ( String ) entry . getValue ( ) ; final String expandedKeyValue = expand ( keyValue , properties ) ; expandedProperties . setProperty ( key , expandedKeyValue ) ; } return expandedProperties ; }
expand a given Properties object and return a new one . This will process each key to a given Properties object get its value and expand it . Each value may contain references to other keys within this given Properties object and if so all keys and their expanded keyValues will be resolved into a new Properties object that will be returned .
9,543
public static String expand ( String keyString , Properties properties ) { return PropertyUtil . expand ( keyString , ( Map ) properties ) ; }
expand a keyString that may contain references to properties located in provided Properties object
9,544
public static String expand ( String keyString , Project project ) { return expand ( keyString , project . getProperties ( ) ) ; }
expand a keyString that may contain referecnes to other properties
9,545
@ SuppressWarnings ( "unchecked" ) public static NodeEntryImpl createFromMap ( final Map < String , Object > map ) throws IllegalArgumentException { final NodeEntryImpl nodeEntry = new NodeEntryImpl ( ) ; final HashMap < String , Object > newmap = new HashMap < String , Object > ( map ) ; for ( final String excludeProp : excludeProps ) { newmap . remove ( excludeProp ) ; } if ( null != newmap . get ( "tags" ) && newmap . get ( "tags" ) instanceof String ) { String tags = ( String ) newmap . get ( "tags" ) ; String [ ] data ; if ( "" . equals ( tags . trim ( ) ) ) { data = new String [ 0 ] ; } else { data = tags . split ( "," ) ; } final HashSet set = new HashSet ( ) ; for ( final String s : data ) { if ( null != s && ! "" . equals ( s . trim ( ) ) ) { set . add ( s . trim ( ) ) ; } } newmap . put ( "tags" , set ) ; } else if ( null != newmap . get ( "tags" ) && newmap . get ( "tags" ) instanceof Collection ) { Collection tags = ( Collection ) newmap . get ( "tags" ) ; HashSet data = new HashSet ( ) ; for ( final Object tag : tags ) { if ( null != tag && ! "" . equals ( tag . toString ( ) . trim ( ) ) ) { data . add ( tag . toString ( ) . trim ( ) ) ; } } newmap . put ( "tags" , data ) ; } else if ( null != newmap . get ( "tags" ) ) { Object o = newmap . get ( "tags" ) ; newmap . put ( "tags" , new HashSet ( Arrays . asList ( o . toString ( ) . trim ( ) ) ) ) ; } try { BeanUtils . populate ( nodeEntry , newmap ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { e . printStackTrace ( ) ; } if ( null == nodeEntry . getNodename ( ) ) { throw new IllegalArgumentException ( "Required property 'nodename' was not specified" ) ; } if ( null == nodeEntry . getAttributes ( ) ) { nodeEntry . setAttributes ( new HashMap < String , String > ( ) ) ; } for ( final Map . Entry < String , Object > entry : newmap . entrySet ( ) ) { if ( ! ResourceXMLConstants . allPropSet . contains ( entry . getKey ( ) ) ) { Object value = entry . getValue ( ) ; if ( null != value ) { nodeEntry . setAttribute ( entry . getKey ( ) , value . toString ( ) ) ; } } } return nodeEntry ; }
Create NodeEntryImpl from map data . It will convert tags of type String as a comma separated list of tags or tags a collection of strings into a set . It will remove properties excluded from allowed import .
9,546
public Charset setCharset ( Charset charset ) { Charset prev = this . charset . get ( ) ; this . charset . set ( charset ) ; return prev ; }
Set the charset to use
9,547
public LogBufferManager < D , T > installManager ( ) { LogBufferManager < D , T > manager = factory . apply ( charset . get ( ) ) ; this . manager . set ( manager ) ; return manager ; }
Install a new inherited thread local buffer manager and return it
9,548
private LogBufferManager < D , T > getOrCreateManager ( ) { if ( null == manager . get ( ) ) { installManager ( ) ; } return manager . get ( ) ; }
If no manager is set install one otherwise return the existing one
9,549
private Holder < T > getOrReset ( ) { if ( buffer . get ( ) == null || buffer . get ( ) . getBuffer ( ) . isEmpty ( ) ) { resetEventBuffer ( ) ; } return buffer . get ( ) ; }
get the thread s event buffer reset it if it is empty
9,550
private void resetEventBuffer ( ) { if ( buffer . get ( ) == null ) { buffer . set ( new Holder < > ( getOrCreateManager ( ) . create ( charset . get ( ) ) ) ) ; } else { buffer . get ( ) . reset ( ) ; } }
reset existing or create a new buffer with the current context
9,551
private void flushEventBuffer ( ) { Holder < T > holder = buffer . get ( ) ; logger . accept ( holder . getBuffer ( ) . get ( ) ) ; holder . clear ( ) ; }
emit a log event for the current contents of the buffer
9,552
public StreamingLogWriter removeOverride ( ) { StreamingLogWriter previous = override . get ( ) . pop ( ) . orElse ( null ) ; return previous ; }
Remove the overriding writer if any
9,553
public static String parameterString ( StepContextId contextId ) { return null != contextId . getParams ( ) ? "@" + parameterString ( contextId . getParams ( ) ) : "" ; }
Generate string for a context id s parameter section if present
9,554
private static void setupNodeStates ( WorkflowState current , WorkflowStateImpl parent , StepIdentifier ident ) { HashMap < String , WorkflowNodeState > nodeStates = new HashMap < > ( ) ; if ( null != parent . getNodeStates ( ) ) { nodeStates . putAll ( parent . getNodeStates ( ) ) ; } ArrayList < String > allNodes = new ArrayList < > ( ) ; if ( null != parent . getNodeSet ( ) ) { allNodes . addAll ( parent . getNodeSet ( ) ) ; } parent . setNodeStates ( nodeStates ) ; parent . setAllNodes ( allNodes ) ; for ( WorkflowStepState workflowStepState : current . getStepStates ( ) ) { StepIdentifier thisident = stepIdentifierAppend ( ident , workflowStepState . getStepIdentifier ( ) ) ; if ( workflowStepState . isNodeStep ( ) ) { for ( String nodeName : current . getNodeSet ( ) ) { HashMap < StepIdentifier , StepState > stepStatesForNode = new HashMap < > ( ) ; StepState state = workflowStepState . getNodeStateMap ( ) . get ( nodeName ) ; stepStatesForNode . put ( thisident , state ) ; WorkflowNodeState orig = nodeStates . get ( nodeName ) ; if ( null != orig && null != orig . getStepStateMap ( ) ) { stepStatesForNode . putAll ( orig . getStepStateMap ( ) ) ; } if ( ! allNodes . contains ( nodeName ) ) { allNodes . add ( nodeName ) ; } WorkflowNodeState workflowNodeState = workflowNodeState ( nodeName , state , thisident , stepStatesForNode ) ; nodeStates . put ( nodeName , workflowNodeState ) ; } } else if ( workflowStepState . hasSubWorkflow ( ) ) { setupNodeStates ( workflowStepState . getSubWorkflowState ( ) , parent , thisident ) ; } } }
Configure the nodeStates map for the workflow by visiting each step in the workflow and connecting the step + node state for nodeSteps to the nodeStates map
9,555
public String setAttribute ( final String name , final String value ) { if ( null != value ) { return getAttributes ( ) . put ( name , value ) ; } else { getAttributes ( ) . remove ( name ) ; return value ; } }
Set the value for a specific attribute
9,556
private File getTemplateFile ( String filename ) throws IOException { File templateFile = null ; final String resource = TEMPLATE_RESOURCES_PATH + "/" + filename ; InputStream is = Setup . class . getClassLoader ( ) . getResourceAsStream ( resource ) ; if ( null == is ) { throw new RuntimeException ( "Unable to load required template: " + resource ) ; } templateFile = File . createTempFile ( "temp" , filename ) ; templateFile . deleteOnExit ( ) ; try { return copyToNativeLineEndings ( is , templateFile ) ; } finally { is . close ( ) ; } }
Look for template in the jar resources otherwise look for it on filepath
9,557
private void validateInstall ( ) throws SetupException { if ( null == parameters . getBaseDir ( ) || parameters . getBaseDir ( ) . equals ( "" ) ) { throw new SetupException ( "rdeck.base property not defined or is the empty string" ) ; } if ( ! checkIfDir ( "rdeck.base" , parameters . getBaseDir ( ) ) ) { throw new SetupException ( parameters . getBaseDir ( ) + " is not a valid rdeck install" ) ; } }
Checks the basic install assumptions
9,558
private boolean checkIfDir ( final String propName , final String path ) { if ( null == path || path . equals ( "" ) ) { throw new IllegalArgumentException ( propName + "property had null or empty value" ) ; } return new File ( path ) . exists ( ) ; }
check if path exists as a directory
9,559
private void generatePreferences ( final String args [ ] , Properties input ) throws SetupException { File frameworkPreferences = new File ( Constants . getFrameworkPreferences ( parameters . getBaseDir ( ) ) ) ; try { Preferences . generate ( args , frameworkPreferences . getAbsolutePath ( ) , input ) ; } catch ( Exception e ) { throw new SetupException ( "failed generating setup preferences: " + e . getMessage ( ) , e ) ; } if ( ! frameworkPreferences . exists ( ) ) { throw new SetupException ( "Unable to generate preferences file: " + frameworkPreferences ) ; } if ( ! frameworkPreferences . isFile ( ) ) { throw new SetupException ( frameworkPreferences + " preferences file is not a regular file" ) ; } }
generate the preferences . properties file
9,560
public StateObj evaluateRules ( final StateObj state ) { MutableStateObj dataState = States . mutable ( ) ; getRuleSet ( ) . stream ( ) . filter ( i -> i . test ( state ) ) . map ( input -> Optional . ofNullable ( input . evaluate ( state ) ) ) . flatMap ( o -> o . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . forEach ( dataState :: updateState ) ; return dataState ; }
Evaluate each rule if it applies accrue the new state changes
9,561
protected boolean authenticate ( String name , char [ ] password ) throws LoginException { try { if ( ( name == null ) || ( password == null ) ) { debug ( "user or pass is null" ) ; return false ; } debug ( "PAM authentication trying (" + serviceName + ") for: " + name ) ; UnixUser authenticate = new PAM ( serviceName ) . authenticate ( name , new String ( password ) ) ; debug ( "PAM authentication succeeded for: " + name ) ; this . unixUser = authenticate ; return true ; } catch ( PAMException e ) { debug ( e . getMessage ( ) ) ; if ( isDebug ( ) ) { e . printStackTrace ( ) ; } return false ; } }
Authenticates using PAM
9,562
protected List < Principal > createRolePrincipals ( UnixUser username ) { ArrayList < Principal > principals = new ArrayList < Principal > ( ) ; if ( null != supplementalRoles ) { for ( String supplementalRole : supplementalRoles ) { Principal rolePrincipal = createRolePrincipal ( supplementalRole ) ; if ( null != rolePrincipal ) { principals . add ( rolePrincipal ) ; } } } if ( useUnixGroups ) { for ( String s : username . getGroups ( ) ) { Principal rolePrincipal = createRolePrincipal ( s ) ; if ( null != rolePrincipal ) { principals . add ( rolePrincipal ) ; } } } return principals ; }
Create Principals for any roles
9,563
private boolean authorizedPath ( AuthContext context , Path path , String action ) { Decision evaluate = context . evaluate ( resourceForPath ( path ) , action , environmentForPath ( path ) ) ; return evaluate . isAuthorized ( ) ; }
Evaluate access based on path
9,564
private Map < String , String > resourceForPath ( Path path ) { return AuthorizationUtil . resource ( STORAGE_PATH_AUTH_RES_TYPE , authResForPath ( path ) ) ; }
Return authorization resource map for a path
9,565
private Map < String , String > authResForPath ( Path path ) { HashMap < String , String > authResource = new HashMap < String , String > ( ) ; authResource . put ( PATH_RES_KEY , path . getPath ( ) ) ; authResource . put ( NAME_RES_KEY , path . getName ( ) ) ; return authResource ; }
Map containing path and name given a path
9,566
protected void go ( ) throws CLIToolOptionsException { if ( null == action ) { throw new CLIToolOptionsException ( "Command expected. Choose one of: " + Arrays . asList ( Actions . values ( ) ) ) ; } try { switch ( action ) { case list : listAction ( ) ; break ; case test : testAction ( ) ; break ; case create : createAction ( ) ; break ; case validate : validateAction ( ) ; break ; default : throw new CLIToolOptionsException ( "Unrecognized action: " + action ) ; } } catch ( IOException | PoliciesParseException e ) { throw new CLIToolOptionsException ( e ) ; } }
Call the action
9,567
private boolean applyArgValidate ( ) throws CLIToolOptionsException { if ( argValidate ) { Validation validation = validatePolicies ( ) ; if ( argVerbose && ! validation . isValid ( ) ) { reportValidation ( validation ) ; } if ( ! validation . isValid ( ) ) { log ( "The validation " + ( validation . isValid ( ) ? "passed" : "failed" ) ) ; exit ( 2 ) ; return true ; } } return false ; }
If argValidate is specified validate the input exit 2 if invalid . Print validation report if argVerbose
9,568
public void parse ( ) throws NodeFileParserException { final ResourceXMLParser resourceXMLParser ; if ( null != file ) { resourceXMLParser = new ResourceXMLParser ( file ) ; } else { resourceXMLParser = new ResourceXMLParser ( input ) ; } resourceXMLParser . setReceiver ( this ) ; try { resourceXMLParser . parse ( ) ; } catch ( ResourceXMLParserException e ) { throw new NodeFileParserException ( e ) ; } catch ( IOException e ) { throw new NodeFileParserException ( e ) ; } }
Parse the project . xml formatted file and fill in the nodes found
9,569
private void fillNode ( final ResourceXMLParser . Entity entity , final NodeEntryImpl node ) { node . setUsername ( entity . getProperty ( NODE_USERNAME ) ) ; node . setHostname ( entity . getProperty ( NODE_HOSTNAME ) ) ; node . setOsArch ( entity . getProperty ( NODE_OS_ARCH ) ) ; node . setOsFamily ( entity . getProperty ( NODE_OS_FAMILY ) ) ; node . setOsName ( entity . getProperty ( NODE_OS_NAME ) ) ; node . setOsVersion ( entity . getProperty ( NODE_OS_VERSION ) ) ; node . setDescription ( entity . getProperty ( COMMON_DESCRIPTION ) ) ; final String tags = entity . getProperty ( COMMON_TAGS ) ; final HashSet < String > tags1 ; if ( null != tags && ! "" . equals ( tags ) ) { tags1 = new HashSet < String > ( ) ; for ( final String s : tags . split ( "," ) ) { tags1 . add ( s . trim ( ) ) ; } } else { tags1 = new HashSet < String > ( ) ; } node . setTags ( tags1 ) ; if ( null == node . getAttributes ( ) ) { node . setAttributes ( new HashMap < String , String > ( ) ) ; } if ( null != entity . getProperties ( ) ) { for ( String key : entity . getProperties ( ) . stringPropertyNames ( ) ) { if ( ! ResourceXMLConstants . allPropSet . contains ( key ) ) { node . getAttributes ( ) . put ( key , entity . getProperty ( key ) ) ; } } } }
Fill the NodeEntryImpl based on the Entity s parsed attributes
9,570
public String [ ] getResourceNames ( ) { if ( null != resourcesList ) { return resourcesList . toArray ( new String [ resourcesList . size ( ) ] ) ; } if ( null != basedirListing ) { return basedirListing . toArray ( new String [ basedirListing . size ( ) ] ) ; } String [ ] list = listZipPath ( zipFile , resourcesBasedir ) ; if ( null != list ) { basedirListing = Arrays . asList ( list ) ; return list ; } return new String [ 0 ] ; }
Get the list of resources in the jar
9,571
public void extractResources ( ) throws IOException { if ( ! cacheDir . isDirectory ( ) ) { if ( ! cacheDir . mkdirs ( ) ) { } } if ( null != resourcesList ) { extractJarContents ( resourcesList , cacheDir ) ; for ( final String s : resourcesList ) { File libFile = new File ( cacheDir , s ) ; libFile . deleteOnExit ( ) ; } } else { ZipUtil . extractZip ( zipFile . getAbsolutePath ( ) , cacheDir , resourcesBasedir , resourcesBasedir ) ; } }
Extract resources return the extracted files
9,572
private void continueProcessing ( ) { try { while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { HashMap < String , String > changes = new HashMap < > ( ) ; getAvailableChanges ( changes ) ; if ( changes . isEmpty ( ) ) { if ( inProcess . isEmpty ( ) ) { workflowEngine . event ( WorkflowSystemEventType . EndOfChanges , "No more state changes expected, finishing workflow." ) ; return ; } if ( Thread . currentThread ( ) . isInterrupted ( ) ) { break ; } waitForChanges ( changes ) ; } if ( changes . isEmpty ( ) ) { continue ; } getContextGlobalData ( changes ) ; processStateChanges ( changes ) ; if ( workflowEngine . isWorkflowEndState ( workflowEngine . getState ( ) ) ) { workflowEngine . event ( WorkflowSystemEventType . WorkflowEndState , "Workflow end state reached." ) ; return ; } processOperations ( results :: add ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } if ( Thread . currentThread ( ) . isInterrupted ( ) ) { workflowEngine . event ( WorkflowSystemEventType . Interrupted , "Engine interrupted, stopping engine..." ) ; cancelFutures ( ) ; interrupted = Thread . interrupted ( ) ; } awaitFutures ( ) ; }
Continue processing from current state
9,573
private void getAvailableChanges ( final Map < String , String > changes ) { WorkflowSystem . OperationCompleted < DAT > task = stateChangeQueue . poll ( ) ; while ( task != null && task . getNewState ( ) != null ) { changes . putAll ( task . getNewState ( ) . getState ( ) ) ; DAT result = task . getResult ( ) ; if ( null != sharedData && null != result ) { sharedData . addData ( result ) ; } task = stateChangeQueue . poll ( ) ; } }
Poll for changes from the queue and process all changes that are immediately available without waiting
9,574
private void processRunnableOperations ( final Consumer < WorkflowSystem . OperationResult < DAT , RES , OP > > resultConsumer , final List < OP > shouldrun , final List < OP > shouldskip , final DAT inputData ) { for ( final OP operation : shouldrun ) { if ( shouldskip . contains ( operation ) ) { continue ; } pending . remove ( operation ) ; workflowEngine . event ( WorkflowSystemEventType . WillRunOperation , String . format ( "operation starting: %s" , operation ) , operation ) ; final ListenableFuture < RES > submit = executorService . submit ( ( ) -> operation . apply ( inputData ) ) ; inProcess . add ( operation ) ; futures . add ( submit ) ; FutureCallback < RES > callback = new FutureCallback < RES > ( ) { public void onSuccess ( final RES successResult ) { workflowEngine . event ( WorkflowSystemEventType . OperationSuccess , String . format ( "operation succeeded: %s" , successResult ) , successResult ) ; assert successResult != null ; WorkflowSystem . OperationResult < DAT , RES , OP > result = result ( successResult , operation ) ; resultConsumer . accept ( result ) ; stateChangeQueue . add ( successResult ) ; inProcess . remove ( operation ) ; } public void onFailure ( final Throwable t ) { workflowEngine . event ( WorkflowSystemEventType . OperationFailed , String . format ( "operation failed: %s" , t ) , t ) ; WorkflowSystem . OperationResult < DAT , RES , OP > result = result ( t , operation ) ; resultConsumer . accept ( result ) ; StateObj newFailureState = operation . getFailureState ( t ) ; if ( null != newFailureState && newFailureState . getState ( ) . size ( ) > 0 ) { WorkflowSystem . OperationCompleted < DAT > objectOperationCompleted = WorkflowEngine . dummyResult ( newFailureState ) ; stateChangeQueue . add ( objectOperationCompleted ) ; } inProcess . remove ( operation ) ; } } ; Futures . addCallback ( submit , callback , manager ) ; } }
Process the runnable operations
9,575
private void waitForChanges ( final Map < String , String > changes ) throws InterruptedException { WorkflowSystem . OperationCompleted < DAT > take = stateChangeQueue . poll ( sleeper . time ( ) , sleeper . unit ( ) ) ; if ( null == take || take . getNewState ( ) . getState ( ) . isEmpty ( ) ) { sleeper . backoff ( ) ; return ; } sleeper . reset ( ) ; changes . putAll ( take . getNewState ( ) . getState ( ) ) ; if ( null != sharedData ) { sharedData . addData ( take . getResult ( ) ) ; } getAvailableChanges ( changes ) ; }
Sleep until changes are available on the queue if any are found then consume remaining and return false otherwise return true
9,576
private void processStateChanges ( final Map < String , String > changes ) { workflowEngine . event ( WorkflowSystemEventType . WillProcessStateChange , String . format ( "saw state changes: %s" , changes ) , changes ) ; workflowEngine . getState ( ) . updateState ( changes ) ; boolean update = Rules . update ( workflowEngine . getRuleEngine ( ) , workflowEngine . getState ( ) ) ; workflowEngine . event ( WorkflowSystemEventType . DidProcessStateChange , String . format ( "applied state changes and rules (changed? %s): %s" , update , workflowEngine . getState ( ) ) , workflowEngine . getState ( ) ) ; }
Handle the state changes for the rule engine
9,577
private void processOperations ( final Consumer < WorkflowSystem . OperationResult < DAT , RES , OP > > resultConsumer ) { int origPendingCount = pending . size ( ) ; List < OP > shouldrun = pending . stream ( ) . filter ( input -> input . shouldRun ( workflowEngine . getState ( ) ) ) . collect ( Collectors . toList ( ) ) ; List < OP > shouldskip = shouldrun . stream ( ) . filter ( input -> input . shouldSkip ( workflowEngine . getState ( ) ) ) . collect ( Collectors . toList ( ) ) ; DAT inputData = null != sharedData ? sharedData . produceNext ( ) : null ; processRunnableOperations ( resultConsumer , shouldrun , shouldskip , inputData ) ; processSkippedOperations ( shouldskip ) ; pending . removeAll ( shouldskip ) ; skipped . addAll ( shouldskip ) ; workflowEngine . eventLoopProgress ( origPendingCount , shouldskip . size ( ) , shouldrun . size ( ) , pending . size ( ) ) ; }
Run and skip pending operations
9,578
private void processSkippedOperations ( final List < OP > shouldskip ) { for ( final OP operation : shouldskip ) { workflowEngine . event ( WorkflowSystemEventType . WillSkipOperation , String . format ( "Skip condition statisfied for operation: %s, skipping" , operation ) , operation ) ; StateObj newstate = operation . getSkipState ( workflowEngine . getState ( ) ) ; WorkflowSystem . OperationCompleted < DAT > objectOperationCompleted = WorkflowEngine . dummyResult ( newstate ) ; stateChangeQueue . add ( objectOperationCompleted ) ; } }
Process skipped operations
9,579
protected List getUserRoles ( final DirContext dirContext , final String username ) throws LoginException , NamingException { if ( _ignoreRoles ) { ArrayList < String > strings = new ArrayList < > ( ) ; addSupplementalRoles ( strings ) ; return strings ; } else { return super . getUserRoles ( dirContext , username ) ; } }
Override to perform behavior of ignoreRoles option
9,580
public boolean login ( ) throws LoginException { if ( ( getShared ( ) . isUseFirstPass ( ) || getShared ( ) . isTryFirstPass ( ) ) && getShared ( ) . isHasSharedAuth ( ) ) { debug ( String . format ( "JettyCombinedLdapLoginModule: login with shared auth, " + "try? %s, use? %s" , getShared ( ) . isTryFirstPass ( ) , getShared ( ) . isUseFirstPass ( ) ) ) ; setAuthenticated ( authenticate ( getShared ( ) . getSharedUserName ( ) , getShared ( ) . getSharedUserPass ( ) ) ) ; } if ( getShared ( ) . isUseFirstPass ( ) && getShared ( ) . isHasSharedAuth ( ) ) { debug ( String . format ( "AbstractSharedLoginModule: using login result: %s" , isAuthenticated ( ) ) ) ; if ( isAuthenticated ( ) ) { wasAuthenticated ( getShared ( ) . getSharedUserName ( ) , getShared ( ) . getSharedUserPass ( ) ) ; } return isAuthenticated ( ) ; } if ( getShared ( ) . isHasSharedAuth ( ) ) { if ( isAuthenticated ( ) ) { return isAuthenticated ( ) ; } debug ( String . format ( "AbstractSharedLoginModule: shared auth failed, now trying callback auth." ) ) ; } Object [ ] userPass = new Object [ 0 ] ; try { userPass = getCallBackAuth ( ) ; } catch ( IOException e ) { if ( isDebug ( ) ) { e . printStackTrace ( ) ; } throw new LoginException ( e . toString ( ) ) ; } catch ( UnsupportedCallbackException e ) { if ( isDebug ( ) ) { e . printStackTrace ( ) ; } throw new LoginException ( e . toString ( ) ) ; } if ( null == userPass || userPass . length < 2 ) { setAuthenticated ( false ) ; } else { String name = ( String ) userPass [ 0 ] ; Object pass = userPass [ 1 ] ; setAuthenticated ( authenticate ( name , pass ) ) ; if ( isAuthenticated ( ) ) { wasAuthenticated ( name , pass ) ; } } return isAuthenticated ( ) ; }
Override default login logic to use shared login credentials if available
9,581
public static void fileCopy ( final File src , final File dest , final boolean overwrite ) throws IOException { if ( ! dest . exists ( ) || ( dest . exists ( ) && overwrite ) ) { FileUtils . mkParentDirs ( dest ) ; if ( overwrite ) { Files . copy ( src . toPath ( ) , dest . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ; } else { Files . copy ( src . toPath ( ) , dest . toPath ( ) ) ; } } }
Copies file src to dest using nio .
9,582
public static void deleteDirOnExit ( final File dir ) { if ( dir . isDirectory ( ) ) { final String [ ] children = dir . list ( ) ; for ( int i = 0 ; i < children . length ; i ++ ) { deleteDirOnExit ( new File ( dir , children [ i ] ) ) ; } } dir . deleteOnExit ( ) ; }
Delete a directory recursively . This method will delete all files and subdirectories .
9,583
public static void fileRename ( final File file , final String newPath , final Class clazz ) { File newDestFile = new File ( newPath ) ; File lockFile = new File ( newDestFile . getAbsolutePath ( ) + ".lock" ) ; try { synchronized ( clazz ) { FileChannel channel = new RandomAccessFile ( lockFile , "rw" ) . getChannel ( ) ; FileLock lock = channel . lock ( ) ; try { try { FileUtils . mkParentDirs ( newDestFile ) ; Files . move ( file . toPath ( ) , newDestFile . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ; } catch ( IOException ioe ) { throw new CoreException ( "Unable to move file " + file + " to destination " + newDestFile + ": " + ioe . getMessage ( ) ) ; } } finally { lock . release ( ) ; channel . close ( ) ; } } } catch ( IOException e ) { System . err . println ( "IOException: " + e . getMessage ( ) ) ; e . printStackTrace ( System . err ) ; throw new CoreException ( "Unable to rename file: " + e . getMessage ( ) , e ) ; } }
Rename a file . Uses Java s nio library to use a lock .
9,584
public static void mkParentDirs ( final File file ) throws IOException { File parentFile = file . getParentFile ( ) ; if ( parentFile == null ) { parentFile = file . getAbsoluteFile ( ) . getParentFile ( ) ; } if ( parentFile != null && ! parentFile . exists ( ) ) { if ( ! parentFile . mkdirs ( ) ) { throw new IOException ( "Unable to create parent directory " + "structure for file " + file . getAbsolutePath ( ) ) ; } } }
Create parent directory structure of a given file if it doesn t already exist .
9,585
public static File getBaseDir ( final List < File > files ) { String common = getCommonPrefix ( files . stream ( ) . map ( new Function < File , String > ( ) { public String apply ( final File file ) { return file . getAbsolutePath ( ) ; } } ) . collect ( Collectors . toList ( ) ) ) ; if ( null != common ) { return new File ( common ) ; } return null ; }
Return common base directory of the given files
9,586
public static String relativePath ( File parent , File child ) { Path superPath = parent . toPath ( ) ; Path subPath = child . toPath ( ) ; if ( ! subPath . startsWith ( superPath ) ) { throw new IllegalArgumentException ( "Not a subpath: " + child ) ; } return superPath . relativize ( subPath ) . toString ( ) ; }
Return the relative path between a parent directory and some child path
9,587
private WorkflowStatusDataResult executeWFSectionNodeDispatch ( StepExecutionContext executionContext , int stepCount , List < StepExecutionResult > results , Map < String , Collection < StepExecutionResult > > failures , final Map < Integer , StepExecutionResult > stepFailures , IWorkflow flowsection , WFSharedContext sharedContext ) throws ExecutionServiceException , DispatcherException { logger . debug ( "Node dispatch for " + flowsection . getCommands ( ) . size ( ) + " steps" ) ; final DispatcherResult dispatch ; final WorkflowExecutionItem innerLoopItem = createInnerLoopItem ( flowsection ) ; final Dispatchable dispatchedWorkflow = new DispatchedWorkflow ( getFramework ( ) . getWorkflowExecutionService ( ) , innerLoopItem , stepCount , executionContext . getStepContext ( ) ) ; WFSharedContext dispatchSharedContext = new WFSharedContext ( sharedContext ) ; dispatch = getFramework ( ) . getExecutionService ( ) . dispatchToNodes ( ExecutionContextImpl . builder ( executionContext ) . sharedDataContext ( dispatchSharedContext ) . stepNumber ( stepCount ) . build ( ) , dispatchedWorkflow ) ; logger . debug ( "Node dispatch result: " + dispatch ) ; WFSharedContext resultData = extractWFDispatcherResult ( dispatch , results , failures , stepFailures , flowsection . getCommands ( ) . size ( ) , stepCount ) ; return workflowResult ( dispatch . isSuccess ( ) , null , ControlBehavior . Continue , resultData ) ; }
Execute a workflow section that should be dispatched across nodes
9,588
private List < IWorkflow > splitWorkflowDispatchedSections ( IWorkflow workflow ) throws ExecutionServiceException { ArrayList < StepExecutionItem > dispatchItems = new ArrayList < > ( ) ; ArrayList < IWorkflow > sections = new ArrayList < > ( ) ; for ( final StepExecutionItem item : workflow . getCommands ( ) ) { StepExecutor executor = getFramework ( ) . getStepExecutionService ( ) . getExecutorForItem ( item ) ; if ( executor . isNodeDispatchStep ( item ) ) { dispatchItems . add ( item ) ; } else { if ( dispatchItems . size ( ) > 0 ) { sections . add ( new WorkflowImpl ( dispatchItems , workflow . getThreadcount ( ) , workflow . isKeepgoing ( ) , workflow . getStrategy ( ) ) ) ; dispatchItems = new ArrayList < > ( ) ; } sections . add ( new WorkflowImpl ( Collections . singletonList ( item ) , workflow . getThreadcount ( ) , workflow . isKeepgoing ( ) , workflow . getStrategy ( ) ) ) ; } } if ( null != dispatchItems && dispatchItems . size ( ) > 0 ) { sections . add ( new WorkflowImpl ( dispatchItems , workflow . getThreadcount ( ) , workflow . isKeepgoing ( ) , workflow . getStrategy ( ) ) ) ; } return sections ; }
Splits a workflow into a sequence of sub - workflows separated along boundaries of node - dispatch sets .
9,589
public static ExtSSHExec build ( final INodeEntry nodeentry , final String [ ] args , final Project project , final Map < String , Map < String , String > > dataContext , final SSHConnectionInfo sshConnectionInfo , final int loglevel , final PluginLogger logger ) throws BuilderException { final ExtSSHExec extSSHExec = new ExtSSHExec ( ) ; build ( extSSHExec , nodeentry , args , project , dataContext , sshConnectionInfo , loglevel , logger ) ; extSSHExec . setAntLogLevel ( loglevel ) ; return extSSHExec ; }
Build a Task that performs SSH command
9,590
private void remove ( final ProviderIdent ident ) { final cacheItem cacheItem = cache . get ( ident ) ; if ( null != cacheItem ) { filecache . remove ( cacheItem . getFirst ( ) ) ; } cache . remove ( ident ) ; }
Remove the association with ident and remove any filecache association as well .
9,591
public synchronized ProviderLoader getLoaderForIdent ( final ProviderIdent ident ) throws ProviderLoaderException { final cacheItem cacheItem = cache . get ( ident ) ; if ( null == cacheItem ) { return rescanForItem ( ident ) ; } final File file = cacheItem . getFirst ( ) ; if ( cacheItem . getSecond ( ) . isExpired ( ident , file ) ) { remove ( ident ) ; return rescanForItem ( ident ) ; } else { return loadFileProvider ( cacheItem ) ; } }
Get the loader for the provider
9,592
private ProviderLoader loadFileProvider ( final cacheItem cached ) { final File file = cached . getFirst ( ) ; final PluginScanner second = cached . getSecond ( ) ; return filecache . get ( file , second ) ; }
return the loader stored in filecache for the file and scanner
9,593
private synchronized ProviderLoader rescanForItem ( final ProviderIdent ident ) throws ProviderLoaderException { File candidate = null ; PluginScanner cscanner = null ; for ( final PluginScanner scanner : getScanners ( ) ) { final File file = scanner . scanForFile ( ident ) ; if ( null != file ) { if ( null != candidate ) { throw new ProviderLoaderException ( "More than one plugin file matched: " + file + ", and " + candidate , ident . getService ( ) , ident . getProviderName ( ) ) ; } candidate = file ; cscanner = scanner ; } } if ( null != candidate ) { final cacheItem cacheItem = new cacheItem ( candidate , cscanner ) ; cache . put ( ident , cacheItem ) ; return loadFileProvider ( cacheItem ) ; } return null ; }
Rescan for the ident and cache and return the loader
9,594
public void addEnv ( final Environment . Variable env ) { if ( null == envVars ) { envVars = new ArrayList < Environment . Variable > ( ) ; } envVars . add ( env ) ; }
Add an Env element
9,595
public void execute ( ) throws BuildException { if ( getHost ( ) == null ) { throw new BuildException ( "Host is required." ) ; } if ( getUserInfo ( ) . getName ( ) == null ) { throw new BuildException ( "Username is required." ) ; } if ( getUserInfo ( ) . getKeyfile ( ) == null && getUserInfo ( ) . getPassword ( ) == null && getSshKeyData ( ) == null ) { throw new BuildException ( "Password or Keyfile is required." ) ; } if ( command == null && commandResource == null ) { throw new BuildException ( "Command or commandResource is required." ) ; } if ( inputFile != null && inputProperty != null ) { throw new BuildException ( "You can't specify both inputFile and" + " inputProperty." ) ; } if ( inputFile != null && ! inputFile . exists ( ) ) { throw new BuildException ( "The input file " + inputFile . getAbsolutePath ( ) + " does not exist." ) ; } Session session = null ; StringBuffer output = new StringBuffer ( ) ; try { session = openSession ( ) ; if ( null != getDisconnectHolder ( ) ) { final Session sub = session ; getDisconnectHolder ( ) . setDisconnectable ( new Disconnectable ( ) { public void disconnect ( ) { sub . disconnect ( ) ; } } ) ; } if ( command != null ) { executeCommand ( session , command , output ) ; } else { try { BufferedReader br = new BufferedReader ( new InputStreamReader ( commandResource . getInputStream ( ) ) ) ; String cmd ; while ( ( cmd = br . readLine ( ) ) != null ) { executeCommand ( session , cmd , output ) ; output . append ( "\n" ) ; } FileUtils . close ( br ) ; } catch ( IOException e ) { if ( getFailonerror ( ) ) { throw new BuildException ( e ) ; } else { log ( "Caught exception: " + e . getMessage ( ) , Project . MSG_ERR ) ; } } } } catch ( JSchException e ) { if ( getFailonerror ( ) ) { throw new BuildException ( e ) ; } else { log ( "Caught exception: " + e . getMessage ( ) , Project . MSG_ERR ) ; } } finally { try { if ( null != this . sshAgentProcess ) { this . sshAgentProcess . stopAgent ( ) ; } } catch ( IOException e ) { log ( "Caught exception: " + e . getMessage ( ) , Project . MSG_ERR ) ; } if ( outputProperty != null ) { getProject ( ) . setNewProperty ( outputProperty , output . toString ( ) ) ; } if ( session != null && session . isConnected ( ) ) { session . disconnect ( ) ; } } }
Execute the command on the remote host .
9,596
private void writeToFile ( String from , boolean append , File to ) throws IOException { FileWriter out = null ; try { out = new FileWriter ( to . getAbsolutePath ( ) , append ) ; StringReader in = new StringReader ( from ) ; char [ ] buffer = new char [ BUFFER_SIZE ] ; int bytesRead ; while ( true ) { bytesRead = in . read ( buffer ) ; if ( bytesRead == - 1 ) { break ; } out . write ( buffer , 0 , bytesRead ) ; } out . flush ( ) ; } finally { if ( out != null ) { out . close ( ) ; } } }
Writes a string to a file . If destination file exists it may be overwritten depending on the append value .
9,597
private Set < Resource < T > > listStackDirectory ( Path path ) { HashSet < Resource < T > > merge = new HashSet < Resource < T > > ( ) ; if ( treeHandlerList . size ( ) > 0 ) { for ( SelectiveTree < T > treeHandler : treeHandlerList ) { if ( PathUtil . hasRoot ( treeHandler . getSubPath ( ) , path ) && ! PathUtil . equals ( treeHandler . getSubPath ( ) , path ) ) { String relativePath = PathUtil . removePrefix ( path . getPath ( ) , treeHandler . getSubPath ( ) . getPath ( ) ) ; String [ ] components = PathUtil . componentsFromPathString ( relativePath ) ; Path subpath = PathUtil . appendPath ( path , components [ 0 ] ) ; merge . add ( new ResourceBase < T > ( subpath , null , true ) ) ; } } } return merge ; }
List all treeHandlers as directories which have the given path as a parent
9,598
public static long genSeed ( final String ident ) { try { MessageDigest instance = MessageDigest . getInstance ( "SHA-1" ) ; byte [ ] strbytes = ident . getBytes ( "UTF-8" ) ; byte [ ] digest = instance . digest ( strbytes ) ; return ByteBuffer . wrap ( digest , 0 , Long . BYTES ) . getLong ( ) ; } catch ( NoSuchAlgorithmException | UnsupportedEncodingException e ) { return ident . hashCode ( ) ; } }
generate random seed from unique ident string
9,599
public void openStream ( ) throws IOException { socket = new Socket ( host , port ) ; socketStream = socket . getOutputStream ( ) ; if ( null != context . get ( "name" ) && null != context . get ( "id" ) ) { Object group = context . get ( "group" ) ; String desc = ( null != group ? group + "/" : "" ) + context . get ( "name" ) ; write ( "Job started: " + desc + ": " + context . get ( "id" ) ) ; } write ( "Execution: " + context . get ( "execid" ) ) ; }
Open a stream called before addEntry is called