idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
15,400
protected R execute ( A ... arg ) throws E { if ( arg == null || arg . length == 0 ) { return execute ( ( A ) null ) ; } return execute ( arg [ 0 ] ) ; }
Executes the action
44
4
15,401
public NodeRepresentation getNodeRepresentation ( Node node , String mediaTypeHint ) throws RepositoryException { NodeRepresentationFactory factory = factory ( node ) ; if ( factory != null ) return factory . createNodeRepresentation ( node , mediaTypeHint ) ; else return new DocumentViewNodeRepresentation ( node ) ; }
Get NodeRepresentation for given node . String mediaTypeHint can be used as external information for representation . By default node will be represented as doc - view .
69
33
15,402
public void spoolDone ( ) { final CountDownLatch sl = this . spoolLatch . get ( ) ; this . spoolLatch . set ( null ) ; sl . countDown ( ) ; }
Mark the file ready for read .
46
7
15,403
public ItemData getItemData ( NodeData parent , QPathEntry [ ] relPathEntries , ItemType itemType ) throws RepositoryException { ItemData item = parent ; for ( int i = 0 ; i < relPathEntries . length ; i ++ ) { if ( i == relPathEntries . length - 1 ) { item = getItemData ( parent , relPathEntries [ i ] , itemType ) ; } else { item = getItemData ( parent , relPathEntries [ i ] , ItemType . UNKNOWN ) ; } if ( item == null ) { break ; } if ( item . isNode ( ) ) { parent = ( NodeData ) item ; } else if ( i < relPathEntries . length - 1 ) { throw new IllegalPathException ( "Path can not contains a property as the intermediate element" ) ; } } return item ; }
Return item data by parent NodeDada and relPathEntries If relpath is JCRPath . THIS_RELPATH = . it return itself
188
30
15,404
public ItemData getItemData ( String identifier , boolean checkChangesLogOnly ) throws RepositoryException { ItemData data = null ; // 1. Try in transient changes ItemState state = changesLog . getItemState ( identifier ) ; if ( state == null ) { // 2. Try from txdatamanager data = transactionableManager . getItemData ( identifier , checkChangesLogOnly ) ; data = updatePathIfNeeded ( data ) ; } else if ( ! state . isDeleted ( ) ) { data = state . getData ( ) ; } return data ; }
Return item data by identifier in this transient storage then in workspace container .
121
14
15,405
public ItemImpl getItem ( NodeData parent , QPathEntry name , boolean pool , ItemType itemType ) throws RepositoryException { return getItem ( parent , name , pool , itemType , true ) ; }
Return Item by parent NodeDada and the name of searched item .
45
14
15,406
public ItemImpl getItem ( NodeData parent , QPathEntry name , boolean pool , ItemType itemType , boolean apiRead , boolean createNullItemData ) throws RepositoryException { long start = 0 ; if ( LOG . isDebugEnabled ( ) ) { start = System . currentTimeMillis ( ) ; LOG . debug ( "getItem(" + parent . getQPath ( ) . getAsString ( ) + " + " + name . getAsString ( ) + " ) >>>>>" ) ; } ItemImpl item = null ; try { return item = readItem ( getItemData ( parent , name , itemType , createNullItemData ) , parent , pool , apiRead ) ; } finally { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "getItem(" + parent . getQPath ( ) . getAsString ( ) + " + " + name . getAsString ( ) + ") --> " + ( item != null ? item . getPath ( ) : "null" ) + " <<<<< " + ( ( System . currentTimeMillis ( ) - start ) / 1000d ) + "sec" ) ; } } }
For internal use . Return Item by parent NodeDada and the name of searched item .
250
18
15,407
public ItemImpl getItem ( NodeData parent , QPathEntry [ ] relPath , boolean pool , ItemType itemType ) throws RepositoryException { long start = 0 ; if ( LOG . isDebugEnabled ( ) ) { start = System . currentTimeMillis ( ) ; StringBuilder debugPath = new StringBuilder ( ) ; for ( QPathEntry rp : relPath ) { debugPath . append ( rp . getAsString ( ) ) ; } LOG . debug ( "getItem(" + parent . getQPath ( ) . getAsString ( ) + " + " + debugPath + " ) >>>>>" ) ; } ItemImpl item = null ; try { return item = readItem ( getItemData ( parent , relPath , itemType ) , pool ) ; } finally { if ( LOG . isDebugEnabled ( ) ) { StringBuilder debugPath = new StringBuilder ( ) ; for ( QPathEntry rp : relPath ) { debugPath . append ( rp . getAsString ( ) ) ; } LOG . debug ( "getItem(" + parent . getQPath ( ) . getAsString ( ) + " + " + debugPath + ") --> " + ( item != null ? item . getPath ( ) : "null" ) + " <<<<< " + ( ( System . currentTimeMillis ( ) - start ) / 1000d ) + "sec" ) ; } } }
Return Item by parent NodeDada and array of QPathEntry which represent a relative path to the searched item
302
22
15,408
public ItemImpl getItem ( QPath path , boolean pool ) throws RepositoryException { long start = 0 ; if ( LOG . isDebugEnabled ( ) ) { start = System . currentTimeMillis ( ) ; LOG . debug ( "getItem(" + path . getAsString ( ) + " ) >>>>>" ) ; } ItemImpl item = null ; try { return item = readItem ( getItemData ( path ) , pool ) ; } finally { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "getItem(" + path . getAsString ( ) + ") --> " + ( item != null ? item . getPath ( ) : "null" ) + " <<<<< " + ( ( System . currentTimeMillis ( ) - start ) / 1000d ) + "sec" ) ; } } }
Return item by absolute path in this transient storage then in workspace container .
179
14
15,409
protected ItemImpl readItem ( ItemData itemData , boolean pool ) throws RepositoryException { return readItem ( itemData , null , pool , true ) ; }
Read ItemImpl of given ItemData . Will call postRead Action and check permissions .
34
17
15,410
protected ItemImpl readItem ( ItemData itemData , NodeData parent , boolean pool , boolean apiRead ) throws RepositoryException { if ( ! apiRead ) { // Need privileges SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( JCRRuntimePermissions . INVOKE_INTERNAL_API_PERMISSION ) ; } } if ( itemData != null ) { ItemImpl item ; ItemImpl pooledItem ; if ( pool && ( pooledItem = itemsPool . get ( itemData , parent ) ) != null ) { // use pooled & reloaded item = pooledItem ; } else { // create new item = itemFactory . createItem ( itemData , parent ) ; } if ( apiRead ) { if ( ! item . hasPermission ( PermissionType . READ ) ) { throw new AccessDeniedException ( "Access denied " + itemData . getQPath ( ) . getAsString ( ) + " for " + session . getUserID ( ) ) ; } session . getActionHandler ( ) . postRead ( item ) ; } return item ; } else { return null ; } }
Create or reload pooled ItemImpl with the given ItemData .
247
12
15,411
public ItemImpl getItemByIdentifier ( String identifier , boolean pool ) throws RepositoryException { return getItemByIdentifier ( identifier , pool , true ) ; }
Return item by identifier in this transient storage then in workspace container .
35
13
15,412
public ItemImpl getItemByIdentifier ( String identifier , boolean pool , boolean apiRead ) throws RepositoryException { long start = 0 ; if ( LOG . isDebugEnabled ( ) ) { start = System . currentTimeMillis ( ) ; LOG . debug ( "getItemByIdentifier(" + identifier + " ) >>>>>" ) ; } ItemImpl item = null ; try { return item = readItem ( getItemData ( identifier ) , null , pool , apiRead ) ; } finally { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "getItemByIdentifier(" + identifier + ") --> " + ( item != null ? item . getPath ( ) : "null" ) + " <<<<< " + ( ( System . currentTimeMillis ( ) - start ) / 1000d ) + "sec" ) ; } } }
For internal use required privileges . Return item by identifier in this transient storage then in workspace container .
184
19
15,413
public AccessControlList getACL ( QPath path ) throws RepositoryException { long start = 0 ; if ( LOG . isDebugEnabled ( ) ) { start = System . currentTimeMillis ( ) ; LOG . debug ( "getACL(" + path . getAsString ( ) + " ) >>>>>" ) ; } try { NodeData parent = ( NodeData ) getItemData ( Constants . ROOT_UUID ) ; if ( path . equals ( Constants . ROOT_PATH ) ) { return parent . getACL ( ) ; } ItemData item = null ; QPathEntry [ ] relPathEntries = path . getRelPath ( path . getDepth ( ) ) ; for ( int i = 0 ; i < relPathEntries . length ; i ++ ) { if ( i == relPathEntries . length - 1 ) { item = getItemData ( parent , relPathEntries [ i ] , ItemType . NODE ) ; } else { item = getItemData ( parent , relPathEntries [ i ] , ItemType . UNKNOWN ) ; } if ( item == null ) { break ; } if ( item . isNode ( ) ) { parent = ( NodeData ) item ; } else if ( i < relPathEntries . length - 1 ) { throw new IllegalPathException ( "Get ACL. Path can not contains a property as the intermediate element" ) ; } } if ( item != null && item . isNode ( ) ) { // node ACL return ( ( NodeData ) item ) . getACL ( ) ; } else { // item not found or it's a property - return parent ACL return parent . getACL ( ) ; } } finally { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "getACL(" + path . getAsString ( ) + ") <<<<< " + ( ( System . currentTimeMillis ( ) - start ) / 1000d ) + "sec" ) ; } } }
Return the ACL of the location . A session pending changes will be searched too . Item path will be traversed from the root node to a last existing item .
426
32
15,414
protected List < ItemState > reindexSameNameSiblings ( NodeData cause , ItemDataConsumer dataManager ) throws RepositoryException { List < ItemState > changes = new ArrayList < ItemState > ( ) ; NodeData parentNodeData = ( NodeData ) dataManager . getItemData ( cause . getParentIdentifier ( ) ) ; NodeData nextSibling = ( NodeData ) dataManager . getItemData ( parentNodeData , new QPathEntry ( cause . getQPath ( ) . getName ( ) , cause . getQPath ( ) . getIndex ( ) + 1 ) , ItemType . NODE ) ; String reindexedId = null ; // repeat till next sibling exists and it's not a caused Node (deleted or moved to) or just // reindexed while ( nextSibling != null && ! nextSibling . getIdentifier ( ) . equals ( cause . getIdentifier ( ) ) && ! nextSibling . getIdentifier ( ) . equals ( reindexedId ) ) { QPath siblingOldPath = QPath . makeChildPath ( nextSibling . getQPath ( ) . makeParentPath ( ) , nextSibling . getQPath ( ) . getName ( ) , nextSibling . getQPath ( ) . getIndex ( ) ) ; // update with new index QPath siblingPath = QPath . makeChildPath ( nextSibling . getQPath ( ) . makeParentPath ( ) , nextSibling . getQPath ( ) . getName ( ) , nextSibling . getQPath ( ) . getIndex ( ) - 1 ) ; NodeData reindexed = new TransientNodeData ( siblingPath , nextSibling . getIdentifier ( ) , nextSibling . getPersistedVersion ( ) , nextSibling . getPrimaryTypeName ( ) , nextSibling . getMixinTypeNames ( ) , nextSibling . getOrderNumber ( ) , nextSibling . getParentIdentifier ( ) , nextSibling . getACL ( ) ) ; reindexedId = reindexed . getIdentifier ( ) ; ItemState reindexedState = ItemState . createUpdatedState ( reindexed ) ; changes . add ( reindexedState ) ; itemsPool . reload ( reindexed ) ; reloadDescendants ( siblingOldPath , siblingPath ) ; // next... nextSibling = ( NodeData ) dataManager . getItemData ( parentNodeData , new QPathEntry ( nextSibling . getQPath ( ) . getName ( ) , nextSibling . getQPath ( ) . getIndex ( ) + 1 ) , ItemType . NODE ) ; } return changes ; }
Reindex same - name siblings of the node Reindex is actual for remove move only . If node is added then its index always is a last in list of childs .
573
35
15,415
public List < PropertyData > getReferencesData ( String identifier , boolean skipVersionStorage ) throws RepositoryException { List < PropertyData > persisted = transactionableManager . getReferencesData ( identifier , skipVersionStorage ) ; List < PropertyData > sessionTransient = new ArrayList < PropertyData > ( ) ; for ( PropertyData p : persisted ) { sessionTransient . add ( p ) ; } return sessionTransient ; }
Returns all REFERENCE properties that refer to this node .
89
12
15,416
private void validate ( QPath path ) throws RepositoryException , AccessDeniedException , ReferentialIntegrityException { List < ItemState > changes = changesLog . getAllStates ( ) ; for ( ItemState itemState : changes ) { if ( itemState . isInternallyCreated ( ) ) { // skip internally created if ( itemState . isMixinChanged ( ) ) { // ...except of check of ACL correct size for internally created // items. // If no permissions in the list throw exception. if ( itemState . isDescendantOf ( path ) ) { if ( ( ( NodeData ) itemState . getData ( ) ) . getACL ( ) . getPermissionsSize ( ) < 1 ) { throw new RepositoryException ( "Node " + itemState . getData ( ) . getQPath ( ) . getAsString ( ) + " has wrong formed ACL." ) ; } } validateMandatoryItem ( itemState ) ; } } else { if ( itemState . isDescendantOf ( path ) ) { validateAccessPermissions ( itemState ) ; validateMandatoryItem ( itemState ) ; } if ( path . isDescendantOf ( itemState . getAncestorToSave ( ) ) ) { throw new ConstraintViolationException ( path . getAsString ( ) + " is the same or descendant of either Session.move()'s destination or source node only " + path . getAsString ( ) ) ; } } } }
Validate all user created changes saves like access permeations mandatory items value constraint .
311
16
15,417
private void validateAccessPermissions ( ItemState changedItem ) throws RepositoryException , AccessDeniedException { if ( changedItem . isAddedAutoCreatedNodes ( ) ) { validateAddNodePermission ( changedItem ) ; } else if ( changedItem . isDeleted ( ) ) { validateRemoveAccessPermission ( changedItem ) ; } else if ( changedItem . isMixinChanged ( ) ) { validateMixinChangedPermission ( changedItem ) ; } else { NodeData parent = ( NodeData ) getItemData ( changedItem . getData ( ) . getParentIdentifier ( ) ) ; if ( parent != null ) { if ( changedItem . getData ( ) . isNode ( ) ) { // add node if ( changedItem . isAdded ( ) ) { if ( ! accessManager . hasPermission ( parent . getACL ( ) , new String [ ] { PermissionType . ADD_NODE } , session . getUserState ( ) . getIdentity ( ) ) ) { throw new AccessDeniedException ( "Access denied: ADD_NODE " + changedItem . getData ( ) . getQPath ( ) . getAsString ( ) + " for: " + session . getUserID ( ) + " item owner " + parent . getACL ( ) . getOwner ( ) ) ; } } } else if ( changedItem . isAdded ( ) || changedItem . isUpdated ( ) ) { // add or update property if ( ! accessManager . hasPermission ( parent . getACL ( ) , new String [ ] { PermissionType . SET_PROPERTY } , session . getUserState ( ) . getIdentity ( ) ) ) { throw new AccessDeniedException ( "Access denied: SET_PROPERTY " + changedItem . getData ( ) . getQPath ( ) . getAsString ( ) + " for: " + session . getUserID ( ) + " item owner " + parent . getACL ( ) . getOwner ( ) ) ; } } } // else - parent not found, deleted in this session or from another } }
Validate ItemState for access permeations
450
8
15,418
private void validateMandatoryItem ( ItemState changedItem ) throws ConstraintViolationException , AccessDeniedException { if ( changedItem . getData ( ) . isNode ( ) && ( changedItem . isAdded ( ) || changedItem . isMixinChanged ( ) ) && ! changesLog . getItemState ( changedItem . getData ( ) . getQPath ( ) ) . isDeleted ( ) ) { // Node not in delete state. It might be a wrong if ( ! changesLog . getItemState ( changedItem . getData ( ) . getIdentifier ( ) ) . isDeleted ( ) ) { NodeData nData = ( NodeData ) changedItem . getData ( ) ; try { validateMandatoryChildren ( nData ) ; } catch ( ConstraintViolationException e ) { throw e ; } catch ( AccessDeniedException e ) { throw e ; } catch ( RepositoryException e ) { LOG . warn ( "Unexpected exception. Probable wrong data. Exception message:" + e . getLocalizedMessage ( ) ) ; } } } }
Validate ItemState which represents the add node for it s all mandatory items
231
15
15,419
void rollback ( ItemData item ) throws InvalidItemStateException , RepositoryException { // remove from changes log (Session pending changes) PlainChangesLog slog = changesLog . pushLog ( item . getQPath ( ) ) ; SessionChangesLog changes = new SessionChangesLog ( slog . getAllStates ( ) , session ) ; for ( Iterator < ItemImpl > removedIter = invalidated . iterator ( ) ; removedIter . hasNext ( ) ; ) { ItemImpl removed = removedIter . next ( ) ; QPath removedPath = removed . getLocation ( ) . getInternalPath ( ) ; ItemState rstate = changes . getItemState ( removedPath ) ; if ( rstate != null ) { if ( rstate . isRenamed ( ) || rstate . isPathChanged ( ) ) { // find DELETED rstate = changes . findItemState ( rstate . getData ( ) . getIdentifier ( ) , false , new int [ ] { ItemState . DELETED } ) ; if ( rstate == null ) { continue ; } } NodeData parent = ( NodeData ) transactionableManager . getItemData ( rstate . getData ( ) . getParentIdentifier ( ) ) ; if ( parent != null ) { ItemData persisted = transactionableManager . getItemData ( parent , rstate . getData ( ) . getQPath ( ) . getEntries ( ) [ rstate . getData ( ) . getQPath ( ) . getEntries ( ) . length - 1 ] , ItemType . getItemType ( rstate . getData ( ) ) ) ; if ( persisted != null ) { // reload item data removed . loadData ( persisted ) ; } } // else it's transient item } else if ( removed . getData ( ) != null ) { // No states for items left usecase ItemData persisted = transactionableManager . getItemData ( removed . getData ( ) . getIdentifier ( ) ) ; if ( persisted != null ) { // reload item data removed . loadData ( persisted ) ; } } removedIter . remove ( ) ; } }
Removes all pending changes of this item
446
8
15,420
protected List < ? extends ItemData > mergeList ( ItemData rootData , DataManager dataManager , boolean deep , int action ) throws RepositoryException { // 1 get all transient descendants List < ItemState > transientDescendants = new ArrayList < ItemState > ( ) ; traverseTransientDescendants ( rootData , action , transientDescendants ) ; if ( deep || ! transientDescendants . isEmpty ( ) ) { // 2 get ALL persisted descendants Map < String , ItemData > descendants = new LinkedHashMap < String , ItemData > ( ) ; traverseStoredDescendants ( rootData , dataManager , action , descendants , true , transientDescendants ) ; // merge data for ( ItemState state : transientDescendants ) { ItemData data = state . getData ( ) ; if ( ! state . isDeleted ( ) ) { descendants . put ( data . getIdentifier ( ) , data ) ; } else { descendants . remove ( data . getIdentifier ( ) ) ; } } Collection < ItemData > desc = descendants . values ( ) ; List < ItemData > retval ; if ( deep ) { int size = desc . size ( ) ; retval = new ArrayList < ItemData > ( size < 10 ? 10 : size ) ; for ( ItemData itemData : desc ) { retval . add ( itemData ) ; if ( deep && itemData . isNode ( ) ) { retval . addAll ( mergeList ( itemData , dataManager , true , action ) ) ; } } } else { retval = new ArrayList < ItemData > ( desc ) ; } return retval ; } else { return getStoredDescendants ( rootData , dataManager , action ) ; } }
Merge a list of nodes and properties of root data . NOTE . Properties in the list will have empty value data . I . e . for operations not changes properties content . USED FOR DELETE .
363
42
15,421
private void traverseStoredDescendants ( ItemData parent , DataManager dataManager , int action , Map < String , ItemData > ret , boolean listOnly , Collection < ItemState > transientDescendants ) throws RepositoryException { if ( parent . isNode ( ) && ! isNew ( parent . getIdentifier ( ) ) ) { if ( action != MERGE_PROPS ) { List < NodeData > childNodes = dataManager . getChildNodesData ( ( NodeData ) parent ) ; for ( int i = 0 , length = childNodes . size ( ) ; i < length ; i ++ ) { NodeData childNode = childNodes . get ( i ) ; ret . put ( childNode . getIdentifier ( ) , childNode ) ; } } if ( action != MERGE_NODES ) { List < PropertyData > childProps = listOnly ? dataManager . listChildPropertiesData ( ( NodeData ) parent ) : dataManager . getChildPropertiesData ( ( NodeData ) parent ) ; outer : for ( int i = 0 , length = childProps . size ( ) ; i < length ; i ++ ) { PropertyData childProp = childProps . get ( i ) ; for ( ItemState transientState : transientDescendants ) { if ( ! transientState . isNode ( ) && ! transientState . isDeleted ( ) && transientState . getData ( ) . getQPath ( ) . getDepth ( ) == childProp . getQPath ( ) . getDepth ( ) && transientState . getData ( ) . getQPath ( ) . getName ( ) . equals ( childProp . getQPath ( ) . getName ( ) ) ) { continue outer ; } } if ( ! childProp . getQPath ( ) . isDescendantOf ( parent . getQPath ( ) , true ) ) { // In case we get the data from the cache, we need to set the correct path QPath qpath = QPath . makeChildPath ( parent . getQPath ( ) , childProp . getQPath ( ) . getName ( ) ) ; childProp = new PersistedPropertyData ( childProp . getIdentifier ( ) , qpath , childProp . getParentIdentifier ( ) , childProp . getPersistedVersion ( ) , childProp . getType ( ) , childProp . isMultiValued ( ) , childProp . getValues ( ) , new SimplePersistedSize ( ( ( PersistedPropertyData ) childProp ) . getPersistedSize ( ) ) ) ; } ret . put ( childProp . getIdentifier ( ) , childProp ) ; } } } }
Calculate all stored descendants for the given parent node
566
11
15,422
private List < ? extends ItemData > getStoredDescendants ( ItemData parent , DataManager dataManager , int action ) throws RepositoryException { if ( parent . isNode ( ) ) { List < ItemData > childItems = null ; List < NodeData > childNodes = dataManager . getChildNodesData ( ( NodeData ) parent ) ; if ( action != MERGE_NODES ) { childItems = new ArrayList < ItemData > ( childNodes ) ; } else { return childNodes ; } List < PropertyData > childProps = dataManager . getChildPropertiesData ( ( NodeData ) parent ) ; if ( action != MERGE_PROPS ) { childItems . addAll ( childProps ) ; } else { return childProps ; } return childItems ; } return null ; }
Get all stored descendants for the given parent node
178
9
15,423
private void traverseTransientDescendants ( ItemData parent , int action , List < ItemState > ret ) throws RepositoryException { if ( parent . isNode ( ) ) { if ( action != MERGE_PROPS ) { Collection < ItemState > childNodes = changesLog . getLastChildrenStates ( parent , true ) ; for ( ItemState childNode : childNodes ) { ret . add ( childNode ) ; } } if ( action != MERGE_NODES ) { Collection < ItemState > childProps = changesLog . getLastChildrenStates ( parent , false ) ; for ( ItemState childProp : childProps ) { ret . add ( childProp ) ; } } } }
Calculate all transient descendants for the given parent node
150
11
15,424
private void reloadDescendants ( QPath parentOld , QPath parent ) throws RepositoryException { List < ItemImpl > items = itemsPool . getDescendats ( parentOld ) ; for ( ItemImpl item : items ) { ItemData oldItemData = item . getData ( ) ; ItemData newItemData = updatePath ( parentOld , parent , oldItemData ) ; ItemImpl reloadedItem = reloadItem ( newItemData ) ; if ( reloadedItem != null ) { invalidated . add ( reloadedItem ) ; } } }
Reload item s descendants in item reference pool
116
9
15,425
private ItemData updatePathIfNeeded ( ItemData data ) throws IllegalPathException { if ( data == null || changesLog . getAllPathsChanged ( ) == null ) return data ; List < ItemState > states = changesLog . getAllPathsChanged ( ) ; for ( int i = 0 , length = states . size ( ) ; i < length ; i ++ ) { ItemState state = states . get ( i ) ; if ( data . getQPath ( ) . isDescendantOf ( state . getOldPath ( ) ) ) { data = updatePath ( state . getOldPath ( ) , state . getData ( ) . getQPath ( ) , data ) ; } } return data ; }
Updates the path if needed and gives the updated item data if an update was needed or the provided item data otherwise
152
23
15,426
private ItemData updatePath ( QPath parentOld , QPath parent , ItemData oldItemData ) throws IllegalPathException { int relativeDegree = oldItemData . getQPath ( ) . getDepth ( ) - parentOld . getDepth ( ) ; QPath newQPath = QPath . makeChildPath ( parent , oldItemData . getQPath ( ) . getRelPath ( relativeDegree ) ) ; ItemData newItemData ; if ( oldItemData . isNode ( ) ) { NodeData oldNodeData = ( NodeData ) oldItemData ; newItemData = new TransientNodeData ( newQPath , oldNodeData . getIdentifier ( ) , oldNodeData . getPersistedVersion ( ) , oldNodeData . getPrimaryTypeName ( ) , oldNodeData . getMixinTypeNames ( ) , oldNodeData . getOrderNumber ( ) , oldNodeData . getParentIdentifier ( ) , oldNodeData . getACL ( ) ) ; } else { PropertyData oldPropertyData = ( PropertyData ) oldItemData ; newItemData = new TransientPropertyData ( newQPath , oldPropertyData . getIdentifier ( ) , oldPropertyData . getPersistedVersion ( ) , oldPropertyData . getType ( ) , oldPropertyData . getParentIdentifier ( ) , oldPropertyData . isMultiValued ( ) , oldPropertyData . getValues ( ) ) ; } return newItemData ; }
Updates the path of the item data and gives the updated objects
313
13
15,427
private static Statistics getStatistics ( Class < ? > target , String signature ) { initIfNeeded ( ) ; Statistics statistics = MAPPING . get ( signature ) ; if ( statistics == null ) { synchronized ( JCRAPIAspect . class ) { Class < ? > interfaceClass = findInterface ( target ) ; if ( interfaceClass != null ) { Map < String , Statistics > allStatistics = ALL_STATISTICS . get ( interfaceClass . getSimpleName ( ) ) ; if ( allStatistics != null ) { int index1 = signature . indexOf ( ' ' ) ; int index = signature . substring ( 0 , index1 ) . lastIndexOf ( ' ' ) ; String name = signature . substring ( index + 1 ) ; statistics = allStatistics . get ( name ) ; } } if ( statistics == null ) { statistics = UNKNOWN ; } Map < String , Statistics > tempMapping = new HashMap < String , Statistics > ( MAPPING ) ; tempMapping . put ( signature , statistics ) ; MAPPING = Collections . unmodifiableMap ( tempMapping ) ; } } if ( statistics == UNKNOWN ) // NOSONAR { return null ; } return statistics ; }
Gives the corresponding statistics for the given target class and AspectJ signature
256
15
15,428
private static void initIfNeeded ( ) { if ( ! INITIALIZED ) { synchronized ( JCRAPIAspect . class ) { if ( ! INITIALIZED ) { ExoContainer container = ExoContainerContext . getTopContainer ( ) ; JCRAPIAspectConfig config = null ; if ( container != null ) { config = ( JCRAPIAspectConfig ) container . getComponentInstanceOfType ( JCRAPIAspectConfig . class ) ; } if ( config == null ) { TARGET_INTERFACES = new Class < ? > [ ] { } ; LOG . warn ( "No interface to monitor could be found" ) ; } else { TARGET_INTERFACES = config . getTargetInterfaces ( ) ; for ( Class < ? > c : TARGET_INTERFACES ) { Statistics global = new Statistics ( null , "global" ) ; Map < String , Statistics > statistics = new TreeMap < String , Statistics > ( ) ; Method [ ] methods = c . getMethods ( ) ; for ( Method m : methods ) { String name = getStatisticsName ( m ) ; statistics . put ( name , new Statistics ( global , name ) ) ; } JCRStatisticsManager . registerStatistics ( c . getSimpleName ( ) , global , statistics ) ; ALL_STATISTICS . put ( c . getSimpleName ( ) , statistics ) ; } } INITIALIZED = true ; } } } }
Initializes the aspect if needed
312
6
15,429
public static DBCleaningScripts prepareScripts ( String dialect , WorkspaceEntry wsEntry ) throws DBCleanException { if ( dialect . startsWith ( DialectConstants . DB_DIALECT_MYSQL ) ) { return new MySQLCleaningScipts ( dialect , wsEntry ) ; } else if ( dialect . startsWith ( DialectConstants . DB_DIALECT_DB2 ) ) { return new DB2CleaningScipts ( dialect , wsEntry ) ; } else if ( dialect . startsWith ( DialectConstants . DB_DIALECT_MSSQL ) ) { return new MSSQLCleaningScipts ( dialect , wsEntry ) ; } else if ( dialect . startsWith ( DialectConstants . DB_DIALECT_PGSQL ) ) { return new PgSQLCleaningScipts ( dialect , wsEntry ) ; } else if ( dialect . startsWith ( DialectConstants . DB_DIALECT_SYBASE ) ) { return new SybaseCleaningScipts ( dialect , wsEntry ) ; } else if ( dialect . startsWith ( DialectConstants . DB_DIALECT_HSQLDB ) ) { return new HSQLDBCleaningScipts ( dialect , wsEntry ) ; } else if ( dialect . startsWith ( DialectConstants . DB_DIALECT_H2 ) ) { return new H2CleaningScipts ( dialect , wsEntry ) ; } else if ( dialect . startsWith ( DialectConstants . DB_DIALECT_ORACLE ) ) { return new OracleCleaningScipts ( dialect , wsEntry ) ; } else { throw new DBCleanException ( "Unsupported dialect " + dialect ) ; } }
Prepare SQL scripts for cleaning workspace data from database .
399
11
15,430
private void triggerRSyncSynchronization ( ) { // Call RSync to retrieve actual index from coordinator if ( modeHandler . getMode ( ) == IndexerIoMode . READ_ONLY ) { EmbeddedCacheManager cacheManager = cache . getCacheManager ( ) ; if ( cacheManager . getCoordinator ( ) instanceof JGroupsAddress && cacheManager . getTransport ( ) instanceof JGroupsTransport ) { JGroupsTransport transport = ( JGroupsTransport ) cacheManager . getTransport ( ) ; // Coordinator's address org . jgroups . Address jgAddress = ( ( JGroupsAddress ) cacheManager . getCoordinator ( ) ) . getJGroupsAddress ( ) ; // if jgAddress is UUID address, not the physical one, then retrieve via channel if ( ! ( jgAddress instanceof IpAddress ) ) { // this is the only way of getting physical address. Channel channel = transport . getChannel ( ) ; jgAddress = ( org . jgroups . Address ) channel . down ( new Event ( Event . GET_PHYSICAL_ADDRESS , jgAddress ) ) ; } if ( jgAddress instanceof IpAddress ) { String address = ( ( IpAddress ) jgAddress ) . getIpAddress ( ) . getHostAddress ( ) ; RSyncJob rSyncJob = new RSyncJob ( String . format ( urlFormatString , address ) , indexPath , rsyncUserName , rsyncPassword ) ; try { // synchronizing access to RSync Job. // No parallel jobs allowed synchronized ( this ) { rSyncJob . execute ( ) ; } } catch ( IOException e ) { LOG . error ( "Failed to retrieve index using RSYNC" , e ) ; } } else { LOG . error ( "Error triggering RSync synchronization, skipped. Unsupported Address object : " + jgAddress . getClass ( ) . getName ( ) ) ; } } else { LOG . error ( "Error triggering RSync synchronization, skipped. Unsupported Address object : " + cacheManager . getCoordinator ( ) . getClass ( ) . getName ( ) ) ; } } }
Call to system RSync binary implementation
468
7
15,431
public static SessionProvider createAnonimProvider ( ) { Identity id = new Identity ( IdentityConstants . ANONIM , new HashSet < MembershipEntry > ( ) ) ; return new SessionProvider ( new ConversationState ( id ) ) ; }
Helper for creating Anonymous session provider .
51
7
15,432
public synchronized Session getSession ( String workspaceName , ManageableRepository repository ) throws LoginException , NoSuchWorkspaceException , RepositoryException { if ( closed ) { throw new IllegalStateException ( "Session provider already closed" ) ; } if ( workspaceName == null ) { throw new IllegalArgumentException ( "Workspace Name is null" ) ; } ExtendedSession session = cache . get ( key ( repository , workspaceName ) ) ; // create and cache new session if ( session == null ) { if ( conversationState != null ) { session = ( ExtendedSession ) repository . getDynamicSession ( workspaceName , conversationState . getIdentity ( ) . getMemberships ( ) ) ; } else if ( ! isSystem ) { session = ( ExtendedSession ) repository . login ( workspaceName ) ; } else { session = ( ExtendedSession ) repository . getSystemSession ( workspaceName ) ; } session . registerLifecycleListener ( this ) ; cache . put ( key ( repository , workspaceName ) , session ) ; } return session ; }
Gets the session from an internal cache if a similar session has already been used or creates a new session and puts it into the internal cache .
219
29
15,433
private String key ( ManageableRepository repository , String workspaceName ) { String repositoryName = repository . getConfiguration ( ) . getName ( ) ; return repositoryName + workspaceName ; }
Key generator for sessions cache .
40
6
15,434
public static String extractCommonAncestor ( String pattern , String absPath ) { pattern = normalizePath ( pattern ) ; absPath = normalizePath ( absPath ) ; String [ ] patterEntries = pattern . split ( "/" ) ; String [ ] pathEntries = absPath . split ( "/" ) ; StringBuilder ancestor = new StringBuilder ( ) ; int count = Math . min ( pathEntries . length , patterEntries . length ) ; for ( int i = 1 ; i < count ; i ++ ) { if ( acceptName ( patterEntries [ i ] , pathEntries [ i ] ) ) { ancestor . append ( "/" ) ; ancestor . append ( pathEntries [ i ] ) ; } else { break ; } } return ancestor . length ( ) == 0 ? JCRPath . ROOT_PATH : ancestor . toString ( ) ; }
Returns common ancestor for paths represented by absolute path and pattern .
190
12
15,435
protected void doUpdateIndex ( Set < String > removedNodes , Set < String > addedNodes , Set < String > parentRemovedNodes , Set < String > parentAddedNodes ) { ChangesHolder changes = searchManager . getChanges ( removedNodes , addedNodes ) ; ChangesHolder parentChanges = parentSearchManager . getChanges ( parentRemovedNodes , parentAddedNodes ) ; if ( changes == null && parentChanges == null ) { return ; } try { doUpdateIndex ( new ChangesFilterListsWrapper ( changes , parentChanges ) ) ; } catch ( RuntimeException e ) { if ( isTXAware ( ) ) { // The indexing is part of the global tx so the error needs to be thrown to // allow to roll back other resources throw e ; } getLogger ( ) . error ( e . getLocalizedMessage ( ) , e ) ; logErrorChanges ( handler , removedNodes , addedNodes ) ; logErrorChanges ( parentHandler , parentRemovedNodes , parentAddedNodes ) ; } }
Update index .
223
3
15,436
private int forceCloseSession ( String repositoryName , String workspaceName ) throws RepositoryException , RepositoryConfigurationException { ManageableRepository mr = repositoryService . getRepository ( repositoryName ) ; WorkspaceContainerFacade wc = mr . getWorkspaceContainer ( workspaceName ) ; SessionRegistry sessionRegistry = ( SessionRegistry ) wc . getComponent ( SessionRegistry . class ) ; return sessionRegistry . closeSessions ( workspaceName ) ; }
Close sessions on specific workspace .
102
6
15,437
public List < String > readList ( ) throws IOException { InputStream in = PrivilegedFileHelper . fileInputStream ( logFile ) ; try { List < String > list = new ArrayList < String > ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( ! line . matches ( "\\x00++" ) ) { list . add ( line ) ; } } return list ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { LOG . warn ( "Exception while closing error log: " + e . toString ( ) ) ; } } } }
Reads the log file .
164
6
15,438
public void addJobEntry ( BackupJob job ) { // jobEntries try { JobEntryInfo info = new JobEntryInfo ( ) ; info . setDate ( Calendar . getInstance ( ) ) ; info . setType ( job . getType ( ) ) ; info . setState ( job . getState ( ) ) ; info . setURL ( job . getStorageURL ( ) ) ; logWriter . write ( info , config ) ; } catch ( IOException e ) { logger . error ( "Can't add job" , e ) ; } catch ( XMLStreamException e ) { logger . error ( "Can't add job" , e ) ; } catch ( BackupOperationException e ) { logger . error ( "Can't add job" , e ) ; } }
Adding the the backup job .
162
6
15,439
public Collection < JobEntryInfo > getJobEntryStates ( ) { HashMap < Integer , JobEntryInfo > infos = new HashMap < Integer , JobEntryInfo > ( ) ; for ( JobEntryInfo jobEntry : jobEntries ) { infos . put ( jobEntry . getID ( ) , jobEntry ) ; } return infos . values ( ) ; }
Getting the states for jobs .
79
6
15,440
public Response mkCol ( Session session , String path , String nodeType , List < String > mixinTypes , List < String > tokens ) { Node node ; try { nullResourceLocks . checkLock ( session , path , tokens ) ; node = session . getRootNode ( ) . addNode ( TextUtil . relativizePath ( path ) , nodeType ) ; // We set the new path path = node . getPath ( ) ; if ( mixinTypes != null ) { addMixins ( node , mixinTypes ) ; } session . save ( ) ; } catch ( ItemExistsException exc ) { return Response . status ( HTTPStatus . METHOD_NOT_ALLOWED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . CONFLICT ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( AccessDeniedException exc ) { return Response . status ( HTTPStatus . FORBIDDEN ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( LockException exc ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( RepositoryException exc ) { log . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } if ( uriBuilder != null ) { return Response . created ( uriBuilder . path ( session . getWorkspace ( ) . getName ( ) ) . path ( path ) . build ( ) ) . build ( ) ; } // to save compatibility if uriBuilder is not provided return Response . status ( HTTPStatus . CREATED ) . build ( ) ; }
Webdav Mkcol method implementation .
396
8
15,441
private void addMixins ( Node node , List < String > mixinTypes ) { for ( int i = 0 ; i < mixinTypes . size ( ) ; i ++ ) { String curMixinType = mixinTypes . get ( i ) ; try { node . addMixin ( curMixinType ) ; } catch ( Exception exc ) { log . error ( "Can't add mixin [" + curMixinType + "]" , exc ) ; } } }
Adds mixins to node .
101
6
15,442
public Response unLock ( Session session , String path , List < String > tokens ) { try { try { Node node = ( Node ) session . getItem ( path ) ; if ( node . isLocked ( ) ) { node . unlock ( ) ; session . save ( ) ; } return Response . status ( HTTPStatus . NO_CONTENT ) . build ( ) ; } catch ( PathNotFoundException exc ) { if ( nullResourceLocks . isLocked ( session , path ) ) { nullResourceLocks . checkLock ( session , path , tokens ) ; nullResourceLocks . removeLock ( session , path ) ; return Response . status ( HTTPStatus . NO_CONTENT ) . build ( ) ; } return Response . status ( HTTPStatus . NOT_FOUND ) . entity ( exc . getMessage ( ) ) . build ( ) ; } } catch ( LockException exc ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { log . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav Unlock method implementation .
261
7
15,443
public static HierarchicalProperty lockDiscovery ( String token , String lockOwner , String timeOut ) { HierarchicalProperty lockDiscovery = new HierarchicalProperty ( new QName ( "DAV:" , "lockdiscovery" ) ) ; HierarchicalProperty activeLock = lockDiscovery . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "activelock" ) ) ) ; HierarchicalProperty lockType = activeLock . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "locktype" ) ) ) ; lockType . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "write" ) ) ) ; HierarchicalProperty lockScope = activeLock . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "lockscope" ) ) ) ; lockScope . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "exclusive" ) ) ) ; HierarchicalProperty depth = activeLock . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "depth" ) ) ) ; depth . setValue ( "Infinity" ) ; if ( lockOwner != null ) { HierarchicalProperty owner = activeLock . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "owner" ) ) ) ; owner . setValue ( lockOwner ) ; } HierarchicalProperty timeout = activeLock . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "timeout" ) ) ) ; timeout . setValue ( "Second-" + timeOut ) ; if ( token != null ) { HierarchicalProperty lockToken = activeLock . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "locktoken" ) ) ) ; HierarchicalProperty lockHref = lockToken . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "href" ) ) ) ; lockHref . setValue ( token ) ; } return lockDiscovery ; }
Returns the information about lock .
459
6
15,444
protected HierarchicalProperty supportedLock ( ) { HierarchicalProperty supportedLock = new HierarchicalProperty ( new QName ( "DAV:" , "supportedlock" ) ) ; HierarchicalProperty lockEntry = new HierarchicalProperty ( new QName ( "DAV:" , "lockentry" ) ) ; supportedLock . addChild ( lockEntry ) ; HierarchicalProperty lockScope = new HierarchicalProperty ( new QName ( "DAV:" , "lockscope" ) ) ; lockScope . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "exclusive" ) ) ) ; lockEntry . addChild ( lockScope ) ; HierarchicalProperty lockType = new HierarchicalProperty ( new QName ( "DAV:" , "locktype" ) ) ; lockType . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "write" ) ) ) ; lockEntry . addChild ( lockType ) ; return supportedLock ; }
The information about supported locks .
218
6
15,445
protected HierarchicalProperty supportedMethodSet ( ) { HierarchicalProperty supportedMethodProp = new HierarchicalProperty ( SUPPORTEDMETHODSET ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "PROPFIND" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "OPTIONS" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "DELETE" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "PROPPATCH" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "CHECKIN" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "CHECKOUT" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "REPORT" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "UNCHECKOUT" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "PUT" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "GET" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "HEAD" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "COPY" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "MOVE" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "VERSION-CONTROL" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "LABEL" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "LOCK" ) ; supportedMethodProp . addChild ( new HierarchicalProperty ( new QName ( "DAV:" , "supported-method" ) ) ) . setAttribute ( "name" , "UNLOCK" ) ; return supportedMethodProp ; }
The information about supported methods .
792
6
15,446
private void updateVersion ( Node fileNode , InputStream inputStream , String autoVersion , List < String > mixins ) throws RepositoryException { if ( ! fileNode . isCheckedOut ( ) ) { fileNode . checkout ( ) ; fileNode . getSession ( ) . save ( ) ; } if ( CHECKOUT . equals ( autoVersion ) ) { updateContent ( fileNode , inputStream , mixins ) ; } else if ( CHECKOUT_CHECKIN . equals ( autoVersion ) ) { updateContent ( fileNode , inputStream , mixins ) ; fileNode . getSession ( ) . save ( ) ; fileNode . checkin ( ) ; } fileNode . getSession ( ) . save ( ) ; }
Updates the content of the versionable file according to auto - version value .
155
16
15,447
void put ( String uuid , CachingIndexReader reader , int n ) { LRUMap cacheSegment = docNumbers [ getSegmentIndex ( uuid . charAt ( 0 ) ) ] ; //UUID key = UUID.fromString(uuid); String key = uuid ; synchronized ( cacheSegment ) { Entry e = ( Entry ) cacheSegment . get ( key ) ; if ( e != null ) { // existing entry // ignore if reader is older than the one in entry if ( reader . getCreationTick ( ) <= e . creationTick ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Ignoring put(). New entry is not from a newer reader. " + "existing: " + e . creationTick + ", new: " + reader . getCreationTick ( ) ) ; } e = null ; } } else { // entry did not exist e = new Entry ( reader . getCreationTick ( ) , n ) ; } if ( e != null ) { cacheSegment . put ( key , e ) ; } } }
Puts a document number into the cache using a uuid as key . An entry is only overwritten if the according reader is younger than the reader associated with the existing entry .
237
36
15,448
public Value createValue ( JCRName value ) throws RepositoryException { if ( value == null ) return null ; try { return new NameValue ( value . getInternalName ( ) , locationFactory ) ; } catch ( IOException e ) { throw new RepositoryException ( "Cannot create NAME Value from JCRName" , e ) ; } }
Create Value from JCRName .
74
7
15,449
public Value createValue ( JCRPath value ) throws RepositoryException { if ( value == null ) return null ; try { return new PathValue ( value . getInternalPath ( ) , locationFactory ) ; } catch ( IOException e ) { throw new RepositoryException ( "Cannot create PATH Value from JCRPath" , e ) ; } }
Create Value from JCRPath .
74
7
15,450
public Value createValue ( Identifier value ) { if ( value == null ) return null ; try { return new ReferenceValue ( value ) ; } catch ( IOException e ) { LOG . warn ( "Cannot create REFERENCE Value from Identifier " + value , e ) ; return null ; } }
Create Value from Id .
64
5
15,451
public Value loadValue ( ValueData data , int type ) throws RepositoryException { try { switch ( type ) { case PropertyType . STRING : return new StringValue ( data ) ; case PropertyType . BINARY : return new BinaryValue ( data , spoolConfig ) ; case PropertyType . BOOLEAN : return new BooleanValue ( data ) ; case PropertyType . LONG : return new LongValue ( data ) ; case PropertyType . DOUBLE : return new DoubleValue ( data ) ; case PropertyType . DATE : return new DateValue ( data ) ; case PropertyType . PATH : return new PathValue ( data , locationFactory ) ; case PropertyType . NAME : return new NameValue ( data , locationFactory ) ; case PropertyType . REFERENCE : return new ReferenceValue ( data , true ) ; case PropertyType . UNDEFINED : return null ; case ExtendedPropertyType . PERMISSION : return new PermissionValue ( data ) ; default : throw new ValueFormatException ( "unknown type " + type ) ; } } catch ( IOException e ) { throw new RepositoryException ( e ) ; } }
Creates new Value object using ValueData
239
8
15,452
protected Connection openConnection ( ) throws SQLException { return SecurityHelper . doPrivilegedSQLExceptionAction ( new PrivilegedExceptionAction < Connection > ( ) { public Connection run ( ) throws SQLException { return ds . getConnection ( ) ; } } ) ; }
Opens connection to database .
62
6
15,453
public String getUrlParams ( ) { StringBuffer osParams = new StringBuffer ( ) ; for ( Iterator i = this . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) i . next ( ) ; if ( entry . getValue ( ) != null ) osParams . append ( "&" + encodeConfig ( entry . getKey ( ) . toString ( ) ) + "=" + encodeConfig ( entry . getValue ( ) . toString ( ) ) ) ; } return osParams . toString ( ) ; }
Generate the url parameter sequence used to pass this configuration to the editor .
132
15
15,454
public String addLock ( Session session , String path ) throws LockException { String repoPath = session . getRepository ( ) . hashCode ( ) + "/" + session . getWorkspace ( ) . getName ( ) + "/" + path ; if ( ! nullResourceLocks . containsKey ( repoPath ) ) { String newLockToken = IdGenerator . generate ( ) ; session . addLockToken ( newLockToken ) ; nullResourceLocks . put ( repoPath , newLockToken ) ; return newLockToken ; } // check if lock owned by this session String currentToken = nullResourceLocks . get ( repoPath ) ; for ( String t : session . getLockTokens ( ) ) { if ( t . equals ( currentToken ) ) return t ; } throw new LockException ( "Resource already locked " + repoPath ) ; }
Locks the node .
181
5
15,455
public void removeLock ( Session session , String path ) { String repoPath = session . getRepository ( ) . hashCode ( ) + "/" + session . getWorkspace ( ) . getName ( ) + "/" + path ; String token = nullResourceLocks . get ( repoPath ) ; session . removeLockToken ( token ) ; nullResourceLocks . remove ( repoPath ) ; }
Removes lock from the node .
85
7
15,456
public boolean isLocked ( Session session , String path ) { String repoPath = session . getRepository ( ) . hashCode ( ) + "/" + session . getWorkspace ( ) . getName ( ) + "/" + path ; if ( nullResourceLocks . get ( repoPath ) != null ) { return true ; } return false ; }
Checks if the node is locked .
75
8
15,457
public void checkLock ( Session session , String path , List < String > tokens ) throws LockException { String repoPath = session . getRepository ( ) . hashCode ( ) + "/" + session . getWorkspace ( ) . getName ( ) + "/" + path ; String currentToken = nullResourceLocks . get ( repoPath ) ; if ( currentToken == null ) { return ; } if ( tokens != null ) { for ( String token : tokens ) { if ( token . equals ( currentToken ) ) { return ; } } } throw new LockException ( "Resource already locked " + repoPath ) ; }
Checks if the node can be unlocked using current tokens .
132
12
15,458
private Object getObject ( Class cl , byte [ ] data ) throws Exception { JsonHandler jsonHandler = new JsonDefaultHandler ( ) ; JsonParser jsonParser = new JsonParserImpl ( ) ; InputStream inputStream = new ByteArrayInputStream ( data ) ; jsonParser . parse ( inputStream , jsonHandler ) ; JsonValue jsonValue = jsonHandler . getJsonObject ( ) ; return new BeanBuilder ( ) . createObject ( cl , jsonValue ) ; }
Will be created the Object from JSON binary data .
103
10
15,459
public Response propPatch ( Session session , String path , HierarchicalProperty body , List < String > tokens , String baseURI ) { try { lockHolder . checkLock ( session , path , tokens ) ; Node node = ( Node ) session . getItem ( path ) ; WebDavNamespaceContext nsContext = new WebDavNamespaceContext ( session ) ; URI uri = new URI ( TextUtil . escape ( baseURI + node . getPath ( ) , ' ' , true ) ) ; List < HierarchicalProperty > setList = Collections . emptyList ( ) ; if ( body . getChild ( new QName ( "DAV:" , "set" ) ) != null ) { setList = setList ( body ) ; } List < HierarchicalProperty > removeList = Collections . emptyList ( ) ; if ( body . getChild ( new QName ( "DAV:" , "remove" ) ) != null ) { removeList = removeList ( body ) ; } PropPatchResponseEntity entity = new PropPatchResponseEntity ( nsContext , node , uri , setList , removeList ) ; return Response . status ( HTTPStatus . MULTISTATUS ) . entity ( entity ) . type ( MediaType . TEXT_XML ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . NOT_FOUND ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( LockException exc ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { log . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav Proppatch method method implementation .
392
10
15,460
public List < HierarchicalProperty > setList ( HierarchicalProperty request ) { HierarchicalProperty set = request . getChild ( new QName ( "DAV:" , "set" ) ) ; HierarchicalProperty prop = set . getChild ( new QName ( "DAV:" , "prop" ) ) ; List < HierarchicalProperty > setList = prop . getChildren ( ) ; return setList ; }
List of properties to set .
92
6
15,461
public List < HierarchicalProperty > removeList ( HierarchicalProperty request ) { HierarchicalProperty remove = request . getChild ( new QName ( "DAV:" , "remove" ) ) ; HierarchicalProperty prop = remove . getChild ( new QName ( "DAV:" , "prop" ) ) ; List < HierarchicalProperty > removeList = prop . getChildren ( ) ; return removeList ; }
List of properties to remove .
92
6
15,462
public Response orderPatch ( Session session , String path , HierarchicalProperty body , String baseURI ) { try { Node node = ( Node ) session . getItem ( path ) ; List < OrderMember > members = getMembers ( body ) ; WebDavNamespaceContext nsContext = new WebDavNamespaceContext ( session ) ; URI uri = new URI ( TextUtil . escape ( baseURI + node . getPath ( ) , ' ' , true ) ) ; if ( doOrder ( node , members ) ) { return Response . ok ( ) . build ( ) ; } OrderPatchResponseEntity orderPatchEntity = new OrderPatchResponseEntity ( nsContext , uri , node , members ) ; return Response . status ( HTTPStatus . MULTISTATUS ) . entity ( orderPatchEntity ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . NOT_FOUND ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( LockException exc ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav OrderPatch method implementation .
293
8
15,463
protected List < OrderMember > getMembers ( HierarchicalProperty body ) { ArrayList < OrderMember > members = new ArrayList < OrderMember > ( ) ; List < HierarchicalProperty > childs = body . getChildren ( ) ; for ( int i = 0 ; i < childs . size ( ) ; i ++ ) { OrderMember member = new OrderMember ( childs . get ( i ) ) ; members . add ( member ) ; } return members ; }
Get oder members .
100
5
15,464
protected boolean doOrder ( Node parentNode , List < OrderMember > members ) { boolean success = true ; for ( int i = 0 ; i < members . size ( ) ; i ++ ) { OrderMember member = members . get ( i ) ; int status = HTTPStatus . OK ; try { parentNode . getSession ( ) . refresh ( false ) ; String positionedNodeName = null ; if ( ! parentNode . hasNode ( member . getSegment ( ) ) ) { throw new PathNotFoundException ( ) ; } if ( ! new QName ( "DAV:" , "last" ) . equals ( member . getPosition ( ) ) ) { NodeIterator nodeIter = parentNode . getNodes ( ) ; boolean finded = false ; while ( nodeIter . hasNext ( ) ) { Node curNode = nodeIter . nextNode ( ) ; if ( new QName ( "DAV:" , "first" ) . equals ( member . getPosition ( ) ) ) { positionedNodeName = curNode . getName ( ) ; finded = true ; break ; } if ( new QName ( "DAV:" , "before" ) . equals ( member . getPosition ( ) ) && curNode . getName ( ) . equals ( member . getPositionSegment ( ) ) ) { positionedNodeName = curNode . getName ( ) ; finded = true ; break ; } if ( new QName ( "DAV:" , "after" ) . equals ( member . getPosition ( ) ) && curNode . getName ( ) . equals ( member . getPositionSegment ( ) ) ) { if ( nodeIter . hasNext ( ) ) { positionedNodeName = nodeIter . nextNode ( ) . getName ( ) ; } finded = true ; break ; } } if ( ! finded ) { throw new AccessDeniedException ( ) ; } } parentNode . getSession ( ) . refresh ( false ) ; parentNode . orderBefore ( member . getSegment ( ) , positionedNodeName ) ; parentNode . getSession ( ) . save ( ) ; } catch ( LockException exc ) { status = HTTPStatus . LOCKED ; } catch ( PathNotFoundException exc ) { status = HTTPStatus . FORBIDDEN ; } catch ( AccessDeniedException exc ) { status = HTTPStatus . FORBIDDEN ; } catch ( RepositoryException exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; status = HTTPStatus . INTERNAL_ERROR ; } member . setStatus ( status ) ; if ( status != HTTPStatus . OK ) { success = false ; } } return success ; }
Order members .
563
3
15,465
private InputStream spoolInputStream ( ObjectReader in , long contentLen ) throws IOException { byte [ ] buffer = new byte [ 0 ] ; byte [ ] tmpBuff ; long readLen = 0 ; File sf = null ; OutputStream sfout = null ; try { while ( true ) { int needToRead = contentLen - readLen > 2048 ? 2048 : ( int ) ( contentLen - readLen ) ; tmpBuff = new byte [ needToRead ] ; if ( needToRead == 0 ) { break ; } in . readFully ( tmpBuff ) ; if ( sfout != null ) { sfout . write ( tmpBuff ) ; } else if ( readLen + needToRead > maxBufferSize && fileCleaner != null ) { sf = PrivilegedFileHelper . createTempFile ( "jcrvd" , null , tempDir ) ; sfout = PrivilegedFileHelper . fileOutputStream ( sf ) ; sfout . write ( buffer ) ; sfout . write ( tmpBuff ) ; buffer = null ; } else { // reallocate new buffer and spool old buffer contents byte [ ] newBuffer = new byte [ ( int ) ( readLen + needToRead ) ] ; System . arraycopy ( buffer , 0 , newBuffer , 0 , ( int ) readLen ) ; System . arraycopy ( tmpBuff , 0 , newBuffer , ( int ) readLen , needToRead ) ; buffer = newBuffer ; } readLen += needToRead ; } if ( buffer != null ) { return new ByteArrayInputStream ( buffer ) ; } else { return PrivilegedFileHelper . fileInputStream ( sf ) ; } } finally { if ( sfout != null ) { sfout . close ( ) ; } if ( sf != null ) { spoolFileList . add ( sf ) ; } } }
Spool input stream .
402
5
15,466
protected TransientItemData copyItemDataDelete ( final ItemData item ) throws RepositoryException { if ( item == null ) { return null ; } // make a copy if ( item . isNode ( ) ) { final NodeData node = ( NodeData ) item ; // the node ACL can't be are null as ACL manager does care about this final AccessControlList acl = node . getACL ( ) ; if ( acl == null ) { throw new RepositoryException ( "Node ACL is null. " + node . getQPath ( ) . getAsString ( ) + " " + node . getIdentifier ( ) ) ; } return new TransientNodeData ( node . getQPath ( ) , node . getIdentifier ( ) , node . getPersistedVersion ( ) , node . getPrimaryTypeName ( ) , node . getMixinTypeNames ( ) , node . getOrderNumber ( ) , node . getParentIdentifier ( ) , acl ) ; } // else - property final PropertyData prop = ( PropertyData ) item ; // make a copy, value wil be null for deleting items TransientPropertyData newData = new TransientPropertyData ( prop . getQPath ( ) , prop . getIdentifier ( ) , prop . getPersistedVersion ( ) , prop . getType ( ) , prop . getParentIdentifier ( ) , prop . isMultiValued ( ) ) ; return newData ; }
Copy ItemData for Delete operation .
305
7
15,467
protected List < ValueData > copyValues ( PropertyData property ) throws RepositoryException { List < ValueData > src = property . getValues ( ) ; List < ValueData > copy = new ArrayList < ValueData > ( src . size ( ) ) ; try { for ( ValueData vd : src ) { copy . add ( ValueDataUtil . createTransientCopy ( vd ) ) ; } } catch ( IOException e ) { throw new RepositoryException ( "Error of Value copy " + property . getQPath ( ) . getAsString ( ) , e ) ; } return copy ; }
Do actual copy of the property ValueDatas .
129
10
15,468
public NodeTypeData build ( ) { if ( nodeDefinitionDataBuilders . size ( ) > 0 ) { childNodeDefinitions = new NodeDefinitionData [ nodeDefinitionDataBuilders . size ( ) ] ; for ( int i = 0 ; i < childNodeDefinitions . length ; i ++ ) { childNodeDefinitions [ i ] = nodeDefinitionDataBuilders . get ( i ) . build ( ) ; } } if ( propertyDefinitionDataBuilders . size ( ) > 0 ) { propertyDefinitions = new PropertyDefinitionData [ propertyDefinitionDataBuilders . size ( ) ] ; for ( int i = 0 ; i < propertyDefinitions . length ; i ++ ) { propertyDefinitions [ i ] = propertyDefinitionDataBuilders . get ( i ) . build ( ) ; } } return new NodeTypeDataImpl ( name , primaryItemName , isMixin , isOrderable , supertypes , propertyDefinitions , childNodeDefinitions ) ; }
Creates instance of NodeTypeData using parameters stored in this object .
201
14
15,469
public static void createVersion ( Node nodeVersioning ) throws Exception { if ( ! nodeVersioning . isNodeType ( NT_FILE ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Version history is not impact with non-nt:file documents, there'is not any version created." ) ; } return ; } if ( ! nodeVersioning . isNodeType ( MIX_VERSIONABLE ) ) { if ( nodeVersioning . canAddMixin ( MIX_VERSIONABLE ) ) { nodeVersioning . addMixin ( MIX_VERSIONABLE ) ; nodeVersioning . save ( ) ; } return ; } if ( ! nodeVersioning . isCheckedOut ( ) ) { nodeVersioning . checkout ( ) ; } else { nodeVersioning . checkin ( ) ; nodeVersioning . checkout ( ) ; } if ( maxAllowVersion != DOCUMENT_AUTO_DEFAULT_VERSION_MAX || maxLiveTime != DOCUMENT_AUTO_DEFAULT_VERSION_EXPIRED ) { removeRedundant ( nodeVersioning ) ; } nodeVersioning . save ( ) ; }
Create new version and clear redundant versions
243
7
15,470
private static void removeRedundant ( Node nodeVersioning ) throws Exception { VersionHistory versionHistory = nodeVersioning . getVersionHistory ( ) ; String baseVersion = nodeVersioning . getBaseVersion ( ) . getName ( ) ; String rootVersion = nodeVersioning . getVersionHistory ( ) . getRootVersion ( ) . getName ( ) ; VersionIterator versions = versionHistory . getAllVersions ( ) ; Date currentDate = new Date ( ) ; Map < String , String > lstVersions = new HashMap < String , String > ( ) ; List < String > lstVersionTime = new ArrayList < String > ( ) ; while ( versions . hasNext ( ) ) { Version version = versions . nextVersion ( ) ; if ( rootVersion . equals ( version . getName ( ) ) || baseVersion . equals ( version . getName ( ) ) ) continue ; if ( maxLiveTime != DOCUMENT_AUTO_DEFAULT_VERSION_EXPIRED && currentDate . getTime ( ) - version . getCreated ( ) . getTime ( ) . getTime ( ) > maxLiveTime ) { versionHistory . removeVersion ( version . getName ( ) ) ; } else { lstVersions . put ( String . valueOf ( version . getCreated ( ) . getTimeInMillis ( ) ) , version . getName ( ) ) ; lstVersionTime . add ( String . valueOf ( version . getCreated ( ) . getTimeInMillis ( ) ) ) ; } } if ( maxAllowVersion <= lstVersionTime . size ( ) && maxAllowVersion != DOCUMENT_AUTO_DEFAULT_VERSION_MAX ) { Collections . sort ( lstVersionTime ) ; String [ ] lsts = lstVersionTime . toArray ( new String [ lstVersionTime . size ( ) ] ) ; for ( int j = 0 ; j <= lsts . length - maxAllowVersion ; j ++ ) { versionHistory . removeVersion ( lstVersions . get ( lsts [ j ] ) ) ; } } }
Remove redundant version - Remove versions has been expired - Remove versions over max allow
437
15
15,471
protected List < PropertyData > getChildProps ( String parentId , boolean withValue ) { return getChildProps . run ( parentId , withValue ) ; }
Internal get child properties .
36
5
15,472
protected ItemData putItem ( ItemData item ) { if ( item . isNode ( ) ) { return putNode ( ( NodeData ) item , ModifyChildOption . MODIFY ) ; } else { return putProperty ( ( PropertyData ) item , ModifyChildOption . MODIFY ) ; } }
Internal put Item .
66
4
15,473
protected ItemData putNode ( NodeData node , ModifyChildOption modifyListsOfChild ) { if ( node . getParentIdentifier ( ) != null ) { if ( modifyListsOfChild == ModifyChildOption . NOT_MODIFY ) { cache . putIfAbsent ( new CacheQPath ( getOwnerId ( ) , node . getParentIdentifier ( ) , node . getQPath ( ) , ItemType . NODE ) , node . getIdentifier ( ) ) ; } else { cache . put ( new CacheQPath ( getOwnerId ( ) , node . getParentIdentifier ( ) , node . getQPath ( ) , ItemType . NODE ) , node . getIdentifier ( ) ) ; } // if MODIFY and List present OR FORCE_MODIFY, then write if ( modifyListsOfChild != ModifyChildOption . NOT_MODIFY ) { cache . addToPatternList ( new CachePatternNodesId ( getOwnerId ( ) , node . getParentIdentifier ( ) ) , node ) ; cache . addToList ( new CacheNodesId ( getOwnerId ( ) , node . getParentIdentifier ( ) ) , node . getIdentifier ( ) , modifyListsOfChild == ModifyChildOption . FORCE_MODIFY ) ; cache . remove ( new CacheNodesByPageId ( getOwnerId ( ) , node . getParentIdentifier ( ) ) ) ; } } if ( modifyListsOfChild == ModifyChildOption . NOT_MODIFY ) { return ( ItemData ) cache . putIfAbsent ( new CacheId ( getOwnerId ( ) , node . getIdentifier ( ) ) , node ) ; } else { return ( ItemData ) cache . put ( new CacheId ( getOwnerId ( ) , node . getIdentifier ( ) ) , node , true ) ; } }
Internal put Node .
407
4
15,474
protected void putNullItem ( NullItemData item ) { boolean inTransaction = cache . isTransactionActive ( ) ; try { if ( ! inTransaction ) { cache . beginTransaction ( ) ; } cache . setLocal ( true ) ; if ( ! item . getIdentifier ( ) . equals ( NullItemData . NULL_ID ) ) { cache . putIfAbsent ( new CacheId ( getOwnerId ( ) , item . getIdentifier ( ) ) , item ) ; } else if ( item . getName ( ) != null && item . getParentIdentifier ( ) != null ) { cache . putIfAbsent ( new CacheQPath ( getOwnerId ( ) , item . getParentIdentifier ( ) , item . getName ( ) , ItemType . getItemType ( item ) ) , NullItemData . NULL_ID ) ; } } finally { cache . setLocal ( false ) ; if ( ! inTransaction ) { dedicatedTxCommit ( ) ; } } }
Internal put NullNode .
209
5
15,475
protected void updateMixin ( NodeData node ) { NodeData prevData = ( NodeData ) cache . put ( new CacheId ( getOwnerId ( ) , node . getIdentifier ( ) ) , node , true ) ; // prevent update NullNodeData if ( ! ( prevData instanceof NullNodeData ) ) { if ( prevData != null ) { // do update ACL if needed if ( prevData . getACL ( ) == null || ! prevData . getACL ( ) . equals ( node . getACL ( ) ) ) { updateChildsACL ( node . getIdentifier ( ) , node . getACL ( ) ) ; } } else if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Previous NodeData not found for mixin update " + node . getQPath ( ) . getAsString ( ) ) ; } } }
Update Node s mixin and ACL .
188
8
15,476
protected Set < String > updateTreePath ( QPath prevRootPath , QPath newRootPath , Set < String > idsToSkip ) { return caller . updateTreePath ( prevRootPath , newRootPath , idsToSkip ) ; }
Check all items in cache if it is a descendant of the previous root path and if so update the path according the new root path .
53
27
15,477
protected void renameItem ( final ItemState state , final ItemState lastDelete ) { ItemData data = state . getData ( ) ; ItemData prevData = getFromBufferedCacheById . run ( data . getIdentifier ( ) ) ; if ( data . isNode ( ) ) { if ( state . isPersisted ( ) ) { // it is state where name can be changed by rename operation, so re-add node removeItem ( lastDelete . getData ( ) ) ; putItem ( state . getData ( ) ) ; } else { // update item data with new name only cache . put ( new CacheId ( getOwnerId ( ) , data . getIdentifier ( ) ) , data , false ) ; } } else { PropertyData prop = ( PropertyData ) data ; if ( prevData != null && ! ( prevData instanceof NullItemData ) ) { PropertyData newProp = new PersistedPropertyData ( prop . getIdentifier ( ) , prop . getQPath ( ) , prop . getParentIdentifier ( ) , prop . getPersistedVersion ( ) , prop . getType ( ) , prop . isMultiValued ( ) , ( ( PropertyData ) prevData ) . getValues ( ) , new SimplePersistedSize ( ( ( PersistedPropertyData ) prevData ) . getPersistedSize ( ) ) ) ; // update item data with new name and old values only cache . put ( new CacheId ( getOwnerId ( ) , newProp . getIdentifier ( ) ) , newProp , false ) ; } else { // remove item to avoid inconsistency in cluster mode since we have not old values cache . remove ( new CacheId ( getOwnerId ( ) , data . getIdentifier ( ) ) ) ; } } }
Apply rename operation on cache . Parent node will be re - added into the cache since parent or name might changing . For other children only item data will be replaced .
372
33
15,478
private void onCacheEntryUpdated ( ItemData data ) { if ( data == null || data instanceof NullItemData ) { return ; } for ( WorkspaceStorageCacheListener listener : listeners ) { try { listener . onCacheEntryUpdated ( data ) ; } catch ( RuntimeException e ) //NOSONAR { LOG . warn ( "The method onCacheEntryUpdated fails for the listener " + listener . getClass ( ) , e ) ; } } }
Called when a cache entry corresponding to the given node has item updated
96
14
15,479
private static DNChar denormalize ( String string ) { if ( string . startsWith ( "&lt;" ) ) return new DNChar ( ' ' , 4 ) ; else if ( string . startsWith ( "&gt;" ) ) return new DNChar ( ' ' , 4 ) ; else if ( string . startsWith ( "&amp;" ) ) return new DNChar ( ' ' , 5 ) ; else if ( string . startsWith ( "&quot;" ) ) return new DNChar ( ' ' , 6 ) ; else if ( string . startsWith ( "&apos;" ) ) return new DNChar ( ' ' , 6 ) ; else if ( string . startsWith ( "_x000D_" ) ) return new DNChar ( ' ' , 7 ) ; else if ( string . startsWith ( "_x000A_" ) ) return new DNChar ( ' ' , 7 ) ; /** * Denormalize of this value cause a 4 fails in TCK. If we don'n do it, it text will be remain * the "_x0009_" value instead of "\t" TCK tests fail because the checkImportSimpleXMLTree * method of DocumentViewImportTest object have a small problem in this place // both * possibilities In logic if (!propVal.equals(encodedAttributeValue) || * !propVal.equals(encodedAttributeValue)) { fail("Value " + encodedAttributeValue + * " of attribute " + decodedAttributeName + " is not correctly imported."); of test the * propVal must be equal of encodedAttributeValue the encoded version of value */ else if ( string . startsWith ( "_x0009_" ) ) return new DNChar ( ' ' , 7 ) ; else if ( string . startsWith ( "_x0020_" ) ) return new DNChar ( ' ' , 7 ) ; else if ( string . startsWith ( "_x005f_" ) ) return new DNChar ( ' ' , 7 ) ; else throw new IllegalArgumentException ( ILLEGAL_DNCHAR ) ; }
Denormalizes and print the given character .
441
9
15,480
public File getFile ( String hash ) { // work with digest return new File ( channel . rootDir , channel . makeFilePath ( hash , 0 ) ) ; }
Construct file name of given hash .
35
7
15,481
public MultiColumnQueryHits execute ( Query query , Sort sort , long resultFetchHint , InternalQName selectorName ) throws IOException { return new QueryHitsAdapter ( evaluate ( query , sort , resultFetchHint ) , selectorName ) ; }
Executes the query and returns the hits that match the query .
56
13
15,482
private boolean authenticate ( Session session , String userName , String password , PasswordEncrypter pe ) throws Exception { boolean authenticated ; Node userNode ; try { userNode = utils . getUserNode ( session , userName ) ; } catch ( PathNotFoundException e ) { return false ; } boolean enabled = userNode . canAddMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ; if ( ! enabled ) { throw new DisabledUserException ( userName ) ; } if ( pe == null ) { authenticated = utils . readString ( userNode , UserProperties . JOS_PASSWORD ) . equals ( password ) ; } else { String encryptedPassword = new String ( pe . encrypt ( utils . readString ( userNode , UserProperties . JOS_PASSWORD ) . getBytes ( ) ) ) ; authenticated = encryptedPassword . equals ( password ) ; } if ( authenticated ) { Calendar lastLoginTime = Calendar . getInstance ( ) ; userNode . setProperty ( UserProperties . JOS_LAST_LOGIN_TIME , lastLoginTime ) ; session . save ( ) ; } return authenticated ; }
Checks if credentials matches .
248
6
15,483
private void createUser ( Session session , UserImpl user , boolean broadcast ) throws Exception { Node userStorageNode = utils . getUsersStorageNode ( session ) ; Node userNode = userStorageNode . addNode ( user . getUserName ( ) ) ; if ( user . getCreatedDate ( ) == null ) { Calendar calendar = Calendar . getInstance ( ) ; user . setCreatedDate ( calendar . getTime ( ) ) ; } user . setInternalId ( userNode . getUUID ( ) ) ; if ( broadcast ) { preSave ( user , true ) ; } writeUser ( user , userNode ) ; session . save ( ) ; putInCache ( user ) ; if ( broadcast ) { postSave ( user , true ) ; } }
Persists new user .
159
5
15,484
private User removeUser ( Session session , String userName , boolean broadcast ) throws Exception { Node userNode = utils . getUserNode ( session , userName ) ; User user = readUser ( userNode ) ; if ( broadcast ) { preDelete ( user ) ; } removeMemberships ( userNode , broadcast ) ; userNode . remove ( ) ; session . save ( ) ; removeFromCache ( userName ) ; removeAllRelatedFromCache ( userName ) ; if ( broadcast ) { postDelete ( user ) ; } return user ; }
Remove user and related membership entities .
114
7
15,485
private void removeMemberships ( Node userNode , boolean broadcast ) throws RepositoryException { PropertyIterator refUserProps = userNode . getReferences ( ) ; while ( refUserProps . hasNext ( ) ) { Node refUserNode = refUserProps . nextProperty ( ) . getParent ( ) ; refUserNode . remove ( ) ; } }
Removes membership entities related to current user .
76
9
15,486
private void saveUser ( Session session , UserImpl user , boolean broadcast ) throws Exception { Node userNode = getUserNode ( session , user ) ; if ( broadcast ) { preSave ( user , false ) ; } String oldName = userNode . getName ( ) ; String newName = user . getUserName ( ) ; if ( ! oldName . equals ( newName ) ) { String oldPath = userNode . getPath ( ) ; String newPath = utils . getUserNodePath ( newName ) ; session . move ( oldPath , newPath ) ; removeFromCache ( oldName ) ; moveMembershipsInCache ( oldName , newName ) ; } writeUser ( user , userNode ) ; session . save ( ) ; putInCache ( user ) ; if ( broadcast ) { postSave ( user , false ) ; } }
Persists user .
180
4
15,487
private Node getUserNode ( Session session , UserImpl user ) throws RepositoryException { if ( user . getInternalId ( ) != null ) { return session . getNodeByUUID ( user . getInternalId ( ) ) ; } else { return utils . getUserNode ( session , user . getUserName ( ) ) ; } }
Returns user node by internal identifier or by name .
73
10
15,488
public UserImpl readUser ( Node userNode ) throws Exception { UserImpl user = new UserImpl ( userNode . getName ( ) ) ; Date creationDate = utils . readDate ( userNode , UserProperties . JOS_CREATED_DATE ) ; Date lastLoginTime = utils . readDate ( userNode , UserProperties . JOS_LAST_LOGIN_TIME ) ; String email = utils . readString ( userNode , UserProperties . JOS_EMAIL ) ; String password = utils . readString ( userNode , UserProperties . JOS_PASSWORD ) ; String firstName = utils . readString ( userNode , UserProperties . JOS_FIRST_NAME ) ; String lastName = utils . readString ( userNode , UserProperties . JOS_LAST_NAME ) ; String displayName = utils . readString ( userNode , UserProperties . JOS_DISPLAY_NAME ) ; boolean enabled = userNode . canAddMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ; user . setInternalId ( userNode . getUUID ( ) ) ; user . setCreatedDate ( creationDate ) ; user . setLastLoginTime ( lastLoginTime ) ; user . setEmail ( email ) ; user . setPassword ( password ) ; user . setFirstName ( firstName ) ; user . setLastName ( lastName ) ; user . setDisplayName ( displayName ) ; user . setEnabled ( enabled ) ; return user ; }
Read user properties from the node in the storage .
334
10
15,489
private void writeUser ( User user , Node node ) throws Exception { node . setProperty ( UserProperties . JOS_EMAIL , user . getEmail ( ) ) ; node . setProperty ( UserProperties . JOS_FIRST_NAME , user . getFirstName ( ) ) ; node . setProperty ( UserProperties . JOS_LAST_NAME , user . getLastName ( ) ) ; node . setProperty ( UserProperties . JOS_PASSWORD , user . getPassword ( ) ) ; node . setProperty ( UserProperties . JOS_DISPLAY_NAME , user . getDisplayName ( ) ) ; node . setProperty ( UserProperties . JOS_USER_NAME , node . getName ( ) ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( user . getCreatedDate ( ) ) ; node . setProperty ( UserProperties . JOS_CREATED_DATE , calendar ) ; }
Write user properties from the node to the storage .
209
10
15,490
void migrateUser ( Node oldUserNode ) throws Exception { String userName = oldUserNode . getName ( ) ; if ( findUserByName ( userName , UserStatus . ANY ) != null ) { removeUser ( userName , false ) ; } UserImpl user = readUser ( oldUserNode ) ; createUser ( user , false ) ; }
Method for user migration .
75
5
15,491
private void preSave ( User user , boolean isNew ) throws Exception { for ( UserEventListener listener : listeners ) { listener . preSave ( user , isNew ) ; } }
Notifying listeners before user creation .
38
7
15,492
private void postSave ( User user , boolean isNew ) throws Exception { for ( UserEventListener listener : listeners ) { listener . postSave ( user , isNew ) ; } }
Notifying listeners after user creation .
38
7
15,493
private void preDelete ( User user ) throws Exception { for ( UserEventListener listener : listeners ) { listener . preDelete ( user ) ; } }
Notifying listeners before user deletion .
31
7
15,494
private void postDelete ( User user ) throws Exception { for ( UserEventListener listener : listeners ) { listener . postDelete ( user ) ; } }
Notifying listeners after user deletion .
31
7
15,495
private void removeAllRelatedFromCache ( String userName ) { cache . remove ( userName , CacheType . USER_PROFILE ) ; cache . remove ( CacheHandler . USER_PREFIX + userName , CacheType . MEMBERSHIP ) ; }
Remove user and related entities from cache .
58
8
15,496
private User getFromCache ( String userName ) { return ( User ) cache . get ( userName , CacheType . USER ) ; }
Get user from cache .
30
5
15,497
private void moveMembershipsInCache ( String oldName , String newName ) { cache . move ( CacheHandler . USER_PREFIX + oldName , CacheHandler . USER_PREFIX + newName , CacheType . MEMBERSHIP ) ; }
Move memberships entities from old key to new one .
58
11
15,498
private void putInCache ( User user ) { cache . put ( user . getUserName ( ) , user , CacheType . USER ) ; }
Put user in cache .
32
5
15,499
public PersistedValueData read ( ObjectReader in , int type ) throws UnknownClassIdException , IOException { File tempDirectory = new File ( SerializationConstants . TEMP_DIR ) ; PrivilegedFileHelper . mkdirs ( tempDirectory ) ; // read id int key ; if ( ( key = in . readInt ( ) ) != SerializationConstants . PERSISTED_VALUE_DATA ) { throw new UnknownClassIdException ( "There is unexpected class [" + key + "]" ) ; } int orderNumber = in . readInt ( ) ; boolean isByteArray = in . readBoolean ( ) ; if ( isByteArray ) { byte [ ] data = new byte [ in . readInt ( ) ] ; in . readFully ( data ) ; return ValueDataUtil . createValueData ( type , orderNumber , data ) ; } else { // read file id - used for reread data optimization String id = in . readString ( ) ; // read file length long length = in . readLong ( ) ; SerializationSpoolFile sf = holder . get ( id ) ; if ( sf == null ) { // Deleted ItemState usecase if ( length == SerializationConstants . NULL_FILE ) { return new StreamPersistedValueData ( orderNumber , ( SerializationSpoolFile ) null , spoolConfig ) ; } sf = new SerializationSpoolFile ( tempDirectory , id , holder ) ; writeToFile ( in , sf , length ) ; holder . put ( id , sf ) ; return new StreamPersistedValueData ( orderNumber , sf , spoolConfig ) ; } else { sf . acquire ( this ) ; // workaround for AsyncReplication test try { PersistedValueData vd = new StreamPersistedValueData ( orderNumber , sf , spoolConfig ) ; // skip data in input stream if ( in . skip ( length ) != length ) { throw new IOException ( "Content isn't skipped correctly." ) ; } return vd ; } finally { sf . release ( this ) ; } } } }
Read and set PersistedValueData object data .
448
10