idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
15,300
private void postDelete ( UserProfile userProfile ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . postDelete ( userProfile ) ; } }
Notifying listeners after profile deletion .
15,301
protected void addScripts ( ) { if ( loadPlugins == null || loadPlugins . size ( ) == 0 ) { return ; } for ( GroovyScript2RestLoaderPlugin loadPlugin : loadPlugins ) { if ( loadPlugin . getXMLConfigs ( ) . size ( ) == 0 ) { continue ; } Session session = null ; try { ManageableRepository repository = repositoryService . getRepository ( loadPlugin . getRepository ( ) ) ; String workspace = loadPlugin . getWorkspace ( ) ; session = repository . getSystemSession ( workspace ) ; String nodeName = loadPlugin . getNode ( ) ; Node node = null ; try { node = ( Node ) session . getItem ( nodeName ) ; } catch ( PathNotFoundException e ) { StringTokenizer tokens = new StringTokenizer ( nodeName , "/" ) ; node = session . getRootNode ( ) ; while ( tokens . hasMoreTokens ( ) ) { String t = tokens . nextToken ( ) ; if ( node . hasNode ( t ) ) { node = node . getNode ( t ) ; } else { node = node . addNode ( t , "nt:folder" ) ; } } } for ( XMLGroovyScript2Rest xg : loadPlugin . getXMLConfigs ( ) ) { String scriptName = xg . getName ( ) ; if ( node . hasNode ( scriptName ) ) { LOG . debug ( "Script {} already created" , scriptName ) ; continue ; } createScript ( node , scriptName , xg . isAutoload ( ) , configurationManager . getInputStream ( xg . getPath ( ) ) ) ; } session . save ( ) ; } catch ( Exception e ) { LOG . error ( "Failed add scripts. " , e ) ; } finally { if ( session != null ) { session . logout ( ) ; } } } }
Add scripts that specified in configuration .
15,302
protected Node createScript ( Node parent , String name , boolean autoload , InputStream stream ) throws Exception { Node scriptFile = parent . addNode ( name , "nt:file" ) ; Node script = scriptFile . addNode ( "jcr:content" , getNodeType ( ) ) ; script . setProperty ( "exo:autoload" , autoload ) ; script . setProperty ( "jcr:mimeType" , "script/groovy" ) ; script . setProperty ( "jcr:lastModified" , Calendar . getInstance ( ) ) ; script . setProperty ( "jcr:data" , stream ) ; return scriptFile ; }
Create JCR node .
15,303
protected void setAttributeSmart ( Element element , String attr , String value ) { if ( value == null ) { element . removeAttribute ( attr ) ; } else { element . setAttribute ( attr , value ) ; } }
Set attribute value . If value is null the attribute will be removed .
15,304
@ Path ( "load/{repository}/{workspace}/{path:.*}" ) @ RolesAllowed ( { "administrators" } ) public Response load ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path , @ DefaultValue ( "true" ) @ QueryParam ( "state" ) boolean state , @ QueryParam ( "sources" ) List < String > sources , @ QueryParam ( "file" ) List < String > files , MultivaluedMap < String , String > properties ) { try { return load ( repository , workspace , path , state , properties , createSourceFolders ( sources ) , createSourceFiles ( files ) ) ; } catch ( MalformedURLException e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . BAD_REQUEST ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } }
Deploy groovy script as REST service . If this property set to true then script will be deployed as REST service if false the script will be undeployed . NOTE is script already deployed and state is true script will be re - deployed .
15,305
@ Path ( "delete/{repository}/{workspace}/{path:.*}" ) public Response deleteScript ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; ses . getItem ( "/" + path ) . remove ( ) ; ses . save ( ) ; return Response . status ( Response . Status . NO_CONTENT ) . build ( ) ; } catch ( PathNotFoundException e ) { String msg = "Path " + path + " does not exists" ; LOG . error ( msg ) ; return Response . status ( Response . Status . NOT_FOUND ) . entity ( msg ) . entity ( MediaType . TEXT_PLAIN ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } }
Remove node that contains groovy script .
15,306
@ Produces ( { "script/groovy" } ) @ Path ( "src/{repository}/{workspace}/{path:.*}" ) public Response getScript ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; Node scriptFile = ( Node ) ses . getItem ( "/" + path ) ; return Response . status ( Response . Status . OK ) . entity ( scriptFile . getNode ( "jcr:content" ) . getProperty ( "jcr:data" ) . getStream ( ) ) . type ( "script/groovy" ) . build ( ) ; } catch ( PathNotFoundException e ) { String msg = "Path " + path + " does not exists" ; LOG . error ( msg ) ; return Response . status ( Response . Status . NOT_FOUND ) . entity ( msg ) . entity ( MediaType . TEXT_PLAIN ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } }
Get source code of groovy script .
15,307
@ Produces ( { MediaType . APPLICATION_JSON } ) @ Path ( "meta/{repository}/{workspace}/{path:.*}" ) public Response getScriptMetadata ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; Node script = ( ( Node ) ses . getItem ( "/" + path ) ) . getNode ( "jcr:content" ) ; ResourceId key = new NodeScriptKey ( repository , workspace , script ) ; ScriptMetadata meta = new ScriptMetadata ( script . getProperty ( "exo:autoload" ) . getBoolean ( ) , groovyPublisher . isPublished ( key ) , script . getProperty ( "jcr:mimeType" ) . getString ( ) , script . getProperty ( "jcr:lastModified" ) . getDate ( ) . getTimeInMillis ( ) ) ; return Response . status ( Response . Status . OK ) . entity ( meta ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } catch ( PathNotFoundException e ) { String msg = "Path " + path + " does not exists" ; LOG . error ( msg ) ; return Response . status ( Response . Status . NOT_FOUND ) . entity ( msg ) . entity ( MediaType . TEXT_PLAIN ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } }
Get groovy script s meta - information .
15,308
@ Produces ( MediaType . APPLICATION_JSON ) @ Path ( "list/{repository}/{workspace}" ) public Response list ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ QueryParam ( "name" ) String name ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; String xpath = "//element(*, exo:groovyResourceContainer)" ; Query query = ses . getWorkspace ( ) . getQueryManager ( ) . createQuery ( xpath , Query . XPATH ) ; QueryResult result = query . execute ( ) ; NodeIterator nodeIterator = result . getNodes ( ) ; ArrayList < String > scriptList = new ArrayList < String > ( ) ; if ( name == null || name . length ( ) == 0 ) { while ( nodeIterator . hasNext ( ) ) { Node node = nodeIterator . nextNode ( ) ; scriptList . add ( node . getParent ( ) . getPath ( ) ) ; } } else { StringBuilder p = new StringBuilder ( ) ; p . append ( ".*" ) ; for ( int i = 0 ; i < name . length ( ) ; i ++ ) { char c = name . charAt ( i ) ; if ( c == '*' || c == '?' ) { p . append ( '.' ) ; } if ( ".()[]^$|" . indexOf ( c ) != - 1 ) { p . append ( '\\' ) ; } p . append ( c ) ; } p . append ( ".*" ) ; Pattern pattern = Pattern . compile ( p . toString ( ) , Pattern . CASE_INSENSITIVE ) ; while ( nodeIterator . hasNext ( ) ) { Node node = nodeIterator . nextNode ( ) ; String scriptName = node . getParent ( ) . getPath ( ) ; if ( pattern . matcher ( scriptName ) . matches ( ) ) { scriptList . add ( scriptName ) ; } } } Collections . sort ( scriptList ) ; return Response . status ( Response . Status . OK ) . entity ( new ScriptList ( scriptList ) ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } }
Returns the list of all groovy - scripts found in workspace .
15,309
protected static String getPath ( String fullPath ) { int sl = fullPath . lastIndexOf ( '/' ) ; return sl > 0 ? "/" + fullPath . substring ( 0 , sl ) : "/" ; }
Extract path to node s parent from full path .
15,310
protected static String getName ( String fullPath ) { int sl = fullPath . lastIndexOf ( '/' ) ; return sl >= 0 ? fullPath . substring ( sl + 1 ) : fullPath ; }
Extract node s name from full node path .
15,311
public HierarchicalProperty getChild ( QName name ) { for ( HierarchicalProperty child : children ) { if ( child . getName ( ) . equals ( name ) ) return child ; } return null ; }
retrieves children property by name .
15,312
public static String md5 ( String data , String enc ) throws UnsupportedEncodingException { try { return digest ( "MD5" , data . getBytes ( enc ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new InternalError ( "MD5 digest not available???" ) ; } }
Calculate an MD5 hash of the string given .
15,313
public static String [ ] explode ( String str , int ch , boolean respectEmpty ) { if ( str == null || str . length ( ) == 0 ) { return new String [ 0 ] ; } ArrayList strings = new ArrayList ( ) ; int pos ; int lastpos = 0 ; while ( ( pos = str . indexOf ( ch , lastpos ) ) >= 0 ) { if ( pos - lastpos > 0 || respectEmpty ) { strings . add ( str . substring ( lastpos , pos ) ) ; } lastpos = pos + 1 ; } if ( lastpos < str . length ( ) ) { strings . add ( str . substring ( lastpos ) ) ; } else if ( respectEmpty && lastpos == str . length ( ) ) { strings . add ( "" ) ; } return ( String [ ] ) strings . toArray ( new String [ strings . size ( ) ] ) ; }
returns an array of strings decomposed of the original string split at every occurance of ch .
15,314
public static String implode ( String [ ] arr , String delim ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i > 0 ) { buf . append ( delim ) ; } buf . append ( arr [ i ] ) ; } return buf . toString ( ) ; }
Concatenates all strings in the string array using the specified delimiter .
15,315
public static String encodeIllegalXMLCharacters ( String text ) { if ( text == null ) { throw new IllegalArgumentException ( "null argument" ) ; } StringBuilder buf = null ; int length = text . length ( ) ; int pos = 0 ; for ( int i = 0 ; i < length ; i ++ ) { int ch = text . charAt ( i ) ; switch ( ch ) { case '<' : case '>' : case '&' : case '"' : case '\'' : if ( buf == null ) { buf = new StringBuilder ( ) ; } if ( i > 0 ) { buf . append ( text . substring ( pos , i ) ) ; } pos = i + 1 ; break ; default : continue ; } if ( ch == '<' ) { buf . append ( "&lt;" ) ; } else if ( ch == '>' ) { buf . append ( "&gt;" ) ; } else if ( ch == '&' ) { buf . append ( "&amp;" ) ; } else if ( ch == '"' ) { buf . append ( "&quot;" ) ; } else if ( ch == '\'' ) { buf . append ( "&apos;" ) ; } } if ( buf == null ) { return text ; } else { if ( pos < length ) { buf . append ( text . substring ( pos ) ) ; } return buf . toString ( ) ; } }
Replaces illegal XML characters in the given string by their corresponding predefined entity references .
15,316
public static String getName ( String path ) { int pos = path . lastIndexOf ( '/' ) ; return pos >= 0 ? path . substring ( pos + 1 ) : "" ; }
Returns the name part of the path
15,317
public static boolean isSibling ( String p1 , String p2 ) { int pos1 = p1 . lastIndexOf ( '/' ) ; int pos2 = p2 . lastIndexOf ( '/' ) ; return ( pos1 == pos2 && pos1 >= 0 && p1 . regionMatches ( 0 , p2 , 0 , pos1 ) ) ; }
Determines if two paths denote hierarchical siblins .
15,318
private InternalQName getNodeTypeName ( Node config ) throws IllegalNameException , RepositoryException { String ntString = config . getAttributes ( ) . getNamedItem ( "primaryType" ) . getNodeValue ( ) ; return resolver . parseJCRName ( ntString ) . getInternalName ( ) ; }
Reads the node type of the root node of the indexing aggregate .
15,319
@ SuppressWarnings ( "unchecked" ) private boolean isIndexRecoveryRequired ( ) throws RepositoryException { if ( recoveryFilters == null ) { recoveryFilters = new ArrayList < AbstractRecoveryFilter > ( ) ; log . info ( "Initializing RecoveryFilters." ) ; if ( recoveryFilterClasses . isEmpty ( ) ) { this . recoveryFilterClasses . add ( DocNumberRecoveryFilter . class . getName ( ) ) ; } for ( String recoveryFilterClassName : recoveryFilterClasses ) { AbstractRecoveryFilter filter = null ; Class < ? extends AbstractRecoveryFilter > filterClass ; try { filterClass = ( Class < ? extends AbstractRecoveryFilter > ) ClassLoading . forName ( recoveryFilterClassName , this ) ; Constructor < ? extends AbstractRecoveryFilter > constuctor = filterClass . getConstructor ( SearchIndex . class ) ; filter = constuctor . newInstance ( this ) ; recoveryFilters . add ( filter ) ; } catch ( ClassNotFoundException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( InstantiationException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( SecurityException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( NoSuchMethodException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } } } for ( AbstractRecoveryFilter filter : recoveryFilters ) { if ( filter . accept ( ) ) { return true ; } } return false ; }
Invokes all recovery filters from the set
15,320
public MultiColumnQueryHits executeQuery ( SessionImpl session , AbstractQueryImpl queryImpl , Query query , QPath [ ] orderProps , boolean [ ] orderSpecs , long resultFetchHint ) throws IOException , RepositoryException { waitForResuming ( ) ; checkOpen ( ) ; workingThreads . incrementAndGet ( ) ; try { FieldComparatorSource scs = queryImpl . isCaseInsensitiveOrder ( ) ? this . sics : this . scs ; Sort sort = new Sort ( createSortFields ( orderProps , orderSpecs , scs ) ) ; final IndexReader reader = getIndexReader ( queryImpl . needsSystemTree ( ) ) ; @ SuppressWarnings ( "resource" ) JcrIndexSearcher searcher = new JcrIndexSearcher ( session , reader , getContext ( ) . getItemStateManager ( ) ) ; searcher . setSimilarity ( getSimilarity ( ) ) ; return new FilterMultiColumnQueryHits ( searcher . execute ( query , sort , resultFetchHint , QueryImpl . DEFAULT_SELECTOR_NAME ) ) { public void close ( ) throws IOException { try { super . close ( ) ; } finally { PerQueryCache . getInstance ( ) . dispose ( ) ; Util . closeOrRelease ( reader ) ; } } } ; } finally { workingThreads . decrementAndGet ( ) ; if ( isSuspended . get ( ) && workingThreads . get ( ) == 0 ) { synchronized ( workingThreads ) { workingThreads . notifyAll ( ) ; } } } }
Executes the query on the search index .
15,321
public IndexFormatVersion getIndexFormatVersion ( ) { if ( indexFormatVersion == null ) { if ( getContext ( ) . getParentHandler ( ) instanceof SearchIndex ) { SearchIndex parent = ( SearchIndex ) getContext ( ) . getParentHandler ( ) ; if ( parent . getIndexFormatVersion ( ) . getVersion ( ) < indexRegister . getDefaultIndex ( ) . getIndexFormatVersion ( ) . getVersion ( ) ) { indexFormatVersion = parent . getIndexFormatVersion ( ) ; } else { indexFormatVersion = indexRegister . getDefaultIndex ( ) . getIndexFormatVersion ( ) ; } } else { indexFormatVersion = indexRegister . getDefaultIndex ( ) . getIndexFormatVersion ( ) ; } } return indexFormatVersion ; }
Returns the index format version that this search index is able to support when a query is executed on this index .
15,322
protected IndexReader getIndexReader ( boolean includeSystemIndex ) throws IOException { if ( ! indexRegister . getDefaultIndex ( ) . isOnline ( ) && ! allowQuery . get ( ) ) { throw new IndexOfflineIOException ( "Index is offline" ) ; } QueryHandler parentHandler = getContext ( ) . getParentHandler ( ) ; CachingMultiIndexReader parentReader = null ; if ( parentHandler instanceof SearchIndex && includeSystemIndex ) { parentReader = ( ( SearchIndex ) parentHandler ) . indexRegister . getDefaultIndex ( ) . getIndexReader ( ) ; } IndexReader reader ; if ( parentReader != null ) { CachingMultiIndexReader [ ] readers = { indexRegister . getDefaultIndex ( ) . getIndexReader ( ) , parentReader } ; reader = new CombinedIndexReader ( readers ) ; } else { reader = indexRegister . getDefaultIndex ( ) . getIndexReader ( ) ; } return new JcrIndexReader ( reader ) ; }
Returns an index reader for this search index . The caller of this method is responsible for closing the index reader when he is finished using it .
15,323
protected SortField [ ] createSortFields ( QPath [ ] orderProps , boolean [ ] orderSpecs , FieldComparatorSource scs ) throws RepositoryException { List < SortField > sortFields = new ArrayList < SortField > ( ) ; for ( int i = 0 ; i < orderProps . length ; i ++ ) { if ( orderProps [ i ] . getEntries ( ) . length == 1 && Constants . JCR_SCORE . equals ( orderProps [ i ] . getName ( ) ) ) { sortFields . add ( new SortField ( null , SortField . SCORE , orderSpecs [ i ] ) ) ; } else { String jcrPath = npResolver . createJCRPath ( orderProps [ i ] ) . getAsString ( false ) ; sortFields . add ( new SortField ( jcrPath , scs , ! orderSpecs [ i ] ) ) ; } } return sortFields . toArray ( new SortField [ sortFields . size ( ) ] ) ; }
Creates the SortFields for the order properties .
15,324
public MultiIndex createNewIndex ( String suffix ) throws IOException { IndexInfos indexInfos = new IndexInfos ( ) ; IndexUpdateMonitor indexUpdateMonitor = new DefaultIndexUpdateMonitor ( ) ; IndexerIoModeHandler modeHandler = new IndexerIoModeHandler ( IndexerIoMode . READ_WRITE ) ; MultiIndex newIndex = new MultiIndex ( this , getContext ( ) . getIndexingTree ( ) , modeHandler , indexInfos , indexUpdateMonitor , cloneDirectoryManager ( this . getDirectoryManager ( ) , suffix ) ) ; return newIndex ; }
Create a new index with the same actual context .
15,325
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
15,326
protected InputStream createSynonymProviderConfigResource ( ) throws IOException { if ( synonymProviderConfigPath != null ) { InputStream fsr ; 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 { return null ; } }
Creates a file system resource to the synonym provider configuration .
15,327
protected SpellChecker createSpellChecker ( ) { 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 .
15,328
public ErrorLog doInitErrorLog ( String path ) throws IOException { File file = new File ( new File ( path ) , ERROR_LOG ) ; return new ErrorLog ( file , errorLogfileSize ) ; }
Initialization error log .
15,329
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 .
15,330
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 .
15,331
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 .
15,332
Node getUserNode ( Session session , String userName ) throws PathNotFoundException , RepositoryException { return ( Node ) session . getItem ( getUserNodePath ( userName ) ) ; }
Returns the node where defined user is stored .
15,333
String getUserNodePath ( String userName ) throws RepositoryException { return service . getStoragePath ( ) + "/" + JCROrganizationServiceImpl . STORAGE_JOS_USERS + "/" + userName ; }
Returns the node path where defined user is stored .
15,334
Node getMembershipTypeNode ( Session session , String name ) throws PathNotFoundException , RepositoryException { return ( Node ) session . getItem ( getMembershipTypeNodePath ( name ) ) ; }
Returns the node where defined membership type is stored .
15,335
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 .
15,336
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 .
15,337
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 .
15,338
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 .
15,339
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
15,340
public void reset ( ) { min . set ( Long . MAX_VALUE ) ; max . set ( 0 ) ; total . set ( 0 ) ; times . set ( 0 ) ; }
Reset the statistics
15,341
protected void refreshIndexes ( Set < String > set ) { if ( set == null ) { return ; } setNames ( set ) ; 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
15,342
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 .
15,343
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 .
15,344
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 .
15,345
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 .
15,346
protected QPath traverseQPath ( String cpid ) throws SQLException , InvalidItemStateException , IllegalNameException { return traverseQPathSQ ( cpid ) ; }
Use simple queries since it is much faster
15,347
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 ( ) ) ; File tempDir = new File ( rootDir , TEMP_DIR_NAME ) ; tempDir . mkdirs ( ) ; if ( tempDir . exists ( ) && tempDir . isDirectory ( ) ) { 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 .
15,348
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 .
15,349
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 .
15,350
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 ) ; 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 .
15,351
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 .
15,352
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 .
15,353
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 .
15,354
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 .
15,355
private Group getFromCache ( String groupId ) { return ( Group ) cache . get ( groupId , CacheType . GROUP ) ; }
Reads group from cache .
15,356
private void putInCache ( Group group ) { cache . put ( group . getId ( ) , group , CacheType . GROUP ) ; }
Puts group in cache .
15,357
private void removeAllRelatedFromCache ( String groupId ) { cache . remove ( CacheHandler . GROUP_PREFIX + groupId , CacheType . MEMBERSHIP ) ; }
Removes related entities from cache .
15,358
private void preSave ( Group group , boolean isNew ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . preSave ( group , isNew ) ; } }
Notifying listeners before group creation .
15,359
private void postSave ( Group group , boolean isNew ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . postSave ( group , isNew ) ; } }
Notifying listeners after group creation .
15,360
private void preDelete ( Group group ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . preDelete ( group ) ; } }
Notifying listeners before group deletion .
15,361
private void postDelete ( Group group ) throws Exception { for ( GroupEventListener listener : listeners ) { listener . postDelete ( group ) ; } }
Notifying listeners after group deletion .
15,362
public void execute ( Runnable command ) { adjustPoolSize ( ) ; if ( numProcessors == 1 ) { command . run ( ) ; } else { try { executor . execute ( command ) ; } catch ( InterruptedException e ) { 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!
15,363
public Result [ ] executeAndWait ( Command [ ] commands ) { Result [ ] results = new Result [ commands . length ] ; if ( numProcessors == 1 ) { 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 ) { r . run ( ) ; } } 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 ; Thread . interrupted ( ) ; continue ; } catch ( InvocationTargetException e ) { ex = e ; } results [ i ] = new Result ( obj , ex ) ; break ; } } if ( interrupted ) { 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 .
15,364
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 .
15,365
private void registerListener ( final ChangesLogWrapper logWrapper , TransactionableResourceManager txResourceManager ) throws RepositoryException { try { txResourceManager . addListener ( new TransactionableResourceManagerListener ( ) { public void onCommit ( boolean onePhase ) throws Exception { } public void onAfterCompletion ( int status ) throws Exception { if ( status == Status . STATUS_COMMITTED ) { transactionManager . suspend ( ) ; SecurityHelper . doPrivilegedAction ( new PrivilegedAction < Void > ( ) { public Void run ( ) { notifySaveItems ( logWrapper . getChangesLog ( ) , false ) ; return null ; } } ) ; } } 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
15,366
protected ItemData getCachedItemData ( NodeData parentData , QPathEntry name , ItemType itemType ) throws RepositoryException { return cache . isEnabled ( ) ? cache . get ( parentData . getIdentifier ( ) , name , itemType ) : null ; }
Get cached ItemData .
15,367
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 .
15,368
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 ( ) ) { 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 .
15,369
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 ( ) ) { 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 .
15,370
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 .
15,371
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 ) { 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 .
15,372
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 .
15,373
private void initRemoteCommands ( ) { if ( rpcService != null ) { 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 .
15,374
private void unregisterRemoteCommands ( ) { if ( rpcService != null ) { rpcService . unregisterCommand ( suspend ) ; rpcService . unregisterCommand ( resume ) ; rpcService . unregisterCommand ( requestForResponsibleForResuming ) ; } }
Unregister remote commands .
15,375
private ItemData initACL ( NodeData parent , NodeData node ) throws RepositoryException { return initACL ( parent , node , null ) ; }
Init ACL of the node .
15,376
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 .
15,377
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
15,378
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
15,379
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 ( ) ) { 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 ( ) ) ) { return true ; } } } return false ; }
Check Property BLOB Values if someone has null file .
15,380
public Response move ( Session session , String srcPath , String destPath ) { try { session . move ( srcPath , destPath ) ; session . save ( ) ; if ( itemExisted ) { return Response . status ( HTTPStatus . NO_CONTENT ) . cacheControl ( cacheControl ) . build ( ) ; } else { if ( uriBuilder != null ) { return Response . created ( uriBuilder . path ( session . getWorkspace ( ) . getName ( ) ) . path ( destPath ) . build ( ) ) . cacheControl ( cacheControl ) . build ( ) ; } 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 .
15,381
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 .
15,382
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 .
15,383
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 .
15,384
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 .
15,385
public void setLocal ( boolean local ) { if ( local && changesList . get ( ) == null ) { beginTransaction ( ) ; } this . local . set ( local ) ; }
Creates all ChangesBuffers with given parameter
15,386
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 .
15,387
@ Path ( "/{path:.*}/" ) public Response getResource ( @ PathParam ( "path" ) String mavenPath , final UriInfo uriInfo , final @ QueryParam ( "view" ) String view , final @ QueryParam ( "gadget" ) String gadget ) { String resourcePath = mavenRoot + mavenPath ; String shaResourcePath = mavenPath . endsWith ( ".sha1" ) ? mavenRoot + mavenPath : mavenRoot + mavenPath + ".sha1" ; mavenPath = uriInfo . getBaseUriBuilder ( ) . path ( getClass ( ) ) . path ( mavenPath ) . build ( ) . toString ( ) ; Session ses = null ; try { 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 ) { 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 .
15,388
public Response getRootNodeList ( final UriInfo uriInfo , final @ QueryParam ( "view" ) String view , final @ QueryParam ( "gadget" ) String gadget ) { return getResource ( "" , uriInfo , view , gadget ) ; }
Browsing of root node of Maven repository .
15,389
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 .
15,390
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 .
15,391
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 ) { printHeader ( ctx ) ; } CONTEXTS = Collections . unmodifiableMap ( tmpContexts ) ; } }
Register a new category of statistics to manage .
15,392
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
15,393
private static void addTriggers ( ) { if ( ! PERSISTENCE_ENABLED ) { return ; } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( "JCRStatisticsManager-Hook" ) { public void run ( ) { printData ( ) ; } } ) ; Thread t = new Thread ( "JCRStatisticsManager-Writer" ) { 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 .
15,394
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 .
15,395
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 .
15,396
private static StatisticsContext getContext ( String category ) { if ( category == null ) { return null ; } return CONTEXTS . get ( category ) ; }
Retrieve statistics context of the given category .
15,397
static String formatName ( String name ) { return name == null ? null : name . replaceAll ( " " , "" ) . replaceAll ( "[,;]" , ", " ) ; }
Format the name of the statistics in the target format
15,398
private static Statistics getStatistics ( String category , String name ) { StatisticsContext context = getContext ( category ) ; if ( context == null ) { return null ; } 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 .
15,399
@ 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 .