idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
15,600
public String getAsString ( boolean showIndex ) { if ( showIndex ) { if ( cachedToStringShowIndex != null ) { return cachedToStringShowIndex ; } } else { if ( cachedToString != null ) { return cachedToString ; } } // String res ; if ( showIndex ) { res = super . getAsString ( ) + QPath . PREFIX_DELIMITER + getIndex ( ) ; } else { res = super . getAsString ( ) ; } // if ( showIndex ) { cachedToStringShowIndex = res ; } else { cachedToString = res ; } // return res ; }
Return entry textual representation .
136
5
15,601
private List < NodeTypeData > registerListOfNodeTypes ( final List < NodeTypeData > nodeTypes , final int alreadyExistsBehaviour ) throws RepositoryException { // validate nodeTypeDataValidator . validateNodeType ( nodeTypes ) ; nodeTypeRepository . registerNodeType ( nodeTypes , this , accessControlPolicy , alreadyExistsBehaviour ) ; for ( NodeTypeData nodeType : nodeTypes ) { for ( NodeTypeManagerListener listener : listeners . values ( ) ) { listener . nodeTypeRegistered ( nodeType . getName ( ) ) ; } } if ( started && rpcService != null && repository != null && repository . getState ( ) == ManageableRepository . ONLINE ) { try { String [ ] names = new String [ nodeTypes . size ( ) ] ; for ( int i = 0 ; i < names . length ; i ++ ) { names [ i ] = nodeTypes . get ( i ) . getName ( ) . getAsString ( ) ; } rpcService . executeCommandOnAllNodes ( registerNodeTypes , false , id , names ) ; } catch ( Exception e ) { LOG . warn ( "Could not register the node types on other cluster nodes" , e ) ; } } return nodeTypes ; }
Registers the provided node types
268
6
15,602
public Query rewrite ( IndexReader reader ) throws IOException { if ( transform == TRANSFORM_NONE ) { Query stdRangeQueryImpl = new TermRangeQuery ( lowerTerm . field ( ) , lowerTerm . text ( ) , upperTerm . text ( ) , inclusive , inclusive ) ; try { stdRangeQuery = stdRangeQueryImpl . rewrite ( reader ) ; return stdRangeQuery ; } catch ( BooleanQuery . TooManyClauses e ) { // failed, use own implementation return this ; } } else { // always use our implementation when we need to transform the // term enum return this ; } }
Tries to rewrite this query into a standard lucene RangeQuery . This rewrite might fail with a TooManyClauses exception . If that happens we use our own implementation .
126
35
15,603
public static void start ( final Cache < Serializable , Object > cache ) { PrivilegedAction < Object > action = new PrivilegedAction < Object > ( ) { public Object run ( ) { cache . start ( ) ; return null ; } } ; SecurityHelper . doPrivilegedAction ( action ) ; }
Start Infinispan cache in privileged mode .
64
9
15,604
public static Object put ( final Cache < Serializable , Object > cache , final Serializable key , final Object value , final long lifespan , final TimeUnit unit ) { PrivilegedAction < Object > action = new PrivilegedAction < Object > ( ) { public Object run ( ) { return cache . put ( key , value , lifespan , unit ) ; } } ; return SecurityHelper . doPrivilegedAction ( action ) ; }
Put in Infinispan cache in privileged mode .
88
10
15,605
public Response lock ( Session session , String path , HierarchicalProperty body , Depth depth , String timeout ) { boolean bodyIsEmpty = ( body == null ) ; String lockToken ; //To force read only mode when open a document by user with only read permission if ( isReadOnly ( session , path ) ) { return Response . status ( HTTPStatus . METHOD_NOT_ALLOWED ) . entity ( "Permission denied" ) . build ( ) ; } try { WebDavNamespaceContext nsContext = new WebDavNamespaceContext ( session ) ; try { Node node = ( Node ) session . getItem ( path ) ; if ( ! node . isNodeType ( "mix:lockable" ) ) { if ( node . canAddMixin ( "mix:lockable" ) ) { node . addMixin ( "mix:lockable" ) ; session . save ( ) ; } } Lock lock ; if ( bodyIsEmpty ) { lock = node . getLock ( ) ; lock . refresh ( ) ; body = new HierarchicalProperty ( new QName ( "DAV" , "activelock" , "D" ) ) ; HierarchicalProperty owner = new HierarchicalProperty ( PropertyConstants . OWNER ) ; HierarchicalProperty href = new HierarchicalProperty ( new QName ( "D" , "href" ) , lock . getLockOwner ( ) ) ; body . addChild ( owner ) . addChild ( href ) ; } else { lock = node . lock ( ( depth . getIntValue ( ) != 1 ) , false ) ; } lockToken = lock . getLockToken ( ) ; } catch ( PathNotFoundException pexc ) { lockToken = nullResourceLocks . addLock ( session , path ) ; } LockRequestEntity requestEntity = new LockRequestEntity ( body ) ; lockToken = WebDavConst . Lock . OPAQUE_LOCK_TOKEN + ":" + lockToken ; //NOSONAR if ( bodyIsEmpty ) { return Response . ok ( body ( nsContext , requestEntity , depth , lockToken , requestEntity . getOwner ( ) , timeout ) , "text/xml" ) . build ( ) ; } else { return Response . ok ( body ( nsContext , requestEntity , depth , lockToken , requestEntity . getOwner ( ) , timeout ) , "text/xml" ) . header ( "Lock-Token" , "<" + lockToken + ">" ) . build ( ) ; } } catch ( LockException exc ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( AccessDeniedException exc ) { return Response . status ( HTTPStatus . FORBIDDEN ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav Lock comand implementation .
651
8
15,606
private StreamingOutput body ( WebDavNamespaceContext nsContext , LockRequestEntity input , Depth depth , String lockToken , String lockOwner , String timeout ) { return new LockResultResponseEntity ( nsContext , lockToken , lockOwner , timeout ) ; }
Writes response body into the stream .
54
8
15,607
private boolean isReadOnly ( Session session , String path ) { try { session . checkPermission ( path , PermissionType . SET_PROPERTY ) ; return false ; } catch ( AccessControlException e ) { return true ; } catch ( RepositoryException e ) { return false ; } }
Check node permission
63
3
15,608
public String dump ( ) throws RepositoryException { StringBuilder tmp = new StringBuilder ( ) ; QueryTreeDump . dump ( this , tmp ) ; return tmp . toString ( ) ; }
Dumps this QueryNode and its child nodes to a String .
41
13
15,609
public Query createQuery ( SessionImpl session , SessionDataManager sessionDataManager , Node node ) throws InvalidQueryException , RepositoryException { AbstractQueryImpl query = createQueryInstance ( ) ; query . init ( session , sessionDataManager , handler , node ) ; return query ; }
Creates a query object from a node that can be executed on the workspace .
58
16
15,610
public Query createQuery ( SessionImpl session , SessionDataManager sessionDataManager , String statement , String language ) throws InvalidQueryException , RepositoryException { AbstractQueryImpl query = createQueryInstance ( ) ; query . init ( session , sessionDataManager , handler , statement , language ) ; return query ; }
Creates a query object that can be executed on the workspace .
63
13
15,611
public void checkIndex ( final InspectionReport report , final boolean isSystem ) throws RepositoryException , IOException { if ( isSuspended . get ( ) ) { try { SecurityHelper . doPrivilegedExceptionAction ( new PrivilegedExceptionAction < Object > ( ) { public Object run ( ) throws RepositoryException , IOException { // try resuming the workspace try { if ( isSystem && parentSearchManager != null && parentSearchManager . isSuspended . get ( ) ) { parentSearchManager . resume ( ) ; } resume ( ) ; handler . checkIndex ( itemMgr , isSystem , report ) ; return null ; } catch ( ResumeException e ) { throw new RepositoryException ( "Can not resume SearchManager for inspection purposes." , e ) ; } finally { // safely return the state of the workspace try { suspend ( ) ; if ( isSystem && parentSearchManager != null && ! parentSearchManager . isSuspended . get ( ) ) { parentSearchManager . suspend ( ) ; } } catch ( SuspendException e ) { LOG . error ( e . getMessage ( ) , e ) ; } } } } ) ; } catch ( PrivilegedActionException e ) { Throwable ex = e . getCause ( ) ; if ( ex instanceof RepositoryException ) { throw ( RepositoryException ) ex ; } else if ( ex instanceof IOException ) { throw ( IOException ) ex ; } else { throw new RepositoryException ( ex . getMessage ( ) , ex ) ; } } } else { // simply run checkIndex, if not suspended handler . checkIndex ( itemMgr , isSystem , report ) ; } }
Check index consistency . Iterator goes through index documents and check does each document have according jcr - node . If index is suspended then it will be temporary resumed while check is running and suspended afterwards .
351
40
15,612
public Set < String > getNodesByUri ( final String uri ) throws RepositoryException { Set < String > result ; final int defaultClauseCount = BooleanQuery . getMaxClauseCount ( ) ; try { // final LocationFactory locationFactory = new // LocationFactory(this); final ValueFactoryImpl valueFactory = new ValueFactoryImpl ( new LocationFactory ( nsReg ) , cleanerHolder ) ; BooleanQuery . setMaxClauseCount ( Integer . MAX_VALUE ) ; BooleanQuery query = new BooleanQuery ( ) ; final String prefix = nsReg . getNamespacePrefixByURI ( uri ) ; query . add ( new WildcardQuery ( new Term ( FieldNames . LABEL , prefix + ":*" ) ) , Occur . SHOULD ) ; // name of the property query . add ( new WildcardQuery ( new Term ( FieldNames . PROPERTIES_SET , prefix + ":*" ) ) , Occur . SHOULD ) ; result = getNodes ( query ) ; // value of the property try { final Set < String > props = getFieldNames ( ) ; query = new BooleanQuery ( ) ; for ( final String fieldName : props ) { if ( ! FieldNames . PROPERTIES_SET . equals ( fieldName ) ) { query . add ( new WildcardQuery ( new Term ( fieldName , "*" + prefix + ":*" ) ) , Occur . SHOULD ) ; } } } catch ( final IndexException e ) { throw new RepositoryException ( e . getLocalizedMessage ( ) , e ) ; } final Set < String > propSet = getNodes ( query ) ; // Manually check property values; for ( final String uuid : propSet ) { if ( isPrefixMatch ( valueFactory , uuid , prefix ) ) { result . add ( uuid ) ; } } } finally { BooleanQuery . setMaxClauseCount ( defaultClauseCount ) ; } return result ; }
Return set of uuid of nodes . Contains in names prefixes maped to the given uri
422
20
15,613
protected String getIndexDirParam ( ) throws RepositoryConfigurationException { String dir = config . getParameterValue ( QueryHandlerParams . PARAM_INDEX_DIR , null ) ; if ( dir == null ) { LOG . warn ( QueryHandlerParams . PARAM_INDEX_DIR + " parameter not found. Using outdated parameter name " + QueryHandlerParams . OLD_PARAM_INDEX_DIR ) ; dir = config . getParameterValue ( QueryHandlerParams . OLD_PARAM_INDEX_DIR ) ; } return dir ; }
^ Returns index - dir parameter from configuration .
121
9
15,614
@ SuppressWarnings ( "unchecked" ) protected IndexerChangesFilter initializeChangesFilter ( ) throws RepositoryException , RepositoryConfigurationException { IndexerChangesFilter newChangesFilter = null ; Class < ? extends IndexerChangesFilter > changesFilterClass = DefaultChangesFilter . class ; String changesFilterClassName = config . getParameterValue ( QueryHandlerParams . PARAM_CHANGES_FILTER_CLASS , null ) ; try { if ( changesFilterClassName != null ) { changesFilterClass = ( Class < ? extends IndexerChangesFilter > ) ClassLoading . forName ( changesFilterClassName , this ) ; } Constructor < ? extends IndexerChangesFilter > constuctor = changesFilterClass . getConstructor ( SearchManager . class , SearchManager . class , QueryHandlerEntry . class , IndexingTree . class , IndexingTree . class , QueryHandler . class , QueryHandler . class , ConfigurationManager . class ) ; if ( parentSearchManager != null ) { newChangesFilter = constuctor . newInstance ( this , parentSearchManager , config , indexingTree , parentSearchManager . getIndexingTree ( ) , handler , parentSearchManager . getHandler ( ) , cfm ) ; } } catch ( SecurityException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( ClassNotFoundException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( NoSuchMethodException 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 ) ; } return newChangesFilter ; }
Initialize changes filter .
443
5
15,615
protected void initializeQueryHandler ( ) throws RepositoryException , RepositoryConfigurationException { // initialize query handler String className = config . getType ( ) ; if ( className == null ) { throw new RepositoryConfigurationException ( "Content hanler configuration fail" ) ; } try { Class < ? > qHandlerClass = ClassLoading . forName ( className , this ) ; try { // We first try a constructor with the workspace id Constructor < ? > constuctor = qHandlerClass . getConstructor ( String . class , QueryHandlerEntry . class , ConfigurationManager . class ) ; handler = ( QueryHandler ) constuctor . newInstance ( wsContainerId , config , cfm ) ; } catch ( NoSuchMethodException e ) { // No constructor with the workspace id can be found so we use the default constructor Constructor < ? > constuctor = qHandlerClass . getConstructor ( QueryHandlerEntry . class , ConfigurationManager . class ) ; handler = ( QueryHandler ) constuctor . newInstance ( config , cfm ) ; } QueryHandler parentHandler = ( this . parentSearchManager != null ) ? parentSearchManager . getHandler ( ) : null ; QueryHandlerContext context = createQueryHandlerContext ( parentHandler ) ; handler . setContext ( context ) ; if ( parentSearchManager != null ) { changesFilter = initializeChangesFilter ( ) ; parentSearchManager . setChangesFilter ( changesFilter ) ; } } catch ( SecurityException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( ClassNotFoundException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( NoSuchMethodException 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 ) ; } }
Initializes the query handler .
479
6
15,616
public void setOnline ( boolean isOnline , boolean allowQuery , boolean dropStaleIndexes ) throws IOException { handler . setOnline ( isOnline , allowQuery , dropStaleIndexes ) ; }
Switches index into corresponding ONLINE or OFFLINE mode . Offline mode means that new indexing data is collected but index is guaranteed to be unmodified during offline state . Passing the allowQuery flag can allow or deny performing queries on index during offline mode . AllowQuery is not used when setting index back online . When dropStaleIndexes is set indexes present on the moment of switching index offline will be marked as stale and removed on switching it back online .
43
93
15,617
public CompletableFuture < Boolean > reindexWorkspace ( final boolean dropExisting , int nThreads ) throws IllegalStateException { // checks if ( handler == null || handler . getIndexerIoModeHandler ( ) == null || changesFilter == null ) { throw new IllegalStateException ( "Index might have not been initialized yet." ) ; } if ( handler . getIndexerIoModeHandler ( ) . getMode ( ) != IndexerIoMode . READ_WRITE ) { throw new IllegalStateException ( "Index is not in READ_WRITE mode and reindexing can't be launched. Please start reindexing on coordinator node." ) ; } if ( isSuspended . get ( ) || ! handler . isOnline ( ) ) { throw new IllegalStateException ( "Can't start reindexing while index is " + ( ( isSuspended . get ( ) ) ? "SUSPENDED." : "already OFFLINE (it means that reindexing is in progress)." ) + "." ) ; } LOG . info ( "Starting hot reindexing on the " + handler . getContext ( ) . getRepositoryName ( ) + "/" + handler . getContext ( ) . getContainer ( ) . getWorkspaceName ( ) + ", with" + ( dropExisting ? "" : "out" ) + " dropping the existing indexes." ) ; // starting new thread, releasing JMX call ExecutorService executorService = Executors . newSingleThreadExecutor ( runnable -> new Thread ( runnable , "HotReindexing-" + handler . getContext ( ) . getRepositoryName ( ) + "-" + handler . getContext ( ) . getContainer ( ) . getWorkspaceName ( ) ) ) ; CompletableFuture < Boolean > reindexFuture = CompletableFuture . supplyAsync ( ( ) -> doReindexing ( dropExisting , nThreads ) , executorService ) ; reindexFuture . thenRun ( ( ) -> executorService . shutdown ( ) ) ; return reindexFuture ; }
Perform hot reindexing of the workspace
446
9
15,618
private void cleanIndexDirectory ( String path ) throws IOException { SecurityHelper . doPrivilegedIOExceptionAction ( ( PrivilegedExceptionAction < Void > ) ( ) -> { File newIndexFolder = new File ( path ) ; if ( newIndexFolder . exists ( ) ) { DirectoryHelper . removeDirectory ( newIndexFolder ) ; } return null ; } ) ; }
remove index directory if exist
77
5
15,619
protected void postInit ( Connection connection ) throws SQLException { String select = "select * from " + DBInitializerHelper . getItemTableName ( containerConfig ) + " where ID='" + Constants . ROOT_PARENT_UUID + "' and PARENT_ID='" + Constants . ROOT_PARENT_UUID + "'" ; if ( ! connection . createStatement ( ) . executeQuery ( select ) . next ( ) ) { String insert = DBInitializerHelper . getRootNodeInitializeScript ( containerConfig ) ; connection . createStatement ( ) . executeUpdate ( insert ) ; } }
Init root node parent record .
134
6
15,620
private static Field . Index getIndexParameter ( int flags ) { if ( ( flags & INDEXED_FLAG ) == 0 ) { return Field . Index . NO ; } else if ( ( flags & TOKENIZED_FLAG ) > 0 ) { return Field . Index . ANALYZED ; } else { return Field . Index . NOT_ANALYZED ; } }
Returns the index parameter extracted from the flags .
82
9
15,621
private static Field . Store getStoreParameter ( int flags ) { if ( ( flags & STORED_FLAG ) > 0 ) { return Field . Store . YES ; } else { return Field . Store . NO ; } }
Returns the store parameter extracted from the flags .
46
9
15,622
private static Field . TermVector getTermVectorParameter ( int flags ) { if ( ( ( flags & STORE_POSITION_WITH_TERM_VECTOR_FLAG ) > 0 ) && ( ( flags & STORE_OFFSET_WITH_TERM_VECTOR_FLAG ) > 0 ) ) { return Field . TermVector . WITH_POSITIONS_OFFSETS ; } else if ( ( flags & STORE_POSITION_WITH_TERM_VECTOR_FLAG ) > 0 ) { return Field . TermVector . WITH_POSITIONS ; } else if ( ( flags & STORE_OFFSET_WITH_TERM_VECTOR_FLAG ) > 0 ) { return Field . TermVector . WITH_OFFSETS ; } else if ( ( flags & STORE_TERM_VECTOR_FLAG ) > 0 ) { return Field . TermVector . YES ; } else { return Field . TermVector . NO ; } }
Returns the term vector parameter extracted from the flags .
212
10
15,623
private void addNamespace ( String prefix , String uri ) { prefixToURI . put ( prefix , uri ) ; uriToPrefix . put ( uri , prefix ) ; }
Adds the given namespace declaration to this resolver .
41
10
15,624
public Response versionControl ( Session session , String path ) { try { Node node = ( Node ) session . getItem ( path ) ; if ( ! node . isNodeType ( "mix:versionable" ) ) { node . addMixin ( "mix:versionable" ) ; session . save ( ) ; } return Response . ok ( ) . build ( ) ; } catch ( LockException exc ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . NOT_FOUND ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { log . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav Version - Control method implementation .
196
9
15,625
public byte [ ] generateLinkContent ( ) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream ( ) ; // LINK HEADER for ( int i = 0 ; i < linkHeader . length ; i ++ ) { byte curByteValue = ( byte ) linkHeader [ i ] ; outStream . write ( curByteValue ) ; } // LINK BODY byte [ ] linkContent = getLinkContent ( ) ; writeInt ( linkContent . length + 2 , outStream ) ; outStream . write ( linkContent ) ; // WRITE END LINK FILE for ( int i = 0 ; i < 6 ; i ++ ) { outStream . write ( 0 ) ; } return outStream . toByteArray ( ) ; }
Generates the content of link .
154
7
15,626
private byte [ ] getLinkContent ( ) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream ( ) ; byte [ ] firstItem = getFirstItem ( ) ; writeInt ( firstItem . length + 2 , outStream ) ; writeBytes ( firstItem , outStream ) ; byte [ ] lastItem = getLastItem ( ) ; writeInt ( lastItem . length + 2 , outStream ) ; writeBytes ( lastItem , outStream ) ; String [ ] pathes = servletPath . split ( "/" ) ; String root = pathes [ pathes . length - 1 ] ; byte [ ] rootItem = getRootItem ( root , servletPath ) ; writeInt ( rootItem . length + 2 , outStream ) ; writeBytes ( rootItem , outStream ) ; pathes = targetPath . split ( "/" ) ; StringBuilder curHref = new StringBuilder ( servletPath ) ; for ( int i = 0 ; i < pathes . length ; i ++ ) { if ( "" . equals ( pathes [ i ] ) ) { continue ; } String curName = pathes [ i ] ; curHref . append ( "/" ) . append ( curName ) ; if ( i < pathes . length - 1 ) { byte [ ] linkItem = getHreffedFolder ( curName , curHref . toString ( ) ) ; writeInt ( linkItem . length + 2 , outStream ) ; writeBytes ( linkItem , outStream ) ; } else { byte [ ] linkFile = getHreffedFile ( curName , curHref . toString ( ) ) ; writeInt ( linkFile . length + 2 , outStream ) ; writeBytes ( linkFile , outStream ) ; } } return outStream . toByteArray ( ) ; }
Gets the content of the link .
387
8
15,627
private byte [ ] getFirstItem ( ) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream ( ) ; int [ ] firstItem = { 0x1F , 0x50 , 0xE0 , 0x4F , 0xD0 , 0x20 , 0xEA , 0x3A , 0x69 , 0x10 , 0xA2 , 0xD8 , 0x08 , 0x00 , 0x2B , 0x30 , 0x30 , 0x9D , } ; writeInts ( firstItem , outStream ) ; return outStream . toByteArray ( ) ; }
Returns the first item .
140
5
15,628
private byte [ ] getLastItem ( ) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream ( ) ; int [ ] lastItem = { 0x2E , 0x80 , 0x00 , 0xDF , 0xEA , 0xBD , 0x65 , 0xC2 , 0xD0 , 0x11 , 0xBC , 0xED , 0x00 , 0xA0 , 0xC9 , 0x0A , 0xB5 , 0x0F } ; writeInts ( lastItem , outStream ) ; return outStream . toByteArray ( ) ; }
Returns the last item .
138
5
15,629
private byte [ ] getRootValue ( String rootName ) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream ( ) ; simpleWriteString ( rootName , outStream ) ; int [ ] rootVal = { 0x20 , 0x00 , 0x3D , 0x04 , 0x30 , 0x04 , 0x20 , 0x00 } ; writeInts ( rootVal , outStream ) ; simpleWriteString ( hostName , outStream ) ; return outStream . toByteArray ( ) ; }
Returns the root value .
116
5
15,630
private void writeZeroString ( String outString , OutputStream outStream ) throws IOException { simpleWriteString ( outString , outStream ) ; outStream . write ( 0 ) ; outStream . write ( 0 ) ; }
Writes zero - string into stream .
47
8
15,631
private void writeInt ( int intValue , OutputStream outStream ) throws IOException { outStream . write ( intValue & 0xFF ) ; outStream . write ( ( intValue >> 8 ) & 0xFF ) ; }
Writes int into stream .
49
6
15,632
private void writeInts ( int [ ] bytes , OutputStream outStream ) throws IOException { for ( int i = 0 ; i < bytes . length ; i ++ ) { byte curByte = ( byte ) bytes [ i ] ; outStream . write ( curByte ) ; } }
Writes int array into stream .
60
7
15,633
private void commitPending ( ) throws IOException { if ( pending . isEmpty ( ) ) { return ; } super . addDocuments ( ( Document [ ] ) pending . values ( ) . toArray ( new Document [ pending . size ( ) ] ) ) ; pending . clear ( ) ; aggregateIndexes . clear ( ) ; }
Commits pending documents to the index .
70
8
15,634
@ Override public Query rewrite ( IndexReader reader ) throws IOException { @ SuppressWarnings ( "serial" ) Query stdWildcardQuery = new MultiTermQuery ( ) { @ Override protected FilteredTermEnum getEnum ( IndexReader reader ) throws IOException { return new WildcardTermEnum ( reader , field , propName , pattern , transform ) ; } /** Prints a user-readable version of this query. */ @ Override public String toString ( String field ) { StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( field ) ; buffer . append ( ' ' ) ; buffer . append ( ToStringUtils . boost ( getBoost ( ) ) ) ; return buffer . toString ( ) ; } } ; try { multiTermQuery = stdWildcardQuery . rewrite ( reader ) ; return multiTermQuery ; } catch ( BooleanQuery . TooManyClauses e ) { // MultiTermQuery not possible log . debug ( "Too many terms to enumerate, using custom WildcardQuery." ) ; return this ; } }
Either rewrites this query to a lucene MultiTermQuery or in case of a TooManyClauses exception to a custom jackrabbit query implementation that uses a BitSet to collect all hits .
225
41
15,635
public BaseXmlExporter getExportVisitor ( XmlMapping type , OutputStream stream , boolean skipBinary , boolean noRecurse , boolean exportChildVersionHistory , ItemDataConsumer dataManager , NamespaceRegistry namespaceRegistry , ValueFactoryImpl systemValueFactory ) throws NamespaceException , RepositoryException , IOException { XMLOutputFactory outputFactory = XMLOutputFactory . newInstance ( ) ; XMLStreamWriter streamWriter ; try { streamWriter = outputFactory . createXMLStreamWriter ( stream , Constants . DEFAULT_ENCODING ) ; } catch ( XMLStreamException e ) { throw new IOException ( e . getLocalizedMessage ( ) , e ) ; } if ( type == XmlMapping . SYSVIEW ) { return new SystemViewStreamExporter ( streamWriter , dataManager , namespaceRegistry , systemValueFactory , skipBinary , noRecurse , exportChildVersionHistory ) ; } else if ( type == XmlMapping . DOCVIEW ) { return new DocumentViewStreamExporter ( streamWriter , dataManager , namespaceRegistry , systemValueFactory , skipBinary , noRecurse ) ; } else if ( type == XmlMapping . BACKUP ) { return new WorkspaceSystemViewStreamExporter ( streamWriter , dataManager , namespaceRegistry , systemValueFactory , skipBinary , noRecurse ) ; } return null ; }
Create export visitor for given type of view . \
294
10
15,636
protected JCRPathMatcher parsePathMatcher ( LocationFactory locFactory , String path ) throws RepositoryException { JCRPath knownPath = null ; boolean forDescendants = false ; boolean forAncestors = false ; if ( path . equals ( "*" ) || path . equals ( ".*" ) ) { // any forDescendants = true ; forAncestors = true ; } else if ( path . endsWith ( "*" ) && path . startsWith ( "*" ) ) { forDescendants = true ; forAncestors = true ; knownPath = parsePath ( path . substring ( 1 , path . length ( ) - 1 ) , locFactory ) ; } else if ( path . endsWith ( "*" ) ) { forDescendants = true ; knownPath = parsePath ( path . substring ( 0 , path . length ( ) - 1 ) , locFactory ) ; } else if ( path . startsWith ( "*" ) ) { forAncestors = true ; knownPath = parsePath ( path . substring ( 1 ) , locFactory ) ; } else { knownPath = parsePath ( path , locFactory ) ; } return new JCRPathMatcher ( knownPath == null ? null : knownPath . getInternalPath ( ) , forDescendants , forAncestors ) ; }
Parses JCR path matcher from string .
285
11
15,637
public boolean checkedOut ( ) throws UnsupportedRepositoryOperationException , RepositoryException { // this will also check if item is valid NodeData vancestor = getVersionableAncestor ( ) ; if ( vancestor != null ) { PropertyData isCheckedOut = ( PropertyData ) dataManager . getItemData ( vancestor , new QPathEntry ( Constants . JCR_ISCHECKEDOUT , 1 ) , ItemType . PROPERTY ) ; return ValueDataUtil . getBoolean ( isCheckedOut . getValues ( ) . get ( 0 ) ) ; } return true ; }
Tell if this node or its nearest versionable ancestor is checked - out .
134
15
15,638
private void doAddMixin ( NodeTypeData type ) throws NoSuchNodeTypeException , ConstraintViolationException , VersionException , LockException , RepositoryException { // Add both to mixinNodeTypes and to jcr:mixinTypes property // Prepare mixin values InternalQName [ ] mixinTypes = nodeData ( ) . getMixinTypeNames ( ) ; List < InternalQName > newMixin = new ArrayList < InternalQName > ( mixinTypes . length + 1 ) ; List < ValueData > values = new ArrayList < ValueData > ( mixinTypes . length + 1 ) ; for ( int i = 0 ; i < mixinTypes . length ; i ++ ) { InternalQName cn = mixinTypes [ i ] ; newMixin . add ( cn ) ; values . add ( new TransientValueData ( cn ) ) ; } newMixin . add ( type . getName ( ) ) ; values . add ( new TransientValueData ( type . getName ( ) ) ) ; PropertyData prop = ( PropertyData ) dataManager . getItemData ( ( ( NodeData ) getData ( ) ) , new QPathEntry ( Constants . JCR_MIXINTYPES , 0 ) , ItemType . PROPERTY , false ) ; ItemState state ; if ( prop != null ) { // there was mixin prop prop = new TransientPropertyData ( prop . getQPath ( ) , prop . getIdentifier ( ) , prop . getPersistedVersion ( ) , prop . getType ( ) , prop . getParentIdentifier ( ) , prop . isMultiValued ( ) , values ) ; state = ItemState . createUpdatedState ( prop ) ; } else { prop = TransientPropertyData . createPropertyData ( this . nodeData ( ) , Constants . JCR_MIXINTYPES , PropertyType . NAME , true , values ) ; state = ItemState . createAddedState ( prop ) ; } NodeTypeDataManager ntmanager = session . getWorkspace ( ) . getNodeTypesHolder ( ) ; // change ACL for ( PropertyDefinitionData def : ntmanager . getAllPropertyDefinitions ( type . getName ( ) ) ) { if ( ntmanager . isNodeType ( Constants . EXO_OWNEABLE , new InternalQName [ ] { type . getName ( ) } ) && def . getName ( ) . equals ( Constants . EXO_OWNER ) ) { AccessControlList acl = new AccessControlList ( session . getUserID ( ) , ( ( NodeData ) data ) . getACL ( ) . getPermissionEntries ( ) ) ; setACL ( acl ) ; } } updateMixin ( newMixin ) ; dataManager . update ( state , false ) ; // Should register jcr:mixinTypes and autocreated items if node is not added ItemAutocreator itemAutocreator = new ItemAutocreator ( ntmanager , valueFactory , dataManager , false ) ; PlainChangesLog changes = itemAutocreator . makeAutoCreatedItems ( nodeData ( ) , type . getName ( ) , dataManager , session . getUserID ( ) ) ; for ( ItemState autoCreatedState : changes . getAllStates ( ) ) { dataManager . update ( autoCreatedState , false ) ; } // launch event session . getActionHandler ( ) . postAddMixin ( this , type . getName ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Node.addMixin Property " + prop . getQPath ( ) . getAsString ( ) + " values " + mixinTypes . length ) ; } }
Internal method to add mixin Nodetype to the Node .
804
14
15,639
protected NodeData getCorrespondingNodeData ( SessionImpl corrSession ) throws ItemNotFoundException , AccessDeniedException , RepositoryException { final QPath myPath = nodeData ( ) . getQPath ( ) ; final SessionDataManager corrDataManager = corrSession . getTransientNodesManager ( ) ; if ( this . isNodeType ( Constants . MIX_REFERENCEABLE ) ) { NodeData corrNode = ( NodeData ) corrDataManager . getItemData ( getUUID ( ) ) ; if ( corrNode != null ) { return corrNode ; } } else { NodeData ancestor = ( NodeData ) dataManager . getItemData ( Constants . ROOT_UUID ) ; for ( int i = 1 ; i < myPath . getDepth ( ) ; i ++ ) { ancestor = ( NodeData ) dataManager . getItemData ( ancestor , myPath . getEntries ( ) [ i ] , ItemType . NODE ) ; if ( corrSession . getWorkspace ( ) . getNodeTypesHolder ( ) . isNodeType ( Constants . MIX_REFERENCEABLE , ancestor . getPrimaryTypeName ( ) , ancestor . getMixinTypeNames ( ) ) ) { NodeData corrAncestor = ( NodeData ) corrDataManager . getItemData ( ancestor . getIdentifier ( ) ) ; if ( corrAncestor == null ) { throw new ItemNotFoundException ( "No corresponding path for ancestor " + ancestor . getQPath ( ) . getAsString ( ) + " in " + corrSession . getWorkspace ( ) . getName ( ) ) ; } NodeData corrNode = ( NodeData ) corrDataManager . getItemData ( corrAncestor , myPath . getRelPath ( myPath . getDepth ( ) - i ) , ItemType . NODE ) ; if ( corrNode != null ) { return corrNode ; } } } } NodeData corrNode = ( NodeData ) corrDataManager . getItemData ( myPath ) ; if ( corrNode != null ) { return corrNode ; } throw new ItemNotFoundException ( "No corresponding path for " + getPath ( ) + " in " + corrSession . getWorkspace ( ) . getName ( ) ) ; }
Return Node corresponding to this Node .
508
7
15,640
public String [ ] getMixinTypeNames ( ) throws RepositoryException { NodeType [ ] mixinTypes = getMixinNodeTypes ( ) ; String [ ] mtNames = new String [ mixinTypes . length ] ; for ( int i = 0 ; i < mtNames . length ; i ++ ) { mtNames [ i ] = mixinTypes [ i ] . getName ( ) ; } return mtNames ; }
Return mixin Nodetype names .
90
9
15,641
private void initDefinition ( NodeData parent ) throws RepositoryException , ConstraintViolationException { if ( this . isRoot ( ) ) { // root - no parent this . definition = new NodeDefinitionData ( null , null , true , true , OnParentVersionAction . ABORT , true , new InternalQName [ ] { Constants . NT_BASE } , null , false ) ; return ; } if ( parent == null ) { parent = ( NodeData ) dataManager . getItemData ( getParentIdentifier ( ) ) ; } this . definition = session . getWorkspace ( ) . getNodeTypesHolder ( ) . getChildNodeDefinition ( getInternalName ( ) , nodeData ( ) . getPrimaryTypeName ( ) , parent . getPrimaryTypeName ( ) , parent . getMixinTypeNames ( ) ) ; if ( definition == null ) { throw new ConstraintViolationException ( "Node definition not found for " + getPath ( ) ) ; } }
Init NodeDefinition .
211
4
15,642
public VersionHistoryImpl versionHistory ( boolean pool ) throws UnsupportedRepositoryOperationException , RepositoryException { if ( ! this . isNodeType ( Constants . MIX_VERSIONABLE ) ) { throw new UnsupportedRepositoryOperationException ( "Node is not mix:versionable " + getPath ( ) ) ; } PropertyData vhProp = ( PropertyData ) dataManager . getItemData ( nodeData ( ) , new QPathEntry ( Constants . JCR_VERSIONHISTORY , 1 ) , ItemType . PROPERTY ) ; if ( vhProp == null ) { throw new UnsupportedRepositoryOperationException ( "Node does not have jcr:versionHistory " + getPath ( ) ) ; } return ( VersionHistoryImpl ) dataManager . getItemByIdentifier ( ValueDataUtil . getString ( vhProp . getValues ( ) . get ( 0 ) ) , pool , false ) ; }
For internal use . Doesn t check the InvalidItemStateException and may return unpooled VersionHistory object .
197
22
15,643
private List < PropertyData > childPropertiesData ( ) throws RepositoryException , AccessDeniedException { List < PropertyData > storedProps = new ArrayList < PropertyData > ( dataManager . getChildPropertiesData ( nodeData ( ) ) ) ; Collections . sort ( storedProps , new PropertiesDataOrderComparator < PropertyData > ( ) ) ; return storedProps ; }
Return child Properties list .
83
5
15,644
private List < NodeData > childNodesData ( ) throws RepositoryException , AccessDeniedException { List < NodeData > storedNodes = new ArrayList < NodeData > ( dataManager . getChildNodesData ( nodeData ( ) ) ) ; Collections . sort ( storedNodes , new NodeDataOrderComparator ( ) ) ; return storedNodes ; }
Return child Nodes list .
79
6
15,645
private int getNextChildIndex ( InternalQName nameToAdd , InternalQName primaryTypeName , NodeData parentNode , NodeDefinitionData def ) throws RepositoryException , ItemExistsException { boolean allowSns = def . isAllowsSameNameSiblings ( ) ; int ind = 1 ; boolean hasSibling = dataManager . hasItemData ( parentNode , new QPathEntry ( nameToAdd , ind ) , ItemType . NODE ) ; while ( hasSibling ) { if ( allowSns ) { ind ++ ; hasSibling = dataManager . hasItemData ( parentNode , new QPathEntry ( nameToAdd , ind ) , ItemType . NODE ) ; } else { throw new ItemExistsException ( "The node " + nameToAdd + " already exists in " + getPath ( ) + " and same name sibling is not allowed " ) ; } } ; return ind ; }
Calculates next child node index . Is used existed node definition if no - get one based on node name and node type .
194
26
15,646
protected boolean accept ( Node node ) { try { return status == UserStatus . ANY || status . matches ( node . canAddMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ) ; } catch ( RepositoryException e ) { if ( LOG . isDebugEnabled ( ) ) { String path = "unknown" ; try { path = node . getPath ( ) ; } catch ( RepositoryException e1 ) { LOG . debug ( "Could not get the node of the node: " + node , e1 ) ; } LOG . debug ( "Could not know if the mixin type " + JCROrganizationServiceImpl . JOS_DISABLED + " has been added to the node " + path , e ) ; } return true ; } }
Tests whether or not the specified node should be included in the node list .
165
16
15,647
public String getPositionSegment ( ) { HierarchicalProperty position = member . getChild ( new QName ( "DAV:" , "position" ) ) ; return position . getChild ( 0 ) . getChild ( new QName ( "DAV:" , "segment" ) ) . getValue ( ) ; }
Position segment getter .
69
5
15,648
public Response copy ( Session destSession , String sourcePath , String destPath ) { try { Workspace workspace = destSession . getWorkspace ( ) ; workspace . copy ( sourcePath , destPath ) ; // If the source resource was successfully moved // to a pre-existing destination resource. if ( itemExisted ) { return Response . noContent ( ) . build ( ) ; } // If the source resource was successfully moved, // and a new resource was created at the destination. else { if ( uriBuilder != null ) { return Response . created ( uriBuilder . path ( workspace . getName ( ) ) . path ( destPath ) . build ( ) ) . build ( ) ; } // to save compatibility if uribuilder is not provided return Response . status ( HTTPStatus . CREATED ) . build ( ) ; } } catch ( ItemExistsException e ) { return Response . status ( HTTPStatus . METHOD_NOT_ALLOWED ) . entity ( e . getMessage ( ) ) . build ( ) ; } catch ( PathNotFoundException e ) { return Response . status ( HTTPStatus . CONFLICT ) . entity ( e . getMessage ( ) ) . build ( ) ; } catch ( AccessDeniedException e ) { return Response . status ( HTTPStatus . FORBIDDEN ) . entity ( e . getMessage ( ) ) . build ( ) ; } catch ( LockException e ) { return Response . status ( HTTPStatus . LOCKED ) . entity ( e . getMessage ( ) ) . build ( ) ; } catch ( RepositoryException e ) { log . error ( e . getMessage ( ) , e ) ; return Response . serverError ( ) . entity ( e . getMessage ( ) ) . build ( ) ; } }
Webdav COPY method implementation for the same workspace .
374
12
15,649
public void execute ( ) throws IOException { // Future todo: Use JNI and librsync library? Runtime run = Runtime . getRuntime ( ) ; try { String command ; if ( excludeDir != null && ! excludeDir . isEmpty ( ) ) { command = "rsync -rv --delete --exclude " + excludeDir + " " + src + " " + dst ; } else { command = "rsync -rv --delete " + src + " " + dst ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Rsync job started: " + command ) ; } if ( userName != null && password != null ) { String [ ] envProperties = new String [ ] { RSYNC_USER_SYSTEM_PROPERTY + "=" + userName , RSYNC_PASSWORD_SYSTEM_PROPERTY + "=" + password } ; process = run . exec ( command , envProperties ) ; } else { process = run . exec ( command ) ; } // Handle process Standard and Error output InputStream stderr = process . getErrorStream ( ) ; InputStreamReader isrErr = new InputStreamReader ( stderr ) ; BufferedReader brErr = new BufferedReader ( isrErr ) ; InputStream stdout = process . getInputStream ( ) ; InputStreamReader isrStd = new InputStreamReader ( stdout ) ; BufferedReader brStd = new BufferedReader ( isrStd ) ; String val = null ; StringBuilder stringBuilderErr = new StringBuilder ( ) ; StringBuilder stringBuilderStd = new StringBuilder ( ) ; while ( ( val = brStd . readLine ( ) ) != null ) { stringBuilderStd . append ( val ) ; stringBuilderStd . append ( ' ' ) ; } while ( ( val = brErr . readLine ( ) ) != null ) { stringBuilderErr . append ( val ) ; stringBuilderErr . append ( ' ' ) ; } Integer returnCode = null ; // wait for thread while ( returnCode == null ) { try { returnCode = process . waitFor ( ) ; } catch ( InterruptedException e ) { // oops, this can happen sometimes } } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Rsync job finished: " + returnCode + ". Error stream output \n" + stringBuilderErr . toString ( ) + " Standard stream output \n" + stringBuilderStd . toString ( ) ) ; } if ( returnCode != 0 ) { throw new IOException ( "RSync job finished with exit code is " + returnCode + ". Error stream output: \n" + stringBuilderErr . toString ( ) ) ; } } finally { process = null ; } }
Executes RSYNC synchronization job
609
7
15,650
private List < ValueData > parseValues ( ) throws RepositoryException { List < ValueData > values = new ArrayList < ValueData > ( propertyInfo . getValuesSize ( ) ) ; List < String > stringValues = new ArrayList < String > ( ) ; for ( int k = 0 ; k < propertyInfo . getValuesSize ( ) ; k ++ ) { if ( propertyInfo . getType ( ) == PropertyType . BINARY ) { try { InputStream vStream = propertyInfo . getValues ( ) . get ( k ) . getInputStream ( ) ; TransientValueData binaryValue = new TransientValueData ( k , vStream , null , valueFactory . getSpoolConfig ( ) ) ; // Call to spool file into tmp binaryValue . getAsStream ( ) . close ( ) ; vStream . close ( ) ; propertyInfo . getValues ( ) . get ( k ) . remove ( ) ; values . add ( binaryValue ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } } else { String val = new String ( propertyInfo . getValues ( ) . get ( k ) . toString ( ) ) ; stringValues . add ( val ) ; values . add ( ( ( BaseValue ) valueFactory . createValue ( val , propertyInfo . getType ( ) ) ) . getInternalData ( ) ) ; } } if ( propertyInfo . getType ( ) == ExtendedPropertyType . PERMISSION ) { ImportNodeData currentNodeInfo = ( ImportNodeData ) getParent ( ) ; currentNodeInfo . setExoPrivileges ( stringValues ) ; } else if ( Constants . EXO_OWNER . equals ( propertyInfo . getName ( ) ) ) { ImportNodeData currentNodeInfo = ( ImportNodeData ) getParent ( ) ; currentNodeInfo . setExoOwner ( stringValues . get ( 0 ) ) ; } return values ; }
Returns the list of ValueData for current property
412
9
15,651
protected String getAttribute ( Map < String , String > attributes , InternalQName name ) throws RepositoryException { JCRName jname = locationFactory . createJCRName ( name ) ; return attributes . get ( jname . getAsString ( ) ) ; }
Returns the value of the named XML attribute .
56
9
15,652
protected void suspendRepository ( ) throws RepositoryException { SecurityHelper . validateSecurityPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; repository . setState ( ManageableRepository . SUSPENDED ) ; }
Suspend repository which means that allow only read operations . All writing threads will wait until resume operations invoked .
57
22
15,653
protected void resumeRepository ( ) throws RepositoryException { // Need privileges to manage repository. SecurityHelper . validateSecurityPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; repository . setState ( ManageableRepository . ONLINE ) ; }
Resume repository . All previously suspended threads continue working .
62
11
15,654
public static long getLength ( ValueData value , int propType ) { if ( propType == PropertyType . BINARY ) { return value . getLength ( ) ; } else if ( propType == PropertyType . NAME || propType == PropertyType . PATH ) { return - 1 ; } else { return value . toString ( ) . length ( ) ; } }
Returns length of the internal value .
78
7
15,655
@ Override public void recreateEntry ( final SessionProvider sessionProvider , final String groupPath , final RegistryEntry entry ) throws RepositoryException { final String entryRelPath = EXO_REGISTRY + "/" + groupPath + "/" + entry . getName ( ) ; final String parentFullPath = "/" + EXO_REGISTRY + "/" + groupPath ; try { Session session = session ( sessionProvider , repositoryService . getCurrentRepository ( ) ) ; // Don't care about concurrency, Session should be dedicated to the Thread, see JCR-765 // synchronized (session) { Node node = session . getRootNode ( ) . getNode ( entryRelPath ) ; // delete existing entry... node . remove ( ) ; // create same entry, // [PN] no check we need here, as we have deleted this node before // checkGroup(sessionProvider, fullParentPath); session . importXML ( parentFullPath , entry . getAsInputStream ( ) , IMPORT_UUID_CREATE_NEW ) ; // save recreated changes session . save ( ) ; // } } catch ( IOException ioe ) { throw new RepositoryException ( "Item " + parentFullPath + "can't be created " + ioe ) ; } catch ( TransformerException te ) { throw new RepositoryException ( "Can't get XML representation from stream " + te ) ; } }
Re - creates an entry in the group .
299
9
15,656
public void initRegistryEntry ( String groupName , String entryName ) throws RepositoryException , RepositoryConfigurationException { String relPath = EXO_REGISTRY + "/" + groupName + "/" + entryName ; for ( RepositoryEntry repConfiguration : repConfigurations ( ) ) { String repName = repConfiguration . getName ( ) ; SessionProvider sysProvider = SessionProvider . createSystemProvider ( ) ; Node root = session ( sysProvider , repositoryService . getRepository ( repName ) ) . getRootNode ( ) ; if ( ! root . hasNode ( relPath ) ) { root . addNode ( relPath , EXO_REGISTRYENTRY_NT ) ; root . save ( ) ; } else { LOG . info ( "The RegistryEntry " + relPath + "is already initialized on repository " + repName ) ; } sysProvider . close ( ) ; } }
Initializes the registry entry
192
5
15,657
public boolean getForceXMLConfigurationValue ( InitParams initParams ) { ValueParam valueParam = initParams . getValueParam ( "force-xml-configuration" ) ; return ( valueParam != null ? Boolean . valueOf ( valueParam . getValue ( ) ) : false ) ; }
Get value of force - xml - configuration param .
65
10
15,658
private void checkGroup ( final SessionProvider sessionProvider , final String groupPath ) throws RepositoryException { String [ ] groupNames = groupPath . split ( "/" ) ; String prefix = "/" + EXO_REGISTRY ; Session session = session ( sessionProvider , repositoryService . getCurrentRepository ( ) ) ; for ( String name : groupNames ) { String path = prefix + "/" + name ; try { Node group = ( Node ) session . getItem ( path ) ; if ( ! group . isNodeType ( EXO_REGISTRYGROUP_NT ) ) throw new RepositoryException ( "Node at " + path + " should be " + EXO_REGISTRYGROUP_NT + " type" ) ; } catch ( PathNotFoundException e ) { Node parent = ( Node ) session . getItem ( prefix ) ; parent . addNode ( name , EXO_REGISTRYGROUP_NT ) ; parent . save ( ) ; } prefix = path ; } }
check if group exists and creates one if necessary
211
9
15,659
private PlainChangesLog makeAutoCreatedItems ( final NodeData parent , final InternalQName nodeTypeName , final ItemDataConsumer targetDataManager , final String owner , boolean addedAutoCreatedNodes ) throws RepositoryException { final PlainChangesLogImpl changes = new PlainChangesLogImpl ( ) ; final NodeTypeData type = nodeTypeDataManager . getNodeType ( nodeTypeName ) ; changes . addAll ( makeAutoCreatedProperties ( parent , nodeTypeName , nodeTypeDataManager . getAllPropertyDefinitions ( nodeTypeName ) , targetDataManager , owner ) . getAllStates ( ) ) ; // Add autocreated child nodes changes . addAll ( makeAutoCreatedNodes ( parent , nodeTypeName , nodeTypeDataManager . getAllChildNodeDefinitions ( nodeTypeName ) , targetDataManager , owner ) . getAllStates ( ) ) ; // versionable if ( nodeTypeDataManager . isNodeType ( Constants . MIX_VERSIONABLE , new InternalQName [ ] { type . getName ( ) } ) ) { // using VH helper as for one new VH, all changes in changes log changes . addAll ( makeMixVesionableChanges ( parent ) . getAllStates ( ) ) ; } return changes ; }
Prepares changes log
268
4
15,660
@ GET @ Produces ( MediaType . APPLICATION_JSON ) @ RolesAllowed ( "administrators" ) @ Path ( "/repository-service-configuration" ) public Response getRepositoryServiceConfiguration ( ) { RepositoryServiceConfiguration configuration = repositoryService . getConfig ( ) ; RepositoryServiceConf conf = new RepositoryServiceConf ( configuration . getRepositoryConfigurations ( ) , configuration . getDefaultRepositoryName ( ) ) ; return Response . ok ( conf , MediaType . APPLICATION_JSON_TYPE ) . cacheControl ( NO_CACHE ) . build ( ) ; }
Gives the repository service configuration which is composed of the configuration of all the repositories and workspaces
129
19
15,661
@ GET @ Produces ( MediaType . APPLICATION_JSON ) @ RolesAllowed ( "administrators" ) @ Path ( "/default-ws-config/{repositoryName}" ) public Response getDefaultWorkspaceConfig ( @ PathParam ( "repositoryName" ) String repositoryName ) { String errorMessage = new String ( ) ; Status status ; try { String defaultWorkspaceName = repositoryService . getRepository ( repositoryName ) . getConfiguration ( ) . getDefaultWorkspaceName ( ) ; for ( WorkspaceEntry wEntry : repositoryService . getRepository ( repositoryName ) . getConfiguration ( ) . getWorkspaceEntries ( ) ) { if ( defaultWorkspaceName . equals ( wEntry . getName ( ) ) ) { return Response . ok ( wEntry ) . cacheControl ( NO_CACHE ) . build ( ) ; } } return Response . status ( Response . Status . NOT_FOUND ) . entity ( "Can not get default workspace configuration." ) . type ( MediaType . TEXT_PLAIN ) . cacheControl ( NO_CACHE ) . build ( ) ; } catch ( RepositoryException e ) { if ( log . isDebugEnabled ( ) ) { log . error ( e . getMessage ( ) , e ) ; } errorMessage = e . getMessage ( ) ; status = Status . NOT_FOUND ; } catch ( Throwable e ) //NOSONAR { if ( log . isDebugEnabled ( ) ) { log . error ( e . getMessage ( ) , e ) ; } errorMessage = e . getMessage ( ) ; status = Status . INTERNAL_SERVER_ERROR ; } return Response . status ( status ) . entity ( errorMessage ) . type ( MediaType . TEXT_PLAIN_TYPE ) . cacheControl ( NO_CACHE ) . build ( ) ; }
Gives the configuration of the default workspace of the given repository
398
12
15,662
@ GET @ Produces ( MediaType . APPLICATION_JSON ) @ RolesAllowed ( "administrators" ) @ Path ( "/repositories" ) public Response getRepositoryNames ( ) { List < String > repositories = new ArrayList < String > ( ) ; for ( RepositoryEntry rEntry : repositoryService . getConfig ( ) . getRepositoryConfigurations ( ) ) { repositories . add ( rEntry . getName ( ) ) ; } return Response . ok ( new NamesList ( repositories ) ) . cacheControl ( NO_CACHE ) . build ( ) ; }
Gives the name of all the existing repositories .
126
10
15,663
@ GET @ Produces ( MediaType . APPLICATION_JSON ) @ RolesAllowed ( "administrators" ) @ Path ( "/workspaces/{repositoryName}" ) public Response getWorkspaceNames ( @ PathParam ( "repositoryName" ) String repositoryName ) { String errorMessage = new String ( ) ; Status status ; try { List < String > workspaces = new ArrayList < String > ( ) ; for ( WorkspaceEntry wEntry : repositoryService . getRepository ( repositoryName ) . getConfiguration ( ) . getWorkspaceEntries ( ) ) { workspaces . add ( wEntry . getName ( ) ) ; } return Response . ok ( new NamesList ( workspaces ) ) . cacheControl ( NO_CACHE ) . build ( ) ; } catch ( RepositoryException e ) { if ( log . isDebugEnabled ( ) ) { log . error ( e . getMessage ( ) , e ) ; } errorMessage = e . getMessage ( ) ; status = Status . NOT_FOUND ; } catch ( Throwable e ) //NOSONAR { if ( log . isDebugEnabled ( ) ) { log . error ( e . getMessage ( ) , e ) ; } errorMessage = e . getMessage ( ) ; status = Status . INTERNAL_SERVER_ERROR ; } return Response . status ( status ) . entity ( errorMessage ) . type ( MediaType . TEXT_PLAIN_TYPE ) . cacheControl ( NO_CACHE ) . build ( ) ; }
Gives the name of all the existing workspaces for a given repository .
327
15
15,664
@ POST @ Consumes ( MediaType . APPLICATION_JSON ) @ RolesAllowed ( "administrators" ) @ Path ( "/update-workspace-config/{repositoryName}/{workspaceName}" ) public Response updateWorkspaceConfiguration ( @ PathParam ( "repositoryName" ) String repositoryName , @ PathParam ( "workspaceName" ) String workspaceName , WorkspaceEntry workspaceEntry ) { return Response . status ( Status . OK ) . entity ( "The method /update-workspace-config not implemented." ) . type ( MediaType . TEXT_PLAIN_TYPE ) . cacheControl ( NO_CACHE ) . build ( ) ; }
Updates the configuration of a given workspace .
147
9
15,665
private String setProperty ( Node node , HierarchicalProperty property ) { String propertyName = WebDavNamespaceContext . createName ( property . getName ( ) ) ; if ( READ_ONLY_PROPS . contains ( property . getName ( ) ) ) { return WebDavConst . getStatusDescription ( HTTPStatus . CONFLICT ) ; } try { Workspace ws = node . getSession ( ) . getWorkspace ( ) ; NodeTypeDataManager nodeTypeHolder = ( ( WorkspaceImpl ) ws ) . getNodeTypesHolder ( ) ; NodeData data = ( NodeData ) ( ( NodeImpl ) node ) . getData ( ) ; InternalQName propName = ( ( SessionImpl ) node . getSession ( ) ) . getLocationFactory ( ) . parseJCRName ( propertyName ) . getInternalName ( ) ; PropertyDefinitionDatas propdefs = nodeTypeHolder . getPropertyDefinitions ( propName , data . getPrimaryTypeName ( ) , data . getMixinTypeNames ( ) ) ; if ( propdefs == null ) { throw new RepositoryException ( ) ; } PropertyDefinitionData propertyDefinitionData = propdefs . getAnyDefinition ( ) ; if ( propertyDefinitionData == null ) { throw new RepositoryException ( ) ; } boolean isMultiValued = propertyDefinitionData . isMultiple ( ) ; if ( node . isNodeType ( WebDavConst . NodeTypes . MIX_VERSIONABLE ) && ! node . isCheckedOut ( ) ) { node . checkout ( ) ; node . save ( ) ; } if ( ! isMultiValued ) { node . setProperty ( propertyName , property . getValue ( ) ) ; } else { String [ ] value = new String [ 1 ] ; value [ 0 ] = property . getValue ( ) ; node . setProperty ( propertyName , value ) ; } node . save ( ) ; return WebDavConst . getStatusDescription ( HTTPStatus . OK ) ; } catch ( AccessDeniedException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . FORBIDDEN ) ; } catch ( ItemNotFoundException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . NOT_FOUND ) ; } catch ( PathNotFoundException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . NOT_FOUND ) ; } catch ( RepositoryException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . CONFLICT ) ; } }
Sets changes the property value .
542
7
15,666
private String removeProperty ( Node node , HierarchicalProperty property ) { try { node . getProperty ( property . getStringName ( ) ) . remove ( ) ; node . save ( ) ; return WebDavConst . getStatusDescription ( HTTPStatus . OK ) ; } catch ( AccessDeniedException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . FORBIDDEN ) ; } catch ( ItemNotFoundException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . NOT_FOUND ) ; } catch ( PathNotFoundException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . NOT_FOUND ) ; } catch ( RepositoryException e ) { return WebDavConst . getStatusDescription ( HTTPStatus . CONFLICT ) ; } }
Removes the property .
173
5
15,667
public Response head ( Session session , String path , String baseURI ) { try { Node node = ( Node ) session . getItem ( path ) ; WebDavNamespaceContext nsContext = new WebDavNamespaceContext ( session ) ; URI uri = new URI ( TextUtil . escape ( baseURI + node . getPath ( ) , ' ' , true ) ) ; if ( ResourceUtil . isFile ( node ) ) { Resource resource = new FileResource ( uri , node , nsContext ) ; String lastModified = resource . getProperty ( PropertyConstants . GETLASTMODIFIED ) . getValue ( ) ; String contentType = resource . getProperty ( PropertyConstants . GETCONTENTTYPE ) . getValue ( ) ; String contentLength = resource . getProperty ( PropertyConstants . GETCONTENTLENGTH ) . getValue ( ) ; return Response . ok ( ) . header ( ExtHttpHeaders . LAST_MODIFIED , lastModified ) . header ( ExtHttpHeaders . CONTENT_TYPE , contentType ) . header ( ExtHttpHeaders . CONTENT_LENGTH , contentLength ) . build ( ) ; } return Response . ok ( ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . NOT_FOUND ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav Head method implementation .
341
7
15,668
public void remove ( ItemState item ) { if ( item . isNode ( ) ) { remove ( item . getData ( ) . getQPath ( ) ) ; } else { removeProperty ( item , - 1 ) ; } }
Removes the property or node and all descendants from the log
49
12
15,669
public void remove ( QPath rootPath ) { for ( int i = items . size ( ) - 1 ; i >= 0 ; i -- ) { ItemState item = items . get ( i ) ; QPath qPath = item . getData ( ) . getQPath ( ) ; if ( qPath . isDescendantOf ( rootPath ) || item . getAncestorToSave ( ) . isDescendantOf ( rootPath ) || item . getAncestorToSave ( ) . equals ( rootPath ) || qPath . equals ( rootPath ) ) { if ( item . isNode ( ) ) { removeNode ( item , i ) ; } else { removeProperty ( item , i ) ; } } } }
Removes the item at the rootPath and all descendants from the log
154
14
15,670
private void removeNode ( ItemState item , int indexItem ) { items . remove ( indexItem ) ; index . remove ( item . getData ( ) . getIdentifier ( ) ) ; index . remove ( item . getData ( ) . getQPath ( ) ) ; index . remove ( new ParentIDQPathBasedKey ( item ) ) ; index . remove ( new IDStateBasedKey ( item . getData ( ) . getIdentifier ( ) , item . getState ( ) ) ) ; childNodesInfo . remove ( item . getData ( ) . getIdentifier ( ) ) ; lastChildNodeStates . remove ( item . getData ( ) . getIdentifier ( ) ) ; childNodeStates . remove ( item . getData ( ) . getIdentifier ( ) ) ; if ( allPathsChanged != null && item . isPathChanged ( ) ) { allPathsChanged . remove ( item ) ; if ( allPathsChanged . isEmpty ( ) ) allPathsChanged = null ; } if ( item . isPersisted ( ) ) { int childInfo [ ] = childNodesInfo . get ( item . getData ( ) . getParentIdentifier ( ) ) ; if ( childInfo != null ) { if ( item . isDeleted ( ) ) { ++ childInfo [ CHILD_NODES_COUNT ] ; } else if ( item . isAdded ( ) ) { -- childInfo [ CHILD_NODES_COUNT ] ; } childNodesInfo . put ( item . getData ( ) . getParentIdentifier ( ) , childInfo ) ; } } Map < String , ItemState > children = lastChildNodeStates . get ( item . getData ( ) . getParentIdentifier ( ) ) ; if ( children != null ) { children . remove ( item . getData ( ) . getIdentifier ( ) ) ; if ( children . isEmpty ( ) ) { lastChildNodeStates . remove ( item . getData ( ) . getParentIdentifier ( ) ) ; } } List < ItemState > listItemStates = childNodeStates . get ( item . getData ( ) . getParentIdentifier ( ) ) ; if ( listItemStates != null ) { listItemStates . remove ( item ) ; if ( listItemStates . isEmpty ( ) ) { childNodeStates . remove ( item . getData ( ) . getParentIdentifier ( ) ) ; } } if ( ( children == null || children . isEmpty ( ) ) && ( listItemStates == null || listItemStates . isEmpty ( ) ) ) { childNodesInfo . remove ( item . getData ( ) . getParentIdentifier ( ) ) ; } }
Removes the node from the log
574
7
15,671
private void removeProperty ( ItemState item , int indexItem ) { if ( indexItem == - 1 ) { items . remove ( item ) ; } else { items . remove ( indexItem ) ; } index . remove ( item . getData ( ) . getIdentifier ( ) ) ; index . remove ( item . getData ( ) . getQPath ( ) ) ; index . remove ( new ParentIDQPathBasedKey ( item ) ) ; index . remove ( new IDStateBasedKey ( item . getData ( ) . getIdentifier ( ) , item . getState ( ) ) ) ; lastChildPropertyStates . remove ( item . getData ( ) . getIdentifier ( ) ) ; childPropertyStates . remove ( item . getData ( ) . getIdentifier ( ) ) ; Map < String , ItemState > children = lastChildPropertyStates . get ( item . getData ( ) . getParentIdentifier ( ) ) ; if ( children != null ) { children . remove ( item . getData ( ) . getIdentifier ( ) ) ; if ( children . isEmpty ( ) ) { lastChildPropertyStates . remove ( item . getData ( ) . getParentIdentifier ( ) ) ; } } List < ItemState > listItemStates = childPropertyStates . get ( item . getData ( ) . getParentIdentifier ( ) ) ; if ( listItemStates != null ) { listItemStates . remove ( item ) ; if ( listItemStates . isEmpty ( ) ) { childPropertyStates . remove ( item . getData ( ) . getParentIdentifier ( ) ) ; } } }
Removes the property from the log
341
7
15,672
public Collection < ItemState > getLastChildrenStates ( ItemData rootData , boolean forNodes ) { Map < String , ItemState > children = forNodes ? lastChildNodeStates . get ( rootData . getIdentifier ( ) ) : lastChildPropertyStates . get ( rootData . getIdentifier ( ) ) ; return children == null ? new ArrayList < ItemState > ( ) : children . values ( ) ; }
Collect last in ChangesLog order item child changes .
91
10
15,673
public ItemState getLastState ( ItemData item , boolean forNode ) { Map < String , ItemState > children = forNode ? lastChildNodeStates . get ( item . getParentIdentifier ( ) ) : lastChildPropertyStates . get ( item . getParentIdentifier ( ) ) ; return children == null ? null : children . get ( item . getIdentifier ( ) ) ; }
Return the last item state from ChangesLog .
83
9
15,674
public List < ItemState > getChildrenChanges ( String rootIdentifier , boolean forNodes ) { List < ItemState > children = forNodes ? childNodeStates . get ( rootIdentifier ) : childPropertyStates . get ( rootIdentifier ) ; return children == null ? new ArrayList < ItemState > ( ) : children ; }
Collect changes of all item direct childs . Including the item itself .
72
14
15,675
public ItemState getItemState ( String itemIdentifier , int state ) { return index . get ( new IDStateBasedKey ( itemIdentifier , state ) ) ; }
Get ItemState by identifier and state .
36
8
15,676
public ItemState getItemState ( NodeData parentData , QPathEntry name , ItemType itemType ) throws IllegalPathException { if ( itemType != ItemType . UNKNOWN ) { return index . get ( new ParentIDQPathBasedKey ( parentData . getIdentifier ( ) , name , itemType ) ) ; } else { ItemState state = index . get ( new ParentIDQPathBasedKey ( parentData . getIdentifier ( ) , name , ItemType . NODE ) ) ; if ( state == null ) { state = index . get ( new ParentIDQPathBasedKey ( parentData . getIdentifier ( ) , name , ItemType . PROPERTY ) ) ; } return state ; } }
Get ItemState by parent and item name .
153
9
15,677
public List < ItemState > getItemStates ( String itemIdentifier ) { List < ItemState > states = new ArrayList < ItemState > ( ) ; List < ItemState > currentStates = getAllStates ( ) ; for ( int i = 0 , length = currentStates . size ( ) ; i < length ; i ++ ) { ItemState state = currentStates . get ( i ) ; if ( state . getData ( ) . getIdentifier ( ) . equals ( itemIdentifier ) ) { states . add ( state ) ; } } return states ; }
Gets items by identifier .
119
6
15,678
public ItemState findItemState ( String id , Boolean isPersisted , int ... states ) throws IllegalPathException { List < ItemState > allStates = getAllStates ( ) ; // search from the end for state for ( int i = allStates . size ( ) - 1 ; i >= 0 ; i -- ) { ItemState istate = allStates . get ( i ) ; boolean byState = false ; if ( states != null ) { for ( int state : states ) { if ( istate . getState ( ) == state ) { byState = true ; break ; } } } else { byState = true ; } if ( byState && ( isPersisted != null ? istate . isPersisted ( ) == isPersisted : true ) && istate . getData ( ) . getIdentifier ( ) . equals ( id ) ) { return istate ; } } return null ; }
Search for an item state of item with given id and filter parameters .
195
14
15,679
private String checkIfFile ( Node node ) { return ResourceUtil . isFile ( node ) ? Boolean . TRUE . toString ( ) : Boolean . FALSE . toString ( ) ; }
Checks if node is file or folder .
40
9
15,680
private void onConnectionClosed ( ) { ConnectionEvent evt = new ConnectionEvent ( this , ConnectionEvent . CONNECTION_CLOSED ) ; for ( ConnectionEventListener listener : listeners ) { try { listener . connectionClosed ( evt ) ; } catch ( Exception e1 ) { LOG . warn ( "An error occurs while notifying the listener " + listener , e1 ) ; } } }
Broadcasts the connection closed event
85
6
15,681
public PropertyDefinitionData [ ] readPropertyDefinitions ( NodeData nodeData ) throws NodeTypeReadException , RepositoryException { List < PropertyDefinitionData > propertyDefinitionDataList ; List < NodeData > childDefinitions = dataManager . getChildNodesData ( nodeData ) ; InternalQName name = null ; if ( childDefinitions . size ( ) > 0 ) name = readMandatoryName ( nodeData , null , Constants . JCR_NODETYPENAME ) ; else return new PropertyDefinitionData [ 0 ] ; propertyDefinitionDataList = new ArrayList < PropertyDefinitionData > ( ) ; for ( NodeData childDefinition : childDefinitions ) { if ( Constants . NT_PROPERTYDEFINITION . equals ( childDefinition . getPrimaryTypeName ( ) ) ) { propertyDefinitionDataList . add ( propertyDefinitionAccessProvider . read ( childDefinition , name ) ) ; } } return propertyDefinitionDataList . toArray ( new PropertyDefinitionData [ propertyDefinitionDataList . size ( ) ] ) ; }
Read PropertyDefinitionData of node type .
219
8
15,682
public static String getPath ( String relativePath , String backupDirCanonicalPath ) throws MalformedURLException { String path = "file:" + backupDirCanonicalPath + "/" + relativePath ; URL urlPath = new URL ( resolveFileURL ( path ) ) ; return urlPath . getFile ( ) ; }
Will be returned absolute path .
71
6
15,683
protected void rollback ( WorkspaceStorageConnection conn ) { try { if ( conn != null ) { conn . rollback ( ) ; } } catch ( IllegalStateException e ) { LOG . error ( "Can not rollback connection" , e ) ; } catch ( RepositoryException e ) { LOG . error ( "Can not rollback connection" , e ) ; } }
Rollback data .
79
4
15,684
private void cleanupSwapDirectory ( ) { PrivilegedAction < Void > action = new PrivilegedAction < Void > ( ) { public Void run ( ) { File [ ] files = containerConfig . spoolConfig . tempDirectory . listFiles ( ) ; if ( files != null && files . length > 0 ) { LOG . info ( "Some files have been found in the swap directory and will be deleted" ) ; for ( int i = 0 ; i < files . length ; i ++ ) { File file = files [ i ] ; // We don't use the file cleaner in case the deletion failed to ensure // that the file won't be deleted while it is currently re-used file . delete ( ) ; } } return null ; } } ; SecurityHelper . doPrivilegedAction ( action ) ; }
Deletes all the files from the swap directory
168
9
15,685
protected void checkIntegrity ( WorkspaceEntry wsConfig , RepositoryEntry repConfig ) throws RepositoryConfigurationException { DatabaseStructureType dbType = DBInitializerHelper . getDatabaseType ( wsConfig ) ; for ( WorkspaceEntry wsEntry : repConfig . getWorkspaceEntries ( ) ) { if ( wsEntry . getName ( ) . equals ( wsConfig . getName ( ) ) || ! wsEntry . getContainer ( ) . getType ( ) . equals ( wsConfig . getContainer ( ) . getType ( ) ) || ! wsEntry . getContainer ( ) . getType ( ) . equals ( this . getClass ( ) . getName ( ) ) ) { continue ; } if ( ! DBInitializerHelper . getDatabaseType ( wsEntry ) . equals ( dbType ) ) { throw new RepositoryConfigurationException ( "All workspaces must be of same DB type. But " + wsEntry . getName ( ) + "=" + DBInitializerHelper . getDatabaseType ( wsEntry ) + " and " + wsConfig . getName ( ) + "=" + dbType ) ; } // source name String wsSourceName = null ; String newWsSourceName = null ; try { wsSourceName = wsEntry . getContainer ( ) . getParameterValue ( "sourceName" ) ; newWsSourceName = wsConfig . getContainer ( ) . getParameterValue ( "sourceName" ) ; } catch ( RepositoryConfigurationException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } if ( wsSourceName != null && newWsSourceName != null ) { if ( dbType . isShareSameDatasource ( ) ) { if ( ! wsSourceName . equals ( newWsSourceName ) ) { throw new RepositoryConfigurationException ( "SourceName must be equals in " + dbType + "-database repository." + " Check " + wsEntry . getName ( ) + " and " + wsConfig . getName ( ) ) ; } } else { if ( wsSourceName . equals ( newWsSourceName ) ) { throw new RepositoryConfigurationException ( "SourceName " + wsSourceName + " already in use in " + wsEntry . getName ( ) + ". SourceName must be different in " + dbType + "-database structure type. Check configuration for " + wsConfig . getName ( ) ) ; } } continue ; } } }
Checks if DataSources used in right manner .
552
10
15,686
private String validateDialect ( String confParam ) { for ( String dbType : DBConstants . DB_DIALECTS ) { if ( confParam . equals ( dbType ) ) { return dbType ; } } return DBConstants . DB_DIALECT_AUTO ; // by default }
Validate dialect .
69
4
15,687
private String composeWorkspaceUniqueName ( String repositoryName , String workspaceName ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( repositoryName ) ; builder . append ( ' ' ) ; builder . append ( workspaceName ) ; builder . append ( ' ' ) ; return builder . toString ( ) ; }
Compose unique workspace name in global JCR instance .
68
11
15,688
private void waitForCoordinator ( ) { LOG . info ( "Waiting to be released by the coordinator" ) ; try { lock . await ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } }
Make the current node wait until being released by the coordinator
56
11
15,689
public static void configureCacheStore ( MappedParametrizedObjectEntry parameterEntry , String dataSourceParamName , String dataColumnParamName , String idColumnParamName , String timeColumnParamName , String dialectParamName ) throws RepositoryException { String dataSourceName = parameterEntry . getParameterValue ( dataSourceParamName , null ) ; String dialect = parameterEntry . getParameterValue ( dialectParamName , DBConstants . DB_DIALECT_AUTO ) . toUpperCase ( ) ; // if data source is defined, then inject correct data-types. // Also it cans be not defined and nothing should be injected // (i.e. no cache loader is used (possibly pattern is changed, to used another cache loader)) DataSource dataSource ; try { dataSource = ( DataSource ) new InitialContext ( ) . lookup ( dataSourceName ) ; } catch ( NamingException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } String blobType ; String charType ; String timeStampType ; try { blobType = JDBCUtils . getAppropriateBlobType ( dataSource ) ; if ( dialect . startsWith ( DBConstants . DB_DIALECT_MYSQL ) && dialect . endsWith ( "-UTF8" ) ) { charType = "VARCHAR(255)" ; } else { charType = JDBCUtils . getAppropriateCharType ( dataSource ) ; } timeStampType = JDBCUtils . getAppropriateTimestamp ( dataSource ) ; } catch ( SQLException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } // set parameters if not defined // if parameter is missing in configuration, then // getParameterValue(INFINISPAN_JDBC_CL_DATA_COLUMN, INFINISPAN_JDBC_CL_AUTO) // will return INFINISPAN_JDBC_CL_AUTO. If parameter is present in configuration and //equals to "auto", then it should be replaced // with correct value for given database if ( parameterEntry . getParameterValue ( dataColumnParamName , "auto" ) . equalsIgnoreCase ( "auto" ) ) { parameterEntry . putParameterValue ( dataColumnParamName , blobType ) ; } if ( parameterEntry . getParameterValue ( idColumnParamName , "auto" ) . equalsIgnoreCase ( "auto" ) ) { parameterEntry . putParameterValue ( idColumnParamName , charType ) ; } if ( parameterEntry . getParameterValue ( timeColumnParamName , "auto" ) . equalsIgnoreCase ( "auto" ) ) { parameterEntry . putParameterValue ( timeColumnParamName , timeStampType ) ; } }
If a cache store is used then fills - in column types . If column type configured from jcr - configuration file then nothing is overridden . Parameters are injected into the given parameterEntry .
603
38
15,690
@ Group public final String getGroup ( ) { if ( fullGroupName != null ) { return fullGroupName ; } StringBuilder sb = new StringBuilder ( ) ; if ( ownerId != null ) { sb . append ( ownerId ) . append ( ' ' ) ; } return fullGroupName = sb . append ( group == null ? id : group ) . toString ( ) ; }
This method is used for the grouping when its enabled . It will return the value of the group if it has been explicitly set otherwise it will return the value of the fullId
85
35
15,691
public long getGlobalDataSizeDirectly ( ) throws QuotaManagerException { long size = 0 ; for ( RepositoryQuotaManager rqm : rQuotaManagers . values ( ) ) { size += rqm . getRepositoryDataSizeDirectly ( ) ; } return size ; }
Calculates the global size by summing sized of all repositories .
64
14
15,692
private PathQueryNode createPathQueryNode ( SimpleNode node ) { root . setLocationNode ( factory . createPathQueryNode ( root ) ) ; node . childrenAccept ( this , root . getLocationNode ( ) ) ; return root . getLocationNode ( ) ; }
Creates the primary path query node .
57
8
15,693
public static Calendar parse ( String dateString ) throws ValueFormatException { try { return ISO8601 . parseEx ( dateString ) ; } catch ( ParseException e ) { throw new ValueFormatException ( "Can not parse date from [" + dateString + "]" , e ) ; } catch ( NumberFormatException e ) { throw new ValueFormatException ( "Can not parse date from [" + dateString + "]" , e ) ; } }
Parse string using possible formats list .
94
8
15,694
public static long createHash ( byte [ ] data ) { long h = 0 ; byte [ ] res ; synchronized ( digestFunction ) { res = digestFunction . digest ( data ) ; } for ( int i = 0 ; i < 4 ; i ++ ) { h <<= 8 ; h |= ( ( int ) res [ i ] ) & 0xFF ; } return h ; }
Generates a digest based on the contents of an array of bytes .
81
14
15,695
public static void backup ( File storageDir , Connection jdbcConn , Map < String , String > scripts ) throws BackupException { Exception exc = null ; ZipObjectWriter contentWriter = null ; ZipObjectWriter contentLenWriter = null ; try { contentWriter = new ZipObjectWriter ( PrivilegedFileHelper . zipOutputStream ( new File ( storageDir , CONTENT_ZIP_FILE ) ) ) ; contentLenWriter = new ZipObjectWriter ( PrivilegedFileHelper . zipOutputStream ( new File ( storageDir , CONTENT_LEN_ZIP_FILE ) ) ) ; for ( Entry < String , String > entry : scripts . entrySet ( ) ) { dumpTable ( jdbcConn , entry . getKey ( ) , entry . getValue ( ) , storageDir , contentWriter , contentLenWriter ) ; } } catch ( IOException e ) { exc = e ; throw new BackupException ( e ) ; } catch ( SQLException e ) { exc = e ; throw new BackupException ( "SQL Exception: " + JDBCUtils . getFullMessage ( e ) , e ) ; } finally { if ( jdbcConn != null ) { try { jdbcConn . close ( ) ; } catch ( SQLException e ) { if ( exc != null ) { LOG . error ( "Can't close connection" , e ) ; throw new BackupException ( exc ) ; } else { throw new BackupException ( e ) ; } } } try { if ( contentWriter != null ) { contentWriter . close ( ) ; } if ( contentLenWriter != null ) { contentLenWriter . close ( ) ; } } catch ( IOException e ) { if ( exc != null ) { LOG . error ( "Can't close zip" , e ) ; throw new BackupException ( exc ) ; } else { throw new BackupException ( e ) ; } } } }
Backup tables .
400
4
15,696
private static void dumpTable ( Connection jdbcConn , String tableName , String script , File storageDir , ZipObjectWriter contentWriter , ZipObjectWriter contentLenWriter ) throws IOException , SQLException { SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; } Statement stmt = null ; ResultSet rs = null ; try { contentWriter . putNextEntry ( new ZipEntry ( tableName ) ) ; contentLenWriter . putNextEntry ( new ZipEntry ( tableName ) ) ; stmt = jdbcConn . createStatement ( java . sql . ResultSet . TYPE_FORWARD_ONLY , java . sql . ResultSet . CONCUR_READ_ONLY ) ; stmt . setFetchSize ( FETCH_SIZE ) ; rs = stmt . executeQuery ( script ) ; ResultSetMetaData metaData = rs . getMetaData ( ) ; int columnCount = metaData . getColumnCount ( ) ; int [ ] columnType = new int [ columnCount ] ; contentWriter . writeInt ( columnCount ) ; for ( int i = 0 ; i < columnCount ; i ++ ) { columnType [ i ] = metaData . getColumnType ( i + 1 ) ; contentWriter . writeInt ( columnType [ i ] ) ; contentWriter . writeString ( metaData . getColumnName ( i + 1 ) ) ; } byte [ ] tmpBuff = new byte [ 2048 ] ; // Now we can output the actual data while ( rs . next ( ) ) { for ( int i = 0 ; i < columnCount ; i ++ ) { InputStream value ; if ( columnType [ i ] == Types . VARBINARY || columnType [ i ] == Types . LONGVARBINARY || columnType [ i ] == Types . BLOB || columnType [ i ] == Types . BINARY || columnType [ i ] == Types . OTHER ) { value = rs . getBinaryStream ( i + 1 ) ; } else { String str = rs . getString ( i + 1 ) ; value = str == null ? null : new ByteArrayInputStream ( str . getBytes ( Constants . DEFAULT_ENCODING ) ) ; } if ( value == null ) { contentLenWriter . writeLong ( - 1 ) ; } else { long len = 0 ; int read = 0 ; while ( ( read = value . read ( tmpBuff ) ) >= 0 ) { contentWriter . write ( tmpBuff , 0 , read ) ; len += read ; } contentLenWriter . writeLong ( len ) ; } } } contentWriter . closeEntry ( ) ; contentLenWriter . closeEntry ( ) ; } finally { if ( rs != null ) { rs . close ( ) ; } if ( stmt != null ) { stmt . close ( ) ; } } }
Dump table .
628
4
15,697
BackupChain startBackup ( BackupConfig config , BackupJobListener jobListener ) throws BackupOperationException , BackupConfigurationException , RepositoryException , RepositoryConfigurationException { validateBackupConfig ( config ) ; Calendar startTime = Calendar . getInstance ( ) ; File dir = FileNameProducer . generateBackupSetDir ( config . getRepository ( ) , config . getWorkspace ( ) , config . getBackupDir ( ) . getPath ( ) , startTime ) ; PrivilegedFileHelper . mkdirs ( dir ) ; config . setBackupDir ( dir ) ; BackupChain bchain = new BackupChainImpl ( config , logsDirectory , repoService , fullBackupType , incrementalBackupType , IdGenerator . generate ( ) , logsDirectory , startTime ) ; bchain . addListener ( messagesListener ) ; bchain . addListener ( jobListener ) ; currentBackups . add ( bchain ) ; bchain . startBackup ( ) ; return bchain ; }
Internally used for call with job listener from scheduler .
211
12
15,698
private void validateBackupConfig ( RepositoryBackupConfig config ) throws BackupConfigurationException { if ( config . getIncrementalJobPeriod ( ) < 0 ) { throw new BackupConfigurationException ( "The parameter 'incremental job period' can not be negative." ) ; } if ( config . getIncrementalJobNumber ( ) < 0 ) { throw new BackupConfigurationException ( "The parameter 'incremental job number' can not be negative." ) ; } if ( config . getIncrementalJobPeriod ( ) == 0 && config . getBackupType ( ) == BackupManager . FULL_AND_INCREMENTAL ) { config . setIncrementalJobPeriod ( defaultIncrementalJobPeriod ) ; } }
Initialize backup chain to workspace backup .
152
8
15,699
private void readParamsFromFile ( ) { PropertiesParam pps = initParams . getPropertiesParam ( BACKUP_PROPERTIES ) ; backupDir = pps . getProperty ( BACKUP_DIR ) ; // full backup type can be not defined. Using default. fullBackupType = pps . getProperty ( FULL_BACKUP_TYPE ) == null ? DEFAULT_VALUE_FULL_BACKUP_TYPE : pps . getProperty ( FULL_BACKUP_TYPE ) ; // incremental backup can be not configured. Using default values. defIncrPeriod = pps . getProperty ( DEFAULT_INCREMENTAL_JOB_PERIOD ) == null ? DEFAULT_VALUE_INCREMENTAL_JOB_PERIOD : pps . getProperty ( DEFAULT_INCREMENTAL_JOB_PERIOD ) ; incrementalBackupType = pps . getProperty ( INCREMENTAL_BACKUP_TYPE ) == null ? DEFAULT_VALUE_INCREMENTAL_BACKUP_TYPE : pps . getProperty ( INCREMENTAL_BACKUP_TYPE ) ; LOG . info ( "Backup dir from configuration file: " + backupDir ) ; LOG . info ( "Full backup type from configuration file: " + fullBackupType ) ; LOG . info ( "(Experimental) Incremental backup type from configuration file: " + incrementalBackupType ) ; LOG . info ( "(Experimental) Default incremental job period from configuration file: " + defIncrPeriod ) ; checkParams ( ) ; }
Get parameters which passed from the file .
339
8