idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
15,800
protected String createDefaultExcerpt ( String text , String excerptStart , String excerptEnd , String fragmentStart , String fragmentEnd , int maxLength ) throws IOException { StringReader reader = new StringReader ( text ) ; StringBuilder excerpt = new StringBuilder ( excerptStart ) ; excerpt . append ( fragmentStart ) ; if ( ! text . isEmpty ( ) ) { int min = excerpt . length ( ) ; char [ ] buf = new char [ maxLength ] ; int len = reader . read ( buf ) ; StringBuilder tmp = new StringBuilder ( ) ; tmp . append ( buf , 0 , len ) ; if ( len == buf . length ) { for ( int i = tmp . length ( ) - 1 ; i > min ; i -- ) { if ( Character . isWhitespace ( tmp . charAt ( i ) ) ) { tmp . delete ( i , tmp . length ( ) ) ; tmp . append ( " ..." ) ; break ; } } } excerpt . append ( Text . encodeIllegalXMLCharacters ( tmp . toString ( ) ) ) ; } excerpt . append ( fragmentEnd ) . append ( excerptEnd ) ; return excerpt . toString ( ) ; }
Creates a default excerpt with the given text .
15,801
protected void putItem ( final ItemData data ) { cache . put ( new CacheId ( data . getIdentifier ( ) ) , new CacheValue ( data , System . currentTimeMillis ( ) + liveTime ) ) ; cache . put ( new CacheQPath ( data . getParentIdentifier ( ) , data . getQPath ( ) , ItemType . getItemType ( data ) ) , new CacheValue ( data , System . currentTimeMillis ( ) + liveTime ) ) ; }
Put item in cache C .
15,802
protected ItemData getItem ( final String identifier ) { long start = System . currentTimeMillis ( ) ; try { final CacheId k = new CacheId ( identifier ) ; final CacheValue v = cache . get ( k ) ; if ( v != null ) { final ItemData c = v . getItem ( ) ; if ( v . getExpiredTime ( ) > System . currentTimeMillis ( ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( name + ", getItem() " + identifier + " + ( c != null ? c . getQPath ( ) . getAsString ( ) + " parent:" + c . getParentIdentifier ( ) : "[null]" ) ) ; } hits . incrementAndGet ( ) ; return c ; } writeLock . lock ( ) ; try { cache . remove ( k ) ; cache . remove ( new CacheQPath ( c . getParentIdentifier ( ) , c . getQPath ( ) , ItemType . getItemType ( c ) ) ) ; if ( c . isNode ( ) ) { nodesCache . remove ( c . getIdentifier ( ) ) ; propertiesCache . remove ( c . getIdentifier ( ) ) ; } } finally { writeLock . unlock ( ) ; } } miss . incrementAndGet ( ) ; return null ; } finally { totalGetTime += System . currentTimeMillis ( ) - start ; } }
Get item from cache C by item id . Checks is it expired calcs statistics .
15,803
public void setLiveTime ( long liveTime ) { writeLock . lock ( ) ; try { this . liveTime = liveTime ; } finally { writeLock . unlock ( ) ; } LOG . info ( name + " : set liveTime=" + liveTime + "ms. New value will be applied to items cached from this moment." ) ; }
Set liveTime of newly cached items .
15,804
protected void removeItem ( final ItemData item ) { final String itemId = item . getIdentifier ( ) ; cache . remove ( new CacheId ( itemId ) ) ; final CacheValue v2 = cache . remove ( new CacheQPath ( item . getParentIdentifier ( ) , item . getQPath ( ) , ItemType . getItemType ( item ) ) ) ; if ( v2 != null && ! v2 . getItem ( ) . getIdentifier ( ) . equals ( itemId ) ) { removeItem ( v2 . getItem ( ) ) ; } }
Remove item from cache C .
15,805
protected PropertyData removeChildProperty ( final String parentIdentifier , final String childIdentifier ) { final List < PropertyData > childProperties = propertiesCache . get ( parentIdentifier ) ; if ( childProperties != null ) { synchronized ( childProperties ) { for ( Iterator < PropertyData > i = childProperties . iterator ( ) ; i . hasNext ( ) ; ) { PropertyData cn = i . next ( ) ; if ( cn . getIdentifier ( ) . equals ( childIdentifier ) ) { i . remove ( ) ; if ( childProperties . size ( ) <= 0 ) { propertiesCache . remove ( parentIdentifier ) ; } return cn ; } } } } return null ; }
Remove property by id if parent properties are cached in CP .
15,806
protected NodeData removeChildNode ( final String parentIdentifier , final String childIdentifier ) { final List < NodeData > childNodes = nodesCache . get ( parentIdentifier ) ; if ( childNodes != null ) { synchronized ( childNodes ) { for ( Iterator < NodeData > i = childNodes . iterator ( ) ; i . hasNext ( ) ; ) { NodeData cn = i . next ( ) ; if ( cn . getIdentifier ( ) . equals ( childIdentifier ) ) { i . remove ( ) ; return cn ; } } } } return null ; }
Remove child node by id if parent child nodes are cached in CN .
15,807
String dump ( ) { StringBuilder res = new StringBuilder ( ) ; for ( Map . Entry < CacheKey , CacheValue > ce : cache . entrySet ( ) ) { res . append ( ce . getKey ( ) . hashCode ( ) ) ; res . append ( "\t\t" ) ; res . append ( ce . getValue ( ) . getItem ( ) . getIdentifier ( ) ) ; res . append ( ", " ) ; res . append ( ce . getValue ( ) . getItem ( ) . getQPath ( ) . getAsString ( ) ) ; res . append ( ", " ) ; res . append ( ce . getValue ( ) . getExpiredTime ( ) ) ; res . append ( ", " ) ; res . append ( ce . getKey ( ) . getClass ( ) . getSimpleName ( ) ) ; res . append ( "\r\n" ) ; } return res . toString ( ) ; }
For debug .
15,808
final protected void restore ( ) throws RepositoryRestoreExeption { try { stateRestore = REPOSITORY_RESTORE_STARTED ; startTime = Calendar . getInstance ( ) ; restoreRepository ( ) ; stateRestore = REPOSITORY_RESTORE_SUCCESSFUL ; endTime = Calendar . getInstance ( ) ; } catch ( Throwable t ) { stateRestore = REPOSITORY_RESTORE_FAIL ; restoreException = t ; throw new RepositoryRestoreExeption ( t . getMessage ( ) , t ) ; } finally { if ( removeJobOnceOver ) { backupManager . restoreRepositoryJobs . remove ( this ) ; } } }
Restore repository . Provide information about start and finish process .
15,809
protected void removeRepository ( RepositoryService repositoryService , String repositoryName ) throws RepositoryException , RepositoryConfigurationException { ManageableRepository mr = null ; try { mr = repositoryService . getRepository ( repositoryName ) ; } catch ( RepositoryException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } if ( mr != null ) { closeAllSession ( mr ) ; repositoryService . removeRepository ( repositoryName ) ; repositoryService . getConfig ( ) . retain ( ) ; } }
Remove repository .
15,810
private void closeAllSession ( ManageableRepository mr ) throws NoSuchWorkspaceException { for ( String wsName : mr . getWorkspaceNames ( ) ) { if ( ! mr . canRemoveWorkspace ( wsName ) ) { WorkspaceContainerFacade wc = mr . getWorkspaceContainer ( wsName ) ; SessionRegistry sessionRegistry = ( SessionRegistry ) wc . getComponent ( SessionRegistry . class ) ; sessionRegistry . closeSessions ( wsName ) ; } } }
Close all open session in repository
15,811
protected List < ItemState > findItemStates ( QPath itemPath ) { List < ItemState > istates = new ArrayList < ItemState > ( ) ; for ( ItemState istate : itemAddStates ) { if ( istate . getData ( ) . getQPath ( ) . equals ( itemPath ) ) istates . add ( istate ) ; } return istates ; }
Find item states .
15,812
protected ItemState findLastItemState ( QPath itemPath ) { for ( int i = itemAddStates . size ( ) - 1 ; i >= 0 ; i -- ) { ItemState istate = itemAddStates . get ( i ) ; if ( istate . getData ( ) . getQPath ( ) . equals ( itemPath ) ) return istate ; } return null ; }
Find last ItemState .
15,813
public List < NodeTypeData > read ( InputStream is ) throws RepositoryException { try { if ( is != null ) { CNDLexer lex = new CNDLexer ( new ANTLRInputStream ( is ) ) ; CommonTokenStream tokens = new CommonTokenStream ( lex ) ; CNDParser parser = new CNDParser ( tokens ) ; CNDParser . cnd_return r ; if ( lex . hasError ( ) ) { throw new RepositoryException ( "Lexer errors found " + lex . getErrors ( ) . toString ( ) ) ; } r = parser . cnd ( ) ; if ( parser . hasError ( ) ) { throw new RepositoryException ( "Parser errors found " + parser . getErrors ( ) . toString ( ) ) ; } CommonTreeNodeStream nodes = new CommonTreeNodeStream ( r . getTree ( ) ) ; CNDWalker walker = new CNDWalker ( nodes ) ; walker . cnd ( namespaceRegistry ) ; return walker . getNodeTypes ( ) ; } else { return new ArrayList < NodeTypeData > ( ) ; } } catch ( IOException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( RecognitionException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } }
Method which reads input stream as compact node type definition string . If any namespaces are placed in stream they are registered through namespace registry .
15,814
protected void execute ( List < String > scripts ) throws SQLException { SecurityHelper . validateSecurityPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; boolean autoCommit = connection . getAutoCommit ( ) ; if ( autoCommit != this . autoCommit ) { connection . setAutoCommit ( this . autoCommit ) ; } Statement st = connection . createStatement ( ) ; try { for ( String scr : scripts ) { String sql = JDBCUtils . cleanWhitespaces ( scr . trim ( ) ) ; if ( ! sql . isEmpty ( ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Execute script: \n[" + sql + "]" ) ; } executeQuery ( st , sql ) ; } } } finally { try { st . close ( ) ; } catch ( SQLException e ) { LOG . error ( "Can't close the Statement." + e . getMessage ( ) ) ; } if ( autoCommit != this . autoCommit ) { connection . setAutoCommit ( autoCommit ) ; } } }
Execute script on database . Set auto commit mode if needed .
15,815
private void initOrderedIterator ( ) { if ( orderedNodes != null ) { return ; } long time = 0 ; if ( LOG . isDebugEnabled ( ) ) { time = System . currentTimeMillis ( ) ; } ScoreNode [ ] [ ] nodes = ( ScoreNode [ ] [ ] ) scoreNodes . toArray ( new ScoreNode [ scoreNodes . size ( ) ] [ ] ) ; final Set < String > invalidIDs = new HashSet < String > ( 2 ) ; final Map < String , NodeData > lcache = new HashMap < String , NodeData > ( ) ; do { if ( invalidIDs . size ( ) > 0 ) { List < ScoreNode [ ] > tmp = new ArrayList < ScoreNode [ ] > ( ) ; for ( int i = 0 ; i < nodes . length ; i ++ ) { if ( ! invalidIDs . contains ( nodes [ i ] [ selectorIndex ] . getNodeId ( ) ) ) { tmp . add ( nodes [ i ] ) ; } } nodes = ( ScoreNode [ ] [ ] ) tmp . toArray ( new ScoreNode [ tmp . size ( ) ] [ ] ) ; invalidIDs . clear ( ) ; } try { Arrays . sort ( nodes , new ScoreNodeComparator ( lcache , invalidIDs ) ) ; } catch ( SortFailedException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } } while ( invalidIDs . size ( ) > 0 ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + nodes . length + " node(s) ordered in " + ( System . currentTimeMillis ( ) - time ) + " ms" ) ; } orderedNodes = new ScoreNodeIteratorImpl ( nodes ) ; }
Initializes the NodeIterator in document order
15,816
public static File getFullBackupFile ( File restoreDir ) { Pattern p = Pattern . compile ( ".+\\.0" ) ; for ( File f : PrivilegedFileHelper . listFiles ( restoreDir , new FileFilter ( ) { public boolean accept ( File pathname ) { Pattern p = Pattern . compile ( ".+\\.[0-9]+" ) ; Matcher m = p . matcher ( pathname . getName ( ) ) ; return m . matches ( ) ; } } ) ) { Matcher m = p . matcher ( f . getName ( ) ) ; if ( m . matches ( ) ) { return f ; } } return null ; }
Returns file with full backup . In case of RDBMS backup it may be a directory .
15,817
public static List < File > getIncrementalFiles ( File restoreDir ) { ArrayList < File > list = new ArrayList < File > ( ) ; Pattern fullBackupPattern = Pattern . compile ( ".+\\.0" ) ; for ( File f : PrivilegedFileHelper . listFiles ( restoreDir , new FileFilter ( ) { public boolean accept ( File pathname ) { Pattern p = Pattern . compile ( ".+\\.[0-9]+" ) ; Matcher m = p . matcher ( pathname . getName ( ) ) ; return m . matches ( ) ; } } ) ) { if ( fullBackupPattern . matcher ( f . getName ( ) ) . matches ( ) == false ) { list . add ( f ) ; } } return list ; }
Get list of incremental backup files .
15,818
public void incrementalRestore ( File incrementalBackupFile ) throws FileNotFoundException , IOException , ClassNotFoundException , RepositoryException { ObjectInputStream ois = null ; try { ois = new ObjectInputStream ( PrivilegedFileHelper . fileInputStream ( incrementalBackupFile ) ) ; while ( true ) { TransactionChangesLog changesLog = readExternal ( ois ) ; changesLog . setSystemId ( Constants . JCR_CORE_RESTORE_WORKSPACE_INITIALIZER_SYSTEM_ID ) ; ChangesLogIterator cli = changesLog . getLogIterator ( ) ; while ( cli . hasNextLog ( ) ) { if ( cli . nextLog ( ) . getEventType ( ) == ExtendedEvent . LOCK ) { cli . removeLog ( ) ; } } saveChangesLog ( changesLog ) ; } } catch ( EOFException ioe ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + ioe . getMessage ( ) ) ; } } }
Perform incremental restore operation .
15,819
public long getNodeChangedSize ( String nodePath ) { Long delta = calculatedChangedNodesSize . get ( nodePath ) ; return delta == null ? 0 : delta ; }
Returns node data changed size if exists or zero otherwise .
15,820
public void merge ( ChangesItem changesItem ) { workspaceChangedSize += changesItem . getWorkspaceChangedSize ( ) ; for ( Entry < String , Long > changesEntry : changesItem . calculatedChangedNodesSize . entrySet ( ) ) { String nodePath = changesEntry . getKey ( ) ; Long currentDelta = changesEntry . getValue ( ) ; Long oldDelta = calculatedChangedNodesSize . get ( nodePath ) ; Long newDelta = currentDelta + ( oldDelta == null ? 0 : oldDelta ) ; calculatedChangedNodesSize . put ( nodePath , newDelta ) ; } for ( String path : changesItem . unknownChangedNodesSize ) { unknownChangedNodesSize . add ( path ) ; } for ( String path : changesItem . asyncUpdate ) { asyncUpdate . add ( path ) ; } }
Merges current changes with new one .
15,821
public static boolean isFile ( Node node ) { try { if ( ! node . isNodeType ( "nt:file" ) ) return false ; if ( ! node . getNode ( "jcr:content" ) . isNodeType ( "nt:resource" ) ) return false ; return true ; } catch ( RepositoryException exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return false ; } }
If the node is file .
15,822
public static boolean isVersion ( Node node ) { try { if ( node . isNodeType ( "nt:version" ) ) return true ; return false ; } catch ( RepositoryException exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return false ; } }
If the node is version .
15,823
private void validateNodeType ( NodeTypeData nodeType ) throws RepositoryException { if ( nodeType == null ) { throw new RepositoryException ( "NodeType object " + nodeType + " is null" ) ; } if ( nodeType . getName ( ) == null ) { throw new RepositoryException ( "NodeType implementation class " + nodeType . getClass ( ) . getName ( ) + " is not supported in this method" ) ; } for ( InternalQName sname : nodeType . getDeclaredSupertypeNames ( ) ) { if ( ! nodeType . getName ( ) . equals ( Constants . NT_BASE ) && nodeType . getName ( ) . equals ( sname ) ) { throw new RepositoryException ( "Invalid super type name" + sname . getAsString ( ) ) ; } } for ( PropertyDefinitionData pdef : nodeType . getDeclaredPropertyDefinitions ( ) ) { if ( ! pdef . getDeclaringNodeType ( ) . equals ( nodeType . getName ( ) ) ) { throw new RepositoryException ( "Invalid declared node type in property definitions with name " + pdef . getName ( ) . getAsString ( ) + " not registred" ) ; } try { validateValueDefaults ( pdef . getRequiredType ( ) , pdef . getDefaultValues ( ) ) ; } catch ( ValueFormatException e ) { throw new ValueFormatException ( "Default value is incompatible with Property type " + PropertyType . nameFromValue ( pdef . getRequiredType ( ) ) + " of " + pdef . getName ( ) . getAsString ( ) + " in nodetype " + nodeType . getName ( ) . getAsString ( ) , e ) ; } try { validateValueConstraints ( pdef . getRequiredType ( ) , pdef . getValueConstraints ( ) ) ; } catch ( ValueFormatException e ) { throw new ValueFormatException ( "Constraints is incompatible with Property type " + PropertyType . nameFromValue ( pdef . getRequiredType ( ) ) + " of " + pdef . getName ( ) . getAsString ( ) + " in nodetype " + nodeType . getName ( ) . getAsString ( ) , e ) ; } } for ( NodeDefinitionData cndef : nodeType . getDeclaredChildNodeDefinitions ( ) ) { if ( ! cndef . getDeclaringNodeType ( ) . equals ( nodeType . getName ( ) ) ) { throw new RepositoryException ( "Invalid declared node type in child node definitions with name " + cndef . getName ( ) . getAsString ( ) + " not registred" ) ; } } }
Check according the JSR - 170
15,824
public Version version ( String versionName , boolean pool ) throws VersionException , RepositoryException { JCRName jcrVersionName = locationFactory . parseJCRName ( versionName ) ; VersionImpl version = ( VersionImpl ) dataManager . getItem ( nodeData ( ) , new QPathEntry ( jcrVersionName . getInternalName ( ) , 1 ) , pool , ItemType . NODE , false ) ; if ( version == null ) { throw new VersionException ( "There are no version with name '" + versionName + "' in the version history " + getPath ( ) ) ; } return version ; }
For internal use . Doesn t check InvalidItemStateException . May return unpooled Version object .
15,825
void migrate ( ) throws RepositoryException { try { LOG . info ( "Migration started." ) ; moveOldStructure ( ) ; service . createStructure ( ) ; migrateGroups ( ) ; migrateMembershipTypes ( ) ; migrateUsers ( ) ; migrateProfiles ( ) ; migrateMemberships ( ) ; removeOldStructure ( ) ; LOG . info ( "Migration completed." ) ; } catch ( Exception e ) { throw new RepositoryException ( "Migration failed" , e ) ; } }
Method that aggregates all needed migration operations in needed order .
15,826
boolean migrationRequired ( ) throws RepositoryException { Session session = service . getStorageSession ( ) ; try { if ( session . itemExists ( storagePathOld ) ) { return true ; } try { Node node = ( Node ) session . getItem ( service . getStoragePath ( ) ) ; return node . isNodeType ( JOS_ORGANIZATION_NODETYPE_OLD ) ; } catch ( PathNotFoundException e ) { return false ; } } finally { session . logout ( ) ; } }
Method to know if migration is need .
15,827
private void moveOldStructure ( ) throws Exception { ExtendedSession session = ( ExtendedSession ) service . getStorageSession ( ) ; try { if ( session . itemExists ( storagePathOld ) ) { return ; } else { session . move ( service . getStoragePath ( ) , storagePathOld , false ) ; session . save ( ) ; } } finally { session . logout ( ) ; } }
Method for moving old storage into temporary location .
15,828
private void removeOldStructure ( ) throws RepositoryException { ExtendedSession session = ( ExtendedSession ) service . getStorageSession ( ) ; try { if ( session . itemExists ( storagePathOld ) ) { NodeIterator usersIter = ( ( ExtendedNode ) session . getItem ( usersStorageOld ) ) . getNodesLazily ( ) ; while ( usersIter . hasNext ( ) ) { Node currentUser = usersIter . nextNode ( ) ; currentUser . remove ( ) ; session . save ( ) ; } NodeIterator groupsIter = ( ( ExtendedNode ) session . getItem ( groupsStorageOld ) ) . getNodesLazily ( ) ; while ( groupsIter . hasNext ( ) ) { Node currentGroup = groupsIter . nextNode ( ) ; currentGroup . remove ( ) ; session . save ( ) ; } NodeIterator membershipTypesIter = ( ( ExtendedNode ) session . getItem ( membershipTypesStorageOld ) ) . getNodesLazily ( ) ; while ( membershipTypesIter . hasNext ( ) ) { Node currentMembershipType = membershipTypesIter . nextNode ( ) ; currentMembershipType . remove ( ) ; session . save ( ) ; } session . getItem ( storagePathOld ) . remove ( ) ; session . save ( ) ; } } finally { session . logout ( ) ; } }
Method for removing old storage from temporary location .
15,829
private void migrateUsers ( ) throws Exception { Session session = service . getStorageSession ( ) ; try { if ( session . itemExists ( usersStorageOld ) ) { NodeIterator iterator = ( ( ExtendedNode ) session . getItem ( usersStorageOld ) ) . getNodesLazily ( ) ; UserHandlerImpl uh = ( ( UserHandlerImpl ) service . getUserHandler ( ) ) ; while ( iterator . hasNext ( ) ) { uh . migrateUser ( iterator . nextNode ( ) ) ; } } } finally { session . logout ( ) ; } }
Method for users migration .
15,830
private void migrateGroups ( ) throws Exception { Session session = service . getStorageSession ( ) ; try { if ( session . itemExists ( groupsStorageOld ) ) { NodeIterator iterator = ( ( ExtendedNode ) session . getItem ( groupsStorageOld ) ) . getNodesLazily ( ) ; GroupHandlerImpl gh = ( ( GroupHandlerImpl ) service . getGroupHandler ( ) ) ; while ( iterator . hasNext ( ) ) { Node oldGroupNode = iterator . nextNode ( ) ; gh . migrateGroup ( oldGroupNode ) ; migrateGroups ( oldGroupNode ) ; } } } finally { session . logout ( ) ; } }
Method for groups migration . Must be run after users and membershipTypes migration .
15,831
private void migrateGroups ( Node startNode ) throws Exception { NodeIterator iterator = ( ( ExtendedNode ) startNode ) . getNodesLazily ( ) ; GroupHandlerImpl gh = ( ( GroupHandlerImpl ) service . getGroupHandler ( ) ) ; while ( iterator . hasNext ( ) ) { Node oldGroupNode = iterator . nextNode ( ) ; gh . migrateGroup ( oldGroupNode ) ; migrateGroups ( oldGroupNode ) ; } }
Method for groups migration .
15,832
private void migrateMembershipTypes ( ) throws Exception { Session session = service . getStorageSession ( ) ; try { if ( session . itemExists ( membershipTypesStorageOld ) ) { NodeIterator iterator = ( ( ExtendedNode ) session . getItem ( membershipTypesStorageOld ) ) . getNodesLazily ( ) ; MembershipTypeHandlerImpl mth = ( ( MembershipTypeHandlerImpl ) service . getMembershipTypeHandler ( ) ) ; while ( iterator . hasNext ( ) ) { Node oldTypeNode = iterator . nextNode ( ) ; mth . migrateMembershipType ( oldTypeNode ) ; } } } finally { session . logout ( ) ; } }
Method for membershipTypes migration .
15,833
private void migrateProfiles ( ) throws Exception { Session session = service . getStorageSession ( ) ; try { if ( session . itemExists ( usersStorageOld ) ) { NodeIterator iterator = ( ( ExtendedNode ) session . getItem ( usersStorageOld ) ) . getNodesLazily ( ) ; UserProfileHandlerImpl uph = ( ( UserProfileHandlerImpl ) service . getUserProfileHandler ( ) ) ; while ( iterator . hasNext ( ) ) { Node oldUserNode = iterator . nextNode ( ) ; uph . migrateProfile ( oldUserNode ) ; } } } finally { session . logout ( ) ; } }
Method for profiles migration .
15,834
private void migrateMemberships ( ) throws Exception { Session session = service . getStorageSession ( ) ; try { if ( session . itemExists ( usersStorageOld ) ) { NodeIterator iterator = ( ( ExtendedNode ) session . getItem ( usersStorageOld ) ) . getNodesLazily ( ) ; MembershipHandlerImpl mh = ( ( MembershipHandlerImpl ) service . getMembershipHandler ( ) ) ; while ( iterator . hasNext ( ) ) { Node oldUserNode = iterator . nextNode ( ) ; mh . migrateMemberships ( oldUserNode ) ; oldUserNode . remove ( ) ; session . save ( ) ; } } } finally { session . logout ( ) ; } }
Method for memberships migration .
15,835
protected void addBooleanValue ( Document doc , String fieldName , Object internalValue ) { doc . add ( createFieldWithoutNorms ( fieldName , internalValue . toString ( ) , PropertyType . BOOLEAN ) ) ; }
Adds the string representation of the boolean value to the document as the named field .
15,836
protected void addReferenceValue ( Document doc , String fieldName , Object internalValue ) { String uuid = internalValue . toString ( ) ; doc . add ( createFieldWithoutNorms ( fieldName , uuid , PropertyType . REFERENCE ) ) ; doc . add ( new Field ( FieldNames . PROPERTIES , FieldNames . createNamedValue ( fieldName , uuid ) , Field . Store . YES , Field . Index . NO , Field . TermVector . NO ) ) ; }
Adds the reference value to the document as the named field . The value s string representation is added as the reference data . Additionally the reference data is stored in the index .
15,837
protected void addPathValue ( Document doc , String fieldName , Object pathString ) { doc . add ( createFieldWithoutNorms ( fieldName , pathString . toString ( ) , PropertyType . PATH ) ) ; }
Adds the path value to the document as the named field . The path value is converted to an indexable string value using the name space mappings with which this class has been created .
15,838
protected void addNameValue ( Document doc , String fieldName , Object internalValue ) { doc . add ( createFieldWithoutNorms ( fieldName , internalValue . toString ( ) , PropertyType . NAME ) ) ; }
Adds the name value to the document as the named field . The name value is converted to an indexable string treating the internal value as a qualified name and mapping the name space using the name space mappings with which this class has been created .
15,839
protected float getPropertyBoost ( InternalQName propertyName ) { if ( indexingConfig == null ) { return DEFAULT_BOOST ; } else { return indexingConfig . getPropertyBoost ( node , propertyName ) ; } }
Returns the boost value for the given property name .
15,840
protected void addNodeName ( Document doc , String namespaceURI , String localName ) throws RepositoryException { String name = mappings . getNamespacePrefixByURI ( namespaceURI ) + ":" + localName ; doc . add ( new Field ( FieldNames . LABEL , name , Field . Store . NO , Field . Index . NOT_ANALYZED_NO_NORMS ) ) ; if ( indexFormatVersion . getVersion ( ) >= IndexFormatVersion . V3 . getVersion ( ) ) { doc . add ( new Field ( FieldNames . NAMESPACE_URI , namespaceURI , Field . Store . NO , Field . Index . NOT_ANALYZED_NO_NORMS ) ) ; doc . add ( new Field ( FieldNames . LOCAL_NAME , localName , Field . Store . NO , Field . Index . NOT_ANALYZED_NO_NORMS ) ) ; } }
Depending on the index format version adds one or two fields to the document for the node name .
15,841
protected long writeValue ( File file , ValueData value ) throws IOException { if ( value . isByteArray ( ) ) { return writeByteArrayValue ( file , value ) ; } else { return writeStreamedValue ( file , value ) ; } }
Write value to a file .
15,842
protected long writeByteArrayValue ( File file , ValueData value ) throws IOException { OutputStream out = new FileOutputStream ( file ) ; try { byte [ ] data = value . getAsByteArray ( ) ; out . write ( data ) ; return data . length ; } finally { out . close ( ) ; } }
Write value array of bytes to a file .
15,843
protected long writeStreamedValue ( File file , ValueData value ) throws IOException { long size ; if ( value instanceof StreamPersistedValueData ) { StreamPersistedValueData streamed = ( StreamPersistedValueData ) value ; if ( streamed . isPersisted ( ) ) { size = copyClose ( streamed . getAsStream ( ) , new FileOutputStream ( file ) ) ; } else { File tempFile ; if ( ( tempFile = streamed . getTempFile ( ) ) != null ) { if ( ! tempFile . renameTo ( file ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Value spool file move (rename) to Values Storage is not succeeded. " + "Trying bytes copy. Spool file: " + tempFile . getAbsolutePath ( ) + ". Destination: " + file . getAbsolutePath ( ) ) ; } size = copyClose ( new FileInputStream ( tempFile ) , new FileOutputStream ( file ) ) ; } else { size = file . length ( ) ; } } else { size = copyClose ( streamed . getStream ( ) , new FileOutputStream ( file ) ) ; } streamed . setPersistedFile ( file ) ; } } else { size = copyClose ( value . getAsStream ( ) , new FileOutputStream ( file ) ) ; } return size ; }
Write streamed value to a file .
15,844
protected long writeOutput ( OutputStream out , ValueData value ) throws IOException { if ( value . isByteArray ( ) ) { byte [ ] buff = value . getAsByteArray ( ) ; out . write ( buff ) ; return buff . length ; } else { InputStream in ; if ( value instanceof StreamPersistedValueData ) { StreamPersistedValueData streamed = ( StreamPersistedValueData ) value ; if ( streamed . isPersisted ( ) ) { in = streamed . getAsStream ( ) ; } else { in = streamed . getStream ( ) ; if ( in == null ) { in = new FileInputStream ( streamed . getTempFile ( ) ) ; } } } else { in = value . getAsStream ( ) ; } try { return copy ( in , out ) ; } finally { in . close ( ) ; } } }
Stream value data to the output .
15,845
protected long copy ( InputStream in , OutputStream out ) throws IOException { boolean inFile = in instanceof FileInputStream && FileInputStream . class . equals ( in . getClass ( ) ) ; boolean outFile = out instanceof FileOutputStream && FileOutputStream . class . equals ( out . getClass ( ) ) ; if ( inFile && outFile ) { FileChannel infch = ( ( FileInputStream ) in ) . getChannel ( ) ; FileChannel outfch = ( ( FileOutputStream ) out ) . getChannel ( ) ; long size = 0 ; long r = 0 ; do { r = outfch . transferFrom ( infch , r , infch . size ( ) ) ; size += r ; } while ( r < infch . size ( ) ) ; return size ; } else { ReadableByteChannel inch = inFile ? ( ( FileInputStream ) in ) . getChannel ( ) : Channels . newChannel ( in ) ; WritableByteChannel outch = outFile ? ( ( FileOutputStream ) out ) . getChannel ( ) : Channels . newChannel ( out ) ; long size = 0 ; int r = 0 ; ByteBuffer buff = ByteBuffer . allocate ( IOBUFFER_SIZE ) ; buff . clear ( ) ; while ( ( r = inch . read ( buff ) ) >= 0 ) { buff . flip ( ) ; do { outch . write ( buff ) ; } while ( buff . hasRemaining ( ) ) ; buff . clear ( ) ; size += r ; } if ( outFile ) ( ( FileChannel ) outch ) . force ( true ) ; return size ; } }
Copy input to output data using NIO .
15,846
protected long copyClose ( InputStream in , OutputStream out ) throws IOException { try { try { return copy ( in , out ) ; } finally { in . close ( ) ; } } finally { out . close ( ) ; } }
Copy input to output data using NIO . Input and output streams will be closed after the operation .
15,847
public Response report ( Session session , String path , HierarchicalProperty body , Depth depth , String baseURI ) { try { Node node = ( Node ) session . getItem ( path ) ; WebDavNamespaceContext nsContext = new WebDavNamespaceContext ( session ) ; String strUri = baseURI + node . getPath ( ) ; URI uri = new URI ( TextUtil . escape ( strUri , '%' , true ) ) ; if ( ! ResourceUtil . isVersioned ( node ) ) { return Response . status ( HTTPStatus . PRECON_FAILED ) . build ( ) ; } VersionedResource resource ; if ( ResourceUtil . isFile ( node ) ) { resource = new VersionedFileResource ( uri , node , nsContext ) ; } else { resource = new VersionedCollectionResource ( uri , node , nsContext ) ; } Set < QName > properties = getProperties ( body ) ; VersionTreeResponseEntity response = new VersionTreeResponseEntity ( nsContext , resource , properties ) ; return Response . status ( HTTPStatus . MULTISTATUS ) . entity ( response ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . NOT_FOUND ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( RepositoryException exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } }
Webdav Report method implementation .
15,848
protected Set < QName > getProperties ( HierarchicalProperty body ) { HashSet < QName > properties = new HashSet < QName > ( ) ; HierarchicalProperty prop = body . getChild ( new QName ( "DAV:" , "prop" ) ) ; if ( prop == null ) { return properties ; } for ( int i = 0 ; i < prop . getChildren ( ) . size ( ) ; i ++ ) { HierarchicalProperty property = prop . getChild ( i ) ; properties . add ( property . getName ( ) ) ; } return properties ; }
Returns the list of properties .
15,849
public void write ( List < NodeTypeData > nodeTypes , OutputStream os ) throws RepositoryException { OutputStreamWriter out = new OutputStreamWriter ( os ) ; try { for ( NodeTypeData nodeType : nodeTypes ) { printNamespaces ( nodeType , out ) ; printNodeTypeDeclaration ( nodeType , out ) ; } out . close ( ) ; } catch ( IOException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } }
Write given list of node types to output stream .
15,850
private void printNamespaces ( NodeTypeData nodeTypeData , OutputStreamWriter out ) throws RepositoryException , IOException { Set < String > namespaces = new HashSet < String > ( ) ; printNameNamespace ( nodeTypeData . getName ( ) , namespaces ) ; printNameNamespace ( nodeTypeData . getPrimaryItemName ( ) , namespaces ) ; if ( nodeTypeData . getDeclaredSupertypeNames ( ) != null ) { for ( InternalQName reqType : nodeTypeData . getDeclaredSupertypeNames ( ) ) { printNameNamespace ( reqType , namespaces ) ; } } if ( nodeTypeData . getDeclaredPropertyDefinitions ( ) != null ) { for ( PropertyDefinitionData property : nodeTypeData . getDeclaredPropertyDefinitions ( ) ) { printNameNamespace ( property . getName ( ) , namespaces ) ; } } if ( nodeTypeData . getDeclaredChildNodeDefinitions ( ) != null ) { for ( NodeDefinitionData child : nodeTypeData . getDeclaredChildNodeDefinitions ( ) ) { printNameNamespace ( child . getName ( ) , namespaces ) ; printNameNamespace ( child . getDefaultPrimaryType ( ) , namespaces ) ; if ( child . getRequiredPrimaryTypes ( ) != null ) { for ( InternalQName reqType : child . getRequiredPrimaryTypes ( ) ) { printNameNamespace ( reqType , namespaces ) ; } } } } for ( String prefix : namespaces ) { String uri = namespaceRegistry . getURI ( prefix ) ; out . write ( "<" + prefix + "='" + uri + "'>\r\n" ) ; } }
Print namespaces to stream
15,851
private void printNodeTypeDeclaration ( NodeTypeData nodeTypeData , OutputStreamWriter out ) throws RepositoryException , IOException { out . write ( "[" + qNameToString ( nodeTypeData . getName ( ) ) + "] " ) ; InternalQName [ ] superTypes = nodeTypeData . getDeclaredSupertypeNames ( ) ; if ( superTypes != null && superTypes . length > 0 ) { if ( superTypes . length > 1 || ! superTypes [ 0 ] . equals ( Constants . NT_BASE ) ) { out . write ( "> " + qNameToString ( superTypes [ 0 ] ) ) ; for ( int i = 1 ; i < superTypes . length ; i ++ ) { out . write ( ", " + qNameToString ( superTypes [ i ] ) ) ; } } } StringBuilder attributes = new StringBuilder ( ) ; if ( nodeTypeData . hasOrderableChildNodes ( ) ) { attributes . append ( "orderable " ) ; } if ( nodeTypeData . isMixin ( ) ) { attributes . append ( "mixin " ) ; } if ( nodeTypeData . getPrimaryItemName ( ) != null ) { attributes . append ( "primaryitem " + qNameToString ( nodeTypeData . getPrimaryItemName ( ) ) ) ; } if ( attributes . length ( ) > 0 ) { out . write ( "\r\n " ) ; out . write ( attributes . toString ( ) ) ; } PropertyDefinitionData [ ] propertyDefinitions = nodeTypeData . getDeclaredPropertyDefinitions ( ) ; if ( propertyDefinitions != null ) { for ( PropertyDefinitionData propertyDefinition : propertyDefinitions ) { printPropertyDeclaration ( propertyDefinition , out ) ; } } NodeDefinitionData [ ] nodeDefinitions = nodeTypeData . getDeclaredChildNodeDefinitions ( ) ; if ( nodeDefinitions != null ) { for ( NodeDefinitionData nodeDefinition : nodeDefinitions ) { printChildDeclaration ( nodeDefinition , out ) ; } } out . write ( "\r\n" ) ; }
Method recursively print to output stream node type definition in cnd format .
15,852
private void printPropertyDeclaration ( PropertyDefinitionData propertyDefinition , OutputStreamWriter out ) throws IOException , RepositoryException { out . write ( "\r\n " ) ; out . write ( "- " + qNameToString ( propertyDefinition . getName ( ) ) ) ; out . write ( " (" + ExtendedPropertyType . nameFromValue ( propertyDefinition . getRequiredType ( ) ) . toUpperCase ( ) + ")" ) ; out . write ( listToString ( propertyDefinition . getDefaultValues ( ) , "'" , "\r\n = " , " " ) ) ; StringBuilder attributes = new StringBuilder ( ) ; if ( propertyDefinition . isAutoCreated ( ) ) { attributes . append ( "autocreated " ) ; } if ( propertyDefinition . isMandatory ( ) ) { attributes . append ( "mandatory " ) ; } if ( propertyDefinition . isProtected ( ) ) { attributes . append ( "protected " ) ; } if ( propertyDefinition . isMultiple ( ) ) { attributes . append ( "multiple " ) ; } if ( propertyDefinition . getOnParentVersion ( ) != OnParentVersionAction . COPY ) { attributes . append ( "\r\n " + OnParentVersionAction . nameFromValue ( propertyDefinition . getOnParentVersion ( ) ) + " " ) ; } if ( attributes . length ( ) > 0 ) { out . write ( "\r\n " ) ; out . write ( attributes . toString ( ) ) ; } out . write ( listToString ( propertyDefinition . getValueConstraints ( ) , "'" , "\r\n < " , " " ) ) ; }
Prints to output stream property definition in CND format
15,853
private void printChildDeclaration ( NodeDefinitionData nodeDefinition , OutputStreamWriter out ) throws IOException , RepositoryException { out . write ( "\r\n " ) ; out . write ( "+ " + qNameToString ( nodeDefinition . getName ( ) ) + " " ) ; InternalQName [ ] requiredTypes = nodeDefinition . getRequiredPrimaryTypes ( ) ; if ( requiredTypes != null && requiredTypes . length > 0 ) { if ( requiredTypes . length > 1 || ! requiredTypes [ 0 ] . equals ( Constants . NT_BASE ) ) { out . write ( "(" + qNameToString ( requiredTypes [ 0 ] ) ) ; for ( int i = 1 ; i < requiredTypes . length ; i ++ ) { out . write ( ", " + qNameToString ( requiredTypes [ i ] ) ) ; } out . write ( ")" ) ; } } if ( nodeDefinition . getDefaultPrimaryType ( ) != null ) { out . write ( "\r\n = " + qNameToString ( nodeDefinition . getDefaultPrimaryType ( ) ) ) ; } StringBuilder attributes = new StringBuilder ( ) ; if ( nodeDefinition . isAutoCreated ( ) ) { attributes . append ( "autocreated " ) ; } if ( nodeDefinition . isMandatory ( ) ) { attributes . append ( "mandatory " ) ; } if ( nodeDefinition . isProtected ( ) ) { attributes . append ( "protected " ) ; } if ( nodeDefinition . isAllowsSameNameSiblings ( ) ) { attributes . append ( "sns " ) ; } if ( nodeDefinition . getOnParentVersion ( ) != OnParentVersionAction . COPY ) { attributes . append ( "\r\n " + OnParentVersionAction . nameFromValue ( nodeDefinition . getOnParentVersion ( ) ) + " " ) ; } if ( attributes . length ( ) > 0 ) { out . write ( "\r\n " ) ; out . write ( attributes . toString ( ) ) ; } }
Print to output stream child node definition in CND format
15,854
public float getNodeBoost ( NodeData state ) { IndexingRule rule = getApplicableIndexingRule ( state ) ; if ( rule != null ) { return rule . getNodeBoost ( ) ; } return DEFAULT_BOOST ; }
Returns the boost for the node scope fulltext index field .
15,855
private PathExpression getCondition ( Node config ) throws IllegalNameException , RepositoryException { Node conditionAttr = config . getAttributes ( ) . getNamedItem ( "condition" ) ; if ( conditionAttr == null ) { return null ; } String conditionString = conditionAttr . getNodeValue ( ) ; int idx ; int axis ; InternalQName elementTest = null ; InternalQName nameTest = null ; InternalQName propertyName ; String propertyValue ; if ( conditionString . startsWith ( "ancestor::" ) ) { axis = PathExpression . ANCESTOR ; idx = "ancestor::" . length ( ) ; } else if ( conditionString . startsWith ( "parent::" ) ) { axis = PathExpression . PARENT ; idx = "parent::" . length ( ) ; } else if ( conditionString . startsWith ( "@" ) ) { axis = PathExpression . SELF ; idx = "@" . length ( ) ; } else { axis = PathExpression . CHILD ; idx = 0 ; } try { if ( conditionString . startsWith ( "element(" , idx ) ) { int colon = conditionString . indexOf ( ',' , idx + "element(" . length ( ) ) ; String name = conditionString . substring ( idx + "element(" . length ( ) , colon ) . trim ( ) ; if ( ! name . equals ( "*" ) ) { nameTest = resolver . parseJCRName ( ISO9075 . decode ( name ) ) . getInternalName ( ) ; } idx = conditionString . indexOf ( ")/@" , colon ) ; String type = conditionString . substring ( colon + 1 , idx ) . trim ( ) ; elementTest = resolver . parseJCRName ( ISO9075 . decode ( type ) ) . getInternalName ( ) ; idx += ")/@" . length ( ) ; } else { if ( axis == PathExpression . ANCESTOR || axis == PathExpression . CHILD || axis == PathExpression . PARENT ) { String name = conditionString . substring ( idx , conditionString . indexOf ( '/' , idx ) ) ; if ( ! name . equals ( "*" ) ) { nameTest = resolver . parseJCRName ( ISO9075 . decode ( name ) ) . getInternalName ( ) ; } idx += name . length ( ) + "/@" . length ( ) ; } } int eq = conditionString . indexOf ( '=' , idx ) ; String name = conditionString . substring ( idx , eq ) . trim ( ) ; propertyName = resolver . parseJCRName ( ISO9075 . decode ( name ) ) . getInternalName ( ) ; int quote = conditionString . indexOf ( '\'' , eq ) + 1 ; propertyValue = conditionString . substring ( quote , conditionString . indexOf ( '\'' , quote ) ) ; } catch ( IndexOutOfBoundsException e ) { throw new RepositoryException ( conditionString ) ; } return new PathExpression ( axis , elementTest , nameTest , propertyName , propertyValue ) ; }
Gets the condition expression from the configuration .
15,856
public void remove ( ) throws IOException { if ( ( fileBuffer != null ) && PrivilegedFileHelper . exists ( fileBuffer ) ) { if ( ! PrivilegedFileHelper . delete ( fileBuffer ) ) { throw new IOException ( "Cannot remove file " + PrivilegedFileHelper . getAbsolutePath ( fileBuffer ) + " Close all streams." ) ; } } }
Remove buffer .
15,857
private void swapBuffers ( ) throws IOException { byte [ ] data = ( ( ByteArrayOutputStream ) out ) . toByteArray ( ) ; fileBuffer = PrivilegedFileHelper . createTempFile ( "decoderBuffer" , ".tmp" ) ; PrivilegedFileHelper . deleteOnExit ( fileBuffer ) ; out = new BufferedOutputStream ( PrivilegedFileHelper . fileOutputStream ( fileBuffer ) , bufferSize ) ; out . write ( data ) ; }
Swap in - memory buffer with file .
15,858
public void logComment ( String message ) throws IOException { if ( reportContext . get ( ) != null ) { reportContext . get ( ) . addComment ( message ) ; } else { writeMessage ( message ) ; } }
Adds comment to log .
15,859
public void logDescription ( String description ) throws IOException { if ( reportContext . get ( ) != null ) { reportContext . get ( ) . addComment ( description ) ; } else { writeMessage ( description ) ; } }
Adds description to log .
15,860
public void logBrokenObjectAndSetInconsistency ( String brokenObject ) throws IOException { setInconsistency ( ) ; if ( reportContext . get ( ) != null ) { reportContext . get ( ) . addBrokenObject ( brokenObject ) ; } else { writeBrokenObject ( brokenObject ) ; } }
Adds detailed event to log .
15,861
public void logExceptionAndSetInconsistency ( String message , Throwable e ) throws IOException { setInconsistency ( ) ; if ( reportContext . get ( ) != null ) { reportContext . get ( ) . addLogException ( message , e ) ; } else { writeException ( message , e ) ; } }
Adds exception with full stack trace .
15,862
private String getIdColumn ( ) throws SQLException { try { return lockManagerEntry . getParameterValue ( ISPNCacheableLockManagerImpl . INFINISPAN_JDBC_CL_ID_COLUMN_NAME ) ; } catch ( RepositoryConfigurationException e ) { throw new SQLException ( e ) ; } }
Returns the column name which contain node identifier .
15,863
protected String getTableName ( ) throws SQLException { try { String dialect = getDialect ( ) ; String quote = "\"" ; if ( dialect . startsWith ( DBConstants . DB_DIALECT_MYSQL ) ) quote = "`" ; return quote + lockManagerEntry . getParameterValue ( ISPNCacheableLockManagerImpl . INFINISPAN_JDBC_TABLE_NAME ) + "_" + "L" + workspaceEntry . getUniqueName ( ) . replace ( "_" , "" ) . replace ( "-" , "_" ) + quote ; } catch ( RepositoryConfigurationException e ) { throw new SQLException ( e ) ; } }
Returns the name of LOCK table .
15,864
public File getNextFile ( ) { File nextFile = null ; try { String sNextName = generateName ( ) ; nextFile = new File ( backupSetDir . getAbsoluteFile ( ) + File . separator + sNextName ) ; if ( isFullBackup && isDirectoryForFullBackup ) { if ( ! PrivilegedFileHelper . exists ( nextFile ) ) { PrivilegedFileHelper . mkdirs ( nextFile ) ; } } else { PrivilegedFileHelper . createNewFile ( nextFile ) ; } } catch ( IOException e ) { LOG . error ( "Can nit get next file : " + e . getLocalizedMessage ( ) , e ) ; } return nextFile ; }
Get next file in backup set .
15,865
private String getStrDate ( Calendar c ) { int m = c . get ( Calendar . MONTH ) + 1 ; int d = c . get ( Calendar . DATE ) ; return "" + c . get ( Calendar . YEAR ) + ( m < 10 ? "0" + m : m ) + ( d < 10 ? "0" + d : d ) ; }
Returns date as String in format YYYYMMDD .
15,866
private String getStrTime ( Calendar c ) { int h = c . get ( Calendar . HOUR ) ; int m = c . get ( Calendar . MINUTE ) ; int s = c . get ( Calendar . SECOND ) ; return "" + ( h < 10 ? "0" + h : h ) + ( m < 10 ? "0" + m : m ) + ( s < 10 ? "0" + s : s ) ; }
Returns time as String in format HHMMSS .
15,867
void createStructure ( ) throws RepositoryException { Session session = getStorageSession ( ) ; try { Node storage = session . getRootNode ( ) . addNode ( storagePath . substring ( 1 ) , STORAGE_NODETYPE ) ; storage . addNode ( STORAGE_JOS_USERS , STORAGE_JOS_USERS_NODETYPE ) ; storage . addNode ( STORAGE_JOS_GROUPS , STORAGE_JOS_GROUPS_NODETYPE ) ; Node storageTypesNode = storage . addNode ( STORAGE_JOS_MEMBERSHIP_TYPES , STORAGE_JOS_MEMBERSHIP_TYPES_NODETYPE ) ; Node anyNode = storageTypesNode . addNode ( JOS_MEMBERSHIP_TYPE_ANY ) ; anyNode . setProperty ( MembershipTypeHandlerImpl . MembershipTypeProperties . JOS_DESCRIPTION , JOS_DESCRIPTION_TYPE_ANY ) ; session . save ( ) ; } finally { session . logout ( ) ; } }
Creates storage structure .
15,868
Session getStorageSession ( ) throws RepositoryException { try { ManageableRepository repository = getWorkingRepository ( ) ; String workspaceName = storageWorkspace ; if ( workspaceName == null ) { workspaceName = repository . getConfiguration ( ) . getDefaultWorkspaceName ( ) ; } return repository . getSystemSession ( workspaceName ) ; } catch ( RepositoryConfigurationException e ) { throw new RepositoryException ( "Can not get system session" , e ) ; } }
Return system Session to org - service storage workspace . For internal use only .
15,869
protected ManageableRepository getWorkingRepository ( ) throws RepositoryException , RepositoryConfigurationException { return repositoryName != null ? repositoryService . getRepository ( repositoryName ) : repositoryService . getCurrentRepository ( ) ; }
Returns working repository . If repository name is configured then it will be returned otherwise the current repository is used .
15,870
public JCRPath createJCRPath ( JCRPath parentLoc , String relPath ) throws RepositoryException { JCRPath addPath = parseNames ( relPath , false ) ; return parentLoc . add ( addPath ) ; }
Creates JCRPath from parent path and relPath
15,871
private boolean isNonspace ( String str , char ch ) throws RepositoryException { if ( ch == '|' ) { throw new RepositoryException ( "Illegal absPath: \"" + str + "\": The path entry contains an illegal char: \"" + ch + "\"" ) ; } return ! ( ( ch == '\t' ) || ( ch == '\n' ) || ( ch == '\f' ) || ( ch == '\r' ) || ( ch == ' ' ) || ( ch == '/' ) || ( ch == ':' ) || ( ch == '[' ) || ( ch == ']' ) || ( ch == '*' ) ) ; }
Some functions for JCRPath Validation
15,872
public boolean isAbsolute ( ) { if ( names [ 0 ] . getIndex ( ) == 1 && names [ 0 ] . getName ( ) . length ( ) == 0 && names [ 0 ] . getNamespace ( ) . length ( ) == 0 ) return true ; else return false ; }
Tell if the path is absolute .
15,873
public QPathEntry [ ] getRelPath ( int relativeDegree ) throws IllegalPathException { int len = getLength ( ) - relativeDegree ; if ( len < 0 ) throw new IllegalPathException ( "Relative degree " + relativeDegree + " is more than depth for " + getAsString ( ) ) ; QPathEntry [ ] relPath = new QPathEntry [ relativeDegree ] ; System . arraycopy ( names , len , relPath , 0 , relPath . length ) ; return relPath ; }
Get relative path with degree .
15,874
public static QPath getCommonAncestorPath ( QPath firstPath , QPath secondPath ) throws PathNotFoundException { if ( ! firstPath . getEntries ( ) [ 0 ] . equals ( secondPath . getEntries ( ) [ 0 ] ) ) { throw new PathNotFoundException ( "For the given ways there is no common ancestor." ) ; } List < QPathEntry > caEntries = new ArrayList < QPathEntry > ( ) ; for ( int i = 0 ; i < firstPath . getEntries ( ) . length ; i ++ ) { if ( firstPath . getEntries ( ) [ i ] . equals ( secondPath . getEntries ( ) [ i ] ) ) { caEntries . add ( firstPath . getEntries ( ) [ i ] ) ; } else { break ; } } return new QPath ( caEntries . toArray ( new QPathEntry [ caEntries . size ( ) ] ) ) ; }
Get common ancestor path .
15,875
public String getAsString ( ) { if ( stringName == null ) { StringBuilder str = new StringBuilder ( ) ; for ( int i = 0 ; i < getLength ( ) ; i ++ ) { str . append ( names [ i ] . getAsString ( true ) ) ; } stringName = str . toString ( ) ; } return stringName ; }
Get String representation .
15,876
public static QPath parse ( String qPath ) throws IllegalPathException { if ( qPath == null ) throw new IllegalPathException ( "Bad internal path '" + qPath + "'" ) ; if ( qPath . length ( ) < 2 || ! qPath . startsWith ( "[]" ) ) throw new IllegalPathException ( "Bad internal path '" + qPath + "'" ) ; int uriStart = 0 ; List < QPathEntry > entries = new ArrayList < QPathEntry > ( ) ; while ( uriStart >= 0 ) { uriStart = qPath . indexOf ( "[" , uriStart ) ; int uriFinish = qPath . indexOf ( "]" , uriStart ) ; String uri = qPath . substring ( uriStart + 1 , uriFinish ) ; int tmp = qPath . indexOf ( "[" , uriFinish ) ; if ( tmp == - 1 ) { tmp = qPath . length ( ) ; uriStart = - 1 ; } else uriStart = tmp ; String localName = qPath . substring ( uriFinish + 1 , tmp ) ; int index = 0 ; int ind = localName . indexOf ( PREFIX_DELIMITER ) ; if ( ind != - 1 ) { index = Integer . parseInt ( localName . substring ( ind + 1 ) ) ; localName = localName . substring ( 0 , ind ) ; } else { if ( uriStart > - 1 ) throw new IllegalPathException ( "Bad internal path '" + qPath + "' each intermediate name should have index" ) ; } entries . add ( new QPathEntry ( uri , localName , index ) ) ; } return new QPath ( entries . toArray ( new QPathEntry [ entries . size ( ) ] ) ) ; }
Parses string and make internal path from it .
15,877
void repair ( boolean ignoreFailure ) throws IOException { if ( errors . size ( ) == 0 ) { log . info ( "No errors found." ) ; return ; } int notRepairable = 0 ; for ( Iterator < ConsistencyCheckError > it = errors . iterator ( ) ; it . hasNext ( ) ; ) { final ConsistencyCheckError error = it . next ( ) ; try { if ( error . repairable ( ) ) { error . repair ( ) ; } else { log . warn ( "Not repairable: " + error ) ; notRepairable ++ ; } } catch ( IOException e ) { if ( ignoreFailure ) { log . warn ( "Exception while reparing: " + e ) ; } else { throw e ; } } catch ( Exception e ) { if ( ignoreFailure ) { log . warn ( "Exception while reparing: " + e ) ; } else { throw new IOException ( e . getMessage ( ) , e ) ; } } } log . info ( "Repaired " + ( errors . size ( ) - notRepairable ) + " errors." ) ; if ( notRepairable > 0 ) { log . warn ( "" + notRepairable + " error(s) not repairable." ) ; } }
Repairs detected errors during the consistency check .
15,878
private void run ( ) throws IOException , RepositoryException { Set < String > multipleEntries = new HashSet < String > ( ) ; documentUUIDs = new HashSet < String > ( ) ; CachingMultiIndexReader reader = index . getIndexReader ( ) ; try { for ( int i = 0 ; i < reader . maxDoc ( ) ; i ++ ) { if ( i > 10 && i % ( reader . maxDoc ( ) / 5 ) == 0 ) { long progress = Math . round ( ( 100.0 * i ) / ( reader . maxDoc ( ) * 2f ) ) ; log . info ( "progress: " + progress + "%" ) ; } if ( reader . isDeleted ( i ) ) { continue ; } final int currentIndex = i ; Document d = reader . document ( currentIndex , FieldSelectors . UUID ) ; String uuid = d . get ( FieldNames . UUID ) ; if ( stateMgr . getItemData ( uuid ) != null ) { if ( ! documentUUIDs . add ( uuid ) ) { multipleEntries . add ( uuid ) ; } } else { errors . add ( new NodeDeleted ( uuid ) ) ; } } } finally { reader . release ( ) ; } for ( Iterator < String > it = multipleEntries . iterator ( ) ; it . hasNext ( ) ; ) { errors . add ( new MultipleEntries ( it . next ( ) ) ) ; } reader = index . getIndexReader ( ) ; try { for ( int i = 0 ; i < reader . maxDoc ( ) ; i ++ ) { if ( i > 10 && i % ( reader . maxDoc ( ) / 5 ) == 0 ) { long progress = Math . round ( ( 100.0 * i ) / ( reader . maxDoc ( ) * 2f ) ) ; log . info ( "progress: " + ( progress + 50 ) + "%" ) ; } if ( reader . isDeleted ( i ) ) { continue ; } final int currentIndex = i ; Document d = reader . document ( currentIndex , FieldSelectors . UUID_AND_PARENT ) ; String uuid = d . get ( FieldNames . UUID ) ; String parentUUIDString = d . get ( FieldNames . PARENT ) ; if ( parentUUIDString == null || documentUUIDs . contains ( parentUUIDString ) ) { continue ; } if ( stateMgr . getItemData ( parentUUIDString ) != null ) { errors . add ( new MissingAncestor ( uuid , parentUUIDString ) ) ; } else { errors . add ( new UnknownParent ( uuid , parentUUIDString ) ) ; } } } finally { reader . release ( ) ; } }
Runs the consistency check .
15,879
public WorkspaceContainer getWorkspaceContainer ( String workspaceName ) { Object comp = getComponentInstance ( workspaceName ) ; return comp != null && comp instanceof WorkspaceContainer ? ( WorkspaceContainer ) comp : null ; }
Get workspace Container by name .
15,880
public WorkspaceEntry getWorkspaceEntry ( String wsName ) { for ( WorkspaceEntry entry : config . getWorkspaceEntries ( ) ) { if ( entry . getName ( ) . equals ( wsName ) ) return entry ; } return null ; }
Get workspace configuration entry by name .
15,881
private void load ( ) throws RepositoryException { NamespaceDataPersister namespacePersister = ( NamespaceDataPersister ) this . getComponentInstanceOfType ( NamespaceDataPersister . class ) ; NamespaceRegistryImpl nsRegistry = ( NamespaceRegistryImpl ) getNamespaceRegistry ( ) ; namespacePersister . start ( ) ; nsRegistry . start ( ) ; JCRNodeTypeDataPersister nodeTypePersister = ( JCRNodeTypeDataPersister ) this . getComponentInstanceOfType ( JCRNodeTypeDataPersister . class ) ; NodeTypeDataManagerImpl ntManager = ( NodeTypeDataManagerImpl ) this . getComponentInstanceOfType ( NodeTypeDataManagerImpl . class ) ; nodeTypePersister . start ( ) ; ntManager . start ( ) ; }
Load namespaces and nodetypes from persistent repository .
15,882
protected InternalQName [ ] getSelectProperties ( ) throws RepositoryException { List < InternalQName > selectProps = new ArrayList < InternalQName > ( ) ; selectProps . addAll ( Arrays . asList ( root . getSelectProperties ( ) ) ) ; if ( selectProps . size ( ) == 0 ) { LocationStepQueryNode [ ] steps = root . getLocationNode ( ) . getPathSteps ( ) ; final InternalQName [ ] ntName = new InternalQName [ 1 ] ; steps [ steps . length - 1 ] . acceptOperands ( new DefaultQueryNodeVisitor ( ) { public Object visit ( AndQueryNode node , Object data ) throws RepositoryException { return node . acceptOperands ( this , data ) ; } public Object visit ( NodeTypeQueryNode node , Object data ) { ntName [ 0 ] = node . getValue ( ) ; return data ; } } , null ) ; if ( ntName [ 0 ] == null ) { ntName [ 0 ] = Constants . NT_BASE ; } NodeTypeData nt = session . getWorkspace ( ) . getNodeTypesHolder ( ) . getNodeType ( ntName [ 0 ] ) ; PropertyDefinitionData [ ] propDefs = nt . getDeclaredPropertyDefinitions ( ) ; for ( int i = 0 ; i < propDefs . length ; i ++ ) { PropertyDefinitionData propDef = propDefs [ i ] ; if ( ! propDef . isResidualSet ( ) && ! propDef . isMultiple ( ) ) { selectProps . add ( propDef . getName ( ) ) ; } } } if ( ! selectProps . contains ( Constants . JCR_PATH ) ) { selectProps . add ( Constants . JCR_PATH ) ; } if ( ! selectProps . contains ( Constants . JCR_SCORE ) ) { selectProps . add ( Constants . JCR_SCORE ) ; } return ( InternalQName [ ] ) selectProps . toArray ( new InternalQName [ selectProps . size ( ) ] ) ; }
Returns the select properties for this query .
15,883
protected Session session ( String repoName , String wsName , List < String > lockTokens ) throws Exception , NoSuchWorkspaceException { ManageableRepository repo = repositoryService . getCurrentRepository ( ) ; if ( PropertyManager . isDevelopping ( ) && log . isWarnEnabled ( ) ) { String currentRepositoryName = repo . getConfiguration ( ) . getName ( ) ; if ( ! currentRepositoryName . equals ( repoName ) ) { log . warn ( "The expected repository was '" + repoName + "' but we will use the current repository instead which is '" + currentRepositoryName + "'" ) ; } } SessionProvider sp = sessionProviderService . getSessionProvider ( null ) ; if ( sp == null ) throw new RepositoryException ( "SessionProvider is not properly set. Make the application calls" + "SessionProviderService.setSessionProvider(..) somewhere before (" + "for instance in Servlet Filter for WEB application)" ) ; Session session = sp . getSession ( wsName , repo ) ; if ( lockTokens != null ) { String [ ] presentLockTokens = session . getLockTokens ( ) ; ArrayList < String > presentLockTokensList = new ArrayList < String > ( ) ; for ( int i = 0 ; i < presentLockTokens . length ; i ++ ) { presentLockTokensList . add ( presentLockTokens [ i ] ) ; } for ( int i = 0 ; i < lockTokens . size ( ) ; i ++ ) { String lockToken = lockTokens . get ( i ) ; if ( ! presentLockTokensList . contains ( lockToken ) ) { session . addLockToken ( lockToken ) ; } } } return session ; }
Gives access to the current session .
15,884
protected String getRepositoryName ( String repoName ) throws RepositoryException { ManageableRepository repo = repositoryService . getCurrentRepository ( ) ; String currentRepositoryName = repo . getConfiguration ( ) . getName ( ) ; if ( PropertyManager . isDevelopping ( ) && log . isWarnEnabled ( ) ) { if ( ! currentRepositoryName . equals ( repoName ) ) { log . warn ( "The expected repository was '" + repoName + "' but we will use the current repository instead which is '" + currentRepositoryName + "'" ) ; } } return currentRepositoryName ; }
Gives the name of the repository to access .
15,885
protected String normalizePath ( String repoPath ) { if ( repoPath . length ( ) > 0 && repoPath . endsWith ( "/" ) ) { return repoPath . substring ( 0 , repoPath . length ( ) - 1 ) ; } return repoPath ; }
Normalizes path .
15,886
protected String path ( String repoPath , boolean withIndex ) { String path = repoPath . substring ( workspaceName ( repoPath ) . length ( ) ) ; if ( path . length ( ) > 0 ) { if ( ! withIndex ) { return TextUtil . removeIndexFromPath ( path ) ; } return path ; } return "/" ; }
Extracts path from repository path .
15,887
protected List < String > lockTokens ( String lockTokenHeader , String ifHeader ) { ArrayList < String > lockTokens = new ArrayList < String > ( ) ; if ( lockTokenHeader != null ) { if ( lockTokenHeader . startsWith ( "<" ) ) { lockTokenHeader = lockTokenHeader . substring ( 1 , lockTokenHeader . length ( ) - 1 ) ; } if ( lockTokenHeader . contains ( WebDavConst . Lock . OPAQUE_LOCK_TOKEN ) ) { lockTokenHeader = lockTokenHeader . split ( ":" ) [ 1 ] ; } lockTokens . add ( lockTokenHeader ) ; } if ( ifHeader != null ) { String headerLockToken = ifHeader . substring ( ifHeader . indexOf ( "(" ) ) ; headerLockToken = headerLockToken . substring ( 2 , headerLockToken . length ( ) - 2 ) ; if ( headerLockToken . contains ( WebDavConst . Lock . OPAQUE_LOCK_TOKEN ) ) { headerLockToken = headerLockToken . split ( ":" ) [ 1 ] ; } lockTokens . add ( headerLockToken ) ; } return lockTokens ; }
Creates the list of Lock tokens from Lock - Token and If headers .
15,888
private URI buildURI ( String path ) throws URISyntaxException { try { return new URI ( path ) ; } catch ( URISyntaxException e ) { return new URI ( TextUtil . escape ( path , '%' , true ) ) ; } }
Build URI from string .
15,889
private boolean isAllowedPath ( String workspaceName , String path ) { if ( pattern == null ) return true ; Matcher matcher = pattern . matcher ( workspaceName + ":" + path ) ; if ( ! matcher . find ( ) ) { log . warn ( "Access not allowed to webdav resource {}" , path ) ; return false ; } return true ; }
Check resource access allowed
15,890
protected void createRepositoryInternally ( String backupId , RepositoryEntry rEntry , String rToken , DBCreationProperties creationProps ) throws RepositoryConfigurationException , RepositoryCreationException { if ( rpcService != null ) { String stringRepositoryEntry = null ; try { JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl ( ) ; JsonValue json = generatorImpl . createJsonObject ( rEntry ) ; stringRepositoryEntry = json . toString ( ) ; } catch ( JsonException e ) { throw new RepositoryCreationException ( "Can not serialize repository entry: " + e . getMessage ( ) , e ) ; } try { Object result = rpcService . executeCommandOnCoordinator ( createRepository , true , backupId , stringRepositoryEntry , rToken , creationProps ) ; if ( result != null ) { if ( result instanceof Throwable ) { throw new RepositoryCreationException ( "Can't create repository " + rEntry . getName ( ) , ( Throwable ) result ) ; } else { throw new RepositoryCreationException ( "createRepository command returned uknown result type." ) ; } } } catch ( RPCException e ) { Throwable cause = ( e ) . getCause ( ) ; if ( cause instanceof RepositoryCreationException ) { throw ( RepositoryCreationException ) cause ; } else if ( cause instanceof RepositoryConfigurationException ) { throw ( RepositoryConfigurationException ) cause ; } else { throw new RepositoryCreationException ( e . getMessage ( ) , e ) ; } } try { List < Object > results = rpcService . executeCommandOnAllNodes ( startRepository , true , stringRepositoryEntry , creationProps ) ; for ( Object result : results ) { if ( result != null ) { if ( result instanceof Throwable ) { throw new RepositoryCreationException ( "Repository " + rEntry . getName ( ) + " created on coordinator, but can not be started at other cluster nodes" , ( ( Throwable ) result ) ) ; } else { throw new RepositoryCreationException ( "startRepository command returns uknown result type" ) ; } } } } catch ( RPCException e ) { throw new RepositoryCreationException ( "Repository " + rEntry . getName ( ) + " created on coordinator, can not be started at other cluster node: " + e . getMessage ( ) , e ) ; } } else { try { createRepositoryLocally ( backupId , rEntry , rToken , creationProps ) ; } finally { pendingRepositories . remove ( rToken ) ; } } }
Create repository internally . serverUrl and connProps contain specific properties for db creation .
15,891
protected void removeRepositoryLocally ( String repositoryName , boolean forceRemove ) throws RepositoryCreationException { try { ManageableRepository repositorty = repositoryService . getRepository ( repositoryName ) ; Set < String > datasources = extractDataSourceNames ( repositorty . getConfiguration ( ) , false ) ; for ( String workspaceName : repositorty . getWorkspaceNames ( ) ) { WorkspaceContainerFacade wc = repositorty . getWorkspaceContainer ( workspaceName ) ; SessionRegistry sessionRegistry = ( SessionRegistry ) wc . getComponent ( SessionRegistry . class ) ; sessionRegistry . closeSessions ( workspaceName ) ; } repositoryService . removeRepository ( repositoryName , forceRemove ) ; repositoryService . getConfig ( ) . retain ( ) ; for ( String dsName : datasources ) { try { DataSource ds = ( DataSource ) initialContextInitializer . getInitialContext ( ) . lookup ( dsName ) ; initialContextInitializer . getInitialContextBinder ( ) . unbind ( dsName ) ; if ( ds instanceof CloseableDataSource ) { ( ( CloseableDataSource ) ds ) . close ( ) ; } } catch ( NamingException e ) { LOG . error ( "Can't unbind datasource " + dsName , e ) ; } catch ( FileNotFoundException e ) { LOG . error ( "Can't unbind datasource " + dsName , e ) ; } catch ( XMLStreamException e ) { LOG . error ( "Can't unbind datasource " + dsName , e ) ; } } } catch ( RepositoryException e ) { throw new RepositoryCreationException ( "Can't remove repository" , e ) ; } catch ( RepositoryConfigurationException e ) { throw new RepositoryCreationException ( "Can't remove repository" , e ) ; } }
Remove repository locally .
15,892
private void traverseResources ( Resource resource , int counter ) throws XMLStreamException , RepositoryException , IllegalResourceTypeException , URISyntaxException , UnsupportedEncodingException { xmlStreamWriter . writeStartElement ( "DAV:" , "response" ) ; xmlStreamWriter . writeStartElement ( "DAV:" , "href" ) ; String href = resource . getIdentifier ( ) . toASCIIString ( ) ; if ( resource . isCollection ( ) ) { xmlStreamWriter . writeCharacters ( href + "/" ) ; } else { xmlStreamWriter . writeCharacters ( href ) ; } xmlStreamWriter . writeEndElement ( ) ; PropstatGroupedRepresentation propstat = new PropstatGroupedRepresentation ( resource , propertyNames , propertyNamesOnly , session ) ; PropertyWriteUtil . writePropStats ( xmlStreamWriter , propstat . getPropStats ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; int d = depth ; if ( resource . isCollection ( ) ) { if ( counter < d ) { CollectionResource collection = ( CollectionResource ) resource ; for ( Resource child : collection . getResources ( ) ) { traverseResources ( child , counter + 1 ) ; } } } }
Traverses resources and collects the vales of required properties .
15,893
private void calculateWorkspaceDataSize ( ) { long dataSize ; try { dataSize = getWorkspaceDataSizeDirectly ( ) ; } catch ( QuotaManagerException e1 ) { throw new IllegalStateException ( "Can't calculate workspace data size" , e1 ) ; } ChangesItem changesItem = new ChangesItem ( ) ; changesItem . updateWorkspaceChangedSize ( dataSize ) ; Runnable task = new ApplyPersistedChangesTask ( context , changesItem ) ; task . run ( ) ; }
Calculates and accumulates workspace data size .
15,894
private void printWarning ( PropertyImpl property , Exception exception ) throws RepositoryException { if ( PropertyManager . isDevelopping ( ) ) { LOG . warn ( "Binary value reader error, content by path " + property . getPath ( ) + ", property id " + property . getData ( ) . getIdentifier ( ) + " : " + exception . getMessage ( ) , exception ) ; } else { LOG . warn ( "Binary value reader error, content by path " + property . getPath ( ) + ", property id " + property . getData ( ) . getIdentifier ( ) + " : " + exception . getMessage ( ) ) ; } }
Print warning message on the console
15,895
private void setJCRProperties ( NodeImpl parent , Properties props ) throws Exception { if ( ! parent . isNodeType ( "dc:elementSet" ) ) { parent . addMixin ( "dc:elementSet" ) ; } ValueFactory vFactory = parent . getSession ( ) . getValueFactory ( ) ; LocationFactory lFactory = parent . getSession ( ) . getLocationFactory ( ) ; for ( Entry entry : props . entrySet ( ) ) { QName qname = ( QName ) entry . getKey ( ) ; JCRName jcrName = lFactory . createJCRName ( new InternalQName ( qname . getNamespace ( ) , qname . getName ( ) ) ) ; PropertyDefinitionData definition = parent . getSession ( ) . getWorkspace ( ) . getNodeTypesHolder ( ) . getPropertyDefinitions ( jcrName . getInternalName ( ) , ( ( NodeData ) parent . getData ( ) ) . getPrimaryTypeName ( ) , ( ( NodeData ) parent . getData ( ) ) . getMixinTypeNames ( ) ) . getAnyDefinition ( ) ; if ( definition != null ) { if ( definition . isMultiple ( ) ) { Value [ ] values = { createValue ( entry . getValue ( ) , vFactory ) } ; parent . setProperty ( jcrName . getAsString ( ) , values ) ; } else { Value value = createValue ( entry . getValue ( ) , vFactory ) ; parent . setProperty ( jcrName . getAsString ( ) , value ) ; } } } }
Sets metainfo properties as JCR properties to node .
15,896
private static String prepareScripts ( String initScriptPath , String itemTableSuffix , String valueTableSuffix , String refTableSuffix , boolean isolatedDB ) throws IOException { String scripts = IOUtil . getStreamContentAsString ( PrivilegedFileHelper . getResourceAsStream ( initScriptPath ) ) ; if ( isolatedDB ) { scripts = scripts . replace ( "MITEM" , itemTableSuffix ) . replace ( "MVALUE" , valueTableSuffix ) . replace ( "MREF" , refTableSuffix ) ; } return scripts ; }
Preparing SQL scripts for database initialization .
15,897
public static String scriptPath ( String dbDialect , boolean multiDb ) { String suffix = multiDb ? "m" : "s" ; String sqlPath = null ; if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_ORACLE ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.ora.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_PGSQL ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.pgsql.sql" ; } else if ( dbDialect . equals ( DBConstants . DB_DIALECT_MYSQL ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.mysql.sql" ; } else if ( dbDialect . equals ( DBConstants . DB_DIALECT_MYSQL_NDB ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.mysql-ndb.sql" ; } else if ( dbDialect . equals ( DBConstants . DB_DIALECT_MYSQL_NDB_UTF8 ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.mysql-ndb-utf8.sql" ; } else if ( dbDialect . equals ( DBConstants . DB_DIALECT_MYSQL_MYISAM ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.mysql-myisam.sql" ; } else if ( dbDialect . equals ( DBConstants . DB_DIALECT_MYSQL_UTF8 ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.mysql-utf8.sql" ; } else if ( dbDialect . equals ( DBConstants . DB_DIALECT_MYSQL_MYISAM_UTF8 ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.mysql-myisam-utf8.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_MSSQL ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.mssql.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_DERBY ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.derby.sql" ; } else if ( dbDialect . equals ( DBConstants . DB_DIALECT_DB2V8 ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.db2v8.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_DB2 ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.db2.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_SYBASE ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.sybase.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_INGRES ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.ingres.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_H2 ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.h2.sql" ; } else if ( dbDialect . startsWith ( DBConstants . DB_DIALECT_HSQLDB ) ) { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.sql" ; } else { sqlPath = "/conf/storage/jcr-" + suffix + "jdbc.sql" ; } return sqlPath ; }
Returns path where SQL scripts for database initialization is stored .
15,898
public static String getRootNodeInitializeScript ( String itemTableName , boolean multiDb ) { String singeDbScript = "insert into " + itemTableName + "(ID, PARENT_ID, NAME, CONTAINER_NAME, VERSION, I_CLASS, I_INDEX, " + "N_ORDER_NUM) VALUES('" + Constants . ROOT_PARENT_UUID + "', '" + Constants . ROOT_PARENT_UUID + "', '" + Constants . ROOT_PARENT_NAME + "', '" + Constants . ROOT_PARENT_CONAINER_NAME + "', 0, 0, 0, 0)" ; String multiDbScript = "insert into " + itemTableName + "(ID, PARENT_ID, NAME, VERSION, I_CLASS, I_INDEX, " + "N_ORDER_NUM) VALUES('" + Constants . ROOT_PARENT_UUID + "', '" + Constants . ROOT_PARENT_UUID + "', '" + Constants . ROOT_PARENT_NAME + "', 0, 0, 0, 0)" ; return multiDb ? multiDbScript : singeDbScript ; }
Initialization script for root node .
15,899
public static String getObjectScript ( String objectName , boolean multiDb , String dialect , WorkspaceEntry wsEntry ) throws RepositoryConfigurationException , IOException { String scripts = prepareScripts ( wsEntry , dialect ) ; String sql = null ; for ( String query : JDBCUtils . splitWithSQLDelimiter ( scripts ) ) { String q = JDBCUtils . cleanWhitespaces ( query ) ; if ( q . contains ( objectName ) ) { if ( sql != null ) { throw new RepositoryConfigurationException ( "Can't find unique script for object creation. Object name: " + objectName ) ; } sql = q ; } } if ( sql != null ) { return sql ; } throw new RepositoryConfigurationException ( "Script for object creation is not found. Object name: " + objectName ) ; }
Returns SQL script for create objects such as index primary of foreign key .