idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
1,200
public List < List < Segment > > getCompactableGroups ( Storage storage , SegmentManager manager ) { List < List < Segment > > compact = new ArrayList < > ( ) ; List < Segment > segments = null ; for ( Segment segment : getCompactableSegments ( manager ) ) { if ( segments == null ) { segments = new ArrayList < > ( ) ; segments . add ( segment ) ; } else if ( segments . stream ( ) . mapToLong ( Segment :: size ) . sum ( ) + segment . size ( ) <= storage . maxSegmentSize ( ) && segments . stream ( ) . mapToLong ( Segment :: count ) . sum ( ) + segment . count ( ) <= storage . maxEntriesPerSegment ( ) ) { segments . add ( segment ) ; } else { compact . add ( segments ) ; segments = new ArrayList < > ( ) ; segments . add ( segment ) ; } } if ( segments != null ) { compact . add ( segments ) ; } return compact ; }
Returns a list of segments lists to compact where segments are grouped according to how they will be merged during compaction .
1,201
private List < Segment > getCompactableSegments ( SegmentManager manager ) { List < Segment > segments = new ArrayList < > ( manager . segments ( ) . size ( ) ) ; Iterator < Segment > iterator = manager . segments ( ) . iterator ( ) ; Segment segment = iterator . next ( ) ; while ( iterator . hasNext ( ) ) { Segment nextSegment = iterator . next ( ) ; if ( segment . isCompacted ( ) || ( segment . isFull ( ) && segment . lastIndex ( ) < compactor . minorIndex ( ) && nextSegment . firstIndex ( ) <= manager . commitIndex ( ) && ! nextSegment . isEmpty ( ) ) ) { segments . add ( segment ) ; } else { break ; } segment = nextSegment ; } return segments ; }
Returns a list of compactable log segments .
1,202
public CompletableFuture < Void > close ( ) { for ( OperationAttempt attempt : new ArrayList < > ( attempts . values ( ) ) ) { attempt . fail ( new ClosedSessionException ( "session closed" ) ) ; } attempts . clear ( ) ; return CompletableFuture . completedFuture ( null ) ; }
Closes the submitter .
1,203
ServerMember update ( Status status , Instant time ) { if ( this . status != status ) { this . status = Assert . notNull ( status , "status" ) ; if ( time . isAfter ( updated ) ) { this . updated = Assert . notNull ( time , "time" ) ; } if ( statusChangeListeners != null ) { statusChangeListeners . accept ( status ) ; } } return this ; }
Updates the member status .
1,204
ServerMember update ( Address clientAddress , Instant time ) { if ( clientAddress != null ) { this . clientAddress = clientAddress ; if ( time . isAfter ( updated ) ) { this . updated = Assert . notNull ( time , "time" ) ; } } return this ; }
Updates the member client address .
1,205
private void delete ( Commit < DeleteCommand > commit ) { try { if ( value != null ) { value . close ( ) ; value = null ; } } finally { commit . close ( ) ; } }
Deletes the value .
1,206
void release ( ) { long references = -- this . references ; if ( ! state . active ( ) && references == 0 ) { context . sessions ( ) . unregisterSession ( id ) ; log . release ( id ) ; if ( closeIndex > 0 ) { log . release ( closeIndex ) ; } } }
Releases a reference to the session .
1,207
ServerSessionContext setKeepAliveIndex ( long keepAliveIndex ) { long previousKeepAliveIndex = this . keepAliveIndex ; this . keepAliveIndex = keepAliveIndex ; if ( previousKeepAliveIndex > 0 ) { log . release ( previousKeepAliveIndex ) ; } return this ; }
Sets the current session keep alive index .
1,208
boolean setRequestSequence ( long requestSequence ) { if ( requestSequence == this . requestSequence + 1 ) { this . requestSequence = requestSequence ; return true ; } else if ( requestSequence <= this . requestSequence ) { return true ; } return false ; }
Checks and sets the current request sequence number .
1,209
ServerSessionContext resendEvents ( long index ) { clearEvents ( index ) ; for ( EventHolder event : events ) { sendEvent ( event ) ; } return this ; }
Resends events from the given sequence .
1,210
private void sendEvent ( EventHolder event , Connection connection ) { PublishRequest request = PublishRequest . builder ( ) . withSession ( id ( ) ) . withEventIndex ( event . eventIndex ) . withPreviousIndex ( Math . max ( event . previousIndex , completeIndex ) ) . withEvents ( event . events ) . build ( ) ; LOGGER . trace ( "{} - Sending {}" , id , request ) ; connection . send ( request ) ; }
Sends an event .
1,211
private void cleanState ( long index ) { if ( keepAliveIndex > 0 ) { log . release ( keepAliveIndex ) ; } context . sessions ( ) . unregisterSession ( id ) ; if ( references == 0 ) { log . release ( id ) ; if ( index > 0 ) { log . release ( index ) ; } } else { this . closeIndex = index ; } }
Cleans session entries on close .
1,212
public synchronized MetaStore storeTerm ( long term ) { LOGGER . trace ( "Store term {}" , term ) ; metadataBuffer . writeLong ( 0 , term ) . flush ( ) ; return this ; }
Stores the current server term .
1,213
ServerSessionManager registerConnection ( String client , Connection connection ) { ServerSessionContext session = clients . get ( client ) ; if ( session != null ) { session . setConnection ( connection ) ; } connections . put ( client , connection ) ; return this ; }
Registers a connection .
1,214
ServerSessionManager unregisterConnection ( Connection connection ) { Iterator < Map . Entry < String , Connection > > iterator = connections . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Map . Entry < String , Connection > entry = iterator . next ( ) ; if ( entry . getValue ( ) . equals ( connection ) ) { ServerSessionContext session = clients . get ( entry . getKey ( ) ) ; if ( session != null ) { session . setConnection ( null ) ; } iterator . remove ( ) ; } } return this ; }
Unregisters a connection .
1,215
ServerSessionContext unregisterSession ( long sessionId ) { ServerSessionContext session = sessions . remove ( sessionId ) ; if ( session != null ) { clients . remove ( session . client ( ) , session ) ; connections . remove ( session . client ( ) , session . getConnection ( ) ) ; } return session ; }
Unregisters a session .
1,216
private void updateHeartbeatTime ( MemberState member , Throwable error ) { if ( heartbeatFuture == null ) { return ; } if ( error != null && member . getHeartbeatStartTime ( ) == heartbeatTime ) { int votingMemberSize = context . getClusterState ( ) . getActiveMemberStates ( ) . size ( ) + ( context . getCluster ( ) . member ( ) . type ( ) == Member . Type . ACTIVE ? 1 : 0 ) ; int quorumSize = ( int ) Math . floor ( votingMemberSize / 2 ) + 1 ; if ( member . getMember ( ) . type ( ) == Member . Type . ACTIVE && ++ heartbeatFailures > votingMemberSize - quorumSize ) { heartbeatFuture . completeExceptionally ( new InternalException ( "Failed to reach consensus" ) ) ; completeHeartbeat ( ) ; } } else { member . setHeartbeatTime ( System . currentTimeMillis ( ) ) ; if ( heartbeatTime <= heartbeatTime ( ) ) { heartbeatFuture . complete ( null ) ; completeHeartbeat ( ) ; } } }
Sets a commit time or fails the commit if a quorum of successful responses cannot be achieved .
1,217
private void updateGlobalIndex ( ) { context . checkThread ( ) ; long currentTime = System . currentTimeMillis ( ) ; long globalMatchIndex = context . getClusterState ( ) . getRemoteMemberStates ( ) . stream ( ) . filter ( m -> m . getMember ( ) . type ( ) != Member . Type . RESERVE && ( m . getMember ( ) . status ( ) == Member . Status . AVAILABLE || currentTime - m . getMember ( ) . updated ( ) . toEpochMilli ( ) < context . getGlobalSuspendTimeout ( ) . toMillis ( ) ) ) . mapToLong ( MemberState :: getMatchIndex ) . min ( ) . orElse ( context . getLog ( ) . lastIndex ( ) ) ; context . setGlobalIndex ( globalMatchIndex ) ; }
Updates the global index .
1,218
public synchronized void replaceSegments ( Collection < Segment > segments , Segment segment ) { segment . descriptor ( ) . update ( System . currentTimeMillis ( ) ) ; segment . descriptor ( ) . lock ( ) ; for ( Segment oldSegment : segments ) { if ( ! this . segments . containsKey ( oldSegment . index ( ) ) ) { throw new IllegalArgumentException ( "unknown segment at index: " + oldSegment . index ( ) ) ; } this . segments . remove ( oldSegment . index ( ) ) ; } this . segments . put ( segment . index ( ) , segment ) ; resetCurrentSegment ( ) ; }
Inserts a segment .
1,219
private OffsetIndex createIndex ( SegmentDescriptor descriptor ) { return new DelegatingOffsetIndex ( HeapBuffer . allocate ( Math . min ( DEFAULT_BUFFER_SIZE , descriptor . maxEntries ( ) ) , OffsetIndex . size ( descriptor . maxEntries ( ) ) ) ) ; }
Creates an in memory segment index .
1,220
private Segment currentSegment ( ) { Segment segment = segments . currentSegment ( ) ; if ( segment . isFull ( ) ) { segments . currentSegment ( ) . flush ( ) ; segment = segments . nextSegment ( ) ; } return segment ; }
Checks whether we need to roll over to a new segment .
1,221
public long append ( Entry entry ) { Assert . notNull ( entry , "entry" ) ; assertIsOpen ( ) ; long index = currentSegment ( ) . append ( entry ) ; entryBuffer . append ( entry ) ; return index ; }
Appends an entry to the log .
1,222
public boolean contains ( long index ) { if ( ! validIndex ( index ) ) return false ; Segment segment = segments . segment ( index ) ; return segment != null && segment . contains ( index ) ; }
Returns a boolean value indicating whether the log contains a live entry at the given index .
1,223
public Log release ( long index ) { assertIsOpen ( ) ; assertValidIndex ( index ) ; Segment segment = segments . segment ( index ) ; Assert . index ( segment != null , "invalid index: " + index ) ; segment . release ( index ) ; return this ; }
Releases the entry at the given index .
1,224
public Log commit ( long index ) { assertIsOpen ( ) ; if ( index > 0 ) { assertValidIndex ( index ) ; segments . commitIndex ( index ) ; if ( storage . flushOnCommit ( ) ) { segments . currentSegment ( ) . flush ( ) ; } } return this ; }
Commits entries up to the given index to the log .
1,225
public Log truncate ( long index ) { assertIsOpen ( ) ; if ( index > 0 ) assertValidIndex ( index ) ; Assert . index ( index >= segments . commitIndex ( ) , "cannot truncate committed entries" ) ; if ( lastIndex ( ) == index ) return this ; for ( Segment segment : segments . reverseSegments ( ) ) { if ( segment . validIndex ( index ) ) { segment . truncate ( index ) ; break ; } else if ( segment . index ( ) > index ) { segments . removeSegment ( segment ) ; } } entryBuffer . clear ( ) ; return this ; }
Truncates the log up to the given index .
1,226
public void close ( ) { assertIsOpen ( ) ; flush ( ) ; compactor . close ( ) ; segments . close ( ) ; open = false ; }
Closes the log .
1,227
public Collection < FixityResult > checkFixity ( final String algorithm ) { try ( FixityInputStream fixityInputStream = new FixityInputStream ( this . getInputStream ( ) , MessageDigest . getInstance ( algorithm ) ) ) { while ( fixityInputStream . read ( devNull ) != - 1 ) { } final URI calculatedChecksum = ContentDigest . asURI ( algorithm , fixityInputStream . getMessageDigest ( ) . digest ( ) ) ; final FixityResult result = new FixityResultImpl ( getExternalIdentifier ( ) , fixityInputStream . getByteCount ( ) , calculatedChecksum , algorithm ) ; return singletonList ( result ) ; } catch ( final IOException e ) { LOGGER . debug ( "Got error closing input stream: {}" , e ) ; throw new RepositoryRuntimeException ( e ) ; } catch ( final NoSuchAlgorithmException e1 ) { throw new RepositoryRuntimeException ( e1 ) ; } }
Calculate the fixity of a CacheEntry by piping it through a simple fixity - calculating InputStream
1,228
public Collection < URI > checkFixity ( final Collection < String > algorithms ) throws UnsupportedAlgorithmException { try ( InputStream binaryStream = this . getInputStream ( ) ) { final Map < String , DigestInputStream > digestInputStreams = new HashMap < > ( ) ; InputStream digestStream = binaryStream ; for ( String digestAlg : algorithms ) { try { digestStream = new DigestInputStream ( digestStream , MessageDigest . getInstance ( digestAlg ) ) ; digestInputStreams . put ( digestAlg , ( DigestInputStream ) digestStream ) ; } catch ( NoSuchAlgorithmException e ) { throw new UnsupportedAlgorithmException ( "Unsupported digest algorithm: " + digestAlg ) ; } } while ( digestStream . read ( devNull ) != - 1 ) { } return digestInputStreams . entrySet ( ) . stream ( ) . map ( entry -> ContentDigest . asURI ( entry . getKey ( ) , entry . getValue ( ) . getMessageDigest ( ) . digest ( ) ) ) . collect ( Collectors . toSet ( ) ) ; } catch ( final IOException e ) { LOGGER . debug ( "Got error closing input stream: {}" , e ) ; throw new RepositoryRuntimeException ( e ) ; } }
Calculate fixity with list of digest algorithms of a CacheEntry by piping it through a simple fixity - calculating InputStream
1,229
public void addedStatement ( final Statement input ) { if ( Operation . ADD == statements . get ( input ) ) { return ; } try { final Resource subject = input . getSubject ( ) ; validateSubject ( subject ) ; LOGGER . debug ( ">> adding statement {}" , input ) ; final Statement s = jcrRdfTools . skolemize ( idTranslator , input , topic . toString ( ) ) ; final FedoraResource resource = idTranslator . convert ( s . getSubject ( ) ) ; final FedoraResource description = resource . getDescription ( ) ; final Property property = s . getPredicate ( ) ; final RDFNode objectNode = s . getObject ( ) ; if ( property . equals ( RDF . type ) && objectNode . isResource ( ) ) { final Resource mixinResource = objectNode . asResource ( ) ; jcrRdfTools . addMixin ( description , mixinResource , input . getModel ( ) . getNsPrefixMap ( ) ) ; statements . put ( input , Operation . ADD ) ; return ; } jcrRdfTools . addProperty ( description , property , objectNode , input . getModel ( ) . getNsPrefixMap ( ) ) ; statements . put ( input , Operation . ADD ) ; } catch ( final ConstraintViolationException e ) { throw e ; } catch ( final javax . jcr . AccessDeniedException e ) { throw new AccessDeniedException ( e ) ; } catch ( final RepositoryException | RepositoryRuntimeException e ) { exceptions . add ( e ) ; } }
When a statement is added to the graph serialize it to a JCR property
1,230
public void removedStatement ( final Statement s ) { if ( Operation . REMOVE == statements . get ( s ) ) { return ; } try { final Resource subject = s . getSubject ( ) ; validateSubject ( subject ) ; LOGGER . trace ( ">> removing statement {}" , s ) ; final FedoraResource resource = idTranslator . convert ( subject ) ; final FedoraResource description = resource . getDescription ( ) ; final Property property = s . getPredicate ( ) ; final RDFNode objectNode = s . getObject ( ) ; if ( property . equals ( RDF . type ) && objectNode . isResource ( ) ) { final Resource mixinResource = objectNode . asResource ( ) ; jcrRdfTools . removeMixin ( description , mixinResource , s . getModel ( ) . getNsPrefixMap ( ) ) ; statements . put ( s , Operation . REMOVE ) ; return ; } jcrRdfTools . removeProperty ( description , property , objectNode , s . getModel ( ) . getNsPrefixMap ( ) ) ; statements . put ( s , Operation . REMOVE ) ; } catch ( final ConstraintViolationException e ) { throw e ; } catch ( final RepositoryException | RepositoryRuntimeException e ) { exceptions . add ( e ) ; } }
When a statement is removed remove it from the JCR properties
1,231
private void validateSubject ( final Resource subject ) { final String subjectURI = subject . getURI ( ) ; if ( ! subject . isAnon ( ) ) { final int hashIndex = subjectURI . lastIndexOf ( "#" ) ; if ( ! ( hashIndex > 0 && topic . getURI ( ) . equals ( subjectURI . substring ( 0 , hashIndex ) ) ) ) { if ( ! topic . equals ( subject . asNode ( ) ) ) { if ( idTranslator . inDomain ( subject ) ) { LOGGER . error ( "{} is not in the topic of this RDF, which is {}." , subject , topic ) ; throw new IncorrectTripleSubjectException ( subject + " is not in the topic of this RDF, which is " + topic ) ; } LOGGER . error ( "subject ({}) is not in repository domain." , subject ) ; throw new OutOfDomainSubjectException ( subject . asNode ( ) ) ; } } } }
If it s not the right kind of node throw an appropriate unchecked exception .
1,232
public void assertNoExceptions ( ) { if ( ! exceptions . isEmpty ( ) ) { throw new MalformedRdfException ( exceptions . stream ( ) . map ( Exception :: getMessage ) . collect ( joining ( "\n" ) ) ) ; } }
Assert that no exceptions were thrown while this listener was processing change
1,233
public void delete ( ) { final FedoraResource description = getDescription ( ) ; if ( description != null ) { description . delete ( ) ; } super . delete ( ) ; }
When deleting the binary we also need to clean up the description document .
1,234
protected boolean hasDescriptionProperty ( final String relPath ) { try { final Node descNode = getDescriptionNodeOrNull ( ) ; if ( descNode == null ) { return false ; } return descNode . hasProperty ( relPath ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
Check of the property exists on the description of this binary .
1,235
private Property getDescriptionProperty ( final String relPath ) { try { return getDescriptionNode ( ) . getProperty ( relPath ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
Return the description property for this binary .
1,236
protected void setContentSize ( final long size ) { try { getDescriptionNode ( ) . setProperty ( CONTENT_SIZE , size ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
Set the content size
1,237
public static URI getUserURI ( final String sessionUserId ) { final String userId = ( sessionUserId == null ? "anonymous" : sessionUserId ) . replaceAll ( "^<|>$" , "" ) ; try { final URI uri = URI . create ( userId ) ; if ( uri . isAbsolute ( ) || uri . isOpaque ( ) ) { return uri ; } else { return buildDefaultURI ( userId ) ; } } catch ( final IllegalArgumentException e ) { return buildDefaultURI ( userId ) ; } }
Returns the user agent based on the session user id .
1,238
private static URI buildDefaultURI ( final String userId ) { String userAgentBaseUri = System . getProperty ( USER_AGENT_BASE_URI_PROPERTY ) ; if ( isNullOrEmpty ( userAgentBaseUri ) ) { userAgentBaseUri = DEFAULT_USER_AGENT_BASE_URI ; } final String userAgentUri = userAgentBaseUri + userId ; LOGGER . trace ( "Default URI is created for user {}: {}" , userId , userAgentUri ) ; return URI . create ( userAgentUri ) ; }
Build default URI with the configured base uri for agent
1,239
public static String getJcrNamespaceForRDFNamespace ( final String rdfNamespaceUri ) { if ( rdfNamespacesToJcrNamespaces . containsKey ( rdfNamespaceUri ) ) { return rdfNamespacesToJcrNamespaces . get ( rdfNamespaceUri ) ; } return rdfNamespaceUri ; }
Convert a Fedora RDF Namespace into its JCR equivalent
1,240
public static String getRDFNamespaceForJcrNamespace ( final String jcrNamespaceUri ) { if ( jcrNamespacesToRDFNamespaces . containsKey ( jcrNamespaceUri ) ) { return jcrNamespacesToRDFNamespaces . get ( jcrNamespaceUri ) ; } return jcrNamespaceUri ; }
Convert a JCR namespace into an RDF namespace fit for downstream consumption .
1,241
public Value createValue ( final Node node , final RDFNode data , final String propertyName ) throws RepositoryException { final ValueFactory valueFactory = node . getSession ( ) . getValueFactory ( ) ; return createValue ( valueFactory , data , getPropertyType ( node , propertyName ) . orElse ( UNDEFINED ) ) ; }
Create a JCR value from an RDFNode for a given JCR property
1,242
public Value createValue ( final ValueFactory valueFactory , final RDFNode data , final int type ) throws RepositoryException { assert ( valueFactory != null ) ; if ( type == UNDEFINED || type == STRING ) { return valueConverter . reverse ( ) . convert ( data ) ; } else if ( type == REFERENCE || type == WEAKREFERENCE ) { if ( ! data . isURIResource ( ) ) { throw new ValueFormatException ( "Reference properties can only refer to URIs, not literals" ) ; } try { final Node nodeFromGraphSubject = getJcrNode ( idTranslator . convert ( data . asResource ( ) ) ) ; return valueFactory . createValue ( nodeFromGraphSubject , type == WEAKREFERENCE ) ; } catch ( final RepositoryRuntimeException e ) { throw new MalformedRdfException ( "Unable to find referenced node" , e ) ; } } else if ( data . isResource ( ) ) { LOGGER . debug ( "Using default JCR value creation for RDF resource: {}" , data ) ; return valueFactory . createValue ( data . asResource ( ) . getURI ( ) , type ) ; } else { LOGGER . debug ( "Using default JCR value creation for RDF literal: {}" , data ) ; String theValue = data . asLiteral ( ) . getString ( ) ; if ( type == DATE ) { theValue = Instant . parse ( data . asLiteral ( ) . getString ( ) ) . toString ( ) ; } return valueFactory . createValue ( theValue , type ) ; } }
Create a JCR value from an RDF node with the given JCR type
1,243
public void addMixin ( final FedoraResource resource , final Resource mixinResource , final Map < String , String > namespaces ) throws RepositoryException { final Node node = getJcrNode ( resource ) ; final Session session = node . getSession ( ) ; final String mixinName = getPropertyNameFromPredicate ( node , mixinResource , namespaces ) ; if ( ! repositoryHasType ( session , mixinName ) ) { final NodeTypeManager mgr = session . getWorkspace ( ) . getNodeTypeManager ( ) ; final NodeTypeTemplate type = mgr . createNodeTypeTemplate ( ) ; type . setName ( mixinName ) ; type . setMixin ( true ) ; type . setQueryable ( true ) ; mgr . registerNodeType ( type , false ) ; } if ( node . isNodeType ( mixinName ) ) { LOGGER . trace ( "Subject {} is already a {}; skipping" , node , mixinName ) ; return ; } if ( node . canAddMixin ( mixinName ) ) { LOGGER . debug ( "Adding mixin: {} to node: {}." , mixinName , node . getPath ( ) ) ; node . addMixin ( mixinName ) ; } else { throw new MalformedRdfException ( "Could not persist triple containing type assertion: " + mixinResource . toString ( ) + " because no such mixin/type can be added to this node: " + node . getPath ( ) + "!" ) ; } }
Add a mixin to a node
1,244
public void removeMixin ( final FedoraResource resource , final Resource mixinResource , final Map < String , String > nsPrefixMap ) throws RepositoryException { final Node node = getJcrNode ( resource ) ; final String mixinName = getPropertyNameFromPredicate ( node , mixinResource , nsPrefixMap ) ; if ( repositoryHasType ( session , mixinName ) && node . isNodeType ( mixinName ) ) { node . removeMixin ( mixinName ) ; } }
Remove a mixin from a node
1,245
public void removeProperty ( final FedoraResource resource , final org . apache . jena . rdf . model . Property predicate , final RDFNode objectNode , final Map < String , String > nsPrefixMap ) throws RepositoryException { final Node node = getJcrNode ( resource ) ; final String propertyName = getPropertyNameFromPredicate ( node , predicate , nsPrefixMap ) ; if ( isManagedPredicate . test ( predicate ) || jcrProperties . contains ( predicate ) ) { throw new ServerManagedPropertyException ( "Could not remove triple containing predicate " + predicate . toString ( ) + " to node " + node . getPath ( ) ) ; } if ( objectNode . isURIResource ( ) && idTranslator . inDomain ( objectNode . asResource ( ) ) && ! isReferenceProperty ( node , propertyName ) ) { nodePropertiesTools . removeReferencePlaceholders ( idTranslator , node , propertyName , objectNode . asResource ( ) ) ; } else { final Value v = createValue ( node , objectNode , propertyName ) ; nodePropertiesTools . removeNodeProperty ( node , propertyName , v ) ; } }
Remove a property from a node
1,246
public Statement skolemize ( final IdentifierConverter < Resource , FedoraResource > idTranslator , final Statement t , final String topic ) throws RepositoryException { Statement skolemized = t ; if ( t . getSubject ( ) . isAnon ( ) ) { skolemized = m . createStatement ( getSkolemizedResource ( idTranslator , skolemized . getSubject ( ) , topic ) , skolemized . getPredicate ( ) , skolemized . getObject ( ) ) ; } else if ( idTranslator . inDomain ( t . getSubject ( ) ) && t . getSubject ( ) . getURI ( ) . contains ( "#" ) ) { findOrCreateHashUri ( idTranslator , t . getSubject ( ) ) ; } if ( t . getObject ( ) . isAnon ( ) ) { skolemized = m . createStatement ( skolemized . getSubject ( ) , skolemized . getPredicate ( ) , getSkolemizedResource ( idTranslator , skolemized . getObject ( ) , topic ) ) ; } else if ( t . getObject ( ) . isResource ( ) && idTranslator . inDomain ( t . getObject ( ) . asResource ( ) ) && t . getObject ( ) . asResource ( ) . getURI ( ) . contains ( "#" ) ) { findOrCreateHashUri ( idTranslator , t . getObject ( ) . asResource ( ) ) ; } return skolemized ; }
Convert an external statement into a persistable statement by skolemizing blank nodes creating hash - uri subjects etc
1,247
public static JsonLDEventMessage from ( final FedoraEvent evt ) { final String baseUrl = evt . getInfo ( ) . get ( BASE_URL ) ; final String objectId = convertToExternalPath ( baseUrl + evt . getPath ( ) ) ; final List < String > types = evt . getTypes ( ) . stream ( ) . map ( rdfType -> rdfType . getTypeAbbreviated ( ) ) . collect ( toList ( ) ) ; final String name = String . join ( ", " , evt . getTypes ( ) . stream ( ) . map ( rdfType -> rdfType . getName ( ) ) . collect ( toList ( ) ) ) ; final List < String > resourceTypes = new ArrayList < > ( evt . getResourceTypes ( ) ) ; if ( ! resourceTypes . contains ( PROV_NAMESPACE + "Entity" ) ) { resourceTypes . add ( PROV_NAMESPACE + "Entity" ) ; } final List < Actor > actor = new ArrayList < > ( ) ; actor . add ( new Person ( evt . getUserURI ( ) . toString ( ) , singletonList ( "Person" ) ) ) ; final String softwareAgent = evt . getInfo ( ) . get ( USER_AGENT ) ; if ( softwareAgent != null ) { actor . add ( new Application ( softwareAgent , singletonList ( "Application" ) ) ) ; } final JsonLDEventMessage msg = new JsonLDEventMessage ( ) ; msg . id = evt . getEventID ( ) ; msg . context = Arrays . asList ( ACTIVITYSTREAMS_NS , new Context ( ) ) ; msg . actor = actor ; msg . published = evt . getDate ( ) ; msg . type = types ; msg . name = name ; msg . object = new Object ( objectId , resourceTypes , baseUrl ) ; return msg ; }
Populate a JsonLDEventMessage from a FedoraEvent
1,248
public static Range convert ( final String source ) { final Matcher matcher = rangePattern . matcher ( source ) ; if ( ! matcher . matches ( ) ) { return new Range ( ) ; } final String from = matcher . group ( 1 ) ; final String to = matcher . group ( 2 ) ; final long start ; if ( from . equals ( "" ) ) { start = 0 ; } else { start = parseLong ( from ) ; } final long end ; if ( to . equals ( "" ) ) { end = - 1 ; } else { end = parseLong ( to ) ; } return new Range ( start , end ) ; }
Convert an HTTP Range header to a Range object
1,249
public static Repository getJcrRepository ( final FedoraRepository repository ) { if ( repository instanceof FedoraRepositoryImpl ) { return ( ( FedoraRepositoryImpl ) repository ) . getJcrRepository ( ) ; } throw new ClassCastException ( "FedoraRepository is not a " + FedoraRepositoryImpl . class . getCanonicalName ( ) ) ; }
Retrieve the internal JCR Repository from a FedoraRepository object
1,250
public InputStream fetchExternalContent ( ) { final URI uri = link . getUri ( ) ; final String scheme = uri . getScheme ( ) ; LOGGER . debug ( "scheme is {}" , scheme ) ; if ( scheme != null ) { try { if ( scheme . equals ( "file" ) ) { return new FileInputStream ( uri . getPath ( ) ) ; } else if ( scheme . equals ( "http" ) || scheme . equals ( "https" ) ) { return uri . toURL ( ) . openStream ( ) ; } } catch ( final IOException e ) { throw new ExternalContentAccessException ( "Failed to read external content from " + uri , e ) ; } } return null ; }
Fetch the external content
1,251
private Link parseLinkHeader ( final String link ) throws ExternalMessageBodyException { final Link realLink = Link . valueOf ( link ) ; try { final String handling = realLink . getParams ( ) . get ( HANDLING ) ; if ( handling == null || ! handling . matches ( "(?i)" + PROXY + "|" + COPY + "|" + REDIRECT ) ) { throw new ExternalMessageBodyException ( "Link header formatted incorrectly: 'handling' parameter incorrect or missing" ) ; } } catch ( final Exception e ) { throw new ExternalMessageBodyException ( "External content link header url is malformed" ) ; } return realLink ; }
Validate that an external content link header is appropriately formatted
1,252
private MediaType findContentType ( final String url ) { if ( url == null ) { return null ; } if ( url . startsWith ( "file" ) ) { return APPLICATION_OCTET_STREAM_TYPE ; } else if ( url . startsWith ( "http" ) ) { try ( CloseableHttpClient httpClient = HttpClients . createDefault ( ) ) { final HttpHead httpHead = new HttpHead ( url ) ; try ( CloseableHttpResponse response = httpClient . execute ( httpHead ) ) { if ( response . getStatusLine ( ) . getStatusCode ( ) == SC_OK ) { final Header contentType = response . getFirstHeader ( CONTENT_TYPE ) ; if ( contentType != null ) { return MediaType . valueOf ( contentType . getValue ( ) ) ; } } } } catch ( final IOException e ) { LOGGER . warn ( "Unable to retrieve external content from {} due to {}" , url , e . getMessage ( ) ) ; } catch ( final Exception e ) { throw new RepositoryRuntimeException ( e ) ; } } LOGGER . debug ( "Defaulting to octet stream for media type" ) ; return APPLICATION_OCTET_STREAM_TYPE ; }
Find the content type for a remote resource
1,253
public void addReferencePlaceholders ( final IdentifierConverter < Resource , FedoraResource > idTranslator , final Node node , final String propertyName , final Resource resource ) throws RepositoryException { try { final Node refNode = getJcrNode ( idTranslator . convert ( resource ) ) ; if ( isExternalNode . test ( refNode ) ) { return ; } final String referencePropertyName = getReferencePropertyName ( propertyName ) ; if ( ! isMultivaluedProperty ( node , propertyName ) ) { if ( node . hasProperty ( referencePropertyName ) ) { node . getProperty ( referencePropertyName ) . remove ( ) ; } if ( node . hasProperty ( propertyName ) ) { node . getProperty ( propertyName ) . remove ( ) ; } } final Value v = node . getSession ( ) . getValueFactory ( ) . createValue ( refNode , true ) ; appendOrReplaceNodeProperty ( node , referencePropertyName , v ) ; } catch ( final IdentifierConversionException e ) { } }
Add a reference placeholder from one node to another in - domain resource
1,254
public void removeReferencePlaceholders ( final IdentifierConverter < Resource , FedoraResource > idTranslator , final Node node , final String propertyName , final Resource resource ) throws RepositoryException { final String referencePropertyName = getReferencePropertyName ( propertyName ) ; final Node refNode = getJcrNode ( idTranslator . convert ( resource ) ) ; final Value v = node . getSession ( ) . getValueFactory ( ) . createValue ( refNode , true ) ; removeNodeProperty ( node , referencePropertyName , v ) ; }
Remove a reference placeholder that links one node to another in - domain resource
1,255
public ExternalContentHandler createFromLinks ( final List < String > links ) throws ExternalMessageBodyException { if ( links == null ) { return null ; } final List < String > externalContentLinks = links . stream ( ) . filter ( x -> x . contains ( EXTERNAL_CONTENT . toString ( ) ) ) . collect ( Collectors . toList ( ) ) ; if ( externalContentLinks . size ( ) > 1 ) { throw new ExternalMessageBodyException ( "More then one External Content Link header in request" ) ; } else if ( externalContentLinks . size ( ) == 1 ) { final String link = externalContentLinks . get ( 0 ) ; final String uri = getUriString ( link ) ; try { validator . validate ( uri ) ; } catch ( final ExternalMessageBodyException e ) { LOGGER . warn ( "Rejected invalid external path {}" , uri ) ; throw e ; } return new ExternalContentHandler ( link ) ; } return null ; }
Looks for ExternalContent link header and if it finds one it will return a new ExternalContentHandler object based on the found Link header . If multiple external content headers were found or the URI provided in the header is not a valid external content path then an ExternalMessageBodyException will be thrown .
1,256
private String doBackwardPathOnly ( final FedoraResource resource ) { final String path = reverse . convert ( resource . getPath ( ) ) ; if ( path == null ) { throw new RepositoryRuntimeException ( "Unable to process reverse chain for resource " + resource ) ; } return convertToExternalPath ( path ) ; }
Get only the resource path to this resource before embedding it in a full URI
1,257
public static String convertToExternalPath ( final String path ) { String newPath = replaceOnce ( path , "/" + CONTAINER_WEBAC_ACL , "/" + FCR_ACL ) ; newPath = replaceOnce ( newPath , "/" + LDPCV_TIME_MAP , "/" + FCR_VERSIONS ) ; newPath = replaceOnce ( newPath , "/" + FEDORA_DESCRIPTION , "/" + FCR_METADATA ) ; return newPath ; }
Converts internal path segments to their external formats .
1,258
public void buildListener ( ) throws RepositoryException { LOGGER . debug ( "Constructing an observer for JCR events..." ) ; session = getJcrSession ( repository . login ( ) ) ; session . getWorkspace ( ) . getObservationManager ( ) . addEventListener ( this , EVENT_TYPES , "/" , true , null , null , false ) ; session . save ( ) ; }
Register this observer with the JCR event listeners
1,259
public void stopListening ( ) throws RepositoryException { try { LOGGER . debug ( "Destroying an observer for JCR events..." ) ; session . getWorkspace ( ) . getObservationManager ( ) . removeEventListener ( this ) ; } finally { session . logout ( ) ; } }
logout of the session
1,260
public void onEvent ( final javax . jcr . observation . EventIterator events ) { Session lookupSession = null ; try { lookupSession = getJcrSession ( repository . login ( ) ) ; @ SuppressWarnings ( "unchecked" ) final Iterator < Event > filteredEvents = filter ( events , eventFilter :: test ) ; eventMapper . apply ( iteratorToStream ( filteredEvents ) ) . map ( filterAndDerefResourceTypes ( lookupSession ) ) . flatMap ( handleMoveEvents ( lookupSession ) ) . forEach ( this :: post ) ; } finally { if ( lookupSession != null ) { lookupSession . logout ( ) ; } } }
Filter JCR events and transform them into our own FedoraEvents .
1,261
@ Scheduled ( fixedRate = REAP_INTERVAL ) public void removeExpired ( ) { final Set < String > reapable = sessions . entrySet ( ) . stream ( ) . filter ( e -> e . getValue ( ) . getExpires ( ) . isPresent ( ) ) . filter ( e -> e . getValue ( ) . getExpires ( ) . get ( ) . isBefore ( now ( ) ) ) . map ( Map . Entry :: getKey ) . collect ( toSet ( ) ) ; reapable . forEach ( key -> { final FedoraSession s = sessions . get ( key ) ; if ( s != null ) { try { s . expire ( ) ; } catch ( final RepositoryRuntimeException e ) { LOGGER . error ( "Got exception rolling back expired session {}: {}" , s , e . getMessage ( ) ) ; } } sessions . remove ( key ) ; } ) ; }
Every REAP_INTERVAL milliseconds check for expired sessions . If the tx is expired roll it back and remove it from the registry .
1,262
public void addHttpHeaderToResponseStream ( final HttpServletResponse servletResponse , final UriInfo uriInfo , final FedoraResource resource ) { getUriAwareHttpHeaderFactories ( ) . forEach ( ( bean , factory ) -> { LOGGER . debug ( "Adding HTTP headers using: {}" , bean ) ; final Multimap < String , String > h = factory . createHttpHeadersForResource ( uriInfo , resource ) ; h . entries ( ) . forEach ( entry -> { servletResponse . addHeader ( entry . getKey ( ) , entry . getValue ( ) ) ; } ) ; } ) ; }
Add additional Http Headers
1,263
public static String toPath ( final IdentifierConverter < Resource , FedoraResource > idTranslator , final String originalPath ) { final Resource resource = idTranslator . toDomain ( originalPath ) ; final String path = idTranslator . asString ( resource ) ; return path . isEmpty ( ) ? "/" : path ; }
Convert a JAX - RS list of PathSegments to a JCR path
1,264
public static CacheEntry forProperty ( final Property property ) throws RepositoryException { if ( property . getName ( ) . endsWith ( PROXY_FOR . getLocalName ( ) ) || property . getName ( ) . endsWith ( REDIRECTS_TO . getLocalName ( ) ) ) { LOGGER . debug ( "Creating ExternalResourceCacheEntry for property: {} {}" , property . getName ( ) , property . getValue ( ) . toString ( ) ) ; return new ExternalResourceCacheEntry ( property ) ; } final Binary binary = property . getBinary ( ) ; if ( binary instanceof ExternalBinaryValue ) { return new ProjectedCacheEntry ( property ) ; } return new BinaryCacheEntry ( property ) ; }
Load a store - specific CacheEntry model
1,265
private RdfStream remapResourceUris ( final String resourceUri , final String mementoUri , final RdfStream rdfStream , final IdentifierConverter < Resource , FedoraResource > idTranslator , final Session jcrSession ) { final IdentifierConverter < Resource , FedoraResource > internalIdTranslator = new InternalIdentifierTranslator ( jcrSession ) ; final org . apache . jena . graph . Node mementoNode = createURI ( mementoUri ) ; final Stream < Triple > mappedStream = rdfStream . map ( t -> mapSubject ( t , resourceUri , mementoUri ) ) . map ( t -> convertToInternalReference ( t , idTranslator , internalIdTranslator ) ) ; return new DefaultRdfStream ( mementoNode , mappedStream ) ; }
Remaps the subjects of triples in rdfStream from the original resource URL to the URL of the new memento and converts objects which reference resources to an internal identifier to prevent enforcement of referential integrity constraints .
1,266
private Triple convertToInternalReference ( final Triple t , final IdentifierConverter < Resource , FedoraResource > idTranslator , final IdentifierConverter < Resource , FedoraResource > internalIdTranslator ) { if ( t . getObject ( ) . isURI ( ) ) { final Resource object = createResource ( t . getObject ( ) . getURI ( ) ) ; if ( idTranslator . inDomain ( object ) ) { final String path = idTranslator . convert ( object ) . getPath ( ) ; final Resource obj = createResource ( internalIdTranslator . toDomain ( path ) . getURI ( ) ) ; LOGGER . debug ( "Converting referencing resource uri {} to internal identifier {}." , t . getObject ( ) . getURI ( ) , obj . getURI ( ) ) ; return new Triple ( t . getSubject ( ) , t . getPredicate ( ) , obj . asNode ( ) ) ; } } return t ; }
Convert the referencing resource uri to un - dereferenceable internal identifier .
1,267
public HttpSession getSession ( final HttpServletRequest servletRequest ) { final HttpSession session ; final String txId = getEmbeddedId ( servletRequest , Prefix . TX ) ; try { if ( txId == null ) { session = createSession ( servletRequest ) ; } else { session = getSessionFromTransaction ( servletRequest , txId ) ; } } catch ( final SessionMissingException e ) { LOGGER . warn ( "Transaction missing: {}" , e . getMessage ( ) ) ; return null ; } return session ; }
Get a JCR session for the given HTTP servlet request with a SecurityContext attached
1,268
protected HttpSession createSession ( final HttpServletRequest servletRequest ) { LOGGER . debug ( "Returning an authenticated session in the default workspace" ) ; return new HttpSession ( repo . login ( credentialsService . getCredentials ( servletRequest ) ) ) ; }
Create a JCR session for the given HTTP servlet request with a SecurityContext attached .
1,269
protected HttpSession getSessionFromTransaction ( final HttpServletRequest servletRequest , final String txId ) { final Principal userPrincipal = servletRequest . getUserPrincipal ( ) ; final String userName = userPrincipal == null ? null : userPrincipal . getName ( ) ; final FedoraSession session = batchService . getSession ( txId , userName ) ; final HttpSession batchSession = new HttpSession ( session ) ; batchSession . makeBatchSession ( ) ; LOGGER . debug ( "Returning a session in the batch {} for user {}" , batchSession , userName ) ; return batchSession ; }
Retrieve a JCR session from an active transaction
1,270
protected String getEmbeddedId ( final HttpServletRequest servletRequest , final Prefix prefix ) { String requestPath = servletRequest . getPathInfo ( ) ; if ( requestPath == null && servletRequest . getContextPath ( ) . isEmpty ( ) ) { requestPath = servletRequest . getRequestURI ( ) ; } String id = null ; if ( requestPath != null ) { final String pathPrefix = prefix . getPrefix ( ) ; final String [ ] part = requestPath . split ( "/" ) ; if ( part . length > 1 && part [ 1 ] . startsWith ( pathPrefix ) ) { id = part [ 1 ] . substring ( pathPrefix . length ( ) ) ; } } return id ; }
Extract the id embedded at the beginning of a request path
1,271
public Stream < Triple > common ( ) { return stream ( spliteratorUnknownSize ( common . find ( ANY , ANY , ANY ) , IMMUTABLE ) , false ) ; }
This method will return null until the source iterator is exhausted .
1,272
public RdfStream addHttpComponentModelsForResourceToStream ( final RdfStream rdfStream , final FedoraResource resource , final UriInfo uriInfo , final IdentifierConverter < Resource , FedoraResource > idTranslator ) { LOGGER . debug ( "Adding additional HTTP context triples to stream" ) ; return new DefaultRdfStream ( rdfStream . topic ( ) , concat ( rdfStream , getUriAwareTripleFactories ( ) . entrySet ( ) . stream ( ) . flatMap ( e -> { LOGGER . debug ( "Adding response information using: {}" , e . getKey ( ) ) ; return stream ( spliteratorUnknownSize ( e . getValue ( ) . createModelForResource ( resource , uriInfo , idTranslator ) . listStatements ( ) , IMMUTABLE ) , false ) . map ( Statement :: asTriple ) ; } ) ) ) ; }
Add additional models to the RDF dataset for the given resource
1,273
public String serialize ( final FedoraEvent evt ) { try { return MAPPER . writeValueAsString ( from ( evt ) ) ; } catch ( final JsonProcessingException ex ) { LOGGER . error ( "Error processing JSON: {}" , ex . getMessage ( ) ) ; return null ; } }
Serialize a FedoraEvent into a JSON String
1,274
private static String getPropertyNameFromPredicate ( final NamespaceRegistry namespaceRegistry , final Resource predicate , final Map < String , String > namespaceMapping ) throws RepositoryException { if ( namespaceMapping != null && namespaceMapping . containsKey ( "fcr" ) ) { throw new FedoraInvalidNamespaceException ( "Invalid fcr namespace properties " + predicate + "." ) ; } final String rdfNamespace = predicate . getNameSpace ( ) ; if ( namespaceMapping != null && namespaceMapping . size ( ) > 0 && ! namespaceMapping . containsValue ( rdfNamespace ) ) { LOGGER . warn ( "The namespace of predicate: {} was possibly misinterpreted as: {}." , predicate , rdfNamespace ) ; } final String rdfLocalname = predicate . getLocalName ( ) ; final String prefix ; assert ( namespaceRegistry != null ) ; final String namespace = getJcrNamespaceForRDFNamespace ( rdfNamespace ) ; if ( namespaceRegistry . isRegisteredUri ( namespace ) ) { LOGGER . debug ( "Discovered namespace: {} in namespace registry." , namespace ) ; prefix = namespaceRegistry . getPrefix ( namespace ) ; } else { LOGGER . debug ( "Didn't discover namespace: {} in namespace registry." , namespace ) ; if ( namespaceMapping != null && namespaceMapping . containsValue ( namespace ) ) { LOGGER . debug ( "Discovered namespace: {} in namespace map: {}." , namespace , namespaceMapping ) ; prefix = namespaceMapping . entrySet ( ) . stream ( ) . filter ( t -> t . getValue ( ) . equals ( namespace ) ) . map ( Map . Entry :: getKey ) . findFirst ( ) . orElse ( null ) ; namespaceRegistry . registerNamespace ( prefix , namespace ) ; } else { prefix = namespaceRegistry . registerNamespace ( namespace ) ; LOGGER . debug ( "Registered prefix: {} for namespace: {}." , prefix , namespace ) ; } } final String propertyName = prefix + ":" + rdfLocalname ; LOGGER . debug ( "Took RDF predicate {} and translated it to JCR property {}" , namespace , propertyName ) ; return propertyName ; }
Get the JCR property name for an RDF predicate
1,275
protected Response getContent ( final String rangeValue , final int limit , final RdfStream rdfStream , final FedoraResource resource ) throws IOException { final RdfNamespacedStream outputStream ; if ( resource instanceof FedoraBinary ) { return getBinaryContent ( rangeValue , resource ) ; } else { outputStream = new RdfNamespacedStream ( new DefaultRdfStream ( rdfStream . topic ( ) , concat ( rdfStream , getResourceTriples ( limit , resource ) ) ) , namespaceRegistry . getNamespaces ( ) ) ; } setVaryAndPreferenceAppliedHeaders ( servletResponse , prefer , resource ) ; return ok ( outputStream ) . build ( ) ; }
This method returns an HTTP response with content body appropriate to the following arguments .
1,276
private RdfStream getResourceTriples ( final int limit , final FedoraResource resource ) { final PreferTag returnPreference ; if ( prefer != null && prefer . hasReturn ( ) ) { returnPreference = prefer . getReturn ( ) ; } else if ( prefer != null && prefer . hasHandling ( ) ) { returnPreference = prefer . getHandling ( ) ; } else { returnPreference = PreferTag . emptyTag ( ) ; } final LdpPreferTag ldpPreferences = new LdpPreferTag ( returnPreference ) ; final Predicate < Triple > tripleFilter = ldpPreferences . prefersServerManaged ( ) ? x -> true : IS_MANAGED_TRIPLE . negate ( ) ; final List < Stream < Triple > > streams = new ArrayList < > ( ) ; if ( returnPreference . getValue ( ) . equals ( "minimal" ) ) { streams . add ( getTriples ( resource , of ( PROPERTIES , MINIMAL ) ) . filter ( tripleFilter ) ) ; if ( ldpPreferences . prefersServerManaged ( ) && ! resource . isMemento ( ) ) { streams . add ( getTriples ( resource , of ( SERVER_MANAGED , MINIMAL ) ) ) ; } } else { streams . add ( getTriples ( resource , PROPERTIES ) . filter ( tripleFilter ) ) ; if ( ldpPreferences . prefersServerManaged ( ) && ! resource . isMemento ( ) ) { streams . add ( getTriples ( resource , SERVER_MANAGED ) ) ; } if ( ldpPreferences . prefersContainment ( ) ) { if ( limit == - 1 ) { streams . add ( getTriples ( resource , LDP_CONTAINMENT ) ) ; } else { streams . add ( getTriples ( resource , LDP_CONTAINMENT ) . limit ( limit ) ) ; } } if ( ldpPreferences . prefersMembership ( ) ) { streams . add ( getTriples ( resource , LDP_MEMBERSHIP ) ) ; } if ( ldpPreferences . prefersReferences ( ) ) { streams . add ( getTriples ( resource , INBOUND_REFERENCES ) ) ; } if ( ldpPreferences . prefersEmbed ( ) ) { streams . add ( getTriples ( resource , EMBED_RESOURCES ) ) ; } } final RdfStream rdfStream = new DefaultRdfStream ( asNode ( resource ) , streams . stream ( ) . reduce ( empty ( ) , Stream :: concat ) ) ; if ( httpTripleUtil != null && ldpPreferences . prefersServerManaged ( ) ) { return httpTripleUtil . addHttpComponentModelsForResourceToStream ( rdfStream , resource , uriInfo , translator ( ) ) ; } return rdfStream ; }
This method returns a stream of RDF triples associated with this target resource
1,277
private Response getBinaryContent ( final String rangeValue , final FedoraResource resource ) throws IOException { final FedoraBinary binary = ( FedoraBinary ) resource ; final CacheControl cc = new CacheControl ( ) ; cc . setMaxAge ( 0 ) ; cc . setMustRevalidate ( true ) ; final Response . ResponseBuilder builder ; if ( rangeValue != null && rangeValue . startsWith ( "bytes" ) ) { final Range range = Range . convert ( rangeValue ) ; final long contentSize = binary . getContentSize ( ) ; final String endAsString ; if ( range . end ( ) == - 1 ) { endAsString = Long . toString ( contentSize - 1 ) ; } else { endAsString = Long . toString ( range . end ( ) ) ; } final String contentRangeValue = String . format ( "bytes %s-%s/%s" , range . start ( ) , endAsString , contentSize ) ; if ( range . end ( ) > contentSize || ( range . end ( ) == - 1 && range . start ( ) > contentSize ) ) { builder = status ( REQUESTED_RANGE_NOT_SATISFIABLE ) . header ( "Content-Range" , contentRangeValue ) ; } else { @ SuppressWarnings ( "resource" ) final RangeRequestInputStream rangeInputStream = new RangeRequestInputStream ( binary . getContent ( ) , range . start ( ) , range . size ( ) ) ; builder = status ( PARTIAL_CONTENT ) . entity ( rangeInputStream ) . header ( "Content-Range" , contentRangeValue ) . header ( CONTENT_LENGTH , range . size ( ) ) ; } } else { @ SuppressWarnings ( "resource" ) final InputStream content = binary . getContent ( ) ; builder = ok ( content ) ; } return builder . type ( getBinaryResourceMediaType ( resource ) . toString ( ) ) . cacheControl ( cc ) . build ( ) ; }
Get the binary content of a datastream
1,278
private void addAcceptPostHeader ( ) { final String rdfTypes = TURTLE + "," + N3 + "," + N3_ALT2 + "," + RDF_XML + "," + NTRIPLES + "," + JSON_LD ; servletResponse . addHeader ( "Accept-Post" , rdfTypes ) ; }
Add the standard Accept - Post header for reuse .
1,279
protected void addLinkAndOptionsHttpHeaders ( final FedoraResource resource ) { addResourceLinkHeaders ( resource ) ; addAcceptExternalHeader ( ) ; final String options ; if ( resource . isMemento ( ) ) { options = "GET,HEAD,OPTIONS,DELETE" ; } else if ( resource instanceof FedoraTimeMap ) { options = "POST,HEAD,GET,OPTIONS" ; servletResponse . addHeader ( "Vary-Post" , MEMENTO_DATETIME_HEADER ) ; addAcceptPostHeader ( ) ; } else if ( resource instanceof FedoraBinary ) { options = "DELETE,HEAD,GET,PUT,OPTIONS" ; } else if ( resource instanceof NonRdfSourceDescription ) { options = "HEAD,GET,DELETE,PUT,PATCH,OPTIONS" ; servletResponse . addHeader ( HTTP_HEADER_ACCEPT_PATCH , contentTypeSPARQLUpdate ) ; } else if ( resource instanceof Container ) { options = "MOVE,COPY,DELETE,POST,HEAD,GET,PUT,PATCH,OPTIONS" ; servletResponse . addHeader ( HTTP_HEADER_ACCEPT_PATCH , contentTypeSPARQLUpdate ) ; addAcceptPostHeader ( ) ; } else { options = "" ; } servletResponse . addHeader ( "Allow" , options ) ; }
Add Link and Option headers
1,280
protected List < String > unpackLinks ( final List < String > rawLinks ) { if ( rawLinks == null ) { return null ; } return rawLinks . stream ( ) . flatMap ( x -> Arrays . stream ( x . split ( "," ) ) ) . collect ( Collectors . toList ( ) ) ; }
Multi - value Link header values parsed by the javax . ws . rs . core are not split out by the framework Therefore we must do this ourselves .
1,281
protected void addResourceHttpHeaders ( final FedoraResource resource ) { if ( resource instanceof FedoraBinary ) { final FedoraBinary binary = ( FedoraBinary ) resource ; final Date createdDate = binary . getCreatedDate ( ) != null ? Date . from ( binary . getCreatedDate ( ) ) : null ; final Date modDate = binary . getLastModifiedDate ( ) != null ? Date . from ( binary . getLastModifiedDate ( ) ) : null ; final ContentDisposition contentDisposition = ContentDisposition . type ( "attachment" ) . fileName ( binary . getFilename ( ) ) . creationDate ( createdDate ) . modificationDate ( modDate ) . size ( binary . getContentSize ( ) ) . build ( ) ; servletResponse . addHeader ( CONTENT_TYPE , binary . getMimeType ( ) ) ; if ( ! binary . isRedirect ( ) ) { servletResponse . addHeader ( CONTENT_LENGTH , String . valueOf ( binary . getContentSize ( ) ) ) ; } servletResponse . addHeader ( "Accept-Ranges" , "bytes" ) ; servletResponse . addHeader ( CONTENT_DISPOSITION , contentDisposition . toString ( ) ) ; } servletResponse . addHeader ( LINK , "<" + LDP_NAMESPACE + "Resource>;rel=\"type\"" ) ; if ( resource instanceof FedoraBinary ) { servletResponse . addHeader ( LINK , "<" + LDP_NAMESPACE + "NonRDFSource>;rel=\"type\"" ) ; } else if ( resource instanceof Container || resource instanceof FedoraTimeMap ) { servletResponse . addHeader ( LINK , "<" + CONTAINER . getURI ( ) + ">;rel=\"type\"" ) ; servletResponse . addHeader ( LINK , buildLink ( RDF_SOURCE . getURI ( ) , "type" ) ) ; if ( resource . hasType ( LDP_BASIC_CONTAINER ) ) { servletResponse . addHeader ( LINK , "<" + BASIC_CONTAINER . getURI ( ) + ">;rel=\"type\"" ) ; } else if ( resource . hasType ( LDP_DIRECT_CONTAINER ) ) { servletResponse . addHeader ( LINK , "<" + DIRECT_CONTAINER . getURI ( ) + ">;rel=\"type\"" ) ; } else if ( resource . hasType ( LDP_INDIRECT_CONTAINER ) ) { servletResponse . addHeader ( LINK , "<" + INDIRECT_CONTAINER . getURI ( ) + ">;rel=\"type\"" ) ; } else { servletResponse . addHeader ( LINK , "<" + BASIC_CONTAINER . getURI ( ) + ">;rel=\"type\"" ) ; } } else { servletResponse . addHeader ( LINK , buildLink ( RDF_SOURCE . getURI ( ) , "type" ) ) ; } if ( httpHeaderInject != null ) { httpHeaderInject . addHttpHeaderToResponseStream ( servletResponse , uriInfo , resource ) ; } addLinkAndOptionsHttpHeaders ( resource ) ; addAclHeader ( resource ) ; addMementoHeaders ( resource ) ; }
Add any resource - specific headers to the response
1,282
protected void checkCacheControlHeaders ( final Request request , final HttpServletResponse servletResponse , final FedoraResource resource , final HttpSession session ) { evaluateRequestPreconditions ( request , servletResponse , resource , session , true ) ; addCacheControlHeaders ( servletResponse , resource , session ) ; }
Evaluate the cache control headers for the request to see if it can be served from the cache .
1,283
protected void evaluateRequestPreconditions ( final Request request , final HttpServletResponse servletResponse , final FedoraResource resource , final HttpSession session ) { evaluateRequestPreconditions ( request , servletResponse , resource , session , false ) ; }
Evaluate request preconditions to ensure the resource is the expected state
1,284
private MediaType acceptabePlainTextMediaType ( ) { final List < MediaType > acceptable = headers . getAcceptableMediaTypes ( ) ; if ( acceptable == null || acceptable . size ( ) == 0 ) { return TEXT_PLAIN_TYPE ; } for ( final MediaType type : acceptable ) { if ( type . isWildcardType ( ) || ( type . isCompatible ( TEXT_PLAIN_TYPE ) && type . isWildcardSubtype ( ) ) ) { return TEXT_PLAIN_TYPE ; } else if ( type . isCompatible ( TEXT_PLAIN_TYPE ) ) { return type ; } } return null ; }
Returns an acceptable plain text media type if possible or null if not .
1,285
@ SuppressWarnings ( "resource" ) protected Response createUpdateResponse ( final FedoraResource resource , final boolean created ) { addCacheControlHeaders ( servletResponse , resource , session ) ; addResourceLinkHeaders ( resource , created ) ; addExternalContentHeaders ( resource ) ; addAclHeader ( resource ) ; addMementoHeaders ( resource ) ; if ( ! created ) { return noContent ( ) . build ( ) ; } final URI location = getUri ( resource ) ; final Response . ResponseBuilder builder = created ( location ) ; if ( prefer == null || ! prefer . hasReturn ( ) ) { final MediaType acceptablePlainText = acceptabePlainTextMediaType ( ) ; if ( acceptablePlainText != null ) { return builder . type ( acceptablePlainText ) . entity ( location . toString ( ) ) . build ( ) ; } return notAcceptable ( mediaTypes ( TEXT_PLAIN_TYPE ) . build ( ) ) . build ( ) ; } else if ( prefer . getReturn ( ) . getValue ( ) . equals ( "minimal" ) ) { return builder . build ( ) ; } else { if ( prefer != null ) { prefer . getReturn ( ) . addResponseHeaders ( servletResponse ) ; } final RdfNamespacedStream rdfStream = new RdfNamespacedStream ( new DefaultRdfStream ( asNode ( resource ) , getResourceTriples ( resource ) ) , namespaceRegistry . getNamespaces ( ) ) ; return builder . entity ( rdfStream ) . build ( ) ; } }
Create the appropriate response after a create or update request is processed . When a resource is created examine the Prefer and Accept headers to determine whether to include a representation . By default the URI for the created resource is return as plain text . If a minimal response is requested then no body is returned . If a non - minimal return is requested return the RDF for the created resource in the appropriate RDF serialization .
1,286
private Model parseBodyAsModel ( final InputStream requestBodyStream , final MediaType contentType , final FedoraResource resource ) throws MalformedRdfException { final Lang format = contentTypeToLang ( contentType . toString ( ) ) ; final Model inputModel ; try { inputModel = createDefaultModel ( ) ; inputModel . read ( requestBodyStream , getUri ( resource ) . toString ( ) , format . getName ( ) . toUpperCase ( ) ) ; return inputModel ; } catch ( final RiotException e ) { throw new BadRequestException ( "RDF was not parsable: " + e . getMessage ( ) , e ) ; } catch ( final RuntimeIOException e ) { if ( e . getCause ( ) instanceof JsonParseException ) { throw new MalformedRdfException ( e . getCause ( ) ) ; } throw new RepositoryRuntimeException ( e ) ; } }
Parse the request body as a Model .
1,287
private Statement createDefaultAccessToStatement ( final String authSubject ) { final String currentResourcePath = authSubject . substring ( 0 , authSubject . indexOf ( "/" + FCR_ACL ) ) ; return createStatement ( createResource ( authSubject ) , WEBAC_ACCESS_TO_PROPERTY , createResource ( currentResourcePath ) ) ; }
Returns a Statement with the resource containing the acl to be the accessTo target for the given auth subject .
1,288
protected static URI checksumURI ( final String checksum ) { if ( ! isBlank ( checksum ) ) { return URI . create ( checksum ) ; } return null ; }
Create a checksum URI object .
1,289
protected int getChildrenLimit ( ) { final List < String > acceptHeaders = headers . getRequestHeader ( ACCEPT ) ; if ( acceptHeaders != null && acceptHeaders . size ( ) > 0 ) { final List < String > accept = Arrays . asList ( acceptHeaders . get ( 0 ) . split ( "," ) ) ; if ( accept . contains ( TEXT_HTML ) ) { return 100 ; } } final List < String > limits = headers . getRequestHeader ( "Limit" ) ; if ( null != limits && limits . size ( ) > 0 ) { try { return Integer . parseInt ( limits . get ( 0 ) ) ; } catch ( final NumberFormatException e ) { LOGGER . warn ( "Invalid 'Limit' header value: {}" , limits . get ( 0 ) ) ; throw new ClientErrorException ( "Invalid 'Limit' header value: " + limits . get ( 0 ) , SC_BAD_REQUEST , e ) ; } } return - 1 ; }
Calculate the max number of children to display at once .
1,290
protected static Collection < String > parseDigestHeader ( final String digest ) throws UnsupportedAlgorithmException { try { final Map < String , String > digestPairs = RFC3230_SPLITTER . split ( nullToEmpty ( digest ) ) ; final boolean allSupportedAlgorithms = digestPairs . keySet ( ) . stream ( ) . allMatch ( ContentDigest . DIGEST_ALGORITHM :: isSupportedAlgorithm ) ; if ( digestPairs . isEmpty ( ) || allSupportedAlgorithms ) { return digestPairs . entrySet ( ) . stream ( ) . filter ( entry -> ContentDigest . DIGEST_ALGORITHM . isSupportedAlgorithm ( entry . getKey ( ) ) ) . map ( entry -> ContentDigest . asURI ( entry . getKey ( ) , entry . getValue ( ) ) . toString ( ) ) . collect ( Collectors . toSet ( ) ) ; } else { throw new UnsupportedAlgorithmException ( String . format ( "Unsupported Digest Algorithim: %1$s" , digest ) ) ; } } catch ( final RuntimeException e ) { if ( e instanceof IllegalArgumentException ) { throw new ClientErrorException ( "Invalid Digest header: " + digest + "\n" , BAD_REQUEST ) ; } throw e ; } }
Parse the RFC - 3230 Digest response header value . Look for a sha1 checksum and return it as a urn if missing or malformed an empty string is returned .
1,291
public static void assertRequiredContainerTriples ( final Model model ) throws ConstraintViolationException { assertContainsRequiredProperties ( model , REQUIRED_PROPERTIES ) ; assertContainsRequiredTypes ( model , CONTAINER_TYPES ) ; }
Throws a ConstraintViolationException if the model does not contain all required server - managed triples for a container .
1,292
public static void assertRequiredDescriptionTriples ( final Model model ) throws ConstraintViolationException { assertContainsRequiredProperties ( model , REQUIRED_PROPERTIES ) ; assertContainsRequiredTypes ( model , BINARY_TYPES ) ; }
Throws a ConstraintViolationException if the model does not contain all required server - managed triples for a binary description .
1,293
public FedoraBinary find ( final FedoraSession session , final String path ) { return cast ( findNode ( session , path ) ) ; }
Retrieve a Datastream instance by pid and dsid
1,294
public void touch ( final boolean includeMembershipResource , final Calendar createdDate , final String createdUser , final Calendar modifiedDate , final String modifyingUser ) throws RepositoryException { super . touch ( includeMembershipResource , createdDate , createdUser , modifiedDate , modifyingUser ) ; if ( createdDate != null || createdUser != null || modifiedDate != null || modifyingUser != null ) { ( ( FedoraBinaryImpl ) getDescribedResource ( ) ) . touch ( false , createdDate , createdUser , modifiedDate , modifyingUser ) ; } }
Overrides the superclass to propagate updates to certain properties to the binary if explicitly set .
1,295
public boolean exists ( final FedoraSession session , final String path ) { final Session jcrSession = getJcrSession ( session ) ; try { return jcrSession . nodeExists ( path ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
test node existence at path
1,296
public Iterator < Node > getVersions ( final Graph graph , final Node subject ) { return getOrderedVersions ( graph , subject , CONTAINS . asResource ( ) ) ; }
Return an iterator of Triples for versions .
1,297
public Iterator < Node > getOrderedVersions ( final Graph g , final Node subject , final Resource predicate ) { final List < Node > vs = listObjects ( g , subject , predicate . asNode ( ) ) . toList ( ) ; vs . sort ( Comparator . comparing ( v -> getVersionDate ( g , v ) ) ) ; return vs . iterator ( ) ; }
Return an iterator of Triples for versions in order that they were created .
1,298
public String getVersionLabel ( final Graph graph , final Node subject ) { final Instant datetime = getVersionDate ( graph , subject ) ; return MEMENTO_RFC_1123_FORMATTER . format ( datetime ) ; }
Get the date time as the version label .
1,299
public Instant getVersionDate ( final Graph graph , final Node subject ) { final String [ ] pathParts = subject . getURI ( ) . split ( "/" ) ; return MEMENTO_LABEL_FORMATTER . parse ( pathParts [ pathParts . length - 1 ] , Instant :: from ) ; }
Gets a modification date of a subject from the graph