idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
147,400
public void addAll ( OptionsContainerBuilder container ) { for ( Entry < Class < ? extends Option < ? , ? > > , ValueContainerBuilder < ? , ? > > entry : container . optionValues . entrySet ( ) ) { addAll ( entry . getKey ( ) , entry . getValue ( ) . build ( ) ) ; } }
Adds all options from the passed container to this container .
73
11
147,401
private static IndexedTypeSet toRootEntities ( ExtendedSearchIntegrator extendedIntegrator , Class < ? > ... selection ) { Set < Class < ? > > entities = new HashSet < Class < ? > > ( ) ; //first build the "entities" set containing all indexed subtypes of "selection". for ( Class < ? > entityType : selection ) { IndexedTypeSet targetedClasses = extendedIntegrator . getIndexedTypesPolymorphic ( IndexedTypeSets . fromClass ( entityType ) ) ; if ( targetedClasses . isEmpty ( ) ) { String msg = entityType . getName ( ) + " is not an indexed entity or a subclass of an indexed entity" ; throw new IllegalArgumentException ( msg ) ; } entities . addAll ( targetedClasses . toPojosSet ( ) ) ; } Set < Class < ? > > cleaned = new HashSet < Class < ? > > ( ) ; Set < Class < ? > > toRemove = new HashSet < Class < ? > > ( ) ; //now remove all repeated types to avoid duplicate loading by polymorphic query loading for ( Class < ? > type : entities ) { boolean typeIsOk = true ; for ( Class < ? > existing : cleaned ) { if ( existing . isAssignableFrom ( type ) ) { typeIsOk = false ; break ; } if ( type . isAssignableFrom ( existing ) ) { toRemove . add ( existing ) ; } } if ( typeIsOk ) { cleaned . add ( type ) ; } } cleaned . removeAll ( toRemove ) ; log . debugf ( "Targets for indexing job: %s" , cleaned ) ; return IndexedTypeSets . fromClasses ( cleaned . toArray ( new Class [ cleaned . size ( ) ] ) ) ; }
From the set of classes a new set is built containing all indexed subclasses but removing then all subtypes of indexed entities .
389
25
147,402
private void updateHostingEntityIfRequired ( ) { if ( hostingEntity != null && hostingEntityRequiresReadAfterUpdate ( ) ) { OgmEntityPersister entityPersister = getHostingEntityPersister ( ) ; if ( GridDialects . hasFacet ( gridDialect , GroupingByEntityDialect . class ) ) { ( ( GroupingByEntityDialect ) gridDialect ) . flushPendingOperations ( getAssociationKey ( ) . getEntityKey ( ) , entityPersister . getTupleContext ( session ) ) ; } entityPersister . processUpdateGeneratedProperties ( entityPersister . getIdentifier ( hostingEntity , session ) , hostingEntity , new Object [ entityPersister . getPropertyNames ( ) . length ] , session ) ; } }
Reads the entity hosting the association from the datastore and applies any property changes from the server side .
168
22
147,403
private static List < Class < ? > > getClassHierarchy ( Class < ? > clazz ) { List < Class < ? > > hierarchy = new ArrayList < Class < ? > > ( 4 ) ; for ( Class < ? > current = clazz ; current != null ; current = current . getSuperclass ( ) ) { hierarchy . add ( current ) ; } return hierarchy ; }
Returns the class hierarchy of the given type from bottom to top starting with the given class itself . Interfaces are not included .
83
25
147,404
public static PersistenceStrategy < ? , ? , ? > getInstance ( CacheMappingType cacheMapping , EmbeddedCacheManager externalCacheManager , URL configurationUrl , JtaPlatform jtaPlatform , Set < EntityKeyMetadata > entityTypes , Set < AssociationKeyMetadata > associationTypes , Set < IdSourceKeyMetadata > idSourceTypes ) { if ( cacheMapping == CacheMappingType . CACHE_PER_KIND ) { return getPerKindStrategy ( externalCacheManager , configurationUrl , jtaPlatform ) ; } else { return getPerTableStrategy ( externalCacheManager , configurationUrl , jtaPlatform , entityTypes , associationTypes , idSourceTypes ) ; } }
Returns a persistence strategy based on the passed configuration .
150
10
147,405
private Iterable < PersistentNoSqlIdentifierGenerator > getPersistentGenerators ( ) { Map < String , EntityPersister > entityPersisters = factory . getMetamodel ( ) . entityPersisters ( ) ; Set < PersistentNoSqlIdentifierGenerator > persistentGenerators = new HashSet < PersistentNoSqlIdentifierGenerator > ( entityPersisters . size ( ) ) ; for ( EntityPersister persister : entityPersisters . values ( ) ) { if ( persister . getIdentifierGenerator ( ) instanceof PersistentNoSqlIdentifierGenerator ) { persistentGenerators . add ( ( PersistentNoSqlIdentifierGenerator ) persister . getIdentifierGenerator ( ) ) ; } } return persistentGenerators ; }
Returns all the persistent id generators which potentially require the creation of an object in the schema .
169
18
147,406
public Relationship createRelationshipForEmbeddedAssociation ( GraphDatabaseService executionEngine , AssociationKey associationKey , EntityKey embeddedKey ) { String query = initCreateEmbeddedAssociationQuery ( associationKey , embeddedKey ) ; Object [ ] queryValues = createRelationshipForEmbeddedQueryValues ( associationKey , embeddedKey ) ; return executeQuery ( executionEngine , query , queryValues ) ; }
Give an embedded association creates all the nodes and relationships required to represent it . It assumes that the entity node containing the association already exists in the db .
82
30
147,407
private RowKeyAndTuple createAndPutAssociationRowForInsert ( Serializable key , PersistentCollection collection , AssociationPersister associationPersister , SharedSessionContractImplementor session , int i , Object entry ) { RowKeyBuilder rowKeyBuilder = initializeRowKeyBuilder ( ) ; Tuple associationRow = new Tuple ( ) ; // the collection has a surrogate key (see @CollectionId) if ( hasIdentifier ) { final Object identifier = collection . getIdentifier ( entry , i ) ; String [ ] names = { getIdentifierColumnName ( ) } ; identifierGridType . nullSafeSet ( associationRow , identifier , names , session ) ; } getKeyGridType ( ) . nullSafeSet ( associationRow , key , getKeyColumnNames ( ) , session ) ; // No need to write to where as we don't do where clauses in OGM :) if ( hasIndex ) { Object index = collection . getIndex ( entry , i , this ) ; indexGridType . nullSafeSet ( associationRow , incrementIndexByBase ( index ) , getIndexColumnNames ( ) , session ) ; } // columns of referenced key final Object element = collection . getElement ( entry ) ; getElementGridType ( ) . nullSafeSet ( associationRow , element , getElementColumnNames ( ) , session ) ; RowKeyAndTuple result = new RowKeyAndTuple ( ) ; result . key = rowKeyBuilder . values ( associationRow ) . build ( ) ; result . tuple = associationRow ; associationPersister . getAssociation ( ) . put ( result . key , result . tuple ) ; return result ; }
Creates an association row representing the given entry and adds it to the association managed by the given persister .
344
22
147,408
@ Override protected void doProcessQueuedOps ( PersistentCollection collection , Serializable key , int nextIndex , SharedSessionContractImplementor session ) throws HibernateException { // nothing to do }
once we re on ORM 5
44
7
147,409
public boolean isIdProperty ( OgmEntityPersister persister , List < String > namesWithoutAlias ) { String join = StringHelper . join ( namesWithoutAlias , "." ) ; Type propertyType = persister . getPropertyType ( namesWithoutAlias . get ( 0 ) ) ; String [ ] identifierColumnNames = persister . getIdentifierColumnNames ( ) ; if ( propertyType . isComponentType ( ) ) { String [ ] embeddedColumnNames = persister . getPropertyColumnNames ( join ) ; for ( String embeddedColumn : embeddedColumnNames ) { if ( ! ArrayHelper . contains ( identifierColumnNames , embeddedColumn ) ) { return false ; } } return true ; } return ArrayHelper . contains ( identifierColumnNames , join ) ; }
Check if the property is part of the identifier of the entity .
159
13
147,410
public void deploySchema ( String generatedProtobufName , RemoteCache < String , String > protobufCache , SchemaCapture schemaCapture , SchemaOverride schemaOverrideService , URL schemaOverrideResource ) { // user defined schema if ( schemaOverrideService != null || schemaOverrideResource != null ) { cachedSchema = new SchemaValidator ( this , schemaOverrideService , schemaOverrideResource , generatedProtobufName ) . provideSchema ( ) ; } // or generate them generateProtoschema ( ) ; try { protobufCache . put ( generatedProtobufName , cachedSchema ) ; String errors = protobufCache . get ( generatedProtobufName + ".errors" ) ; if ( errors != null ) { throw LOG . errorAtSchemaDeploy ( generatedProtobufName , errors ) ; } LOG . successfulSchemaDeploy ( generatedProtobufName ) ; } catch ( HotRodClientException hrce ) { throw LOG . errorAtSchemaDeploy ( generatedProtobufName , hrce ) ; } if ( schemaCapture != null ) { schemaCapture . put ( generatedProtobufName , cachedSchema ) ; } }
Typically this is transparently handled by using the Protostream codecs but be aware of it when bypassing Protostream .
247
26
147,411
public static void archiveFile ( @ NotNull final ArchiveOutputStream out , @ NotNull final VirtualFileDescriptor source , final long fileSize ) throws IOException { if ( ! source . hasContent ( ) ) { throw new IllegalArgumentException ( "Provided source is not a file: " + source . getPath ( ) ) ; } //noinspection ChainOfInstanceofChecks if ( out instanceof TarArchiveOutputStream ) { final TarArchiveEntry entry = new TarArchiveEntry ( source . getPath ( ) + source . getName ( ) ) ; entry . setSize ( fileSize ) ; entry . setModTime ( source . getTimeStamp ( ) ) ; out . putArchiveEntry ( entry ) ; } else if ( out instanceof ZipArchiveOutputStream ) { final ZipArchiveEntry entry = new ZipArchiveEntry ( source . getPath ( ) + source . getName ( ) ) ; entry . setSize ( fileSize ) ; entry . setTime ( source . getTimeStamp ( ) ) ; out . putArchiveEntry ( entry ) ; } else { throw new IOException ( "Unknown archive output stream" ) ; } final InputStream input = source . getInputStream ( ) ; try { IOUtil . copyStreams ( input , fileSize , out , IOUtil . BUFFER_ALLOCATOR ) ; } finally { if ( source . shouldCloseStream ( ) ) { input . close ( ) ; } } out . closeArchiveEntry ( ) ; }
Adds the file to the tar archive represented by output stream . It s caller s responsibility to close output stream properly .
325
23
147,412
void setRightChild ( final byte b , @ NotNull final MutableNode child ) { final ChildReference right = children . getRight ( ) ; if ( right == null || ( right . firstByte & 0xff ) != ( b & 0xff ) ) { throw new IllegalArgumentException ( ) ; } children . setAt ( children . size ( ) - 1 , new ChildReferenceMutable ( b , child ) ) ; }
Sets in - place the right child with the same first byte .
91
14
147,413
public boolean needMerge ( @ NotNull final BasePage left , @ NotNull final BasePage right ) { final int leftSize = left . getSize ( ) ; final int rightSize = right . getSize ( ) ; return leftSize == 0 || rightSize == 0 || leftSize + rightSize <= ( ( ( isDupTree ( left ) ? getDupPageMaxSize ( ) : getPageMaxSize ( ) ) * 7 ) >> 3 ) ; }
Is invoked on the leaf deletion only .
99
8
147,414
@ NotNull static MetaTreeImpl . Proto saveMetaTree ( @ NotNull final ITreeMutable metaTree , @ NotNull final EnvironmentImpl env , @ NotNull final ExpiredLoggableCollection expired ) { final long newMetaTreeAddress = metaTree . save ( ) ; final Log log = env . getLog ( ) ; final int lastStructureId = env . getLastStructureId ( ) ; final long dbRootAddress = log . write ( DatabaseRoot . DATABASE_ROOT_TYPE , Loggable . NO_STRUCTURE_ID , DatabaseRoot . asByteIterable ( newMetaTreeAddress , lastStructureId ) ) ; expired . add ( dbRootAddress , ( int ) ( log . getWrittenHighAddress ( ) - dbRootAddress ) ) ; return new MetaTreeImpl . Proto ( newMetaTreeAddress , dbRootAddress ) ; }
Saves meta tree writes database root and flushes the log .
187
13
147,415
@ SuppressWarnings ( { "OverlyLongMethod" } ) public void clearProperties ( @ NotNull final PersistentStoreTransaction txn , @ NotNull final Entity entity ) { final Transaction envTxn = txn . getEnvironmentTransaction ( ) ; final PersistentEntityId id = ( PersistentEntityId ) entity . getId ( ) ; final int entityTypeId = id . getTypeId ( ) ; final long entityLocalId = id . getLocalId ( ) ; final PropertiesTable properties = getPropertiesTable ( txn , entityTypeId ) ; final PropertyKey propertyKey = new PropertyKey ( entityLocalId , 0 ) ; try ( Cursor cursor = getPrimaryPropertyIndexCursor ( txn , properties ) ) { for ( boolean success = cursor . getSearchKeyRange ( PropertyKey . propertyKeyToEntry ( propertyKey ) ) != null ; success ; success = cursor . getNext ( ) ) { ByteIterable keyEntry = cursor . getKey ( ) ; final PropertyKey key = PropertyKey . entryToPropertyKey ( keyEntry ) ; if ( key . getEntityLocalId ( ) != entityLocalId ) { break ; } final int propertyId = key . getPropertyId ( ) ; final ByteIterable value = cursor . getValue ( ) ; final PropertyValue propValue = propertyTypes . entryToPropertyValue ( value ) ; txn . propertyChanged ( id , propertyId , propValue . getData ( ) , null ) ; properties . deleteNoFail ( txn , entityLocalId , value , propertyId , propValue . getType ( ) ) ; } } }
Clears all properties of specified entity .
342
8
147,416
boolean deleteEntity ( @ NotNull final PersistentStoreTransaction txn , @ NotNull final PersistentEntity entity ) { clearProperties ( txn , entity ) ; clearBlobs ( txn , entity ) ; deleteLinks ( txn , entity ) ; final PersistentEntityId id = entity . getId ( ) ; final int entityTypeId = id . getTypeId ( ) ; final long entityLocalId = id . getLocalId ( ) ; final ByteIterable key = LongBinding . longToCompressedEntry ( entityLocalId ) ; if ( config . isDebugSearchForIncomingLinksOnDelete ( ) ) { // search for incoming links final List < String > allLinkNames = getAllLinkNames ( txn ) ; for ( final String entityType : txn . getEntityTypes ( ) ) { for ( final String linkName : allLinkNames ) { //noinspection LoopStatementThatDoesntLoop for ( final Entity referrer : txn . findLinks ( entityType , entity , linkName ) ) { throw new EntityStoreException ( entity + " is about to be deleted, but it is referenced by " + referrer + ", link name: " + linkName ) ; } } } } if ( getEntitiesTable ( txn , entityTypeId ) . delete ( txn . getEnvironmentTransaction ( ) , key ) ) { txn . entityDeleted ( id ) ; return true ; } return false ; }
Deletes specified entity clearing all its properties and deleting all its outgoing links .
307
15
147,417
private void deleteLinks ( @ NotNull final PersistentStoreTransaction txn , @ NotNull final PersistentEntity entity ) { final PersistentEntityId id = entity . getId ( ) ; final int entityTypeId = id . getTypeId ( ) ; final long entityLocalId = id . getLocalId ( ) ; final Transaction envTxn = txn . getEnvironmentTransaction ( ) ; final LinksTable links = getLinksTable ( txn , entityTypeId ) ; final IntHashSet deletedLinks = new IntHashSet ( ) ; try ( Cursor cursor = links . getFirstIndexCursor ( envTxn ) ) { for ( boolean success = cursor . getSearchKeyRange ( PropertyKey . propertyKeyToEntry ( new PropertyKey ( entityLocalId , 0 ) ) ) != null ; success ; success = cursor . getNext ( ) ) { final ByteIterable keyEntry = cursor . getKey ( ) ; final PropertyKey key = PropertyKey . entryToPropertyKey ( keyEntry ) ; if ( key . getEntityLocalId ( ) != entityLocalId ) { break ; } final ByteIterable valueEntry = cursor . getValue ( ) ; if ( links . delete ( envTxn , keyEntry , valueEntry ) ) { int linkId = key . getPropertyId ( ) ; if ( getLinkName ( txn , linkId ) != null ) { deletedLinks . add ( linkId ) ; final LinkValue linkValue = LinkValue . entryToLinkValue ( valueEntry ) ; txn . linkDeleted ( entity . getId ( ) , ( PersistentEntityId ) linkValue . getEntityId ( ) , linkValue . getLinkId ( ) ) ; } } } } for ( Integer linkId : deletedLinks ) { links . deleteAllIndex ( envTxn , linkId , entityLocalId ) ; } }
Deletes all outgoing links of specified entity .
391
9
147,418
@ Deprecated public int getEntityTypeId ( @ NotNull final String entityType , final boolean allowCreate ) { return getEntityTypeId ( txnProvider , entityType , allowCreate ) ; }
Gets or creates id of the entity type .
42
10
147,419
public int getPropertyId ( @ NotNull final PersistentStoreTransaction txn , @ NotNull final String propertyName , final boolean allowCreate ) { return allowCreate ? propertyIds . getOrAllocateId ( txn , propertyName ) : propertyIds . getId ( txn , propertyName ) ; }
Gets id of a property and creates the new one if necessary .
67
14
147,420
public int getLinkId ( @ NotNull final PersistentStoreTransaction txn , @ NotNull final String linkName , final boolean allowCreate ) { return allowCreate ? linkIds . getOrAllocateId ( txn , linkName ) : linkIds . getId ( txn , linkName ) ; }
Gets id of a link and creates the new one if necessary .
67
14
147,421
@ Override public synchronized void start ( ) { if ( ! started . getAndSet ( true ) ) { finished . set ( false ) ; thread . start ( ) ; } }
Starts processor thread .
38
5
147,422
@ Override public void finish ( ) { if ( started . get ( ) && ! finished . getAndSet ( true ) ) { waitUntilFinished ( ) ; super . finish ( ) ; // recreate thread (don't start) for processor reuse createProcessorThread ( ) ; clearQueues ( ) ; started . set ( false ) ; } }
Signals that the processor to finish and waits until it finishes .
74
13
147,423
int acquireTransaction ( @ NotNull final Thread thread ) { try ( CriticalSection ignored = criticalSection . enter ( ) ) { final int currentThreadPermits = getThreadPermitsToAcquire ( thread ) ; waitForPermits ( thread , currentThreadPermits > 0 ? nestedQueue : regularQueue , 1 , currentThreadPermits ) ; } return 1 ; }
Acquire transaction with a single permit in a thread . Transactions are acquired reentrantly i . e . with respect to transactions already acquired in the thread .
77
32
147,424
void releaseTransaction ( @ NotNull final Thread thread , final int permits ) { try ( CriticalSection ignored = criticalSection . enter ( ) ) { int currentThreadPermits = getThreadPermits ( thread ) ; if ( permits > currentThreadPermits ) { throw new ExodusException ( "Can't release more permits than it was acquired" ) ; } acquiredPermits -= permits ; currentThreadPermits -= permits ; if ( currentThreadPermits == 0 ) { threadPermits . remove ( thread ) ; } else { threadPermits . put ( thread , currentThreadPermits ) ; } notifyNextWaiters ( ) ; } }
Release transaction that was acquired in a thread with specified permits .
132
12
147,425
private int tryAcquireExclusiveTransaction ( @ NotNull final Thread thread , final int timeout ) { long nanos = TimeUnit . MILLISECONDS . toNanos ( timeout ) ; try ( CriticalSection ignored = criticalSection . enter ( ) ) { if ( getThreadPermits ( thread ) > 0 ) { throw new ExodusException ( "Exclusive transaction can't be nested" ) ; } final Condition condition = criticalSection . newCondition ( ) ; final long currentOrder = acquireOrder ++ ; regularQueue . put ( currentOrder , condition ) ; while ( acquiredPermits > 0 || regularQueue . firstKey ( ) != currentOrder ) { try { nanos = condition . awaitNanos ( nanos ) ; if ( nanos < 0 ) { break ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; break ; } } if ( acquiredPermits == 0 && regularQueue . firstKey ( ) == currentOrder ) { regularQueue . pollFirstEntry ( ) ; acquiredPermits = availablePermits ; threadPermits . put ( thread , availablePermits ) ; return availablePermits ; } regularQueue . remove ( currentOrder ) ; notifyNextWaiters ( ) ; } return 0 ; }
Wait for exclusive permit during a timeout in milliseconds .
264
10
147,426
protected boolean waitForJobs ( ) throws InterruptedException { final Pair < Long , Job > peekPair ; try ( Guard ignored = timeQueue . lock ( ) ) { peekPair = timeQueue . peekPair ( ) ; } if ( peekPair == null ) { awake . acquire ( ) ; return true ; } final long timeout = Long . MAX_VALUE - peekPair . getFirst ( ) - System . currentTimeMillis ( ) ; if ( timeout < 0 ) { return false ; } return awake . tryAcquire ( timeout , TimeUnit . MILLISECONDS ) ; }
returns true if a job was queued within a timeout
129
12
147,427
void apply ( ) { final FlushLog log = new FlushLog ( ) ; store . logOperations ( txn , log ) ; final BlobVault blobVault = store . getBlobVault ( ) ; if ( blobVault . requiresTxn ( ) ) { try { blobVault . flushBlobs ( blobStreams , blobFiles , deferredBlobsToDelete , txn ) ; } catch ( Exception e ) { // out of disk space not expected there throw ExodusException . toEntityStoreException ( e ) ; } } txn . setCommitHook ( new Runnable ( ) { @ Override public void run ( ) { log . flushed ( ) ; final EntityIterableCacheAdapterMutable cache = PersistentStoreTransaction . this . mutableCache ; if ( cache != null ) { // mutableCache can be null if only blobs are modified applyAtomicCaches ( cache ) ; } } } ) ; }
exposed only for tests
205
5
147,428
@ NotNull private String getFQName ( @ NotNull final String localName , Object ... params ) { final StringBuilder builder = new StringBuilder ( ) ; builder . append ( storeName ) ; builder . append ( ' ' ) ; builder . append ( localName ) ; for ( final Object param : params ) { builder . append ( ' ' ) ; builder . append ( param ) ; } //noinspection ConstantConditions return StringInterner . intern ( builder . toString ( ) ) ; }
Gets fully - qualified name of a table or sequence .
106
12
147,429
public static void writeUTF ( @ NotNull final OutputStream stream , @ NotNull final String str ) throws IOException { try ( DataOutputStream dataStream = new DataOutputStream ( stream ) ) { int len = str . length ( ) ; if ( len < SINGLE_UTF_CHUNK_SIZE ) { dataStream . writeUTF ( str ) ; } else { int startIndex = 0 ; int endIndex ; do { endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE ; if ( endIndex > len ) { endIndex = len ; } dataStream . writeUTF ( str . substring ( startIndex , endIndex ) ) ; startIndex += SINGLE_UTF_CHUNK_SIZE ; } while ( endIndex < len ) ; } } }
Writes long strings to output stream as several chunks .
170
11
147,430
@ Nullable public static String readUTF ( @ NotNull final InputStream stream ) throws IOException { final DataInputStream dataInput = new DataInputStream ( stream ) ; if ( stream instanceof ByteArraySizedInputStream ) { final ByteArraySizedInputStream sizedStream = ( ByteArraySizedInputStream ) stream ; final int streamSize = sizedStream . size ( ) ; if ( streamSize >= 2 ) { sizedStream . mark ( Integer . MAX_VALUE ) ; final int utfLen = dataInput . readUnsignedShort ( ) ; if ( utfLen == streamSize - 2 ) { boolean isAscii = true ; final byte [ ] bytes = sizedStream . toByteArray ( ) ; for ( int i = 0 ; i < utfLen ; ++ i ) { if ( ( bytes [ i + 2 ] & 0xff ) > 127 ) { isAscii = false ; break ; } } if ( isAscii ) { return fromAsciiByteArray ( bytes , 2 , utfLen ) ; } } sizedStream . reset ( ) ; } } try { String result = null ; StringBuilder builder = null ; for ( ; ; ) { final String temp ; try { temp = dataInput . readUTF ( ) ; if ( result != null && result . length ( ) == 0 && builder != null && builder . length ( ) == 0 && temp . length ( ) == 0 ) { break ; } } catch ( EOFException e ) { break ; } if ( result == null ) { result = temp ; } else { if ( builder == null ) { builder = new StringBuilder ( ) ; builder . append ( result ) ; } builder . append ( temp ) ; } } return ( builder != null ) ? builder . toString ( ) : result ; } finally { dataInput . close ( ) ; } }
Reads a string from input stream saved as a sequence of UTF chunks .
392
15
147,431
protected long save ( ) { // save leaf nodes ReclaimFlag flag = saveChildren ( ) ; // save self. complementary to {@link load()} final byte type = getType ( ) ; final BTreeBase tree = getTree ( ) ; final int structureId = tree . structureId ; final Log log = tree . log ; if ( flag == ReclaimFlag . PRESERVE ) { // there is a chance to update the flag to RECLAIM if ( log . getWrittenHighAddress ( ) % log . getFileLengthBound ( ) == 0 ) { // page will be exactly on file border flag = ReclaimFlag . RECLAIM ; } else { final ByteIterable [ ] iterables = getByteIterables ( flag ) ; long result = log . tryWrite ( type , structureId , new CompoundByteIterable ( iterables ) ) ; if ( result < 0 ) { iterables [ 0 ] = CompressedUnsignedLongByteIterable . getIterable ( ( size << 1 ) + ReclaimFlag . RECLAIM . value ) ; result = log . writeContinuously ( type , structureId , new CompoundByteIterable ( iterables ) ) ; if ( result < 0 ) { throw new TooBigLoggableException ( ) ; } } return result ; } } return log . write ( type , structureId , new CompoundByteIterable ( getByteIterables ( flag ) ) ) ; }
Save page to log
303
4
147,432
@ Override public EnvironmentConfig setSetting ( @ NotNull final String key , @ NotNull final Object value ) { return ( EnvironmentConfig ) super . setSetting ( key , value ) ; }
Sets the value of the setting with the specified key .
40
12
147,433
@ Nullable public final String getStringContent ( final long blobHandle , @ NotNull final Transaction txn ) throws IOException { String result ; result = stringContentCache . tryKey ( this , blobHandle ) ; if ( result == null ) { final InputStream content = getContent ( blobHandle , txn ) ; if ( content == null ) { logger . error ( "Blob string not found: " + getBlobLocation ( blobHandle ) , new FileNotFoundException ( ) ) ; } result = content == null ? null : UTFUtil . readUTF ( content ) ; if ( result != null && result . length ( ) <= config . getBlobStringsCacheMaxValueSize ( ) ) { if ( stringContentCache . getObject ( this , blobHandle ) == null ) { stringContentCache . cacheObject ( this , blobHandle , result ) ; } } } return result ; }
Returns string content of blob identified by specified blob handle . String contents cache is used .
191
17
147,434
@ Override public final Job queueIn ( final Job job , final long millis ) { return pushAt ( job , System . currentTimeMillis ( ) + millis ) ; }
Queues a job for execution in specified time .
39
10
147,435
public void put ( @ NotNull final Transaction txn , final long localId , final int blobId , @ NotNull final ByteIterable value ) { primaryStore . put ( txn , PropertyKey . propertyKeyToEntry ( new PropertyKey ( localId , blobId ) ) , value ) ; allBlobsIndex . put ( txn , IntegerBinding . intToCompressedEntry ( blobId ) , LongBinding . longToCompressedEntry ( localId ) ) ; }
Setter for blob handle value .
103
7
147,436
public void put ( @ NotNull final PersistentStoreTransaction txn , final long localId , @ NotNull final ByteIterable value , @ Nullable final ByteIterable oldValue , final int propertyId , @ NotNull final ComparableValueType type ) { final Store valueIdx = getOrCreateValueIndex ( txn , propertyId ) ; final ByteIterable key = PropertyKey . propertyKeyToEntry ( new PropertyKey ( localId , propertyId ) ) ; final Transaction envTxn = txn . getEnvironmentTransaction ( ) ; primaryStore . put ( envTxn , key , value ) ; final ByteIterable secondaryValue = LongBinding . longToCompressedEntry ( localId ) ; boolean success ; if ( oldValue == null ) { success = allPropsIndex . put ( envTxn , IntegerBinding . intToCompressedEntry ( propertyId ) , secondaryValue ) ; } else { success = deleteFromStore ( envTxn , valueIdx , secondaryValue , createSecondaryKeys ( store . getPropertyTypes ( ) , oldValue , type ) ) ; } if ( success ) { for ( final ByteIterable secondaryKey : createSecondaryKeys ( store . getPropertyTypes ( ) , value , type ) ) { valueIdx . put ( envTxn , secondaryKey , secondaryValue ) ; } } checkStatus ( success , "Failed to put" ) ; }
Setter for property value . Doesn t affect entity version and doesn t invalidate any of the cached entity iterables .
299
24
147,437
public Iterator < K > tailIterator ( @ NotNull final K key ) { return new Iterator < K > ( ) { private Stack < TreePos < K > > stack ; private boolean hasNext ; private boolean hasNextValid ; @ Override public boolean hasNext ( ) { if ( hasNextValid ) { return hasNext ; } hasNextValid = true ; if ( stack == null ) { Node < K > root = getRoot ( ) ; if ( root == null ) { hasNext = false ; return hasNext ; } stack = new Stack <> ( ) ; if ( ! root . getLess ( key , stack ) ) { stack . push ( new TreePos <> ( root ) ) ; } } TreePos < K > treePos = stack . peek ( ) ; if ( treePos . node . isLeaf ( ) ) { while ( treePos . pos >= ( treePos . node . isTernary ( ) ? 2 : 1 ) ) { stack . pop ( ) ; if ( stack . isEmpty ( ) ) { hasNext = false ; return hasNext ; } treePos = stack . peek ( ) ; } } else { if ( treePos . pos == 0 ) { treePos = new TreePos <> ( treePos . node . getFirstChild ( ) ) ; } else if ( treePos . pos == 1 ) { treePos = new TreePos <> ( treePos . node . getSecondChild ( ) ) ; } else { treePos = new TreePos <> ( treePos . node . getThirdChild ( ) ) ; } stack . push ( treePos ) ; while ( ! treePos . node . isLeaf ( ) ) { treePos = new TreePos <> ( treePos . node . getFirstChild ( ) ) ; stack . push ( treePos ) ; } } treePos . pos ++ ; hasNext = true ; return hasNext ; } @ Override public K next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } hasNextValid = false ; TreePos < K > treePos = stack . peek ( ) ; // treePos.pos must be 1 or 2 here return treePos . pos == 1 ? treePos . node . getFirstKey ( ) : treePos . node . getSecondKey ( ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Returns an iterator that iterates over all elements greater or equal to key in ascending order
515
17
147,438
@ Nullable public ByteIterable get ( @ NotNull final Transaction txn , @ NotNull final ByteIterable first ) { return this . first . get ( txn , first ) ; }
Search for the first entry in the first database . Use this method for databases configured with no duplicates .
41
21
147,439
@ Nullable public ByteIterable get2 ( @ NotNull final Transaction txn , @ NotNull final ByteIterable second ) { return this . second . get ( txn , second ) ; }
Search for the second entry in the second database . Use this method for databases configured with no duplicates .
42
21
147,440
@ Override public void close ( ) { if ( closed ) return ; closed = true ; tcpSocketConsumer . prepareToShutdown ( ) ; if ( shouldSendCloseMessage ) eventLoop . addHandler ( new EventHandler ( ) { @ Override public boolean action ( ) throws InvalidEventHandlerException { try { TcpChannelHub . this . sendCloseMessage ( ) ; tcpSocketConsumer . stop ( ) ; closed = true ; if ( LOG . isDebugEnabled ( ) ) Jvm . debug ( ) . on ( getClass ( ) , "closing connection to " + socketAddressSupplier ) ; while ( clientChannel != null ) { if ( LOG . isDebugEnabled ( ) ) Jvm . debug ( ) . on ( getClass ( ) , "waiting for disconnect to " + socketAddressSupplier ) ; } } catch ( ConnectionDroppedException e ) { throw new InvalidEventHandlerException ( e ) ; } // we just want this to run once throw new InvalidEventHandlerException ( ) ; } @ NotNull @ Override public String toString ( ) { return TcpChannelHub . class . getSimpleName ( ) + "..close()" ; } } ) ; }
called when we are completed finished with using the TcpChannelHub
251
13
147,441
private void sendCloseMessage ( ) { this . lock ( ( ) -> { TcpChannelHub . this . writeMetaDataForKnownTID ( 0 , outWire , null , 0 ) ; TcpChannelHub . this . outWire . writeDocument ( false , w -> w . writeEventName ( EventId . onClientClosing ) . text ( "" ) ) ; } , TryLock . LOCK ) ; // wait up to 1 seconds to receive an close request acknowledgment from the server try { final boolean await = receivedClosedAcknowledgement . await ( 1 , TimeUnit . SECONDS ) ; if ( ! await ) if ( Jvm . isDebugEnabled ( getClass ( ) ) ) Jvm . debug ( ) . on ( getClass ( ) , "SERVER IGNORED CLOSE REQUEST: shutting down the client anyway as the " + "server did not respond to the close() request." ) ; } catch ( InterruptedException ignore ) { Thread . currentThread ( ) . interrupt ( ) ; } }
used to signal to the server that the client is going to drop the connection and waits up to one second for the server to acknowledge the receipt of this message
215
31
147,442
public long nextUniqueTransaction ( long timeMs ) { long id = timeMs ; for ( ; ; ) { long old = transactionID . get ( ) ; if ( old >= id ) id = old + 1 ; if ( transactionID . compareAndSet ( old , id ) ) break ; } return id ; }
the transaction id are generated as unique timestamps
66
10
147,443
public void checkConnection ( ) { long start = Time . currentTimeMillis ( ) ; while ( clientChannel == null ) { tcpSocketConsumer . checkNotShutdown ( ) ; if ( start + timeoutMs > Time . currentTimeMillis ( ) ) try { condition . await ( 1 , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new IORuntimeException ( "Interrupted" ) ; } else throw new IORuntimeException ( "Not connected to " + socketAddressSupplier ) ; } if ( clientChannel == null ) throw new IORuntimeException ( "Not connected to " + socketAddressSupplier ) ; }
blocks until there is a connection
146
6
147,444
protected boolean closeAtomically ( ) { if ( isClosed . compareAndSet ( false , true ) ) { Closeable . closeQuietly ( networkStatsListener ) ; return true ; } else { //was already closed. return false ; } }
Close the connection atomically .
54
6
147,445
private void onRead0 ( ) { assert inWire . startUse ( ) ; ensureCapacity ( ) ; try { while ( ! inWire . bytes ( ) . isEmpty ( ) ) { try ( DocumentContext dc = inWire . readingDocument ( ) ) { if ( ! dc . isPresent ( ) ) return ; try { if ( YamlLogging . showServerReads ( ) ) logYaml ( dc ) ; onRead ( dc , outWire ) ; onWrite ( outWire ) ; } catch ( Exception e ) { Jvm . warn ( ) . on ( getClass ( ) , "inWire=" + inWire . getClass ( ) + ",yaml=" + Wires . fromSizePrefixedBlobs ( dc ) , e ) ; } } } } finally { assert inWire . endUse ( ) ; } }
process all messages in this batch provided there is plenty of output space .
179
14
147,446
private boolean hasReceivedHeartbeat ( ) { long currentTimeMillis = System . currentTimeMillis ( ) ; boolean result = lastTimeMessageReceived + heartbeatTimeoutMs >= currentTimeMillis ; if ( ! result ) Jvm . warn ( ) . on ( getClass ( ) , Integer . toHexString ( hashCode ( ) ) + " missed heartbeat, lastTimeMessageReceived=" + lastTimeMessageReceived + ", currentTimeMillis=" + currentTimeMillis ) ; return result ; }
called periodically to check that the heartbeat has been received
109
10
147,447
public boolean mapsCell ( String cell ) { return mappedCells . stream ( ) . anyMatch ( x -> x . equals ( cell ) ) ; }
Returns if this maps the specified cell .
32
8
147,448
public double getDegrees ( ) { double kms = getValue ( GeoDistanceUnit . KILOMETRES ) ; return DistanceUtils . dist2Degrees ( kms , DistanceUtils . EARTH_MEAN_RADIUS_KM ) ; }
Return the numeric distance value in degrees .
61
8
147,449
public NRShape makeShape ( Date from , Date to ) { UnitNRShape fromShape = tree . toUnitShape ( from ) ; UnitNRShape toShape = tree . toUnitShape ( to ) ; return tree . toRangeShape ( fromShape , toShape ) ; }
Makes an spatial shape representing the time range defined by the two specified dates .
58
16
147,450
public static int validateGeohashMaxLevels ( Integer userMaxLevels , int defaultMaxLevels ) { int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels ; if ( maxLevels < 1 || maxLevels > GeohashPrefixTree . getMaxLevelsPossible ( ) ) { throw new IndexException ( "max_levels must be in range [1, {}], but found {}" , GeohashPrefixTree . getMaxLevelsPossible ( ) , maxLevels ) ; } return maxLevels ; }
Checks if the specified max levels is correct .
126
10
147,451
public static Double checkLatitude ( String name , Double latitude ) { if ( latitude == null ) { throw new IndexException ( "{} required" , name ) ; } else if ( latitude < MIN_LATITUDE || latitude > MAX_LATITUDE ) { throw new IndexException ( "{} must be in range [{}, {}], but found {}" , name , MIN_LATITUDE , MAX_LATITUDE , latitude ) ; } return latitude ; }
Checks if the specified latitude is correct .
106
9
147,452
public static Double checkLongitude ( String name , Double longitude ) { if ( longitude == null ) { throw new IndexException ( "{} required" , name ) ; } else if ( longitude < MIN_LONGITUDE || longitude > MAX_LONGITUDE ) { throw new IndexException ( "{} must be in range [{}, {}], but found {}" , name , MIN_LONGITUDE , MAX_LONGITUDE , longitude ) ; } return longitude ; }
Checks if the specified longitude is correct .
112
10
147,453
public Set < String > postProcessingFields ( ) { Set < String > fields = new LinkedHashSet <> ( ) ; query . forEach ( condition -> fields . addAll ( condition . postProcessingFields ( ) ) ) ; sort . forEach ( condition -> fields . addAll ( condition . postProcessingFields ( ) ) ) ; return fields ; }
Returns the names of the involved fields when post processing .
81
11
147,454
public static Index index ( String keyspace , String table , String name ) { return new Index ( table , name ) . keyspace ( keyspace ) ; }
Returns a new index creation statement using the session s keyspace .
33
13
147,455
public GeoShapeMapper transform ( GeoTransformation ... transformations ) { if ( this . transformations == null ) { this . transformations = Arrays . asList ( transformations ) ; } else { this . transformations . addAll ( Arrays . asList ( transformations ) ) ; } return this ; }
Sets the transformations to be applied to the shape before indexing it .
61
15
147,456
@ JsonProperty ( "paging" ) void paging ( String paging ) { builder . paging ( IndexPagingState . fromByteBuffer ( ByteBufferUtils . byteBuffer ( paging ) ) ) ; }
Sets the specified starting partition key .
48
8
147,457
public boolean mapsCell ( String cell ) { return mappers . values ( ) . stream ( ) . anyMatch ( mapper -> mapper . mapsCell ( cell ) ) ; }
Returns if this has any mapping for the specified cell .
38
11
147,458
private static String convertPathToResource ( String path ) { File file = new File ( path ) ; List < String > parts = new ArrayList < String > ( ) ; do { parts . add ( file . getName ( ) ) ; file = file . getParentFile ( ) ; } while ( file != null ) ; StringBuffer sb = new StringBuffer ( ) ; int size = parts . size ( ) ; for ( int a = size - 1 ; a >= 0 ; a -- ) { if ( sb . length ( ) > 0 ) { sb . append ( "_" ) ; } sb . append ( parts . get ( a ) ) ; } // TODO: Better regex replacement return sb . toString ( ) . replace ( ' ' , ' ' ) . replace ( "+" , "plus" ) . toLowerCase ( Locale . US ) ; }
Converts any path into something that can be placed in an Android directory .
187
15
147,459
public static String formatDateTime ( Context context , ReadablePartial time , int flags ) { return android . text . format . DateUtils . formatDateTime ( context , toMillis ( time ) , flags | FORMAT_UTC ) ; }
Formats a date or a time according to the local conventions .
53
13
147,460
public static String formatDateRange ( Context context , ReadablePartial start , ReadablePartial end , int flags ) { return formatDateRange ( context , toMillis ( start ) , toMillis ( end ) , flags ) ; }
Formats a date or a time range according to the local conventions .
51
14
147,461
public static CharSequence getRelativeTimeSpanString ( Context context , ReadableInstant time , int flags ) { boolean abbrevRelative = ( flags & ( FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL ) ) != 0 ; // We set the millis to 0 so we aren't off by a fraction of a second when counting intervals DateTime now = DateTime . now ( time . getZone ( ) ) . withMillisOfSecond ( 0 ) ; DateTime timeDt = new DateTime ( time ) . withMillisOfSecond ( 0 ) ; boolean past = ! now . isBefore ( timeDt ) ; Interval interval = past ? new Interval ( timeDt , now ) : new Interval ( now , timeDt ) ; int resId ; long count ; if ( Minutes . minutesIn ( interval ) . isLessThan ( Minutes . ONE ) ) { count = Seconds . secondsIn ( interval ) . getSeconds ( ) ; if ( past ) { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_num_seconds_ago ; } else { resId = R . plurals . joda_time_android_num_seconds_ago ; } } else { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_in_num_seconds ; } else { resId = R . plurals . joda_time_android_in_num_seconds ; } } } else if ( Hours . hoursIn ( interval ) . isLessThan ( Hours . ONE ) ) { count = Minutes . minutesIn ( interval ) . getMinutes ( ) ; if ( past ) { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_num_minutes_ago ; } else { resId = R . plurals . joda_time_android_num_minutes_ago ; } } else { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_in_num_minutes ; } else { resId = R . plurals . joda_time_android_in_num_minutes ; } } } else if ( Days . daysIn ( interval ) . isLessThan ( Days . ONE ) ) { count = Hours . hoursIn ( interval ) . getHours ( ) ; if ( past ) { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_num_hours_ago ; } else { resId = R . plurals . joda_time_android_num_hours_ago ; } } else { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_in_num_hours ; } else { resId = R . plurals . joda_time_android_in_num_hours ; } } } else if ( Weeks . weeksIn ( interval ) . isLessThan ( Weeks . ONE ) ) { count = Days . daysIn ( interval ) . getDays ( ) ; if ( past ) { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_num_days_ago ; } else { resId = R . plurals . joda_time_android_num_days_ago ; } } else { if ( abbrevRelative ) { resId = R . plurals . joda_time_android_abbrev_in_num_days ; } else { resId = R . plurals . joda_time_android_in_num_days ; } } } else { return formatDateRange ( context , time , time , flags ) ; } String format = context . getResources ( ) . getQuantityString ( resId , ( int ) count ) ; return String . format ( format , count ) ; }
Returns a string describing time as a time relative to now .
885
12
147,462
public static CharSequence formatDuration ( Context context , ReadableDuration readableDuration ) { Resources res = context . getResources ( ) ; Duration duration = readableDuration . toDuration ( ) ; final int hours = ( int ) duration . getStandardHours ( ) ; if ( hours != 0 ) { return res . getQuantityString ( R . plurals . joda_time_android_duration_hours , hours , hours ) ; } final int minutes = ( int ) duration . getStandardMinutes ( ) ; if ( minutes != 0 ) { return res . getQuantityString ( R . plurals . joda_time_android_duration_minutes , minutes , minutes ) ; } final int seconds = ( int ) duration . getStandardSeconds ( ) ; return res . getQuantityString ( R . plurals . joda_time_android_duration_seconds , seconds , seconds ) ; }
Return given duration in a human - friendly format . For example 4 minutes or 1 second . Returns only largest meaningful unit of time from seconds up to hours .
188
31
147,463
public DateTimeZone getZone ( String id ) { if ( id == null ) { return null ; } Object obj = iZoneInfoMap . get ( id ) ; if ( obj == null ) { return null ; } if ( id . equals ( obj ) ) { // Load zone data for the first time. return loadZoneData ( id ) ; } if ( obj instanceof SoftReference < ? > ) { @ SuppressWarnings ( "unchecked" ) SoftReference < DateTimeZone > ref = ( SoftReference < DateTimeZone > ) obj ; DateTimeZone tz = ref . get ( ) ; if ( tz != null ) { return tz ; } // Reference cleared; load data again. return loadZoneData ( id ) ; } // If this point is reached, mapping must link to another. return getZone ( ( String ) obj ) ; }
If an error is thrown while loading zone data the exception is logged to system error and null is returned for this and all future requests .
184
27
147,464
public void addNotification ( @ Observes final DesignerNotificationEvent event ) { if ( user . getIdentifier ( ) . equals ( event . getUserId ( ) ) ) { if ( event . getNotification ( ) != null && ! event . getNotification ( ) . equals ( "openinxmleditor" ) ) { final NotificationPopupView view = new NotificationPopupView ( ) ; activeNotifications . add ( view ) ; view . setPopupPosition ( getMargin ( ) , activeNotifications . size ( ) * SPACING ) ; view . setNotification ( event . getNotification ( ) ) ; view . setType ( event . getType ( ) ) ; view . setNotificationWidth ( getWidth ( ) + "px" ) ; view . show ( new Command ( ) { @ Override public void execute ( ) { //The notification has been shown and can now be removed deactiveNotifications . add ( view ) ; remove ( ) ; } } ) ; } } }
Display a Notification message
217
4
147,465
private void remove ( ) { if ( removing ) { return ; } if ( deactiveNotifications . size ( ) == 0 ) { return ; } removing = true ; final NotificationPopupView view = deactiveNotifications . get ( 0 ) ; final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation ( view ) { @ Override public void onUpdate ( double progress ) { super . onUpdate ( progress ) ; for ( int i = 0 ; i < activeNotifications . size ( ) ; i ++ ) { NotificationPopupView v = activeNotifications . get ( i ) ; final int left = v . getPopupLeft ( ) ; final int top = ( int ) ( ( ( i + 1 ) * SPACING ) - ( progress * SPACING ) ) ; v . setPopupPosition ( left , top ) ; } } @ Override public void onComplete ( ) { super . onComplete ( ) ; view . hide ( ) ; deactiveNotifications . remove ( view ) ; activeNotifications . remove ( view ) ; removing = false ; remove ( ) ; } } ; fadeOutAnimation . run ( 500 ) ; }
Remove a notification message . Recursive until all pending removals have been completed .
247
17
147,466
public static String readDesignerVersion ( ServletContext context ) { String retStr = "" ; BufferedReader br = null ; try { InputStream inputStream = context . getResourceAsStream ( "/META-INF/MANIFEST.MF" ) ; br = new BufferedReader ( new InputStreamReader ( inputStream , "UTF-8" ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { if ( line . startsWith ( BUNDLE_VERSION ) ) { retStr = line . substring ( BUNDLE_VERSION . length ( ) + 1 ) ; retStr = retStr . trim ( ) ; } } inputStream . close ( ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } finally { if ( br != null ) { IOUtils . closeQuietly ( br ) ; } } return retStr ; }
Returns the designer version from the manifest .
206
8
147,467
public boolean isDuplicateName ( String name ) { if ( name == null || name . trim ( ) . isEmpty ( ) ) { return false ; } List < AssignmentRow > as = view . getAssignmentRows ( ) ; if ( as != null && ! as . isEmpty ( ) ) { int nameCount = 0 ; for ( AssignmentRow row : as ) { if ( name . trim ( ) . compareTo ( row . getName ( ) ) == 0 ) { nameCount ++ ; if ( nameCount > 1 ) { return true ; } } } } return false ; }
Tests whether a Row name occurs more than once in the list of rows
126
15
147,468
public String getValueForDisplayValue ( final String key ) { if ( mapDisplayValuesToValues . containsKey ( key ) ) { return mapDisplayValuesToValues . get ( key ) ; } return key ; }
Returns real unquoted value for a DisplayValue
45
10
147,469
public List < AssignmentRow > getAssignmentRows ( VariableType varType ) { List < AssignmentRow > rows = new ArrayList < AssignmentRow > ( ) ; List < Variable > handledVariables = new ArrayList < Variable > ( ) ; // Create an AssignmentRow for each Assignment for ( Assignment assignment : assignments ) { if ( assignment . getVariableType ( ) == varType ) { String dataType = getDisplayNameFromDataType ( assignment . getDataType ( ) ) ; AssignmentRow row = new AssignmentRow ( assignment . getName ( ) , assignment . getVariableType ( ) , dataType , assignment . getCustomDataType ( ) , assignment . getProcessVarName ( ) , assignment . getConstant ( ) ) ; rows . add ( row ) ; handledVariables . add ( assignment . getVariable ( ) ) ; } } List < Variable > vars = null ; if ( varType == VariableType . INPUT ) { vars = inputVariables ; } else { vars = outputVariables ; } // Create an AssignmentRow for each Variable that doesn't have an Assignment for ( Variable var : vars ) { if ( ! handledVariables . contains ( var ) ) { AssignmentRow row = new AssignmentRow ( var . getName ( ) , var . getVariableType ( ) , var . getDataType ( ) , var . getCustomDataType ( ) , null , null ) ; rows . add ( row ) ; } } return rows ; }
Gets a list of AssignmentRows based on the current Assignments
311
15
147,470
public static Diagram parseJson ( String json , Boolean keepGlossaryLink ) throws JSONException { JSONObject modelJSON = new JSONObject ( json ) ; return parseJson ( modelJSON , keepGlossaryLink ) ; }
Parse the json string to the diagram model assumes that the json is hierarchical ordered
50
16
147,471
public static Diagram parseJson ( JSONObject json , Boolean keepGlossaryLink ) throws JSONException { ArrayList < Shape > shapes = new ArrayList < Shape > ( ) ; HashMap < String , JSONObject > flatJSON = flatRessources ( json ) ; for ( String resourceId : flatJSON . keySet ( ) ) { parseRessource ( shapes , flatJSON , resourceId , keepGlossaryLink ) ; } String id = "canvas" ; if ( json . has ( "resourceId" ) ) { id = json . getString ( "resourceId" ) ; shapes . remove ( new Shape ( id ) ) ; } ; Diagram diagram = new Diagram ( id ) ; // remove Diagram // (Diagram)getShapeWithId(json.getString("resourceId"), shapes); parseStencilSet ( json , diagram ) ; parseSsextensions ( json , diagram ) ; parseStencil ( json , diagram ) ; parseProperties ( json , diagram , keepGlossaryLink ) ; parseChildShapes ( shapes , json , diagram ) ; parseBounds ( json , diagram ) ; diagram . setShapes ( shapes ) ; return diagram ; }
do the parsing on an JSONObject assumes that the json is hierarchical ordered so all shapes are reachable over child relations
257
23
147,472
private static void parseRessource ( ArrayList < Shape > shapes , HashMap < String , JSONObject > flatJSON , String resourceId , Boolean keepGlossaryLink ) throws JSONException { JSONObject modelJSON = flatJSON . get ( resourceId ) ; Shape current = getShapeWithId ( modelJSON . getString ( "resourceId" ) , shapes ) ; parseStencil ( modelJSON , current ) ; parseProperties ( modelJSON , current , keepGlossaryLink ) ; parseOutgoings ( shapes , modelJSON , current ) ; parseChildShapes ( shapes , modelJSON , current ) ; parseDockers ( modelJSON , current ) ; parseBounds ( modelJSON , current ) ; parseTarget ( shapes , modelJSON , current ) ; }
Parse one resource to a shape object and add it to the shapes array
164
15
147,473
private static void parseStencil ( JSONObject modelJSON , Shape current ) throws JSONException { // get stencil type if ( modelJSON . has ( "stencil" ) ) { JSONObject stencil = modelJSON . getJSONObject ( "stencil" ) ; // TODO other attributes of stencil String stencilString = "" ; if ( stencil . has ( "id" ) ) { stencilString = stencil . getString ( "id" ) ; } current . setStencil ( new StencilType ( stencilString ) ) ; } }
parse the stencil out of a JSONObject and set it to the current shape
122
16
147,474
private static void parseStencilSet ( JSONObject modelJSON , Diagram current ) throws JSONException { // get stencil type if ( modelJSON . has ( "stencilset" ) ) { JSONObject object = modelJSON . getJSONObject ( "stencilset" ) ; String url = null ; String namespace = null ; if ( object . has ( "url" ) ) { url = object . getString ( "url" ) ; } if ( object . has ( "namespace" ) ) { namespace = object . getString ( "namespace" ) ; } current . setStencilset ( new StencilSet ( url , namespace ) ) ; } }
crates a StencilSet object and add it to the current diagram
144
15
147,475
@ SuppressWarnings ( "unchecked" ) private static void parseProperties ( JSONObject modelJSON , Shape current , Boolean keepGlossaryLink ) throws JSONException { if ( modelJSON . has ( "properties" ) ) { JSONObject propsObject = modelJSON . getJSONObject ( "properties" ) ; Iterator < String > keys = propsObject . keys ( ) ; Pattern pattern = Pattern . compile ( jsonPattern ) ; while ( keys . hasNext ( ) ) { StringBuilder result = new StringBuilder ( ) ; int lastIndex = 0 ; String key = keys . next ( ) ; String value = propsObject . getString ( key ) ; if ( ! keepGlossaryLink ) { Matcher matcher = pattern . matcher ( value ) ; while ( matcher . find ( ) ) { String id = matcher . group ( 1 ) ; current . addGlossaryIds ( id ) ; String text = matcher . group ( 2 ) ; result . append ( text ) ; lastIndex = matcher . end ( ) ; } result . append ( value . substring ( lastIndex ) ) ; value = result . toString ( ) ; } current . putProperty ( key , value ) ; } } }
create a HashMap form the json properties and add it to the shape
262
14
147,476
private static void parseSsextensions ( JSONObject modelJSON , Diagram current ) throws JSONException { if ( modelJSON . has ( "ssextensions" ) ) { JSONArray array = modelJSON . getJSONArray ( "ssextensions" ) ; for ( int i = 0 ; i < array . length ( ) ; i ++ ) { current . addSsextension ( array . getString ( i ) ) ; } } }
adds all json extension to an diagram
96
8
147,477
private static void parseOutgoings ( ArrayList < Shape > shapes , JSONObject modelJSON , Shape current ) throws JSONException { if ( modelJSON . has ( "outgoing" ) ) { ArrayList < Shape > outgoings = new ArrayList < Shape > ( ) ; JSONArray outgoingObject = modelJSON . getJSONArray ( "outgoing" ) ; for ( int i = 0 ; i < outgoingObject . length ( ) ; i ++ ) { Shape out = getShapeWithId ( outgoingObject . getJSONObject ( i ) . getString ( "resourceId" ) , shapes ) ; outgoings . add ( out ) ; out . addIncoming ( current ) ; } if ( outgoings . size ( ) > 0 ) { current . setOutgoings ( outgoings ) ; } } }
parse the outgoings form an json object and add all shape references to the current shapes add new shapes to the shape array
174
25
147,478
private static void parseChildShapes ( ArrayList < Shape > shapes , JSONObject modelJSON , Shape current ) throws JSONException { if ( modelJSON . has ( "childShapes" ) ) { ArrayList < Shape > childShapes = new ArrayList < Shape > ( ) ; JSONArray childShapeObject = modelJSON . getJSONArray ( "childShapes" ) ; for ( int i = 0 ; i < childShapeObject . length ( ) ; i ++ ) { childShapes . add ( getShapeWithId ( childShapeObject . getJSONObject ( i ) . getString ( "resourceId" ) , shapes ) ) ; } if ( childShapes . size ( ) > 0 ) { for ( Shape each : childShapes ) { each . setParent ( current ) ; } current . setChildShapes ( childShapes ) ; } ; } }
creates a shape list containing all child shapes and set it to the current shape new shape get added to the shape array
185
24
147,479
private static void parseDockers ( JSONObject modelJSON , Shape current ) throws JSONException { if ( modelJSON . has ( "dockers" ) ) { ArrayList < Point > dockers = new ArrayList < Point > ( ) ; JSONArray dockersObject = modelJSON . getJSONArray ( "dockers" ) ; for ( int i = 0 ; i < dockersObject . length ( ) ; i ++ ) { Double x = dockersObject . getJSONObject ( i ) . getDouble ( "x" ) ; Double y = dockersObject . getJSONObject ( i ) . getDouble ( "y" ) ; dockers . add ( new Point ( x , y ) ) ; } if ( dockers . size ( ) > 0 ) { current . setDockers ( dockers ) ; } } }
creates a point array of all dockers and add it to the current shape
178
16
147,480
private static void parseBounds ( JSONObject modelJSON , Shape current ) throws JSONException { if ( modelJSON . has ( "bounds" ) ) { JSONObject boundsObject = modelJSON . getJSONObject ( "bounds" ) ; current . setBounds ( new Bounds ( new Point ( boundsObject . getJSONObject ( "lowerRight" ) . getDouble ( "x" ) , boundsObject . getJSONObject ( "lowerRight" ) . getDouble ( "y" ) ) , new Point ( boundsObject . getJSONObject ( "upperLeft" ) . getDouble ( "x" ) , boundsObject . getJSONObject ( "upperLeft" ) . getDouble ( "y" ) ) ) ) ; } }
creates a bounds object with both point parsed from the json and set it to the current shape
157
19
147,481
private static void parseTarget ( ArrayList < Shape > shapes , JSONObject modelJSON , Shape current ) throws JSONException { if ( modelJSON . has ( "target" ) ) { JSONObject targetObject = modelJSON . getJSONObject ( "target" ) ; if ( targetObject . has ( "resourceId" ) ) { current . setTarget ( getShapeWithId ( targetObject . getString ( "resourceId" ) , shapes ) ) ; } } }
parse the target resource and add it to the current shape
98
11
147,482
public static HashMap < String , JSONObject > flatRessources ( JSONObject object ) throws JSONException { HashMap < String , JSONObject > result = new HashMap < String , JSONObject > ( ) ; // no cycle in hierarchies!! if ( object . has ( "resourceId" ) && object . has ( "childShapes" ) ) { result . put ( object . getString ( "resourceId" ) , object ) ; JSONArray childShapes = object . getJSONArray ( "childShapes" ) ; for ( int i = 0 ; i < childShapes . length ( ) ; i ++ ) { result . putAll ( flatRessources ( childShapes . getJSONObject ( i ) ) ) ; } } ; return result ; }
Prepare a model JSON for analyze resolves the hierarchical structure creates a HashMap which contains all resourceIds as keys and for each key the JSONObject all id are keys of this map
164
37
147,483
public void setInvalidValues ( final Set < String > invalidValues , final boolean isCaseSensitive , final String invalidValueErrorMessage ) { if ( isCaseSensitive ) { this . invalidValues = invalidValues ; } else { this . invalidValues = new HashSet < String > ( ) ; for ( String value : invalidValues ) { this . invalidValues . add ( value . toLowerCase ( ) ) ; } } this . isCaseSensitive = isCaseSensitive ; this . invalidValueErrorMessage = invalidValueErrorMessage ; }
Sets the invalid values for the TextBox
114
9
147,484
public void setRegExp ( final String pattern , final String invalidCharactersInNameErrorMessage , final String invalidCharacterTypedMessage ) { regExp = RegExp . compile ( pattern ) ; this . invalidCharactersInNameErrorMessage = invalidCharactersInNameErrorMessage ; this . invalidCharacterTypedMessage = invalidCharacterTypedMessage ; }
Sets the RegExp pattern for the TextBox
70
10
147,485
public HashMap < String , String > getProperties ( ) { if ( this . properties == null ) { this . properties = new HashMap < String , String > ( ) ; } return properties ; }
return a HashMap with all properties name as key value as value
43
13
147,486
public String putProperty ( String key , String value ) { return this . getProperties ( ) . put ( key , value ) ; }
changes an existing property with the same name or adds a new one
29
13
147,487
List < String > getRuleFlowNames ( HttpServletRequest req ) { final String [ ] projectAndBranch = getProjectAndBranchNames ( req ) ; // Query RuleFlowGroups for asset project and branch List < RefactoringPageRow > results = queryService . query ( DesignerFindRuleFlowNamesQuery . NAME , new HashSet < ValueIndexTerm > ( ) { { add ( new ValueSharedPartIndexTerm ( "*" , PartType . RULEFLOW_GROUP , TermSearchType . WILDCARD ) ) ; add ( new ValueModuleNameIndexTerm ( projectAndBranch [ 0 ] ) ) ; if ( projectAndBranch [ 1 ] != null ) { add ( new ValueBranchNameIndexTerm ( projectAndBranch [ 1 ] ) ) ; } } } ) ; final List < String > ruleFlowGroupNames = new ArrayList < String > ( ) ; for ( RefactoringPageRow row : results ) { ruleFlowGroupNames . add ( ( String ) row . getValue ( ) ) ; } Collections . sort ( ruleFlowGroupNames ) ; // Query RuleFlowGroups for all projects and branches results = queryService . query ( DesignerFindRuleFlowNamesQuery . NAME , new HashSet < ValueIndexTerm > ( ) { { add ( new ValueSharedPartIndexTerm ( "*" , PartType . RULEFLOW_GROUP , TermSearchType . WILDCARD ) ) ; } } ) ; final List < String > otherRuleFlowGroupNames = new LinkedList < String > ( ) ; for ( RefactoringPageRow row : results ) { String ruleFlowGroupName = ( String ) row . getValue ( ) ; if ( ! ruleFlowGroupNames . contains ( ruleFlowGroupName ) ) { // but only add the new ones otherRuleFlowGroupNames . add ( ruleFlowGroupName ) ; } } Collections . sort ( otherRuleFlowGroupNames ) ; ruleFlowGroupNames . addAll ( otherRuleFlowGroupNames ) ; return ruleFlowGroupNames ; }
package scope in order to test the method
435
8
147,488
public static Map < String , IDiagramPlugin > getLocalPluginsRegistry ( ServletContext context ) { if ( LOCAL == null ) { LOCAL = initializeLocalPlugins ( context ) ; } return LOCAL ; }
Initialize the local plugins registry
49
6
147,489
public boolean addSsextension ( String ssExt ) { if ( this . ssextensions == null ) { this . ssextensions = new ArrayList < String > ( ) ; } return this . ssextensions . add ( ssExt ) ; }
Add an additional SSExtension
57
7
147,490
private static JSONObject parseStencil ( String stencilId ) throws JSONException { JSONObject stencilObject = new JSONObject ( ) ; stencilObject . put ( "id" , stencilId . toString ( ) ) ; return stencilObject ; }
Delivers the correct JSON Object for the stencilId
56
11
147,491
private static JSONArray parseChildShapesRecursive ( ArrayList < Shape > childShapes ) throws JSONException { if ( childShapes != null ) { JSONArray childShapesArray = new JSONArray ( ) ; for ( Shape childShape : childShapes ) { JSONObject childShapeObject = new JSONObject ( ) ; childShapeObject . put ( "resourceId" , childShape . getResourceId ( ) . toString ( ) ) ; childShapeObject . put ( "properties" , parseProperties ( childShape . getProperties ( ) ) ) ; childShapeObject . put ( "stencil" , parseStencil ( childShape . getStencilId ( ) ) ) ; childShapeObject . put ( "childShapes" , parseChildShapesRecursive ( childShape . getChildShapes ( ) ) ) ; childShapeObject . put ( "outgoing" , parseOutgoings ( childShape . getOutgoings ( ) ) ) ; childShapeObject . put ( "bounds" , parseBounds ( childShape . getBounds ( ) ) ) ; childShapeObject . put ( "dockers" , parseDockers ( childShape . getDockers ( ) ) ) ; if ( childShape . getTarget ( ) != null ) { childShapeObject . put ( "target" , parseTarget ( childShape . getTarget ( ) ) ) ; } childShapesArray . put ( childShapeObject ) ; } return childShapesArray ; } return new JSONArray ( ) ; }
Parses all child Shapes recursively and adds them to the correct JSON Object
328
18
147,492
private static JSONObject parseTarget ( Shape target ) throws JSONException { JSONObject targetObject = new JSONObject ( ) ; targetObject . put ( "resourceId" , target . getResourceId ( ) . toString ( ) ) ; return targetObject ; }
Delivers the correct JSON Object for the target
54
9
147,493
private static JSONArray parseDockers ( ArrayList < Point > dockers ) throws JSONException { if ( dockers != null ) { JSONArray dockersArray = new JSONArray ( ) ; for ( Point docker : dockers ) { JSONObject dockerObject = new JSONObject ( ) ; dockerObject . put ( "x" , docker . getX ( ) . doubleValue ( ) ) ; dockerObject . put ( "y" , docker . getY ( ) . doubleValue ( ) ) ; dockersArray . put ( dockerObject ) ; } return dockersArray ; } return new JSONArray ( ) ; }
Delivers the correct JSON Object for the dockers
130
10
147,494
private static JSONArray parseOutgoings ( ArrayList < Shape > outgoings ) throws JSONException { if ( outgoings != null ) { JSONArray outgoingsArray = new JSONArray ( ) ; for ( Shape outgoing : outgoings ) { JSONObject outgoingObject = new JSONObject ( ) ; outgoingObject . put ( "resourceId" , outgoing . getResourceId ( ) . toString ( ) ) ; outgoingsArray . put ( outgoingObject ) ; } return outgoingsArray ; } return new JSONArray ( ) ; }
Delivers the correct JSON Object for outgoings
116
10
147,495
private static JSONObject parseProperties ( HashMap < String , String > properties ) throws JSONException { if ( properties != null ) { JSONObject propertiesObject = new JSONObject ( ) ; for ( String key : properties . keySet ( ) ) { String propertyValue = properties . get ( key ) ; /* * if(propertyValue.matches("true|false")) { * * propertiesObject.put(key, propertyValue.equals("true")); * * } else if(propertyValue.matches("[0-9]+")) { * * Integer value = Integer.parseInt(propertyValue); * propertiesObject.put(key, value); * * } else */ if ( propertyValue . startsWith ( "{" ) && propertyValue . endsWith ( "}" ) ) { propertiesObject . put ( key , new JSONObject ( propertyValue ) ) ; } else { propertiesObject . put ( key , propertyValue . toString ( ) ) ; } } return propertiesObject ; } return new JSONObject ( ) ; }
Delivers the correct JSON Object for properties
216
8
147,496
private static JSONArray parseStencilSetExtensions ( ArrayList < String > extensions ) { if ( extensions != null ) { JSONArray extensionsArray = new JSONArray ( ) ; for ( String extension : extensions ) { extensionsArray . put ( extension . toString ( ) ) ; } return extensionsArray ; } return new JSONArray ( ) ; }
Delivers the correct JSON Object for the Stencilset Extensions
73
13
147,497
private static JSONObject parseStencilSet ( StencilSet stencilSet ) throws JSONException { if ( stencilSet != null ) { JSONObject stencilSetObject = new JSONObject ( ) ; stencilSetObject . put ( "url" , stencilSet . getUrl ( ) . toString ( ) ) ; stencilSetObject . put ( "namespace" , stencilSet . getNamespace ( ) . toString ( ) ) ; return stencilSetObject ; } return new JSONObject ( ) ; }
Delivers the correct JSON Object for the Stencilset
113
12
147,498
private static JSONObject parseBounds ( Bounds bounds ) throws JSONException { if ( bounds != null ) { JSONObject boundsObject = new JSONObject ( ) ; JSONObject lowerRight = new JSONObject ( ) ; JSONObject upperLeft = new JSONObject ( ) ; lowerRight . put ( "x" , bounds . getLowerRight ( ) . getX ( ) . doubleValue ( ) ) ; lowerRight . put ( "y" , bounds . getLowerRight ( ) . getY ( ) . doubleValue ( ) ) ; upperLeft . put ( "x" , bounds . getUpperLeft ( ) . getX ( ) . doubleValue ( ) ) ; upperLeft . put ( "y" , bounds . getUpperLeft ( ) . getY ( ) . doubleValue ( ) ) ; boundsObject . put ( "lowerRight" , lowerRight ) ; boundsObject . put ( "upperLeft" , upperLeft ) ; return boundsObject ; } return new JSONObject ( ) ; }
Delivers the correct JSON Object for the Bounds
211
10
147,499
public static String createQuotedConstant ( String str ) { if ( str == null || str . isEmpty ( ) ) { return str ; } try { Double . parseDouble ( str ) ; } catch ( NumberFormatException nfe ) { return "\"" + str + "\"" ; } return str ; }
Puts strings inside quotes and numerics are left as they are .
67
14