idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
33,300
void setFeature ( XMLReader reader , String featureName , boolean value ) { try { if ( reader . getFeature ( featureName ) != value ) { reader . setFeature ( featureName , value ) ; } } catch ( SAXException e ) { getLogger ( ) . warn ( e , "Cannot set feature " + featureName ) ; } }
Sets the reader s named feature to the supplied value only if the feature is not already set to that value . This method does nothing if the feature is not known to the reader .
33,301
public long consumeLong ( ) throws ParsingException , IllegalStateException { if ( completed ) throwNoMoreContent ( ) ; String value = currentToken ( ) . value ( ) ; try { long result = Long . parseLong ( value ) ; moveToNextToken ( ) ; return result ; } catch ( NumberFormatException e ) { Position position = currentToken ( ) . position ( ) ; String msg = CommonI18n . expectingValidLongAtLineAndColumn . text ( value , position . getLine ( ) , position . getColumn ( ) ) ; throw new ParsingException ( position , msg ) ; } }
Convert the value of this token to a long return it and move to the next token .
33,302
public String consume ( ) throws ParsingException , IllegalStateException { if ( completed ) throwNoMoreContent ( ) ; String result = currentToken ( ) . value ( ) ; moveToNextToken ( ) ; return result ; }
Return the value of this token and move to the next token .
33,303
final Token currentToken ( ) throws IllegalStateException , NoSuchElementException { if ( currentToken == null ) { if ( completed ) { throw new NoSuchElementException ( CommonI18n . noMoreContent . text ( ) ) ; } throw new IllegalStateException ( CommonI18n . startMethodMustBeCalledBeforeConsumingOrMatching . text ( ) ) ; } assert currentToken != null ; return currentToken ; }
Get the current token .
33,304
final Token previousToken ( ) throws IllegalStateException , NoSuchElementException { if ( currentToken == null ) { if ( completed ) { if ( tokens . isEmpty ( ) ) { throw new NoSuchElementException ( CommonI18n . noMoreContent . text ( ) ) ; } return tokens . get ( tokens . size ( ) - 1 ) ; } throw new IllegalStateException ( CommonI18n . startMethodMustBeCalledBeforeConsumingOrMatching . text ( ) ) ; } if ( tokenIterator . previousIndex ( ) == 0 ) { throw new NoSuchElementException ( CommonI18n . noMoreContent . text ( ) ) ; } return tokens . get ( tokenIterator . previousIndex ( ) - 1 ) ; }
Get the previous token . This does not modify the state .
33,305
static String generateFragment ( String content , int indexOfProblem , int charactersToIncludeBeforeAndAfter , String highlightText ) { assert content != null ; assert indexOfProblem < content . length ( ) ; int beforeStart = Math . max ( 0 , indexOfProblem - charactersToIncludeBeforeAndAfter ) ; String before = content . substring ( beforeStart , indexOfProblem ) ; int afterEnd = Math . min ( indexOfProblem + charactersToIncludeBeforeAndAfter , content . length ( ) ) ; String after = content . substring ( indexOfProblem , afterEnd ) ; return before + ( highlightText != null ? highlightText : "" ) + after ; }
Utility method to generate a highlighted fragment of a particular point in the stream .
33,306
protected PlanNode createCanonicalPlan ( QueryContext context , Query query ) { PlanNode plan = null ; Map < SelectorName , Table > usedSources = new HashMap < SelectorName , Table > ( ) ; plan = createPlanNode ( context , query . source ( ) , usedSources ) ; Map < String , Subquery > subqueriesByVariableName = new HashMap < String , Subquery > ( ) ; plan = attachCriteria ( context , plan , query . constraint ( ) , query . columns ( ) , subqueriesByVariableName ) ; plan = attachProject ( context , plan , query . columns ( ) , usedSources ) ; if ( query . isDistinct ( ) ) { plan = attachDuplicateRemoval ( context , plan ) ; } plan = attachSorting ( context , plan , query . orderings ( ) ) ; plan = attachLimits ( context , plan , query . getLimits ( ) ) ; if ( query . getLimits ( ) . isLimitedToSingleRowWithNoOffset ( ) && query . orderings ( ) . isEmpty ( ) ) { context . getHints ( ) . isExistsQuery = true ; } plan = attachSubqueries ( context , plan , subqueriesByVariableName ) ; validate ( context , query , usedSources ) ; for ( Subquery subquery : Visitors . subqueries ( query , false ) ) { createPlan ( context , subquery . getQuery ( ) ) ; } return plan ; }
Create a canonical query plan for the given query .
33,307
protected void validate ( QueryContext context , QueryCommand query , Map < SelectorName , Table > usedSelectors ) { Validator validator = new Validator ( context , usedSelectors ) ; query . accept ( new WalkAllVisitor ( validator ) { protected void enqueue ( Visitable objectToBeVisited ) { if ( objectToBeVisited instanceof Subquery ) return ; super . enqueue ( objectToBeVisited ) ; } } ) ; }
Validate the supplied query .
33,308
protected PlanNode createCanonicalPlan ( QueryContext context , SetQuery query ) { PlanNode left = createPlan ( context , query . getLeft ( ) ) ; PlanNode right = createPlan ( context , query . getRight ( ) ) ; PlanNode plan = new PlanNode ( Type . SET_OPERATION ) ; plan . addChildren ( left , right ) ; plan . setProperty ( Property . SET_OPERATION , query . operation ( ) ) ; plan . setProperty ( Property . SET_USE_ALL , query . isAll ( ) ) ; plan = attachSorting ( context , plan , query . orderings ( ) ) ; plan = attachLimits ( context , plan , query . getLimits ( ) ) ; if ( query . getLimits ( ) . isLimitedToSingleRowWithNoOffset ( ) && query . orderings ( ) . isEmpty ( ) ) { context . getHints ( ) . isExistsQuery = true ; } return plan ; }
Create a canonical query plan for the given set query .
33,309
protected PlanNode createPlanNode ( QueryContext context , Source source , Map < SelectorName , Table > usedSelectors ) { if ( source instanceof Selector ) { assert source instanceof AllNodes || source instanceof NamedSelector ; Selector selector = ( Selector ) source ; PlanNode node = new PlanNode ( Type . SOURCE ) ; if ( selector . hasAlias ( ) ) { node . addSelector ( selector . alias ( ) ) ; node . setProperty ( Property . SOURCE_ALIAS , selector . alias ( ) ) ; node . setProperty ( Property . SOURCE_NAME , selector . name ( ) ) ; } else { node . addSelector ( selector . name ( ) ) ; node . setProperty ( Property . SOURCE_NAME , selector . name ( ) ) ; } NameFactory nameFactory = context . getExecutionContext ( ) . getValueFactories ( ) . getNameFactory ( ) ; Table table = context . getSchemata ( ) . getTable ( selector . name ( ) . qualifiedForm ( nameFactory ) ) ; if ( table != null ) { if ( table instanceof View ) context . getHints ( ) . hasView = true ; if ( usedSelectors . put ( selector . aliasOrName ( ) , table ) != null ) { I18n msg = GraphI18n . selectorNamesMayNotBeUsedMoreThanOnce ; context . getProblems ( ) . addError ( msg , selector . aliasOrName ( ) . getString ( ) ) ; } node . setProperty ( Property . SOURCE_COLUMNS , table . getColumns ( ) ) ; } else { context . getProblems ( ) . addError ( GraphI18n . tableDoesNotExist , selector . name ( ) ) ; } return node ; } if ( source instanceof Join ) { Join join = ( Join ) source ; JoinCondition joinCondition = join . getJoinCondition ( ) ; PlanNode node = new PlanNode ( Type . JOIN ) ; node . setProperty ( Property . JOIN_TYPE , join . type ( ) ) ; node . setProperty ( Property . JOIN_ALGORITHM , JoinAlgorithm . NESTED_LOOP ) ; node . setProperty ( Property . JOIN_CONDITION , joinCondition ) ; context . getHints ( ) . hasJoin = true ; if ( join . type ( ) == JoinType . LEFT_OUTER ) { context . getHints ( ) . hasOptionalJoin = true ; } Source [ ] clauses = new Source [ ] { join . getLeft ( ) , join . getRight ( ) } ; for ( int i = 0 ; i < 2 ; i ++ ) { PlanNode sourceNode = createPlanNode ( context , clauses [ i ] , usedSelectors ) ; node . addLastChild ( sourceNode ) ; } for ( PlanNode child : node . getChildren ( ) ) { node . addSelectors ( child . getSelectors ( ) ) ; } return node ; } assert false ; return null ; }
Create a JOIN or SOURCE node that contain the source information .
33,310
protected PlanNode attachCriteria ( final QueryContext context , PlanNode plan , Constraint constraint , List < ? extends Column > columns , Map < String , Subquery > subqueriesByVariableName ) { if ( constraint == null ) return plan ; context . getHints ( ) . hasCriteria = true ; LinkedList < Constraint > andableConstraints = new LinkedList < Constraint > ( ) ; separateAndConstraints ( constraint , andableConstraints ) ; assert ! andableConstraints . isEmpty ( ) ; Map < String , String > propertyNameByAlias = new HashMap < String , String > ( ) ; for ( Column column : columns ) { if ( column . getColumnName ( ) != null && ! column . getColumnName ( ) . equals ( column . getPropertyName ( ) ) ) { propertyNameByAlias . put ( column . getColumnName ( ) , column . getPropertyName ( ) ) ; } } while ( ! andableConstraints . isEmpty ( ) ) { Constraint criteria = andableConstraints . removeLast ( ) ; criteria = PlanUtil . replaceSubqueriesWithBindVariables ( context , criteria , subqueriesByVariableName ) ; criteria = PlanUtil . replaceAliasesWithProperties ( context , criteria , propertyNameByAlias ) ; PlanNode criteriaNode = new PlanNode ( Type . SELECT ) ; criteriaNode . setProperty ( Property . SELECT_CRITERIA , criteria ) ; criteriaNode . addSelectors ( Visitors . getSelectorsReferencedBy ( criteria ) ) ; Visitors . visitAll ( criteria , new Visitors . AbstractVisitor ( ) { public void visit ( FullTextSearch obj ) { context . getHints ( ) . hasFullTextSearch = true ; } } ) ; criteriaNode . addFirstChild ( plan ) ; plan = criteriaNode ; } if ( ! subqueriesByVariableName . isEmpty ( ) ) { context . getHints ( ) . hasSubqueries = true ; } return plan ; }
Attach all criteria above the join nodes . The optimizer will push these criteria down to the appropriate source .
33,311
protected PlanNode attachLimits ( QueryContext context , PlanNode plan , Limit limit ) { if ( limit . isUnlimited ( ) ) return plan ; context . getHints ( ) . hasLimit = true ; PlanNode limitNode = new PlanNode ( Type . LIMIT ) ; boolean attach = false ; if ( limit . getOffset ( ) != 0 ) { limitNode . setProperty ( Property . LIMIT_OFFSET , limit . getOffset ( ) ) ; attach = true ; } if ( ! limit . isUnlimited ( ) ) { limitNode . setProperty ( Property . LIMIT_COUNT , limit . getRowLimit ( ) ) ; attach = true ; } if ( attach ) { limitNode . addLastChild ( plan ) ; plan = limitNode ; } return plan ; }
Attach a LIMIT node at the top of the plan tree .
33,312
protected PlanNode attachProject ( QueryContext context , PlanNode plan , List < ? extends Column > columns , Map < SelectorName , Table > selectors ) { PlanNode projectNode = new PlanNode ( Type . PROJECT ) ; List < Column > newColumns = new LinkedList < Column > ( ) ; List < String > newTypes = new ArrayList < String > ( ) ; final boolean multipleSelectors = selectors . size ( ) > 1 ; final boolean qualifyExpandedColumns = context . getHints ( ) . qualifyExpandedColumnNames ; if ( columns == null || columns . isEmpty ( ) ) { for ( Map . Entry < SelectorName , Table > entry : selectors . entrySet ( ) ) { SelectorName tableName = entry . getKey ( ) ; Table table = entry . getValue ( ) ; projectNode . addSelector ( tableName ) ; allColumnsFor ( table , tableName , newColumns , newTypes , qualifyExpandedColumns ) ; } } else { for ( Column column : columns ) { SelectorName tableName = column . selectorName ( ) ; projectNode . addSelector ( tableName ) ; Table table = selectors . get ( tableName ) ; if ( table == null ) { context . getProblems ( ) . addError ( GraphI18n . tableDoesNotExist , tableName ) ; } else { String columnName = column . getPropertyName ( ) ; if ( "*" . equals ( columnName ) || columnName == null ) { allColumnsFor ( table , tableName , newColumns , newTypes , qualifyExpandedColumns ) ; } else { if ( ! newColumns . contains ( column ) ) { if ( multipleSelectors && column . getPropertyName ( ) . equals ( column . getColumnName ( ) ) ) { column = column . withColumnName ( column . getSelectorName ( ) + "." + column . getColumnName ( ) ) ; } newColumns . add ( column ) ; org . modeshape . jcr . query . validate . Schemata . Column schemaColumn = table . getColumn ( columnName ) ; if ( schemaColumn != null ) { newTypes . add ( schemaColumn . getPropertyTypeName ( ) ) ; } else { newTypes . add ( context . getTypeSystem ( ) . getDefaultType ( ) ) ; } } } boolean validateColumnExistance = context . getHints ( ) . validateColumnExistance && ! table . hasExtraColumns ( ) ; boolean columnNameIsWildcard = columnName == null || "*" . equals ( columnName ) ; if ( ! columnNameIsWildcard && table . getColumn ( columnName ) == null && validateColumnExistance ) { context . getProblems ( ) . addError ( GraphI18n . columnDoesNotExistOnTable , columnName , tableName ) ; } } } } projectNode . setProperty ( Property . PROJECT_COLUMNS , newColumns ) ; projectNode . setProperty ( Property . PROJECT_COLUMN_TYPES , newTypes ) ; projectNode . addLastChild ( plan ) ; return projectNode ; }
Attach a PROJECT node at the top of the plan tree .
33,313
protected PlanNode attachSubqueries ( QueryContext context , PlanNode plan , Map < String , Subquery > subqueriesByVariableName ) { List < String > varNames = new ArrayList < String > ( subqueriesByVariableName . keySet ( ) ) ; Collections . sort ( varNames ) ; Collections . reverse ( varNames ) ; for ( String varName : varNames ) { Subquery subquery = subqueriesByVariableName . get ( varName ) ; PlanNode subqueryNode = createPlan ( context , subquery . getQuery ( ) ) ; setSubqueryVariableName ( subqueryNode , varName ) ; PlanNode depQuery = new PlanNode ( Type . DEPENDENT_QUERY ) ; depQuery . addChildren ( subqueryNode , plan ) ; depQuery . addSelectors ( subqueryNode . getSelectors ( ) ) ; depQuery . addSelectors ( plan . getSelectors ( ) ) ; plan = depQuery ; } return plan ; }
Attach plan nodes for each subquery resulting with the first subquery at the top of the plan tree .
33,314
public synchronized Repository getRepository ( ) throws ResourceException { if ( this . repository == null ) { LOGGER . debug ( "Deploying repository URL [{0}]" , repositoryURL ) ; this . repository = deployRepository ( repositoryURL ) ; } return this . repository ; }
Provides access to the configured repository .
33,315
public Object createConnectionFactory ( ConnectionManager cxManager ) throws ResourceException { JcrRepositoryHandle handle = new JcrRepositoryHandle ( this , cxManager ) ; return handle ; }
Creates a Connection Factory instance .
33,316
protected static void validate ( IndexDefinition defn , Problems problems ) { if ( ! defn . hasSingleColumn ( ) ) { problems . addError ( JcrI18n . localIndexProviderDoesNotSupportMultiColumnIndexes , defn . getName ( ) , defn . getProviderName ( ) ) ; } switch ( defn . getKind ( ) ) { case TEXT : problems . addError ( JcrI18n . localIndexProviderDoesNotSupportTextIndexes , defn . getName ( ) , defn . getProviderName ( ) ) ; } }
Validate whether the index definition is acceptable for this provider .
33,317
public boolean add ( T entry ) { assert entry != null ; if ( ! addEntries . get ( ) ) return false ; try { producerLock . lock ( ) ; long position = cursor . claim ( ) ; int index = ( int ) ( position & mask ) ; buffer [ index ] = entry ; return cursor . publish ( position ) ; } finally { producerLock . unlock ( ) ; } }
Add to this buffer a single entry . This method blocks if there is no room in the ring buffer providing back pressure on the caller in such cases . Note that if this method blocks for any length of time that means at least one consumer has yet to process all of the entries that are currently in the ring buffer . In such cases consider whether a larger ring buffer is warranted .
33,318
public boolean add ( T [ ] entries ) { assert entries != null ; if ( entries . length == 0 || ! addEntries . get ( ) ) return false ; try { producerLock . lock ( ) ; long position = cursor . claim ( entries . length ) ; for ( int i = 0 ; i != entries . length ; ++ i ) { int index = ( int ) ( position & mask ) ; buffer [ index ] = entries [ i ] ; } return cursor . publish ( position ) ; } finally { producerLock . unlock ( ) ; } }
Add to this buffer multiple entries . This method blocks until it is added .
33,319
public boolean remove ( C consumer ) { if ( consumer != null ) { ConsumerRunner match = null ; for ( ConsumerRunner runner : consumers ) { if ( runner . getConsumer ( ) . equals ( consumer ) ) { match = runner ; break ; } } if ( match != null ) { match . close ( ) ; return true ; } } return false ; }
Remove the supplied consumer and block until it stops running and is closed and removed from this buffer . The consumer is removed at the earliest conevenient point and will stop seeing entries as soon as it is removed .
33,320
public void shutdown ( ) { this . addEntries . set ( false ) ; this . cursor . complete ( ) ; if ( this . gcConsumer != null ) this . gcConsumer . close ( ) ; for ( ConsumerRunner runner : new HashSet < > ( consumers ) ) { runner . waitForCompletion ( ) ; } assert consumers . isEmpty ( ) ; }
Shutdown this ring buffer by preventing any further entries but allowing all existing entries to be processed by all consumers .
33,321
public void put ( String name , Object value ) { if ( value instanceof EsRequest ) { document . setDocument ( name , ( ( EsRequest ) value ) . document ) ; } else { document . set ( name , value ) ; } }
Adds single property value .
33,322
public void put ( String name , Object [ ] values ) { if ( values instanceof EsRequest [ ] ) { Object [ ] docs = new Object [ values . length ] ; for ( int i = 0 ; i < docs . length ; i ++ ) { docs [ i ] = ( ( EsRequest ) values [ i ] ) . document ; } document . setArray ( name , docs ) ; } else { document . setArray ( name , values ) ; } }
Adds multivalued property value .
33,323
public static boolean isValidName ( String name ) { if ( name == null || name . length ( ) == 0 ) return false ; CharacterIterator iter = new StringCharacterIterator ( name ) ; char c = iter . first ( ) ; if ( ! isValidNameStart ( c ) ) return false ; while ( c != CharacterIterator . DONE ) { if ( ! isValidName ( c ) ) return false ; c = iter . next ( ) ; } return true ; }
Determine if the supplied name is a valid XML Name .
33,324
public static boolean isValidNcName ( String name ) { if ( name == null || name . length ( ) == 0 ) return false ; CharacterIterator iter = new StringCharacterIterator ( name ) ; char c = iter . first ( ) ; if ( ! isValidNcNameStart ( c ) ) return false ; while ( c != CharacterIterator . DONE ) { if ( ! isValidNcName ( c ) ) return false ; c = iter . next ( ) ; } return true ; }
Determine if the supplied name is a valid XML NCName .
33,325
protected final QueryEngine queryEngine ( ) { if ( queryEngine == null ) { try { engineInitLock . lock ( ) ; if ( queryEngine == null ) { QueryEngineBuilder builder = null ; if ( ! repoConfig . getIndexProviders ( ) . isEmpty ( ) ) { builder = IndexQueryEngine . builder ( ) ; logger . debug ( "Queries with indexes are enabled for the '{0}' repository. Executing queries may require scanning the repository contents when the query cannot use the defined indexes." , repoConfig . getName ( ) ) ; } else { builder = ScanningQueryEngine . builder ( ) ; logger . debug ( "Queries with no indexes are enabled for the '{0}' repository. Executing queries will always scan the repository contents." , repoConfig . getName ( ) ) ; } queryEngine = builder . using ( repoConfig , indexManager , runningState . context ( ) ) . build ( ) ; } } finally { engineInitLock . unlock ( ) ; } } return queryEngine ; }
Obtain the query engine which is created lazily and in a thread - safe manner .
33,326
protected void reindexIfNeeded ( boolean async , final boolean includeSystemContent ) { final ScanningRequest request = toBeScanned . drain ( ) ; if ( ! request . isEmpty ( ) ) { final RepositoryCache repoCache = runningState . repositoryCache ( ) ; scan ( async , ( ) -> { ScanOperation op = ( workspaceName , path , writer ) -> { NodeCache workspaceCache = repoCache . getWorkspaceCache ( workspaceName ) ; if ( workspaceCache != null ) { CachedNode node = workspaceCache . getNode ( workspaceCache . getRootKey ( ) ) ; if ( ! path . isRoot ( ) ) { for ( Segment segment : path ) { ChildReference child = node . getChildReferences ( workspaceCache ) . getChild ( segment ) ; if ( child == null ) { node = null ; break ; } node = workspaceCache . getNode ( child ) ; if ( node == null ) break ; } } if ( node != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Performing full reindexing for repository '{0}' and workspace '{1}'" , repoCache . getName ( ) , workspaceName ) ; } boolean scanSystemContent = includeSystemContent || repoCache . getSystemWorkspaceName ( ) . equals ( workspaceName ) ; updateIndexesStatus ( workspaceName , IndexManager . IndexStatus . ENABLED , IndexManager . IndexStatus . REINDEXING ) ; if ( reindexContent ( workspaceName , workspaceCache , node , Integer . MAX_VALUE , scanSystemContent , writer ) ) { commitChanges ( workspaceName ) ; } updateIndexesStatus ( workspaceName , IndexManager . IndexStatus . REINDEXING , IndexManager . IndexStatus . ENABLED ) ; } } } ; request . onEachPathInWorkspace ( op ) ; return null ; } ) ; } }
Reindex the repository only if there is at least one provider that required scanning and reindexing .
33,327
protected void cleanAndReindex ( boolean async ) { final IndexWriter writer = getIndexWriter ( ) ; scan ( async , getIndexWriter ( ) , new Callable < Void > ( ) { @ SuppressWarnings ( "synthetic-access" ) public Void call ( ) throws Exception { writer . clearAllIndexes ( ) ; reindexContent ( true , writer ) ; return null ; } } ) ; }
Clean all indexes and reindex all content .
33,328
private void reindexContent ( boolean includeSystemContent , IndexWriter indexes ) { if ( indexes . canBeSkipped ( ) ) return ; RepositoryCache repoCache = runningState . repositoryCache ( ) ; logger . debug ( JcrI18n . reindexAll . text ( runningState . name ( ) ) ) ; if ( includeSystemContent ) { String systemWorkspaceName = repoCache . getSystemWorkspaceName ( ) ; updateIndexesStatus ( systemWorkspaceName , IndexManager . IndexStatus . ENABLED , IndexManager . IndexStatus . REINDEXING ) ; NodeCache systemWorkspaceCache = repoCache . getWorkspaceCache ( systemWorkspaceName ) ; CachedNode rootNode = systemWorkspaceCache . getNode ( repoCache . getSystemKey ( ) ) ; logger . debug ( "Starting reindex of system content in '{0}' repository." , runningState . name ( ) ) ; if ( reindexSystemContent ( rootNode , Integer . MAX_VALUE , indexes ) ) { commitChanges ( systemWorkspaceName ) ; } logger . debug ( "Completed reindex of system content in '{0}' repository." , runningState . name ( ) ) ; updateIndexesStatus ( systemWorkspaceName , IndexManager . IndexStatus . REINDEXING , IndexManager . IndexStatus . ENABLED ) ; } for ( String workspaceName : repoCache . getWorkspaceNames ( ) ) { updateIndexesStatus ( workspaceName , IndexManager . IndexStatus . ENABLED , IndexManager . IndexStatus . REINDEXING ) ; NodeCache workspaceCache = repoCache . getWorkspaceCache ( workspaceName ) ; CachedNode rootNode = workspaceCache . getNode ( workspaceCache . getRootKey ( ) ) ; logger . debug ( "Starting reindex of workspace '{0}' content in '{1}' repository." , runningState . name ( ) , workspaceName ) ; if ( reindexContent ( workspaceName , workspaceCache , rootNode , Integer . MAX_VALUE , false , indexes ) ) { commitChanges ( workspaceName ) ; } logger . debug ( "Completed reindex of workspace '{0}' content in '{1}' repository." , runningState . name ( ) , workspaceName ) ; updateIndexesStatus ( workspaceName , IndexManager . IndexStatus . REINDEXING , IndexManager . IndexStatus . ENABLED ) ; } }
Crawl and index all of the repository content .
33,329
public void reindexContent ( JcrWorkspace workspace , Path path , int depth ) { if ( getIndexWriter ( ) . canBeSkipped ( ) ) { return ; } CheckArg . isPositive ( depth , "depth" ) ; JcrSession session = workspace . getSession ( ) ; NodeCache cache = session . cache ( ) . getWorkspace ( ) ; String workspaceName = workspace . getName ( ) ; CachedNode node = cache . getNode ( cache . getRootKey ( ) ) ; for ( Segment segment : path ) { ChildReference ref = node . getChildReferences ( cache ) . getChild ( segment ) ; if ( ref == null ) return ; node = cache . getNode ( ref ) ; } updateIndexesStatus ( workspaceName , IndexManager . IndexStatus . ENABLED , IndexManager . IndexStatus . REINDEXING ) ; RepositoryCache repoCache = runningState . repositoryCache ( ) ; String systemWorkspaceName = repoCache . getSystemWorkspaceName ( ) ; String systemWorkspaceKey = repoCache . getSystemWorkspaceKey ( ) ; if ( node . getKey ( ) . getWorkspaceKey ( ) . equals ( systemWorkspaceKey ) ) { if ( reindexSystemContent ( node , depth , getIndexWriter ( ) ) ) { commitChanges ( systemWorkspaceName ) ; } } else { if ( reindexContent ( workspaceName , cache , node , depth , path . isRoot ( ) , getIndexWriter ( ) ) ) { commitChanges ( workspaceName ) ; } } updateIndexesStatus ( workspaceName , IndexManager . IndexStatus . REINDEXING , IndexManager . IndexStatus . ENABLED ) ; }
Crawl and index the content starting at the supplied path in the named workspace to the designated depth .
33,330
public Future < Boolean > reindexContentAsync ( final JcrWorkspace workspace ) { return indexingExecutorService . submit ( ( ) -> { reindexContent ( workspace ) ; return Boolean . TRUE ; } ) ; }
Asynchronously crawl and index the content in the named workspace .
33,331
public Future < Boolean > reindexContentAsync ( final JcrWorkspace workspace , final Path path , final int depth ) { return indexingExecutorService . submit ( ( ) -> { reindexContent ( workspace , path , depth ) ; return Boolean . TRUE ; } ) ; }
Asynchronously crawl and index the content starting at the supplied path in the named workspace to the designated depth .
33,332
public void register ( Map < String , String > namespaceUrisByPrefix ) { if ( namespaceUrisByPrefix == null || namespaceUrisByPrefix . isEmpty ( ) ) return ; final Lock lock = this . namespacesLock . writeLock ( ) ; try { lock . lock ( ) ; SystemContent systemContent = systemContent ( false ) ; systemContent . registerNamespaces ( namespaceUrisByPrefix ) ; systemContent . save ( ) ; for ( Map . Entry < String , String > entry : namespaceUrisByPrefix . entrySet ( ) ) { String prefix = entry . getKey ( ) . trim ( ) ; String uri = entry . getValue ( ) . trim ( ) ; if ( prefix . length ( ) == 0 ) continue ; this . cache . register ( prefix , uri ) ; } } finally { lock . unlock ( ) ; } }
Register a set of namespaces .
33,333
public static ReferrerCounts create ( Map < NodeKey , Integer > strongCountsByReferrerKey , Map < NodeKey , Integer > weakCountsByReferrerKey ) { if ( strongCountsByReferrerKey == null ) strongCountsByReferrerKey = EMPTY_COUNTS ; if ( weakCountsByReferrerKey == null ) weakCountsByReferrerKey = EMPTY_COUNTS ; if ( strongCountsByReferrerKey . isEmpty ( ) && weakCountsByReferrerKey . isEmpty ( ) ) return null ; return new ReferrerCounts ( strongCountsByReferrerKey , weakCountsByReferrerKey ) ; }
Create a new instance of the snapshot .
33,334
protected void process ( XSDSchema schema , String encoding , long contentSize , Node rootNode ) throws Exception { assert schema != null ; logger . debug ( "Target namespace: '{0}'" , schema . getTargetNamespace ( ) ) ; rootNode . setProperty ( SrampLexicon . CONTENT_TYPE , MimeTypeConstants . APPLICATION_XML ) ; if ( encoding != null ) { rootNode . setProperty ( SrampLexicon . CONTENT_ENCODING , encoding ) ; } rootNode . setProperty ( SrampLexicon . CONTENT_SIZE , contentSize ) ; @ SuppressWarnings ( "unchecked" ) List < XSDAnnotation > annotations = schema . getAnnotations ( ) ; processAnnotations ( annotations , rootNode ) ; processNonSchemaAttributes ( schema , rootNode , Collections . < String > emptySet ( ) ) ; for ( EObject obj : schema . eContents ( ) ) { if ( obj instanceof XSDSimpleTypeDefinition ) { processSimpleTypeDefinition ( ( XSDSimpleTypeDefinition ) obj , rootNode ) ; } else if ( obj instanceof XSDComplexTypeDefinition ) { processComplexTypeDefinition ( ( XSDComplexTypeDefinition ) obj , rootNode ) ; } else if ( obj instanceof XSDElementDeclaration ) { processElementDeclaration ( ( XSDElementDeclaration ) obj , rootNode ) ; } else if ( obj instanceof XSDAttributeDeclaration ) { processAttributeDeclaration ( ( XSDAttributeDeclaration ) obj , rootNode , false ) ; } else if ( obj instanceof XSDImport ) { processImport ( ( XSDImport ) obj , rootNode ) ; } else if ( obj instanceof XSDInclude ) { processInclude ( ( XSDInclude ) obj , rootNode ) ; } else if ( obj instanceof XSDRedefine ) { processRedefine ( ( XSDRedefine ) obj , rootNode ) ; } else if ( obj instanceof XSDAttributeGroupDefinition ) { processAttributeGroupDefinition ( ( XSDAttributeGroupDefinition ) obj , rootNode ) ; } else if ( obj instanceof XSDAnnotation ) { } } resolveReferences ( ) ; }
Read an XSDSchema instance and create the node hierarchy under the given root node .
33,335
public void externalNodeRemoved ( String externalNodeKey ) { if ( this . snapshot . get ( ) . containsProjectionForExternalNode ( externalNodeKey ) ) { synchronized ( this ) { Snapshot current = this . snapshot . get ( ) ; Snapshot updated = current . withoutProjection ( externalNodeKey ) ; if ( current != updated ) { this . snapshot . compareAndSet ( current , updated ) ; } } } }
Signals that an external node with the given key has been removed .
33,336
public void internalNodeRemoved ( String internalNodeKey ) { if ( this . snapshot . get ( ) . containsProjectionForInternalNode ( internalNodeKey ) ) { synchronized ( this ) { Snapshot current = this . snapshot . get ( ) ; Snapshot updated = current ; for ( Projection projection : current . getProjections ( ) ) { if ( internalNodeKey . equalsIgnoreCase ( projection . getProjectedNodeKey ( ) ) ) { String externalNodeKey = projection . getExternalNodeKey ( ) ; removeStoredProjection ( externalNodeKey ) ; updated = updated . withoutProjection ( externalNodeKey ) ; } } if ( current != updated ) { this . snapshot . compareAndSet ( current , updated ) ; } } } }
Signals that an internal node with the given key has been removed .
33,337
public Connector getConnectorForSourceName ( String sourceName ) { assert sourceName != null ; return this . snapshot . get ( ) . getConnectorWithSourceKey ( NodeKey . keyForSourceName ( sourceName ) ) ; }
Returns a connector which was registered for the given source name .
33,338
public DocumentTranslator getDocumentTranslator ( ) { if ( translator == null ) { translator = repository . repositoryCache ( ) . getDocumentTranslator ( ) . withLargeStringSize ( Long . MAX_VALUE ) ; } return translator ; }
Returns the repository s document translator .
33,339
void start ( ScheduledExecutorService service ) { if ( rollupFuture . get ( ) != null ) { return ; } durations . put ( DurationMetric . QUERY_EXECUTION_TIME , new DurationHistory ( TimeUnit . MILLISECONDS , MAXIMUM_LONG_RUNNING_QUERY_COUNT ) ) ; durations . put ( DurationMetric . SEQUENCER_EXECUTION_TIME , new DurationHistory ( TimeUnit . MILLISECONDS , MAXIMUM_LONG_RUNNING_SEQUENCING_COUNT ) ) ; durations . put ( DurationMetric . SESSION_LIFETIME , new DurationHistory ( TimeUnit . MILLISECONDS , MAXIMUM_LONG_RUNNING_SESSION_COUNT ) ) ; for ( ValueMetric metric : EnumSet . allOf ( ValueMetric . class ) ) { boolean resetUponRollup = ! metric . isContinuous ( ) ; values . put ( metric , new ValueHistory ( resetUponRollup ) ) ; } DateTime now = timeFactory . create ( ) ; this . weeksStartTime . compareAndSet ( null , now ) ; this . daysStartTime . compareAndSet ( null , now ) ; this . hoursStartTime . compareAndSet ( null , now ) ; this . minutesStartTime . compareAndSet ( null , now ) ; this . secondsStartTime . compareAndSet ( null , now ) ; rollup ( ) ; this . rollupFuture . set ( service . scheduleAtFixedRate ( new Runnable ( ) { @ SuppressWarnings ( "synthetic-access" ) public void run ( ) { rollup ( ) ; } } , CAPTURE_DELAY_IN_SECONDS , CAPTURE_INTERVAL_IN_SECONDS , TimeUnit . SECONDS ) ) ; }
Start recording statistics .
33,340
void stop ( ) { ScheduledFuture < ? > future = this . rollupFuture . getAndSet ( null ) ; if ( future != null && ! future . isDone ( ) && ! future . isCancelled ( ) ) { future . cancel ( false ) ; } }
Stop recording statistics .
33,341
@ SuppressWarnings ( "fallthrough" ) private void rollup ( ) { DateTime now = timeFactory . create ( ) ; Window largest = null ; for ( DurationHistory history : durations . values ( ) ) { largest = history . rollup ( ) ; } for ( ValueHistory history : values . values ( ) ) { largest = history . rollup ( ) ; } if ( largest == null ) return ; switch ( largest ) { case PREVIOUS_52_WEEKS : this . weeksStartTime . set ( now ) ; case PREVIOUS_7_DAYS : this . daysStartTime . set ( now ) ; case PREVIOUS_24_HOURS : this . hoursStartTime . set ( now ) ; case PREVIOUS_60_MINUTES : this . minutesStartTime . set ( now ) ; case PREVIOUS_60_SECONDS : this . secondsStartTime . set ( now ) ; } }
Method called once every second by the scheduled job .
33,342
public void increment ( ValueMetric metric , long incrementalValue ) { assert metric != null ; ValueHistory history = values . get ( metric ) ; if ( history != null ) history . recordIncrement ( incrementalValue ) ; }
Record an incremental change to a value called by the code that knows when and how the metric changes .
33,343
public void set ( ValueMetric metric , long value ) { assert metric != null ; ValueHistory history = values . get ( metric ) ; if ( history != null ) history . recordNewValue ( value ) ; }
Record a specific value for a metric called by the code that knows when and how the metric changes .
33,344
void recordDuration ( DurationMetric metric , long duration , TimeUnit timeUnit , Map < String , String > payload ) { assert metric != null ; DurationHistory history = durations . get ( metric ) ; if ( history != null ) history . recordDuration ( duration , timeUnit , payload ) ; }
Record a new duration for the given metric called by the code that knows about the duration .
33,345
public static Statistics statisticsFor ( long [ ] values ) { int length = values . length ; if ( length == 0 ) return EMPTY_STATISTICS ; if ( length == 1 ) return statisticsFor ( values [ 0 ] ) ; long total = 0L ; long max = Long . MIN_VALUE ; long min = Long . MAX_VALUE ; for ( long value : values ) { total += value ; max = Math . max ( max , value ) ; min = Math . min ( min , value ) ; } double mean = ( ( double ) total ) / length ; double varianceSquared = 0.0d ; double distance = 0.0d ; for ( long value : values ) { distance = mean - value ; varianceSquared = varianceSquared + ( distance * distance ) ; } return new StatisticsImpl ( length , min , max , mean , Math . sqrt ( varianceSquared ) ) ; }
Utility method to construct the statistics for a series of values .
33,346
public static Statistics statisticsFor ( Statistics [ ] statistics ) { int length = statistics . length ; if ( length == 0 ) return EMPTY_STATISTICS ; if ( length == 1 ) return statistics [ 0 ] != null ? statistics [ 0 ] : EMPTY_STATISTICS ; int count = 0 ; long max = Long . MIN_VALUE ; long min = Long . MAX_VALUE ; double mean = 0.0d ; double variance = 0.0d ; for ( Statistics stat : statistics ) { if ( stat == null ) continue ; count += stat . getCount ( ) ; max = Math . max ( max , stat . getMaximum ( ) ) ; min = Math . min ( min , stat . getMinimum ( ) ) ; mean = mean + ( stat . getMean ( ) * stat . getCount ( ) ) ; } mean = mean / count ; double meanDelta = 0.0d ; for ( Statistics stat : statistics ) { if ( stat == null ) continue ; meanDelta = stat . getMean ( ) - mean ; variance = variance + ( stat . getCount ( ) * ( stat . getVariance ( ) + ( meanDelta * meanDelta ) ) ) ; } return new StatisticsImpl ( count , min , max , mean , variance ) ; }
Utility method to construct the composite statistics for a series of sampled statistics .
33,347
public void setRecordsAmount ( int amount ) { int ipp = Integer . parseInt ( itemsPerPageEditor . getValueAsString ( ) ) ; pageTotal = amount % ipp == 0 ? amount / ipp : amount / ipp + 1 ; draw ( 0 ) ; }
Assigns total number of records .
33,348
public List < ParsingResult > parseUsing ( final String ddl , final String firstParserId , final String secondParserId , final String ... additionalParserIds ) throws ParsingException { CheckArg . isNotEmpty ( firstParserId , "firstParserId" ) ; CheckArg . isNotEmpty ( secondParserId , "secondParserId" ) ; if ( additionalParserIds != null ) { CheckArg . containsNoNulls ( additionalParserIds , "additionalParserIds" ) ; } final int numParsers = ( ( additionalParserIds == null ) ? 2 : ( additionalParserIds . length + 2 ) ) ; final List < DdlParser > selectedParsers = new ArrayList < DdlParser > ( numParsers ) ; { final DdlParser parser = getParser ( firstParserId ) ; if ( parser == null ) { throw new ParsingException ( Position . EMPTY_CONTENT_POSITION , DdlSequencerI18n . unknownParser . text ( firstParserId ) ) ; } selectedParsers . add ( parser ) ; } { final DdlParser parser = getParser ( secondParserId ) ; if ( parser == null ) { throw new ParsingException ( Position . EMPTY_CONTENT_POSITION , DdlSequencerI18n . unknownParser . text ( secondParserId ) ) ; } selectedParsers . add ( parser ) ; } if ( ( additionalParserIds != null ) && ( additionalParserIds . length != 0 ) ) { for ( final String id : additionalParserIds ) { final DdlParser parser = getParser ( id ) ; if ( parser == null ) { throw new ParsingException ( Position . EMPTY_CONTENT_POSITION , DdlSequencerI18n . unknownParser . text ( id ) ) ; } selectedParsers . add ( parser ) ; } } return parseUsing ( ddl , selectedParsers ) ; }
Parse the supplied DDL using multiple parsers returning the result of each parser with its score in the order of highest scoring to lowest scoring .
33,349
public ResolvedRequest withPath ( String path ) { assert repositoryName != null ; assert workspaceName != null ; return new ResolvedRequest ( request , repositoryName , workspaceName , path ) ; }
Create a new request that is similar to this request except with the supplied path . This can only be done if the repository name and workspace name are non - null
33,350
public String findJcrName ( String cmisName ) { for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list . get ( i ) . cmisName != null && list . get ( i ) . cmisName . equals ( cmisName ) ) { return list . get ( i ) . jcrName ; } } return cmisName ; }
Determines the name of the given property from cmis domain in jcr domain .
33,351
public String findCmisName ( String jcrName ) { for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list . get ( i ) . jcrName != null && list . get ( i ) . jcrName . equals ( jcrName ) ) { return list . get ( i ) . cmisName ; } } return jcrName ; }
Determines the name of the given property from jcr domain in cmis domain .
33,352
public int getJcrType ( PropertyType propertyType ) { switch ( propertyType ) { case BOOLEAN : return javax . jcr . PropertyType . BOOLEAN ; case DATETIME : return javax . jcr . PropertyType . DATE ; case DECIMAL : return javax . jcr . PropertyType . DECIMAL ; case HTML : return javax . jcr . PropertyType . STRING ; case INTEGER : return javax . jcr . PropertyType . LONG ; case URI : return javax . jcr . PropertyType . URI ; case ID : return javax . jcr . PropertyType . STRING ; default : return javax . jcr . PropertyType . UNDEFINED ; } }
Converts type of property .
33,353
public Object [ ] jcrValues ( Property < ? > property ) { @ SuppressWarnings ( "unchecked" ) List < Object > values = ( List < Object > ) property . getValues ( ) ; switch ( property . getType ( ) ) { case STRING : return asStrings ( values ) ; case BOOLEAN : return asBooleans ( values ) ; case DECIMAL : return asDecimals ( values ) ; case INTEGER : return asIntegers ( values ) ; case DATETIME : return asDateTime ( values ) ; case URI : return asURI ( values ) ; case ID : return asIDs ( values ) ; case HTML : return asHTMLs ( values ) ; default : return null ; } }
Converts value of the property for the jcr domain .
33,354
private Boolean [ ] asBooleans ( List < Object > values ) { ValueFactory < Boolean > factory = valueFactories . getBooleanFactory ( ) ; Boolean [ ] res = new Boolean [ values . size ( ) ] ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = factory . create ( values . get ( i ) ) ; } return res ; }
Converts CMIS value of boolean type into JCR value of boolean type .
33,355
private Long [ ] asIntegers ( List < Object > values ) { ValueFactory < Long > factory = valueFactories . getLongFactory ( ) ; Long [ ] res = new Long [ values . size ( ) ] ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = factory . create ( values . get ( i ) ) ; } return res ; }
Converts CMIS value of integer type into JCR value of boolean type .
33,356
private BigDecimal [ ] asDecimals ( List < Object > values ) { ValueFactory < BigDecimal > factory = valueFactories . getDecimalFactory ( ) ; BigDecimal [ ] res = new BigDecimal [ values . size ( ) ] ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = factory . create ( values . get ( i ) ) ; } return res ; }
Converts CMIS value of decimal type into JCR value of boolean type .
33,357
private URI [ ] asURI ( List < Object > values ) { ValueFactory < URI > factory = valueFactories . getUriFactory ( ) ; URI [ ] res = new URI [ values . size ( ) ] ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = factory . create ( ( ( GregorianCalendar ) values . get ( i ) ) . getTime ( ) ) ; } return res ; }
Converts CMIS value of URI type into JCR value of URI type .
33,358
private String [ ] asIDs ( List < Object > values ) { ValueFactory < String > factory = valueFactories . getStringFactory ( ) ; String [ ] res = new String [ values . size ( ) ] ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = factory . create ( values . get ( i ) ) ; } return res ; }
Converts CMIS value of ID type into JCR value of String type .
33,359
protected void workspaceAdded ( String workspaceName ) { String workspaceKey = NodeKey . keyForWorkspaceName ( workspaceName ) ; if ( systemWorkspaceKey . equals ( workspaceKey ) ) { return ; } Collection < SequencingConfiguration > configs = new LinkedList < SequencingConfiguration > ( ) ; for ( Sequencer sequencer : sequencersById . values ( ) ) { boolean updated = false ; for ( SequencerPathExpression expression : pathExpressionsBySequencerId . get ( sequencer . getUniqueId ( ) ) ) { if ( expression . appliesToWorkspace ( workspaceName ) ) { updated = true ; configs . add ( new SequencingConfiguration ( expression , sequencer ) ) ; } } if ( DEBUG && updated ) { LOGGER . debug ( "Updated sequencer '{0}' (id={1}) configuration due to new workspace '{2}' in repository '{3}'" , sequencer . getName ( ) , sequencer . getUniqueId ( ) , workspaceName , repository . name ( ) ) ; } } if ( configs . isEmpty ( ) ) return ; try { configChangeLock . lock ( ) ; Map < String , Collection < SequencingConfiguration > > configByWorkspaceName = new HashMap < String , Collection < SequencingConfiguration > > ( this . configByWorkspaceName ) ; configByWorkspaceName . put ( workspaceName , configs ) ; this . configByWorkspaceName = configByWorkspaceName ; } finally { configChangeLock . unlock ( ) ; } }
Signal that a new workspace was added .
33,360
protected void workspaceRemoved ( String workspaceName ) { try { configChangeLock . lock ( ) ; Map < String , Collection < SequencingConfiguration > > configByWorkspaceName = new HashMap < String , Collection < SequencingConfiguration > > ( this . configByWorkspaceName ) ; if ( configByWorkspaceName . remove ( workspaceName ) != null ) { this . configByWorkspaceName = configByWorkspaceName ; } } finally { configChangeLock . unlock ( ) ; } }
Signal that a new workspace was removed .
33,361
public static void register ( String name , Object obj ) { register ( name , obj , null , null , null , null ) ; }
A convenience method that registers the supplied object with the supplied name .
33,362
public Set < Name > getMixinTypes ( ) { if ( types . length == 1 ) { return Collections . emptySet ( ) ; } return new HashSet < Name > ( Arrays . asList ( Arrays . copyOfRange ( types , 1 , types . length ) ) ) ; }
Returns the mixins for this node .
33,363
private boolean hasModifierNamed ( String modifierName ) { for ( ModifierMetadata modifier : modifiers ) { if ( modifierName . equalsIgnoreCase ( modifier . getName ( ) ) ) { return true ; } } return false ; }
Checks if a modifier with the given name is found among this method s identifiers .
33,364
public double getMedianValue ( ) { Lock lock = this . getLock ( ) . writeLock ( ) ; try { lock . lock ( ) ; int count = this . values . size ( ) ; if ( count == 0 ) { return 0.0d ; } if ( this . medianValue == null ) { Comparator < T > comparator = this . math . getComparator ( ) ; Collections . sort ( this . values , comparator ) ; this . medianValue = 0.0d ; if ( count == 1 ) { this . medianValue = this . values . get ( 0 ) . doubleValue ( ) ; } else if ( count % 2 != 0 ) { this . medianValue = this . values . get ( ( ( count + 1 ) / 2 ) - 1 ) . doubleValue ( ) ; } else { int upperMiddleValueIndex = count / 2 ; int lowerMiddleValueIndex = upperMiddleValueIndex - 1 ; double lowerValue = this . values . get ( lowerMiddleValueIndex ) . doubleValue ( ) ; double upperValue = this . values . get ( upperMiddleValueIndex ) . doubleValue ( ) ; this . medianValue = ( lowerValue + upperValue ) / 2.0d ; } this . median = this . math . create ( this . medianValue ) ; this . histogram = null ; } } finally { lock . unlock ( ) ; } return this . medianValue ; }
Return the median value .
33,365
public double getStandardDeviation ( ) { Lock lock = this . getLock ( ) . readLock ( ) ; lock . lock ( ) ; try { return this . sigma ; } finally { lock . unlock ( ) ; } }
Return the standard deviation . The standard deviation is a measure of the variation in a series of values . Values with a lower standard deviation has less variance in the values than a series of values with a higher standard deviation .
33,366
public org . modeshape . jcr . api . Problems backupRepository ( File backupDirectory , BackupOptions options ) throws RepositoryException { final BackupActivity backupActivity = createBackupActivity ( backupDirectory , options ) ; try { if ( runningState . suspendExistingUserTransaction ( ) ) { LOGGER . debug ( "Suspended existing active user transaction before the backup operation starts" ) ; } try { return new JcrProblems ( backupActivity . execute ( ) ) ; } finally { runningState . resumeExistingUserTransaction ( ) ; } } catch ( SystemException e ) { throw new RuntimeException ( e ) ; } }
Start backing up the repository .
33,367
public org . modeshape . jcr . api . Problems restoreRepository ( final JcrRepository repository , final File backupDirectory , final RestoreOptions options ) throws RepositoryException { final String backupLocString = backupDirectory . getAbsolutePath ( ) ; LOGGER . debug ( "Beginning restore of '{0}' repository from {1} with options {2}" , repository . getName ( ) , backupLocString , options ) ; repository . prepareToRestore ( ) ; final RestoreActivity restoreActivity = createRestoreActivity ( backupDirectory , options ) ; org . modeshape . jcr . api . Problems problems = null ; try { if ( runningState . suspendExistingUserTransaction ( ) ) { LOGGER . debug ( "Suspended existing active user transaction before the restore operation starts" ) ; } problems = new JcrProblems ( restoreActivity . execute ( ) ) ; if ( ! problems . hasProblems ( ) ) { try { repository . completeRestore ( options ) ; } catch ( Throwable t ) { restoreActivity . problems . addError ( t , JcrI18n . repositoryCannotBeRestartedAfterRestore , repository . getName ( ) , t . getMessage ( ) ) ; } finally { runningState . resumeExistingUserTransaction ( ) ; } } } catch ( SystemException e ) { throw new RuntimeException ( e ) ; } LOGGER . debug ( "Completed restore of '{0}' repository from {1}" , repository . getName ( ) , backupLocString ) ; return problems ; }
Start asynchronously backing up the repository .
33,368
protected final Metadata prepareMetadata ( final Binary binary , final Context context ) throws IOException , RepositoryException { Metadata metadata = new Metadata ( ) ; String mimeType = binary . getMimeType ( ) ; if ( StringUtil . isBlank ( mimeType ) ) { mimeType = context . mimeTypeOf ( null , binary ) ; } if ( ! StringUtil . isBlank ( mimeType ) ) { metadata . set ( Metadata . CONTENT_TYPE , mimeType ) ; } return metadata ; }
Creates a new tika metadata object used by the parser . This will contain the mime - type of the content being parsed if this is available to the underlying context . If not Tika s autodetection mechanism is used to try and get the mime - type .
33,369
private List < ServerAddress > convertToServerAddresses ( Set < String > addresses ) { return addresses . stream ( ) . map ( this :: stringToServerAddress ) . filter ( Objects :: nonNull ) . collect ( Collectors . toList ( ) ) ; }
Converts list of addresses specified in text format to mongodb specific address .
33,370
private void setAttribute ( DBCollection content , String fieldName , Object value ) { DBObject header = content . findOne ( HEADER_QUERY ) ; BasicDBObject newHeader = new BasicDBObject ( ) ; newHeader . put ( FIELD_CHUNK_TYPE , header . get ( FIELD_CHUNK_TYPE ) ) ; newHeader . put ( FIELD_MIME_TYPE , header . get ( FIELD_MIME_TYPE ) ) ; newHeader . put ( FIELD_EXTRACTED_TEXT , header . get ( FIELD_EXTRACTED_TEXT ) ) ; newHeader . put ( FIELD_UNUSED , header . get ( FIELD_UNUSED ) ) ; newHeader . put ( FIELD_UNUSED_SINCE , header . get ( FIELD_UNUSED_SINCE ) ) ; newHeader . put ( fieldName , value ) ; content . update ( HEADER_QUERY , newHeader ) ; }
Modifies content header .
33,371
private Object getAttribute ( DBCollection content , String fieldName ) { return content . findOne ( HEADER_QUERY ) . get ( fieldName ) ; }
Gets attribute s value .
33,372
private boolean isExpired ( DBCollection content , long deadline ) { Long unusedSince = ( Long ) getAttribute ( content , FIELD_UNUSED_SINCE ) ; return unusedSince != null && unusedSince < deadline ; }
Checks status of unused content .
33,373
protected boolean pushDownJoinCriteria ( PlanNode criteriaNode , PlanNode joinNode ) { JoinType joinType = ( JoinType ) joinNode . getProperty ( Property . JOIN_TYPE ) ; switch ( joinType ) { case CROSS : joinNode . setProperty ( Property . JOIN_TYPE , JoinType . INNER ) ; moveCriteriaIntoOnClause ( criteriaNode , joinNode ) ; break ; case INNER : moveCriteriaIntoOnClause ( criteriaNode , joinNode ) ; break ; default : } return false ; }
Attempt to push down criteria that applies to the JOIN as additional constraints on the JOIN itself .
33,374
private void moveCriteriaIntoOnClause ( PlanNode criteriaNode , PlanNode joinNode ) { List < Constraint > constraints = joinNode . getPropertyAsList ( Property . JOIN_CONSTRAINTS , Constraint . class ) ; Constraint criteria = criteriaNode . getProperty ( Property . SELECT_CRITERIA , Constraint . class ) ; if ( constraints == null || constraints . isEmpty ( ) ) { constraints = new LinkedList < Constraint > ( ) ; joinNode . setProperty ( Property . JOIN_CONSTRAINTS , constraints ) ; } if ( ! constraints . contains ( criteria ) ) { constraints . add ( criteria ) ; if ( criteriaNode . hasBooleanProperty ( Property . IS_DEPENDENT ) ) { joinNode . setProperty ( Property . IS_DEPENDENT , Boolean . TRUE ) ; } } criteriaNode . extractFromParent ( ) ; }
Move the criteria that applies to the join to be included in the actual join criteria .
33,375
protected void moveExtraProperties ( String oldNodeId , String newNodeId ) { ExtraPropertiesStore extraPropertiesStore = extraPropertiesStore ( ) ; if ( extraPropertiesStore == null || ! extraPropertiesStore . contains ( oldNodeId ) ) { return ; } Map < Name , Property > existingExtraProps = extraPropertiesStore . getProperties ( oldNodeId ) ; extraPropertiesStore . removeProperties ( oldNodeId ) ; extraPropertiesStore . storeProperties ( newNodeId , existingExtraProps ) ; }
Moves a set of extra properties from an old to a new node after their IDs have changed .
33,376
protected void checkFieldNotNull ( Object fieldValue , String fieldName ) throws RepositoryException { if ( fieldValue == null ) { throw new RepositoryException ( JcrI18n . requiredFieldNotSetInConnector . text ( getSourceName ( ) , getClass ( ) , fieldName ) ) ; } }
Utility method that checks whether the field with the supplied name is set .
33,377
protected void populateRuleStack ( LinkedList < OptimizerRule > ruleStack , PlanHints hints ) { ruleStack . addFirst ( ReorderSortAndRemoveDuplicates . INSTANCE ) ; ruleStack . addFirst ( RewritePathAndNameCriteria . INSTANCE ) ; if ( hints . hasSubqueries ) { ruleStack . addFirst ( RaiseVariableName . INSTANCE ) ; } ruleStack . addFirst ( RewriteAsRangeCriteria . INSTANCE ) ; if ( hints . hasJoin ) { ruleStack . addFirst ( AddJoinConditionColumnsToSources . INSTANCE ) ; ruleStack . addFirst ( ChooseJoinAlgorithm . USE_ONLY_NESTED_JOIN_ALGORITHM ) ; ruleStack . addFirst ( RewriteIdentityJoins . INSTANCE ) ; } ruleStack . addFirst ( AddOrderingColumnsToSources . INSTANCE ) ; ruleStack . addFirst ( PushProjects . INSTANCE ) ; ruleStack . addFirst ( PushSelectCriteria . INSTANCE ) ; ruleStack . addFirst ( AddAccessNodes . INSTANCE ) ; ruleStack . addFirst ( JoinOrder . INSTANCE ) ; ruleStack . addFirst ( RightOuterToLeftOuterJoins . INSTANCE ) ; ruleStack . addFirst ( CopyCriteria . INSTANCE ) ; if ( hints . hasView ) { ruleStack . addFirst ( ReplaceViews . INSTANCE ) ; } ruleStack . addFirst ( RewritePseudoColumns . INSTANCE ) ; populateIndexingRules ( ruleStack , hints ) ; ruleStack . addLast ( OrderIndexesByCost . INSTANCE ) ; }
Method that is used to create the initial rule stack . This method can be overridden by subclasses
33,378
public Schemata getSchemataForSession ( JcrSession session ) { assert session != null ; if ( ! overridesNamespaceMappings ( session ) ) { return this ; } return new SessionSchemata ( session ) ; }
Get a schemata instance that works with the supplied session and that uses the session - specific namespace mappings . Note that the resulting instance does not change as the session s namespace mappings are changed so when that happens the JcrSession must call this method again to obtain a new schemata .
33,379
private boolean overridesNamespaceMappings ( JcrSession session ) { NamespaceRegistry registry = session . context ( ) . getNamespaceRegistry ( ) ; if ( registry instanceof LocalNamespaceRegistry ) { Set < Namespace > localNamespaces = ( ( LocalNamespaceRegistry ) registry ) . getLocalNamespaces ( ) ; if ( localNamespaces . isEmpty ( ) ) { return false ; } for ( Namespace namespace : localNamespaces ) { if ( prefixesByUris . containsKey ( namespace . getNamespaceUri ( ) ) ) return true ; } return false ; } for ( Namespace namespace : registry . getNamespaces ( ) ) { String expectedPrefix = prefixesByUris . get ( namespace . getNamespaceUri ( ) ) ; if ( expectedPrefix == null ) { continue ; } if ( ! namespace . getPrefix ( ) . equals ( expectedPrefix ) ) return true ; } return false ; }
Determine if the session overrides any namespace mappings used by this schemata .
33,380
private List < Entry > removeValues ( Collection < ? > values , boolean ifMatch ) { LinkedList < Entry > results = null ; ListIterator < ? > iter = this . values . listIterator ( size ( ) ) ; while ( iter . hasPrevious ( ) ) { int index = iter . previousIndex ( ) ; Object value = iter . previous ( ) ; if ( ifMatch == values . contains ( value ) ) { iter . remove ( ) ; if ( results == null ) { results = new LinkedList < > ( ) ; } results . addFirst ( new BasicEntry ( index , value ) ) ; } } return results != null ? results : Collections . < Entry > emptyList ( ) ; }
Remove some of the values in this array .
33,381
private boolean isExistCmisObject ( String path ) { try { session . getObjectByPath ( path ) ; return true ; } catch ( CmisObjectNotFoundException e ) { return false ; } }
Utility method for checking if CMIS object exists at defined path
33,382
private void rename ( CmisObject object , String name ) { Map < String , Object > newName = new HashMap < String , Object > ( ) ; newName . put ( "cmis:name" , name ) ; object . updateProperties ( newName ) ; }
Utility method for renaming CMIS object
33,383
private Document cmisObject ( String id ) { CmisObject cmisObject ; try { cmisObject = session . getObject ( id ) ; } catch ( CmisObjectNotFoundException e ) { return null ; } if ( cmisObject == null ) { return null ; } switch ( cmisObject . getBaseTypeId ( ) ) { case CMIS_FOLDER : return cmisFolder ( cmisObject ) ; case CMIS_DOCUMENT : return cmisDocument ( cmisObject ) ; case CMIS_POLICY : case CMIS_RELATIONSHIP : case CMIS_SECONDARY : case CMIS_ITEM : } return null ; }
Converts CMIS object to JCR node .
33,384
private Document cmisFolder ( CmisObject cmisObject ) { Folder folder = ( Folder ) cmisObject ; DocumentWriter writer = newDocument ( ObjectId . toString ( ObjectId . Type . OBJECT , folder . getId ( ) ) ) ; ObjectType objectType = cmisObject . getType ( ) ; if ( objectType . isBaseType ( ) ) { writer . setPrimaryType ( NodeType . NT_FOLDER ) ; } else { writer . setPrimaryType ( objectType . getId ( ) ) ; } writer . setParent ( folder . getParentId ( ) ) ; writer . addMixinType ( NodeType . MIX_REFERENCEABLE ) ; writer . addMixinType ( NodeType . MIX_LAST_MODIFIED ) ; cmisProperties ( folder , writer ) ; cmisChildren ( folder , writer ) ; writer . addMixinType ( "mode:accessControllable" ) ; writer . addChild ( ObjectId . toString ( ObjectId . Type . ACL , folder . getId ( ) ) , "mode:acl" ) ; if ( folder . isRootFolder ( ) ) { writer . addChild ( ObjectId . toString ( ObjectId . Type . REPOSITORY_INFO , "" ) , REPOSITORY_INFO_NODE_NAME ) ; } return writer . document ( ) ; }
Translates CMIS folder object to JCR node
33,385
public Document cmisDocument ( CmisObject cmisObject ) { org . apache . chemistry . opencmis . client . api . Document doc = ( org . apache . chemistry . opencmis . client . api . Document ) cmisObject ; DocumentWriter writer = newDocument ( ObjectId . toString ( ObjectId . Type . OBJECT , doc . getId ( ) ) ) ; ObjectType objectType = cmisObject . getType ( ) ; if ( objectType . isBaseType ( ) ) { writer . setPrimaryType ( NodeType . NT_FILE ) ; } else { writer . setPrimaryType ( objectType . getId ( ) ) ; } List < Folder > parents = doc . getParents ( ) ; ArrayList < String > parentIds = new ArrayList < String > ( ) ; for ( Folder f : parents ) { parentIds . add ( ObjectId . toString ( ObjectId . Type . OBJECT , f . getId ( ) ) ) ; } writer . setParents ( parentIds ) ; writer . addMixinType ( NodeType . MIX_REFERENCEABLE ) ; writer . addMixinType ( NodeType . MIX_LAST_MODIFIED ) ; cmisProperties ( doc , writer ) ; writer . addChild ( ObjectId . toString ( ObjectId . Type . CONTENT , doc . getId ( ) ) , JcrConstants . JCR_CONTENT ) ; writer . addMixinType ( "mode:accessControllable" ) ; writer . addChild ( ObjectId . toString ( ObjectId . Type . ACL , cmisObject . getId ( ) ) , "mode:acl" ) ; return writer . document ( ) ; }
Translates cmis document object to JCR node .
33,386
private Document cmisContent ( String id ) { DocumentWriter writer = newDocument ( ObjectId . toString ( ObjectId . Type . CONTENT , id ) ) ; org . apache . chemistry . opencmis . client . api . Document doc = ( org . apache . chemistry . opencmis . client . api . Document ) session . getObject ( id ) ; writer . setPrimaryType ( NodeType . NT_RESOURCE ) ; writer . setParent ( id ) ; ContentStream contentStream = doc . getContentStream ( ) ; if ( contentStream != null ) { BinaryValue content = new CmisConnectorBinary ( contentStream , getSourceName ( ) , id , getMimeTypeDetector ( ) ) ; writer . addProperty ( JcrConstants . JCR_DATA , content ) ; writer . addProperty ( JcrConstants . JCR_MIME_TYPE , contentStream . getMimeType ( ) ) ; } Property < Object > lastModified = doc . getProperty ( PropertyIds . LAST_MODIFICATION_DATE ) ; Property < Object > lastModifiedBy = doc . getProperty ( PropertyIds . LAST_MODIFIED_BY ) ; writer . addProperty ( JcrLexicon . LAST_MODIFIED , properties . jcrValues ( lastModified ) ) ; writer . addProperty ( JcrLexicon . LAST_MODIFIED_BY , properties . jcrValues ( lastModifiedBy ) ) ; return writer . document ( ) ; }
Converts binary content into JCR node .
33,387
private void cmisProperties ( CmisObject object , DocumentWriter writer ) { List < Property < ? > > list = object . getProperties ( ) ; for ( Property < ? > property : list ) { String pname = properties . findJcrName ( property . getId ( ) ) ; if ( pname != null ) { writer . addProperty ( pname , properties . jcrValues ( property ) ) ; } } }
Converts CMIS object s properties to JCR node properties .
33,388
private void cmisChildren ( Folder folder , DocumentWriter writer ) { ItemIterable < CmisObject > it = folder . getChildren ( ) ; for ( CmisObject obj : it ) { writer . addChild ( obj . getId ( ) , obj . getName ( ) ) ; } }
Converts CMIS folder children to JCR node children
33,389
private Document cmisRepository ( ) { RepositoryInfo info = session . getRepositoryInfo ( ) ; DocumentWriter writer = newDocument ( ObjectId . toString ( ObjectId . Type . REPOSITORY_INFO , "" ) ) ; writer . setPrimaryType ( CmisLexicon . REPOSITORY ) ; writer . setId ( REPOSITORY_INFO_ID ) ; writer . addProperty ( CmisLexicon . VENDOR_NAME , info . getVendorName ( ) ) ; writer . addProperty ( CmisLexicon . PRODUCT_NAME , info . getProductName ( ) ) ; writer . addProperty ( CmisLexicon . PRODUCT_VERSION , info . getProductVersion ( ) ) ; return writer . document ( ) ; }
Translates CMIS repository information into Node .
33,390
private ContentStream jcrBinaryContent ( Document document ) { Document props = document . getDocument ( "properties" ) . getDocument ( JcrLexicon . Namespace . URI ) ; Binary value = props . getBinary ( "data" ) ; if ( value == null ) { return null ; } byte [ ] content = value . getBytes ( ) ; String fileName = props . getString ( "fileName" ) ; String mimeType = props . getString ( "mimeType" ) ; ByteArrayInputStream bin = new ByteArrayInputStream ( content ) ; bin . reset ( ) ; return new ContentStreamImpl ( fileName , BigInteger . valueOf ( content . length ) , mimeType , bin ) ; }
Creates content stream using JCR node .
33,391
private void importTypes ( List < Tree < ObjectType > > types , NodeTypeManager typeManager , NamespaceRegistry registry ) throws RepositoryException { for ( Tree < ObjectType > tree : types ) { importType ( tree . getItem ( ) , typeManager , registry ) ; importTypes ( tree . getChildren ( ) , typeManager , registry ) ; } }
Import CMIS types to JCR repository .
33,392
@ SuppressWarnings ( "unchecked" ) public void importType ( ObjectType cmisType , NodeTypeManager typeManager , NamespaceRegistry registry ) throws RepositoryException { NodeTypeTemplate type = typeManager . createNodeTypeTemplate ( ) ; type . setName ( cmisType . getId ( ) ) ; type . setAbstract ( false ) ; type . setMixin ( false ) ; type . setOrderableChildNodes ( true ) ; type . setQueryable ( true ) ; if ( ! cmisType . isBaseType ( ) ) { type . setDeclaredSuperTypeNames ( superTypes ( cmisType ) ) ; } Map < String , PropertyDefinition < ? > > props = cmisType . getPropertyDefinitions ( ) ; Set < String > names = props . keySet ( ) ; for ( String name : names ) { PropertyDefinition < ? > pd = props . get ( name ) ; PropertyDefinitionTemplate pt = typeManager . createPropertyDefinitionTemplate ( ) ; pt . setRequiredType ( properties . getJcrType ( pd . getPropertyType ( ) ) ) ; pt . setAutoCreated ( false ) ; pt . setAvailableQueryOperators ( new String [ ] { } ) ; pt . setName ( name ) ; pt . setMandatory ( pd . isRequired ( ) ) ; type . getPropertyDefinitionTemplates ( ) . add ( pt ) ; } NodeTypeDefinition [ ] nodeDefs = new NodeTypeDefinition [ ] { type } ; typeManager . registerNodeTypes ( nodeDefs , true ) ; }
Import given CMIS type to the JCR repository .
33,393
private String [ ] superTypes ( ObjectType cmisType ) { if ( cmisType . getBaseTypeId ( ) == BaseTypeId . CMIS_FOLDER ) { return new String [ ] { JcrConstants . NT_FOLDER } ; } if ( cmisType . getBaseTypeId ( ) == BaseTypeId . CMIS_DOCUMENT ) { return new String [ ] { JcrConstants . NT_FILE } ; } return new String [ ] { cmisType . getParentType ( ) . getId ( ) } ; }
Determines supertypes for the given CMIS type in terms of JCR .
33,394
@ SuppressWarnings ( "unchecked" ) private void registerRepositoryInfoType ( NodeTypeManager typeManager ) throws RepositoryException { NodeTypeTemplate type = typeManager . createNodeTypeTemplate ( ) ; type . setName ( "cmis:repository" ) ; type . setAbstract ( false ) ; type . setMixin ( false ) ; type . setOrderableChildNodes ( true ) ; type . setQueryable ( true ) ; type . setDeclaredSuperTypeNames ( new String [ ] { JcrConstants . NT_FOLDER } ) ; PropertyDefinitionTemplate vendorName = typeManager . createPropertyDefinitionTemplate ( ) ; vendorName . setAutoCreated ( false ) ; vendorName . setName ( "cmis:vendorName" ) ; vendorName . setMandatory ( false ) ; type . getPropertyDefinitionTemplates ( ) . add ( vendorName ) ; PropertyDefinitionTemplate productName = typeManager . createPropertyDefinitionTemplate ( ) ; productName . setAutoCreated ( false ) ; productName . setName ( "cmis:productName" ) ; productName . setMandatory ( false ) ; type . getPropertyDefinitionTemplates ( ) . add ( productName ) ; PropertyDefinitionTemplate productVersion = typeManager . createPropertyDefinitionTemplate ( ) ; productVersion . setAutoCreated ( false ) ; productVersion . setName ( "cmis:productVersion" ) ; productVersion . setMandatory ( false ) ; type . getPropertyDefinitionTemplates ( ) . add ( productVersion ) ; NodeTypeDefinition [ ] nodeDefs = new NodeTypeDefinition [ ] { type } ; typeManager . registerNodeTypes ( nodeDefs , true ) ; }
Defines node type for the repository info .
33,395
public QueryResult execute ( String query , String language ) throws RepositoryException { logger . trace ( "Executing query: {0}" , query ) ; final Query jcrQuery = getLocalSession ( ) . getSession ( ) . getWorkspace ( ) . getQueryManager ( ) . createQuery ( query , language ) ; return jcrQuery . execute ( ) ; }
This execute method is used for redirection so that the JNDI implementation can control calling execute .
33,396
public Repositories getRepositories ( ) { JSONRestClient . Response response = jsonRestClient . doGet ( ) ; if ( ! response . isOK ( ) ) { throw new RuntimeException ( JdbcI18n . invalidServerResponse . text ( jsonRestClient . url ( ) , response . asString ( ) ) ) ; } return new Repositories ( response . json ( ) ) ; }
Returns a list with all the available repositories .
33,397
public Workspaces getWorkspaces ( String repositoryName ) { String url = jsonRestClient . appendToBaseURL ( repositoryName ) ; JSONRestClient . Response response = jsonRestClient . doGet ( url ) ; if ( ! response . isOK ( ) ) { throw new RuntimeException ( JdbcI18n . invalidServerResponse . text ( url , response . asString ( ) ) ) ; } return new Workspaces ( response . json ( ) ) ; }
Returns all the workspaces for the named repository .
33,398
public String queryPlan ( String query , String queryLanguage ) { String url = jsonRestClient . appendToURL ( QUERY_PLAN_METHOD ) ; String contentType = contentTypeForQueryLanguage ( queryLanguage ) ; JSONRestClient . Response response = jsonRestClient . postStreamTextPlain ( new ByteArrayInputStream ( query . getBytes ( ) ) , url , contentType ) ; if ( ! response . isOK ( ) ) { throw new RuntimeException ( JdbcI18n . invalidServerResponse . text ( url , response . asString ( ) ) ) ; } return response . asString ( ) ; }
Returns a string representation of a query plan in a given language .
33,399
public long getCardinality ( ) { if ( pos > 0 ) { return totalHits ; } try { EsResponse res = client . search ( index , type , query ) ; Document hits = ( Document ) res . get ( "hits" ) ; totalHits = hits . getInteger ( "total" ) ; return totalHits ; } catch ( Exception e ) { throw new EsIndexException ( e ) ; } }
Gets cardinality for this search request .