repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.buildTree
protected static void buildTree(EndpointPart parent, String[] parts, int index, String endpointType) { // Check if operation qualifier is part of last element String name = parts[index]; String qualifier = null; if (index == parts.length - 1) { qualifier = EndpointUtil.decodeEndpointOperation(parts[index], false); name = EndpointUtil.decodeEndpointURI(parts[index]); } // Check if part is defined in the parent EndpointPart child = parent.addChild(name); if (index < parts.length - 1) { buildTree(child, parts, index + 1, endpointType); } else { // Check if part has an operation qualifier if (qualifier != null) { child = child.addChild(qualifier); child.setQualifier(true); } child.setEndpointType(endpointType); } }
java
protected static void buildTree(EndpointPart parent, String[] parts, int index, String endpointType) { // Check if operation qualifier is part of last element String name = parts[index]; String qualifier = null; if (index == parts.length - 1) { qualifier = EndpointUtil.decodeEndpointOperation(parts[index], false); name = EndpointUtil.decodeEndpointURI(parts[index]); } // Check if part is defined in the parent EndpointPart child = parent.addChild(name); if (index < parts.length - 1) { buildTree(child, parts, index + 1, endpointType); } else { // Check if part has an operation qualifier if (qualifier != null) { child = child.addChild(qualifier); child.setQualifier(true); } child.setEndpointType(endpointType); } }
[ "protected", "static", "void", "buildTree", "(", "EndpointPart", "parent", ",", "String", "[", "]", "parts", ",", "int", "index", ",", "String", "endpointType", ")", "{", "// Check if operation qualifier is part of last element", "String", "name", "=", "parts", "[",...
This method builds a tree. @param parent The current parent node @param parts The parts of the URI being processed @param index The current index into the parts array @param endpointType The endpoint type
[ "This", "method", "builds", "a", "tree", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L182-L205
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.extractEndpointInfo
protected static List<EndpointInfo> extractEndpointInfo(EndpointPart root) { List<EndpointInfo> endpoints = new ArrayList<EndpointInfo>(); root.extractEndpointInfo(endpoints, ""); return endpoints; }
java
protected static List<EndpointInfo> extractEndpointInfo(EndpointPart root) { List<EndpointInfo> endpoints = new ArrayList<EndpointInfo>(); root.extractEndpointInfo(endpoints, ""); return endpoints; }
[ "protected", "static", "List", "<", "EndpointInfo", ">", "extractEndpointInfo", "(", "EndpointPart", "root", ")", "{", "List", "<", "EndpointInfo", ">", "endpoints", "=", "new", "ArrayList", "<", "EndpointInfo", ">", "(", ")", ";", "root", ".", "extractEndpoin...
This method expands a tree into the collapsed set of endpoints. @param root The tree @return The list of endpoints
[ "This", "method", "expands", "a", "tree", "into", "the", "collapsed", "set", "of", "endpoints", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L213-L219
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.initEndpointInfo
protected static void initEndpointInfo(List<EndpointInfo> endpoints) { for (int i = 0; i < endpoints.size(); i++) { initEndpointInfo(endpoints.get(i)); } }
java
protected static void initEndpointInfo(List<EndpointInfo> endpoints) { for (int i = 0; i < endpoints.size(); i++) { initEndpointInfo(endpoints.get(i)); } }
[ "protected", "static", "void", "initEndpointInfo", "(", "List", "<", "EndpointInfo", ">", "endpoints", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "endpoints", ".", "size", "(", ")", ";", "i", "++", ")", "{", "initEndpointInfo", "(", "...
This method initialises the list of endpoint information. @param endpoints The endpoint information
[ "This", "method", "initialises", "the", "list", "of", "endpoint", "information", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L226-L230
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.initEndpointInfo
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 { // Check if plural 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()); } }
java
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 { // Check if plural 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()); } }
[ "protected", "static", "void", "initEndpointInfo", "(", "EndpointInfo", "endpoint", ")", "{", "endpoint", ".", "setRegex", "(", "createRegex", "(", "endpoint", ".", "getEndpoint", "(", ")", ",", "endpoint", ".", "metaURI", "(", ")", ")", ")", ";", "String", ...
This method initialises the endpoint information. @param endpoint The endpoint information
[ "This", "method", "initialises", "the", "endpoint", "information", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L237-L280
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.hasMetrics
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; }
java
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; }
[ "protected", "static", "boolean", "hasMetrics", "(", "CommunicationSummaryStatistics", "css", ")", "{", "if", "(", "css", ".", "getCount", "(", ")", ">", "0", ")", "{", "return", "true", ";", "}", "for", "(", "ConnectionStatistics", "cs", ":", "css", ".", ...
This method determines whether the communication summary statistics have defined metrics. @param css The communication summary structure @return Whether they include metrics
[ "This", "method", "determines", "whether", "the", "communication", "summary", "statistics", "have", "defined", "metrics", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L333-L348
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.doGetUnboundEndpoints
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>(); // Process the fragments to identify which endpoints are not used in any trace for (int i = 0; i < fragments.size(); i++) { Trace trace = fragments.get(i); if (trace.initialFragment() && !trace.getNodes().isEmpty() && trace.getTransaction() == null) { // Check if top level node is Consumer if (trace.getNodes().get(0) instanceof Consumer) { Consumer consumer = (Consumer) trace.getNodes().get(0); String endpoint = EndpointUtil.encodeEndpoint(consumer.getUri(), consumer.getOperation()); // Check whether endpoint already known, and that it did not result // in a fault (e.g. want to ignore spurious URIs that are not // associated with a valid transaction) 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); } } } // Check whether any of the top level endpoints are already associated with // a transaction config 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(); } } } } } } } // Check if the endpoints should be compressed to identify common patterns if (compress) { ret = compressEndpointInfo(ret); } Collections.sort(ret, new Comparator<EndpointInfo>() { @Override public int compare(EndpointInfo arg0, EndpointInfo arg1) { return arg0.getEndpoint().compareTo(arg1.getEndpoint()); } }); return ret; }
java
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>(); // Process the fragments to identify which endpoints are not used in any trace for (int i = 0; i < fragments.size(); i++) { Trace trace = fragments.get(i); if (trace.initialFragment() && !trace.getNodes().isEmpty() && trace.getTransaction() == null) { // Check if top level node is Consumer if (trace.getNodes().get(0) instanceof Consumer) { Consumer consumer = (Consumer) trace.getNodes().get(0); String endpoint = EndpointUtil.encodeEndpoint(consumer.getUri(), consumer.getOperation()); // Check whether endpoint already known, and that it did not result // in a fault (e.g. want to ignore spurious URIs that are not // associated with a valid transaction) 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); } } } // Check whether any of the top level endpoints are already associated with // a transaction config 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(); } } } } } } } // Check if the endpoints should be compressed to identify common patterns if (compress) { ret = compressEndpointInfo(ret); } Collections.sort(ret, new Comparator<EndpointInfo>() { @Override public int compare(EndpointInfo arg0, EndpointInfo arg1) { return arg0.getEndpoint().compareTo(arg1.getEndpoint()); } }); return ret; }
[ "protected", "List", "<", "EndpointInfo", ">", "doGetUnboundEndpoints", "(", "String", "tenantId", ",", "List", "<", "Trace", ">", "fragments", ",", "boolean", "compress", ")", "{", "List", "<", "EndpointInfo", ">", "ret", "=", "new", "ArrayList", "<", "Endp...
This method obtains the unbound endpoints from a list of trace fragments. @param tenantId The tenant @param fragments The list of trace fragments @param compress Whether the list should be compressed (i.e. to identify patterns) @return The list of unbound endpoints
[ "This", "method", "obtains", "the", "unbound", "endpoints", "from", "a", "list", "of", "trace", "fragments", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L368-L439
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.obtainEndpoints
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); } } }
java
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); } } }
[ "protected", "void", "obtainEndpoints", "(", "List", "<", "Node", ">", "nodes", ",", "List", "<", "EndpointInfo", ">", "endpoints", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodes", ".", "size", "(", ")", ";", "i", "++", ")", "{...
This method collects the information regarding endpoints. @param nodes The nodes @param endpoints The list of endpoints
[ "This", "method", "collects", "the", "information", "regarding", "endpoints", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L447-L465
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.obtainProducerEndpoints
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); } } }
java
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); } } }
[ "protected", "void", "obtainProducerEndpoints", "(", "List", "<", "Node", ">", "nodes", ",", "List", "<", "EndpointInfo", ">", "endpoints", ",", "Map", "<", "String", ",", "EndpointInfo", ">", "map", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i"...
This method collects the information regarding endpoints for contained producers. @param nodes The nodes @param endpoints The list of endpoint info @param map The map of endpoints to info
[ "This", "method", "collects", "the", "information", "regarding", "endpoints", "for", "contained", "producers", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L475-L496
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.createRegex
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(); }
java
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(); }
[ "protected", "static", "String", "createRegex", "(", "String", "endpoint", ",", "boolean", "meta", ")", "{", "StringBuilder", "regex", "=", "new", "StringBuilder", "(", ")", ";", "regex", ".", "append", "(", "'", "'", ")", ";", "for", "(", "int", "i", ...
This method derives the regular expression from the supplied URI. @param endpoint The endpoint @param meta Whether this is a meta endpoint @return The regular expression
[ "This", "method", "derives", "the", "regular", "expression", "from", "the", "supplied", "URI", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L506-L524
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/internal/actions/EvaluateURIActionHandler.java
EvaluateURIActionHandler.processQueryParameters
protected boolean processQueryParameters(Trace trace, Node node) { boolean ret = false; // Translate query string into a map 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; }
java
protected boolean processQueryParameters(Trace trace, Node node) { boolean ret = false; // Translate query string into a map 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; }
[ "protected", "boolean", "processQueryParameters", "(", "Trace", "trace", ",", "Node", "node", ")", "{", "boolean", "ret", "=", "false", ";", "// Translate query string into a map", "Set", "<", "Property", ">", "queryString", "=", "node", ".", "getProperties", "(",...
This method processes the query parameters associated with the supplied node to extract templated named values as properties on the trace node. @param trace The trace @param node The node @return Whether query parameters were processed
[ "This", "method", "processes", "the", "query", "parameters", "associated", "with", "the", "supplied", "node", "to", "extract", "templated", "named", "values", "as", "properties", "on", "the", "trace", "node", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/internal/actions/EvaluateURIActionHandler.java#L180-L211
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/model/trace/InteractionNode.java
InteractionNode.multipleConsumers
public boolean multipleConsumers() { // TODO: When HWKAPM-698 implemented, it may no longer be necessary to capture this info Set<Property> props=getProperties(Producer.PROPERTY_PUBLISH); return !props.isEmpty() && props.iterator().next().getValue().equalsIgnoreCase(Boolean.TRUE.toString()); }
java
public boolean multipleConsumers() { // TODO: When HWKAPM-698 implemented, it may no longer be necessary to capture this info Set<Property> props=getProperties(Producer.PROPERTY_PUBLISH); return !props.isEmpty() && props.iterator().next().getValue().equalsIgnoreCase(Boolean.TRUE.toString()); }
[ "public", "boolean", "multipleConsumers", "(", ")", "{", "// TODO: When HWKAPM-698 implemented, it may no longer be necessary to capture this info", "Set", "<", "Property", ">", "props", "=", "getProperties", "(", "Producer", ".", "PROPERTY_PUBLISH", ")", ";", "return", "!"...
This method determines whether the interaction node is associated with a multi-consumer communication. @return Whether interaction relates to multiple consumers
[ "This", "method", "determines", "whether", "the", "interaction", "node", "is", "associated", "with", "a", "multi", "-", "consumer", "communication", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/model/trace/InteractionNode.java#L100-L105
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/internal/actions/ExpressionBasedActionHandler.java
ExpressionBasedActionHandler.getValue
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; }
java
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; }
[ "protected", "String", "getValue", "(", "Trace", "trace", ",", "Node", "node", ",", "Direction", "direction", ",", "Map", "<", "String", ",", "?", ">", "headers", ",", "Object", "[", "]", "values", ")", "{", "if", "(", "expression", "!=", "null", ")", ...
This method returns the value, associated with the expression, for the supplied data. @param trace The trace @param node The node @param direction The direction @param headers The optional headers @param values The values @return The result of the expression
[ "This", "method", "returns", "the", "value", "associated", "with", "the", "expression", "for", "the", "supplied", "data", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/internal/actions/ExpressionBasedActionHandler.java#L108-L115
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.startSpanWithParent
public void startSpanWithParent(SpanBuilder spanBuilder, Span parent, String id) { if (parent != null) { spanBuilder.asChildOf(parent.context()); } doStartSpan(spanBuilder, id); }
java
public void startSpanWithParent(SpanBuilder spanBuilder, Span parent, String id) { if (parent != null) { spanBuilder.asChildOf(parent.context()); } doStartSpan(spanBuilder, id); }
[ "public", "void", "startSpanWithParent", "(", "SpanBuilder", "spanBuilder", ",", "Span", "parent", ",", "String", "id", ")", "{", "if", "(", "parent", "!=", "null", ")", "{", "spanBuilder", ".", "asChildOf", "(", "parent", ".", "context", "(", ")", ")", ...
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. The optional id is associated with the started span. @param spanBuilder The span builder @param parent The parent span @param id The optional id to associate with the span
[ "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", ...
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L138-L144
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.startSpanWithContext
public void startSpanWithContext(SpanBuilder spanBuilder, SpanContext context, String id) { if (context != null) { spanBuilder.asChildOf(context); } doStartSpan(spanBuilder, id); }
java
public void startSpanWithContext(SpanBuilder spanBuilder, SpanContext context, String id) { if (context != null) { spanBuilder.asChildOf(context); } doStartSpan(spanBuilder, id); }
[ "public", "void", "startSpanWithContext", "(", "SpanBuilder", "spanBuilder", ",", "SpanContext", "context", ",", "String", "id", ")", "{", "if", "(", "context", "!=", "null", ")", "{", "spanBuilder", ".", "asChildOf", "(", "context", ")", ";", "}", "doStartS...
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. The optional id is associated with the started span. @param spanBuilder The span builder @param context The span context @param id The optional id to associate with the span
[ "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", ...
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L169-L175
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.hasSpanWithId
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; }
java
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; }
[ "public", "boolean", "hasSpanWithId", "(", "String", "id", ")", "{", "TraceState", "ts", "=", "traceState", ".", "get", "(", ")", ";", "if", "(", "id", "!=", "null", "&&", "ts", "!=", "null", ")", "{", "boolean", "spanFound", "=", "ts", ".", "getSpan...
This method determines whether there is a span available associated with the supplied id. @return Whether a span exists with the id
[ "This", "method", "determines", "whether", "there", "is", "a", "span", "available", "associated", "with", "the", "supplied", "id", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L275-L287
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.isCurrentSpan
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; }
java
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; }
[ "public", "boolean", "isCurrentSpan", "(", "String", "id", ")", "{", "TraceState", "ts", "=", "traceState", ".", "get", "(", ")", ";", "if", "(", "id", "!=", "null", "&&", "ts", "!=", "null", ")", "{", "boolean", "spanFound", "=", "ts", ".", "peekId"...
This method determines whether the current span is associated with the supplied id. @return Whether the current span is associated with the id
[ "This", "method", "determines", "whether", "the", "current", "span", "is", "associated", "with", "the", "supplied", "id", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L295-L307
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.getSpan
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; }
java
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; }
[ "public", "Span", "getSpan", "(", ")", "{", "TraceState", "ts", "=", "traceState", ".", "get", "(", ")", ";", "if", "(", "ts", "!=", "null", ")", "{", "Span", "span", "=", "ts", ".", "peekSpan", "(", ")", ";", "if", "(", "log", ".", "isLoggable",...
This method retrieves the current span, if available. @return The current span, or null if not defined
[ "This", "method", "retrieves", "the", "current", "span", "if", "available", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L314-L329
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.suspend
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(); // Check if id already used 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(); } } }
java
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(); // Check if id already used 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(); } } }
[ "public", "void", "suspend", "(", "String", "id", ")", "{", "TraceState", "ts", "=", "traceState", ".", "get", "(", ")", ";", "if", "(", "log", ".", "isLoggable", "(", "Level", ".", "FINEST", ")", ")", "{", "log", ".", "finest", "(", "\"Suspend trace...
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. @param id The id to associated with the suspended trace state
[ "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",...
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L338-L364
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.resume
public void resume(String id) { try { suspendedStateLock.lock(); TraceState ts = suspendedState.get(id); if (ts != null) { clearExpire(ts); // Log after finding trace state, otherwise may generate alot of logging if (log.isLoggable(Level.FINEST)) { log.finest("Resume trace state = " + ts + " id = " + id); } // Check if thread already used 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(); } }
java
public void resume(String id) { try { suspendedStateLock.lock(); TraceState ts = suspendedState.get(id); if (ts != null) { clearExpire(ts); // Log after finding trace state, otherwise may generate alot of logging if (log.isLoggable(Level.FINEST)) { log.finest("Resume trace state = " + ts + " id = " + id); } // Check if thread already used 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(); } }
[ "public", "void", "resume", "(", "String", "id", ")", "{", "try", "{", "suspendedStateLock", ".", "lock", "(", ")", ";", "TraceState", "ts", "=", "suspendedState", ".", "get", "(", "id", ")", ";", "if", "(", "ts", "!=", "null", ")", "{", "clearExpire...
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. @param id The id of the trace state to resume
[ "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", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L373-L399
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.includePath
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; }
java
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; }
[ "public", "boolean", "includePath", "(", "String", "path", ")", "{", "if", "(", "path", ".", "startsWith", "(", "\"/hawkular/apm\"", ")", ")", "{", "return", "false", ";", "}", "int", "dotPos", "=", "path", ".", "lastIndexOf", "(", "'", "'", ")", ";", ...
This method determines if the supplied path should be monitored. @param path The path @return Whether the path is valid for monitoring
[ "This", "method", "determines", "if", "the", "supplied", "path", "should", "be", "monitored", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L450-L475
train
hawkular/hawkular-apm
client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java
OpenTracingManager.sanitizePaths
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; }
java
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; }
[ "public", "String", "sanitizePaths", "(", "String", "baseUri", ",", "String", "resourcePath", ")", "{", "if", "(", "baseUri", ".", "endsWith", "(", "\"/\"", ")", "&&", "resourcePath", ".", "startsWith", "(", "\"/\"", ")", ")", "{", "return", "baseUri", "."...
Helper to remove duplicate slashes @param baseUri the base URI, usually in the format "/context/restapp/" @param resourcePath the resource path, usually in the format "/resource/method/record" @return The two parameters joined, with the double slash between them removed, like "/context/restapp/resource/method/record"
[ "Helper", "to", "remove", "duplicate", "slashes" ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L543-L552
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/internal/actions/helpers/JSON.java
JSON.serialize
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); } } } }
java
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); } } } }
[ "public", "static", "String", "serialize", "(", "Object", "data", ")", "{", "String", "ret", "=", "null", ";", "if", "(", "data", "!=", "null", ")", "{", "if", "(", "data", ".", "getClass", "(", ")", "==", "String", ".", "class", ")", "{", "ret", ...
This method serializes the supplied object to a JSON document. @param data The object @return The JSON representation
[ "This", "method", "serializes", "the", "supplied", "object", "to", "a", "JSON", "document", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/internal/actions/helpers/JSON.java#L43-L60
train
hawkular/hawkular-apm
server/processors/src/main/java/org/hawkular/apm/server/processor/tracecompletiontime/TraceCompletionInformationUtil.java
TraceCompletionInformationUtil.initialiseLinks
public static void initialiseLinks(TraceCompletionInformation ci, long fragmentBaseTime, Node n, StringBuilder nodeId) { // Add Communication to represent a potential 'CausedBy' link from one or more fragments back to // this node TraceCompletionInformation.Communication c = new TraceCompletionInformation.Communication(); c.getIds().add(nodeId.toString()); // Define a a multi-consumer as potentially multiple CausedBy correlations may be created // back to this node c.setMultipleConsumers(true); // Calculate the base duration for the communication 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) { // Get correlation ids 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()); // Calculate the base duration for the communication 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); // Remove this child's specific path, so that next iteration will add a different path number nodeId.delete(len, nodeId.length()); } } }
java
public static void initialiseLinks(TraceCompletionInformation ci, long fragmentBaseTime, Node n, StringBuilder nodeId) { // Add Communication to represent a potential 'CausedBy' link from one or more fragments back to // this node TraceCompletionInformation.Communication c = new TraceCompletionInformation.Communication(); c.getIds().add(nodeId.toString()); // Define a a multi-consumer as potentially multiple CausedBy correlations may be created // back to this node c.setMultipleConsumers(true); // Calculate the base duration for the communication 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) { // Get correlation ids 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()); // Calculate the base duration for the communication 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); // Remove this child's specific path, so that next iteration will add a different path number nodeId.delete(len, nodeId.length()); } } }
[ "public", "static", "void", "initialiseLinks", "(", "TraceCompletionInformation", "ci", ",", "long", "fragmentBaseTime", ",", "Node", "n", ",", "StringBuilder", "nodeId", ")", "{", "// Add Communication to represent a potential 'CausedBy' link from one or more fragments back to",...
This method initialises the completion time information for a trace instance. @param ci The information @param fragmentBaseTime The base time for the fragment (microseconds) @param n The node @param nodeId The path id for the node
[ "This", "method", "initialises", "the", "completion", "time", "information", "for", "a", "trace", "instance", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/processors/src/main/java/org/hawkular/apm/server/processor/tracecompletiontime/TraceCompletionInformationUtil.java#L48-L109
train
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java
ElasticsearchClient.getSingleton
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; }
java
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; }
[ "public", "static", "synchronized", "ElasticsearchClient", "getSingleton", "(", ")", "{", "if", "(", "singleton", "==", "null", ")", "{", "singleton", "=", "new", "ElasticsearchClient", "(", ")", ";", "try", "{", "singleton", ".", "init", "(", ")", ";", "}...
This method explicit instantiates the singleton. For use outside a CDI environment. @return The singleton
[ "This", "method", "explicit", "instantiates", "the", "singleton", ".", "For", "use", "outside", "a", "CDI", "environment", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java#L127-L137
train
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java
ElasticsearchClient.prepareMapping
@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; }
java
@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; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "boolean", "prepareMapping", "(", "String", "index", ",", "Map", "<", "String", ",", "Object", ">", "defaultMappings", ")", "{", "boolean", "success", "=", "true", ";", "for", "(", "Map", ".", ...
This method applies the supplied mapping to the index. @param index The name of the index @param defaultMappings The default mappings @return true if the mapping was successful
[ "This", "method", "applies", "the", "supplied", "mapping", "to", "the", "index", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java#L273-L307
train
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java
ElasticsearchClient.createIndex
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; }
java
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; }
[ "private", "boolean", "createIndex", "(", "String", "index", ",", "Map", "<", "String", ",", "Object", ">", "defaultSettings", ")", "{", "IndicesExistsResponse", "res", "=", "client", ".", "admin", "(", ")", ".", "indices", "(", ")", ".", "prepareExists", ...
Check if index is created. if not it will created it @param index The index @return returns true if it just created the index. False if the index already existed
[ "Check", "if", "index", "is", "created", ".", "if", "not", "it", "will", "created", "it" ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java#L315-L328
train
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java
ElasticsearchClient.determineHostsAsProperty
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 + "'"); } } }
java
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 + "'"); } } }
[ "private", "void", "determineHostsAsProperty", "(", ")", "{", "if", "(", "hosts", ".", "startsWith", "(", "\"${\"", ")", "&&", "hosts", ".", "endsWith", "(", "\"}\"", ")", ")", "{", "String", "hostsProperty", "=", "hosts", ".", "substring", "(", "2", ","...
sets hosts if the _hosts propertey is determined to be a property placeholder Throws IllegalArgumentException argument exception when nothing found
[ "sets", "hosts", "if", "the", "_hosts", "propertey", "is", "determined", "to", "be", "a", "property", "placeholder", "Throws", "IllegalArgumentException", "argument", "exception", "when", "nothing", "found" ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java#L334-L344
train
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java
ElasticsearchClient.clearTenant
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); } }
java
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); } }
[ "public", "void", "clearTenant", "(", "String", "tenantId", ")", "{", "String", "index", "=", "getIndex", "(", "tenantId", ")", ";", "synchronized", "(", "knownIndices", ")", "{", "IndicesAdminClient", "indices", "=", "client", ".", "admin", "(", ")", ".", ...
Removes all data associated with tenant. @param tenantId index
[ "Removes", "all", "data", "associated", "with", "tenant", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java#L360-L379
train
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java
ElasticsearchClient.close
@PreDestroy public void close() { if (node != null) { node.close(); } if (client != null) { client.close(); client = null; } }
java
@PreDestroy public void close() { if (node != null) { node.close(); } if (client != null) { client.close(); client = null; } }
[ "@", "PreDestroy", "public", "void", "close", "(", ")", "{", "if", "(", "node", "!=", "null", ")", "{", "node", ".", "close", "(", ")", ";", "}", "if", "(", "client", "!=", "null", ")", "{", "client", ".", "close", "(", ")", ";", "client", "=",...
This method closes the Elasticsearch client.
[ "This", "method", "closes", "the", "Elasticsearch", "client", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java#L385-L394
train
hawkular/hawkular-apm
server/processors-zipkin/src/main/java/org/hawkular/apm/server/processor/zipkin/CompletionTimeUtil.java
CompletionTimeUtil.spanToCompletionTime
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; }
java
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; }
[ "public", "static", "CompletionTime", "spanToCompletionTime", "(", "SpanCache", "spanCache", ",", "Span", "span", ")", "{", "CompletionTime", "completionTime", "=", "new", "CompletionTime", "(", ")", ";", "completionTime", ".", "setId", "(", "span", ".", "getId", ...
Convert span to CompletionTime object @param span the span @param spanCache span cache @return completion time derived from the supplied span, if the uri of the completion time cannot be derived (span is server span and client span also does not contain url) it returns null
[ "Convert", "span", "to", "CompletionTime", "object" ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/processors-zipkin/src/main/java/org/hawkular/apm/server/processor/zipkin/CompletionTimeUtil.java#L46-L83
train
hawkular/hawkular-apm
server/processors/src/main/java/org/hawkular/apm/server/processor/communicationdetails/CommunicationDetailsDeriver.java
CommunicationDetailsDeriver.initialiseOutbound
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()); } } // Only record if outbound ids found if (!ob.getLinkIds().isEmpty()) { // Check if pub/sub 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); // Remove this child's specific path, so that next iteration will add a different path number nodeId.delete(len, nodeId.length()); } } }
java
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()); } } // Only record if outbound ids found if (!ob.getLinkIds().isEmpty()) { // Check if pub/sub 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); // Remove this child's specific path, so that next iteration will add a different path number nodeId.delete(len, nodeId.length()); } } }
[ "protected", "static", "void", "initialiseOutbound", "(", "Node", "n", ",", "long", "baseTime", ",", "CommunicationDetails", "cd", ",", "StringBuilder", "nodeId", ")", "{", "CommunicationDetails", ".", "Outbound", "ob", "=", "new", "CommunicationDetails", ".", "Ou...
This method initialises the outbound information from the consumer's nodes in the supplied communication details. @param n The node @param baseTime The fragment's base time (ns) @param cd The communication details @param nodeId The path id for the node
[ "This", "method", "initialises", "the", "outbound", "information", "from", "the", "consumer", "s", "nodes", "in", "the", "supplied", "communication", "details", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/processors/src/main/java/org/hawkular/apm/server/processor/communicationdetails/CommunicationDetailsDeriver.java#L220-L255
train
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchUtil.java
ElasticsearchUtil.buildFilter
public static FilterBuilder buildFilter(Criteria criteria) { if (criteria.getTransaction() != null && criteria.getTransaction().trim().isEmpty()) { return FilterBuilders.missingFilter(TRANSACTION_FIELD); } return null; }
java
public static FilterBuilder buildFilter(Criteria criteria) { if (criteria.getTransaction() != null && criteria.getTransaction().trim().isEmpty()) { return FilterBuilders.missingFilter(TRANSACTION_FIELD); } return null; }
[ "public", "static", "FilterBuilder", "buildFilter", "(", "Criteria", "criteria", ")", "{", "if", "(", "criteria", ".", "getTransaction", "(", ")", "!=", "null", "&&", "criteria", ".", "getTransaction", "(", ")", ".", "trim", "(", ")", ".", "isEmpty", "(", ...
This method returns a filter associated with the supplied criteria. @param criteria The criteria @return The filter, or null if not relevant
[ "This", "method", "returns", "a", "filter", "associated", "with", "the", "supplied", "criteria", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchUtil.java#L170-L175
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/utils/TimeUtil.java
TimeUtil.toMicros
public static long toMicros(Instant instant) { return TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + TimeUnit.NANOSECONDS.toMicros(instant.getNano()); }
java
public static long toMicros(Instant instant) { return TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + TimeUnit.NANOSECONDS.toMicros(instant.getNano()); }
[ "public", "static", "long", "toMicros", "(", "Instant", "instant", ")", "{", "return", "TimeUnit", ".", "SECONDS", ".", "toMicros", "(", "instant", ".", "getEpochSecond", "(", ")", ")", "+", "TimeUnit", ".", "NANOSECONDS", ".", "toMicros", "(", "instant", ...
This method returns the timestamp, associated with the supplied instant, in microseconds. @param instant The instant @return The timestamp in microseconds
[ "This", "method", "returns", "the", "timestamp", "associated", "with", "the", "supplied", "instant", "in", "microseconds", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/utils/TimeUtil.java#L36-L38
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/model/config/CollectorConfiguration.java
CollectorConfiguration.getProperty
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; }
java
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; }
[ "public", "String", "getProperty", "(", "String", "name", ",", "String", "def", ")", "{", "String", "ret", "=", "PropertyUtil", ".", "getProperty", "(", "name", ",", "null", ")", ";", "if", "(", "ret", "==", "null", ")", "{", "if", "(", "getProperties"...
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. @param name The name of the required property @param def The optional default value @return The property value, or if not found then the default
[ "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", "."...
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/model/config/CollectorConfiguration.java#L72-L87
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/model/config/CollectorConfiguration.java
CollectorConfiguration.merge
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()); }
java
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()); }
[ "public", "void", "merge", "(", "CollectorConfiguration", "config", ",", "boolean", "overwrite", ")", "throws", "IllegalArgumentException", "{", "for", "(", "String", "key", ":", "config", ".", "getInstrumentation", "(", ")", ".", "keySet", "(", ")", ")", "{",...
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. @param config The configuration to merge @param overwrite Whether to overwrite when conflict found @throws IllegalArgumentException Failed to merge due to a conflict
[ "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"...
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/model/config/CollectorConfiguration.java#L126-L141
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/internal/actions/ExpressionHandlerFactory.java
ExpressionHandlerFactory.getHandler
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; }
java
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; }
[ "public", "static", "ExpressionHandler", "getHandler", "(", "Expression", "expression", ")", "{", "ExpressionHandler", "ret", "=", "null", ";", "Class", "<", "?", "extends", "ExpressionHandler", ">", "cls", "=", "handlers", ".", "get", "(", "expression", ".", ...
This method returns an expression handler for the supplied expression. @param expression The expression @return The handler
[ "This", "method", "returns", "an", "expression", "handler", "for", "the", "supplied", "expression", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/internal/actions/ExpressionHandlerFactory.java#L57-L69
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/internal/CommunicationSummaryTreeBuilder.java
CommunicationSummaryTreeBuilder.buildCommunicationSummaryTree
public static Collection<CommunicationSummaryStatistics> buildCommunicationSummaryTree( Collection<CommunicationSummaryStatistics> nodes, Set<String> endpoints) { Map<String, CommunicationSummaryStatistics> nodeMap = new HashMap<String, CommunicationSummaryStatistics>(); // Create a map of nodes for (CommunicationSummaryStatistics css : nodes) { nodeMap.put(css.getId(), css); } List<CommunicationSummaryStatistics> ret = new ArrayList<>(); for (String endpoint : endpoints) { // Check if a 'client' node also exists for the endpoint, and if so, use this as the // initial endpoint 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; }
java
public static Collection<CommunicationSummaryStatistics> buildCommunicationSummaryTree( Collection<CommunicationSummaryStatistics> nodes, Set<String> endpoints) { Map<String, CommunicationSummaryStatistics> nodeMap = new HashMap<String, CommunicationSummaryStatistics>(); // Create a map of nodes for (CommunicationSummaryStatistics css : nodes) { nodeMap.put(css.getId(), css); } List<CommunicationSummaryStatistics> ret = new ArrayList<>(); for (String endpoint : endpoints) { // Check if a 'client' node also exists for the endpoint, and if so, use this as the // initial endpoint 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; }
[ "public", "static", "Collection", "<", "CommunicationSummaryStatistics", ">", "buildCommunicationSummaryTree", "(", "Collection", "<", "CommunicationSummaryStatistics", ">", "nodes", ",", "Set", "<", "String", ">", "endpoints", ")", "{", "Map", "<", "String", ",", "...
This method returns the supplied list of flat nodes as a set of tree structures with related nodes. @param nodes The collection of nodes represented as a flat list @param endpoints The initial endpoints @return The nodes returns as a collection of independent tree structures
[ "This", "method", "returns", "the", "supplied", "list", "of", "flat", "nodes", "as", "a", "set", "of", "tree", "structures", "with", "related", "nodes", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/internal/CommunicationSummaryTreeBuilder.java#L50-L76
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.setConfigurationService
protected void setConfigurationService(ConfigurationService configService) { if (log.isLoggable(Level.FINER)) { log.finer("Set configuration service = " + configService); } configurationService = configService; if (configurationService != null) { initConfig(); } }
java
protected void setConfigurationService(ConfigurationService configService) { if (log.isLoggable(Level.FINER)) { log.finer("Set configuration service = " + configService); } configurationService = configService; if (configurationService != null) { initConfig(); } }
[ "protected", "void", "setConfigurationService", "(", "ConfigurationService", "configService", ")", "{", "if", "(", "log", ".", "isLoggable", "(", "Level", ".", "FINER", ")", ")", "{", "log", ".", "finer", "(", "\"Set configuration service = \"", "+", "configServic...
This method sets the configuration service. @param configService The configuration service
[ "This", "method", "sets", "the", "configuration", "service", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L105-L115
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.initConfig
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 { // Wait for a period of time and try doing the initial config again Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; } }).schedule(new Runnable() { @Override public void run() { initConfig(); } }, configRetryInterval, TimeUnit.SECONDS); } }
java
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 { // Wait for a period of time and try doing the initial config again Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; } }).schedule(new Runnable() { @Override public void run() { initConfig(); } }, configRetryInterval, TimeUnit.SECONDS); } }
[ "protected", "void", "initConfig", "(", ")", "{", "CollectorConfiguration", "config", "=", "configurationService", ".", "getCollector", "(", "null", ",", "null", ",", "null", ",", "null", ")", ";", "if", "(", "config", "!=", "null", ")", "{", "configLastUpda...
This method initialises the configuration.
[ "This", "method", "initialises", "the", "configuration", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L120-L151
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.initRefreshCycle
protected void initRefreshCycle() { // Check if should check for updates 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() { @Override 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); } }
java
protected void initRefreshCycle() { // Check if should check for updates 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() { @Override 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); } }
[ "protected", "void", "initRefreshCycle", "(", ")", "{", "// Check if should check for updates", "Integer", "refresh", "=", "PropertyUtil", ".", "getPropertyAsInteger", "(", "PropertyUtil", ".", "HAWKULAR_APM_CONFIG_REFRESH", ")", ";", "if", "(", "log", ".", "isLoggable"...
This method initialises the refresh cycle.
[ "This", "method", "initialises", "the", "refresh", "cycle", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L156-L207
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.mergeProducer
protected void mergeProducer(Producer inner, Producer outer) { if (log.isLoggable(Level.FINEST)) { log.finest("Merging Producer = " + inner + " into Producer = " + outer); } // NOTE: For now, assumption is that inner Producer is equivalent to the outer // and results from instrumentation rules being triggered multiple times // for the same message. // Merge correlation - just replace for now if (log.isLoggable(Level.FINEST)) { log.finest("Merging Producers: replacing correlation ids (" + outer.getCorrelationIds() + ") with (" + inner.getCorrelationIds() + ")"); } outer.setCorrelationIds(inner.getCorrelationIds()); // Remove the inner Producer from the child nodes of the outer outer.getNodes().remove(inner); }
java
protected void mergeProducer(Producer inner, Producer outer) { if (log.isLoggable(Level.FINEST)) { log.finest("Merging Producer = " + inner + " into Producer = " + outer); } // NOTE: For now, assumption is that inner Producer is equivalent to the outer // and results from instrumentation rules being triggered multiple times // for the same message. // Merge correlation - just replace for now if (log.isLoggable(Level.FINEST)) { log.finest("Merging Producers: replacing correlation ids (" + outer.getCorrelationIds() + ") with (" + inner.getCorrelationIds() + ")"); } outer.setCorrelationIds(inner.getCorrelationIds()); // Remove the inner Producer from the child nodes of the outer outer.getNodes().remove(inner); }
[ "protected", "void", "mergeProducer", "(", "Producer", "inner", ",", "Producer", "outer", ")", "{", "if", "(", "log", ".", "isLoggable", "(", "Level", ".", "FINEST", ")", ")", "{", "log", ".", "finest", "(", "\"Merging Producer = \"", "+", "inner", "+", ...
This method merges an inner Producer node information into its containing Producer node, before removing the inner node. @param inner @param outer
[ "This", "method", "merges", "an", "inner", "Producer", "node", "information", "into", "its", "containing", "Producer", "node", "before", "removing", "the", "inner", "node", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L571-L589
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.processInContent
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"); } }
java
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"); } }
[ "protected", "void", "processInContent", "(", "String", "location", ",", "FragmentBuilder", "builder", ",", "int", "hashCode", ")", "{", "if", "(", "builder", ".", "isInBufferActive", "(", "hashCode", ")", ")", "{", "processIn", "(", "location", ",", "null", ...
This method processes the in content if available. @param location The instrumentation location @param builder The builder @param hashCode The hash code, or -1 to ignore the hash code
[ "This", "method", "processes", "the", "in", "content", "if", "available", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L894-L901
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.processOutContent
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"); } }
java
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"); } }
[ "protected", "void", "processOutContent", "(", "String", "location", ",", "FragmentBuilder", "builder", ",", "int", "hashCode", ")", "{", "if", "(", "builder", ".", "isOutBufferActive", "(", "hashCode", ")", ")", "{", "processOut", "(", "location", ",", "null"...
This method processes the out content if available. @param location The instrumentation location @param builder The builder @param hashCode The hash code, or -1 to ignore the hash code
[ "This", "method", "processes", "the", "out", "content", "if", "available", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1002-L1009
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.push
protected void push(String location, FragmentBuilder builder, Node node) { // Check if any in content should be processed for the current node processInContent(location, builder, -1); builder.pushNode(node); }
java
protected void push(String location, FragmentBuilder builder, Node node) { // Check if any in content should be processed for the current node processInContent(location, builder, -1); builder.pushNode(node); }
[ "protected", "void", "push", "(", "String", "location", ",", "FragmentBuilder", "builder", ",", "Node", "node", ")", "{", "// Check if any in content should be processed for the current node", "processInContent", "(", "location", ",", "builder", ",", "-", "1", ")", ";...
This method pushes a new node into the trace fragment. @param location The instrumentation location @param builder The fragment builder @param node The node
[ "This", "method", "pushes", "a", "new", "node", "into", "the", "trace", "fragment", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1018-L1024
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.pop
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; } // Check if any in or out content should be processed for the current node 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; }
java
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; } // Check if any in or out content should be processed for the current node 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; }
[ "protected", "<", "T", "extends", "Node", ">", "T", "pop", "(", "String", "location", ",", "FragmentBuilder", "builder", ",", "Class", "<", "T", ">", "cls", ",", "String", "uri", ")", "{", "if", "(", "builder", "==", "null", ")", "{", "if", "(", "l...
This method pops an existing node from the trace fragment. @param location The instrumentation location @param The class to pop @param The optional URI to match @return The node
[ "This", "method", "pops", "an", "existing", "node", "from", "the", "trace", "fragment", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1034-L1068
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.processValues
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()) { // TODO: Need to have config to determine whether headers should be logged 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); } }
java
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()) { // TODO: Need to have config to determine whether headers should be logged 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); } }
[ "protected", "void", "processValues", "(", "Trace", "trace", ",", "Node", "node", ",", "Direction", "direction", ",", "Map", "<", "String", ",", "?", ">", "headers", ",", "Object", "[", "]", "values", ")", "{", "if", "(", "node", ".", "interactionNode", ...
This method processes the values associated with the start or end of a scoped activity. @param trace The trace @param node The node @param direction The direction @param headers The optional headers @param values The values
[ "This", "method", "processes", "the", "values", "associated", "with", "the", "start", "or", "end", "of", "a", "scoped", "activity", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1080-L1115
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.getHeaderValueText
protected String getHeaderValueText(Object value) { if (value == null) { return null; } // TODO: Type conversion based on provided config 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; }
java
protected String getHeaderValueText(Object value) { if (value == null) { return null; } // TODO: Type conversion based on provided config 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; }
[ "protected", "String", "getHeaderValueText", "(", "Object", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "null", ";", "}", "// TODO: Type conversion based on provided config", "if", "(", "value", ".", "getClass", "(", ")", "==", "St...
This method returns a textual representation of the supplied header value. @param value The original value @return The text representation, or null if no suitable found
[ "This", "method", "returns", "a", "textual", "representation", "of", "the", "supplied", "header", "value", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1124-L1142
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.checkForCompletion
protected void checkForCompletion(FragmentBuilder builder, Node node) { // Check if completed 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); } // Check if first top level node is an internal consumer // and if so move subsequent top level nodes within its scope 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(); // Remove uncompleted correlation ids for (String id : builder.getUncompletedCorrelationIds()) { correlations.remove(id); } diagnostics(); } }
java
protected void checkForCompletion(FragmentBuilder builder, Node node) { // Check if completed 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); } // Check if first top level node is an internal consumer // and if so move subsequent top level nodes within its scope 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(); // Remove uncompleted correlation ids for (String id : builder.getUncompletedCorrelationIds()) { correlations.remove(id); } diagnostics(); } }
[ "protected", "void", "checkForCompletion", "(", "FragmentBuilder", "builder", ",", "Node", "node", ")", "{", "// Check if completed", "if", "(", "builder", ".", "isComplete", "(", ")", ")", "{", "if", "(", "node", "!=", "null", ")", "{", "Trace", "trace", ...
This method checks whether the supplied fragment has been completed and therefore should be processed. @param node The most recently popped node @param builder The fragment builder
[ "This", "method", "checks", "whether", "the", "supplied", "fragment", "has", "been", "completed", "and", "therefore", "should", "be", "processed", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1151-L1194
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java
DefaultTraceCollector.spawnFragment
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; // Set to null to indicate internal if (!trace.getNodes().isEmpty()) { Node rootNode = trace.getNodes().get(0); uri = rootNode.getUri(); operation = rootNode.getOperation(); } // Create Producer node to represent the internal connection to the spawned fragment 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); } // Transfer relevant details to the spawned trace and builder Trace spawnedTrace = spawnedBuilder.getTrace(); spawnedTrace.setTraceId(trace.getTraceId()); spawnedTrace.setTransaction(trace.getTransaction()); spawnedBuilder.setLevel(parentBuilder.getLevel()); // Create Consumer node to represent other end of internal spawn link 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 immediately as easier than attempting to determine end of spawned scope and // removing it from the stack then. // TODO: Could look at moving subsequent top level nodes under this Consumer // at the point when the fragment is recorded pop(location, spawnedBuilder, Consumer.class, uri); }
java
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; // Set to null to indicate internal if (!trace.getNodes().isEmpty()) { Node rootNode = trace.getNodes().get(0); uri = rootNode.getUri(); operation = rootNode.getOperation(); } // Create Producer node to represent the internal connection to the spawned fragment 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); } // Transfer relevant details to the spawned trace and builder Trace spawnedTrace = spawnedBuilder.getTrace(); spawnedTrace.setTraceId(trace.getTraceId()); spawnedTrace.setTransaction(trace.getTransaction()); spawnedBuilder.setLevel(parentBuilder.getLevel()); // Create Consumer node to represent other end of internal spawn link 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 immediately as easier than attempting to determine end of spawned scope and // removing it from the stack then. // TODO: Could look at moving subsequent top level nodes under this Consumer // at the point when the fragment is recorded pop(location, spawnedBuilder, Consumer.class, uri); }
[ "protected", "void", "spawnFragment", "(", "FragmentBuilder", "parentBuilder", ",", "Node", "node", ",", "int", "position", ",", "FragmentBuilder", "spawnedBuilder", ")", "{", "Trace", "trace", "=", "parentBuilder", ".", "getTrace", "(", ")", ";", "String", "id"...
This method creates a new linked fragment to handle some asynchronous activities.
[ "This", "method", "creates", "a", "new", "linked", "fragment", "to", "handle", "some", "asynchronous", "activities", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/DefaultTraceCollector.java#L1505-L1560
train
hawkular/hawkular-apm
server/infinispan/src/main/java/org/hawkular/apm/server/infinispan/InfinispanCacheManager.java
InfinispanCacheManager.getDefaultCache
public static synchronized <K, V> Cache<K, V> getDefaultCache(String cacheName) { if (defaultCacheManager == null) { defaultCacheManager = new DefaultCacheManager(); } return defaultCacheManager.getCache(cacheName); }
java
public static synchronized <K, V> Cache<K, V> getDefaultCache(String cacheName) { if (defaultCacheManager == null) { defaultCacheManager = new DefaultCacheManager(); } return defaultCacheManager.getCache(cacheName); }
[ "public", "static", "synchronized", "<", "K", ",", "V", ">", "Cache", "<", "K", ",", "V", ">", "getDefaultCache", "(", "String", "cacheName", ")", "{", "if", "(", "defaultCacheManager", "==", "null", ")", "{", "defaultCacheManager", "=", "new", "DefaultCac...
This method returns a default cache. @param cacheName The cache name @return The default cache
[ "This", "method", "returns", "a", "default", "cache", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/infinispan/src/main/java/org/hawkular/apm/server/infinispan/InfinispanCacheManager.java#L37-L42
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/ServiceResolver.java
ServiceResolver.getSingletonService
@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; }
java
@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; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "getSingletonService", "(", "Class", "<", "T", ">", "intf", ")", "{", "T", "ret", "=", "null", ";", "synchronized", "(", "singletons", ")", "{", "if", "(", "sin...
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. @param intf The interface @return The service, or null if not found @param <T> The service interface
[ "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", ...
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/ServiceResolver.java#L47-L66
train
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/ServiceResolver.java
ServiceResolver.getServices
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; }
java
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; }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "getServices", "(", "Class", "<", "T", ">", "intf", ")", "{", "List", "<", "T", ">", "ret", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "for", "(", "T", "service", ":", "Ser...
This method returns the list of service implementations that implement the supplied interface. @param intf The interface @return The list @param <T> The service interface
[ "This", "method", "returns", "the", "list", "of", "service", "implementations", "that", "implement", "the", "supplied", "interface", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/ServiceResolver.java#L77-L91
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FilterManager.java
FilterManager.init
public void init(String txn, TransactionConfig btc) { FilterProcessor fp = null; if (btc.getFilter() != null) { fp = new FilterProcessor(txn, btc); } synchronized (filterMap) { // Check if old filter processor needs to be removed FilterProcessor oldfp = filterMap.get(txn); if (oldfp != null) { globalExclusionFilters.remove(oldfp); btxnFilters.remove(oldfp); } if (fp != null) { // Add new filter processor filterMap.put(txn, fp); if (fp.isIncludeAll()) { globalExclusionFilters.add(fp); } else { btxnFilters.add(fp); } } else { filterMap.remove(txn); } } }
java
public void init(String txn, TransactionConfig btc) { FilterProcessor fp = null; if (btc.getFilter() != null) { fp = new FilterProcessor(txn, btc); } synchronized (filterMap) { // Check if old filter processor needs to be removed FilterProcessor oldfp = filterMap.get(txn); if (oldfp != null) { globalExclusionFilters.remove(oldfp); btxnFilters.remove(oldfp); } if (fp != null) { // Add new filter processor filterMap.put(txn, fp); if (fp.isIncludeAll()) { globalExclusionFilters.add(fp); } else { btxnFilters.add(fp); } } else { filterMap.remove(txn); } } }
[ "public", "void", "init", "(", "String", "txn", ",", "TransactionConfig", "btc", ")", "{", "FilterProcessor", "fp", "=", "null", ";", "if", "(", "btc", ".", "getFilter", "(", ")", "!=", "null", ")", "{", "fp", "=", "new", "FilterProcessor", "(", "txn",...
This method initialises the filter manager with the supplied transaction configuration. @param txn The transaction name @param btc The configuration
[ "This", "method", "initialises", "the", "filter", "manager", "with", "the", "supplied", "transaction", "configuration", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FilterManager.java#L77-L104
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FilterManager.java
FilterManager.remove
public void remove(String txn) { synchronized (filterMap) { // Check if old filter processor needs to be removed FilterProcessor oldfp = filterMap.get(txn); if (oldfp != null) { globalExclusionFilters.remove(oldfp); btxnFilters.remove(oldfp); } } }
java
public void remove(String txn) { synchronized (filterMap) { // Check if old filter processor needs to be removed FilterProcessor oldfp = filterMap.get(txn); if (oldfp != null) { globalExclusionFilters.remove(oldfp); btxnFilters.remove(oldfp); } } }
[ "public", "void", "remove", "(", "String", "txn", ")", "{", "synchronized", "(", "filterMap", ")", "{", "// Check if old filter processor needs to be removed", "FilterProcessor", "oldfp", "=", "filterMap", ".", "get", "(", "txn", ")", ";", "if", "(", "oldfp", "!...
This method removes the transaction. @param txn The name of the transaction
[ "This", "method", "removes", "the", "transaction", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FilterManager.java#L111-L120
train
hawkular/hawkular-apm
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FilterManager.java
FilterManager.getFilterProcessor
public FilterProcessor getFilterProcessor(String endpoint) { FilterProcessor ret = (onlyNamedTransactions ? null : unnamedBTxn); synchronized (filterMap) { // First check if a global exclusion filter applies 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; } } // Check if transaction specific applies 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; }
java
public FilterProcessor getFilterProcessor(String endpoint) { FilterProcessor ret = (onlyNamedTransactions ? null : unnamedBTxn); synchronized (filterMap) { // First check if a global exclusion filter applies 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; } } // Check if transaction specific applies 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; }
[ "public", "FilterProcessor", "getFilterProcessor", "(", "String", "endpoint", ")", "{", "FilterProcessor", "ret", "=", "(", "onlyNamedTransactions", "?", "null", ":", "unnamedBTxn", ")", ";", "synchronized", "(", "filterMap", ")", "{", "// First check if a global excl...
This method determines whether the supplied endpoint is associated with a defined transaction, or valid due to global inclusion criteria. @param endpoint The endpoint @return The filter processor, with empty txn name if endpoint globally valid, or null if endpoint should be excluded
[ "This", "method", "determines", "whether", "the", "supplied", "endpoint", "is", "associated", "with", "a", "defined", "transaction", "or", "valid", "due", "to", "global", "inclusion", "criteria", "." ]
57a4df0611b359597626563ea5f9ac64d4bb2533
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FilterManager.java#L131-L168
train
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/EmojiApi.java
EmojiApi.search
public static List<EmojiChar> search(String... annotations) { return Emoji.findByAnnotations(SPACE_JOINER.join(annotations)); }
java
public static List<EmojiChar> search(String... annotations) { return Emoji.findByAnnotations(SPACE_JOINER.join(annotations)); }
[ "public", "static", "List", "<", "EmojiChar", ">", "search", "(", "String", "...", "annotations", ")", "{", "return", "Emoji", ".", "findByAnnotations", "(", "SPACE_JOINER", ".", "join", "(", "annotations", ")", ")", ";", "}" ]
Finds matching Emoji character by its annotated metadata. @param annotations The annotation tags to be matched @return A list containing the instances of the marching characters
[ "Finds", "matching", "Emoji", "character", "by", "its", "annotated", "metadata", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-emoji/src/main/java/humanize/emoji/EmojiApi.java#L115-L118
train
mfornos/humanize
humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java
ExtendedMessageFormat.applyPattern
@Override 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); } } //$FALL-THROUGH$ stripCustom.append(c[pos.getIndex()]); next(pos); } super.applyPattern(stripCustom.toString()); toPattern = insertFormats(super.toPattern(), foundDescriptions); if (containsElements(foundFormats)) { Format[] origFormats = getFormats(); // only loop over what we know we have, as MessageFormat on Java 1.3 // seems to provide an extra format element: 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); } }
java
@Override 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); } } //$FALL-THROUGH$ stripCustom.append(c[pos.getIndex()]); next(pos); } super.applyPattern(stripCustom.toString()); toPattern = insertFormats(super.toPattern(), foundDescriptions); if (containsElements(foundFormats)) { Format[] origFormats = getFormats(); // only loop over what we know we have, as MessageFormat on Java 1.3 // seems to provide an extra format element: 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); } }
[ "@", "Override", "public", "final", "void", "applyPattern", "(", "String", "pattern", ")", "{", "if", "(", "hasRegistry", "(", ")", ")", "{", "super", ".", "applyPattern", "(", "pattern", ")", ";", "toPattern", "=", "super", ".", "toPattern", "(", ")", ...
Apply the specified pattern. @param pattern String
[ "Apply", "the", "specified", "pattern", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java#L168-L260
train
mfornos/humanize
humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java
ExtendedMessageFormat.getFormat
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; }
java
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; }
[ "private", "Format", "getFormat", "(", "String", "desc", ")", "{", "if", "(", "registry", "!=", "null", ")", "{", "String", "name", "=", "desc", ";", "String", "args", "=", "\"\"", ";", "int", "i", "=", "desc", ".", "indexOf", "(", "START_FMT", ")", ...
Get a custom format from a format description. @param desc String @return Format
[ "Get", "a", "custom", "format", "from", "a", "format", "description", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java#L442-L463
train
mfornos/humanize
humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java
ExtendedMessageFormat.getQuotedString
private void getQuotedString(String pattern, ParsePosition pos, boolean escapingOn) { appendQuotedString(pattern, pos, null, escapingOn); }
java
private void getQuotedString(String pattern, ParsePosition pos, boolean escapingOn) { appendQuotedString(pattern, pos, null, escapingOn); }
[ "private", "void", "getQuotedString", "(", "String", "pattern", ",", "ParsePosition", "pos", ",", "boolean", "escapingOn", ")", "{", "appendQuotedString", "(", "pattern", ",", "pos", ",", "null", ",", "escapingOn", ")", ";", "}" ]
Consume quoted string only @param pattern pattern to parse @param pos current parse position @param escapingOn whether to process escaped quotes
[ "Consume", "quoted", "string", "only" ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java#L475-L479
train
mfornos/humanize
humanize-taglib/src/main/java/org/apache/taglibs/standard/tag/common/fmt/HumanizeMessageSupport.java
HumanizeMessageSupport.doEndTag
public int doEndTag() throws JspException { String key = null; LocalizationContext locCtxt = null; // determine the message key by... if (keySpecified) { // ... reading 'key' attribute key = keyAttrValue; } else { // ... retrieving and trimming our body 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) { // use resource bundle from parent <bundle> tag BundleSupport parent = (BundleSupport) t; locCtxt = parent.getLocalizationContext(); prefix = parent.getPrefix(); } else { locCtxt = BundleSupport.getLocalizationContext(pageContext); } } else { // localization context taken from 'bundle' attribute 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 { // prepend 'prefix' attribute from parent bundle if (prefix != null) key = prefix + key; message = bundle.getString(key); // Perform parametric replacement if required if (!params.isEmpty()) { Object[] messageArgs = params.toArray(); Locale locale; if (locCtxt.getLocale() != null) { locale = locCtxt.getLocale(); } else { // For consistency with the <fmt:formatXXX> actions, // we try to get a locale that matches the user's // preferences // as well as the locales supported by 'date' and // 'number'. // System.out.println("LOCALE-LESS LOCCTXT: GETTING FORMATTING LOCALE"); locale = SetLocaleSupport.getFormattingLocale(pageContext); // System.out.println("LOCALE: " + locale); } 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; }
java
public int doEndTag() throws JspException { String key = null; LocalizationContext locCtxt = null; // determine the message key by... if (keySpecified) { // ... reading 'key' attribute key = keyAttrValue; } else { // ... retrieving and trimming our body 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) { // use resource bundle from parent <bundle> tag BundleSupport parent = (BundleSupport) t; locCtxt = parent.getLocalizationContext(); prefix = parent.getPrefix(); } else { locCtxt = BundleSupport.getLocalizationContext(pageContext); } } else { // localization context taken from 'bundle' attribute 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 { // prepend 'prefix' attribute from parent bundle if (prefix != null) key = prefix + key; message = bundle.getString(key); // Perform parametric replacement if required if (!params.isEmpty()) { Object[] messageArgs = params.toArray(); Locale locale; if (locCtxt.getLocale() != null) { locale = locCtxt.getLocale(); } else { // For consistency with the <fmt:formatXXX> actions, // we try to get a locale that matches the user's // preferences // as well as the locales supported by 'date' and // 'number'. // System.out.println("LOCALE-LESS LOCCTXT: GETTING FORMATTING LOCALE"); locale = SetLocaleSupport.getFormattingLocale(pageContext); // System.out.println("LOCALE: " + locale); } 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; }
[ "public", "int", "doEndTag", "(", ")", "throws", "JspException", "{", "String", "key", "=", "null", ";", "LocalizationContext", "locCtxt", "=", "null", ";", "// determine the message key by...", "if", "(", "keySpecified", ")", "{", "// ... reading 'key' attribute", ...
Tag attributes known at translation time
[ "Tag", "attributes", "known", "at", "translation", "time" ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-taglib/src/main/java/org/apache/taglibs/standard/tag/common/fmt/HumanizeMessageSupport.java#L102-L213
train
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/Emoji.java
Emoji.codePointsToString
public static String codePointsToString(String... points) { StringBuilder ret = new StringBuilder(); for (String hexPoint : points) { ret.append(codePointToString(hexPoint)); } return ret.toString(); }
java
public static String codePointsToString(String... points) { StringBuilder ret = new StringBuilder(); for (String hexPoint : points) { ret.append(codePointToString(hexPoint)); } return ret.toString(); }
[ "public", "static", "String", "codePointsToString", "(", "String", "...", "points", ")", "{", "StringBuilder", "ret", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "hexPoint", ":", "points", ")", "{", "ret", ".", "append", "(", "codePoi...
Transforms a list of Unicode code points, as hex strings, into a proper encoded string. @param points The list of Unicode code point as a hex strings @return the concatenation of the proper encoded string for the given points @see Emoji#codePointToString(String)
[ "Transforms", "a", "list", "of", "Unicode", "code", "points", "as", "hex", "strings", "into", "a", "proper", "encoded", "string", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-emoji/src/main/java/humanize/emoji/Emoji.java#L59-L69
train
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/Emoji.java
Emoji.codePointToString
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; }
java
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; }
[ "public", "static", "String", "codePointToString", "(", "String", "point", ")", "{", "String", "ret", ";", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "point", ")", ")", "{", "return", "point", ";", "}", "int", "unicodeScalar", "=", "Integer", ".", ...
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. @param point The Unicode code point as a hex string @return the proper encoded string reification of a given point
[ "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", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-emoji/src/main/java/humanize/emoji/Emoji.java#L80-L100
train
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/Emoji.java
Emoji.findByVendorCodePoint
public static EmojiChar findByVendorCodePoint(Vendor vendor, String point) { Emoji emoji = Emoji.getInstance(); return emoji._findByVendorCodePoint(vendor, point); }
java
public static EmojiChar findByVendorCodePoint(Vendor vendor, String point) { Emoji emoji = Emoji.getInstance(); return emoji._findByVendorCodePoint(vendor, point); }
[ "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. @param vendor the vendor @param point the raw character for the code point in the vendor space @return the corresponding emoji character or null if not found
[ "Finds", "an", "emoji", "character", "by", "vendor", "code", "point", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-emoji/src/main/java/humanize/emoji/Emoji.java#L147-L151
train
mfornos/humanize
humanize-slim/src/main/java/humanize/spi/MessageFormat.java
MessageFormat.render
public StringBuffer render(StringBuffer buffer, Object... arguments) { return format(arguments, buffer, null); }
java
public StringBuffer render(StringBuffer buffer, Object... arguments) { return format(arguments, buffer, null); }
[ "public", "StringBuffer", "render", "(", "StringBuffer", "buffer", ",", "Object", "...", "arguments", ")", "{", "return", "format", "(", "arguments", ",", "buffer", ",", "null", ")", ";", "}" ]
Formats the current pattern with the given arguments. @param buffer The StringBuffer @param arguments The formatting arguments @return StringBuffer with the formatted message
[ "Formats", "the", "current", "pattern", "with", "the", "given", "arguments", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/spi/MessageFormat.java#L108-L113
train
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/EmojiChar.java
EmojiChar.mapTo
public String mapTo(Vendor vendor) { String[] m = getMapping(vendor); return m == null ? null : m[VENDOR_MAP_RAW]; }
java
public String mapTo(Vendor vendor) { String[] m = getMapping(vendor); return m == null ? null : m[VENDOR_MAP_RAW]; }
[ "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. @param vendor the vendor @return the raw character for the vendor specified, null if not found
[ "Gets", "the", "raw", "character", "value", "of", "this", "emoji", "character", "for", "a", "given", "vendor", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-emoji/src/main/java/humanize/emoji/EmojiChar.java#L229-L233
train
mfornos/humanize
humanize-joda/src/main/java/humanize/time/joda/FormatTables.java
FormatTables.get
public static Map<String, Format> get(String name) { return instance().methods.get(name); }
java
public static Map<String, Format> get(String name) { return instance().methods.get(name); }
[ "public", "static", "Map", "<", "String", ",", "Format", ">", "get", "(", "String", "name", ")", "{", "return", "instance", "(", ")", ".", "methods", ".", "get", "(", "name", ")", ";", "}" ]
Retrieves a variants map for a given format name. @param name The format name @return a mutable map of variants
[ "Retrieves", "a", "variants", "map", "for", "a", "given", "format", "name", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-joda/src/main/java/humanize/time/joda/FormatTables.java#L29-L32
train
mfornos/humanize
humanize-slim/src/main/java/humanize/time/PrettyTimeFormat.java
PrettyTimeFormat.format
public String format(Date ref, Date then) { return prettyTime.format(DurationHelper.calculateDuration(ref, then, prettyTime.getUnits())); }
java
public String format(Date ref, Date then) { return prettyTime.format(DurationHelper.calculateDuration(ref, then, prettyTime.getUnits())); }
[ "public", "String", "format", "(", "Date", "ref", ",", "Date", "then", ")", "{", "return", "prettyTime", ".", "format", "(", "DurationHelper", ".", "calculateDuration", "(", "ref", ",", "then", ",", "prettyTime", ".", "getUnits", "(", ")", ")", ")", ";",...
Convenience format method. @param ref The date of reference. @param then The future date. @return a relative format date as text representation
[ "Convenience", "format", "method", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/time/PrettyTimeFormat.java#L87-L90
train
mfornos/humanize
humanize-slim/src/main/java/humanize/time/PrettyTimeFormat.java
PrettyTimeFormat.format
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); }
java
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); }
[ "public", "String", "format", "(", "Date", "ref", ",", "Date", "then", ",", "long", "precision", ")", "{", "List", "<", "Duration", ">", "durations", "=", "DurationHelper", ".", "calculatePreciseDuration", "(", "ref", ",", "then", ",", "prettyTime", ".", "...
Convenience format method for precise durations. @param ref The date of reference. @param then The future date. @param precision The precision to retain in milliseconds. @return a relative format date as text representation or an empty string if no durations are retained
[ "Convenience", "format", "method", "for", "precise", "durations", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/time/PrettyTimeFormat.java#L104-L109
train
mfornos/humanize
humanize-icu/src/main/java/humanize/ICUHumanize.java
ICUHumanize.transliterate
public static String transliterate(final String text, final String id) { Transliterator transliterator = Transliterator.getInstance(id); return transliterator.transform(text); }
java
public static String transliterate(final String text, final String id) { Transliterator transliterator = Transliterator.getInstance(id); return transliterator.transform(text); }
[ "public", "static", "String", "transliterate", "(", "final", "String", "text", ",", "final", "String", "id", ")", "{", "Transliterator", "transliterator", "=", "Transliterator", ".", "getInstance", "(", "id", ")", ";", "return", "transliterator", ".", "transform...
Converts the characters of the given text to the specified script. <p> The simplest identifier is a 'basic ID'. </p> <pre> basicID := (&lt;source&gt; "-")? &lt;target&gt; ("/" &lt;variant&gt;)? </pre> <p> A basic ID typically names a source and target. In "Katakana-Latin", "Katakana" is the source and "Latin" is the target. The source specifier describes the characters or strings that the transform will modify. The target specifier describes the result of the modification. If the source is not given, then the source is "Any", the set of all characters. Source and Target specifiers can be Script IDs (long like "Latin" or short like "Latn"), Unicode language Identifiers (like fr, en_US, or zh_Hant), or special tags (like Any or Hex). For example: </p> <pre> Katakana-Latin Null Hex-Any/Perl Latin-el Greek-en_US/UNGEGN </pre> <p> Some basic IDs contain a further specifier following a forward slash. This is the variant, and it further specifies the transform when several versions of a single transformation are possible. For example, ICU provides several transforms that convert from Unicode characters to escaped representations. These include standard Unicode syntax "U+4E01", Perl syntax "\x{4E01}", XML syntax "&#x4E01;", and others. The transforms for these operations are named "Any-Hex/Unicode", "Any-Hex/Perl", and "Any-Hex/XML", respectively. If no variant is specified, then the default variant is selected. In the example of "Any-Hex", this is the Java variant (for historical reasons), so "Any-Hex" is equivalent to "Any-Hex/Java". </p> @param text The text to be transformed @param id The transliterator identifier @return transliterated text
[ "Converts", "the", "characters", "of", "the", "given", "text", "to", "the", "specified", "script", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-icu/src/main/java/humanize/ICUHumanize.java#L1740-L1744
train
mfornos/humanize
humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java
JodaTimeFormatProvider.factory
public static FormatFactory factory() { return new FormatFactory() { @Override 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); } }; }
java
public static FormatFactory factory() { return new FormatFactory() { @Override 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); } }; }
[ "public", "static", "FormatFactory", "factory", "(", ")", "{", "return", "new", "FormatFactory", "(", ")", "{", "@", "Override", "public", "Format", "getFormat", "(", "String", "name", ",", "String", "args", ",", "Locale", "locale", ")", "{", "Map", "<", ...
Creates a factory for the specified format. @return FormatFactory instance
[ "Creates", "a", "factory", "for", "the", "specified", "format", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java#L34-L53
train
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.naturalDay
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); }
java
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); }
[ "public", "static", "String", "naturalDay", "(", "int", "style", ",", "Date", "then", ")", "{", "Date", "today", "=", "new", "Date", "(", ")", ";", "long", "delta", "=", "then", ".", "getTime", "(", ")", "-", "today", ".", "getTime", "(", ")", ";",...
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. @param style The style of the Date @param then The date (GMT) @return String with 'today', 'tomorrow' or 'yesterday' compared to current day. Otherwise, returns a string formatted according to a locale sensitive DateFormat.
[ "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",...
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L1492-L1506
train
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.naturalTime
public static String naturalTime(Date reference, Date duration) { return context.get().formatRelativeDate(reference, duration); }
java
public static String naturalTime(Date reference, Date duration) { return context.get().formatRelativeDate(reference, duration); }
[ "public", "static", "String", "naturalTime", "(", "Date", "reference", ",", "Date", "duration", ")", "{", "return", "context", ".", "get", "(", ")", ".", "formatRelativeDate", "(", "reference", ",", "duration", ")", ";", "}" ]
Computes both past and future relative dates. <p> E.g. 'one day ago', 'one day from now', '10 years ago', '3 minutes from now', 'right now' and so on. @param reference The reference @param duration The duration @return String representing the relative date
[ "Computes", "both", "past", "and", "future", "relative", "dates", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L1558-L1561
train
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.ordinal
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)); }
java
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)); }
[ "public", "static", "String", "ordinal", "(", "Number", "value", ")", "{", "int", "v", "=", "value", ".", "intValue", "(", ")", ";", "int", "vc", "=", "v", "%", "100", ";", "if", "(", "vc", ">", "10", "&&", "vc", "<", "14", ")", "return", "Stri...
Converts a number to its ordinal as a string. <p> E.g. 1 becomes '1st', 2 becomes '2nd', 3 becomes '3rd', etc. @param value The number to convert @return String representing the number as ordinal
[ "Converts", "a", "number", "to", "its", "ordinal", "as", "a", "string", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L1744-L1753
train
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.times
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()) }); }
java
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()) }); }
[ "public", "static", "String", "times", "(", "final", "Number", "num", ")", "{", "java", ".", "text", ".", "MessageFormat", "f", "=", "new", "java", ".", "text", ".", "MessageFormat", "(", "context", ".", "get", "(", ")", ".", "getBundle", "(", ")", "...
Interprets numbers as occurrences. @param num The number of occurrences @return textual representation of the number as occurrences
[ "Interprets", "numbers", "as", "occurrences", "." ]
59fc103045de9d217c9e77dbcb7621f992f46c63
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L2731-L2738
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/alphabet/NormalAlphabet.java
NormalAlphabet.getCentralCuts
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."); } }
java
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."); } }
[ "public", "double", "[", "]", "getCentralCuts", "(", "Integer", "size", ")", "throws", "SAXException", "{", "switch", "(", "size", ")", "{", "case", "2", ":", "return", "center_case2", ";", "case", "3", ":", "return", "center_case3", ";", "case", "4", ":...
Produces central cut intervals lines for the normal distribution. @param size the Alphabet size [2 - 20]. @return an array of central lines for the specified alphabet size. @throws SAXException if error occurs.
[ "Produces", "central", "cut", "intervals", "lines", "for", "the", "normal", "distribution", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/alphabet/NormalAlphabet.java#L728-L771
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/datastructure/DoublyLinkedSortedList.java
DoublyLinkedSortedList.addElement
public void addElement(T data) { Node<T> newNode = new Node<T>(data); if (isEmpty()) { // // if it is the very first node in the list first = newNode; size = 1; } else { // if this node is greater than the list's head // 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 node is the current node less than the new one // 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 all list elements are greater than the new one // if (null == current) { prev.next = newNode; newNode.prev = prev; size++; } if (size > this.maxSize) { dropLastElement(); } } } }
java
public void addElement(T data) { Node<T> newNode = new Node<T>(data); if (isEmpty()) { // // if it is the very first node in the list first = newNode; size = 1; } else { // if this node is greater than the list's head // 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 node is the current node less than the new one // 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 all list elements are greater than the new one // if (null == current) { prev.next = newNode; newNode.prev = prev; size++; } if (size > this.maxSize) { dropLastElement(); } } } }
[ "public", "void", "addElement", "(", "T", "data", ")", "{", "Node", "<", "T", ">", "newNode", "=", "new", "Node", "<", "T", ">", "(", "data", ")", ";", "if", "(", "isEmpty", "(", ")", ")", "{", "//", "// if it is the very first node in the list", "firs...
Adds a data instance. @param data the data to put in the list.
[ "Adds", "a", "data", "instance", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/datastructure/DoublyLinkedSortedList.java#L102-L160
train
jMotif/SAX
src/main/java/net/seninp/util/SortedArrayList.java
SortedArrayList.insertSorted
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); } }
java
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); } }
[ "public", "void", "insertSorted", "(", "T", "value", ")", "{", "add", "(", "value", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Comparable", "<", "T", ">", "cmp", "=", "(", "Comparable", "<", "T", ">", ")", "value", ";", "for", "("...
Inserts an element and sorts the array. @param value the value to insert.
[ "Inserts", "an", "element", "and", "sorts", "the", "array", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/util/SortedArrayList.java#L27-L34
train
jMotif/SAX
src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java
EuclideanDistance.distance2
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"); } }
java
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"); } }
[ "public", "double", "distance2", "(", "double", "[", "]", "point1", ",", "double", "[", "]", "point2", ")", "throws", "Exception", "{", "if", "(", "point1", ".", "length", "==", "point2", ".", "length", ")", "{", "Double", "sum", "=", "0D", ";", "for...
Calculates the square of the Euclidean distance between two multidimensional points represented by the rational vectors. @param point1 The first point. @param point2 The second point. @return The Euclidean distance. @throws Exception In the case of error.
[ "Calculates", "the", "square", "of", "the", "Euclidean", "distance", "between", "two", "multidimensional", "points", "represented", "by", "the", "rational", "vectors", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java#L75-L87
train
jMotif/SAX
src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java
EuclideanDistance.distance2
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"); } }
java
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"); } }
[ "public", "long", "distance2", "(", "int", "[", "]", "point1", ",", "int", "[", "]", "point2", ")", "throws", "Exception", "{", "if", "(", "point1", ".", "length", "==", "point2", ".", "length", ")", "{", "long", "sum", "=", "0", ";", "for", "(", ...
Calculates the square of the Euclidean distance between two multidimensional points represented by integer vectors. @param point1 The first point. @param point2 The second point. @return The Euclidean distance. @throws Exception In the case of error.
[ "Calculates", "the", "square", "of", "the", "Euclidean", "distance", "between", "two", "multidimensional", "points", "represented", "by", "integer", "vectors", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java#L98-L109
train
jMotif/SAX
src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java
EuclideanDistance.seriesDistance
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"); } }
java
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"); } }
[ "public", "double", "seriesDistance", "(", "double", "[", "]", "[", "]", "series1", ",", "double", "[", "]", "[", "]", "series2", ")", "throws", "Exception", "{", "if", "(", "series1", ".", "length", "==", "series2", ".", "length", ")", "{", "Double", ...
Calculates Euclidean distance between two multi-dimensional time-series of equal length. @param series1 The first series. @param series2 The second series. @return The eclidean distance. @throws Exception if error occures.
[ "Calculates", "Euclidean", "distance", "between", "two", "multi", "-", "dimensional", "time", "-", "series", "of", "equal", "length", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java#L119-L130
train
jMotif/SAX
src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java
EuclideanDistance.normalizedDistance
public double normalizedDistance(double[] point1, double[] point2) throws Exception { return Math.sqrt(distance2(point1, point2)) / point1.length; }
java
public double normalizedDistance(double[] point1, double[] point2) throws Exception { return Math.sqrt(distance2(point1, point2)) / point1.length; }
[ "public", "double", "normalizedDistance", "(", "double", "[", "]", "point1", ",", "double", "[", "]", "point2", ")", "throws", "Exception", "{", "return", "Math", ".", "sqrt", "(", "distance2", "(", "point1", ",", "point2", ")", ")", "/", "point1", ".", ...
Calculates the Normalized Euclidean distance between two points. @param point1 The first point. @param point2 The second point. @return The Euclidean distance. @throws Exception In the case of error.
[ "Calculates", "the", "Normalized", "Euclidean", "distance", "between", "two", "points", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java#L140-L142
train
jMotif/SAX
src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java
EuclideanDistance.earlyAbandonedDistance
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"); } }
java
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"); } }
[ "public", "Double", "earlyAbandonedDistance", "(", "double", "[", "]", "series1", ",", "double", "[", "]", "series2", ",", "double", "cutoff", ")", "throws", "Exception", "{", "if", "(", "series1", ".", "length", "==", "series2", ".", "length", ")", "{", ...
Implements Euclidean distance with early abandoning. @param series1 the first series. @param series2 the second series. @param cutoff the cut-off threshold @return the distance if it is less than cutoff or Double.NAN if it is above. @throws Exception if error occurs.
[ "Implements", "Euclidean", "distance", "with", "early", "abandoning", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java#L154-L173
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/datastructure/FrequencyTableEntry.java
FrequencyTableEntry.getStr
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; }
java
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; }
[ "public", "char", "[", "]", "getStr", "(", ")", "{", "char", "[", "]", "res", "=", "new", "char", "[", "this", ".", "payload", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "res", ".", "length", ";", "i", "++", "...
Get a string payload. @return a string payload.
[ "Get", "a", "string", "payload", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/datastructure/FrequencyTableEntry.java#L43-L49
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/datastructure/FrequencyTableEntry.java
FrequencyTableEntry.isTrivial
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; }
java
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; }
[ "public", "boolean", "isTrivial", "(", "Integer", "complexity", ")", "{", "int", "len", "=", "payload", ".", "length", ";", "if", "(", "(", "null", "==", "complexity", ")", "||", "(", "len", "<", "2", ")", ")", "{", "return", "true", ";", "}", "els...
Check the complexity of the string. @param complexity If 1 - single letter used, 2 - two or more letters, 3 - 3 or more etc.. @return Returns true if complexity conditions are met.
[ "Check", "the", "complexity", "of", "the", "string", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/datastructure/FrequencyTableEntry.java#L103-L124
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/motif/EMMAImplementation.java
EMMAImplementation.ADM
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++) { // diagonal wouldn't count anyway 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; }
java
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++) { // diagonal wouldn't count anyway 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; }
[ "private", "static", "MotifRecord", "ADM", "(", "double", "[", "]", "series", ",", "ArrayList", "<", "Integer", ">", "neighborhood", ",", "int", "motifSize", ",", "double", "range", ",", "double", "znormThreshold", ")", "throws", "Exception", "{", "MotifRecord...
This is not a real ADM implementation. @param series the input timeseries. @param neighborhood the neighborhood coordinates. @param motifSize the motif size. @param range the range value. @param znormThreshold z-normalization threshold. @return the best motif record found within the neighborhood. @throws Exception if error occurs.
[ "This", "is", "not", "a", "real", "ADM", "implementation", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/motif/EMMAImplementation.java#L178-L225
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/motif/EMMAImplementation.java
EMMAImplementation.isNonTrivialMatch
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; }
java
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; }
[ "private", "static", "boolean", "isNonTrivialMatch", "(", "double", "[", "]", "series", ",", "int", "i", ",", "int", "j", ",", "Integer", "motifSize", ",", "double", "range", ",", "double", "znormThreshold", ")", "{", "if", "(", "Math", ".", "abs", "(", ...
Checks for the overlap and the range-configured distance. @param series the series to use. @param i the position of subseries a. @param j the position of subseries b. @param motifSize the motif length. @param range the range value. @param znormThreshold z-normalization threshold. @return true if all is cool, false if overlaps or above the range value.
[ "Checks", "for", "the", "overlap", "and", "the", "range", "-", "configured", "distance", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/motif/EMMAImplementation.java#L238-L252
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/motif/EMMAImplementation.java
EMMAImplementation.eaDistance
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); }
java
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); }
[ "private", "static", "Double", "eaDistance", "(", "double", "[", "]", "series", ",", "int", "a", ",", "int", "b", ",", "Integer", "motifSize", ",", "double", "range", ",", "double", "znormThreshold", ")", "{", "distCounter", "++", ";", "double", "cutOff2",...
Early abandoning distance configure by range. @param series the series to use. @param a the position of subseries a. @param b the position of subseries b. @param motifSize the motif length. @param range the range value. @param znormThreshold z-normalization threshold. @return a distance value or NAN if above the threshold.
[ "Early", "abandoning", "distance", "configure", "by", "range", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/motif/EMMAImplementation.java#L265-L285
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/datastructure/SAXRecord.java
SAXRecord.compareTo
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "int", "compareTo", "(", "SAXRecord", "o", ")", "{", "int", "a", "=", "this", ".", "occurrences", ".", "size", "(", ")", ";", "int", "b", "=", "o", ".", "getIndexes", "(", ")", ".", "size", "(", ")", ";", "if", "(", "...
This comparator compares entries by the length of the entries array - i.e. by the total frequency of entry occurrence. @param o an entry to compare with. @return results of comparison.
[ "This", "comparator", "compares", "entries", "by", "the", "length", "of", "the", "entries", "array", "-", "i", ".", "e", ".", "by", "the", "total", "frequency", "of", "entry", "occurrence", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/datastructure/SAXRecord.java#L85-L96
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/discord/BruteForceDiscordImplementation.java
BruteForceDiscordImplementation.series2BruteForceDiscords
public static DiscordRecords series2BruteForceDiscords(double[] series, Integer windowSize, int discordCollectionSize, SlidingWindowMarkerAlgorithm marker, double nThreshold) throws Exception { DiscordRecords discords = new DiscordRecords(); // init new registry to the full length, but mark the end of it // 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); // mark start and number of iterations Date start = new Date(); DiscordRecord bestDiscord = findBestDiscordBruteForce(series, windowSize, globalTrackVisitRegistry, nThreshold); bestDiscord.setPayload("#" + discordCounter); Date end = new Date(); // if the discord is null we getting out of the search 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()); // collect the result // discords.add(bestDiscord); // and maintain data structures // marker.markVisited(globalTrackVisitRegistry, bestDiscord.getPosition(), windowSize); discordCounter++; } // done deal // return discords; }
java
public static DiscordRecords series2BruteForceDiscords(double[] series, Integer windowSize, int discordCollectionSize, SlidingWindowMarkerAlgorithm marker, double nThreshold) throws Exception { DiscordRecords discords = new DiscordRecords(); // init new registry to the full length, but mark the end of it // 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); // mark start and number of iterations Date start = new Date(); DiscordRecord bestDiscord = findBestDiscordBruteForce(series, windowSize, globalTrackVisitRegistry, nThreshold); bestDiscord.setPayload("#" + discordCounter); Date end = new Date(); // if the discord is null we getting out of the search 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()); // collect the result // discords.add(bestDiscord); // and maintain data structures // marker.markVisited(globalTrackVisitRegistry, bestDiscord.getPosition(), windowSize); discordCounter++; } // done deal // return discords; }
[ "public", "static", "DiscordRecords", "series2BruteForceDiscords", "(", "double", "[", "]", "series", ",", "Integer", "windowSize", ",", "int", "discordCollectionSize", ",", "SlidingWindowMarkerAlgorithm", "marker", ",", "double", "nThreshold", ")", "throws", "Exception...
Brute force discord search implementation. BRUTE FORCE algorithm. @param series the data we work with. @param windowSize the sliding window size. @param discordCollectionSize the number of discords we look for. @param marker the marker window algorithm implementation. @param nThreshold the z-Normalization threshold value. @return discords. @throws Exception if error occurs.
[ "Brute", "force", "discord", "search", "implementation", ".", "BRUTE", "FORCE", "algorithm", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/discord/BruteForceDiscordImplementation.java#L37-L90
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/discord/BruteForceDiscordImplementation.java
BruteForceDiscordImplementation.findBestDiscordBruteForce
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())) { // outer loop outerRegistry.markVisited(outerIdx); // imo this is a useless piece // check the global visits registry // if (globalRegistry.isVisited(outerIdx)) { // continue; // } 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())) { // inner loop innerRegistry.markVisited(innerIdx); if (Math.abs(outerIdx - innerIdx) > windowSize) { // > means they shall not overlap even // over a single point 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; }
java
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())) { // outer loop outerRegistry.markVisited(outerIdx); // imo this is a useless piece // check the global visits registry // if (globalRegistry.isVisited(outerIdx)) { // continue; // } 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())) { // inner loop innerRegistry.markVisited(innerIdx); if (Math.abs(outerIdx - innerIdx) > windowSize) { // > means they shall not overlap even // over a single point 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; }
[ "private", "static", "DiscordRecord", "findBestDiscordBruteForce", "(", "double", "[", "]", "series", ",", "Integer", "windowSize", ",", "VisitRegistry", "globalRegistry", ",", "double", "nThreshold", ")", "throws", "Exception", "{", "Date", "start", "=", "new", "...
Finds the best discord. BRUTE FORCE algorithm. @param series the data. @param windowSize the SAX sliding window size. @param globalRegistry the visit registry to use. @param nThreshold the z-Normalization threshold value. @return the best discord with respect to registry. @throws Exception if error occurs.
[ "Finds", "the", "best", "discord", ".", "BRUTE", "FORCE", "algorithm", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/discord/BruteForceDiscordImplementation.java#L102-L170
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.ts2string
public char[] ts2string(double[] ts, int paaSize, double[] cuts, double nThreshold) throws SAXException { if (paaSize == ts.length) { return tsProcessor.ts2String(tsProcessor.znorm(ts, nThreshold), cuts); } else { // perform PAA conversion double[] paa = tsProcessor.paa(tsProcessor.znorm(ts, nThreshold), paaSize); return tsProcessor.ts2String(paa, cuts); } }
java
public char[] ts2string(double[] ts, int paaSize, double[] cuts, double nThreshold) throws SAXException { if (paaSize == ts.length) { return tsProcessor.ts2String(tsProcessor.znorm(ts, nThreshold), cuts); } else { // perform PAA conversion double[] paa = tsProcessor.paa(tsProcessor.znorm(ts, nThreshold), paaSize); return tsProcessor.ts2String(paa, cuts); } }
[ "public", "char", "[", "]", "ts2string", "(", "double", "[", "]", "ts", ",", "int", "paaSize", ",", "double", "[", "]", "cuts", ",", "double", "nThreshold", ")", "throws", "SAXException", "{", "if", "(", "paaSize", "==", "ts", ".", "length", ")", "{"...
Convert the timeseries into SAX string representation. @param ts the timeseries. @param paaSize the PAA size. @param cuts the alphabet cuts. @param nThreshold the normalization thresholds. @return The SAX representation for timeseries. @throws SAXException if error occurs.
[ "Convert", "the", "timeseries", "into", "SAX", "string", "representation", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L49-L60
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.ts2saxByChunking
public SAXRecords ts2saxByChunking(double[] ts, int paaSize, double[] cuts, double nThreshold) throws SAXException { SAXRecords saxFrequencyData = new SAXRecords(); // Z normalize it double[] normalizedTS = tsProcessor.znorm(ts, nThreshold); // perform PAA conversion if needed double[] paa = tsProcessor.paa(normalizedTS, paaSize); // Convert the PAA to a string. char[] currentString = tsProcessor.ts2String(paa, cuts); // create the datastructure for (int i = 0; i < currentString.length; i++) { char c = currentString[i]; int pos = (int) Math.floor(i * ts.length / currentString.length); saxFrequencyData.add(String.valueOf(c).toCharArray(), pos); } return saxFrequencyData; }
java
public SAXRecords ts2saxByChunking(double[] ts, int paaSize, double[] cuts, double nThreshold) throws SAXException { SAXRecords saxFrequencyData = new SAXRecords(); // Z normalize it double[] normalizedTS = tsProcessor.znorm(ts, nThreshold); // perform PAA conversion if needed double[] paa = tsProcessor.paa(normalizedTS, paaSize); // Convert the PAA to a string. char[] currentString = tsProcessor.ts2String(paa, cuts); // create the datastructure for (int i = 0; i < currentString.length; i++) { char c = currentString[i]; int pos = (int) Math.floor(i * ts.length / currentString.length); saxFrequencyData.add(String.valueOf(c).toCharArray(), pos); } return saxFrequencyData; }
[ "public", "SAXRecords", "ts2saxByChunking", "(", "double", "[", "]", "ts", ",", "int", "paaSize", ",", "double", "[", "]", "cuts", ",", "double", "nThreshold", ")", "throws", "SAXException", "{", "SAXRecords", "saxFrequencyData", "=", "new", "SAXRecords", "(",...
Converts the input time series into a SAX data structure via chunking and Z normalization. @param ts the input data. @param paaSize the PAA size. @param cuts the Alphabet cuts. @param nThreshold the normalization threshold value. @return SAX representation of the time series. @throws SAXException if error occurs.
[ "Converts", "the", "input", "time", "series", "into", "a", "SAX", "data", "structure", "via", "chunking", "and", "Z", "normalization", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L73-L96
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.charDistance
public int charDistance(char a, char b) { return Math.abs(Character.getNumericValue(a) - Character.getNumericValue(b)); }
java
public int charDistance(char a, char b) { return Math.abs(Character.getNumericValue(a) - Character.getNumericValue(b)); }
[ "public", "int", "charDistance", "(", "char", "a", ",", "char", "b", ")", "{", "return", "Math", ".", "abs", "(", "Character", ".", "getNumericValue", "(", "a", ")", "-", "Character", ".", "getNumericValue", "(", "b", ")", ")", ";", "}" ]
Compute the distance between the two chars based on the ASCII symbol codes. @param a The first char. @param b The second char. @return The distance.
[ "Compute", "the", "distance", "between", "the", "two", "chars", "based", "on", "the", "ASCII", "symbol", "codes", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L316-L318
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.strDistance
public int strDistance(char[] a, char[] b) throws SAXException { if (a.length == b.length) { int distance = 0; for (int i = 0; i < a.length; i++) { int tDist = Math.abs(Character.getNumericValue(a[i]) - Character.getNumericValue(b[i])); distance += tDist; } return distance; } else { throw new SAXException("Unable to compute SAX distance, string lengths are not equal"); } }
java
public int strDistance(char[] a, char[] b) throws SAXException { if (a.length == b.length) { int distance = 0; for (int i = 0; i < a.length; i++) { int tDist = Math.abs(Character.getNumericValue(a[i]) - Character.getNumericValue(b[i])); distance += tDist; } return distance; } else { throw new SAXException("Unable to compute SAX distance, string lengths are not equal"); } }
[ "public", "int", "strDistance", "(", "char", "[", "]", "a", ",", "char", "[", "]", "b", ")", "throws", "SAXException", "{", "if", "(", "a", ".", "length", "==", "b", ".", "length", ")", "{", "int", "distance", "=", "0", ";", "for", "(", "int", ...
Compute the distance between the two strings, this function use the numbers associated with ASCII codes, i.e. distance between a and b would be 1. @param a The first string. @param b The second string. @return The pairwise distance. @throws SAXException if length are differ.
[ "Compute", "the", "distance", "between", "the", "two", "strings", "this", "function", "use", "the", "numbers", "associated", "with", "ASCII", "codes", "i", ".", "e", ".", "distance", "between", "a", "and", "b", "would", "be", "1", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L329-L341
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.saxMinDist
public double saxMinDist(char[] a, char[] b, double[][] distanceMatrix, int n, int w) throws SAXException { if (a.length == b.length) { double dist = 0.0D; for (int i = 0; i < a.length; i++) { if (Character.isLetter(a[i]) && Character.isLetter(b[i])) { // ... forms have numeric values from 10 through 35 int numA = Character.getNumericValue(a[i]) - 10; int numB = Character.getNumericValue(b[i]) - 10; int maxIdx = distanceMatrix[0].length; if (numA > (maxIdx - 1) || numA < 0 || numB > (maxIdx - 1) || numB < 0) { throw new SAXException( "The character index greater than " + maxIdx + " or less than 0!"); } double localDist = distanceMatrix[numA][numB]; dist = dist + localDist * localDist; } else { throw new SAXException("Non-literal character found!"); } } return Math.sqrt((double) n / (double) w) * Math.sqrt(dist); } else { throw new SAXException("Data arrays lengths are not equal!"); } }
java
public double saxMinDist(char[] a, char[] b, double[][] distanceMatrix, int n, int w) throws SAXException { if (a.length == b.length) { double dist = 0.0D; for (int i = 0; i < a.length; i++) { if (Character.isLetter(a[i]) && Character.isLetter(b[i])) { // ... forms have numeric values from 10 through 35 int numA = Character.getNumericValue(a[i]) - 10; int numB = Character.getNumericValue(b[i]) - 10; int maxIdx = distanceMatrix[0].length; if (numA > (maxIdx - 1) || numA < 0 || numB > (maxIdx - 1) || numB < 0) { throw new SAXException( "The character index greater than " + maxIdx + " or less than 0!"); } double localDist = distanceMatrix[numA][numB]; dist = dist + localDist * localDist; } else { throw new SAXException("Non-literal character found!"); } } return Math.sqrt((double) n / (double) w) * Math.sqrt(dist); } else { throw new SAXException("Data arrays lengths are not equal!"); } }
[ "public", "double", "saxMinDist", "(", "char", "[", "]", "a", ",", "char", "[", "]", "b", ",", "double", "[", "]", "[", "]", "distanceMatrix", ",", "int", "n", ",", "int", "w", ")", "throws", "SAXException", "{", "if", "(", "a", ".", "length", "=...
This function implements SAX MINDIST function which uses alphabet based distance matrix. @param a The SAX string. @param b The SAX string. @param distanceMatrix The distance matrix to use. @param n the time series length (sliding window length). @param w the number of PAA segments. @return distance between strings. @throws SAXException If error occurs.
[ "This", "function", "implements", "SAX", "MINDIST", "function", "which", "uses", "alphabet", "based", "distance", "matrix", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L354-L380
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.checkMinDistIsZero
public boolean checkMinDistIsZero(char[] a, char[] b) { for (int i = 0; i < a.length; i++) { if (charDistance(a[i], b[i]) > 1) { return false; } } return true; }
java
public boolean checkMinDistIsZero(char[] a, char[] b) { for (int i = 0; i < a.length; i++) { if (charDistance(a[i], b[i]) > 1) { return false; } } return true; }
[ "public", "boolean", "checkMinDistIsZero", "(", "char", "[", "]", "a", ",", "char", "[", "]", "b", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "a", ".", "length", ";", "i", "++", ")", "{", "if", "(", "charDistance", "(", "a", "...
Check for trivial mindist case. @param a first string. @param b second string. @return true if mindist between strings is zero.
[ "Check", "for", "trivial", "mindist", "case", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L389-L396
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.ts2Shingles
public Map<String, Integer> ts2Shingles(double[] series, int windowSize, int paaSize, int alphabetSize, NumerosityReductionStrategy strategy, double nrThreshold, int shingleSize) throws SAXException { // build all shingles String[] alphabet = new String[alphabetSize]; for (int i = 0; i < alphabetSize; i++) { alphabet[i] = String.valueOf(TSProcessor.ALPHABET[i]); } String[] allShingles = getAllPermutations(alphabet, shingleSize); // result HashMap<String, Integer> res = new HashMap<String, Integer>(allShingles.length); for (String s : allShingles) { res.put(s, 0); } // discretize SAXRecords saxData = ts2saxViaWindow(series, windowSize, paaSize, na.getCuts(alphabetSize), strategy, nrThreshold); // fill in the counts for (SAXRecord sr : saxData) { String word = String.valueOf(sr.getPayload()); int frequency = sr.getIndexes().size(); for (int i = 0; i <= word.length() - shingleSize; i++) { String shingle = word.substring(i, i + shingleSize); res.put(shingle, res.get(shingle) + frequency); } } return res; }
java
public Map<String, Integer> ts2Shingles(double[] series, int windowSize, int paaSize, int alphabetSize, NumerosityReductionStrategy strategy, double nrThreshold, int shingleSize) throws SAXException { // build all shingles String[] alphabet = new String[alphabetSize]; for (int i = 0; i < alphabetSize; i++) { alphabet[i] = String.valueOf(TSProcessor.ALPHABET[i]); } String[] allShingles = getAllPermutations(alphabet, shingleSize); // result HashMap<String, Integer> res = new HashMap<String, Integer>(allShingles.length); for (String s : allShingles) { res.put(s, 0); } // discretize SAXRecords saxData = ts2saxViaWindow(series, windowSize, paaSize, na.getCuts(alphabetSize), strategy, nrThreshold); // fill in the counts for (SAXRecord sr : saxData) { String word = String.valueOf(sr.getPayload()); int frequency = sr.getIndexes().size(); for (int i = 0; i <= word.length() - shingleSize; i++) { String shingle = word.substring(i, i + shingleSize); res.put(shingle, res.get(shingle) + frequency); } } return res; }
[ "public", "Map", "<", "String", ",", "Integer", ">", "ts2Shingles", "(", "double", "[", "]", "series", ",", "int", "windowSize", ",", "int", "paaSize", ",", "int", "alphabetSize", ",", "NumerosityReductionStrategy", "strategy", ",", "double", "nrThreshold", ",...
Converts a single time-series into map of shingle frequencies. @param series the time series. @param windowSize the sliding window size. @param paaSize the PAA segments number. @param alphabetSize the alphabet size. @param strategy the numerosity reduction strategy. @param nrThreshold the SAX normalization threshold. @param shingleSize the shingle size. @return map of shingle frequencies. @throws SAXException if error occurs.
[ "Converts", "a", "single", "time", "-", "series", "into", "map", "of", "shingle", "frequencies", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L514-L546
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.getAllPermutations
public static String[] getAllPermutations(String[] alphabet, int wordLength) { // initialize our returned list with the number of elements calculated above String[] allLists = new String[(int) Math.pow(alphabet.length, wordLength)]; // lists of length 1 are just the original elements if (wordLength == 1) return alphabet; else { // the recursion--get all lists of length 3, length 2, all the way up to 1 String[] allSublists = getAllPermutations(alphabet, wordLength - 1); // append the sublists to each element int arrayIndex = 0; for (int i = 0; i < alphabet.length; i++) { for (int j = 0; j < allSublists.length; j++) { // add the newly appended combination to the list allLists[arrayIndex] = alphabet[i] + allSublists[j]; arrayIndex++; } } return allLists; } }
java
public static String[] getAllPermutations(String[] alphabet, int wordLength) { // initialize our returned list with the number of elements calculated above String[] allLists = new String[(int) Math.pow(alphabet.length, wordLength)]; // lists of length 1 are just the original elements if (wordLength == 1) return alphabet; else { // the recursion--get all lists of length 3, length 2, all the way up to 1 String[] allSublists = getAllPermutations(alphabet, wordLength - 1); // append the sublists to each element int arrayIndex = 0; for (int i = 0; i < alphabet.length; i++) { for (int j = 0; j < allSublists.length; j++) { // add the newly appended combination to the list allLists[arrayIndex] = alphabet[i] + allSublists[j]; arrayIndex++; } } return allLists; } }
[ "public", "static", "String", "[", "]", "getAllPermutations", "(", "String", "[", "]", "alphabet", ",", "int", "wordLength", ")", "{", "// initialize our returned list with the number of elements calculated above\r", "String", "[", "]", "allLists", "=", "new", "String",...
Get all permutations of the given alphabet of given length. @param alphabet the alphabet to use. @param wordLength the word length. @return set of permutation.
[ "Get", "all", "permutations", "of", "the", "given", "alphabet", "of", "given", "length", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L555-L580
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.timeToString
public static String timeToString(long start, long finish) { Duration duration = new Duration(finish - start); // in milliseconds PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d") .appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds() .appendSuffix("s").appendMillis().appendSuffix("ms").toFormatter(); return formatter.print(duration.toPeriod()); }
java
public static String timeToString(long start, long finish) { Duration duration = new Duration(finish - start); // in milliseconds PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d") .appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds() .appendSuffix("s").appendMillis().appendSuffix("ms").toFormatter(); return formatter.print(duration.toPeriod()); }
[ "public", "static", "String", "timeToString", "(", "long", "start", ",", "long", "finish", ")", "{", "Duration", "duration", "=", "new", "Duration", "(", "finish", "-", "start", ")", ";", "// in milliseconds\r", "PeriodFormatter", "formatter", "=", "new", "Per...
Generic method to convert the milliseconds into the elapsed time string. @param start Start timestamp. @param finish End timestamp. @return String representation of the elapsed time.
[ "Generic", "method", "to", "convert", "the", "milliseconds", "into", "the", "elapsed", "time", "string", "." ]
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L589-L598
train
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/discord/HOTSAXImplementation.java
HOTSAXImplementation.series2DiscordsDeprecated
@Deprecated public static DiscordRecords series2DiscordsDeprecated(double[] series, int discordsNumToReport, int windowSize, int paaSize, int alphabetSize, SlidingWindowMarkerAlgorithm markerAlgorithm, NumerosityReductionStrategy strategy, double nThreshold) throws Exception { Date start = new Date(); // get the SAX transform NormalAlphabet normalA = new NormalAlphabet(); SAXRecords sax = sp.ts2saxViaWindow(series, windowSize, alphabetSize, normalA.getCuts(alphabetSize), strategy, nThreshold); Date saxEnd = new Date(); LOGGER.debug("discretized in {}, words: {}, indexes: {}", SAXProcessor.timeToString(start.getTime(), saxEnd.getTime()), sax.getRecords().size(), sax.getIndexes().size()); // instantiate the hash HashMap<String, ArrayList<Integer>> hash = new HashMap<String, ArrayList<Integer>>(); // fill the hash for (SAXRecord sr : sax.getRecords()) { for (Integer pos : sr.getIndexes()) { // add to hash String word = String.valueOf(sr.getPayload()); if (!(hash.containsKey(word))) { hash.put(word, new ArrayList<Integer>()); } hash.get(String.valueOf(word)).add(pos); } } Date hashEnd = new Date(); LOGGER.debug("Hash filled in : {}", SAXProcessor.timeToString(saxEnd.getTime(), hashEnd.getTime())); DiscordRecords discords = getDiscordsWithHash(series, windowSize, hash, discordsNumToReport, markerAlgorithm, nThreshold); Date end = new Date(); LOGGER.info("{} discords found in {}", discords.getSize(), SAXProcessor.timeToString(start.getTime(), end.getTime())); return discords; }
java
@Deprecated public static DiscordRecords series2DiscordsDeprecated(double[] series, int discordsNumToReport, int windowSize, int paaSize, int alphabetSize, SlidingWindowMarkerAlgorithm markerAlgorithm, NumerosityReductionStrategy strategy, double nThreshold) throws Exception { Date start = new Date(); // get the SAX transform NormalAlphabet normalA = new NormalAlphabet(); SAXRecords sax = sp.ts2saxViaWindow(series, windowSize, alphabetSize, normalA.getCuts(alphabetSize), strategy, nThreshold); Date saxEnd = new Date(); LOGGER.debug("discretized in {}, words: {}, indexes: {}", SAXProcessor.timeToString(start.getTime(), saxEnd.getTime()), sax.getRecords().size(), sax.getIndexes().size()); // instantiate the hash HashMap<String, ArrayList<Integer>> hash = new HashMap<String, ArrayList<Integer>>(); // fill the hash for (SAXRecord sr : sax.getRecords()) { for (Integer pos : sr.getIndexes()) { // add to hash String word = String.valueOf(sr.getPayload()); if (!(hash.containsKey(word))) { hash.put(word, new ArrayList<Integer>()); } hash.get(String.valueOf(word)).add(pos); } } Date hashEnd = new Date(); LOGGER.debug("Hash filled in : {}", SAXProcessor.timeToString(saxEnd.getTime(), hashEnd.getTime())); DiscordRecords discords = getDiscordsWithHash(series, windowSize, hash, discordsNumToReport, markerAlgorithm, nThreshold); Date end = new Date(); LOGGER.info("{} discords found in {}", discords.getSize(), SAXProcessor.timeToString(start.getTime(), end.getTime())); return discords; }
[ "@", "Deprecated", "public", "static", "DiscordRecords", "series2DiscordsDeprecated", "(", "double", "[", "]", "series", ",", "int", "discordsNumToReport", ",", "int", "windowSize", ",", "int", "paaSize", ",", "int", "alphabetSize", ",", "SlidingWindowMarkerAlgorithm"...
Old implementation. Nearest neighbot for a candidate subsequence is searched among all other time-series subsequences, regardless of their exclusion by EXACT or MINDIST. This also accepts a marker implementation which is responsible for marking a segment as visited. @param series The timeseries. @param discordsNumToReport The number of discords to report. @param windowSize SAX sliding window size. @param paaSize SAX PAA value. @param alphabetSize SAX alphabet size. @param markerAlgorithm marker algorithm. @param strategy the numerosity reduction strategy. @param nThreshold the normalization threshold value. @return Discords found within the series. @throws Exception if error occurs.
[ "Old", "implementation", ".", "Nearest", "neighbot", "for", "a", "candidate", "subsequence", "is", "searched", "among", "all", "other", "time", "-", "series", "subsequences", "regardless", "of", "their", "exclusion", "by", "EXACT", "or", "MINDIST", ".", "This", ...
39ee07a69facaa330def5130b8790aeda85f1061
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/discord/HOTSAXImplementation.java#L374-L416
train