idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
7,900 | private static List < Column > getAncestorColumns ( Resource currentResource , Resource rootResource ) { List < Column > columns = new ArrayList < > ( ) ; List < Resource > ancestors = getAncestors ( currentResource , rootResource ) ; for ( int i = 0 ; i < ancestors . size ( ) ; i ++ ) { Resource r = ancestors . get ( i ) ; String activeId ; if ( i < ancestors . size ( ) - 1 ) { activeId = ancestors . get ( i + 1 ) . getPath ( ) ; } else { activeId = currentResource . getPath ( ) ; } Column column = new Column ( ) . columnId ( r . getPath ( ) ) . lazy ( true ) . activeId ( activeId ) ; columns . add ( column ) ; } return columns ; } | Generate column for each ancestor . |
7,901 | public void _waitForNonStaleResults ( Duration waitTimeout ) { theWaitForNonStaleResults = true ; timeout = ObjectUtils . firstNonNull ( waitTimeout , getDefaultTimeout ( ) ) ; } | Instruct the query to wait for non stale result for the specified wait timeout . This shouldn t be used outside of unit tests unless you are well aware of the implications |
7,902 | public List < String > getProjectionFields ( ) { return fieldsToFetchToken != null && fieldsToFetchToken . projections != null ? Arrays . asList ( fieldsToFetchToken . projections ) : Collections . emptyList ( ) ; } | Gets the fields for projection |
7,903 | public void _randomOrdering ( String seed ) { assertNoRawQuery ( ) ; if ( StringUtils . isBlank ( seed ) ) { _randomOrdering ( ) ; return ; } _noCaching ( ) ; orderByTokens . add ( OrderByToken . createRandom ( seed ) ) ; } | Order the search results randomly using the specified seed this is useful if you want to have repeatable random queries |
7,904 | @ SuppressWarnings ( "ConstantConditions" ) public void _whereLucene ( String fieldName , String whereClause , boolean exact ) { fieldName = ensureValidFieldName ( fieldName , false ) ; List < QueryToken > tokens = getCurrentWhereTokens ( ) ; appendOperatorIfNeeded ( tokens ) ; negateIfNeeded ( tokens , fieldName ) ; WhereToken . WhereOptions options = exact ? new WhereToken . WhereOptions ( exact ) : null ; WhereToken whereToken = WhereToken . create ( WhereOperator . LUCENE , fieldName , addQueryParameter ( whereClause ) , options ) ; tokens . add ( whereToken ) ; } | Filter the results from the index using the specified where clause . |
7,905 | public void _openSubclause ( ) { _currentClauseDepth ++ ; List < QueryToken > tokens = getCurrentWhereTokens ( ) ; appendOperatorIfNeeded ( tokens ) ; negateIfNeeded ( tokens , null ) ; tokens . add ( OpenSubclauseToken . INSTANCE ) ; } | Simplified method for opening a new clause within the query |
7,906 | public void _closeSubclause ( ) { _currentClauseDepth -- ; List < QueryToken > tokens = getCurrentWhereTokens ( ) ; tokens . add ( CloseSubclauseToken . INSTANCE ) ; } | Simplified method for closing a clause within the query |
7,907 | public void _whereIn ( String fieldName , Collection < Object > values ) { _whereIn ( fieldName , values , false ) ; } | Check that the field has one of the specified value |
7,908 | public void _whereEndsWith ( String fieldName , Object value , boolean exact ) { WhereParams whereParams = new WhereParams ( ) ; whereParams . setFieldName ( fieldName ) ; whereParams . setValue ( value ) ; whereParams . setAllowWildcards ( true ) ; Object transformToEqualValue = transformValue ( whereParams ) ; List < QueryToken > tokens = getCurrentWhereTokens ( ) ; appendOperatorIfNeeded ( tokens ) ; whereParams . setFieldName ( ensureValidFieldName ( whereParams . getFieldName ( ) , whereParams . isNestedPath ( ) ) ) ; negateIfNeeded ( tokens , whereParams . getFieldName ( ) ) ; WhereToken whereToken = WhereToken . create ( WhereOperator . ENDS_WITH , whereParams . getFieldName ( ) , addQueryParameter ( transformToEqualValue ) , new WhereToken . WhereOptions ( exact ) ) ; tokens . add ( whereToken ) ; } | Matches fields which ends with the specified value . |
7,909 | public void _whereBetween ( String fieldName , Object start , Object end , boolean exact ) { fieldName = ensureValidFieldName ( fieldName , false ) ; List < QueryToken > tokens = getCurrentWhereTokens ( ) ; appendOperatorIfNeeded ( tokens ) ; negateIfNeeded ( tokens , fieldName ) ; WhereParams startParams = new WhereParams ( ) ; startParams . setValue ( start ) ; startParams . setFieldName ( fieldName ) ; WhereParams endParams = new WhereParams ( ) ; endParams . setValue ( end ) ; endParams . setFieldName ( fieldName ) ; String fromParameterName = addQueryParameter ( start == null ? "*" : transformValue ( startParams , true ) ) ; String toParameterName = addQueryParameter ( end == null ? "NULL" : transformValue ( endParams , true ) ) ; WhereToken whereToken = WhereToken . create ( WhereOperator . BETWEEN , fieldName , null , new WhereToken . WhereOptions ( exact , fromParameterName , toParameterName ) ) ; tokens . add ( whereToken ) ; } | Matches fields where the value is between the specified start and end inclusive |
7,910 | public void _orElse ( ) { List < QueryToken > tokens = getCurrentWhereTokens ( ) ; if ( tokens . isEmpty ( ) ) { return ; } if ( tokens . get ( tokens . size ( ) - 1 ) instanceof QueryOperatorToken ) { throw new IllegalStateException ( "Cannot add OR, previous token was already an operator token." ) ; } tokens . add ( QueryOperatorToken . OR ) ; } | Add an OR to the query |
7,911 | public void _orderBy ( String field , OrderingType ordering ) { assertNoRawQuery ( ) ; String f = ensureValidFieldName ( field , false ) ; orderByTokens . add ( OrderByToken . createAscending ( f , ordering ) ) ; } | Order the results by the specified fields The fields are the names of the fields to sort defaulting to sorting by ascending . You can prefix a field name with - to indicate sorting by descending or + to sort by ascending |
7,912 | public void _orderByDescending ( String field , OrderingType ordering ) { assertNoRawQuery ( ) ; String f = ensureValidFieldName ( field , false ) ; orderByTokens . add ( OrderByToken . createDescending ( f , ordering ) ) ; } | Order the results by the specified fields The fields are the names of the fields to sort defaulting to sorting by descending . You can prefix a field name with - to indicate sorting by descending or + to sort by ascending |
7,913 | protected IndexQuery generateIndexQuery ( String query ) { IndexQuery indexQuery = new IndexQuery ( ) ; indexQuery . setQuery ( query ) ; indexQuery . setStart ( start ) ; indexQuery . setWaitForNonStaleResults ( theWaitForNonStaleResults ) ; indexQuery . setWaitForNonStaleResultsTimeout ( timeout ) ; indexQuery . setQueryParameters ( queryParameters ) ; indexQuery . setDisableCaching ( disableCaching ) ; if ( pageSize != null ) { indexQuery . setPageSize ( pageSize ) ; } return indexQuery ; } | Generates the index query . |
7,914 | public QueryResult createSnapshot ( ) { QueryResult queryResult = new QueryResult ( ) ; queryResult . setResults ( getResults ( ) ) ; queryResult . setIncludes ( getIncludes ( ) ) ; queryResult . setIndexName ( getIndexName ( ) ) ; queryResult . setIndexTimestamp ( getIndexTimestamp ( ) ) ; queryResult . setIncludedPaths ( getIncludedPaths ( ) ) ; queryResult . setStale ( isStale ( ) ) ; queryResult . setSkippedResults ( getSkippedResults ( ) ) ; queryResult . setTotalResults ( getTotalResults ( ) ) ; queryResult . setHighlightings ( getHighlightings ( ) != null ? new HashMap < > ( getHighlightings ( ) ) : null ) ; queryResult . setExplanations ( getExplanations ( ) != null ? new HashMap < > ( getExplanations ( ) ) : null ) ; queryResult . setTimings ( getTimings ( ) ) ; queryResult . setLastQueryTime ( getLastQueryTime ( ) ) ; queryResult . setDurationInMs ( getDurationInMs ( ) ) ; queryResult . setResultEtag ( getResultEtag ( ) ) ; queryResult . setNodeTag ( getNodeTag ( ) ) ; queryResult . setCounterIncludes ( getCounterIncludes ( ) ) ; queryResult . setIncludedCounterNames ( getIncludedCounterNames ( ) ) ; return queryResult ; } | Creates a snapshot of the query results |
7,915 | public List < SubscriptionState > getSubscriptions ( int start , int take , String database ) { RequestExecutor requestExecutor = _store . getRequestExecutor ( ObjectUtils . firstNonNull ( database , _store . getDatabase ( ) ) ) ; GetSubscriptionsCommand command = new GetSubscriptionsCommand ( start , take ) ; requestExecutor . execute ( command ) ; return Arrays . asList ( command . getResult ( ) ) ; } | It downloads a list of all existing subscriptions in a database . |
7,916 | public void delete ( String name , String database ) { RequestExecutor requestExecutor = _store . getRequestExecutor ( ObjectUtils . firstNonNull ( database , _store . getDatabase ( ) ) ) ; DeleteSubscriptionCommand command = new DeleteSubscriptionCommand ( name ) ; requestExecutor . execute ( command ) ; } | Delete a subscription . |
7,917 | public SubscriptionState getSubscriptionState ( String subscriptionName , String database ) { if ( StringUtils . isEmpty ( subscriptionName ) ) { throw new IllegalArgumentException ( "SubscriptionName cannot be null" ) ; } RequestExecutor requestExecutor = _store . getRequestExecutor ( ObjectUtils . firstNonNull ( database , _store . getDatabase ( ) ) ) ; GetSubscriptionStateCommand command = new GetSubscriptionStateCommand ( subscriptionName ) ; requestExecutor . execute ( command ) ; return command . getResult ( ) ; } | Returns subscription definition and it s current state |
7,918 | public void dropConnection ( String name , String database ) { RequestExecutor requestExecutor = _store . getRequestExecutor ( ObjectUtils . firstNonNull ( database , _store . getDatabase ( ) ) ) ; DropSubscriptionConnectionCommand command = new DropSubscriptionConnectionCommand ( name ) ; requestExecutor . execute ( command ) ; } | Force server to close current client subscription connection to the server |
7,919 | private static String getContentPath ( HttpServletRequest request ) { String contentPath = ( String ) request . getAttribute ( Value . CONTENTPATH_ATTRIBUTE ) ; if ( contentPath == null ) { contentPath = ( ( SlingHttpServletRequest ) request ) . getRequestPathInfo ( ) . getSuffix ( ) ; } return contentPath ; } | Current content path |
7,920 | public static < T extends EventArgs > void invoke ( List < EventHandler < T > > delegates , Object sender , T event ) { for ( EventHandler < T > delegate : delegates ) { delegate . handle ( sender , event ) ; } } | Helper used for invoking event on list of delegates |
7,921 | private static void checkOffset ( String value , int offset , char expected ) throws IndexOutOfBoundsException { char found = value . charAt ( offset ) ; if ( found != expected ) { throw new IndexOutOfBoundsException ( "Expected '" + expected + "' character but found '" + found + "'" ) ; } } | Check if the expected character exist at the given offset of the |
7,922 | public void saveChanges ( ) { BatchOperation saveChangeOperation = new BatchOperation ( this ) ; try ( BatchCommand command = saveChangeOperation . createRequest ( ) ) { if ( command == null ) { return ; } if ( noTracking ) { throw new IllegalStateException ( "Cannot execute saveChanges when entity tracking is disabled in session." ) ; } _requestExecutor . execute ( command , sessionInfo ) ; updateSessionAfterSaveChanges ( command . getResult ( ) ) ; saveChangeOperation . setResult ( command . getResult ( ) ) ; } } | Saves all the changes to the Raven server . |
7,923 | public boolean exists ( String id ) { if ( id == null ) { throw new IllegalArgumentException ( "id cannot be null" ) ; } if ( _knownMissingIds . contains ( id ) ) { return false ; } if ( documentsById . getValue ( id ) != null ) { return true ; } HeadDocumentCommand command = new HeadDocumentCommand ( id , null ) ; _requestExecutor . execute ( command , sessionInfo ) ; return command . getResult ( ) != null ; } | Check if document exists without loading it |
7,924 | public < T > void refresh ( T entity ) { DocumentInfo documentInfo = documentsByEntity . get ( entity ) ; if ( documentInfo == null ) { throw new IllegalStateException ( "Cannot refresh a transient instance" ) ; } incrementRequestCount ( ) ; GetDocumentsCommand command = new GetDocumentsCommand ( new String [ ] { documentInfo . getId ( ) } , null , false ) ; _requestExecutor . execute ( command , sessionInfo ) ; refreshInternal ( entity , command , documentInfo ) ; } | Refreshes the specified entity from Raven server . |
7,925 | protected void spatial ( String field , Function < SpatialOptionsFactory , SpatialOptions > indexing ) { spatialOptionsStrings . put ( field , indexing . apply ( new SpatialOptionsFactory ( ) ) ) ; } | Register a field to be spatially indexed |
7,926 | @ SuppressWarnings ( "unchecked" ) public Object convertToEntity ( Class entityType , String id , ObjectNode document ) { try { if ( ObjectNode . class . equals ( entityType ) ) { return document ; } Object defaultValue = InMemoryDocumentSessionOperations . getDefaultValue ( entityType ) ; Object entity = defaultValue ; String documentType = _session . getConventions ( ) . getJavaClass ( id , document ) ; if ( documentType != null ) { Class type = Class . forName ( documentType ) ; if ( entityType . isAssignableFrom ( type ) ) { entity = _session . getConventions ( ) . getEntityMapper ( ) . treeToValue ( document , type ) ; } } if ( entity == defaultValue ) { entity = _session . getConventions ( ) . getEntityMapper ( ) . treeToValue ( document , entityType ) ; } if ( id != null ) { _session . getGenerateEntityIdOnTheClient ( ) . trySetIdentity ( entity , id ) ; } return entity ; } catch ( Exception e ) { throw new IllegalStateException ( "Could not convert document " + id + " to entity of type " + entityType . getName ( ) , e ) ; } } | Converts a json object to an entity . |
7,927 | protected final JSONArray getPages ( Iterator < Page > pages , int depth , PageFilter pageFilter ) throws JSONException { JSONArray pagesArray = new JSONArray ( ) ; while ( pages . hasNext ( ) ) { Page page = pages . next ( ) ; JSONObject pageObject = getPage ( page ) ; if ( pageObject != null ) { Iterator < Page > children = listChildren ( page . adaptTo ( Resource . class ) , pageFilter ) ; if ( ! children . hasNext ( ) ) { pageObject . put ( "leaf" , true ) ; } else if ( depth < getMaxDepth ( ) - 1 ) { pageObject . put ( "children" , getPages ( children , depth + 1 , pageFilter ) ) ; } pagesArray . put ( pageObject ) ; } } return pagesArray ; } | Generate JSON objects for pages . |
7,928 | protected final Iterator < Page > listChildren ( Resource parentResource , PageFilter pageFilter ) { return new PageIterator ( parentResource . listChildren ( ) , pageFilter ) ; } | Lists children using custom page iterator . |
7,929 | @ SuppressWarnings ( "null" ) protected final JSONObject getPage ( Page page ) throws JSONException { Resource resource = page . adaptTo ( Resource . class ) ; JSONObject pageObject = new JSONObject ( ) ; pageObject . put ( "name" , page . getName ( ) ) ; String title = page . getTitle ( ) ; if ( StringUtils . isEmpty ( title ) ) { title = page . getName ( ) ; } pageObject . put ( "text" , title ) ; pageObject . put ( "type" , resource . getResourceType ( ) ) ; String template = page . getProperties ( ) . get ( NameConstants . PN_TEMPLATE , String . class ) ; if ( StringUtils . isNotEmpty ( template ) ) { pageObject . put ( "template" , template ) ; } pageObject . put ( "cls" , "page" ) ; return pageObject ; } | Generate JSON object for page |
7,930 | public String getIdentifier ( ) { if ( identifier != null ) { return identifier ; } if ( urls == null ) { return null ; } if ( database != null ) { return String . join ( "," , urls ) + " (DB: " + database + ")" ; } return String . join ( "," , urls ) ; } | Gets the identifier for this store . |
7,931 | public IDocumentSession openSession ( String database ) { SessionOptions sessionOptions = new SessionOptions ( ) ; sessionOptions . setDatabase ( database ) ; return openSession ( sessionOptions ) ; } | Opens the session for a particular database |
7,932 | public IDocumentStore initialize ( ) { if ( initialized ) { return this ; } assertValidConfiguration ( ) ; try { if ( getConventions ( ) . getDocumentIdGenerator ( ) == null ) { MultiDatabaseHiLoIdGenerator generator = new MultiDatabaseHiLoIdGenerator ( this , getConventions ( ) ) ; _multiDbHiLo = generator ; getConventions ( ) . setDocumentIdGenerator ( generator :: generateDocumentId ) ; } getConventions ( ) . freeze ( ) ; initialized = true ; } catch ( Exception e ) { close ( ) ; throw ExceptionsUtils . unwrapException ( e ) ; } return this ; } | Initializes this instance . |
7,933 | private static boolean isPageInTemplateDefinition ( Page page ) { Resource resource = page . adaptTo ( Resource . class ) ; if ( resource != null ) { Resource parent = resource . getParent ( ) ; if ( parent != null ) { return StringUtils . equals ( NT_TEMPLATE , parent . getValueMap ( ) . get ( JCR_PRIMARYTYPE , String . class ) ) ; } } return false ; } | Checks if the given page is part of the editable template definition itself . |
7,934 | public void execute ( IDocumentStore store , DocumentConventions conventions , String database ) { DocumentConventions oldConventions = getConventions ( ) ; try { setConventions ( ObjectUtils . firstNonNull ( conventions , getConventions ( ) , store . getConventions ( ) ) ) ; IndexDefinition indexDefinition = createIndexDefinition ( ) ; indexDefinition . setName ( getIndexName ( ) ) ; if ( lockMode != null ) { indexDefinition . setLockMode ( lockMode ) ; } if ( priority != null ) { indexDefinition . setPriority ( priority ) ; } store . maintenance ( ) . forDatabase ( ObjectUtils . firstNonNull ( database , store . getDatabase ( ) ) ) . send ( new PutIndexesOperation ( indexDefinition ) ) ; } finally { setConventions ( oldConventions ) ; } } | Executes the index creation against the specified document database using the specified conventions |
7,935 | public static boolean is ( Set < String > runModes , String ... expectedRunModes ) { if ( runModes != null && expectedRunModes != null ) { for ( String expectedRunMode : expectedRunModes ) { if ( runModes . contains ( expectedRunMode ) ) { return true ; } } } return false ; } | Checks if given run mode is active . |
7,936 | public IndexDefinition createIndexDefinition ( ) { if ( conventions == null ) { conventions = new DocumentConventions ( ) ; } IndexDefinitionBuilder indexDefinitionBuilder = new IndexDefinitionBuilder ( getIndexName ( ) ) ; indexDefinitionBuilder . setIndexesStrings ( indexesStrings ) ; indexDefinitionBuilder . setAnalyzersStrings ( analyzersStrings ) ; indexDefinitionBuilder . setMap ( map ) ; indexDefinitionBuilder . setReduce ( reduce ) ; indexDefinitionBuilder . setStoresStrings ( storesStrings ) ; indexDefinitionBuilder . setSuggestionsOptions ( indexSuggestions ) ; indexDefinitionBuilder . setTermVectorsStrings ( termVectorsStrings ) ; indexDefinitionBuilder . setSpatialIndexesStrings ( spatialOptionsStrings ) ; indexDefinitionBuilder . setOutputReduceToCollection ( outputReduceToCollection ) ; indexDefinitionBuilder . setAdditionalSources ( getAdditionalSources ( ) ) ; return indexDefinitionBuilder . toIndexDefinition ( conventions ) ; } | Creates the index definition . |
7,937 | protected PageFilter getPageFilter ( SlingHttpServletRequest request ) { String predicateName = RequestParam . get ( request , RP_PREDICATE ) ; if ( StringUtils . isNotEmpty ( predicateName ) ) { PredicateProvider predicateProvider = getPredicateProvider ( ) ; if ( predicateProvider == null ) { throw new RuntimeException ( "PredicateProvider service not available." ) ; } Predicate predicate = predicateProvider . getPredicate ( predicateName ) ; if ( predicate == null ) { throw new RuntimeException ( "Predicate '" + predicateName + "' not available." ) ; } return new PredicatePageFilter ( predicate , true , true ) ; } return null ; } | Can be overridden by subclasses to filter page list via page filter . If not overridden it supports defining a page filter via predicate request attribute . |
7,938 | private IndexedPropertyMethodMetadata < ? > getIndexedPropertyMethodMetadata ( Collection < MethodMetadata < ? , ? > > methodMetadataOfType ) { for ( MethodMetadata methodMetadata : methodMetadataOfType ) { AnnotatedMethod annotatedMethod = methodMetadata . getAnnotatedMethod ( ) ; Annotation indexedAnnotation = annotatedMethod . getByMetaAnnotation ( IndexDefinition . class ) ; if ( indexedAnnotation != null ) { if ( ! ( methodMetadata instanceof PrimitivePropertyMethodMetadata ) ) { throw new XOException ( "Only primitive properties are allowed to be used for indexing." ) ; } return new IndexedPropertyMethodMetadata < > ( ( PropertyMethod ) annotatedMethod , ( PrimitivePropertyMethodMetadata ) methodMetadata , metadataFactory . createIndexedPropertyMetadata ( ( PropertyMethod ) annotatedMethod ) ) ; } } return null ; } | Determine the indexed property from a list of method metadata . |
7,939 | private Collection < MethodMetadata < ? , ? > > getMethodMetadataOfType ( AnnotatedType annotatedType , Collection < AnnotatedMethod > annotatedMethods ) { Collection < MethodMetadata < ? , ? > > methodMetadataOfType = new ArrayList < > ( ) ; for ( AnnotatedMethod annotatedMethod : annotatedMethods ) { MethodMetadata < ? , ? > methodMetadata ; ImplementedBy implementedBy = annotatedMethod . getAnnotation ( ImplementedBy . class ) ; ResultOf resultOf = annotatedMethod . getAnnotation ( ResultOf . class ) ; if ( implementedBy != null ) { methodMetadata = new ImplementedByMethodMetadata < > ( annotatedMethod , implementedBy . value ( ) , metadataFactory . createImplementedByMetadata ( annotatedMethod ) ) ; } else if ( resultOf != null ) { methodMetadata = createResultOfMetadata ( annotatedMethod , resultOf ) ; } else if ( annotatedMethod instanceof PropertyMethod ) { PropertyMethod propertyMethod = ( PropertyMethod ) annotatedMethod ; Transient transientAnnotation = propertyMethod . getAnnotationOfProperty ( Transient . class ) ; if ( transientAnnotation != null ) { methodMetadata = new TransientPropertyMethodMetadata ( propertyMethod ) ; } else { methodMetadata = createPropertyMethodMetadata ( annotatedType , propertyMethod ) ; } } else { methodMetadata = new UnsupportedOperationMethodMetadata ( ( UserMethod ) annotatedMethod ) ; } methodMetadataOfType . add ( methodMetadata ) ; } return methodMetadataOfType ; } | Return the collection of method metadata from the given collection of annotated methods . |
7,940 | public static < T > DependencyResolver < T > newInstance ( Collection < T > elements , DependencyProvider < T > dependencyProvider ) { return new DependencyResolver < T > ( elements , dependencyProvider ) ; } | Creates an instance of the resolver . |
7,941 | public List < T > resolve ( ) { blockedBy = new HashMap < > ( ) ; Set < T > queue = new LinkedHashSet < > ( ) ; Set < T > allElements = new HashSet < > ( ) ; queue . addAll ( elements ) ; while ( ! queue . isEmpty ( ) ) { T element = queue . iterator ( ) . next ( ) ; Set < T > dependencies = dependencyProvider . getDependencies ( element ) ; queue . addAll ( dependencies ) ; blockedBy . put ( element , dependencies ) ; queue . remove ( element ) ; allElements . add ( element ) ; } List < T > result = new LinkedList < > ( ) ; for ( T element : allElements ) { resolve ( element , result ) ; } return result ; } | Resolves the dependencies to a list . |
7,942 | private void resolve ( T element , List < T > result ) { Set < T > dependencies = blockedBy . get ( element ) ; if ( dependencies != null ) { for ( T dependency : dependencies ) { resolve ( dependency , result ) ; } blockedBy . remove ( element ) ; result . add ( element ) ; } } | Resolves an element . |
7,943 | public void put ( Id id , Object value , Mode mode ) { if ( Mode . WRITE . equals ( mode ) ) { writeCache . put ( id , value ) ; } readCache . put ( new CacheKey ( id ) , value ) ; } | Put an instance into the cache . |
7,944 | public Object get ( Id id , Mode mode ) { Object value = writeCache . get ( id ) ; if ( value == null ) { value = readCache . get ( new CacheKey ( id ) ) ; if ( value != null && Mode . WRITE . equals ( mode ) ) { writeCache . put ( id , value ) ; } } return value ; } | Lookup an instance in the cache identified by its id . |
7,945 | public void remove ( Id id ) { readCache . remove ( new CacheKey ( id ) ) ; writeCache . remove ( id ) ; } | Removes an instance from the cache . |
7,946 | private void initializeEntity ( Collection < ? extends TypeMetadata > types , NodeState nodeState ) { for ( TypeMetadata type : types ) { Collection < TypeMetadata > superTypes = type . getSuperTypes ( ) ; initializeEntity ( superTypes , nodeState ) ; for ( MethodMetadata < ? , ? > methodMetadata : type . getProperties ( ) ) { if ( methodMetadata instanceof AbstractRelationPropertyMethodMetadata ) { AbstractRelationPropertyMethodMetadata < ? > relationPropertyMethodMetadata = ( AbstractRelationPropertyMethodMetadata ) methodMetadata ; RelationTypeMetadata < RelationshipMetadata < RemoteRelationshipType > > relationshipMetadata = relationPropertyMethodMetadata . getRelationshipMetadata ( ) ; RemoteRelationshipType relationshipType = relationshipMetadata . getDatastoreMetadata ( ) . getDiscriminator ( ) ; RelationTypeMetadata . Direction direction = relationPropertyMethodMetadata . getDirection ( ) ; RemoteDirection remoteDirection ; switch ( direction ) { case FROM : remoteDirection = RemoteDirection . OUTGOING ; break ; case TO : remoteDirection = RemoteDirection . INCOMING ; break ; default : throw new XOException ( "Unsupported direction: " + direction ) ; } if ( nodeState . getRelationships ( remoteDirection , relationshipType ) == null ) { nodeState . setRelationships ( remoteDirection , relationshipType , new StateTracker < > ( new LinkedHashSet < > ( ) ) ) ; } } } } } | Initializes all relation properties of the given node state with empty collections . |
7,947 | public void log ( String message ) { switch ( level ) { case TRACE : LOGGER . trace ( message ) ; break ; case DEBUG : LOGGER . debug ( message ) ; break ; case INFO : LOGGER . info ( message ) ; break ; case WARN : LOGGER . warn ( message ) ; break ; case ERROR : LOGGER . error ( message ) ; break ; default : throw new XOException ( "Unsupported log log level " + level ) ; } } | Log a message using the configured log level . |
7,948 | private Object convertParameter ( Object value ) { if ( entityInstanceManager . isInstance ( value ) ) { return entityInstanceManager . getDatastoreType ( value ) ; } else if ( relationInstanceManager . isInstance ( value ) ) { return relationInstanceManager . getDatastoreType ( value ) ; } else if ( value instanceof Collection ) { Collection collection = ( Collection ) value ; List < Object > values = new ArrayList < > ( ) ; for ( Object o : collection ) { values . add ( convertParameter ( o ) ) ; } return values ; } return value ; } | Converts the given parameter value to instances which can be passed to the datastore . |
7,949 | public < P extends PluginRepository < ? , ? > > P getPluginManager ( Class < ? > pluginType ) { return ( P ) pluginRepositories . get ( pluginType ) ; } | Return a plugin repository identified by the plugin interface type . |
7,950 | private void ensureIndex ( DS session , EntityTypeMetadata < NodeMetadata < L > > entityTypeMetadata , IndexedPropertyMethodMetadata < IndexedPropertyMetadata > indexedProperty ) { if ( indexedProperty != null ) { IndexedPropertyMetadata datastoreMetadata = indexedProperty . getDatastoreMetadata ( ) ; if ( datastoreMetadata . isCreate ( ) ) { L label = entityTypeMetadata . getDatastoreMetadata ( ) . getDiscriminator ( ) ; PrimitivePropertyMethodMetadata < PropertyMetadata > propertyMethodMetadata = indexedProperty . getPropertyMethodMetadata ( ) ; if ( label != null && propertyMethodMetadata != null ) { ensureIndex ( session , label , propertyMethodMetadata , datastoreMetadata . isUnique ( ) ) ; } } } } | Ensures that an index exists for the given entity and property . |
7,951 | private void ensureIndex ( DS session , L label , PrimitivePropertyMethodMetadata < PropertyMetadata > propertyMethodMetadata , boolean unique ) { PropertyMetadata propertyMetadata = propertyMethodMetadata . getDatastoreMetadata ( ) ; String statement ; if ( unique ) { LOGGER . debug ( "Creating constraint for label {} on property '{}'." , label , propertyMetadata . getName ( ) ) ; statement = String . format ( "CREATE CONSTRAINT ON (n:%s) ASSERT n.%s IS UNIQUE" , label . getName ( ) , propertyMetadata . getName ( ) ) ; } else { LOGGER . debug ( "Creating index for label {} on property '{}'." , label , propertyMetadata . getName ( ) ) ; statement = String . format ( "CREATE INDEX ON :%s(%s)" , label . getName ( ) , propertyMetadata . getName ( ) ) ; } try ( ResultIterator iterator = session . createQuery ( Cypher . class ) . execute ( statement , Collections . emptyMap ( ) ) ) { } } | Ensures that an index exists for the given label and property . |
7,952 | public CompositeType getCompositeType ( ) { return CompositeTypeBuilder . create ( CompositeObject . class , metadata , typeMetadata -> typeMetadata . getAnnotatedType ( ) . getAnnotatedElement ( ) ) ; } | Convert this set into a composite type . |
7,953 | public void registerInstanceListener ( Object instanceListener ) { for ( Method method : instanceListener . getClass ( ) . getMethods ( ) ) { evaluateMethod ( instanceListener , PostCreate . class , method , postCreateMethods ) ; evaluateMethod ( instanceListener , PreUpdate . class , method , preUpdateMethods ) ; evaluateMethod ( instanceListener , PostUpdate . class , method , postUpdateMethods ) ; evaluateMethod ( instanceListener , PreDelete . class , method , preDeleteMethods ) ; evaluateMethod ( instanceListener , PostDelete . class , method , postDeleteMethods ) ; evaluateMethod ( instanceListener , PostLoad . class , method , postLoadMethods ) ; } } | Add an instance listener instance . |
7,954 | private void evaluateMethod ( Object listener , Class < ? extends Annotation > annotation , Method method , Map < Object , Set < Method > > methods ) { if ( method . isAnnotationPresent ( annotation ) ) { if ( method . getParameterTypes ( ) . length != 1 ) { throw new XOException ( "Life cycle method '" + method . toGenericString ( ) + "' annotated with '" + annotation . getName ( ) + "' must declare exactly one parameter but declares " + method . getParameterTypes ( ) . length + "." ) ; } Set < Method > listenerMethods = methods . get ( listener ) ; if ( listenerMethods == null ) { listenerMethods = new HashSet < > ( ) ; methods . put ( listener , listenerMethods ) ; } listenerMethods . add ( method ) ; } } | Evaluates a method if an annotation is present and if true adds to the map of life cycle methods . |
7,955 | private < T > void invoke ( Map < Object , Set < Method > > methods , T instance ) { for ( Map . Entry < Object , Set < Method > > entry : methods . entrySet ( ) ) { Object listener = entry . getKey ( ) ; Set < Method > listenerMethods = entry . getValue ( ) ; if ( listenerMethods != null ) { for ( Method method : listenerMethods ) { Class < ? > parameterType = method . getParameterTypes ( ) [ 0 ] ; if ( parameterType . isAssignableFrom ( instance . getClass ( ) ) ) { try { method . invoke ( listener , instance ) ; } catch ( IllegalAccessException e ) { throw new XOException ( "Cannot access instance listener method " + method . toGenericString ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new XOException ( "Cannot invoke instance listener method " + method . toGenericString ( ) , e ) ; } } } } } } | Invokes all registered lifecycle methods on a given instance . |
7,956 | public < T > T readInstance ( DatastoreType datastoreType ) { return getInstance ( datastoreType , TransactionalCache . Mode . READ ) ; } | Return the proxy instance which corresponds to the given datastore type for reading . |
7,957 | public < T > T createInstance ( DatastoreType datastoreType , DynamicType < ? > types ) { return newInstance ( getDatastoreId ( datastoreType ) , datastoreType , types , TransactionalCache . Mode . WRITE ) ; } | Return the proxy instance which corresponds to the given datastore type for writing . |
7,958 | private < T > T getInstance ( DatastoreType datastoreType , TransactionalCache . Mode cacheMode ) { DatastoreId id = getDatastoreId ( datastoreType ) ; Object instance = cache . get ( id , cacheMode ) ; if ( instance == null ) { DynamicType < ? > types = getTypes ( datastoreType ) ; instance = newInstance ( id , datastoreType , types , cacheMode ) ; if ( TransactionalCache . Mode . READ . equals ( cacheMode ) ) { instanceListenerService . postLoad ( instance ) ; } } return ( T ) instance ; } | Return the proxy instance which corresponds to the given datastore type . |
7,959 | private < T > T newInstance ( DatastoreId id , DatastoreType datastoreType , DynamicType < ? > types , TransactionalCache . Mode cacheMode ) { validateType ( types ) ; InstanceInvocationHandler invocationHandler = new InstanceInvocationHandler ( datastoreType , getProxyMethodService ( ) ) ; T instance = proxyFactory . createInstance ( invocationHandler , types . getCompositeType ( ) ) ; cache . put ( id , instance , cacheMode ) ; return instance ; } | Create a proxy instance which corresponds to the given datastore type . |
7,960 | private void validateType ( DynamicType < ? > dynamicType ) { int size = dynamicType . getMetadata ( ) . size ( ) ; if ( size == 1 ) { if ( dynamicType . isAbstract ( ) ) { throw new XOException ( "Cannot create an instance of a single abstract type " + dynamicType ) ; } } else if ( dynamicType . isFinal ( ) ) { throw new XOException ( "Cannot create an instance overriding a final type " + dynamicType ) ; } } | Validates the given types . |
7,961 | public < Instance > boolean isInstance ( Instance instance ) { if ( instance instanceof CompositeObject ) { Object delegate = ( ( CompositeObject ) instance ) . getDelegate ( ) ; return isDatastoreType ( delegate ) ; } return false ; } | Determine if a given instance is a datastore type handled by this manager . |
7,962 | public < Instance > DatastoreType getDatastoreType ( Instance instance ) { InstanceInvocationHandler < DatastoreType > invocationHandler = proxyFactory . getInvocationHandler ( instance ) ; return invocationHandler . getDatastoreType ( ) ; } | Return the datastore type represented by an instance . |
7,963 | public DynamicType < RelationTypeMetadata < RelationMetadata > > getRelationTypes ( Set < EntityDiscriminator > sourceDiscriminators , RelationDiscriminator discriminator , Set < EntityDiscriminator > targetDiscriminators ) { DynamicType < RelationTypeMetadata < RelationMetadata > > dynamicType = new DynamicType < > ( ) ; Set < RelationMapping < EntityDiscriminator , RelationMetadata , RelationDiscriminator > > relations = relationMappings . get ( discriminator ) ; if ( relations != null ) { Set < RelationTypeMetadata < RelationMetadata > > relationTypes = new HashSet < > ( ) ; for ( RelationMapping < EntityDiscriminator , RelationMetadata , RelationDiscriminator > relation : relations ) { Set < EntityDiscriminator > source = relation . getSource ( ) ; Set < EntityDiscriminator > target = relation . getTarget ( ) ; if ( sourceDiscriminators . containsAll ( source ) && targetDiscriminators . containsAll ( target ) ) { RelationTypeMetadata < RelationMetadata > relationType = relation . getRelationType ( ) ; relationTypes . add ( relationType ) ; } } dynamicType = new DynamicType < > ( relationTypes ) ; } return dynamicType ; } | Determine the relation type for the given source discriminators relation descriminator and target discriminators . |
7,964 | private < T > Map < PrimitivePropertyMethodMetadata < PropertyMetadata > , Object > prepareExample ( Example < T > example , Class < ? > type , Class < ? > ... types ) { Map < PrimitivePropertyMethodMetadata < PropertyMetadata > , Object > exampleEntity = new HashMap < > ( ) ; ExampleProxyMethodService < T > proxyMethodService = ( ExampleProxyMethodService < T > ) exampleProxyMethodServices . get ( type ) ; if ( proxyMethodService == null ) { proxyMethodService = new ExampleProxyMethodService ( type , sessionContext ) ; exampleProxyMethodServices . put ( type , proxyMethodService ) ; } InstanceInvocationHandler invocationHandler = new InstanceInvocationHandler ( exampleEntity , proxyMethodService ) ; List < Class < ? > > effectiveTypes = new ArrayList < > ( types . length + 1 ) ; effectiveTypes . add ( type ) ; effectiveTypes . addAll ( Arrays . asList ( types ) ) ; CompositeType compositeType = CompositeTypeBuilder . create ( CompositeObject . class , type , types ) ; T instance = sessionContext . getProxyFactory ( ) . createInstance ( invocationHandler , compositeType ) ; example . prepare ( instance ) ; return exampleEntity ; } | Setup an example entity . |
7,965 | private < T > ResultIterable < T > findByExample ( Class < ? > type , Map < PrimitivePropertyMethodMetadata < PropertyMetadata > , Object > entity ) { sessionContext . getCacheSynchronizationService ( ) . flush ( ) ; EntityTypeMetadata < EntityMetadata > entityTypeMetadata = sessionContext . getMetadataProvider ( ) . getEntityMetadata ( type ) ; EntityDiscriminator entityDiscriminator = entityTypeMetadata . getDatastoreMetadata ( ) . getDiscriminator ( ) ; if ( entityDiscriminator == null ) { throw new XOException ( "Type " + type . getName ( ) + " has no discriminator (i.e. cannot be identified in datastore)." ) ; } ResultIterator < Entity > iterator = sessionContext . getDatastoreSession ( ) . getDatastoreEntityManager ( ) . findEntity ( entityTypeMetadata , entityDiscriminator , entity ) ; AbstractInstanceManager < EntityId , Entity > entityInstanceManager = sessionContext . getEntityInstanceManager ( ) ; ResultIterator < T > resultIterator = new ResultIterator < T > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public T next ( ) { Entity entity = iterator . next ( ) ; return entityInstanceManager . readInstance ( entity ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "Cannot remove instance." ) ; } public void close ( ) { iterator . close ( ) ; } } ; XOTransaction xoTransaction = sessionContext . getXOTransaction ( ) ; final ResultIterator < T > transactionalIterator = xoTransaction != null ? new TransactionalResultIterator < > ( resultIterator , xoTransaction ) : resultIterator ; return sessionContext . getInterceptorFactory ( ) . addInterceptor ( new AbstractResultIterable < T > ( ) { public ResultIterator < T > iterator ( ) { return transactionalIterator ; } } , ResultIterable . class ) ; } | Find entities according to the given example entity . |
7,966 | private Set < Discriminator > getAggregatedDiscriminators ( EntityTypeMetadata < EntityMetadata > typeMetadata ) { Set < Discriminator > discriminators = aggregatedDiscriminators . get ( typeMetadata ) ; if ( discriminators == null ) { discriminators = new HashSet < > ( ) ; Discriminator discriminator = typeMetadata . getDatastoreMetadata ( ) . getDiscriminator ( ) ; if ( discriminator != null ) { discriminators . add ( discriminator ) ; } for ( EntityTypeMetadata < EntityMetadata > superTypeMetadata : aggregatedSuperTypes . get ( typeMetadata ) ) { discriminator = superTypeMetadata . getDatastoreMetadata ( ) . getDiscriminator ( ) ; if ( discriminator != null ) { discriminators . add ( discriminator ) ; } } aggregatedDiscriminators . put ( typeMetadata , discriminators ) ; } return discriminators ; } | Determine the set of discriminators for one type i . e . the discriminator of the type itself and of all it s super types . |
7,967 | public static Collection < Class < ? > > getTypes ( Collection < String > typeNames ) { Set < Class < ? > > types = new HashSet < > ( ) ; for ( String typeName : typeNames ) { types . add ( ClassHelper . getType ( typeName ) ) ; } return types ; } | Load a collection of classes . |
7,968 | public static < T > T newInstance ( Class < T > type ) { try { return type . newInstance ( ) ; } catch ( InstantiationException e ) { throw new XOException ( "Cannot create instance of type '" + type . getName ( ) + "'" , e ) ; } catch ( IllegalAccessException e ) { throw new XOException ( "Access denied to type '" + type . getName ( ) + "'" , e ) ; } } | Create an instance of a class . |
7,969 | public static Class < ? > getTypeParameter ( Class < ? > genericType , Class < ? > type ) { Type [ ] genericInterfaces = type . getGenericInterfaces ( ) ; for ( Type genericInterface : genericInterfaces ) { if ( genericInterface instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) genericInterface ; if ( genericType . equals ( parameterizedType . getRawType ( ) ) ) { Type typeParameter = ( ( ParameterizedType ) genericInterface ) . getActualTypeArguments ( ) [ 0 ] ; if ( typeParameter instanceof Class < ? > ) { return ( Class < ? > ) typeParameter ; } } } } return null ; } | Determines the type of a class implementing a generic interface with one type parameter . |
7,970 | public Collection < AnnotatedMethod > getMethods ( ) { for ( Method method : type . getDeclaredMethods ( ) ) { if ( ! method . isSynthetic ( ) ) { Class < ? > returnType = method . getReturnType ( ) ; Type genericReturnType = method . getGenericReturnType ( ) ; Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; Type [ ] genericParameterTypes = method . getGenericParameterTypes ( ) ; if ( PropertyMethod . GET . matches ( method ) ) { String name = PropertyMethod . GET . getName ( method ) ; getters . put ( name , method ) ; addType ( type , name , returnType , genericReturnType ) ; } else if ( PropertyMethod . IS . matches ( method ) ) { String name = PropertyMethod . IS . getName ( method ) ; getters . put ( name , method ) ; addType ( type , name , returnType , genericReturnType ) ; } else if ( PropertyMethod . SET . matches ( method ) ) { String name = PropertyMethod . SET . getName ( method ) ; setters . put ( name , method ) ; addType ( type , name , parameterTypes [ 0 ] , genericParameterTypes [ 0 ] ) ; } else { methods . add ( method ) ; } } } List < AnnotatedMethod > typeMethods = new ArrayList < > ( ) ; Map < String , GetPropertyMethod > getPropertyMethods = new HashMap < > ( ) ; for ( Map . Entry < String , Method > methodEntry : getters . entrySet ( ) ) { String name = methodEntry . getKey ( ) ; Method getter = methodEntry . getValue ( ) ; Class < ? > propertyType = types . get ( name ) ; Type genericType = genericTypes . get ( name ) ; GetPropertyMethod getPropertyMethod = new GetPropertyMethod ( getter , name , propertyType , genericType ) ; typeMethods . add ( getPropertyMethod ) ; getPropertyMethods . put ( name , getPropertyMethod ) ; } for ( Map . Entry < String , Method > methodEntry : setters . entrySet ( ) ) { String name = methodEntry . getKey ( ) ; Method setter = methodEntry . getValue ( ) ; GetPropertyMethod getPropertyMethod = getPropertyMethods . get ( name ) ; Class < ? > propertyType = types . get ( name ) ; Type genericType = genericTypes . get ( name ) ; SetPropertyMethod setPropertyMethod = new SetPropertyMethod ( setter , getPropertyMethod , name , propertyType , genericType ) ; typeMethods . add ( setPropertyMethod ) ; } for ( Method method : methods ) { typeMethods . add ( new UserMethod ( method ) ) ; } return typeMethods ; } | Return the methods of the type . |
7,971 | private List < Content > rewriteAnchor ( Element element ) { if ( element . getContent ( ) . isEmpty ( ) ) { element . setText ( "" ) ; } Link link = getAnchorLink ( element ) ; Element anchorElement = buildAnchorElement ( link , element ) ; List < Content > content = new ArrayList < Content > ( ) ; if ( anchorElement != null ) { anchorElement . addContent ( element . cloneContent ( ) ) ; content . add ( anchorElement ) ; } else { content . addAll ( element . getContent ( ) ) ; } return content ; } | Checks if the given anchor element has to be rewritten . |
7,972 | private boolean getAnchorLegacyMetadataFromSingleData ( ValueMap resourceProps , Element element ) { boolean foundAny = false ; JSONObject metadata = null ; Attribute dataAttribute = element . getAttribute ( "data" ) ; if ( dataAttribute != null ) { String metadataString = dataAttribute . getValue ( ) ; if ( StringUtils . isNotEmpty ( metadataString ) ) { try { metadata = new JSONObject ( metadataString ) ; } catch ( JSONException ex ) { log . debug ( "Invalid link metadata: " + metadataString , ex ) ; } } } if ( metadata != null ) { JSONArray names = metadata . names ( ) ; for ( int i = 0 ; i < names . length ( ) ; i ++ ) { String name = names . optString ( i ) ; resourceProps . put ( name , metadata . opt ( name ) ) ; foundAny = true ; } } return foundAny ; } | Support legacy data structures where link metadata is stored as JSON fragment in single HTML5 data attribute . |
7,973 | private void getAnchorLegacyMetadataFromRel ( ValueMap resourceProps , Element element ) { String href = element . getAttributeValue ( "href" ) ; String linkWindowTarget = element . getAttributeValue ( "target" ) ; if ( href == null || href . startsWith ( "#" ) ) { return ; } JSONObject metadata = null ; String metadataString = element . getAttributeValue ( "rel" ) ; if ( StringUtils . isNotEmpty ( metadataString ) ) { try { metadata = new JSONObject ( metadataString ) ; } catch ( JSONException ex ) { log . debug ( "Invalid link metadata: " + metadataString , ex ) ; } } if ( metadata == null ) { metadata = new JSONObject ( ) ; } JSONArray metadataPropertyNames = metadata . names ( ) ; if ( metadataPropertyNames != null ) { for ( int i = 0 ; i < metadataPropertyNames . length ( ) ; i ++ ) { String metadataPropertyName = metadataPropertyNames . optString ( i ) ; JSONArray valueArray = metadata . optJSONArray ( metadataPropertyName ) ; if ( valueArray != null ) { List < String > values = new ArrayList < String > ( ) ; for ( int j = 0 ; j < valueArray . length ( ) ; j ++ ) { values . add ( valueArray . optString ( j ) ) ; } resourceProps . put ( metadataPropertyName , values . toArray ( new String [ values . size ( ) ] ) ) ; } else { Object value = metadata . opt ( metadataPropertyName ) ; if ( value != null ) { resourceProps . put ( metadataPropertyName , value ) ; } } } } LinkType linkType = null ; String linkTypeString = resourceProps . get ( LinkNameConstants . PN_LINK_TYPE , String . class ) ; for ( Class < ? extends LinkType > candidateClass : linkHandlerConfig . getLinkTypes ( ) ) { LinkType candidate = AdaptTo . notNull ( adaptable , candidateClass ) ; if ( StringUtils . isNotEmpty ( linkTypeString ) ) { if ( StringUtils . equals ( linkTypeString , candidate . getId ( ) ) ) { linkType = candidate ; break ; } } else if ( candidate . accepts ( href ) ) { linkType = candidate ; break ; } } if ( linkType == null ) { return ; } if ( linkType instanceof InternalLinkType || linkType instanceof MediaLinkType ) { String htmlSuffix = "." + FileExtension . HTML ; if ( StringUtils . endsWith ( href , htmlSuffix ) ) { href = StringUtils . substringBeforeLast ( href , htmlSuffix ) ; } } resourceProps . put ( linkType . getPrimaryLinkRefProperty ( ) , href ) ; resourceProps . put ( LinkNameConstants . PN_LINK_WINDOW_TARGET , linkWindowTarget ) ; } | Support legacy data structures where link metadata is stored as JSON fragment in rel attribute . |
7,974 | private List < Content > rewriteImage ( Element element ) { Media media = getImageMedia ( element ) ; Element imageElement = buildImageElement ( media , element ) ; List < Content > content = new ArrayList < Content > ( ) ; if ( imageElement != null ) { content . add ( imageElement ) ; } return content ; } | Checks if the given image element has to be rewritten . |
7,975 | private Element buildImageElement ( Media media , Element element ) { if ( media . isValid ( ) ) { element . setAttribute ( "src" , media . getUrl ( ) ) ; } return element ; } | Builds image element for given media metadata . |
7,976 | private String unexternalizeImageRef ( String ref ) { String unexternalizedRef = ref ; if ( StringUtils . isNotEmpty ( unexternalizedRef ) ) { unexternalizedRef = decodeIfEncoded ( unexternalizedRef ) ; unexternalizedRef = StringUtils . removeEnd ( unexternalizedRef , "/" + JcrConstants . JCR_CONTENT + ".default" ) ; unexternalizedRef = StringUtils . removeEnd ( unexternalizedRef , "/_jcr_content.default" ) ; } return unexternalizedRef ; } | Converts the RTE externalized form of media reference to internal form . |
7,977 | private String decodeIfEncoded ( String value ) { if ( StringUtils . contains ( value , "%" ) ) { try { return URLDecoder . decode ( value , CharEncoding . UTF_8 ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } } return value ; } | URL - decode value if required . |
7,978 | public static Map < String , Object > keyValuePairAsMap ( String key , Object value ) { Map < String , Object > paramMap = new HashMap < > ( ) ; paramMap . put ( key , value ) ; return paramMap ; } | Convert key value pair to map |
7,979 | private Rendition getInlineRendition ( MediaArgs mediaArgs ) { return new InlineRendition ( this . resource , this . media , mediaArgs , this . fileName , this . adaptable ) ; } | Get inline rendition instance . |
7,980 | private void addRendition ( Set < RenditionMetadata > candidates , Rendition rendition , MediaArgs mediaArgs ) { if ( ! mediaArgs . isIncludeAssetThumbnails ( ) && AssetRendition . isThumbnailRendition ( rendition ) ) { return ; } boolean isIncludeAssetWebRenditions = mediaArgs . isIncludeAssetWebRenditions ( ) != null ? mediaArgs . isIncludeAssetWebRenditions ( ) : true ; if ( ! isIncludeAssetWebRenditions && AssetRendition . isWebRendition ( rendition ) ) { return ; } RenditionMetadata renditionMetadata = createRenditionMetadata ( rendition ) ; candidates . add ( renditionMetadata ) ; } | adds rendition to the list of candidates if it should be available for resolving |
7,981 | private Set < RenditionMetadata > getRendtionsMatchingFileExtensions ( String [ ] fileExtensions , MediaArgs mediaArgs ) { Set < RenditionMetadata > allRenditions = getAvailableRenditions ( mediaArgs ) ; if ( fileExtensions == null || fileExtensions . length == 0 ) { return allRenditions ; } Set < RenditionMetadata > matchingRenditions = new TreeSet < RenditionMetadata > ( ) ; for ( RenditionMetadata rendition : allRenditions ) { for ( String fileExtension : fileExtensions ) { if ( StringUtils . equalsIgnoreCase ( fileExtension , rendition . getFileExtension ( ) ) ) { matchingRenditions . add ( rendition ) ; break ; } } } return matchingRenditions ; } | Get all renditions that match the requested list of file extension . |
7,982 | private String [ ] getRequestedFileExtensions ( MediaArgs mediaArgs ) { Set < String > mediaArgsFileExtensions = new HashSet < String > ( ) ; if ( mediaArgs . getFileExtensions ( ) != null && mediaArgs . getFileExtensions ( ) . length > 0 ) { mediaArgsFileExtensions . addAll ( ImmutableList . copyOf ( mediaArgs . getFileExtensions ( ) ) ) ; } final Set < String > mediaFormatFileExtensions = new HashSet < String > ( ) ; visitMediaFormats ( mediaArgs , new MediaFormatVisitor < Object > ( ) { public Object visit ( MediaFormat mediaFormat ) { if ( mediaFormat . getExtensions ( ) != null && mediaFormat . getExtensions ( ) . length > 0 ) { mediaFormatFileExtensions . addAll ( ImmutableList . copyOf ( mediaFormat . getExtensions ( ) ) ) ; } return null ; } } ) ; final String [ ] fileExtensions ; if ( ! mediaArgsFileExtensions . isEmpty ( ) && ! mediaFormatFileExtensions . isEmpty ( ) ) { Collection < String > intersection = Sets . intersection ( mediaArgsFileExtensions , mediaFormatFileExtensions ) ; if ( intersection . isEmpty ( ) ) { return null ; } else { fileExtensions = intersection . toArray ( new String [ intersection . size ( ) ] ) ; } } else if ( ! mediaArgsFileExtensions . isEmpty ( ) ) { fileExtensions = mediaArgsFileExtensions . toArray ( new String [ mediaArgsFileExtensions . size ( ) ] ) ; } else { fileExtensions = mediaFormatFileExtensions . toArray ( new String [ mediaFormatFileExtensions . size ( ) ] ) ; } return fileExtensions ; } | Get merged list of file extensions from both media formats and media args . |
7,983 | private RenditionMetadata getExactMatchRendition ( final Set < RenditionMetadata > candidates , MediaArgs mediaArgs ) { if ( mediaArgs . getFixedWidth ( ) > 0 || mediaArgs . getFixedHeight ( ) > 0 ) { for ( RenditionMetadata candidate : candidates ) { if ( candidate . matches ( mediaArgs . getFixedWidth ( ) , mediaArgs . getFixedHeight ( ) ) ) { return candidate ; } } } else if ( mediaArgs . getMediaFormats ( ) != null && mediaArgs . getMediaFormats ( ) . length > 0 ) { return visitMediaFormats ( mediaArgs , new MediaFormatVisitor < RenditionMetadata > ( ) { public RenditionMetadata visit ( MediaFormat mediaFormat ) { for ( RenditionMetadata candidate : candidates ) { if ( candidate . matches ( ( int ) mediaFormat . getEffectiveMinWidth ( ) , ( int ) mediaFormat . getEffectiveMinHeight ( ) , ( int ) mediaFormat . getEffectiveMaxWidth ( ) , ( int ) mediaFormat . getEffectiveMaxHeight ( ) , mediaFormat . getRatio ( ) ) ) { candidate . setMediaFormat ( mediaFormat ) ; return candidate ; } } return null ; } } ) ; } else { return getOriginalOrFirstRendition ( candidates ) ; } return null ; } | Get rendition that matches exactly with the given media args requirements . |
7,984 | private RenditionMetadata getOriginalOrFirstRendition ( Set < RenditionMetadata > candidates ) { if ( this . originalRendition != null && candidates . contains ( this . originalRendition ) ) { return this . originalRendition ; } else if ( ! candidates . isEmpty ( ) ) { return candidates . iterator ( ) . next ( ) ; } else { return null ; } } | Returns original rendition - if it is contained in the candidate set . Otherwise first candidate is returned . If a VirtualCropRenditionMetadata is present always the first one is returned . |
7,985 | @ SuppressWarnings ( "null" ) private < T > T visitMediaFormats ( MediaArgs mediaArgs , MediaFormatVisitor < T > mediaFormatVisitor ) { MediaFormat [ ] mediaFormats = mediaArgs . getMediaFormats ( ) ; if ( mediaFormats != null ) { for ( MediaFormat mediaFormat : mediaFormats ) { T returnValue = mediaFormatVisitor . visit ( mediaFormat ) ; if ( returnValue != null ) { return returnValue ; } } } return null ; } | Iterate over all media formats defined in media args . Ignores invalid media formats . If the media format visitor returns a value that is not null iteration is stopped and the value is returned from this method . |
7,986 | private boolean resolveFirstMatchRenditions ( Media media , Asset asset , MediaArgs mediaArgs ) { Rendition rendition = asset . getRendition ( mediaArgs ) ; if ( rendition != null ) { media . setRenditions ( ImmutableList . of ( rendition ) ) ; media . setUrl ( rendition . getUrl ( ) ) ; return true ; } return false ; } | Check if a matching rendition is found for any of the provided media formats and other media args . The first match is returned . |
7,987 | private boolean resolveAllRenditions ( Media media , Asset asset , MediaArgs mediaArgs ) { boolean allMandatory = mediaArgs . isMediaFormatsMandatory ( ) ; boolean allResolved = true ; boolean anyResolved = false ; List < Rendition > resolvedRenditions = new ArrayList < > ( ) ; for ( MediaFormat mediaFormat : mediaArgs . getMediaFormats ( ) ) { MediaArgs renditionMediaArgs = mediaArgs . clone ( ) ; renditionMediaArgs . mediaFormat ( mediaFormat ) ; renditionMediaArgs . mediaFormatsMandatory ( false ) ; Rendition rendition = asset . getRendition ( renditionMediaArgs ) ; if ( rendition != null ) { resolvedRenditions . add ( rendition ) ; anyResolved = true ; } else { allResolved = false ; } } media . setRenditions ( resolvedRenditions ) ; if ( ! resolvedRenditions . isEmpty ( ) ) { media . setUrl ( resolvedRenditions . get ( 0 ) . getUrl ( ) ) ; } if ( allMandatory ) { return allResolved ; } else { return anyResolved ; } } | Iterates over all defined media format and tries to find a matching rendition for each of them in combination with the other media args . |
7,988 | public Page getRelativePage ( String relativePath ) { String path = getRootPath ( ) ; if ( path == null ) { return null ; } StringBuilder sb = new StringBuilder ( path ) ; if ( ! relativePath . startsWith ( "/" ) ) { sb . append ( "/" ) ; } sb . append ( relativePath ) ; return pageManager . getPage ( sb . toString ( ) ) ; } | Get page relative to site root . |
7,989 | protected boolean isNotModified ( Resource resource , SlingHttpServletRequest request , SlingHttpServletResponse response ) throws IOException { return CacheHeader . isNotModified ( resource , request , response , false ) ; } | Checks if the resource was modified since last request |
7,990 | protected void sendBinaryData ( byte [ ] binaryData , String contentType , SlingHttpServletRequest request , SlingHttpServletResponse response ) throws IOException { response . setContentType ( contentType ) ; response . setContentLength ( binaryData . length ) ; if ( RequestPath . hasSelector ( request , SELECTOR_DOWNLOAD ) ) { response . setContentType ( ContentType . DOWNLOAD ) ; StringBuilder dispositionHeader = new StringBuilder ( "attachment;" ) ; String suffix = request . getRequestPathInfo ( ) . getSuffix ( ) ; suffix = StringUtils . stripStart ( suffix , "/" ) ; if ( StringUtils . isNotEmpty ( suffix ) ) { dispositionHeader . append ( "filename=\"" ) . append ( suffix ) . append ( '\"' ) ; } response . setHeader ( HEADER_CONTENT_DISPOSITION , dispositionHeader . toString ( ) ) ; } OutputStream out = response . getOutputStream ( ) ; out . write ( binaryData ) ; out . flush ( ) ; } | Send binary data to output stream . Respect optional content disposition header handling . |
7,991 | protected UrlConfig getUrlConfigForTarget ( Adaptable adaptable , Page targetPage ) { Resource targetResource = null ; if ( targetPage != null ) { targetResource = targetPage . adaptTo ( Resource . class ) ; } return getUrlConfigForTarget ( adaptable , targetResource ) ; } | Get URL configuration for target page . If this is invalid or not available get it from adaptable . |
7,992 | protected UrlConfig getUrlConfigForTarget ( Adaptable adaptable , Resource targetResource ) { UrlConfig config = null ; if ( targetResource != null ) { config = new UrlConfig ( targetResource ) ; } if ( config == null || ! config . isValid ( ) ) { config = new UrlConfig ( adaptable ) ; } return config ; } | Get URL configuration for target resource . If this is invalid or not available get it from adaptable . |
7,993 | public MediaFormat build ( ) { if ( this . name == null ) { throw new IllegalArgumentException ( "Name is missing." ) ; } return new MediaFormat ( name , label , description , width , minWidth , maxWidth , height , minHeight , maxHeight , ratio , ratioWidth , ratioHeight , fileSizeMax , nonNullArray ( extensions ) , renditionGroup , download , internal , ranking , ImmutableValueMap . copyOf ( properties ) ) ; } | Builds the media format definition . |
7,994 | protected Rendition getDamRendition ( MediaArgs mediaArgs ) { return new DamRendition ( this . damAsset , this . cropDimension , this . rotation , mediaArgs , adaptable ) ; } | Get DAM rendition instance . |
7,995 | protected HtmlElement < ? > getImageElement ( Media media ) { Image img = new Image ( ) ; Asset asset = media . getAsset ( ) ; String altText = null ; if ( asset != null ) { altText = asset . getAltText ( ) ; } if ( StringUtils . isNotEmpty ( altText ) ) { img . setAlt ( altText ) ; } return img ; } | Create an IMG element with alt text . |
7,996 | protected void setResponsiveImageSource ( HtmlElement < ? > mediaElement , JSONArray responsiveImageSources , Media media ) { mediaElement . setData ( PROP_RESPONSIVE_SOURCES , responsiveImageSources . toString ( ) ) ; } | Set attribute on media element for responsive image sources |
7,997 | protected HtmlElement < ? > getImageElement ( Media media ) { Image img = new Image ( ) . addCssClass ( MediaNameConstants . CSS_DUMMYIMAGE ) ; return img ; } | Create an IMG element . |
7,998 | public HtmlComment createComment ( String text ) { HtmlComment comment = new HtmlComment ( text ) ; this . addContent ( comment ) ; return comment ; } | Creates and adds html comment . |
7,999 | private static boolean isNt ( Resource resource , String nodeTypeName ) { if ( resource != null ) { return StringUtils . equals ( resource . getResourceType ( ) , nodeTypeName ) ; } return false ; } | Checks if the given resource is a node with the given node type name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.