code
stringlengths
73
34.1k
label
stringclasses
1 value
protected void initFollowsFrom(APMSpanBuilder builder, TraceRecorder recorder, Reference ref, ContextSampler sampler) { APMSpan referenced = (APMSpan) ref.getReferredTo(); initTopLevelState(referenced.getTraceContext().getTopSpan(), recorder, sampler); // Top level node in spawned fragment sho...
java
protected void processNoPrimaryReference(APMSpanBuilder builder, TraceRecorder recorder, ContextSampler sampler) { // No primary reference found, so means that all references will be treated // as equal, to provide a join construct within a separate fragment. initTopLevelState(this, recorder, sa...
java
protected void processRemainingReferences(APMSpanBuilder builder, Reference primaryRef) { // Check if other references for (Reference ref : builder.references) { if (primaryRef == ref) { continue; } // Setup correlation ids for other references ...
java
public void init(String txn, TransactionConfig btc) { if (log.isLoggable(Level.FINE)) { log.fine("ProcessManager: initialise btxn '" + txn + "' config=" + btc + " processors=" + btc.getProcessors().size()); } if (btc.getProcessors() != null && !btc.getProcessors(...
java
public void process(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object... values) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager: process trace=" + trace + " node=" + node + " direction=" + direction + " headers=" + headers ...
java
public static String toUnique(Span span) { String id = span.getId(); if (span.clientSpan()) { id = getClientId(span.getId()); } return id; }
java
protected void doPublish(String tenantId, List<T> items, String subscriber, int retryCount, long delay) throws Exception { String data = mapper.writeValueAsString(items); TextMessage tm = session.createTextMessage(data); if (tenantId != null) { tm.setStringProperty("ten...
java
protected void init() { Properties props = new Properties(); props.put("bootstrap.servers", PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_URI_PUBLISHER, PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_URI)) .substring(PropertyUtil.KAFKA_PREFIX.length())); ...
java
public Criteria addProperty(String name, String value, Operator operator) { properties.add(new PropertyCriteria(name, value, operator)); return this; }
java
public boolean transactionWide() { return !(!properties.isEmpty() || !correlationIds.isEmpty() || hostName != null || uri != null || operation != null); }
java
public Criteria deriveTransactionWide() { Criteria ret = new Criteria(); ret.setStartTime(startTime); ret.setEndTime(endTime); ret.setProperties(getProperties().stream().filter(p -> p.getName().equals(Constants.PROP_PRINCIPAL)) .collect(Collectors.toSet())); ret.s...
java
public static CollectorConfiguration getConfiguration(String type) { return loadConfig(PropertyUtil.getProperty(HAWKULAR_APM_CONFIG, DEFAULT_URI), type); }
java
protected static CollectorConfiguration loadConfig(String uri, String type) { final CollectorConfiguration config = new CollectorConfiguration(); if (type == null) { type = DEFAULT_TYPE; } uri += java.io.File.separator + type; File f = new File(uri); if (!...
java
protected void process(String tenantId, List<S> items, int retryCount) throws Exception { ProcessingUnit<S, T> pu = new ProcessingUnit<S, T>(); pu.setProcessor(getProcessor()); pu.setRetrySubscriber(retrySubscriber); pu.setRetryCount(retryCount); pu.setResultHan...
java
public static List<SourceInfo> getSourceInfo(String tenantId, List<Trace> items) throws RetryAttemptException { List<SourceInfo> sourceInfoList = new ArrayList<SourceInfo>(); int curpos=0; // This method initialises the deriver with a list of trace fragments ...
java
protected static void initialiseSourceInfo(List<SourceInfo> sourceInfoList, String tenantId, Trace trace, StringBuffer parentNodeId, int pos, Node node) { SourceInfo si = new SourceInfo(); parentNodeId.append(':'); parentNodeId.append(pos); si.setId(parentNodeId.toString()...
java
protected static Span findRootOrServerSpan(String tenantId, Span span, SpanCache spanCache) { while (span != null && !span.serverSpan() && !span.topLevelSpan()) { span = spanCache.get(tenantId, span.getParentId()); } return span; }
java
public static SourceInfo getSourceInfo(String tenantId, Span serverSpan, SpanCache spanCache) { String clientSpanId = SpanUniqueIdGenerator.getClientId(serverSpan.getId()); if (spanCache != null && clientSpanId != null) { Span clientSpan = spanCache.get(tenantId, clientSpanId); ...
java
public static ProcessorActionHandler getHandler(ProcessorAction action) { ProcessorActionHandler ret = null; Class<? extends ProcessorActionHandler> cls = handlers.get(action.getClass()); if (cls != null) { try { Constructor<? extends ProcessorActionHandler> con = cls...
java
protected static boolean processConfig() { // Read configuration CollectorConfiguration config = configService.getCollector(null, null, null, null); if (config != null) { try { updateInstrumentation(config); } catch (Exception e) { log.sev...
java
public static void updateInstrumentation(CollectorConfiguration config) throws Exception { List<String> scripts = new ArrayList<String>(); List<String> scriptNames = new ArrayList<String>(); Map<String, Instrumentation> instrumentTypes=config.getInstrumentation(); for (Map.Entry<String,...
java
public Node build() { ContainerNode ret = null; if (nodeType == NodeType.Component) { ret = new Component(); ((Component) ret).setComponentType(componentType); } else if (nodeType == NodeType.Consumer) { ret = new Consumer(); ((Consumer) ret).setE...
java
public void endProcessingNode() { if (nodeCount.decrementAndGet() == 0 && recorder != null) { Node node = rootNode.build(); trace.setTimestamp(node.getTimestamp()); trace.setTransaction(getTransaction()); trace.getNodes().add(node); if (checkForSampl...
java
public EndpointRef getSourceEndpoint() { return new EndpointRef(TagUtil.getUriPath(topSpan.getTags()), topSpan.getOperationName(), false); }
java
public void initTraceState(Map<String, Object> state) { Object traceId = state.get(Constants.HAWKULAR_APM_TRACEID); Object transaction = state.get(Constants.HAWKULAR_APM_TXN); Object level = state.get(Constants.HAWKULAR_APM_LEVEL); if (traceId != null) { setTraceId(traceId.to...
java
private static boolean checkForSamplingProperties(Node node) { Set<Property> samplingProperties = node instanceof ContainerNode ? ((ContainerNode) node).getPropertiesIncludingDescendants(Tags.SAMPLING_PRIORITY.getKey()) : node.getProperties(Tags.SAMPLING_PRIORITY.getKey()); ...
java
public static String encodeEndpoint(String uri, String operation) { StringBuilder buf=new StringBuilder(); if (uri != null && !uri.trim().isEmpty()) { buf.append(uri); } if (operation != null && !operation.trim().isEmpty()) { buf.append('['); buf.appen...
java
public static String decodeEndpointURI(String endpoint) { int ind=endpoint.indexOf('['); if (ind == 0) { return null; } else if (ind != -1) { return endpoint.substring(0, ind); } return endpoint; }
java
public static String decodeEndpointOperation(String endpoint, boolean stripped) { int ind=endpoint.indexOf('['); if (ind != -1) { if (stripped) { return endpoint.substring(ind+1, endpoint.length()-1); } return endpoint.substring(ind); } ...
java
public static String encodeClientURI(String uri) { if (uri == null) { return Constants.URI_CLIENT_PREFIX; } return Constants.URI_CLIENT_PREFIX + uri; }
java
public static String decodeClientURI(String clientUri) { return clientUri.startsWith(Constants.URI_CLIENT_PREFIX) ? clientUri.substring(Constants.URI_CLIENT_PREFIX.length()): clientUri; }
java
public static EndpointRef getSourceEndpoint(Trace fragment) { Node rootNode = fragment.getNodes().isEmpty() ? null : fragment.getNodes().get(0); if (rootNode == null) { return null; } // Create endpoint reference. If initial fragment and root node is a Producer, // th...
java
protected void submitTraces() { if (!traces.isEmpty()) { // Locally store list and create new list for subsequent traces List<Trace> toSend = traces; traces = new ArrayList<>(batchSize + 1); executor.execute(new Runnable() { @Override ...
java
public static List<HttpCode> getHttpStatusCodes(List<BinaryAnnotation> binaryAnnotations) { if (binaryAnnotations == null) { return Collections.emptyList(); } List<HttpCode> httpCodes = new ArrayList<>(); for (BinaryAnnotation binaryAnnotation: binaryAnnotations) { ...
java
public static List<HttpCode> getClientOrServerErrors(List<HttpCode> httpCodes) { return httpCodes.stream() .filter(x -> x.isClientOrServerError()) .collect(Collectors.toList()); }
java
public static String getHttpMethod(Span span) { if (isHttp(span)) { BinaryAnnotation ba = span.getBinaryAnnotation("http.method"); String httpMethod = null; if (ba != null) { httpMethod = ba.getValue().toUpperCase(); } else if (span.getName() != nu...
java
private static Integer toInt(String str) { Integer num = null; try { num = Integer.parseInt(str); } catch (NumberFormatException ex) { log.severe(String.format("failed to convert str: %s to integer", str)); } return num; }
java
public static String serialize(Object value) { if (value instanceof String) { return (String) value; } else if (value instanceof byte[]) { return new String((byte[]) value); }
java
public Set<Property> allProperties() { Set<Property> properties = new HashSet<Property>(); for (Node n : nodes) { n.includeProperties(properties); } return Collections.unmodifiableSet(properties); }
java
public long calculateDuration() { if (!nodes.isEmpty()) { long endTime = 0; for (int i = 0; i < getNodes().size(); i++) { Node node = getNodes().get(i); long nodeEndTime = node.overallEndTime(); if (nodeEndTime > endTime) { ...
java
public Set<Node> getCorrelatedNodes(CorrelationIdentifier cid) { Set<Node> ret = new HashSet<Node>(); for (Node n : getNodes()) { n.findCorrelatedNodes(cid, ret); } return ret; }
java
protected void initNode() { /** * quick fix for integration tests. if hosts property set to "embedded" then a local node is start. * maven dependencies need to be defined correctly for this to work */ ClassLoader cl = Thread.currentThread().getContextClassLoader(); tr...
java
public void close() { if (log.isLoggable(Level.FINEST)) { log.finest("Close Elasticsearch node=" + node + " client=" + client); } if (client != null) { client.close(); client = null; } if (node != null) { node.stop(); ...
java
public <T> T cast(Object obj, Class<T> clz) { if (!clz.isAssignableFrom(obj.getClass())) { return null; } return clz.cast(obj); }
java
public String formatSQL(Object obj, Object expr) { String sql = null; // Check whether an SQL statement has been provided if (expr instanceof String) { sql = (String)expr; if (log.isLoggable(Level.FINEST)) { log.finest("SQL retrieved from state = "+sql);...
java
protected FaultDescriptor getFaultDescriptor(Object fault) { for (int i = 0; i < faultDescriptors.size(); i++) { if (faultDescriptors.get(i).isValid(fault)) { return faultDescriptors.get(i); } } return null; }
java
public String faultName(Object fault) { FaultDescriptor fd = getFaultDescriptor(fault); if (fd != null) { return fd.getName(fault); } return fault.getClass().getSimpleName(); }
java
public String faultDescription(Object fault) { FaultDescriptor fd = getFaultDescriptor(fault); if (fd != null) { return fd.getDescription(fault); } return fault.toString(); }
java
public String removeAfter(String original, String marker) { int index = original.indexOf(marker); if (index != -1) { return original.substring(0, index); } return original; }
java
public Map<String, String> getHeaders(String type, Object target) { HeadersAccessor accessor = getHeadersAccessor(type); if (accessor != null) { Map<String, String> ret = accessor.getHeaders(target); return ret; } return null; }
java
public static BinaryAnnotationMappingDeriver getInstance(String path) { if (instance == null) { synchronized (LOCK) { if (instance == null) { instance = path == null ? new BinaryAnnotationMappingDeriver() : new BinaryAnnotationMappingDe...
java
public MappingResult mappingResult(List<BinaryAnnotation> binaryAnnotations) { if (binaryAnnotations == null) { return new MappingResult(); } List<String> componentTypes = new ArrayList<>(); List<String> endpointTypes = new ArrayList<>(); MappingResult.Builder mappi...
java
protected void deriveNodeDetails(Trace trace, List<Node> nodes, List<NodeDetails> rts, boolean initial, Set<Property> commonProperties) { for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); // If consumer or producer, check that endpoint type has been set, ...
java
protected Set<Property> obtainCommonProperties(Trace trace) { Set<Property> commonProperties = trace.getProperties(Constants.PROP_SERVICE_NAME); commonProperties.addAll(trace.getProperties(Constants.PROP_BUILD_STAMP)); commonProperties.addAll(trace.getProperties(Constants.PROP_PRINCIPAL)); ...
java
protected long calculateActualTime(Node n) { long childElapsed = 0; if (n.containerNode()) { long startTime=n.getTimestamp() + n.getDuration(); long endTime = n.getTimestamp(); for (int i = 0; i < ((ContainerNode) n).getNodes().size(); i++) { Node chil...
java
public boolean process(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object[] values) { if (predicate != null) { return predicate.test(trace, node, direction, headers, values); } return true; }
java
public boolean isVersionValid(String version) { if (fromVersion != null && version != null) { if (version.compareTo(fromVersion) < 0) { return false; } } if (toVersion != null) { if (version == null || version.compareTo(toVersion) >= 0) { ...
java
public void finest(String mesg, Throwable t) { log(Level.FINEST, mesg, t); }
java
public void finer(String mesg, Throwable t) { log(Level.FINER, mesg, t); }
java
public void fine(String mesg, Throwable t) { log(Level.FINE, mesg, t); }
java
public void info(String mesg, Throwable t) { log(Level.INFO, mesg, t); }
java
public void warning(String mesg, Throwable t) { log(Level.WARNING, mesg, t); }
java
public void severe(String mesg, Throwable t) { log(Level.SEVERE, mesg, t); }
java
public void log(Level mesgLevel, String mesg, Throwable t) { if (mesgLevel.ordinal() >= level.ordinal()) { StringBuilder builder = new StringBuilder(); builder.append(mesgLevel.name()); builder.append(": ["); builder.append(simpleClassName != null ? simpleClassNam...
java
public static String deriveOperation(Span span) { if (SpanHttpDeriverUtil.isHttp(span)) { return SpanHttpDeriverUtil.getHttpMethod(span); } return span.getName(); }
java
public boolean isCompleteExceptIgnoredNodes() { synchronized (nodeStack) { if (nodeStack.isEmpty() && retainedNodes.isEmpty()) { return true; } else { // Check that remaining nodes can be ignored for (int i=0; i < nodeStack.size(); i++) { ...
java
public void pushNode(Node node) { initNode(node); // Reset in stream inStream = null; synchronized (nodeStack) { // Clear popped stack poppedNodes.clear(); // Check if fragment is in suppression mode if (suppress) { supp...
java
public Node popNode(Class<? extends Node> cls, String uri) { synchronized (nodeStack) { // Check if fragment is in suppression mode if (suppress) { if (!suppressedNodeStack.isEmpty()) { // Check if node is on the suppressed stack ...
java
protected Node popNode(Stack<Node> stack, Class<? extends Node> cls, String uri) { Node top = stack.isEmpty() ? null : stack.peek(); if (top != null) { if (nodeMatches(top, cls, uri)) { Node node = stack.pop(); poppedNodes.push(node); return n...
java
protected boolean nodeMatches(Node node, Class<? extends Node> cls, String uri) { if (node.getClass() == cls) { return uri == null || NodeUtil.isOriginalURI(node, uri); } return false; }
java
public void retainNode(String id) { synchronized (retainedNodes) { Node current = getCurrentNode(); if (current != null) { retainedNodes.put(id, current); } } }
java
public void addUncompletedCorrelationId(String id, Node node, int position) { NodePlaceholder placeholder = new NodePlaceholder(); placeholder.setNode(node); placeholder.setPosition(position); uncompletedCorrelationIdsNodeMap.put(id, placeholder); }
java
public int getUncompletedCorrelationIdPosition(String id) { if (uncompletedCorrelationIdsNodeMap.containsKey(id)) { return uncompletedCorrelationIdsNodeMap.get(id).getPosition(); } return -1; }
java
public Node removeUncompletedCorrelationId(String id) { NodePlaceholder placeholder=uncompletedCorrelationIdsNodeMap.remove(id); if (placeholder != null) { return placeholder.getNode(); } return null; }
java
public void writeInData(int hashCode, byte[] b, int offset, int len) { if (inStream != null && (hashCode == -1 || hashCode == inHashCode)) { inStream.write(b, offset, len); } }
java
public byte[] getInData(int hashCode) { if (inStream != null && (hashCode == -1 || hashCode == inHashCode)) { try { inStream.close(); } catch (IOException e) { log.severe("Failed to close in data stream: " + e); } byte[] b = inStrea...
java
public void writeOutData(int hashCode, byte[] b, int offset, int len) { if (outStream != null && (hashCode == -1 || hashCode == outHashCode)) { outStream.write(b, offset, len); } }
java
public byte[] getOutData(int hashCode) { if (outStream != null && (hashCode == -1 || hashCode == outHashCode)) { try { outStream.close(); } catch (IOException e) { log.severe("Failed to close out data stream: " + e); } byte[] b = ou...
java
public void setState(Object context, String name, Object value) { StateInformation si = stateInformation.get(name); if (si == null) { si = new StateInformation(); stateInformation.put(name, si); } si.set(context, value); }
java
public Object getState(Object context, String name) { StateInformation si = stateInformation.get(name); if (si == null) { return null; } return si.get(context); }
java
public static String getUriPath(String value) { try { URL url = new URL(value); return url.getPath(); } catch (MalformedURLException e) { return value; } }
java
public static String getUriPath(Map<String, Object> tags) { for (Map.Entry<String,Object> entry : tags.entrySet()) { if (isUriKey(entry.getKey())) { return getUriPath(entry.getValue().toString()); } } return null; }
java
@Deprecated public static void rewriteURI(Node node, String uri) { node.getProperties().add(new Property(APM_ORIGINAL_URI, node.getUri())); node.setUri(uri); }
java
@Deprecated public static boolean isOriginalURI(Node node, String uri) { if (node.getUri().equals(uri)) { return true; } if (node.hasProperty(APM_ORIGINAL_URI)) { return node.getProperties(APM_ORIGINAL_URI).iterator().next().getValue().equals(uri); } r...
java
protected Object getDataValue(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object[] values) { if (source == DataSource.Content) { return values[index]; } else if (source == DataSource.Header) { return headers.get(key); } return ...
java
@Override protected void includeProperties(Set<Property> allProperties) { super.includeProperties(allProperties); nodes.forEach(n -> n.includeProperties(allProperties)); }
java
@Override protected long overallEndTime() { long ret = super.overallEndTime(); for (Node child : nodes) { long childEndTime = child.overallEndTime(); if (childEndTime > ret) { ret = childEndTime; } } return ret; }
java
protected Collection<CommunicationSummaryStatistics> doGetCommunicationSummaryStatistics(String tenantId, Criteria criteria) { String index = client.getIndex(tenantId); Map<String, CommunicationSummaryStatistics> stats = new HashMap<>(); if (!criteria.transactionWide()) { Criteria t...
java
private void buildCommunicationSummaryStatistics(Map<String, CommunicationSummaryStatistics> stats, String index, Criteria criteria, boolean addMetrics) { if (!refresh(index)) { return; } // Don't specify target class, so that que...
java
static String getServiceFromBuildName(String buildName) { if (null == buildName || buildName.isEmpty()) { return buildName; } return buildName.substring(0, buildName.lastIndexOf('-')); }
java
public static void executeDatabaseScript(String script) throws SQLException, MalformedURLException { File file = new File(script); DatabaseUtils.executeSqlScript(DatabaseUtils.getDBConnection(null), file.toURI().toURL()); }
java
private static void executeSqlScript(Connection connection, URL scriptUrl) throws SQLException { for (String sqlStatement : readSqlStatements(scriptUrl)) { if (!sqlStatement.trim().isEmpty()) { connection.prepareStatement(sqlStatement).executeUpdate(); } } }
java
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.rea...
java
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); ...
java
public Node addInteractionCorrelationId(String id) { this.correlationIds.add(new CorrelationIdentifier(Scope.Interaction, id)); return this; }
java
public Node addControlFlowCorrelationId(String id) { this.correlationIds.add(new CorrelationIdentifier(Scope.ControlFlow, id)); return this; }
java
public Node addCausedByCorrelationId(String id) { this.correlationIds.add(new CorrelationIdentifier(Scope.CausedBy, id)); return this; }
java
protected void findCorrelatedNodes(CorrelationIdentifier cid, Set<Node> nodes) { if (isCorrelated(cid)) { nodes.add(this); } }
java
protected boolean isCorrelated(CorrelationIdentifier cid) { for (CorrelationIdentifier id : correlationIds) { if (id.equals(cid)) { return true; } } return false; }
java
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); ...
java