idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
9,500 | public static void executeDatabaseScript ( String script ) throws SQLException , MalformedURLException { File file = new File ( script ) ; DatabaseUtils . executeSqlScript ( DatabaseUtils . getDBConnection ( null ) , file . toURI ( ) . toURL ( ) ) ; } | Executes database script from resources directory |
9,501 | private static void executeSqlScript ( Connection connection , URL scriptUrl ) throws SQLException { for ( String sqlStatement : readSqlStatements ( scriptUrl ) ) { if ( ! sqlStatement . trim ( ) . isEmpty ( ) ) { connection . prepareStatement ( sqlStatement ) . executeUpdate ( ) ; } } } | Executes SQL script . |
9,502 | private static String [ ] readSqlStatements ( URL url ) { try { char buffer [ ] = new char [ 256 ] ; StringBuilder result = new StringBuilder ( ) ; InputStreamReader reader = new InputStreamReader ( url . openStream ( ) , "UTF-8" ) ; while ( true ) { int count = reader . read ( buffer ) ; if ( count < 0 ) { break ; } result . append ( buffer , 0 , count ) ; } return result . toString ( ) . split ( ";" ) ; } catch ( IOException ex ) { throw new RuntimeException ( "Cannot read " + url , ex ) ; } } | Reads SQL statements from file . SQL commands in file must be separated by a semicolon . |
9,503 | public void call ( Message mesg , String interactionId , String btxnName ) { boolean activated = collector . session ( ) . activate ( uri , null , interactionId ) ; if ( activated ) { collector . consumerStart ( null , uri , "Test" , null , interactionId ) ; collector . setTransaction ( null , btxnName ) ; } if ( calledServices != null ) { String calledServiceName = calledServices . get ( mesg . getType ( ) ) ; synchronized ( this ) { try { wait ( ( ( int ) Math . random ( ) % 300 ) + 50 ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( calledServiceName != null ) { Service calledService = registry . getServiceInstance ( calledServiceName ) ; String nextInteractionId = UUID . randomUUID ( ) . toString ( ) ; if ( activated ) { collector . producerStart ( null , calledService . getUri ( ) , "Test" , null , nextInteractionId ) ; } synchronized ( this ) { try { wait ( ( ( int ) Math . random ( ) % 100 ) + 10 ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } calledService . call ( mesg , nextInteractionId , collector . getTransaction ( ) ) ; if ( activated ) { collector . producerEnd ( null , calledService . getUri ( ) , "Test" , null ) ; } } } if ( activated ) { collector . consumerEnd ( null , uri , "Test" , null ) ; } setLastUsed ( System . currentTimeMillis ( ) ) ; registry . returnServiceInstance ( this ) ; } | This method simulates calling the service . |
9,504 | public Node addInteractionCorrelationId ( String id ) { this . correlationIds . add ( new CorrelationIdentifier ( Scope . Interaction , id ) ) ; return this ; } | This method adds an interaction scoped correlation id . |
9,505 | public Node addControlFlowCorrelationId ( String id ) { this . correlationIds . add ( new CorrelationIdentifier ( Scope . ControlFlow , id ) ) ; return this ; } | This method adds a control flow scoped correlation id . |
9,506 | public Node addCausedByCorrelationId ( String id ) { this . correlationIds . add ( new CorrelationIdentifier ( Scope . CausedBy , id ) ) ; return this ; } | This method adds a caused by scoped correlation id . |
9,507 | protected void findCorrelatedNodes ( CorrelationIdentifier cid , Set < Node > nodes ) { if ( isCorrelated ( cid ) ) { nodes . add ( this ) ; } } | This method identifies all of the nodes within a trace that are associated with the supplied correlation identifier . |
9,508 | protected boolean isCorrelated ( CorrelationIdentifier cid ) { for ( CorrelationIdentifier id : correlationIds ) { if ( id . equals ( cid ) ) { return true ; } } return false ; } | This method determines whether the node is correlated to the supplied identifier . |
9,509 | protected static List < EndpointInfo > compressEndpointInfo ( List < EndpointInfo > endpoints ) { List < EndpointInfo > others = new ArrayList < EndpointInfo > ( ) ; EndpointPart rootPart = new EndpointPart ( ) ; for ( int i = 0 ; i < endpoints . size ( ) ; i ++ ) { EndpointInfo endpoint = endpoints . get ( i ) ; if ( endpoint . getEndpoint ( ) != null && endpoint . getEndpoint ( ) . length ( ) > 1 && endpoint . getEndpoint ( ) . charAt ( 0 ) == '/' ) { String [ ] parts = endpoint . getEndpoint ( ) . split ( "/" ) ; buildTree ( rootPart , parts , 1 , endpoint . getType ( ) ) ; } else { others . add ( new EndpointInfo ( endpoint ) ) ; } } List < EndpointInfo > info = null ; if ( endpoints . size ( ) != others . size ( ) ) { rootPart . collapse ( ) ; info = extractEndpointInfo ( rootPart ) ; info . addAll ( others ) ; } else { info = others ; } initEndpointInfo ( info ) ; return info ; } | This method compresses the list of endpoints to identify common patterns . |
9,510 | protected static void buildTree ( EndpointPart parent , String [ ] parts , int index , String endpointType ) { String name = parts [ index ] ; String qualifier = null ; if ( index == parts . length - 1 ) { qualifier = EndpointUtil . decodeEndpointOperation ( parts [ index ] , false ) ; name = EndpointUtil . decodeEndpointURI ( parts [ index ] ) ; } EndpointPart child = parent . addChild ( name ) ; if ( index < parts . length - 1 ) { buildTree ( child , parts , index + 1 , endpointType ) ; } else { if ( qualifier != null ) { child = child . addChild ( qualifier ) ; child . setQualifier ( true ) ; } child . setEndpointType ( endpointType ) ; } } | This method builds a tree . |
9,511 | protected static List < EndpointInfo > extractEndpointInfo ( EndpointPart root ) { List < EndpointInfo > endpoints = new ArrayList < EndpointInfo > ( ) ; root . extractEndpointInfo ( endpoints , "" ) ; return endpoints ; } | This method expands a tree into the collapsed set of endpoints . |
9,512 | protected static void initEndpointInfo ( List < EndpointInfo > endpoints ) { for ( int i = 0 ; i < endpoints . size ( ) ; i ++ ) { initEndpointInfo ( endpoints . get ( i ) ) ; } } | This method initialises the list of endpoint information . |
9,513 | protected static void initEndpointInfo ( EndpointInfo endpoint ) { endpoint . setRegex ( createRegex ( endpoint . getEndpoint ( ) , endpoint . metaURI ( ) ) ) ; String uri = EndpointUtil . decodeEndpointURI ( endpoint . getEndpoint ( ) ) ; if ( uri != null ) { endpoint . setUriRegex ( createRegex ( uri , endpoint . metaURI ( ) ) ) ; } if ( uri != null && endpoint . metaURI ( ) ) { StringBuilder template = new StringBuilder ( ) ; String [ ] parts = uri . split ( "/" ) ; String part = null ; int paramNo = 1 ; for ( int j = 1 ; j < parts . length ; j ++ ) { template . append ( "/" ) ; if ( parts [ j ] . equals ( "*" ) ) { if ( part == null ) { template . append ( "{" ) ; template . append ( "param" ) ; template . append ( paramNo ++ ) ; template . append ( "}" ) ; } else { if ( part . length ( ) > 1 && part . charAt ( part . length ( ) - 1 ) == 's' ) { part = part . substring ( 0 , part . length ( ) - 1 ) ; } template . append ( "{" ) ; template . append ( part ) ; template . append ( "Id}" ) ; } part = null ; } else { part = parts [ j ] ; template . append ( part ) ; } } endpoint . setUriTemplate ( template . toString ( ) ) ; } } | This method initialises the endpoint information . |
9,514 | protected static boolean hasMetrics ( CommunicationSummaryStatistics css ) { if ( css . getCount ( ) > 0 ) { return true ; } for ( ConnectionStatistics cs : css . getOutbound ( ) . values ( ) ) { if ( cs . getCount ( ) > 0 ) { return true ; } if ( cs . getNode ( ) != null ) { if ( hasMetrics ( cs . getNode ( ) ) ) { return true ; } } } return false ; } | This method determines whether the communication summary statistics have defined metrics . |
9,515 | protected List < EndpointInfo > doGetUnboundEndpoints ( String tenantId , List < Trace > fragments , boolean compress ) { List < EndpointInfo > ret = new ArrayList < EndpointInfo > ( ) ; Map < String , EndpointInfo > map = new HashMap < String , EndpointInfo > ( ) ; for ( int i = 0 ; i < fragments . size ( ) ; i ++ ) { Trace trace = fragments . get ( i ) ; if ( trace . initialFragment ( ) && ! trace . getNodes ( ) . isEmpty ( ) && trace . getTransaction ( ) == null ) { if ( trace . getNodes ( ) . get ( 0 ) instanceof Consumer ) { Consumer consumer = ( Consumer ) trace . getNodes ( ) . get ( 0 ) ; String endpoint = EndpointUtil . encodeEndpoint ( consumer . getUri ( ) , consumer . getOperation ( ) ) ; if ( ! map . containsKey ( endpoint ) && consumer . getProperties ( Constants . PROP_FAULT ) . isEmpty ( ) ) { EndpointInfo info = new EndpointInfo ( ) ; info . setEndpoint ( endpoint ) ; info . setType ( consumer . getEndpointType ( ) ) ; ret . add ( info ) ; map . put ( endpoint , info ) ; } } else { obtainProducerEndpoints ( trace . getNodes ( ) , ret , map ) ; } } } if ( configService != null ) { Map < String , TransactionConfig > configs = configService . getTransactions ( tenantId , 0 ) ; for ( TransactionConfig config : configs . values ( ) ) { if ( config . getFilter ( ) != null && config . getFilter ( ) . getInclusions ( ) != null ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Remove unbound URIs associated with btxn config=" + config ) ; } for ( String filter : config . getFilter ( ) . getInclusions ( ) ) { if ( filter != null && ! filter . trim ( ) . isEmpty ( ) ) { Iterator < EndpointInfo > iter = ret . iterator ( ) ; while ( iter . hasNext ( ) ) { EndpointInfo info = iter . next ( ) ; if ( Pattern . matches ( filter , info . getEndpoint ( ) ) ) { iter . remove ( ) ; } } } } } } } if ( compress ) { ret = compressEndpointInfo ( ret ) ; } Collections . sort ( ret , new Comparator < EndpointInfo > ( ) { public int compare ( EndpointInfo arg0 , EndpointInfo arg1 ) { return arg0 . getEndpoint ( ) . compareTo ( arg1 . getEndpoint ( ) ) ; } } ) ; return ret ; } | This method obtains the unbound endpoints from a list of trace fragments . |
9,516 | protected void obtainEndpoints ( List < Node > nodes , List < EndpointInfo > endpoints ) { for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { Node node = nodes . get ( i ) ; if ( node . getUri ( ) != null ) { EndpointInfo ei = new EndpointInfo ( ) ; ei . setEndpoint ( EndpointUtil . encodeEndpoint ( node . getUri ( ) , node . getOperation ( ) ) ) ; if ( ! endpoints . contains ( ei ) ) { initEndpointInfo ( ei ) ; endpoints . add ( ei ) ; } } if ( node instanceof ContainerNode ) { obtainEndpoints ( ( ( ContainerNode ) node ) . getNodes ( ) , endpoints ) ; } } } | This method collects the information regarding endpoints . |
9,517 | protected void obtainProducerEndpoints ( List < Node > nodes , List < EndpointInfo > endpoints , Map < String , EndpointInfo > map ) { for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { Node node = nodes . get ( i ) ; if ( node instanceof Producer ) { String endpoint = EndpointUtil . encodeEndpoint ( node . getUri ( ) , node . getOperation ( ) ) ; if ( ! map . containsKey ( endpoint ) ) { EndpointInfo info = new EndpointInfo ( ) ; info . setEndpoint ( endpoint ) ; info . setType ( ( ( Producer ) node ) . getEndpointType ( ) ) ; endpoints . add ( info ) ; map . put ( endpoint , info ) ; } } if ( node instanceof ContainerNode ) { obtainProducerEndpoints ( ( ( ContainerNode ) node ) . getNodes ( ) , endpoints , map ) ; } } } | This method collects the information regarding endpoints for contained producers . |
9,518 | protected static String createRegex ( String endpoint , boolean meta ) { StringBuilder regex = new StringBuilder ( ) ; regex . append ( '^' ) ; for ( int i = 0 ; i < endpoint . length ( ) ; i ++ ) { char ch = endpoint . charAt ( i ) ; if ( "*" . indexOf ( ch ) != - 1 ) { regex . append ( '.' ) ; } else if ( "\\.^$|?+[]{}()" . indexOf ( ch ) != - 1 ) { regex . append ( '\\' ) ; } regex . append ( ch ) ; } regex . append ( '$' ) ; return regex . toString ( ) ; } | This method derives the regular expression from the supplied URI . |
9,519 | protected boolean processQueryParameters ( Trace trace , Node node ) { boolean ret = false ; Set < Property > queryString = node . getProperties ( Constants . PROP_HTTP_QUERY ) ; if ( ! queryString . isEmpty ( ) ) { StringTokenizer st = new StringTokenizer ( queryString . iterator ( ) . next ( ) . getValue ( ) , "&" ) ; while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) ; String [ ] namevalue = token . split ( "=" ) ; if ( namevalue . length == 2 ) { if ( queryParameters . contains ( namevalue [ 0 ] ) ) { try { node . getProperties ( ) . add ( new Property ( namevalue [ 0 ] , URLDecoder . decode ( namevalue [ 1 ] , "UTF-8" ) ) ) ; ret = true ; } catch ( UnsupportedEncodingException e ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Failed to decode value '" + namevalue [ 1 ] + "': " + e ) ; } } } else if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Ignoring query parameter '" + namevalue [ 0 ] + "'" ) ; } } else if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Query string part does not include name/value pair: " + token ) ; } } } return ret ; } | This method processes the query parameters associated with the supplied node to extract templated named values as properties on the trace node . |
9,520 | public boolean multipleConsumers ( ) { Set < Property > props = getProperties ( Producer . PROPERTY_PUBLISH ) ; return ! props . isEmpty ( ) && props . iterator ( ) . next ( ) . getValue ( ) . equalsIgnoreCase ( Boolean . TRUE . toString ( ) ) ; } | This method determines whether the interaction node is associated with a multi - consumer communication . |
9,521 | protected String getValue ( Trace trace , Node node , Direction direction , Map < String , ? > headers , Object [ ] values ) { if ( expression != null ) { return expression . evaluate ( trace , node , direction , headers , values ) ; } return null ; } | This method returns the value associated with the expression for the supplied data . |
9,522 | public void startSpanWithParent ( SpanBuilder spanBuilder , Span parent , String id ) { if ( parent != null ) { spanBuilder . asChildOf ( parent . context ( ) ) ; } doStartSpan ( spanBuilder , id ) ; } | This is a convenience method for situations where we don t know if a parent span is available . If we try to add a childOf relationship to a null parent it would cause a null pointer exception . |
9,523 | public void startSpanWithContext ( SpanBuilder spanBuilder , SpanContext context , String id ) { if ( context != null ) { spanBuilder . asChildOf ( context ) ; } doStartSpan ( spanBuilder , id ) ; } | This is a convenience method for situations where we don t know if a parent span is available . If we try to add a childOf relationship to a null context it would cause a null pointer exception . |
9,524 | public boolean hasSpanWithId ( String id ) { TraceState ts = traceState . get ( ) ; if ( id != null && ts != null ) { boolean spanFound = ts . getSpanForId ( id ) != null ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Has span with id = " + id + "? " + spanFound ) ; } return spanFound ; } return false ; } | This method determines whether there is a span available associated with the supplied id . |
9,525 | public boolean isCurrentSpan ( String id ) { TraceState ts = traceState . get ( ) ; if ( id != null && ts != null ) { boolean spanFound = ts . peekId ( ) . equals ( id ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Is current span id = " + id + "? " + spanFound ) ; } return spanFound ; } return false ; } | This method determines whether the current span is associated with the supplied id . |
9,526 | public Span getSpan ( ) { TraceState ts = traceState . get ( ) ; if ( ts != null ) { Span span = ts . peekSpan ( ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Get span = " + span + " trace state = " + ts ) ; } return span ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Get span requested, but no trace state" ) ; } return null ; } | This method retrieves the current span if available . |
9,527 | public void suspend ( String id ) { TraceState ts = traceState . get ( ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Suspend trace state = " + ts + " id = " + id ) ; } if ( ts != null ) { setExpire ( ts ) ; try { suspendedStateLock . lock ( ) ; if ( suspendedState . containsKey ( id ) && log . isLoggable ( Level . FINEST ) ) { log . finest ( "WARNING: Overwriting previous suspended trace state = " + suspendedState . get ( id ) + " id = " + id ) ; } suspendedState . put ( id , ts ) ; traceState . remove ( ) ; } finally { suspendedStateLock . unlock ( ) ; } } } | This method suspends any current trace state associated with this thread and associates it with the supplied id . This state can then be re - activated using the resume method . |
9,528 | public void resume ( String id ) { try { suspendedStateLock . lock ( ) ; TraceState ts = suspendedState . get ( id ) ; if ( ts != null ) { clearExpire ( ts ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Resume trace state = " + ts + " id = " + id ) ; } if ( traceState . get ( ) != null && log . isLoggable ( Level . FINEST ) ) { log . finest ( "WARNING: Overwriting previous trace state = " + traceState . get ( ) ) ; } traceState . set ( ts ) ; suspendedState . remove ( id ) ; } } finally { suspendedStateLock . unlock ( ) ; } } | This method attempts to resume a previously suspended trace state associated with the supplied id . When resumed the trace state is associated with the current thread . |
9,529 | public boolean includePath ( String path ) { if ( path . startsWith ( "/hawkular/apm" ) ) { return false ; } int dotPos = path . lastIndexOf ( '.' ) ; int slashPos = path . lastIndexOf ( '/' ) ; if ( dotPos <= slashPos ) { return true ; } if ( ! fileExtensionWhitelist . isEmpty ( ) ) { String extension = path . substring ( dotPos + 1 ) ; if ( fileExtensionWhitelist . contains ( extension ) ) { if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Path " + path + " not skipped, because of whitelist" ) ; } return true ; } } if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Path " + path + " skipped" ) ; } return false ; } | This method determines if the supplied path should be monitored . |
9,530 | public String sanitizePaths ( String baseUri , String resourcePath ) { if ( baseUri . endsWith ( "/" ) && resourcePath . startsWith ( "/" ) ) { return baseUri . substring ( 0 , baseUri . length ( ) - 1 ) + resourcePath ; } if ( ( ! baseUri . endsWith ( "/" ) ) && ( ! resourcePath . startsWith ( "/" ) ) ) { return baseUri + "/" + resourcePath ; } return baseUri + resourcePath ; } | Helper to remove duplicate slashes |
9,531 | public static String serialize ( Object data ) { String ret = null ; if ( data != null ) { if ( data . getClass ( ) == String . class ) { ret = ( String ) data ; } else if ( data instanceof byte [ ] ) { ret = new String ( ( byte [ ] ) data ) ; } else { try { ret = mapper . writeValueAsString ( data ) ; } catch ( JsonProcessingException e ) { if ( log . isLoggable ( Level . FINEST ) ) { log . log ( Level . FINEST , "Failed to serialize object into json" , e ) ; } } } } } | This method serializes the supplied object to a JSON document . |
9,532 | public static void initialiseLinks ( TraceCompletionInformation ci , long fragmentBaseTime , Node n , StringBuilder nodeId ) { TraceCompletionInformation . Communication c = new TraceCompletionInformation . Communication ( ) ; c . getIds ( ) . add ( nodeId . toString ( ) ) ; c . setMultipleConsumers ( true ) ; c . setBaseDuration ( n . getTimestamp ( ) - fragmentBaseTime ) ; c . setExpire ( System . currentTimeMillis ( ) + TraceCompletionInformation . Communication . DEFAULT_EXPIRY_WINDOW_MILLIS ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Adding communication to completion information: ci=" + ci + " comms=" + c ) ; } ci . getCommunications ( ) . add ( c ) ; if ( n . getClass ( ) == Producer . class ) { List < CorrelationIdentifier > cids = n . findCorrelationIds ( Scope . Interaction , Scope . ControlFlow ) ; if ( ! cids . isEmpty ( ) ) { c = new TraceCompletionInformation . Communication ( ) ; for ( int i = 0 ; i < cids . size ( ) ; i ++ ) { c . getIds ( ) . add ( cids . get ( i ) . getValue ( ) ) ; } c . setMultipleConsumers ( ( ( Producer ) n ) . multipleConsumers ( ) ) ; c . setBaseDuration ( n . getTimestamp ( ) - fragmentBaseTime ) ; c . setExpire ( System . currentTimeMillis ( ) + TraceCompletionInformation . Communication . DEFAULT_EXPIRY_WINDOW_MILLIS ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Adding communication to completion information: ci=" + ci + " comms=" + c ) ; } ci . getCommunications ( ) . add ( c ) ; } } else if ( n . containerNode ( ) ) { ContainerNode cn = ( ContainerNode ) n ; for ( int i = 0 ; i < cn . getNodes ( ) . size ( ) ; i ++ ) { int len = nodeId . length ( ) ; nodeId . append ( ':' ) ; nodeId . append ( i ) ; initialiseLinks ( ci , fragmentBaseTime , cn . getNodes ( ) . get ( i ) , nodeId ) ; nodeId . delete ( len , nodeId . length ( ) ) ; } } } | This method initialises the completion time information for a trace instance . |
9,533 | public static synchronized ElasticsearchClient getSingleton ( ) { if ( singleton == null ) { singleton = new ElasticsearchClient ( ) ; try { singleton . init ( ) ; } catch ( Exception e ) { log . log ( Level . SEVERE , "Failed to initialise Elasticsearch client" , e ) ; } } return singleton ; } | This method explicit instantiates the singleton . For use outside a CDI environment . |
9,534 | @ SuppressWarnings ( "unchecked" ) private boolean prepareMapping ( String index , Map < String , Object > defaultMappings ) { boolean success = true ; for ( Map . Entry < String , Object > stringObjectEntry : defaultMappings . entrySet ( ) ) { Map < String , Object > mapping = ( Map < String , Object > ) stringObjectEntry . getValue ( ) ; if ( mapping == null ) { throw new RuntimeException ( "type mapping not defined" ) ; } PutMappingRequestBuilder putMappingRequestBuilder = client . admin ( ) . indices ( ) . preparePutMapping ( ) . setIndices ( index ) ; putMappingRequestBuilder . setType ( stringObjectEntry . getKey ( ) ) ; putMappingRequestBuilder . setSource ( mapping ) ; if ( log . isLoggable ( Level . FINE ) ) { log . fine ( "Elasticsearch create mapping for index '" + index + " and type '" + stringObjectEntry . getKey ( ) + "': " + mapping ) ; } PutMappingResponse resp = putMappingRequestBuilder . execute ( ) . actionGet ( ) ; if ( resp . isAcknowledged ( ) ) { if ( log . isLoggable ( Level . FINE ) ) { log . fine ( "Elasticsearch mapping for index '" + index + " and type '" + stringObjectEntry . getKey ( ) + "' was acknowledged" ) ; } } else { success = false ; log . warning ( "Elasticsearch mapping creation was not acknowledged for index '" + index + " and type '" + stringObjectEntry . getKey ( ) + "'" ) ; } } return success ; } | This method applies the supplied mapping to the index . |
9,535 | private boolean createIndex ( String index , Map < String , Object > defaultSettings ) { IndicesExistsResponse res = client . admin ( ) . indices ( ) . prepareExists ( index ) . execute ( ) . actionGet ( ) ; boolean created = false ; if ( ! res . isExists ( ) ) { CreateIndexRequestBuilder req = client . admin ( ) . indices ( ) . prepareCreate ( index ) ; req . setSettings ( defaultSettings ) ; created = req . execute ( ) . actionGet ( ) . isAcknowledged ( ) ; if ( ! created ) { throw new RuntimeException ( "Could not create index [" + index + "]" ) ; } } return created ; } | Check if index is created . if not it will created it |
9,536 | private void determineHostsAsProperty ( ) { if ( hosts . startsWith ( "${" ) && hosts . endsWith ( "}" ) ) { String hostsProperty = hosts . substring ( 2 , hosts . length ( ) - 1 ) ; hosts = PropertyUtil . getProperty ( hostsProperty ) ; if ( hosts == null ) { throw new IllegalArgumentException ( "Could not find property '" + hostsProperty + "'" ) ; } } } | sets hosts if the _hosts propertey is determined to be a property placeholder Throws IllegalArgumentException argument exception when nothing found |
9,537 | public void clearTenant ( String tenantId ) { String index = getIndex ( tenantId ) ; synchronized ( knownIndices ) { IndicesAdminClient indices = client . admin ( ) . indices ( ) ; boolean indexExists = indices . prepareExists ( index ) . execute ( ) . actionGet ( ) . isExists ( ) ; if ( indexExists ) { indices . prepareDelete ( index ) . execute ( ) . actionGet ( ) ; } knownIndices . remove ( index ) ; } } | Removes all data associated with tenant . |
9,538 | public void close ( ) { if ( node != null ) { node . close ( ) ; } if ( client != null ) { client . close ( ) ; client = null ; } } | This method closes the Elasticsearch client . |
9,539 | public static CompletionTime spanToCompletionTime ( SpanCache spanCache , Span span ) { CompletionTime completionTime = new CompletionTime ( ) ; completionTime . setId ( span . getId ( ) ) ; if ( span . getTimestamp ( ) != null ) { completionTime . setTimestamp ( span . getTimestamp ( ) ) ; } if ( span . getDuration ( ) != null ) { completionTime . setDuration ( span . getDuration ( ) ) ; } completionTime . setOperation ( SpanDeriverUtil . deriveOperation ( span ) ) ; completionTime . getProperties ( ) . add ( new Property ( Constants . PROP_FAULT , SpanDeriverUtil . deriveFault ( span ) ) ) ; completionTime . setHostAddress ( span . ipv4 ( ) ) ; if ( span . service ( ) != null ) { completionTime . getProperties ( ) . add ( new Property ( Constants . PROP_SERVICE_NAME , span . service ( ) ) ) ; } URL url = getUrl ( spanCache , span ) ; if ( url == null && span . serverSpan ( ) && spanCache . get ( null , SpanUniqueIdGenerator . getClientId ( span . getId ( ) ) ) != null ) { return null ; } if ( url != null ) { String uri = span . clientSpan ( ) ? EndpointUtil . encodeClientURI ( url . getPath ( ) ) : url . getPath ( ) ; completionTime . setUri ( uri ) ; completionTime . setEndpointType ( url . getProtocol ( ) == null ? null : url . getProtocol ( ) . toUpperCase ( ) ) ; } else { completionTime . setEndpointType ( "Unknown" ) ; } completionTime . getProperties ( ) . addAll ( span . binaryAnnotationMapping ( ) . getProperties ( ) ) ; return completionTime ; } | Convert span to CompletionTime object |
9,540 | protected static void initialiseOutbound ( Node n , long baseTime , CommunicationDetails cd , StringBuilder nodeId ) { CommunicationDetails . Outbound ob = new CommunicationDetails . Outbound ( ) ; ob . getLinkIds ( ) . add ( nodeId . toString ( ) ) ; ob . setMultiConsumer ( true ) ; ob . setProducerOffset ( n . getTimestamp ( ) - baseTime ) ; cd . getOutbound ( ) . add ( ob ) ; if ( n . getClass ( ) == Producer . class ) { ob = new CommunicationDetails . Outbound ( ) ; for ( int j = 0 ; j < n . getCorrelationIds ( ) . size ( ) ; j ++ ) { CorrelationIdentifier ci = n . getCorrelationIds ( ) . get ( j ) ; if ( ci . getScope ( ) == Scope . Interaction || ci . getScope ( ) == Scope . ControlFlow ) { ob . getLinkIds ( ) . add ( ci . getValue ( ) ) ; } } if ( ! ob . getLinkIds ( ) . isEmpty ( ) ) { ob . setMultiConsumer ( ( ( Producer ) n ) . multipleConsumers ( ) ) ; ob . setProducerOffset ( n . getTimestamp ( ) - baseTime ) ; cd . getOutbound ( ) . add ( ob ) ; } } else if ( n . containerNode ( ) ) { for ( int i = 0 ; i < ( ( ContainerNode ) n ) . getNodes ( ) . size ( ) ; i ++ ) { int len = nodeId . length ( ) ; nodeId . append ( ':' ) ; nodeId . append ( i ) ; initialiseOutbound ( ( ( ContainerNode ) n ) . getNodes ( ) . get ( i ) , baseTime , cd , nodeId ) ; nodeId . delete ( len , nodeId . length ( ) ) ; } } } | This method initialises the outbound information from the consumer s nodes in the supplied communication details . |
9,541 | public static FilterBuilder buildFilter ( Criteria criteria ) { if ( criteria . getTransaction ( ) != null && criteria . getTransaction ( ) . trim ( ) . isEmpty ( ) ) { return FilterBuilders . missingFilter ( TRANSACTION_FIELD ) ; } return null ; } | This method returns a filter associated with the supplied criteria . |
9,542 | public static long toMicros ( Instant instant ) { return TimeUnit . SECONDS . toMicros ( instant . getEpochSecond ( ) ) + TimeUnit . NANOSECONDS . toMicros ( instant . getNano ( ) ) ; } | This method returns the timestamp associated with the supplied instant in microseconds . |
9,543 | public String getProperty ( String name , String def ) { String ret = PropertyUtil . getProperty ( name , null ) ; if ( ret == null ) { if ( getProperties ( ) . containsKey ( name ) ) { ret = getProperties ( ) . get ( name ) ; } else { ret = def ; } } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Get property '" + name + "' (default=" + def + ") = " + ret ) ; } return ret ; } | This method returns the property associated with the supplied name . The system properties will be checked first and if not available then the collector configuration properties . |
9,544 | public void merge ( CollectorConfiguration config , boolean overwrite ) throws IllegalArgumentException { for ( String key : config . getInstrumentation ( ) . keySet ( ) ) { if ( getInstrumentation ( ) . containsKey ( key ) && ! overwrite ) { throw new IllegalArgumentException ( "Instrumentation for '" + key + "' already exists" ) ; } getInstrumentation ( ) . put ( key , config . getInstrumentation ( ) . get ( key ) ) ; } for ( String key : config . getTransactions ( ) . keySet ( ) ) { if ( getTransactions ( ) . containsKey ( key ) && ! overwrite ) { throw new IllegalArgumentException ( "Transaction config for '" + key + "' already exists" ) ; } getTransactions ( ) . put ( key , config . getTransactions ( ) . get ( key ) ) ; } getProperties ( ) . putAll ( config . getProperties ( ) ) ; } | This method merges the supplied configuration into this configuration . If a conflict is found if overwrite is true then the supplied config element will be used otherwise an exception will be raised . |
9,545 | public static ExpressionHandler getHandler ( Expression expression ) { ExpressionHandler ret = null ; Class < ? extends ExpressionHandler > cls = handlers . get ( expression . getClass ( ) ) ; if ( cls != null ) { try { Constructor < ? extends ExpressionHandler > con = cls . getConstructor ( Expression . class ) ; ret = con . newInstance ( expression ) ; } catch ( Exception e ) { log . log ( Level . SEVERE , "Failed to instantiate handler for expression '" + expression + "'" , e ) ; } } return ret ; } | This method returns an expression handler for the supplied expression . |
9,546 | public static Collection < CommunicationSummaryStatistics > buildCommunicationSummaryTree ( Collection < CommunicationSummaryStatistics > nodes , Set < String > endpoints ) { Map < String , CommunicationSummaryStatistics > nodeMap = new HashMap < String , CommunicationSummaryStatistics > ( ) ; for ( CommunicationSummaryStatistics css : nodes ) { nodeMap . put ( css . getId ( ) , css ) ; } List < CommunicationSummaryStatistics > ret = new ArrayList < > ( ) ; for ( String endpoint : endpoints ) { CommunicationSummaryStatistics n = nodeMap . get ( EndpointUtil . encodeClientURI ( endpoint ) ) ; if ( n == null ) { n = nodeMap . get ( endpoint ) ; } if ( n != null ) { CommunicationSummaryStatistics rootNode = new CommunicationSummaryStatistics ( n ) ; initCommunicationSummaryTreeNode ( rootNode , nodeMap , new HashSet < > ( Collections . singleton ( rootNode . getId ( ) ) ) ) ; ret . add ( rootNode ) ; } } return ret ; } | This method returns the supplied list of flat nodes as a set of tree structures with related nodes . |
9,547 | protected void setConfigurationService ( ConfigurationService configService ) { if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Set configuration service = " + configService ) ; } configurationService = configService ; if ( configurationService != null ) { initConfig ( ) ; } } | This method sets the configuration service . |
9,548 | protected void initConfig ( ) { CollectorConfiguration config = configurationService . getCollector ( null , null , null , null ) ; if ( config != null ) { configLastUpdated = System . currentTimeMillis ( ) ; filterManager = new FilterManager ( config ) ; try { processorManager = new ProcessorManager ( config ) ; } catch ( Throwable t ) { if ( t != null ) { log . log ( Level . SEVERE , "Failed to initialise Process Manager" , t ) ; } } initRefreshCycle ( ) ; } else { Executors . newSingleThreadScheduledExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { Thread t = Executors . defaultThreadFactory ( ) . newThread ( r ) ; t . setDaemon ( true ) ; return t ; } } ) . schedule ( new Runnable ( ) { public void run ( ) { initConfig ( ) ; } } , configRetryInterval , TimeUnit . SECONDS ) ; } } | This method initialises the configuration . |
9,549 | protected void initRefreshCycle ( ) { Integer refresh = PropertyUtil . getPropertyAsInteger ( PropertyUtil . HAWKULAR_APM_CONFIG_REFRESH ) ; if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Configuration refresh cycle (in seconds) = " + refresh ) ; } if ( refresh != null ) { Executors . newSingleThreadScheduledExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { Thread t = Executors . defaultThreadFactory ( ) . newThread ( r ) ; t . setDaemon ( true ) ; return t ; } } ) . scheduleAtFixedRate ( new Runnable ( ) { public void run ( ) { try { Map < String , TransactionConfig > changed = configurationService . getTransactions ( null , configLastUpdated ) ; for ( Map . Entry < String , TransactionConfig > stringBusinessTxnConfigEntry : changed . entrySet ( ) ) { TransactionConfig btc = stringBusinessTxnConfigEntry . getValue ( ) ; if ( btc . isDeleted ( ) ) { if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Removing config for btxn '" + stringBusinessTxnConfigEntry . getKey ( ) + "' = " + btc ) ; } filterManager . remove ( stringBusinessTxnConfigEntry . getKey ( ) ) ; processorManager . remove ( stringBusinessTxnConfigEntry . getKey ( ) ) ; } else { if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Changed config for btxn '" + stringBusinessTxnConfigEntry . getKey ( ) + "' = " + btc ) ; } filterManager . init ( stringBusinessTxnConfigEntry . getKey ( ) , btc ) ; processorManager . init ( stringBusinessTxnConfigEntry . getKey ( ) , btc ) ; } if ( btc . getLastUpdated ( ) > configLastUpdated ) { configLastUpdated = btc . getLastUpdated ( ) ; } } } catch ( Exception e ) { log . log ( Level . SEVERE , "Failed to update transaction configuration" , e ) ; } } } , refresh . intValue ( ) , refresh . intValue ( ) , TimeUnit . SECONDS ) ; } } | This method initialises the refresh cycle . |
9,550 | protected void mergeProducer ( Producer inner , Producer outer ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Merging Producer = " + inner + " into Producer = " + outer ) ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Merging Producers: replacing correlation ids (" + outer . getCorrelationIds ( ) + ") with (" + inner . getCorrelationIds ( ) + ")" ) ; } outer . setCorrelationIds ( inner . getCorrelationIds ( ) ) ; outer . getNodes ( ) . remove ( inner ) ; } | This method merges an inner Producer node information into its containing Producer node before removing the inner node . |
9,551 | protected void processInContent ( String location , FragmentBuilder builder , int hashCode ) { if ( builder . isInBufferActive ( hashCode ) ) { processIn ( location , null , builder . getInData ( hashCode ) ) ; } else if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "processInContent: location=[" + location + "] hashCode=" + hashCode + " in buffer is not active" ) ; } } | This method processes the in content if available . |
9,552 | protected void processOutContent ( String location , FragmentBuilder builder , int hashCode ) { if ( builder . isOutBufferActive ( hashCode ) ) { processOut ( location , null , builder . getOutData ( hashCode ) ) ; } else if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "processOutContent: location=[" + location + "] hashCode=" + hashCode + " out buffer is not active" ) ; } } | This method processes the out content if available . |
9,553 | protected void push ( String location , FragmentBuilder builder , Node node ) { processInContent ( location , builder , - 1 ) ; builder . pushNode ( node ) ; } | This method pushes a new node into the trace fragment . |
9,554 | protected < T extends Node > T pop ( String location , FragmentBuilder builder , Class < T > cls , String uri ) { if ( builder == null ) { if ( log . isLoggable ( Level . WARNING ) ) { log . warning ( "No fragment builder for this thread (" + Thread . currentThread ( ) + ") - trying to pop node of type: " + cls ) ; } return null ; } if ( builder . getCurrentNode ( ) == null ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "WARNING: No 'current node' for this thread (" + Thread . currentThread ( ) + ") - trying to pop node of type: " + cls ) ; } return null ; } processInContent ( location , builder , - 1 ) ; processOutContent ( location , builder , - 1 ) ; Node node = builder . popNode ( cls , uri ) ; if ( node != null ) { builder . finishNode ( node ) ; return cls . cast ( node ) ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Current node (type=" + builder . getCurrentNode ( ) . getClass ( ) + ") does not match required cls=" + cls + " and uri=" + uri + " at location=" + location ) ; } return null ; } | This method pops an existing node from the trace fragment . |
9,555 | protected void processValues ( Trace trace , Node node , Direction direction , Map < String , ? > headers , Object [ ] values ) { if ( node . interactionNode ( ) ) { Message m = null ; if ( direction == Direction . In ) { m = ( ( InteractionNode ) node ) . getIn ( ) ; if ( m == null ) { m = new Message ( ) ; ( ( InteractionNode ) node ) . setIn ( m ) ; } } else { m = ( ( InteractionNode ) node ) . getOut ( ) ; if ( m == null ) { m = new Message ( ) ; ( ( InteractionNode ) node ) . setOut ( m ) ; } } if ( headers != null && m . getHeaders ( ) . isEmpty ( ) ) { for ( Map . Entry < String , ? > stringEntry : headers . entrySet ( ) ) { String value = getHeaderValueText ( stringEntry . getValue ( ) ) ; if ( value != null ) { m . getHeaders ( ) . put ( stringEntry . getKey ( ) , value ) ; } } } } if ( processorManager != null ) { processorManager . process ( trace , node , direction , headers , values ) ; } } | This method processes the values associated with the start or end of a scoped activity . |
9,556 | protected String getHeaderValueText ( Object value ) { if ( value == null ) { return null ; } if ( value . getClass ( ) == String . class ) { return ( String ) value ; } else if ( value instanceof List ) { List < ? > list = ( List < ? > ) value ; if ( list . size ( ) == 1 ) { return getHeaderValueText ( list . get ( 0 ) ) ; } else { return list . toString ( ) ; } } return null ; } | This method returns a textual representation of the supplied header value . |
9,557 | protected void checkForCompletion ( FragmentBuilder builder , Node node ) { if ( builder . isComplete ( ) ) { if ( node != null ) { Trace trace = builder . getTrace ( ) ; if ( builder . getLevel ( ) . ordinal ( ) <= ReportingLevel . None . ordinal ( ) ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Not recording trace (level=" + builder . getLevel ( ) + "): " + trace ) ; } } else { if ( trace != null && ! trace . getNodes ( ) . isEmpty ( ) ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Record trace: " + trace ) ; } if ( trace . getNodes ( ) . size ( ) > 1 && trace . getNodes ( ) . get ( 0 ) . getClass ( ) == Consumer . class && ( ( Consumer ) trace . getNodes ( ) . get ( 0 ) ) . getEndpointType ( ) == null ) { Consumer consumer = ( Consumer ) trace . getNodes ( ) . get ( 0 ) ; while ( trace . getNodes ( ) . size ( ) > 1 ) { consumer . getNodes ( ) . add ( trace . getNodes ( ) . get ( 1 ) ) ; trace . getNodes ( ) . remove ( 1 ) ; } } recorder . record ( trace ) ; } } } fragmentManager . clear ( ) ; for ( String id : builder . getUncompletedCorrelationIds ( ) ) { correlations . remove ( id ) ; } diagnostics ( ) ; } } | This method checks whether the supplied fragment has been completed and therefore should be processed . |
9,558 | protected void spawnFragment ( FragmentBuilder parentBuilder , Node node , int position , FragmentBuilder spawnedBuilder ) { Trace trace = parentBuilder . getTrace ( ) ; String id = UUID . randomUUID ( ) . toString ( ) ; String location = null ; String uri = null ; String operation = null ; String type = null ; if ( ! trace . getNodes ( ) . isEmpty ( ) ) { Node rootNode = trace . getNodes ( ) . get ( 0 ) ; uri = rootNode . getUri ( ) ; operation = rootNode . getOperation ( ) ; } Producer producer = new Producer ( ) ; producer . setEndpointType ( type ) ; producer . setUri ( uri ) ; producer . setOperation ( operation ) ; producer . getCorrelationIds ( ) . add ( new CorrelationIdentifier ( Scope . ControlFlow , id ) ) ; if ( node != null && node . containerNode ( ) ) { parentBuilder . initNode ( producer ) ; if ( position == - 1 ) { ( ( ContainerNode ) node ) . getNodes ( ) . add ( producer ) ; } else { ( ( ContainerNode ) node ) . getNodes ( ) . add ( position , producer ) ; } } else { push ( location , parentBuilder , producer ) ; pop ( location , parentBuilder , Producer . class , uri ) ; } Trace spawnedTrace = spawnedBuilder . getTrace ( ) ; spawnedTrace . setTraceId ( trace . getTraceId ( ) ) ; spawnedTrace . setTransaction ( trace . getTransaction ( ) ) ; spawnedBuilder . setLevel ( parentBuilder . getLevel ( ) ) ; Consumer consumer = new Consumer ( ) ; consumer . setEndpointType ( type ) ; consumer . setUri ( uri ) ; consumer . setOperation ( operation ) ; consumer . getCorrelationIds ( ) . add ( new CorrelationIdentifier ( Scope . ControlFlow , id ) ) ; push ( location , spawnedBuilder , consumer ) ; pop ( location , spawnedBuilder , Consumer . class , uri ) ; } | This method creates a new linked fragment to handle some asynchronous activities . |
9,559 | public static synchronized < K , V > Cache < K , V > getDefaultCache ( String cacheName ) { if ( defaultCacheManager == null ) { defaultCacheManager = new DefaultCacheManager ( ) ; } return defaultCacheManager . getCache ( cacheName ) ; } | This method returns a default cache . |
9,560 | @ SuppressWarnings ( "unchecked" ) public static < T > T getSingletonService ( Class < T > intf ) { T ret = null ; synchronized ( singletons ) { if ( singletons . containsKey ( intf ) ) { ret = ( T ) singletons . get ( intf ) ; } else { List < T > services = getServices ( intf ) ; if ( ! services . isEmpty ( ) ) { ret = services . get ( 0 ) ; } singletons . put ( intf , ret ) ; } } return ret ; } | This method identifies a service implementation that implements the supplied interface and returns it as a singleton so that subsequent calls for the same service will get the same instance . |
9,561 | public static < T > List < T > getServices ( Class < T > intf ) { List < T > ret = new ArrayList < T > ( ) ; for ( T service : ServiceLoader . load ( intf ) ) { if ( ! ( service instanceof ServiceStatus ) || ( ( ServiceStatus ) service ) . isAvailable ( ) ) { if ( service instanceof ServiceLifecycle ) { ( ( ServiceLifecycle ) service ) . init ( ) ; } ret . add ( service ) ; } } return ret ; } | This method returns the list of service implementations that implement the supplied interface . |
9,562 | public void init ( String txn , TransactionConfig btc ) { FilterProcessor fp = null ; if ( btc . getFilter ( ) != null ) { fp = new FilterProcessor ( txn , btc ) ; } synchronized ( filterMap ) { FilterProcessor oldfp = filterMap . get ( txn ) ; if ( oldfp != null ) { globalExclusionFilters . remove ( oldfp ) ; btxnFilters . remove ( oldfp ) ; } if ( fp != null ) { filterMap . put ( txn , fp ) ; if ( fp . isIncludeAll ( ) ) { globalExclusionFilters . add ( fp ) ; } else { btxnFilters . add ( fp ) ; } } else { filterMap . remove ( txn ) ; } } } | This method initialises the filter manager with the supplied transaction configuration . |
9,563 | public void remove ( String txn ) { synchronized ( filterMap ) { FilterProcessor oldfp = filterMap . get ( txn ) ; if ( oldfp != null ) { globalExclusionFilters . remove ( oldfp ) ; btxnFilters . remove ( oldfp ) ; } } } | This method removes the transaction . |
9,564 | public FilterProcessor getFilterProcessor ( String endpoint ) { FilterProcessor ret = ( onlyNamedTransactions ? null : unnamedBTxn ) ; synchronized ( filterMap ) { for ( int i = 0 ; i < globalExclusionFilters . size ( ) ; i ++ ) { if ( globalExclusionFilters . get ( i ) . isExcluded ( endpoint ) ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Excluding endpoint=" + endpoint ) ; } return null ; } } for ( int i = 0 ; i < btxnFilters . size ( ) ; i ++ ) { if ( btxnFilters . get ( i ) . isIncluded ( endpoint ) ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Endpoint has passed inclusion filter: endpoint=" + endpoint ) ; } if ( btxnFilters . get ( i ) . isExcluded ( endpoint ) ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Endpoint has failed exclusion filter: endpoint=" + endpoint ) ; } return null ; } ret = btxnFilters . get ( i ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Endpoint belongs to transaction '" + ret + ": endpoint=" + endpoint ) ; } break ; } } } return ret ; } | This method determines whether the supplied endpoint is associated with a defined transaction or valid due to global inclusion criteria . |
9,565 | public static List < EmojiChar > search ( String ... annotations ) { return Emoji . findByAnnotations ( SPACE_JOINER . join ( annotations ) ) ; } | Finds matching Emoji character by its annotated metadata . |
9,566 | public final void applyPattern ( String pattern ) { if ( hasRegistry ( ) ) { super . applyPattern ( pattern ) ; toPattern = super . toPattern ( ) ; return ; } ArrayList < Format > foundFormats = new ArrayList < Format > ( ) ; ArrayList < String > foundDescriptions = new ArrayList < String > ( ) ; StringBuilder stripCustom = new StringBuilder ( pattern . length ( ) ) ; ParsePosition pos = new ParsePosition ( 0 ) ; char [ ] c = pattern . toCharArray ( ) ; int fmtCount = 0 ; while ( pos . getIndex ( ) < pattern . length ( ) ) { char charType = c [ pos . getIndex ( ) ] ; if ( QUOTE == charType ) { appendQuotedString ( pattern , pos , stripCustom , true ) ; continue ; } if ( START_FE == charType ) { fmtCount ++ ; seekNonWs ( pattern , pos ) ; int start = pos . getIndex ( ) ; int index = readArgumentIndex ( pattern , next ( pos ) ) ; stripCustom . append ( START_FE ) . append ( index ) ; seekNonWs ( pattern , pos ) ; Format format = null ; String formatDescription = null ; if ( c [ pos . getIndex ( ) ] == START_FMT ) { formatDescription = parseFormatDescription ( pattern , next ( pos ) ) ; format = getFormat ( formatDescription ) ; if ( format == null ) { stripCustom . append ( START_FMT ) . append ( formatDescription ) ; } } foundFormats . add ( format ) ; foundDescriptions . add ( format == null ? null : formatDescription ) ; Preconditions . checkState ( foundFormats . size ( ) == fmtCount ) ; Preconditions . checkState ( foundDescriptions . size ( ) == fmtCount ) ; if ( c [ pos . getIndex ( ) ] != END_FE ) { throw new IllegalArgumentException ( "Unreadable format element at position " + start ) ; } } stripCustom . append ( c [ pos . getIndex ( ) ] ) ; next ( pos ) ; } super . applyPattern ( stripCustom . toString ( ) ) ; toPattern = insertFormats ( super . toPattern ( ) , foundDescriptions ) ; if ( containsElements ( foundFormats ) ) { Format [ ] origFormats = getFormats ( ) ; Iterator < Format > it = foundFormats . iterator ( ) ; for ( int i = 0 ; it . hasNext ( ) ; i ++ ) { Format f = it . next ( ) ; if ( f != null ) { origFormats [ i ] = f ; } } super . setFormats ( origFormats ) ; } } | Apply the specified pattern . |
9,567 | private Format getFormat ( String desc ) { if ( registry != null ) { String name = desc ; String args = "" ; int i = desc . indexOf ( START_FMT ) ; if ( i > 0 ) { name = desc . substring ( 0 , i ) . trim ( ) ; args = desc . substring ( i + 1 ) . trim ( ) ; } FormatFactory factory = registry . get ( name ) ; if ( factory != null ) { return factory . getFormat ( name , args , getLocale ( ) ) ; } } return null ; } | Get a custom format from a format description . |
9,568 | private void getQuotedString ( String pattern , ParsePosition pos , boolean escapingOn ) { appendQuotedString ( pattern , pos , null , escapingOn ) ; } | Consume quoted string only |
9,569 | public int doEndTag ( ) throws JspException { String key = null ; LocalizationContext locCtxt = null ; if ( keySpecified ) { key = keyAttrValue ; } else { if ( bodyContent != null && bodyContent . getString ( ) != null ) key = bodyContent . getString ( ) . trim ( ) ; } if ( ( key == null ) || key . equals ( "" ) ) { try { pageContext . getOut ( ) . print ( "??????" ) ; } catch ( IOException ioe ) { throw new JspTagException ( ioe . toString ( ) , ioe ) ; } return EVAL_PAGE ; } String prefix = null ; if ( ! bundleSpecified ) { Tag t = findAncestorWithClass ( this , BundleSupport . class ) ; if ( t != null ) { BundleSupport parent = ( BundleSupport ) t ; locCtxt = parent . getLocalizationContext ( ) ; prefix = parent . getPrefix ( ) ; } else { locCtxt = BundleSupport . getLocalizationContext ( pageContext ) ; } } else { locCtxt = bundleAttrValue ; if ( locCtxt . getLocale ( ) != null ) { SetLocaleSupport . setResponseLocale ( pageContext , locCtxt . getLocale ( ) ) ; } } String message = UNDEFINED_KEY + key + UNDEFINED_KEY ; if ( locCtxt != null ) { ResourceBundle bundle = locCtxt . getResourceBundle ( ) ; if ( bundle != null ) { try { if ( prefix != null ) key = prefix + key ; message = bundle . getString ( key ) ; if ( ! params . isEmpty ( ) ) { Object [ ] messageArgs = params . toArray ( ) ; Locale locale ; if ( locCtxt . getLocale ( ) != null ) { locale = locCtxt . getLocale ( ) ; } else { locale = SetLocaleSupport . getFormattingLocale ( pageContext ) ; } MessageFormat formatter = ( locale != null ) ? Humanize . messageFormat ( message , locale ) : Humanize . messageFormat ( message ) ; message = formatter . format ( messageArgs ) ; } } catch ( MissingResourceException mre ) { message = UNDEFINED_KEY + key + UNDEFINED_KEY ; } } } if ( var != null ) { pageContext . setAttribute ( var , message , scope ) ; } else { try { pageContext . getOut ( ) . print ( message ) ; } catch ( IOException ioe ) { throw new JspTagException ( ioe . toString ( ) , ioe ) ; } } return EVAL_PAGE ; } | Tag attributes known at translation time |
9,570 | public static String codePointsToString ( String ... points ) { StringBuilder ret = new StringBuilder ( ) ; for ( String hexPoint : points ) { ret . append ( codePointToString ( hexPoint ) ) ; } return ret . toString ( ) ; } | Transforms a list of Unicode code points as hex strings into a proper encoded string . |
9,571 | public static String codePointToString ( String point ) { String ret ; if ( Strings . isNullOrEmpty ( point ) ) { return point ; } int unicodeScalar = Integer . parseInt ( point , 16 ) ; if ( Character . isSupplementaryCodePoint ( unicodeScalar ) ) { ret = String . valueOf ( Character . toChars ( unicodeScalar ) ) ; } else { ret = String . valueOf ( ( char ) unicodeScalar ) ; } return ret ; } | Transforms an Unicode code point given as a hex string into a proper encoded string . Supplementary code points are encoded in UTF - 16 as required by Java . |
9,572 | public static EmojiChar findByVendorCodePoint ( Vendor vendor , String point ) { Emoji emoji = Emoji . getInstance ( ) ; return emoji . _findByVendorCodePoint ( vendor , point ) ; } | Finds an emoji character by vendor code point . |
9,573 | public StringBuffer render ( StringBuffer buffer , Object ... arguments ) { return format ( arguments , buffer , null ) ; } | Formats the current pattern with the given arguments . |
9,574 | public String mapTo ( Vendor vendor ) { String [ ] m = getMapping ( vendor ) ; return m == null ? null : m [ VENDOR_MAP_RAW ] ; } | Gets the raw character value of this emoji character for a given vendor . |
9,575 | public static Map < String , Format > get ( String name ) { return instance ( ) . methods . get ( name ) ; } | Retrieves a variants map for a given format name . |
9,576 | public String format ( Date ref , Date then ) { return prettyTime . format ( DurationHelper . calculateDuration ( ref , then , prettyTime . getUnits ( ) ) ) ; } | Convenience format method . |
9,577 | public String format ( Date ref , Date then , long precision ) { List < Duration > durations = DurationHelper . calculatePreciseDuration ( ref , then , prettyTime . getUnits ( ) ) ; List < Duration > retained = retainPrecision ( durations , precision ) ; return retained . isEmpty ( ) ? "" : prettyTime . format ( retained ) ; } | Convenience format method for precise durations . |
9,578 | public static String transliterate ( final String text , final String id ) { Transliterator transliterator = Transliterator . getInstance ( id ) ; return transliterator . transform ( text ) ; } | Converts the characters of the given text to the specified script . |
9,579 | public static FormatFactory factory ( ) { return new FormatFactory ( ) { public Format getFormat ( String name , String args , Locale locale ) { Map < String , Format > mt = FormatTables . get ( name ) ; Preconditions . checkArgument ( mt != null , "There's no format instance for [%s]" , name ) ; Format m = mt . get ( ( args == null || args . length ( ) < 1 ) ? FormatNames . DEFAULT : args ) ; Preconditions . checkArgument ( m != null , "There's no signature in [%s] for the given args [%s]" , name , args ) ; return ( ( ConfigurableFormat ) m ) . withLocale ( locale ) ; } } ; } | Creates a factory for the specified format . |
9,580 | public static String naturalDay ( int style , Date then ) { Date today = new Date ( ) ; long delta = then . getTime ( ) - today . getTime ( ) ; long days = delta / ND_FACTOR ; if ( days == 0 ) return context . get ( ) . getMessage ( "today" ) ; else if ( days == 1 ) return context . get ( ) . getMessage ( "tomorrow" ) ; else if ( days == - 1 ) return context . get ( ) . getMessage ( "yesterday" ) ; return formatDate ( style , then ) ; } | For dates that are the current day or within one day return today tomorrow or yesterday as appropriate . Otherwise returns a string formatted according to a locale sensitive DateFormat . |
9,581 | public static String naturalTime ( Date reference , Date duration ) { return context . get ( ) . formatRelativeDate ( reference , duration ) ; } | Computes both past and future relative dates . |
9,582 | public static String ordinal ( Number value ) { int v = value . intValue ( ) ; int vc = v % 100 ; if ( vc > 10 && vc < 14 ) return String . format ( ORDINAL_FMT , v , context . get ( ) . ordinalSuffix ( 0 ) ) ; return String . format ( ORDINAL_FMT , v , context . get ( ) . ordinalSuffix ( v % 10 ) ) ; } | Converts a number to its ordinal as a string . |
9,583 | public static String times ( final Number num ) { java . text . MessageFormat f = new java . text . MessageFormat ( context . get ( ) . getBundle ( ) . getString ( "times.choice" ) , currentLocale ( ) ) ; return f . format ( new Object [ ] { Math . abs ( num . intValue ( ) ) } ) ; } | Interprets numbers as occurrences . |
9,584 | public double [ ] getCentralCuts ( Integer size ) throws SAXException { switch ( size ) { case 2 : return center_case2 ; case 3 : return center_case3 ; case 4 : return center_case4 ; case 5 : return center_case5 ; case 6 : return center_case6 ; case 7 : return center_case7 ; case 8 : return center_case8 ; case 9 : return center_case9 ; case 10 : return center_case10 ; case 11 : return center_case11 ; case 12 : return center_case12 ; case 13 : return center_case13 ; case 14 : return center_case14 ; case 15 : return center_case15 ; case 16 : return center_case16 ; case 17 : return center_case17 ; case 18 : return center_case18 ; case 19 : return center_case19 ; case 20 : return center_case20 ; default : throw new SAXException ( "Invalid alphabet size." ) ; } } | Produces central cut intervals lines for the normal distribution . |
9,585 | public void addElement ( T data ) { Node < T > newNode = new Node < T > ( data ) ; if ( isEmpty ( ) ) { first = newNode ; size = 1 ; } else { if ( this . comparator . compare ( newNode . data , first . data ) > 0 ) { Node < T > tmp = first ; first = newNode ; first . next = tmp ; tmp . prev = first ; size ++ ; } else { Node < T > prev = first ; Node < T > current = first . next ; while ( current != null ) { if ( this . comparator . compare ( newNode . data , current . data ) > 0 ) { prev . next = newNode ; newNode . prev = prev ; current . prev = newNode ; newNode . next = current ; size ++ ; break ; } current = current . next ; prev = prev . next ; } if ( null == current ) { prev . next = newNode ; newNode . prev = prev ; size ++ ; } if ( size > this . maxSize ) { dropLastElement ( ) ; } } } } | Adds a data instance . |
9,586 | public void insertSorted ( T value ) { add ( value ) ; @ SuppressWarnings ( "unchecked" ) Comparable < T > cmp = ( Comparable < T > ) value ; for ( int i = size ( ) - 1 ; i > 0 && cmp . compareTo ( get ( i - 1 ) ) < 0 ; i -- ) { Collections . swap ( this , i , i - 1 ) ; } } | Inserts an element and sorts the array . |
9,587 | public double distance2 ( double [ ] point1 , double [ ] point2 ) throws Exception { if ( point1 . length == point2 . length ) { Double sum = 0D ; for ( int i = 0 ; i < point1 . length ; i ++ ) { double tmp = point2 [ i ] - point1 [ i ] ; sum = sum + tmp * tmp ; } return sum ; } else { throw new Exception ( "Exception in Euclidean distance: array lengths are not equal" ) ; } } | Calculates the square of the Euclidean distance between two multidimensional points represented by the rational vectors . |
9,588 | public long distance2 ( int [ ] point1 , int [ ] point2 ) throws Exception { if ( point1 . length == point2 . length ) { long sum = 0 ; for ( int i = 0 ; i < point1 . length ; i ++ ) { sum = sum + ( point2 [ i ] - point1 [ i ] ) * ( point2 [ i ] - point1 [ i ] ) ; } return sum ; } else { throw new Exception ( "Exception in Euclidean distance: array lengths are not equal" ) ; } } | Calculates the square of the Euclidean distance between two multidimensional points represented by integer vectors . |
9,589 | public double seriesDistance ( double [ ] [ ] series1 , double [ ] [ ] series2 ) throws Exception { if ( series1 . length == series2 . length ) { Double res = 0D ; for ( int i = 0 ; i < series1 . length ; i ++ ) { res = res + distance2 ( series1 [ i ] , series2 [ i ] ) ; } return Math . sqrt ( res ) ; } else { throw new Exception ( "Exception in Euclidean distance: array lengths are not equal" ) ; } } | Calculates Euclidean distance between two multi - dimensional time - series of equal length . |
9,590 | public double normalizedDistance ( double [ ] point1 , double [ ] point2 ) throws Exception { return Math . sqrt ( distance2 ( point1 , point2 ) ) / point1 . length ; } | Calculates the Normalized Euclidean distance between two points . |
9,591 | public Double earlyAbandonedDistance ( double [ ] series1 , double [ ] series2 , double cutoff ) throws Exception { if ( series1 . length == series2 . length ) { double cutOff2 = cutoff ; if ( Double . MAX_VALUE != cutoff ) { cutOff2 = cutoff * cutoff ; } Double res = 0D ; for ( int i = 0 ; i < series1 . length ; i ++ ) { res = res + distance2 ( series1 [ i ] , series2 [ i ] ) ; if ( res > cutOff2 ) { return Double . NaN ; } } return Math . sqrt ( res ) ; } else { throw new Exception ( "Exception in Euclidean distance: array lengths are not equal" ) ; } } | Implements Euclidean distance with early abandoning . |
9,592 | public char [ ] getStr ( ) { char [ ] res = new char [ this . payload . length ] ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = this . payload [ i ] ; } return res ; } | Get a string payload . |
9,593 | public boolean isTrivial ( Integer complexity ) { int len = payload . length ; if ( ( null == complexity ) || ( len < 2 ) ) { return true ; } else if ( ( complexity . intValue ( ) > 0 ) && ( len > 2 ) ) { Set < Character > seen = new TreeSet < Character > ( ) ; for ( int i = 0 ; i < len ; i ++ ) { Character c = Character . valueOf ( this . payload [ i ] ) ; if ( seen . contains ( c ) ) { continue ; } else { seen . add ( c ) ; } } if ( complexity . intValue ( ) <= seen . size ( ) ) { return false ; } } return true ; } | Check the complexity of the string . |
9,594 | private static MotifRecord ADM ( double [ ] series , ArrayList < Integer > neighborhood , int motifSize , double range , double znormThreshold ) throws Exception { MotifRecord res = new MotifRecord ( - 1 , new ArrayList < Integer > ( ) ) ; ArrayList < BitSet > admDistances = new ArrayList < BitSet > ( neighborhood . size ( ) ) ; for ( int i = 0 ; i < neighborhood . size ( ) ; i ++ ) { admDistances . add ( new BitSet ( i ) ) ; } for ( int i = 0 ; i < neighborhood . size ( ) ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { boolean isMatch = isNonTrivialMatch ( series , neighborhood . get ( i ) , neighborhood . get ( j ) , motifSize , range , znormThreshold ) ; if ( isMatch ) { admDistances . get ( i ) . set ( j ) ; admDistances . get ( j ) . set ( i ) ; } } } int maxCount = 0 ; for ( int i = 0 ; i < neighborhood . size ( ) ; i ++ ) { int tmpCounter = 0 ; for ( int j = 0 ; j < neighborhood . size ( ) ; j ++ ) { if ( admDistances . get ( i ) . get ( j ) ) { tmpCounter ++ ; } } if ( tmpCounter > maxCount ) { maxCount = tmpCounter ; ArrayList < Integer > occurrences = new ArrayList < > ( ) ; for ( int j = 0 ; j < neighborhood . size ( ) ; j ++ ) { if ( admDistances . get ( i ) . get ( j ) ) { occurrences . add ( neighborhood . get ( j ) ) ; } } res = new MotifRecord ( neighborhood . get ( i ) , occurrences ) ; } } return res ; } | This is not a real ADM implementation . |
9,595 | private static boolean isNonTrivialMatch ( double [ ] series , int i , int j , Integer motifSize , double range , double znormThreshold ) { if ( Math . abs ( i - j ) < motifSize ) { return false ; } Double dd = eaDistance ( series , i , j , motifSize , range , znormThreshold ) ; if ( Double . isFinite ( dd ) ) { return true ; } return false ; } | Checks for the overlap and the range - configured distance . |
9,596 | private static Double eaDistance ( double [ ] series , int a , int b , Integer motifSize , double range , double znormThreshold ) { distCounter ++ ; double cutOff2 = range * range ; double [ ] seriesA = tp . znorm ( tp . subseriesByCopy ( series , a , a + motifSize ) , znormThreshold ) ; double [ ] seriesB = tp . znorm ( tp . subseriesByCopy ( series , b , b + motifSize ) , znormThreshold ) ; Double res = 0D ; for ( int i = 0 ; i < motifSize ; i ++ ) { res = res + distance2 ( seriesA [ i ] , seriesB [ i ] ) ; if ( res > cutOff2 ) { eaCounter ++ ; return Double . NaN ; } } return Math . sqrt ( res ) ; } | Early abandoning distance configure by range . |
9,597 | public int compareTo ( SAXRecord o ) { int a = this . occurrences . size ( ) ; int b = o . getIndexes ( ) . size ( ) ; if ( a == b ) { return 0 ; } else if ( a > b ) { return 1 ; } return - 1 ; } | This comparator compares entries by the length of the entries array - i . e . by the total frequency of entry occurrence . |
9,598 | public static DiscordRecords series2BruteForceDiscords ( double [ ] series , Integer windowSize , int discordCollectionSize , SlidingWindowMarkerAlgorithm marker , double nThreshold ) throws Exception { DiscordRecords discords = new DiscordRecords ( ) ; VisitRegistry globalTrackVisitRegistry = new VisitRegistry ( series . length ) ; globalTrackVisitRegistry . markVisited ( series . length - windowSize - 1 , series . length ) ; int discordCounter = 0 ; while ( discords . getSize ( ) < discordCollectionSize ) { LOGGER . debug ( "currently known discords: {} out of {}" , discords . getSize ( ) , discordCollectionSize ) ; Date start = new Date ( ) ; DiscordRecord bestDiscord = findBestDiscordBruteForce ( series , windowSize , globalTrackVisitRegistry , nThreshold ) ; bestDiscord . setPayload ( "#" + discordCounter ) ; Date end = new Date ( ) ; if ( bestDiscord . getNNDistance ( ) == 0.0D || bestDiscord . getPosition ( ) == - 1 ) { LOGGER . debug ( "breaking the outer search loop, discords found: {} last seen discord: {}" + discords . getSize ( ) , bestDiscord ) ; break ; } bestDiscord . setInfo ( "position " + bestDiscord . getPosition ( ) + ", NN distance " + bestDiscord . getNNDistance ( ) + ", elapsed time: " + SAXProcessor . timeToString ( start . getTime ( ) , end . getTime ( ) ) + ", " + bestDiscord . getInfo ( ) ) ; LOGGER . debug ( "{}" , bestDiscord . getInfo ( ) ) ; discords . add ( bestDiscord ) ; marker . markVisited ( globalTrackVisitRegistry , bestDiscord . getPosition ( ) , windowSize ) ; discordCounter ++ ; } return discords ; } | Brute force discord search implementation . BRUTE FORCE algorithm . |
9,599 | private static DiscordRecord findBestDiscordBruteForce ( double [ ] series , Integer windowSize , VisitRegistry globalRegistry , double nThreshold ) throws Exception { Date start = new Date ( ) ; long distanceCallsCounter = 0 ; double bestSoFarDistance = - 1.0 ; int bestSoFarPosition = - 1 ; VisitRegistry outerRegistry = globalRegistry . clone ( ) ; int outerIdx = - 1 ; while ( - 1 != ( outerIdx = outerRegistry . getNextRandomUnvisitedPosition ( ) ) ) { outerRegistry . markVisited ( outerIdx ) ; double [ ] candidateSeq = tsProcessor . znorm ( tsProcessor . subseriesByCopy ( series , outerIdx , outerIdx + windowSize ) , nThreshold ) ; double nearestNeighborDistance = Double . MAX_VALUE ; VisitRegistry innerRegistry = new VisitRegistry ( series . length - windowSize ) ; int innerIdx ; while ( - 1 != ( innerIdx = innerRegistry . getNextRandomUnvisitedPosition ( ) ) ) { innerRegistry . markVisited ( innerIdx ) ; if ( Math . abs ( outerIdx - innerIdx ) > windowSize ) { double [ ] currentSubsequence = tsProcessor . znorm ( tsProcessor . subseriesByCopy ( series , innerIdx , innerIdx + windowSize ) , nThreshold ) ; double dist = ed . earlyAbandonedDistance ( candidateSeq , currentSubsequence , nearestNeighborDistance ) ; distanceCallsCounter ++ ; if ( ( ! Double . isNaN ( dist ) ) && dist < nearestNeighborDistance ) { nearestNeighborDistance = dist ; } } } if ( ! ( Double . isInfinite ( nearestNeighborDistance ) ) && nearestNeighborDistance > bestSoFarDistance ) { bestSoFarDistance = nearestNeighborDistance ; bestSoFarPosition = outerIdx ; LOGGER . trace ( "discord updated: pos {}, dist {}" , bestSoFarPosition , bestSoFarDistance ) ; } } Date firstDiscord = new Date ( ) ; LOGGER . debug ( "best discord found at {}, best distance: {}, in {} distance calls: {}" , bestSoFarPosition , bestSoFarDistance , SAXProcessor . timeToString ( start . getTime ( ) , firstDiscord . getTime ( ) ) , distanceCallsCounter ) ; DiscordRecord res = new DiscordRecord ( bestSoFarPosition , bestSoFarDistance ) ; res . setLength ( windowSize ) ; res . setInfo ( "distance calls: " + distanceCallsCounter ) ; return res ; } | Finds the best discord . BRUTE FORCE algorithm . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.