idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
15,900 | public static boolean useSequenceForOrderNumber ( WorkspaceEntry wsConfig , String dbDialect ) throws RepositoryConfigurationException { try { if ( wsConfig . getContainer ( ) . getParameterValue ( JDBCWorkspaceDataContainer . USE_SEQUENCE_FOR_ORDER_NUMBER , JDBCWorkspaceDataContainer . USE_SEQUENCE_AUTO ) . equalsIgnoreCase ( JDBCWorkspaceDataContainer . USE_SEQUENCE_AUTO ) ) { return JDBCWorkspaceDataContainer . useSequenceDefaultValue ( ) ; } else { return wsConfig . getContainer ( ) . getParameterBoolean ( JDBCWorkspaceDataContainer . USE_SEQUENCE_FOR_ORDER_NUMBER ) ; } } catch ( RepositoryConfigurationException e ) { return JDBCWorkspaceDataContainer . useSequenceDefaultValue ( ) ; } } | Use sequence for order number . |
15,901 | SessionImpl createSession ( ConversationState user ) throws RepositoryException , LoginException { if ( IdentityConstants . SYSTEM . equals ( user . getIdentity ( ) . getUserId ( ) ) ) { SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( JCRRuntimePermissions . CREATE_SYSTEM_SESSION_PERMISSION ) ; } } else if ( DynamicIdentity . DYNAMIC . equals ( user . getIdentity ( ) . getUserId ( ) ) ) { SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( JCRRuntimePermissions . CREATE_DYNAMIC_SESSION_PERMISSION ) ; } } if ( SessionReference . isStarted ( ) ) { return new TrackedSession ( workspaceName , user , container ) ; } else { return new SessionImpl ( workspaceName , user , container ) ; } } | Creates Session object by given Credentials |
15,902 | public synchronized void retain ( ) throws RepositoryException { try { if ( ! isRetainable ( ) ) throw new RepositoryException ( "Unsupported configuration place " + configurationService . getURL ( param . getValue ( ) ) + " If you want to save configuration, start repository from standalone file." + " Or persister-class-name not configured" ) ; OutputStream saveStream = null ; if ( configurationPersister != null ) { saveStream = new ByteArrayOutputStream ( ) ; } else { URL filePath = configurationService . getURL ( param . getValue ( ) ) ; final File sourceConfig = new File ( filePath . toURI ( ) ) ; final File backUp = new File ( sourceConfig . getAbsoluteFile ( ) + "." + indexBackupFile ++ ) ; if ( indexBackupFile > maxBackupFiles ) { indexBackupFile = 1 ; } try { SecurityHelper . doPrivilegedIOExceptionAction ( new PrivilegedExceptionAction < Void > ( ) { public Void run ( ) throws IOException { DirectoryHelper . deleteDstAndRename ( sourceConfig , backUp ) ; return null ; } } ) ; } catch ( IOException ioe ) { throw new RepositoryException ( "Can't back up configuration on path " + PrivilegedFileHelper . getAbsolutePath ( sourceConfig ) , ioe ) ; } saveStream = PrivilegedFileHelper . fileOutputStream ( sourceConfig ) ; } IBindingFactory bfact ; try { bfact = SecurityHelper . doPrivilegedExceptionAction ( new PrivilegedExceptionAction < IBindingFactory > ( ) { public IBindingFactory run ( ) throws Exception { return BindingDirectory . getFactory ( RepositoryServiceConfiguration . class ) ; } } ) ; } catch ( PrivilegedActionException pae ) { Throwable cause = pae . getCause ( ) ; if ( cause instanceof JiBXException ) { throw ( JiBXException ) cause ; } else if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else { throw new RuntimeException ( cause ) ; } } IMarshallingContext mctx = bfact . createMarshallingContext ( ) ; mctx . marshalDocument ( this , "ISO-8859-1" , null , saveStream ) ; saveStream . close ( ) ; if ( configurationPersister != null ) { configurationPersister . write ( new ByteArrayInputStream ( ( ( ByteArrayOutputStream ) saveStream ) . toByteArray ( ) ) ) ; } } catch ( JiBXException e ) { throw new RepositoryException ( e ) ; } catch ( FileNotFoundException e ) { throw new RepositoryException ( e ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } catch ( RepositoryConfigurationException e ) { throw new RepositoryException ( e ) ; } catch ( Exception e ) { throw new RepositoryException ( e ) ; } } | Retain configuration of JCR If configurationPersister is configured it write data in to the persister otherwise it try to save configuration in file |
15,903 | protected void doRestore ( File backupFile ) throws BackupException { if ( ! PrivilegedFileHelper . exists ( backupFile ) ) { LOG . warn ( "Nothing to restore for quotas" ) ; return ; } ZipObjectReader in = null ; try { in = new ZipObjectReader ( PrivilegedFileHelper . zipInputStream ( backupFile ) ) ; quotaPersister . restoreWorkspaceData ( rName , wsName , in ) ; } catch ( IOException e ) { throw new BackupException ( e ) ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { LOG . error ( "Can't close input stream" , e ) ; } } } repairDataSize ( ) ; } | Restores content . |
15,904 | private void repairDataSize ( ) { try { long dataSize = quotaPersister . getWorkspaceDataSize ( rName , wsName ) ; ChangesItem changesItem = new ChangesItem ( ) ; changesItem . updateWorkspaceChangedSize ( dataSize ) ; quotaPersister . setWorkspaceDataSize ( rName , wsName , 0 ) ; Runnable task = new ApplyPersistedChangesTask ( wqm . getContext ( ) , changesItem ) ; task . run ( ) ; } catch ( UnknownDataSizeException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( e . getMessage ( ) , e ) ; } } } | After workspace data size being restored need also to update repository and global data size on respective value . |
15,905 | protected void doBackup ( File backupFile ) throws BackupException { ZipObjectWriter out = null ; try { out = new ZipObjectWriter ( PrivilegedFileHelper . zipOutputStream ( backupFile ) ) ; quotaPersister . backupWorkspaceData ( rName , wsName , out ) ; } catch ( IOException e ) { throw new BackupException ( e ) ; } finally { if ( out != null ) { try { out . close ( ) ; } catch ( IOException e ) { LOG . error ( "Can't close output stream" , e ) ; } } } } | Backups data to define file . |
15,906 | private void importResource ( Node parentNode , InputStream file_in , String resourceType , ArtifactDescriptor artifact ) throws RepositoryException { String filename ; if ( resourceType . equals ( "metadata" ) ) { filename = "maven-metadata.xml" ; } else { filename = String . format ( "%s-%s.%s" , artifact . getArtifactId ( ) , artifact . getVersionId ( ) , resourceType ) ; } OutputStream fout = null ; File tmp_file = null ; try { String tmpFilename = getUniqueFilename ( filename ) ; tmp_file = File . createTempFile ( tmpFilename , null ) ; fout = new FileOutputStream ( tmp_file ) ; IOUtils . copy ( file_in , fout ) ; fout . flush ( ) ; } catch ( FileNotFoundException e ) { LOG . error ( "Cannot create .tmp file for storing artifact" , e ) ; } catch ( IOException e ) { LOG . error ( "IO exception on .tmp file for storing artifact" , e ) ; } finally { IOUtils . closeQuietly ( file_in ) ; IOUtils . closeQuietly ( fout ) ; } writePrimaryContent ( parentNode , filename , resourceType , tmp_file ) ; writeChecksum ( parentNode , filename , tmp_file , "SHA1" ) ; try { FileUtils . forceDelete ( tmp_file ) ; } catch ( IOException e ) { LOG . error ( "Cannot delete tmp file" , e ) ; } } | this method used for writing to repo jars poms and their checksums |
15,907 | private IndexInfos createIndexInfos ( Boolean system , IndexerIoModeHandler modeHandler , QueryHandlerEntry config , QueryHandler handler ) throws RepositoryConfigurationException { try { RSyncConfiguration rSyncConfiguration = new RSyncConfiguration ( config ) ; if ( rSyncConfiguration . getRsyncEntryName ( ) != null ) { return new RsyncIndexInfos ( wsId , cache , system , modeHandler , handler . getContext ( ) . getIndexDirectory ( ) , rSyncConfiguration ) ; } else { return new ISPNIndexInfos ( wsId , cache , true , modeHandler ) ; } } catch ( RepositoryConfigurationException e ) { return new ISPNIndexInfos ( wsId , cache , true , modeHandler ) ; } } | Factory method for creating corresponding IndexInfos class . RSyncIndexInfos created if RSync configured and ISPNIndexInfos otherwise |
15,908 | @ ManagedDescription ( "The number of active locks" ) public int getNumLocks ( ) { try { return getNumLocks . run ( ) ; } catch ( LockException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } return - 1 ; } | Returns the number of active locks . |
15,909 | protected boolean hasLocks ( ) { try { return hasLocks . run ( ) ; } catch ( LockException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } return true ; } | Indicates if some locks have already been created . |
15,910 | public boolean isLockLive ( String nodeId ) throws LockException { try { return isLockLive . run ( nodeId ) ; } catch ( LockException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } return false ; } | Check is LockManager contains lock . No matter it is in pending or persistent state . |
15,911 | protected LockData getLockDataById ( String nodeId ) { try { return getLockDataById . run ( nodeId ) ; } catch ( LockException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } return null ; } | Returns lock data by node identifier . |
15,912 | protected synchronized List < LockData > getLockList ( ) { try { return getLockList . run ( ) ; } catch ( LockException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An exception occurred: " + e . getMessage ( ) ) ; } } return null ; } | Returns all locks . |
15,913 | public SessionLockManager getSessionLockManager ( String sessionId , SessionDataManager transientManager ) { CacheableSessionLockManager sessionManager = new CacheableSessionLockManager ( sessionId , this , transientManager ) ; sessionLockManagers . put ( sessionId , sessionManager ) ; return sessionManager ; } | Return new instance of session lock manager . |
15,914 | public synchronized void removeExpired ( ) { final List < String > removeLockList = new ArrayList < String > ( ) ; for ( LockData lock : getLockList ( ) ) { if ( ! lock . isSessionScoped ( ) && lock . getTimeToDeath ( ) < 0 ) { removeLockList . add ( lock . getNodeIdentifier ( ) ) ; } } Collections . sort ( removeLockList ) ; for ( String rLock : removeLockList ) { removeLock ( rLock ) ; } } | Remove expired locks . Used from LockRemover . |
15,915 | protected void removeLock ( String nodeIdentifier ) { try { NodeData nData = ( NodeData ) dataManager . getItemData ( nodeIdentifier ) ; if ( nData == null ) { return ; } PlainChangesLog changesLog = new PlainChangesLogImpl ( new ArrayList < ItemState > ( ) , IdentityConstants . SYSTEM , ExtendedEvent . UNLOCK ) ; ItemData lockOwner = copyItemData ( ( PropertyData ) dataManager . getItemData ( nData , new QPathEntry ( Constants . JCR_LOCKOWNER , 1 ) , ItemType . PROPERTY ) ) ; if ( lockOwner == null ) { return ; } changesLog . add ( ItemState . createDeletedState ( lockOwner ) ) ; ItemData lockIsDeep = copyItemData ( ( PropertyData ) dataManager . getItemData ( nData , new QPathEntry ( Constants . JCR_LOCKISDEEP , 1 ) , ItemType . PROPERTY ) ) ; if ( lockIsDeep == null ) { return ; } changesLog . add ( ItemState . createDeletedState ( lockIsDeep ) ) ; if ( lockOwner == null && lockIsDeep == null ) { return ; } dataManager . save ( new TransactionChangesLog ( changesLog ) ) ; } catch ( JCRInvalidItemStateException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "The propperty was removed in other node of cluster." , e ) ; } } catch ( RepositoryException e ) { LOG . error ( "Error occur during removing lock" + e . getLocalizedMessage ( ) , e ) ; } } | Remove lock used by Lock remover . |
15,916 | protected void removeAll ( ) { List < LockData > locks = getLockList ( ) ; for ( LockData lockData : locks ) { removeLock ( lockData . getNodeIdentifier ( ) ) ; } } | Remove all locks . |
15,917 | public static byte [ ] getAsByteArray ( TransactionChangesLog dataChangesLog ) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( os ) ; oos . writeObject ( dataChangesLog ) ; byte [ ] bArray = os . toByteArray ( ) ; return bArray ; } | getAsByteArray . Make the array of bytes from ChangesLog . |
15,918 | public static TransactionChangesLog getAsItemDataChangesLog ( byte [ ] byteArray ) throws IOException , ClassNotFoundException { ByteArrayInputStream is = new ByteArrayInputStream ( byteArray ) ; ObjectInputStream ois = new ObjectInputStream ( is ) ; TransactionChangesLog objRead = ( TransactionChangesLog ) ois . readObject ( ) ; return objRead ; } | getAsItemDataChangesLog . Make the ChangesLog from array of bytes . |
15,919 | public PlainChangesLog read ( ObjectReader in ) throws UnknownClassIdException , IOException { int key ; if ( ( key = in . readInt ( ) ) != SerializationConstants . PLAIN_CHANGES_LOG_IMPL ) { throw new UnknownClassIdException ( "There is unexpected class [" + key + "]" ) ; } int eventType = in . readInt ( ) ; String sessionId = in . readString ( ) ; List < ItemState > items = new ArrayList < ItemState > ( ) ; int listSize = in . readInt ( ) ; for ( int i = 0 ; i < listSize ; i ++ ) { ItemStateReader isr = new ItemStateReader ( holder , spoolConfig ) ; ItemState is = isr . read ( in ) ; items . add ( is ) ; } return new PlainChangesLogImpl ( items , sessionId , eventType ) ; } | Read and set PlainChangesLog data . |
15,920 | public void write ( ObjectWriter out , PlainChangesLog pcl ) throws IOException { out . writeInt ( SerializationConstants . PLAIN_CHANGES_LOG_IMPL ) ; out . writeInt ( pcl . getEventType ( ) ) ; out . writeString ( pcl . getSessionId ( ) ) ; List < ItemState > list = pcl . getAllStates ( ) ; int listSize = list . size ( ) ; out . writeInt ( listSize ) ; ItemStateWriter wr = new ItemStateWriter ( ) ; for ( int i = 0 ; i < listSize ; i ++ ) { wr . write ( out , list . get ( i ) ) ; } } | Write PlainChangesLog data . |
15,921 | private ExtendedNode getUsersStorageNode ( ) throws RepositoryException { Session session = service . getStorageSession ( ) ; try { return ( ExtendedNode ) utils . getUsersStorageNode ( service . getStorageSession ( ) ) ; } finally { session . logout ( ) ; } } | Returns users storage node . |
15,922 | protected void closeStatements ( ) { try { if ( findItemById != null ) { findItemById . close ( ) ; } if ( findItemByPath != null ) { findItemByPath . close ( ) ; } if ( findItemByName != null ) { findItemByName . close ( ) ; } if ( findChildPropertyByPath != null ) { findChildPropertyByPath . close ( ) ; } if ( findPropertyByName != null ) { findPropertyByName . close ( ) ; } if ( findDescendantNodes != null ) { findDescendantNodes . close ( ) ; } if ( findDescendantProperties != null ) { findDescendantProperties . close ( ) ; } if ( findReferences != null ) { findReferences . close ( ) ; } if ( findValuesByPropertyId != null ) { findValuesByPropertyId . close ( ) ; } if ( findValuesDataByPropertyId != null ) { findValuesDataByPropertyId . close ( ) ; } if ( findNodesByParentId != null ) { findNodesByParentId . close ( ) ; } if ( findLastOrderNumberByParentId != null ) { findLastOrderNumberByParentId . close ( ) ; } if ( findNodesCountByParentId != null ) { findNodesCountByParentId . close ( ) ; } if ( findPropertiesByParentId != null ) { findPropertiesByParentId . close ( ) ; } if ( findMaxPropertyVersions != null ) { findMaxPropertyVersions . close ( ) ; } if ( insertNode != null ) { insertNode . close ( ) ; } if ( insertProperty != null ) { insertProperty . close ( ) ; } if ( insertReference != null ) { insertReference . close ( ) ; } if ( insertValue != null ) { insertValue . close ( ) ; } if ( updateNode != null ) { updateNode . close ( ) ; } if ( updateProperty != null ) { updateProperty . close ( ) ; } if ( deleteItem != null ) { deleteItem . close ( ) ; } if ( deleteReference != null ) { deleteReference . close ( ) ; } if ( deleteValue != null ) { deleteValue . close ( ) ; } if ( renameNode != null ) { renameNode . close ( ) ; } if ( findNodesAndProperties != null ) { findNodesAndProperties . close ( ) ; } if ( findNodesCount != null ) { findNodesCount . close ( ) ; } if ( findWorkspaceDataSize != null ) { findWorkspaceDataSize . close ( ) ; } if ( findNodeDataSize != null ) { findNodeDataSize . close ( ) ; } if ( findNodePropertiesOnValueStorage != null ) { findNodePropertiesOnValueStorage . close ( ) ; } if ( findWorkspacePropertiesOnValueStorage != null ) { findWorkspacePropertiesOnValueStorage . close ( ) ; } if ( findValueStorageDescAndSize != null ) { findValueStorageDescAndSize . close ( ) ; } } catch ( SQLException e ) { LOG . error ( "Can't close the statement: " + e . getMessage ( ) ) ; } } | Close all statements . |
15,923 | public List < NodeDataIndexing > getNodesAndProperties ( String lastNodeId , int offset , int limit ) throws RepositoryException , IllegalStateException { List < NodeDataIndexing > result = new ArrayList < NodeDataIndexing > ( ) ; checkIfOpened ( ) ; try { startTxIfNeeded ( ) ; ResultSet resultSet = findNodesAndProperties ( lastNodeId , offset , limit ) ; int processed = 0 ; try { TempNodeData tempNodeData = null ; while ( resultSet . next ( ) ) { if ( tempNodeData == null ) { tempNodeData = new TempNodeData ( resultSet ) ; processed ++ ; } else if ( ! resultSet . getString ( COLUMN_ID ) . equals ( tempNodeData . cid ) ) { if ( ! needToSkipOffsetNodes ( ) || processed > offset ) { result . add ( createNodeDataIndexing ( tempNodeData ) ) ; } tempNodeData = new TempNodeData ( resultSet ) ; processed ++ ; } if ( ! needToSkipOffsetNodes ( ) || processed > offset ) { String key = resultSet . getString ( "P_NAME" ) ; SortedSet < TempPropertyData > values = tempNodeData . properties . get ( key ) ; if ( values == null ) { values = new TreeSet < TempPropertyData > ( ) ; tempNodeData . properties . put ( key , values ) ; } values . add ( new ExtendedTempPropertyData ( resultSet ) ) ; } } if ( tempNodeData != null && ( ! needToSkipOffsetNodes ( ) || processed > offset ) ) { result . add ( createNodeDataIndexing ( tempNodeData ) ) ; } } finally { try { resultSet . close ( ) ; } catch ( SQLException e ) { LOG . error ( "Can't close the ResultSet: " + e . getMessage ( ) ) ; } } } catch ( IOException e ) { throw new RepositoryException ( e ) ; } catch ( IllegalNameException e ) { throw new RepositoryException ( e ) ; } catch ( SQLException e ) { throw new RepositoryException ( e ) ; } if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "getNodesAndProperties(%s, %s, %s) = %s elements" , lastNodeId , offset , limit , result . size ( ) ) ; } return result ; } | Returns from storage the next page of nodes and its properties . |
15,924 | public long getNodesCount ( ) throws RepositoryException { try { ResultSet countNodes = findNodesCount ( ) ; try { if ( countNodes . next ( ) ) { return countNodes . getLong ( 1 ) ; } else { throw new SQLException ( "ResultSet has't records." ) ; } } finally { JDBCUtils . freeResources ( countNodes , null , null ) ; } } catch ( SQLException e ) { throw new RepositoryException ( "Can not calculate nodes count" , e ) ; } } | Reads count of nodes in workspace . |
15,925 | public long getWorkspaceDataSize ( ) throws RepositoryException { long dataSize = 0 ; ResultSet result = null ; try { result = findWorkspaceDataSize ( ) ; try { if ( result . next ( ) ) { dataSize += result . getLong ( 1 ) ; } } finally { JDBCUtils . freeResources ( result , null , null ) ; } result = findWorkspacePropertiesOnValueStorage ( ) ; try { while ( result . next ( ) ) { String storageDesc = result . getString ( DBConstants . COLUMN_VSTORAGE_DESC ) ; String propertyId = result . getString ( DBConstants . COLUMN_VPROPERTY_ID ) ; int orderNum = result . getInt ( DBConstants . COLUMN_VORDERNUM ) ; ValueIOChannel channel = containerConfig . valueStorageProvider . getChannel ( storageDesc ) ; dataSize += channel . getValueSize ( getIdentifier ( propertyId ) , orderNum ) ; } } finally { JDBCUtils . freeResources ( result , null , null ) ; } } catch ( IOException e ) { throw new RepositoryException ( e ) ; } catch ( SQLException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } return dataSize ; } | Calculates workspace data size . |
15,926 | public long getNodeDataSize ( String nodeIdentifier ) throws RepositoryException { long dataSize = 0 ; ResultSet result = null ; try { result = findNodeDataSize ( getInternalId ( nodeIdentifier ) ) ; try { if ( result . next ( ) ) { dataSize += result . getLong ( 1 ) ; } } finally { JDBCUtils . freeResources ( result , null , null ) ; } result = findNodePropertiesOnValueStorage ( getInternalId ( nodeIdentifier ) ) ; try { while ( result . next ( ) ) { String storageDesc = result . getString ( DBConstants . COLUMN_VSTORAGE_DESC ) ; String propertyId = result . getString ( DBConstants . COLUMN_VPROPERTY_ID ) ; int orderNum = result . getInt ( DBConstants . COLUMN_VORDERNUM ) ; ValueIOChannel channel = containerConfig . valueStorageProvider . getChannel ( storageDesc ) ; dataSize += channel . getValueSize ( getIdentifier ( propertyId ) , orderNum ) ; } } finally { JDBCUtils . freeResources ( result , null , null ) ; } } catch ( IOException e ) { throw new RepositoryException ( e ) ; } catch ( SQLException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } return dataSize ; } | Calculates node data size . |
15,927 | protected ItemData getItemByIdentifier ( String cid ) throws RepositoryException , IllegalStateException { checkIfOpened ( ) ; try { ResultSet item = findItemByIdentifier ( cid ) ; try { if ( item . next ( ) ) { return itemData ( null , item , item . getInt ( COLUMN_CLASS ) , null ) ; } return null ; } finally { try { item . close ( ) ; } catch ( SQLException e ) { LOG . error ( "Can't close the ResultSet: " + e . getMessage ( ) ) ; } } } catch ( SQLException e ) { throw new RepositoryException ( "getItemData() error" , e ) ; } catch ( IOException e ) { throw new RepositoryException ( "getItemData() error" , e ) ; } } | Get Item By Identifier . |
15,928 | protected ItemData getItemByName ( NodeData parent , String parentId , QPathEntry name , ItemType itemType ) throws RepositoryException , IllegalStateException { checkIfOpened ( ) ; try { ResultSet item = null ; try { item = findItemByName ( parentId , name . getAsString ( ) , name . getIndex ( ) ) ; while ( item . next ( ) ) { int columnClass = item . getInt ( COLUMN_CLASS ) ; if ( itemType == ItemType . UNKNOWN || columnClass == itemType . ordinal ( ) ) { return itemData ( parent . getQPath ( ) , item , columnClass , parent . getACL ( ) ) ; } } return null ; } finally { try { if ( item != null ) { item . close ( ) ; } } catch ( SQLException e ) { LOG . error ( "Can't close the ResultSet: " + e . getMessage ( ) ) ; } } } catch ( SQLException e ) { throw new RepositoryException ( e ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } } | Gets an item data from database . |
15,929 | private ItemData itemData ( QPath parentPath , ResultSet item , int itemClass , AccessControlList parentACL ) throws RepositoryException , SQLException , IOException { String cid = item . getString ( COLUMN_ID ) ; String cname = item . getString ( COLUMN_NAME ) ; int cversion = item . getInt ( COLUMN_VERSION ) ; String cpid = item . getString ( COLUMN_PARENTID ) ; try { if ( itemClass == I_CLASS_NODE ) { int cindex = item . getInt ( COLUMN_INDEX ) ; int cnordernumb = item . getInt ( COLUMN_NORDERNUM ) ; return loadNodeRecord ( parentPath , cname , cid , cpid , cindex , cversion , cnordernumb , parentACL ) ; } int cptype = item . getInt ( COLUMN_PTYPE ) ; boolean cpmultivalued = item . getBoolean ( COLUMN_PMULTIVALUED ) ; return loadPropertyRecord ( parentPath , cname , cid , cpid , cversion , cptype , cpmultivalued ) ; } catch ( InvalidItemStateException e ) { throw new InvalidItemStateException ( "FATAL: Can't build item path for name " + cname + " id: " + getIdentifier ( cid ) + ". " + e ) ; } } | Build ItemData . |
15,930 | protected MixinInfo readMixins ( String cid ) throws SQLException , IllegalNameException { ResultSet mtrs = findPropertyByName ( cid , Constants . JCR_MIXINTYPES . getAsString ( ) ) ; try { List < InternalQName > mts = null ; boolean owneable = false ; boolean privilegeable = false ; if ( mtrs . next ( ) ) { mts = new ArrayList < InternalQName > ( ) ; do { byte [ ] mxnb = mtrs . getBytes ( COLUMN_VDATA ) ; if ( mxnb != null ) { InternalQName mxn = InternalQName . parse ( new String ( mxnb ) ) ; mts . add ( mxn ) ; if ( ! privilegeable && Constants . EXO_PRIVILEGEABLE . equals ( mxn ) ) { privilegeable = true ; } else if ( ! owneable && Constants . EXO_OWNEABLE . equals ( mxn ) ) { owneable = true ; } } } while ( mtrs . next ( ) ) ; } return new MixinInfo ( mts , owneable , privilegeable ) ; } finally { try { mtrs . close ( ) ; } catch ( SQLException e ) { LOG . error ( "Can't close the ResultSet: " + e . getMessage ( ) ) ; } } } | Read mixins from database . |
15,931 | protected PersistedPropertyData loadPropertyRecord ( QPath parentPath , String cname , String cid , String cpid , int cversion , int cptype , boolean cpmultivalued ) throws RepositoryException , SQLException , IOException { try { QPath qpath = QPath . makeChildPath ( parentPath == null ? traverseQPath ( cpid ) : parentPath , InternalQName . parse ( cname ) ) ; String identifier = getIdentifier ( cid ) ; List < ValueDataWrapper > data = readValues ( cid , cptype , identifier , cversion ) ; long size = 0 ; List < ValueData > values = new ArrayList < ValueData > ( ) ; for ( ValueDataWrapper vdDataWrapper : data ) { values . add ( vdDataWrapper . value ) ; size += vdDataWrapper . size ; } PersistedPropertyData pdata = new PersistedPropertyData ( identifier , qpath , getIdentifier ( cpid ) , cversion , cptype , cpmultivalued , values , new SimplePersistedSize ( size ) ) ; return pdata ; } catch ( IllegalNameException e ) { throw new RepositoryException ( e ) ; } } | Load PropertyData record . |
15,932 | private void deleteValues ( String cid , PropertyData pdata , boolean update , ChangedSizeHandler sizeHandler ) throws IOException , SQLException , RepositoryException , InvalidItemStateException { Set < String > storages = new HashSet < String > ( ) ; final ResultSet valueRecords = findValueStorageDescAndSize ( cid ) ; try { if ( valueRecords . next ( ) ) { do { final String storageId = valueRecords . getString ( COLUMN_VSTORAGE_DESC ) ; if ( ! valueRecords . wasNull ( ) ) { storages . add ( storageId ) ; } else { sizeHandler . accumulatePrevSize ( valueRecords . getLong ( 1 ) ) ; } } while ( valueRecords . next ( ) ) ; } for ( String storageId : storages ) { final ValueIOChannel channel = this . containerConfig . valueStorageProvider . getChannel ( storageId ) ; try { sizeHandler . accumulatePrevSize ( channel . getValueSize ( pdata . getIdentifier ( ) ) ) ; channel . delete ( pdata . getIdentifier ( ) ) ; valueChanges . add ( channel ) ; } finally { channel . close ( ) ; } } deleteValueData ( cid ) ; } finally { JDBCUtils . freeResources ( valueRecords , null , null ) ; } } | Delete Property Values . |
15,933 | private List < ValueDataWrapper > readValues ( String cid , int cptype , String identifier , int cversion ) throws IOException , SQLException , ValueStorageNotFoundException { List < ValueDataWrapper > data = new ArrayList < ValueDataWrapper > ( ) ; final ResultSet valueRecords = findValuesByPropertyId ( cid ) ; try { while ( valueRecords . next ( ) ) { final int orderNum = valueRecords . getInt ( COLUMN_VORDERNUM ) ; final String storageId = valueRecords . getString ( COLUMN_VSTORAGE_DESC ) ; ValueDataWrapper vdWrapper = valueRecords . wasNull ( ) ? ValueDataUtil . readValueData ( cid , cptype , orderNum , cversion , valueRecords . getBinaryStream ( COLUMN_VDATA ) , containerConfig . spoolConfig ) : readValueData ( identifier , orderNum , cptype , storageId ) ; data . add ( vdWrapper ) ; } } finally { try { valueRecords . close ( ) ; } catch ( SQLException e ) { LOG . error ( "Can't close the ResultSet: " + e . getMessage ( ) ) ; } } return data ; } | Read Property Values . |
15,934 | protected ValueDataWrapper readValueData ( String identifier , int orderNumber , int type , String storageId ) throws SQLException , IOException , ValueStorageNotFoundException { ValueIOChannel channel = this . containerConfig . valueStorageProvider . getChannel ( storageId ) ; try { return channel . read ( identifier , orderNumber , type , containerConfig . spoolConfig ) ; } finally { channel . close ( ) ; } } | Read ValueData from External Storage . |
15,935 | public IndexerIoModeHandler getModeHandler ( ) { if ( modeHandler == null ) { if ( ctx . getCache ( ) . getStatus ( ) != ComponentStatus . RUNNING ) { throw new IllegalStateException ( "The cache should be started first" ) ; } synchronized ( this ) { if ( modeHandler == null ) { this . modeHandler = new IndexerIoModeHandler ( cacheManager . isCoordinator ( ) || ctx . getCache ( ) . getAdvancedCache ( ) . getRpcManager ( ) == null ? IndexerIoMode . READ_WRITE : IndexerIoMode . READ_ONLY ) ; } } } return modeHandler ; } | Get the mode handler |
15,936 | @ SuppressWarnings ( "rawtypes" ) protected void doPushState ( ) { final boolean debugEnabled = LOG . isDebugEnabled ( ) ; if ( debugEnabled ) { LOG . debug ( "start pushing in-memory state to cache cacheLoader collection" ) ; } Map < String , ChangesFilterListsWrapper > changesMap = new HashMap < String , ChangesFilterListsWrapper > ( ) ; List < ChangesKey > processedItemKeys = new ArrayList < ChangesKey > ( ) ; DataContainer dc = ctx . getCache ( ) . getAdvancedCache ( ) . getDataContainer ( ) ; Set keys = dc . keySet ( ) ; InternalCacheEntry entry ; for ( Object k : keys ) { if ( ( entry = dc . get ( k ) ) != null ) { if ( entry . getValue ( ) instanceof ChangesFilterListsWrapper && entry . getKey ( ) instanceof ChangesKey ) { if ( debugEnabled ) { LOG . debug ( "Received list wrapper, start indexing..." ) ; } ChangesFilterListsWrapper staleListIncache = ( ChangesFilterListsWrapper ) entry . getValue ( ) ; ChangesKey key = ( ChangesKey ) entry . getKey ( ) ; ChangesFilterListsWrapper listToPush = changesMap . get ( key . getWsId ( ) ) ; if ( listToPush == null ) { listToPush = new ChangesFilterListsWrapper ( new HashSet < String > ( ) , new HashSet < String > ( ) , new HashSet < String > ( ) , new HashSet < String > ( ) ) ; changesMap . put ( key . getWsId ( ) , listToPush ) ; } if ( staleListIncache . getParentAddedNodes ( ) != null ) listToPush . getParentAddedNodes ( ) . addAll ( staleListIncache . getParentAddedNodes ( ) ) ; if ( staleListIncache . getParentRemovedNodes ( ) != null ) listToPush . getParentRemovedNodes ( ) . addAll ( staleListIncache . getParentRemovedNodes ( ) ) ; if ( staleListIncache . getAddedNodes ( ) != null ) listToPush . getAddedNodes ( ) . addAll ( staleListIncache . getAddedNodes ( ) ) ; if ( staleListIncache . getRemovedNodes ( ) != null ) listToPush . getRemovedNodes ( ) . addAll ( staleListIncache . getRemovedNodes ( ) ) ; processedItemKeys . add ( key ) ; } } } for ( Entry < String , ChangesFilterListsWrapper > changesEntry : changesMap . entrySet ( ) ) { ChangesKey changesKey = new ChangesKey ( changesEntry . getKey ( ) , IdGenerator . generate ( ) ) ; ctx . getCache ( ) . putAsync ( changesKey , changesEntry . getValue ( ) ) ; } for ( ChangesKey key : processedItemKeys ) { ctx . getCache ( ) . removeAsync ( key ) ; } if ( debugEnabled ) { LOG . debug ( "in-memory state passed to cache cacheStore successfully" ) ; } } | Flushes all cache content to underlying CacheStore |
15,937 | public static String getStatusDescription ( int status ) { String description = "" ; Integer statusKey = new Integer ( status ) ; if ( statusDescriptions . containsKey ( statusKey ) ) { description = statusDescriptions . get ( statusKey ) ; } return String . format ( "%s %d %s" , WebDavConst . HTTPVER , status , description ) ; } | Returns status description by it s code . |
15,938 | private void spoolContent ( InputStream is ) throws IOException , FileNotFoundException { SwapFile swapFile = SwapFile . get ( spoolConfig . tempDirectory , System . currentTimeMillis ( ) + "_" + SEQUENCE . incrementAndGet ( ) , spoolConfig . fileCleaner ) ; try { OutputStream os = PrivilegedFileHelper . fileOutputStream ( swapFile ) ; try { byte [ ] bytes = new byte [ 1024 ] ; int length ; while ( ( length = is . read ( bytes ) ) != - 1 ) { os . write ( bytes , 0 , length ) ; } } finally { os . close ( ) ; } } finally { swapFile . spoolDone ( ) ; is . close ( ) ; } tempFile = swapFile ; } | Spools the content extracted from the URL |
15,939 | public MatchResult match ( QPath input ) { try { return match ( new Context ( input ) ) . getMatchResult ( ) ; } catch ( RepositoryException e ) { throw ( IllegalArgumentException ) new IllegalArgumentException ( "QPath not normalized" ) . initCause ( e ) ; } } | Matches this pattern against the input . |
15,940 | private void addPathsWithUnknownChangedSize ( ChangesItem changesItem , ItemState state ) { if ( ! state . isPersisted ( ) && ( state . isDeleted ( ) || state . isRenamed ( ) ) ) { String itemPath = getPath ( state . getData ( ) . getQPath ( ) ) ; for ( String trackedPath : quotaPersister . getAllTrackedNodes ( rName , wsName ) ) { if ( itemPath . startsWith ( trackedPath ) ) { changesItem . addPathWithUnknownChangedSize ( itemPath ) ; } } } } | Checks if changes were made but changed size is unknown . If so determinate for which nodes data size should be recalculated at all and put those paths into respective collection . |
15,941 | private void behaveWhenQuotaExceeded ( String message ) throws ExceededQuotaLimitException { switch ( exceededQuotaBehavior ) { case EXCEPTION : throw new ExceededQuotaLimitException ( message ) ; case WARNING : LOG . warn ( message ) ; break ; } } | What to do if data size exceeded quota limit . Throwing exception or logging only . Depends on preconfigured parameter . |
15,942 | protected void pushChangesToCoordinator ( ChangesItem changesItem ) throws SecurityException , RPCException { if ( ! changesItem . isEmpty ( ) ) { rpcService . executeCommandOnCoordinator ( applyPersistedChangesTask , true , changesItem ) ; } } | Push changes to coordinator to apply . |
15,943 | private String getPath ( QPath path ) { try { return lFactory . createJCRPath ( path ) . getAsString ( false ) ; } catch ( RepositoryException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } } | Returns item absolute path . |
15,944 | private Serializable executeCommand ( RemoteCommand command , Serializable ... args ) throws RPCException { try { return command . execute ( args ) ; } catch ( Throwable e ) { throw new RPCException ( e . getMessage ( ) , e ) ; } } | Command executing . |
15,945 | public ItemState read ( ObjectReader in ) throws UnknownClassIdException , IOException { int key ; if ( ( key = in . readInt ( ) ) != SerializationConstants . ITEM_STATE ) { throw new UnknownClassIdException ( "There is unexpected class [" + key + "]" ) ; } ItemState is = null ; try { int state = in . readInt ( ) ; boolean isPersisted = in . readBoolean ( ) ; boolean eventFire = in . readBoolean ( ) ; QPath oldPath = null ; if ( in . readInt ( ) == SerializationConstants . NOT_NULL_DATA ) { byte [ ] buf = new byte [ in . readInt ( ) ] ; in . readFully ( buf ) ; oldPath = QPath . parse ( new String ( buf , Constants . DEFAULT_ENCODING ) ) ; } boolean isNodeData = in . readBoolean ( ) ; if ( isNodeData ) { PersistedNodeDataReader rdr = new PersistedNodeDataReader ( ) ; is = new ItemState ( rdr . read ( in ) , state , eventFire , null , false , isPersisted , oldPath ) ; } else { PersistedPropertyDataReader rdr = new PersistedPropertyDataReader ( holder , spoolConfig ) ; is = new ItemState ( rdr . read ( in ) , state , eventFire , null , false , isPersisted , oldPath ) ; } return is ; } catch ( EOFException e ) { throw new StreamCorruptedException ( "Unexpected EOF in middle of data block." ) ; } catch ( IllegalPathException e ) { throw new IOException ( "Data corrupted" , e ) ; } } | Read and set ItemState data . |
15,946 | public Response search ( Session session , HierarchicalProperty body , String baseURI ) { try { SearchRequestEntity requestEntity = new SearchRequestEntity ( body ) ; Query query = session . getWorkspace ( ) . getQueryManager ( ) . createQuery ( requestEntity . getQuery ( ) , requestEntity . getQueryLanguage ( ) ) ; QueryResult queryResult = query . execute ( ) ; WebDavNamespaceContext nsContext = new WebDavNamespaceContext ( session ) ; SearchResultResponseEntity searchResult = new SearchResultResponseEntity ( queryResult , nsContext , baseURI ) ; return Response . status ( HTTPStatus . MULTISTATUS ) . entity ( searchResult ) . build ( ) ; } catch ( PathNotFoundException exc ) { return Response . status ( HTTPStatus . NOT_FOUND ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( UnsupportedQueryException exc ) { return Response . status ( HTTPStatus . BAD_REQUEST ) . entity ( exc . getMessage ( ) ) . build ( ) ; } catch ( Exception exc ) { LOG . error ( exc . getMessage ( ) , exc ) ; return Response . serverError ( ) . entity ( exc . getMessage ( ) ) . build ( ) ; } } | Webdav search method implementation . |
15,947 | public int getDoc ( IndexReader reader ) throws IOException { if ( doc == - 1 ) { TermDocs docs = reader . termDocs ( new Term ( FieldNames . UUID , id . toString ( ) ) ) ; try { if ( docs . next ( ) ) { return docs . doc ( ) ; } else { throw new IOException ( "Node with id " + id + " not found in index" ) ; } } finally { docs . close ( ) ; } } else { return doc ; } } | Returns the document number for this score node . |
15,948 | private String [ ] safeListToArray ( List < String > v ) { return v != null ? v . toArray ( new String [ v . size ( ) ] ) : new String [ 0 ] ; } | Convert list to array . |
15,949 | public void removeWorkspaceIndex ( WorkspaceEntry wsConfig , boolean isSystem ) throws RepositoryConfigurationException , IOException { String indexDirName = wsConfig . getQueryHandler ( ) . getParameterValue ( QueryHandlerParams . PARAM_INDEX_DIR ) ; File indexDir = new File ( indexDirName ) ; if ( PrivilegedFileHelper . exists ( indexDir ) ) { removeFolder ( indexDir ) ; } if ( isSystem ) { File systemIndexDir = new File ( indexDirName + "_" + SystemSearchManager . INDEX_DIR_SUFFIX ) ; if ( PrivilegedFileHelper . exists ( systemIndexDir ) ) { removeFolder ( systemIndexDir ) ; } } } | Remove all file of workspace index . |
15,950 | public PlainChangesLog pushLog ( QPath rootPath ) { PlainChangesLog cLog = new PlainChangesLogImpl ( getDescendantsChanges ( rootPath ) , session ) ; if ( rootPath . equals ( Constants . ROOT_PATH ) ) { clear ( ) ; } else { remove ( rootPath ) ; } return cLog ; } | Creates new changes log with rootPath and its descendants of this one and removes those entries . |
15,951 | protected void doRestore ( ) throws Throwable { PlainChangesLog changes = read ( ) ; TransactionChangesLog tLog = new TransactionChangesLog ( changes ) ; tLog . setSystemId ( Constants . JCR_CORE_RESTORE_WORKSPACE_INITIALIZER_SYSTEM_ID ) ; dataManager . save ( tLog ) ; } | Perform restore operation . |
15,952 | private String removeAsterisk ( String str ) { if ( str . startsWith ( "*" ) ) { str = str . substring ( 1 ) ; } if ( str . endsWith ( "*" ) ) { str = str . substring ( 0 , str . length ( ) - 1 ) ; } return str ; } | Removes asterisk from beginning and from end of statement . |
15,953 | public Set < VersionResource > getVersions ( ) throws RepositoryException , IllegalResourceTypeException { Set < VersionResource > resources = new HashSet < VersionResource > ( ) ; VersionIterator versions = versionHistory . getAllVersions ( ) ; while ( versions . hasNext ( ) ) { Version version = versions . nextVersion ( ) ; if ( "jcr:rootVersion" . equals ( version . getName ( ) ) ) { continue ; } resources . add ( new VersionResource ( versionURI ( version . getName ( ) ) , versionedResource , version , namespaceContext ) ) ; } return resources ; } | Returns all versions of a resource . |
15,954 | public VersionResource getVersion ( String name ) throws RepositoryException , IllegalResourceTypeException { return new VersionResource ( versionURI ( name ) , versionedResource , versionHistory . getVersion ( name ) , namespaceContext ) ; } | Returns the version of resouce by name . |
15,955 | protected final URI versionURI ( String versionName ) { return URI . create ( versionedResource . getIdentifier ( ) . toASCIIString ( ) + "?version=" + versionName ) ; } | Returns URI of the resource version . |
15,956 | protected String buildPathX8 ( String fileName ) { final int xLength = 8 ; char [ ] chs = fileName . toCharArray ( ) ; StringBuilder path = new StringBuilder ( ) ; for ( int i = 0 ; i < xLength ; i ++ ) { path . append ( File . separator ) . append ( chs [ i ] ) ; } path . append ( fileName . substring ( xLength ) ) ; return path . toString ( ) ; } | best for now 12 . 07 . 07 |
15,957 | private void load ( ) throws IOException { if ( PrivilegedFileHelper . exists ( storage ) ) { InputStream in = PrivilegedFileHelper . fileInputStream ( storage ) ; try { Properties props = new Properties ( ) ; log . debug ( "loading namespace mappings..." ) ; props . load ( in ) ; Iterator < Object > iter = props . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String prefix = ( String ) iter . next ( ) ; String uri = props . getProperty ( prefix ) ; log . debug ( prefix + " -> " + uri ) ; prefixToURI . put ( prefix , uri ) ; uriToPrefix . put ( uri , prefix ) ; } prefixCount = props . size ( ) ; log . debug ( "namespace mappings loaded." ) ; } finally { in . close ( ) ; } } } | Loads currently known mappings from a . properties file . |
15,958 | private void store ( ) throws IOException { Properties props = new Properties ( ) ; Iterator < String > iter = prefixToURI . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String prefix = iter . next ( ) ; String uri = prefixToURI . get ( prefix ) ; props . setProperty ( prefix , uri ) ; } OutputStream out = PrivilegedFileHelper . fileOutputStream ( storage ) ; try { out = new BufferedOutputStream ( out ) ; props . store ( out , null ) ; } finally { out . close ( ) ; } } | Writes the currently known mappings into a . properties file . |
15,959 | public static RegistryEntry parse ( final byte [ ] bytes ) throws IOException , SAXException , ParserConfigurationException { try { return SecurityHelper . doPrivilegedExceptionAction ( new PrivilegedExceptionAction < RegistryEntry > ( ) { public RegistryEntry run ( ) throws Exception { return new RegistryEntry ( DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( new ByteArrayInputStream ( bytes ) ) ) ; } } ) ; } catch ( PrivilegedActionException pae ) { Throwable cause = pae . getCause ( ) ; if ( cause instanceof ParserConfigurationException ) { throw ( ParserConfigurationException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else if ( cause instanceof SAXException ) { throw ( SAXException ) cause ; } else if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else { throw new RuntimeException ( cause ) ; } } } | Factory method to create RegistryEntry from serialized XML |
15,960 | public void addClassTag ( String tag , Class type ) { tagToClass . put ( tag , type ) ; classToTag . put ( type , tag ) ; } | Sets a tag to use instead of the fully qualifier class name . This can make the JSON easier to read . |
15,961 | public < T > void setSerializer ( Class < T > type , JsonSerializer < T > serializer ) { classToSerializer . put ( type , serializer ) ; } | Registers a serializer to use for the specified type instead of the default behavior of serializing all of an objects fields . |
15,962 | public void setElementType ( Class type , String fieldName , Class elementType ) { ObjectMap < String , FieldMetadata > fields = getFields ( type ) ; FieldMetadata metadata = fields . get ( fieldName ) ; if ( metadata == null ) throw new JsonException ( "Field not found: " + fieldName + " (" + type . getName ( ) + ")" ) ; metadata . elementType = elementType ; } | Sets the type of elements in a collection . When the element type is known the class for each element in the collection does not need to be written unless different from the element type . |
15,963 | public void setWriter ( Writer writer ) { if ( ! ( writer instanceof JsonWriter ) ) writer = new JsonWriter ( writer ) ; this . writer = ( JsonWriter ) writer ; this . writer . setOutputType ( outputType ) ; this . writer . setQuoteLongValues ( quoteLongValues ) ; } | Sets the writer where JSON output will be written . This is only necessary when not using the toJson methods . |
15,964 | public void writeFields ( Object object ) { Class type = object . getClass ( ) ; Object [ ] defaultValues = getDefaultValues ( type ) ; OrderedMap < String , FieldMetadata > fields = getFields ( type ) ; int i = 0 ; for ( FieldMetadata metadata : new OrderedMapValues < FieldMetadata > ( fields ) ) { Field field = metadata . field ; try { Object value = field . get ( object ) ; if ( defaultValues != null ) { Object defaultValue = defaultValues [ i ++ ] ; if ( value == null && defaultValue == null ) continue ; if ( value != null && defaultValue != null ) { if ( value . equals ( defaultValue ) ) continue ; if ( value . getClass ( ) . isArray ( ) && defaultValue . getClass ( ) . isArray ( ) ) { equals1 [ 0 ] = value ; equals2 [ 0 ] = defaultValue ; if ( Arrays . deepEquals ( equals1 , equals2 ) ) continue ; } } } if ( debug ) System . out . println ( "Writing field: " + field . getName ( ) + " (" + type . getName ( ) + ")" ) ; writer . name ( field . getName ( ) ) ; writeValue ( value , field . getType ( ) , metadata . elementType ) ; } catch ( IllegalAccessException ex ) { throw new JsonException ( "Error accessing field: " + field . getName ( ) + " (" + type . getName ( ) + ")" , ex ) ; } catch ( JsonException ex ) { ex . addTrace ( field + " (" + type . getName ( ) + ")" ) ; throw ex ; } catch ( Exception runtimeEx ) { JsonException ex = new JsonException ( runtimeEx ) ; ex . addTrace ( field + " (" + type . getName ( ) + ")" ) ; throw ex ; } } } | Writes all fields of the specified object to the current JSON object . |
15,965 | public void writeField ( Object object , String fieldName , String jsonName , Class elementType ) { Class type = object . getClass ( ) ; ObjectMap < String , FieldMetadata > fields = getFields ( type ) ; FieldMetadata metadata = fields . get ( fieldName ) ; if ( metadata == null ) throw new JsonException ( "Field not found: " + fieldName + " (" + type . getName ( ) + ")" ) ; Field field = metadata . field ; if ( elementType == null ) elementType = metadata . elementType ; try { if ( debug ) System . out . println ( "Writing field: " + field . getName ( ) + " (" + type . getName ( ) + ")" ) ; writer . name ( jsonName ) ; writeValue ( field . get ( object ) , field . getType ( ) , elementType ) ; } catch ( IllegalAccessException ex ) { throw new JsonException ( "Error accessing field: " + field . getName ( ) + " (" + type . getName ( ) + ")" , ex ) ; } catch ( JsonException ex ) { ex . addTrace ( field + " (" + type . getName ( ) + ")" ) ; throw ex ; } catch ( Exception runtimeEx ) { JsonException ex = new JsonException ( runtimeEx ) ; ex . addTrace ( field + " (" + type . getName ( ) + ")" ) ; throw ex ; } } | Writes the specified field to the current JSON object . |
15,966 | public void writeValue ( String name , Object value ) { try { writer . name ( name ) ; } catch ( IOException ex ) { throw new JsonException ( ex ) ; } if ( value == null ) writeValue ( value , null , null ) ; else writeValue ( value , value . getClass ( ) , null ) ; } | Writes the value as a field on the current JSON object without writing the actual class . |
15,967 | public void writeValue ( String name , Object value , Class knownType ) { try { writer . name ( name ) ; } catch ( IOException ex ) { throw new JsonException ( ex ) ; } writeValue ( value , knownType , null ) ; } | Writes the value as a field on the current JSON object writing the class of the object if it differs from the specified known type . |
15,968 | public void writeValue ( Object value ) { if ( value == null ) writeValue ( value , null , null ) ; else writeValue ( value , value . getClass ( ) , null ) ; } | Writes the value without writing the class of the object . |
15,969 | boolean detectLongRunningJob ( long currentTime , Job job ) { if ( job . status ( ) == JobStatus . RUNNING && ! longRunningJobs . containsKey ( job ) ) { int jobExecutionsCount = job . executionsCount ( ) ; Long jobStartedtimeInMillis = job . lastExecutionStartedTimeInMillis ( ) ; Thread threadRunningJob = job . threadRunningJob ( ) ; if ( jobStartedtimeInMillis != null && threadRunningJob != null && currentTime - jobStartedtimeInMillis > detectionThresholdInMillis ) { logger . warn ( "Job '{}' is still running after {}ms (detection threshold = {}ms), stack trace = {}" , job . name ( ) , currentTime - jobStartedtimeInMillis , detectionThresholdInMillis , Stream . of ( threadRunningJob . getStackTrace ( ) ) . map ( StackTraceElement :: toString ) . collect ( Collectors . joining ( "\n " ) ) ) ; longRunningJobs . put ( job , new LongRunningJobInfo ( jobStartedtimeInMillis , jobExecutionsCount ) ) ; return true ; } } return false ; } | Check whether a job is running for too long or not . |
15,970 | public Job schedule ( Runnable runnable , Schedule when ) { return schedule ( null , runnable , when ) ; } | Schedule the executions of a process . |
15,971 | public Optional < Job > findJob ( String name ) { return Optional . ofNullable ( indexedJobsByName . get ( name ) ) ; } | Find a job by its name |
15,972 | public void gracefullyShutdown ( Duration timeout ) { logger . info ( "Shutting down..." ) ; if ( ! shuttingDown ) { synchronized ( this ) { shuttingDown = true ; threadPoolExecutor . shutdown ( ) ; } for ( Job job : jobStatus ( ) ) { Runnable runningJob = job . runningJob ( ) ; if ( runningJob != null ) { threadPoolExecutor . remove ( runningJob ) ; } job . status ( JobStatus . DONE ) ; } synchronized ( launcherNotifier ) { launcherNotifier . set ( false ) ; launcherNotifier . notify ( ) ; } } threadPoolExecutor . awaitTermination ( timeout . toMillis ( ) , TimeUnit . MILLISECONDS ) ; } | Wait until the current running jobs are executed and cancel jobs that are planned to be executed . |
15,973 | private void launcher ( ) { while ( ! shuttingDown ) { Long timeBeforeNextExecution = null ; synchronized ( this ) { if ( nextExecutionsOrder . size ( ) > 0 ) { timeBeforeNextExecution = nextExecutionsOrder . get ( 0 ) . nextExecutionTimeInMillis ( ) - timeProvider . currentTime ( ) ; } } if ( timeBeforeNextExecution == null || timeBeforeNextExecution > 0L ) { synchronized ( launcherNotifier ) { if ( shuttingDown ) { return ; } if ( launcherNotifier . get ( ) ) { if ( timeBeforeNextExecution == null ) { launcherNotifier . wait ( ) ; } else { launcherNotifier . wait ( timeBeforeNextExecution ) ; } } launcherNotifier . set ( true ) ; } } else { synchronized ( this ) { if ( shuttingDown ) { return ; } if ( nextExecutionsOrder . size ( ) > 0 ) { Job jobToRun = nextExecutionsOrder . remove ( 0 ) ; jobToRun . status ( JobStatus . READY ) ; jobToRun . runningJob ( ( ) -> runJob ( jobToRun ) ) ; if ( threadPoolExecutor . getActiveCount ( ) == threadPoolExecutor . getMaximumPoolSize ( ) ) { logger . warn ( "Job thread pool is full, either tasks take too much time to execute" + " or either the thread pool is too small" ) ; } threadPoolExecutor . execute ( jobToRun . runningJob ( ) ) ; } } } } } | The daemon that will be in charge of placing the jobs in the thread pool when they are ready to be executed . |
15,974 | private void runJob ( Job jobToRun ) { long startExecutionTime = timeProvider . currentTime ( ) ; long timeBeforeNextExecution = jobToRun . nextExecutionTimeInMillis ( ) - startExecutionTime ; if ( timeBeforeNextExecution < 0 ) { logger . debug ( "Job '{}' execution is {}ms late" , jobToRun . name ( ) , - timeBeforeNextExecution ) ; } jobToRun . status ( JobStatus . RUNNING ) ; jobToRun . lastExecutionStartedTimeInMillis ( startExecutionTime ) ; jobToRun . threadRunningJob ( Thread . currentThread ( ) ) ; try { jobToRun . runnable ( ) . run ( ) ; } catch ( Throwable t ) { logger . error ( "Error during job '{}' execution" , jobToRun . name ( ) , t ) ; } jobToRun . executionsCount ( jobToRun . executionsCount ( ) + 1 ) ; jobToRun . lastExecutionEndedTimeInMillis ( timeProvider . currentTime ( ) ) ; jobToRun . threadRunningJob ( null ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Job '{}' executed in {}ms" , jobToRun . name ( ) , timeProvider . currentTime ( ) - startExecutionTime ) ; } if ( shuttingDown ) { return ; } synchronized ( this ) { scheduleNextExecution ( jobToRun ) ; } } | The wrapper around a job that will be executed in the thread pool . It is especially in charge of logging changing the job status and checking for the next job to be executed . |
15,975 | private HttpURLConnection configureURLConnection ( HttpMethod method , String urlString , Map < String , String > httpHeaders , int contentLength ) throws IOException { preconditionNotNull ( method , "method cannot be null" ) ; preconditionNotNull ( urlString , "urlString cannot be null" ) ; preconditionNotNull ( httpHeaders , "httpHeaders cannot be null" ) ; HttpURLConnection connection = getHttpURLConnection ( urlString ) ; connection . setRequestMethod ( method . name ( ) ) ; Map < String , String > headerKeyValues = new HashMap < > ( defaultHttpHeaders ) ; headerKeyValues . putAll ( httpHeaders ) ; for ( Map . Entry < String , String > entry : headerKeyValues . entrySet ( ) ) { connection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; log . trace ( "Header request property: key='{}', value='{}'" , entry . getKey ( ) , entry . getValue ( ) ) ; } if ( contentLength > 0 ) { connection . setDoOutput ( true ) ; connection . setDoInput ( true ) ; } connection . setRequestProperty ( "Content-Length" , Integer . toString ( contentLength ) ) ; return connection ; } | Provides an internal convenience method to allow easy overriding by test classes |
15,976 | String getResponseEncoding ( URLConnection connection ) { String charset = null ; String contentType = connection . getHeaderField ( "Content-Type" ) ; if ( contentType != null ) { for ( String param : contentType . replace ( " " , "" ) . split ( ";" ) ) { if ( param . startsWith ( "charset=" ) ) { charset = param . split ( "=" , 2 ) [ 1 ] ; break ; } } } return charset ; } | Determine the response encoding if specified |
15,977 | public static PDFont mapDefaultFonts ( Font font ) { if ( fontNameEqualsAnyOf ( font , Font . SANS_SERIF , Font . DIALOG , Font . DIALOG_INPUT , "Arial" , "Helvetica" ) ) return chooseMatchingHelvetica ( font ) ; if ( fontNameEqualsAnyOf ( font , Font . MONOSPACED , "courier" , "courier new" ) ) return chooseMatchingCourier ( font ) ; if ( fontNameEqualsAnyOf ( font , Font . SERIF , "Times" , "Times New Roman" , "Times Roman" ) ) return chooseMatchingTimes ( font ) ; if ( fontNameEqualsAnyOf ( font , "Symbol" ) ) return PDType1Font . SYMBOL ; if ( fontNameEqualsAnyOf ( font , "ZapfDingbats" , "Dingbats" ) ) return PDType1Font . ZAPF_DINGBATS ; return null ; } | Find a PDFont for the given font object which does not need to be embedded . |
15,978 | public static PDFont chooseMatchingTimes ( Font font ) { if ( ( font . getStyle ( ) & ( Font . ITALIC | Font . BOLD ) ) == ( Font . ITALIC | Font . BOLD ) ) return PDType1Font . TIMES_BOLD_ITALIC ; if ( ( font . getStyle ( ) & Font . ITALIC ) == Font . ITALIC ) return PDType1Font . TIMES_ITALIC ; if ( ( font . getStyle ( ) & Font . BOLD ) == Font . BOLD ) return PDType1Font . TIMES_BOLD ; return PDType1Font . TIMES_ROMAN ; } | Get a PDType1Font . TIMES - variant which matches the given font |
15,979 | public static PDFont chooseMatchingCourier ( Font font ) { if ( ( font . getStyle ( ) & ( Font . ITALIC | Font . BOLD ) ) == ( Font . ITALIC | Font . BOLD ) ) return PDType1Font . COURIER_BOLD_OBLIQUE ; if ( ( font . getStyle ( ) & Font . ITALIC ) == Font . ITALIC ) return PDType1Font . COURIER_OBLIQUE ; if ( ( font . getStyle ( ) & Font . BOLD ) == Font . BOLD ) return PDType1Font . COURIER_BOLD ; return PDType1Font . COURIER ; } | Get a PDType1Font . COURIER - variant which matches the given font |
15,980 | public static PDFont chooseMatchingHelvetica ( Font font ) { if ( ( font . getStyle ( ) & ( Font . ITALIC | Font . BOLD ) ) == ( Font . ITALIC | Font . BOLD ) ) return PDType1Font . HELVETICA_BOLD_OBLIQUE ; if ( ( font . getStyle ( ) & Font . ITALIC ) == Font . ITALIC ) return PDType1Font . HELVETICA_OBLIQUE ; if ( ( font . getStyle ( ) & Font . BOLD ) == Font . BOLD ) return PDType1Font . HELVETICA_BOLD ; return PDType1Font . HELVETICA ; } | Get a PDType1Font . HELVETICA - variant which matches the given font |
15,981 | @ SuppressWarnings ( "WeakerAccess" ) public void registerFont ( String fontName , File fontFile ) { if ( ! fontFile . exists ( ) ) throw new IllegalArgumentException ( "Font " + fontFile + " does not exist!" ) ; FontEntry entry = new FontEntry ( ) ; entry . overrideName = fontName ; entry . file = fontFile ; fontFiles . add ( entry ) ; } | Register a font . |
15,982 | @ SuppressWarnings ( "WeakerAccess" ) public void registerFont ( String name , PDFont font ) { fontMap . put ( name , font ) ; } | Register a font which is already associated with the PDDocument |
15,983 | @ SuppressWarnings ( "WeakerAccess" ) protected PDFont mapFont ( final Font font , final IFontTextDrawerEnv env ) throws IOException , FontFormatException { for ( final FontEntry fontEntry : fontFiles ) { if ( fontEntry . overrideName == null ) { Font javaFont = Font . createFont ( Font . TRUETYPE_FONT , fontEntry . file ) ; fontEntry . overrideName = javaFont . getFontName ( ) ; } if ( fontEntry . file . getName ( ) . toLowerCase ( Locale . US ) . endsWith ( ".ttc" ) ) { TrueTypeCollection collection = new TrueTypeCollection ( fontEntry . file ) ; collection . processAllFonts ( new TrueTypeCollection . TrueTypeFontProcessor ( ) { public void process ( TrueTypeFont ttf ) throws IOException { PDFont pdFont = PDType0Font . load ( env . getDocument ( ) , ttf , true ) ; fontMap . put ( fontEntry . overrideName , pdFont ) ; fontMap . put ( pdFont . getName ( ) , pdFont ) ; } } ) ; } else { PDFont pdFont = PDType0Font . load ( env . getDocument ( ) , fontEntry . file ) ; fontMap . put ( fontEntry . overrideName , pdFont ) ; } } fontFiles . clear ( ) ; return fontMap . get ( font . getFontName ( ) ) ; } | Try to map the java . awt . Font to a PDFont . |
15,984 | public float getPixelSize ( ) { if ( mVectorState == null && mVectorState . mVPathRenderer == null || mVectorState . mVPathRenderer . mBaseWidth == 0 || mVectorState . mVPathRenderer . mBaseHeight == 0 || mVectorState . mVPathRenderer . mViewportHeight == 0 || mVectorState . mVPathRenderer . mViewportWidth == 0 ) { return 1 ; } float intrinsicWidth = mVectorState . mVPathRenderer . mBaseWidth ; float intrinsicHeight = mVectorState . mVPathRenderer . mBaseHeight ; float viewportWidth = mVectorState . mVPathRenderer . mViewportWidth ; float viewportHeight = mVectorState . mVPathRenderer . mViewportHeight ; float scaleX = viewportWidth / intrinsicWidth ; float scaleY = viewportHeight / intrinsicHeight ; return Math . min ( scaleX , scaleY ) ; } | The size of a pixel when scaled from the intrinsic dimension to the viewport dimension . This is used to calculate the path animation accuracy . |
15,985 | @ RequestMapping ( path = "/api" , method = RequestMethod . GET , produces = { "application/hal+json" , "application/json" } ) public HalRepresentation getHomeDocument ( final HttpServletRequest request ) { final String homeUrl = request . getRequestURL ( ) . toString ( ) ; return new HalRepresentation ( linkingTo ( ) . self ( homeUrl ) . single ( linkBuilder ( "search" , "/api/products{?q,embedded}" ) . withTitle ( "Search Products" ) . withType ( "application/hal+json" ) . build ( ) ) . build ( ) ) ; } | Entry point for the products REST API . |
15,986 | public static Builder copyOf ( final Link prototype ) { return new Builder ( prototype . rel , prototype . href ) . withType ( prototype . type ) . withProfile ( prototype . profile ) . withTitle ( prototype . title ) . withName ( prototype . name ) . withDeprecation ( prototype . deprecation ) . withHrefLang ( prototype . hreflang ) ; } | Create a Builder instance and initialize it from a prototype Link . |
15,987 | public static Embedded embedded ( final String rel , final HalRepresentation embeddedItem ) { return new Embedded ( singletonMap ( rel , embeddedItem ) ) ; } | Create an Embedded instance with a single embedded HalRepresentations that will be rendered as a single item instead of an array of embedded items . |
15,988 | public static Embedded embedded ( final String rel , final List < ? extends HalRepresentation > embeddedRepresentations ) { return new Embedded ( singletonMap ( rel , new ArrayList < > ( embeddedRepresentations ) ) ) ; } | Create an Embedded instance with a list of nested HalRepresentations for a single link - relation type . |
15,989 | private int calcLastPage ( int total , int pageSize ) { if ( total == 0 ) { return firstPage ; } else { final int zeroBasedPageNo = total % pageSize > 0 ? total / pageSize : total / pageSize - 1 ; return firstPage + zeroBasedPageNo ; } } | Returns the number of the last page if the total number of items is known . |
15,990 | private String pageUri ( final UriTemplate uriTemplate , final int pageNumber , final int pageSize ) { if ( pageSize == MAX_VALUE ) { return uriTemplate . expand ( ) ; } return uriTemplate . set ( pageNumberVar ( ) , pageNumber ) . set ( pageSizeVar ( ) , pageSize ) . expand ( ) ; } | Return the HREF of the page specified by UriTemplate pageNumber and pageSize . |
15,991 | @ SuppressWarnings ( "rawtypes" ) public Stream < Link > stream ( ) { return links . values ( ) . stream ( ) . map ( obj -> { if ( obj instanceof List ) { return ( List ) obj ; } else { return singletonList ( obj ) ; } } ) . flatMap ( Collection :: stream ) ; } | Returns a Stream of links . |
15,992 | private int calcLastPageSkip ( int total , int skip , int limit ) { if ( skip > total - limit ) { return skip ; } if ( total % limit > 0 ) { return total - total % limit ; } return total - limit ; } | Calculate the number of items to skip for the last page . |
15,993 | private String pageUri ( final UriTemplate uriTemplate , final int skip , final int limit ) { if ( limit == MAX_VALUE ) { return uriTemplate . expand ( ) ; } return uriTemplate . set ( skipVar ( ) , skip ) . set ( limitVar ( ) , limit ) . expand ( ) ; } | Return the URI of the page with N skipped items and a page limitted to pages of size M . |
15,994 | public List < Product > searchFor ( final Optional < String > searchTerm ) { if ( searchTerm . isPresent ( ) ) { return products . stream ( ) . filter ( matchingProductsFor ( searchTerm . get ( ) ) ) . collect ( toList ( ) ) ; } else { return products ; } } | Searches for products using a case - insensitive search term . |
15,995 | HalRepresentation mergeWithEmbedding ( final Curies curies ) { this . curies = this . curies . mergeWith ( curies ) ; if ( this . links != null ) { removeDuplicateCuriesFromEmbedding ( curies ) ; this . links = this . links . using ( this . curies ) ; if ( embedded != null ) { embedded = embedded . using ( this . curies ) ; } } else { if ( embedded != null ) { embedded = embedded . using ( curies ) ; } } return this ; } | Merges the Curies of an embedded resource with the Curies of this resource and updates link - relation types in _links and _embedded items . |
15,996 | public < T extends HalRepresentation > T as ( final Class < T > type ) throws IOException { return objectMapper . readValue ( json , type ) ; } | Specify the type that is used to parse and map the json . |
15,997 | private Optional < JsonNode > findPossiblyCuriedEmbeddedNode ( final HalRepresentation halRepresentation , final JsonNode jsonNode , final String rel ) { final JsonNode embedded = jsonNode . get ( "_embedded" ) ; if ( embedded != null ) { final Curies curies = halRepresentation . getCuries ( ) ; final JsonNode curiedNode = embedded . get ( curies . resolve ( rel ) ) ; if ( curiedNode == null ) { return Optional . ofNullable ( embedded . get ( curies . expand ( rel ) ) ) ; } else { return Optional . of ( curiedNode ) ; } } else { return Optional . empty ( ) ; } } | Returns the JsonNode of the embedded items by link - relation type and resolves possibly curied rels . |
15,998 | public void register ( final Link curi ) { if ( ! curi . getRel ( ) . equals ( "curies" ) ) { throw new IllegalArgumentException ( "Link must be a CURI" ) ; } final boolean alreadyRegistered = curies . stream ( ) . anyMatch ( link -> link . getHref ( ) . equals ( curi . getHref ( ) ) ) ; if ( alreadyRegistered ) { curies . removeIf ( link -> link . getName ( ) . equals ( curi . getName ( ) ) ) ; curies . replaceAll ( link -> link . getName ( ) . equals ( curi . getName ( ) ) ? curi : link ) ; } curies . add ( curi ) ; } | Registers a CURI link in the Curies instance . |
15,999 | public Curies mergeWith ( final Curies other ) { final Curies merged = copyOf ( this ) ; other . curies . forEach ( merged :: register ) ; return merged ; } | Merges this Curies with another instance of Curies and returns the merged instance . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.