idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
4,200
public static String getAttribute ( Element el , String name ) { return el . hasAttribute ( name ) ? el . getAttribute ( name ) : "" ; }
Obtains the value of the given element attribute . This function fixes the difference in return values between the different DOM implementations .
4,201
public static TermLengthOrPercent createLengthOrPercent ( String spec ) { spec = spec . trim ( ) ; if ( spec . endsWith ( "%" ) ) { try { float val = Float . parseFloat ( spec . substring ( 0 , spec . length ( ) - 1 ) ) ; TermPercent perc = CSSFactory . getTermFactory ( ) . createPercent ( val ) ; return perc ; } catch ( NumberFormatException e ) { return null ; } } else { try { float val = Float . parseFloat ( spec ) ; TermLength len = CSSFactory . getTermFactory ( ) . createLength ( val , TermLength . Unit . px ) ; return len ; } catch ( NumberFormatException e ) { return null ; } } }
Creates a CSS length or percentage from a string .
4,202
private static void recursiveFindBadNodesInTable ( Node n , Node cellroot , Vector < Node > nodes ) { Node cell = cellroot ; if ( n . getNodeType ( ) == Node . ELEMENT_NODE ) { String tag = n . getNodeName ( ) ; if ( tag . equalsIgnoreCase ( "table" ) ) { if ( cell != null ) return ; } else if ( tag . equalsIgnoreCase ( "tbody" ) || tag . equalsIgnoreCase ( "thead" ) || tag . equalsIgnoreCase ( "tfoot" ) || tag . equalsIgnoreCase ( "tr" ) || tag . equalsIgnoreCase ( "col" ) || tag . equalsIgnoreCase ( "colgroup" ) ) { } else if ( tag . equalsIgnoreCase ( "td" ) || tag . equalsIgnoreCase ( "th" ) || tag . equalsIgnoreCase ( "caption" ) ) { cell = n ; } else { if ( cell == null ) { nodes . add ( n ) ; return ; } } } else if ( n . getNodeType ( ) == Node . TEXT_NODE ) { if ( cell == null && n . getNodeValue ( ) . trim ( ) . length ( ) > 0 ) { nodes . add ( n ) ; return ; } } NodeList child = n . getChildNodes ( ) ; for ( int i = 0 ; i < child . getLength ( ) ; i ++ ) recursiveFindBadNodesInTable ( child . item ( i ) , cell , nodes ) ; }
Finds all the nodes in a table that cannot be contained in the table according to the HTML syntax .
4,203
public String getMarkerText ( ) { String text ; if ( styleType == CSSProperty . ListStyleType . UPPER_ALPHA ) text = "" + ( ( char ) ( 64 + ( itemNumber % 24 ) ) ) ; else if ( styleType == CSSProperty . ListStyleType . LOWER_ALPHA ) text = "" + ( ( char ) ( 96 + ( itemNumber % 24 ) ) ) ; else if ( styleType == CSSProperty . ListStyleType . UPPER_ROMAN ) text = "" + binaryToRoman ( itemNumber ) ; else if ( styleType == CSSProperty . ListStyleType . LOWER_ROMAN ) text = "" + binaryToRoman ( itemNumber ) . toLowerCase ( ) ; else text = String . valueOf ( itemNumber ) ; return text + ". " ; }
Get ordered list item marker text depending on list - style - type property .
4,204
private int findItemNumber ( ) { ElementBox parent = getParent ( ) ; int cnt = 0 ; for ( int i = parent . getStartChild ( ) ; i < parent . getEndChild ( ) ; i ++ ) { Box child = parent . getSubBox ( i ) ; if ( child instanceof ListItemBox ) cnt ++ ; if ( child == this ) return cnt ; } return 1 ; }
Finds the item number . Currently this correspond to the number of list - item boxes before this box within the parent box .
4,205
public void drawMarker ( Graphics2D g ) { Shape oldclip = g . getClip ( ) ; if ( clipblock != null ) g . setClip ( applyClip ( oldclip , clipblock . getClippedContentBounds ( ) ) ) ; if ( image != null ) { if ( ! drawImage ( g ) ) drawBullet ( g ) ; } else drawBullet ( g ) ; g . setClip ( oldclip ) ; }
Draw the list item symbol number or image depending on list - style - type
4,206
protected void drawBullet ( Graphics2D g ) { ctx . updateGraphics ( g ) ; int x = ( int ) Math . round ( getAbsoluteContentX ( ) - 1.2 * ctx . getEm ( ) ) ; int y = ( int ) Math . round ( getAbsoluteContentY ( ) + 0.5 * ctx . getEm ( ) ) ; int r = ( int ) Math . round ( 0.4 * ctx . getEm ( ) ) ; if ( styleType == CSSProperty . ListStyleType . CIRCLE ) g . drawOval ( x , y , r , r ) ; else if ( styleType == CSSProperty . ListStyleType . SQUARE ) g . fillRect ( x , y , r , r ) ; else if ( styleType == CSSProperty . ListStyleType . DISC ) g . fillOval ( x , y , r , r ) ; else if ( styleType != CSSProperty . ListStyleType . NONE ) drawText ( g , getMarkerText ( ) ) ; }
Draws a bullet or text marker
4,207
protected boolean drawImage ( Graphics2D g ) { int ofs = getFirstInlineBoxBaseline ( ) ; if ( ofs == - 1 ) ofs = ctx . getBaselineOffset ( ) ; int x = ( int ) Math . round ( getAbsoluteContentX ( ) - 0.5 * ctx . getEm ( ) ) ; int y = getAbsoluteContentY ( ) + ofs ; Image img = image . getImage ( ) ; if ( img != null ) { int w = img . getWidth ( image ) ; int h = img . getHeight ( image ) ; g . drawImage ( img , x - w , y - h , image ) ; return true ; } else return false ; }
Draws an image marker
4,208
protected void drawText ( Graphics2D g , String text ) { int x = getAbsoluteContentX ( ) ; int y = getAbsoluteContentY ( ) ; FontMetrics fm = g . getFontMetrics ( ) ; Rectangle2D rect = fm . getStringBounds ( text , g ) ; int ofs = getFirstInlineBoxBaseline ( ) ; if ( ofs == - 1 ) ofs = ctx . getBaselineOffset ( ) ; g . drawString ( text , x + ( ( int ) rect . getX ( ) ) - ( ( int ) Math . round ( rect . getWidth ( ) ) ) , y + ofs ) ; }
Draws a text marker
4,209
protected URLConnection createConnection ( URL url ) throws IOException { URLConnection con = url . openConnection ( ) ; con . setRequestProperty ( "User-Agent" , USER_AGENT ) ; return con ; }
Creates and configures the URL connection .
4,210
public void dumpTo ( OutputStream out ) { PrintWriter writer ; try { writer = new PrintWriter ( new OutputStreamWriter ( out , "utf-8" ) ) ; } catch ( UnsupportedEncodingException e ) { writer = new PrintWriter ( out ) ; } recursiveDump ( root , 0 , writer ) ; writer . close ( ) ; }
Formats the complete tag tree to an output stream .
4,211
protected void repaint ( int t ) { if ( container != null ) { Rectangle bounds = owner . getAbsoluteBounds ( ) ; container . repaint ( t , bounds . x , bounds . y , bounds . width , bounds . height ) ; } }
Fires repaint event within t milliseconds .
4,212
public BufferedImage getBufferedImage ( ) { if ( image == null || abort ) return null ; if ( container == null ) waitForLoad ( ) ; BufferedImage img = new BufferedImage ( getIntrinsicWidth ( ) , getIntrinsicHeight ( ) , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D g = img . createGraphics ( ) ; g . drawImage ( image , null , null ) ; g . dispose ( ) ; return img ; }
Gets the loaded image as BufferedImage object . May return null if no data available .
4,213
public void reset ( ) { abort = false ; complete = false ; width = - 1 ; height = - 1 ; if ( image != null ) image . flush ( ) ; image = null ; }
Resets all data to default state releases the image resources .
4,214
public ResponseBuilder initialize ( final Resource parent , final Resource child ) { if ( MISSING_RESOURCE . equals ( parent ) ) { throw new NotFoundException ( ) ; } else if ( DELETED_RESOURCE . equals ( parent ) ) { throw new ClientErrorException ( GONE ) ; } else if ( ACL . equals ( getRequest ( ) . getExt ( ) ) || ldpResourceTypes ( parent . getInteractionModel ( ) ) . noneMatch ( LDP . Container :: equals ) ) { throw new NotAllowedException ( GET , Stream . of ( HEAD , OPTIONS , PATCH , PUT , DELETE ) . toArray ( String [ ] :: new ) ) ; } else if ( ! MISSING_RESOURCE . equals ( child ) && ! DELETED_RESOURCE . equals ( child ) ) { throw new ClientErrorException ( CONFLICT ) ; } else if ( ! supportsInteractionModel ( ldpType ) ) { throw new BadRequestException ( "Unsupported interaction model provided" , status ( BAD_REQUEST ) . link ( UnsupportedInteractionModel . getIRIString ( ) , LDP . constrainedBy . getIRIString ( ) ) . build ( ) ) ; } else if ( ldpType . equals ( LDP . NonRDFSource ) && rdfSyntax != null ) { LOGGER . error ( "Cannot save {} as a NonRDFSource with RDF syntax" , getIdentifier ( ) ) ; throw new BadRequestException ( "Cannot save resource as a NonRDFSource with RDF syntax" ) ; } setParent ( parent ) ; return status ( CREATED ) ; }
Initialize the response .
4,215
public CompletionStage < ResponseBuilder > createResource ( final ResponseBuilder builder ) { LOGGER . debug ( "Creating resource as {}" , getIdentifier ( ) ) ; final TrellisDataset mutable = TrellisDataset . createDataset ( ) ; final TrellisDataset immutable = TrellisDataset . createDataset ( ) ; return handleResourceCreation ( mutable , immutable , builder ) . whenComplete ( ( a , b ) -> mutable . close ( ) ) . whenComplete ( ( a , b ) -> immutable . close ( ) ) ; }
Create a new resource .
4,216
public String getSubject ( ) { if ( triple . getSubject ( ) instanceof IRI ) { return ( ( IRI ) triple . getSubject ( ) ) . getIRIString ( ) ; } return triple . getSubject ( ) . ntriplesString ( ) ; }
Get the subject of the triple as a string .
4,217
public String getObject ( ) { if ( triple . getObject ( ) instanceof Literal ) { return ( ( Literal ) triple . getObject ( ) ) . getLexicalForm ( ) ; } else if ( triple . getObject ( ) instanceof IRI ) { return ( ( IRI ) triple . getObject ( ) ) . getIRIString ( ) ; } return triple . getObject ( ) . ntriplesString ( ) ; }
Get the object of the triple as a string .
4,218
public static Optional < IRI > getContainer ( final IRI identifier ) { if ( identifier . getIRIString ( ) . equals ( TRELLIS_DATA_PREFIX ) ) { return Optional . empty ( ) ; } final String path = identifier . getIRIString ( ) . substring ( TRELLIS_DATA_PREFIX . length ( ) ) ; final int index = Math . max ( path . lastIndexOf ( '/' ) , 0 ) ; return Optional . of ( rdf . createIRI ( TRELLIS_DATA_PREFIX + path . substring ( 0 , index ) ) ) ; }
Get the structural - logical container for this resource .
4,219
public void initialize ( ) { final IRI root = rdf . createIRI ( TRELLIS_DATA_PREFIX ) ; final IRI rootAuth = rdf . createIRI ( TRELLIS_DATA_PREFIX + "#auth" ) ; try ( final TrellisDataset dataset = TrellisDataset . createDataset ( ) ) { dataset . add ( rdf . createQuad ( Trellis . PreferAccessControl , rootAuth , ACL . mode , ACL . Read ) ) ; dataset . add ( rdf . createQuad ( Trellis . PreferAccessControl , rootAuth , ACL . mode , ACL . Write ) ) ; dataset . add ( rdf . createQuad ( Trellis . PreferAccessControl , rootAuth , ACL . mode , ACL . Control ) ) ; dataset . add ( rdf . createQuad ( Trellis . PreferAccessControl , rootAuth , ACL . agentClass , FOAF . Agent ) ) ; dataset . add ( rdf . createQuad ( Trellis . PreferAccessControl , rootAuth , ACL . accessTo , root ) ) ; LOGGER . debug ( "Preparing to initialize Trellis at {}" , root ) ; trellis . getResourceService ( ) . get ( root ) . thenCompose ( res -> initialize ( root , res , dataset ) ) . exceptionally ( err -> { LOGGER . warn ( "Unable to auto-initialize Trellis: {}. See DEBUG log for more info" , err . getMessage ( ) ) ; LOGGER . debug ( "Error auto-initializing Trellis" , err ) ; return null ; } ) . toCompletableFuture ( ) . join ( ) ; } }
Initialize the Trellis backend with a root container and default ACL quads .
4,220
public void getResource ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers ) { fetchResource ( new TrellisRequest ( request , uriInfo , headers ) ) . thenApply ( ResponseBuilder :: build ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Perform a GET operation on an LDP Resource .
4,221
public void options ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers ) { final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers ) ; final String urlBase = getBaseUrl ( req ) ; final IRI identifier = rdf . createIRI ( TRELLIS_DATA_PREFIX + req . getPath ( ) ) ; final OptionsHandler optionsHandler = new OptionsHandler ( req , trellis , req . getVersion ( ) != null , urlBase ) ; fetchTrellisResource ( identifier , req . getVersion ( ) ) . thenApply ( optionsHandler :: initialize ) . thenApply ( optionsHandler :: ldpOptions ) . thenApply ( ResponseBuilder :: build ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Perform an OPTIONS operation on an LDP Resource .
4,222
public void updateResource ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers , final SecurityContext secContext , final String body ) { final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers , secContext ) ; final String urlBase = getBaseUrl ( req ) ; final IRI identifier = rdf . createIRI ( TRELLIS_DATA_PREFIX + req . getPath ( ) ) ; final PatchHandler patchHandler = new PatchHandler ( req , body , trellis , defaultJsonLdProfile , urlBase ) ; getParent ( identifier ) . thenCombine ( trellis . getResourceService ( ) . get ( identifier ) , patchHandler :: initialize ) . thenCompose ( patchHandler :: updateResource ) . thenCompose ( patchHandler :: updateMemento ) . thenApply ( ResponseBuilder :: build ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Perform a PATCH operation on an LDP Resource .
4,223
public void deleteResource ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers , final SecurityContext secContext ) { final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers , secContext ) ; final String urlBase = getBaseUrl ( req ) ; final IRI identifier = rdf . createIRI ( TRELLIS_DATA_PREFIX + req . getPath ( ) ) ; final DeleteHandler deleteHandler = new DeleteHandler ( req , trellis , urlBase ) ; getParent ( identifier ) . thenCombine ( trellis . getResourceService ( ) . get ( identifier ) , deleteHandler :: initialize ) . thenCompose ( deleteHandler :: deleteResource ) . thenApply ( ResponseBuilder :: build ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Perform a DELETE operation on an LDP Resource .
4,224
public void createResource ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers , final SecurityContext secContext , final InputStream body ) { final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers , secContext ) ; final String urlBase = getBaseUrl ( req ) ; final String path = req . getPath ( ) ; final String identifier = getIdentifier ( req ) ; final String separator = path . isEmpty ( ) ? "" : "/" ; final IRI parent = rdf . createIRI ( TRELLIS_DATA_PREFIX + path ) ; final IRI child = rdf . createIRI ( TRELLIS_DATA_PREFIX + path + separator + identifier ) ; final PostHandler postHandler = new PostHandler ( req , parent , identifier , body , trellis , urlBase ) ; trellis . getResourceService ( ) . get ( parent ) . thenCombine ( trellis . getResourceService ( ) . get ( child ) , postHandler :: initialize ) . thenCompose ( postHandler :: createResource ) . thenCompose ( postHandler :: updateMemento ) . thenApply ( ResponseBuilder :: build ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Perform a POST operation on a LDP Resource .
4,225
public void setResource ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers , final SecurityContext secContext , final InputStream body ) { final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers , secContext ) ; final String urlBase = getBaseUrl ( req ) ; final IRI identifier = rdf . createIRI ( TRELLIS_DATA_PREFIX + req . getPath ( ) ) ; final PutHandler putHandler = new PutHandler ( req , body , trellis , preconditionRequired , createUncontained , urlBase ) ; getParent ( identifier ) . thenCombine ( trellis . getResourceService ( ) . get ( identifier ) , putHandler :: initialize ) . thenCompose ( putHandler :: setResource ) . thenCompose ( putHandler :: updateMemento ) . thenApply ( ResponseBuilder :: build ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Perform a PUT operation on a LDP Resource .
4,226
public void write ( final Stream < Triple > triples , final OutputStream out , final String subject ) { final Writer writer = new OutputStreamWriter ( out , UTF_8 ) ; try { template . execute ( writer , new HtmlData ( namespaceService , subject , triples . collect ( toList ( ) ) , css , js , icon ) ) . flush ( ) ; } catch ( final IOException ex ) { throw new UncheckedIOException ( ex ) ; } }
Send the content to an output stream .
4,227
public ResponseBuilder initialize ( final Resource resource ) { if ( MISSING_RESOURCE . equals ( resource ) ) { throw new NotFoundException ( ) ; } else if ( DELETED_RESOURCE . equals ( resource ) ) { throw new ClientErrorException ( GONE ) ; } LOGGER . debug ( "Acceptable media types: {}" , getRequest ( ) . getAcceptableMediaTypes ( ) ) ; this . syntax = getSyntax ( getServices ( ) . getIOService ( ) , getRequest ( ) . getAcceptableMediaTypes ( ) , resource . getBinaryMetadata ( ) . filter ( b -> ! DESCRIPTION . equals ( getRequest ( ) . getExt ( ) ) ) . map ( b -> b . getMimeType ( ) . orElse ( APPLICATION_OCTET_STREAM ) ) . orElse ( null ) ) ; if ( ACL . equals ( getRequest ( ) . getExt ( ) ) && ! resource . hasAcl ( ) ) { throw new NotFoundException ( ) ; } setResource ( resource ) ; return ok ( ) ; }
Initialize the get handler .
4,228
public ResponseBuilder standardHeaders ( final ResponseBuilder builder ) { builder . lastModified ( from ( getResource ( ) . getModified ( ) ) ) . header ( VARY , ACCEPT ) ; final IRI model ; if ( getRequest ( ) . getExt ( ) == null || DESCRIPTION . equals ( getRequest ( ) . getExt ( ) ) ) { if ( syntax != null ) { builder . header ( VARY , PREFER ) ; builder . type ( syntax . mediaType ( ) ) ; } model = getResource ( ) . getBinaryMetadata ( ) . isPresent ( ) && syntax != null ? LDP . RDFSource : getResource ( ) . getInteractionModel ( ) ; getResource ( ) . getExtraLinkRelations ( ) . collect ( toMap ( Entry :: getKey , Entry :: getValue ) ) . entrySet ( ) . forEach ( entry -> builder . link ( entry . getKey ( ) , join ( " " , entry . getValue ( ) ) ) ) ; } else { model = LDP . RDFSource ; } addLdpHeaders ( builder , model ) ; addMementoHeaders ( builder ) ; return builder ; }
Get the standard headers .
4,229
public ResponseBuilder addMementoHeaders ( final ResponseBuilder builder , final SortedSet < Instant > mementos ) { if ( ! ACL . equals ( getRequest ( ) . getExt ( ) ) ) { builder . link ( getIdentifier ( ) , "original timegate" ) . links ( MementoResource . getMementoLinks ( getIdentifier ( ) , mementos ) . map ( link -> MementoResource . filterLinkParams ( link , ! includeMementoDates ) ) . toArray ( Link [ ] :: new ) ) ; } return builder ; }
Add the memento headers .
4,230
public ResponseBuilder getTimeMapBuilder ( final SortedSet < Instant > mementos , final TrellisRequest req , final String baseUrl ) { final List < MediaType > acceptableTypes = req . getAcceptableMediaTypes ( ) ; final String identifier = fromUri ( baseUrl ) . path ( req . getPath ( ) ) . build ( ) . toString ( ) ; final List < Link > links = getMementoLinks ( identifier , mementos ) . collect ( toList ( ) ) ; final ResponseBuilder builder = ok ( ) . link ( identifier , ORIGINAL + " " + TIMEGATE ) ; builder . links ( links . stream ( ) . map ( this :: filterLinkParams ) . toArray ( Link [ ] :: new ) ) . link ( Resource . getIRIString ( ) , TYPE ) . link ( RDFSource . getIRIString ( ) , TYPE ) . header ( ALLOW , join ( "," , GET , HEAD , OPTIONS ) ) ; final RDFSyntax syntax = getSyntax ( trellis . getIOService ( ) , acceptableTypes , APPLICATION_LINK_FORMAT ) ; if ( syntax != null ) { final IRI profile = getProfile ( acceptableTypes , syntax ) ; final IRI jsonldProfile = profile != null ? profile : compacted ; final StreamingOutput stream = new StreamingOutput ( ) { public void write ( final OutputStream out ) throws IOException { trellis . getIOService ( ) . write ( timemap . asRdf ( identifier , links ) , out , syntax , jsonldProfile ) ; } } ; return builder . type ( syntax . mediaType ( ) ) . entity ( stream ) ; } return builder . type ( APPLICATION_LINK_FORMAT ) . entity ( links . stream ( ) . map ( this :: filterLinkParams ) . map ( Link :: toString ) . collect ( joining ( ",\n" ) ) + "\n" ) ; }
Create a response builder for a TimeMap response .
4,231
public ResponseBuilder getTimeGateBuilder ( final SortedSet < Instant > mementos , final TrellisRequest req , final String baseUrl ) { final String identifier = fromUri ( baseUrl ) . path ( req . getPath ( ) ) . build ( ) . toString ( ) ; return status ( FOUND ) . location ( fromUri ( identifier + "?version=" + req . getDatetime ( ) . getInstant ( ) . getEpochSecond ( ) ) . build ( ) ) . link ( identifier , ORIGINAL + " " + TIMEGATE ) . links ( getMementoLinks ( identifier , mementos ) . map ( this :: filterLinkParams ) . toArray ( Link [ ] :: new ) ) . header ( VARY , ACCEPT_DATETIME ) ; }
Create a response builder for a TimeGate response .
4,232
public static Stream < Link > getMementoLinks ( final String identifier , final SortedSet < Instant > mementos ) { if ( mementos . isEmpty ( ) ) { return empty ( ) ; } return concat ( getTimeMap ( identifier , mementos . first ( ) , mementos . last ( ) ) , mementos . stream ( ) . map ( mementoToLink ( identifier ) ) ) ; }
Retrieve all of the Memento - related link headers given a collection of datetimes .
4,233
public static Link filterLinkParams ( final Link link , final boolean filter ) { if ( filter ) { if ( TIMEMAP . equals ( link . getRel ( ) ) ) { return Link . fromUri ( link . getUri ( ) ) . rel ( TIMEMAP ) . type ( APPLICATION_LINK_FORMAT ) . build ( ) ; } else if ( MEMENTO . equals ( link . getRel ( ) ) ) { return Link . fromUri ( link . getUri ( ) ) . rel ( MEMENTO ) . build ( ) ; } } return link ; }
Filter link parameters from a provided Link object if configured to do so .
4,234
private static String cleanIdentifier ( final String identifier ) { final String id = identifier . split ( "#" ) [ 0 ] . split ( "\\?" ) [ 0 ] ; if ( id . endsWith ( "/" ) ) { return id . substring ( 0 , id . length ( ) - 1 ) ; } return id ; }
Clean the identifier .
4,235
public String getSlug ( ) { final Slug slug = Slug . valueOf ( headers . getFirst ( SLUG ) ) ; if ( slug != null && ! slug . getValue ( ) . isEmpty ( ) ) { return slug . getValue ( ) ; } return null ; }
Get the slug header .
4,236
public Link getLink ( ) { final String link = headers . getFirst ( LINK ) ; if ( link != null ) { return Link . valueOf ( link ) ; } return null ; }
Get the Link header .
4,237
public static Version valueOf ( final String value ) { if ( value != null ) { final Instant time = parse ( value ) ; if ( time != null ) { return new Version ( time ) ; } } return null ; }
Create a Version object from a string value .
4,238
public String get ( final String key , final Function < String , String > mapper ) { try { return cache . get ( key , ( ) -> mapper . apply ( key ) ) ; } catch ( final ExecutionException ex ) { LOGGER . warn ( "Error fetching {} from cache: {}" , key , ex . getMessage ( ) ) ; return null ; } }
Lazily get a value from the cache .
4,239
public static Slug valueOf ( final String value ) { if ( value != null ) { final String decoded = decodeSlug ( value ) ; if ( decoded != null ) { return new Slug ( decoded ) ; } } return null ; }
Get a Slug object from a decoded string value .
4,240
public List < LabelledTriple > getTriples ( ) { return triples . stream ( ) . map ( this :: labelTriple ) . sorted ( sortSubjects . thenComparing ( sortPredicates ) . thenComparing ( sortObjects ) ) . collect ( toList ( ) ) ; }
Get the triples .
4,241
public String getTitle ( ) { final Map < IRI , List < String > > titles = triples . stream ( ) . filter ( triple -> titleCandidates . contains ( triple . getPredicate ( ) ) ) . filter ( triple -> triple . getObject ( ) instanceof Literal ) . collect ( groupingBy ( Triple :: getPredicate , mapping ( triple -> ( ( Literal ) triple . getObject ( ) ) . getLexicalForm ( ) , toList ( ) ) ) ) ; return titleCandidates . stream ( ) . filter ( titles :: containsKey ) . map ( titles :: get ) . flatMap ( List :: stream ) . findFirst ( ) . orElseGet ( this :: getSubject ) ; }
Get the title .
4,242
public static void recursiveDelete ( final ServiceBundler services , final Session session , final IRI identifier , final String baseUrl ) { final List < IRI > resources = services . getResourceService ( ) . get ( identifier ) . thenApply ( res -> res . stream ( LDP . PreferContainment ) . map ( Quad :: getObject ) . filter ( IRI . class :: isInstance ) . map ( IRI . class :: cast ) . collect ( toList ( ) ) ) . toCompletableFuture ( ) . join ( ) ; resources . forEach ( id -> recursiveDelete ( services , session , id , baseUrl ) ) ; resources . stream ( ) . parallel ( ) . map ( id -> { final TrellisDataset immutable = TrellisDataset . createDataset ( ) ; services . getAuditService ( ) . creation ( id , session ) . stream ( ) . map ( skolemizeQuads ( services . getResourceService ( ) , baseUrl ) ) . forEachOrdered ( immutable :: add ) ; return services . getResourceService ( ) . delete ( Metadata . builder ( id ) . interactionModel ( LDP . Resource ) . container ( identifier ) . build ( ) ) . thenCompose ( future -> services . getResourceService ( ) . add ( id , immutable . asDataset ( ) ) ) . whenComplete ( ( a , b ) -> immutable . close ( ) ) . thenAccept ( future -> services . getEventService ( ) . emit ( new SimpleEvent ( externalUrl ( id , baseUrl ) , session . getAgent ( ) , asList ( PROV . Activity , AS . Delete ) , singletonList ( LDP . Resource ) ) ) ) ; } ) . map ( CompletionStage :: toCompletableFuture ) . forEach ( CompletableFuture :: join ) ; }
Recursively delete resources under the given identifier .
4,243
public static CompletionStage < Void > copy ( final ServiceBundler services , final Session session , final Resource resource , final IRI destination , final String baseUrl ) { final Metadata . Builder builder = Metadata . builder ( destination ) . interactionModel ( resource . getInteractionModel ( ) ) ; resource . getContainer ( ) . ifPresent ( builder :: container ) ; resource . getBinaryMetadata ( ) . ifPresent ( builder :: binary ) ; resource . getInsertedContentRelation ( ) . ifPresent ( builder :: insertedContentRelation ) ; resource . getMemberOfRelation ( ) . ifPresent ( builder :: memberOfRelation ) ; resource . getMemberRelation ( ) . ifPresent ( builder :: memberRelation ) ; resource . getMembershipResource ( ) . ifPresent ( builder :: membershipResource ) ; try ( final Stream < Quad > stream = resource . stream ( Trellis . PreferUserManaged ) ) { LOGGER . debug ( "Copying {} to {}" , resource . getIdentifier ( ) , destination ) ; final TrellisDataset mutable = new TrellisDataset ( stream . collect ( toDataset ( ) ) ) ; return services . getResourceService ( ) . create ( builder . build ( ) , mutable . asDataset ( ) ) . whenComplete ( ( a , b ) -> mutable . close ( ) ) . thenCompose ( future -> { final TrellisDataset immutable = TrellisDataset . createDataset ( ) ; services . getAuditService ( ) . creation ( resource . getIdentifier ( ) , session ) . stream ( ) . map ( skolemizeQuads ( services . getResourceService ( ) , baseUrl ) ) . forEachOrdered ( immutable :: add ) ; return services . getResourceService ( ) . add ( resource . getIdentifier ( ) , immutable . asDataset ( ) ) . whenComplete ( ( a , b ) -> immutable . close ( ) ) ; } ) . thenCompose ( future -> services . getMementoService ( ) . put ( services . getResourceService ( ) , resource . getIdentifier ( ) ) ) . thenAccept ( future -> services . getEventService ( ) . emit ( new SimpleEvent ( externalUrl ( destination , baseUrl ) , session . getAgent ( ) , asList ( PROV . Activity , AS . Create ) , singletonList ( resource . getInteractionModel ( ) ) ) ) ) ; } }
Copy a resource to another location .
4,244
public static String getLastSegment ( final List < PathSegment > segments ) { if ( segments . isEmpty ( ) ) { return "" ; } return segments . get ( segments . size ( ) - 1 ) . getPath ( ) ; }
Get the last path segment .
4,245
public static String getAllButLastSegment ( final List < PathSegment > segments ) { if ( segments . isEmpty ( ) ) { return "" ; } return segments . subList ( 0 , segments . size ( ) - 1 ) . stream ( ) . map ( PathSegment :: getPath ) . collect ( joining ( "/" ) ) ; }
From a list of segments use all but the last item joined in a String .
4,246
public static String externalUrl ( final IRI identifier , final String baseUrl ) { if ( baseUrl . endsWith ( "/" ) ) { return replaceOnce ( identifier . getIRIString ( ) , TRELLIS_DATA_PREFIX , baseUrl ) ; } return replaceOnce ( identifier . getIRIString ( ) , TRELLIS_DATA_PREFIX , baseUrl + "/" ) ; }
Generate an external URL for the given location and baseURL .
4,247
public CompletionStage < Void > put ( final Resource resource , final Instant time ) { return runAsync ( ( ) -> { final File resourceDir = FileUtils . getResourceDirectory ( directory , resource . getIdentifier ( ) ) ; if ( ! resourceDir . exists ( ) ) { resourceDir . mkdirs ( ) ; } FileUtils . writeMemento ( resourceDir , resource , time . truncatedTo ( SECONDS ) ) ; } ) ; }
Create a Memento from a resource at a particular time .
4,248
public static String buildEtagHash ( final String identifier , final Instant modified , final Prefer prefer ) { final String sep = "." ; final String hash = prefer != null ? prefer . getInclude ( ) . hashCode ( ) + sep + prefer . getOmit ( ) . hashCode ( ) : "" ; return md5Hex ( modified . toEpochMilli ( ) + sep + modified . getNano ( ) + sep + hash + sep + identifier ) ; }
Build a hash value suitable for generating an ETag .
4,249
public static Set < IRI > triplePreferences ( final Prefer prefer ) { final Set < IRI > include = new HashSet < > ( DEFAULT_REPRESENTATION ) ; if ( prefer != null ) { if ( prefer . getInclude ( ) . contains ( LDP . PreferMinimalContainer . getIRIString ( ) ) ) { include . remove ( LDP . PreferContainment ) ; include . remove ( LDP . PreferMembership ) ; } if ( prefer . getOmit ( ) . contains ( LDP . PreferMinimalContainer . getIRIString ( ) ) ) { include . remove ( Trellis . PreferUserManaged ) ; } prefer . getOmit ( ) . stream ( ) . map ( rdf :: createIRI ) . forEach ( include :: remove ) ; prefer . getInclude ( ) . stream ( ) . map ( rdf :: createIRI ) . filter ( iri -> ! ignoredPreferences . contains ( iri ) ) . forEach ( include :: add ) ; } return include ; }
Get a collection of IRIs for identifying the categories of triples to retrieve .
4,250
public static Function < Triple , Triple > unskolemizeTriples ( final ResourceService svc , final String baseUrl ) { return triple -> rdf . createTriple ( ( BlankNodeOrIRI ) svc . toExternal ( svc . unskolemize ( triple . getSubject ( ) ) , baseUrl ) , triple . getPredicate ( ) , svc . toExternal ( svc . unskolemize ( triple . getObject ( ) ) , baseUrl ) ) ; }
Convert triples from a skolemized form to an externa form .
4,251
public static Function < Triple , Triple > skolemizeTriples ( final ResourceService svc , final String baseUrl ) { return triple -> rdf . createTriple ( ( BlankNodeOrIRI ) svc . toInternal ( svc . skolemize ( triple . getSubject ( ) ) , baseUrl ) , triple . getPredicate ( ) , svc . toInternal ( svc . skolemize ( triple . getObject ( ) ) , baseUrl ) ) ; }
Convert triples from an external form to a skolemized form .
4,252
public static BiConsumer < Object , Throwable > closeInputStreamAsync ( final InputStream input ) { return ( val , err ) -> { try { input . close ( ) ; } catch ( final IOException ex ) { throw new UncheckedIOException ( "Error closing input stream" , ex ) ; } } ; }
Close an input stream in an async chain .
4,253
public static boolean isContainer ( final IRI ldpType ) { return LDP . Container . equals ( ldpType ) || LDP . BasicContainer . equals ( ldpType ) || LDP . DirectContainer . equals ( ldpType ) || LDP . IndirectContainer . equals ( ldpType ) ; }
Check whether an LDP type is a sort of container .
4,254
public static void checkRequiredPreconditions ( final boolean required , final String ifMatch , final String ifUnmodifiedSince ) { if ( required && ifMatch == null && ifUnmodifiedSince == null ) { throw new ClientErrorException ( status ( PRECONDITION_REQUIRED ) . build ( ) ) ; } }
Check whether conditional requests are required .
4,255
public ResponseBuilder initialize ( final Resource resource ) { if ( MISSING_RESOURCE . equals ( resource ) ) { throw new NotFoundException ( ) ; } else if ( DELETED_RESOURCE . equals ( resource ) ) { throw new ClientErrorException ( GONE ) ; } setResource ( resource ) ; return status ( NO_CONTENT ) ; }
Initialize the request handler .
4,256
public CompletionStage < ResponseBuilder > deleteResource ( final ResponseBuilder builder ) { LOGGER . debug ( "Deleting {}" , getIdentifier ( ) ) ; final TrellisDataset mutable = TrellisDataset . createDataset ( ) ; final TrellisDataset immutable = TrellisDataset . createDataset ( ) ; return handleDeletion ( mutable , immutable ) . thenApply ( future -> builder ) . whenComplete ( ( a , b ) -> immutable . close ( ) ) . whenComplete ( ( a , b ) -> mutable . close ( ) ) ; }
Delete the resource in the persistence layer .
4,257
public static Depth valueOf ( final String value ) { if ( value != null && values . contains ( value . toLowerCase ( ) ) ) { return new Depth ( value ) ; } return null ; }
Create a Depth object from a value .
4,258
public static CompletableFuture < Resource > findResource ( final RDFConnection rdfConnection , final IRI identifier ) { return supplyAsync ( ( ) -> { final TriplestoreResource res = new TriplestoreResource ( rdfConnection , identifier ) ; res . fetchData ( ) ; if ( ! res . exists ( ) ) { return MISSING_RESOURCE ; } else if ( res . isDeleted ( ) ) { return DELETED_RESOURCE ; } return res ; } ) ; }
Try to load a Trellis resource .
4,259
protected void fetchData ( ) { LOGGER . debug ( "Fetching data from RDF datastore for: {}" , identifier ) ; final Var binarySubject = Var . alloc ( "binarySubject" ) ; final Var binaryPredicate = Var . alloc ( "binaryPredicate" ) ; final Var binaryObject = Var . alloc ( "binaryObject" ) ; final Query q = new Query ( ) ; q . setQuerySelectType ( ) ; q . addResultVar ( PREDICATE ) ; q . addResultVar ( OBJECT ) ; q . addResultVar ( binarySubject ) ; q . addResultVar ( binaryPredicate ) ; q . addResultVar ( binaryObject ) ; final ElementPathBlock epb1 = new ElementPathBlock ( ) ; epb1 . addTriple ( create ( rdf . asJenaNode ( identifier ) , PREDICATE , OBJECT ) ) ; final ElementPathBlock epb2 = new ElementPathBlock ( ) ; epb2 . addTriple ( create ( rdf . asJenaNode ( identifier ) , rdf . asJenaNode ( DC . hasPart ) , binarySubject ) ) ; epb2 . addTriple ( create ( rdf . asJenaNode ( identifier ) , rdf . asJenaNode ( RDF . type ) , rdf . asJenaNode ( LDP . NonRDFSource ) ) ) ; epb2 . addTriple ( create ( binarySubject , binaryPredicate , binaryObject ) ) ; final ElementGroup elg = new ElementGroup ( ) ; elg . addElement ( epb1 ) ; elg . addElement ( new ElementOptional ( epb2 ) ) ; q . setQueryPattern ( new ElementNamedGraph ( rdf . asJenaNode ( Trellis . PreferServerManaged ) , elg ) ) ; rdfConnection . querySelect ( q , qs -> { final RDFNode s = qs . get ( "binarySubject" ) ; final RDFNode p = qs . get ( "binaryPredicate" ) ; final RDFNode o = qs . get ( "binaryObject" ) ; nodesToTriple ( s , p , o ) . ifPresent ( t -> data . put ( t . getPredicate ( ) , t . getObject ( ) ) ) ; data . put ( getPredicate ( qs ) , getObject ( qs ) ) ; } ) ; }
Fetch data for this resource .
4,260
public static Credentials parse ( final String encoded ) { try { final String decoded = new String ( Base64 . getDecoder ( ) . decode ( encoded ) , UTF_8 ) ; final String [ ] parts = decoded . split ( ":" , 2 ) ; if ( parts . length == 2 ) { return new Credentials ( parts [ 0 ] , parts [ 1 ] ) ; } } catch ( final IllegalArgumentException ex ) { } return null ; }
Create a set of credentials .
4,261
public static Prefer valueOf ( final String value ) { if ( value != null ) { final Map < String , String > data = new HashMap < > ( ) ; final Set < String > params = new HashSet < > ( ) ; stream ( value . split ( ";" ) ) . map ( String :: trim ) . map ( pref -> pref . split ( "=" , 2 ) ) . forEach ( x -> { if ( x . length == 2 ) { data . put ( x [ 0 ] . trim ( ) , x [ 1 ] . trim ( ) ) ; } else { params . add ( x [ 0 ] . trim ( ) ) ; } } ) ; return new Prefer ( data . get ( PREFER_RETURN ) , parseParameter ( data . get ( PREFER_INCLUDE ) ) , parseParameter ( data . get ( PREFER_OMIT ) ) , params , data . get ( PREFER_HANDLING ) ) ; } return null ; }
Create a Prefer header representation from a header string .
4,262
public static Prefer ofInclude ( final String ... includes ) { final List < String > iris = asList ( includes ) ; if ( iris . isEmpty ( ) ) { return valueOf ( join ( "=" , PREFER_RETURN , PREFER_REPRESENTATION ) ) ; } return valueOf ( join ( "=" , PREFER_RETURN , PREFER_REPRESENTATION ) + "; " + PREFER_INCLUDE + "=\"" + iris . stream ( ) . collect ( joining ( " " ) ) + "\"" ) ; }
Build a Prefer object with a set of included IRIs .
4,263
public static Prefer ofOmit ( final String ... omits ) { final List < String > iris = asList ( omits ) ; if ( iris . isEmpty ( ) ) { return valueOf ( join ( "=" , PREFER_RETURN , PREFER_REPRESENTATION ) ) ; } return valueOf ( join ( "=" , PREFER_RETURN , PREFER_REPRESENTATION ) + "; " + PREFER_OMIT + "=\"" + iris . stream ( ) . collect ( joining ( " " ) ) + "\"" ) ; }
Build a Prefer object with a set of omitted IRIs .
4,264
public static File getResourceDirectory ( final File baseDirectory , final IRI identifier ) { requireNonNull ( baseDirectory , "The baseDirectory may not be null!" ) ; requireNonNull ( identifier , "The identifier may not be null!" ) ; final String id = identifier . getIRIString ( ) ; final StringJoiner joiner = new StringJoiner ( separator ) ; final CRC32 hasher = new CRC32 ( ) ; hasher . update ( id . getBytes ( UTF_8 ) ) ; final String intermediate = Long . toHexString ( hasher . getValue ( ) ) ; range ( 0 , intermediate . length ( ) / LENGTH ) . limit ( MAX ) . forEach ( i -> joiner . add ( intermediate . substring ( i * LENGTH , ( i + 1 ) * LENGTH ) ) ) ; joiner . add ( md5Hex ( id ) ) ; return new File ( baseDirectory , joiner . toString ( ) ) ; }
Get a directory for a given resource identifier .
4,265
public static Stream < Quad > parseQuad ( final String line ) { final List < Token > tokens = new ArrayList < > ( ) ; makeTokenizerString ( line ) . forEachRemaining ( tokens :: add ) ; final List < Node > nodes = tokens . stream ( ) . filter ( Token :: isNode ) . map ( Token :: asNode ) . filter ( Objects :: nonNull ) . collect ( toList ( ) ) ; if ( nodes . size ( ) == 3 ) { return of ( rdf . asQuad ( create ( defaultGraphIRI , nodes . get ( 0 ) , nodes . get ( 1 ) , nodes . get ( 2 ) ) ) ) ; } else if ( nodes . size ( ) == 4 ) { return of ( rdf . asQuad ( create ( nodes . get ( 3 ) , nodes . get ( 0 ) , nodes . get ( 1 ) , nodes . get ( 2 ) ) ) ) ; } else { LOGGER . warn ( "Skipping invalid data value: {}" , line ) ; return empty ( ) ; } }
Parse a string into a stream of Quads .
4,266
public static Stream < Path > uncheckedList ( final Path path ) { try { return Files . list ( path ) ; } catch ( final IOException ex ) { throw new UncheckedIOException ( "Error fetching file list" , ex ) ; } }
Fetch a stream of files in the provided directory path .
4,267
public static void writeMemento ( final File resourceDir , final Resource resource , final Instant time ) { try ( final BufferedWriter writer = newBufferedWriter ( getNquadsFile ( resourceDir , time ) . toPath ( ) , UTF_8 , CREATE , WRITE , TRUNCATE_EXISTING ) ) { try ( final Stream < String > quads = generateServerManaged ( resource ) . map ( FileUtils :: serializeQuad ) ) { final Iterator < String > lineIter = quads . iterator ( ) ; while ( lineIter . hasNext ( ) ) { writer . write ( lineIter . next ( ) + lineSeparator ( ) ) ; } } try ( final Stream < String > quads = resource . stream ( ) . filter ( FileUtils :: notServerManaged ) . map ( FileUtils :: serializeQuad ) ) { final Iterator < String > lineiter = quads . iterator ( ) ; while ( lineiter . hasNext ( ) ) { writer . write ( lineiter . next ( ) + lineSeparator ( ) ) ; } } } catch ( final IOException ex ) { throw new UncheckedIOException ( "Error writing resource version for " + resource . getIdentifier ( ) . getIRIString ( ) , ex ) ; } }
Write a Memento to a particular resource directory .
4,268
public static InputStream getBoundedStream ( final InputStream stream , final int from , final int to ) throws IOException { final long skipped = stream . skip ( from ) ; LOGGER . debug ( "Skipped {} bytes" , skipped ) ; return new BoundedInputStream ( stream , ( long ) to - from ) ; }
Get a bounded inputstream .
4,269
public static String serializeQuad ( final Quad quad ) { return quad . getSubject ( ) + SEP + quad . getPredicate ( ) + SEP + quad . getObject ( ) + SEP + quad . getGraphName ( ) . map ( g -> g + " ." ) . orElse ( "." ) ; }
Serialize an RDF Quad .
4,270
public static File getNquadsFile ( final File dir , final Instant time ) { return new File ( dir , Long . toString ( time . getEpochSecond ( ) ) + ".nq" ) ; }
Get the nquads file for a given moment in time .
4,271
public static RDFConnection buildRDFConnection ( final String location ) { if ( location != null ) { if ( location . startsWith ( "http://" ) || location . startsWith ( "https://" ) ) { LOGGER . info ( "Using remote Triplestore for persistence at {}" , location ) ; return connect ( location ) ; } LOGGER . info ( "Using local TDB2 database at {}" , location ) ; return connect ( wrap ( connectDatasetGraph ( location ) ) ) ; } LOGGER . info ( "Using an in-memory dataset for resources" ) ; return connect ( createTxnMem ( ) ) ; }
Build an RDF connection from a location value .
4,272
public static Range valueOf ( final String value ) { final int [ ] vals = parse ( value ) ; if ( vals . length == 2 ) { return new Range ( vals [ 0 ] , vals [ 1 ] ) ; } return null ; }
Get a Range object from a header value .
4,273
public static AcceptDatetime valueOf ( final String value ) { if ( value != null ) { final Instant time = parseDatetime ( value ) ; if ( time != null ) { return new AcceptDatetime ( time ) ; } } return null ; }
Create an Accept - Datetime header object from a string .
4,274
public static Optional < Principal > withWebIdClaim ( final Claims claims ) { final String webid = claims . get ( WEBID , String . class ) ; if ( webid == null ) return empty ( ) ; LOGGER . debug ( "Using JWT claim with webid: {}" , webid ) ; return of ( new OAuthPrincipal ( webid ) ) ; }
Generate a Principal from a webid claim .
4,275
public static Optional < Principal > withSubjectClaim ( final Claims claims ) { final String subject = claims . getSubject ( ) ; if ( subject == null ) return empty ( ) ; if ( isUrl ( subject ) ) { LOGGER . debug ( "Using JWT claim with sub: {}" , subject ) ; return of ( new OAuthPrincipal ( subject ) ) ; } final String iss = claims . getIssuer ( ) ; if ( iss != null && isUrl ( iss ) ) { final String webid = iss . endsWith ( "/" ) ? iss + subject : iss + "/" + subject ; LOGGER . debug ( "Using JWT claim with generated webid: {}" , webid ) ; return of ( new OAuthPrincipal ( webid ) ) ; } if ( claims . containsKey ( WEBSITE ) ) { final String site = claims . get ( WEBSITE , String . class ) ; LOGGER . debug ( "Using JWT claim with website: {}" , site ) ; return of ( new OAuthPrincipal ( site ) ) ; } return empty ( ) ; }
Generate a Principal from a subject claim .
4,276
public static Optional < Key > buildRSAPublicKey ( final String keyType , final BigInteger modulus , final BigInteger exponent ) { try { return of ( KeyFactory . getInstance ( keyType ) . generatePublic ( new RSAPublicKeySpec ( modulus , exponent ) ) ) ; } catch ( final NoSuchAlgorithmException | InvalidKeySpecException ex ) { LOGGER . error ( "Error generating RSA Key from JWKS entry" , ex ) ; } return empty ( ) ; }
Build an RSA public key .
4,277
protected void checkCache ( final Instant modified , final EntityTag etag ) { HttpUtils . checkIfMatch ( getRequest ( ) . getHeaders ( ) . getFirst ( IF_MATCH ) , etag ) ; HttpUtils . checkIfUnmodifiedSince ( getRequest ( ) . getHeaders ( ) . getFirst ( IF_UNMODIFIED_SINCE ) , modified ) ; HttpUtils . checkIfNoneMatch ( getRequest ( ) . getMethod ( ) , getRequest ( ) . getHeaders ( ) . getFirst ( IF_NONE_MATCH ) , etag ) ; HttpUtils . checkIfModifiedSince ( getRequest ( ) . getMethod ( ) , getRequest ( ) . getHeaders ( ) . getFirst ( IF_MODIFIED_SINCE ) , modified ) ; }
Check the cache .
4,278
public ResponseBuilder initialize ( final Resource parent , final Resource resource ) { setResource ( DELETED_RESOURCE . equals ( resource ) || MISSING_RESOURCE . equals ( resource ) ? null : resource ) ; if ( getResource ( ) != null ) { final Instant modified = getResource ( ) . getModified ( ) ; final EntityTag etag ; if ( getResource ( ) . getBinaryMetadata ( ) . isPresent ( ) && ! isRdfType ( getRequest ( ) . getContentType ( ) ) ) { etag = new EntityTag ( buildEtagHash ( getIdentifier ( ) + "BINARY" , modified , null ) ) ; } else { etag = new EntityTag ( buildEtagHash ( getIdentifier ( ) , modified , getRequest ( ) . getPrefer ( ) ) ) ; } checkRequiredPreconditions ( preconditionRequired , getRequest ( ) . getHeaders ( ) . getFirst ( IF_MATCH ) , getRequest ( ) . getHeaders ( ) . getFirst ( IF_UNMODIFIED_SINCE ) ) ; checkCache ( modified , etag ) ; } if ( ACL . equals ( getRequest ( ) . getExt ( ) ) && rdfSyntax == null ) { throw new NotAcceptableException ( ) ; } if ( ! createUncontained || resource . getContainer ( ) . isPresent ( ) ) { setParent ( parent ) ; } return status ( NO_CONTENT ) ; }
Initialize the response handler .
4,279
public CompletionStage < ResponseBuilder > setResource ( final ResponseBuilder builder ) { LOGGER . debug ( "Setting resource as {}" , getIdentifier ( ) ) ; final IRI ldpType = getLdpType ( ) ; if ( ! supportsInteractionModel ( ldpType ) ) { throw new BadRequestException ( "Unsupported interaction model provided" , status ( BAD_REQUEST ) . link ( UnsupportedInteractionModel . getIRIString ( ) , LDP . constrainedBy . getIRIString ( ) ) . build ( ) ) ; } if ( getResource ( ) != null && ! isBinaryDescription ( ) && ldpResourceTypes ( ldpType ) . noneMatch ( getResource ( ) . getInteractionModel ( ) :: equals ) ) { LOGGER . error ( "Cannot change the LDP type to {} for {}" , ldpType , getIdentifier ( ) ) ; throw new ClientErrorException ( "Cannot change the LDP type to " + ldpType , status ( CONFLICT ) . build ( ) ) ; } LOGGER . debug ( "Using LDP Type: {}" , ldpType ) ; final TrellisDataset mutable = TrellisDataset . createDataset ( ) ; final TrellisDataset immutable = TrellisDataset . createDataset ( ) ; LOGGER . debug ( "Persisting {} with mutable data:\n{}\n and immutable data:\n{}" , getIdentifier ( ) , mutable , immutable ) ; return handleResourceUpdate ( mutable , immutable , builder , ldpType ) . whenComplete ( ( a , b ) -> mutable . close ( ) ) . whenComplete ( ( a , b ) -> immutable . close ( ) ) ; }
Store the resource to the persistence layer .
4,280
public CompletionStage < ResponseBuilder > updateMemento ( final ResponseBuilder builder ) { return getServices ( ) . getMementoService ( ) . put ( getServices ( ) . getResourceService ( ) , getInternalId ( ) ) . exceptionally ( ex -> { LOGGER . warn ( "Unable to store memento for {}: {}" , getInternalId ( ) , ex . getMessage ( ) ) ; return null ; } ) . thenApply ( stage -> builder ) ; }
Update the memento resource .
4,281
protected CompletionStage < Void > emitEvent ( final IRI identifier , final IRI activityType , final IRI resourceType ) { getServices ( ) . getEventService ( ) . emit ( new SimpleEvent ( getUrl ( identifier ) , getSession ( ) . getAgent ( ) , asList ( PROV . Activity , activityType ) , asList ( resourceType ) ) ) ; if ( AS . Update . equals ( activityType ) && LDP . IndirectContainer . equals ( getParentModel ( ) ) ) { return emitMembershipUpdateEvent ( ) ; } else if ( AS . Create . equals ( activityType ) || AS . Delete . equals ( activityType ) ) { final IRI model = getParentModel ( ) ; final IRI id = getParentIdentifier ( ) ; if ( HttpUtils . isContainer ( model ) ) { getServices ( ) . getEventService ( ) . emit ( new SimpleEvent ( getUrl ( id ) , getSession ( ) . getAgent ( ) , asList ( PROV . Activity , AS . Update ) , asList ( model ) ) ) ; if ( ! parent . getMembershipResource ( ) . map ( MutatingLdpHandler :: removeHashFragment ) . filter ( isEqual ( id ) ) . isPresent ( ) ) { return allOf ( getServices ( ) . getResourceService ( ) . touch ( id ) . toCompletableFuture ( ) , emitMembershipUpdateEvent ( ) . toCompletableFuture ( ) ) ; } return getServices ( ) . getResourceService ( ) . touch ( id ) ; } } return completedFuture ( null ) ; }
Emit events for the change .
4,282
protected void checkConstraint ( final Optional < Graph > graph , final IRI type , final RDFSyntax syntax ) { graph . ifPresent ( g -> { final List < ConstraintViolation > violations = constraintServices . stream ( ) . parallel ( ) . flatMap ( svc -> svc . constrainedBy ( type , g ) ) . collect ( toList ( ) ) ; if ( ! violations . isEmpty ( ) ) { final ResponseBuilder err = status ( CONFLICT ) ; violations . forEach ( v -> err . link ( v . getConstraint ( ) . getIRIString ( ) , LDP . constrainedBy . getIRIString ( ) ) ) ; final StreamingOutput stream = new StreamingOutput ( ) { public void write ( final OutputStream out ) throws IOException { getServices ( ) . getIOService ( ) . write ( violations . stream ( ) . flatMap ( v2 -> v2 . getTriples ( ) . stream ( ) ) , out , syntax ) ; } } ; throw new ClientErrorException ( err . entity ( stream ) . build ( ) ) ; } } ) ; }
Check the constraints of a graph .
4,283
public TrellisConfiguration setAdditionalConfig ( final String name , final Object value ) { extras . put ( name , value ) ; return this ; }
Set an extra configuration value .
4,284
public CompletionStage < ResponseBuilder > updateResource ( final ResponseBuilder builder ) { LOGGER . debug ( "Updating {} via PATCH" , getIdentifier ( ) ) ; if ( ACL . equals ( getRequest ( ) . getExt ( ) ) ) { getLinkTypes ( LDP . RDFSource ) . forEach ( type -> builder . link ( type , "type" ) ) ; } else { getLinkTypes ( getResource ( ) . getInteractionModel ( ) ) . forEach ( type -> builder . link ( type , "type" ) ) ; } final TrellisDataset mutable = TrellisDataset . createDataset ( ) ; final TrellisDataset immutable = TrellisDataset . createDataset ( ) ; return assembleResponse ( mutable , immutable , builder ) . whenComplete ( ( a , b ) -> mutable . close ( ) ) . whenComplete ( ( a , b ) -> immutable . close ( ) ) ; }
Update the resource in the persistence layer .
4,285
protected Object getLdpComponent ( final T config , final boolean initialize ) { final TrellisHttpResource ldpResource = new TrellisHttpResource ( getServiceBundler ( ) , config . getBaseUrl ( ) ) ; if ( initialize ) { ldpResource . initialize ( ) ; } return ldpResource ; }
Get the TrellisHttpResource matcher .
4,286
public void moveResource ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers , final SecurityContext security ) { final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers , security ) ; final String baseUrl = getBaseUrl ( req ) ; final IRI identifier = rdf . createIRI ( TRELLIS_DATA_PREFIX + req . getPath ( ) ) ; final IRI destination = getDestination ( headers , baseUrl ) ; final Session session = getSession ( req . getPrincipalName ( ) ) ; getParent ( destination ) . thenCombine ( services . getResourceService ( ) . get ( destination ) , this :: checkResources ) . thenCompose ( parent -> services . getResourceService ( ) . touch ( parent . getIdentifier ( ) ) ) . thenCompose ( future -> services . getResourceService ( ) . get ( identifier ) ) . thenApply ( this :: checkResource ) . thenAccept ( res -> recursiveCopy ( services , session , res , destination , baseUrl ) ) . thenAccept ( future -> recursiveDelete ( services , session , identifier , baseUrl ) ) . thenCompose ( future -> services . getResourceService ( ) . delete ( Metadata . builder ( identifier ) . interactionModel ( LDP . Resource ) . build ( ) ) ) . thenCompose ( future -> { final TrellisDataset immutable = TrellisDataset . createDataset ( ) ; services . getAuditService ( ) . creation ( identifier , session ) . stream ( ) . map ( skolemizeQuads ( services . getResourceService ( ) , baseUrl ) ) . forEachOrdered ( immutable :: add ) ; return services . getResourceService ( ) . add ( identifier , immutable . asDataset ( ) ) . whenComplete ( ( a , b ) -> immutable . close ( ) ) ; } ) . thenAccept ( future -> services . getEventService ( ) . emit ( new SimpleEvent ( externalUrl ( identifier , baseUrl ) , session . getAgent ( ) , asList ( PROV . Activity , AS . Delete ) , singletonList ( LDP . Resource ) ) ) ) . thenApply ( future -> status ( NO_CONTENT ) . build ( ) ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Move a resource .
4,287
@ Consumes ( { APPLICATION_XML } ) @ Produces ( { APPLICATION_XML } ) public void getProperties ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers , final DavPropFind propfind ) throws ParserConfigurationException { final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers ) ; final IRI identifier = rdf . createIRI ( TRELLIS_DATA_PREFIX + req . getPath ( ) ) ; final String location = fromUri ( getBaseUrl ( req ) ) . path ( req . getPath ( ) ) . build ( ) . toString ( ) ; final Document doc = getDocument ( ) ; services . getResourceService ( ) . get ( identifier ) . thenApply ( this :: checkResource ) . thenApply ( propertiesToMultiStatus ( doc , location , propfind ) ) . thenApply ( multistatus -> status ( MULTI_STATUS ) . entity ( multistatus ) . build ( ) ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Get properties for a resource .
4,288
@ Consumes ( { APPLICATION_XML } ) @ Produces ( { APPLICATION_XML } ) public void updateProperties ( final AsyncResponse response , final Request request , final UriInfo uriInfo , final HttpHeaders headers , final SecurityContext security , final DavPropertyUpdate propertyUpdate ) throws ParserConfigurationException { final Document doc = getDocument ( ) ; final TrellisRequest req = new TrellisRequest ( request , uriInfo , headers , security ) ; final IRI identifier = rdf . createIRI ( TRELLIS_DATA_PREFIX + req . getPath ( ) ) ; final String baseUrl = getBaseUrl ( req ) ; final String location = fromUri ( baseUrl ) . path ( req . getPath ( ) ) . build ( ) . toString ( ) ; final Session session = getSession ( req . getPrincipalName ( ) ) ; services . getResourceService ( ) . get ( identifier ) . thenApply ( this :: checkResource ) . thenCompose ( resourceToMultiStatus ( doc , identifier , location , baseUrl , session , propertyUpdate ) ) . thenApply ( multistatus -> status ( MULTI_STATUS ) . entity ( multistatus ) . build ( ) ) . exceptionally ( this :: handleException ) . thenApply ( response :: resume ) ; }
Update properties on a resource .
4,289
public static Enum < ? > [ ] [ ] explodeArguments ( TestConstructor constructor ) { checkNotNull ( constructor , "constructor" ) ; return explodeParameters ( constructor . getVariationTypes ( ) , constructor . getName ( ) + " constructor" ) ; }
Explode a list of argument values for invoking the specified constructor with all combinations of its parameters .
4,290
public static Enum < ? > [ ] [ ] explodeArguments ( Method method ) { checkNotNull ( method , "method" ) ; return explodeParameters ( method . getParameterTypes ( ) , method . getDeclaringClass ( ) . getName ( ) + '.' + method . getName ( ) + " method" ) ; }
Explode a list of argument values for invoking the specified method with all combinations of its parameters .
4,291
public static TestConstructor findSingle ( Class < ? > cls ) { final TestConstructor [ ] constructors = findAll ( cls ) ; if ( constructors . length == 0 ) { throw new IllegalStateException ( cls . getName ( ) + " requires at least 1 public constructor" ) ; } else if ( constructors . length == 1 ) { return constructors [ 0 ] ; } else { throw new IllegalStateException ( "Class " + cls . getName ( ) + " has too many parameterized constructors. " + "Should only be 1 (with enum variations)." ) ; } }
Find the parameterized constructor of cls if there is one or the default constructor if there isn t .
4,292
public QueryResponse < RegulatoryFeature > getRegulatory ( String id , QueryOptions options ) throws IOException { return execute ( id , "regulatory" , options , RegulatoryFeature . class ) ; }
check data model returned
4,293
private String formatDnaAllele ( ) { if ( ">" . equals ( mutationType ) ) { return reference + '>' + alternate ; } else if ( "delins" . equals ( mutationType ) ) { return "del" + reference + "ins" + alternate ; } else if ( "del" . equals ( mutationType ) ) { return mutationType + reference ; } else if ( "dup" . equals ( mutationType ) ) { return mutationType + alternate ; } else if ( "ins" . equals ( mutationType ) ) { return mutationType + alternate ; } else { throw new AssertionError ( "unknown mutation type: '" + mutationType + "'" ) ; } }
Generate HGVS DNA allele .
4,294
private String formatCdnaCoords ( ) { if ( cdnaStart . equals ( cdnaEnd ) ) { return cdnaStart . toString ( ) ; } else { return cdnaStart . toString ( ) + "_" + cdnaEnd . toString ( ) ; } }
Generate HGVS cDNA coordinates string .
4,295
protected void justify ( Variant variant , int startOffset , int endOffset , String allele , String genomicSequence , String strand ) { StringBuilder stringBuilder = new StringBuilder ( allele ) ; if ( "-" . equals ( strand ) ) { while ( startOffset > 0 && genomicSequence . charAt ( startOffset - 1 ) == stringBuilder . charAt ( stringBuilder . length ( ) - 1 ) ) { stringBuilder . deleteCharAt ( stringBuilder . length ( ) - 1 ) ; stringBuilder . insert ( 0 , genomicSequence . charAt ( startOffset - 1 ) ) ; startOffset -- ; endOffset -- ; variant . setStart ( variant . getStart ( ) - 1 ) ; variant . setEnd ( variant . getEnd ( ) - 1 ) ; } } else { while ( ( endOffset + 1 ) < genomicSequence . length ( ) && genomicSequence . charAt ( endOffset + 1 ) == stringBuilder . charAt ( 0 ) ) { stringBuilder . deleteCharAt ( 0 ) ; stringBuilder . append ( genomicSequence . charAt ( endOffset + 1 ) ) ; startOffset ++ ; endOffset ++ ; variant . setStart ( variant . getStart ( ) + 1 ) ; variant . setEnd ( variant . getEnd ( ) + 1 ) ; } } if ( variant . getReference ( ) . isEmpty ( ) ) { variant . setAlternate ( stringBuilder . toString ( ) ) ; } else { variant . setReference ( stringBuilder . toString ( ) ) ; } }
Justify an indel to the left or right along a sequence seq .
4,296
public List < Variant > read ( ) { Variant variant = null ; boolean valid = false ; while ( iterator . hasNext ( ) && ! valid ) { variant = iterator . next ( ) ; valid = isValid ( variant ) ; } if ( valid ) { if ( variant . getType ( ) == null ) { variant . setType ( variant . inferType ( variant . getReference ( ) , variant . getAlternate ( ) ) ) ; } return Collections . singletonList ( variant ) ; } else { return null ; } }
Performs one read of from a CellBase variation collection .
4,297
private List < String > calculateTranscriptHgvs ( Variant variant , Transcript transcript , String geneId ) { String mutationType = ">" ; HgvsStringBuilder hgvsStringBuilder = new HgvsStringBuilder ( ) ; hgvsStringBuilder . setKind ( isCoding ( transcript ) ? HgvsStringBuilder . Kind . CODING : HgvsStringBuilder . Kind . NON_CODING ) ; hgvsStringBuilder . setCdnaStart ( genomicToCdnaCoord ( transcript , variant . getStart ( ) ) ) ; hgvsStringBuilder . setCdnaEnd ( hgvsStringBuilder . getCdnaStart ( ) ) ; hgvsStringBuilder . setTranscriptId ( transcript . getId ( ) ) ; hgvsStringBuilder . setGeneId ( geneId ) ; String reference ; String alternate ; if ( transcript . getStrand ( ) . equals ( "-" ) ) { reference = String . valueOf ( VariantAnnotationUtils . COMPLEMENTARY_NT . get ( variant . getReference ( ) . charAt ( 0 ) ) ) ; alternate = String . valueOf ( VariantAnnotationUtils . COMPLEMENTARY_NT . get ( variant . getAlternate ( ) . charAt ( 0 ) ) ) ; } else { reference = variant . getReference ( ) ; alternate = variant . getAlternate ( ) ; } hgvsStringBuilder . setMutationType ( mutationType ) ; hgvsStringBuilder . setReference ( reference ) ; hgvsStringBuilder . setAlternate ( alternate ) ; return Collections . singletonList ( hgvsStringBuilder . format ( ) ) ; }
Generates cdna HGVS names from an SNV .
4,298
private void addChunkId ( Document dbObject ) { List < String > chunkIds = new ArrayList < > ( ) ; int chunkStart = ( Integer ) dbObject . get ( "start" ) / MongoDBCollectionConfiguration . VARIATION_CHUNK_SIZE ; int chunkEnd = ( Integer ) dbObject . get ( "end" ) / MongoDBCollectionConfiguration . VARIATION_CHUNK_SIZE ; String chunkIdSuffix = MongoDBCollectionConfiguration . VARIATION_CHUNK_SIZE / 1000 + "k" ; for ( int i = chunkStart ; i <= chunkEnd ; i ++ ) { if ( dbObject . containsKey ( "chromosome" ) ) { chunkIds . add ( dbObject . get ( "chromosome" ) + "_" + i + "_" + chunkIdSuffix ) ; } else { chunkIds . add ( dbObject . get ( "sequenceName" ) + "_" + i + "_" + chunkIdSuffix ) ; } } dbObject . put ( "_chunkIds" , chunkIds ) ; }
by MongoDBCellbaseLoader must be replaced by an appropriate method in this adaptor
4,299
public String getVariantAnnotationId ( Variant variant ) { return variant . getChromosome ( ) + ":" + variant . getStart ( ) + ":" + variant . getReference ( ) + ":" + variant . getAlternate ( ) ; }
FIXME Next two methods should be moved near the Variant Annotation tool