idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
15,300
protected DirectoryManager cloneDirectoryManager ( DirectoryManager directoryManager , String suffix ) throws IOException { try { DirectoryManager df = directoryManager . getClass ( ) . newInstance ( ) ; df . init ( this . path + suffix ) ; return df ; } catch ( IOException e ) { throw e ; } catch ( Exception e ) { IOException ex = new IOException ( ) ; ex . initCause ( e ) ; throw ex ; } }
Clone the default Index directory manager
93
7
15,301
protected InputStream createSynonymProviderConfigResource ( ) throws IOException { if ( synonymProviderConfigPath != null ) { InputStream fsr ; // simple sanity check String separator = PrivilegedSystemHelper . getProperty ( "file.separator" ) ; if ( synonymProviderConfigPath . endsWith ( PrivilegedSystemHelper . getProperty ( "file.separator" ) ) ) { throw new IOException ( "Invalid synonymProviderConfigPath: " + synonymProviderConfigPath ) ; } if ( cfm == null ) { int lastSeparator = synonymProviderConfigPath . lastIndexOf ( separator ) ; if ( lastSeparator != - 1 ) { File root = new File ( path , synonymProviderConfigPath . substring ( 0 , lastSeparator ) ) ; fsr = new BufferedInputStream ( PrivilegedFileHelper . fileInputStream ( new File ( root , synonymProviderConfigPath . substring ( lastSeparator + 1 ) ) ) ) ; } else { fsr = new BufferedInputStream ( PrivilegedFileHelper . fileInputStream ( new File ( synonymProviderConfigPath ) ) ) ; } synonymProviderConfigFs = fsr ; } else { try { fsr = cfm . getInputStream ( synonymProviderConfigPath ) ; } catch ( Exception e ) { throw new IOException ( e . getLocalizedMessage ( ) , e ) ; } } return fsr ; } else { // path not configured return null ; } }
Creates a file system resource to the synonym provider configuration .
322
13
15,302
protected SpellChecker createSpellChecker ( ) { // spell checker config SpellChecker spCheck = null ; if ( spellCheckerClass != null ) { try { spCheck = spellCheckerClass . newInstance ( ) ; spCheck . init ( SearchIndex . this , spellCheckerMinDistance , spellCheckerMorePopular ) ; } catch ( IOException e ) { log . warn ( "Exception initializing spell checker: " + spellCheckerClass , e ) ; } catch ( InstantiationException e ) { log . warn ( "Exception initializing spell checker: " + spellCheckerClass , e ) ; } catch ( IllegalAccessException e ) { log . warn ( "Exception initializing spell checker: " + spellCheckerClass , e ) ; } } return spCheck ; }
Creates a spell checker for this query handler .
172
11
15,303
public ErrorLog doInitErrorLog ( String path ) throws IOException { File file = new File ( new File ( path ) , ERROR_LOG ) ; return new ErrorLog ( file , errorLogfileSize ) ; }
Initialization error log .
46
5
15,304
void waitForResuming ( ) throws IOException { if ( isSuspended . get ( ) ) { try { latcher . get ( ) . await ( ) ; } catch ( InterruptedException e ) { throw new IOException ( e ) ; } } }
If component is suspended need to wait resuming and not allow execute query on closed index .
56
18
15,305
Node getUsersStorageNode ( Session session ) throws PathNotFoundException , RepositoryException { return ( Node ) session . getItem ( service . getStoragePath ( ) + "/" + JCROrganizationServiceImpl . STORAGE_JOS_USERS ) ; }
Returns the node where all users are stored .
57
9
15,306
Node getMembershipTypeStorageNode ( Session session ) throws PathNotFoundException , RepositoryException { return ( Node ) session . getItem ( service . getStoragePath ( ) + "/" + JCROrganizationServiceImpl . STORAGE_JOS_MEMBERSHIP_TYPES ) ; }
Returns the node where all membership types are stored .
67
10
15,307
Node getUserNode ( Session session , String userName ) throws PathNotFoundException , RepositoryException { return ( Node ) session . getItem ( getUserNodePath ( userName ) ) ; }
Returns the node where defined user is stored .
42
9
15,308
String getUserNodePath ( String userName ) throws RepositoryException { return service . getStoragePath ( ) + "/" + JCROrganizationServiceImpl . STORAGE_JOS_USERS + "/" + userName ; }
Returns the node path where defined user is stored .
50
10
15,309
Node getMembershipTypeNode ( Session session , String name ) throws PathNotFoundException , RepositoryException { return ( Node ) session . getItem ( getMembershipTypeNodePath ( name ) ) ; }
Returns the node where defined membership type is stored .
44
10
15,310
Node getProfileNode ( Session session , String userName ) throws PathNotFoundException , RepositoryException { return ( Node ) session . getItem ( service . getStoragePath ( ) + "/" + JCROrganizationServiceImpl . STORAGE_JOS_USERS + "/" + userName + "/" + JCROrganizationServiceImpl . JOS_PROFILE ) ; }
Returns the node where profile of defined user is stored .
82
11
15,311
String getMembershipTypeNodePath ( String name ) throws RepositoryException { return service . getStoragePath ( ) + "/" + JCROrganizationServiceImpl . STORAGE_JOS_MEMBERSHIP_TYPES + "/" + ( name . equals ( MembershipTypeHandler . ANY_MEMBERSHIP_TYPE ) ? JCROrganizationServiceImpl . JOS_MEMBERSHIP_TYPE_ANY : name ) ; }
Returns the path where defined membership type is stored .
101
10
15,312
GroupIds getGroupIds ( Node groupNode ) throws RepositoryException { String storagePath = getGroupStoragePath ( ) ; String nodePath = groupNode . getPath ( ) ; String groupId = nodePath . substring ( storagePath . length ( ) ) ; String parentId = groupId . substring ( 0 , groupId . lastIndexOf ( "/" ) ) ; return new GroupIds ( groupId , parentId ) ; }
Evaluate the group identifier and parent group identifier based on group node path .
96
16
15,313
IdComponents splitId ( String id ) throws IndexOutOfBoundsException { String [ ] membershipIDs = id . split ( "," ) ; String groupNodeId = membershipIDs [ 0 ] ; String userName = membershipIDs [ 1 ] ; String type = membershipIDs [ 2 ] ; return new IdComponents ( groupNodeId , userName , type ) ; }
Splits membership identifier into several components .
78
8
15,314
public void printData ( PrintWriter pw ) { long lmin = min . get ( ) ; if ( lmin == Long . MAX_VALUE ) { lmin = - 1 ; } long lmax = max . get ( ) ; long ltotal = total . get ( ) ; long ltimes = times . get ( ) ; float favg = ltimes == 0 ? 0f : ( float ) ltotal / ltimes ; pw . print ( lmin ) ; pw . print ( ' ' ) ; pw . print ( lmax ) ; pw . print ( ' ' ) ; pw . print ( ltotal ) ; pw . print ( ' ' ) ; pw . print ( favg ) ; pw . print ( ' ' ) ; pw . print ( ltimes ) ; }
Print the current snapshot of the metrics and evaluate the average value
173
12
15,315
public void reset ( ) { min . set ( Long . MAX_VALUE ) ; max . set ( 0 ) ; total . set ( 0 ) ; times . set ( 0 ) ; }
Reset the statistics
39
4
15,316
protected void refreshIndexes ( Set < String > set ) { // do nothing if null is passed if ( set == null ) { return ; } setNames ( set ) ; // callback multiIndex to refresh lists try { MultiIndex multiIndex = getMultiIndex ( ) ; if ( multiIndex != null ) { multiIndex . refreshIndexList ( ) ; } } catch ( IOException e ) { LOG . error ( "Failed to update indexes! " + e . getMessage ( ) , e ) ; } }
Update index configuration when it changes on persistent storage
107
9
15,317
protected void visitChildProperties ( NodeData node ) throws RepositoryException { if ( isInterrupted ( ) ) return ; for ( PropertyData data : dataManager . getChildPropertiesData ( node ) ) { if ( isInterrupted ( ) ) return ; data . accept ( this ) ; } }
Visit all child properties .
64
5
15,318
protected void visitChildNodes ( NodeData node ) throws RepositoryException { if ( isInterrupted ( ) ) return ; for ( NodeData data : dataManager . getChildNodesData ( node ) ) { if ( isInterrupted ( ) ) return ; data . accept ( this ) ; } }
Visit all child nodes .
64
5
15,319
public QueryNode [ ] getPredicates ( ) { if ( operands == null ) { return EMPTY ; } else { return ( QueryNode [ ] ) operands . toArray ( new QueryNode [ operands . size ( ) ] ) ; } }
Returns the predicate nodes for this location step . This method may also return a position predicate .
54
18
15,320
public Boolean getParameterBoolean ( String name , Boolean defaultValue ) { String value = getParameterValue ( name , null ) ; if ( value != null ) { return new Boolean ( value ) ; } return defaultValue ; }
Parse named parameter as Boolean .
47
7
15,321
@ Override protected QPath traverseQPath ( String cpid ) throws SQLException , InvalidItemStateException , IllegalNameException { return traverseQPathSQ ( cpid ) ; }
Use simple queries since it is much faster
41
8
15,322
protected void prepareRootDir ( String rootDirPath ) throws IOException , RepositoryConfigurationException { this . rootDir = new File ( rootDirPath ) ; if ( ! rootDir . exists ( ) ) { if ( rootDir . mkdirs ( ) ) { LOG . info ( "Value storage directory created: " + rootDir . getAbsolutePath ( ) ) ; // create internal temp dir File tempDir = new File ( rootDir , TEMP_DIR_NAME ) ; tempDir . mkdirs ( ) ; if ( tempDir . exists ( ) && tempDir . isDirectory ( ) ) { // care about storage temp dir cleanup for ( File tmpf : tempDir . listFiles ( ) ) if ( ! tmpf . delete ( ) ) LOG . warn ( "Storage temporary directory contains un-deletable file " + tmpf . getAbsolutePath ( ) + ". It's recommended to leave this directory for JCR External Values Storage private use." ) ; } else throw new RepositoryConfigurationException ( "Cannot create " + TEMP_DIR_NAME + " directory under External Value Storage." ) ; } else { LOG . warn ( "Directory IS NOT created: " + rootDir . getAbsolutePath ( ) ) ; } } else { if ( ! rootDir . isDirectory ( ) ) { throw new RepositoryConfigurationException ( "File exists but is not a directory " + rootDirPath ) ; } } }
Prepare RootDir .
304
5
15,323
private void addChild ( Session session , GroupImpl parent , GroupImpl child , boolean broadcast ) throws Exception { Node parentNode = utils . getGroupNode ( session , parent ) ; Node groupNode = parentNode . addNode ( child . getGroupName ( ) , JCROrganizationServiceImpl . JOS_HIERARCHY_GROUP_NODETYPE ) ; String parentId = parent == null ? null : parent . getId ( ) ; child . setParentId ( parentId ) ; child . setInternalId ( groupNode . getUUID ( ) ) ; if ( broadcast ) { preSave ( child , true ) ; } writeGroup ( child , groupNode ) ; session . save ( ) ; putInCache ( child ) ; if ( broadcast ) { postSave ( child , true ) ; } }
Adds child group .
174
4
15,324
private Collection < Group > findGroups ( Session session , Group parent , boolean recursive ) throws Exception { List < Group > groups = new ArrayList < Group > ( ) ; String parentId = parent == null ? "" : parent . getId ( ) ; NodeIterator childNodes = utils . getGroupNode ( session , parentId ) . getNodes ( ) ; while ( childNodes . hasNext ( ) ) { Node groupNode = childNodes . nextNode ( ) ; if ( ! groupNode . getName ( ) . startsWith ( JCROrganizationServiceImpl . JOS_MEMBERSHIP ) ) { Group group = readGroup ( groupNode ) ; groups . add ( group ) ; if ( recursive ) { groups . addAll ( findGroups ( session , group , recursive ) ) ; } } } return groups ; }
Find children groups . Parent group is not included in result .
182
12
15,325
private Group removeGroup ( Session session , Group group , boolean broadcast ) throws Exception { if ( group == null ) { throw new OrganizationServiceException ( "Can not remove group, since it is null" ) ; } Node groupNode = utils . getGroupNode ( session , group ) ; // need to minus one because of child "jos:memberships" node long childrenCount = ( ( ExtendedNode ) groupNode ) . getNodesLazily ( 1 ) . getSize ( ) - 1 ; if ( childrenCount > 0 ) { throw new OrganizationServiceException ( "Can not remove group till children exist" ) ; } if ( broadcast ) { preDelete ( group ) ; } removeMemberships ( groupNode , broadcast ) ; groupNode . remove ( ) ; session . save ( ) ; removeFromCache ( group . getId ( ) ) ; removeAllRelatedFromCache ( group . getId ( ) ) ; if ( broadcast ) { postDelete ( group ) ; } return group ; }
Removes group and all related membership entities . Throws exception if children exist .
209
16
15,326
private void removeMemberships ( Node groupNode , boolean broadcast ) throws RepositoryException { NodeIterator refUsers = groupNode . getNode ( JCROrganizationServiceImpl . JOS_MEMBERSHIP ) . getNodes ( ) ; while ( refUsers . hasNext ( ) ) { refUsers . nextNode ( ) . remove ( ) ; } }
Remove all membership entities related to current group .
78
9
15,327
void migrateGroup ( Node oldGroupNode ) throws Exception { String groupName = oldGroupNode . getName ( ) ; String desc = utils . readString ( oldGroupNode , GroupProperties . JOS_DESCRIPTION ) ; String label = utils . readString ( oldGroupNode , GroupProperties . JOS_LABEL ) ; String parentId = utils . readString ( oldGroupNode , MigrationTool . JOS_PARENT_ID ) ; GroupImpl group = new GroupImpl ( groupName , parentId ) ; group . setDescription ( desc ) ; group . setLabel ( label ) ; Group parentGroup = findGroupById ( group . getParentId ( ) ) ; if ( findGroupById ( group . getId ( ) ) != null ) { removeGroup ( group , false ) ; } addChild ( parentGroup , group , false ) ; }
Method for group migration .
185
5
15,328
private Group readGroup ( Node groupNode ) throws Exception { String groupName = groupNode . getName ( ) ; String desc = utils . readString ( groupNode , GroupProperties . JOS_DESCRIPTION ) ; String label = utils . readString ( groupNode , GroupProperties . JOS_LABEL ) ; String parentId = utils . getGroupIds ( groupNode ) . parentId ; GroupImpl group = new GroupImpl ( groupName , parentId ) ; group . setInternalId ( groupNode . getUUID ( ) ) ; group . setDescription ( desc ) ; group . setLabel ( label ) ; return group ; }
Read group properties from node .
140
6
15,329
private void writeGroup ( Group group , Node node ) throws OrganizationServiceException { try { node . setProperty ( GroupProperties . JOS_LABEL , group . getLabel ( ) ) ; node . setProperty ( GroupProperties . JOS_DESCRIPTION , group . getDescription ( ) ) ; } catch ( RepositoryException e ) { throw new OrganizationServiceException ( "Can not write group properties" , e ) ; } }
Write group properties to the node .
92
7
15,330
private Group getFromCache ( String groupId ) { return ( Group ) cache . get ( groupId , CacheType . GROUP ) ; }
Reads group from cache .
29
6
15,331
private void putInCache ( Group group ) { cache . put ( group . getId ( ) , group , CacheType . GROUP ) ; }
Puts group in cache .
30
6
15,332
private void removeAllRelatedFromCache ( String groupId ) { cache . remove ( CacheHandler . GROUP_PREFIX + groupId , CacheType . MEMBERSHIP ) ; }
Removes related entities from cache .
40
7
15,333
private void preSave ( Group group , boolean isNew ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . preSave ( group , isNew ) ; } }
Notifying listeners before group creation .
38
7
15,334
private void postSave ( Group group , boolean isNew ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . postSave ( group , isNew ) ; } }
Notifying listeners after group creation .
38
7
15,335
private void preDelete ( Group group ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . preDelete ( group ) ; } }
Notifying listeners before group deletion .
31
7
15,336
private void postDelete ( Group group ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . postDelete ( group ) ; } }
Notifying listeners after group deletion .
31
7
15,337
public void execute ( Runnable command ) { adjustPoolSize ( ) ; if ( numProcessors == 1 ) { // if there is only one processor execute with current thread command . run ( ) ; } else { try { executor . execute ( command ) ; } catch ( InterruptedException e ) { // run with current thread instead command . run ( ) ; } } }
Executes the given command . This method will block if all threads in the pool are busy and return only when the command has been accepted . Care must be taken that no deadlock occurs when multiple commands are scheduled for execution . In general commands should not depend on the execution of other commands!
79
58
15,338
public Result [ ] executeAndWait ( Command [ ] commands ) { Result [ ] results = new Result [ commands . length ] ; if ( numProcessors == 1 ) { // optimize for one processor for ( int i = 0 ; i < commands . length ; i ++ ) { Object obj = null ; InvocationTargetException ex = null ; try { obj = commands [ i ] . call ( ) ; } catch ( Exception e ) { ex = new InvocationTargetException ( e ) ; } results [ i ] = new Result ( obj , ex ) ; } } else { FutureResult [ ] futures = new FutureResult [ commands . length ] ; for ( int i = 0 ; i < commands . length ; i ++ ) { final Command c = commands [ i ] ; futures [ i ] = new FutureResult ( ) ; Runnable r = futures [ i ] . setter ( new Callable ( ) { public Object call ( ) throws Exception { return c . call ( ) ; } } ) ; try { executor . execute ( r ) ; } catch ( InterruptedException e ) { // run with current thread instead r . run ( ) ; } } // wait for all results boolean interrupted = false ; for ( int i = 0 ; i < futures . length ; i ++ ) { Object obj = null ; InvocationTargetException ex = null ; for ( ; ; ) { try { obj = futures [ i ] . get ( ) ; } catch ( InterruptedException e ) { interrupted = true ; // reset interrupted status and try again Thread . interrupted ( ) ; continue ; } catch ( InvocationTargetException e ) { ex = e ; } results [ i ] = new Result ( obj , ex ) ; break ; } } if ( interrupted ) { // restore interrupt status again Thread . currentThread ( ) . interrupt ( ) ; } } return results ; }
Executes a set of commands and waits until all commands have been executed . The results of the commands are returned in the same order as the commands .
389
30
15,339
private void adjustPoolSize ( ) { if ( lastCheck + 1000 < System . currentTimeMillis ( ) ) { int n = Runtime . getRuntime ( ) . availableProcessors ( ) ; if ( numProcessors != n ) { executor . setMaximumPoolSize ( n ) ; numProcessors = n ; } lastCheck = System . currentTimeMillis ( ) ; } }
Adjusts the pool size at most once every second .
82
11
15,340
private void registerListener ( final ChangesLogWrapper logWrapper , TransactionableResourceManager txResourceManager ) throws RepositoryException { try { // Why calling the listeners non tx aware has been done like this: // 1. If we call them in the commit phase and we use Arjuna with ISPN, we get: // ActionStatus.COMMITTING > is not in a valid state to be invoking cache operations on. // at org.infinispan.interceptors.TxInterceptor.enlist(TxInterceptor.java:195) // at org.infinispan.interceptors.TxInterceptor.enlistReadAndInvokeNext(TxInterceptor.java:167) // at org.infinispan.interceptors.TxInterceptor.visitGetKeyValueCommand(TxInterceptor.java:162) // at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:64) // This is due to the fact that ISPN enlist the cache even for a read access and enlistments are not // allowed in the commit phase // 2. If we call them in the commit phase, we use Arjuna with ISPN and we suspend the current tx, // we get deadlocks because we try to acquire locks on cache entries that have been locked by the main tx. // 3. If we call them in the afterComplete, we use JOTM with ISPN and we suspend and resume the current tx, we get: // jotm: resume: Invalid Transaction Status:STATUS_COMMITTED (Current.java, line 743) // javax.transaction.InvalidTransactionException: Invalid resume org.objectweb.jotm.TransactionImpl // at org.objectweb.jotm.Current.resume(Current.java:744) // This is due to the fact that it is not allowed to resume a tx when its status is STATUS_COMMITED txResourceManager . addListener ( new TransactionableResourceManagerListener ( ) { public void onCommit ( boolean onePhase ) throws Exception { } public void onAfterCompletion ( int status ) throws Exception { if ( status == Status . STATUS_COMMITTED ) { // Since the tx is successfully committed we can call components non tx aware // The listeners will need to be executed outside the current tx so we suspend // the current tx we can face enlistment issues on product like ISPN transactionManager . suspend ( ) ; SecurityHelper . doPrivilegedAction ( new PrivilegedAction < Void > ( ) { public Void run ( ) { notifySaveItems ( logWrapper . getChangesLog ( ) , false ) ; return null ; } } ) ; // Since the resume method could cause issue with some TM at this stage, we don't resume the tx } } public void onAbort ( ) throws Exception { } } ) ; } catch ( Exception e ) { throw new RepositoryException ( "The listener for the components not tx aware could not be added" , e ) ; } }
This will allow to notify listeners that are not TxAware once the Tx is committed
649
19
15,341
protected ItemData getCachedItemData ( NodeData parentData , QPathEntry name , ItemType itemType ) throws RepositoryException { return cache . isEnabled ( ) ? cache . get ( parentData . getIdentifier ( ) , name , itemType ) : null ; }
Get cached ItemData .
58
5
15,342
protected ItemData getCachedItemData ( String identifier ) throws RepositoryException { return cache . isEnabled ( ) ? cache . get ( identifier ) : null ; }
Returns an item from cache by Identifier or null if the item don t cached .
34
17
15,343
protected List < NodeData > getChildNodesData ( final NodeData nodeData , boolean forcePersistentRead ) throws RepositoryException { List < NodeData > childNodes = null ; if ( ! forcePersistentRead && cache . isEnabled ( ) ) { childNodes = cache . getChildNodes ( nodeData ) ; if ( childNodes != null ) { return childNodes ; } } final DataRequest request = new DataRequest ( nodeData . getIdentifier ( ) , DataRequest . GET_NODES ) ; try { request . start ( ) ; if ( ! forcePersistentRead && cache . isEnabled ( ) ) { // Try first to get the value from the cache since a // request could have been launched just before childNodes = cache . getChildNodes ( nodeData ) ; if ( childNodes != null ) { return childNodes ; } } return executeAction ( new PrivilegedExceptionAction < List < NodeData > > ( ) { public List < NodeData > run ( ) throws RepositoryException { List < NodeData > childNodes = CacheableWorkspaceDataManager . super . getChildNodesData ( nodeData ) ; if ( cache . isEnabled ( ) ) { cache . addChildNodes ( nodeData , childNodes ) ; } return childNodes ; } } ) ; } finally { request . done ( ) ; } }
Get child NodesData .
294
6
15,344
protected List < PropertyData > getReferencedPropertiesData ( final String identifier ) throws RepositoryException { List < PropertyData > refProps = null ; if ( cache . isEnabled ( ) ) { refProps = cache . getReferencedProperties ( identifier ) ; if ( refProps != null ) { return refProps ; } } final DataRequest request = new DataRequest ( identifier , DataRequest . GET_REFERENCES ) ; try { request . start ( ) ; if ( cache . isEnabled ( ) ) { // Try first to get the value from the cache since a // request could have been launched just before refProps = cache . getReferencedProperties ( identifier ) ; if ( refProps != null ) { return refProps ; } } return executeAction ( new PrivilegedExceptionAction < List < PropertyData > > ( ) { public List < PropertyData > run ( ) throws RepositoryException { List < PropertyData > refProps = CacheableWorkspaceDataManager . super . getReferencesData ( identifier , false ) ; if ( cache . isEnabled ( ) ) { cache . addReferencedProperties ( identifier , refProps ) ; } return refProps ; } } ) ; } finally { request . done ( ) ; } }
Get referenced properties data .
272
5
15,345
protected List < PropertyData > getCachedCleanChildPropertiesData ( NodeData nodeData ) { if ( cache . isEnabled ( ) ) { List < PropertyData > childProperties = cache . getChildProperties ( nodeData ) ; if ( childProperties != null ) { boolean skip = false ; for ( PropertyData prop : childProperties ) { if ( prop != null && ! ( prop instanceof NullPropertyData ) && forceLoad ( prop ) ) { cache . remove ( prop . getIdentifier ( ) , prop ) ; skip = true ; } } if ( ! skip ) { return childProperties ; } } } return null ; }
Gets the list of child properties from the cache and checks if one of them is incomplete if everything is ok it returns the list otherwise it returns null .
137
31
15,346
protected List < PropertyData > getChildPropertiesData ( final NodeData nodeData , boolean forcePersistentRead ) throws RepositoryException { List < PropertyData > childProperties = null ; if ( ! forcePersistentRead ) { childProperties = getCachedCleanChildPropertiesData ( nodeData ) ; if ( childProperties != null ) { return childProperties ; } } final DataRequest request = new DataRequest ( nodeData . getIdentifier ( ) , DataRequest . GET_PROPERTIES ) ; try { request . start ( ) ; if ( ! forcePersistentRead ) { // Try first to get the value from the cache since a // request could have been launched just before childProperties = getCachedCleanChildPropertiesData ( nodeData ) ; if ( childProperties != null ) { return childProperties ; } } return executeAction ( new PrivilegedExceptionAction < List < PropertyData > > ( ) { public List < PropertyData > run ( ) throws RepositoryException { List < PropertyData > childProperties = CacheableWorkspaceDataManager . super . getChildPropertiesData ( nodeData ) ; if ( childProperties . size ( ) > 0 && cache . isEnabled ( ) ) { cache . addChildProperties ( nodeData , childProperties ) ; } return childProperties ; } } ) ; } finally { request . done ( ) ; } }
Get child PropertyData .
297
5
15,347
protected ItemData getPersistedItemData ( NodeData parentData , QPathEntry name , ItemType itemType ) throws RepositoryException { ItemData data = super . getItemData ( parentData , name , itemType ) ; if ( cache . isEnabled ( ) ) { if ( data == null ) { if ( itemType == ItemType . NODE || itemType == ItemType . UNKNOWN ) { cache . put ( new NullNodeData ( parentData , name ) ) ; } else { cache . put ( new NullPropertyData ( parentData , name ) ) ; } } else { cache . put ( data ) ; } } return data ; }
Get persisted ItemData .
137
5
15,348
private void initRemoteCommands ( ) { if ( rpcService != null ) { // register commands suspend = rpcService . registerCommand ( new RemoteCommand ( ) { public String getId ( ) { return "org.exoplatform.services.jcr.impl.dataflow.persistent.CacheableWorkspaceDataManager-suspend-" + dataContainer . getUniqueName ( ) ; } public Serializable execute ( Serializable [ ] args ) throws Throwable { suspendLocally ( ) ; return null ; } } ) ; resume = rpcService . registerCommand ( new RemoteCommand ( ) { public String getId ( ) { return "org.exoplatform.services.jcr.impl.dataflow.persistent.CacheableWorkspaceDataManager-resume-" + dataContainer . getUniqueName ( ) ; } public Serializable execute ( Serializable [ ] args ) throws Throwable { resumeLocally ( ) ; return null ; } } ) ; requestForResponsibleForResuming = rpcService . registerCommand ( new RemoteCommand ( ) { public String getId ( ) { return "org.exoplatform.services.jcr.impl.dataflow.persistent.CacheableWorkspaceDataManager" + "-requestForResponsibilityForResuming-" + dataContainer . getUniqueName ( ) ; } public Serializable execute ( Serializable [ ] args ) throws Throwable { return isResponsibleForResuming . get ( ) ; } } ) ; } }
Initialization remote commands .
318
5
15,349
private void unregisterRemoteCommands ( ) { if ( rpcService != null ) { rpcService . unregisterCommand ( suspend ) ; rpcService . unregisterCommand ( resume ) ; rpcService . unregisterCommand ( requestForResponsibleForResuming ) ; } }
Unregister remote commands .
61
5
15,350
private ItemData initACL ( NodeData parent , NodeData node ) throws RepositoryException { return initACL ( parent , node , null ) ; }
Init ACL of the node .
33
6
15,351
private NodeData getACL ( String identifier , ACLSearch search ) throws RepositoryException { final ItemData item = getItemData ( identifier , false ) ; return item != null && item . isNode ( ) ? initACL ( null , ( NodeData ) item , search ) : null ; }
Find Item by identifier to get the missing ACL information .
63
11
15,352
public List < ACLHolder > getACLHolders ( ) throws RepositoryException { WorkspaceStorageConnection conn = dataContainer . openConnection ( ) ; try { return conn . getACLHolders ( ) ; } finally { conn . close ( ) ; } }
Gets the list of all the ACL holders
57
9
15,353
protected boolean loadFilters ( final boolean cleanOnFail , boolean asynchronous ) { if ( ! filtersSupported . get ( ) ) { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( "The bloom filters are not supported therefore they cannot be reloaded" ) ; } return false ; } filtersEnabled . set ( false ) ; this . filterPermissions = new BloomFilter < String > ( bfProbability , bfElementNumber ) ; this . filterOwner = new BloomFilter < String > ( bfProbability , bfElementNumber ) ; if ( asynchronous ) { new Thread ( new Runnable ( ) { public void run ( ) { doLoadFilters ( cleanOnFail ) ; } } , "BloomFilter-Loader-" + dataContainer . getName ( ) ) . start ( ) ; return true ; } else { return doLoadFilters ( cleanOnFail ) ; } }
Loads the bloom filters
194
5
15,354
private boolean forceLoad ( PropertyData prop ) { final List < ValueData > vals = prop . getValues ( ) ; for ( int i = 0 ; i < vals . size ( ) ; i ++ ) { ValueData vd = vals . get ( i ) ; if ( ! vd . isByteArray ( ) ) { // check if file is correct FilePersistedValueData fpvd = ( FilePersistedValueData ) vd ; if ( fpvd . getFile ( ) == null ) { if ( fpvd instanceof StreamPersistedValueData && ( ( StreamPersistedValueData ) fpvd ) . getUrl ( ) != null ) continue ; return true ; } else if ( ! PrivilegedFileHelper . exists ( fpvd . getFile ( ) ) ) // check if file exist { return true ; } } } return false ; }
Check Property BLOB Values if someone has null file .
187
11
15,355
public Response move ( Session session , String srcPath , String destPath ) { try { session . move ( srcPath , destPath ) ; session . save ( ) ; // If the source resource was successfully moved // to a pre-existing destination resource. if ( itemExisted ) { return Response . status ( HTTPStatus . NO_CONTENT ) . cacheControl ( cacheControl ) . build ( ) ; } // If the source resource was successfully moved, // and a new resource was created at the destination. else { if ( uriBuilder != null ) { return Response . created ( uriBuilder . path ( session . getWorkspace ( ) . getName ( ) ) . path ( destPath ) . build ( ) ) . cacheControl ( cacheControl ) . build ( ) ; } // to save compatibility if uriBuilder is not provided return Response . status ( HTTPStatus . CREATED ) . cacheControl ( cacheControl ) . build ( ) ; } } catch ( LockException exc ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . CONFLICT ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( RepositoryException exc ) { log . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav Move method implementation .
318
7
15,356
protected List < ValueData > loadPropertyValues ( NodeData parentNode , ItemData property , InternalQName propertyName ) throws RepositoryException { if ( property == null ) { property = dataManager . getItemData ( parentNode , new QPathEntry ( propertyName , 1 ) , ItemType . PROPERTY ) ; } if ( property != null ) { if ( property . isNode ( ) ) throw new RepositoryException ( "Fail to load property " + propertyName + "not found for " + parentNode . getQPath ( ) . getAsString ( ) ) ; return ( ( PropertyData ) property ) . getValues ( ) ; } return null ; }
Load values .
142
3
15,357
protected void awaitTasksTermination ( ) { delegated . shutdown ( ) ; try { delegated . awaitTermination ( Long . MAX_VALUE , TimeUnit . NANOSECONDS ) ; } catch ( InterruptedException e ) { LOG . warn ( "Termination has been interrupted" ) ; } }
Awaits until all tasks will be done .
65
10
15,358
public int closeSessions ( String workspaceName ) { int closedSessions = 0 ; for ( SessionImpl session : sessionsMap . values ( ) ) { if ( session . getWorkspace ( ) . getName ( ) . equals ( workspaceName ) ) { session . logout ( ) ; closedSessions ++ ; } } return closedSessions ; }
closeSessions will be closed the all sessions on specific workspace .
74
13
15,359
public void commitTransaction ( ) { CompressedISPNChangesBuffer changesContainer = getChangesBufferSafe ( ) ; final TransactionManager tm = getTransactionManager ( ) ; try { final List < ChangesContainer > containers = changesContainer . getSortedList ( ) ; commitChanges ( tm , containers ) ; } finally { changesList . set ( null ) ; changesContainer = null ; } }
Sort changes and commit data to the cache .
82
9
15,360
public void setLocal ( boolean local ) { // start local transaction if ( local && changesList . get ( ) == null ) { beginTransaction ( ) ; } this . local . set ( local ) ; }
Creates all ChangesBuffers with given parameter
43
9
15,361
private CompressedISPNChangesBuffer getChangesBufferSafe ( ) { CompressedISPNChangesBuffer changesContainer = changesList . get ( ) ; if ( changesContainer == null ) { throw new IllegalStateException ( "changesContainer should not be empty" ) ; } return changesContainer ; }
Tries to get buffer and if it is null throws an exception otherwise returns buffer .
60
17
15,362
@ GET @ Path ( "/{path:.*}/" ) public Response getResource ( @ PathParam ( "path" ) String mavenPath , final @ Context UriInfo uriInfo , final @ QueryParam ( "view" ) String view , final @ QueryParam ( "gadget" ) String gadget ) { String resourcePath = mavenRoot + mavenPath ; // JCR resource String shaResourcePath = mavenPath . endsWith ( ".sha1" ) ? mavenRoot + mavenPath : mavenRoot + mavenPath + ".sha1" ; mavenPath = uriInfo . getBaseUriBuilder ( ) . path ( getClass ( ) ) . path ( mavenPath ) . build ( ) . toString ( ) ; Session ses = null ; try { // JCR resource SessionProvider sp = sessionProviderService . getSessionProvider ( null ) ; if ( sp == null ) throw new RepositoryException ( "Access to JCR Repository denied. SessionProvider is null." ) ; ses = sp . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; ExtendedNode node = ( ExtendedNode ) ses . getRootNode ( ) . getNode ( resourcePath ) ; if ( isFile ( node ) ) { if ( view != null && view . equalsIgnoreCase ( "true" ) ) { ExtendedNode shaNode = null ; try { shaNode = ( ExtendedNode ) ses . getRootNode ( ) . getNode ( shaResourcePath ) ; } catch ( RepositoryException e ) { // no .sh1 file found if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } return getArtifactInfo ( node , mavenPath , gadget , shaNode ) ; } else { return downloadArtifact ( node ) ; } } else { return browseRepository ( node , mavenPath , gadget ) ; } } catch ( PathNotFoundException e ) { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( e . getLocalizedMessage ( ) , e ) ; return Response . status ( Response . Status . NOT_FOUND ) . build ( ) ; } catch ( AccessDeniedException e ) { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( e . getLocalizedMessage ( ) , e ) ; if ( ses == null || ses . getUserID ( ) . equals ( IdentityConstants . ANONIM ) ) return Response . status ( Response . Status . UNAUTHORIZED ) . header ( ExtHttpHeaders . WWW_AUTHENTICATE , "Basic realm=\"" + realmName + "\"" ) . build ( ) ; else return Response . status ( Response . Status . FORBIDDEN ) . build ( ) ; } catch ( Exception e ) { LOG . error ( "Failed get maven artifact" , e ) ; throw new WebApplicationException ( e ) ; } finally { if ( ses != null ) ses . logout ( ) ; } }
Return Response with Maven artifact if it is file or HTML page for browsing if requested URL is folder .
666
21
15,363
@ GET public Response getRootNodeList ( final @ Context UriInfo uriInfo , final @ QueryParam ( "view" ) String view , final @ QueryParam ( "gadget" ) String gadget ) { return getResource ( "" , uriInfo , view , gadget ) ; }
Browsing of root node of Maven repository .
61
11
15,364
private static boolean isFile ( Node node ) throws RepositoryException { if ( ! node . isNodeType ( "nt:file" ) ) { return false ; } if ( ! node . getNode ( "jcr:content" ) . isNodeType ( "nt:resource" ) ) { return false ; } return true ; }
Check is node represents file .
71
6
15,365
private Response downloadArtifact ( Node node ) throws Exception { NodeRepresentation nodeRepresentation = nodeRepresentationService . getNodeRepresentation ( node , null ) ; if ( node . canAddMixin ( "exo:mavencounter" ) ) { node . addMixin ( "exo:mavencounter" ) ; node . getSession ( ) . save ( ) ; } node . setProperty ( "exo:downloadcounter" , node . getProperty ( "exo:downloadcounter" ) . getLong ( ) + 1l ) ; node . getSession ( ) . save ( ) ; long lastModified = nodeRepresentation . getLastModified ( ) ; String contentType = nodeRepresentation . getMediaType ( ) ; long contentLength = nodeRepresentation . getContentLenght ( ) ; InputStream entity = nodeRepresentation . getInputStream ( ) ; Response response = Response . ok ( entity , contentType ) . header ( HttpHeaders . CONTENT_LENGTH , Long . toString ( contentLength ) ) . lastModified ( new Date ( lastModified ) ) . build ( ) ; return response ; }
Get content of JCR node .
246
7
15,366
public static void registerStatistics ( String category , Statistics global , Map < String , Statistics > allStatistics ) { if ( category == null || category . length ( ) == 0 ) { throw new IllegalArgumentException ( "The category of the statistics cannot be empty" ) ; } if ( allStatistics == null || allStatistics . isEmpty ( ) ) { throw new IllegalArgumentException ( "The list of statistics " + category + " cannot be empty" ) ; } PrintWriter pw = null ; if ( PERSISTENCE_ENABLED ) { pw = initWriter ( category ) ; if ( pw == null ) { LOG . warn ( "Cannot create the print writer for the statistics " + category ) ; } } startIfNeeded ( ) ; synchronized ( JCRStatisticsManager . class ) { Map < String , StatisticsContext > tmpContexts = new HashMap < String , StatisticsContext > ( CONTEXTS ) ; StatisticsContext ctx = new StatisticsContext ( pw , global , allStatistics ) ; tmpContexts . put ( category , ctx ) ; if ( pw != null ) { // Define the file header printHeader ( ctx ) ; } CONTEXTS = Collections . unmodifiableMap ( tmpContexts ) ; } }
Register a new category of statistics to manage .
267
9
15,367
private static void startIfNeeded ( ) { if ( ! STARTED ) { synchronized ( JCRStatisticsManager . class ) { if ( ! STARTED ) { addTriggers ( ) ; ExoContainer container = ExoContainerContext . getTopContainer ( ) ; ManagementContext ctx = null ; if ( container != null ) { ctx = container . getManagementContext ( ) ; } if ( ctx == null ) { LOG . warn ( "Cannot register the statistics" ) ; } else { ctx . register ( new JCRStatisticsManager ( ) ) ; } STARTED = true ; } } } }
Starts the manager if needed
131
6
15,368
private static void addTriggers ( ) { if ( ! PERSISTENCE_ENABLED ) { return ; } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( "JCRStatisticsManager-Hook" ) { @ Override public void run ( ) { printData ( ) ; } } ) ; Thread t = new Thread ( "JCRStatisticsManager-Writer" ) { @ Override public void run ( ) { while ( true ) { try { sleep ( PERSISTENCE_TIMEOUT ) ; } catch ( InterruptedException e ) { LOG . debug ( "InterruptedException" , e ) ; } printData ( ) ; } } } ; t . setDaemon ( true ) ; t . start ( ) ; }
Add all the triggers that will keep the file up to date only if the persistence is enabled .
162
19
15,369
private static void printData ( ) { Map < String , StatisticsContext > tmpContexts = CONTEXTS ; for ( StatisticsContext context : tmpContexts . values ( ) ) { printData ( context ) ; } }
Add one line of data to all the csv files .
46
12
15,370
private static void printData ( StatisticsContext context ) { if ( context . writer == null ) { return ; } boolean first = true ; if ( context . global != null ) { context . global . printData ( context . writer ) ; first = false ; } for ( Statistics s : context . allStatistics . values ( ) ) { if ( first ) { first = false ; } else { context . writer . print ( ' ' ) ; } s . printData ( context . writer ) ; } context . writer . println ( ) ; context . writer . flush ( ) ; }
Add one line of data to the csv file related to the given context .
120
16
15,371
private static StatisticsContext getContext ( String category ) { if ( category == null ) { return null ; } return CONTEXTS . get ( category ) ; }
Retrieve statistics context of the given category .
33
9
15,372
static String formatName ( String name ) { return name == null ? null : name . replaceAll ( " " , "" ) . replaceAll ( "[,;]" , ", " ) ; }
Format the name of the statistics in the target format
40
10
15,373
private static Statistics getStatistics ( String category , String name ) { StatisticsContext context = getContext ( category ) ; if ( context == null ) { return null ; } // Format the name name = formatName ( name ) ; if ( name == null ) { return null ; } Statistics statistics ; if ( GLOBAL_STATISTICS_NAME . equalsIgnoreCase ( name ) ) { statistics = context . global ; } else { statistics = context . allStatistics . get ( name ) ; } return statistics ; }
Retrieve statistics of the given category and name .
107
10
15,374
@ Managed @ ManagedDescription ( "Reset all the statistics." ) public static void resetAll ( @ ManagedDescription ( "The name of the category of the statistics" ) @ ManagedName ( "categoryName" ) String category ) { StatisticsContext context = getContext ( category ) ; if ( context != null ) { context . reset ( ) ; } }
Allows to reset all the statistics corresponding to the given category .
77
12
15,375
public QPath getRemainder ( ) { if ( matchPos + matchLength >= pathLength ) { return null ; } else { try { throw new RepositoryException ( "Not implemented" ) ; //return path.subPath(matchPos + matchLength, pathLength); } catch ( RepositoryException e ) { throw ( IllegalStateException ) new IllegalStateException ( "Path not normalized" ) . initCause ( e ) ; } } }
Returns the remaining path after the matching part .
94
9
15,376
private void calculateDocFilter ( ) throws IOException { PerQueryCache cache = PerQueryCache . getInstance ( ) ; @ SuppressWarnings ( "unchecked" ) Map < String , BitSet > readerCache = ( Map < String , BitSet > ) cache . get ( MatchAllScorer . class , reader ) ; if ( readerCache == null ) { readerCache = new HashMap < String , BitSet > ( ) ; cache . put ( MatchAllScorer . class , reader , readerCache ) ; } // get BitSet for field docFilter = ( BitSet ) readerCache . get ( field ) ; if ( docFilter != null ) { // use cached BitSet; return ; } // otherwise calculate new docFilter = new BitSet ( reader . maxDoc ( ) ) ; // we match all terms String namedValue = FieldNames . createNamedValue ( field , "" ) ; TermEnum terms = reader . terms ( new Term ( FieldNames . PROPERTIES , namedValue ) ) ; try { TermDocs docs = reader . termDocs ( ) ; try { while ( terms . term ( ) != null && terms . term ( ) . field ( ) == FieldNames . PROPERTIES && terms . term ( ) . text ( ) . startsWith ( namedValue ) ) { docs . seek ( terms ) ; while ( docs . next ( ) ) { docFilter . set ( docs . doc ( ) ) ; } terms . next ( ) ; } } finally { docs . close ( ) ; } } finally { terms . close ( ) ; } // put BitSet into cache readerCache . put ( field , docFilter ) ; }
Calculates a BitSet filter that includes all the nodes that have content in properties according to the field name passed in the constructor of this MatchAllScorer .
352
33
15,377
public String [ ] getSynonyms ( String word ) { String [ ] synonyms = table . get ( word ) ; if ( synonyms == null ) return EMPTY ; String [ ] copy = new String [ synonyms . length ] ; // copy for guaranteed immutability System . arraycopy ( synonyms , 0 , copy , 0 , synonyms . length ) ; return copy ; }
Returns the synonym set for the given word sorted ascending .
81
12
15,378
public static void writePropStats ( XMLStreamWriter xmlStreamWriter , Map < String , Set < HierarchicalProperty > > propStatuses ) throws XMLStreamException { for ( Map . Entry < String , Set < HierarchicalProperty > > stat : propStatuses . entrySet ( ) ) { xmlStreamWriter . writeStartElement ( "DAV:" , "propstat" ) ; xmlStreamWriter . writeStartElement ( "DAV:" , "prop" ) ; for ( HierarchicalProperty prop : propStatuses . get ( stat . getKey ( ) ) ) { writeProperty ( xmlStreamWriter , prop ) ; } xmlStreamWriter . writeEndElement ( ) ; xmlStreamWriter . writeStartElement ( "DAV:" , "status" ) ; xmlStreamWriter . writeCharacters ( stat . getKey ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; // D:propstat xmlStreamWriter . writeEndElement ( ) ; } }
Writes the statuses of properties into XML .
204
10
15,379
public static void writeProperty ( XMLStreamWriter xmlStreamWriter , HierarchicalProperty prop ) throws XMLStreamException { String uri = prop . getName ( ) . getNamespaceURI ( ) ; String prefix = xmlStreamWriter . getNamespaceContext ( ) . getPrefix ( uri ) ; if ( prefix == null ) { prefix = "" ; } String local = prop . getName ( ) . getLocalPart ( ) ; if ( prop . getValue ( ) == null ) { if ( prop . getChildren ( ) . size ( ) != 0 ) { xmlStreamWriter . writeStartElement ( prefix , local , uri ) ; if ( ! uri . equalsIgnoreCase ( "DAV:" ) ) { xmlStreamWriter . writeNamespace ( prefix , uri ) ; } writeAttributes ( xmlStreamWriter , prop ) ; for ( int i = 0 ; i < prop . getChildren ( ) . size ( ) ; i ++ ) { HierarchicalProperty property = prop . getChildren ( ) . get ( i ) ; writeProperty ( xmlStreamWriter , property ) ; } xmlStreamWriter . writeEndElement ( ) ; } else { xmlStreamWriter . writeEmptyElement ( prefix , local , uri ) ; if ( ! uri . equalsIgnoreCase ( "DAV:" ) ) { xmlStreamWriter . writeNamespace ( prefix , uri ) ; } writeAttributes ( xmlStreamWriter , prop ) ; } } else { xmlStreamWriter . writeStartElement ( prefix , local , uri ) ; if ( ! uri . equalsIgnoreCase ( "DAV:" ) ) { xmlStreamWriter . writeNamespace ( prefix , uri ) ; } writeAttributes ( xmlStreamWriter , prop ) ; xmlStreamWriter . writeCharacters ( prop . getValue ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; } }
Writes the statuses of property into XML .
394
10
15,380
public static void writeAttributes ( XMLStreamWriter xmlStreamWriter , HierarchicalProperty property ) throws XMLStreamException { Map < String , String > attributes = property . getAttributes ( ) ; Iterator < String > keyIter = attributes . keySet ( ) . iterator ( ) ; while ( keyIter . hasNext ( ) ) { String attrName = keyIter . next ( ) ; String attrValue = attributes . get ( attrName ) ; xmlStreamWriter . writeAttribute ( attrName , attrValue ) ; } }
Writes property attributes into XML .
113
7
15,381
private String getRealm ( String sUrl ) throws IOException , ModuleException { AuthorizationHandler ah = AuthorizationInfo . getAuthHandler ( ) ; try { URL url = new URL ( sUrl ) ; HTTPConnection connection = new HTTPConnection ( url ) ; connection . removeModule ( CookieModule . class ) ; AuthorizationInfo . setAuthHandler ( null ) ; HTTPResponse resp = connection . Get ( url . getFile ( ) ) ; String authHeader = resp . getHeader ( "WWW-Authenticate" ) ; if ( authHeader == null ) { return null ; } String realm = authHeader . split ( "=" ) [ 1 ] ; realm = realm . substring ( 1 , realm . length ( ) - 1 ) ; return realm ; } finally { AuthorizationInfo . setAuthHandler ( ah ) ; } }
Get realm by URL .
174
5
15,382
public static String getChecksum ( InputStream in , String algo ) throws NoSuchAlgorithmException , IOException { MessageDigest md = MessageDigest . getInstance ( algo ) ; DigestInputStream digestInputStream = new DigestInputStream ( in , md ) ; digestInputStream . on ( true ) ; while ( digestInputStream . read ( ) > - 1 ) { digestInputStream . read ( ) ; } byte [ ] bytes = digestInputStream . getMessageDigest ( ) . digest ( ) ; return generateString ( bytes ) ; }
Generates checksum for the InputStream .
119
9
15,383
private static String generateString ( byte [ ] bytes ) { StringBuffer sb = new StringBuffer ( ) ; for ( byte b : bytes ) { int v = b & 0xFF ; sb . append ( ( char ) HEX . charAt ( v >> 4 ) ) ; sb . append ( ( char ) HEX . charAt ( v & 0x0f ) ) ; } return sb . toString ( ) ; }
Converts the array of bytes into a HEX string .
94
12
15,384
public static void cleanWorkspaceData ( WorkspaceEntry wsEntry ) throws DBCleanException { SecurityHelper . validateSecurityPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; Connection jdbcConn = getConnection ( wsEntry ) ; String dialect = resolveDialect ( jdbcConn , wsEntry ) ; boolean autoCommit = dialect . startsWith ( DialectConstants . DB_DIALECT_SYBASE ) ; try { jdbcConn . setAutoCommit ( autoCommit ) ; DBCleanerTool dbCleaner = getWorkspaceDBCleaner ( jdbcConn , wsEntry ) ; doClean ( dbCleaner ) ; } catch ( SQLException e ) { throw new DBCleanException ( e ) ; } finally { try { jdbcConn . close ( ) ; } catch ( SQLException e ) { LOG . error ( "Can not close connection" , e ) ; } } }
Cleans workspace data from database .
218
7
15,385
public static void cleanRepositoryData ( RepositoryEntry rEntry ) throws DBCleanException { SecurityHelper . validateSecurityPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; WorkspaceEntry wsEntry = rEntry . getWorkspaceEntries ( ) . get ( 0 ) ; boolean multiDB = getMultiDbParameter ( wsEntry ) ; if ( multiDB ) { for ( WorkspaceEntry entry : rEntry . getWorkspaceEntries ( ) ) { cleanWorkspaceData ( entry ) ; } } else { Connection jdbcConn = getConnection ( wsEntry ) ; String dialect = resolveDialect ( jdbcConn , wsEntry ) ; boolean autoCommit = dialect . startsWith ( DialectConstants . DB_DIALECT_SYBASE ) ; try { jdbcConn . setAutoCommit ( autoCommit ) ; DBCleanerTool dbCleaner = getRepositoryDBCleaner ( jdbcConn , rEntry ) ; doClean ( dbCleaner ) ; } catch ( SQLException e ) { throw new DBCleanException ( e ) ; } finally { try { jdbcConn . close ( ) ; } catch ( SQLException e ) { LOG . error ( "Can not close connection" , e ) ; } } } }
Cleans repository data from database .
291
7
15,386
public static DBCleanerTool getRepositoryDBCleaner ( Connection jdbcConn , RepositoryEntry rEntry ) throws DBCleanException { SecurityHelper . validateSecurityPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; WorkspaceEntry wsEntry = rEntry . getWorkspaceEntries ( ) . get ( 0 ) ; boolean multiDb = getMultiDbParameter ( wsEntry ) ; if ( multiDb ) { throw new DBCleanException ( "It is not possible to create cleaner with common connection for multi database repository configuration" ) ; } String dialect = resolveDialect ( jdbcConn , wsEntry ) ; boolean autoCommit = dialect . startsWith ( DialectConstants . DB_DIALECT_SYBASE ) ; DBCleaningScripts scripts = DBCleaningScriptsFactory . prepareScripts ( dialect , rEntry ) ; return new DBCleanerTool ( jdbcConn , autoCommit , scripts . getCleaningScripts ( ) , scripts . getCommittingScripts ( ) , scripts . getRollbackingScripts ( ) ) ; }
Returns database cleaner for repository .
247
6
15,387
public static DBCleanerTool getWorkspaceDBCleaner ( Connection jdbcConn , WorkspaceEntry wsEntry ) throws DBCleanException { SecurityHelper . validateSecurityPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; String dialect = resolveDialect ( jdbcConn , wsEntry ) ; boolean autoCommit = dialect . startsWith ( DialectConstants . DB_DIALECT_SYBASE ) ; DBCleaningScripts scripts = DBCleaningScriptsFactory . prepareScripts ( dialect , wsEntry ) ; return new DBCleanerTool ( jdbcConn , autoCommit , scripts . getCleaningScripts ( ) , scripts . getCommittingScripts ( ) , scripts . getRollbackingScripts ( ) ) ; }
Returns database cleaner for workspace .
179
6
15,388
private static Connection getConnection ( WorkspaceEntry wsEntry ) throws DBCleanException { String dsName = getSourceNameParameter ( wsEntry ) ; DataSource ds ; try { ds = ( DataSource ) new InitialContext ( ) . lookup ( dsName ) ; } catch ( NamingException e ) { throw new DBCleanException ( e ) ; } if ( ds == null ) { throw new DBCleanException ( "Data source " + dsName + " not found" ) ; } final DataSource dsF = ds ; Connection jdbcConn ; try { jdbcConn = SecurityHelper . doPrivilegedSQLExceptionAction ( new PrivilegedExceptionAction < Connection > ( ) { public Connection run ( ) throws Exception { return dsF . getConnection ( ) ; } } ) ; } catch ( SQLException e ) { throw new DBCleanException ( e ) ; } return jdbcConn ; }
Opens connection to database underlying a workspace .
209
9
15,389
private String hash ( String dataId ) { try { MessageDigest digest = MessageDigest . getInstance ( hashAlgorithm ) ; digest . update ( dataId . getBytes ( "UTF-8" ) ) ; return new BigInteger ( 1 , digest . digest ( ) ) . toString ( 32 ) ; } catch ( NumberFormatException e ) { throw new RuntimeException ( "Could not generate the hash code of '" + dataId + "' with the algorithm '" + hashAlgorithm + "'" , e ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( "Could not generate the hash code of '" + dataId + "' with the algorithm '" + hashAlgorithm + "'" , e ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( "Could not generate the hash code of '" + dataId + "' with the algorithm '" + hashAlgorithm + "'" , e ) ; } }
Gives the hash code of the given data id
207
10
15,390
private QPathEntry parsePatternQPathEntry ( String namePattern , SessionImpl session ) throws RepositoryException { int colonIndex = namePattern . indexOf ( ' ' ) ; int bracketIndex = namePattern . lastIndexOf ( ' ' ) ; String namespaceURI ; String localName ; int index = getDefaultIndex ( ) ; if ( bracketIndex != - 1 ) { int rbracketIndex = namePattern . lastIndexOf ( ' ' ) ; if ( rbracketIndex < bracketIndex ) { throw new RepositoryException ( "Malformed pattern expression " + namePattern ) ; } index = Integer . parseInt ( namePattern . substring ( bracketIndex + 1 , rbracketIndex ) ) ; } if ( colonIndex == - 1 ) { namespaceURI = "" ; localName = ( bracketIndex == - 1 ) ? namePattern : namePattern . substring ( 0 , bracketIndex ) ; } else { String prefix = namePattern . substring ( 0 , colonIndex ) ; localName = ( bracketIndex == - 1 ) ? namePattern . substring ( colonIndex + 1 ) : namePattern . substring ( 0 , bracketIndex ) ; if ( prefix . indexOf ( "*" ) != - 1 ) { namespaceURI = "*" ; } else { namespaceURI = session . getNamespaceURI ( prefix ) ; } } return new PatternQPathEntry ( namespaceURI , localName , index ) ; }
Parse QPathEntry from string namePattern . NamePattern may contain wildcard symbols in namespace and local name . And may not contain index which means look all samename siblings . So ordinary QPathEntry parser is not acceptable .
301
46
15,391
protected void accumulatePersistedNodesChanges ( Map < String , Long > calculatedChangedNodesSize ) throws QuotaManagerException { for ( Entry < String , Long > entry : calculatedChangedNodesSize . entrySet ( ) ) { String nodePath = entry . getKey ( ) ; long delta = entry . getValue ( ) ; try { long dataSize = delta + quotaPersister . getNodeDataSize ( rName , wsName , nodePath ) ; quotaPersister . setNodeDataSizeIfQuotaExists ( rName , wsName , nodePath , dataSize ) ; } catch ( UnknownDataSizeException e ) { calculateNodeDataSizeTool . getAndSetNodeDataSize ( nodePath ) ; } } }
Update nodes data size .
156
5
15,392
protected void accumulatePersistedWorkspaceChanges ( long delta ) throws QuotaManagerException { long dataSize = 0 ; try { dataSize = quotaPersister . getWorkspaceDataSize ( rName , wsName ) ; } catch ( UnknownDataSizeException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( e . getMessage ( ) , e ) ; } } long newDataSize = Math . max ( dataSize + delta , 0 ) ; // avoid possible inconsistency quotaPersister . setWorkspaceDataSize ( rName , wsName , newDataSize ) ; }
Update workspace data size .
129
5
15,393
protected void accumulatePersistedRepositoryChanges ( long delta ) { long dataSize = 0 ; try { dataSize = quotaPersister . getRepositoryDataSize ( rName ) ; } catch ( UnknownDataSizeException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( e . getMessage ( ) , e ) ; } } long newDataSize = Math . max ( dataSize + delta , 0 ) ; // to avoid possible inconsistency quotaPersister . setRepositoryDataSize ( rName , newDataSize ) ; }
Update repository data size .
117
5
15,394
private void accumulatePersistedGlobalChanges ( long delta ) { long dataSize = 0 ; try { dataSize = quotaPersister . getGlobalDataSize ( ) ; } catch ( UnknownDataSizeException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( e . getMessage ( ) , e ) ; } } long newDataSize = Math . max ( dataSize + delta , 0 ) ; // to avoid possible inconsistency quotaPersister . setGlobalDataSize ( newDataSize ) ; }
Update global data size .
109
5
15,395
protected NodeImpl parent ( final boolean pool ) throws RepositoryException { NodeImpl parent = ( NodeImpl ) dataManager . getItemByIdentifier ( getParentIdentifier ( ) , pool ) ; if ( parent == null ) { throw new ItemNotFoundException ( "FATAL: Parent is null for " + getPath ( ) + " parent UUID: " + getParentIdentifier ( ) ) ; } return parent ; }
Get parent node item .
91
5
15,396
public NodeData parentData ( ) throws RepositoryException { checkValid ( ) ; NodeData parent = ( NodeData ) dataManager . getItemData ( getData ( ) . getParentIdentifier ( ) ) ; if ( parent == null ) { throw new ItemNotFoundException ( "FATAL: Parent is null for " + getPath ( ) + " parent UUID: " + getData ( ) . getParentIdentifier ( ) ) ; } return parent ; }
Get and return parent node data .
100
7
15,397
public JCRPath getLocation ( ) throws RepositoryException { if ( this . location == null ) { this . location = session . getLocationFactory ( ) . createJCRPath ( qpath ) ; } return this . location ; }
Get item JCRPath location .
50
7
15,398
public String getType ( ) { if ( input == null ) { return "allprop" ; } if ( input . getChild ( PropertyConstants . DAV_ALLPROP_INCLUDE ) != null ) { return "include" ; } QName name = input . getChild ( 0 ) . getName ( ) ; if ( name . getNamespaceURI ( ) . equals ( "DAV:" ) ) return name . getLocalPart ( ) ; else return null ; }
Returns the type of request .
103
6
15,399
public R run ( A ... arg ) throws E { final TransactionManager tm = getTransactionManager ( ) ; Transaction tx = null ; try { if ( tm != null ) { try { tx = tm . suspend ( ) ; } catch ( SystemException e ) { LOG . warn ( "Cannot suspend the current transaction" , e ) ; } } return execute ( arg ) ; } finally { if ( tx != null ) { try { tm . resume ( tx ) ; } catch ( Exception e ) { LOG . warn ( "Cannot resume the current transaction" , e ) ; } } } }
Executes the action outside the context of the current tx
128
11