idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
17,500 | public OIdentifiable getKeyAt ( final int iIndex ) { if ( rids != null && rids [ iIndex ] != null ) return rids [ iIndex ] ; final ORecordId rid = itemFromStream ( iIndex ) ; if ( rids != null ) rids [ iIndex ] = rid ; return rid ; } | Lazy unmarshall the RID if not in memory . |
17,501 | public void close ( ) { if ( indexManager != null ) indexManager . flush ( ) ; if ( schema != null ) schema . close ( ) ; if ( security != null ) security . close ( ) ; } | Closes internal objects |
17,502 | public MuleMessage doHttpSendRequest ( String url , String method , String payload , String contentType ) { Map < String , String > properties = new HashMap < String , String > ( ) ; properties . put ( "http.method" , method ) ; properties . put ( "Content-Type" , contentType ) ; MuleMessage response = send ( url , payload , properties ) ; return response ; } | Perform a HTTP call sending information to the server using POST or PUT |
17,503 | public MuleMessage doHttpReceiveRequest ( String url , String method , String acceptConentType , String acceptCharSet ) { Map < String , String > properties = new HashMap < String , String > ( ) ; properties . put ( "http.method" , method ) ; properties . put ( "Accept" , acceptConentType ) ; properties . put ( "Accept-Charset" , acceptCharSet ) ; MuleMessage response = send ( url , null , properties ) ; return response ; } | Perform a HTTP call receiving information from the server using GET or DELETE |
17,504 | public byte [ ] toByteArray ( ) { if ( this . pos == this . length ) return this . buffer ; else { byte [ ] res = new byte [ this . pos ] ; System . arraycopy ( this . buffer , 0 , res , 0 , this . pos ) ; return res ; } } | Returns the written to the stream data as a byte array |
17,505 | public void write ( byte [ ] b , int off , int len ) { this . checkIncreaseArray ( len ) ; System . arraycopy ( b , off , this . buffer , this . pos , len ) ; this . pos += len ; } | Writes a byte array content into the stream |
17,506 | public void writeTag ( int tagClass , boolean primitive , int tag ) throws AsnException { if ( tag < 0 ) throw new AsnException ( "Tag must not be negative" ) ; if ( tag <= 30 ) { int toEncode = ( tagClass & 0x03 ) << 6 ; toEncode |= ( primitive ? 0 : 1 ) << 5 ; toEncode |= tag & 0x1F ; this . write ( toEncode ) ; } else { int toEncode = ( tagClass & 0x03 ) << 6 ; toEncode |= ( primitive ? 0 : 1 ) << 5 ; toEncode |= 0x1F ; this . write ( toEncode ) ; int byteArr = 8 ; byte [ ] buf = new byte [ byteArr ] ; int pos = byteArr ; while ( true ) { int dd ; if ( tag <= 0x7F ) { dd = tag ; if ( pos != byteArr ) dd = dd | 0x80 ; buf [ -- pos ] = ( byte ) dd ; break ; } else { dd = ( tag & 0x7F ) ; tag >>= 7 ; if ( pos != byteArr ) dd = dd | 0x80 ; buf [ -- pos ] = ( byte ) dd ; } } this . write ( buf , pos , byteArr - pos ) ; } } | Writes a tag field into the atream |
17,507 | public void writeLength ( int v ) throws IOException { if ( v == Tag . Indefinite_Length ) { this . write ( 0x80 ) ; return ; } else if ( v > 0x7F ) { int count ; byte [ ] buf = new byte [ 4 ] ; if ( ( v & 0xFF000000 ) > 0 ) { buf [ 0 ] = ( byte ) ( ( v >> 24 ) & 0xFF ) ; buf [ 1 ] = ( byte ) ( ( v >> 16 ) & 0xFF ) ; buf [ 2 ] = ( byte ) ( ( v >> 8 ) & 0xFF ) ; buf [ 3 ] = ( byte ) ( v & 0xFF ) ; count = 4 ; } else if ( ( v & 0x00FF0000 ) > 0 ) { buf [ 0 ] = ( byte ) ( ( v >> 16 ) & 0xFF ) ; buf [ 1 ] = ( byte ) ( ( v >> 8 ) & 0xFF ) ; buf [ 2 ] = ( byte ) ( v & 0xFF ) ; count = 3 ; } else if ( ( v & 0x0000FF00 ) > 0 ) { buf [ 0 ] = ( byte ) ( ( v >> 8 ) & 0xFF ) ; buf [ 1 ] = ( byte ) ( v & 0xFF ) ; count = 2 ; } else { buf [ 0 ] = ( byte ) ( v & 0xFF ) ; count = 1 ; } this . buffer [ pos ] = ( byte ) ( 0x80 | count ) ; for ( int i1 = 0 ; i1 < count ; i1 ++ ) { this . buffer [ pos + i1 + 1 ] = buf [ i1 ] ; } this . pos += count + 1 ; } else { this . write ( v ) ; } } | Write the length field into the stream Use Tag . Indefinite_Length for writing the indefinite length |
17,508 | public void FinalizeContent ( int lenPos ) { if ( lenPos == Tag . Indefinite_Length ) { this . write ( 0 ) ; this . write ( 0 ) ; } else { int length = this . pos - lenPos - 1 ; if ( length <= 0x7F ) { this . buffer [ lenPos ] = ( byte ) length ; } else { int count ; byte [ ] buf = new byte [ 4 ] ; if ( ( length & 0xFF000000 ) > 0 ) { buf [ 0 ] = ( byte ) ( ( length >> 24 ) & 0xFF ) ; buf [ 1 ] = ( byte ) ( ( length >> 16 ) & 0xFF ) ; buf [ 2 ] = ( byte ) ( ( length >> 8 ) & 0xFF ) ; buf [ 3 ] = ( byte ) ( length & 0xFF ) ; count = 4 ; } else if ( ( length & 0x00FF0000 ) > 0 ) { buf [ 0 ] = ( byte ) ( ( length >> 16 ) & 0xFF ) ; buf [ 1 ] = ( byte ) ( ( length >> 8 ) & 0xFF ) ; buf [ 2 ] = ( byte ) ( length & 0xFF ) ; count = 3 ; } else if ( ( length & 0x0000FF00 ) > 0 ) { buf [ 0 ] = ( byte ) ( ( length >> 8 ) & 0xFF ) ; buf [ 1 ] = ( byte ) ( length & 0xFF ) ; count = 2 ; } else { buf [ 0 ] = ( byte ) ( length & 0xFF ) ; count = 1 ; } this . checkIncreaseArray ( count ) ; System . arraycopy ( this . buffer , lenPos + 1 , this . buffer , lenPos + 1 + count , length ) ; this . pos += count ; this . buffer [ lenPos ] = ( byte ) ( 0x80 | count ) ; for ( int i1 = 0 ; i1 < count ; i1 ++ ) { this . buffer [ lenPos + i1 + 1 ] = buf [ i1 ] ; } } } } | This method must be invoked after finishing the content writing |
17,509 | private static byte _getByte ( int startIndex , BitSetStrictLength set ) throws AsnException { int count = 8 ; byte data = 0 ; while ( count > 0 ) { if ( set . length ( ) - 1 < startIndex ) { break ; } else { boolean lit = set . get ( startIndex ) ; if ( lit ) { data |= ( 0x01 << ( count - 1 ) ) ; } startIndex ++ ; count -- ; } } return data ; } | Attepts to read up to 8 bits and store into byte . If less is found only those are returned |
17,510 | public void startup ( ) { underlying . startup ( ) ; OProfiler . getInstance ( ) . registerHookValue ( profilerPrefix + "enabled" , new OProfilerHookValue ( ) { public Object getValue ( ) { return isEnabled ( ) ; } } ) ; OProfiler . getInstance ( ) . registerHookValue ( profilerPrefix + "current" , new OProfilerHookValue ( ) { public Object getValue ( ) { return getSize ( ) ; } } ) ; OProfiler . getInstance ( ) . registerHookValue ( profilerPrefix + "max" , new OProfilerHookValue ( ) { public Object getValue ( ) { return getMaxSize ( ) ; } } ) ; } | All operations running at cache initialization stage |
17,511 | public Cipher getCipher ( ) throws GeneralSecurityException { Cipher cipher = Cipher . getInstance ( "Blowfish/ECB/PKCS5Padding" ) ; cipher . init ( Cipher . DECRYPT_MODE , new SecretKeySpec ( key , "Blowfish" ) ) ; return cipher ; } | Creates a cipher for decrypting data with the specified key . |
17,512 | public Cipher getEncryptionCipher ( ) throws GeneralSecurityException { Cipher cipher = Cipher . getInstance ( "Blowfish/ECB/PKCS5Padding" ) ; cipher . init ( Cipher . ENCRYPT_MODE , new SecretKeySpec ( key , "Blowfish" ) ) ; return cipher ; } | Creates a cipher for encrypting data with the specified key . |
17,513 | public Object execute ( final Map < Object , Object > iArgs ) { if ( className == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseRecord database = getDatabase ( ) ; final OClass oClass = database . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( oClass == null ) return null ; for ( final OIndex < ? > oIndex : oClass . getClassIndexes ( ) ) { database . getMetadata ( ) . getIndexManager ( ) . dropIndex ( oIndex . getName ( ) ) ; } final OClass superClass = oClass . getSuperClass ( ) ; final int [ ] clustersToIndex = oClass . getPolymorphicClusterIds ( ) ; final String [ ] clusterNames = new String [ clustersToIndex . length ] ; for ( int i = 0 ; i < clustersToIndex . length ; i ++ ) { clusterNames [ i ] = database . getClusterNameById ( clustersToIndex [ i ] ) ; } final int clusterId = oClass . getDefaultClusterId ( ) ; ( ( OSchemaProxy ) database . getMetadata ( ) . getSchema ( ) ) . dropClassInternal ( className ) ; ( ( OSchemaProxy ) database . getMetadata ( ) . getSchema ( ) ) . saveInternal ( ) ; database . getMetadata ( ) . getSchema ( ) . reload ( ) ; deleteDefaultCluster ( clusterId ) ; if ( superClass == null ) return true ; for ( final OIndex < ? > oIndex : superClass . getIndexes ( ) ) { for ( final String clusterName : clusterNames ) oIndex . getInternal ( ) . removeCluster ( clusterName ) ; OLogManager . instance ( ) . info ( "Index %s is used in super class of %s and should be rebuilt." , oIndex . getName ( ) , className ) ; oIndex . rebuild ( ) ; } return true ; } | Execute the DROP CLASS . |
17,514 | public int compareTo ( final OCompositeKey otherKey ) { final Iterator < Object > inIter = keys . iterator ( ) ; final Iterator < Object > outIter = otherKey . keys . iterator ( ) ; while ( inIter . hasNext ( ) && outIter . hasNext ( ) ) { final Object inKey = inIter . next ( ) ; final Object outKey = outIter . next ( ) ; if ( outKey instanceof OAlwaysGreaterKey ) return - 1 ; if ( outKey instanceof OAlwaysLessKey ) return 1 ; final int result = comparator . compare ( inKey , outKey ) ; if ( result != 0 ) return result ; } return 0 ; } | Performs partial comparison of two composite keys . |
17,515 | public Map < String , Object > getVariables ( ) { final HashMap < String , Object > map = new HashMap < String , Object > ( ) ; if ( inherited != null ) map . putAll ( inherited . getVariables ( ) ) ; if ( variables != null ) map . putAll ( variables ) ; return map ; } | Returns a read - only map with all the variables . |
17,516 | @ SuppressWarnings ( "unchecked" ) public < T > T getPropertyValue ( ElementDescriptor < T > property ) { if ( mProperties == null ) { return null ; } return ( T ) mProperties . get ( property ) ; } | Returns the value of a property in this propstat element . |
17,517 | public < T > void clear ( ElementDescriptor < T > property ) { if ( mSet != null ) { mSet . remove ( property ) ; } } | Remove a property from the initial values . |
17,518 | public long countClass ( final String iClassName ) { final OClass cls = getMetadata ( ) . getSchema ( ) . getClass ( iClassName ) ; if ( cls == null ) throw new IllegalArgumentException ( "Class '" + iClassName + "' not found in database" ) ; return cls . count ( ) ; } | Returns the number of the records of the class iClassName . |
17,519 | public OBinarySerializer < ? > getObjectSerializer ( final byte identifier ) { OBinarySerializer < ? > impl = serializerIdMap . get ( identifier ) ; if ( impl == null ) { final Class < ? extends OBinarySerializer < ? > > cls = serializerClassesIdMap . get ( identifier ) ; if ( cls != null ) try { impl = cls . newInstance ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot create an instance of class %s invoking the empty constructor" , cls ) ; } } return impl ; } | Obtain OBinarySerializer instance by it s id . |
17,520 | public long addRecord ( final ORecordId iRid , final byte [ ] iContent ) throws IOException { if ( iContent . length == 0 ) return - 1 ; final int recordSize = iContent . length + RECORD_FIX_SIZE ; acquireExclusiveLock ( ) ; try { final long [ ] newFilePosition = getFreeSpace ( recordSize ) ; writeRecord ( newFilePosition , iRid . clusterId , iRid . clusterPosition , iContent ) ; return getAbsolutePosition ( newFilePosition ) ; } finally { releaseExclusiveLock ( ) ; } } | Add the record content in file . |
17,521 | public byte [ ] getRecord ( final long iPosition ) throws IOException { if ( iPosition == - 1 ) return null ; acquireSharedLock ( ) ; try { final long [ ] pos = getRelativePosition ( iPosition ) ; final OFile file = files [ ( int ) pos [ 0 ] ] ; final int recordSize = file . readInt ( pos [ 1 ] ) ; if ( recordSize <= 0 ) return null ; if ( pos [ 1 ] + RECORD_FIX_SIZE + recordSize > file . getFilledUpTo ( ) ) throw new OStorageException ( "Error on reading record from file '" + file . getName ( ) + "', position " + iPosition + ", size " + OFileUtils . getSizeAsString ( recordSize ) + ": the record size is bigger then the file itself (" + OFileUtils . getSizeAsString ( getFilledUpTo ( ) ) + "). Probably the record is dirty due to a previous crash. It is strongly suggested to restore the database or export and reimport this one." ) ; final byte [ ] content = new byte [ recordSize ] ; file . read ( pos [ 1 ] + RECORD_FIX_SIZE , content , recordSize ) ; return content ; } finally { releaseSharedLock ( ) ; } } | Returns the record content from file . |
17,522 | public int getRecordSize ( final long iPosition ) throws IOException { acquireSharedLock ( ) ; try { final long [ ] pos = getRelativePosition ( iPosition ) ; final OFile file = files [ ( int ) pos [ 0 ] ] ; return file . readInt ( pos [ 1 ] ) ; } finally { releaseSharedLock ( ) ; } } | Returns the record size . |
17,523 | public long setRecord ( final long iPosition , final ORecordId iRid , final byte [ ] iContent ) throws IOException { acquireExclusiveLock ( ) ; try { long [ ] pos = getRelativePosition ( iPosition ) ; final OFile file = files [ ( int ) pos [ 0 ] ] ; final int recordSize = file . readInt ( pos [ 1 ] ) ; final int contentLength = iContent != null ? iContent . length : 0 ; if ( contentLength == recordSize ) { file . write ( pos [ 1 ] + RECORD_FIX_SIZE , iContent ) ; OProfiler . getInstance ( ) . updateCounter ( PROFILER_UPDATE_REUSED_ALL , + 1 ) ; return iPosition ; } else if ( recordSize - contentLength > RECORD_FIX_SIZE + 50 ) { writeRecord ( pos , iRid . clusterId , iRid . clusterPosition , iContent ) ; handleHole ( iPosition + RECORD_FIX_SIZE + contentLength , recordSize - contentLength - RECORD_FIX_SIZE ) ; OProfiler . getInstance ( ) . updateCounter ( PROFILER_UPDATE_REUSED_PARTIAL , + 1 ) ; } else { handleHole ( iPosition , recordSize ) ; pos = getFreeSpace ( contentLength + RECORD_FIX_SIZE ) ; writeRecord ( pos , iRid . clusterId , iRid . clusterPosition , iContent ) ; OProfiler . getInstance ( ) . updateCounter ( PROFILER_UPDATE_NOT_REUSED , + 1 ) ; } return getAbsolutePosition ( pos ) ; } finally { releaseExclusiveLock ( ) ; } } | Set the record content in file . |
17,524 | public List < ODataHoleInfo > getHolesList ( ) { acquireSharedLock ( ) ; try { final List < ODataHoleInfo > holes = new ArrayList < ODataHoleInfo > ( ) ; final int tot = holeSegment . getHoles ( ) ; for ( int i = 0 ; i < tot ; ++ i ) { final ODataHoleInfo h = holeSegment . getHole ( i ) ; if ( h != null ) holes . add ( h ) ; } return holes ; } finally { releaseSharedLock ( ) ; } } | Returns the list of holes as pair of position & ppos |
17,525 | private static boolean betweenLongitudes ( double topLeftLon , double bottomRightLon , double lon ) { if ( topLeftLon <= bottomRightLon ) return lon >= topLeftLon && lon <= bottomRightLon ; else return lon >= topLeftLon || lon <= bottomRightLon ; } | Returns true if and only if lon is between the longitudes topLeftLon and bottomRightLon . |
17,526 | public int getPropertyStatus ( ElementDescriptor < ? > descriptor ) { PropStat propStat = mPropStatByProperty . get ( descriptor ) ; if ( propStat == null ) { return STATUS_NONE ; } return propStat . getStatusCode ( ) ; } | Return the status of a specific property . |
17,527 | public < T > T getPropertyValue ( ElementDescriptor < T > descriptor ) { PropStat propStat = mPropStatByProperty . get ( descriptor ) ; if ( propStat == null ) { return null ; } return propStat . getPropertyValue ( descriptor ) ; } | Get the value of a specific property . |
17,528 | private static synchronized Set < OIndexFactory > getFactories ( ) { if ( FACTORIES == null ) { final Iterator < OIndexFactory > ite = lookupProviderWithOrientClassLoader ( OIndexFactory . class , orientClassLoader ) ; final Set < OIndexFactory > factories = new HashSet < OIndexFactory > ( ) ; while ( ite . hasNext ( ) ) { factories . add ( ite . next ( ) ) ; } FACTORIES = Collections . unmodifiableSet ( factories ) ; } return FACTORIES ; } | Cache a set of all factories . we do not use the service loader directly since it is not concurrent . |
17,529 | public void addListener ( final ORecordListener iListener ) { if ( _listeners == null ) _listeners = Collections . newSetFromMap ( new WeakHashMap < ORecordListener , Boolean > ( ) ) ; _listeners . add ( iListener ) ; } | Add a listener to the current document to catch all the supported events . |
17,530 | public static String getComponentProjectName ( int componentType , String groupId , String artifactId ) { IModel m = ModelFactory . newModel ( groupId , artifactId , null , null , MuleVersionEnum . MAIN_MULE_VERSION , null , null ) ; String projectFolderName = null ; ComponentEnum compEnum = ComponentEnum . get ( componentType ) ; switch ( compEnum ) { case INTEGRATION_COMPONENT : projectFolderName = m . getIntegrationComponentProject ( ) ; break ; case INTEGRATION_TESTSTUBS_COMPONENT : projectFolderName = m . getTeststubStandaloneProject ( ) ; break ; case SD_SCHEMA_COMPONENT : projectFolderName = m . getSchemaProject ( ) ; break ; } return projectFolderName ; } | public static final int IM_SCHEMA_COMPONENT = 3 ; |
17,531 | protected boolean checkConsistency ( Object o1 , Object o2 ) { return checkConsistency ( o1 , o2 , null , null ) ; } | convenience method for unit testing |
17,532 | public boolean checkConsistency ( final Object legacyEntity , final Object lightblueEntity , final String methodName , MethodCallStringifier callToLogInCaseOfInconsistency ) { if ( legacyEntity == null && lightblueEntity == null ) { return true ; } if ( callToLogInCaseOfInconsistency == null ) { callToLogInCaseOfInconsistency = new LazyMethodCallStringifier ( ) ; } try { Timer p2j = new Timer ( "ConsistencyChecker's pojo2json conversion" ) ; final JsonNode legacyJson = objectMapper . valueToTree ( legacyEntity ) ; final JsonNode lightblueJson = objectMapper . valueToTree ( lightblueEntity ) ; p2j . complete ( ) ; try { Timer t = new Timer ( "checkConsistency (jiff)" ) ; List < JsonDelta > deltas = jiff . computeDiff ( legacyJson , lightblueJson ) ; boolean consistent = deltas . isEmpty ( ) ; long jiffConsistencyCheckTook = t . complete ( ) ; if ( inconsistencyLog . isDebugEnabled ( ) ) { inconsistencyLog . debug ( "Jiff consistency check took: " + jiffConsistencyCheckTook + " ms" ) ; inconsistencyLog . debug ( "Jiff consistency check passed: true" ) ; } if ( consistent ) { return true ; } String legacyJsonStr = objectMapper . writeValueAsString ( legacyEntity ) ; String lightblueJsonStr = objectMapper . writeValueAsString ( lightblueEntity ) ; if ( "true" . equals ( legacyJsonStr ) || "false" . equals ( legacyJsonStr ) ) { legacyJsonStr = "\"" + legacyJsonStr + "\"" ; } if ( "true" . equals ( lightblueJsonStr ) || "false" . equals ( lightblueJsonStr ) ) { lightblueJsonStr = "\"" + lightblueJsonStr + "\"" ; } if ( "null" . equals ( legacyJsonStr ) || "null" . equals ( lightblueJsonStr ) ) { logInconsistency ( Thread . currentThread ( ) . getName ( ) , callToLogInCaseOfInconsistency . toString ( ) , legacyJsonStr , lightblueJsonStr , "One object is null and the other isn't" ) ; } else { if ( legacyJsonStr . length ( ) >= maxJsonStrLengthForJsonCompare || lightblueJsonStr . length ( ) >= maxJsonStrLengthForJsonCompare ) { inconsistencyLog . debug ( "Using jiff to produce inconsistency warning" ) ; logInconsistencyUsingJiff ( Thread . currentThread ( ) . getName ( ) , legacyJsonStr , lightblueJsonStr , deltas , callToLogInCaseOfInconsistency , Boolean . valueOf ( System . getProperty ( "lightblue.facade.consistencyChecker.blocking" , "false" ) ) ) ; } else { inconsistencyLog . debug ( "Using org.skyscreamer.jsonassert.JSONCompare to produce inconsistency warning" ) ; logInconsistencyUsingJSONCompare ( Thread . currentThread ( ) . getName ( ) , legacyJsonStr , lightblueJsonStr , callToLogInCaseOfInconsistency , Boolean . valueOf ( System . getProperty ( "lightblue.facade.consistencyChecker.blocking" , "false" ) ) ) ; } } return false ; } catch ( IOException e ) { inconsistencyLog . error ( "Consistency check failed in " + implementationName + "." + callToLogInCaseOfInconsistency + "! Invalid JSON: legacyJson=" + legacyJson + ", lightblueJson=" + lightblueJson , e ) ; } } catch ( Exception e ) { inconsistencyLog . error ( "Consistency check failed in " + implementationName + "." + callToLogInCaseOfInconsistency + "! legacyEntity=" + legacyEntity + ", lightblueEntity=" + lightblueEntity , e ) ; } return false ; } | Check that objects are equal using org . skyscreamer . jsonassert library . |
17,533 | public Object execute ( final Map < Object , Object > iArgs ) { if ( newRecords == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final OCommandParameters commandParameters = new OCommandParameters ( iArgs ) ; if ( indexName != null ) { final OIndex < ? > index = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndex ( indexName ) ; if ( index == null ) throw new OCommandExecutionException ( "Target index '" + indexName + "' not found" ) ; Map < String , Object > result = null ; for ( Map < String , Object > candidate : newRecords ) { index . put ( getIndexKeyValue ( commandParameters , candidate ) , getIndexValue ( commandParameters , candidate ) ) ; result = candidate ; } return new ODocument ( result ) ; } else { final List < ODocument > docs = new ArrayList < ODocument > ( ) ; for ( Map < String , Object > candidate : newRecords ) { final ODocument doc = className != null ? new ODocument ( className ) : new ODocument ( ) ; OSQLHelper . bindParameters ( doc , candidate , commandParameters ) ; if ( clusterName != null ) { doc . save ( clusterName ) ; } else { doc . save ( ) ; } docs . add ( doc ) ; } if ( docs . size ( ) == 1 ) { return docs . get ( 0 ) ; } else { return docs ; } } } | Execute the INSERT and return the ODocument object created . |
17,534 | @ SuppressWarnings ( "unchecked" ) public OGraphEdge link ( final OGraphVertex iTargetVertex , final String iClassName ) { if ( iTargetVertex == null ) throw new IllegalArgumentException ( "Missed the target vertex" ) ; final OGraphEdge edge = new OGraphEdge ( database , iClassName , this , iTargetVertex ) ; getOutEdges ( ) . add ( edge ) ; Set < ODocument > recordEdges = ( ( Set < ODocument > ) document . field ( OGraphDatabase . VERTEX_FIELD_OUT ) ) ; if ( recordEdges == null ) { recordEdges = new HashSet < ODocument > ( ) ; document . field ( OGraphDatabase . VERTEX_FIELD_OUT , recordEdges ) ; } recordEdges . add ( edge . getDocument ( ) ) ; document . setDirty ( ) ; iTargetVertex . getInEdges ( ) . add ( edge ) ; recordEdges = ( ( Set < ODocument > ) iTargetVertex . getDocument ( ) . field ( OGraphDatabase . VERTEX_FIELD_IN ) ) ; if ( recordEdges == null ) { recordEdges = new HashSet < ODocument > ( ) ; iTargetVertex . getDocument ( ) . field ( OGraphDatabase . VERTEX_FIELD_IN , recordEdges ) ; } recordEdges . add ( edge . getDocument ( ) ) ; iTargetVertex . getDocument ( ) . setDirty ( ) ; return edge ; } | Create a link between the current vertex and the target one . The link is of type iClassName . |
17,535 | public OGraphVertex unlink ( final OGraphVertex iTargetVertex ) { if ( iTargetVertex == null ) throw new IllegalArgumentException ( "Missed the target vertex" ) ; unlink ( database , document , iTargetVertex . getDocument ( ) ) ; return this ; } | Remove the link between the current vertex and the target one . |
17,536 | public boolean hasInEdges ( ) { final Set < ODocument > docs = document . field ( OGraphDatabase . VERTEX_FIELD_IN ) ; return docs != null && ! docs . isEmpty ( ) ; } | Returns true if the vertex has at least one incoming edge otherwise false . |
17,537 | public boolean hasOutEdges ( ) { final Set < ODocument > docs = document . field ( OGraphDatabase . VERTEX_FIELD_OUT ) ; return docs != null && ! docs . isEmpty ( ) ; } | Returns true if the vertex has at least one outgoing edge otherwise false . |
17,538 | public Set < OGraphEdge > getInEdges ( final String iEdgeLabel ) { Set < OGraphEdge > temp = in != null ? in . get ( ) : null ; if ( temp == null ) { if ( iEdgeLabel == null ) temp = new HashSet < OGraphEdge > ( ) ; in = new SoftReference < Set < OGraphEdge > > ( temp ) ; final Set < Object > docs = document . field ( OGraphDatabase . VERTEX_FIELD_IN ) ; if ( docs != null ) { for ( Object o : docs ) { final ODocument doc = ( ODocument ) ( ( OIdentifiable ) o ) . getRecord ( ) ; if ( iEdgeLabel != null && ! iEdgeLabel . equals ( doc . field ( OGraphDatabase . LABEL ) ) ) continue ; temp . add ( ( OGraphEdge ) database . getUserObjectByRecord ( doc , null ) ) ; } } } else if ( iEdgeLabel != null ) { HashSet < OGraphEdge > filtered = new HashSet < OGraphEdge > ( ) ; for ( OGraphEdge e : temp ) { if ( iEdgeLabel . equals ( e . getLabel ( ) ) ) filtered . add ( e ) ; } temp = filtered ; } return temp ; } | Returns the incoming edges of current node having the requested label . If there are no edged then an empty set is returned . |
17,539 | @ SuppressWarnings ( "unchecked" ) public Set < OGraphVertex > browseOutEdgesVertexes ( ) { final Set < OGraphVertex > resultset = new HashSet < OGraphVertex > ( ) ; Set < OGraphEdge > temp = out != null ? out . get ( ) : null ; if ( temp == null ) { final Set < OIdentifiable > docEdges = ( Set < OIdentifiable > ) document . field ( OGraphDatabase . VERTEX_FIELD_OUT ) ; if ( docEdges != null ) for ( OIdentifiable d : docEdges ) { resultset . add ( ( OGraphVertex ) database . getUserObjectByRecord ( ( ODocument ) ( ( ODocument ) d . getRecord ( ) ) . field ( OGraphDatabase . EDGE_FIELD_IN ) , null ) ) ; } } else { for ( OGraphEdge edge : temp ) { resultset . add ( edge . getIn ( ) ) ; } } return resultset ; } | Returns the set of Vertexes from the outgoing edges . It avoids to unmarshall edges . |
17,540 | @ SuppressWarnings ( "unchecked" ) public Set < OGraphVertex > browseInEdgesVertexes ( ) { final Set < OGraphVertex > resultset = new HashSet < OGraphVertex > ( ) ; Set < OGraphEdge > temp = in != null ? in . get ( ) : null ; if ( temp == null ) { final Set < ODocument > docEdges = ( Set < ODocument > ) document . field ( OGraphDatabase . VERTEX_FIELD_IN ) ; if ( docEdges != null ) for ( ODocument d : docEdges ) { resultset . add ( ( OGraphVertex ) database . getUserObjectByRecord ( ( ODocument ) d . field ( OGraphDatabase . EDGE_FIELD_OUT ) , null ) ) ; } } else { for ( OGraphEdge edge : temp ) { resultset . add ( edge . getOut ( ) ) ; } } return resultset ; } | Returns the set of Vertexes from the incoming edges . It avoids to unmarshall edges . |
17,541 | public static void unlink ( final ODatabaseGraphTx iDatabase , final ODocument iSourceVertex , final ODocument iTargetVertex ) { if ( iTargetVertex == null ) throw new IllegalArgumentException ( "Missed the target vertex" ) ; if ( iDatabase . existsUserObjectByRID ( iSourceVertex . getIdentity ( ) ) ) { final OGraphVertex vertex = ( OGraphVertex ) iDatabase . getUserObjectByRecord ( iSourceVertex , null ) ; if ( vertex . out != null ) { final Set < OGraphEdge > obj = vertex . out . get ( ) ; if ( obj != null ) for ( OGraphEdge e : obj ) if ( e . getIn ( ) . getDocument ( ) . equals ( iTargetVertex ) ) obj . remove ( e ) ; } } if ( iDatabase . existsUserObjectByRID ( iTargetVertex . getIdentity ( ) ) ) { final OGraphVertex vertex = ( OGraphVertex ) iDatabase . getUserObjectByRecord ( iTargetVertex , null ) ; if ( vertex . in != null ) { final Set < OGraphEdge > obj = vertex . in . get ( ) ; if ( obj != null ) for ( OGraphEdge e : obj ) if ( e . getOut ( ) . getDocument ( ) . equals ( iSourceVertex ) ) obj . remove ( e ) ; } } final List < ODocument > edges2Remove = new ArrayList < ODocument > ( ) ; ODocument edge = null ; Set < ODocument > docs = iSourceVertex . field ( OGraphDatabase . VERTEX_FIELD_OUT ) ; if ( docs != null ) { for ( OIdentifiable d : docs ) { final ODocument doc = ( ODocument ) d . getRecord ( ) ; if ( doc . field ( OGraphDatabase . EDGE_FIELD_IN ) . equals ( iTargetVertex ) ) { edges2Remove . add ( doc ) ; edge = doc ; } } for ( ODocument d : edges2Remove ) docs . remove ( d ) ; } if ( edge == null ) throw new OGraphException ( "Edge not found between the ougoing edges" ) ; iSourceVertex . setDirty ( ) ; iSourceVertex . save ( ) ; docs = iTargetVertex . field ( OGraphDatabase . VERTEX_FIELD_IN ) ; if ( docs != null ) { edges2Remove . clear ( ) ; for ( OIdentifiable d : docs ) { final ODocument doc = ( ODocument ) d . getRecord ( ) ; if ( doc . field ( OGraphDatabase . EDGE_FIELD_IN ) . equals ( iTargetVertex ) ) edges2Remove . add ( doc ) ; } for ( ODocument d : edges2Remove ) docs . remove ( d ) ; } iTargetVertex . setDirty ( ) ; iTargetVertex . save ( ) ; edge . delete ( ) ; } | Unlinks all the edges between iSourceVertex and iTargetVertex |
17,542 | public SyncCollection limitNumberOfResults ( int limit ) { if ( limit > 0 ) { addLimit ( WebDavSearch . NRESULTS , limit ) ; } else { removeLimit ( WebDavSearch . NRESULTS ) ; } return this ; } | Limit the number of results in the response if supported by the server . A non - positive value will remove the limit . |
17,543 | public int getNumberOfResultsLimit ( ) { if ( mLimit == null ) { return 0 ; } Integer limit = ( Integer ) mLimit . get ( WebDavSearch . NRESULTS ) ; return limit == null ? 0 : limit ; } | Returns the limit for the number of results in this request . |
17,544 | private < T > void addLimit ( ElementDescriptor < T > descriptor , T limit ) { if ( mLimit == null ) { mLimit = new HashMap < ElementDescriptor < ? > , Object > ( 6 ) ; } mLimit . put ( descriptor , limit ) ; } | Add a limit to the request . |
17,545 | public void put ( K k , V v ) { cache . put ( k , v ) ; acquireLock ( k ) . countDown ( ) ; } | Caches the given mapping and releases all waiting locks . |
17,546 | public V get ( K k ) throws InterruptedException { await ( k ) ; return cache . get ( k ) ; } | Retrieve the value associated with the given key blocking as long as necessary . |
17,547 | public V get ( K k , long timeout , TimeUnit unit ) throws InterruptedException , TimeoutException { await ( k , timeout , unit ) ; return cache . get ( k ) ; } | Retrieve the value associated with the given key blocking as long as necessary up to the specified maximum . |
17,548 | public void await ( K k , long timeout , TimeUnit unit ) throws InterruptedException , TimeoutException { if ( ! acquireLock ( k ) . await ( timeout , unit ) ) { throw new TimeoutException ( "Wait time for retrieving value for key " + k + " exceeded " + timeout + " " + unit ) ; } } | Waits until the key has been assigned a value up to the specified maximum . |
17,549 | public static void initEndpointDirectories ( MuleContext muleContext , String [ ] serviceNames , String [ ] endpointNames ) throws Exception { List < Lifecycle > services = new ArrayList < Lifecycle > ( ) ; for ( String serviceName : serviceNames ) { try { Lifecycle service = muleContext . getRegistry ( ) . lookupObject ( serviceName ) ; services . add ( service ) ; } catch ( Exception e ) { logger . error ( "Error '" + e . getMessage ( ) + "' occured while stopping the service " + serviceName + ". Perhaps the service did not exist in the config?" ) ; throw e ; } } for ( String endpointName : endpointNames ) { initEndpointDirectory ( muleContext , endpointName ) ; } for ( @ SuppressWarnings ( "unused" ) Lifecycle service : services ) { } } | Initiates a list of sftp - endpoint - directories . Ensures that affected services are stopped during the initiation . |
17,550 | static protected SftpClient getSftpClient ( MuleContext muleContext , String endpointName ) throws IOException { ImmutableEndpoint endpoint = getImmutableEndpoint ( muleContext , endpointName ) ; try { SftpClient sftpClient = SftpConnectionFactory . createClient ( endpoint ) ; return sftpClient ; } catch ( Exception e ) { throw new RuntimeException ( "Login failed" , e ) ; } } | Returns a SftpClient that is logged in to the sftp server that the endpoint is configured against . |
17,551 | static protected void recursiveDelete ( MuleContext muleContext , SftpClient sftpClient , String endpointName , String relativePath ) throws IOException { EndpointURI endpointURI = getImmutableEndpoint ( muleContext , endpointName ) . getEndpointURI ( ) ; String path = endpointURI . getPath ( ) + relativePath ; try { sftpClient . chmod ( path , 00700 ) ; sftpClient . changeWorkingDirectory ( sftpClient . getAbsolutePath ( path ) ) ; String [ ] directories = sftpClient . listDirectories ( ) ; for ( String directory : directories ) { recursiveDelete ( muleContext , sftpClient , endpointName , relativePath + "/" + directory ) ; } sftpClient . changeWorkingDirectory ( sftpClient . getAbsolutePath ( path ) ) ; String [ ] files = sftpClient . listFiles ( ) ; for ( String file : files ) { sftpClient . deleteFile ( file ) ; } try { sftpClient . deleteDirectory ( path ) ; } catch ( Exception e ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Failed delete directory " + path , e ) ; } } catch ( Exception e ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Failed to recursivly delete directory " + path , e ) ; } } | Deletes a directory with all its files and sub - directories . The reason it do a chmod 700 before the delete is that some tests changes the permission and thus we have to restore the right to delete it ... |
17,552 | public OMVRBTreeEntryPersistent < K , V > save ( ) throws OSerializationException { if ( ! dataProvider . isEntryDirty ( ) ) return this ; final boolean isNew = dataProvider . getIdentity ( ) . isNew ( ) ; if ( left != null && left . dataProvider . getIdentity ( ) . isNew ( ) ) { if ( isNew ) { left . dataProvider . save ( ) ; } else left . save ( ) ; } if ( right != null && right . dataProvider . getIdentity ( ) . isNew ( ) ) { if ( isNew ) { right . dataProvider . save ( ) ; } else right . save ( ) ; } if ( parent != null && parent . dataProvider . getIdentity ( ) . isNew ( ) ) { if ( isNew ) { parent . dataProvider . save ( ) ; } else parent . save ( ) ; } dataProvider . save ( ) ; checkEntryStructure ( ) ; if ( pTree . searchNodeInCache ( dataProvider . getIdentity ( ) ) != this ) { pTree . addNodeInMemory ( this ) ; } return this ; } | Assures that all the links versus parent left and right are consistent . |
17,553 | public OMVRBTreeEntryPersistent < K , V > delete ( ) throws IOException { if ( dataProvider != null ) { pTree . removeNodeFromMemory ( this ) ; pTree . removeEntry ( dataProvider . getIdentity ( ) ) ; if ( getLeft ( ) != null ) ( ( OMVRBTreeEntryPersistent < K , V > ) getLeft ( ) ) . delete ( ) ; if ( getRight ( ) != null ) ( ( OMVRBTreeEntryPersistent < K , V > ) getRight ( ) ) . delete ( ) ; dataProvider . removeIdentityChangedListener ( this ) ; dataProvider . delete ( ) ; clear ( ) ; } return this ; } | Delete all the nodes recursively . IF they are not loaded in memory load all the tree . |
17,554 | protected int disconnect ( final boolean iForceDirty , final int iLevel ) { if ( dataProvider == null ) return 1 ; int totalDisconnected = 0 ; final ORID rid = dataProvider . getIdentity ( ) ; boolean disconnectedFromParent = false ; if ( parent != null ) { if ( canDisconnectFrom ( parent ) || iForceDirty ) { if ( parent . left == this ) { parent . left = null ; } else if ( parent . right == this ) { parent . right = null ; } else OLogManager . instance ( ) . warn ( this , "Node " + rid + " has the parent (" + parent + ") unlinked to itself. It links to " + parent ) ; totalDisconnected += parent . disconnect ( iForceDirty , iLevel + 1 ) ; parent = null ; disconnectedFromParent = true ; } } else { disconnectedFromParent = true ; } boolean disconnectedFromLeft = false ; if ( left != null ) { if ( canDisconnectFrom ( left ) || iForceDirty ) { if ( left . parent == this ) left . parent = null ; else OLogManager . instance ( ) . warn ( this , "Node " + rid + " has the left (" + left + ") unlinked to itself. It links to " + left . parent ) ; totalDisconnected += left . disconnect ( iForceDirty , iLevel + 1 ) ; left = null ; disconnectedFromLeft = true ; } } else { disconnectedFromLeft = true ; } boolean disconnectedFromRight = false ; if ( right != null ) { if ( canDisconnectFrom ( right ) || iForceDirty ) { if ( right . parent == this ) right . parent = null ; else OLogManager . instance ( ) . warn ( this , "Node " + rid + " has the right (" + right + ") unlinked to itself. It links to " + right . parent ) ; totalDisconnected += right . disconnect ( iForceDirty , iLevel + 1 ) ; right = null ; disconnectedFromRight = true ; } } else { disconnectedFromLeft = true ; } if ( disconnectedFromParent && disconnectedFromLeft && disconnectedFromRight ) if ( ( ! dataProvider . isEntryDirty ( ) && ! dataProvider . getIdentity ( ) . isTemporary ( ) || iForceDirty ) && ! pTree . isNodeEntryPoint ( this ) ) { totalDisconnected ++ ; pTree . removeNodeFromMemory ( this ) ; clear ( ) ; } return totalDisconnected ; } | Disconnect the current node from others . |
17,555 | public V setValue ( final V iValue ) { V oldValue = getValue ( ) ; int index = tree . getPageIndex ( ) ; if ( dataProvider . setValueAt ( index , iValue ) ) markDirty ( ) ; return oldValue ; } | Invalidate serialized Value associated in order to be re - marshalled on the next node storing . |
17,556 | public static OIdentifiable readIdentifiable ( final OChannelBinaryClient network ) throws IOException { final int classId = network . readShort ( ) ; if ( classId == RECORD_NULL ) return null ; if ( classId == RECORD_RID ) { return network . readRID ( ) ; } else { final ORecordInternal < ? > record = Orient . instance ( ) . getRecordFactoryManager ( ) . newInstance ( network . readByte ( ) ) ; if ( record instanceof ORecordSchemaAware < ? > ) ( ( ORecordSchemaAware < ? > ) record ) . fill ( network . readRID ( ) , network . readInt ( ) , network . readBytes ( ) , false ) ; else record . fill ( network . readRID ( ) , network . readInt ( ) , network . readBytes ( ) , false ) ; return record ; } } | SENT AS SHORT AS FIRST PACKET AFTER SOCKET CONNECTION |
17,557 | public static Map < Identity , JsonNode > getDocumentIdMap ( List < JsonNode > list , List < String > identityFields ) { Map < Identity , JsonNode > map = new HashMap < > ( ) ; if ( list != null ) { LOGGER . debug ( "Getting doc IDs for {} docs, fields={}" , list . size ( ) , identityFields ) ; for ( JsonNode node : list ) { Identity id = new Identity ( node , identityFields ) ; LOGGER . debug ( "ID={}" , id ) ; map . put ( id , node ) ; } } return map ; } | Build an id - doc map from a list of docs |
17,558 | public static boolean fastCompareDocs ( JsonNode sourceDocument , JsonNode destinationDocument , List < String > exclusionPaths , boolean ignoreTimestampMSDiffs ) { try { JsonDiff diff = new JsonDiff ( ) ; diff . setOption ( JsonDiff . Option . ARRAY_ORDER_INSIGNIFICANT ) ; diff . setOption ( JsonDiff . Option . RETURN_LEAVES_ONLY ) ; diff . setFilter ( new AbstractFieldFilter ( ) { public boolean includeField ( List < String > fieldName ) { return ! fieldName . get ( fieldName . size ( ) - 1 ) . endsWith ( "#" ) ; } } ) ; List < JsonDelta > list = diff . computeDiff ( sourceDocument , destinationDocument ) ; for ( JsonDelta x : list ) { String field = x . getField ( ) ; if ( ! isExcluded ( exclusionPaths , field ) ) { if ( reallyDifferent ( x . getNode1 ( ) , x . getNode2 ( ) , ignoreTimestampMSDiffs ) ) { return true ; } } } } catch ( Exception e ) { LOGGER . error ( "Cannot compare docs:{}" , e , e ) ; } return false ; } | Compare two docs fast if they are the same excluding exclusions |
17,559 | public synchronized void createHole ( final long iRecordOffset , final int iRecordSize ) throws IOException { final long timer = OProfiler . getInstance ( ) . startChrono ( ) ; final int recycledPosition ; final ODataHoleInfo hole ; if ( ! freeHoles . isEmpty ( ) ) { recycledPosition = freeHoles . remove ( 0 ) ; hole = availableHolesList . get ( recycledPosition ) ; hole . dataOffset = iRecordOffset ; hole . size = iRecordSize ; } else { recycledPosition = getHoles ( ) ; hole = new ODataHoleInfo ( iRecordSize , iRecordOffset , recycledPosition ) ; availableHolesList . add ( hole ) ; file . allocateSpace ( RECORD_SIZE ) ; } availableHolesBySize . put ( hole , hole ) ; availableHolesByPosition . put ( hole , hole ) ; if ( maxHoleSize < iRecordSize ) maxHoleSize = iRecordSize ; final long p = recycledPosition * RECORD_SIZE ; file . writeLong ( p , iRecordOffset ) ; file . writeInt ( p + OBinaryProtocol . SIZE_LONG , iRecordSize ) ; OProfiler . getInstance ( ) . stopChrono ( PROFILER_DATA_HOLE_CREATE , timer ) ; } | Appends the hole to the end of the segment . |
17,560 | public synchronized ODataHoleInfo getHole ( final int iPosition ) { final ODataHoleInfo hole = availableHolesList . get ( iPosition ) ; if ( hole . dataOffset == - 1 ) return null ; return hole ; } | Fills the holes information into OPhysicalPosition object given as parameter . |
17,561 | public synchronized void updateHole ( final ODataHoleInfo iHole , final long iNewDataOffset , final int iNewRecordSize ) throws IOException { final long timer = OProfiler . getInstance ( ) . startChrono ( ) ; final boolean offsetChanged = iNewDataOffset != iHole . dataOffset ; final boolean sizeChanged = iNewRecordSize != iHole . size ; if ( maxHoleSize < iNewRecordSize ) maxHoleSize = iNewRecordSize ; if ( offsetChanged ) availableHolesByPosition . remove ( iHole ) ; if ( sizeChanged ) availableHolesBySize . remove ( iHole ) ; if ( offsetChanged ) iHole . dataOffset = iNewDataOffset ; if ( sizeChanged ) iHole . size = iNewRecordSize ; if ( offsetChanged ) availableHolesByPosition . put ( iHole , iHole ) ; if ( sizeChanged ) availableHolesBySize . put ( iHole , iHole ) ; final long holePosition = iHole . holeOffset * RECORD_SIZE ; if ( offsetChanged ) file . writeLong ( holePosition , iNewDataOffset ) ; if ( sizeChanged ) file . writeInt ( holePosition + OBinaryProtocol . SIZE_LONG , iNewRecordSize ) ; OProfiler . getInstance ( ) . stopChrono ( PROFILER_DATA_HOLE_UPDATE , timer ) ; } | Update hole data |
17,562 | public synchronized void deleteHole ( int iHolePosition ) throws IOException { final ODataHoleInfo hole = availableHolesList . get ( iHolePosition ) ; availableHolesBySize . remove ( hole ) ; availableHolesByPosition . remove ( hole ) ; hole . dataOffset = - 1 ; freeHoles . add ( iHolePosition ) ; iHolePosition = iHolePosition * RECORD_SIZE ; file . writeLong ( iHolePosition , - 1 ) ; } | Delete the hole |
17,563 | protected T getObject ( ) { final T object ; if ( reusedObject != null ) { object = reusedObject ; object . reset ( ) ; } else object = ( T ) database . newInstance ( className ) ; return object ; } | Returns the object to use for the operation . |
17,564 | @ SneakyThrows ( IOException . class ) public static String sha1 ( String input ) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest . getInstance ( "SHA1" ) ; byte [ ] result = mDigest . digest ( input . getBytes ( "UTF-8" ) ) ; String resultString = String . format ( "%040x" , new BigInteger ( 1 , result ) ) ; return resultString ; } | Calculates the SHA1 Digest of a given input . |
17,565 | public void saveRecord ( final ORecordInternal < ? > iRecord , final String iClusterName , final OPERATION_MODE iMode , final ORecordCallback < ? extends Number > iCallback ) { try { database . executeSaveRecord ( iRecord , iClusterName , iRecord . getVersion ( ) , iRecord . getRecordType ( ) , true , iMode , iCallback ) ; } catch ( Exception e ) { final ORecordId rid = ( ORecordId ) iRecord . getIdentity ( ) ; if ( rid . isValid ( ) ) database . getLevel1Cache ( ) . freeRecord ( rid ) ; if ( e instanceof RuntimeException ) throw ( RuntimeException ) e ; throw new OException ( e ) ; } } | Update the record . |
17,566 | public void deleteRecord ( final ORecordInternal < ? > iRecord , final OPERATION_MODE iMode ) { if ( ! iRecord . getIdentity ( ) . isPersistent ( ) ) return ; try { database . executeDeleteRecord ( iRecord , iRecord . getVersion ( ) , true , true , iMode ) ; } catch ( Exception e ) { final ORecordId rid = ( ORecordId ) iRecord . getIdentity ( ) ; if ( rid . isValid ( ) ) database . getLevel1Cache ( ) . freeRecord ( rid ) ; if ( e instanceof RuntimeException ) throw ( RuntimeException ) e ; throw new OException ( e ) ; } } | Deletes the record . |
17,567 | @ SuppressWarnings ( "unchecked" ) public < RET > RET execute ( final Object ... iArgs ) { setParameters ( iArgs ) ; return ( RET ) ODatabaseRecordThreadLocal . INSTANCE . get ( ) . getStorage ( ) . command ( this ) ; } | Delegates the execution to the configured command executor . |
17,568 | public Collection < ODocument > getEntriesBetween ( final Object iRangeFrom , final Object iRangeTo ) { return getEntriesBetween ( iRangeFrom , iRangeTo , true ) ; } | Returns a set of documents with key between the range passed as parameter . Range bounds are included . |
17,569 | public long rebuild ( final OProgressListener iProgressListener ) { long documentIndexed = 0 ; final boolean intentInstalled = getDatabase ( ) . declareIntent ( new OIntentMassiveInsert ( ) ) ; acquireExclusiveLock ( ) ; try { try { map . clear ( ) ; } catch ( Exception e ) { } int documentNum = 0 ; long documentTotal = 0 ; for ( final String cluster : clustersToIndex ) documentTotal += getDatabase ( ) . countClusterElements ( cluster ) ; if ( iProgressListener != null ) iProgressListener . onBegin ( this , documentTotal ) ; for ( final String clusterName : clustersToIndex ) try { for ( final ORecord < ? > record : getDatabase ( ) . browseCluster ( clusterName ) ) { if ( record instanceof ODocument ) { final ODocument doc = ( ODocument ) record ; if ( indexDefinition == null ) throw new OConfigurationException ( "Index '" + name + "' cannot be rebuilt because has no a valid definition (" + indexDefinition + ")" ) ; final Object fieldValue = indexDefinition . getDocumentValueToIndex ( doc ) ; if ( fieldValue != null ) { if ( fieldValue instanceof Collection ) { for ( final Object fieldValueItem : ( Collection < ? > ) fieldValue ) { put ( fieldValueItem , doc ) ; } } else put ( fieldValue , doc ) ; ++ documentIndexed ; } } documentNum ++ ; if ( iProgressListener != null ) iProgressListener . onProgress ( this , documentNum , documentNum * 100f / documentTotal ) ; } } catch ( NoSuchElementException e ) { } lazySave ( ) ; if ( iProgressListener != null ) iProgressListener . onCompletition ( this , true ) ; } catch ( final Exception e ) { if ( iProgressListener != null ) iProgressListener . onCompletition ( this , false ) ; try { map . clear ( ) ; } catch ( Exception e2 ) { } throw new OIndexException ( "Error on rebuilding the index for clusters: " + clustersToIndex , e ) ; } finally { if ( intentInstalled ) getDatabase ( ) . declareIntent ( null ) ; releaseExclusiveLock ( ) ; } return documentIndexed ; } | Populates the index with all the existent records . Uses the massive insert intent to speed up and keep the consumed memory low . |
17,570 | public boolean isConnected ( ) { if ( socket != null && socket . isConnected ( ) && ! socket . isInputShutdown ( ) && ! socket . isOutputShutdown ( ) ) return true ; return false ; } | Tells if the channel is connected . |
17,571 | public void detach ( Object self ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { for ( String fieldName : doc . fieldNames ( ) ) { Object value = getValue ( self , fieldName , false , null ) ; if ( value instanceof OLazyObjectMultivalueElement ) ( ( OLazyObjectMultivalueElement ) value ) . detach ( ) ; OObjectEntitySerializer . setFieldValue ( getField ( fieldName , self . getClass ( ) ) , self , value ) ; } OObjectEntitySerializer . setIdField ( self . getClass ( ) , self , doc . getIdentity ( ) ) ; OObjectEntitySerializer . setVersionField ( self . getClass ( ) , self , doc . getVersion ( ) ) ; } | Method that detaches all fields contained in the document to the given object |
17,572 | public void attach ( Object self ) throws IllegalArgumentException , IllegalAccessException , NoSuchMethodException , InvocationTargetException { for ( Class < ? > currentClass = self . getClass ( ) ; currentClass != Object . class ; ) { if ( Proxy . class . isAssignableFrom ( currentClass ) ) { currentClass = currentClass . getSuperclass ( ) ; continue ; } for ( Field f : currentClass . getDeclaredFields ( ) ) { Object value = OObjectEntitySerializer . getFieldValue ( f , self ) ; value = setValue ( self , f . getName ( ) , value ) ; OObjectEntitySerializer . setFieldValue ( f , self , value ) ; } currentClass = currentClass . getSuperclass ( ) ; if ( currentClass == null || currentClass . equals ( ODocument . class ) ) currentClass = Object . class ; } } | Method that attaches all data contained in the object to the associated document |
17,573 | private void ensureRespondJsScriptElement ( ) { if ( this . respondJsScript == null ) { this . respondJsScript = Document . get ( ) . createScriptElement ( ) ; this . respondJsScript . setSrc ( GWT . getModuleBaseForStaticFiles ( ) + DefaultIE8ThemeController . RESPOND_JS_LOCATION ) ; this . respondJsScript . setType ( "text/javascript" ) ; } } | Ensure respond js script element . |
17,574 | public static MessageDispatcherServlet createMessageDispatcherServlet ( Class ... contextConfigLocation ) { StringBuilder items = new StringBuilder ( ) ; for ( Class aClass : contextConfigLocation ) { items . append ( aClass . getName ( ) ) ; items . append ( "," ) ; } MessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet ( ) ; messageDispatcherServlet . setContextClass ( AnnotationConfigWebApplicationContext . class ) ; messageDispatcherServlet . setContextConfigLocation ( removeEnd ( items . toString ( ) , "," ) ) ; messageDispatcherServlet . setTransformWsdlLocations ( true ) ; return messageDispatcherServlet ; } | Creates a spring - ws message dispatcher servlet |
17,575 | static Integer getReceivedStations ( AisExtractor extractor , int slotTimeout , int startIndex ) { if ( slotTimeout == 3 || slotTimeout == 5 || slotTimeout == 7 ) return extractor . getValue ( startIndex + 5 , startIndex + 19 ) ; else return null ; } | Returns received stations as per 1371 - 4 . pdf . |
17,576 | private static Integer getHourUtc ( AisExtractor extractor , int slotTimeout , int startIndex ) { if ( slotTimeout == 1 ) { int hours = extractor . getValue ( startIndex + 5 , startIndex + 10 ) ; return hours ; } else return null ; } | Returns hour UTC as per 1371 - 4 . pdf . |
17,577 | private static Integer getMinuteUtc ( AisExtractor extractor , int slotTimeout , int startIndex ) { if ( slotTimeout == 1 ) { int minutes = extractor . getValue ( startIndex + 10 , startIndex + 17 ) ; return minutes ; } else return null ; } | Returns minute UTC as per 1371 - 4 . pdf . |
17,578 | private static Integer getSlotOffset ( AisExtractor extractor , int slotTimeout , int startIndex ) { if ( slotTimeout == 0 ) return extractor . getValue ( startIndex + 5 , startIndex + 19 ) ; else return null ; } | Returns slot offset as per 1371 - 4 . pdf . |
17,579 | public synchronized int getValue ( int from , int to ) { try { SixBit . convertSixBitToBits ( message , padBits , bitSet , calculated , from , to ) ; return ( int ) SixBit . getValue ( from , to , bitSet ) ; } catch ( SixBitException | ArrayIndexOutOfBoundsException e ) { throw new AisParseException ( e ) ; } } | Returns an unsigned integer value using the bits from character position start to position stop in the decoded message . |
17,580 | public synchronized int getSignedValue ( int from , int to ) { try { SixBit . convertSixBitToBits ( message , padBits , bitSet , calculated , from , to ) ; return ( int ) SixBit . getSignedValue ( from , to , bitSet ) ; } catch ( SixBitException e ) { throw new AisParseException ( e ) ; } } | Returns a signed integer value using the bits from character position start to position stop in the decoded message . |
17,581 | public static Object getField ( Object obj , String name ) { try { Class < ? extends Object > klass = obj . getClass ( ) ; do { try { Field field = klass . getDeclaredField ( name ) ; field . setAccessible ( true ) ; return field . get ( obj ) ; } catch ( NoSuchFieldException e ) { klass = klass . getSuperclass ( ) ; } } while ( klass != null ) ; throw new RuntimeException ( ) ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } | Gets a field from an object . |
17,582 | public final double getDistanceToKm ( Position position ) { double lat1 = toRadians ( lat ) ; double lat2 = toRadians ( position . lat ) ; double lon1 = toRadians ( lon ) ; double lon2 = toRadians ( position . lon ) ; double deltaLon = lon2 - lon1 ; double cosLat2 = cos ( lat2 ) ; double cosLat1 = cos ( lat1 ) ; double sinLat1 = sin ( lat1 ) ; double sinLat2 = sin ( lat2 ) ; double cosDeltaLon = cos ( deltaLon ) ; double top = sqrt ( sqr ( cosLat2 * sin ( deltaLon ) ) + sqr ( cosLat1 * sinLat2 - sinLat1 * cosLat2 * cosDeltaLon ) ) ; double bottom = sinLat1 * sinLat2 + cosLat1 * cosLat2 * cosDeltaLon ; double distance = radiusEarthKm * atan2 ( top , bottom ) ; return abs ( distance ) ; } | returns distance between two WGS84 positions according to Vincenty s formula from Wikipedia |
17,583 | public final double getDistanceKmToPath ( Position p1 , Position p2 ) { double d = radiusEarthKm * asin ( sin ( getDistanceToKm ( p1 ) / radiusEarthKm ) * sin ( toRadians ( getBearingDegrees ( p1 ) - p1 . getBearingDegrees ( p2 ) ) ) ) ; return abs ( d ) ; } | calculates the distance of a point to the great circle path between p1 and p2 . |
17,584 | @ SuppressWarnings ( "unchecked" ) public static void setModelClass ( Class < ? > modelClass ) throws IllegalArgumentException { if ( ! DefaultModelImpl . class . isAssignableFrom ( modelClass ) ) { throw new IllegalArgumentException ( "Modelclass, " + modelClass . getName ( ) + ", is not a subtype of " + DefaultModelImpl . class . getName ( ) ) ; } ModelFactory . modelClass = ( Class < DefaultModelImpl > ) modelClass ; } | Register a custom model class must be a subclass to DefaultModelImpl . |
17,585 | public static void resetModelClass ( ) { ModelFactory . modelClass = DefaultModelImpl . class ; System . err . println ( "[INFO] Reset model-class: " + ModelFactory . modelClass . getName ( ) ) ; } | Reset model class to the default class . |
17,586 | public static IModel newModel ( String groupId , String artifactId , String version , String service , MuleVersionEnum muleVersion , TransportEnum inboundTransport , TransportEnum outboundTransport , TransformerEnum transformerType ) { return doCreateNewModel ( groupId , artifactId , version , service , muleVersion , null , null , inboundTransport , outboundTransport , transformerType , null , null ) ; } | Constructor - method to use when services with inbound and outbound services |
17,587 | public static void lockMemory ( boolean useSystemJNADisabled ) { if ( useSystemJNADisabled ) disableUsingSystemJNA ( ) ; try { int errorCode = MemoryLockerLinux . INSTANCE . mlockall ( MemoryLockerLinux . LOCK_CURRENT_MEMORY ) ; if ( errorCode != 0 ) { final String errorMessage ; int lastError = Native . getLastError ( ) ; switch ( lastError ) { case MemoryLockerLinux . EPERM : errorMessage = "The calling process does not have the appropriate privilege to perform the requested operation(EPERM)." ; break ; case MemoryLockerLinux . EAGAIN : errorMessage = "Some or all of the memory identified by the operation could not be locked when the call was made(EAGAIN)." ; break ; case MemoryLockerLinux . ENOMEM : errorMessage = "Unable to lock JVM memory. This can result in part of the JVM being swapped out, especially if mmapping of files enabled. Increase RLIMIT_MEMLOCK or run OrientDB server as root(ENOMEM)." ; break ; case MemoryLockerLinux . EINVAL : errorMessage = "The flags argument is zero, or includes unimplemented flags(EINVAL)." ; break ; case MemoryLockerLinux . ENOSYS : errorMessage = "The implementation does not support this memory locking interface(ENOSYS)." ; break ; default : errorMessage = "Unexpected exception with code " + lastError + "." ; break ; } OLogManager . instance ( ) . error ( null , "[MemoryLocker.lockMemory] Error occurred while locking memory: %s" , errorMessage ) ; } else { OLogManager . instance ( ) . info ( null , "[MemoryLocker.lockMemory] Memory locked successfully!" ) ; } } catch ( UnsatisfiedLinkError e ) { OLogManager . instance ( ) . config ( null , "[MemoryLocker.lockMemory] Cannot lock virtual memory. It seems that you OS (%s) doesn't support this feature" , System . getProperty ( "os.name" ) ) ; } } | This method locks memory to prevent swapping . This method provide information about success or problems with locking memory . You can reed console output to know if memory locked successfully or not . If system error occurred such as permission any specific exception will be thrown . |
17,588 | public OMVRBTreeEntry < K , V > getFirstInMemory ( ) { OMVRBTreeEntry < K , V > node = this ; OMVRBTreeEntry < K , V > prev = this ; while ( node != null ) { prev = node ; node = node . getPreviousInMemory ( ) ; } return prev ; } | Returns the first Entry only by traversing the memory or null if no such . |
17,589 | public OMVRBTreeEntry < K , V > getPreviousInMemory ( ) { OMVRBTreeEntry < K , V > t = this ; OMVRBTreeEntry < K , V > p = null ; if ( t . getLeftInMemory ( ) != null ) { p = t . getLeftInMemory ( ) ; while ( p . getRightInMemory ( ) != null ) p = p . getRightInMemory ( ) ; } else { p = t . getParentInMemory ( ) ; while ( p != null && t == p . getLeftInMemory ( ) ) { t = p ; p = p . getParentInMemory ( ) ; } } return p ; } | Returns the previous of the current Entry only by traversing the memory or null if no such . |
17,590 | private V linearSearch ( final K iKey ) { V value = null ; int i = 0 ; tree . pageItemComparator = - 1 ; for ( int s = getSize ( ) ; i < s ; ++ i ) { if ( tree . comparator != null ) tree . pageItemComparator = tree . comparator . compare ( getKeyAt ( i ) , iKey ) ; else tree . pageItemComparator = ( ( Comparable < ? super K > ) getKeyAt ( i ) ) . compareTo ( iKey ) ; if ( tree . pageItemComparator == 0 ) { tree . pageItemFound = true ; value = getValueAt ( i ) ; break ; } else if ( tree . pageItemComparator > 0 ) break ; } tree . pageIndex = i ; return value ; } | Linear search inside the node |
17,591 | private V binarySearch ( final K iKey ) { int low = 0 ; int high = getSize ( ) - 1 ; int mid = 0 ; while ( low <= high ) { mid = ( low + high ) >>> 1 ; Object midVal = getKeyAt ( mid ) ; if ( tree . comparator != null ) tree . pageItemComparator = tree . comparator . compare ( ( K ) midVal , iKey ) ; else tree . pageItemComparator = ( ( Comparable < ? super K > ) midVal ) . compareTo ( iKey ) ; if ( tree . pageItemComparator == 0 ) { tree . pageItemFound = true ; tree . pageIndex = mid ; return getValueAt ( tree . pageIndex ) ; } if ( low == high ) break ; if ( tree . pageItemComparator < 0 ) low = mid + 1 ; else high = mid ; } tree . pageIndex = mid ; return null ; } | Binary search inside the node |
17,592 | public int compareTo ( final OMVRBTreeEntry < K , V > o ) { if ( o == null ) return 1 ; if ( o == this ) return 0 ; if ( getSize ( ) == 0 ) return - 1 ; if ( o . getSize ( ) == 0 ) return 1 ; if ( tree . comparator != null ) return tree . comparator . compare ( getFirstKey ( ) , o . getFirstKey ( ) ) ; return ( ( Comparable < K > ) getFirstKey ( ) ) . compareTo ( o . getFirstKey ( ) ) ; } | Compares two nodes by their first keys . |
17,593 | public static long parsePeriod ( String periodStr ) { PeriodFormatter fmt = PeriodFormat . getDefault ( ) ; Period p = fmt . parsePeriod ( periodStr ) ; return p . toStandardDuration ( ) . getMillis ( ) ; } | Returns the period in msecs |
17,594 | public Date getEndDate ( Date startDate , long period ) { long now = getNow ( ) . getTime ( ) ; long endDate = startDate . getTime ( ) + period ; if ( now - period > endDate ) { return new Date ( endDate ) ; } else { return null ; } } | Returns the end date given the start date end the period . The end date is startDate + period but only if endDate is at least one period ago . That is we always leave the last incomplete period unprocessed . |
17,595 | protected List < MigrationJob > createJobs ( Date startDate , Date endDate , ActiveExecution ae ) throws Exception { List < MigrationJob > ret = new ArrayList < MigrationJob > ( ) ; LOGGER . debug ( "Creating the migrator to setup new jobs" ) ; MigrationJob mj = new MigrationJob ( ) ; mj . setConfigurationName ( getMigrationConfiguration ( ) . getConfigurationName ( ) ) ; mj . setScheduledDate ( getNow ( ) ) ; mj . setGenerated ( true ) ; mj . setStatus ( MigrationJob . STATE_AVAILABLE ) ; mj . setConsistencyChecker ( new MigrationJob . ConsistencyChecker ( ) ) ; mj . getConsistencyChecker ( ) . setJobRangeBegin ( ClientConstants . getDateFormat ( ) . format ( startDate ) ) ; mj . getConsistencyChecker ( ) . setJobRangeEnd ( ClientConstants . getDateFormat ( ) . format ( endDate ) ) ; mj . getConsistencyChecker ( ) . setConfigurationName ( mj . getConfigurationName ( ) ) ; Migrator migrator = createMigrator ( mj , ae ) ; mj . setQuery ( migrator . createRangeQuery ( startDate , endDate ) ) ; LOGGER . debug ( "Migration job query:{}" , mj . getQuery ( ) ) ; ret . add ( mj ) ; return ret ; } | Create a migration job or jobs to process records created between the given dates . startDate is inclusive end date is exclusive |
17,596 | private OMMapBufferEntry [ ] searchAmongExisting ( OFileMMap file , final OMMapBufferEntry [ ] fileEntries , final long beginOffset , final int size ) { if ( fileEntries . length == 0 ) { return EMPTY_BUFFER_ENTRIES ; } final OMMapBufferEntry lastEntry = fileEntries [ fileEntries . length - 1 ] ; if ( lastEntry . beginOffset + lastEntry . size <= beginOffset ) { return EMPTY_BUFFER_ENTRIES ; } final LastMMapEntrySearchInfo entrySearchInfo = mapEntrySearchInfo . get ( file ) ; final int beginSearchPosition ; final int endSearchPosition ; if ( entrySearchInfo == null ) { beginSearchPosition = 0 ; endSearchPosition = fileEntries . length - 1 ; } else { if ( entrySearchInfo . requestedPosition <= beginOffset ) { beginSearchPosition = entrySearchInfo . foundMmapIndex ; endSearchPosition = fileEntries . length - 1 ; } else { beginSearchPosition = 0 ; endSearchPosition = entrySearchInfo . foundMmapIndex ; } } final int resultFirstPosition ; if ( endSearchPosition - beginSearchPosition > BINARY_SEARCH_THRESHOLD ) resultFirstPosition = binarySearch ( fileEntries , beginOffset , beginSearchPosition , endSearchPosition ) ; else resultFirstPosition = linearSearch ( fileEntries , beginOffset , beginSearchPosition , endSearchPosition ) ; if ( beginSearchPosition < 0 ) return EMPTY_BUFFER_ENTRIES ; int resultLastPosition = fileEntries . length - 1 ; for ( int i = resultFirstPosition ; i <= resultLastPosition ; i ++ ) { final OMMapBufferEntry entry = fileEntries [ i ] ; if ( entry . beginOffset + entry . size >= beginOffset + size ) { resultLastPosition = i ; break ; } } final int length = resultLastPosition - resultFirstPosition + 1 ; final OMMapBufferEntry [ ] foundEntries = new OMMapBufferEntry [ length ] ; if ( length > 0 ) { System . arraycopy ( fileEntries , resultFirstPosition , foundEntries , 0 , length ) ; mapEntrySearchInfo . put ( file , new LastMMapEntrySearchInfo ( resultFirstPosition , beginOffset ) ) ; } return foundEntries ; } | This method search in already mapped entries to find if necessary entry is already mapped and can be returned . |
17,597 | private OMMapBufferEntry mapNew ( final OFileMMap file , final long beginOffset ) throws IOException { return new OMMapBufferEntry ( file , file . map ( beginOffset , file . getFileSize ( ) - ( int ) beginOffset ) , beginOffset , file . getFileSize ( ) - ( int ) beginOffset ) ; } | This method maps new part of file if not all file content is mapped . |
17,598 | private void acquireLocksOnEntries ( final OMMapBufferEntry [ ] entries , OPERATION_TYPE operationType ) { if ( operationType == OPERATION_TYPE . WRITE ) for ( OMMapBufferEntry entry : entries ) { entry . acquireWriteLock ( ) ; entry . setDirty ( ) ; } else for ( OMMapBufferEntry entry : entries ) entry . acquireReadLock ( ) ; } | Locks all entries . |
17,599 | private void removeFileEntries ( OMMapBufferEntry [ ] fileEntries ) { if ( fileEntries != null ) { for ( OMMapBufferEntry entry : fileEntries ) { removeEntry ( entry ) ; } } } | Removes all files entries . Flush will be performed before removing . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.