idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
2,600
|
protected void addCachedExtensionVersion ( String feature , E extension ) { List < E > versions = this . extensionsVersions . get ( feature ) ; if ( versions == null ) { versions = new ArrayList < E > ( ) ; this . extensionsVersions . put ( feature , versions ) ; versions . add ( extension ) ; } else { int index = 0 ; while ( index < versions . size ( ) && extension . getId ( ) . getVersion ( ) . compareTo ( versions . get ( index ) . getId ( ) . getVersion ( ) ) < 0 ) { ++ index ; } versions . add ( index , extension ) ; } }
|
Register extension in all caches .
|
2,601
|
protected void removeCachedExtension ( E extension ) { this . extensions . remove ( extension . getId ( ) ) ; removeCachedExtensionVersion ( extension . getId ( ) . getId ( ) , extension ) ; if ( ! this . strictId ) { for ( String feature : extension . getFeatures ( ) ) { removeCachedExtensionVersion ( feature , extension ) ; } } }
|
Remove extension from all caches .
|
2,602
|
protected void removeCachedExtensionVersion ( String feature , E extension ) { List < E > extensionVersions = this . extensionsVersions . get ( feature ) ; extensionVersions . remove ( extension ) ; if ( extensionVersions . isEmpty ( ) ) { this . extensionsVersions . remove ( feature ) ; } }
|
Remove passed extension associated to passed feature from the cache .
|
2,603
|
public static byte [ ] convert ( char [ ] password , ToBytesMode mode ) { byte [ ] passwd ; switch ( mode ) { case PKCS12 : passwd = PBEParametersGenerator . PKCS12PasswordToBytes ( password ) ; break ; case PKCS5 : passwd = PBEParametersGenerator . PKCS5PasswordToBytes ( password ) ; break ; default : passwd = PBEParametersGenerator . PKCS5PasswordToUTF8Bytes ( password ) ; break ; } return passwd ; }
|
Convert password to bytes .
|
2,604
|
public static String getPrefix ( String namespaceString ) { Namespace namespace = toNamespace ( namespaceString ) ; return namespace != null ? namespace . getType ( ) : null ; }
|
Extract prefix of the id used to find custom factory .
|
2,605
|
private void filter ( Element list ) { Node child = list . getFirstChild ( ) ; Node previousListItem = null ; while ( child != null ) { Node nextSibling = child . getNextSibling ( ) ; if ( isAllowedInsideList ( child ) ) { if ( child . getNodeName ( ) . equalsIgnoreCase ( TAG_LI ) ) { previousListItem = child ; } } else { if ( previousListItem == null ) { previousListItem = list . getOwnerDocument ( ) . createElement ( TAG_LI ) ; list . insertBefore ( previousListItem , child ) ; ( ( Element ) previousListItem ) . setAttribute ( ATTRIBUTE_STYLE , "list-style-type: none" ) ; } previousListItem . appendChild ( child ) ; } child = nextSibling ; } }
|
Transforms the given list in a valid XHTML list by moving the nodes that are not allowed inside < ; ul> ; and < ; ol> ; in < ; li> ; elements .
|
2,606
|
private boolean isAllowedInsideList ( Node node ) { return ( node . getNodeType ( ) != Node . ELEMENT_NODE || node . getNodeName ( ) . equalsIgnoreCase ( TAG_LI ) ) && ( node . getNodeType ( ) != Node . TEXT_NODE || node . getNodeValue ( ) . trim ( ) . length ( ) == 0 ) ; }
|
Checks if a given node is allowed or not as a child of a < ; ul> ; or < ; ol> ; element .
|
2,607
|
private ComponentDescriptor createComponentDescriptor ( Class < ? > componentClass , String hint , Type componentRoleType ) { DefaultComponentDescriptor descriptor = new DefaultComponentDescriptor ( ) ; descriptor . setRoleType ( componentRoleType ) ; descriptor . setImplementation ( componentClass ) ; descriptor . setRoleHint ( hint ) ; descriptor . setInstantiationStrategy ( createComponentInstantiationStrategy ( componentClass ) ) ; for ( Field field : ReflectionUtils . getAllFields ( componentClass ) ) { ComponentDependency dependency = createComponentDependency ( field ) ; if ( dependency != null ) { descriptor . addComponentDependency ( dependency ) ; } } return descriptor ; }
|
Create a component descriptor for the passed component implementation class hint and component role class .
|
2,608
|
public synchronized void flushEvents ( ) { while ( ! this . events . isEmpty ( ) ) { ComponentEventEntry entry = this . events . pop ( ) ; sendEvent ( entry . event , entry . descriptor , entry . componentManager ) ; } }
|
Force to send all stored events .
|
2,609
|
private void notifyComponentEvent ( Event event , ComponentDescriptor < ? > descriptor , ComponentManager componentManager ) { if ( this . shouldStack ) { synchronized ( this ) { this . events . push ( new ComponentEventEntry ( event , descriptor , componentManager ) ) ; } } else { sendEvent ( event , descriptor , componentManager ) ; } }
|
Send or stack the provided event dependening on the configuration .
|
2,610
|
private void sendEvent ( Event event , ComponentDescriptor < ? > descriptor , ComponentManager componentManager ) { if ( this . observationManager != null ) { this . observationManager . notify ( event , componentManager , descriptor ) ; } }
|
Send the event .
|
2,611
|
public static CertifyingSigner getInstance ( boolean forSigning , CertifiedKeyPair certifier , SignerFactory factory ) { return new CertifyingSigner ( certifier . getCertificate ( ) , factory . getInstance ( forSigning , certifier . getPrivateKey ( ) ) ) ; }
|
Get a certifying signer instance from the given signer factory for a given certifier .
|
2,612
|
protected void jobStarting ( ) { this . jobContext . pushCurrentJob ( this ) ; this . observationManager . notify ( new JobStartedEvent ( getRequest ( ) . getId ( ) , getType ( ) , this . request ) , this ) ; if ( this . status instanceof AbstractJobStatus ) { ( ( AbstractJobStatus < R > ) this . status ) . setStartDate ( new Date ( ) ) ; ( ( AbstractJobStatus < R > ) this . status ) . setState ( JobStatus . State . RUNNING ) ; ( ( AbstractJobStatus ) this . status ) . startListening ( ) ; } if ( getRequest ( ) . isVerbose ( ) ) { if ( getStatus ( ) . getRequest ( ) . getId ( ) != null ) { this . logger . info ( LOG_BEGIN_ID , "Starting job of type [{}] with identifier [{}]" , getType ( ) , getStatus ( ) . getRequest ( ) . getId ( ) ) ; } else { this . logger . info ( LOG_BEGIN , "Starting job of type [{}]" , getType ( ) ) ; } } }
|
Called when the job is starting .
|
2,613
|
protected void jobFinished ( Throwable error ) { this . lock . lock ( ) ; try { if ( this . status instanceof AbstractJobStatus ) { ( ( AbstractJobStatus ) this . status ) . setError ( error ) ; } this . observationManager . notify ( new JobFinishingEvent ( getRequest ( ) . getId ( ) , getType ( ) , this . request ) , this , error ) ; if ( getRequest ( ) . isVerbose ( ) ) { if ( getStatus ( ) . getRequest ( ) . getId ( ) != null ) { this . logger . info ( LOG_END_ID , "Finished job of type [{}] with identifier [{}]" , getType ( ) , getStatus ( ) . getRequest ( ) . getId ( ) ) ; } else { this . logger . info ( LOG_END , "Finished job of type [{}]" , getType ( ) ) ; } } if ( this . status instanceof AbstractJobStatus ) { ( ( AbstractJobStatus ) this . status ) . setEndDate ( new Date ( ) ) ; ( ( AbstractJobStatus ) this . status ) . stopListening ( ) ; ( ( AbstractJobStatus ) this . status ) . setState ( JobStatus . State . FINISHED ) ; } this . finishedCondition . signalAll ( ) ; this . jobContext . popCurrentJob ( ) ; try { if ( this . request . getId ( ) != null ) { this . store . storeAsync ( this . status ) ; } } catch ( Throwable t ) { this . logger . warn ( LOG_STATUS_STORE_FAILED , "Failed to store job status [{}]" , this . status , t ) ; } } finally { this . lock . unlock ( ) ; this . observationManager . notify ( new JobFinishedEvent ( getRequest ( ) . getId ( ) , getType ( ) , this . request ) , this , error ) ; } }
|
Called when the job is done .
|
2,614
|
protected void initializeUberspector ( String classname ) { if ( ! StringUtils . isEmpty ( classname ) && ! classname . equals ( this . getClass ( ) . getCanonicalName ( ) ) ) { Uberspect u = instantiateUberspector ( classname ) ; if ( u == null ) { return ; } if ( u instanceof UberspectLoggable ) { ( ( UberspectLoggable ) u ) . setLog ( this . log ) ; } if ( u instanceof RuntimeServicesAware ) { ( ( RuntimeServicesAware ) u ) . setRuntimeServices ( this . runtime ) ; } try { u . init ( ) ; this . uberspectors . add ( u ) ; } catch ( Exception e ) { this . log . warn ( e . getMessage ( ) ) ; } } }
|
Instantiates and initializes an uberspector class and adds it to the array . Also set the log and runtime services if the class implements the proper interfaces .
|
2,615
|
protected Uberspect instantiateUberspector ( String classname ) { Object o = null ; try { o = ClassUtils . getNewInstance ( classname ) ; } catch ( ClassNotFoundException e ) { this . log . warn ( String . format ( "The specified uberspector [%s]" + " does not exist or is not accessible to the current classloader." , classname ) ) ; } catch ( IllegalAccessException e ) { this . log . warn ( String . format ( "The specified uberspector [%s] does not have a public default constructor." , classname ) ) ; } catch ( InstantiationException e ) { this . log . warn ( String . format ( "The specified uberspector [%s] cannot be instantiated." , classname ) ) ; } catch ( ExceptionInInitializerError e ) { this . log . warn ( String . format ( "Exception while instantiating the Uberspector [%s]: %s" , classname , e . getMessage ( ) ) ) ; } if ( ! ( o instanceof Uberspect ) ) { if ( o != null ) { this . log . warn ( "The specified class for Uberspect [" + classname + "] does not implement " + Uberspect . class . getName ( ) ) ; } return null ; } return ( Uberspect ) o ; }
|
Tries to create an uberspector instance using reflection .
|
2,616
|
private void validateExtension ( LocalExtension localExtension , boolean dependencies ) { Collection < String > namespaces = DefaultInstalledExtension . getNamespaces ( localExtension ) ; if ( namespaces == null ) { if ( dependencies || ! DefaultInstalledExtension . isDependency ( localExtension , null ) ) { try { validateExtension ( localExtension , null , Collections . emptyMap ( ) ) ; } catch ( InvalidExtensionException e ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . warn ( "Invalid extension [{}]" , localExtension . getId ( ) , e ) ; } else { this . logger . warn ( "Invalid extension [{}] ({})" , localExtension . getId ( ) , ExceptionUtils . getRootCauseMessage ( e ) ) ; } addInstalledExtension ( localExtension , null , false ) ; } } } else { for ( String namespace : namespaces ) { if ( dependencies || ! DefaultInstalledExtension . isDependency ( localExtension , namespace ) ) { try { validateExtension ( localExtension , namespace , Collections . emptyMap ( ) ) ; } catch ( InvalidExtensionException e ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . warn ( "Invalid extension [{}] on namespace [{}]" , localExtension . getId ( ) , namespace , e ) ; } else { this . logger . warn ( "Invalid extension [{}] on namespace [{}] ({})" , localExtension . getId ( ) , namespace , ExceptionUtils . getRootCauseMessage ( e ) ) ; } addInstalledExtension ( localExtension , namespace , false ) ; } } } } }
|
Check extension validity and set it as not installed if not .
|
2,617
|
private DefaultInstalledExtension validateExtension ( LocalExtension localExtension , String namespace , Map < String , ExtensionDependency > managedDependencies ) throws InvalidExtensionException { DefaultInstalledExtension installedExtension = this . extensions . get ( localExtension . getId ( ) ) ; if ( installedExtension != null && installedExtension . isValidated ( namespace ) ) { return installedExtension ; } if ( namespace != null && DefaultInstalledExtension . getNamespaces ( localExtension ) == null ) { return validateExtension ( localExtension , null , managedDependencies ) ; } if ( ! DefaultInstalledExtension . isInstalled ( localExtension , namespace ) ) { throw new InvalidExtensionException ( String . format ( "Extension [%s] is not installed" , localExtension ) ) ; } if ( this . coreExtensionRepository . exists ( localExtension . getId ( ) . getId ( ) ) ) { throw new InvalidExtensionException ( String . format ( "Extension [%s] already exists as a core extension" , localExtension ) ) ; } InvalidExtensionException dependencyException = null ; for ( ExtensionDependency dependency : localExtension . getDependencies ( ) ) { try { dependency = ExtensionUtils . getDependency ( dependency , managedDependencies , localExtension ) ; validateDependency ( dependency , namespace , ExtensionUtils . append ( managedDependencies , localExtension ) ) ; } catch ( InvalidExtensionException e ) { if ( ! dependency . isOptional ( ) ) { if ( dependencyException == null ) { dependencyException = e ; } } } } if ( dependencyException != null ) { throw dependencyException ; } return localExtension instanceof DefaultInstalledExtension ? ( DefaultInstalledExtension ) localExtension : addInstalledExtension ( localExtension , namespace , true ) ; }
|
Check extension validity against a specific namespace .
|
2,618
|
public static void setFieldValue ( Object instanceContainingField , String fieldName , Object fieldValue ) { Class < ? > targetClass = instanceContainingField . getClass ( ) ; while ( targetClass != null ) { for ( Field field : targetClass . getDeclaredFields ( ) ) { if ( field . getName ( ) . equalsIgnoreCase ( fieldName ) ) { try { boolean isAccessible = field . isAccessible ( ) ; try { field . setAccessible ( true ) ; field . set ( instanceContainingField , fieldValue ) ; } finally { field . setAccessible ( isAccessible ) ; } } catch ( Exception e ) { throw new RuntimeException ( "Failed to set field [" + fieldName + "] in instance of [" + instanceContainingField . getClass ( ) . getName ( ) + "]. The Java Security Manager has " + "probably been configured to prevent settting private field values. XWiki requires " + "this ability to work." , e ) ; } return ; } } targetClass = targetClass . getSuperclass ( ) ; } }
|
Sets a value to a field using reflection even if the field is private .
|
2,619
|
public static Type resolveType ( Type targetType , Type rootType ) { Type resolvedType ; if ( targetType instanceof ParameterizedType && rootType instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) targetType ; resolvedType = resolveType ( ( Class < ? > ) parameterizedType . getRawType ( ) , parameterizedType . getActualTypeArguments ( ) , getTypeClass ( rootType ) ) ; } else { resolvedType = resolveType ( getTypeClass ( rootType ) , null , getTypeClass ( targetType ) ) ; } return resolvedType ; }
|
Find and replace the generic parameters with the real types .
|
2,620
|
public static String serializeType ( Type type ) { if ( type == null ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; String rawTypeName = getTypeName ( parameterizedType . getRawType ( ) ) ; if ( parameterizedType . getOwnerType ( ) != null ) { if ( parameterizedType . getOwnerType ( ) instanceof Class ) { sb . append ( ( ( Class < ? > ) parameterizedType . getOwnerType ( ) ) . getName ( ) ) ; } else { sb . append ( parameterizedType . getOwnerType ( ) . toString ( ) ) ; } sb . append ( '.' ) ; if ( parameterizedType . getOwnerType ( ) instanceof ParameterizedType ) { sb . append ( rawTypeName . replace ( ( ( Class < ? > ) ( ( ParameterizedType ) parameterizedType . getOwnerType ( ) ) . getRawType ( ) ) . getName ( ) + '$' , "" ) ) ; } else { sb . append ( rawTypeName ) ; } } else { sb . append ( rawTypeName ) ; } if ( parameterizedType . getActualTypeArguments ( ) != null && parameterizedType . getActualTypeArguments ( ) . length > 0 ) { sb . append ( OPEN_GENERIC ) ; boolean first = true ; for ( Type typeArgument : parameterizedType . getActualTypeArguments ( ) ) { if ( ! first ) { sb . append ( ", " ) ; } sb . append ( getTypeName ( typeArgument ) ) ; first = false ; } sb . append ( CLOSE_GENERIC ) ; } } else { sb . append ( getTypeName ( type ) ) ; } return sb . toString ( ) ; }
|
Serialize a type in a String using a standard definition .
|
2,621
|
public V get ( K key , V defaultValue ) { V sharedValue = get ( key ) ; if ( sharedValue == null ) { sharedValue = defaultValue ; put ( key , defaultValue ) ; } return sharedValue ; }
|
Get the value associated to the passed key . If no value can be found stored and return the passed default value .
|
2,622
|
public void put ( K key , V value ) { this . lock . writeLock ( ) . lock ( ) ; try { this . map . put ( key , new SoftReference < > ( value ) ) ; } finally { this . lock . writeLock ( ) . unlock ( ) ; } }
|
Associate passed key to passed value .
|
2,623
|
private void cacheEntryInserted ( String key , T value ) { InfinispanCacheEntryEvent < T > event = new InfinispanCacheEntryEvent < > ( new InfinispanCacheEntry < T > ( this , key , value ) ) ; T previousValue = this . preEventData . get ( key ) ; if ( previousValue != null ) { if ( previousValue != value ) { disposeCacheValue ( previousValue ) ; } sendEntryModifiedEvent ( event ) ; } else { sendEntryAddedEvent ( event ) ; } }
|
Dispatch data insertion event .
|
2,624
|
private void cacheEntryRemoved ( String key , T value ) { InfinispanCacheEntryEvent < T > event = new InfinispanCacheEntryEvent < > ( new InfinispanCacheEntry < T > ( this , key , value ) ) ; sendEntryRemovedEvent ( event ) ; }
|
Dispatch data remove event .
|
2,625
|
private void checkNonCoreGroupId ( Model model ) throws EnforcerRuleException { String groupId = model . getGroupId ( ) ; if ( groupId . equals ( CORE_GROUP_ID ) || ( groupId . startsWith ( CORE_GROUP_ID_PREFIX ) && ! groupId . equals ( CONTRIB_GROUP_ID ) && ! groupId . startsWith ( CONTRIB_GROUP_ID_PREFIX ) ) ) { throw new EnforcerRuleException ( String . format ( "Contrib extension group id have to be prefixed with [%s]" , CONTRIB_GROUP_ID ) ) ; } }
|
Make sure the group id does not start with org . xwiki or starts with org . xwiki . contrib .
|
2,626
|
private void checkNonCoreArtifactId ( Model model ) throws EnforcerRuleException { String artifactId = model . getArtifactId ( ) ; for ( String prefix : CORE_ARTIFACT_ID_PREFIXES ) { if ( artifactId . startsWith ( prefix ) ) { throw new EnforcerRuleException ( "The [%s] artifact id prefix is reserved for XWiki Core Committers." ) ; } } }
|
Make sure that non core artifacts don t use reserved artifact prefixes .
|
2,627
|
public void writeStartDocument ( String encoding , String version ) throws FilterException { try { this . writer . writeStartDocument ( encoding , version ) ; } catch ( XMLStreamException e ) { throw new FilterException ( "Failed to write start document" , e ) ; } }
|
Write the XML Declaration .
|
2,628
|
private String getTypeName ( Type type ) { String name ; if ( type instanceof Class ) { name = ( ( Class < ? > ) type ) . getName ( ) ; } else if ( type instanceof ParameterizedType ) { name = ( ( Class < ? > ) ( ( ParameterizedType ) type ) . getRawType ( ) ) . getName ( ) ; } else { name = type . toString ( ) ; } return name ; }
|
Get class name without generics .
|
2,629
|
private String getTypeGenericName ( Type type ) { StringBuilder sb = new StringBuilder ( getTypeName ( type ) ) ; if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Type [ ] generics = parameterizedType . getActualTypeArguments ( ) ; if ( generics . length > 0 ) { sb . append ( '<' ) ; for ( int i = 0 ; i < generics . length ; ++ i ) { if ( i > 0 ) { sb . append ( ',' ) ; } sb . append ( getTypeGenericName ( generics [ i ] ) ) ; } sb . append ( '>' ) ; } } return sb . toString ( ) ; }
|
Get type name .
|
2,630
|
public void updateExtensions ( ) { Thread thread = new Thread ( new Runnable ( ) { public void run ( ) { DefaultCoreExtensionRepository . this . scanner . updateExtensions ( DefaultCoreExtensionRepository . this . extensions . values ( ) ) ; } } ) ; thread . setPriority ( Thread . MIN_PRIORITY ) ; thread . setDaemon ( true ) ; thread . setName ( "Core extension repository updater" ) ; thread . start ( ) ; }
|
Update core extensions only if there is any remote repository and it s not disabled .
|
2,631
|
public void startListening ( ) { this . observationManager . addListener ( new WrappedThreadEventListener ( this . progress ) ) ; this . logListener = new LoggerListener ( LoggerListener . class . getName ( ) + '_' + hashCode ( ) , this . logs ) ; if ( isIsolated ( ) ) { this . loggerManager . pushLogListener ( this . logListener ) ; } else { this . observationManager . addListener ( new WrappedThreadEventListener ( this . logListener ) ) ; } }
|
Start listening to events .
|
2,632
|
public void stopListening ( ) { if ( isIsolated ( ) ) { this . loggerManager . popLogListener ( ) ; } else { this . observationManager . removeListener ( this . logListener . getName ( ) ) ; } this . observationManager . removeListener ( this . progress . getName ( ) ) ; this . progress . getRootStep ( ) . finish ( ) ; }
|
Stop listening to events .
|
2,633
|
public < E > List < InlineDiffChunk < E > > inline ( List < E > previous , List < E > next ) { setError ( null ) ; try { return this . inlineDiffDisplayer . display ( this . diffManager . diff ( previous , next , null ) ) ; } catch ( DiffException e ) { setError ( e ) ; return null ; } }
|
Builds an in - line diff between two versions of a list of elements .
|
2,634
|
public List < InlineDiffChunk < Character > > inline ( String previous , String next ) { setError ( null ) ; try { return this . inlineDiffDisplayer . display ( this . diffManager . diff ( this . charSplitter . split ( previous ) , this . charSplitter . split ( next ) , null ) ) ; } catch ( DiffException e ) { setError ( e ) ; return null ; } }
|
Builds an in - line diff between two versions of a text .
|
2,635
|
public X509CertificateHolder getCertificate ( Selector selector ) { try { return ( X509CertificateHolder ) this . store . getMatches ( selector ) . iterator ( ) . next ( ) ; } catch ( Throwable t ) { return null ; } }
|
Get the first certificate matching the provided selector .
|
2,636
|
public void initialize ( ComponentManager manager , ClassLoader classLoader ) { try { List < ComponentDeclaration > componentDeclarations = getDeclaredComponents ( classLoader , COMPONENT_LIST ) ; List < ComponentDeclaration > componentOverrideDeclarations = getDeclaredComponents ( classLoader , COMPONENT_OVERRIDE_LIST ) ; for ( ComponentDeclaration componentOverrideDeclaration : componentOverrideDeclarations ) { componentDeclarations . remove ( componentOverrideDeclaration ) ; componentDeclarations . add ( new ComponentDeclaration ( componentOverrideDeclaration . getImplementationClassName ( ) , 0 ) ) ; } initialize ( manager , classLoader , componentDeclarations ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to get the list of components to load" , e ) ; } }
|
Loads all components defined using annotations .
|
2,637
|
private Collection < ComponentDescriptor < ? > > getComponentsDescriptors ( ClassLoader classLoader , List < ComponentDeclaration > componentDeclarations ) { Map < RoleHint < ? > , ComponentDescriptor < ? > > descriptorMap = new HashMap < > ( ) ; Map < RoleHint < ? > , Integer > priorityMap = new HashMap < > ( ) ; for ( ComponentDeclaration componentDeclaration : componentDeclarations ) { Class < ? > componentClass ; try { componentClass = classLoader . loadClass ( componentDeclaration . getImplementationClassName ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( String . format ( "Failed to load component class [%s] for annotation parsing" , componentDeclaration . getImplementationClassName ( ) ) , e ) ; } for ( Type componentRoleType : findComponentRoleTypes ( componentClass ) ) { for ( ComponentDescriptor < ? > componentDescriptor : this . factory . createComponentDescriptors ( componentClass , componentRoleType ) ) { RoleHint < ? > roleHint = new RoleHint ( componentDescriptor . getRoleType ( ) , componentDescriptor . getRoleHint ( ) ) ; addComponent ( descriptorMap , priorityMap , roleHint , componentDescriptor , componentDeclaration , true ) ; } } } return descriptorMap . values ( ) ; }
|
Find all component descriptors out of component declarations .
|
2,638
|
private List < ComponentDeclaration > getDeclaredComponents ( ClassLoader classLoader , String location ) throws IOException { List < ComponentDeclaration > annotatedClassNames = new ArrayList < > ( ) ; Enumeration < URL > urls = classLoader . getResources ( location ) ; while ( urls . hasMoreElements ( ) ) { URL url = urls . nextElement ( ) ; LOGGER . debug ( "Loading declared component definitions from [{}]" , url ) ; InputStream componentListStream = url . openStream ( ) ; try { annotatedClassNames . addAll ( getDeclaredComponents ( componentListStream ) ) ; } finally { componentListStream . close ( ) ; } } return annotatedClassNames ; }
|
Get all components listed in the passed resource file .
|
2,639
|
public List < ComponentDeclaration > getDeclaredComponentsFromJAR ( InputStream jarFile ) throws IOException { ZipInputStream zis = new ZipInputStream ( jarFile ) ; List < ComponentDeclaration > componentDeclarations = null ; List < ComponentDeclaration > componentOverrideDeclarations = null ; for ( ZipEntry entry = zis . getNextEntry ( ) ; entry != null && ( componentDeclarations == null || componentOverrideDeclarations == null ) ; entry = zis . getNextEntry ( ) ) { if ( entry . getName ( ) . equals ( ComponentAnnotationLoader . COMPONENT_LIST ) ) { componentDeclarations = getDeclaredComponents ( zis ) ; } else if ( entry . getName ( ) . equals ( ComponentAnnotationLoader . COMPONENT_OVERRIDE_LIST ) ) { componentOverrideDeclarations = getDeclaredComponents ( zis ) ; } } if ( componentOverrideDeclarations != null ) { if ( componentDeclarations == null ) { componentDeclarations = new ArrayList < > ( ) ; } for ( ComponentDeclaration componentOverrideDeclaration : componentOverrideDeclarations ) { componentDeclarations . add ( new ComponentDeclaration ( componentOverrideDeclaration . getImplementationClassName ( ) , 0 ) ) ; } } return componentDeclarations ; }
|
Get all components listed in a JAR file .
|
2,640
|
public CertifiedPublicKey convert ( X509CertificateHolder cert ) { if ( cert == null ) { return null ; } return new BcX509CertifiedPublicKey ( cert , this . factory ) ; }
|
Convert Bouncy Castle certificate holder .
|
2,641
|
private void surroundWithParagraph ( Document document , Node body , Node beginNode , Node endNode ) { Element paragraph = document . createElement ( TAG_P ) ; body . insertBefore ( paragraph , beginNode ) ; Node child = beginNode ; while ( child != endNode ) { Node nextChild = child . getNextSibling ( ) ; paragraph . appendChild ( body . removeChild ( child ) ) ; child = nextChild ; } }
|
Surround passed nodes with a paragraph element .
|
2,642
|
private void validateBean ( Object bean ) throws PropertyException { if ( getValidatorFactory ( ) != null ) { Validator validator = getValidatorFactory ( ) . getValidator ( ) ; Set < ConstraintViolation < Object > > constraintViolations = validator . validate ( bean ) ; if ( ! constraintViolations . isEmpty ( ) ) { throw new PropertyException ( "Failed to validate bean: [" + constraintViolations . iterator ( ) . next ( ) . getMessage ( ) + "]" ) ; } } }
|
Validate populated values based on JSR 303 .
|
2,643
|
public < E > DiffResult < E > diff ( List < E > previous , List < E > next , DiffConfiguration < E > configuration ) { DiffResult < E > result ; try { result = this . diffManager . diff ( previous , next , configuration ) ; } catch ( DiffException e ) { result = new DefaultDiffResult < E > ( previous , next ) ; result . getLog ( ) . error ( "Failed to execute diff" , e ) ; } return result ; }
|
Produce a diff between the two provided versions .
|
2,644
|
public < E > MergeResult < E > merge ( List < E > commonAncestor , List < E > next , List < E > current , MergeConfiguration < E > configuration ) { MergeResult < E > result ; try { result = this . diffManager . merge ( commonAncestor , next , current , configuration ) ; } catch ( MergeException e ) { result = new DefaultMergeResult < E > ( commonAncestor , next , current ) ; result . getLog ( ) . error ( "Failed to execute merge" , e ) ; } return result ; }
|
Execute a 3 - way merge on provided versions .
|
2,645
|
void analyseRevision ( R revision , List < E > previous ) { if ( currentRevision == null ) { return ; } if ( previous == null || previous . isEmpty ( ) ) { resolveRemainingToCurrent ( ) ; } else { resolveToCurrent ( DiffUtils . diff ( currentRevisionContent , previous ) . getDeltas ( ) ) ; assert currentRevisionContent . equals ( previous ) : "Patch application failed" ; } currentRevision = revision ; }
|
Resolve revision of line to current revision based on given previous content and prepare for next analysis .
|
2,646
|
private void resolveToCurrent ( List < Delta < E > > deltas ) { int lineOffset = 0 ; for ( Delta < E > d : deltas ) { Chunk < E > original = d . getOriginal ( ) ; Chunk < E > revised = d . getRevised ( ) ; int pos = original . getPosition ( ) + lineOffset ; for ( int i = 0 ; i < original . size ( ) ; i ++ ) { int origLine = elementList . remove ( pos ) ; currentRevisionContent . remove ( pos ) ; if ( origLine != - 1 ) { sourceRevisions . set ( origLine , currentRevision ) ; } } for ( int i = 0 ; i < revised . size ( ) ; i ++ ) { currentRevisionContent . add ( pos + i , revised . getLines ( ) . get ( i ) ) ; elementList . add ( pos + i , - 1 ) ; } lineOffset += revised . size ( ) - original . size ( ) ; } }
|
Resolve revision of line to current revision based on given previous content .
|
2,647
|
private void resolveRemainingToCurrent ( ) { for ( int i = 0 ; i < this . size ; i ++ ) { if ( sourceRevisions . get ( i ) == null ) { sourceRevisions . set ( i , currentRevision ) ; } } }
|
Resolve all line remaining without revision to current .
|
2,648
|
private void performArchive ( ) throws Exception { File sourceDir = new File ( this . project . getBuild ( ) . getOutputDirectory ( ) ) ; if ( sourceDir . listFiles ( ) == null ) { throw new Exception ( String . format ( "No XAR XML files found in [%s]. Has the Maven Resource plugin be called?" , sourceDir ) ) ; } File xarFile = new File ( this . project . getBuild ( ) . getDirectory ( ) , this . project . getArtifactId ( ) + "-" + this . project . getVersion ( ) + ".xar" ) ; ZipArchiver archiver = new ZipArchiver ( ) ; archiver . setEncoding ( this . encoding ) ; archiver . setDestFile ( xarFile ) ; archiver . setIncludeEmptyDirs ( false ) ; archiver . setCompress ( true ) ; if ( this . includeDependencies ) { unpackDependentXARs ( ) ; } performTransformations ( ) ; File resourcesDir = getResourcesDirectory ( ) ; if ( ! hasPackageXmlFile ( resourcesDir ) ) { addFilesToArchive ( archiver , sourceDir ) ; } else { File packageXml = new File ( resourcesDir , PACKAGE_XML ) ; addFilesToArchive ( archiver , sourceDir , packageXml ) ; } archiver . createArchive ( ) ; this . project . getArtifact ( ) . setFile ( xarFile ) ; }
|
Create the XAR by zipping the resource files .
|
2,649
|
private void unpackDependentXARs ( ) throws MojoExecutionException { Set < Artifact > artifacts = this . project . getArtifacts ( ) ; if ( artifacts != null ) { for ( Artifact artifact : artifacts ) { if ( ! artifact . isOptional ( ) && "xar" . equals ( artifact . getType ( ) ) ) { unpackXARToOutputDirectory ( artifact , getIncludes ( ) , getExcludes ( ) ) ; } } } }
|
Unpack XAR dependencies before pack then into it .
|
2,650
|
private void generatePackageXml ( File packageFile , Collection < ArchiveEntry > files ) throws Exception { getLog ( ) . info ( String . format ( "Generating package.xml descriptor at [%s]" , packageFile . getPath ( ) ) ) ; OutputFormat outputFormat = new OutputFormat ( "" , true ) ; outputFormat . setEncoding ( this . encoding ) ; OutputStream out = new FileOutputStream ( packageFile ) ; XMLWriter writer = new XMLWriter ( out , outputFormat ) ; writer . write ( toXML ( files ) ) ; writer . close ( ) ; out . close ( ) ; }
|
Create and add package configuration file to the package .
|
2,651
|
private Document toXML ( Collection < ArchiveEntry > files ) throws Exception { Document doc = new DOMDocument ( ) ; Element packageElement = new DOMElement ( "package" ) ; doc . setRootElement ( packageElement ) ; Element infoElement = new DOMElement ( "infos" ) ; packageElement . add ( infoElement ) ; addInfoElements ( infoElement ) ; Element filesElement = new DOMElement ( FILES_TAG ) ; packageElement . add ( filesElement ) ; addFileElements ( files , filesElement ) ; return doc ; }
|
Generate a DOM4J Document containing the generated XML .
|
2,652
|
private void addFilesToArchive ( ZipArchiver archiver , File sourceDir ) throws Exception { File generatedPackageFile = new File ( sourceDir , PACKAGE_XML ) ; if ( generatedPackageFile . exists ( ) ) { generatedPackageFile . delete ( ) ; } archiver . addDirectory ( sourceDir , getIncludes ( ) , getExcludes ( ) ) ; generatePackageXml ( generatedPackageFile , archiver . getFiles ( ) . values ( ) ) ; archiver . addFile ( generatedPackageFile , PACKAGE_XML ) ; }
|
Adds the files from a specific directory to an archive . It also builds a package . xml file based on that content which is also added to the archive .
|
2,653
|
private void addFilesToArchive ( ZipArchiver archiver , File sourceDir , File packageXml ) throws Exception { Collection < String > documentNames ; getLog ( ) . info ( String . format ( "Using the existing package.xml descriptor at [%s]" , packageXml . getPath ( ) ) ) ; try { documentNames = getDocumentNamesFromXML ( packageXml ) ; } catch ( Exception e ) { getLog ( ) . error ( String . format ( "The existing [%s] is invalid." , PACKAGE_XML ) ) ; throw e ; } Queue < File > fileQueue = new LinkedList < > ( ) ; addContentsToQueue ( fileQueue , sourceDir ) ; while ( ! fileQueue . isEmpty ( ) && ! documentNames . isEmpty ( ) ) { File currentFile = fileQueue . poll ( ) ; if ( currentFile . isDirectory ( ) ) { addContentsToQueue ( fileQueue , currentFile ) ; } else { String documentReference = XWikiDocument . getReference ( currentFile ) ; if ( documentNames . contains ( documentReference ) ) { String archivedFilePath = currentFile . getAbsolutePath ( ) . substring ( ( sourceDir . getAbsolutePath ( ) + File . separator ) . length ( ) ) ; archivedFilePath = archivedFilePath . replace ( File . separatorChar , '/' ) ; archiver . addFile ( currentFile , archivedFilePath ) ; documentNames . remove ( documentReference ) ; } } } if ( ! documentNames . isEmpty ( ) ) { StringBuilder errorMessage = new StringBuilder ( "The following documents could not be found: " ) ; for ( String name : documentNames ) { errorMessage . append ( name ) ; errorMessage . append ( " " ) ; } throw new Exception ( errorMessage . toString ( ) ) ; } archiver . addFile ( packageXml , PACKAGE_XML ) ; }
|
Adds files from a specific directory to an archive . It uses an existing package . xml to filter the files to be added .
|
2,654
|
private static void addContentsToQueue ( Queue < File > fileQueue , File sourceDir ) throws MojoExecutionException { File [ ] files = sourceDir . listFiles ( ) ; if ( files != null ) { for ( File currentFile : files ) { fileQueue . add ( currentFile ) ; } } else { throw new MojoExecutionException ( String . format ( "Couldn't get list of files in source dir [%s]" , sourceDir ) ) ; } }
|
Adds the contents of a specific directory to a queue of files .
|
2,655
|
public static void stripHTMLEnvelope ( Document document ) { org . w3c . dom . Element root = document . getDocumentElement ( ) ; if ( root . getNodeName ( ) . equalsIgnoreCase ( HTMLConstants . TAG_HTML ) ) { Node bodyNode = null ; Node headNode = null ; NodeList nodes = root . getChildNodes ( ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node node = nodes . item ( i ) ; if ( node . getNodeName ( ) . equalsIgnoreCase ( HTMLConstants . TAG_HEAD ) ) { headNode = node ; } else if ( node . getNodeName ( ) . equalsIgnoreCase ( HTMLConstants . TAG_BODY ) ) { bodyNode = node ; } } if ( headNode != null ) { root . removeChild ( headNode ) ; } if ( bodyNode != null ) { NodeList bodyChildrenNodes = bodyNode . getChildNodes ( ) ; while ( bodyChildrenNodes . getLength ( ) > 0 ) { root . insertBefore ( bodyChildrenNodes . item ( 0 ) , null ) ; } root . removeChild ( bodyNode ) ; } } }
|
Strip the HTML envelope if it exists . Precisely this means removing the head tag and move all tags in the body tag directly under the html element . This is useful for example if you wish to insert an HTML fragment into an existing HTML page .
|
2,656
|
public static void stripFirstElementInside ( Document document , String parentTagName , String elementTagName ) { NodeList parentNodes = document . getElementsByTagName ( parentTagName ) ; if ( parentNodes . getLength ( ) > 0 ) { Node parentNode = parentNodes . item ( 0 ) ; Node pNode = parentNode . getFirstChild ( ) ; if ( elementTagName . equalsIgnoreCase ( pNode . getNodeName ( ) ) ) { NodeList pChildrenNodes = pNode . getChildNodes ( ) ; while ( pChildrenNodes . getLength ( ) > 0 ) { parentNode . insertBefore ( pChildrenNodes . item ( 0 ) , null ) ; } parentNode . removeChild ( pNode ) ; } } }
|
Remove the first element inside a parent element and copy the element s children in the parent .
|
2,657
|
protected void store ( BufferedWriter out , String type , byte [ ] data ) throws IOException { write ( out , type , data ) ; out . close ( ) ; }
|
Write data encoded based64 between PEM line headers and close the writer .
|
2,658
|
protected void write ( BufferedWriter out , String type , byte [ ] data ) throws IOException { writeHeader ( out , type ) ; out . write ( this . base64 . encode ( data , 64 ) ) ; out . newLine ( ) ; writeFooter ( out , type ) ; }
|
Write data encoded based64 between PEM line headers .
|
2,659
|
private static void writeHeader ( BufferedWriter out , String type ) throws IOException { out . write ( PEM_BEGIN + type + DASHES ) ; out . newLine ( ) ; }
|
Write a PEM like header .
|
2,660
|
private static void writeFooter ( BufferedWriter out , String type ) throws IOException { out . write ( PEM_END + type + DASHES ) ; out . newLine ( ) ; }
|
Write a PEM like footer .
|
2,661
|
protected File getStoreFile ( StoreReference store ) { if ( store instanceof FileStoreReference ) { return ( ( FileStoreReference ) store ) . getFile ( ) ; } throw new IllegalArgumentException ( String . format ( "Unsupported store reference [%s] for this implementation." , store . getClass ( ) . getName ( ) ) ) ; }
|
Return the file corresponding to the given store reference .
|
2,662
|
protected X509CertifiedPublicKey getPublicKey ( CertifiedPublicKey publicKey ) { if ( publicKey instanceof X509CertifiedPublicKey ) { return ( X509CertifiedPublicKey ) publicKey ; } throw new IllegalArgumentException ( String . format ( "Unsupported certificate [%s], expecting X509 certificates." , publicKey . getClass ( ) . getName ( ) ) ) ; }
|
Return the X . 509 certificate .
|
2,663
|
protected String getCertIdentifier ( X509CertifiedPublicKey publicKey ) throws IOException { byte [ ] keyId = publicKey . getSubjectKeyIdentifier ( ) ; if ( keyId != null ) { return this . hex . encode ( keyId ) ; } return publicKey . getSerialNumber ( ) . toString ( ) + ", " + publicKey . getIssuer ( ) . getName ( ) ; }
|
Return a unique identifier appropriate for a file name . If the certificate as a subject key identifier the result is this encoded identifier . Else use the concatenation of the certificate serial number and the issuer name .
|
2,664
|
protected Object readObject ( BufferedReader in , byte [ ] password ) throws IOException , GeneralSecurityException { String line ; Object obj = null ; while ( ( line = in . readLine ( ) ) != null ) { obj = processObject ( in , line , password ) ; if ( obj != null ) { break ; } } return obj ; }
|
Read an object from a PEM like file .
|
2,665
|
protected Object processObject ( BufferedReader in , String line , byte [ ] password ) throws IOException , GeneralSecurityException { if ( line . contains ( PEM_BEGIN + CERTIFICATE + DASHES ) ) { return this . certificateFactory . decode ( readBytes ( in , PEM_END + CERTIFICATE + DASHES ) ) ; } return null ; }
|
Process an object from a PEM like file .
|
2,666
|
protected byte [ ] readBytes ( BufferedReader in , String endMarker ) throws IOException { String line ; StringBuilder buf = new StringBuilder ( ) ; while ( ( line = in . readLine ( ) ) != null ) { if ( line . contains ( endMarker ) ) { break ; } buf . append ( line . trim ( ) ) ; } return this . base64 . decode ( buf . toString ( ) ) ; }
|
Read base64 data up to an end marker and decode them .
|
2,667
|
private void onPushLevelProgress ( int steps , Object source , boolean singlesteplevel ) { if ( this . currentStep . isLevelFinished ( ) ) { this . currentStep = this . currentStep . getParent ( ) . nextStep ( null , source ) ; } this . currentStep = this . currentStep . addLevel ( steps , source , singlesteplevel ) ; }
|
Adds a new level to the progress stack .
|
2,668
|
private void onEndStepProgress ( Object source ) { DefaultJobProgressStep step = findStep ( this . currentStep , source ) ; if ( step == null ) { LOGGER . warn ( "Could not find any matching step for source [{}]. Ignoring EndStepProgress." , source . toString ( ) ) ; return ; } this . currentStep = step ; this . currentStep . finish ( ) ; }
|
Close current step .
|
2,669
|
private void onStepProgress ( Object source ) { onStartStepProgress ( null , source ) ; if ( this . currentStep . getParent ( ) . getChildren ( ) . size ( ) == 1 ) { this . currentStep = this . currentStep . getParent ( ) . nextStep ( null , source ) ; } }
|
Move progress to next step .
|
2,670
|
public static int skipElement ( XMLStreamReader xmlReader ) throws XMLStreamException { if ( ! xmlReader . isStartElement ( ) ) { throw new XMLStreamException ( "Current node is not start element" ) ; } if ( ! xmlReader . isEndElement ( ) ) { for ( xmlReader . next ( ) ; ! xmlReader . isEndElement ( ) ; xmlReader . next ( ) ) { if ( xmlReader . isStartElement ( ) ) { skipElement ( xmlReader ) ; } } } return xmlReader . getEventType ( ) ; }
|
Go to the end of the current element . This include skipping any children element .
|
2,671
|
public static boolean isDependency ( Extension extension , String namespace ) { boolean isDependency = false ; if ( namespace == null ) { isDependency = extension . getProperty ( PKEY_DEPENDENCY , false ) ; } else { Object namespacesObject = extension . getProperty ( PKEY_NAMESPACES ) ; if ( namespacesObject instanceof Map ) { Map < String , Object > installedNamespace = ( ( Map < String , Map < String , Object > > ) namespacesObject ) . get ( namespace ) ; isDependency = installedNamespace != null ? ( installedNamespace . get ( PKEY_NAMESPACES_DEPENDENCY ) == Boolean . TRUE ) : isDependency ( extension , null ) ; } else { isDependency = isDependency ( extension , null ) ; } } return isDependency ; }
|
Indicate if the extension as been installed as a dependency of another one .
|
2,672
|
public void setNamespaceProperty ( String key , Object value , String namespace ) { try { this . propertiesLock . lock ( ) ; Map < String , Object > namespaceProperties = getNamespaceProperties ( namespace ) ; if ( namespaceProperties != null ) { namespaceProperties . put ( key , value ) ; } } finally { this . propertiesLock . unlock ( ) ; } }
|
Sets the value of the specified extension property on the given namespace .
|
2,673
|
public void startStep ( String translationKey , String message , Object ... arguments ) { this . progress . startStep ( this , new Message ( translationKey , message , arguments ) ) ; }
|
Close current step if any and move to next one .
|
2,674
|
private void performUnArchive ( ) throws MojoExecutionException { Artifact artifact = findArtifact ( ) ; getLog ( ) . debug ( String . format ( "Source XAR = [%s]" , artifact . getFile ( ) ) ) ; unpack ( artifact . getFile ( ) , this . outputDirectory , "XAR Plugin" , true , getIncludes ( ) , getExcludes ( ) ) ; unpackDependentXars ( artifact ) ; }
|
Unzip xar artifact and its dependencies .
|
2,675
|
protected void unpackDependentXars ( Artifact artifact ) throws MojoExecutionException { try { Set < Artifact > dependencies = resolveArtifactDependencies ( artifact ) ; for ( Artifact dependency : dependencies ) { unpack ( dependency . getFile ( ) , this . outputDirectory , "XAR Plugin" , false , getIncludes ( ) , getExcludes ( ) ) ; } } catch ( Exception e ) { throw new MojoExecutionException ( String . format ( "Failed to unpack artifact [%s] dependencies" , artifact ) , e ) ; } }
|
Unpack xar dependencies of the provided artifact .
|
2,676
|
private void customizeEviction ( ConfigurationBuilder builder ) { EntryEvictionConfiguration eec = ( EntryEvictionConfiguration ) getCacheConfiguration ( ) . get ( EntryEvictionConfiguration . CONFIGURATIONID ) ; if ( eec != null && eec . getAlgorithm ( ) == EntryEvictionConfiguration . Algorithm . LRU ) { customizeEvictionMaxEntries ( builder , eec ) ; customizeExpirationWakeUpInterval ( builder , eec ) ; customizeExpirationMaxIdle ( builder , eec ) ; customizeExpirationLifespan ( builder , eec ) ; } }
|
Customize the eviction configuration .
|
2,677
|
private void completeFilesystem ( ConfigurationBuilder builder , Configuration configuration ) { PersistenceConfigurationBuilder persistence = builder . persistence ( ) ; if ( containsIncompleteFileLoader ( configuration ) ) { for ( StoreConfigurationBuilder < ? , ? > store : persistence . stores ( ) ) { if ( store instanceof SingleFileStoreConfigurationBuilder ) { SingleFileStoreConfigurationBuilder singleFileStore = ( SingleFileStoreConfigurationBuilder ) store ; singleFileStore . location ( createTempDir ( ) ) ; } } } }
|
Add missing location for filesystem based cache .
|
2,678
|
public Configuration customize ( Configuration defaultConfiguration , Configuration namedConfiguration ) { ConfigurationBuilder builder = new ConfigurationBuilder ( ) ; if ( namedConfiguration != null ) { read ( builder , namedConfiguration ) ; } else { if ( defaultConfiguration != null ) { read ( builder , defaultConfiguration ) ; } customizeEviction ( builder ) ; } return builder . build ( ) ; }
|
Customize provided configuration based on XWiki cache configuration .
|
2,679
|
public boolean containLogsFrom ( LogLevel level ) { for ( LogEvent log : this ) { if ( log . getLevel ( ) . compareTo ( level ) <= 0 ) { return true ; } } return false ; }
|
Indicate if the list contains logs of a specific level .
|
2,680
|
public InputStream openStream ( ) { ClassLoader classLoader = clazz . getClassLoader ( ) ; if ( classLoader == null ) { classLoader = ClassLoader . getSystemClassLoader ( ) ; } return new ClassLoaderAsset ( getResourceNameOfClass ( clazz ) , classLoader ) . openStream ( ) ; }
|
Converts the Class name into a Resource URL and uses the ClassloaderResource for loading the Class .
|
2,681
|
private ArchivePath calculatePath ( File root , File child ) { String rootPath = unifyPath ( root . getPath ( ) ) ; String childPath = unifyPath ( child . getPath ( ) ) ; String archiveChildPath = childPath . replaceFirst ( Pattern . quote ( rootPath ) , "" ) ; return new BasicPath ( archiveChildPath ) ; }
|
Calculate the relative child path .
|
2,682
|
private void initialize ( int blockSize , int recordSize ) { this . debug = false ; this . blockSize = blockSize ; this . recordSize = recordSize ; this . recsPerBlock = ( this . blockSize / this . recordSize ) ; this . blockBuffer = new byte [ this . blockSize ] ; if ( this . inStream != null ) { this . currBlkIdx = - 1 ; this . currRecIdx = this . recsPerBlock ; } else { this . currBlkIdx = 0 ; this . currRecIdx = 0 ; } }
|
Initialization common to all constructors .
|
2,683
|
public boolean isEOFRecord ( byte [ ] record ) { for ( int i = 0 , sz = this . getRecordSize ( ) ; i < sz ; ++ i ) { if ( record [ i ] != 0 ) { return false ; } } return true ; }
|
Determine if an archive record indicate End of Archive . End of archive is indicated by a record that consists entirely of null bytes .
|
2,684
|
public void skipRecord ( ) throws IOException { if ( this . debug ) { System . err . println ( "SkipRecord: recIdx = " + this . currRecIdx + " blkIdx = " + this . currBlkIdx ) ; } if ( this . inStream == null ) { throw new IOException ( "reading (via skip) from an output buffer" ) ; } if ( this . currRecIdx >= this . recsPerBlock ) { if ( ! this . readBlock ( ) ) { return ; } } this . currRecIdx ++ ; }
|
Skip over a record on the input stream .
|
2,685
|
public byte [ ] readRecord ( ) throws IOException { if ( this . debug ) { System . err . println ( "ReadRecord: recIdx = " + this . currRecIdx + " blkIdx = " + this . currBlkIdx ) ; } if ( this . inStream == null ) { throw new IOException ( "reading from an output buffer" ) ; } if ( this . currRecIdx >= this . recsPerBlock ) { if ( ! this . readBlock ( ) ) { return null ; } } byte [ ] result = new byte [ this . recordSize ] ; System . arraycopy ( this . blockBuffer , ( this . currRecIdx * this . recordSize ) , result , 0 , this . recordSize ) ; this . currRecIdx ++ ; return result ; }
|
Read a record from the input stream and return the data .
|
2,686
|
public void writeRecord ( byte [ ] record ) throws IOException { if ( this . debug ) { System . err . println ( "WriteRecord: recIdx = " + this . currRecIdx + " blkIdx = " + this . currBlkIdx ) ; } if ( this . outStream == null ) { throw new IOException ( "writing to an input buffer" ) ; } if ( record . length != this . recordSize ) { throw new IOException ( "record to write has length '" + record . length + "' which is not the record size of '" + this . recordSize + "'" ) ; } if ( this . currRecIdx >= this . recsPerBlock ) { this . writeBlock ( ) ; } System . arraycopy ( record , 0 , this . blockBuffer , ( this . currRecIdx * this . recordSize ) , this . recordSize ) ; this . currRecIdx ++ ; }
|
Write an archive record to the archive .
|
2,687
|
public void writeRecord ( byte [ ] buf , int offset ) throws IOException { if ( this . debug ) { System . err . println ( "WriteRecord: recIdx = " + this . currRecIdx + " blkIdx = " + this . currBlkIdx ) ; } if ( this . outStream == null ) { throw new IOException ( "writing to an input buffer" ) ; } if ( ( offset + this . recordSize ) > buf . length ) { throw new IOException ( "record has length '" + buf . length + "' with offset '" + offset + "' which is less than the record size of '" + this . recordSize + "'" ) ; } if ( this . currRecIdx >= this . recsPerBlock ) { this . writeBlock ( ) ; } System . arraycopy ( buf , offset , this . blockBuffer , ( this . currRecIdx * this . recordSize ) , this . recordSize ) ; this . currRecIdx ++ ; }
|
Write an archive record to the archive where the record may be inside of a larger array buffer . The buffer must be offset plus record size long .
|
2,688
|
private void writeBlock ( ) throws IOException { if ( this . debug ) { System . err . println ( "WriteBlock: blkIdx = " + this . currBlkIdx ) ; } if ( this . outStream == null ) { throw new IOException ( "writing to an input buffer" ) ; } this . outStream . write ( this . blockBuffer , 0 , this . blockSize ) ; this . outStream . flush ( ) ; this . currRecIdx = 0 ; this . currBlkIdx ++ ; }
|
Write a TarBuffer block to the archive .
|
2,689
|
private void flushBlock ( ) throws IOException { if ( this . debug ) { System . err . println ( "TarBuffer.flushBlock() called." ) ; } if ( this . outStream == null ) { throw new IOException ( "writing to an input buffer" ) ; } if ( this . currRecIdx > 0 ) { int offset = this . currRecIdx * this . recordSize ; byte [ ] zeroBuffer = new byte [ this . blockSize - offset ] ; System . arraycopy ( zeroBuffer , 0 , this . blockBuffer , offset , zeroBuffer . length ) ; this . writeBlock ( ) ; } }
|
Flush the current data block if it has any data in it .
|
2,690
|
public void close ( ) throws IOException { if ( this . debug ) { System . err . println ( "TarBuffer.closeBuffer()." ) ; } if ( this . outStream != null ) { this . flushBlock ( ) ; if ( this . outStream != System . out && this . outStream != System . err ) { this . outStream . close ( ) ; this . outStream = null ; } } else if ( this . inStream != null ) { if ( this . inStream != System . in ) { this . inStream . close ( ) ; this . inStream = null ; } } }
|
Close the TarBuffer . If this is an output buffer also flush the current block before closing .
|
2,691
|
private Node removeNodeRecursively ( final NodeImpl node , final ArchivePath path ) { final NodeImpl parentNode = content . get ( path . getParent ( ) ) ; if ( parentNode != null ) { parentNode . removeChild ( node ) ; } nestedArchives . remove ( path ) ; if ( node . getChildren ( ) != null ) { final Set < Node > children = node . getChildren ( ) ; final Set < Node > childrenCopy = new HashSet < Node > ( children ) ; for ( Node child : childrenCopy ) { node . removeChild ( child ) ; content . remove ( child . getPath ( ) ) ; } } return content . remove ( path ) ; }
|
Removes the specified node and its associated children from the contents of this archive .
|
2,692
|
private boolean nestedContains ( ArchivePath path ) { for ( Entry < ArchivePath , ArchiveAsset > nestedArchiveEntry : nestedArchives . entrySet ( ) ) { ArchivePath archivePath = nestedArchiveEntry . getKey ( ) ; ArchiveAsset archiveAsset = nestedArchiveEntry . getValue ( ) ; if ( startsWith ( path , archivePath ) ) { Archive < ? > nestedArchive = archiveAsset . getArchive ( ) ; ArchivePath nestedAssetPath = getNestedPath ( path , archivePath ) ; return nestedArchive . contains ( nestedAssetPath ) ; } } return false ; }
|
Check to see if a path is found in a nested archive
|
2,693
|
private Node getNestedNode ( ArchivePath path ) { for ( Entry < ArchivePath , ArchiveAsset > nestedArchiveEntry : nestedArchives . entrySet ( ) ) { ArchivePath archivePath = nestedArchiveEntry . getKey ( ) ; ArchiveAsset archiveAsset = nestedArchiveEntry . getValue ( ) ; if ( startsWith ( path , archivePath ) ) { Archive < ? > nestedArchive = archiveAsset . getArchive ( ) ; ArchivePath nestedAssetPath = getNestedPath ( path , archivePath ) ; return nestedArchive . get ( nestedAssetPath ) ; } } return null ; }
|
Attempt to get the asset from a nested archive .
|
2,694
|
private boolean startsWith ( ArchivePath fullPath , ArchivePath startingPath ) { final String context = fullPath . get ( ) ; final String startingContext = startingPath . get ( ) ; return context . startsWith ( startingContext ) ; }
|
Check to see if one path starts with another
|
2,695
|
private ArchivePath getNestedPath ( ArchivePath fullPath , ArchivePath basePath ) { final String context = fullPath . get ( ) ; final String baseContent = basePath . get ( ) ; String nestedArchiveContext = context . substring ( baseContent . length ( ) ) ; return new BasicPath ( nestedArchiveContext ) ; }
|
Given a full path and a base path return a new path containing the full path with the base path removed from the beginning .
|
2,696
|
private void initialize ( ) { this . file = null ; this . header = new TarHeader ( ) ; this . gnuFormat = false ; this . ustarFormat = true ; this . unixFormat = false ; }
|
Initialization code common to all constructors .
|
2,697
|
public boolean isDescendent ( TarEntry desc ) { return desc . header . name . toString ( ) . startsWith ( this . header . name . toString ( ) ) ; }
|
Determine if the given entry is a descendant of this entry . Descendancy is determined by the name of the descendant starting with this entry s name .
|
2,698
|
public boolean isDirectory ( ) { if ( this . file != null ) { return this . file . isDirectory ( ) ; } if ( this . header != null ) { if ( this . header . linkFlag == TarHeader . LF_DIR ) { return true ; } if ( this . header . name . toString ( ) . endsWith ( "/" ) ) { return true ; } } return false ; }
|
Return whether or not this entry represents a directory .
|
2,699
|
public void getFileTarHeader ( TarHeader hdr , File file ) throws InvalidHeaderException { this . file = file ; String name = file . getPath ( ) ; String osname = System . getProperty ( "os.name" ) ; if ( osname != null ) { String Win32Prefix = "windows" ; if ( osname . toLowerCase ( ) . startsWith ( Win32Prefix ) ) { if ( name . length ( ) > 2 ) { char ch1 = name . charAt ( 0 ) ; char ch2 = name . charAt ( 1 ) ; if ( ch2 == ':' && ( ( ch1 >= 'a' && ch1 <= 'z' ) || ( ch1 >= 'A' && ch1 <= 'Z' ) ) ) { name = name . substring ( 2 ) ; } } } } name = name . replace ( File . separatorChar , '/' ) ; for ( ; name . startsWith ( "/" ) ; ) { name = name . substring ( 1 ) ; } hdr . linkName = new StringBuffer ( "" ) ; hdr . name = new StringBuffer ( name ) ; if ( file . isDirectory ( ) ) { hdr . size = 0 ; hdr . mode = 040755 ; hdr . linkFlag = TarHeader . LF_DIR ; if ( hdr . name . charAt ( hdr . name . length ( ) - 1 ) != '/' ) { hdr . name . append ( "/" ) ; } } else { hdr . size = file . length ( ) ; hdr . mode = 0100644 ; hdr . linkFlag = TarHeader . LF_NORMAL ; } hdr . modTime = file . lastModified ( ) / 1000 ; hdr . checkSum = 0 ; hdr . devMajor = 0 ; hdr . devMinor = 0 ; }
|
Fill in a TarHeader with information from a File .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.