idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
1,300
|
public String getObjectTitle ( final Graph graph , final Node sub ) { if ( sub == null ) { return "" ; } final Optional < String > title = TITLE_PROPERTIES . stream ( ) . map ( Property :: asNode ) . flatMap ( p -> listObjects ( graph , sub , p ) . toList ( ) . stream ( ) ) . filter ( Node :: isLiteral ) . map ( Node :: getLiteral ) . map ( LiteralLabel :: toString ) . findFirst ( ) ; return title . orElse ( sub . isURI ( ) ? sub . getURI ( ) : sub . isBlank ( ) ? sub . getBlankNodeLabel ( ) : sub . toString ( ) ) ; }
|
Get the canonical title of a subject from the graph
|
1,301
|
public String getObjectsAsString ( final Graph graph , final Node subject , final Resource predicate , final boolean uriAsLink ) { LOGGER . trace ( "Getting Objects as String: s:{}, p:{}, g:{}" , subject , predicate , graph ) ; final Iterator < Node > iterator = listObjects ( graph , subject , predicate . asNode ( ) ) ; if ( iterator . hasNext ( ) ) { final Node obj = iterator . next ( ) ; if ( obj . isLiteral ( ) ) { final String lit = obj . getLiteralValue ( ) . toString ( ) ; return lit . isEmpty ( ) ? "<empty>" : lit ; } return uriAsLink ? "<<a href=\"" + obj . getURI ( ) + "\">" + obj . getURI ( ) + "</a>>" : obj . getURI ( ) ; } return "" ; }
|
Get the string version of the object that matches the given subject and predicate
|
1,302
|
public Node getOriginalResource ( final Node subject ) { if ( ! subject . isURI ( ) ) { return subject ; } final String subjectUri = subject . getURI ( ) ; final int index = subjectUri . indexOf ( FCR_VERSIONS ) ; if ( index > 0 ) { return NodeFactory . createURI ( subjectUri . substring ( 0 , index - 1 ) ) ; } else { return subject ; } }
|
Returns the original resource as a URI Node if the subject represents a memento uri ; otherwise it returns the subject parameter .
|
1,303
|
public int getNumChildren ( final Graph graph , final Node subject ) { LOGGER . trace ( "Getting number of children: s:{}, g:{}" , subject , graph ) ; return ( int ) asStream ( listObjects ( graph , subject , CONTAINS . asNode ( ) ) ) . count ( ) ; }
|
Get the number of child resources associated with the arg subject as specified by the triple found in the arg graph with the predicate RdfLexicon . HAS_CHILD_COUNT .
|
1,304
|
public Map < String , String > getNodeBreadcrumbs ( final UriInfo uriInfo , final Node subject ) { final String topic = subject . getURI ( ) ; LOGGER . trace ( "Generating breadcrumbs for subject {}" , subject ) ; final String baseUri = uriInfo . getBaseUri ( ) . toString ( ) ; if ( ! topic . startsWith ( baseUri ) ) { LOGGER . trace ( "Topic wasn't part of our base URI {}" , baseUri ) ; return emptyMap ( ) ; } final String salientPath = topic . substring ( baseUri . length ( ) ) ; final StringJoiner cumulativePath = new StringJoiner ( "/" ) ; return stream ( salientPath . split ( "/" ) ) . filter ( seg -> ! seg . isEmpty ( ) ) . collect ( toMap ( seg -> uriInfo . getBaseUriBuilder ( ) . path ( cumulativePath . add ( seg ) . toString ( ) ) . build ( ) . toString ( ) , seg -> seg , ( u , v ) -> null , LinkedHashMap :: new ) ) ; }
|
Generate url to local name breadcrumbs for a given node s tree
|
1,305
|
public List < Triple > getSortedTriples ( final Model model , final Iterator < Triple > it ) { final List < Triple > triples = newArrayList ( it ) ; triples . sort ( new TripleOrdering ( model ) ) ; return triples ; }
|
Sort a Iterator of Triples alphabetically by its subject predicate and object
|
1,306
|
public String getPrefixPreamble ( final PrefixMapping mapping ) { return mapping . getNsPrefixMap ( ) . entrySet ( ) . stream ( ) . map ( e -> "PREFIX " + e . getKey ( ) + ": <" + e . getValue ( ) + ">" ) . collect ( joining ( "\n" , "" , "\n\n" ) ) ; }
|
Get a prefix preamble appropriate for a SPARQL - UPDATE query from a prefix mapping object
|
1,307
|
public boolean isRdfResource ( final Graph graph , final Node subject , final String namespace , final String resource ) { LOGGER . trace ( "Is RDF Resource? s:{}, ns:{}, r:{}, g:{}" , subject , namespace , resource , graph ) ; return graph . find ( subject , type . asNode ( ) , createResource ( namespace + resource ) . asNode ( ) ) . hasNext ( ) ; }
|
Determines whether the subject is kind of RDF resource
|
1,308
|
public boolean isRootResource ( final Graph graph , final Node subject ) { final String rootRes = graph . getPrefixMapping ( ) . expandPrefix ( FEDORA_REPOSITORY_ROOT ) ; final Node root = createResource ( rootRes ) . asNode ( ) ; return graph . contains ( subject , rdfType ( ) . asNode ( ) , root ) ; }
|
Is the subject the repository root resource .
|
1,309
|
public static Node getContentNode ( final Node subject ) { return subject == null ? null : NodeFactory . createURI ( subject . getURI ( ) . replace ( "/" + FCR_METADATA , "" ) ) ; }
|
Get the content - bearing node for the given subject
|
1,310
|
public static boolean isManagedProperty ( final Node property ) { return property . isURI ( ) && isManagedPredicate . test ( createProperty ( property . getURI ( ) ) ) ; }
|
Test if a Predicate is managed
|
1,311
|
private FedoraBinary getBinary ( final String extUrl ) { if ( wrappedBinary == null ) { wrappedBinary = getBinaryImplementation ( extUrl ) ; } return wrappedBinary ; }
|
Get the proxied binary content object wrapped by this object
|
1,312
|
private FedoraBinary getBinaryImplementation ( final String extUrl ) { String url = extUrl ; if ( url == null || url . isEmpty ( ) ) { url = getURLInfo ( ) ; } if ( url != null ) { if ( url . toLowerCase ( ) . startsWith ( LOCAL_FILE_ACCESS_TYPE ) ) { return new LocalFileBinary ( getNode ( ) ) ; } else if ( url . toLowerCase ( ) . startsWith ( URL_ACCESS_TYPE ) ) { return new UrlBinary ( getNode ( ) ) ; } } return new InternalFedoraBinary ( getNode ( ) ) ; }
|
Return the proper object that can handle this type of binary
|
1,313
|
private String getURLInfo ( ) { try { if ( hasProperty ( PROXY_FOR ) ) { return getNode ( ) . getProperty ( PROXY_FOR ) . getValue ( ) . getString ( ) ; } else if ( hasProperty ( REDIRECTS_TO ) ) { return getNode ( ) . getProperty ( REDIRECTS_TO ) . getValue ( ) . getString ( ) ; } } catch ( RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } return null ; }
|
Fetch the URL of the external binary
|
1,314
|
private void addURIToAuthorize ( final HttpServletRequest httpRequest , final URI uri ) { @ SuppressWarnings ( "unchecked" ) Set < URI > targetURIs = ( Set < URI > ) httpRequest . getAttribute ( URIS_TO_AUTHORIZE ) ; if ( targetURIs == null ) { targetURIs = new HashSet < > ( ) ; httpRequest . setAttribute ( URIS_TO_AUTHORIZE , targetURIs ) ; } targetURIs . add ( uri ) ; }
|
Add URIs to collect permissions information for .
|
1,315
|
private boolean isPayloadIndirectOrDirect ( final HttpServletRequest request ) { return Collections . list ( request . getHeaders ( "Link" ) ) . stream ( ) . map ( Link :: valueOf ) . map ( Link :: getUri ) . anyMatch ( l -> directOrIndirect . contains ( l ) ) ; }
|
Is the request to create an indirect or direct container .
|
1,316
|
private boolean isResourceIndirectOrDirect ( final FedoraResource resource ) { return resource . getTypes ( ) . stream ( ) . anyMatch ( l -> directOrIndirect . contains ( l ) ) ; }
|
Is the current resource a direct or indirect container
|
1,317
|
private boolean isAuthorizedForMembershipResource ( final HttpServletRequest request , final Subject currentUser ) throws IOException { if ( resourceExists ( request ) && request . getMethod ( ) . equalsIgnoreCase ( "POST" ) ) { if ( isResourceIndirectOrDirect ( resource ( request ) ) ) { final URI membershipResource = getHasMemberFromResource ( request ) ; addURIToAuthorize ( request , membershipResource ) ; if ( ! currentUser . isPermitted ( new WebACPermission ( WEBAC_MODE_WRITE , membershipResource ) ) ) { return false ; } } } else if ( request . getMethod ( ) . equalsIgnoreCase ( "PUT" ) ) { if ( containerExists ( request ) && isResourceIndirectOrDirect ( getContainer ( request ) ) ) { final URI membershipResource = getHasMemberFromResource ( request , getContainer ( request ) ) ; addURIToAuthorize ( request , membershipResource ) ; if ( ! currentUser . isPermitted ( new WebACPermission ( WEBAC_MODE_WRITE , membershipResource ) ) ) { return false ; } } } else if ( isSparqlUpdate ( request ) && isResourceIndirectOrDirect ( resource ( request ) ) ) { final URI membershipResource = getHasMemberFromPatch ( request ) ; if ( membershipResource != null ) { log . debug ( "Found membership resource: {}" , membershipResource ) ; addURIToAuthorize ( request , membershipResource ) ; if ( ! currentUser . isPermitted ( new WebACPermission ( WEBAC_MODE_WRITE , membershipResource ) ) ) { return false ; } } } else if ( request . getMethod ( ) . equalsIgnoreCase ( "DELETE" ) ) { if ( isResourceIndirectOrDirect ( resource ( request ) ) ) { final URI membershipResource = getHasMemberFromResource ( request ) ; addURIToAuthorize ( request , membershipResource ) ; if ( ! currentUser . isPermitted ( new WebACPermission ( WEBAC_MODE_WRITE , membershipResource ) ) ) { return false ; } } else if ( isResourceIndirectOrDirect ( getContainer ( request ) ) ) { final FedoraResource container = getContainer ( request ) ; final URI membershipResource = getHasMemberFromResource ( request , container ) ; addURIToAuthorize ( request , membershipResource ) ; if ( ! currentUser . isPermitted ( new WebACPermission ( WEBAC_MODE_WRITE , membershipResource ) ) ) { return false ; } } } if ( isPayloadIndirectOrDirect ( request ) ) { final URI membershipResource = getHasMemberFromRequest ( request ) ; if ( membershipResource != null ) { log . debug ( "Found membership resource: {}" , membershipResource ) ; addURIToAuthorize ( request , membershipResource ) ; if ( ! currentUser . isPermitted ( new WebACPermission ( WEBAC_MODE_WRITE , membershipResource ) ) ) { return false ; } } } return true ; }
|
Check if we are authorized to access the target of membershipRelation if required . Really this is a test for failure . The default is true because we might not be looking at an indirect or direct container .
|
1,318
|
private URI getHasMemberFromRequest ( final HttpServletRequest request ) throws IOException { final String baseUri = request . getRequestURL ( ) . toString ( ) ; final RDFReader reader ; final String contentType = request . getContentType ( ) ; final Lang format = contentTypeToLang ( contentType ) ; final Model inputModel ; try { inputModel = createDefaultModel ( ) ; reader = inputModel . getReader ( format . getName ( ) . toUpperCase ( ) ) ; reader . read ( inputModel , request . getInputStream ( ) , baseUri ) ; final Statement st = inputModel . getProperty ( null , MEMBERSHIP_RESOURCE ) ; return ( st != null ? URI . create ( st . getObject ( ) . toString ( ) ) : null ) ; } 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 ) ; } }
|
Get the memberRelation object from the contents .
|
1,319
|
private URI getHasMemberFromPatch ( final HttpServletRequest request ) throws IOException { final String sparqlString = IOUtils . toString ( request . getInputStream ( ) , UTF_8 ) ; final String baseURI = request . getRequestURL ( ) . toString ( ) . replace ( request . getContextPath ( ) , "" ) . replaceAll ( request . getPathInfo ( ) , "" ) . replaceAll ( "rest$" , "" ) ; final UpdateRequest sparqlUpdate = UpdateFactory . create ( sparqlString ) ; final Stream < Quad > insertDeleteData = sparqlUpdate . getOperations ( ) . stream ( ) . filter ( update -> update instanceof UpdateData ) . map ( update -> ( UpdateData ) update ) . flatMap ( update -> update . getQuads ( ) . stream ( ) ) ; final List < UpdateModify > updateModifyStream = sparqlUpdate . getOperations ( ) . stream ( ) . filter ( update -> ( update instanceof UpdateModify ) ) . peek ( update -> log . debug ( "Inspecting update statement for DELETE clause: {}" , update . toString ( ) ) ) . map ( update -> ( UpdateModify ) update ) . collect ( toList ( ) ) ; final Stream < Quad > insertQuadData = updateModifyStream . stream ( ) . flatMap ( update -> update . getInsertQuads ( ) . stream ( ) ) ; final Stream < Quad > deleteQuadData = updateModifyStream . stream ( ) . flatMap ( update -> update . getDeleteQuads ( ) . stream ( ) ) ; return Stream . concat ( Stream . concat ( insertDeleteData , insertQuadData ) , deleteQuadData ) . filter ( update -> update . getPredicate ( ) . equals ( MEMBERSHIP_RESOURCE . asNode ( ) ) && update . getObject ( ) . isURI ( ) ) . map ( update -> update . getObject ( ) . getURI ( ) ) . map ( update -> update . replace ( "file:///" , baseURI ) ) . findFirst ( ) . map ( URI :: create ) . orElse ( null ) ; }
|
Get the membershipRelation from a PATCH request
|
1,320
|
public static URI asURI ( final String algorithm , final String value ) { try { final String scheme = DIGEST_ALGORITHM . getScheme ( algorithm ) ; return new URI ( scheme , value , null ) ; } catch ( final URISyntaxException unlikelyException ) { LOGGER . warn ( "Exception creating checksum URI: {}" , unlikelyException ) ; throw new RepositoryRuntimeException ( unlikelyException ) ; } }
|
Convert a MessageDigest algorithm and checksum value to a URN
|
1,321
|
public static String getAlgorithm ( final URI digestUri ) { if ( digestUri == null ) { return DEFAULT_ALGORITHM ; } return DIGEST_ALGORITHM . fromScheme ( digestUri . getScheme ( ) + ":" + digestUri . getSchemeSpecificPart ( ) . split ( ":" , 2 ) [ 0 ] ) . algorithm ; }
|
Given a digest URI get the corresponding MessageDigest algorithm
|
1,322
|
private Node getMemberResource ( final FedoraResource parent ) throws RepositoryException { final Node membershipResource ; if ( parent . hasProperty ( LDP_MEMBER_RESOURCE ) ) { final Property memberResource = getJcrNode ( parent ) . getProperty ( LDP_MEMBER_RESOURCE ) ; if ( REFERENCE_TYPES . contains ( memberResource . getType ( ) ) ) { membershipResource = nodeConverter ( ) . convert ( memberResource . getNode ( ) ) . asNode ( ) ; } else { membershipResource = createURI ( memberResource . getString ( ) ) ; } } else { membershipResource = uriFor ( parent ) ; } return membershipResource ; }
|
Get the membership resource relation asserted by the container
|
1,323
|
public static javax . jcr . Node nodeForValue ( final Session session , final Value v ) throws RepositoryException { if ( v . getType ( ) == PATH ) { return session . getNode ( v . getString ( ) ) ; } else if ( v . getType ( ) == REFERENCE || v . getType ( ) == WEAKREFERENCE ) { return session . getNodeByIdentifier ( v . getString ( ) ) ; } else { throw new RepositoryRuntimeException ( "Cannot convert value of type " + PropertyType . nameFromValue ( v . getType ( ) ) + " to a node reference" ) ; } }
|
Get the node that a property value refers to .
|
1,324
|
public Map < String , Collection < String > > getRoles ( final Node node ) { return getAgentRoles ( nodeConverter . convert ( node ) ) ; }
|
Get the roles assigned to this Node .
|
1,325
|
private static Stream < String > getAgentMembers ( final IdentifierConverter < Resource , FedoraResource > translator , final FedoraResource resource , final String hashPortion ) { final List < Triple > triples = resource . getTriples ( translator , PROPERTIES ) . filter ( triple -> hashPortion == null || triple . getSubject ( ) . getURI ( ) . endsWith ( hashPortion ) ) . collect ( toList ( ) ) ; final boolean hasVcardGroup = triples . stream ( ) . anyMatch ( triple -> triple . matches ( triple . getSubject ( ) , RDF_TYPE_NODE , VCARD_GROUP_NODE ) ) ; if ( hasVcardGroup ) { return triples . stream ( ) . filter ( triple -> triple . predicateMatches ( VCARD_MEMBER_NODE ) ) . map ( Triple :: getObject ) . flatMap ( WebACRolesProvider :: nodeToStringStream ) . map ( WebACRolesProvider :: stripUserAgentBaseURI ) ; } else { return empty ( ) ; } }
|
Given a FedoraResource return a list of agents .
|
1,326
|
private static Stream < String > nodeToStringStream ( final org . apache . jena . graph . Node object ) { if ( object . isURI ( ) ) { return of ( object . getURI ( ) ) ; } else if ( object . isLiteral ( ) ) { return of ( object . getLiteralValue ( ) . toString ( ) ) ; } else { return empty ( ) ; } }
|
Map a Jena Node to a Stream of Strings . Any non - URI non - Literals map to an empty Stream making this suitable to use with flatMap .
|
1,327
|
static Optional < ACLHandle > getEffectiveAcl ( final FedoraResource resource , final boolean ancestorAcl , final SessionFactory sessionFactory ) { try { final FedoraResource aclResource = resource . getAcl ( ) ; if ( aclResource != null ) { final List < WebACAuthorization > authorizations = getAuthorizations ( aclResource , ancestorAcl , sessionFactory ) ; if ( authorizations . size ( ) > 0 ) { return Optional . of ( new ACLHandle ( resource , authorizations ) ) ; } } if ( getJcrNode ( resource ) . getDepth ( ) == 0 ) { LOGGER . debug ( "No ACLs defined on this node or in parent hierarchy" ) ; return Optional . empty ( ) ; } else { LOGGER . trace ( "Checking parent resource for ACL. No ACL found at {}" , resource . getPath ( ) ) ; return getEffectiveAcl ( resource . getContainer ( ) , true , sessionFactory ) ; } } catch ( final RepositoryException ex ) { LOGGER . debug ( "Exception finding effective ACL: {}" , ex . getMessage ( ) ) ; return Optional . empty ( ) ; } }
|
Recursively find the effective ACL as a URI along with the FedoraResource that points to it . This way if the effective ACL is pointed to from a parent resource the child will inherit any permissions that correspond to access to that parent . This ACL resource may or may not exist and it may be external to the fedora repository .
|
1,328
|
public Response runRestore ( final InputStream bodyStream ) throws IOException { if ( null == bodyStream ) { throw new WebApplicationException ( serverError ( ) . entity ( "Request body must not be null" ) . build ( ) ) ; } final String body = IOUtils . toString ( bodyStream ) ; final File backupDirectory = new File ( body . trim ( ) ) ; if ( ! backupDirectory . exists ( ) ) { throw new WebApplicationException ( serverError ( ) . entity ( "Backup directory does not exist: " + backupDirectory . getAbsolutePath ( ) ) . build ( ) ) ; } final Collection < Throwable > problems = repositoryService . restoreRepository ( session . getFedoraSession ( ) , backupDirectory ) ; if ( ! problems . isEmpty ( ) ) { LOGGER . error ( "Problems restoring up the repository:" ) ; final String problemsOutput = problems . stream ( ) . map ( Throwable :: getMessage ) . peek ( LOGGER :: error ) . collect ( joining ( "\n" ) ) ; throw new WebApplicationException ( serverError ( ) . entity ( problemsOutput ) . build ( ) ) ; } return noContent ( ) . header ( "Warning" , "This endpoint will be moving to an extension module in a future release of Fedora" ) . build ( ) ; }
|
This method runs a repository restore .
|
1,329
|
public PreferTag getReturn ( ) { return preferTags ( ) . stream ( ) . filter ( x -> x . getTag ( ) . equals ( "return" ) ) . findFirst ( ) . orElse ( emptyTag ( ) ) ; }
|
Get the return tag or a blank default if none exists .
|
1,330
|
public void addResponseHeaders ( final HttpServletResponse servletResponse ) { final String receivedParam = ofNullable ( params . get ( "received" ) ) . orElse ( "" ) ; final List < String > includes = asList ( ofNullable ( params . get ( "include" ) ) . orElse ( " " ) . split ( " " ) ) ; final List < String > omits = asList ( ofNullable ( params . get ( "omit" ) ) . orElse ( " " ) . split ( " " ) ) ; final StringBuilder includeBuilder = new StringBuilder ( ) ; final StringBuilder omitBuilder = new StringBuilder ( ) ; if ( ! ( value . equals ( "minimal" ) || receivedParam . equals ( "minimal" ) ) ) { final List < String > appliedPrefs = asList ( PREFER_SERVER_MANAGED . toString ( ) , LDP_NAMESPACE + "PreferMinimalContainer" , LDP_NAMESPACE + "PreferMembership" , LDP_NAMESPACE + "PreferContainment" ) ; final List < String > includePrefs = asList ( EMBED_CONTAINED . toString ( ) , INBOUND_REFERENCES . toString ( ) ) ; includes . forEach ( param -> includeBuilder . append ( ( appliedPrefs . contains ( param ) || includePrefs . contains ( param ) ) ? param + " " : "" ) ) ; omits . forEach ( param -> omitBuilder . append ( ( appliedPrefs . contains ( param ) && ! includes . contains ( param ) ) ? param + " " : "" ) ) ; } final String appliedReturn = value . equals ( "minimal" ) ? "return=minimal" : "return=representation" ; final String appliedReceived = receivedParam . equals ( "minimal" ) ? "received=minimal" : "" ; final StringBuilder preferenceAppliedBuilder = new StringBuilder ( appliedReturn ) ; preferenceAppliedBuilder . append ( appliedReceived . length ( ) > 0 ? "; " + appliedReceived : "" ) ; appendHeaderParam ( preferenceAppliedBuilder , "include" , includeBuilder . toString ( ) . trim ( ) ) ; appendHeaderParam ( preferenceAppliedBuilder , "omit" , omitBuilder . toString ( ) . trim ( ) ) ; servletResponse . addHeader ( "Preference-Applied" , preferenceAppliedBuilder . toString ( ) . trim ( ) ) ; servletResponse . addHeader ( "Vary" , "Prefer" ) ; }
|
Add appropriate response headers to indicate that the incoming preferences were acknowledged
|
1,331
|
public void publishJCREvent ( final FedoraEvent fedoraEvent ) throws JMSException { LOGGER . debug ( "Received an event from the internal bus." ) ; final Message tm = eventFactory . getMessage ( fedoraEvent , jmsSession ) ; LOGGER . debug ( "Transformed the event to a JMS message." ) ; producer . send ( tm ) ; LOGGER . debug ( "Put event: {} onto JMS." , tm . getJMSMessageID ( ) ) ; }
|
When an EventBus mesage is received map it to our JMS message payload and push it onto the queue .
|
1,332
|
public void acquireConnections ( ) throws JMSException { LOGGER . debug ( "Initializing: {}" , this . getClass ( ) . getCanonicalName ( ) ) ; connection = connectionFactory . createConnection ( ) ; connection . start ( ) ; jmsSession = connection . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; producer = jmsSession . createProducer ( createDestination ( ) ) ; eventBus . register ( this ) ; }
|
Connect to JCR Repostory and JMS queue
|
1,333
|
public void releaseConnections ( ) throws JMSException { LOGGER . debug ( "Tearing down: {}" , this . getClass ( ) . getCanonicalName ( ) ) ; producer . close ( ) ; jmsSession . close ( ) ; connection . close ( ) ; eventBus . unregister ( this ) ; }
|
Close external connections
|
1,334
|
public Long getRepositorySize ( ) { try { LOGGER . debug ( "Calculating repository size from index" ) ; final Repository repo = getJcrRepository ( repository ) ; return ServiceHelpers . getRepositorySize ( repo ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
|
Calculate the total size of all the binary properties in the repository
|
1,335
|
public FedoraResource getResourceFromPath ( final String externalPath ) { final Resource resource = translator ( ) . toDomain ( externalPath ) ; final FedoraResource fedoraResource = translator ( ) . convert ( resource ) ; if ( fedoraResource instanceof Tombstone ) { final String resourceURI = TRAILING_SLASH_REGEX . matcher ( resource . getURI ( ) ) . replaceAll ( "" ) ; throw new TombstoneException ( fedoraResource , resourceURI + "/fcr:tombstone" ) ; } return fedoraResource ; }
|
Get the FedoraResource for the resource at the external path
|
1,336
|
protected void setUpJMSInfo ( final UriInfo uriInfo , final HttpHeaders headers ) { try { String baseURL = getBaseUrlProperty ( uriInfo ) ; if ( baseURL . length ( ) == 0 ) { baseURL = uriInfo . getBaseUri ( ) . toString ( ) ; } LOGGER . debug ( "setting baseURL = " + baseURL ) ; session . getFedoraSession ( ) . addSessionData ( BASE_URL , baseURL ) ; if ( ! StringUtils . isBlank ( headers . getHeaderString ( "user-agent" ) ) ) { session . getFedoraSession ( ) . addSessionData ( USER_AGENT , headers . getHeaderString ( "user-agent" ) ) ; } } catch ( final Exception ex ) { LOGGER . warn ( "Error setting baseURL" , ex . getMessage ( ) ) ; } }
|
Set the baseURL for JMS events .
|
1,337
|
public static RdfStream fromModel ( final Node node , final Model model ) { return new DefaultRdfStream ( node , stream ( spliteratorUnknownSize ( model . listStatements ( ) , IMMUTABLE ) , false ) . map ( Statement :: asTriple ) ) ; }
|
Create an RdfStream from an existing Model .
|
1,338
|
public static Converter < Node , Resource > nodeToResource ( final Converter < Resource , FedoraResource > c ) { return nodeConverter . andThen ( c . reverse ( ) ) ; }
|
Get a converter that can transform a Node to a Resource
|
1,339
|
private void monitorForChanges ( ) { if ( monitorRunning ) { return ; } final Path path ; try { path = Paths . get ( configPath ) ; } catch ( final Exception e ) { LOGGER . warn ( "Cannot monitor configuration {}, disabling monitoring; {}" , configPath , e . getMessage ( ) ) ; return ; } if ( ! path . toFile ( ) . exists ( ) ) { LOGGER . debug ( "Configuration {} does not exist, disabling monitoring" , configPath ) ; return ; } final Path directoryPath = path . getParent ( ) ; try { final WatchService watchService = FileSystems . getDefault ( ) . newWatchService ( ) ; directoryPath . register ( watchService , ENTRY_MODIFY ) ; monitorThread = new Thread ( new Runnable ( ) { public void run ( ) { try { for ( ; ; ) { final WatchKey key ; try { key = watchService . take ( ) ; } catch ( final InterruptedException e ) { LOGGER . debug ( "Interrupted the configuration monitor thread." ) ; break ; } for ( final WatchEvent < ? > event : key . pollEvents ( ) ) { final WatchEvent . Kind < ? > kind = event . kind ( ) ; if ( kind == OVERFLOW ) { continue ; } final Path changed = ( Path ) event . context ( ) ; if ( changed . equals ( path . getFileName ( ) ) ) { LOGGER . info ( "Configuration {} has been updated, reloading." , path ) ; try { loadConfiguration ( ) ; } catch ( final IOException e ) { LOGGER . error ( "Failed to reload configuration {}" , configPath , e ) ; } } final boolean valid = key . reset ( ) ; if ( ! valid ) { LOGGER . debug ( "Monitor of {} is no longer valid" , path ) ; break ; } } } } finally { try { watchService . close ( ) ; } catch ( final IOException e ) { LOGGER . error ( "Failed to stop configuration monitor" , e ) ; } } monitorRunning = false ; } } ) ; } catch ( final IOException e ) { LOGGER . error ( "Failed to start configuration monitor" , e ) ; } monitorThread . start ( ) ; monitorRunning = true ; }
|
Starts up monitoring of the configuration for changes .
|
1,340
|
public void setConfigPath ( final String configPath ) { if ( configPath != null && configPath . startsWith ( "classpath:" ) ) { final String relativePath = configPath . substring ( 10 ) ; this . configPath = this . getClass ( ) . getResource ( relativePath ) . getPath ( ) ; } else { this . configPath = configPath ; } }
|
Set the file path for the configuration
|
1,341
|
public String get ( ) { final String s = randomUUID ( ) . toString ( ) ; final String id ; if ( count > 0 && length > 0 ) { final StringJoiner joiner = new StringJoiner ( "/" , "" , "/" + s ) ; IntStream . rangeClosed ( 0 , count - 1 ) . forEach ( x -> joiner . add ( s . substring ( x * length , ( x + 1 ) * length ) ) ) ; id = joiner . toString ( ) ; } else { id = s ; } return id ; }
|
Mint a unique identifier as a UUID
|
1,342
|
public FedoraResource find ( final FedoraSession session , final String path ) { final Session jcrSession = getJcrSession ( session ) ; try { return new FedoraResourceImpl ( jcrSession . getNode ( path ) ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
|
Retrieve an existing Fedora resource at the given path
|
1,343
|
public void copyObject ( final FedoraSession session , final String source , final String destination ) { final Session jcrSession = getJcrSession ( session ) ; try { jcrSession . getWorkspace ( ) . copy ( source , destination ) ; touchLdpMembershipResource ( getJcrNode ( find ( session , destination ) ) ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
|
Copy an existing object from the source path to the destination path
|
1,344
|
public void moveObject ( final FedoraSession session , final String source , final String destination ) { final Session jcrSession = getJcrSession ( session ) ; try { final FedoraResource srcResource = find ( session , source ) ; final Node sourceNode = getJcrNode ( srcResource ) ; final String name = sourceNode . getName ( ) ; final Node parent = sourceNode . getDepth ( ) > 0 ? sourceNode . getParent ( ) : null ; jcrSession . getWorkspace ( ) . move ( source , destination ) ; if ( parent != null ) { createTombstone ( parent , name ) ; } touchLdpMembershipResource ( getJcrNode ( find ( session , source ) ) ) ; touchLdpMembershipResource ( getJcrNode ( find ( session , destination ) ) ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
|
Move an existing object from the source path to the destination path
|
1,345
|
private javax . jcr . Binary getBinaryContent ( ) { try { return getProperty ( JCR_DATA ) . getBinary ( ) ; } catch ( final PathNotFoundException e ) { throw new PathNotFoundRuntimeException ( e ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
|
Retrieve the JCR Binary object
|
1,346
|
private void verifyChecksums ( final Collection < URI > checksums , final Property dataProperty ) throws InvalidChecksumException { final Map < URI , URI > checksumErrors = new HashMap < > ( ) ; checksums . forEach ( checksum -> { final String algorithm = ContentDigest . getAlgorithm ( checksum ) ; try { if ( algorithm . equals ( SHA1 . algorithm ) ) { final String dsSHA1 = ( ( Binary ) dataProperty . getBinary ( ) ) . getHexHash ( ) ; final URI dsSHA1Uri = ContentDigest . asURI ( SHA1 . algorithm , dsSHA1 ) ; if ( ! dsSHA1Uri . equals ( checksum ) ) { LOGGER . debug ( "Failed checksum test" ) ; checksumErrors . put ( checksum , dsSHA1Uri ) ; } } else { final CacheEntry cacheEntry = CacheEntryFactory . forProperty ( dataProperty ) ; cacheEntry . checkFixity ( algorithm ) . stream ( ) . findFirst ( ) . ifPresent ( fixityResult -> { if ( ! fixityResult . matches ( checksum ) ) { LOGGER . debug ( "Failed checksum test" ) ; checksumErrors . put ( checksum , fixityResult . getComputedChecksum ( ) ) ; } } ) ; } } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } } ) ; if ( ! checksumErrors . isEmpty ( ) ) { final String template = "Checksum Mismatch of %1$s and %2$s\n" ; final StringBuilder error = new StringBuilder ( ) ; checksumErrors . forEach ( ( key , value ) -> error . append ( String . format ( template , key , value ) ) ) ; throw new InvalidChecksumException ( error . toString ( ) ) ; } }
|
This method ensures that the arg checksums are valid against the binary associated with the arg dataProperty . If one or more of the checksums are invalid an InvalidChecksumException is thrown .
|
1,347
|
private static void decorateContentNode ( final Node dsNode , final Node descNode , final Collection < URI > checksums ) throws RepositoryException { if ( dsNode == null ) { LOGGER . warn ( "{} node appears to be null!" , JCR_CONTENT ) ; return ; } if ( dsNode . hasProperty ( JCR_DATA ) ) { final Property dataProperty = dsNode . getProperty ( JCR_DATA ) ; final Binary binary = ( Binary ) dataProperty . getBinary ( ) ; final String dsChecksum = binary . getHexHash ( ) ; checksums . add ( ContentDigest . asURI ( SHA1 . algorithm , dsChecksum ) ) ; final String [ ] checksumArray = new String [ checksums . size ( ) ] ; checksums . stream ( ) . map ( Object :: toString ) . collect ( Collectors . toSet ( ) ) . toArray ( checksumArray ) ; if ( descNode != null ) { descNode . setProperty ( CONTENT_DIGEST , checksumArray ) ; descNode . setProperty ( CONTENT_SIZE , dataProperty . getLength ( ) ) ; } LOGGER . debug ( "Decorated data property at path: {}" , dataProperty . getPath ( ) ) ; } }
|
Add necessary information to node
|
1,348
|
private Stream < Triple > memberRelations ( final FedoraResource container ) throws RepositoryException { final org . apache . jena . graph . Node memberRelation ; if ( container . hasProperty ( LDP_HAS_MEMBER_RELATION ) ) { final Property property = getJcrNode ( container ) . getProperty ( LDP_HAS_MEMBER_RELATION ) ; memberRelation = createURI ( property . getString ( ) ) ; } else if ( container . hasType ( LDP_BASIC_CONTAINER ) ) { memberRelation = LDP_MEMBER . asNode ( ) ; } else { return empty ( ) ; } final String insertedContainerProperty ; if ( container . hasType ( LDP_INDIRECT_CONTAINER ) ) { if ( container . hasProperty ( LDP_INSERTED_CONTENT_RELATION ) ) { insertedContainerProperty = getJcrNode ( container ) . getProperty ( LDP_INSERTED_CONTENT_RELATION ) . getString ( ) ; } else { return empty ( ) ; } } else { insertedContainerProperty = MEMBER_SUBJECT . getURI ( ) ; } return container . getChildren ( ) . flatMap ( UncheckedFunction . uncheck ( child -> { final org . apache . jena . graph . Node childSubject = uriFor ( child . getDescribedResource ( ) ) ; if ( insertedContainerProperty . equals ( MEMBER_SUBJECT . getURI ( ) ) ) { return of ( create ( subject ( ) , memberRelation , childSubject ) ) ; } String insertedContentProperty = getPropertyNameFromPredicate ( getJcrNode ( resource ( ) ) , createResource ( insertedContainerProperty ) , null ) ; if ( child . hasProperty ( insertedContentProperty ) ) { } else if ( child . hasProperty ( getReferencePropertyName ( insertedContentProperty ) ) ) { insertedContentProperty = getReferencePropertyName ( insertedContentProperty ) ; } else { return empty ( ) ; } return iteratorToStream ( new PropertyValueIterator ( getJcrNode ( child ) . getProperty ( insertedContentProperty ) ) ) . map ( uncheck ( v -> create ( subject ( ) , memberRelation , new ValueConverter ( getJcrNode ( container ) . getSession ( ) , translator ( ) ) . convert ( v ) . asNode ( ) ) ) ) ; } ) ) ; }
|
Get the member relations assert on the subject by the given node
|
1,349
|
@ SuppressWarnings ( "unchecked" ) private Stream < FedoraResource > nodeToGoodChildren ( final Node input ) throws RepositoryException { return iteratorToStream ( input . getNodes ( ) ) . filter ( nastyChildren . negate ( ) ) . flatMap ( uncheck ( ( final Node child ) -> child . isNodeType ( FEDORA_PAIRTREE ) ? nodeToGoodChildren ( child ) : of ( nodeConverter . convert ( child ) ) ) ) ; }
|
Get the good children for a node by skipping all pairtree nodes in the way .
|
1,350
|
private static Stream < FedoraResource > getAllChildren ( final FedoraResource resource ) { return concat ( of ( resource ) , resource . getChildren ( ) . flatMap ( FedoraResourceImpl :: getAllChildren ) ) ; }
|
Get all children recursively and flatten into a single Stream .
|
1,351
|
public void touch ( final boolean includeMembershipResource , final Calendar createdDate , final String createdUser , final Calendar modifiedDate , final String modifyingUser ) throws RepositoryException { FedoraTypesUtils . touch ( getNode ( ) , createdDate , createdUser , modifiedDate , modifyingUser ) ; if ( includeMembershipResource ) { touchLdpMembershipResource ( getNode ( ) , modifiedDate , modifyingUser ) ; } }
|
Touches a resource to ensure that the implicitly updated properties are updated if not explicitly set .
|
1,352
|
protected static Function < Triple , Triple > convertMementoReferences ( final IdentifierConverter < Resource , FedoraResource > translator , final IdentifierConverter < Resource , FedoraResource > internalTranslator ) { return t -> { final String subjectURI = t . getSubject ( ) . getURI ( ) ; final String subjectPath ; final int hashIndex = subjectURI . indexOf ( "#" ) ; if ( hashIndex != - 1 ) { subjectPath = subjectURI . substring ( 0 , hashIndex ) ; } else { subjectPath = subjectURI ; } final Resource subject = createResource ( subjectPath ) ; final FedoraResource subjResc = translator . convert ( subject ) ; org . apache . jena . graph . Node subjectNode = translator . reverse ( ) . convert ( subjResc . getOriginalResource ( ) ) . asNode ( ) ; if ( hashIndex != - 1 ) { subjectNode = createURI ( subjectNode . getURI ( ) + subjectURI . substring ( hashIndex ) ) ; } org . apache . jena . graph . Node objectNode = t . getObject ( ) ; if ( t . getObject ( ) . isURI ( ) ) { final Resource object = createResource ( t . getObject ( ) . getURI ( ) ) ; if ( internalTranslator . inDomain ( object ) ) { final FedoraResource objResc = internalTranslator . convert ( object ) ; final Resource newObject = translator . reverse ( ) . convert ( objResc ) ; objectNode = newObject . asNode ( ) ; } } return new Triple ( subjectNode , t . getPredicate ( ) , objectNode ) ; } ; }
|
Returns a function that converts the subject to the original URI and the object of a triple from an undereferenceable internal identifier back to it s original external resource path . If the object is not an internal identifier the object is returned .
|
1,353
|
private static long dateTimeDifference ( final Temporal d1 , final Temporal d2 ) { return ChronoUnit . SECONDS . between ( d1 , d2 ) ; }
|
Calculate the difference between two datetime to the unit .
|
1,354
|
public void validate ( final String extPath ) throws ExternalMessageBodyException { if ( allowedList == null || allowedList . size ( ) == 0 ) { throw new ExternalMessageBodyException ( "External content is disallowed by the server" ) ; } if ( isEmpty ( extPath ) ) { throw new ExternalMessageBodyException ( "External content path was empty" ) ; } final String path = normalizePath ( extPath . toLowerCase ( ) ) ; final URI uri ; try { uri = new URI ( path ) ; uri . toURL ( ) ; } catch ( final Exception e ) { throw new ExternalMessageBodyException ( "Path was not a valid URI: " + extPath ) ; } final String decodedPath = uri . getPath ( ) ; if ( RELATIVE_MOD_PATTERN . matcher ( decodedPath ) . matches ( ) ) { throw new ExternalMessageBodyException ( "Path was not absolute: " + extPath ) ; } if ( ! uri . isAbsolute ( ) ) { throw new ExternalMessageBodyException ( "Path was not absolute: " + extPath ) ; } final String scheme = uri . getScheme ( ) ; if ( ! ALLOWED_SCHEMES . contains ( scheme ) ) { throw new ExternalMessageBodyException ( "Path did not provide an allowed scheme: " + extPath ) ; } if ( scheme . equals ( "file" ) && ! Paths . get ( uri ) . toFile ( ) . exists ( ) ) { throw new ExternalMessageBodyException ( "Path did not match any allowed external content paths: " + extPath ) ; } if ( allowedList . stream ( ) . anyMatch ( allowed -> path . startsWith ( allowed ) ) ) { return ; } throw new ExternalMessageBodyException ( "Path did not match any allowed external content paths: " + extPath ) ; }
|
Validates that an external path is valid . The path must be an HTTP or file URI within the allow list of paths be absolute and contain no relative modifier .
|
1,355
|
protected synchronized void loadConfiguration ( ) throws IOException { LOGGER . info ( "Loading list of allowed external content locations from {}" , configPath ) ; try ( final Stream < String > stream = Files . lines ( Paths . get ( configPath ) ) ) { allowedList = stream . map ( line -> normalizePath ( line . trim ( ) . toLowerCase ( ) ) ) . filter ( line -> isAllowanceValid ( line ) ) . collect ( Collectors . toList ( ) ) ; } }
|
Loads the allowed list .
|
1,356
|
public static void validatePath ( final Session session , final String path ) { final NamespaceRegistry namespaceRegistry = getNamespaceRegistry ( session ) ; final String [ ] pathSegments = path . replaceAll ( "^/+" , "" ) . replaceAll ( "/+$" , "" ) . split ( "/" ) ; for ( final String segment : pathSegments ) { final int colonPosition = segment . indexOf ( ':' ) ; if ( segment . length ( ) > 0 && colonPosition > - 1 ) { final String prefix = segment . substring ( 0 , colonPosition ) ; if ( ! prefix . equals ( "fedora" ) && ! prefix . equals ( "fcr" ) ) { if ( prefix . length ( ) == 0 ) { throw new FedoraInvalidNamespaceException ( "Empty namespace in " + segment ) ; } try { namespaceRegistry . getURI ( prefix ) ; } catch ( final NamespaceException e ) { throw new FedoraInvalidNamespaceException ( "Prefix " + prefix + " has not been registered" , e ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } } } } }
|
Validate resource path for unregistered namespace prefixes
|
1,357
|
public static Map < String , String > getNamespaces ( final Session session ) { final NamespaceRegistry registry = getNamespaceRegistry ( session ) ; final Map < String , String > namespaces = new HashMap < > ( ) ; try { stream ( registry . getPrefixes ( ) ) . filter ( internalPrefix . negate ( ) ) . forEach ( x -> { try { namespaces . put ( x , registry . getURI ( x ) ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } } ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } return namespaces ; }
|
Retrieve the namespaces as a Map
|
1,358
|
private static Map < String , String > filterNamespacesToPresent ( final Model model , final Map < String , String > nsPrefixes ) { final Map < String , String > resultNses = new HashMap < > ( ) ; final Set < Entry < String , String > > nsSet = nsPrefixes . entrySet ( ) ; final NsIterator nsIt = model . listNameSpaces ( ) ; while ( nsIt . hasNext ( ) ) { final String ns = nsIt . next ( ) ; final Optional < Entry < String , String > > nsOpt = nsSet . stream ( ) . filter ( nsEntry -> nsEntry . getValue ( ) . equals ( ns ) ) . findFirst ( ) ; if ( nsOpt . isPresent ( ) ) { final Entry < String , String > nsMatch = nsOpt . get ( ) ; resultNses . put ( nsMatch . getKey ( ) , nsMatch . getValue ( ) ) ; } } return resultNses ; }
|
Filters the map of namespace prefix mappings to just those containing namespace URIs present in the model
|
1,359
|
public Response runBackup ( final InputStream bodyStream ) throws IOException { File backupDirectory ; if ( null != bodyStream ) { final String body = IOUtils . toString ( bodyStream ) . trim ( ) ; backupDirectory = new File ( body . trim ( ) ) ; if ( body . isEmpty ( ) ) { backupDirectory = createTempDir ( ) ; } else if ( ! backupDirectory . exists ( ) || ! backupDirectory . canWrite ( ) ) { throw new WebApplicationException ( serverError ( ) . entity ( "Backup directory does not exist or is not writable: " + backupDirectory . getAbsolutePath ( ) ) . build ( ) ) ; } } else { backupDirectory = createTempDir ( ) ; } LOGGER . debug ( "Backing up to: {}" , backupDirectory . getAbsolutePath ( ) ) ; final Collection < Throwable > problems = repositoryService . backupRepository ( session . getFedoraSession ( ) , backupDirectory ) ; if ( ! problems . isEmpty ( ) ) { LOGGER . error ( "Problems backing up the repository:" ) ; final String output = problems . stream ( ) . map ( Throwable :: getMessage ) . peek ( LOGGER :: error ) . collect ( joining ( "\n" ) ) ; throw new WebApplicationException ( serverError ( ) . entity ( output ) . build ( ) ) ; } return ok ( ) . header ( "Warning" , "This endpoint will be moving to an extension module in a future release of Fedora" ) . entity ( backupDirectory . getCanonicalPath ( ) ) . build ( ) ; }
|
This method runs a repository backup .
|
1,360
|
protected synchronized void loadConfiguration ( ) throws IOException { final ObjectMapper mapper = new ObjectMapper ( new YAMLFactory ( ) ) ; final TypeReference < HashMap < String , String > > typeRef = new TypeReference < HashMap < String , String > > ( ) { } ; namespaces = mapper . readValue ( new File ( configPath ) , typeRef ) ; }
|
Load the namespace prefix to URI configuration file
|
1,361
|
private FedoraResource getResourceFromSubject ( final String subjectUri ) { final UriTemplate uriTemplate = new UriTemplate ( uriInfo . getBaseUriBuilder ( ) . clone ( ) . path ( FedoraLdp . class ) . toTemplate ( ) ) ; final Map < String , String > values = new HashMap < > ( ) ; uriTemplate . match ( subjectUri , values ) ; if ( values . containsKey ( "path" ) ) { try { return translator ( ) . convert ( translator ( ) . toDomain ( values . get ( "path" ) ) ) ; } catch ( final RuntimeException e ) { if ( e . getCause ( ) instanceof PathNotFoundException ) { return null ; } else { throw e ; } } } return null ; }
|
Get a FedoraResource for the subject of the graph if it exists .
|
1,362
|
public void buildRepository ( ) { try { LOGGER . info ( "Using repo config (classpath): {}" , repositoryConfiguration . getURL ( ) ) ; getPropertiesLoader ( ) . loadSystemProperties ( ) ; final RepositoryConfiguration config = RepositoryConfiguration . read ( repositoryConfiguration . getURL ( ) ) ; repository = modeShapeEngine . deploy ( config ) ; final org . modeshape . common . collection . Problems problems = repository . getStartupProblems ( ) ; for ( final org . modeshape . common . collection . Problem p : problems ) { LOGGER . error ( "ModeShape Start Problem: {}" , p . getMessageString ( ) ) ; } } catch ( final Exception e ) { throw new RepositoryRuntimeException ( e ) ; } }
|
Generate a JCR repository from the given configuration
|
1,363
|
public void stopRepository ( ) throws InterruptedException { LOGGER . info ( "Initiating shutdown of ModeShape" ) ; final String repoName = repository . getName ( ) ; try { final Future < Boolean > futureUndeployRepo = modeShapeEngine . undeploy ( repoName ) ; if ( futureUndeployRepo . get ( ) ) { LOGGER . info ( "ModeShape repository {} has undeployed." , repoName ) ; } else { LOGGER . error ( "ModeShape repository {} undeploy failed without an exception, still deployed." , repoName ) ; } LOGGER . info ( "Repository {} undeployed." , repoName ) ; } catch ( final NoSuchRepositoryException e ) { LOGGER . error ( "Repository {} unknown, cannot undeploy." , repoName , e ) ; } catch ( final ExecutionException e ) { LOGGER . error ( "Repository {} cannot undeploy." , repoName , e . getCause ( ) ) ; } final Future < Boolean > futureShutdownEngine = modeShapeEngine . shutdown ( ) ; try { if ( futureShutdownEngine . get ( ) ) { LOGGER . info ( "ModeShape Engine has shutdown." ) ; } else { LOGGER . error ( "ModeShape Engine shutdown failed without an exception, still running." ) ; } } catch ( final ExecutionException e ) { LOGGER . error ( "ModeShape Engine shutdown failed." , e . getCause ( ) ) ; } }
|
Attempts to undeploy the repository and shutdown the ModeShape engine on context destroy .
|
1,364
|
private static Long getNodePropertySize ( final Node node ) throws RepositoryException { Long size = 0L ; for ( final PropertyIterator i = node . getProperties ( ) ; i . hasNext ( ) ; ) { final Property p = i . nextProperty ( ) ; if ( p . isMultiple ( ) ) { for ( final Value v : p . getValues ( ) ) { size += v . getBinary ( ) . getSize ( ) ; } } else { size += p . getBinary ( ) . getSize ( ) ; } } return size ; }
|
Get the total size of a Node s properties
|
1,365
|
private static Long getContentSize ( final Node ds ) { try { long size = 0L ; if ( ds . hasNode ( JCR_CONTENT ) ) { final Node contentNode = ds . getNode ( JCR_CONTENT ) ; if ( contentNode . hasProperty ( JCR_DATA ) ) { size = ds . getNode ( JCR_CONTENT ) . getProperty ( JCR_DATA ) . getBinary ( ) . getSize ( ) ; } } return size ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } }
|
Get the size of the JCR content binary property
|
1,366
|
public Response createTransaction ( @ PathParam ( "path" ) final String externalPath ) throws URISyntaxException { if ( batchService . exists ( session . getId ( ) , getUserPrincipal ( ) ) ) { LOGGER . debug ( "renewing transaction {}" , session . getId ( ) ) ; batchService . refresh ( session . getId ( ) , getUserPrincipal ( ) ) ; final Response . ResponseBuilder res = noContent ( ) ; session . getFedoraSession ( ) . getExpires ( ) . ifPresent ( expires -> { res . expires ( from ( expires ) ) ; } ) ; return res . build ( ) ; } if ( externalPath != null && ! externalPath . isEmpty ( ) ) { return status ( BAD_REQUEST ) . build ( ) ; } batchService . begin ( session . getFedoraSession ( ) , getUserPrincipal ( ) ) ; session . makeBatchSession ( ) ; LOGGER . info ( "Created transaction '{}'" , session . getId ( ) ) ; final Response . ResponseBuilder res = created ( new URI ( translator ( ) . toDomain ( "/tx:" + session . getId ( ) ) . toString ( ) ) ) ; session . getFedoraSession ( ) . getExpires ( ) . ifPresent ( expires -> { res . expires ( from ( expires ) ) ; } ) ; return res . build ( ) ; }
|
Create a new transaction resource and add it to the registry
|
1,367
|
@ Path ( "fcr:commit" ) public Response commit ( @ PathParam ( "path" ) final String externalPath ) { LOGGER . info ( "Commit transaction '{}'" , externalPath ) ; return finalizeTransaction ( externalPath , getUserPrincipal ( ) , true ) ; }
|
Commit a transaction resource
|
1,368
|
@ Path ( "fcr:rollback" ) public Response rollback ( @ PathParam ( "path" ) final String externalPath ) { LOGGER . info ( "Rollback transaction '{}'" , externalPath ) ; return finalizeTransaction ( externalPath , getUserPrincipal ( ) , false ) ; }
|
Rollback a transaction
|
1,369
|
public static Session getJcrSession ( final FedoraSession session ) { if ( session instanceof FedoraSessionImpl ) { return ( ( FedoraSessionImpl ) session ) . getJcrSession ( ) ; } throw new ClassCastException ( "FedoraSession is not a " + FedoraSessionImpl . class . getCanonicalName ( ) ) ; }
|
Get the internal JCR session from an existing FedoraSession
|
1,370
|
public static Triple mapSubject ( final Triple t , final String resourceUri , final String destinationUri ) { final Node destinationNode = createURI ( destinationUri ) ; return mapSubject ( t , resourceUri , destinationNode ) ; }
|
Maps the subject of t from resourceUri to destinationUri to produce a new Triple . If the triple does not have the subject resourceUri then the triple is unchanged .
|
1,371
|
public static Triple mapSubject ( final Triple t , final String resourceUri , final Node destinationNode ) { final Node tripleSubj = t . getSubject ( ) ; final String tripleSubjUri = tripleSubj . getURI ( ) ; final Node subject ; if ( tripleSubjUri . equals ( resourceUri ) ) { subject = destinationNode ; } else if ( tripleSubjUri . startsWith ( resourceUri ) ) { final String suffix = tripleSubjUri . substring ( resourceUri . length ( ) ) ; subject = createURI ( destinationNode . getURI ( ) + suffix ) ; } else { subject = t . getSubject ( ) ; } return new Triple ( subject , t . getPredicate ( ) , t . getObject ( ) ) ; }
|
Maps the subject of t from resourceUri to destinationNode to produce a new Triple . If the triple does not have the subject resourceUri then the triple is unchanged .
|
1,372
|
public String serialize ( final FedoraEvent evt ) { try { final Model model = EventSerializer . toModel ( evt ) ; final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; model . write ( out , "TTL" ) ; return out . toString ( "UTF-8" ) ; } catch ( final UnsupportedEncodingException ex ) { throw new RepositoryRuntimeException ( ex ) ; } }
|
Serialize a FedoraEvent in RDF using Turtle syntax
|
1,373
|
public static Link buildConstraintLink ( final ConstraintViolationException e , final ServletContext context , final UriInfo uriInfo ) { String path = context . getContextPath ( ) ; if ( path . equals ( "/" ) ) { path = "" ; } final String constraintURI = uriInfo == null ? "" : String . format ( "%s://%s%s%s%s.rdf" , uriInfo . getBaseUri ( ) . getScheme ( ) , uriInfo . getBaseUri ( ) . getAuthority ( ) , path , CONSTRAINT_DIR , e . getClass ( ) . toString ( ) . substring ( e . getClass ( ) . toString ( ) . lastIndexOf ( '.' ) + 1 ) ) ; return Link . fromUri ( constraintURI ) . rel ( CONSTRAINED_BY . getURI ( ) ) . build ( ) ; }
|
Creates a constrainedBy link header with the appropriate RDF URL for the exception .
|
1,374
|
public static Optional < Integer > getPropertyType ( final Node node , final String propertyName ) throws RepositoryException { LOGGER . debug ( "Getting type of property: {} from node: {}" , propertyName , node ) ; return getDefinitionForPropertyName ( node , propertyName ) . map ( PropertyDefinition :: getRequiredType ) ; }
|
Get the JCR property type ID for a given property name . If unsure mark it as UNDEFINED .
|
1,375
|
public static String getReferencePropertyOriginalName ( final String refPropertyName ) { final int i = refPropertyName . lastIndexOf ( REFERENCE_PROPERTY_SUFFIX ) ; return i < 0 ? refPropertyName : refPropertyName . substring ( 0 , i ) ; }
|
Given an internal reference node property get the original name
|
1,376
|
public static boolean isReferenceProperty ( final Node node , final String propertyName ) throws RepositoryException { final Optional < PropertyDefinition > propertyDefinition = getDefinitionForPropertyName ( node , propertyName ) ; return propertyDefinition . isPresent ( ) && ( propertyDefinition . get ( ) . getRequiredType ( ) == REFERENCE || propertyDefinition . get ( ) . getRequiredType ( ) == WEAKREFERENCE ) ; }
|
Check if a property definition is a reference property
|
1,377
|
public static Node getClosestExistingAncestor ( final Session session , final String path ) throws RepositoryException { String potentialPath = path . startsWith ( "/" ) ? path : "/" + path ; while ( ! potentialPath . isEmpty ( ) ) { if ( session . nodeExists ( potentialPath ) ) { return session . getNode ( potentialPath ) ; } potentialPath = potentialPath . substring ( 0 , potentialPath . lastIndexOf ( '/' ) ) ; } return session . getRootNode ( ) ; }
|
Get the closest ancestor that current exists
|
1,378
|
public static Node getJcrNode ( final FedoraResource resource ) { if ( resource instanceof FedoraResourceImpl ) { return ( ( FedoraResourceImpl ) resource ) . getNode ( ) ; } throw new IllegalArgumentException ( "FedoraResource is of the wrong type" ) ; }
|
Retrieve the underlying JCR Node from the FedoraResource
|
1,379
|
public static Function < Resource , Optional < String > > resourceToProperty ( final Session session ) { return resource -> { try { final NamespaceRegistry registry = getNamespaceRegistry ( session ) ; return Optional . of ( registry . getPrefix ( resource . getNameSpace ( ) ) + ":" + resource . getLocalName ( ) ) ; } catch ( final RepositoryException ex ) { LOGGER . debug ( "Could not resolve resource namespace ({}): {}" , resource . toString ( ) , ex . getMessage ( ) ) ; } return empty ( ) ; } ; }
|
Using a JCR session return a function that maps an RDF Resource to a corresponding property name .
|
1,380
|
private static void touch ( final Node node , final Calendar modified , final String modifyingUser ) { touch ( node , null , null , modified , modifyingUser ) ; }
|
Updates the LAST_MODIFIED_DATE and LAST_MODIFIED_BY properties to the provided values .
|
1,381
|
public static void touch ( final Node node , final Calendar created , final String creatingUser , final Calendar modified , final String modifyingUser ) { try { if ( created != null ) { node . setProperty ( FEDORA_CREATED , created ) ; } if ( creatingUser != null ) { node . setProperty ( FEDORA_CREATEDBY , creatingUser ) ; } if ( modified != null ) { node . setProperty ( FEDORA_LASTMODIFIED , modified ) ; } else { node . setProperty ( FEDORA_LASTMODIFIED , getInstance ( getTimeZone ( "UTC" ) ) ) ; } if ( modifyingUser != null ) { node . setProperty ( FEDORA_LASTMODIFIEDBY , modifyingUser ) ; } else { if ( node . hasProperty ( FEDORA_LASTMODIFIEDBY ) ) { node . getProperty ( FEDORA_LASTMODIFIEDBY ) . remove ( ) ; } } } catch ( final javax . jcr . AccessDeniedException ex ) { throw new AccessDeniedException ( ex ) ; } catch ( final RepositoryException ex ) { throw new RepositoryRuntimeException ( ex ) ; } }
|
Updates the LAST_MODIFIED_DATE LAST_MODIFIED_BY CREATED_DATE and CREATED_BY properties to the provided values .
|
1,382
|
public static Optional < Node > getContainingNode ( final Node node ) { try { if ( node . getDepth ( ) == 0 ) { return empty ( ) ; } final Node parent = node . getParent ( ) ; if ( parent . isNodeType ( FEDORA_PAIRTREE ) || parent . isNodeType ( FEDORA_NON_RDF_SOURCE_DESCRIPTION ) ) { return getContainingNode ( parent ) ; } return Optional . of ( parent ) ; } catch ( final RepositoryException ex ) { throw new RepositoryRuntimeException ( ex ) ; } }
|
Get the JCR Node that corresponds to the containing node in the repository . This may be the direct parent node but it may also be a more distant ancestor .
|
1,383
|
public static EventType valueOf ( final Integer i ) { final EventType type = translation . get ( i ) ; if ( isNull ( type ) ) { throw new IllegalArgumentException ( "Invalid event type: " + i ) ; } return type ; }
|
Get the Fedora event type for a JCR type
|
1,384
|
public static FedoraEvent from ( final Event event ) { requireNonNull ( event ) ; try { @ SuppressWarnings ( "unchecked" ) final Map < String , String > info = new HashMap < > ( event . getInfo ( ) ) ; final String userdata = event . getUserData ( ) ; try { if ( userdata != null && ! userdata . isEmpty ( ) ) { final JsonNode json = MAPPER . readTree ( userdata ) ; if ( json . has ( BASE_URL ) ) { String url = json . get ( BASE_URL ) . asText ( ) ; while ( url . endsWith ( "/" ) ) { url = url . substring ( 0 , url . length ( ) - 1 ) ; } info . put ( BASE_URL , url ) ; } if ( json . has ( USER_AGENT ) ) { info . put ( USER_AGENT , json . get ( USER_AGENT ) . asText ( ) ) ; } } else { LOGGER . debug ( "Event UserData is empty!" ) ; } } catch ( final IOException ex ) { LOGGER . warn ( "Error extracting user data: " + userdata , ex . getMessage ( ) ) ; } final Set < String > resourceTypes = getResourceTypes ( event ) . collect ( toSet ( ) ) ; return new FedoraEventImpl ( valueOf ( event . getType ( ) ) , cleanPath ( event ) , resourceTypes , event . getUserID ( ) , FedoraSessionUserUtil . getUserURI ( event . getUserID ( ) ) , ofEpochMilli ( event . getDate ( ) ) , info ) ; } catch ( final RepositoryException ex ) { throw new RepositoryRuntimeException ( "Error converting JCR Event to FedoraEvent" , ex ) ; } }
|
Convert a JCR Event to a FedoraEvent
|
1,385
|
public static Stream < String > getResourceTypes ( final Event event ) { if ( event instanceof org . modeshape . jcr . api . observation . Event ) { try { final org . modeshape . jcr . api . observation . Event modeEvent = ( org . modeshape . jcr . api . observation . Event ) event ; final Stream . Builder < NodeType > types = Stream . builder ( ) ; for ( final NodeType type : modeEvent . getMixinNodeTypes ( ) ) { types . add ( type ) ; } types . add ( modeEvent . getPrimaryNodeType ( ) ) ; return types . build ( ) . map ( NodeType :: getName ) ; } catch ( final RepositoryException e ) { throw new RepositoryRuntimeException ( e ) ; } } return empty ( ) ; }
|
Get the RDF Types of the resource corresponding to this JCR Event
|
1,386
|
@ SuppressWarnings ( "resource" ) public InputStream retrieveExternalContent ( final URI sourceUri ) throws IOException { final HttpGet httpGet = new HttpGet ( sourceUri ) ; final CloseableHttpClient client = getCloseableHttpClient ( ) ; final HttpResponse response = client . execute ( httpGet ) ; return response . getEntity ( ) . getContent ( ) ; }
|
Retrieve the content at the URI using the global connection pool .
|
1,387
|
public static Object toBean ( JSONObject jsonObject ) { if ( jsonObject == null || jsonObject . isNullObject ( ) ) { return null ; } DynaBean dynaBean = null ; JsonConfig jsonConfig = new JsonConfig ( ) ; Map props = JSONUtils . getProperties ( jsonObject ) ; dynaBean = JSONUtils . newDynaBean ( jsonObject , jsonConfig ) ; for ( Iterator entries = jsonObject . names ( jsonConfig ) . iterator ( ) ; entries . hasNext ( ) ; ) { String name = ( String ) entries . next ( ) ; String key = JSONUtils . convertToJavaIdentifier ( name , jsonConfig ) ; Class type = ( Class ) props . get ( name ) ; Object value = jsonObject . get ( name ) ; try { if ( ! JSONUtils . isNull ( value ) ) { if ( value instanceof JSONArray ) { dynaBean . set ( key , JSONArray . toCollection ( ( JSONArray ) value ) ) ; } else if ( String . class . isAssignableFrom ( type ) || Boolean . class . isAssignableFrom ( type ) || JSONUtils . isNumber ( type ) || Character . class . isAssignableFrom ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { dynaBean . set ( key , value ) ; } else { dynaBean . set ( key , toBean ( ( JSONObject ) value ) ) ; } } else { if ( type . isPrimitive ( ) ) { log . warn ( "Tried to assign null value to " + key + ":" + type . getName ( ) ) ; dynaBean . set ( key , JSONUtils . getMorpherRegistry ( ) . morph ( type , null ) ) ; } else { dynaBean . set ( key , null ) ; } } } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( "Error while setting property=" + name + " type" + type , e ) ; } } return dynaBean ; }
|
Creates a JSONDynaBean from a JSONObject .
|
1,388
|
protected final String shaveOffNonJavaIdentifierStartChars ( String str ) { String str2 = str ; boolean ready = false ; while ( ! ready ) { if ( ! Character . isJavaIdentifierStart ( str2 . charAt ( 0 ) ) ) { str2 = str2 . substring ( 1 ) ; if ( str2 . length ( ) == 0 ) { throw new JSONException ( "Can't convert '" + str + "' to a valid Java identifier" ) ; } } else { ready = true ; } } return str2 ; }
|
Removes all non JavaIdentifier chars from the start of the string .
|
1,389
|
public JSON read ( String xml ) { JSON json = null ; try { Document doc = new Builder ( ) . build ( new StringReader ( xml ) ) ; Element root = doc . getRootElement ( ) ; if ( isNullObject ( root ) ) { return JSONNull . getInstance ( ) ; } String defaultType = getType ( root , JSONTypes . STRING ) ; if ( isArray ( root , true ) ) { json = processArrayElement ( root , defaultType ) ; if ( forceTopLevelObject ) { String key = removeNamespacePrefix ( root . getQualifiedName ( ) ) ; json = new JSONObject ( ) . element ( key , json ) ; } } else { json = processObjectElement ( root , defaultType ) ; if ( forceTopLevelObject ) { String key = removeNamespacePrefix ( root . getQualifiedName ( ) ) ; json = new JSONObject ( ) . element ( key , json ) ; } } } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( e ) ; } return json ; }
|
Creates a JSON value from a XML string .
|
1,390
|
public JSON readFromStream ( InputStream stream ) { try { StringBuffer xml = new StringBuffer ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( stream ) ) ; String line = null ; while ( ( line = in . readLine ( ) ) != null ) { xml . append ( line ) ; } return read ( xml . toString ( ) ) ; } catch ( IOException ioe ) { throw new JSONException ( ioe ) ; } }
|
Creates a JSON value from an input stream .
|
1,391
|
private boolean canAutoExpand ( JSONArray array ) { for ( int i = 0 ; i < array . size ( ) ; i ++ ) { if ( ! ( array . get ( i ) instanceof JSONObject ) ) { return false ; } } return true ; }
|
Only perform auto expansion if all children are objects .
|
1,392
|
public static String getFunctionBody ( String function ) { return RegexpUtils . getMatcher ( FUNCTION_BODY_PATTERN , true ) . getGroupIfMatches ( function , 1 ) ; }
|
Returns the body of a function literal .
|
1,393
|
public static String getFunctionParams ( String function ) { return RegexpUtils . getMatcher ( FUNCTION_PARAMS_PATTERN , true ) . getGroupIfMatches ( function , 1 ) ; }
|
Returns the params of a function literal .
|
1,394
|
public static Class getInnerComponentType ( Class type ) { if ( ! type . isArray ( ) ) { return type ; } return getInnerComponentType ( type . getComponentType ( ) ) ; }
|
Returns the inner - most component type of an Array .
|
1,395
|
public static Map getProperties ( JSONObject jsonObject ) { Map properties = new HashMap ( ) ; for ( Iterator keys = jsonObject . keys ( ) ; keys . hasNext ( ) ; ) { String key = ( String ) keys . next ( ) ; properties . put ( key , getTypeClass ( jsonObject . get ( key ) ) ) ; } return properties ; }
|
Creates a Map with all the properties of the JSONObject .
|
1,396
|
public static boolean isArray ( Class clazz ) { return clazz != null && ( clazz . isArray ( ) || Collection . class . isAssignableFrom ( clazz ) || ( JSONArray . class . isAssignableFrom ( clazz ) ) ) ; }
|
Tests if a Class represents an array or Collection .
|
1,397
|
public static boolean isArray ( Object obj ) { if ( ( obj != null && obj . getClass ( ) . isArray ( ) ) || ( obj instanceof Collection ) || ( obj instanceof JSONArray ) ) { return true ; } return false ; }
|
Tests if obj is an array or Collection .
|
1,398
|
public static boolean isBoolean ( Class clazz ) { return clazz != null && ( Boolean . TYPE . isAssignableFrom ( clazz ) || Boolean . class . isAssignableFrom ( clazz ) ) ; }
|
Tests if Class represents a Boolean or primitive boolean
|
1,399
|
public static boolean isBoolean ( Object obj ) { if ( ( obj instanceof Boolean ) || ( obj != null && obj . getClass ( ) == Boolean . TYPE ) ) { return true ; } return false ; }
|
Tests if obj is a Boolean or primitive boolean
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.