idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
21,700 | protected void initializeAttributeIndices ( ) { m_ActiveIndices = new boolean [ m_Data . numAttributes ( ) ] ; for ( int i = 0 ; i < m_ActiveIndices . length ; i ++ ) m_ActiveIndices [ i ] = true ; } | initializes the attribute indices . |
21,701 | protected double norm ( double x , int i ) { if ( Double . isNaN ( m_Ranges [ i ] [ R_MIN ] ) || ( m_Ranges [ i ] [ R_MAX ] == m_Ranges [ i ] [ R_MIN ] ) ) return 0 ; else return ( x - m_Ranges [ i ] [ R_MIN ] ) / ( m_Ranges [ i ] [ R_WIDTH ] ) ; } | Normalizes a given value of a numeric attribute . |
21,702 | protected double difference ( int index , double val1 , double val2 ) { if ( m_Data . attribute ( index ) . isNominal ( ) == true ) { if ( isMissingValue ( val1 ) || isMissingValue ( val2 ) || ( ( int ) val1 != ( int ) val2 ) ) { return 1 ; } else { return 0 ; } } else { if ( isMissingValue ( val1 ) || isMissingValue ( val2 ) ) { if ( isMissingValue ( val1 ) && isMissingValue ( val2 ) ) { if ( ! m_DontNormalize ) return 1 ; else return ( m_Ranges [ index ] [ R_MAX ] - m_Ranges [ index ] [ R_MIN ] ) ; } else { double diff ; if ( isMissingValue ( val2 ) ) { diff = ( ! m_DontNormalize ) ? norm ( val1 , index ) : val1 ; } else { diff = ( ! m_DontNormalize ) ? norm ( val2 , index ) : val2 ; } if ( ! m_DontNormalize && diff < 0.5 ) { diff = 1.0 - diff ; } else if ( m_DontNormalize ) { if ( ( m_Ranges [ index ] [ R_MAX ] - diff ) > ( diff - m_Ranges [ index ] [ R_MIN ] ) ) return m_Ranges [ index ] [ R_MAX ] - diff ; else return diff - m_Ranges [ index ] [ R_MIN ] ; } return diff ; } } else { return ( ! m_DontNormalize ) ? ( norm ( val1 , index ) - norm ( val2 , index ) ) : ( val1 - val2 ) ; } } } | Computes the difference between two given attribute values . |
21,703 | public double [ ] [ ] initializeRanges ( ) { if ( m_Data == null ) { m_Ranges = null ; return m_Ranges ; } int numAtt = m_Data . numAttributes ( ) ; double [ ] [ ] ranges = new double [ numAtt ] [ 3 ] ; if ( m_Data . numInstances ( ) <= 0 ) { initializeRangesEmpty ( numAtt , ranges ) ; m_Ranges = ranges ; return m_Ranges ; } else { updateRangesFirst ( m_Data . instance ( 0 ) , numAtt , ranges ) ; } for ( int i = 1 ; i < m_Data . numInstances ( ) ; i ++ ) updateRanges ( m_Data . instance ( i ) , numAtt , ranges ) ; m_Ranges = ranges ; return m_Ranges ; } | Initializes the ranges using all instances of the dataset . Sets m_Ranges . |
21,704 | public void updateRangesFirst ( Instance instance , int numAtt , double [ ] [ ] ranges ) { for ( int j = 0 ; j < numAtt ; j ++ ) { if ( ! instance . isMissing ( j ) ) { ranges [ j ] [ R_MIN ] = instance . value ( j ) ; ranges [ j ] [ R_MAX ] = instance . value ( j ) ; ranges [ j ] [ R_WIDTH ] = 0.0 ; } else { ranges [ j ] [ R_MIN ] = Double . POSITIVE_INFINITY ; ranges [ j ] [ R_MAX ] = - Double . POSITIVE_INFINITY ; ranges [ j ] [ R_WIDTH ] = Double . POSITIVE_INFINITY ; } } } | Used to initialize the ranges . For this the values of the first instance is used to save time . Sets low and high to the values of the first instance and width to zero . |
21,705 | public void initializeRangesEmpty ( int numAtt , double [ ] [ ] ranges ) { for ( int j = 0 ; j < numAtt ; j ++ ) { ranges [ j ] [ R_MIN ] = Double . POSITIVE_INFINITY ; ranges [ j ] [ R_MAX ] = - Double . POSITIVE_INFINITY ; ranges [ j ] [ R_WIDTH ] = Double . POSITIVE_INFINITY ; } } | Used to initialize the ranges . |
21,706 | public double [ ] [ ] updateRanges ( Instance instance , double [ ] [ ] ranges ) { for ( int j = 0 ; j < ranges . length ; j ++ ) { double value = instance . value ( j ) ; if ( ! instance . isMissing ( j ) ) { if ( value < ranges [ j ] [ R_MIN ] ) { ranges [ j ] [ R_MIN ] = value ; ranges [ j ] [ R_WIDTH ] = ranges [ j ] [ R_MAX ] - ranges [ j ] [ R_MIN ] ; } else { if ( instance . value ( j ) > ranges [ j ] [ R_MAX ] ) { ranges [ j ] [ R_MAX ] = value ; ranges [ j ] [ R_WIDTH ] = ranges [ j ] [ R_MAX ] - ranges [ j ] [ R_MIN ] ; } } } } return ranges ; } | Updates the ranges given a new instance . |
21,707 | public double [ ] [ ] initializeRanges ( int [ ] instList ) throws Exception { if ( m_Data == null ) throw new Exception ( "No instances supplied." ) ; int numAtt = m_Data . numAttributes ( ) ; double [ ] [ ] ranges = new double [ numAtt ] [ 3 ] ; if ( m_Data . numInstances ( ) <= 0 ) { initializeRangesEmpty ( numAtt , ranges ) ; return ranges ; } else { updateRangesFirst ( m_Data . instance ( instList [ 0 ] ) , numAtt , ranges ) ; for ( int i = 1 ; i < instList . length ; i ++ ) { updateRanges ( m_Data . instance ( instList [ i ] ) , numAtt , ranges ) ; } } return ranges ; } | Initializes the ranges of a subset of the instances of this dataset . Therefore m_Ranges is not set . |
21,708 | public boolean inRanges ( Instance instance , double [ ] [ ] ranges ) { boolean isIn = true ; for ( int j = 0 ; isIn && ( j < ranges . length ) ; j ++ ) { if ( ! instance . isMissing ( j ) ) { double value = instance . value ( j ) ; isIn = value <= ranges [ j ] [ R_MAX ] ; if ( isIn ) isIn = value >= ranges [ j ] [ R_MIN ] ; } } return isIn ; } | Test if an instance is within the given ranges . |
21,709 | public static void setURLStreamHandlerFactory ( URLStreamHandlerFactory factory ) { synchronized ( PROTOCOL_HANDLERS ) { if ( Handler . factory != null ) { throw new IllegalStateException ( "URLStreamHandlerFactory already set." ) ; } PROTOCOL_HANDLERS . clear ( ) ; Handler . factory = factory ; } } | Sets the URL stream handler factory for the environment . This allows specification of the factory used in creating underlying stream handlers . This can be called once per JVM instance . |
21,710 | public void bind ( ) throws DcerpcException , IOException { synchronized ( this ) { try { this . state = 1 ; DcerpcMessage bind = new DcerpcBind ( this . binding , this ) ; sendrecv ( bind ) ; } catch ( IOException ioe ) { this . state = 0 ; throw ioe ; } } } | Bind the handle |
21,711 | public String [ ] list ( ) throws SmbException { return SmbEnumerationUtil . list ( this , "*" , ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM , null , null ) ; } | List the contents of this SMB resource . The list returned by this method will be ; |
21,712 | public void update ( byte [ ] input , int offset , int len ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "update: " + this . updates + " " + offset + ":" + len ) ; log . trace ( Hexdump . toHexString ( input , offset , Math . min ( len , 256 ) ) ) ; } if ( len == 0 ) { return ; } this . digest . update ( input , offset , len ) ; this . updates ++ ; } | Update digest with data |
21,713 | public void setupMIC ( byte [ ] type1 , byte [ ] type2 ) throws GeneralSecurityException , IOException { byte [ ] sk = this . masterKey ; if ( sk == null ) { return ; } MessageDigest mac = Crypto . getHMACT64 ( sk ) ; mac . update ( type1 ) ; mac . update ( type2 ) ; byte [ ] type3 = toByteArray ( ) ; mac . update ( type3 ) ; setMic ( mac . digest ( ) ) ; } | Sets the MIC |
21,714 | public static int getDefaultFlags ( CIFSContext tc ) { return NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_VERSION | ( tc . getConfig ( ) . isUseUnicode ( ) ? NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM ) ; } | Returns the default flags for a generic Type - 3 message in the current environment . |
21,715 | public static List < AvPair > decode ( byte [ ] data ) throws CIFSException { List < AvPair > pairs = new LinkedList < > ( ) ; int pos = 0 ; boolean foundEnd = false ; while ( pos + 4 <= data . length ) { int avId = SMBUtil . readInt2 ( data , pos ) ; int avLen = SMBUtil . readInt2 ( data , pos + 2 ) ; pos += 4 ; if ( avId == AvPair . MsvAvEOL ) { if ( avLen != 0 ) { throw new CIFSException ( "Invalid avLen for AvEOL" ) ; } foundEnd = true ; break ; } byte [ ] raw = new byte [ avLen ] ; System . arraycopy ( data , pos , raw , 0 , avLen ) ; pairs . add ( parseAvPair ( avId , raw ) ) ; pos += avLen ; } if ( ! foundEnd ) { throw new CIFSException ( "Missing AvEOL" ) ; } return pairs ; } | Decode a list of AvPairs |
21,716 | public static void remove ( List < AvPair > pairs , int type ) { Iterator < AvPair > it = pairs . iterator ( ) ; while ( it . hasNext ( ) ) { AvPair p = it . next ( ) ; if ( p . getType ( ) == type ) { it . remove ( ) ; } } } | Remove all occurances of the given type |
21,717 | public static void replace ( List < AvPair > pairs , AvPair rep ) { remove ( pairs , rep . getType ( ) ) ; pairs . add ( rep ) ; } | Replace all occurances of the given type |
21,718 | public void close ( ) throws IOException { try { if ( this . handle . isValid ( ) ) { this . handle . close ( ) ; } } finally { this . file . clearAttributeCache ( ) ; this . tmp = null ; } } | Closes this output stream and releases any system resources associated with it . |
21,719 | public void treeConnectLogon ( ) throws SmbException { String logonShare = getContext ( ) . getConfig ( ) . getLogonShare ( ) ; if ( logonShare == null || logonShare . isEmpty ( ) ) { throw new SmbException ( "Logon share is not defined" ) ; } try ( SmbTreeImpl t = getSmbTree ( logonShare , null ) ) { t . treeConnect ( null , null ) ; } catch ( CIFSException e ) { throw SmbException . wrap ( e ) ; } } | Establish a tree connection with the configured logon share |
21,720 | public static int readn ( InputStream in , byte [ ] b , int off , int len ) throws IOException { int i = 0 , n = - 5 ; if ( off + len > b . length ) { throw new IOException ( "Buffer too short, bufsize " + b . length + " read " + len ) ; } while ( i < len ) { n = in . read ( b , off + i , len - i ) ; if ( n <= 0 ) { break ; } i += n ; } return i ; } | Read bytes from the input stream into a buffer |
21,721 | public < T extends Response > T sendrecv ( Request request , T response , Set < RequestParam > params ) throws IOException { if ( isDisconnected ( ) && this . state != 5 ) { throw new TransportException ( "Transport is disconnected " + this . name ) ; } try { long timeout = ! params . contains ( RequestParam . NO_TIMEOUT ) ? getResponseTimeout ( request ) : 0 ; long firstKey = doSend ( request , response , params , timeout ) ; if ( Thread . currentThread ( ) == this . thread ) { synchronized ( this . inLock ) { Long peekKey = peekKey ( ) ; if ( peekKey == firstKey ) { doRecv ( response ) ; response . received ( ) ; return response ; } doSkip ( peekKey ) ; } } return waitForResponses ( request , response , timeout ) ; } catch ( IOException ioe ) { log . warn ( "sendrecv failed" , ioe ) ; try { disconnect ( true ) ; } catch ( IOException ioe2 ) { ioe . addSuppressed ( ioe2 ) ; log . info ( "disconnect failed" , ioe2 ) ; } throw ioe ; } catch ( InterruptedException ie ) { throw new TransportException ( ie ) ; } finally { Response curResp = response ; Request curReq = request ; while ( curResp != null ) { this . response_map . remove ( curResp . getMid ( ) ) ; Request next = curReq . getNext ( ) ; if ( next != null ) { curReq = next ; curResp = next . getResponse ( ) ; } else { break ; } } } } | Send a request message and recieve response |
21,722 | public synchronized boolean disconnect ( boolean hard , boolean inUse ) throws IOException { IOException ioe = null ; switch ( this . state ) { case 0 : case 5 : case 6 : return false ; case 2 : hard = true ; case 3 : if ( this . response_map . size ( ) != 0 && ! hard && inUse ) { break ; } try { this . state = 5 ; boolean wasInUse = doDisconnect ( hard , inUse ) ; this . state = 6 ; return wasInUse ; } catch ( IOException ioe0 ) { this . state = 6 ; ioe = ioe0 ; } case 4 : this . thread = null ; this . state = 6 ; break ; default : log . error ( "Invalid state: " + this . state ) ; this . thread = null ; this . state = 6 ; break ; } if ( ioe != null ) throw ioe ; return false ; } | Disconnect the transport |
21,723 | protected void doRecv ( Response response ) throws IOException { CommonServerMessageBlock resp = ( CommonServerMessageBlock ) response ; this . negotiated . setupResponse ( response ) ; try { if ( this . smb2 ) { doRecvSMB2 ( resp ) ; } else { doRecvSMB1 ( resp ) ; } } catch ( Exception e ) { log . warn ( "Failure decoding message, disconnecting transport" , e ) ; response . exception ( e ) ; synchronized ( response ) { response . notifyAll ( ) ; } throw e ; } } | must be synchronized with peekKey |
21,724 | public static boolean isDotQuadIP ( String hostname ) { if ( Character . isDigit ( hostname . charAt ( 0 ) ) ) { int i , len , dots ; char [ ] data ; i = dots = 0 ; len = hostname . length ( ) ; data = hostname . toCharArray ( ) ; while ( i < len && Character . isDigit ( data [ i ++ ] ) ) { if ( i == len && dots == 3 ) { return true ; } if ( i < len && data [ i ] == '.' ) { dots ++ ; i ++ ; } } } return false ; } | Check whether a hostname is actually an ip address |
21,725 | public static synchronized final void init ( Properties props ) throws CIFSException { if ( INSTANCE != null ) { throw new CIFSException ( "Singleton context is already initialized" ) ; } Properties p = new Properties ( ) ; try { String filename = System . getProperty ( "jcifs.properties" ) ; if ( filename != null && filename . length ( ) > 1 ) { try ( FileInputStream in = new FileInputStream ( filename ) ) { p . load ( in ) ; } } } catch ( IOException ioe ) { log . error ( "Failed to load config" , ioe ) ; } p . putAll ( System . getProperties ( ) ) ; if ( props != null ) { p . putAll ( props ) ; } INSTANCE = new SingletonContext ( p ) ; } | Initialize singleton context using custom properties |
21,726 | public static synchronized final SingletonContext getInstance ( ) { if ( INSTANCE == null ) { try { log . debug ( "Initializing singleton context" ) ; init ( null ) ; } catch ( CIFSException e ) { log . error ( "Failed to create singleton JCIFS context" , e ) ; } } return INSTANCE ; } | Get singleton context |
21,727 | public static int getPowerOf2 ( long value ) { Preconditions . checkArgument ( isPowerOf2 ( value ) ) ; return Long . SIZE - ( Long . numberOfLeadingZeros ( value ) + 1 ) ; } | Returns an integer X such that 2^X = value . Throws an exception if value is not a power of 2 . |
21,728 | public void rollback ( ) throws BackendException { Throwable excep = null ; for ( IndexTransaction itx : indexTx . values ( ) ) { try { itx . rollback ( ) ; } catch ( Throwable e ) { excep = e ; } } storeTx . rollback ( ) ; if ( excep != null ) { if ( excep instanceof BackendException ) throw ( BackendException ) excep ; else throw new PermanentBackendException ( "Unexpected exception" , excep ) ; } } | Rolls back all transactions and makes sure that this does not get cut short by exceptions . If exceptions occur the storage exception takes priority on re - throw . |
21,729 | public boolean contains ( int partitionId ) { if ( lowerID < upperID ) { return lowerID <= partitionId && upperID > partitionId ; } else { return ( lowerID <= partitionId && partitionId < idUpperBound ) || ( upperID > partitionId && partitionId >= 0 ) ; } } | Returns true of the given partitionId lies within this partition id range else false . |
21,730 | public int getRandomID ( ) { int partitionWidth ; if ( lowerID < upperID ) partitionWidth = upperID - lowerID ; else partitionWidth = ( idUpperBound - lowerID ) + upperID ; Preconditions . checkArgument ( partitionWidth > 0 , partitionWidth ) ; return ( random . nextInt ( partitionWidth ) + lowerID ) % idUpperBound ; } | Returns a random partition id that lies within this partition id range . |
21,731 | public double incBy ( K o , double inc ) { Counter c = countMap . get ( o ) ; if ( c == null ) { c = new Counter ( ) ; countMap . put ( o , c ) ; } c . count += inc ; return c . count ; } | Increases the count of object o by inc and returns the new count value |
21,732 | public File getHomeDirectory ( ) { if ( ! configuration . has ( STORAGE_DIRECTORY ) ) throw new UnsupportedOperationException ( "No home directory specified" ) ; File dir = new File ( configuration . get ( STORAGE_DIRECTORY ) ) ; Preconditions . checkArgument ( dir . isDirectory ( ) , "Not a directory" ) ; return dir ; } | Returns the home directory for the graph database initialized in this configuration |
21,733 | public synchronized void close ( ) throws BackendException { if ( ! isOpen ) return ; this . isOpen = false ; if ( readExecutor != null ) readExecutor . shutdown ( ) ; if ( sendThread != null ) sendThread . close ( CLOSE_DOWN_WAIT ) ; if ( readExecutor != null ) { try { readExecutor . awaitTermination ( 1 , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { log . error ( "Could not terminate reader thread pool for KCVSLog " + name + " due to interruption" ) ; } if ( ! readExecutor . isTerminated ( ) ) { readExecutor . shutdownNow ( ) ; log . error ( "Reader thread pool for KCVSLog " + name + " did not shut down in time - could not clean up or set read markers" ) ; } else { for ( MessagePuller puller : msgPullers ) { puller . close ( ) ; } } } writeSetting ( manager . senderId , MESSAGE_COUNTER_COLUMN , numMsgCounter . get ( ) ) ; store . close ( ) ; manager . closedLog ( this ) ; } | Closes the log by terminating all threads and waiting for their termination . |
21,734 | private void sendMessages ( final List < MessageEnvelope > msgEnvelopes ) { try { boolean success = BackendOperation . execute ( new BackendOperation . Transactional < Boolean > ( ) { public Boolean call ( StoreTransaction txh ) throws BackendException { ListMultimap < StaticBuffer , Entry > mutations = ArrayListMultimap . create ( ) ; for ( MessageEnvelope env : msgEnvelopes ) { mutations . put ( env . key , env . entry ) ; long ts = env . entry . getColumn ( ) . getLong ( 0 ) ; log . debug ( "Preparing to write {} to storage with column/timestamp {}" , env , times . getTime ( ts ) ) ; } Map < StaticBuffer , KCVMutation > muts = new HashMap < StaticBuffer , KCVMutation > ( mutations . keySet ( ) . size ( ) ) ; for ( StaticBuffer key : mutations . keySet ( ) ) { muts . put ( key , new KCVMutation ( mutations . get ( key ) , KeyColumnValueStore . NO_DELETIONS ) ) ; log . debug ( "Built mutation on key {} with {} additions" , key , mutations . get ( key ) . size ( ) ) ; } manager . storeManager . mutateMany ( ImmutableMap . of ( store . getName ( ) , muts ) , txh ) ; log . debug ( "Wrote {} total envelopes with operation timestamp {}" , msgEnvelopes . size ( ) , txh . getConfiguration ( ) . getCommitTime ( ) ) ; return Boolean . TRUE ; } public String toString ( ) { return "messageSending" ; } } , this , times , maxWriteTime ) ; Preconditions . checkState ( success ) ; log . debug ( "Wrote {} messages to backend" , msgEnvelopes . size ( ) ) ; for ( MessageEnvelope msgEnvelope : msgEnvelopes ) msgEnvelope . message . delivered ( ) ; } catch ( TitanException e ) { for ( MessageEnvelope msgEnvelope : msgEnvelopes ) msgEnvelope . message . failed ( e ) ; throw e ; } } | Sends a batch of messages by persisting them to the storage backend . |
21,735 | public void addition ( E entry ) { if ( additions == null ) additions = new ArrayList < E > ( ) ; additions . add ( entry ) ; } | Adds a new entry as an addition to this mutation |
21,736 | public void deletion ( K key ) { if ( deletions == null ) deletions = new ArrayList < K > ( ) ; deletions . add ( key ) ; } | Adds a new key as a deletion to this mutation |
21,737 | public void merge ( Mutation < E , K > m ) { Preconditions . checkNotNull ( m ) ; if ( null != m . additions ) { if ( null == additions ) additions = m . additions ; else additions . addAll ( m . additions ) ; } if ( null != m . deletions ) { if ( null == deletions ) deletions = m . deletions ; else deletions . addAll ( m . deletions ) ; } } | Merges another mutation into this mutation . Ensures that all additions and deletions are added to this mutation . Does not remove duplicates if such exist - this needs to be ensured by the caller . |
21,738 | public CTConnection makeRawConnection ( ) throws TTransportException { final Config cfg = cfgRef . get ( ) ; String hostname = cfg . getRandomHost ( ) ; log . debug ( "Creating TSocket({}, {}, {}, {}, {})" , hostname , cfg . port , cfg . username , cfg . password , cfg . timeoutMS ) ; TSocket socket ; if ( null != cfg . sslTruststoreLocation && ! cfg . sslTruststoreLocation . isEmpty ( ) ) { TSSLTransportFactory . TSSLTransportParameters params = new TSSLTransportFactory . TSSLTransportParameters ( ) { { setTrustStore ( cfg . sslTruststoreLocation , cfg . sslTruststorePassword ) ; } } ; socket = TSSLTransportFactory . getClientSocket ( hostname , cfg . port , cfg . timeoutMS , params ) ; } else { socket = new TSocket ( hostname , cfg . port , cfg . timeoutMS ) ; } TTransport transport = new TFramedTransport ( socket , cfg . frameSize ) ; log . trace ( "Created transport {}" , transport ) ; TBinaryProtocol protocol = new TBinaryProtocol ( transport ) ; Cassandra . Client client = new Cassandra . Client ( protocol ) ; if ( ! transport . isOpen ( ) ) { transport . open ( ) ; } if ( cfg . username != null ) { Map < String , String > credentials = new HashMap < String , String > ( ) { { put ( IAuthenticator . USERNAME_KEY , cfg . username ) ; put ( IAuthenticator . PASSWORD_KEY , cfg . password ) ; } } ; try { client . login ( new AuthenticationRequest ( credentials ) ) ; } catch ( Exception e ) { throw new TTransportException ( e ) ; } } return new CTConnection ( transport , client , cfg ) ; } | Create a Cassandra - Thrift connection but do not attempt to set a keyspace on the connection . |
21,739 | public Q profiler ( QueryProfiler profiler ) { Preconditions . checkNotNull ( profiler ) ; this . profiler = profiler ; return getThis ( ) ; } | Sets the query profiler to observe this query . Must be set before the query is executed to take effect . |
21,740 | public static final Geoshape point ( final float latitude , final float longitude ) { Preconditions . checkArgument ( isValidCoordinate ( latitude , longitude ) , "Invalid coordinate provided" ) ; return new Geoshape ( new float [ ] [ ] { new float [ ] { latitude } , new float [ ] { longitude } } ) ; } | Constructs a point from its latitude and longitude information |
21,741 | public static final Geoshape circle ( final float latitude , final float longitude , final float radiusInKM ) { Preconditions . checkArgument ( isValidCoordinate ( latitude , longitude ) , "Invalid coordinate provided" ) ; Preconditions . checkArgument ( radiusInKM > 0 , "Invalid radius provided [%s]" , radiusInKM ) ; return new Geoshape ( new float [ ] [ ] { new float [ ] { latitude , Float . NaN } , new float [ ] { longitude , radiusInKM } } ) ; } | Constructs a circle from a given center point and a radius in kilometer |
21,742 | public static void awaitGraphIndexUpdate ( TitanGraph g , String indexName , long time , TemporalUnit unit ) { awaitIndexUpdate ( g , indexName , null , time , unit ) ; } | This method blocks and waits until the provided index has been updated across the entire Titan cluster and reached a stable state . This method will wait for the given period of time and throw an exception if the index did not reach a final state within that time . The method simply returns when the index has reached the final state prior to the time period expiring . |
21,743 | public static final void clear ( TitanGraph graph ) { Preconditions . checkNotNull ( graph ) ; Preconditions . checkArgument ( graph instanceof StandardTitanGraph , "Invalid graph instance detected: %s" , graph . getClass ( ) ) ; StandardTitanGraph g = ( StandardTitanGraph ) graph ; Preconditions . checkArgument ( ! g . isOpen ( ) , "Graph needs to be shut down before it can be cleared." ) ; final GraphDatabaseConfiguration config = g . getConfiguration ( ) ; BackendOperation . execute ( new Callable < Boolean > ( ) { public Boolean call ( ) throws Exception { config . getBackend ( ) . clearStorage ( ) ; return true ; } public String toString ( ) { return "ClearBackend" ; } } , Duration . ofSeconds ( 20 ) ) ; } | Clears out the entire graph . This will delete ALL of the data stored in this graph and the data will NOT be recoverable . This method is intended only for development and testing use . |
21,744 | public static void attachProperties ( final TitanVertex vertex , final Object ... propertyKeyValues ) { if ( null == vertex ) throw Graph . Exceptions . argumentCanNotBeNull ( "vertex" ) ; for ( int i = 0 ; i < propertyKeyValues . length ; i = i + 2 ) { if ( ! propertyKeyValues [ i ] . equals ( T . id ) && ! propertyKeyValues [ i ] . equals ( T . label ) ) vertex . property ( ( String ) propertyKeyValues [ i ] , propertyKeyValues [ i + 1 ] ) ; } } | This is essentially an adjusted copy&paste from TinkerPop s ElementHelper class . The reason for copying it is so that we can determine the cardinality of a property key based on Titan s schema which is tied to this particular transaction and not the graph . |
21,745 | public boolean hasCommonOrder ( ) { Order lastOrder = null ; for ( OrderEntry oe : list ) { if ( lastOrder == null ) lastOrder = oe . order ; else if ( lastOrder != oe . order ) return false ; } return true ; } | Whether all individual orders are the same |
21,746 | public synchronized Instant getStartTime ( TimestampProvider times ) { if ( startTime == null ) { startTime = times . getTime ( ) ; } return startTime ; } | Returns the start time of this marker if such has been defined or the current time if not |
21,747 | private static final String [ ] deduplicateKeys ( String [ ] keys ) { synchronized ( KEY_CACHE ) { KEY_HULL . setKeys ( keys ) ; KeyContainer retrieved = KEY_CACHE . get ( KEY_HULL ) ; if ( retrieved == null ) { retrieved = new KeyContainer ( keys ) ; KEY_CACHE . put ( retrieved , retrieved ) ; } return retrieved . getKeys ( ) ; } } | Deduplicates keys arrays to keep the memory footprint on CompactMap to a minimum . |
21,748 | public static StaticBuffer get ( KeyColumnValueStore store , StaticBuffer key , StaticBuffer column , StoreTransaction txh ) throws BackendException { KeySliceQuery query = new KeySliceQuery ( key , column , BufferUtil . nextBiggerBuffer ( column ) ) . setLimit ( 2 ) ; List < Entry > result = store . getSlice ( query , txh ) ; if ( result . size ( ) > 1 ) log . warn ( "GET query returned more than 1 result: store {} | key {} | column {}" , new Object [ ] { store . getName ( ) , key , column } ) ; if ( result . isEmpty ( ) ) return null ; else return result . get ( 0 ) . getValueAs ( StaticBuffer . STATIC_FACTORY ) ; } | Retrieves the value for the specified column and key under the given transaction from the store if such exists otherwise returns NULL |
21,749 | public static boolean containsKeyColumn ( KeyColumnValueStore store , StaticBuffer key , StaticBuffer column , StoreTransaction txh ) throws BackendException { return get ( store , key , column , txh ) != null ; } | Returns true if the specified key - column pair exists in the store . |
21,750 | public < O > O get ( final String key , final Class < O > datatype ) { StaticBuffer column = string2StaticBuffer ( key ) ; final KeySliceQuery query = new KeySliceQuery ( rowKey , column , BufferUtil . nextBiggerBuffer ( column ) ) ; StaticBuffer result = BackendOperation . execute ( new BackendOperation . Transactional < StaticBuffer > ( ) { public StaticBuffer call ( StoreTransaction txh ) throws BackendException { List < Entry > entries = store . getSlice ( query , txh ) ; if ( entries . isEmpty ( ) ) return null ; return entries . get ( 0 ) . getValueAs ( StaticBuffer . STATIC_FACTORY ) ; } public String toString ( ) { return "getConfiguration" ; } } , txProvider , times , maxOperationWaitTime ) ; if ( result == null ) return null ; return staticBuffer2Object ( result , datatype ) ; } | Reads the configuration property for this StoreManager |
21,751 | public < O > void set ( String key , O value ) { set ( key , value , null , false ) ; } | Sets a configuration property for this StoreManager . |
21,752 | private Map < StaticBuffer , Pair < Put , Delete > > convertToCommands ( Map < String , Map < StaticBuffer , KCVMutation > > mutations , final long putTimestamp , final long delTimestamp ) throws PermanentBackendException { Map < StaticBuffer , Pair < Put , Delete > > commandsPerKey = new HashMap < StaticBuffer , Pair < Put , Delete > > ( ) ; for ( Map . Entry < String , Map < StaticBuffer , KCVMutation > > entry : mutations . entrySet ( ) ) { String cfString = getCfNameForStoreName ( entry . getKey ( ) ) ; byte [ ] cfName = cfString . getBytes ( ) ; for ( Map . Entry < StaticBuffer , KCVMutation > m : entry . getValue ( ) . entrySet ( ) ) { byte [ ] key = m . getKey ( ) . as ( StaticBuffer . ARRAY_FACTORY ) ; KCVMutation mutation = m . getValue ( ) ; Pair < Put , Delete > commands = commandsPerKey . get ( m . getKey ( ) ) ; if ( commands == null ) { commands = new Pair < Put , Delete > ( ) ; commandsPerKey . put ( m . getKey ( ) , commands ) ; } if ( mutation . hasDeletions ( ) ) { if ( commands . getSecond ( ) == null ) { Delete d = new Delete ( key ) ; compat . setTimestamp ( d , delTimestamp ) ; commands . setSecond ( d ) ; } for ( StaticBuffer b : mutation . getDeletions ( ) ) { commands . getSecond ( ) . deleteColumns ( cfName , b . as ( StaticBuffer . ARRAY_FACTORY ) , delTimestamp ) ; } } if ( mutation . hasAdditions ( ) ) { if ( commands . getFirst ( ) == null ) { Put p = new Put ( key , putTimestamp ) ; commands . setFirst ( p ) ; } for ( Entry e : mutation . getAdditions ( ) ) { commands . getFirst ( ) . add ( cfName , e . getColumnAs ( StaticBuffer . ARRAY_FACTORY ) , putTimestamp , e . getValueAs ( StaticBuffer . ARRAY_FACTORY ) ) ; } } } } return commandsPerKey ; } | Convert Titan internal Mutation representation into HBase native commands . |
21,753 | protected void validateIndexStatus ( ) { TitanSchemaVertex schemaVertex = mgmt . getSchemaVertex ( index ) ; Set < SchemaStatus > acceptableStatuses = SchemaAction . REINDEX . getApplicableStatus ( ) ; boolean isValidIndex = true ; String invalidIndexHint ; if ( index instanceof RelationTypeIndex || ( index instanceof TitanGraphIndex && ( ( TitanGraphIndex ) index ) . isCompositeIndex ( ) ) ) { SchemaStatus actualStatus = schemaVertex . getStatus ( ) ; isValidIndex = acceptableStatuses . contains ( actualStatus ) ; invalidIndexHint = String . format ( "The index has status %s, but one of %s is required" , actualStatus , acceptableStatuses ) ; } else { Preconditions . checkArgument ( index instanceof TitanGraphIndex , "Unexpected index: %s" , index ) ; TitanGraphIndex gindex = ( TitanGraphIndex ) index ; Preconditions . checkArgument ( gindex . isMixedIndex ( ) ) ; Map < String , SchemaStatus > invalidKeyStatuses = new HashMap < > ( ) ; int acceptableFields = 0 ; for ( PropertyKey key : gindex . getFieldKeys ( ) ) { SchemaStatus status = gindex . getIndexStatus ( key ) ; if ( status != SchemaStatus . DISABLED && ! acceptableStatuses . contains ( status ) ) { isValidIndex = false ; invalidKeyStatuses . put ( key . name ( ) , status ) ; log . warn ( "Index {} has key {} in an invalid status {}" , index , key , status ) ; } if ( acceptableStatuses . contains ( status ) ) acceptableFields ++ ; } invalidIndexHint = String . format ( "The following index keys have invalid status: %s (status must be one of %s)" , Joiner . on ( "," ) . withKeyValueSeparator ( " has status " ) . join ( invalidKeyStatuses ) , acceptableStatuses ) ; if ( isValidIndex && acceptableFields == 0 ) { isValidIndex = false ; invalidIndexHint = "The index does not contain any valid keys" ; } } Preconditions . checkArgument ( isValidIndex , "The index %s is in an invalid state and cannot be indexed. %s" , indexName , invalidIndexHint ) ; log . debug ( "Index {} is valid for re-indexing" ) ; } | Check that our target index is in either the ENABLED or REGISTERED state . |
21,754 | public void register ( String store , String key , KeyInformation information , BaseTransaction tx ) throws BackendException { if ( mode == Mode . CLOUD ) { CloudSolrClient client = ( CloudSolrClient ) solrClient ; try { createCollectionIfNotExists ( client , configuration , store ) ; } catch ( IOException e ) { throw new PermanentBackendException ( e ) ; } catch ( SolrServerException e ) { throw new PermanentBackendException ( e ) ; } catch ( InterruptedException e ) { throw new PermanentBackendException ( e ) ; } catch ( KeeperException e ) { throw new PermanentBackendException ( e ) ; } } } | Unlike the ElasticSearch Index which is schema free Solr requires a schema to support searching . This means that you will need to modify the solr schema with the appropriate field definitions in order to work properly . If you have a running instance of Solr and you modify its schema with new fields don t forget to re - index! |
21,755 | private static boolean checkIfCollectionExists ( CloudSolrClient server , String collection ) throws KeeperException , InterruptedException { ZkStateReader zkStateReader = server . getZkStateReader ( ) ; zkStateReader . updateClusterState ( true ) ; ClusterState clusterState = zkStateReader . getClusterState ( ) ; return clusterState . getCollectionOrNull ( collection ) != null ; } | Checks if the collection has already been created in Solr . |
21,756 | private static void waitForRecoveriesToFinish ( CloudSolrClient server , String collection ) throws KeeperException , InterruptedException { ZkStateReader zkStateReader = server . getZkStateReader ( ) ; try { boolean cont = true ; while ( cont ) { boolean sawLiveRecovering = false ; zkStateReader . updateClusterState ( true ) ; ClusterState clusterState = zkStateReader . getClusterState ( ) ; Map < String , Slice > slices = clusterState . getSlicesMap ( collection ) ; Preconditions . checkNotNull ( "Could not find collection:" + collection , slices ) ; for ( Map . Entry < String , Slice > entry : slices . entrySet ( ) ) { Map < String , Replica > shards = entry . getValue ( ) . getReplicasMap ( ) ; for ( Map . Entry < String , Replica > shard : shards . entrySet ( ) ) { String state = shard . getValue ( ) . getStr ( ZkStateReader . STATE_PROP ) ; if ( ( state . equals ( Replica . State . RECOVERING ) || state . equals ( Replica . State . DOWN ) ) && clusterState . liveNodesContain ( shard . getValue ( ) . getStr ( ZkStateReader . NODE_NAME_PROP ) ) ) { sawLiveRecovering = true ; } } } if ( ! sawLiveRecovering ) { cont = false ; } else { Thread . sleep ( 1000 ) ; } } } finally { logger . info ( "Exiting solr wait" ) ; } } | Wait for all the collection shards to be ready . |
21,757 | protected String [ ] parseCommandlineArgs ( ) throws MojoExecutionException { if ( commandlineArgs == null ) { return null ; } else { try { return CommandLineUtils . translateCommandline ( commandlineArgs ) ; } catch ( Exception e ) { throw new MojoExecutionException ( e . getMessage ( ) ) ; } } } | Parses the argument string given by the user . Strings are recognized as everything between STRING_WRAPPER . PARAMETER_DELIMITER is ignored inside a string . STRING_WRAPPER and PARAMETER_DELIMITER can be escaped using ESCAPE_CHAR . |
21,758 | protected void registerSourceRoots ( ) { if ( sourceRoot != null ) { getLog ( ) . info ( "Registering compile source root " + sourceRoot ) ; project . addCompileSourceRoot ( sourceRoot . toString ( ) ) ; } if ( testSourceRoot != null ) { getLog ( ) . info ( "Registering compile test source root " + testSourceRoot ) ; project . addTestCompileSourceRoot ( testSourceRoot . toString ( ) ) ; } } | Register compile and compile tests source roots if necessary |
21,759 | private void genImportCode ( ) { Set < String > imports = new HashSet < String > ( ) ; imports . add ( "java.util.*" ) ; imports . add ( "java.io.IOException" ) ; imports . add ( "java.lang.reflect.*" ) ; imports . add ( "com.baidu.bjf.remoting.protobuf.code.*" ) ; imports . add ( "com.baidu.bjf.remoting.protobuf.utils.*" ) ; imports . add ( "com.baidu.bjf.remoting.protobuf.*" ) ; imports . add ( "com.google.protobuf.*" ) ; if ( ! StringUtils . isEmpty ( getPackage ( ) ) ) { imports . add ( getTargetProxyClassname ( ) ) ; } for ( String pkg : imports ) { templator . setVariable ( "importPackage" , pkg ) ; templator . addBlock ( "imports" ) ; } } | Gen import code . |
21,760 | public void reset ( ) { if ( varValuesTab == null ) { varValuesTab = new String [ mtp . varTabCnt ] ; } else { for ( int varNo = 0 ; varNo < mtp . varTabCnt ; varNo ++ ) { varValuesTab [ varNo ] = null ; } } if ( blockDynTab == null ) { blockDynTab = new BlockDynTabRec [ mtp . blockTabCnt ] ; } for ( int blockNo = 0 ; blockNo < mtp . blockTabCnt ; blockNo ++ ) { BlockDynTabRec bdtr = blockDynTab [ blockNo ] ; if ( bdtr == null ) { bdtr = new BlockDynTabRec ( ) ; blockDynTab [ blockNo ] = bdtr ; } bdtr . instances = 0 ; bdtr . firstBlockInstNo = - 1 ; bdtr . lastBlockInstNo = - 1 ; } blockInstTabCnt = 0 ; } | Resets the MiniTemplator object to the initial state . All variable values are cleared and all added block instances are deleted . This method can be used to produce another HTML page with the same template . It is faster than creating another MiniTemplator object because the template does not have to be read and parsed again . |
21,761 | public Map < String , String > getVariables ( ) { HashMap < String , String > map = new HashMap < String , String > ( mtp . varTabCnt ) ; for ( int varNo = 0 ; varNo < mtp . varTabCnt ; varNo ++ ) map . put ( mtp . varTab [ varNo ] , varValuesTab [ varNo ] ) ; return map ; } | Returns a map with the names and current values of the template variables . |
21,762 | private int registerBlockInstance ( ) { int blockInstNo = blockInstTabCnt ++ ; if ( blockInstTab == null ) { blockInstTab = new BlockInstTabRec [ 64 ] ; } if ( blockInstTabCnt > blockInstTab . length ) { blockInstTab = ( BlockInstTabRec [ ] ) MiniTemplatorParser . resizeArray ( blockInstTab , 2 * blockInstTabCnt ) ; } blockInstTab [ blockInstNo ] = new BlockInstTabRec ( ) ; return blockInstNo ; } | Returns the block instance number . |
21,763 | public void generateOutput ( String outputFileName ) throws IOException { FileOutputStream stream = null ; OutputStreamWriter writer = null ; try { stream = new FileOutputStream ( outputFileName ) ; writer = new OutputStreamWriter ( stream , charset ) ; generateOutput ( writer ) ; } finally { if ( writer != null ) { writer . close ( ) ; } if ( stream != null ) { stream . close ( ) ; } } } | Generates the HTML page and writes it into a file . |
21,764 | public void generateOutput ( Writer outputWriter ) throws IOException { String s = generateOutput ( ) ; outputWriter . write ( s ) ; } | Generates the HTML page and writes it to a character stream . |
21,765 | public String generateOutput ( ) { if ( blockDynTab [ 0 ] . instances == 0 ) { addBlockByNo ( 0 ) ; } for ( int blockNo = 0 ; blockNo < mtp . blockTabCnt ; blockNo ++ ) { BlockDynTabRec bdtr = blockDynTab [ blockNo ] ; bdtr . currBlockInstNo = bdtr . firstBlockInstNo ; } StringBuilder out = new StringBuilder ( ) ; writeBlockInstances ( out , 0 , - 1 ) ; return out . toString ( ) ; } | Generates the HTML page and returns it as a string . |
21,766 | private void writeBlockInstances ( StringBuilder out , int blockNo , int parentInstLevel ) { BlockDynTabRec bdtr = blockDynTab [ blockNo ] ; while ( true ) { int blockInstNo = bdtr . currBlockInstNo ; if ( blockInstNo == - 1 ) { break ; } BlockInstTabRec bitr = blockInstTab [ blockInstNo ] ; if ( bitr . parentInstLevel < parentInstLevel ) { throw new AssertionError ( ) ; } if ( bitr . parentInstLevel > parentInstLevel ) { break ; } writeBlockInstance ( out , blockInstNo ) ; bdtr . currBlockInstNo = bitr . nextBlockInstNo ; } } | Called recursively . |
21,767 | private void beginMainBlock ( ) { int blockNo = registerBlock ( null ) ; BlockTabRec btr = blockTab [ blockNo ] ; btr . tPosBegin = 0 ; btr . tPosContentsBegin = 0 ; openBlocksTab [ currentNestingLevel ] = blockNo ; currentNestingLevel ++ ; } | The main block is an implicitly defined block that covers the whole template . |
21,768 | private void endMainBlock ( ) { BlockTabRec btr = blockTab [ 0 ] ; btr . tPosContentsEnd = templateText . length ( ) ; btr . tPosEnd = templateText . length ( ) ; btr . definitionIsOpen = false ; currentNestingLevel -- ; } | Completes the main block registration . |
21,769 | private boolean processTemplateCommand ( String cmdLine , int cmdTPosBegin , int cmdTPosEnd ) throws MiniTemplator . TemplateSyntaxException { int p0 = skipBlanks ( cmdLine , 0 ) ; if ( p0 >= cmdLine . length ( ) ) { return false ; } int p = skipNonBlanks ( cmdLine , p0 ) ; String cmd = cmdLine . substring ( p0 , p ) ; String parms = cmdLine . substring ( p ) ; if ( cmd . equalsIgnoreCase ( "$beginBlock" ) ) { processBeginBlockCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else if ( cmd . equalsIgnoreCase ( "$endBlock" ) ) { processEndBlockCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else if ( cmd . equalsIgnoreCase ( "$include" ) ) { processIncludeCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else if ( cmd . equalsIgnoreCase ( "$if" ) ) { processIfCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else if ( cmd . equalsIgnoreCase ( "$elseIf" ) ) { processElseIfCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else if ( cmd . equalsIgnoreCase ( "$else" ) ) { processElseCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else if ( cmd . equalsIgnoreCase ( "$endIf" ) ) { processEndIfCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else { if ( cmd . startsWith ( "$" ) && ! cmd . startsWith ( "${" ) ) { throw new MiniTemplator . TemplateSyntaxException ( "Unknown command \"" + cmd + "\" in template at offset " + cmdTPosBegin + "." ) ; } else { return false ; } } return true ; } | Returns false if the command should be treatet as normal template text . |
21,770 | private boolean processShortFormTemplateCommand ( String cmdLine , int cmdTPosBegin , int cmdTPosEnd ) throws MiniTemplator . TemplateSyntaxException { int p0 = skipBlanks ( cmdLine , 0 ) ; if ( p0 >= cmdLine . length ( ) ) { return false ; } int p = p0 ; char cmd1 = cmdLine . charAt ( p ++ ) ; if ( cmd1 == '/' && p < cmdLine . length ( ) && ! Character . isWhitespace ( cmdLine . charAt ( p ) ) ) { p ++ ; } String cmd = cmdLine . substring ( p0 , p ) ; String parms = cmdLine . substring ( p ) . trim ( ) ; if ( cmd . equals ( "?" ) ) { processIfCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else if ( cmd . equals ( ":" ) ) { if ( parms . length ( ) > 0 ) { processElseIfCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else { processElseCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } } else if ( cmd . equals ( "/?" ) ) { processEndIfCmd ( parms , cmdTPosBegin , cmdTPosEnd ) ; } else { return false ; } return true ; } | Returns false if the command is not recognized and should be treatet as normal temlate text . |
21,771 | private int registerBlock ( String blockName ) { int blockNo = blockTabCnt ++ ; if ( blockTabCnt > blockTab . length ) { blockTab = ( BlockTabRec [ ] ) resizeArray ( blockTab , 2 * blockTabCnt ) ; } BlockTabRec btr = new BlockTabRec ( ) ; blockTab [ blockNo ] = btr ; btr . blockName = blockName ; if ( blockName != null ) { btr . nextWithSameName = lookupBlockName ( blockName ) ; } else { btr . nextWithSameName = - 1 ; } btr . nestingLevel = currentNestingLevel ; if ( currentNestingLevel > 0 ) { btr . parentBlockNo = openBlocksTab [ currentNestingLevel - 1 ] ; } else { btr . parentBlockNo = - 1 ; } btr . definitionIsOpen = true ; btr . blockVarCnt = 0 ; btr . firstVarRefNo = - 1 ; btr . blockVarNoToVarNoMap = new int [ 32 ] ; btr . dummy = false ; if ( blockName != null ) { blockNameToNoMap . put ( blockName . toUpperCase ( ) , new Integer ( blockNo ) ) ; } return blockNo ; } | Returns the block number of the newly registered block . |
21,772 | private void excludeTemplateRange ( int tPosBegin , int tPosEnd ) { if ( blockTabCnt > 0 ) { BlockTabRec btr = blockTab [ blockTabCnt - 1 ] ; if ( btr . dummy && btr . tPosEnd == tPosBegin ) { btr . tPosContentsEnd = tPosEnd ; btr . tPosEnd = tPosEnd ; return ; } } int blockNo = registerBlock ( null ) ; BlockTabRec btr = blockTab [ blockNo ] ; btr . tPosBegin = tPosBegin ; btr . tPosContentsBegin = tPosBegin ; btr . tPosContentsEnd = tPosEnd ; btr . tPosEnd = tPosEnd ; btr . definitionIsOpen = false ; btr . dummy = true ; } | Registers a dummy block to exclude a range within the template text . |
21,773 | private void checkBlockDefinitionsComplete ( ) throws MiniTemplator . TemplateSyntaxException { for ( int blockNo = 0 ; blockNo < blockTabCnt ; blockNo ++ ) { BlockTabRec btr = blockTab [ blockNo ] ; if ( btr . definitionIsOpen ) { throw new MiniTemplator . TemplateSyntaxException ( "Missing $EndBlock command in template for block \"" + btr . blockName + "\"." ) ; } } if ( currentNestingLevel != 0 ) { throw new MiniTemplator . TemplateSyntaxException ( "Block nesting level error at end of template." ) ; } } | Checks that all block definitions are closed . |
21,774 | private boolean conditionalExclude ( int tPosBegin , int tPosEnd ) { if ( isCondEnabled ( condLevel ) ) { return false ; } excludeTemplateRange ( tPosBegin , tPosEnd ) ; return true ; } | Otherwise nothing is done and false is returned . |
21,775 | private boolean evaluateConditionFlags ( String flags ) { int p = 0 ; while ( true ) { p = skipBlanks ( flags , p ) ; if ( p >= flags . length ( ) ) { break ; } boolean complement = false ; if ( flags . charAt ( p ) == '!' ) { complement = true ; p ++ ; } p = skipBlanks ( flags , p ) ; if ( p >= flags . length ( ) ) { break ; } int p0 = p ; p = skipNonBlanks ( flags , p0 + 1 ) ; String flag = flags . substring ( p0 , p ) . toUpperCase ( ) ; if ( ( conditionFlags != null && conditionFlags . contains ( flag ) ) ^ complement ) { return true ; } } return false ; } | Returns true the condition is met . |
21,776 | private void associateVariablesWithBlocks ( ) { int varRefNo = 0 ; int activeBlockNo = 0 ; int nextBlockNo = 1 ; while ( varRefNo < varRefTabCnt ) { VarRefTabRec vrtr = varRefTab [ varRefNo ] ; int varRefTPos = vrtr . tPosBegin ; int varNo = vrtr . varNo ; if ( varRefTPos >= blockTab [ activeBlockNo ] . tPosEnd ) { activeBlockNo = blockTab [ activeBlockNo ] . parentBlockNo ; continue ; } if ( nextBlockNo < blockTabCnt && varRefTPos >= blockTab [ nextBlockNo ] . tPosBegin ) { activeBlockNo = nextBlockNo ; nextBlockNo ++ ; continue ; } BlockTabRec btr = blockTab [ activeBlockNo ] ; if ( varRefTPos < btr . tPosBegin ) { throw new AssertionError ( ) ; } int blockVarNo = btr . blockVarCnt ++ ; if ( btr . blockVarCnt > btr . blockVarNoToVarNoMap . length ) { btr . blockVarNoToVarNoMap = ( int [ ] ) resizeArray ( btr . blockVarNoToVarNoMap , 2 * btr . blockVarCnt ) ; } btr . blockVarNoToVarNoMap [ blockVarNo ] = varNo ; if ( btr . firstVarRefNo == - 1 ) { btr . firstVarRefNo = varRefNo ; } vrtr . blockNo = activeBlockNo ; vrtr . blockVarNo = blockVarNo ; varRefNo ++ ; } } | Associates variable references with blocks . |
21,777 | private int registerVariable ( String varName ) { int varNo = varTabCnt ++ ; if ( varTabCnt > varTab . length ) { varTab = ( String [ ] ) resizeArray ( varTab , 2 * varTabCnt ) ; } varTab [ varNo ] = varName ; varNameToNoMap . put ( varName . toUpperCase ( ) , new Integer ( varNo ) ) ; return varNo ; } | Returns the variable number of the newly registered variable . |
21,778 | public int lookupVariableName ( String varName ) { Integer varNoWrapper = varNameToNoMap . get ( varName . toUpperCase ( ) ) ; if ( varNoWrapper == null ) { return - 1 ; } int varNo = varNoWrapper . intValue ( ) ; return varNo ; } | Returns - 1 if the variable name is not found . |
21,779 | public int lookupBlockName ( String blockName ) { Integer blockNoWrapper = blockNameToNoMap . get ( blockName . toUpperCase ( ) ) ; if ( blockNoWrapper == null ) { return - 1 ; } int blockNo = blockNoWrapper . intValue ( ) ; return blockNo ; } | Returns - 1 if the block name is not found . |
21,780 | protected void initEncodeMethodTemplateVariable ( ) { Set < Integer > orders = new HashSet < Integer > ( ) ; for ( FieldInfo field : fields ) { boolean isList = field . isList ( ) ; if ( ! isList ) { checkType ( field . getFieldType ( ) , field . getField ( ) ) ; } if ( orders . contains ( field . getOrder ( ) ) ) { throw new IllegalArgumentException ( "Field order '" + field . getOrder ( ) + "' on field" + field . getField ( ) . getName ( ) + " already exsit." ) ; } FieldType fieldType = field . getFieldType ( ) ; String accessByField = getAccessByField ( "t" , field . getField ( ) , cls ) ; String fieldName = CodedConstant . getFieldName ( field . getOrder ( ) ) ; String encodeFieldType = CodedConstant . getFiledType ( fieldType , isList ) ; templator . setVariable ( "encodeFieldType" , encodeFieldType ) ; templator . setVariable ( "encodeFieldName" , fieldName ) ; templator . setVariable ( "encodeFieldGetter" , accessByField ) ; String writeValueToField = CodedConstant . getWriteValueToField ( fieldType , accessByField , isList ) ; templator . setVariable ( "writeValueToField" , writeValueToField ) ; if ( field . isRequired ( ) ) { templator . setVariableOpt ( "checkNull" , CodedConstant . getRequiredCheck ( field . getOrder ( ) , field . getField ( ) ) ) ; } else { templator . setVariable ( "checkNull" , "" ) ; } String calcSize = CodedConstant . getMappedTypeSize ( field , field . getOrder ( ) , field . getFieldType ( ) , isList , debug , outputPath ) ; templator . setVariable ( "calcSize" , calcSize ) ; String encodeWriteFieldValue = CodedConstant . getMappedWriteCode ( field , "output" , field . getOrder ( ) , field . getFieldType ( ) , isList ) ; templator . setVariable ( "encodeWriteFieldValue" , encodeWriteFieldValue ) ; templator . addBlock ( "encodeFields" ) ; } } | Inits the encode method template variable . |
21,781 | public static String getWriteValueToField ( FieldType type , String express , boolean isList ) { if ( ( type == FieldType . STRING || type == FieldType . BYTES ) && ! isList ) { String method = "copyFromUtf8" ; if ( type == FieldType . BYTES ) { method = "copyFrom" ; } return "com.google.protobuf.ByteString." + method + "(" + express + ")" ; } return express ; } | Gets the write value to field . |
21,782 | public static String getRequiredCheck ( int order , Field field ) { String fieldName = getFieldName ( order ) ; String code = "if (" + fieldName + "== null) {\n" ; code += "throw new UninitializedMessageException(CodedConstant.asList(\"" + field . getName ( ) + "\"))" + ClassCode . JAVA_LINE_BREAK ; code += "}\n" ; return code ; } | get required field check java expression . |
21,783 | public static String getEnumName ( Enum [ ] e , int value ) { if ( e != null ) { int toCompareValue ; for ( Enum en : e ) { if ( en instanceof EnumReadable ) { toCompareValue = ( ( EnumReadable ) en ) . value ( ) ; } else { toCompareValue = en . ordinal ( ) ; } if ( value == toCompareValue ) { return en . name ( ) ; } } } return "" ; } | Gets the enum name . |
21,784 | public static < T extends Enum < T > > T getEnumValue ( Class < T > enumType , String name ) { if ( StringUtils . isEmpty ( name ) ) { return null ; } try { T v = Enum . valueOf ( enumType , name ) ; return v ; } catch ( IllegalArgumentException e ) { return null ; } } | Gets the enumeration value . |
21,785 | private static List < Integer > convertList ( List < String > list ) { if ( list == null ) { return null ; } List < Integer > ret = new ArrayList < Integer > ( list . size ( ) ) ; for ( String v : list ) { ret . add ( StringUtils . toInt ( v ) ) ; } return ret ; } | Convert list . |
21,786 | private static boolean isStartWith ( String testString , String [ ] targetStrings ) { for ( String s : targetStrings ) { if ( testString . startsWith ( s ) ) { return true ; } } return false ; } | Checks if is start with . |
21,787 | private static Class getByClass ( String name ) { try { return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( name ) ; } catch ( Throwable e ) { } return null ; } | Gets the by class . |
21,788 | public static < K , V > MapEntryLite < K , V > newDefaultInstance ( WireFormat . FieldType keyType , K defaultKey , WireFormat . FieldType valueType , V defaultValue ) { return new MapEntryLite < K , V > ( keyType , defaultKey , valueType , defaultValue ) ; } | Creates a default MapEntryLite message instance . |
21,789 | static < K , V > void writeTo ( CodedOutputStream output , Metadata < K , V > metadata , K key , V value ) throws IOException { CodedConstant . writeElement ( output , metadata . keyType , KEY_FIELD_NUMBER , key ) ; CodedConstant . writeElement ( output , metadata . valueType , VALUE_FIELD_NUMBER , value ) ; } | Write to . |
21,790 | static < K , V > int computeSerializedSize ( Metadata < K , V > metadata , K key , V value ) { return CodedConstant . computeElementSize ( metadata . keyType , KEY_FIELD_NUMBER , key ) + CodedConstant . computeElementSize ( metadata . valueType , VALUE_FIELD_NUMBER , value ) ; } | Compute serialized size . |
21,791 | @ SuppressWarnings ( "unchecked" ) static < T > T parseField ( CodedInputStream input , ExtensionRegistryLite extensionRegistry , WireFormat . FieldType type , T value ) throws IOException { switch ( type ) { case MESSAGE : int length = input . readRawVarint32 ( ) ; final int oldLimit = input . pushLimit ( length ) ; Codec < ? extends Object > codec = ProtobufProxy . create ( value . getClass ( ) ) ; T ret = ( T ) codec . decode ( input . readRawBytes ( length ) ) ; input . popLimit ( oldLimit ) ; return ret ; case ENUM : return ( T ) ( java . lang . Integer ) input . readEnum ( ) ; case GROUP : throw new RuntimeException ( "Groups are not allowed in maps." ) ; default : return ( T ) CodedConstant . readPrimitiveField ( input , type , true ) ; } } | Parses the field . |
21,792 | static < K , V > Map . Entry < K , V > parseEntry ( CodedInputStream input , Metadata < K , V > metadata , ExtensionRegistryLite extensionRegistry ) throws IOException { K key = metadata . defaultKey ; V value = metadata . defaultValue ; while ( true ) { int tag = input . readTag ( ) ; if ( tag == 0 ) { break ; } if ( tag == CodedConstant . makeTag ( KEY_FIELD_NUMBER , metadata . keyType . getWireType ( ) ) ) { key = parseField ( input , extensionRegistry , metadata . keyType , key ) ; } else if ( tag == CodedConstant . makeTag ( VALUE_FIELD_NUMBER , metadata . valueType . getWireType ( ) ) ) { value = parseField ( input , extensionRegistry , metadata . valueType , value ) ; } else { if ( ! input . skipField ( tag ) ) { break ; } } } return new AbstractMap . SimpleImmutableEntry < K , V > ( key , value ) ; } | Parses the entry . |
21,793 | public IDLProxyObject newInstnace ( ) { try { Object object = cls . newInstance ( ) ; return new IDLProxyObject ( codec , object , cls ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } } | New instnace . |
21,794 | private IDLProxyObject doSetFieldValue ( String fullField , String field , Object value , Object object , boolean useCache , Map < String , ReflectInfo > cachedFields ) { Field f ; if ( useCache ) { ReflectInfo info = cachedFields . get ( fullField ) ; if ( info != null ) { setField ( value , info . target , info . field ) ; return this ; } } int index = field . indexOf ( '.' ) ; if ( index != - 1 ) { String parent = field . substring ( 0 , index ) ; String sub = field . substring ( index + 1 ) ; try { f = FieldUtils . findField ( object . getClass ( ) , parent ) ; if ( f == null ) { throw new RuntimeException ( "No field '" + parent + "' found at class " + object . getClass ( ) . getName ( ) ) ; } Class < ? > type = f . getType ( ) ; f . setAccessible ( true ) ; Object o = f . get ( object ) ; if ( o == null ) { boolean memberClass = type . isMemberClass ( ) ; if ( memberClass && Modifier . isStatic ( type . getModifiers ( ) ) ) { Constructor < ? > constructor = type . getConstructor ( new Class [ 0 ] ) ; constructor . setAccessible ( true ) ; o = constructor . newInstance ( new Object [ 0 ] ) ; } else if ( memberClass ) { Constructor < ? > constructor = type . getConstructor ( new Class [ ] { object . getClass ( ) } ) ; constructor . setAccessible ( true ) ; o = constructor . newInstance ( new Object [ ] { object } ) ; } else { o = type . newInstance ( ) ; } f . set ( object , o ) ; } return put ( fullField , sub , value , o ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } } f = FieldUtils . findField ( object . getClass ( ) , field ) ; if ( f == null ) { throw new RuntimeException ( "No field '" + field + "' found at class " + object . getClass ( ) . getName ( ) ) ; } if ( useCache && ! cachedFields . containsKey ( fullField ) ) { cachedFields . put ( fullField , new ReflectInfo ( f , object ) ) ; } setField ( value , object , f ) ; return this ; } | Do set field value . |
21,795 | private void setSystemProperties ( ) { if ( systemProperties != null ) { originalSystemProperties = System . getProperties ( ) ; for ( Property systemProperty : systemProperties ) { String value = systemProperty . getValue ( ) ; System . setProperty ( systemProperty . getKey ( ) , value == null ? "" : value ) ; } } } | Pass any given system properties to the java system properties . |
21,796 | private Artifact getExecutablePomArtifact ( Artifact executableArtifact ) { return this . artifactFactory . createBuildArtifact ( executableArtifact . getGroupId ( ) , executableArtifact . getArtifactId ( ) , executableArtifact . getVersion ( ) , "pom" ) ; } | Get the artifact which refers to the POM of the executable artifact . |
21,797 | private void waitFor ( long millis ) { Object lock = new Object ( ) ; synchronized ( lock ) { try { lock . wait ( millis ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; getLog ( ) . warn ( "Spuriously interrupted while waiting for " + millis + "ms" , e ) ; } } } | Stop program execution for nn millis . |
21,798 | private static List < Class < ? > > createMessageClass ( ProtoFile protoFile , boolean multi , boolean debug , boolean generateSouceOnly , File sourceOutputDir , List < CodeDependent > cds , Set < String > compiledClass , Set < String > enumNames , Set < String > packages , Map < String , String > mappedUniName , boolean isUniName ) { List < Type > types = protoFile . getTypes ( ) ; if ( types == null || types . isEmpty ( ) ) { throw new RuntimeException ( "No message defined in '.proto' IDL" ) ; } int count = 0 ; Iterator < Type > iter = types . iterator ( ) ; while ( iter . hasNext ( ) ) { Type next = iter . next ( ) ; if ( next instanceof EnumType ) { continue ; } count ++ ; } if ( ! multi && count != 1 ) { throw new RuntimeException ( "Only one message defined allowed in '.proto' IDL" ) ; } List < Class < ? > > ret = new ArrayList < Class < ? > > ( types . size ( ) ) ; List < MessageType > messageTypes = new ArrayList < MessageType > ( ) ; for ( Type type : types ) { Class checkClass = checkClass ( protoFile , type , mappedUniName , isUniName ) ; if ( checkClass != null ) { ret . add ( checkClass ) ; continue ; } CodeDependent cd ; if ( type instanceof MessageType ) { messageTypes . add ( ( MessageType ) type ) ; continue ; } } for ( MessageType mt : messageTypes ) { CodeDependent cd ; cd = createCodeByType ( protoFile , ( MessageType ) mt , enumNames , true , new ArrayList < Type > ( ) , cds , packages , mappedUniName , isUniName ) ; if ( cd . isDepndency ( ) ) { cds . add ( cd ) ; } else { cds . add ( 0 , cd ) ; } } CodeDependent codeDependent ; List < CodeDependent > copiedCds = new ArrayList < ProtobufIDLProxy . CodeDependent > ( cds ) ; while ( ( codeDependent = hasDependency ( copiedCds , compiledClass ) ) != null ) { if ( debug ) { CodePrinter . printCode ( codeDependent . code , "generate jprotobuf code" ) ; } if ( ! generateSouceOnly ) { Class < ? > newClass = JDKCompilerHelper . getJdkCompiler ( ) . compile ( codeDependent . getClassName ( ) , codeDependent . code , ProtobufIDLProxy . class . getClassLoader ( ) , null , - 1 ) ; ret . add ( newClass ) ; } else { writeSourceCode ( codeDependent , sourceOutputDir ) ; } } return ret ; } | Creates the message class . |
21,799 | private static Map < String , IDLProxyObject > doCreate ( ProtoFile protoFile , boolean multi , boolean debug , File path , boolean generateSouceOnly , File sourceOutputDir , List < CodeDependent > cds , Map < String , String > uniMappedName , boolean isUniName ) throws IOException { return doCreatePro ( Arrays . asList ( protoFile ) , multi , debug , path , generateSouceOnly , sourceOutputDir , cds , new HashSet < String > ( ) , uniMappedName , isUniName ) ; } | Do create . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.