idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
34,600 | public String getAsString ( String key ) { Object value = mValues . get ( key ) ; return value != null ? value . toString ( ) : null ; } | Gets a value and converts it to a String . |
34,601 | public int getVersion ( ) throws SQLException { try { return this . submit ( new VersionCallable ( ) ) . get ( ) ; } catch ( InterruptedException e ) { logger . log ( Level . SEVERE , "Failed to get database version" , e ) ; throw new SQLException ( e ) ; } catch ( ExecutionException e ) { logger . log ( Level . SEVERE , "Failed to get database version" , e ) ; throw new SQLException ( e ) ; } } | Returns the current version of the database . |
34,602 | public < T > Future < T > submit ( SQLCallable < T > callable ) { return this . submitTaskToQueue ( new SQLQueueCallable < T > ( db , callable ) ) ; } | Submits a database task for execution |
34,603 | public < T > Future < T > submitTransaction ( SQLCallable < T > callable ) { return this . submitTaskToQueue ( new SQLQueueCallable < T > ( db , callable , true ) ) ; } | Submits a database task for execution in a transaction |
34,604 | public void shutdown ( ) { if ( acceptTasks . getAndSet ( false ) ) { Future < ? > close = queue . submit ( new Runnable ( ) { public void run ( ) { db . close ( ) ; } } ) ; queue . shutdown ( ) ; try { close . get ( ) ; queue . awaitTermination ( 5 , TimeUnit . MINUTES ) ; } catch ( InterruptedException e ) { logger . log ( Level . SEVERE , "Interrupted while waiting for queue to terminate" , e ) ; } catch ( ExecutionException e ) { logger . log ( Level . SEVERE , "Failed to close database" , e ) ; } } else { logger . log ( Level . WARNING , "Database is already closed." ) ; } } | Shuts down this database queue and closes the underlying database connection . Any tasks previously submitted for execution will still be executed however the queue will not accept additional tasks |
34,605 | private < T > Future < T > submitTaskToQueue ( SQLQueueCallable < T > callable ) { if ( acceptTasks . get ( ) ) { return queue . submit ( callable ) ; } else { throw new RejectedExecutionException ( "Database is closed" ) ; } } | Adds a task to the queue checking if the queue is still open to accepting tasks |
34,606 | public synchronized String getSQLiteVersion ( ) { if ( this . sqliteVersion == null ) { try { this . sqliteVersion = this . submit ( new SQLiteVersionCallable ( ) ) . get ( ) ; return sqliteVersion ; } catch ( InterruptedException e ) { logger . log ( Level . WARNING , "Could not determine SQLite version" , e ) ; } catch ( ExecutionException e ) { logger . log ( Level . WARNING , "Could not determine SQLite version" , e ) ; } this . sqliteVersion = "unknown" ; } return this . sqliteVersion ; } | Returns the SQLite Version . |
34,607 | private boolean validateEncryptionKeyData ( KeyData data ) { if ( data . getIv ( ) . length != ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE ) { LOGGER . warning ( "IV does not have the expected size: " + ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE + " bytes" ) ; return false ; } return true ; } | PRIVATE HELPER METHODS |
34,608 | @ SuppressWarnings ( "unchecked" ) private List < DBParameter > parametersToIndexRevision ( DocumentRevision rev , String indexName , List < FieldSort > fieldNames ) { Misc . checkNotNull ( rev , "rev" ) ; Misc . checkNotNull ( indexName , "indexName" ) ; Misc . checkNotNull ( fieldNames , "fieldNames" ) ; int arrayCount = 0 ; String arrayFieldName = null ; for ( FieldSort fieldName : fieldNames ) { Object value = ValueExtractor . extractValueForFieldName ( fieldName . field , rev . getBody ( ) ) ; if ( value != null && value instanceof List ) { arrayCount = arrayCount + 1 ; arrayFieldName = fieldName . field ; } } if ( arrayCount > 1 ) { String msg = String . format ( "Indexing %s in index %s includes > 1 array field; " + "Only one array field per index allowed." , rev . getId ( ) , indexName ) ; logger . log ( Level . SEVERE , msg ) ; return null ; } List < DBParameter > parameters = new ArrayList < DBParameter > ( ) ; List < Object > arrayFieldValues = null ; if ( arrayCount == 1 ) { arrayFieldValues = ( List ) ValueExtractor . extractValueForFieldName ( arrayFieldName , rev . getBody ( ) ) ; } if ( arrayFieldValues != null && arrayFieldValues . size ( ) > 0 ) { for ( Object value : arrayFieldValues ) { List < FieldSort > initialIncludedFields = Arrays . asList ( new FieldSort ( "_id" ) , new FieldSort ( "_rev" ) , new FieldSort ( arrayFieldName ) ) ; List < Object > initialArgs = Arrays . asList ( rev . getId ( ) , rev . getRevision ( ) , value ) ; DBParameter parameter = populateDBParameter ( fieldNames , initialIncludedFields , initialArgs , indexName , rev ) ; parameters . add ( parameter ) ; } } else { List < FieldSort > initialIncludedFields = Arrays . asList ( new FieldSort ( "_id" ) , new FieldSort ( "_rev" ) ) ; List < Object > initialArgs = Arrays . < Object > asList ( rev . getId ( ) , rev . getRevision ( ) ) ; DBParameter parameter = populateDBParameter ( fieldNames , initialIncludedFields , initialArgs , indexName , rev ) ; parameters . add ( parameter ) ; } return parameters ; } | Returns a List of DBParameters containing table name and ContentValues to index a document in an index . |
34,609 | private static SQLDatabase internalOpenSQLDatabase ( File dbFile , KeyProvider provider ) throws SQLException { boolean runningOnAndroid = Misc . isRunningOnAndroid ( ) ; boolean useSqlCipher = ( provider . getEncryptionKey ( ) != null ) ; try { if ( runningOnAndroid ) { if ( useSqlCipher ) { return ( SQLDatabase ) Class . forName ( "com.cloudant.sync.internal.sqlite.android" + ".AndroidSQLCipherSQLite" ) . getMethod ( "open" , File . class , KeyProvider . class ) . invoke ( null , new Object [ ] { dbFile , provider } ) ; } else { return ( SQLDatabase ) Class . forName ( "com.cloudant.sync.internal.sqlite.android" + ".AndroidSQLite" ) . getMethod ( "open" , File . class ) . invoke ( null , dbFile ) ; } } else { if ( useSqlCipher ) { throw new UnsupportedOperationException ( "No SQLCipher-based database " + "implementation for Java SE" ) ; } else { return ( SQLDatabase ) Class . forName ( "com.cloudant.sync.internal.sqlite" + ".sqlite4java.SQLiteWrapper" ) . getMethod ( "open" , File . class ) . invoke ( null , dbFile ) ; } } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "Failed to load database module" , e ) ; throw new SQLException ( "Failed to load database module" , e ) ; } } | Internal method for creating a SQLDatabase that allows a null filename to create an in - memory database which can be useful for performing checks but creating in - memory databases is not permitted from outside of this class hence the private visibility . |
34,610 | public Task createDocument ( Task task ) { DocumentRevision rev = new DocumentRevision ( ) ; rev . setBody ( DocumentBodyFactory . create ( task . asMap ( ) ) ) ; try { DocumentRevision created = this . mDocumentStore . database ( ) . create ( rev ) ; return Task . fromRevision ( created ) ; } catch ( DocumentException de ) { return null ; } catch ( DocumentStoreException de ) { return null ; } } | Creates a task assigning an ID . |
34,611 | public Task updateDocument ( Task task ) throws ConflictException , DocumentStoreException { DocumentRevision rev = task . getDocumentRevision ( ) ; rev . setBody ( DocumentBodyFactory . create ( task . asMap ( ) ) ) ; try { DocumentRevision updated = this . mDocumentStore . database ( ) . update ( rev ) ; return Task . fromRevision ( updated ) ; } catch ( DocumentException de ) { return null ; } } | Updates a Task document within the DocumentStore . |
34,612 | public void deleteDocument ( Task task ) throws ConflictException , DocumentNotFoundException , DocumentStoreException { this . mDocumentStore . database ( ) . delete ( task . getDocumentRevision ( ) ) ; } | Deletes a Task document within the DocumentStore . |
34,613 | protected static boolean validFieldName ( String fieldName ) { String [ ] parts = fieldName . split ( "\\." ) ; for ( String part : parts ) { if ( part . startsWith ( "$" ) ) { String msg = String . format ( "Field names cannot start with a $ in field %s" , part ) ; logger . log ( Level . SEVERE , msg ) ; return false ; } } return true ; } | Validate the field name string is usable . |
34,614 | public static String tokenizerToJson ( Tokenizer tokenizer ) { Map < String , String > settingsMap = new HashMap < String , String > ( ) ; if ( tokenizer != null ) { settingsMap . put ( TOKENIZE , tokenizer . tokenizerName ) ; settingsMap . put ( TOKENIZE_ARGS , tokenizer . tokenizerArguments ) ; } return JSONUtils . serializeAsString ( settingsMap ) ; } | Convert Tokenizer into serialized options or empty map if null |
34,615 | public static UnindexedMatcher matcherWithSelector ( Map < String , Object > selector ) { ChildrenQueryNode root = buildExecutionTreeForSelector ( selector ) ; if ( root == null ) { return null ; } UnindexedMatcher matcher = new UnindexedMatcher ( ) ; matcher . root = root ; return matcher ; } | Return a new initialised matcher . |
34,616 | protected static boolean compareLT ( Object l , Object r ) { if ( l == null || r == null ) { return false ; } else if ( ! ( l instanceof String || l instanceof Number ) ) { String msg = String . format ( "Value in document not a Number or String: %s" , l ) ; logger . log ( Level . WARNING , msg ) ; return false ; } else if ( l instanceof String ) { if ( r instanceof Number ) { return false ; } String lStr = ( String ) l ; String rStr = ( String ) r ; return lStr . compareTo ( rStr ) < 0 ; } else if ( r instanceof String ) { return true ; } else { Number lNum = ( Number ) l ; Number rNum = ( Number ) r ; return lNum . doubleValue ( ) < rNum . doubleValue ( ) ; } } | 4 . BLOB |
34,617 | public List < String > documentIds ( ) { List < String > documentIds = new ArrayList < String > ( ) ; List < DocumentRevision > docs = CollectionUtils . newArrayList ( iterator ( ) ) ; for ( DocumentRevision doc : docs ) { documentIds . add ( doc . getId ( ) ) ; } return documentIds ; } | Returns a list of the document IDs in this query result . |
34,618 | public static List < String > createRevisionIdHistory ( DocumentRevs documentRevs ) { validateDocumentRevs ( documentRevs ) ; String latestRevision = documentRevs . getRev ( ) ; int generation = CouchUtils . generationFromRevId ( latestRevision ) ; assert generation == documentRevs . getRevisions ( ) . getStart ( ) ; List < String > revisionHistory = CouchUtils . couchStyleRevisionHistoryToFullRevisionIDs ( generation , documentRevs . getRevisions ( ) . getIds ( ) ) ; logger . log ( Level . FINER , "Revisions history: " + revisionHistory ) ; return revisionHistory ; } | Create the list of the revision IDs in ascending order . |
34,619 | public List < DocumentRevision > delete ( final String id ) throws DocumentNotFoundException , DocumentStoreException { Misc . checkNotNull ( id , "ID" ) ; try { if ( id . startsWith ( CouchConstants . _local_prefix ) ) { String localId = id . substring ( CouchConstants . _local_prefix . length ( ) ) ; deleteLocalDocument ( localId ) ; return Collections . singletonList ( null ) ; } else { return get ( queue . submitTransaction ( new DeleteAllRevisionsCallable ( id ) ) ) ; } } catch ( ExecutionException e ) { throwCauseAs ( e , DocumentNotFoundException . class ) ; String message = "Failed to delete document" ; logger . log ( Level . SEVERE , message , e ) ; throw new DocumentStoreException ( message , e . getCause ( ) ) ; } } | delete all leaf nodes |
34,620 | public static < T > T get ( Future < T > future ) throws ExecutionException { try { return future . get ( ) ; } catch ( InterruptedException e ) { logger . log ( Level . SEVERE , "Re-throwing InterruptedException as ExecutionException" ) ; throw new ExecutionException ( e ) ; } } | helper to avoid having to catch ExecutionExceptions |
34,621 | public static String join ( String separator , Collection < String > stringsToJoin ) { StringBuilder builder = new StringBuilder ( ) ; int index = stringsToJoin . size ( ) ; for ( String str : stringsToJoin ) { index -- ; if ( str != null ) { builder . append ( str ) ; if ( index > 0 ) { builder . append ( separator ) ; } } } return builder . toString ( ) ; } | Utility to join strings with a separator . Skips null strings and does not append a trailing separator . |
34,622 | public static void checkNotNull ( Object param , String errorMessagePrefix ) throws IllegalArgumentException { checkArgument ( param != null , ( errorMessagePrefix != null ? errorMessagePrefix : "Parameter" ) + " must not be null." ) ; } | Check that a parameter is not null and throw IllegalArgumentException with a message of errorMessagePrefix + must not be null . if it is null defaulting to Parameter must not be null . . |
34,623 | public static void checkNotNullOrEmpty ( String param , String errorMessagePrefix ) throws IllegalArgumentException { checkNotNull ( param , errorMessagePrefix ) ; checkArgument ( ! param . isEmpty ( ) , ( errorMessagePrefix != null ? errorMessagePrefix : "Parameter" ) + " must not be empty." ) ; } | Check that a string parameter is not null or empty and throw IllegalArgumentException with a message of errorMessagePrefix + must not be empty . if it is empty defaulting to Parameter must not be empty . |
34,624 | private void setup ( ) { try { this . partBoundary = ( "--" + boundary ) . getBytes ( "UTF-8" ) ; this . trailingBoundary = ( "--" + boundary + "--" ) . getBytes ( "UTF-8" ) ; this . contentType = "content-type: application/json" . getBytes ( "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } attachments = new ArrayList < Attachment > ( ) ; contentLength += partBoundary . length ; contentLength += 6 ; contentLength += contentType . length ; contentLength += 2 ; contentLength += trailingBoundary . length ; } | common constructor stuff |
34,625 | public static void updateAllIndexes ( List < Index > indexes , Database database , SQLDatabaseQueue queue ) throws QueryException { IndexUpdater updater = new IndexUpdater ( database , queue ) ; updater . updateAllIndexes ( indexes ) ; } | Update all indexes in a set . |
34,626 | public static void updateIndex ( String indexName , List < FieldSort > fieldNames , Database database , SQLDatabaseQueue queue ) throws QueryException { IndexUpdater updater = new IndexUpdater ( database , queue ) ; updater . updateIndex ( indexName , fieldNames ) ; } | Update a single index . |
34,627 | public void setOthers ( String name , Object value ) { if ( name . startsWith ( "_" ) ) { throw new RuntimeException ( "This is a reserved field, and should not be treated as document content." ) ; } this . others . put ( name , value ) ; } | Jackson will automatically put any field it can not find match to this |
34,628 | @ SuppressWarnings ( "unchecked" ) public static Map < String , Object > normaliseAndValidateQuery ( Map < String , Object > query ) throws QueryException { boolean isWildCard = false ; if ( query . isEmpty ( ) ) { isWildCard = true ; } query = addImplicitAnd ( query ) ; String compoundOperator = ( String ) query . keySet ( ) . toArray ( ) [ 0 ] ; List < Object > predicates = new ArrayList < Object > ( ) ; if ( query . get ( compoundOperator ) instanceof List ) { predicates = addImplicitEq ( ( List < Object > ) query . get ( compoundOperator ) ) ; predicates = handleShortHandOperators ( predicates ) ; predicates = compressMultipleNotOperators ( predicates ) ; predicates = truncateModArguments ( predicates ) ; } Map < String , Object > selector = new HashMap < String , Object > ( ) ; selector . put ( compoundOperator , predicates ) ; if ( ! isWildCard ) { validateSelector ( selector ) ; } return selector ; } | Expand implicit operators in a query and validate |
34,629 | @ SuppressWarnings ( "unchecked" ) private static void validateSelector ( Map < String , Object > selector ) throws QueryException { String topLevelOp = ( String ) selector . keySet ( ) . toArray ( ) [ 0 ] ; if ( topLevelOp . equals ( AND ) || topLevelOp . equals ( OR ) ) { Object topLevelArg = selector . get ( topLevelOp ) ; if ( topLevelArg instanceof List ) { validateCompoundOperatorClauses ( ( List < Object > ) topLevelArg , new Boolean [ ] { false } ) ; } } } | we are going to need to walk the query tree to validate it before executing it |
34,630 | @ SuppressWarnings ( "unchecked" ) private static void validateCompoundOperatorClauses ( List < Object > clauses , Boolean [ ] textClauseLimitReached ) throws QueryException { for ( Object obj : clauses ) { if ( ! ( obj instanceof Map ) ) { String msg = String . format ( "Operator argument must be a Map %s" , clauses . toString ( ) ) ; throw new QueryException ( msg ) ; } Map < String , Object > clause = ( Map < String , Object > ) obj ; if ( clause . size ( ) != 1 ) { String msg ; msg = String . format ( "Operator argument clause should have one key value pair: %s" , clauses . toString ( ) ) ; throw new QueryException ( msg ) ; } String key = ( String ) clause . keySet ( ) . toArray ( ) [ 0 ] ; if ( Arrays . asList ( OR , NOT , AND ) . contains ( key ) ) { Object compoundClauses = clause . get ( key ) ; validateCompoundOperatorOperand ( compoundClauses ) ; validateCompoundOperatorClauses ( ( List < Object > ) compoundClauses , textClauseLimitReached ) ; } else if ( ! ( key . startsWith ( "$" ) ) ) { validateClause ( ( Map < String , Object > ) clause . get ( key ) ) ; } else if ( key . equalsIgnoreCase ( TEXT ) ) { validateTextClause ( clause . get ( key ) , textClauseLimitReached ) ; } else { String msg = String . format ( "%s operator cannot be a top level operator" , key ) ; throw new QueryException ( msg ) ; } } } | This method runs the list of clauses making up the selector through a series of validation steps and returns whether the clause list is valid or not . |
34,631 | public InputStream getInputStream ( File file , Attachment . Encoding encoding ) throws IOException { InputStream is = new FileInputStream ( file ) ; if ( key != null ) { try { is = new EncryptedAttachmentInputStream ( is , key ) ; } catch ( InvalidKeyException ex ) { throw new IOException ( "Bad key used to open file; check encryption key." , ex ) ; } } switch ( encoding ) { case Plain : break ; case Gzip : is = new GZIPInputStream ( is ) ; } return is ; } | Return a stream to be used to read from the file on disk . |
34,632 | public OutputStream getOutputStream ( File file , Attachment . Encoding encoding ) throws IOException { OutputStream os = FileUtils . openOutputStream ( file ) ; if ( key != null ) { try { byte [ ] iv = new byte [ 16 ] ; new SecureRandom ( ) . nextBytes ( iv ) ; os = new EncryptedAttachmentOutputStream ( os , key , iv ) ; } catch ( InvalidKeyException ex ) { throw new IOException ( "Bad key used to write file; check encryption key." , ex ) ; } catch ( InvalidAlgorithmParameterException ex ) { throw new IOException ( "Bad key used to write file; check encryption key." , ex ) ; } } switch ( encoding ) { case Plain : break ; case Gzip : os = new GZIPOutputStream ( os ) ; } return os ; } | Get stream for writing attachment data to disk . |
34,633 | public void addValueToKey ( K key , V value ) { this . addValuesToKey ( key , Collections . singletonList ( value ) ) ; } | Add a value to the map under the existing key or creating a new key if it does not yet exist . |
34,634 | public void addValuesToKey ( K key , Collection < V > valueCollection ) { if ( ! valueCollection . isEmpty ( ) ) { List < V > collectionToAppendValuesOn = new ArrayList < V > ( ) ; List < V > existing = this . putIfAbsent ( key , collectionToAppendValuesOn ) ; if ( existing != null ) { collectionToAppendValuesOn = existing ; } collectionToAppendValuesOn . addAll ( valueCollection ) ; } } | Add a collection of one or more values to the map under the existing key or creating a new key if it does not yet exist in the map . |
34,635 | private String queryAsString ( Map < String , Object > query ) { ArrayList < String > queryParts = new ArrayList < String > ( query . size ( ) ) ; for ( Map . Entry < String , Object > entry : query . entrySet ( ) ) { String value = this . encodeQueryParameter ( entry . getValue ( ) . toString ( ) ) ; String key = this . encodeQueryParameter ( entry . getKey ( ) ) ; String term = String . format ( "%s=%s" , key , value ) ; queryParts . add ( term ) ; } return Misc . join ( "&" , queryParts ) ; } | Joins the entries in a map into a URL - encoded query string . |
34,636 | void replicationComplete ( ) { reloadTasksFromModel ( ) ; Toast . makeText ( getApplicationContext ( ) , R . string . replication_completed , Toast . LENGTH_LONG ) . show ( ) ; dismissDialog ( DIALOG_PROGRESS ) ; } | Called by TasksModel when it receives a replication complete callback . TasksModel takes care of calling this on the main thread . |
34,637 | void replicationError ( ) { Log . i ( LOG_TAG , "error()" ) ; reloadTasksFromModel ( ) ; Toast . makeText ( getApplicationContext ( ) , R . string . replication_error , Toast . LENGTH_LONG ) . show ( ) ; dismissDialog ( DIALOG_PROGRESS ) ; } | Called by TasksModel when it receives a replication error callback . TasksModel takes care of calling this on the main thread . |
34,638 | protected static PreparedAttachment prepareAttachment ( String attachmentsDir , AttachmentStreamFactory attachmentStreamFactory , Attachment attachment , long length , long encodedLength ) throws AttachmentException { PreparedAttachment pa = new PreparedAttachment ( attachment , attachmentsDir , length , attachmentStreamFactory ) ; if ( pa . attachment . encoding == Attachment . Encoding . Plain ) { if ( pa . length != length ) { throw new AttachmentNotSavedException ( String . format ( "Actual length of %d does not equal expected length of %d" , pa . length , length ) ) ; } } else { if ( pa . encodedLength != encodedLength ) { throw new AttachmentNotSavedException ( String . format ( "Actual encoded length of %d does not equal expected encoded length of %d" , pa . encodedLength , pa . length ) ) ; } } return pa ; } | prepare an attachment and check validity of length and encodedLength metadata |
34,639 | public static Map < String , SavedAttachment > findExistingAttachments ( Map < String , ? extends Attachment > attachments ) { Map < String , SavedAttachment > existingAttachments = new HashMap < String , SavedAttachment > ( ) ; for ( Map . Entry < String , ? extends Attachment > a : attachments . entrySet ( ) ) { if ( a instanceof SavedAttachment ) { existingAttachments . put ( a . getKey ( ) , ( SavedAttachment ) a . getValue ( ) ) ; } } return existingAttachments ; } | Return a map of the existing attachments in the map passed in . |
34,640 | public static Map < String , Attachment > findNewAttachments ( Map < String , ? extends Attachment > attachments ) { Map < String , Attachment > newAttachments = new HashMap < String , Attachment > ( ) ; for ( Map . Entry < String , ? extends Attachment > a : attachments . entrySet ( ) ) { if ( ! ( a instanceof SavedAttachment ) ) { newAttachments . put ( a . getKey ( ) , a . getValue ( ) ) ; } } return newAttachments ; } | Return a map of the new attachments in the map passed in . |
34,641 | public static void copyAttachment ( SQLDatabase db , long parentSequence , long newSequence , String filename ) throws SQLException { Cursor c = null ; try { c = db . rawQuery ( SQL_ATTACHMENTS_SELECT , new String [ ] { filename , String . valueOf ( parentSequence ) } ) ; copyCursorValuesToNewSequence ( db , c , newSequence ) ; } finally { DatabaseUtils . closeCursorQuietly ( c ) ; } } | Copy a single attachment for a given revision to a new revision . |
34,642 | public static void purgeAttachments ( SQLDatabase db , String attachmentsDir ) { Set < String > currentKeys = new HashSet < String > ( ) ; Cursor c = null ; try { db . delete ( "attachments" , "sequence IN " + "(SELECT sequence from revs WHERE json IS null)" , null ) ; c = db . rawQuery ( SQL_ATTACHMENTS_SELECT_ALL_KEYS , null ) ; while ( c . moveToNext ( ) ) { byte [ ] key = c . getBlob ( 0 ) ; currentKeys . add ( keyToString ( key ) ) ; } } catch ( SQLException e ) { logger . log ( Level . SEVERE , "SQL exception in purgeAttachments when updating attachments table" , e ) ; return ; } finally { DatabaseUtils . closeCursorQuietly ( c ) ; } try { File attachments = new File ( attachmentsDir ) ; c = db . rawQuery ( SQL_ATTACHMENTS_SELECT_KEYS_FILENAMES , null ) ; while ( c . moveToNext ( ) ) { String keyForFile = c . getString ( 0 ) ; if ( ! currentKeys . contains ( keyForFile ) ) { File f = new File ( attachments , c . getString ( 1 ) ) ; try { boolean deleted = f . delete ( ) ; if ( deleted ) { db . delete ( ATTACHMENTS_KEY_FILENAME , "key = ?" , new String [ ] { keyForFile } ) ; } else { logger . warning ( "Could not delete file from BLOB store: " + f . getAbsolutePath ( ) ) ; } } catch ( SecurityException e ) { String msg = String . format ( "SecurityException deleting %s from blob store" , f . getAbsolutePath ( ) ) ; logger . log ( Level . WARNING , msg , e ) ; } } } } catch ( SQLException e ) { logger . log ( Level . SEVERE , "SQL exception in purgeAttachments when removing redundant attachments" , e ) ; } finally { DatabaseUtils . closeCursorQuietly ( c ) ; } } | Called by DatabaseImpl on the execution queue this needs to have the db passed to it . |
34,643 | static String generateFilenameForKey ( SQLDatabase db , String keyString ) throws NameGenerationException { String filename = null ; long result = - 1 ; int tries = 0 ; while ( result == - 1 && tries < 200 ) { byte [ ] randomBytes = new byte [ 20 ] ; filenameRandom . nextBytes ( randomBytes ) ; String candidate = keyToString ( randomBytes ) ; ContentValues contentValues = new ContentValues ( ) ; contentValues . put ( "key" , keyString ) ; contentValues . put ( "filename" , candidate ) ; result = db . insert ( ATTACHMENTS_KEY_FILENAME , contentValues ) ; if ( result != - 1 ) { filename = candidate ; } tries ++ ; } if ( filename != null ) { return filename ; } else { throw new NameGenerationException ( String . format ( "Couldn't generate unique filename for attachment with key %s" , keyString ) ) ; } } | Iterate candidate filenames generated from the filenameRandom generator until we find one which doesn t already exist . |
34,644 | public void put ( int index , long value ) { if ( desc . get ( index ) != Cursor . FIELD_TYPE_INTEGER ) { throw new IllegalArgumentException ( "Inserting an integer, but expecting " + getTypeName ( desc . get ( index ) ) ) ; } this . values . add ( index , value ) ; } | Internally we always store the SQLite number as long |
34,645 | private URI addAuthInterceptorIfRequired ( URI uri ) { String uriProtocol = uri . getScheme ( ) ; String uriHost = uri . getHost ( ) ; String uriPath = uri . getRawPath ( ) ; int uriPort = getDefaultPort ( uri ) ; setUserInfo ( uri ) ; setAuthInterceptor ( uriHost , uriPath , uriProtocol , uriPort ) ; return scrubUri ( uri , uriHost , uriPath , uriProtocol , uriPort ) ; } | - else add cookie interceptor if needed |
34,646 | public E username ( String username ) { Misc . checkNotNull ( username , "username" ) ; this . username = username ; return ( E ) this ; } | Sets the username to use when authenticating with the server . |
34,647 | public E password ( String password ) { Misc . checkNotNull ( password , "password" ) ; this . password = password ; return ( E ) this ; } | Sets the password to use when authenticating with the server . |
34,648 | public List < Index > listIndexes ( ) throws QueryException { try { return DatabaseImpl . get ( dbQueue . submit ( new ListIndexesCallable ( ) ) ) ; } catch ( ExecutionException e ) { String msg = "Failed to list indexes" ; logger . log ( Level . SEVERE , msg , e ) ; throw new QueryException ( msg , e ) ; } } | Get a list of indexes and their definitions as a Map . |
34,649 | private Index ensureIndexed ( List < FieldSort > fieldNames , String indexName , IndexType indexType , Tokenizer tokenizer ) throws QueryException { synchronized ( this ) { return IndexCreator . ensureIndexed ( new Index ( fieldNames , indexName , indexType , tokenizer ) , database , dbQueue ) ; } } | Add a single possibly compound index for the given field names . |
34,650 | public void deleteIndex ( final String indexName ) throws QueryException { Misc . checkNotNullOrEmpty ( indexName , "indexName" ) ; Future < Void > result = dbQueue . submitTransaction ( new DeleteIndexCallable ( indexName ) ) ; try { result . get ( ) ; } catch ( ExecutionException e ) { String message = "Execution error during index deletion" ; logger . log ( Level . SEVERE , message , e ) ; throw new QueryException ( message , e ) ; } catch ( InterruptedException e ) { String message = "Execution interrupted error during index deletion" ; logger . log ( Level . SEVERE , message , e ) ; throw new QueryException ( message , e ) ; } } | Delete an index . |
34,651 | public void refreshAllIndexes ( ) throws QueryException { List < Index > indexes = listIndexes ( ) ; IndexUpdater . updateAllIndexes ( indexes , database , dbQueue ) ; } | Update all indexes . |
34,652 | public QueryResult find ( Map < String , Object > query , final List < Index > indexes , long skip , long limit , List < String > fields , final List < FieldSort > sortDocument ) throws QueryException { fields = normaliseFields ( fields ) ; validateFields ( fields ) ; query = QueryValidator . normaliseAndValidateQuery ( query ) ; Boolean [ ] indexesCoverQuery = new Boolean [ ] { false } ; final ChildrenQueryNode root = translateQuery ( query , indexes , indexesCoverQuery ) ; Future < List < String > > result = queue . submit ( new SQLCallable < List < String > > ( ) { public List < String > call ( SQLDatabase database ) throws Exception { Set < String > docIdSet = executeQueryTree ( root , database ) ; List < String > docIdList ; if ( sortDocument != null && ! sortDocument . isEmpty ( ) ) { docIdList = sortIds ( docIdSet , sortDocument , indexes , database ) ; } else { docIdList = docIdSet != null ? new ArrayList < String > ( docIdSet ) : null ; } return docIdList ; } } ) ; List < String > docIds ; try { docIds = result . get ( ) ; } catch ( ExecutionException e ) { String message = "Execution error encountered" ; logger . log ( Level . SEVERE , message , e ) ; throw new QueryException ( message , e . getCause ( ) ) ; } catch ( InterruptedException e ) { String message = "Execution interrupted error encountered" ; logger . log ( Level . SEVERE , message , e ) ; throw new QueryException ( message , e . getCause ( ) ) ; } if ( docIds == null ) { return null ; } UnindexedMatcher matcher = matcherForIndexCoverage ( indexesCoverQuery , query ) ; if ( matcher != null ) { String msg = "query could not be executed using indexes alone; falling back to " ; msg += "filtering documents themselves. This will be VERY SLOW as each candidate " ; msg += "document is loaded from the datastore and matched against the query selector." ; logger . log ( Level . WARNING , msg ) ; } return new QueryResult ( docIds , database , fields , skip , limit , matcher ) ; } | Execute the query passed using the selection of index definition provided . |
34,653 | private void validateFields ( List < String > fields ) { if ( fields == null ) { return ; } List < String > badFields = new ArrayList < String > ( ) ; for ( String field : fields ) { if ( field . contains ( "." ) ) { badFields . add ( field ) ; } } if ( ! badFields . isEmpty ( ) ) { String msg = String . format ( "Projection field(s) cannot use dotted notation: %s" , Misc . join ( ", " , badFields ) ) ; logger . log ( Level . SEVERE , msg ) ; throw new IllegalArgumentException ( msg ) ; } } | Checks if the fields are valid . |
34,654 | private List < String > sortIds ( Set < String > docIdSet , List < FieldSort > sortDocument , List < Index > indexes , SQLDatabase db ) throws QueryException { boolean smallResultSet = ( docIdSet . size ( ) < SMALL_RESULT_SET_SIZE_THRESHOLD ) ; SqlParts orderBy = sqlToSortIds ( docIdSet , sortDocument , indexes ) ; List < String > sortedIds = null ; Cursor cursor = null ; try { cursor = db . rawQuery ( orderBy . sqlWithPlaceHolders , orderBy . placeHolderValues ) ; while ( cursor . moveToNext ( ) ) { if ( sortedIds == null ) { sortedIds = new ArrayList < String > ( ) ; } String candidateId = cursor . getString ( 0 ) ; if ( smallResultSet ) { sortedIds . add ( candidateId ) ; } else { if ( docIdSet . contains ( candidateId ) ) { sortedIds . add ( candidateId ) ; } } } } catch ( SQLException e ) { logger . log ( Level . SEVERE , "Failed to sort doc ids." , e ) ; return null ; } finally { DatabaseUtils . closeCursorQuietly ( cursor ) ; } return sortedIds ; } | Return ordered list of document IDs using provided indexes . |
34,655 | protected static SqlParts sqlToSortIds ( Set < String > docIdSet , List < FieldSort > sortDocument , List < Index > indexes ) throws QueryException { String chosenIndex = chooseIndexForSort ( sortDocument , indexes ) ; if ( chosenIndex == null ) { String msg = String . format ( Locale . ENGLISH , "No single index can satisfy order %s" , sortDocument ) ; logger . log ( Level . SEVERE , msg ) ; throw new QueryException ( msg ) ; } String indexTable = QueryImpl . tableNameForIndex ( chosenIndex ) ; List < String > orderClauses = new ArrayList < String > ( ) ; for ( FieldSort clause : sortDocument ) { String fieldName = clause . field ; String direction = clause . sort == FieldSort . Direction . ASCENDING ? "asc" : "desc" ; String orderClause = String . format ( "\"%s\" %s" , fieldName , direction . toUpperCase ( Locale . ENGLISH ) ) ; orderClauses . add ( orderClause ) ; } List < String > parameterList = new ArrayList < String > ( ) ; String whereClause = "" ; if ( docIdSet . size ( ) < SMALL_RESULT_SET_SIZE_THRESHOLD ) { List < String > placeholders = new ArrayList < String > ( ) ; for ( String docId : docIdSet ) { placeholders . add ( "?" ) ; parameterList . add ( docId ) ; } whereClause = String . format ( "WHERE _id IN (%s)" , Misc . join ( ", " , placeholders ) ) ; } String orderBy = Misc . join ( ", " , orderClauses ) ; String sql = String . format ( "SELECT DISTINCT _id FROM %s %s ORDER BY %s" , indexTable , whereClause , orderBy ) ; String [ ] parameters = new String [ parameterList . size ( ) ] ; return SqlParts . partsForSql ( sql , parameterList . toArray ( parameters ) ) ; } | Return SQL to get ordered list of docIds . |
34,656 | public static String generateNextRevisionId ( String revisionId ) { validateRevisionId ( revisionId ) ; int generation = generationFromRevId ( revisionId ) ; String digest = createUUID ( ) ; return Integer . toString ( generation + 1 ) + "-" + digest ; } | DBObject IDs have a generation count a hyphen and a UUID . |
34,657 | public static AndroidSQLCipherSQLite open ( File path , KeyProvider provider ) { SQLiteDatabase db = SQLiteDatabase . openOrCreateDatabase ( path , KeyUtils . sqlCipherKeyForKeyProvider ( provider ) , null ) ; return new AndroidSQLCipherSQLite ( db ) ; } | Constructor for creating SQLCipher - based SQLite database . |
34,658 | protected void upgradePreferences ( ) { String alarmDueElapsed = "com.cloudant.sync.replication.PeriodicReplicationService.alarmDueElapsed" ; if ( mPrefs . contains ( alarmDueElapsed ) ) { String alarmDueClock = "com.cloudant.sync.replication.PeriodicReplicationService.alarmDueClock" ; String replicationsActive = "com.cloudant.sync.replication.PeriodicReplicationService.periodicReplicationsActive" ; long elapsed = mPrefs . getLong ( alarmDueElapsed , 0 ) ; long clock = mPrefs . getLong ( alarmDueClock , 0 ) ; boolean enabled = mPrefs . getBoolean ( replicationsActive , false ) ; SharedPreferences . Editor editor = mPrefs . edit ( ) ; editor . putLong ( constructKey ( LAST_ALARM_ELAPSED_TIME_SUFFIX ) , elapsed - ( getIntervalInSeconds ( ) * MILLISECONDS_IN_SECOND ) ) ; editor . putLong ( constructKey ( LAST_ALARM_CLOCK_TIME_SUFFIX ) , clock - ( getIntervalInSeconds ( ) * MILLISECONDS_IN_SECOND ) ) ; editor . putBoolean ( constructKey ( PERIODIC_REPLICATION_ENABLED_SUFFIX ) , enabled ) ; editor . remove ( alarmDueElapsed ) ; editor . remove ( alarmDueClock ) ; editor . remove ( replicationsActive ) ; editor . apply ( ) ; } } | If the stored preferences are in the old format upgrade them to the new format so that the app continues to work after upgrade to this version . |
34,659 | public synchronized void startPeriodicReplication ( ) { if ( ! isPeriodicReplicationEnabled ( ) ) { setPeriodicReplicationEnabled ( true ) ; AlarmManager alarmManager = ( AlarmManager ) getSystemService ( Context . ALARM_SERVICE ) ; Intent alarmIntent = new Intent ( this , clazz ) ; alarmIntent . setAction ( PeriodicReplicationReceiver . ALARM_ACTION ) ; PendingIntent pendingAlarmIntent = PendingIntent . getBroadcast ( this , 0 , alarmIntent , 0 ) ; long initialTriggerTime ; if ( explicitlyStopped ( ) ) { initialTriggerTime = SystemClock . elapsedRealtime ( ) ; setExplicitlyStopped ( false ) ; } else { initialTriggerTime = getNextAlarmDueElapsedTime ( ) ; } alarmManager . setInexactRepeating ( AlarmManager . ELAPSED_REALTIME_WAKEUP , initialTriggerTime , getIntervalInSeconds ( ) * MILLISECONDS_IN_SECOND , pendingAlarmIntent ) ; } else { Log . i ( TAG , "Attempted to start an already running alarm manager" ) ; } } | Start periodic replications . |
34,660 | public synchronized void stopPeriodicReplication ( ) { if ( isPeriodicReplicationEnabled ( ) ) { setPeriodicReplicationEnabled ( false ) ; AlarmManager alarmManager = ( AlarmManager ) getSystemService ( Context . ALARM_SERVICE ) ; Intent alarmIntent = new Intent ( this , clazz ) ; alarmIntent . setAction ( PeriodicReplicationReceiver . ALARM_ACTION ) ; PendingIntent pendingAlarmIntent = PendingIntent . getBroadcast ( this , 0 , alarmIntent , 0 ) ; alarmManager . cancel ( pendingAlarmIntent ) ; stopReplications ( ) ; } else { Log . i ( TAG , "Attempted to stop an already stopped alarm manager" ) ; } } | Stop replications currently in progress and cancel future scheduled replications . |
34,661 | private void setPeriodicReplicationEnabled ( boolean running ) { SharedPreferences . Editor editor = mPrefs . edit ( ) ; editor . putBoolean ( constructKey ( PERIODIC_REPLICATION_ENABLED_SUFFIX ) , running ) ; editor . apply ( ) ; } | Set a flag in SharedPreferences to indicate whether periodic replications are enabled . |
34,662 | private void setExplicitlyStopped ( boolean explicitlyStopped ) { SharedPreferences . Editor editor = mPrefs . edit ( ) ; editor . putBoolean ( constructKey ( EXPLICITLY_STOPPED_SUFFIX ) , explicitlyStopped ) ; editor . apply ( ) ; } | Set a flag in SharedPreferences to indicate whether periodic replications were explicitly stopped . |
34,663 | private void resetAlarmDueTimesOnReboot ( ) { setPeriodicReplicationEnabled ( false ) ; long initialInterval = getNextAlarmDueClockTime ( ) - System . currentTimeMillis ( ) ; if ( initialInterval < 0 ) { setLastAlarmTime ( getIntervalInSeconds ( ) * MILLISECONDS_IN_SECOND ) ; } else if ( initialInterval > getIntervalInSeconds ( ) * MILLISECONDS_IN_SECOND ) { setLastAlarmTime ( 0 ) ; } else { setLastAlarmTime ( ( getIntervalInSeconds ( ) * MILLISECONDS_IN_SECOND ) - initialInterval ) ; } } | Reset the alarm times stored in SharedPreferences following a reboot of the device . After a reboot the AlarmManager must be setup again so that periodic replications will occur following reboot . |
34,664 | public static void setReplicationsPending ( Context context , Class < ? extends PeriodicReplicationService > prsClass , boolean pending ) { SharedPreferences prefs = context . getSharedPreferences ( PREFERENCES_FILE_NAME , Context . MODE_PRIVATE ) ; SharedPreferences . Editor editor = prefs . edit ( ) ; editor . putBoolean ( constructKey ( prsClass , REPLICATIONS_PENDING_SUFFIX ) , pending ) ; editor . apply ( ) ; } | Sets whether there are replications pending . This may be because replications are currently in progress and have not yet completed or because a previous scheduled replication didn t take place because the conditions for replication were not met . |
34,665 | public static boolean replicationsPending ( Context context , Class < ? extends PeriodicReplicationService > prsClass ) { SharedPreferences prefs = context . getSharedPreferences ( PREFERENCES_FILE_NAME , Context . MODE_PRIVATE ) ; return prefs . getBoolean ( constructKey ( prsClass , REPLICATIONS_PENDING_SUFFIX ) , true ) ; } | Gets whether there are replications pending . Replications may be pending because they are currently in progress and have not yet completed or because a previous scheduled replication didn t take place because the conditions for replication were not met . |
34,666 | private < T > T executeWithRetry ( final Callable < ExecuteResult > task , InputStreamProcessor < T > processor ) throws CouchException { int attempts = 10 ; CouchException lastException = null ; while ( attempts -- > 0 ) { ExecuteResult result = null ; try { result = task . call ( ) ; if ( result . stream != null ) { try { return processor . processStream ( result . stream ) ; } catch ( Exception e ) { if ( attempts > 0 ) { logger . log ( Level . WARNING , "Received an exception during response " + "stream processing. A retry will be attempted." , e ) ; } else { logger . log ( Level . SEVERE , "Response stream processing failed, no " + "retries remaining." , e ) ; throw e ; } } finally { result . stream . close ( ) ; } } } catch ( Exception e ) { throw new CouchException ( "Unexpected exception" , e , - 1 ) ; } lastException = result . exception ; if ( result . fatal ) { throw result . exception ; } } throw lastException ; } | return an InputStream if successful or throw an exception |
34,667 | public Response update ( String id , Object document ) { Misc . checkNotNullOrEmpty ( id , "id" ) ; Misc . checkNotNull ( document , "Document" ) ; getDocumentRev ( id ) ; return putUpdate ( id , document ) ; } | Document should be complete document include _id matches ID |
34,668 | public List < Response > bulkCreateSerializedDocs ( List < String > serializedDocs ) { Misc . checkNotNull ( serializedDocs , "Serialized doc list" ) ; String payload = generateBulkSerializedDocsPayload ( serializedDocs ) ; return bulkCreateDocs ( payload ) ; } | Bulk insert a list of document that are serialized to JSON data already . For performance reasons the JSON doc is not validated . |
34,669 | public String initializeView ( Model model , RenderRequest renderRequest ) { IUserInstance ui = userInstanceManager . getUserInstance ( portalRequestUtils . getCurrentPortalRequest ( ) ) ; UserPreferencesManager upm = ( UserPreferencesManager ) ui . getPreferencesManager ( ) ; IUserLayoutManager ulm = upm . getUserLayoutManager ( ) ; IUserLayout userLayout = ulm . getUserLayout ( ) ; model . addAttribute ( "marketplaceFname" , this . marketplaceFName ) ; List < IUserLayoutNodeDescription > collections = favoritesUtils . getFavoriteCollections ( userLayout ) ; model . addAttribute ( "collections" , collections ) ; List < IUserLayoutNodeDescription > favorites = favoritesUtils . getFavoritePortletLayoutNodes ( userLayout ) ; model . addAttribute ( "favorites" , favorites ) ; model . addAttribute ( "successMessageCode" , renderRequest . getParameter ( "successMessageCode" ) ) ; model . addAttribute ( "errorMessageCode" , renderRequest . getParameter ( "errorMessageCode" ) ) ; model . addAttribute ( "nameOfFavoriteActedUpon" , renderRequest . getParameter ( "nameOfFavoriteActedUpon" ) ) ; String viewName = "jsp/Favorites/edit" ; if ( collections . isEmpty ( ) && favorites . isEmpty ( ) ) { viewName = "jsp/Favorites/edit_zero" ; } logger . trace ( "Favorites Portlet EDIT mode built model [{}] and selected view {}." , model , viewName ) ; return viewName ; } | Handles all Favorites portlet EDIT mode renders . Populates model with user s favorites and selects a view to display those favorites . |
34,670 | public String getAttributeValue ( String name ) { Attr att = node . getAttributeNode ( name ) ; if ( att == null ) return null ; return att . getNodeValue ( ) ; } | Returns the value of an attribute or null if such an attribute is not defined on the underlying element . |
34,671 | public static Element getPLFNode ( Element compViewNode , IPerson person , boolean create , boolean includeChildNodes ) throws PortalException { Document plf = ( Document ) person . getAttribute ( Constants . PLF ) ; String ID = compViewNode . getAttribute ( Constants . ATT_ID ) ; Element plfNode = plf . getElementById ( ID ) ; if ( plfNode != null ) return plfNode ; if ( compViewNode . getNodeName ( ) . equals ( "layout" ) ) return plf . getDocumentElement ( ) ; if ( create == true ) return createPlfNodeAndPath ( compViewNode , includeChildNodes , person ) ; return null ; } | This method returns the PLF version of the passed in compViewNode . If create is false and a node with the same id is not found in the PLF then null is returned . If the create is true then an attempt is made to create the node along with any necessary ancestor nodes needed to represent the path along the tree . |
34,672 | public static Element createPlfNodeAndPath ( Element compViewNode , boolean includeChildNodes , IPerson person ) throws PortalException { Element compViewParent = ( Element ) compViewNode . getParentNode ( ) ; Element plfParent = getPLFNode ( compViewParent , person , true , false ) ; Document plf = ( Document ) person . getAttribute ( Constants . PLF ) ; if ( compViewNode . getAttribute ( Constants . ATT_ID ) . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) return createILFCopy ( compViewNode , compViewParent , includeChildNodes , plf , plfParent , person ) ; return createOrMovePLFOwnedNode ( compViewNode , compViewParent , true , includeChildNodes , plf , plfParent , person ) ; } | Creates a copy of the passed in ILF node in the PLF if not already there as well as creating any ancestor nodes along the path from this node up to the layout root if they are not there . |
34,673 | private static Element createILFCopy ( Element compViewNode , Element compViewParent , boolean includeChildNodes , Document plf , Element plfParent , IPerson person ) throws PortalException { Element plfNode = ( Element ) plf . importNode ( compViewNode , includeChildNodes ) ; plfNode . removeAttributeNS ( Constants . NS_URI , Constants . LCL_ADD_CHILD_ALLOWED ) ; plfNode . removeAttributeNS ( Constants . NS_URI , Constants . LCL_DELETE_ALLOWED ) ; plfNode . removeAttributeNS ( Constants . NS_URI , Constants . LCL_EDIT_ALLOWED ) ; plfNode . removeAttributeNS ( Constants . NS_URI , Constants . LCL_MOVE_ALLOWED ) ; String ID = plfNode . getAttribute ( Constants . ATT_ID ) ; plfNode . setIdAttribute ( Constants . ATT_ID , true ) ; IUserLayoutStore uls = null ; uls = UserLayoutStoreLocator . getUserLayoutStore ( ) ; if ( plfNode . getAttribute ( Constants . ATT_PLF_ID ) . equals ( "" ) ) { String plfID = null ; try { if ( ! plfNode . getAttribute ( Constants . ATT_CHANNEL_ID ) . equals ( "" ) ) plfID = uls . generateNewChannelSubscribeId ( person ) ; else plfID = uls . generateNewFolderId ( person ) ; } catch ( Exception e ) { throw new PortalException ( "Exception encountered while " + "generating new user layout node " + "Id for userId=" + person . getID ( ) , e ) ; } plfNode . setAttributeNS ( Constants . NS_URI , Constants . ATT_PLF_ID , plfID ) ; plfNode . setAttributeNS ( Constants . NS_URI , Constants . ATT_ORIGIN , ID ) ; } plfParent . appendChild ( plfNode ) ; PositionManager . updatePositionSet ( compViewParent , plfParent , person ) ; return plfNode ; } | Creates a copy of an ilf node in the plf and sets up necessary storage attributes . |
34,674 | static Element createOrMovePLFOwnedNode ( Element compViewNode , Element compViewParent , boolean createIfNotFound , boolean createChildNodes , Document plf , Element plfParent , IPerson person ) throws PortalException { Element child = ( Element ) compViewParent . getFirstChild ( ) ; Element nextOwnedSibling = null ; boolean insertionPointFound = false ; while ( child != null ) { if ( insertionPointFound && nextOwnedSibling == null && ! child . getAttribute ( Constants . ATT_ID ) . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) nextOwnedSibling = child ; if ( child == compViewNode ) insertionPointFound = true ; child = ( Element ) child . getNextSibling ( ) ; } if ( insertionPointFound == false ) return null ; String nextSibID = null ; Element nextPlfSib = null ; if ( nextOwnedSibling != null ) { nextSibID = nextOwnedSibling . getAttribute ( Constants . ATT_ID ) ; nextPlfSib = plf . getElementById ( nextSibID ) ; } String plfNodeID = compViewNode . getAttribute ( Constants . ATT_ID ) ; Element plfNode = plf . getElementById ( plfNodeID ) ; if ( plfNode == null ) { if ( createIfNotFound == true ) { plfNode = ( Element ) plf . importNode ( compViewNode , createChildNodes ) ; plfNode . setIdAttribute ( Constants . ATT_ID , true ) ; } else return null ; } if ( nextPlfSib == null ) plfParent . appendChild ( plfNode ) ; else plfParent . insertBefore ( plfNode , nextPlfSib ) ; PositionManager . updatePositionSet ( compViewParent , plfParent , person ) ; return ( Element ) plfNode ; } | Creates or moves the plf copy of a node in the composite view and inserting it before its next highest sibling so that if dlm is not used then the model ends up exactly like the original non - dlm persistance version . The position set is also updated and if no ilf copy nodes are found in the sibling list the set is cleared if it exists . |
34,675 | public static void mergeFragment ( Document fragment , Document composite , IAuthorizationPrincipal ap ) throws AuthorizationException { Element fragmentLayout = fragment . getDocumentElement ( ) ; Element fragmentRoot = ( Element ) fragmentLayout . getFirstChild ( ) ; Element compositeLayout = composite . getDocumentElement ( ) ; Element compositeRoot = ( Element ) compositeLayout . getFirstChild ( ) ; mergeChildren ( fragmentRoot , compositeRoot , ap , new HashSet ( ) ) ; } | Passes the layout root of each of these documents to mergeChildren causing all children of newLayout to be merged into compositeLayout following merging protocal for distributed layout management . |
34,676 | private static boolean mergeAllowed ( Element child , IAuthorizationPrincipal ap ) throws AuthorizationException { if ( ! child . getTagName ( ) . equals ( "channel" ) ) return true ; String channelPublishId = child . getAttribute ( "chanID" ) ; return ap . canRender ( channelPublishId ) ; } | Tests to see if channels to be merged from ILF can be rendered by the end user . If not then they are discarded from the merge . |
34,677 | private Object [ ] getPersonGroupMemberKeys ( IGroupMember gm ) { Object [ ] keys = null ; EntityIdentifier ei = gm . getUnderlyingEntityIdentifier ( ) ; IPersonAttributes attr = personAttributeDao . getPerson ( ei . getKey ( ) ) ; if ( attr != null && attr . getAttributes ( ) != null && ! attr . getAttributes ( ) . isEmpty ( ) ) { IPerson p = PersonFactory . createPerson ( ) ; p . setAttributes ( attr . getAttributes ( ) ) ; keys = p . getAttributeValues ( memberOfAttributeName ) ; log . debug ( "Groups for person {} is: {}" , p . getUserName ( ) , Arrays . toString ( keys ) ) ; } return keys != null ? keys : new Object [ ] { } ; } | gm should already be determined to be reference to person |
34,678 | public IEntityGroup newInstance ( Class entityType ) throws GroupsException { log . warn ( "Unsupported method accessed: SmartLdapGroupStore.newInstance" ) ; throw new UnsupportedOperationException ( UNSUPPORTED_MESSAGE ) ; } | Return an UnsupportedOperationException ! |
34,679 | public EntityIdentifier [ ] searchForGroups ( String query , SearchMethod method , Class leaftype ) throws GroupsException { if ( isTreeRefreshRequired ( ) ) { refreshTree ( ) ; } log . debug ( "Invoking searchForGroups(): query={}, method={}, leaftype=" , query , method , leaftype . getName ( ) ) ; final IEntityGroup root = getRootGroup ( ) ; if ( ! leaftype . equals ( root . getLeafType ( ) ) ) { return new EntityIdentifier [ 0 ] ; } final String [ ] [ ] specials = new String [ ] [ ] { new String [ ] { "\\" , "\\\\" } , new String [ ] { "[" , "\\[" } , new String [ ] { "{" , "\\{" } , new String [ ] { "^" , "\\^" } , new String [ ] { "$" , "\\$" } , new String [ ] { "." , "\\." } , new String [ ] { "|" , "\\|" } , new String [ ] { "?" , "\\?" } , new String [ ] { "*" , "\\*" } , new String [ ] { "+" , "\\+" } , new String [ ] { "(" , "\\(" } , new String [ ] { ")" , "\\)" } } ; for ( String [ ] s : specials ) { query = query . replace ( s [ 0 ] , s [ 1 ] ) ; } String regex ; switch ( method ) { case DISCRETE : case DISCRETE_CI : regex = query . toUpperCase ( ) ; break ; case STARTS_WITH : case STARTS_WITH_CI : regex = query . toUpperCase ( ) + ".*" ; break ; case ENDS_WITH : case ENDS_WITH_CI : regex = ".*" + query . toUpperCase ( ) ; break ; case CONTAINS : case CONTAINS_CI : regex = ".*" + query . toUpperCase ( ) + ".*" ; break ; default : String msg = "Unsupported search method: " + method ; throw new GroupsException ( msg ) ; } List < EntityIdentifier > rslt = new ArrayList < > ( ) ; for ( Map . Entry < String , List < String > > y : groupsTree . getKeysByUpperCaseName ( ) . entrySet ( ) ) { if ( y . getKey ( ) . matches ( regex ) ) { List < String > keys = y . getValue ( ) ; for ( String k : keys ) { rslt . add ( new EntityIdentifier ( k , IEntityGroup . class ) ) ; } } } return rslt . toArray ( new EntityIdentifier [ rslt . size ( ) ] ) ; } | Treats case sensitive and case insensitive searching the same . |
34,680 | @ RequestMapping ( method = RequestMethod . POST , params = "action=removeElement" ) public ModelAndView removeElement ( HttpServletRequest request , HttpServletResponse response ) throws IOException { IUserInstance ui = userInstanceManager . getUserInstance ( request ) ; IPerson per = getPerson ( ui , response ) ; UserPreferencesManager upm = ( UserPreferencesManager ) ui . getPreferencesManager ( ) ; IUserLayoutManager ulm = upm . getUserLayoutManager ( ) ; try { String elementId = request . getParameter ( "elementID" ) ; if ( ! ulm . deleteNode ( elementId ) ) { logger . info ( "Failed to remove element ID {} from layout root folder ID {}, delete node returned false" , elementId , ulm . getRootFolderId ( ) ) ; response . sendError ( HttpServletResponse . SC_FORBIDDEN ) ; return new ModelAndView ( "jsonView" , Collections . singletonMap ( "error" , getMessage ( "error.element.update" , "Unable to update element" , RequestContextUtils . getLocale ( request ) ) ) ) ; } ulm . saveUserLayout ( ) ; return new ModelAndView ( "jsonView" , Collections . emptyMap ( ) ) ; } catch ( PortalException e ) { return handlePersistError ( request , response , e ) ; } } | Remove an element from the layout . |
34,681 | @ RequestMapping ( method = RequestMethod . POST , params = "action=removeByFName" ) public ModelAndView removeByFName ( HttpServletRequest request , HttpServletResponse response , @ RequestParam ( value = "fname" ) String fname ) throws IOException { IUserInstance ui = userInstanceManager . getUserInstance ( request ) ; UserPreferencesManager upm = ( UserPreferencesManager ) ui . getPreferencesManager ( ) ; IUserLayoutManager ulm = upm . getUserLayoutManager ( ) ; try { String elementId = ulm . getUserLayout ( ) . findNodeId ( new PortletSubscribeIdResolver ( fname ) ) ; if ( elementId != null ) { if ( ! ulm . deleteNode ( elementId ) ) { logger . info ( "Failed to remove element ID {} from layout root folder ID {}, delete node returned false" , elementId , ulm . getRootFolderId ( ) ) ; response . setStatus ( HttpServletResponse . SC_FORBIDDEN ) ; return new ModelAndView ( "jsonView" , Collections . singletonMap ( "error" , getMessage ( "error.element.update" , "Unable to update element" , RequestContextUtils . getLocale ( request ) ) ) ) ; } } else { response . sendError ( HttpServletResponse . SC_BAD_REQUEST ) ; return null ; } ulm . saveUserLayout ( ) ; return new ModelAndView ( "jsonView" , Collections . emptyMap ( ) ) ; } catch ( PortalException e ) { return handlePersistError ( request , response , e ) ; } } | Remove the first element with the provided fname from the layout . |
34,682 | @ RequestMapping ( method = RequestMethod . POST , params = "action=addFolder" ) public ModelAndView addFolder ( HttpServletRequest request , HttpServletResponse response , @ RequestParam ( "targetId" ) String targetId , @ RequestParam ( value = "siblingId" , required = false ) String siblingId , @ RequestBody ( required = false ) Map < String , Map < String , String > > attributes ) { IUserLayoutManager ulm = userInstanceManager . getUserInstance ( request ) . getPreferencesManager ( ) . getUserLayoutManager ( ) ; final Locale locale = RequestContextUtils . getLocale ( request ) ; if ( ! ulm . getNode ( targetId ) . isAddChildAllowed ( ) ) { response . setStatus ( HttpServletResponse . SC_FORBIDDEN ) ; return new ModelAndView ( "jsonView" , Collections . singletonMap ( "error" , getMessage ( "error.add.element" , "Unable to add element" , locale ) ) ) ; } UserLayoutFolderDescription newFolder = new UserLayoutFolderDescription ( ) ; newFolder . setHidden ( false ) ; newFolder . setImmutable ( false ) ; newFolder . setAddChildAllowed ( true ) ; newFolder . setFolderType ( IUserLayoutFolderDescription . REGULAR_TYPE ) ; if ( attributes != null && ! attributes . isEmpty ( ) ) { setObjectAttributes ( newFolder , request , attributes ) ; } ulm . addNode ( newFolder , targetId , siblingId ) ; try { ulm . saveUserLayout ( ) ; } catch ( PortalException e ) { return handlePersistError ( request , response , e ) ; } Map < String , Object > model = new HashMap < > ( ) ; model . put ( "response" , getMessage ( "success.add.folder" , "Added a new folder" , locale ) ) ; model . put ( "folderId" , newFolder . getId ( ) ) ; model . put ( "immutable" , newFolder . isImmutable ( ) ) ; return new ModelAndView ( "jsonView" , model ) ; } | Add a new folder to the layout . |
34,683 | @ RequestMapping ( method = RequestMethod . POST , params = "action=renameTab" ) public ModelAndView renameTab ( HttpServletRequest request , HttpServletResponse response ) throws IOException { IUserInstance ui = userInstanceManager . getUserInstance ( request ) ; UserPreferencesManager upm = ( UserPreferencesManager ) ui . getPreferencesManager ( ) ; IUserLayoutManager ulm = upm . getUserLayoutManager ( ) ; String tabId = request . getParameter ( "tabId" ) ; IUserLayoutFolderDescription tab = ( IUserLayoutFolderDescription ) ulm . getNode ( tabId ) ; String tabName = request . getParameter ( "tabName" ) ; if ( ! ulm . canUpdateNode ( tab ) ) { logger . warn ( "Attempting to rename an immutable tab" ) ; response . sendError ( HttpServletResponse . SC_FORBIDDEN ) ; return new ModelAndView ( "jsonView" , Collections . singletonMap ( "error" , getMessage ( "error.element.update" , "Unable to update element" , RequestContextUtils . getLocale ( request ) ) ) ) ; } tab . setName ( StringUtils . isBlank ( tabName ) ? DEFAULT_TAB_NAME : tabName ) ; final boolean updated = ulm . updateNode ( tab ) ; if ( updated ) { try { ulm . saveUserLayout ( ) ; } catch ( PortalException e ) { return handlePersistError ( request , response , e ) ; } this . stylesheetUserPreferencesService . setLayoutAttribute ( request , PreferencesScope . STRUCTURE , tabId , "name" , tabName ) ; } Map < String , String > model = Collections . singletonMap ( "message" , "saved new tab name" ) ; return new ModelAndView ( "jsonView" , model ) ; } | Rename a specified tab . |
34,684 | private void setObjectAttributes ( IUserLayoutNodeDescription node , HttpServletRequest request , Map < String , Map < String , String > > attributes ) { for ( String name : attributes . get ( "attributes" ) . keySet ( ) ) { try { BeanUtils . setProperty ( node , name , attributes . get ( name ) ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { logger . warn ( "Unable to set attribute: " + name + "on object of type: " + node . getType ( ) ) ; } } Map < String , String > structureAttributes = attributes . get ( "structureAttributes" ) ; if ( structureAttributes != null ) { for ( String name : structureAttributes . keySet ( ) ) { this . stylesheetUserPreferencesService . setLayoutAttribute ( request , PreferencesScope . STRUCTURE , node . getId ( ) , name , structureAttributes . get ( name ) ) ; } } } | Attempt to map the attribute values to the given object . |
34,685 | protected boolean isTab ( IUserLayoutManager ulm , String folderId ) throws PortalException { return ulm . getRootFolderId ( ) . equals ( ulm . getParentId ( folderId ) ) ; } | A folder is a tab if its parent element is the layout element |
34,686 | protected String getMessage ( String key , String defaultMessage , Locale locale ) { try { return messageSource . getMessage ( key , new Object [ ] { } , defaultMessage , locale ) ; } catch ( Exception e ) { logger . error ( "Error resolving message with key {}." , key , e ) ; return defaultMessage ; } } | Syntactic sugar for safely resolving a no - args message from message bundle . |
34,687 | private boolean moveElementInternal ( HttpServletRequest request , String sourceId , String destinationId , String method ) { logger . debug ( "moveElementInternal invoked for sourceId={}, destinationId={}, method={}" , sourceId , destinationId , method ) ; if ( StringUtils . isEmpty ( destinationId ) ) { return true ; } IUserInstance ui = userInstanceManager . getUserInstance ( request ) ; UserPreferencesManager upm = ( UserPreferencesManager ) ui . getPreferencesManager ( ) ; IUserLayoutManager ulm = upm . getUserLayoutManager ( ) ; boolean success = false ; if ( isTab ( ulm , destinationId ) ) { Enumeration < String > columns = ulm . getChildIds ( destinationId ) ; if ( columns . hasMoreElements ( ) ) { success = attemptNodeMove ( ulm , sourceId , columns . nextElement ( ) , null ) ; } else { IUserLayoutFolderDescription newColumn = new UserLayoutFolderDescription ( ) ; newColumn . setName ( "Column" ) ; newColumn . setId ( "tbd" ) ; newColumn . setFolderType ( IUserLayoutFolderDescription . REGULAR_TYPE ) ; newColumn . setHidden ( false ) ; newColumn . setUnremovable ( false ) ; newColumn . setImmutable ( false ) ; IUserLayoutNodeDescription col = ulm . addNode ( newColumn , destinationId , null ) ; if ( col != null ) { success = attemptNodeMove ( ulm , sourceId , col . getId ( ) , null ) ; } else { logger . info ( "Unable to move item into existing columns on tab {} and unable to create new column" , destinationId ) ; } } } else { if ( isFolder ( ulm , destinationId ) ) { success = attemptNodeMove ( ulm , sourceId , destinationId , null ) ; } else { success = attemptNodeMove ( ulm , sourceId , ulm . getParentId ( destinationId ) , "insertBefore" . equals ( method ) ? destinationId : null ) ; } } try { if ( success ) { ulm . saveUserLayout ( ) ; } } catch ( PortalException e ) { logger . warn ( "Error saving layout" , e ) ; return false ; } return success ; } | Moves the source element . |
34,688 | protected final void setReportFormGroups ( final F report ) { if ( ! report . getGroups ( ) . isEmpty ( ) ) { return ; } final Set < AggregatedGroupMapping > groups = this . getGroups ( ) ; if ( ! groups . isEmpty ( ) ) { report . getGroups ( ) . add ( groups . iterator ( ) . next ( ) . getId ( ) ) ; } } | Set the groups to have selected by default if not already set |
34,689 | protected final boolean showFullColumnHeaderDescriptions ( F form ) { boolean showFullHeaderDescriptions = false ; switch ( form . getFormat ( ) ) { case csv : { showFullHeaderDescriptions = true ; break ; } case html : { showFullHeaderDescriptions = true ; break ; } default : { showFullHeaderDescriptions = false ; } } return showFullHeaderDescriptions ; } | Returns true to indicate report format is only data table and doesn t have report graph titles etc . so the report columns needs to fully describe the data columns . CSV and HTML tables require full column header descriptions . |
34,690 | private AggregatedGroupMapping [ ] extractGroupsArray ( Set < D > columnGroups ) { Set < AggregatedGroupMapping > groupMappings = new HashSet < AggregatedGroupMapping > ( ) ; for ( D discriminator : columnGroups ) { groupMappings . add ( discriminator . getAggregatedGroup ( ) ) ; } return groupMappings . toArray ( new AggregatedGroupMapping [ 0 ] ) ; } | use a Set to filter down to unique values . |
34,691 | public static Preference createSingleTextPreference ( String name , String label ) { return createSingleTextPreference ( name , "attribute.displayName." + name , TextDisplay . TEXT , null ) ; } | Define a single - valued text input preferences . This method is a convenient wrapper for the most common expected use case and assumes null values for the default value and a predictable label . |
34,692 | public static Preference createSingleTextPreference ( String name , String label , TextDisplay displayType , String defaultValue ) { SingleTextPreferenceInput input = new SingleTextPreferenceInput ( ) ; input . setDefault ( defaultValue ) ; input . setDisplay ( displayType ) ; Preference pref = new Preference ( ) ; pref . setName ( name ) ; pref . setLabel ( label ) ; pref . setPreferenceInput ( new JAXBElement < SingleTextPreferenceInput > ( new QName ( "single-text-parameter-input" ) , SingleTextPreferenceInput . class , input ) ) ; return pref ; } | Craete a single - valued text input preference . |
34,693 | public static Preference createSingleChoicePreference ( String name , String label , SingleChoiceDisplay displayType , List < Option > options , String defaultValue ) { SingleChoicePreferenceInput input = new SingleChoicePreferenceInput ( ) ; input . setDefault ( defaultValue ) ; input . setDisplay ( displayType ) ; input . getOptions ( ) . addAll ( options ) ; Preference pref = new Preference ( ) ; pref . setName ( name ) ; pref . setLabel ( label ) ; pref . setPreferenceInput ( new JAXBElement < SingleChoicePreferenceInput > ( new QName ( "single-choice-parameter-input" ) , SingleChoicePreferenceInput . class , input ) ) ; return pref ; } | Create a single - valued choice preference input . |
34,694 | public static Preference createMultiTextPreference ( String name , String label , TextDisplay displayType , List < String > defaultValues ) { MultiTextPreferenceInput input = new MultiTextPreferenceInput ( ) ; input . getDefaults ( ) . addAll ( defaultValues ) ; input . setDisplay ( displayType ) ; Preference pref = new Preference ( ) ; pref . setName ( name ) ; pref . setLabel ( label ) ; pref . setPreferenceInput ( new JAXBElement < MultiTextPreferenceInput > ( new QName ( "multi-text-parameter-input" ) , MultiTextPreferenceInput . class , input ) ) ; return pref ; } | Create a multi - valued text input preference . |
34,695 | public static Preference createMultiChoicePreference ( String name , String label , MultiChoiceDisplay displayType , List < Option > options , List < String > defaultValues ) { MultiChoicePreferenceInput input = new MultiChoicePreferenceInput ( ) ; input . getDefaults ( ) . addAll ( defaultValues ) ; input . setDisplay ( displayType ) ; input . getOptions ( ) . addAll ( options ) ; Preference pref = new Preference ( ) ; pref . setName ( name ) ; pref . setLabel ( label ) ; pref . setPreferenceInput ( new JAXBElement < MultiChoicePreferenceInput > ( new QName ( "multi-choice-parameter-input" ) , MultiChoicePreferenceInput . class , input ) ) ; return pref ; } | Create a multi - valued choice input preference . |
34,696 | private void initRelatedPortlets ( ) { final Set < MarketplacePortletDefinition > allRelatedPortlets = new HashSet < > ( ) ; for ( PortletCategory parentCategory : this . portletCategoryRegistry . getParentCategories ( this ) ) { final Set < IPortletDefinition > portletsInCategory = this . portletCategoryRegistry . getAllChildPortlets ( parentCategory ) ; for ( IPortletDefinition portletDefinition : portletsInCategory ) { allRelatedPortlets . add ( new MarketplacePortletDefinition ( portletDefinition , this . marketplaceService , this . portletCategoryRegistry ) ) ; } } allRelatedPortlets . remove ( this ) ; this . relatedPortlets = allRelatedPortlets ; } | Initialize related portlets . This must be called lazily so that MarketplacePortletDefinitions instantiated as related portlets off of a MarketplacePortletDefinition do not always instantiate their related MarketplacePortletDefinitions ad infinitem . |
34,697 | public Set < MarketplacePortletDefinition > getRandomSamplingRelatedPortlets ( final IPerson user ) { Validate . notNull ( user , "Cannot filter to BROWSEable by a null user" ) ; final IAuthorizationPrincipal principal = AuthorizationPrincipalHelper . principalFromUser ( user ) ; if ( this . relatedPortlets == null ) { this . initRelatedPortlets ( ) ; } if ( this . relatedPortlets . isEmpty ( ) ) { return this . relatedPortlets ; } List < MarketplacePortletDefinition > tempList = new ArrayList < MarketplacePortletDefinition > ( this . relatedPortlets ) ; Collections . shuffle ( tempList ) ; final int count = Math . min ( QUANTITY_RELATED_PORTLETS_TO_SHOW , tempList . size ( ) ) ; final Set < MarketplacePortletDefinition > rslt = new HashSet < MarketplacePortletDefinition > ( ) ; for ( final MarketplacePortletDefinition relatedPortlet : tempList ) { if ( marketplaceService . mayBrowsePortlet ( principal , relatedPortlet ) ) { rslt . add ( relatedPortlet ) ; } if ( rslt . size ( ) >= count ) break ; } return rslt ; } | Obtain up to QUANTITY_RELATED_PORTLETS_TO_SHOW random related portlets BROWSEable by the given user . |
34,698 | public String getRenderUrl ( ) { final String alternativeMaximizedUrl = getAlternativeMaximizedLink ( ) ; if ( null != alternativeMaximizedUrl ) { return alternativeMaximizedUrl ; } final String contextPath = PortalWebUtils . currentRequestContextPath ( ) ; return contextPath + "/p/" + getFName ( ) + "/render.uP" ; } | Convenience method for getting a bookmarkable URL for rendering the defined portlet |
34,699 | static void evaluateAndApply ( List < NodeInfo > order , Element compViewParent , Element positionSet , IntegrationResult result ) throws PortalException { adjustPositionSet ( order , positionSet , result ) ; if ( hasAffectOnCVP ( order , compViewParent ) ) { applyToNodes ( order , compViewParent ) ; result . setChangedILF ( true ) ; ; } } | This method determines if applying all of the positioning rules and restrictions ended up making changes to the compViewParent or the original position set . If changes are applicable to the CVP then they are applied . If the position set changed then the original stored in the PLF is updated . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.