idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
9,700 | public static FrameworkProjectConfig create ( final String name , final File propertyFile , final Properties properties , final IFilesystemFramework filesystemFramework ) { if ( ! propertyFile . exists ( ) ) { generateProjectPropertiesFile ( name , propertyFile , false , properties , true ) ; } return create ( name , propertyFile , filesystemFramework ) ; } | Create and generate file with the given properties if not null |
9,701 | public void setProjectProperties ( final Properties properties ) { generateProjectPropertiesFile ( getName ( ) , propertyFile , true , properties , false , null , false ) ; loadProperties ( ) ; } | Set the project properties file contents exactly |
9,702 | public String reformat ( final Map < String , String > context , final String message ) { final HashMap < String , String > tokens = new HashMap < String , String > ( ) ; if ( null != context ) { tokens . putAll ( context ) ; } if ( null != generator ) { tokens . putAll ( generator . getMap ( ) ) ; } else if ( null != data ) { tokens . putAll ( data ) ; } final String [ ] arr = { null != tokens . get ( "user" ) ? tokens . get ( "user" ) : "" , null != tokens . get ( "node" ) ? tokens . get ( "node" ) : "" , null != tokens . get ( "command" ) ? tokens . get ( "command" ) : "" , tokens . get ( "level" ) , message } ; synchronized ( messageFormat ) { return messageFormat . format ( arr ) ; } } | Combines the context data and the local static or dynamic context data and reformats the message |
9,703 | public static StateObj state ( StateObj ... states ) { MutableStateObj mutable = mutable ( ) ; for ( StateObj state : states ) { mutable . updateState ( state ) ; } return state ( mutable . getState ( ) ) ; } | merge multiple state objects in order |
9,704 | public static Set < String > getGroups ( AclRuleSetSource source ) { HashSet < String > strings = new HashSet < > ( ) ; for ( AclRule rule : source . getRuleSet ( ) . getRules ( ) ) { if ( rule . getGroup ( ) != null ) { strings . add ( rule . getGroup ( ) ) ; } } return strings ; } | collect the set of groups used in a rule set |
9,705 | public static Authorization append ( Authorization a , Authorization b ) { if ( a instanceof AclRuleSetSource && b instanceof AclRuleSetSource ) { return RuleEvaluator . createRuleEvaluator ( merge ( ( AclRuleSetSource ) a , ( AclRuleSetSource ) b ) ) ; } return new MultiAuthorization ( a , b ) ; } | Merge to authorization resources |
9,706 | public String resolvePropertyValue ( final String name , final PropertyScope scope ) { if ( null == scope || scope == PropertyScope . Unspecified ) { throw new IllegalArgumentException ( "scope must be specified" ) ; } String value = null ; if ( scope . isInstanceLevel ( ) ) { if ( null != instanceScopeResolver ) { value = instanceScopeResolver . getProperty ( name ) ; log . trace ( "resolvePropertyValue(" + scope + ")(I) " + name + " = " + value ) ; } } if ( null != value || scope == PropertyScope . InstanceOnly ) { log . debug ( "resolvePropertyValue(" + scope + ") " + name + " = " + value ) ; return value ; } if ( scope . isProjectLevel ( ) ) { if ( null != projectScopeResolver ) { value = projectScopeResolver . getProperty ( name ) ; log . trace ( "resolvePropertyValue(" + scope + ")(P) " + name + " = " + value ) ; } } if ( null != value || scope == PropertyScope . ProjectOnly ) { log . debug ( "resolvePropertyValue(" + scope + ") " + name + " = " + value ) ; return value ; } if ( null != frameworkScopeResolver ) { if ( scope . isFrameworkLevel ( ) ) { value = frameworkScopeResolver . getProperty ( name ) ; log . trace ( "resolvePropertyValue(" + scope + ")(F) " + name + " = " + value ) ; } } log . debug ( "resolvePropertyValue(" + scope + ") " + name + " = " + value ) ; return value ; } | Resolve the property value |
9,707 | public static String expandUrlString ( final String urlString , final MultiDataContext < ContextView , DataContext > dataContext , final String nodename ) { final int qindex = urlString . indexOf ( '?' ) ; final StringBuilder builder = new StringBuilder ( ) ; builder . append ( SharedDataContextUtils . replaceDataReferences ( qindex > 0 ? urlString . substring ( 0 , qindex ) : urlString , dataContext , ContextView . node ( nodename ) , ContextView :: nodeStep , urlPathEncoder , true , false ) ) ; if ( qindex > 0 ) { builder . append ( "?" ) ; if ( qindex < urlString . length ( ) - 1 ) { builder . append ( SharedDataContextUtils . replaceDataReferences ( urlString . substring ( qindex + 1 ) , dataContext , ContextView . node ( nodename ) , ContextView :: nodeStep , urlQueryEncoder , true , false ) ) ; } } return builder . toString ( ) ; } | Expand data references in a URL string using proper encoding for path and query parts . |
9,708 | private File withPath ( Path path , File dir ) { return new File ( dir , path . getPath ( ) ) ; } | file for a given path in the specified subdir |
9,709 | public T providerOfType ( final String providerName ) throws ExecutionServiceException { if ( null == providerName ) { throw new NullPointerException ( "provider name was null for Service: " + getName ( ) ) ; } if ( isCacheInstances ( ) ) { if ( null == instanceregistry . get ( providerName ) ) { T instance = createProviderInstanceOfType ( providerName ) ; instanceregistry . put ( providerName , instance ) ; return instance ; } return instanceregistry . get ( providerName ) ; } else { return createProviderInstanceOfType ( providerName ) ; } } | Return the provider instance of the given name . |
9,710 | public String copyFile ( final ExecutionContext executionContext , final File file , final INodeEntry node , final String destination ) throws FileCopierException { return copyFile ( executionContext , file , null , null , node , destination ) ; } | Copy existing file |
9,711 | public String copyScriptContent ( final ExecutionContext executionContext , final String s , final INodeEntry node , final String destination ) throws FileCopierException { return copyFile ( executionContext , null , null , s , node , destination ) ; } | Copy string content |
9,712 | private Properties loadCacheData ( final File cacheFile ) { final Properties cacheProperties = new Properties ( ) ; if ( cacheFile . isFile ( ) ) { try { final FileInputStream fileInputStream = new FileInputStream ( cacheFile ) ; try { cacheProperties . load ( fileInputStream ) ; } finally { fileInputStream . close ( ) ; } } catch ( IOException e ) { logger . debug ( "failed to load cache data from file: " + cacheFile ) ; } } return cacheProperties ; } | Load properties file with some cache data |
9,713 | private void cacheResponseInfo ( final httpClientInteraction method , final File cacheFile ) { Properties newprops = new Properties ( ) ; if ( null != method . getResponseHeader ( LAST_MODIFIED ) ) { newprops . setProperty ( LAST_MODIFIED , method . getResponseHeader ( LAST_MODIFIED ) . getValue ( ) ) ; } if ( null != method . getResponseHeader ( E_TAG ) ) { newprops . setProperty ( E_TAG , method . getResponseHeader ( E_TAG ) . getValue ( ) ) ; } if ( null != method . getResponseHeader ( CONTENT_TYPE ) ) { newprops . setProperty ( CONTENT_TYPE , method . getResponseHeader ( CONTENT_TYPE ) . getValue ( ) ) ; } if ( newprops . size ( ) > 0 ) { try { final FileOutputStream fileOutputStream = new FileOutputStream ( cacheFile ) ; try { newprops . store ( fileOutputStream , "URLFileUpdater cache data for URL: " + url ) ; } finally { fileOutputStream . close ( ) ; } } catch ( IOException e ) { logger . debug ( "Failed to write cache header info to file: " + cacheFile + ", " + e . getMessage ( ) , e ) ; } } else if ( cacheFile . exists ( ) ) { if ( ! cacheFile . delete ( ) ) { logger . warn ( "Unable to delete cachefile: " + cacheFile . getAbsolutePath ( ) ) ; } } } | Cache etag and last - modified header info for a response |
9,714 | public static void configureNodeContextThreadLocalsForProject ( final Project project ) { final InheritableThreadLocal < String > localNodeName = new InheritableThreadLocal < > ( ) ; final InheritableThreadLocal < String > localUserName = new InheritableThreadLocal < > ( ) ; if ( null == project . getReference ( NODE_NAME_LOCAL_REF_ID ) ) { project . addReference ( NODE_NAME_LOCAL_REF_ID , localNodeName ) ; } if ( null == project . getReference ( NODE_USER_LOCAL_REF_ID ) ) { project . addReference ( NODE_USER_LOCAL_REF_ID , localUserName ) ; } } | Adds InheritableNodeLocal references to the Project for use by the node context tasks |
9,715 | public static String getThreadLocalForProject ( final String nodeNameLocalRefId , final Project project ) { final Object o = project . getReference ( nodeNameLocalRefId ) ; String thrNode = null ; if ( null != o && o instanceof InheritableThreadLocal ) { InheritableThreadLocal < String > local = ( InheritableThreadLocal < String > ) o ; thrNode = local . get ( ) ; } return thrNode ; } | Extract the threadlocal stored as a reference in the project and return the string value or null . |
9,716 | public static void addNodeContextTasks ( final INodeEntry nodeentry , final Project project , final Sequential seq ) { final Task nodenamelocal = genSetThreadLocalRefValue ( NODE_NAME_LOCAL_REF_ID , nodeentry . getNodename ( ) ) ; nodenamelocal . setProject ( project ) ; seq . addTask ( nodenamelocal ) ; if ( null != nodeentry . extractUserName ( ) ) { final Task userlocal = genSetThreadLocalRefValue ( NODE_USER_LOCAL_REF_ID , nodeentry . extractUserName ( ) ) ; userlocal . setProject ( project ) ; seq . addTask ( userlocal ) ; } } | Add tasks to the Sequential to set threadlocal values for the node name and username |
9,717 | private static Task genSetThreadLocalRefValue ( final String refid , final String value ) { final SetThreadLocalTask task = new SetThreadLocalTask ( ) ; task . setRefid ( refid ) ; task . setValue ( value ) ; return task ; } | Return a task configured to set the thread local value for a particular refid |
9,718 | private String formatMessage ( final String message ) { if ( null != reformatter ) { return reformatter . reformat ( context , message ) ; } else { return message ; } } | Return the reformatted message or the original if no reformatter is specified . |
9,719 | private void writeBufferedData ( ) throws IOException { if ( buffer . length ( ) > 0 ) { out . write ( formatMessage ( buffer . toString ( ) ) . getBytes ( ) ) ; out . write ( '\n' ) ; buffer = new StringBuffer ( ) ; } } | If the buffer has content then reformat and write the content to the output stream . |
9,720 | public INodeSet getNodeSet ( ) { final NodeSetMerge list = getNodeSetMerge ( ) ; Map < String , Exception > exceptions = Collections . synchronizedMap ( new HashMap < > ( ) ) ; int index = 1 ; nodesSourceExceptions . clear ( ) ; for ( final ResourceModelSource nodesSource : getResourceModelSourcesInternal ( ) ) { try { INodeSet nodes = nodesSource . getNodes ( ) ; if ( null == nodes ) { logger . warn ( "Empty nodes result from [" + nodesSource . toString ( ) + "]" ) ; } else { list . addNodeSet ( nodes ) ; } if ( nodesSource instanceof ResourceModelSourceErrors ) { ResourceModelSourceErrors nodeerrors = ( ResourceModelSourceErrors ) nodesSource ; List < String > modelSourceErrors = nodeerrors . getModelSourceErrors ( ) ; if ( modelSourceErrors != null && modelSourceErrors . size ( ) > 0 ) { logger . error ( "Some errors getting nodes from [" + nodesSource . toString ( ) + "]: " + modelSourceErrors ) ; exceptions . put ( index + ".source" , new ResourceModelSourceException ( TextUtils . join ( modelSourceErrors . toArray ( new String [ 0 ] ) , ';' ) ) ) ; } } } catch ( ResourceModelSourceException | RuntimeException e ) { logger . error ( "Cannot get nodes from [" + nodesSource . toString ( ) + "]: " + e . getMessage ( ) ) ; logger . debug ( "Cannot get nodes from [" + nodesSource . toString ( ) + "]: " + e . getMessage ( ) , e ) ; exceptions . put ( index + ".source" , new ResourceModelSourceException ( e . getMessage ( ) , e ) ) ; } catch ( Throwable e ) { logger . error ( "Cannot get nodes from [" + nodesSource . toString ( ) + "]: " + e . getMessage ( ) ) ; logger . debug ( "Cannot get nodes from [" + nodesSource . toString ( ) + "]: " + e . getMessage ( ) , e ) ; exceptions . put ( index + ".source" , new ResourceModelSourceException ( e . getMessage ( ) ) ) ; } index ++ ; } synchronized ( nodesSourceExceptions ) { nodesSourceExceptions . putAll ( exceptions ) ; } return list ; } | Returns the set of nodes for the project |
9,721 | private synchronized void unloadSources ( ) { nodesSourceList = new ArrayList < > ( ) ; Closeables . closeQuietly ( nodeSourceReferences ) ; nodeSourceReferences = new HashSet < > ( ) ; sourcesOpened = false ; } | Clear the sources list and close all plugin loader references |
9,722 | public synchronized List < ExtPluginConfiguration > listNodeEnhancerConfigurations ( ) { return listPluginConfigurations ( projectConfig . getProjectProperties ( ) , NODE_ENHANCER_PROP_PREFIX , ServiceNameConstants . NodeEnhancer ) ; } | list the configurations of node enhancer providers . |
9,723 | public void addNode ( final INodeEntry node ) { final ResourceXMLParser . Entity entity = createEntity ( node ) ; addEntity ( entity ) ; } | Add Node object |
9,724 | private ResourceXMLParser . Entity createEntity ( final INodeEntry node ) { final ResourceXMLParser . Entity ent = new ResourceXMLParser . Entity ( ) ; ent . setName ( node . getNodename ( ) ) ; ent . setResourceType ( NODE_ENTITY_TAG ) ; if ( null != node . getAttributes ( ) ) { for ( final String setName : node . getAttributes ( ) . keySet ( ) ) { String value = node . getAttributes ( ) . get ( setName ) ; ent . setProperty ( setName , value ) ; } } if ( null != node . getTags ( ) ) { ent . setProperty ( "tags" , joinStrings ( node . getTags ( ) , ", " ) ) ; } return ent ; } | Create entity from Node |
9,725 | private static String joinStrings ( final Set tags , final String delim ) { ArrayList < String > strings = new ArrayList < String > ( tags ) ; String [ ] objects = strings . toArray ( new String [ strings . size ( ) ] ) ; Arrays . sort ( objects ) ; final StringBuffer sb = new StringBuffer ( ) ; for ( final String tag : objects ) { if ( sb . length ( ) > 0 ) { sb . append ( delim ) ; } sb . append ( tag ) ; } return sb . toString ( ) ; } | utility to join tags into string |
9,726 | public void generate ( ) throws IOException { final Document doc = DocumentFactory . getInstance ( ) . createDocument ( ) ; final Element root = doc . addElement ( "project" ) ; for ( final ResourceXMLParser . Entity entity : entities ) { if ( NODE_ENTITY_TAG . equals ( entity . getResourceType ( ) ) ) { final Element ent = genEntityCommon ( root , entity ) ; genNode ( ent , entity ) ; } } if ( null != file ) { FileOutputStream out = new FileOutputStream ( file ) ; try { serializeDocToStream ( out , doc ) ; } finally { out . close ( ) ; } } else if ( null != output ) { serializeDocToStream ( output , doc ) ; } } | Generate and store the XML file |
9,727 | private void genAttributes ( final Element ent , final ResourceXMLParser . Entity entity ) { if ( null == entity . getProperties ( ) ) { return ; } for ( final String key : entity . getProperties ( ) . stringPropertyNames ( ) ) { if ( ! ResourceXMLConstants . allPropSet . contains ( key ) ) { if ( isValidName ( key ) ) { ent . addAttribute ( key , entity . getProperties ( ) . getProperty ( key ) ) ; } else { final Element atelm = ent . addElement ( ATTRIBUTE_TAG ) ; atelm . addAttribute ( ATTRIBUTE_NAME_ATTR , key ) ; atelm . addAttribute ( ATTRIBUTE_VALUE_ATTR , entity . getProperties ( ) . getProperty ( key ) ) ; } } } } | Generate resources section and resource references |
9,728 | private void genNode ( final Element ent , final ResourceXMLParser . Entity entity ) { for ( final String nodeProp : nodeProps ) { ent . addAttribute ( nodeProp , notNull ( entity . getProperty ( nodeProp ) ) ) ; } genAttributes ( ent , entity ) ; } | Gen node tag contents |
9,729 | private Element genEntityCommon ( final Element root , final ResourceXMLParser . Entity entity ) { final Element tag = root . addElement ( entity . getResourceType ( ) ) ; tag . addAttribute ( COMMON_NAME , entity . getName ( ) ) ; tag . addAttribute ( COMMON_DESCRIPTION , notNull ( entity . getProperty ( COMMON_DESCRIPTION ) ) ) ; tag . addAttribute ( COMMON_TAGS , notNull ( entity . getProperty ( COMMON_TAGS ) ) ) ; return tag ; } | Create entity tag based on resourceType of entity and add common attributes |
9,730 | private static void serializeDocToStream ( final OutputStream output , final Document doc ) throws IOException { final OutputFormat format = OutputFormat . createPrettyPrint ( ) ; final XMLWriter writer = new XMLWriter ( output , format ) ; writer . write ( doc ) ; writer . flush ( ) ; } | Write Document to a file |
9,731 | public OutputStream removeThreadStream ( ) { final OutputStream orig = inheritOutputStream . get ( ) ; inheritOutputStream . set ( null ) ; return orig ; } | Remove the custom stream for the current thread . |
9,732 | public static Report errorReport ( String key , String message ) { return buildReport ( ) . error ( key , message ) . build ( ) ; } | Return a report for a single error item |
9,733 | private static void validate ( Properties props , Report report , List < Property > properties , PropertyScope ignoredScope ) { if ( null != properties ) { for ( final Property property : properties ) { if ( null != ignoredScope && property . getScope ( ) != null && property . getScope ( ) . compareTo ( ignoredScope ) <= 0 ) { continue ; } final String key = property . getName ( ) ; final String value = props . getProperty ( key ) ; if ( null == value || "" . equals ( value ) ) { if ( property . isRequired ( ) ) { report . errors . put ( key , "required" ) ; continue ; } } else { final PropertyValidator validator = property . getValidator ( ) ; if ( null != validator ) { try { if ( ! validator . isValid ( value ) ) { report . errors . put ( key , "Invalid value: " + value ) ; } } catch ( ValidationException e ) { report . errors . put ( key , "Invalid value: " + e . getMessage ( ) ) ; } } } } } } | Validate ignoring properties below a scope if set |
9,734 | public static Map < String , String > mapProperties ( final Map < String , String > input , final Description desc ) { final Map < String , String > mapping = desc . getPropertiesMapping ( ) ; if ( null == mapping ) { return input ; } return performMapping ( input , mapping , false ) ; } | Converts a set of input configuration keys using the description s configuration to property mapping or the same input if the description has no mapping |
9,735 | public static Map < String , String > performMapping ( final Map < String , String > input , final Map < String , String > mapping , final boolean skip ) { final Map < String , String > props = new HashMap < String , String > ( ) ; for ( final Map . Entry < String , String > entry : input . entrySet ( ) ) { if ( null != mapping . get ( entry . getKey ( ) ) ) { props . put ( mapping . get ( entry . getKey ( ) ) , entry . getValue ( ) ) ; } else if ( ! skip ) { props . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return props ; } | Convert input keys via the supplied mapping . |
9,736 | public static Map < String , String > demapProperties ( final Map < String , String > input , final Description desc ) { final Map < String , String > mapping = desc . getPropertiesMapping ( ) ; return demapProperties ( input , mapping , true ) ; } | Reverses a set of properties mapped using the description s configuration to property mapping or the same input if the description has no mapping |
9,737 | public static Map < String , String > demapProperties ( final Map < String , String > input , final Map < String , String > mapping , final boolean skip ) { if ( null == mapping ) { return input ; } final Map < String , String > rev = new HashMap < String , String > ( ) ; for ( final Map . Entry < String , String > entry : mapping . entrySet ( ) ) { rev . put ( entry . getValue ( ) , entry . getKey ( ) ) ; } return performMapping ( input , rev , skip ) ; } | Reverses a set of properties mapped using the specified property mapping or the same input if the description has no mapping |
9,738 | public static int copyStreamCount ( final InputStream in , final OutputStream out ) throws IOException { final byte [ ] buffer = new byte [ 10240 ] ; int tot = 0 ; int c ; c = in . read ( buffer ) ; while ( c >= 0 ) { if ( c > 0 ) { out . write ( buffer , 0 , c ) ; tot += c ; } c = in . read ( buffer ) ; } return tot ; } | Read the data from the input stream and copy to the outputstream . |
9,739 | public static int copyWriterCount ( final Reader in , final Writer out ) throws IOException { final char [ ] buffer = new char [ 10240 ] ; int tot = 0 ; int c ; c = in . read ( buffer ) ; while ( c >= 0 ) { if ( c > 0 ) { out . write ( buffer , 0 , c ) ; tot += c ; } c = in . read ( buffer ) ; } return tot ; } | Read the data from the reader and copy to the writer . |
9,740 | public static void copyStreamWithFilterSet ( final InputStream in , final OutputStream out , final FilterSet set ) throws IOException { final BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; final BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( out ) ) ; String lSep = System . getProperty ( "line.separator" ) ; String line = reader . readLine ( ) ; while ( null != line ) { writer . write ( set . replaceTokens ( line ) ) ; writer . write ( lSep ) ; line = reader . readLine ( ) ; } writer . flush ( ) ; } | Read the data from the input stream and write to the outputstream filtering with an Ant FilterSet . |
9,741 | public static Mapper concat ( final Mapper first , final Mapper second ) { return new ConcatMapper ( new Mapper [ ] { first , second } ) ; } | Concatenate two Mappers . |
9,742 | public static Collection map ( Mapper mapper , Object o ) { return java . util . Collections . singleton ( mapper . map ( o ) ) ; } | Trivial case of a single object . |
9,743 | public static Map makeMap ( Mapper mapper , Object [ ] a ) { return makeMap ( mapper , java . util . Arrays . asList ( a ) , false ) ; } | Create a new Map by using the array objects as keys and the mapping result as values . Discard keys which return null values from the mapper . |
9,744 | public static Map makeMap ( Mapper mapper , Collection c ) { return makeMap ( mapper , c . iterator ( ) , false ) ; } | Create a new Map by using the collection objects as keys and the mapping result as values . Discard keys which return null values from the mapper . |
9,745 | public static Map makeMap ( Mapper mapper , Collection c , boolean includeNull ) { return makeMap ( mapper , c . iterator ( ) , includeNull ) ; } | Create a new Map by using the collection objects as keys and the mapping result as values . |
9,746 | public static Map makeMap ( Mapper mapper , Iterator i ) { return makeMap ( mapper , i , false ) ; } | Create a new Map by using the iterator objects as keys and the mapping result as values . Discard keys which return null values from the mapper . |
9,747 | public static Map makeMap ( Mapper mapper , Iterator i , boolean includeNull ) { HashMap h = new HashMap ( ) ; for ( ; i . hasNext ( ) ; ) { Object k = i . next ( ) ; Object v = mapper . map ( k ) ; if ( includeNull || v != null ) { h . put ( k , v ) ; } } return h ; } | Create a new Map by using the iterator objects as keys and the mapping result as values . |
9,748 | public static Map makeMap ( Mapper mapper , Enumeration en ) { return makeMap ( mapper , en , false ) ; } | Create a new Map by using the enumeration objects as keys and the mapping result as values . Discard keys which return null values from the mapper . |
9,749 | public static Map makeMap ( Mapper mapper , Enumeration en , boolean includeNull ) { HashMap h = new HashMap ( ) ; for ( ; en . hasMoreElements ( ) ; ) { Object k = en . nextElement ( ) ; Object v = mapper . map ( k ) ; if ( includeNull || v != null ) { h . put ( k , v ) ; } } return h ; } | Create a new Map by using the enumeration objects as keys and the mapping result as values . |
9,750 | public static Mapper beanMapper ( final String property ) { return new Mapper ( ) { public Object map ( Object a ) { try { return BeanUtils . getProperty ( a , property ) ; } catch ( Exception e ) { throw new ClassCastException ( "Object was not the expected class: " + a . getClass ( ) ) ; } } } ; } | Create a mapper for bean properties |
9,751 | public static Mapper filterMapper ( final Predicate pred ) { return new Mapper ( ) { public Object map ( Object a ) { return pred . evaluate ( a ) ? a : null ; } } ; } | Return a mapper than maps an object to itself if the predicate evaluates to true and to null otherwise . |
9,752 | public ResourceFormatGenerator getGeneratorForFileExtension ( final File file ) throws UnsupportedFormatException { String extension = file . getName ( ) . lastIndexOf ( "." ) > 0 ? file . getName ( ) . substring ( file . getName ( ) . lastIndexOf ( "." ) + 1 ) : null ; if ( null != extension ) { return getGeneratorForFileExtension ( extension ) ; } else { throw new UnsupportedFormatException ( "Could not determine format for file: " + file . getAbsolutePath ( ) ) ; } } | Return a generator for a file based on the file extension . |
9,753 | public ResourceFormatGenerator getGeneratorForFileExtension ( final String extension ) throws UnsupportedFormatException { for ( final ResourceFormatGenerator generator : listGenerators ( ) ) { if ( generator . getFileExtensions ( ) . contains ( extension ) ) { return generator ; } } throw new UnsupportedFormatException ( "No provider available to parse file extension: " + extension ) ; } | Return a generator for a file based on the bare file extension . |
9,754 | public ResourceFormatGenerator getGeneratorForMIMEType ( final String mimeType ) throws UnsupportedFormatException { final String cleanMime ; if ( mimeType . indexOf ( ";" ) > 0 ) { cleanMime = mimeType . substring ( 0 , mimeType . indexOf ( ";" ) ) ; } else { cleanMime = mimeType ; } if ( ! ResourceFormatParserService . validMimeType ( cleanMime ) ) { throw new IllegalArgumentException ( "Invalid MIME type: " + mimeType ) ; } for ( final ResourceFormatGenerator generator : listGenerators ( ) ) { if ( null != generator . getMIMETypes ( ) ) { if ( generator . getMIMETypes ( ) . contains ( cleanMime ) ) { return generator ; } else { for ( final String s : generator . getMIMETypes ( ) ) { if ( ResourceFormatParserService . validMimeType ( s ) && cleanMime . startsWith ( "*/" ) ) { String t1 = cleanMime . substring ( 2 ) ; String t2 = s . substring ( s . indexOf ( "/" ) + 1 ) ; if ( t1 . equals ( t2 ) ) { return generator ; } } } } } } throw new UnsupportedFormatException ( "No provider available to parse MIME type: " + mimeType ) ; } | Return a generator for a mime type . |
9,755 | public static < T extends ContentMeta > TreeBuilder < T > builder ( ) { return new TreeBuilder < T > ( ) . base ( new EmptyTree < T > ( ) ) ; } | Build a new tree with an empty base |
9,756 | public static < T extends ContentMeta > TreeBuilder < T > builder ( Tree < T > base ) { return new TreeBuilder < T > ( ) . base ( base ) ; } | Build a new tree with given base |
9,757 | public TreeBuilder < T > subTree ( Path path , Tree < T > subtree , boolean fullPath ) { treeStack . add ( new SubPathTree < T > ( subtree , path , fullPath ) ) ; return this ; } | Add a tree responsible for a subpath of the base tree . |
9,758 | public TreeBuilder < T > convert ( ContentConverter < T > converter , Path path ) { return convert ( converter , PathUtil . subpathSelector ( path ) ) ; } | Convert data content for all resources below the given path |
9,759 | public TreeBuilder < T > convert ( ContentConverter < T > converter , PathSelector selector ) { return TreeBuilder . < T > builder ( new ConverterTree < T > ( build ( ) , converter , selector ) ) ; } | Convert data content for all resource paths matched by the path selector |
9,760 | public TreeBuilder < T > convert ( ContentConverter < T > converter , Path subpath , ResourceSelector < T > resourceSelector ) { return convert ( converter , PathUtil . subpathSelector ( subpath ) , resourceSelector ) ; } | Convert data content for all resources matching the resource selector and within the sub path |
9,761 | public TreeBuilder < T > convert ( ContentConverter < T > converter , PathSelector pathSelector , ResourceSelector < T > resourceSelector ) { return TreeBuilder . < T > builder ( new ConverterTree < T > ( build ( ) , converter , pathSelector , resourceSelector ) ) ; } | Convert data content for all resources matching the resource selector and the path selector |
9,762 | public TreeBuilder < T > convert ( ContentConverter < T > converter ) { return TreeBuilder . < T > builder ( new ConverterTree < T > ( build ( ) , converter , PathUtil . allpathSelector ( ) ) ) ; } | Convert all content in the tree |
9,763 | public TreeBuilder < T > listen ( Listener < T > listener ) { return listen ( listener , PathUtil . allpathSelector ( ) ) ; } | Listen to events on all paths of the tree |
9,764 | private TreeBuilder < T > listen ( Listener < T > listener , String resourceSelector ) { return TreeBuilder . < T > builder ( new ListenerTree < T > ( build ( ) , listener , PathUtil . < T > resourceSelector ( resourceSelector ) ) ) ; } | Listen to events on selective resources of the tree |
9,765 | public Tree < T > build ( ) { Tree < T > result = base ; if ( null == base && treeStack . size ( ) == 1 ) { result = treeStack . get ( 0 ) ; } else if ( treeStack . size ( ) > 0 ) { result = new TreeStack < T > ( treeStack , base ) ; } else if ( null == base ) { throw new IllegalArgumentException ( "base tree was not set" ) ; } return result ; } | Build the tree |
9,766 | public synchronized boolean needsReload ( final File file ) throws IOException { final long lastMod = file . lastModified ( ) ; if ( ! file . exists ( ) ) { mtimes . remove ( file ) ; } final Long aLong = mtimes . get ( file ) ; return null == aLong || lastMod > aLong ; } | Returns true if the file does not exist or has been modified since the last time it was loaded . |
9,767 | public synchronized Properties getProperties ( final File file ) throws IOException { final Properties fileprops ; if ( needsReload ( file ) ) { fileprops = new Properties ( ) ; final InputStream is = new FileInputStream ( file ) ; try { fileprops . load ( is ) ; } finally { if ( null != is ) { is . close ( ) ; } } mtimes . put ( file , file . lastModified ( ) ) ; props . put ( file , fileprops ) ; return fileprops ; } return props . get ( file ) ; } | Get the java Properties stored in the file loading from disk only if the file has been modified since the last read or the cached data has been invalidated . |
9,768 | public static Condition equalsCondition ( final StateObj state ) { return new Condition ( ) { public boolean test ( final StateObj input ) { return input . hasState ( state ) ; } public String toString ( ) { return "(State equals: " + state + ")" ; } } ; } | Create a condition when the given state is set |
9,769 | public static Condition matchesCondition ( String key , boolean keyRegex , String value , boolean valueRegex ) { return new MatchesCondition ( key , keyRegex , value , valueRegex ) ; } | Create a single match condition |
9,770 | public static boolean update ( RuleEngine ruleEngine , MutableStateObj state ) { StateObj newState = ruleEngine . evaluateRules ( state ) ; state . updateState ( newState ) ; return newState . getState ( ) . size ( ) > 0 ; } | Update the state by evaluating the rules and applying state changes |
9,771 | public static Map < String , Map < String , String > > merge ( final Map < String , Map < String , String > > targetContext , final Map < String , Map < String , String > > newContext ) { final HashMap < String , Map < String , String > > result = deepCopy ( targetContext ) ; for ( final Map . Entry < String , Map < String , String > > entry : newContext . entrySet ( ) ) { if ( ! targetContext . containsKey ( entry . getKey ( ) ) ) { result . put ( entry . getKey ( ) , new HashMap < > ( ) ) ; } else { result . put ( entry . getKey ( ) , new HashMap < > ( targetContext . get ( entry . getKey ( ) ) ) ) ; } result . get ( entry . getKey ( ) ) . putAll ( entry . getValue ( ) ) ; } return result ; } | Merge one context onto another by adding or replacing values in a new map |
9,772 | public static Map < String , Map < String , String > > addContext ( final String key , final Map < String , String > data , final Map < String , Map < String , String > > context ) { final Map < String , Map < String , String > > newdata = new HashMap < > ( ) ; if ( null != context ) { newdata . putAll ( context ) ; } newdata . put ( key , data ) ; return newdata ; } | Return a new context with appended data set |
9,773 | public static Map < String , String > generateEnvVarsFromData ( final Map < String , String > options , final String prefix ) { if ( null == options ) { return null ; } final HashMap < String , String > envs = new HashMap < String , String > ( ) ; for ( final Map . Entry < String , String > entry : options . entrySet ( ) ) { if ( null != entry . getKey ( ) && null != entry . getValue ( ) ) { envs . put ( generateEnvVarName ( prefix + "." + entry . getKey ( ) ) , entry . getValue ( ) ) ; } } return envs ; } | Convert option keys into environment variable names . Convert to uppercase and prepend RD_ |
9,774 | public static void addEnvVars ( final EnvironmentConfigurable sshexecTask , final Map < String , Map < String , String > > dataContext ) { final Map < String , String > environment = generateEnvVarsFromContext ( dataContext ) ; if ( null != environment ) { for ( final Map . Entry < String , String > entry : environment . entrySet ( ) ) { final String key = entry . getKey ( ) ; if ( null != key && null != entry . getValue ( ) ) { final Environment . Variable env = new Environment . Variable ( ) ; env . setKey ( key ) ; env . setValue ( entry . getValue ( ) ) ; sshexecTask . addEnv ( env ) ; } } } } | add Env elements to pass environment variables to the ExtSSHExec |
9,775 | public static Map < String , String > nodeData ( final INodeEntry nodeentry ) { final HashMap < String , String > data = new HashMap < String , String > ( ) ; if ( null != nodeentry ) { HashSet < String > skipProps = new HashSet < String > ( ) ; skipProps . addAll ( Arrays . asList ( "nodename" , "osName" , "osVersion" , "osArch" , "osFamily" ) ) ; data . put ( "name" , notNull ( nodeentry . getNodename ( ) ) ) ; data . put ( "hostname" , notNull ( nodeentry . getHostname ( ) ) ) ; data . put ( "os-name" , notNull ( nodeentry . getOsName ( ) ) ) ; data . put ( "os-version" , notNull ( nodeentry . getOsVersion ( ) ) ) ; data . put ( "os-arch" , notNull ( nodeentry . getOsArch ( ) ) ) ; data . put ( "os-family" , notNull ( nodeentry . getOsFamily ( ) ) ) ; data . put ( "username" , notNull ( nodeentry . getUsername ( ) ) ) ; data . put ( "description" , notNull ( nodeentry . getDescription ( ) ) ) ; data . put ( "tags" , null != nodeentry . getTags ( ) ? join ( nodeentry . getTags ( ) , "," ) : "" ) ; if ( null != nodeentry . getAttributes ( ) ) { for ( final String name : nodeentry . getAttributes ( ) . keySet ( ) ) { if ( null != nodeentry . getAttributes ( ) . get ( name ) && ! data . containsKey ( name ) && ! skipProps . contains ( name ) ) { data . put ( name , notNull ( nodeentry . getAttributes ( ) . get ( name ) ) ) ; } } } } return data ; } | Generate a dataset for a INodeEntry |
9,776 | public static String join ( final Collection < String > list , final String separator ) { final StringBuilder sb = new StringBuilder ( ) ; for ( final String s : list ) { if ( sb . length ( ) > 0 ) { sb . append ( separator ) ; } sb . append ( s ) ; } return sb . toString ( ) ; } | Join a list of strings into a single string with a separator |
9,777 | public static void addEnvVarsFromContextForExec ( final ExecTask execTask , final Map < String , Map < String , String > > dataContext ) { final Map < String , String > environment = generateEnvVarsFromContext ( dataContext ) ; if ( null != environment ) { for ( final Map . Entry < String , String > entry : environment . entrySet ( ) ) { final String key = entry . getKey ( ) ; if ( null != key && null != entry . getValue ( ) ) { final Environment . Variable env = new Environment . Variable ( ) ; env . setKey ( key ) ; env . setValue ( entry . getValue ( ) ) ; execTask . addEnv ( env ) ; } } } } | Add embedded env elements for any included context data for the script |
9,778 | private void setSubjectPrincipals ( ) { if ( null != userPrincipal ) { this . subject . getPrincipals ( ) . add ( userPrincipal ) ; } if ( null != rolePrincipals ) { for ( Principal rolePrincipal : rolePrincipals ) { this . subject . getPrincipals ( ) . add ( rolePrincipal ) ; } } } | Set the principals for the Subject |
9,779 | public static < T , W > List < T > listFirst ( List < Pair < T , W > > list ) { ArrayList < T > ts = new ArrayList < T > ( ) ; for ( Pair < T , W > twPair : list ) { ts . add ( twPair . getFirst ( ) ) ; } return ts ; } | Return a List of the first items from a list of pairs |
9,780 | public static < T , W > List < W > listSecond ( List < Pair < T , W > > list ) { ArrayList < W > ts = new ArrayList < W > ( ) ; for ( Pair < T , W > twPair : list ) { ts . add ( twPair . getSecond ( ) ) ; } return ts ; } | Return a List of the second items from a list of pairs |
9,781 | public static GeneratedScript script ( final String script , final String [ ] args , final String fileExtension ) { return new GeneratedScriptBuilder ( script , args , fileExtension ) ; } | Create a script |
9,782 | private static String convert2PropName ( String argProp ) throws Exception { if ( ! argProp . startsWith ( "--" ) ) { throw new Exception ( "argument: " + argProp + " does not start with --" ) ; } if ( argProp . indexOf ( "=" ) == - 1 ) { throw new Exception ( "argument: " + argProp + " does not contain an = sign" ) ; } String argProperty = argProp . substring ( 2 ) ; if ( null == argProperty || "" . equals ( argProperty ) ) throw new Exception ( "argument: " + argProp + " not valid" ) ; String argPropName = argProperty . split ( "=" ) [ 0 ] ; if ( null == argPropName || "" . equals ( argPropName ) ) throw new Exception ( "argument: " + argProp + " not valid" ) ; int equalsAt = argProperty . indexOf ( '=' ) ; String argPropValue = argProperty . substring ( equalsAt + 1 ) ; if ( null == argPropValue || "" . equals ( argPropValue ) ) throw new Exception ( "argument: " + argProp + " not valid" ) ; return argPropName ; } | also check if it is a valid type of property |
9,783 | @ SuppressWarnings ( "unchecked" ) protected List getUserRoles ( DirContext dirContext , String username ) throws LoginException , NamingException { String userDn = _userRdnAttribute + "=" + username + "," + _userBaseDn ; return getUserRolesByDn ( dirContext , userDn , username ) ; } | attempts to get the users roles from the root context |
9,784 | @ SuppressWarnings ( "unchecked" ) public Hashtable getEnvironment ( ) { Properties env = new Properties ( ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , _contextFactory ) ; String url = null ; if ( _providerUrl != null ) { url = _providerUrl ; } else { if ( _hostname != null ) { url = "ldap://" + _hostname + "/" ; if ( _port != 0 ) { url += ":" + _port + "/" ; } LOG . warn ( "Using hostname and port. Use providerUrl instead: " + url ) ; } } env . put ( Context . PROVIDER_URL , url ) ; if ( _authenticationMethod != null ) { env . put ( Context . SECURITY_AUTHENTICATION , _authenticationMethod ) ; } if ( _bindDn != null ) { env . put ( Context . SECURITY_PRINCIPAL , _bindDn ) ; } if ( _bindPassword != null ) { env . put ( Context . SECURITY_CREDENTIALS , _bindPassword ) ; } env . put ( "com.sun.jndi.ldap.read.timeout" , Long . toString ( _timeoutRead ) ) ; env . put ( "com.sun.jndi.ldap.connect.timeout" , Long . toString ( _timeoutConnect ) ) ; if ( url != null && url . startsWith ( "ldaps" ) && _ldapsVerifyHostname ) { try { URI uri = new URI ( url ) ; HostnameVerifyingSSLSocketFactory . setTargetHost ( uri . getHost ( ) ) ; env . put ( "java.naming.ldap.factory.socket" , "com.dtolabs.rundeck.jetty.jaas.HostnameVerifyingSSLSocketFactory" ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; } } return env ; } | get the context for connection |
9,785 | public static Description buildDescriptionWith ( Consumer < DescriptionBuilder > builder ) { DescriptionBuilder builder1 = builder ( ) ; builder . accept ( builder1 ) ; return builder1 . build ( ) ; } | Build a description |
9,786 | public DescriptionBuilder property ( final Consumer < PropertyBuilder > builder ) { PropertyBuilder propertyBuilder = PropertyBuilder . builder ( ) ; builder . accept ( propertyBuilder ) ; replaceOrAddProperty ( propertyBuilder . build ( ) ) ; return this ; } | Add a new property or replace an existing property with the same name with a consumer |
9,787 | public DescriptionBuilder removeProperty ( final String name ) { final Property found = findProperty ( name ) ; if ( null != found ) { properties . remove ( found ) ; } return this ; } | Remove a previously defined property by name |
9,788 | public DescriptionBuilder metadata ( final String key , final String value ) { metadata . put ( key , value ) ; return this ; } | Set a metadata value |
9,789 | public static Set < Attribute > authorizationEnvironment ( final String project ) { return Collections . singleton ( new Attribute ( URI . create ( EnvironmentalContext . URI_BASE + "project" ) , project ) ) ; } | Creates an authorization environment for a project . |
9,790 | public static void createFileStructure ( final File projectDir ) throws IOException { if ( ! projectDir . exists ( ) && ! projectDir . mkdirs ( ) ) { throw new IOException ( "failed creating project base dir: " + projectDir . getAbsolutePath ( ) ) ; } final File etcDir = new File ( projectDir , FrameworkProject . ETC_DIR_NAME ) ; if ( ! etcDir . exists ( ) && ! etcDir . mkdirs ( ) ) { throw new IOException ( "failed creating project etc dir: " + etcDir . getAbsolutePath ( ) ) ; } } | Creates the file structure for a project |
9,791 | private List < INodeEntry > select ( final int count , final Collection < INodeEntry > nodes ) { List < INodeEntry > source = new ArrayList < > ( nodes ) ; List < INodeEntry > selected = new ArrayList < > ( ) ; int total = Math . min ( count , nodes . size ( ) ) ; for ( int i = 0 ; i < total ; i ++ ) { selected . add ( source . remove ( random . nextInt ( source . size ( ) ) ) ) ; } return selected ; } | Select count random items from the input nodes or if nodes is smaller than count reorders them |
9,792 | public Callable < ResponderResult > createSequence ( final Responder responder , final ResultHandler resultHandler ) { return new Sequence < > ( this , this . chainResponder ( responder , resultHandler ) ) ; } | Create a Callable that will execute another responder if this one is successful with a specified resultHandler for the second one . |
9,793 | private Decision evaluate ( Map < String , String > resource , Subject subject , String action , Set < Attribute > environment , List < AclRule > matchedRules ) { Decision decision = internalEvaluate ( resource , subject , action , environment , matchedRules ) ; if ( decision . isAuthorized ( ) ) { logger . info ( MessageFormat . format ( "Evaluating {0} ({1}ms)" , decision , decision . evaluationDuration ( ) ) ) ; } else { logger . warn ( MessageFormat . format ( "Evaluating {0} ({1}ms)" , decision , decision . evaluationDuration ( ) ) ) ; } return decision ; } | Return the evaluation decision for the resource subject action environment and contexts |
9,794 | @ SuppressWarnings ( "rawtypes" ) boolean predicateMatchRules ( final Map < String , String > resource , final Function < String , Predicate < String > > predicateTransformer , final Function < List , Predicate < String > > listpred , final Map < String , Object > ruleResource , final String sourceIdentity ) { for ( final Object o : ruleResource . entrySet ( ) ) { final Map . Entry entry = ( Map . Entry ) o ; final String key = ( String ) entry . getKey ( ) ; final Object test = entry . getValue ( ) ; final boolean matched = applyTest ( resource , predicateTransformer , key , test , listpred , sourceIdentity ) ; if ( ! matched ) { return false ; } } return true ; } | Return true if all entries in the match map pass the predicate tests for the resource |
9,795 | File resolveProviderConflict ( final Collection < FileCache . MemoFile > matched ) { final HashMap < File , VersionCompare > versions = new HashMap < File , VersionCompare > ( ) ; final ArrayList < File > toCompare = new ArrayList < File > ( ) ; for ( final FileCache . MemoFile file : matched ) { final String vers = getVersionForFile ( file . getFile ( ) ) ; if ( null != vers ) { versions . put ( file . getFile ( ) , VersionCompare . forString ( vers ) ) ; toCompare . add ( file . getFile ( ) ) ; } } final Comparator < File > c = new VersionCompare . fileComparator ( versions ) ; final List < File > sorted = new ArrayList < File > ( toCompare ) ; Collections . sort ( sorted , c ) ; if ( sorted . size ( ) > 0 ) { return sorted . get ( sorted . size ( ) - 1 ) ; } return null ; } | Return a single file that should be used among all te files matching a single provider identity or null if the conflict cannot be resolved . |
9,796 | public final File scanForFile ( final ProviderIdent ident ) throws PluginScannerException { if ( ! extdir . exists ( ) || ! extdir . isDirectory ( ) ) { return null ; } return scanFor ( ident , extdir . listFiles ( getFileFilter ( ) ) ) ; } | scan for matching file for the provider def |
9,797 | public boolean isExpired ( final ProviderIdent ident , final File file ) { return ! file . exists ( ) || ! scannedFiles . contains ( memoize ( file ) ) ; } | Return true if the entry has expired |
9,798 | private File scanFor ( final ProviderIdent ident , final File [ ] files ) throws PluginScannerException { final List < FileCache . MemoFile > candidates = new ArrayList < > ( ) ; HashSet < FileCache . MemoFile > prescanned = new HashSet < > ( scannedFiles ) ; HashSet < FileCache . MemoFile > newscanned = new HashSet < > ( ) ; for ( final File file : files ) { FileCache . MemoFile memo = memoize ( file ) ; if ( cachedFileValidity ( file ) ) { newscanned . add ( memo ) ; if ( test ( ident , file ) ) { candidates . add ( memo ) ; } } prescanned . remove ( memo ) ; } clearMemos ( prescanned ) ; scannedFiles = newscanned ; if ( candidates . size ( ) == 1 ) { return candidates . get ( 0 ) . getFile ( ) ; } if ( candidates . size ( ) > 1 ) { final File resolved = resolveProviderConflict ( candidates ) ; if ( null == resolved ) { log . warn ( "More than one plugin file matched: " + StringArrayUtil . asString ( candidates . toArray ( ) , "," ) + ": " + ident ) ; } else { return resolved ; } } return null ; } | Return the first valid file found |
9,799 | private String resolve ( final String propName ) { return ResolverUtil . resolveProperty ( propName , null , node , frameworkProject , framework ) ; } | Resolve a property by looking for node attribute project then framework value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.