code
stringlengths
73
34.1k
label
stringclasses
1 value
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.decod...
java
protected static List<EndpointInfo> extractEndpointInfo(EndpointPart root) { List<EndpointInfo> endpoints = new ArrayList<EndpointInfo>(); root.extractEndpointInfo(endpoints, ""); return endpoints; }
java
protected static void initEndpointInfo(List<EndpointInfo> endpoints) { for (int i = 0; i < endpoints.size(); i++) { initEndpointInfo(endpoints.get(i)); } }
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(...
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()...
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 endp...
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...
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 = En...
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('.'); ...
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(quer...
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....
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; }
java
public void startSpanWithParent(SpanBuilder spanBuilder, Span parent, String id) { if (parent != null) { spanBuilder.asChildOf(parent.context()); } doStartSpan(spanBuilder, id); }
java
public void startSpanWithContext(SpanBuilder spanBuilder, SpanContext context, String id) { if (context != null) { spanBuilder.asChildOf(context); } doStartSpan(spanBuilder, id); }
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); ...
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); } ...
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...
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(); ...
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.isLo...
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 (!fileExtensionWhiteli...
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 bas...
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 { ...
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 Trac...
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...
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>) stringObjectEnt...
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().p...
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 IllegalArgumentExcepti...
java
public void clearTenant(String tenantId) { String index = getIndex(tenantId); synchronized (knownIndices) { IndicesAdminClient indices = client.admin().indices(); boolean indexExists = indices.prepareExists(index) .execute() .actionGet() ...
java
@PreDestroy public void close() { if (node != null) { node.close(); } if (client != null) { client.close(); client = null; } }
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 (sp...
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.g...
java
public static FilterBuilder buildFilter(Criteria criteria) { if (criteria.getTransaction() != null && criteria.getTransaction().trim().isEmpty()) { return FilterBuilders.missingFilter(TRANSACTION_FIELD); } return null; }
java
public static long toMicros(Instant instant) { return TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + TimeUnit.NANOSECONDS.toMicros(instant.getNano()); }
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; } } ...
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 f...
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(E...
java
public static Collection<CommunicationSummaryStatistics> buildCommunicationSummaryTree( Collection<CommunicationSummaryStatistics> nodes, Set<String> endpoints) { Map<String, CommunicationSummaryStatistics> nodeMap = new HashMap<String, CommunicationSummaryStatistics>(); // Create a map of ...
java
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 initConfig() { CollectorConfiguration config = configurationService.getCollector(null, null, null, null); if (config != null) { configLastUpdated = System.currentTimeMillis(); filterManager = new FilterManager(config); try { processorM...
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); } ...
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 in...
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=[" + locat...
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=[" + ...
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); }
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...
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 ...
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<?...
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()) { ...
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 o...
java
public static synchronized <K, V> Cache<K, V> getDefaultCache(String cacheName) { if (defaultCacheManager == null) { defaultCacheManager = new DefaultCacheManager(); } return defaultCacheManager.getCache(cacheName); }
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)...
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) { ...
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 oldf...
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); ...
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++) { ...
java
public static List<EmojiChar> search(String... annotations) { return Emoji.findByAnnotations(SPACE_JOINER.join(annotations)); }
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> foundDes...
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...
java
private void getQuotedString(String pattern, ParsePosition pos, boolean escapingOn) { appendQuotedString(pattern, pos, null, escapingOn); }
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 { // ... r...
java
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 codePointToString(String point) { String ret; if (Strings.isNullOrEmpty(point)) { return point; } int unicodeScalar = Integer.parseInt(point, 16); if (Character.isSupplementaryCodePoint(unicodeScalar)) { ret = St...
java
public static EmojiChar findByVendorCodePoint(Vendor vendor, String point) { Emoji emoji = Emoji.getInstance(); return emoji._findByVendorCodePoint(vendor, point); }
java
public StringBuffer render(StringBuffer buffer, Object... arguments) { return format(arguments, buffer, null); }
java
public String mapTo(Vendor vendor) { String[] m = getMapping(vendor); return m == null ? null : m[VENDOR_MAP_RAW]; }
java
public static Map<String, Format> get(String name) { return instance().methods.get(name); }
java
public String format(Date ref, Date then) { return prettyTime.format(DurationHelper.calculateDuration(ref, then, prettyTime.getUnits())); }
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); ...
java
public static String transliterate(final String text, final String id) { Transliterator transliterator = Transliterator.getInstance(id); return transliterator.transform(text); }
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 != nu...
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....
java
public static String naturalTime(Date reference, Date duration) { return context.get().formatRelativeDate(reference, duration); }
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)); }
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()) }); }
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 ...
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.da...
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); } }
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 { ...
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 Ex...
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 {...
java
public double normalizedDistance(double[] point1, double[] point2) throws Exception { return Math.sqrt(distance2(point1, point2)) / point1.length; }
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 =...
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; }
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 = Ch...
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 (i...
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)) { ret...
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.subs...
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; }
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 en...
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...
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(tsPr...
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 doub...
java
public int charDistance(char a, char b) { return Math.abs(Character.getNumericValue(a) - Character.getNumericValue(b)); }
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 dist...
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 num...
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; }
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 < ...
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 (wordLen...
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(...
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()...
java