proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
prometheus_client_java
|
client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmRuntimeInfoMetric.java
|
Builder
|
register
|
class Builder {
private final PrometheusProperties config;
private String version;
private String vendor;
private String runtime;
private Builder(PrometheusProperties config) {
this.config = config;
}
/**
* Package private. For testing only.
*/
Builder version(String version) {
this.version = version;
return this;
}
/**
* Package private. For testing only.
*/
Builder vendor(String vendor) {
this.vendor = vendor;
return this;
}
/**
* Package private. For testing only.
*/
Builder runtime(String runtime) {
this.runtime = runtime;
return this;
}
public void register() {
register(PrometheusRegistry.defaultRegistry);
}
public void register(PrometheusRegistry registry) {<FILL_FUNCTION_BODY>}
}
|
String version = this.version != null ? this.version : System.getProperty("java.runtime.version", "unknown");
String vendor = this.vendor != null ? this.vendor : System.getProperty("java.vm.vendor", "unknown");
String runtime = this.runtime != null ? this.runtime : System.getProperty("java.runtime.name", "unknown");
new JvmRuntimeInfoMetric(version, vendor, runtime, config).register(registry);
| 235
| 116
| 351
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetrics.java
|
JvmThreadsMetrics
|
getThreadStateCountMap
|
class JvmThreadsMetrics {
private static final String UNKNOWN = "UNKNOWN";
private static final String JVM_THREADS_STATE = "jvm_threads_state";
private static final String JVM_THREADS_CURRENT = "jvm_threads_current";
private static final String JVM_THREADS_DAEMON = "jvm_threads_daemon";
private static final String JVM_THREADS_PEAK = "jvm_threads_peak";
private static final String JVM_THREADS_STARTED_TOTAL = "jvm_threads_started_total";
private static final String JVM_THREADS_DEADLOCKED = "jvm_threads_deadlocked";
private static final String JVM_THREADS_DEADLOCKED_MONITOR = "jvm_threads_deadlocked_monitor";
private final PrometheusProperties config;
private final ThreadMXBean threadBean;
private final boolean isNativeImage;
private JvmThreadsMetrics(boolean isNativeImage, ThreadMXBean threadBean, PrometheusProperties config) {
this.config = config;
this.threadBean = threadBean;
this.isNativeImage = isNativeImage;
}
private void register(PrometheusRegistry registry) {
GaugeWithCallback.builder(config)
.name(JVM_THREADS_CURRENT)
.help("Current thread count of a JVM")
.callback(callback -> callback.call(threadBean.getThreadCount()))
.register(registry);
GaugeWithCallback.builder(config)
.name(JVM_THREADS_DAEMON)
.help("Daemon thread count of a JVM")
.callback(callback -> callback.call(threadBean.getDaemonThreadCount()))
.register(registry);
GaugeWithCallback.builder(config)
.name(JVM_THREADS_PEAK)
.help("Peak thread count of a JVM")
.callback(callback -> callback.call(threadBean.getPeakThreadCount()))
.register(registry);
CounterWithCallback.builder(config)
.name(JVM_THREADS_STARTED_TOTAL)
.help("Started thread count of a JVM")
.callback(callback -> callback.call(threadBean.getTotalStartedThreadCount()))
.register(registry);
if (!isNativeImage) {
GaugeWithCallback.builder(config)
.name(JVM_THREADS_DEADLOCKED)
.help("Cycles of JVM-threads that are in deadlock waiting to acquire object monitors or ownable synchronizers")
.callback(callback -> callback.call(nullSafeArrayLength(threadBean.findDeadlockedThreads())))
.register(registry);
GaugeWithCallback.builder(config)
.name(JVM_THREADS_DEADLOCKED_MONITOR)
.help("Cycles of JVM-threads that are in deadlock waiting to acquire object monitors")
.callback(callback -> callback.call(nullSafeArrayLength(threadBean.findMonitorDeadlockedThreads())))
.register(registry);
GaugeWithCallback.builder(config)
.name(JVM_THREADS_STATE)
.help("Current count of threads by state")
.labelNames("state")
.callback(callback -> {
Map<String, Integer> threadStateCounts = getThreadStateCountMap(threadBean);
for (Map.Entry<String, Integer> entry : threadStateCounts.entrySet()) {
callback.call(entry.getValue(), entry.getKey());
}
})
.register(registry);
}
}
private Map<String, Integer> getThreadStateCountMap(ThreadMXBean threadBean) {<FILL_FUNCTION_BODY>}
private double nullSafeArrayLength(long[] array) {
return null == array ? 0 : array.length;
}
public static Builder builder() {
return new Builder(PrometheusProperties.get());
}
public static Builder builder(PrometheusProperties config) {
return new Builder(config);
}
public static class Builder {
private final PrometheusProperties config;
private Boolean isNativeImage;
private ThreadMXBean threadBean;
private Builder(PrometheusProperties config) {
this.config = config;
}
/**
* Package private. For testing only.
*/
Builder threadBean(ThreadMXBean threadBean) {
this.threadBean = threadBean;
return this;
}
/**
* Package private. For testing only.
*/
Builder isNativeImage(boolean isNativeImage) {
this.isNativeImage = isNativeImage;
return this;
}
public void register() {
register(PrometheusRegistry.defaultRegistry);
}
public void register(PrometheusRegistry registry) {
ThreadMXBean threadBean = this.threadBean != null ? this.threadBean : ManagementFactory.getThreadMXBean();
boolean isNativeImage = this.isNativeImage != null ? this.isNativeImage : NativeImageChecker.isGraalVmNativeImage;
new JvmThreadsMetrics(isNativeImage, threadBean, config).register(registry);
}
}
}
|
long[] threadIds = threadBean.getAllThreadIds();
// Code to remove any thread id values <= 0
int writePos = 0;
for (int i = 0; i < threadIds.length; i++) {
if (threadIds[i] > 0) {
threadIds[writePos++] = threadIds[i];
}
}
int numberOfInvalidThreadIds = threadIds.length - writePos;
threadIds = Arrays.copyOf(threadIds, writePos);
// Get thread information without computing any stack traces
ThreadInfo[] allThreads = threadBean.getThreadInfo(threadIds, 0);
// Initialize the map with all thread states
HashMap<String, Integer> threadCounts = new HashMap<String, Integer>();
for (Thread.State state : Thread.State.values()) {
threadCounts.put(state.name(), 0);
}
// Collect the actual thread counts
for (ThreadInfo curThread : allThreads) {
if (curThread != null) {
Thread.State threadState = curThread.getThreadState();
threadCounts.put(threadState.name(), threadCounts.get(threadState.name()) + 1);
}
}
// Add the thread count for invalid thread ids
threadCounts.put(UNKNOWN, numberOfInvalidThreadIds);
return threadCounts;
| 1,363
| 352
| 1,715
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/registry/MetricNameFilter.java
|
MetricNameFilter
|
matchesNameEqualTo
|
class MetricNameFilter implements Predicate<String> {
/**
* For convenience, a filter that allows all names.
*/
public static final Predicate<String> ALLOW_ALL = name -> true;
private final Collection<String> nameIsEqualTo;
private final Collection<String> nameIsNotEqualTo;
private final Collection<String> nameStartsWith;
private final Collection<String> nameDoesNotStartWith;
private MetricNameFilter(Collection<String> nameIsEqualTo, Collection<String> nameIsNotEqualTo, Collection<String> nameStartsWith, Collection<String> nameDoesNotStartWith) {
this.nameIsEqualTo = unmodifiableCollection(new ArrayList<>(nameIsEqualTo));
this.nameIsNotEqualTo = unmodifiableCollection(new ArrayList<>(nameIsNotEqualTo));
this.nameStartsWith = unmodifiableCollection(new ArrayList<>(nameStartsWith));
this.nameDoesNotStartWith = unmodifiableCollection(new ArrayList<>(nameDoesNotStartWith));
}
@Override
public boolean test(String sampleName) {
return matchesNameEqualTo(sampleName)
&& !matchesNameNotEqualTo(sampleName)
&& matchesNameStartsWith(sampleName)
&& !matchesNameDoesNotStartWith(sampleName);
}
private boolean matchesNameEqualTo(String metricName) {<FILL_FUNCTION_BODY>}
private boolean matchesNameNotEqualTo(String metricName) {
if (nameIsNotEqualTo.isEmpty()) {
return false;
}
for (String name : nameIsNotEqualTo) {
// The following ignores suffixes like _total.
// "request_count" and "request_count_total" both match a metric named "request_count".
if (name.startsWith(metricName)) {
return true;
}
}
return false;
}
private boolean matchesNameStartsWith(String metricName) {
if (nameStartsWith.isEmpty()) {
return true;
}
for (String prefix : nameStartsWith) {
if (metricName.startsWith(prefix)) {
return true;
}
}
return false;
}
private boolean matchesNameDoesNotStartWith(String metricName) {
if (nameDoesNotStartWith.isEmpty()) {
return false;
}
for (String prefix : nameDoesNotStartWith) {
if (metricName.startsWith(prefix)) {
return true;
}
}
return false;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final Collection<String> nameEqualTo = new ArrayList<>();
private final Collection<String> nameNotEqualTo = new ArrayList<>();
private final Collection<String> nameStartsWith = new ArrayList<>();
private final Collection<String> nameDoesNotStartWith = new ArrayList<>();
private Builder() {
}
/**
* @see #nameMustBeEqualTo(Collection)
*/
public Builder nameMustBeEqualTo(String... names) {
return nameMustBeEqualTo(Arrays.asList(names));
}
/**
* Only samples with one of the {@code names} will be included.
* <p>
* Note that the provided {@code names} will be matched against the sample name (i.e. the time series name)
* and not the metric name. For instance, to retrieve all samples from a histogram, you must include the
* '_count', '_sum' and '_bucket' names.
* <p>
* This method should be used by HTTP exporters to implement the {@code ?name[]=} URL parameters.
*
* @param names empty means no restriction.
*/
public Builder nameMustBeEqualTo(Collection<String> names) {
if (names != null) {
nameEqualTo.addAll(names);
}
return this;
}
/**
* @see #nameMustNotBeEqualTo(Collection)
*/
public Builder nameMustNotBeEqualTo(String... names) {
return nameMustNotBeEqualTo(Arrays.asList(names));
}
/**
* All samples that are not in {@code names} will be excluded.
* <p>
* Note that the provided {@code names} will be matched against the sample name (i.e. the time series name)
* and not the metric name. For instance, to exclude all samples from a histogram, you must exclude the
* '_count', '_sum' and '_bucket' names.
*
* @param names empty means no name will be excluded.
*/
public Builder nameMustNotBeEqualTo(Collection<String> names) {
if (names != null) {
nameNotEqualTo.addAll(names);
}
return this;
}
/**
* @see #nameMustStartWith(Collection)
*/
public Builder nameMustStartWith(String... prefixes) {
return nameMustStartWith(Arrays.asList(prefixes));
}
/**
* Only samples whose name starts with one of the {@code prefixes} will be included.
*
* @param prefixes empty means no restriction.
*/
public Builder nameMustStartWith(Collection<String> prefixes) {
if (prefixes != null) {
nameStartsWith.addAll(prefixes);
}
return this;
}
/**
* @see #nameMustNotStartWith(Collection)
*/
public Builder nameMustNotStartWith(String... prefixes) {
return nameMustNotStartWith(Arrays.asList(prefixes));
}
/**
* Samples with names starting with one of the {@code prefixes} will be excluded.
*
* @param prefixes empty means no time series will be excluded.
*/
public Builder nameMustNotStartWith(Collection<String> prefixes) {
if (prefixes != null) {
nameDoesNotStartWith.addAll(prefixes);
}
return this;
}
public MetricNameFilter build() {
return new MetricNameFilter(nameEqualTo, nameNotEqualTo, nameStartsWith, nameDoesNotStartWith);
}
}
}
|
if (nameIsEqualTo.isEmpty()) {
return true;
}
for (String name : nameIsEqualTo) {
// The following ignores suffixes like _total.
// "request_count" and "request_count_total" both match a metric named "request_count".
if (name.startsWith(metricName)) {
return true;
}
}
return false;
| 1,580
| 105
| 1,685
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/registry/PrometheusRegistry.java
|
PrometheusRegistry
|
scrape
|
class PrometheusRegistry {
public static final PrometheusRegistry defaultRegistry = new PrometheusRegistry();
private final Set<String> prometheusNames = ConcurrentHashMap.newKeySet();
private final List<Collector> collectors = new CopyOnWriteArrayList<>();
private final List<MultiCollector> multiCollectors = new CopyOnWriteArrayList<>();
public void register(Collector collector) {
String prometheusName = collector.getPrometheusName();
if (prometheusName != null) {
if (!prometheusNames.add(prometheusName)) {
throw new IllegalStateException("Can't register " + prometheusName + " because a metric with that name is already registered.");
}
}
collectors.add(collector);
}
public void register(MultiCollector collector) {
for (String prometheusName : collector.getPrometheusNames()) {
if (!prometheusNames.add(prometheusName)) {
throw new IllegalStateException("Can't register " + prometheusName + " because that name is already registered.");
}
}
multiCollectors.add(collector);
}
public void unregister(Collector collector) {
collectors.remove(collector);
String prometheusName = collector.getPrometheusName();
if (prometheusName != null) {
prometheusNames.remove(collector.getPrometheusName());
}
}
public void unregister(MultiCollector collector) {
multiCollectors.remove(collector);
for (String prometheusName : collector.getPrometheusNames()) {
prometheusNames.remove(prometheusName(prometheusName));
}
}
public MetricSnapshots scrape() {
return scrape((PrometheusScrapeRequest) null);
}
public MetricSnapshots scrape(PrometheusScrapeRequest scrapeRequest) {<FILL_FUNCTION_BODY>}
public MetricSnapshots scrape(Predicate<String> includedNames) {
if (includedNames == null) {
return scrape();
}
return scrape(includedNames, null);
}
public MetricSnapshots scrape(Predicate<String> includedNames, PrometheusScrapeRequest scrapeRequest) {
if (includedNames == null) {
return scrape(scrapeRequest);
}
MetricSnapshots.Builder result = MetricSnapshots.builder();
for (Collector collector : collectors) {
String prometheusName = collector.getPrometheusName();
// prometheusName == null means the name is unknown, and we have to scrape to learn the name.
// prometheusName != null means we can skip the scrape if the name is excluded.
if (prometheusName == null || includedNames.test(prometheusName)) {
MetricSnapshot snapshot = scrapeRequest == null ? collector.collect(includedNames) : collector.collect(includedNames, scrapeRequest);
if (snapshot != null) {
result.metricSnapshot(snapshot);
}
}
}
for (MultiCollector collector : multiCollectors) {
List<String> prometheusNames = collector.getPrometheusNames();
// empty prometheusNames means the names are unknown, and we have to scrape to learn the names.
// non-empty prometheusNames means we can exclude the collector if all names are excluded by the filter.
boolean excluded = !prometheusNames.isEmpty();
for (String prometheusName : prometheusNames) {
if (includedNames.test(prometheusName)) {
excluded = false;
break;
}
}
if (!excluded) {
MetricSnapshots snapshots = scrapeRequest == null ? collector.collect(includedNames) : collector.collect(includedNames, scrapeRequest);
for (MetricSnapshot snapshot : snapshots) {
if (snapshot != null) {
result.metricSnapshot(snapshot);
}
}
}
}
return result.build();
}
}
|
MetricSnapshots.Builder result = MetricSnapshots.builder();
for (Collector collector : collectors) {
MetricSnapshot snapshot = scrapeRequest == null ? collector.collect() : collector.collect(scrapeRequest);
if (snapshot != null) {
if (result.containsMetricName(snapshot.getMetadata().getName())) {
throw new IllegalStateException(snapshot.getMetadata().getPrometheusName() + ": duplicate metric name.");
}
result.metricSnapshot(snapshot);
}
}
for (MultiCollector collector : multiCollectors) {
MetricSnapshots snaphots = scrapeRequest == null ? collector.collect() : collector.collect(scrapeRequest);
for (MetricSnapshot snapshot : snaphots) {
if (result.containsMetricName(snapshot.getMetadata().getName())) {
throw new IllegalStateException(snapshot.getMetadata().getPrometheusName() + ": duplicate metric name.");
}
result.metricSnapshot(snapshot);
}
}
return result.build();
| 1,039
| 274
| 1,313
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/ClassicHistogramBucket.java
|
ClassicHistogramBucket
|
compareTo
|
class ClassicHistogramBucket implements Comparable<ClassicHistogramBucket> {
private final long count; // not cumulative
private final double upperBound;
public ClassicHistogramBucket(double upperBound, long count) {
this.count = count;
this.upperBound = upperBound;
if (Double.isNaN(upperBound)) {
throw new IllegalArgumentException("Cannot use NaN as an upper bound for a histogram bucket");
}
if (count < 0) {
throw new IllegalArgumentException(count + ": " + ClassicHistogramBuckets.class.getSimpleName() + " cannot have a negative count");
}
}
public long getCount() {
return count;
}
public double getUpperBound() {
return upperBound;
}
/**
* For sorting a list of buckets by upper bound.
*/
@Override
public int compareTo(ClassicHistogramBucket other) {<FILL_FUNCTION_BODY>}
}
|
int result = Double.compare(upperBound, other.upperBound);
if (result != 0) {
return result;
}
return Long.compare(count, other.count);
| 256
| 51
| 307
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/CounterSnapshot.java
|
Builder
|
build
|
class Builder extends DataPointSnapshot.Builder<Builder> {
private Exemplar exemplar = null;
private Double value = null;
private long createdTimestampMillis = 0L;
private Builder() {
}
/**
* Counter value. This is required. The value must not be negative.
*/
public Builder value(double value) {
this.value = value;
return this;
}
public Builder exemplar(Exemplar exemplar) {
this.exemplar = exemplar;
return this;
}
public Builder createdTimestampMillis(long createdTimestampMillis) {
this.createdTimestampMillis = createdTimestampMillis;
return this;
}
public CounterDataPointSnapshot build() {<FILL_FUNCTION_BODY>}
@Override
protected Builder self() {
return this;
}
}
|
if (value == null) {
throw new IllegalArgumentException("Missing required field: value is null.");
}
return new CounterDataPointSnapshot(value, labels, exemplar, createdTimestampMillis, scrapeTimestampMillis);
| 226
| 58
| 284
|
<methods>public abstract List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> getDataPoints() ,public io.prometheus.metrics.model.snapshots.MetricMetadata getMetadata() <variables>protected final non-sealed List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> dataPoints,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/DataPointSnapshot.java
|
DataPointSnapshot
|
validate
|
class DataPointSnapshot {
private final Labels labels;
private final long createdTimestampMillis;
private final long scrapeTimestampMillis;
protected DataPointSnapshot(Labels labels, long createdTimestampMillis, long scrapeTimestampMillis) {
this.labels = labels;
this.createdTimestampMillis = createdTimestampMillis;
this.scrapeTimestampMillis = scrapeTimestampMillis;
validate();
}
private void validate() {<FILL_FUNCTION_BODY>}
public Labels getLabels() {
return labels;
}
public boolean hasScrapeTimestamp() {
return scrapeTimestampMillis != 0L;
}
/**
* This will only return a reasonable value if {@link #hasScrapeTimestamp()} is true.
*/
public long getScrapeTimestampMillis() {
return scrapeTimestampMillis;
}
public boolean hasCreatedTimestamp() {
return createdTimestampMillis != 0L;
}
/**
* This will only return a reasonable value if {@link #hasCreatedTimestamp()} is true.
* Some metrics like Gauge don't have created timestamps. For these metrics {@link #hasCreatedTimestamp()}
* is always false.
*/
public long getCreatedTimestampMillis() {
return createdTimestampMillis;
}
public static abstract class Builder<T extends Builder<T>> {
protected Labels labels = Labels.EMPTY;
protected long scrapeTimestampMillis = 0L;
public T labels(Labels labels) {
this.labels = labels;
return self();
}
/**
* In most cases you should not set a scrape timestamp,
* because the scrape timestamp is set by the Prometheus server during scraping.
* Exceptions include mirroring metrics with given timestamps from other metric sources.
*/
public T scrapeTimestampMillis(long scrapeTimestampMillis) {
this.scrapeTimestampMillis = scrapeTimestampMillis;
return self();
}
protected abstract T self();
}
}
|
if (labels == null) {
throw new IllegalArgumentException("Labels cannot be null. Use Labels.EMPTY if there are no labels.");
}
if (createdTimestampMillis < 0) {
throw new IllegalArgumentException("Created timestamp cannot be negative. Use 0 if the metric doesn't have a created timestamp.");
}
if (scrapeTimestampMillis < 0) {
throw new IllegalArgumentException("Scrape timestamp cannot be negative. Use 0 to indicate that the Prometheus server should set the scrape timestamp.");
}
if (hasCreatedTimestamp() && hasScrapeTimestamp()) {
if (scrapeTimestampMillis < createdTimestampMillis) {
throw new IllegalArgumentException("The scrape timestamp cannot be before the created timestamp");
}
}
| 531
| 190
| 721
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/DistributionDataPointSnapshot.java
|
DistributionDataPointSnapshot
|
validate
|
class DistributionDataPointSnapshot extends DataPointSnapshot {
private final long count; // optional, negative value means no count.
private final double sum; // optional, Double.NaN means no sum.
private final Exemplars exemplars; // optional, Exemplars.EMPTY means no Exemplars.
/**
* See JavaDoc of the child classes.
*/
protected DistributionDataPointSnapshot(long count, double sum, Exemplars exemplars, Labels labels, long createdTimestampMillis, long scrapeTimestampMillis) {
super(labels, createdTimestampMillis, scrapeTimestampMillis);
this.count = count;
this.sum = sum;
this.exemplars = exemplars == null ? Exemplars.EMPTY : exemplars;
validate();
}
private void validate() {<FILL_FUNCTION_BODY>}
public boolean hasCount() {
return count >= 0;
}
public boolean hasSum() {
return !Double.isNaN(sum);
}
/**
* This will return garbage if {@link #hasCount()} is {@code false}.
*/
public long getCount() {
return count;
}
/**
* This will return garbage if {@link #hasSum()} is {@code false}.
*/
public double getSum() {
return sum;
}
/**
* May be {@link Exemplars#EMPTY}, but will never be {@code null}.
*/
public Exemplars getExemplars() {
return exemplars;
}
static abstract class Builder<T extends Builder<T>> extends DataPointSnapshot.Builder<T> {
protected long count = -1;
protected double sum = Double.NaN;
protected long createdTimestampMillis = 0L;
protected Exemplars exemplars = Exemplars.EMPTY;
/**
* Count can be explicitly set on summaries (this is a public method for summary metrics),
* and it is set implicitly on histograms (derived from the bucket counts).
*/
protected T count(long count) {
this.count = count;
return self();
}
public T sum(double sum) {
this.sum = sum;
return self();
}
public T exemplars(Exemplars exemplars) {
this.exemplars = exemplars;
return self();
}
public T createdTimestampMillis(long createdTimestampMillis) {
this.createdTimestampMillis = createdTimestampMillis;
return self();
}
}
}
|
// If a histogram or summary observes negative values the sum could be negative.
// According to OpenMetrics sum should be omitted in that case, but we don't enforce this here.
| 647
| 46
| 693
|
<methods>public long getCreatedTimestampMillis() ,public io.prometheus.metrics.model.snapshots.Labels getLabels() ,public long getScrapeTimestampMillis() ,public boolean hasCreatedTimestamp() ,public boolean hasScrapeTimestamp() <variables>private final non-sealed long createdTimestampMillis,private final non-sealed io.prometheus.metrics.model.snapshots.Labels labels,private final non-sealed long scrapeTimestampMillis
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Exemplar.java
|
Builder
|
build
|
class Builder {
private Double value = null;
private Labels labels = Labels.EMPTY;
private String traceId = null;
private String spanId = null;
private long timestampMillis = 0L;
private Builder() {
}
public Builder value(double value) {
this.value = value;
return this;
}
public Builder traceId(String traceId) {
this.traceId = traceId;
return this;
}
public Builder spanId(String spanId) {
this.spanId = spanId;
return this;
}
public Builder labels(Labels labels) {
if (labels == null) {
throw new NullPointerException();
}
this.labels = labels;
return this;
}
public Builder timestampMillis(long timestampMillis) {
this.timestampMillis = timestampMillis;
return this;
}
/**
* @throws IllegalStateException if {@link #value(double)} wasn't called.
*/
public Exemplar build() {<FILL_FUNCTION_BODY>}
}
|
if (value == null) {
throw new IllegalStateException("cannot build an Exemplar without a value");
}
Labels allLabels;
if (traceId != null && spanId != null) {
allLabels = Labels.of(TRACE_ID, traceId, SPAN_ID, spanId);
} else if (traceId != null) {
allLabels = Labels.of(TRACE_ID, traceId);
} else if (spanId != null) {
allLabels = Labels.of(SPAN_ID, spanId);
} else {
allLabels = Labels.EMPTY;
}
if (!labels.isEmpty()) {
allLabels = allLabels.merge(labels);
}
return new Exemplar(value, allLabels, timestampMillis);
| 290
| 214
| 504
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Exemplars.java
|
Exemplars
|
get
|
class Exemplars implements Iterable<Exemplar> {
/**
* EMPTY means no Exemplars.
*/
public static final Exemplars EMPTY = new Exemplars(Collections.emptyList());
private final List<Exemplar> exemplars;
private Exemplars(Collection<Exemplar> exemplars) {
ArrayList<Exemplar> copy = new ArrayList<>(exemplars.size());
for (Exemplar exemplar : exemplars) {
if (exemplar == null) {
throw new NullPointerException("Illegal null value in Exemplars");
}
copy.add(exemplar);
}
this.exemplars = Collections.unmodifiableList(copy);
}
/**
* Create a new Exemplars instance.
* You can either create Exemplars with one of the static {@code Exemplars.of(...)} methods,
* or you can use the {@link Exemplars#builder()}.
*
* @param exemplars a copy of the exemplars collection will be created.
*/
public static Exemplars of(Collection<Exemplar> exemplars) {
return new Exemplars(exemplars);
}
/**
* Create a new Exemplars instance.
* You can either create Exemplars with one of the static {@code Exemplars.of(...)} methods,
* or you can use the {@link Exemplars#builder()}.
*
* @param exemplars a copy of the exemplars array will be created.
*/
public static Exemplars of(Exemplar... exemplars) {
return new Exemplars(Arrays.asList(exemplars));
}
@Override
public Iterator<Exemplar> iterator() {
return exemplars.iterator();
}
public int size() {
return exemplars.size();
}
public Exemplar get(int index) {
return exemplars.get(index);
}
/**
* This is used by classic histograms to find an exemplar with a value between lowerBound and upperBound.
* If there is more than one exemplar within the bounds the one with the newest time stamp is returned.
*/
public Exemplar get(double lowerBound, double upperBound) {<FILL_FUNCTION_BODY>}
/**
* Find the Exemplar with the newest timestamp. May return {@code null}.
*/
public Exemplar getLatest() {
Exemplar latest = null;
for (int i=0; i<exemplars.size(); i++) {
Exemplar candidate = exemplars.get(i);
if (candidate == null) {
continue;
}
if (latest == null) {
latest = candidate;
continue;
}
if (!latest.hasTimestamp()) {
latest = candidate;
continue;
}
if (candidate.hasTimestamp()) {
if (latest.getTimestampMillis() < candidate.getTimestampMillis()) {
latest = candidate;
}
}
}
return latest;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final ArrayList<Exemplar> exemplars = new ArrayList<>();
private Builder() {
}
/**
* Add an exemplar. This can be called multiple times to add multiple exemplars.
*/
public Builder exemplar(Exemplar exemplar) {
exemplars.add(exemplar);
return this;
}
/**
* Add all exemplars form the collection.
*/
public Builder exemplars(Collection<Exemplar> exemplars) {
this.exemplars.addAll(exemplars);
return this;
}
public Exemplars build() {
return Exemplars.of(exemplars);
}
}
}
|
Exemplar result = null;
for (int i = 0; i < exemplars.size(); i++) {
Exemplar exemplar = exemplars.get(i);
double value = exemplar.getValue();
if (value > lowerBound && value <= upperBound) {
if (result == null) {
result = exemplar;
} else if (result.hasTimestamp() && exemplar.hasTimestamp()) {
if (exemplar.getTimestampMillis() > result.getTimestampMillis()) {
result = exemplar;
}
}
}
}
return result;
| 984
| 153
| 1,137
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/GaugeSnapshot.java
|
Builder
|
build
|
class Builder extends DataPointSnapshot.Builder<Builder> {
private Exemplar exemplar = null;
private Double value = null;
private Builder() {
}
/**
* Gauge value. This is required.
*/
public Builder value(double value) {
this.value = value;
return this;
}
/**
* Optional
*/
public Builder exemplar(Exemplar exemplar) {
this.exemplar = exemplar;
return this;
}
public GaugeDataPointSnapshot build() {<FILL_FUNCTION_BODY>}
@Override
protected Builder self() {
return this;
}
}
|
if (value == null) {
throw new IllegalArgumentException("Missing required field: value is null.");
}
return new GaugeDataPointSnapshot(value, labels, exemplar, scrapeTimestampMillis);
| 178
| 53
| 231
|
<methods>public abstract List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> getDataPoints() ,public io.prometheus.metrics.model.snapshots.MetricMetadata getMetadata() <variables>protected final non-sealed List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> dataPoints,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Label.java
|
Label
|
compareTo
|
class Label implements Comparable<Label> {
private final String name;
private final String value;
public Label(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
@Override
public int compareTo(Label other) {<FILL_FUNCTION_BODY>}
}
|
int nameCompare = name.compareTo(other.name);
return nameCompare != 0 ? nameCompare : value.compareTo(other.value);
| 121
| 39
| 160
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/MetricMetadata.java
|
MetricMetadata
|
validate
|
class MetricMetadata {
/**
* Name without suffix.
* <p>
* For example, the name for a counter "http_requests_total" is "http_requests".
* The name of an info called "jvm_info" is "jvm".
* <p>
* We allow dots in label names. Dots are automatically replaced with underscores in Prometheus
* exposition formats. However, if metrics from this library are exposed in OpenTelemetry
* format dots are retained.
* <p>
* See {@link #MetricMetadata(String, String, Unit)} for more info on naming conventions.
*/
private final String name;
/**
* Same as name, except if name contains dots, then the prometheusName is {@code name.replace(".", "_")}.
*/
private final String prometheusName;
/**
* optional, may be {@code null}.
*/
private final String help;
/**
* optional, may be {@code null}.
*/
private final Unit unit;
/**
* See {@link #MetricMetadata(String, String, Unit)}
*/
public MetricMetadata(String name) {
this(name, null, null);
}
/**
* See {@link #MetricMetadata(String, String, Unit)}
*/
public MetricMetadata(String name, String help) {
this(name, help, null);
}
/**
* Constructor.
* @param name must not be {@code null}. {@link PrometheusNaming#isValidMetricName(String) isValidMetricName(name)}
* must be {@code true}. Use {@link PrometheusNaming#sanitizeMetricName(String)} to convert arbitrary
* strings into valid names.
* @param help optional. May be {@code null}.
* @param unit optional. May be {@code null}.
*/
public MetricMetadata(String name, String help, Unit unit) {
this.name = name;
this.help = help;
this.unit = unit;
validate();
this.prometheusName = name.contains(".") ? PrometheusNaming.prometheusName(name) : name;
}
/**
* The name does not include the {@code _total} suffix for counter metrics
* or the {@code _info} suffix for Info metrics.
* <p>
* The name may contain dots. Use {@link #getPrometheusName()} to get the name in Prometheus format,
* i.e. with dots replaced by underscores.
*/
public String getName() {
return name;
}
/**
* Same as {@link #getName()} but with dots replaced by underscores.
* <p>
* This is used by Prometheus exposition formats.
*/
public String getPrometheusName() {
return prometheusName;
}
public String getHelp() {
return help;
}
public boolean hasUnit() {
return unit != null;
}
public Unit getUnit() {
return unit;
}
private void validate() {<FILL_FUNCTION_BODY>}
}
|
if (name == null) {
throw new IllegalArgumentException("Missing required field: name is null");
}
String error = PrometheusNaming.validateMetricName(name);
if (error != null) {
throw new IllegalArgumentException("'" + name + "': Illegal metric name. " + error
+ " Call " + PrometheusNaming.class.getSimpleName() + ".sanitizeMetricName(name) to avoid this error.");
}
| 815
| 117
| 932
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/MetricSnapshot.java
|
MetricSnapshot
|
validateLabels
|
class MetricSnapshot {
private final MetricMetadata metadata;
protected final List<? extends DataPointSnapshot> dataPoints;
protected MetricSnapshot(MetricMetadata metadata, DataPointSnapshot... dataPoints) {
this(metadata, Arrays.asList(dataPoints));
}
protected MetricSnapshot(MetricMetadata metadata, Collection<? extends DataPointSnapshot> dataPoints) {
if (metadata == null) {
throw new NullPointerException("metadata");
}
if (dataPoints == null) {
throw new NullPointerException("dataPoints");
}
this.metadata = metadata;
List<? extends DataPointSnapshot> dataCopy = new ArrayList<>(dataPoints);
dataCopy.sort(Comparator.comparing(DataPointSnapshot::getLabels));
this.dataPoints = Collections.unmodifiableList(dataCopy);
validateLabels();
}
public MetricMetadata getMetadata() {
return metadata;
}
public abstract List<? extends DataPointSnapshot> getDataPoints();
protected void validateLabels() {<FILL_FUNCTION_BODY>}
public static abstract class Builder<T extends Builder<T>> {
private String name;
private String help;
private Unit unit;
/**
* The name is required.
* If the name is missing or invalid, {@code build()} will throw an {@link IllegalArgumentException}.
* See {@link PrometheusNaming#isValidMetricName(String)} for info on valid metric names.
*/
public T name(String name) {
this.name = name;
return self();
}
public T help(String help) {
this.help = help;
return self();
}
public T unit(Unit unit) {
this.unit = unit;
return self();
}
protected MetricMetadata buildMetadata() {
return new MetricMetadata(name, help, unit);
}
protected abstract T self();
}
}
|
// Verify that labels are unique (the same set of names/values must not be used multiple times for the same metric).
for (int i = 0; i < dataPoints.size() - 1; i++) {
if (dataPoints.get(i).getLabels().equals(dataPoints.get(i + 1).getLabels())) {
throw new DuplicateLabelsException(metadata, dataPoints.get(i).getLabels());
}
}
// Should we verify that all entries in data have the same label names?
// No. They should have the same label names, but according to OpenMetrics this is not a MUST.
| 498
| 157
| 655
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/MetricSnapshots.java
|
Builder
|
containsMetricName
|
class Builder {
private final List<MetricSnapshot> snapshots = new ArrayList<>();
private Builder() {
}
public boolean containsMetricName(String name) {<FILL_FUNCTION_BODY>}
/**
* Add a metric snapshot. Call multiple times to add multiple metric snapshots.
*/
public Builder metricSnapshot(MetricSnapshot snapshot) {
snapshots.add(snapshot);
return this;
}
public MetricSnapshots build() {
return new MetricSnapshots(snapshots);
}
}
|
for (MetricSnapshot snapshot : snapshots) {
if (snapshot.getMetadata().getPrometheusName().equals(prometheusName(name))) {
return true;
}
}
return false;
| 143
| 58
| 201
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/NativeHistogramBuckets.java
|
NativeHistogramBuckets
|
validate
|
class NativeHistogramBuckets implements Iterable<NativeHistogramBucket> {
public static final NativeHistogramBuckets EMPTY = new NativeHistogramBuckets(new int[]{}, new long[]{});
private final int[] bucketIndexes; // sorted
private final long[] counts;
private NativeHistogramBuckets(int[] bucketIndexes, long[] counts) {
this.bucketIndexes = bucketIndexes;
this.counts = counts;
}
/**
* To create a new {@link NativeHistogramBuckets} instance, you can either use one of the static {@code of(...)}
* methods, or use {@link NativeHistogramBuckets#builder()}.
* @param bucketIndexes see class javadoc of {@link NativeHistogramBuckets}. May be empty.
* @param counts must have the same length as bucketIndexes
*/
public static NativeHistogramBuckets of(int[] bucketIndexes, long[] counts) {
int[] bucketIndexesCopy = Arrays.copyOf(bucketIndexes, bucketIndexes.length);
long[] countsCopy = Arrays.copyOf(counts, counts.length);
sortAndValidate(bucketIndexesCopy, countsCopy);
return new NativeHistogramBuckets(bucketIndexesCopy, countsCopy);
}
/**
* To create a new {@link NativeHistogramBuckets} instance, you can either use one of the static {@code of(...)}
* methods, or use {@link NativeHistogramBuckets#builder()}.
* @param bucketIndexes see class javadoc of {@link NativeHistogramBuckets}. May be empty.
* @param counts must have the same size as bucketIndexes
*/
public static NativeHistogramBuckets of(List<Integer> bucketIndexes, List<Long> counts) {
int[] bucketIndexesCopy = new int[bucketIndexes.size()];
for (int i=0; i<bucketIndexes.size(); i++) {
bucketIndexesCopy[i] = bucketIndexes.get(i);
}
long[] countsCopy = new long[counts.size()];
for (int i=0; i<counts.size(); i++) {
countsCopy[i] = counts.get(i);
}
sortAndValidate(bucketIndexesCopy, countsCopy);
return new NativeHistogramBuckets(bucketIndexesCopy, countsCopy);
}
public int size() {
return bucketIndexes.length;
}
private List<NativeHistogramBucket> asList() {
List<NativeHistogramBucket> result = new ArrayList<>(size());
for (int i=0; i<bucketIndexes.length; i++) {
result.add(new NativeHistogramBucket(bucketIndexes[i], counts[i]));
}
return Collections.unmodifiableList(result);
}
@Override
public Iterator<NativeHistogramBucket> iterator() {
return asList().iterator();
}
public Stream<NativeHistogramBucket> stream() {
return asList().stream();
}
public int getBucketIndex(int i) {
return bucketIndexes[i];
}
public long getCount(int i) {
return counts[i];
}
private static void sortAndValidate(int[] bucketIndexes, long[] counts) {
if (bucketIndexes.length != counts.length) {
throw new IllegalArgumentException("bucketIndexes.length == " + bucketIndexes.length + " but counts.length == " + counts.length + ". Expected the same length.");
}
sort(bucketIndexes, counts);
validate(bucketIndexes, counts);
}
private static void sort(int[] bucketIndexes, long[] counts) {
// Bubblesort. Should be efficient here as in most cases bucketIndexes is already sorted.
int n = bucketIndexes.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (bucketIndexes[j] > bucketIndexes[j + 1]) {
swap(j, j+1, bucketIndexes, counts);
}
}
}
}
private static void swap(int i, int j, int[] bucketIndexes, long[] counts) {
int tmpInt = bucketIndexes[j];
bucketIndexes[j] = bucketIndexes[i];
bucketIndexes[i] = tmpInt;
long tmpLong = counts[j];
counts[j] = counts[i];
counts[i] = tmpLong;
}
private static void validate(int[] bucketIndexes, long[] counts) {<FILL_FUNCTION_BODY>}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final List<Integer> bucketIndexes = new ArrayList<>();
private final List<Long> counts = new ArrayList<>();
private Builder() {}
/**
* Add a native histogram bucket. Call multiple times to add multiple buckets.
*/
public Builder bucket(int bucketIndex, long count) {
bucketIndexes.add(bucketIndex);
counts.add(count);
return this;
}
public NativeHistogramBuckets build() {
return NativeHistogramBuckets.of(bucketIndexes, counts);
}
}
}
|
// Preconditions:
// * bucketIndexes sorted
// * bucketIndexes and counts have the same length
for (int i=0; i<bucketIndexes.length; i++) {
if (counts[i] < 0) {
throw new IllegalArgumentException("Bucket counts cannot be negative.");
}
if (i > 0) {
if (bucketIndexes[i-1] == bucketIndexes[i]) {
throw new IllegalArgumentException("Duplicate bucket index " + bucketIndexes[i]);
}
}
}
| 1,385
| 140
| 1,525
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Quantile.java
|
Quantile
|
validate
|
class Quantile {
private final double quantile;
private final double value;
/**
* @param quantile expecting 0.0 <= quantile <= 1.0, otherwise an {@link IllegalArgumentException} will be thrown.
* @param value
*/
public Quantile(double quantile, double value) {
this.quantile = quantile;
this.value = value;
validate();
}
public double getQuantile() {
return quantile;
}
public double getValue() {
return value;
}
private void validate() {<FILL_FUNCTION_BODY>}
}
|
if (quantile < 0.0 || quantile > 1.0) {
throw new IllegalArgumentException(quantile + ": Illegal quantile. Expecting 0 <= quantile <= 1");
}
| 168
| 52
| 220
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Quantiles.java
|
Quantiles
|
validate
|
class Quantiles implements Iterable<Quantile> {
private final List<Quantile> quantiles;
public static final Quantiles EMPTY = new Quantiles(Collections.emptyList());
private Quantiles(List<Quantile> quantiles) {
quantiles = new ArrayList<>(quantiles);
quantiles.sort(Comparator.comparing(Quantile::getQuantile));
this.quantiles = Collections.unmodifiableList(quantiles);
validate();
}
private void validate() {<FILL_FUNCTION_BODY>}
/**
* Create a new Quantiles instance.
* You can either create Quantiles with one of the static {@code Quantiles.of(...)} methods,
* or you can use the {@link Quantiles#builder()}.
*/
public static Quantiles of(List<Quantile> quantiles) {
return new Quantiles(quantiles);
}
/**
* Create a new Quantiles instance.
* You can either create Quantiles with one of the static {@code Quantiles.of(...)} methods,
* or you can use the {@link Quantiles#builder()}.
*/
public static Quantiles of(Quantile... quantiles) {
return of(Arrays.asList(quantiles));
}
public int size() {
return quantiles.size();
}
public Quantile get(int i) {
return quantiles.get(i);
}
@Override
public Iterator<Quantile> iterator() {
return quantiles.iterator();
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final List<Quantile> quantiles = new ArrayList<>();
private Builder() {
}
/**
* Add a quantile. Call multiple times to add multiple quantiles.
*/
public Builder quantile(Quantile quantile) {
quantiles.add(quantile);
return this;
}
/**
* Add a quantile. Call multiple times to add multiple quantiles.
* @param quantile 0.0 <= quantile <= 1.0
*/
public Builder quantile(double quantile, double value) {
quantiles.add(new Quantile(quantile, value));
return this;
}
public Quantiles build() {
return new Quantiles(quantiles);
}
}
}
|
for (int i=0; i< quantiles.size() - 1; i++) {
if (quantiles.get(i).getQuantile() == quantiles.get(i+1).getQuantile()) {
throw new IllegalArgumentException("Duplicate " + quantiles.get(i).getQuantile() + " quantile.");
}
}
| 613
| 90
| 703
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/StateSetSnapshot.java
|
StateSetDataPointSnapshot
|
validate
|
class StateSetDataPointSnapshot extends DataPointSnapshot implements Iterable<State> {
private final String[] names;
private final boolean[] values;
/**
* To create a new {@link StateSetDataPointSnapshot}, you can either call the constructor directly or use the
* Builder with {@link StateSetDataPointSnapshot#builder()}.
*
* @param names state names. Must have at least 1 entry.
* The constructor will create a copy of the array.
* @param values state values. Must have the same length as {@code names}.
* The constructor will create a copy of the array.
* @param labels must not be null. Use {@link Labels#EMPTY} if there are no labels.
*/
public StateSetDataPointSnapshot(String[] names, boolean[] values, Labels labels) {
this(names, values, labels, 0L);
}
/**
* Constructor with an additional scrape timestamp.
* This is only useful in rare cases as the scrape timestamp is usually set by the Prometheus server
* during scraping. Exceptions include mirroring metrics with given timestamps from other metric sources.
*/
public StateSetDataPointSnapshot(String[] names, boolean[] values, Labels labels, long scrapeTimestampMillis) {
super(labels, 0L, scrapeTimestampMillis);
if (names.length == 0) {
throw new IllegalArgumentException("StateSet must have at least one state.");
}
if (names.length != values.length) {
throw new IllegalArgumentException("names[] and values[] must have the same length");
}
String[] namesCopy = Arrays.copyOf(names, names.length);
boolean[] valuesCopy = Arrays.copyOf(values, names.length);
sort(namesCopy, valuesCopy);
this.names = namesCopy;
this.values = valuesCopy;
validate();
}
public int size() {
return names.length;
}
public String getName(int i) {
return names[i];
}
public boolean isTrue(int i) {
return values[i];
}
private void validate() {<FILL_FUNCTION_BODY>}
private List<State> asList() {
List<State> result = new ArrayList<>(size());
for (int i = 0; i < names.length; i++) {
result.add(new State(names[i], values[i]));
}
return Collections.unmodifiableList(result);
}
@Override
public Iterator<State> iterator() {
return asList().iterator();
}
public Stream<State> stream() {
return asList().stream();
}
private static void sort(String[] names, boolean[] values) {
// Bubblesort
int n = names.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (names[j].compareTo(names[j + 1]) > 0) {
swap(j, j + 1, names, values);
}
}
}
}
private static void swap(int i, int j, String[] names, boolean[] values) {
String tmpName = names[j];
names[j] = names[i];
names[i] = tmpName;
boolean tmpValue = values[j];
values[j] = values[i];
values[i] = tmpValue;
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends DataPointSnapshot.Builder<Builder> {
private final ArrayList<String> names = new ArrayList<>();
private final ArrayList<Boolean> values = new ArrayList<>();
private Builder() {}
/**
* Add a state. Call multple times to add multiple states.
*/
public Builder state(String name, boolean value) {
names.add(name);
values.add(value);
return this;
}
@Override
protected Builder self() {
return this;
}
public StateSetDataPointSnapshot build() {
boolean[] valuesArray = new boolean[values.size()];
for (int i = 0; i < values.size(); i++) {
valuesArray[i] = values.get(i);
}
return new StateSetDataPointSnapshot(names.toArray(new String[]{}), valuesArray, labels, scrapeTimestampMillis);
}
}
}
|
for (int i = 0; i < names.length; i++) {
if (names[i].length() == 0) {
throw new IllegalArgumentException("Empty string as state name");
}
if (i > 0 && names[i - 1].equals(names[i])) {
throw new IllegalArgumentException(names[i] + " duplicate state name");
}
}
| 1,143
| 97
| 1,240
|
<methods>public abstract List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> getDataPoints() ,public io.prometheus.metrics.model.snapshots.MetricMetadata getMetadata() <variables>protected final non-sealed List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> dataPoints,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/SummarySnapshot.java
|
SummaryDataPointSnapshot
|
validate
|
class SummaryDataPointSnapshot extends DistributionDataPointSnapshot {
private final Quantiles quantiles;
/**
* To create a new {@link SummaryDataPointSnapshot}, you can either call the constructor directly
* or use the Builder with {@link SummaryDataPointSnapshot#builder()}.
*
* @param count total number of observations. Optional, pass -1 if not available.
* @param sum sum of all observed values. Optional, pass {@link Double#NaN} if not available.
* @param quantiles must not be {@code null}. Use {@link Quantiles#EMPTY} if there are no quantiles.
* @param labels must not be {@code null}. Use {@link Labels#EMPTY} if there are no labels.
* @param exemplars must not be {@code null}. Use {@link Exemplars#EMPTY} if there are no exemplars.
* @param createdTimestampMillis timestamp (as in {@link System#currentTimeMillis()}) when this summary
* data (this specific set of labels) was created.
* Note that this refers to the creation of the timeseries,
* not the creation of the snapshot.
* The created timestamp optional. Use {@code 0L} if there is no created timestamp.
*/
public SummaryDataPointSnapshot(long count, double sum, Quantiles quantiles, Labels labels, Exemplars exemplars, long createdTimestampMillis) {
this(count, sum, quantiles, labels, exemplars, createdTimestampMillis, 0);
}
/**
* Constructor with an additional scrape timestamp.
* This is only useful in rare cases as the scrape timestamp is usually set by the Prometheus server
* during scraping. Exceptions include mirroring metrics with given timestamps from other metric sources.
*/
public SummaryDataPointSnapshot(long count, double sum, Quantiles quantiles, Labels labels, Exemplars exemplars, long createdTimestampMillis, long scrapeTimestampMillis) {
super(count, sum, exemplars, labels, createdTimestampMillis, scrapeTimestampMillis);
this.quantiles = quantiles;
validate();
}
public Quantiles getQuantiles() {
return quantiles;
}
private void validate() {<FILL_FUNCTION_BODY>}
public static Builder builder() {
return new Builder();
}
public static class Builder extends DistributionDataPointSnapshot.Builder<Builder> {
private Quantiles quantiles = Quantiles.EMPTY;
private Builder() {
}
@Override
protected Builder self() {
return this;
}
public Builder quantiles(Quantiles quantiles) {
this.quantiles = quantiles;
return this;
}
@Override
public Builder count(long count) {
super.count(count);
return this;
}
public SummaryDataPointSnapshot build() {
return new SummaryDataPointSnapshot(count, sum, quantiles, labels, exemplars, createdTimestampMillis, scrapeTimestampMillis);
}
}
}
|
for (Label label : getLabels()) {
if (label.getName().equals("quantile")) {
throw new IllegalArgumentException("quantile is a reserved label name for summaries");
}
}
if (quantiles == null) {
throw new NullPointerException();
}
| 759
| 74
| 833
|
<methods>public abstract List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> getDataPoints() ,public io.prometheus.metrics.model.snapshots.MetricMetadata getMetadata() <variables>protected final non-sealed List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> dataPoints,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Unit.java
|
Unit
|
equals
|
class Unit {
private final String name;
public static final Unit RATIO = new Unit("ratio");
public static final Unit SECONDS = new Unit("seconds");
public static final Unit BYTES = new Unit("bytes");
public static final Unit CELSIUS = new Unit("celsius");
public static final Unit JOULES = new Unit("joules");
public static final Unit GRAMS = new Unit("grams");
public static final Unit METERS = new Unit("meters");
public static final Unit VOLTS = new Unit("volts");
public static final Unit AMPERES = new Unit("amperes");
public Unit(String name) {
if (name == null) {
throw new NullPointerException("Unit name cannot be null.");
}
if (name.trim().isEmpty()) {
throw new IllegalArgumentException("Unit name cannot be empty.");
}
this.name = name.trim();
}
@Override
public String toString() {
return name;
}
public static double nanosToSeconds(long nanos) {
return nanos / 1E9;
}
public static double millisToSeconds(long millis) {
return millis / 1E3;
}
public static double secondsToMillis(double seconds) {
return seconds * 1E3;
}
public static double kiloBytesToBytes(double kilobytes) {
return kilobytes * 1024;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Unit unit = (Unit) o;
return Objects.equals(name, unit.name);
| 436
| 59
| 495
|
<no_super_class>
|
prometheus_client_java
|
client_java/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/UnknownSnapshot.java
|
Builder
|
build
|
class Builder extends DataPointSnapshot.Builder<Builder> {
private Exemplar exemplar = null;
private Double value = null;
private Builder() {
}
/**
* required.
*/
public Builder value(double value) {
this.value = value;
return this;
}
/**
* Optional
*/
public Builder exemplar(Exemplar exemplar) {
this.exemplar = exemplar;
return this;
}
public UnknownDataPointSnapshot build() {<FILL_FUNCTION_BODY>}
@Override
protected Builder self() {
return this;
}
}
|
if (value == null) {
throw new IllegalArgumentException("Missing required field: value is null.");
}
return new UnknownDataPointSnapshot(value, labels, exemplar, scrapeTimestampMillis);
| 171
| 52
| 223
|
<methods>public abstract List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> getDataPoints() ,public io.prometheus.metrics.model.snapshots.MetricMetadata getMetadata() <variables>protected final non-sealed List<? extends io.prometheus.metrics.model.snapshots.DataPointSnapshot> dataPoints,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata
|
prometheus_client_java
|
client_java/prometheus-metrics-tracer/prometheus-metrics-tracer-otel/src/main/java/io/prometheus/metrics/tracer/otel/OpenTelemetrySpanContext.java
|
OpenTelemetrySpanContext
|
isAvailable
|
class OpenTelemetrySpanContext implements SpanContext {
public static boolean isAvailable() {<FILL_FUNCTION_BODY>}
@Override
public String getCurrentTraceId() {
String traceId = Span.current().getSpanContext().getTraceId();
return TraceId.isValid(traceId) ? traceId : null;
}
@Override
public String getCurrentSpanId() {
String spanId = Span.current().getSpanContext().getSpanId();
return SpanId.isValid(spanId) ? spanId : null;
}
@Override
public boolean isCurrentSpanSampled() {
return Span.current().getSpanContext().isSampled();
}
@Override
public void markCurrentSpanAsExemplar() {
Span.current().setAttribute(EXEMPLAR_ATTRIBUTE_NAME, EXEMPLAR_ATTRIBUTE_VALUE);
}
}
|
try {
OpenTelemetrySpanContext test = new OpenTelemetrySpanContext();
test.getCurrentSpanId();
test.getCurrentTraceId();
test.isCurrentSpanSampled();
return true;
} catch (LinkageError ignored) {
// NoClassDefFoundError:
// Either OpenTelemetry is not present, or it is version 0.9.1 or older when io.opentelemetry.api.trace.Span did not exist.
// IncompatibleClassChangeError:
// The application uses an OpenTelemetry version between 0.10.0 and 0.15.0 when SpanContext was a class, and not an interface.
return false;
}
| 226
| 180
| 406
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/internal/AutolinkPostProcessor.java
|
AutolinkPostProcessor
|
createTextNode
|
class AutolinkPostProcessor implements PostProcessor {
private LinkExtractor linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL, LinkType.EMAIL))
.build();
@Override
public Node process(Node node) {
AutolinkVisitor autolinkVisitor = new AutolinkVisitor();
node.accept(autolinkVisitor);
return node;
}
private void linkify(Text originalTextNode) {
String literal = originalTextNode.getLiteral();
Node lastNode = originalTextNode;
List<SourceSpan> sourceSpans = originalTextNode.getSourceSpans();
SourceSpan sourceSpan = sourceSpans.size() == 1 ? sourceSpans.get(0) : null;
Iterator<Span> spans = linkExtractor.extractSpans(literal).iterator();
while (spans.hasNext()) {
Span span = spans.next();
if (lastNode == originalTextNode && !spans.hasNext() && !(span instanceof LinkSpan)) {
// Didn't find any links, don't bother changing existing node.
return;
}
Text textNode = createTextNode(literal, span, sourceSpan);
if (span instanceof LinkSpan) {
String destination = getDestination((LinkSpan) span, textNode.getLiteral());
Link linkNode = new Link(destination, null);
linkNode.appendChild(textNode);
linkNode.setSourceSpans(textNode.getSourceSpans());
lastNode = insertNode(linkNode, lastNode);
} else {
lastNode = insertNode(textNode, lastNode);
}
}
// Original node no longer needed
originalTextNode.unlink();
}
private static Text createTextNode(String literal, Span span, SourceSpan sourceSpan) {<FILL_FUNCTION_BODY>}
private static String getDestination(LinkSpan linkSpan, String linkText) {
if (linkSpan.getType() == LinkType.EMAIL) {
return "mailto:" + linkText;
} else {
return linkText;
}
}
private static Node insertNode(Node node, Node insertAfterNode) {
insertAfterNode.insertAfter(node);
return node;
}
private class AutolinkVisitor extends AbstractVisitor {
int inLink = 0;
@Override
public void visit(Link link) {
inLink++;
super.visit(link);
inLink--;
}
@Override
public void visit(Text text) {
if (inLink == 0) {
linkify(text);
}
}
}
}
|
int beginIndex = span.getBeginIndex();
int endIndex = span.getEndIndex();
String text = literal.substring(beginIndex, endIndex);
Text textNode = new Text(text);
if (sourceSpan != null) {
int length = endIndex - beginIndex;
textNode.addSourceSpan(SourceSpan.of(sourceSpan.getLineIndex(), beginIndex, length));
}
return textNode;
| 693
| 111
| 804
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/StrikethroughExtension.java
|
StrikethroughExtension
|
extend
|
class StrikethroughExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension,
TextContentRenderer.TextContentRendererExtension, MarkdownRenderer.MarkdownRendererExtension {
private final boolean requireTwoTildes;
private StrikethroughExtension(Builder builder) {
this.requireTwoTildes = builder.requireTwoTildes;
}
/**
* @return the extension with default options
*/
public static Extension create() {
return builder().build();
}
/**
* @return a builder to configure the behavior of the extension
*/
public static Builder builder() {
return new Builder();
}
@Override
public void extend(Parser.Builder parserBuilder) {
parserBuilder.customDelimiterProcessor(new StrikethroughDelimiterProcessor(requireTwoTildes));
}
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
@Override
public NodeRenderer create(HtmlNodeRendererContext context) {
return new StrikethroughHtmlNodeRenderer(context);
}
});
}
@Override
public void extend(TextContentRenderer.Builder rendererBuilder) {<FILL_FUNCTION_BODY>}
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
@Override
public NodeRenderer create(MarkdownNodeRendererContext context) {
return new StrikethroughMarkdownNodeRenderer(context);
}
@Override
public Set<Character> getSpecialCharacters() {
return Collections.singleton('~');
}
});
}
public static class Builder {
private boolean requireTwoTildes = false;
/**
* @param requireTwoTildes Whether two tilde characters ({@code ~~}) are required for strikethrough or whether
* one is also enough. Default is {@code false}; both a single tilde and two tildes can be used for strikethrough.
* @return {@code this}
*/
public Builder requireTwoTildes(boolean requireTwoTildes) {
this.requireTwoTildes = requireTwoTildes;
return this;
}
/**
* @return a configured extension
*/
public Extension build() {
return new StrikethroughExtension(this);
}
}
}
|
rendererBuilder.nodeRendererFactory(new TextContentNodeRendererFactory() {
@Override
public NodeRenderer create(TextContentNodeRendererContext context) {
return new StrikethroughTextContentNodeRenderer(context);
}
});
| 622
| 61
| 683
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/internal/StrikethroughDelimiterProcessor.java
|
StrikethroughDelimiterProcessor
|
process
|
class StrikethroughDelimiterProcessor implements DelimiterProcessor {
private final boolean requireTwoTildes;
public StrikethroughDelimiterProcessor() {
this(false);
}
public StrikethroughDelimiterProcessor(boolean requireTwoTildes) {
this.requireTwoTildes = requireTwoTildes;
}
@Override
public char getOpeningCharacter() {
return '~';
}
@Override
public char getClosingCharacter() {
return '~';
}
@Override
public int getMinLength() {
return requireTwoTildes ? 2 : 1;
}
@Override
public int process(DelimiterRun openingRun, DelimiterRun closingRun) {<FILL_FUNCTION_BODY>}
}
|
if (openingRun.length() == closingRun.length() && openingRun.length() <= 2) {
// GitHub only accepts either one or two delimiters, but not a mix or more than that.
Text opener = openingRun.getOpener();
// Wrap nodes between delimiters in strikethrough.
String delimiter = openingRun.length() == 1 ? opener.getLiteral() : opener.getLiteral() + opener.getLiteral();
Node strikethrough = new Strikethrough(delimiter);
SourceSpans sourceSpans = new SourceSpans();
sourceSpans.addAllFrom(openingRun.getOpeners(openingRun.length()));
for (Node node : Nodes.between(opener, closingRun.getCloser())) {
strikethrough.appendChild(node);
sourceSpans.addAll(node.getSourceSpans());
}
sourceSpans.addAllFrom(closingRun.getClosers(closingRun.length()));
strikethrough.setSourceSpans(sourceSpans.getSourceSpans());
opener.insertAfter(strikethrough);
return openingRun.length();
} else {
return 0;
}
| 211
| 316
| 527
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/internal/StrikethroughHtmlNodeRenderer.java
|
StrikethroughHtmlNodeRenderer
|
renderChildren
|
class StrikethroughHtmlNodeRenderer extends StrikethroughNodeRenderer {
private final HtmlNodeRendererContext context;
private final HtmlWriter html;
public StrikethroughHtmlNodeRenderer(HtmlNodeRendererContext context) {
this.context = context;
this.html = context.getWriter();
}
@Override
public void render(Node node) {
Map<String, String> attributes = context.extendAttributes(node, "del", Collections.<String, String>emptyMap());
html.tag("del", attributes);
renderChildren(node);
html.tag("/del");
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
| 179
| 51
| 230
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/internal/StrikethroughMarkdownNodeRenderer.java
|
StrikethroughMarkdownNodeRenderer
|
renderChildren
|
class StrikethroughMarkdownNodeRenderer extends StrikethroughNodeRenderer {
private final MarkdownNodeRendererContext context;
private final MarkdownWriter writer;
public StrikethroughMarkdownNodeRenderer(MarkdownNodeRendererContext context) {
this.context = context;
this.writer = context.getWriter();
}
@Override
public void render(Node node) {
Strikethrough strikethrough = (Strikethrough) node;
writer.raw(strikethrough.getOpeningDelimiter());
renderChildren(node);
writer.raw(strikethrough.getClosingDelimiter());
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
| 188
| 51
| 239
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/internal/StrikethroughTextContentNodeRenderer.java
|
StrikethroughTextContentNodeRenderer
|
renderChildren
|
class StrikethroughTextContentNodeRenderer extends StrikethroughNodeRenderer {
private final TextContentNodeRendererContext context;
private final TextContentWriter textContent;
public StrikethroughTextContentNodeRenderer(TextContentNodeRendererContext context) {
this.context = context;
this.textContent = context.getWriter();
}
@Override
public void render(Node node) {
textContent.write('/');
renderChildren(node);
textContent.write('/');
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
| 151
| 51
| 202
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TablesExtension.java
|
TablesExtension
|
extend
|
class TablesExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension,
TextContentRenderer.TextContentRendererExtension, MarkdownRenderer.MarkdownRendererExtension {
private TablesExtension() {
}
public static Extension create() {
return new TablesExtension();
}
@Override
public void extend(Parser.Builder parserBuilder) {
parserBuilder.customBlockParserFactory(new TableBlockParser.Factory());
}
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
@Override
public NodeRenderer create(HtmlNodeRendererContext context) {
return new TableHtmlNodeRenderer(context);
}
});
}
@Override
public void extend(TextContentRenderer.Builder rendererBuilder) {<FILL_FUNCTION_BODY>}
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
@Override
public NodeRenderer create(MarkdownNodeRendererContext context) {
return new TableMarkdownNodeRenderer(context);
}
@Override
public Set<Character> getSpecialCharacters() {
return Collections.singleton('|');
}
});
}
}
|
rendererBuilder.nodeRendererFactory(new TextContentNodeRendererFactory() {
@Override
public NodeRenderer create(TextContentNodeRendererContext context) {
return new TableTextContentNodeRenderer(context);
}
});
| 332
| 58
| 390
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableHtmlNodeRenderer.java
|
TableHtmlNodeRenderer
|
getCellAttributes
|
class TableHtmlNodeRenderer extends TableNodeRenderer {
private final HtmlWriter htmlWriter;
private final HtmlNodeRendererContext context;
public TableHtmlNodeRenderer(HtmlNodeRendererContext context) {
this.htmlWriter = context.getWriter();
this.context = context;
}
protected void renderBlock(TableBlock tableBlock) {
htmlWriter.line();
htmlWriter.tag("table", getAttributes(tableBlock, "table"));
renderChildren(tableBlock);
htmlWriter.tag("/table");
htmlWriter.line();
}
protected void renderHead(TableHead tableHead) {
htmlWriter.line();
htmlWriter.tag("thead", getAttributes(tableHead, "thead"));
renderChildren(tableHead);
htmlWriter.tag("/thead");
htmlWriter.line();
}
protected void renderBody(TableBody tableBody) {
htmlWriter.line();
htmlWriter.tag("tbody", getAttributes(tableBody, "tbody"));
renderChildren(tableBody);
htmlWriter.tag("/tbody");
htmlWriter.line();
}
protected void renderRow(TableRow tableRow) {
htmlWriter.line();
htmlWriter.tag("tr", getAttributes(tableRow, "tr"));
renderChildren(tableRow);
htmlWriter.tag("/tr");
htmlWriter.line();
}
protected void renderCell(TableCell tableCell) {
String tagName = tableCell.isHeader() ? "th" : "td";
htmlWriter.line();
htmlWriter.tag(tagName, getCellAttributes(tableCell, tagName));
renderChildren(tableCell);
htmlWriter.tag("/" + tagName);
htmlWriter.line();
}
private Map<String, String> getAttributes(Node node, String tagName) {
return context.extendAttributes(node, tagName, Collections.<String, String>emptyMap());
}
private Map<String, String> getCellAttributes(TableCell tableCell, String tagName) {<FILL_FUNCTION_BODY>}
private static String getAlignValue(TableCell.Alignment alignment) {
switch (alignment) {
case LEFT:
return "left";
case CENTER:
return "center";
case RIGHT:
return "right";
}
throw new IllegalStateException("Unknown alignment: " + alignment);
}
private void renderChildren(Node parent) {
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
}
}
|
if (tableCell.getAlignment() != null) {
return context.extendAttributes(tableCell, tagName, Collections.singletonMap("align", getAlignValue(tableCell.getAlignment())));
} else {
return context.extendAttributes(tableCell, tagName, Collections.<String, String>emptyMap());
}
| 661
| 88
| 749
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() ,public void render(org.commonmark.node.Node) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableMarkdownNodeRenderer.java
|
TableMarkdownNodeRenderer
|
renderHead
|
class TableMarkdownNodeRenderer extends TableNodeRenderer implements NodeRenderer {
private final MarkdownWriter writer;
private final MarkdownNodeRendererContext context;
private final AsciiMatcher pipe = AsciiMatcher.builder().c('|').build();
private final List<TableCell.Alignment> columns = new ArrayList<>();
public TableMarkdownNodeRenderer(MarkdownNodeRendererContext context) {
this.writer = context.getWriter();
this.context = context;
}
@Override
protected void renderBlock(TableBlock node) {
columns.clear();
writer.pushTight(true);
renderChildren(node);
writer.popTight();
writer.block();
}
@Override
protected void renderHead(TableHead node) {<FILL_FUNCTION_BODY>}
@Override
protected void renderBody(TableBody node) {
renderChildren(node);
}
@Override
protected void renderRow(TableRow node) {
renderChildren(node);
// Trailing | at the end of the line
writer.raw("|");
writer.block();
}
@Override
protected void renderCell(TableCell node) {
if (node.getParent() != null && node.getParent().getParent() instanceof TableHead) {
columns.add(node.getAlignment());
}
writer.raw("|");
writer.pushRawEscape(pipe);
renderChildren(node);
writer.popRawEscape();
}
private void renderChildren(Node parent) {
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
}
}
|
renderChildren(node);
for (TableCell.Alignment columnAlignment : columns) {
writer.raw('|');
if (columnAlignment == TableCell.Alignment.LEFT) {
writer.raw(":---");
} else if (columnAlignment == TableCell.Alignment.RIGHT) {
writer.raw("---:");
} else if (columnAlignment == TableCell.Alignment.CENTER) {
writer.raw(":---:");
} else {
writer.raw("---");
}
}
writer.raw("|");
writer.block();
| 447
| 154
| 601
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() ,public void render(org.commonmark.node.Node) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableNodeRenderer.java
|
TableNodeRenderer
|
render
|
class TableNodeRenderer implements NodeRenderer {
@Override
public Set<Class<? extends Node>> getNodeTypes() {
return new HashSet<>(Arrays.asList(
TableBlock.class,
TableHead.class,
TableBody.class,
TableRow.class,
TableCell.class
));
}
@Override
public void render(Node node) {<FILL_FUNCTION_BODY>}
protected abstract void renderBlock(TableBlock node);
protected abstract void renderHead(TableHead node);
protected abstract void renderBody(TableBody node);
protected abstract void renderRow(TableRow node);
protected abstract void renderCell(TableCell node);
}
|
if (node instanceof TableBlock) {
renderBlock((TableBlock) node);
} else if (node instanceof TableHead) {
renderHead((TableHead) node);
} else if (node instanceof TableBody) {
renderBody((TableBody) node);
} else if (node instanceof TableRow) {
renderRow((TableRow) node);
} else if (node instanceof TableCell) {
renderCell((TableCell) node);
}
| 179
| 114
| 293
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableTextContentNodeRenderer.java
|
TableTextContentNodeRenderer
|
renderChildren
|
class TableTextContentNodeRenderer extends TableNodeRenderer {
private final TextContentWriter textContentWriter;
private final TextContentNodeRendererContext context;
public TableTextContentNodeRenderer(TextContentNodeRendererContext context) {
this.textContentWriter = context.getWriter();
this.context = context;
}
protected void renderBlock(TableBlock tableBlock) {
renderChildren(tableBlock);
if (tableBlock.getNext() != null) {
textContentWriter.write("\n");
}
}
protected void renderHead(TableHead tableHead) {
renderChildren(tableHead);
}
protected void renderBody(TableBody tableBody) {
renderChildren(tableBody);
}
protected void renderRow(TableRow tableRow) {
textContentWriter.line();
renderChildren(tableRow);
textContentWriter.line();
}
protected void renderCell(TableCell tableCell) {
renderChildren(tableCell);
textContentWriter.write('|');
textContentWriter.whitespace();
}
private void renderLastCell(TableCell tableCell) {
renderChildren(tableCell);
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
// For last cell in row, we dont render the delimiter.
if (node instanceof TableCell && next == null) {
renderLastCell((TableCell) node);
} else {
context.render(node);
}
node = next;
}
| 318
| 103
| 421
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() ,public void render(org.commonmark.node.Node) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/HeadingAnchorExtension.java
|
HeadingAnchorExtension
|
extend
|
class HeadingAnchorExtension implements HtmlRenderer.HtmlRendererExtension {
private final String defaultId;
private final String idPrefix;
private final String idSuffix;
private HeadingAnchorExtension(Builder builder) {
this.defaultId = builder.defaultId;
this.idPrefix = builder.idPrefix;
this.idSuffix = builder.idSuffix;
}
/**
* @return the extension built with default settings
*/
public static Extension create() {
return new HeadingAnchorExtension(builder());
}
/**
* @return a builder to configure the extension settings
*/
public static Builder builder() {
return new Builder();
}
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {<FILL_FUNCTION_BODY>}
public static class Builder {
private String defaultId = "id";
private String idPrefix = "";
private String idSuffix = "";
/**
* @param value Default value for the id to take if no generated id can be extracted. Default "id"
* @return {@code this}
*/
public Builder defaultId(String value) {
this.defaultId = value;
return this;
}
/**
* @param value Set the value to be prepended to every id generated. Default ""
* @return {@code this}
*/
public Builder idPrefix(String value) {
this.idPrefix = value;
return this;
}
/**
* @param value Set the value to be appended to every id generated. Default ""
* @return {@code this}
*/
public Builder idSuffix(String value) {
this.idSuffix = value;
return this;
}
/**
* @return a configured extension
*/
public Extension build() {
return new HeadingAnchorExtension(this);
}
}
}
|
rendererBuilder.attributeProviderFactory(new AttributeProviderFactory() {
@Override
public AttributeProvider create(AttributeProviderContext context) {
return HeadingIdAttributeProvider.create(defaultId, idPrefix, idSuffix);
}
});
| 489
| 66
| 555
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/IdGenerator.java
|
IdGenerator
|
compileAllowedCharactersPattern
|
class IdGenerator {
private final Pattern allowedCharacters;
private final Map<String, Integer> identityMap;
private final String prefix;
private final String suffix;
private String defaultIdentifier;
private IdGenerator(Builder builder) {
this.allowedCharacters = compileAllowedCharactersPattern();
this.defaultIdentifier = builder.defaultIdentifier;
this.prefix = builder.prefix;
this.suffix = builder.suffix;
this.identityMap = new HashMap<>();
}
/**
* @return a new builder with default arguments
*/
public static Builder builder() {
return new Builder();
}
/**
* <p>
* Generate an ID based on the provided text and previously generated IDs.
* <p>
* This method is not thread safe, concurrent calls can end up
* with non-unique identifiers.
* <p>
* Note that collision can occur in the case that
* <ul>
* <li>Method called with 'X'</li>
* <li>Method called with 'X' again</li>
* <li>Method called with 'X-1'</li>
* </ul>
* <p>
* In that case, the three generated IDs will be:
* <ul>
* <li>X</li>
* <li>X-1</li>
* <li>X-1</li>
* </ul>
* <p>
* Therefore if collisions are unacceptable you should ensure that
* numbers are stripped from end of {@code text}.
*
* @param text Text that the identifier should be based on. Will be normalised, then used to generate the
* identifier.
* @return {@code text} if this is the first instance that the {@code text} has been passed
* to the method. Otherwise, {@code text + "-" + X} will be returned, where X is the number of times
* that {@code text} has previously been passed in. If {@code text} is empty, the default
* identifier given in the constructor will be used.
*/
public String generateId(String text) {
String normalizedIdentity = text != null ? normalizeText(text) : defaultIdentifier;
if (normalizedIdentity.length() == 0) {
normalizedIdentity = defaultIdentifier;
}
if (!identityMap.containsKey(normalizedIdentity)) {
identityMap.put(normalizedIdentity, 1);
return prefix + normalizedIdentity + suffix;
} else {
int currentCount = identityMap.get(normalizedIdentity);
identityMap.put(normalizedIdentity, currentCount + 1);
return prefix + normalizedIdentity + "-" + currentCount + suffix;
}
}
private static Pattern compileAllowedCharactersPattern() {<FILL_FUNCTION_BODY>}
/**
* Assume we've been given a space separated text.
*
* @param text Text to normalize to an ID
*/
private String normalizeText(String text) {
String firstPassNormalising = text.toLowerCase().replace(" ", "-");
StringBuilder sb = new StringBuilder();
Matcher matcher = allowedCharacters.matcher(firstPassNormalising);
while (matcher.find()) {
sb.append(matcher.group());
}
return sb.toString();
}
public static class Builder {
private String defaultIdentifier = "id";
private String prefix = "";
private String suffix = "";
public IdGenerator build() {
return new IdGenerator(this);
}
/**
* @param defaultId the default identifier to use in case the provided text is empty or only contains unusable characters
* @return {@code this}
*/
public Builder defaultId(String defaultId) {
this.defaultIdentifier = defaultId;
return this;
}
/**
* @param prefix the text to place before the generated identity
* @return {@code this}
*/
public Builder prefix(String prefix) {
this.prefix = prefix;
return this;
}
/**
* @param suffix the text to place after the generated identity
* @return {@code this}
*/
public Builder suffix(String suffix) {
this.suffix = suffix;
return this;
}
}
}
|
String regex = "[\\w\\-_]+";
try {
return Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
} catch (IllegalArgumentException e) {
// Android only supports the flag in API level 24. But it actually uses Unicode character classes by
// default, so not specifying the flag is ok. See issue #71.
return Pattern.compile(regex);
}
| 1,090
| 113
| 1,203
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java
|
HeadingIdAttributeProvider
|
setAttributes
|
class HeadingIdAttributeProvider implements AttributeProvider {
private final IdGenerator idGenerator;
private HeadingIdAttributeProvider(String defaultId, String prefix, String suffix) {
idGenerator = IdGenerator.builder()
.defaultId(defaultId)
.prefix(prefix)
.suffix(suffix)
.build();
}
public static HeadingIdAttributeProvider create(String defaultId, String prefix, String suffix) {
return new HeadingIdAttributeProvider(defaultId, prefix, suffix);
}
@Override
public void setAttributes(Node node, String tagName, final Map<String, String> attributes) {<FILL_FUNCTION_BODY>}
}
|
if (node instanceof Heading) {
final List<String> wordList = new ArrayList<>();
node.accept(new AbstractVisitor() {
@Override
public void visit(Text text) {
wordList.add(text.getLiteral());
}
@Override
public void visit(Code code) {
wordList.add(code.getLiteral());
}
});
String finalString = "";
for (String word : wordList) {
finalString += word;
}
finalString = finalString.trim().toLowerCase();
attributes.put("id", idGenerator.generateId(finalString));
}
| 172
| 168
| 340
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributesExtension.java
|
ImageAttributesExtension
|
extend
|
class ImageAttributesExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension {
private ImageAttributesExtension() {
}
public static Extension create() {
return new ImageAttributesExtension();
}
@Override
public void extend(Parser.Builder parserBuilder) {
parserBuilder.customDelimiterProcessor(new ImageAttributesDelimiterProcessor());
}
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {<FILL_FUNCTION_BODY>}
}
|
rendererBuilder.attributeProviderFactory(new AttributeProviderFactory() {
@Override
public AttributeProvider create(AttributeProviderContext context) {
return ImageAttributesAttributeProvider.create();
}
});
| 126
| 54
| 180
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesAttributeProvider.java
|
ImageAttributesAttributeProvider
|
setAttributes
|
class ImageAttributesAttributeProvider implements AttributeProvider {
private ImageAttributesAttributeProvider() {
}
public static ImageAttributesAttributeProvider create() {
return new ImageAttributesAttributeProvider();
}
@Override
public void setAttributes(Node node, String tagName, final Map<String, String> attributes) {<FILL_FUNCTION_BODY>}
}
|
if (node instanceof Image) {
node.accept(new AbstractVisitor() {
@Override
public void visit(CustomNode node) {
if (node instanceof ImageAttributes) {
ImageAttributes imageAttributes = (ImageAttributes) node;
for (Map.Entry<String, String> entry : imageAttributes.getAttributes().entrySet()) {
attributes.put(entry.getKey(), entry.getValue());
}
// Now that we have used the image attributes we remove the node.
imageAttributes.unlink();
}
}
});
}
| 91
| 140
| 231
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesDelimiterProcessor.java
|
ImageAttributesDelimiterProcessor
|
process
|
class ImageAttributesDelimiterProcessor implements DelimiterProcessor {
// Only allow a defined set of attributes to be used.
private static final Set<String> SUPPORTED_ATTRIBUTES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList("width", "height")));
@Override
public char getOpeningCharacter() {
return '{';
}
@Override
public char getClosingCharacter() {
return '}';
}
@Override
public int getMinLength() {
return 1;
}
@Override
public int process(DelimiterRun openingRun, DelimiterRun closingRun) {<FILL_FUNCTION_BODY>}
}
|
if (openingRun.length() != 1) {
return 0;
}
// Check if the attributes can be applied - if the previous node is an Image, and if all the attributes are in
// the set of SUPPORTED_ATTRIBUTES
Text opener = openingRun.getOpener();
Node nodeToStyle = opener.getPrevious();
if (!(nodeToStyle instanceof Image)) {
return 0;
}
List<Node> toUnlink = new ArrayList<>();
StringBuilder content = new StringBuilder();
for (Node node : Nodes.between(opener, closingRun.getCloser())) {
// Only Text nodes can be used for attributes
if (node instanceof Text) {
content.append(((Text) node).getLiteral());
toUnlink.add(node);
} else {
// This node type is not supported, so stop here (no need to check any further ones).
return 0;
}
}
Map<String, String> attributesMap = new LinkedHashMap<>();
String attributes = content.toString();
for (String s : attributes.split("\\s+")) {
String[] attribute = s.split("=");
if (attribute.length > 1 && SUPPORTED_ATTRIBUTES.contains(attribute[0].toLowerCase())) {
attributesMap.put(attribute[0], attribute[1]);
} else {
// This attribute is not supported, so stop here (no need to check any further ones).
return 0;
}
}
// Unlink the tmp nodes
for (Node node : toUnlink) {
node.unlink();
}
if (attributesMap.size() > 0) {
ImageAttributes imageAttributes = new ImageAttributes(attributesMap);
// The new node is added as a child of the image node to which the attributes apply.
nodeToStyle.appendChild(imageAttributes);
}
return 1;
| 185
| 489
| 674
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/InsExtension.java
|
InsExtension
|
extend
|
class InsExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension, TextContentRenderer.TextContentRendererExtension, MarkdownRenderer.MarkdownRendererExtension {
private InsExtension() {
}
public static Extension create() {
return new InsExtension();
}
@Override
public void extend(Parser.Builder parserBuilder) {
parserBuilder.customDelimiterProcessor(new InsDelimiterProcessor());
}
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
@Override
public NodeRenderer create(HtmlNodeRendererContext context) {
return new InsHtmlNodeRenderer(context);
}
});
}
@Override
public void extend(TextContentRenderer.Builder rendererBuilder) {
rendererBuilder.nodeRendererFactory(new TextContentNodeRendererFactory() {
@Override
public NodeRenderer create(TextContentNodeRendererContext context) {
return new InsTextContentNodeRenderer(context);
}
});
}
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {<FILL_FUNCTION_BODY>}
}
|
rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
@Override
public NodeRenderer create(MarkdownNodeRendererContext context) {
return new InsMarkdownNodeRenderer(context);
}
@Override
public Set<Character> getSpecialCharacters() {
// We technically don't need to escape single occurrences of +, but that's all the extension API
// exposes currently.
return Collections.singleton('+');
}
});
| 296
| 123
| 419
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsDelimiterProcessor.java
|
InsDelimiterProcessor
|
process
|
class InsDelimiterProcessor implements DelimiterProcessor {
@Override
public char getOpeningCharacter() {
return '+';
}
@Override
public char getClosingCharacter() {
return '+';
}
@Override
public int getMinLength() {
return 2;
}
@Override
public int process(DelimiterRun openingRun, DelimiterRun closingRun) {<FILL_FUNCTION_BODY>}
}
|
if (openingRun.length() >= 2 && closingRun.length() >= 2) {
// Use exactly two delimiters even if we have more, and don't care about internal openers/closers.
Text opener = openingRun.getOpener();
// Wrap nodes between delimiters in ins.
Node ins = new Ins();
SourceSpans sourceSpans = new SourceSpans();
sourceSpans.addAllFrom(openingRun.getOpeners(2));
for (Node node : Nodes.between(opener, closingRun.getCloser())) {
ins.appendChild(node);
sourceSpans.addAll(node.getSourceSpans());
}
sourceSpans.addAllFrom(closingRun.getClosers(2));
ins.setSourceSpans(sourceSpans.getSourceSpans());
opener.insertAfter(ins);
return 2;
} else {
return 0;
}
| 124
| 249
| 373
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsHtmlNodeRenderer.java
|
InsHtmlNodeRenderer
|
renderChildren
|
class InsHtmlNodeRenderer extends InsNodeRenderer {
private final HtmlNodeRendererContext context;
private final HtmlWriter html;
public InsHtmlNodeRenderer(HtmlNodeRendererContext context) {
this.context = context;
this.html = context.getWriter();
}
@Override
public void render(Node node) {
Map<String, String> attributes = context.extendAttributes(node, "ins", Collections.<String, String>emptyMap());
html.tag("ins", attributes);
renderChildren(node);
html.tag("/ins");
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
| 170
| 51
| 221
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsMarkdownNodeRenderer.java
|
InsMarkdownNodeRenderer
|
renderChildren
|
class InsMarkdownNodeRenderer extends InsNodeRenderer {
private final MarkdownNodeRendererContext context;
private final MarkdownWriter writer;
public InsMarkdownNodeRenderer(MarkdownNodeRendererContext context) {
this.context = context;
this.writer = context.getWriter();
}
@Override
public void render(Node node) {
writer.raw("++");
renderChildren(node);
writer.raw("++");
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
| 140
| 51
| 191
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsTextContentNodeRenderer.java
|
InsTextContentNodeRenderer
|
renderChildren
|
class InsTextContentNodeRenderer extends InsNodeRenderer {
private final TextContentNodeRendererContext context;
public InsTextContentNodeRenderer(TextContentNodeRendererContext context) {
this.context = context;
}
@Override
public void render(Node node) {
renderChildren(node);
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
| 104
| 51
| 155
|
<methods>public Set<Class<? extends org.commonmark.node.Node>> getNodeTypes() <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemsExtension.java
|
TaskListItemsExtension
|
extend
|
class TaskListItemsExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension {
private TaskListItemsExtension() {
}
public static Extension create() {
return new TaskListItemsExtension();
}
@Override
public void extend(Parser.Builder parserBuilder) {
parserBuilder.postProcessor(new TaskListItemPostProcessor());
}
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {<FILL_FUNCTION_BODY>}
}
|
rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
@Override
public NodeRenderer create(HtmlNodeRendererContext context) {
return new TaskListItemHtmlNodeRenderer(context);
}
});
| 125
| 58
| 183
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemHtmlNodeRenderer.java
|
TaskListItemHtmlNodeRenderer
|
renderChildren
|
class TaskListItemHtmlNodeRenderer implements NodeRenderer {
private final HtmlNodeRendererContext context;
private final HtmlWriter html;
public TaskListItemHtmlNodeRenderer(HtmlNodeRendererContext context) {
this.context = context;
this.html = context.getWriter();
}
@Override
public Set<Class<? extends Node>> getNodeTypes() {
return Collections.<Class<? extends Node>>singleton(TaskListItemMarker.class);
}
@Override
public void render(Node node) {
if (node instanceof TaskListItemMarker) {
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("type", "checkbox");
attributes.put("disabled", "");
if (((TaskListItemMarker) node).isChecked()) {
attributes.put("checked", "");
}
html.tag("input", context.extendAttributes(node, "input", attributes));
// Add a space after the input tag (as the next text node has been trimmed)
html.text(" ");
renderChildren(node);
}
}
private void renderChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
| 301
| 51
| 352
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemPostProcessor.java
|
TaskListItemVisitor
|
visit
|
class TaskListItemVisitor extends AbstractVisitor {
@Override
public void visit(ListItem listItem) {<FILL_FUNCTION_BODY>}
}
|
Node child = listItem.getFirstChild();
if (child instanceof Paragraph) {
Node node = child.getFirstChild();
if (node instanceof Text) {
Text textNode = (Text) node;
Matcher matcher = REGEX_TASK_LIST_ITEM.matcher(textNode.getLiteral());
if (matcher.matches()) {
String checked = matcher.group(1);
boolean isChecked = Objects.equals(checked, "X") || Objects.equals(checked, "x");
// Add the task list item marker node as the first child of the list item.
listItem.prependChild(new TaskListItemMarker(isChecked));
// Parse the node using the input after the task marker (in other words, group 2 from the matcher).
// (Note that the String has been trimmed, so we should add a space between the
// TaskListItemMarker and the text that follows it when we come to render it).
textNode.setLiteral(matcher.group(2));
}
}
}
visitChildren(listItem);
| 44
| 275
| 319
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterVisitor.java
|
YamlFrontMatterVisitor
|
visit
|
class YamlFrontMatterVisitor extends AbstractVisitor {
private Map<String, List<String>> data;
public YamlFrontMatterVisitor() {
data = new LinkedHashMap<>();
}
@Override
public void visit(CustomNode customNode) {<FILL_FUNCTION_BODY>}
public Map<String, List<String>> getData() {
return data;
}
}
|
if (customNode instanceof YamlFrontMatterNode) {
data.put(((YamlFrontMatterNode) customNode).getKey(), ((YamlFrontMatterNode) customNode).getValues());
} else {
super.visit(customNode);
}
| 110
| 73
| 183
|
<methods>public non-sealed void <init>() ,public void visit(org.commonmark.node.BlockQuote) ,public void visit(org.commonmark.node.BulletList) ,public void visit(org.commonmark.node.Code) ,public void visit(org.commonmark.node.Document) ,public void visit(org.commonmark.node.Emphasis) ,public void visit(org.commonmark.node.FencedCodeBlock) ,public void visit(org.commonmark.node.HardLineBreak) ,public void visit(org.commonmark.node.Heading) ,public void visit(org.commonmark.node.ThematicBreak) ,public void visit(org.commonmark.node.HtmlInline) ,public void visit(org.commonmark.node.HtmlBlock) ,public void visit(org.commonmark.node.Image) ,public void visit(org.commonmark.node.IndentedCodeBlock) ,public void visit(org.commonmark.node.Link) ,public void visit(org.commonmark.node.ListItem) ,public void visit(org.commonmark.node.OrderedList) ,public void visit(org.commonmark.node.Paragraph) ,public void visit(org.commonmark.node.SoftLineBreak) ,public void visit(org.commonmark.node.StrongEmphasis) ,public void visit(org.commonmark.node.Text) ,public void visit(org.commonmark.node.LinkReferenceDefinition) ,public void visit(org.commonmark.node.CustomBlock) ,public void visit(org.commonmark.node.CustomNode) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/internal/YamlFrontMatterBlockParser.java
|
YamlFrontMatterBlockParser
|
tryContinue
|
class YamlFrontMatterBlockParser extends AbstractBlockParser {
private static final Pattern REGEX_METADATA = Pattern.compile("^[ ]{0,3}([A-Za-z0-9._-]+):\\s*(.*)");
private static final Pattern REGEX_METADATA_LIST = Pattern.compile("^[ ]+-\\s*(.*)");
private static final Pattern REGEX_METADATA_LITERAL = Pattern.compile("^\\s*(.*)");
private static final Pattern REGEX_BEGIN = Pattern.compile("^-{3}(\\s.*)?");
private static final Pattern REGEX_END = Pattern.compile("^(-{3}|\\.{3})(\\s.*)?");
private boolean inLiteral;
private String currentKey;
private List<String> currentValues;
private YamlFrontMatterBlock block;
public YamlFrontMatterBlockParser() {
inLiteral = false;
currentKey = null;
currentValues = new ArrayList<>();
block = new YamlFrontMatterBlock();
}
@Override
public Block getBlock() {
return block;
}
@Override
public void addLine(SourceLine line) {
}
@Override
public BlockContinue tryContinue(ParserState parserState) {<FILL_FUNCTION_BODY>}
@Override
public void parseInlines(InlineParser inlineParser) {
}
private static String parseString(String s) {
// Limited parsing of https://yaml.org/spec/1.2.2/#73-flow-scalar-styles
// We assume input is well-formed and otherwise treat it as a plain string. In a real
// parser, e.g. `'foo` would be invalid because it's missing a trailing `'`.
if (s.startsWith("'") && s.endsWith("'")) {
String inner = s.substring(1, s.length() - 1);
return inner.replace("''", "'");
} else if (s.startsWith("\"") && s.endsWith("\"")) {
String inner = s.substring(1, s.length() - 1);
// Only support escaped `\` and `"`, nothing else.
return inner
.replace("\\\"", "\"")
.replace("\\\\", "\\");
} else {
return s;
}
}
public static class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
CharSequence line = state.getLine().getContent();
BlockParser parentParser = matchedBlockParser.getMatchedBlockParser();
// check whether this line is the first line of whole document or not
if (parentParser.getBlock() instanceof Document && parentParser.getBlock().getFirstChild() == null &&
REGEX_BEGIN.matcher(line).matches()) {
return BlockStart.of(new YamlFrontMatterBlockParser()).atIndex(state.getNextNonSpaceIndex());
}
return BlockStart.none();
}
}
}
|
final CharSequence line = parserState.getLine().getContent();
if (REGEX_END.matcher(line).matches()) {
if (currentKey != null) {
block.appendChild(new YamlFrontMatterNode(currentKey, currentValues));
}
return BlockContinue.finished();
}
Matcher matcher = REGEX_METADATA.matcher(line);
if (matcher.matches()) {
if (currentKey != null) {
block.appendChild(new YamlFrontMatterNode(currentKey, currentValues));
}
inLiteral = false;
currentKey = matcher.group(1);
currentValues = new ArrayList<>();
String value = matcher.group(2);
if ("|".equals(value)) {
inLiteral = true;
} else if (!"".equals(value)) {
currentValues.add(parseString(value));
}
return BlockContinue.atIndex(parserState.getIndex());
} else {
if (inLiteral) {
matcher = REGEX_METADATA_LITERAL.matcher(line);
if (matcher.matches()) {
if (currentValues.size() == 1) {
currentValues.set(0, currentValues.get(0) + "\n" + matcher.group(1).trim());
} else {
currentValues.add(matcher.group(1).trim());
}
}
} else {
matcher = REGEX_METADATA_LIST.matcher(line);
if (matcher.matches()) {
String value = matcher.group(1);
currentValues.add(parseString(value));
}
}
return BlockContinue.atIndex(parserState.getIndex());
}
| 809
| 463
| 1,272
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/BlockContent.java
|
BlockContent
|
add
|
class BlockContent {
private final StringBuilder sb;
private int lineCount = 0;
public BlockContent() {
sb = new StringBuilder();
}
public BlockContent(String content) {
sb = new StringBuilder(content);
}
public void add(CharSequence line) {<FILL_FUNCTION_BODY>}
public String getString() {
return sb.toString();
}
}
|
if (lineCount != 0) {
sb.append('\n');
}
sb.append(line);
lineCount++;
| 113
| 40
| 153
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/BlockQuoteParser.java
|
Factory
|
tryStart
|
class Factory extends AbstractBlockParserFactory {
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {<FILL_FUNCTION_BODY>}
}
|
int nextNonSpace = state.getNextNonSpaceIndex();
if (isMarker(state, nextNonSpace)) {
int newColumn = state.getColumn() + state.getIndent() + 1;
// optional following space or tab
if (Characters.isSpaceOrTab(state.getLine().getContent(), nextNonSpace + 1)) {
newColumn++;
}
return BlockStart.of(new BlockQuoteParser()).atColumn(newColumn);
} else {
return BlockStart.none();
}
| 45
| 133
| 178
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/Delimiter.java
|
Delimiter
|
getOpeners
|
class Delimiter implements DelimiterRun {
public final List<Text> characters;
public final char delimiterChar;
private final int originalLength;
// Can open emphasis, see spec.
private final boolean canOpen;
// Can close emphasis, see spec.
private final boolean canClose;
public Delimiter previous;
public Delimiter next;
public Delimiter(List<Text> characters, char delimiterChar, boolean canOpen, boolean canClose, Delimiter previous) {
this.characters = characters;
this.delimiterChar = delimiterChar;
this.canOpen = canOpen;
this.canClose = canClose;
this.previous = previous;
this.originalLength = characters.size();
}
@Override
public boolean canOpen() {
return canOpen;
}
@Override
public boolean canClose() {
return canClose;
}
@Override
public int length() {
return characters.size();
}
@Override
public int originalLength() {
return originalLength;
}
@Override
public Text getOpener() {
return characters.get(characters.size() - 1);
}
@Override
public Text getCloser() {
return characters.get(0);
}
@Override
public Iterable<Text> getOpeners(int length) {<FILL_FUNCTION_BODY>}
@Override
public Iterable<Text> getClosers(int length) {
if (!(length >= 1 && length <= length())) {
throw new IllegalArgumentException("length must be between 1 and " + length() + ", was " + length);
}
return characters.subList(0, length);
}
}
|
if (!(length >= 1 && length <= length())) {
throw new IllegalArgumentException("length must be between 1 and " + length() + ", was " + length);
}
return characters.subList(characters.size() - length, characters.size());
| 457
| 66
| 523
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/FencedCodeBlockParser.java
|
Factory
|
checkOpener
|
class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
int indent = state.getIndent();
if (indent >= Parsing.CODE_BLOCK_INDENT) {
return BlockStart.none();
}
int nextNonSpace = state.getNextNonSpaceIndex();
FencedCodeBlockParser blockParser = checkOpener(state.getLine().getContent(), nextNonSpace, indent);
if (blockParser != null) {
return BlockStart.of(blockParser).atIndex(nextNonSpace + blockParser.block.getOpeningFenceLength());
} else {
return BlockStart.none();
}
}
}
// spec: A code fence is a sequence of at least three consecutive backtick characters (`) or tildes (~). (Tildes and
// backticks cannot be mixed.)
private static FencedCodeBlockParser checkOpener(CharSequence line, int index, int indent) {<FILL_FUNCTION_BODY>
|
int backticks = 0;
int tildes = 0;
int length = line.length();
loop:
for (int i = index; i < length; i++) {
switch (line.charAt(i)) {
case '`':
backticks++;
break;
case '~':
tildes++;
break;
default:
break loop;
}
}
if (backticks >= 3 && tildes == 0) {
// spec: If the info string comes after a backtick fence, it may not contain any backtick characters.
if (Characters.find('`', line, index + backticks) != -1) {
return null;
}
return new FencedCodeBlockParser('`', backticks, indent);
} else if (tildes >= 3 && backticks == 0) {
// spec: Info strings for tilde code blocks can contain backticks and tildes
return new FencedCodeBlockParser('~', tildes, indent);
} else {
return null;
}
| 267
| 280
| 547
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/HeadingParser.java
|
HeadingParser
|
tryContinue
|
class HeadingParser extends AbstractBlockParser {
private final Heading block = new Heading();
private final SourceLines content;
public HeadingParser(int level, SourceLines content) {
block.setLevel(level);
this.content = content;
}
@Override
public Block getBlock() {
return block;
}
@Override
public BlockContinue tryContinue(ParserState parserState) {<FILL_FUNCTION_BODY>}
@Override
public void parseInlines(InlineParser inlineParser) {
inlineParser.parse(content, block);
}
public static class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
if (state.getIndent() >= Parsing.CODE_BLOCK_INDENT) {
return BlockStart.none();
}
SourceLine line = state.getLine();
int nextNonSpace = state.getNextNonSpaceIndex();
if (line.getContent().charAt(nextNonSpace) == '#') {
HeadingParser atxHeading = getAtxHeading(line.substring(nextNonSpace, line.getContent().length()));
if (atxHeading != null) {
return BlockStart.of(atxHeading).atIndex(line.getContent().length());
}
}
int setextHeadingLevel = getSetextHeadingLevel(line.getContent(), nextNonSpace);
if (setextHeadingLevel > 0) {
SourceLines paragraph = matchedBlockParser.getParagraphLines();
if (!paragraph.isEmpty()) {
return BlockStart.of(new HeadingParser(setextHeadingLevel, paragraph))
.atIndex(line.getContent().length())
.replaceActiveBlockParser();
}
}
return BlockStart.none();
}
}
// spec: An ATX heading consists of a string of characters, parsed as inline content, between an opening sequence of
// 1–6 unescaped # characters and an optional closing sequence of any number of unescaped # characters. The opening
// sequence of # characters must be followed by a space or by the end of line. The optional closing sequence of #s
// must be preceded by a space and may be followed by spaces only.
private static HeadingParser getAtxHeading(SourceLine line) {
Scanner scanner = Scanner.of(SourceLines.of(line));
int level = scanner.matchMultiple('#');
if (level == 0 || level > 6) {
return null;
}
if (!scanner.hasNext()) {
// End of line after markers is an empty heading
return new HeadingParser(level, SourceLines.empty());
}
char next = scanner.peek();
if (!(next == ' ' || next == '\t')) {
return null;
}
scanner.whitespace();
Position start = scanner.position();
Position end = start;
boolean hashCanEnd = true;
while (scanner.hasNext()) {
char c = scanner.peek();
switch (c) {
case '#':
if (hashCanEnd) {
scanner.matchMultiple('#');
int whitespace = scanner.whitespace();
// If there's other characters, the hashes and spaces were part of the heading
if (scanner.hasNext()) {
end = scanner.position();
}
hashCanEnd = whitespace > 0;
} else {
scanner.next();
end = scanner.position();
}
break;
case ' ':
case '\t':
hashCanEnd = true;
scanner.next();
break;
default:
hashCanEnd = false;
scanner.next();
end = scanner.position();
}
}
SourceLines source = scanner.getSource(start, end);
String content = source.getContent();
if (content.isEmpty()) {
return new HeadingParser(level, SourceLines.empty());
}
return new HeadingParser(level, source);
}
// spec: A setext heading underline is a sequence of = characters or a sequence of - characters, with no more than
// 3 spaces indentation and any number of trailing spaces.
private static int getSetextHeadingLevel(CharSequence line, int index) {
switch (line.charAt(index)) {
case '=':
if (isSetextHeadingRest(line, index + 1, '=')) {
return 1;
}
case '-':
if (isSetextHeadingRest(line, index + 1, '-')) {
return 2;
}
}
return 0;
}
private static boolean isSetextHeadingRest(CharSequence line, int index, char marker) {
int afterMarker = Characters.skip(marker, line, index, line.length());
int afterSpace = Characters.skipSpaceTab(line, afterMarker, line.length());
return afterSpace >= line.length();
}
}
|
// In both ATX and Setext headings, once we have the heading markup, there's nothing more to parse.
return BlockContinue.none();
| 1,297
| 41
| 1,338
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/HtmlBlockParser.java
|
HtmlBlockParser
|
tryContinue
|
class HtmlBlockParser extends AbstractBlockParser {
private static final String TAGNAME = "[A-Za-z][A-Za-z0-9-]*";
private static final String ATTRIBUTENAME = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
private static final String UNQUOTEDVALUE = "[^\"'=<>`\\x00-\\x20]+";
private static final String SINGLEQUOTEDVALUE = "'[^']*'";
private static final String DOUBLEQUOTEDVALUE = "\"[^\"]*\"";
private static final String ATTRIBUTEVALUE = "(?:" + UNQUOTEDVALUE + "|" + SINGLEQUOTEDVALUE
+ "|" + DOUBLEQUOTEDVALUE + ")";
private static final String ATTRIBUTEVALUESPEC = "(?:" + "\\s*=" + "\\s*" + ATTRIBUTEVALUE
+ ")";
private static final String ATTRIBUTE = "(?:" + "\\s+" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC
+ "?)";
private static final String OPENTAG = "<" + TAGNAME + ATTRIBUTE + "*" + "\\s*/?>";
private static final String CLOSETAG = "</" + TAGNAME + "\\s*[>]";
private static final Pattern[][] BLOCK_PATTERNS = new Pattern[][]{
{null, null}, // not used (no type 0)
{
Pattern.compile("^<(?:script|pre|style|textarea)(?:\\s|>|$)", Pattern.CASE_INSENSITIVE),
Pattern.compile("</(?:script|pre|style|textarea)>", Pattern.CASE_INSENSITIVE)
},
{
Pattern.compile("^<!--"),
Pattern.compile("-->")
},
{
Pattern.compile("^<[?]"),
Pattern.compile("\\?>")
},
{
Pattern.compile("^<![A-Z]"),
Pattern.compile(">")
},
{
Pattern.compile("^<!\\[CDATA\\["),
Pattern.compile("\\]\\]>")
},
{
Pattern.compile("^</?(?:" +
"address|article|aside|" +
"base|basefont|blockquote|body|" +
"caption|center|col|colgroup|" +
"dd|details|dialog|dir|div|dl|dt|" +
"fieldset|figcaption|figure|footer|form|frame|frameset|" +
"h1|h2|h3|h4|h5|h6|head|header|hr|html|" +
"iframe|" +
"legend|li|link|" +
"main|menu|menuitem|" +
"nav|noframes|" +
"ol|optgroup|option|" +
"p|param|" +
"search|section|summary|" +
"table|tbody|td|tfoot|th|thead|title|tr|track|" +
"ul" +
")(?:\\s|[/]?[>]|$)", Pattern.CASE_INSENSITIVE),
null // terminated by blank line
},
{
Pattern.compile("^(?:" + OPENTAG + '|' + CLOSETAG + ")\\s*$", Pattern.CASE_INSENSITIVE),
null // terminated by blank line
}
};
private final HtmlBlock block = new HtmlBlock();
private final Pattern closingPattern;
private boolean finished = false;
private BlockContent content = new BlockContent();
private HtmlBlockParser(Pattern closingPattern) {
this.closingPattern = closingPattern;
}
@Override
public Block getBlock() {
return block;
}
@Override
public BlockContinue tryContinue(ParserState state) {<FILL_FUNCTION_BODY>}
@Override
public void addLine(SourceLine line) {
content.add(line.getContent());
if (closingPattern != null && closingPattern.matcher(line.getContent()).find()) {
finished = true;
}
}
@Override
public void closeBlock() {
block.setLiteral(content.getString());
content = null;
}
public static class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
int nextNonSpace = state.getNextNonSpaceIndex();
CharSequence line = state.getLine().getContent();
if (state.getIndent() < 4 && line.charAt(nextNonSpace) == '<') {
for (int blockType = 1; blockType <= 7; blockType++) {
// Type 7 can not interrupt a paragraph (not even a lazy one)
if (blockType == 7 && (
matchedBlockParser.getMatchedBlockParser().getBlock() instanceof Paragraph ||
state.getActiveBlockParser().canHaveLazyContinuationLines())) {
continue;
}
Pattern opener = BLOCK_PATTERNS[blockType][0];
Pattern closer = BLOCK_PATTERNS[blockType][1];
boolean matches = opener.matcher(line.subSequence(nextNonSpace, line.length())).find();
if (matches) {
return BlockStart.of(new HtmlBlockParser(closer)).atIndex(state.getIndex());
}
}
}
return BlockStart.none();
}
}
}
|
if (finished) {
return BlockContinue.none();
}
// Blank line ends type 6 and type 7 blocks
if (state.isBlank() && closingPattern == null) {
return BlockContinue.none();
} else {
return BlockContinue.atIndex(state.getIndex());
}
| 1,462
| 87
| 1,549
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/IndentedCodeBlockParser.java
|
Factory
|
tryStart
|
class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {<FILL_FUNCTION_BODY>}
}
|
// An indented code block cannot interrupt a paragraph.
if (state.getIndent() >= Parsing.CODE_BLOCK_INDENT && !state.isBlank() && !(state.getActiveBlockParser().getBlock() instanceof Paragraph)) {
return BlockStart.of(new IndentedCodeBlockParser()).atColumn(state.getColumn() + Parsing.CODE_BLOCK_INDENT);
} else {
return BlockStart.none();
}
| 50
| 116
| 166
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/LinkReferenceDefinitions.java
|
LinkReferenceDefinitions
|
add
|
class LinkReferenceDefinitions {
// LinkedHashMap for determinism and to preserve document order
private final Map<String, LinkReferenceDefinition> definitions = new LinkedHashMap<>();
public void add(LinkReferenceDefinition definition) {<FILL_FUNCTION_BODY>}
public LinkReferenceDefinition get(String label) {
String normalizedLabel = Escaping.normalizeLabelContent(label);
return definitions.get(normalizedLabel);
}
}
|
String normalizedLabel = Escaping.normalizeLabelContent(definition.getLabel());
// spec: When there are multiple matching link reference definitions, the first is used
if (!definitions.containsKey(normalizedLabel)) {
definitions.put(normalizedLabel, definition);
}
| 113
| 71
| 184
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/ListItemParser.java
|
ListItemParser
|
tryContinue
|
class ListItemParser extends AbstractBlockParser {
private final ListItem block = new ListItem();
/**
* Minimum number of columns that the content has to be indented (relative to the containing block) to be part of
* this list item.
*/
private int contentIndent;
private boolean hadBlankLine;
public ListItemParser(int markerIndent, int contentIndent) {
this.contentIndent = contentIndent;
block.setMarkerIndent(markerIndent);
block.setContentIndent(contentIndent);
}
@Override
public boolean isContainer() {
return true;
}
@Override
public boolean canContain(Block childBlock) {
if (hadBlankLine) {
// We saw a blank line in this list item, that means the list block is loose.
//
// spec: if any of its constituent list items directly contain two block-level elements with a blank line
// between them
Block parent = block.getParent();
if (parent instanceof ListBlock) {
((ListBlock) parent).setTight(false);
}
}
return true;
}
@Override
public Block getBlock() {
return block;
}
@Override
public BlockContinue tryContinue(ParserState state) {<FILL_FUNCTION_BODY>}
}
|
if (state.isBlank()) {
if (block.getFirstChild() == null) {
// Blank line after empty list item
return BlockContinue.none();
} else {
Block activeBlock = state.getActiveBlockParser().getBlock();
// If the active block is a code block, blank lines in it should not affect if the list is tight.
hadBlankLine = activeBlock instanceof Paragraph || activeBlock instanceof ListItem;
return BlockContinue.atIndex(state.getNextNonSpaceIndex());
}
}
if (state.getIndent() >= contentIndent) {
return BlockContinue.atColumn(state.getColumn() + contentIndent);
} else {
// Note: We'll hit this case for lazy continuation lines, they will get added later.
return BlockContinue.none();
}
| 348
| 213
| 561
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/ParagraphParser.java
|
ParagraphParser
|
tryContinue
|
class ParagraphParser extends AbstractBlockParser {
private final Paragraph block = new Paragraph();
private final LinkReferenceDefinitionParser linkReferenceDefinitionParser = new LinkReferenceDefinitionParser();
@Override
public boolean canHaveLazyContinuationLines() {
return true;
}
@Override
public Block getBlock() {
return block;
}
@Override
public BlockContinue tryContinue(ParserState state) {<FILL_FUNCTION_BODY>}
@Override
public void addLine(SourceLine line) {
linkReferenceDefinitionParser.parse(line);
}
@Override
public void addSourceSpan(SourceSpan sourceSpan) {
// Some source spans might belong to link reference definitions, others to the paragraph.
// The parser will handle that.
linkReferenceDefinitionParser.addSourceSpan(sourceSpan);
}
@Override
public void closeBlock() {
if (linkReferenceDefinitionParser.getParagraphLines().isEmpty()) {
block.unlink();
} else {
block.setSourceSpans(linkReferenceDefinitionParser.getParagraphSourceSpans());
}
}
@Override
public void parseInlines(InlineParser inlineParser) {
SourceLines lines = linkReferenceDefinitionParser.getParagraphLines();
if (!lines.isEmpty()) {
inlineParser.parse(lines, block);
}
}
public SourceLines getParagraphLines() {
return linkReferenceDefinitionParser.getParagraphLines();
}
public List<LinkReferenceDefinition> getDefinitions() {
return linkReferenceDefinitionParser.getDefinitions();
}
}
|
if (!state.isBlank()) {
return BlockContinue.atIndex(state.getIndex());
} else {
return BlockContinue.none();
}
| 417
| 46
| 463
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/StaggeredDelimiterProcessor.java
|
StaggeredDelimiterProcessor
|
add
|
class StaggeredDelimiterProcessor implements DelimiterProcessor {
private final char delim;
private int minLength = 0;
private LinkedList<DelimiterProcessor> processors = new LinkedList<>(); // in reverse getMinLength order
StaggeredDelimiterProcessor(char delim) {
this.delim = delim;
}
@Override
public char getOpeningCharacter() {
return delim;
}
@Override
public char getClosingCharacter() {
return delim;
}
@Override
public int getMinLength() {
return minLength;
}
void add(DelimiterProcessor dp) {<FILL_FUNCTION_BODY>}
private DelimiterProcessor findProcessor(int len) {
for (DelimiterProcessor p : processors) {
if (p.getMinLength() <= len) {
return p;
}
}
return processors.getFirst();
}
@Override
public int process(DelimiterRun openingRun, DelimiterRun closingRun) {
return findProcessor(openingRun.length()).process(openingRun, closingRun);
}
}
|
final int len = dp.getMinLength();
ListIterator<DelimiterProcessor> it = processors.listIterator();
boolean added = false;
while (it.hasNext()) {
DelimiterProcessor p = it.next();
int pLen = p.getMinLength();
if (len > pLen) {
it.previous();
it.add(dp);
added = true;
break;
} else if (len == pLen) {
throw new IllegalArgumentException("Cannot add two delimiter processors for char '" + delim + "' and minimum length " + len + "; conflicting processors: " + p + ", " + dp);
}
}
if (!added) {
processors.add(dp);
this.minLength = len;
}
| 304
| 201
| 505
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/ThematicBreakParser.java
|
Factory
|
isThematicBreak
|
class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
if (state.getIndent() >= 4) {
return BlockStart.none();
}
int nextNonSpace = state.getNextNonSpaceIndex();
CharSequence line = state.getLine().getContent();
if (isThematicBreak(line, nextNonSpace)) {
var literal = String.valueOf(line.subSequence(state.getIndex(), line.length()));
return BlockStart.of(new ThematicBreakParser(literal)).atIndex(line.length());
} else {
return BlockStart.none();
}
}
}
// spec: A line consisting of 0-3 spaces of indentation, followed by a sequence of three or more matching -, _, or *
// characters, each followed optionally by any number of spaces, forms a thematic break.
private static boolean isThematicBreak(CharSequence line, int index) {<FILL_FUNCTION_BODY>
|
int dashes = 0;
int underscores = 0;
int asterisks = 0;
int length = line.length();
for (int i = index; i < length; i++) {
switch (line.charAt(i)) {
case '-':
dashes++;
break;
case '_':
underscores++;
break;
case '*':
asterisks++;
break;
case ' ':
case '\t':
// Allowed, even between markers
break;
default:
return false;
}
}
return ((dashes >= 3 && underscores == 0 && asterisks == 0) ||
(underscores >= 3 && dashes == 0 && asterisks == 0) ||
(asterisks >= 3 && dashes == 0 && underscores == 0));
| 259
| 223
| 482
|
<methods>public non-sealed void <init>() ,public void addLine(org.commonmark.parser.SourceLine) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public boolean canContain(org.commonmark.node.Block) ,public boolean canHaveLazyContinuationLines() ,public void closeBlock() ,public boolean isContainer() ,public void parseInlines(org.commonmark.parser.InlineParser) <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/inline/AutolinkInlineParser.java
|
AutolinkInlineParser
|
tryParse
|
class AutolinkInlineParser implements InlineContentParser {
private static final Pattern URI = Pattern
.compile("^[a-zA-Z][a-zA-Z0-9.+-]{1,31}:[^<>\u0000-\u0020]*$");
private static final Pattern EMAIL = Pattern
.compile("^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$");
@Override
public ParsedInline tryParse(InlineParserState inlineParserState) {<FILL_FUNCTION_BODY>}
}
|
Scanner scanner = inlineParserState.scanner();
scanner.next();
Position textStart = scanner.position();
if (scanner.find('>') > 0) {
SourceLines textSource = scanner.getSource(textStart, scanner.position());
String content = textSource.getContent();
scanner.next();
String destination = null;
if (URI.matcher(content).matches()) {
destination = content;
} else if (EMAIL.matcher(content).matches()) {
destination = "mailto:" + content;
}
if (destination != null) {
Link link = new Link(destination, null);
Text text = new Text(content);
text.setSourceSpans(textSource.getSourceSpans());
link.appendChild(text);
return ParsedInline.of(link, scanner.position());
}
}
return ParsedInline.none();
| 255
| 248
| 503
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/inline/BackslashInlineParser.java
|
BackslashInlineParser
|
tryParse
|
class BackslashInlineParser implements InlineContentParser {
private static final Pattern ESCAPABLE = Pattern.compile('^' + Escaping.ESCAPABLE);
@Override
public ParsedInline tryParse(InlineParserState inlineParserState) {<FILL_FUNCTION_BODY>}
}
|
Scanner scanner = inlineParserState.scanner();
// Backslash
scanner.next();
char next = scanner.peek();
if (next == '\n') {
scanner.next();
return ParsedInline.of(new HardLineBreak(), scanner.position());
} else if (ESCAPABLE.matcher(String.valueOf(next)).matches()) {
scanner.next();
return ParsedInline.of(new Text(String.valueOf(next)), scanner.position());
} else {
return ParsedInline.of(new Text("\\"), scanner.position());
}
| 80
| 165
| 245
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/inline/BackticksInlineParser.java
|
BackticksInlineParser
|
tryParse
|
class BackticksInlineParser implements InlineContentParser {
@Override
public ParsedInline tryParse(InlineParserState inlineParserState) {<FILL_FUNCTION_BODY>}
}
|
Scanner scanner = inlineParserState.scanner();
Position start = scanner.position();
int openingTicks = scanner.matchMultiple('`');
Position afterOpening = scanner.position();
while (scanner.find('`') > 0) {
Position beforeClosing = scanner.position();
int count = scanner.matchMultiple('`');
if (count == openingTicks) {
Code node = new Code();
String content = scanner.getSource(afterOpening, beforeClosing).getContent();
content = content.replace('\n', ' ');
// spec: If the resulting string both begins and ends with a space character, but does not consist
// entirely of space characters, a single space character is removed from the front and back.
if (content.length() >= 3 &&
content.charAt(0) == ' ' &&
content.charAt(content.length() - 1) == ' ' &&
Characters.hasNonSpace(content)) {
content = content.substring(1, content.length() - 1);
}
node.setLiteral(content);
return ParsedInline.of(node, scanner.position());
}
}
// If we got here, we didn't find a matching closing backtick sequence.
SourceLines source = scanner.getSource(start, afterOpening);
Text text = new Text(source.getContent());
return ParsedInline.of(text, afterOpening);
| 53
| 378
| 431
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/inline/EmphasisDelimiterProcessor.java
|
EmphasisDelimiterProcessor
|
process
|
class EmphasisDelimiterProcessor implements DelimiterProcessor {
private final char delimiterChar;
protected EmphasisDelimiterProcessor(char delimiterChar) {
this.delimiterChar = delimiterChar;
}
@Override
public char getOpeningCharacter() {
return delimiterChar;
}
@Override
public char getClosingCharacter() {
return delimiterChar;
}
@Override
public int getMinLength() {
return 1;
}
@Override
public int process(DelimiterRun openingRun, DelimiterRun closingRun) {<FILL_FUNCTION_BODY>}
}
|
// "multiple of 3" rule for internal delimiter runs
if ((openingRun.canClose() || closingRun.canOpen()) &&
closingRun.originalLength() % 3 != 0 &&
(openingRun.originalLength() + closingRun.originalLength()) % 3 == 0) {
return 0;
}
int usedDelimiters;
Node emphasis;
// calculate actual number of delimiters used from this closer
if (openingRun.length() >= 2 && closingRun.length() >= 2) {
usedDelimiters = 2;
emphasis = new StrongEmphasis(String.valueOf(delimiterChar) + delimiterChar);
} else {
usedDelimiters = 1;
emphasis = new Emphasis(String.valueOf(delimiterChar));
}
SourceSpans sourceSpans = SourceSpans.empty();
sourceSpans.addAllFrom(openingRun.getOpeners(usedDelimiters));
Text opener = openingRun.getOpener();
for (Node node : Nodes.between(opener, closingRun.getCloser())) {
emphasis.appendChild(node);
sourceSpans.addAll(node.getSourceSpans());
}
sourceSpans.addAllFrom(closingRun.getClosers(usedDelimiters));
emphasis.setSourceSpans(sourceSpans.getSourceSpans());
opener.insertAfter(emphasis);
return usedDelimiters;
| 177
| 377
| 554
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/inline/EntityInlineParser.java
|
EntityInlineParser
|
tryParse
|
class EntityInlineParser implements InlineContentParser {
private static final AsciiMatcher hex = AsciiMatcher.builder().range('0', '9').range('A', 'F').range('a', 'f').build();
private static final AsciiMatcher dec = AsciiMatcher.builder().range('0', '9').build();
private static final AsciiMatcher entityStart = AsciiMatcher.builder().range('A', 'Z').range('a', 'z').build();
private static final AsciiMatcher entityContinue = entityStart.newBuilder().range('0', '9').build();
@Override
public ParsedInline tryParse(InlineParserState inlineParserState) {<FILL_FUNCTION_BODY>}
private ParsedInline entity(Scanner scanner, Position start) {
String text = scanner.getSource(start, scanner.position()).getContent();
return ParsedInline.of(new Text(Html5Entities.entityToString(text)), scanner.position());
}
}
|
Scanner scanner = inlineParserState.scanner();
Position start = scanner.position();
// Skip `&`
scanner.next();
char c = scanner.peek();
if (c == '#') {
// Numeric
scanner.next();
if (scanner.next('x') || scanner.next('X')) {
int digits = scanner.match(hex);
if (1 <= digits && digits <= 6 && scanner.next(';')) {
return entity(scanner, start);
}
} else {
int digits = scanner.match(dec);
if (1 <= digits && digits <= 7 && scanner.next(';')) {
return entity(scanner, start);
}
}
} else if (entityStart.matches(c)) {
scanner.match(entityContinue);
if (scanner.next(';')) {
return entity(scanner, start);
}
}
return ParsedInline.none();
| 264
| 266
| 530
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/inline/HtmlInlineParser.java
|
HtmlInlineParser
|
tryOpenTag
|
class HtmlInlineParser implements InlineContentParser {
private static final AsciiMatcher asciiLetter = AsciiMatcher.builder().range('A', 'Z').range('a', 'z').build();
// spec: A tag name consists of an ASCII letter followed by zero or more ASCII letters, digits, or hyphens (-).
private static final AsciiMatcher tagNameStart = asciiLetter;
private static final AsciiMatcher tagNameContinue = tagNameStart.newBuilder().range('0', '9').c('-').build();
// spec: An attribute name consists of an ASCII letter, _, or :, followed by zero or more ASCII letters, digits,
// _, ., :, or -. (Note: This is the XML specification restricted to ASCII. HTML5 is laxer.)
private static final AsciiMatcher attributeStart = asciiLetter.newBuilder().c('_').c(':').build();
private static final AsciiMatcher attributeContinue = attributeStart.newBuilder().range('0', '9').c('.').c('-').build();
// spec: An unquoted attribute value is a nonempty string of characters not including whitespace, ", ', =, <, >, or `.
private static final AsciiMatcher attributeValueEnd = AsciiMatcher.builder()
.c(' ').c('\t').c('\n').c('\u000B').c('\f').c('\r')
.c('"').c('\'').c('=').c('<').c('>').c('`')
.build();
@Override
public ParsedInline tryParse(InlineParserState inlineParserState) {
Scanner scanner = inlineParserState.scanner();
Position start = scanner.position();
// Skip over `<`
scanner.next();
char c = scanner.peek();
if (tagNameStart.matches(c)) {
if (tryOpenTag(scanner)) {
return htmlInline(start, scanner);
}
} else if (c == '/') {
if (tryClosingTag(scanner)) {
return htmlInline(start, scanner);
}
} else if (c == '?') {
if (tryProcessingInstruction(scanner)) {
return htmlInline(start, scanner);
}
} else if (c == '!') {
// comment, declaration or CDATA
scanner.next();
c = scanner.peek();
if (c == '-') {
if (tryComment(scanner)) {
return htmlInline(start, scanner);
}
} else if (c == '[') {
if (tryCdata(scanner)) {
return htmlInline(start, scanner);
}
} else if (asciiLetter.matches(c)) {
if (tryDeclaration(scanner)) {
return htmlInline(start, scanner);
}
}
}
return ParsedInline.none();
}
private static ParsedInline htmlInline(Position start, Scanner scanner) {
String text = scanner.getSource(start, scanner.position()).getContent();
HtmlInline node = new HtmlInline();
node.setLiteral(text);
return ParsedInline.of(node, scanner.position());
}
private static boolean tryOpenTag(Scanner scanner) {<FILL_FUNCTION_BODY>}
private static boolean tryClosingTag(Scanner scanner) {
// spec: A closing tag consists of the string </, a tag name, optional whitespace, and the character >.
scanner.next();
if (scanner.match(tagNameStart) >= 1) {
scanner.match(tagNameContinue);
scanner.whitespace();
return scanner.next('>');
}
return false;
}
private static boolean tryProcessingInstruction(Scanner scanner) {
// spec: A processing instruction consists of the string <?, a string of characters not including the string ?>,
// and the string ?>.
scanner.next();
while (scanner.find('?') > 0) {
scanner.next();
if (scanner.next('>')) {
return true;
}
}
return false;
}
private static boolean tryComment(Scanner scanner) {
// spec: An [HTML comment](@) consists of `<!-->`, `<!--->`, or `<!--`, a string of
// characters not including the string `-->`, and `-->` (see the
// [HTML spec](https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state)).
// Skip first `-`
scanner.next();
if (!scanner.next('-')) {
return false;
}
if (scanner.next('>') || scanner.next("->")) {
return true;
}
while (scanner.find('-') >= 0) {
if (scanner.next("-->")) {
return true;
} else {
scanner.next();
}
}
return false;
}
private static boolean tryCdata(Scanner scanner) {
// spec: A CDATA section consists of the string <![CDATA[, a string of characters not including the string ]]>,
// and the string ]]>.
// Skip `[`
scanner.next();
if (scanner.next("CDATA[")) {
while (scanner.find(']') >= 0) {
if (scanner.next("]]>")) {
return true;
} else {
scanner.next();
}
}
}
return false;
}
private static boolean tryDeclaration(Scanner scanner) {
// spec: A declaration consists of the string <!, an ASCII letter, zero or more characters not including
// the character >, and the character >.
scanner.match(asciiLetter);
if (scanner.whitespace() <= 0) {
return false;
}
if (scanner.find('>') >= 0) {
scanner.next();
return true;
}
return false;
}
}
|
// spec: An open tag consists of a < character, a tag name, zero or more attributes, optional whitespace,
// an optional / character, and a > character.
scanner.next();
scanner.match(tagNameContinue);
boolean whitespace = scanner.whitespace() >= 1;
// spec: An attribute consists of whitespace, an attribute name, and an optional attribute value specification.
while (whitespace && scanner.match(attributeStart) >= 1) {
scanner.match(attributeContinue);
// spec: An attribute value specification consists of optional whitespace, a = character,
// optional whitespace, and an attribute value.
whitespace = scanner.whitespace() >= 1;
if (scanner.next('=')) {
scanner.whitespace();
char valueStart = scanner.peek();
if (valueStart == '\'') {
scanner.next();
if (scanner.find('\'') < 0) {
return false;
}
scanner.next();
} else if (valueStart == '"') {
scanner.next();
if (scanner.find('"') < 0) {
return false;
}
scanner.next();
} else {
if (scanner.find(attributeValueEnd) <= 0) {
return false;
}
}
// Whitespace is required between attributes
whitespace = scanner.whitespace() >= 1;
}
}
scanner.next('/');
return scanner.next('>');
| 1,623
| 392
| 2,015
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/inline/ParsedInline.java
|
ParsedInline
|
of
|
class ParsedInline {
protected ParsedInline() {
}
public static ParsedInline none() {
return null;
}
public static ParsedInline of(Node node, Position position) {<FILL_FUNCTION_BODY>}
}
|
if (node == null) {
throw new NullPointerException("node must not be null");
}
if (position == null) {
throw new NullPointerException("position must not be null");
}
return new ParsedInlineImpl(node, position);
| 76
| 70
| 146
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/renderer/NodeRendererMap.java
|
NodeRendererMap
|
add
|
class NodeRendererMap {
private final Map<Class<? extends Node>, NodeRenderer> renderers = new HashMap<>(32);
public void add(NodeRenderer nodeRenderer) {<FILL_FUNCTION_BODY>}
public void render(Node node) {
NodeRenderer nodeRenderer = renderers.get(node.getClass());
if (nodeRenderer != null) {
nodeRenderer.render(node);
}
}
}
|
for (Class<? extends Node> nodeType : nodeRenderer.getNodeTypes()) {
// Overwrite existing renderer
renderers.put(nodeType, nodeRenderer);
}
| 117
| 49
| 166
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/util/Escaping.java
|
Escaping
|
replaceAll
|
class Escaping {
public static final String ESCAPABLE = "[!\"#$%&\'()*+,./:;<=>?@\\[\\\\\\]^_`{|}~-]";
public static final String ENTITY = "&(?:#x[a-f0-9]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,31});";
private static final Pattern BACKSLASH_OR_AMP = Pattern.compile("[\\\\&]");
private static final Pattern ENTITY_OR_ESCAPED_CHAR =
Pattern.compile("\\\\" + ESCAPABLE + '|' + ENTITY, Pattern.CASE_INSENSITIVE);
// From RFC 3986 (see "reserved", "unreserved") except don't escape '[' or ']' to be compatible with JS encodeURI
private static final Pattern ESCAPE_IN_URI =
Pattern.compile("(%[a-fA-F0-9]{0,2}|[^:/?#@!$&'()*+,;=a-zA-Z0-9\\-._~])");
private static final char[] HEX_DIGITS =
new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static final Pattern WHITESPACE = Pattern.compile("[ \t\r\n]+");
private static final Replacer UNESCAPE_REPLACER = new Replacer() {
@Override
public void replace(String input, StringBuilder sb) {
if (input.charAt(0) == '\\') {
sb.append(input, 1, input.length());
} else {
sb.append(Html5Entities.entityToString(input));
}
}
};
private static final Replacer URI_REPLACER = new Replacer() {
@Override
public void replace(String input, StringBuilder sb) {
if (input.startsWith("%")) {
if (input.length() == 3) {
// Already percent-encoded, preserve
sb.append(input);
} else {
// %25 is the percent-encoding for %
sb.append("%25");
sb.append(input, 1, input.length());
}
} else {
byte[] bytes = input.getBytes(Charset.forName("UTF-8"));
for (byte b : bytes) {
sb.append('%');
sb.append(HEX_DIGITS[(b >> 4) & 0xF]);
sb.append(HEX_DIGITS[b & 0xF]);
}
}
}
};
public static String escapeHtml(String input) {
// Avoid building a new string in the majority of cases (nothing to escape)
StringBuilder sb = null;
loop:
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
String replacement;
switch (c) {
case '&':
replacement = "&";
break;
case '<':
replacement = "<";
break;
case '>':
replacement = ">";
break;
case '\"':
replacement = """;
break;
default:
if (sb != null) {
sb.append(c);
}
continue loop;
}
if (sb == null) {
sb = new StringBuilder();
sb.append(input, 0, i);
}
sb.append(replacement);
}
return sb != null ? sb.toString() : input;
}
/**
* Replace entities and backslash escapes with literal characters.
*/
public static String unescapeString(String s) {
if (BACKSLASH_OR_AMP.matcher(s).find()) {
return replaceAll(ENTITY_OR_ESCAPED_CHAR, s, UNESCAPE_REPLACER);
} else {
return s;
}
}
public static String percentEncodeUrl(String s) {
return replaceAll(ESCAPE_IN_URI, s, URI_REPLACER);
}
public static String normalizeLabelContent(String input) {
String trimmed = input.trim();
// This is necessary to correctly case fold "ẞ" to "SS":
// "ẞ".toLowerCase(Locale.ROOT) -> "ß"
// "ß".toUpperCase(Locale.ROOT) -> "SS"
// Note that doing upper first (or only upper without lower) wouldn't work because:
// "ẞ".toUpperCase(Locale.ROOT) -> "ẞ"
String caseFolded = trimmed.toLowerCase(Locale.ROOT).toUpperCase(Locale.ROOT);
return WHITESPACE.matcher(caseFolded).replaceAll(" ");
}
private static String replaceAll(Pattern p, String s, Replacer replacer) {<FILL_FUNCTION_BODY>}
private interface Replacer {
void replace(String input, StringBuilder sb);
}
}
|
Matcher matcher = p.matcher(s);
if (!matcher.find()) {
return s;
}
StringBuilder sb = new StringBuilder(s.length() + 16);
int lastEnd = 0;
do {
sb.append(s, lastEnd, matcher.start());
replacer.replace(matcher.group(), sb);
lastEnd = matcher.end();
} while (matcher.find());
if (lastEnd != s.length()) {
sb.append(s, lastEnd, s.length());
}
return sb.toString();
| 1,398
| 156
| 1,554
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/util/Html5Entities.java
|
Html5Entities
|
readEntities
|
class Html5Entities {
private static final Map<String, String> NAMED_CHARACTER_REFERENCES = readEntities();
private static final String ENTITY_PATH = "/org/commonmark/internal/util/entities.properties";
public static String entityToString(String input) {
if (!input.startsWith("&") || !input.endsWith(";")) {
return input;
}
String value = input.substring(1, input.length() - 1);
if (value.startsWith("#")) {
value = value.substring(1);
int base = 10;
if (value.startsWith("x") || value.startsWith("X")) {
value = value.substring(1);
base = 16;
}
try {
int codePoint = Integer.parseInt(value, base);
if (codePoint == 0) {
return "\uFFFD";
}
return new String(Character.toChars(codePoint));
} catch (IllegalArgumentException e) {
return "\uFFFD";
}
} else {
String s = NAMED_CHARACTER_REFERENCES.get(value);
if (s != null) {
return s;
} else {
return input;
}
}
}
private static Map<String, String> readEntities() {<FILL_FUNCTION_BODY>}
}
|
Map<String, String> entities = new HashMap<>();
InputStream stream = Html5Entities.class.getResourceAsStream(ENTITY_PATH);
Charset charset = StandardCharsets.UTF_8;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream, charset))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.length() == 0) {
continue;
}
int equal = line.indexOf("=");
String key = line.substring(0, equal);
String value = line.substring(equal + 1);
entities.put(key, value);
}
} catch (IOException e) {
throw new IllegalStateException("Failed reading data for HTML named character references", e);
}
entities.put("NewLine", "\n");
return entities;
| 371
| 224
| 595
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/util/LinkScanner.java
|
LinkScanner
|
scanLinkTitleContent
|
class LinkScanner {
/**
* Attempt to scan the contents of a link label (inside the brackets), stopping after the content or returning false.
* The stopped position can bei either the closing {@code ]}, or the end of the line if the label continues on
* the next line.
*/
public static boolean scanLinkLabelContent(Scanner scanner) {
while (scanner.hasNext()) {
switch (scanner.peek()) {
case '\\':
scanner.next();
if (isEscapable(scanner.peek())) {
scanner.next();
}
break;
case ']':
return true;
case '[':
// spec: Unescaped square bracket characters are not allowed inside the opening and closing
// square brackets of link labels.
return false;
default:
scanner.next();
}
}
return true;
}
/**
* Attempt to scan a link destination, stopping after the destination or returning false.
*/
public static boolean scanLinkDestination(Scanner scanner) {
if (!scanner.hasNext()) {
return false;
}
if (scanner.next('<')) {
while (scanner.hasNext()) {
switch (scanner.peek()) {
case '\\':
scanner.next();
if (isEscapable(scanner.peek())) {
scanner.next();
}
break;
case '\n':
case '<':
return false;
case '>':
scanner.next();
return true;
default:
scanner.next();
}
}
return false;
} else {
return scanLinkDestinationWithBalancedParens(scanner);
}
}
public static boolean scanLinkTitle(Scanner scanner) {
if (!scanner.hasNext()) {
return false;
}
char endDelimiter;
switch (scanner.peek()) {
case '"':
endDelimiter = '"';
break;
case '\'':
endDelimiter = '\'';
break;
case '(':
endDelimiter = ')';
break;
default:
return false;
}
scanner.next();
if (!scanLinkTitleContent(scanner, endDelimiter)) {
return false;
}
if (!scanner.hasNext()) {
return false;
}
scanner.next();
return true;
}
public static boolean scanLinkTitleContent(Scanner scanner, char endDelimiter) {<FILL_FUNCTION_BODY>}
// spec: a nonempty sequence of characters that does not start with <, does not include ASCII space or control
// characters, and includes parentheses only if (a) they are backslash-escaped or (b) they are part of a balanced
// pair of unescaped parentheses
private static boolean scanLinkDestinationWithBalancedParens(Scanner scanner) {
int parens = 0;
boolean empty = true;
while (scanner.hasNext()) {
char c = scanner.peek();
switch (c) {
case ' ':
return !empty;
case '\\':
scanner.next();
if (isEscapable(scanner.peek())) {
scanner.next();
}
break;
case '(':
parens++;
// Limit to 32 nested parens for pathological cases
if (parens > 32) {
return false;
}
scanner.next();
break;
case ')':
if (parens == 0) {
return true;
} else {
parens--;
}
scanner.next();
break;
default:
// or control character
if (Character.isISOControl(c)) {
return !empty;
}
scanner.next();
break;
}
empty = false;
}
return true;
}
private static boolean isEscapable(char c) {
switch (c) {
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '@':
case '[':
case '\\':
case ']':
case '^':
case '_':
case '`':
case '{':
case '|':
case '}':
case '~':
return true;
}
return false;
}
}
|
while (scanner.hasNext()) {
char c = scanner.peek();
if (c == '\\') {
scanner.next();
if (isEscapable(scanner.peek())) {
scanner.next();
}
} else if (c == endDelimiter) {
return true;
} else if (endDelimiter == ')' && c == '(') {
// unescaped '(' in title within parens is invalid
return false;
} else {
scanner.next();
}
}
return true;
| 1,265
| 150
| 1,415
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/internal/util/Parsing.java
|
Parsing
|
columnsToNextTabStop
|
class Parsing {
public static int CODE_BLOCK_INDENT = 4;
public static int columnsToNextTabStop(int column) {<FILL_FUNCTION_BODY>}
}
|
// Tab stop is 4
return 4 - (column % 4);
| 52
| 23
| 75
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/AbstractVisitor.java
|
AbstractVisitor
|
visitChildren
|
class AbstractVisitor implements Visitor {
@Override
public void visit(BlockQuote blockQuote) {
visitChildren(blockQuote);
}
@Override
public void visit(BulletList bulletList) {
visitChildren(bulletList);
}
@Override
public void visit(Code code) {
visitChildren(code);
}
@Override
public void visit(Document document) {
visitChildren(document);
}
@Override
public void visit(Emphasis emphasis) {
visitChildren(emphasis);
}
@Override
public void visit(FencedCodeBlock fencedCodeBlock) {
visitChildren(fencedCodeBlock);
}
@Override
public void visit(HardLineBreak hardLineBreak) {
visitChildren(hardLineBreak);
}
@Override
public void visit(Heading heading) {
visitChildren(heading);
}
@Override
public void visit(ThematicBreak thematicBreak) {
visitChildren(thematicBreak);
}
@Override
public void visit(HtmlInline htmlInline) {
visitChildren(htmlInline);
}
@Override
public void visit(HtmlBlock htmlBlock) {
visitChildren(htmlBlock);
}
@Override
public void visit(Image image) {
visitChildren(image);
}
@Override
public void visit(IndentedCodeBlock indentedCodeBlock) {
visitChildren(indentedCodeBlock);
}
@Override
public void visit(Link link) {
visitChildren(link);
}
@Override
public void visit(ListItem listItem) {
visitChildren(listItem);
}
@Override
public void visit(OrderedList orderedList) {
visitChildren(orderedList);
}
@Override
public void visit(Paragraph paragraph) {
visitChildren(paragraph);
}
@Override
public void visit(SoftLineBreak softLineBreak) {
visitChildren(softLineBreak);
}
@Override
public void visit(StrongEmphasis strongEmphasis) {
visitChildren(strongEmphasis);
}
@Override
public void visit(Text text) {
visitChildren(text);
}
@Override
public void visit(LinkReferenceDefinition linkReferenceDefinition) {
visitChildren(linkReferenceDefinition);
}
@Override
public void visit(CustomBlock customBlock) {
visitChildren(customBlock);
}
@Override
public void visit(CustomNode customNode) {
visitChildren(customNode);
}
/**
* Visit the child nodes.
*
* @param parent the parent node whose children should be visited
*/
protected void visitChildren(Node parent) {<FILL_FUNCTION_BODY>}
}
|
Node node = parent.getFirstChild();
while (node != null) {
// A subclass of this visitor might modify the node, resulting in getNext returning a different node or no
// node after visiting it. So get the next node before visiting.
Node next = node.getNext();
node.accept(this);
node = next;
}
| 731
| 91
| 822
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/Block.java
|
Block
|
setParent
|
class Block extends Node {
public Block getParent() {
return (Block) super.getParent();
}
@Override
protected void setParent(Node parent) {<FILL_FUNCTION_BODY>}
}
|
if (!(parent instanceof Block)) {
throw new IllegalArgumentException("Parent of block must also be block (can not be inline)");
}
super.setParent(parent);
| 59
| 46
| 105
|
<methods>public non-sealed void <init>() ,public abstract void accept(org.commonmark.node.Visitor) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public void appendChild(org.commonmark.node.Node) ,public org.commonmark.node.Node getFirstChild() ,public org.commonmark.node.Node getLastChild() ,public org.commonmark.node.Node getNext() ,public org.commonmark.node.Node getParent() ,public org.commonmark.node.Node getPrevious() ,public List<org.commonmark.node.SourceSpan> getSourceSpans() ,public void insertAfter(org.commonmark.node.Node) ,public void insertBefore(org.commonmark.node.Node) ,public void prependChild(org.commonmark.node.Node) ,public void setSourceSpans(List<org.commonmark.node.SourceSpan>) ,public java.lang.String toString() ,public void unlink() <variables>private org.commonmark.node.Node firstChild,private org.commonmark.node.Node lastChild,private org.commonmark.node.Node next,private org.commonmark.node.Node parent,private org.commonmark.node.Node prev,private List<org.commonmark.node.SourceSpan> sourceSpans
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/FencedCodeBlock.java
|
FencedCodeBlock
|
setClosingFenceLength
|
class FencedCodeBlock extends Block {
private String fenceCharacter;
private Integer openingFenceLength;
private Integer closingFenceLength;
private int fenceIndent;
private String info;
private String literal;
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
/**
* @return the fence character that was used, e.g. {@code `} or {@code ~}, if available, or null otherwise
*/
public String getFenceCharacter() {
return fenceCharacter;
}
public void setFenceCharacter(String fenceCharacter) {
this.fenceCharacter = fenceCharacter;
}
/**
* @return the length of the opening fence (how many of {{@link #getFenceCharacter()}} were used to start the code
* block) if available, or null otherwise
*/
public Integer getOpeningFenceLength() {
return openingFenceLength;
}
public void setOpeningFenceLength(Integer openingFenceLength) {
if (openingFenceLength != null && openingFenceLength < 3) {
throw new IllegalArgumentException("openingFenceLength needs to be >= 3");
}
checkFenceLengths(openingFenceLength, closingFenceLength);
this.openingFenceLength = openingFenceLength;
}
/**
* @return the length of the closing fence (how many of {@link #getFenceCharacter()} were used to end the code
* block) if available, or null otherwise
*/
public Integer getClosingFenceLength() {
return closingFenceLength;
}
public void setClosingFenceLength(Integer closingFenceLength) {<FILL_FUNCTION_BODY>}
public int getFenceIndent() {
return fenceIndent;
}
public void setFenceIndent(int fenceIndent) {
this.fenceIndent = fenceIndent;
}
/**
* @see <a href="http://spec.commonmark.org/0.18/#info-string">CommonMark spec</a>
*/
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getLiteral() {
return literal;
}
public void setLiteral(String literal) {
this.literal = literal;
}
/**
* @deprecated use {@link #getFenceCharacter()} instead
*/
@Deprecated
public char getFenceChar() {
return fenceCharacter != null && !fenceCharacter.isEmpty() ? fenceCharacter.charAt(0) : '\0';
}
/**
* @deprecated use {@link #setFenceCharacter} instead
*/
@Deprecated
public void setFenceChar(char fenceChar) {
this.fenceCharacter = fenceChar != '\0' ? String.valueOf(fenceChar) : null;
}
/**
* @deprecated use {@link #getOpeningFenceLength} instead
*/
@Deprecated
public int getFenceLength() {
return openingFenceLength != null ? openingFenceLength : 0;
}
/**
* @deprecated use {@link #setOpeningFenceLength} instead
*/
@Deprecated
public void setFenceLength(int fenceLength) {
this.openingFenceLength = fenceLength != 0 ? fenceLength : null;
}
private static void checkFenceLengths(Integer openingFenceLength, Integer closingFenceLength) {
if (openingFenceLength != null && closingFenceLength != null) {
if (closingFenceLength < openingFenceLength) {
throw new IllegalArgumentException("fence lengths required to be: closingFenceLength >= openingFenceLength");
}
}
}
}
|
if (closingFenceLength != null && closingFenceLength < 3) {
throw new IllegalArgumentException("closingFenceLength needs to be >= 3");
}
checkFenceLengths(openingFenceLength, closingFenceLength);
this.closingFenceLength = closingFenceLength;
| 989
| 79
| 1,068
|
<methods>public non-sealed void <init>() ,public org.commonmark.node.Block getParent() <variables>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/Image.java
|
Image
|
toStringAttributes
|
class Image extends Node {
private String destination;
private String title;
public Image() {
}
public Image(String destination, String title) {
this.destination = destination;
this.title = title;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
protected String toStringAttributes() {<FILL_FUNCTION_BODY>}
}
|
return "destination=" + destination + ", title=" + title;
| 201
| 21
| 222
|
<methods>public non-sealed void <init>() ,public abstract void accept(org.commonmark.node.Visitor) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public void appendChild(org.commonmark.node.Node) ,public org.commonmark.node.Node getFirstChild() ,public org.commonmark.node.Node getLastChild() ,public org.commonmark.node.Node getNext() ,public org.commonmark.node.Node getParent() ,public org.commonmark.node.Node getPrevious() ,public List<org.commonmark.node.SourceSpan> getSourceSpans() ,public void insertAfter(org.commonmark.node.Node) ,public void insertBefore(org.commonmark.node.Node) ,public void prependChild(org.commonmark.node.Node) ,public void setSourceSpans(List<org.commonmark.node.SourceSpan>) ,public java.lang.String toString() ,public void unlink() <variables>private org.commonmark.node.Node firstChild,private org.commonmark.node.Node lastChild,private org.commonmark.node.Node next,private org.commonmark.node.Node parent,private org.commonmark.node.Node prev,private List<org.commonmark.node.SourceSpan> sourceSpans
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/Link.java
|
Link
|
toStringAttributes
|
class Link extends Node {
private String destination;
private String title;
public Link() {
}
public Link(String destination, String title) {
this.destination = destination;
this.title = title;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
protected String toStringAttributes() {<FILL_FUNCTION_BODY>}
}
|
return "destination=" + destination + ", title=" + title;
| 201
| 21
| 222
|
<methods>public non-sealed void <init>() ,public abstract void accept(org.commonmark.node.Visitor) ,public void addSourceSpan(org.commonmark.node.SourceSpan) ,public void appendChild(org.commonmark.node.Node) ,public org.commonmark.node.Node getFirstChild() ,public org.commonmark.node.Node getLastChild() ,public org.commonmark.node.Node getNext() ,public org.commonmark.node.Node getParent() ,public org.commonmark.node.Node getPrevious() ,public List<org.commonmark.node.SourceSpan> getSourceSpans() ,public void insertAfter(org.commonmark.node.Node) ,public void insertBefore(org.commonmark.node.Node) ,public void prependChild(org.commonmark.node.Node) ,public void setSourceSpans(List<org.commonmark.node.SourceSpan>) ,public java.lang.String toString() ,public void unlink() <variables>private org.commonmark.node.Node firstChild,private org.commonmark.node.Node lastChild,private org.commonmark.node.Node next,private org.commonmark.node.Node parent,private org.commonmark.node.Node prev,private List<org.commonmark.node.SourceSpan> sourceSpans
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/Node.java
|
Node
|
unlink
|
class Node {
private Node parent = null;
private Node firstChild = null;
private Node lastChild = null;
private Node prev = null;
private Node next = null;
private List<SourceSpan> sourceSpans = null;
public abstract void accept(Visitor visitor);
public Node getNext() {
return next;
}
public Node getPrevious() {
return prev;
}
public Node getFirstChild() {
return firstChild;
}
public Node getLastChild() {
return lastChild;
}
public Node getParent() {
return parent;
}
protected void setParent(Node parent) {
this.parent = parent;
}
public void appendChild(Node child) {
child.unlink();
child.setParent(this);
if (this.lastChild != null) {
this.lastChild.next = child;
child.prev = this.lastChild;
this.lastChild = child;
} else {
this.firstChild = child;
this.lastChild = child;
}
}
public void prependChild(Node child) {
child.unlink();
child.setParent(this);
if (this.firstChild != null) {
this.firstChild.prev = child;
child.next = this.firstChild;
this.firstChild = child;
} else {
this.firstChild = child;
this.lastChild = child;
}
}
public void unlink() {<FILL_FUNCTION_BODY>}
public void insertAfter(Node sibling) {
sibling.unlink();
sibling.next = this.next;
if (sibling.next != null) {
sibling.next.prev = sibling;
}
sibling.prev = this;
this.next = sibling;
sibling.parent = this.parent;
if (sibling.next == null) {
sibling.parent.lastChild = sibling;
}
}
public void insertBefore(Node sibling) {
sibling.unlink();
sibling.prev = this.prev;
if (sibling.prev != null) {
sibling.prev.next = sibling;
}
sibling.next = this;
this.prev = sibling;
sibling.parent = this.parent;
if (sibling.prev == null) {
sibling.parent.firstChild = sibling;
}
}
/**
* @return the source spans of this node if included by the parser, an empty list otherwise
* @since 0.16.0
*/
public List<SourceSpan> getSourceSpans() {
return sourceSpans != null ? Collections.unmodifiableList(sourceSpans) : Collections.<SourceSpan>emptyList();
}
/**
* Replace the current source spans with the provided list.
*
* @param sourceSpans the new source spans to set
* @since 0.16.0
*/
public void setSourceSpans(List<SourceSpan> sourceSpans) {
if (sourceSpans.isEmpty()) {
this.sourceSpans = null;
} else {
this.sourceSpans = new ArrayList<>(sourceSpans);
}
}
/**
* Add a source span to the end of the list.
*
* @param sourceSpan the source span to add
* @since 0.16.0
*/
public void addSourceSpan(SourceSpan sourceSpan) {
if (sourceSpans == null) {
this.sourceSpans = new ArrayList<>();
}
this.sourceSpans.add(sourceSpan);
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" + toStringAttributes() + "}";
}
protected String toStringAttributes() {
return "";
}
}
|
if (this.prev != null) {
this.prev.next = this.next;
} else if (this.parent != null) {
this.parent.firstChild = this.next;
}
if (this.next != null) {
this.next.prev = this.prev;
} else if (this.parent != null) {
this.parent.lastChild = this.prev;
}
this.parent = null;
this.next = null;
this.prev = null;
| 1,025
| 135
| 1,160
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/Nodes.java
|
NodeIterator
|
next
|
class NodeIterator implements Iterator<Node> {
private Node node;
private final Node end;
private NodeIterator(Node first, Node end) {
node = first;
this.end = end;
}
@Override
public boolean hasNext() {
return node != null && node != end;
}
@Override
public Node next() {<FILL_FUNCTION_BODY>}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
|
Node result = node;
node = node.getNext();
return result;
| 138
| 24
| 162
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/SourceSpan.java
|
SourceSpan
|
equals
|
class SourceSpan {
private final int lineIndex;
private final int columnIndex;
private final int length;
public static SourceSpan of(int lineIndex, int columnIndex, int length) {
return new SourceSpan(lineIndex, columnIndex, length);
}
private SourceSpan(int lineIndex, int columnIndex, int length) {
this.lineIndex = lineIndex;
this.columnIndex = columnIndex;
this.length = length;
}
/**
* @return 0-based index of line in source
*/
public int getLineIndex() {
return lineIndex;
}
/**
* @return 0-based index of column (character on line) in source
*/
public int getColumnIndex() {
return columnIndex;
}
/**
* @return length of the span in characters
*/
public int getLength() {
return length;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(lineIndex, columnIndex, length);
}
@Override
public String toString() {
return "SourceSpan{" +
"line=" + lineIndex +
", column=" + columnIndex +
", length=" + length +
"}";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SourceSpan that = (SourceSpan) o;
return lineIndex == that.lineIndex &&
columnIndex == that.columnIndex &&
length == that.length;
| 354
| 88
| 442
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/node/SourceSpans.java
|
SourceSpans
|
addAll
|
class SourceSpans {
private List<SourceSpan> sourceSpans;
public static SourceSpans empty() {
return new SourceSpans();
}
public List<SourceSpan> getSourceSpans() {
return sourceSpans != null ? sourceSpans : Collections.<SourceSpan>emptyList();
}
public void addAllFrom(Iterable<? extends Node> nodes) {
for (Node node : nodes) {
addAll(node.getSourceSpans());
}
}
public void addAll(List<SourceSpan> other) {<FILL_FUNCTION_BODY>}
}
|
if (other.isEmpty()) {
return;
}
if (sourceSpans == null) {
sourceSpans = new ArrayList<>();
}
if (sourceSpans.isEmpty()) {
sourceSpans.addAll(other);
} else {
int lastIndex = sourceSpans.size() - 1;
SourceSpan a = sourceSpans.get(lastIndex);
SourceSpan b = other.get(0);
if (a.getLineIndex() == b.getLineIndex() && a.getColumnIndex() + a.getLength() == b.getColumnIndex()) {
sourceSpans.set(lastIndex, SourceSpan.of(a.getLineIndex(), a.getColumnIndex(), a.getLength() + b.getLength()));
sourceSpans.addAll(other.subList(1, other.size()));
} else {
sourceSpans.addAll(other);
}
}
| 160
| 234
| 394
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/parser/SourceLine.java
|
SourceLine
|
substring
|
class SourceLine {
private final CharSequence content;
private final SourceSpan sourceSpan;
public static SourceLine of(CharSequence content, SourceSpan sourceSpan) {
return new SourceLine(content, sourceSpan);
}
private SourceLine(CharSequence content, SourceSpan sourceSpan) {
if (content == null) {
throw new NullPointerException("content must not be null");
}
this.content = content;
this.sourceSpan = sourceSpan;
}
public CharSequence getContent() {
return content;
}
public SourceSpan getSourceSpan() {
return sourceSpan;
}
public SourceLine substring(int beginIndex, int endIndex) {<FILL_FUNCTION_BODY>}
}
|
CharSequence newContent = content.subSequence(beginIndex, endIndex);
SourceSpan newSourceSpan = null;
if (sourceSpan != null) {
int columnIndex = sourceSpan.getColumnIndex() + beginIndex;
int length = endIndex - beginIndex;
if (length != 0) {
newSourceSpan = SourceSpan.of(sourceSpan.getLineIndex(), columnIndex, length);
}
}
return SourceLine.of(newContent, newSourceSpan);
| 191
| 124
| 315
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/parser/SourceLines.java
|
SourceLines
|
getSourceSpans
|
class SourceLines {
private final List<SourceLine> lines = new ArrayList<>();
public static SourceLines empty() {
return new SourceLines();
}
public static SourceLines of(SourceLine sourceLine) {
SourceLines sourceLines = new SourceLines();
sourceLines.addLine(sourceLine);
return sourceLines;
}
public static SourceLines of(List<SourceLine> sourceLines) {
SourceLines result = new SourceLines();
result.lines.addAll(sourceLines);
return result;
}
public void addLine(SourceLine sourceLine) {
lines.add(sourceLine);
}
public List<SourceLine> getLines() {
return lines;
}
public boolean isEmpty() {
return lines.isEmpty();
}
public String getContent() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.size(); i++) {
if (i != 0) {
sb.append('\n');
}
sb.append(lines.get(i).getContent());
}
return sb.toString();
}
public List<SourceSpan> getSourceSpans() {<FILL_FUNCTION_BODY>}
}
|
List<SourceSpan> sourceSpans = new ArrayList<>();
for (SourceLine line : lines) {
SourceSpan sourceSpan = line.getSourceSpan();
if (sourceSpan != null) {
sourceSpans.add(sourceSpan);
}
}
return sourceSpans;
| 333
| 77
| 410
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/renderer/html/DefaultUrlSanitizer.java
|
DefaultUrlSanitizer
|
sanitizeLinkUrl
|
class DefaultUrlSanitizer implements UrlSanitizer {
private Set<String> protocols;
public DefaultUrlSanitizer() {
this(Arrays.asList("http", "https", "mailto"));
}
public DefaultUrlSanitizer(Collection<String> protocols) {
this.protocols = new HashSet<>(protocols);
}
@Override
public String sanitizeLinkUrl(String url) {<FILL_FUNCTION_BODY>}
@Override
public String sanitizeImageUrl(String url) {
return sanitizeLinkUrl(url);
}
private String stripHtmlSpaces(String s) {
int i = 0, n = s.length();
for (; n > i; --n) {
if (!isHtmlSpace(s.charAt(n - 1))) {
break;
}
}
for (; i < n; ++i) {
if (!isHtmlSpace(s.charAt(i))) {
break;
}
}
if (i == 0 && n == s.length()) {
return s;
}
return s.substring(i, n);
}
private boolean isHtmlSpace(int ch) {
switch (ch) {
case ' ':
case '\t':
case '\n':
case '\u000c':
case '\r':
return true;
default:
return false;
}
}
}
|
url = stripHtmlSpaces(url);
protocol_loop:
for (int i = 0, n = url.length(); i < n; ++i) {
switch (url.charAt(i)) {
case '/':
case '#':
case '?': // No protocol.
break protocol_loop;
case ':':
String protocol = url.substring(0, i).toLowerCase();
if (!protocols.contains(protocol)) {
return "";
}
break protocol_loop;
}
}
return url;
| 378
| 144
| 522
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/renderer/html/HtmlRenderer.java
|
Builder
|
nodeRendererFactory
|
class Builder {
private String softbreak = "\n";
private boolean escapeHtml = false;
private boolean sanitizeUrls = false;
private UrlSanitizer urlSanitizer = new DefaultUrlSanitizer();
private boolean percentEncodeUrls = false;
private List<AttributeProviderFactory> attributeProviderFactories = new ArrayList<>();
private List<HtmlNodeRendererFactory> nodeRendererFactories = new ArrayList<>();
/**
* @return the configured {@link HtmlRenderer}
*/
public HtmlRenderer build() {
return new HtmlRenderer(this);
}
/**
* The HTML to use for rendering a softbreak, defaults to {@code "\n"} (meaning the rendered result doesn't have
* a line break).
* <p>
* Set it to {@code "<br>"} (or {@code "<br />"} to make them hard breaks.
* <p>
* Set it to {@code " "} to ignore line wrapping in the source.
*
* @param softbreak HTML for softbreak
* @return {@code this}
*/
public Builder softbreak(String softbreak) {
this.softbreak = softbreak;
return this;
}
/**
* Whether {@link HtmlInline} and {@link HtmlBlock} should be escaped, defaults to {@code false}.
* <p>
* Note that {@link HtmlInline} is only a tag itself, not the text between an opening tag and a closing tag. So
* markup in the text will be parsed as normal and is not affected by this option.
*
* @param escapeHtml true for escaping, false for preserving raw HTML
* @return {@code this}
*/
public Builder escapeHtml(boolean escapeHtml) {
this.escapeHtml = escapeHtml;
return this;
}
/**
* Whether {@link Image} src and {@link Link} href should be sanitized, defaults to {@code false}.
*
* @param sanitizeUrls true for sanitization, false for preserving raw attribute
* @return {@code this}
* @since 0.14.0
*/
public Builder sanitizeUrls(boolean sanitizeUrls) {
this.sanitizeUrls = sanitizeUrls;
return this;
}
/**
* {@link UrlSanitizer} used to filter URL's if {@link #sanitizeUrls} is true.
*
* @param urlSanitizer Filterer used to filter {@link Image} src and {@link Link}.
* @return {@code this}
* @since 0.14.0
*/
public Builder urlSanitizer(UrlSanitizer urlSanitizer) {
this.urlSanitizer = urlSanitizer;
return this;
}
/**
* Whether URLs of link or images should be percent-encoded, defaults to {@code false}.
* <p>
* If enabled, the following is done:
* <ul>
* <li>Existing percent-encoded parts are preserved (e.g. "%20" is kept as "%20")</li>
* <li>Reserved characters such as "/" are preserved, except for "[" and "]" (see encodeURI in JS)</li>
* <li>Unreserved characters such as "a" are preserved</li>
* <li>Other characters such umlauts are percent-encoded</li>
* </ul>
*
* @param percentEncodeUrls true to percent-encode, false for leaving as-is
* @return {@code this}
*/
public Builder percentEncodeUrls(boolean percentEncodeUrls) {
this.percentEncodeUrls = percentEncodeUrls;
return this;
}
/**
* Add a factory for an attribute provider for adding/changing HTML attributes to the rendered tags.
*
* @param attributeProviderFactory the attribute provider factory to add
* @return {@code this}
*/
public Builder attributeProviderFactory(AttributeProviderFactory attributeProviderFactory) {
if (attributeProviderFactory == null) {
throw new NullPointerException("attributeProviderFactory must not be null");
}
this.attributeProviderFactories.add(attributeProviderFactory);
return this;
}
/**
* Add a factory for instantiating a node renderer (done when rendering). This allows to override the rendering
* of node types or define rendering for custom node types.
* <p>
* If multiple node renderers for the same node type are created, the one from the factory that was added first
* "wins". (This is how the rendering for core node types can be overridden; the default rendering comes last.)
*
* @param nodeRendererFactory the factory for creating a node renderer
* @return {@code this}
*/
public Builder nodeRendererFactory(HtmlNodeRendererFactory nodeRendererFactory) {<FILL_FUNCTION_BODY>}
/**
* @param extensions extensions to use on this HTML renderer
* @return {@code this}
*/
public Builder extensions(Iterable<? extends Extension> extensions) {
if (extensions == null) {
throw new NullPointerException("extensions must not be null");
}
for (Extension extension : extensions) {
if (extension instanceof HtmlRendererExtension) {
HtmlRendererExtension htmlRendererExtension = (HtmlRendererExtension) extension;
htmlRendererExtension.extend(this);
}
}
return this;
}
}
|
if (nodeRendererFactory == null) {
throw new NullPointerException("nodeRendererFactory must not be null");
}
this.nodeRendererFactories.add(nodeRendererFactory);
return this;
| 1,377
| 53
| 1,430
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/renderer/html/HtmlWriter.java
|
HtmlWriter
|
tag
|
class HtmlWriter {
private static final Map<String, String> NO_ATTRIBUTES = Collections.emptyMap();
private final Appendable buffer;
private char lastChar = 0;
public HtmlWriter(Appendable out) {
if (out == null) {
throw new NullPointerException("out must not be null");
}
this.buffer = out;
}
public void raw(String s) {
append(s);
}
public void text(String text) {
append(Escaping.escapeHtml(text));
}
public void tag(String name) {
tag(name, NO_ATTRIBUTES);
}
public void tag(String name, Map<String, String> attrs) {
tag(name, attrs, false);
}
public void tag(String name, Map<String, String> attrs, boolean voidElement) {<FILL_FUNCTION_BODY>}
public void line() {
if (lastChar != 0 && lastChar != '\n') {
append("\n");
}
}
protected void append(String s) {
try {
buffer.append(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
int length = s.length();
if (length != 0) {
lastChar = s.charAt(length - 1);
}
}
}
|
append("<");
append(name);
if (attrs != null && !attrs.isEmpty()) {
for (Map.Entry<String, String> attrib : attrs.entrySet()) {
append(" ");
append(Escaping.escapeHtml(attrib.getKey()));
append("=\"");
append(Escaping.escapeHtml(attrib.getValue()));
append("\"");
}
}
if (voidElement) {
append(" /");
}
append(">");
| 367
| 133
| 500
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/renderer/markdown/MarkdownRenderer.java
|
Builder
|
extensions
|
class Builder {
private final List<MarkdownNodeRendererFactory> nodeRendererFactories = new ArrayList<>();
/**
* @return the configured {@link MarkdownRenderer}
*/
public MarkdownRenderer build() {
return new MarkdownRenderer(this);
}
/**
* Add a factory for instantiating a node renderer (done when rendering). This allows to override the rendering
* of node types or define rendering for custom node types.
* <p>
* If multiple node renderers for the same node type are created, the one from the factory that was added first
* "wins". (This is how the rendering for core node types can be overridden; the default rendering comes last.)
*
* @param nodeRendererFactory the factory for creating a node renderer
* @return {@code this}
*/
public Builder nodeRendererFactory(MarkdownNodeRendererFactory nodeRendererFactory) {
this.nodeRendererFactories.add(nodeRendererFactory);
return this;
}
/**
* @param extensions extensions to use on this renderer
* @return {@code this}
*/
public Builder extensions(Iterable<? extends Extension> extensions) {<FILL_FUNCTION_BODY>}
}
|
for (Extension extension : extensions) {
if (extension instanceof MarkdownRendererExtension) {
MarkdownRendererExtension markdownRendererExtension = (MarkdownRendererExtension) extension;
markdownRendererExtension.extend(this);
}
}
return this;
| 303
| 66
| 369
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/renderer/markdown/MarkdownWriter.java
|
MarkdownWriter
|
block
|
class MarkdownWriter {
private final Appendable buffer;
private int blockSeparator = 0;
private char lastChar;
private boolean atLineStart = true;
// Stacks of settings that affect various rendering behaviors. The common pattern here is that callers use "push" to
// change a setting, render some nodes, and then "pop" the setting off the stack again to restore previous state.
private final LinkedList<String> prefixes = new LinkedList<>();
private final LinkedList<Boolean> tight = new LinkedList<>();
private final LinkedList<CharMatcher> rawEscapes = new LinkedList<>();
public MarkdownWriter(Appendable out) {
buffer = out;
}
/**
* Write the supplied string (raw/unescaped except if {@link #pushRawEscape} was used).
*/
public void raw(String s) {
flushBlockSeparator();
write(s, null);
}
/**
* Write the supplied character (raw/unescaped except if {@link #pushRawEscape} was used).
*/
public void raw(char c) {
flushBlockSeparator();
write(c);
}
/**
* Write the supplied string with escaping.
*
* @param s the string to write
* @param escape which characters to escape
*/
public void text(String s, CharMatcher escape) {
if (s.isEmpty()) {
return;
}
flushBlockSeparator();
write(s, escape);
lastChar = s.charAt(s.length() - 1);
atLineStart = false;
}
/**
* Write a newline (line terminator).
*/
public void line() {
write('\n');
writePrefixes();
atLineStart = true;
}
/**
* Enqueue a block separator to be written before the next text is written. Block separators are not written
* straight away because if there are no more blocks to write we don't want a separator (at the end of the document).
*/
public void block() {<FILL_FUNCTION_BODY>}
/**
* Push a prefix onto the top of the stack. All prefixes are written at the beginning of each line, until the
* prefix is popped again.
*
* @param prefix the raw prefix string
*/
public void pushPrefix(String prefix) {
prefixes.addLast(prefix);
}
/**
* Write a prefix.
*
* @param prefix the raw prefix string to write
*/
public void writePrefix(String prefix) {
boolean tmp = atLineStart;
raw(prefix);
atLineStart = tmp;
}
/**
* Remove the last prefix from the top of the stack.
*/
public void popPrefix() {
prefixes.removeLast();
}
/**
* Change whether blocks are tight or loose. Loose is the default where blocks are separated by a blank line. Tight
* is where blocks are not separated by a blank line. Tight blocks are used in lists, if there are no blank lines
* within the list.
* <p>
* Note that changing this does not affect block separators that have already been enqueued with {@link #block()},
* only future ones.
*/
public void pushTight(boolean tight) {
this.tight.addLast(tight);
}
/**
* Remove the last "tight" setting from the top of the stack.
*/
public void popTight() {
this.tight.removeLast();
}
/**
* Escape the characters matching the supplied matcher, in all text (text and raw). This might be useful to
* extensions that add another layer of syntax, e.g. the tables extension that uses `|` to separate cells and needs
* all `|` characters to be escaped (even in code spans).
*
* @param rawEscape the characters to escape in raw text
*/
public void pushRawEscape(CharMatcher rawEscape) {
rawEscapes.add(rawEscape);
}
/**
* Remove the last raw escape from the top of the stack.
*/
public void popRawEscape() {
rawEscapes.removeLast();
}
/**
* @return the last character that was written
*/
public char getLastChar() {
return lastChar;
}
/**
* @return whether we're at the line start (not counting any prefixes), i.e. after a {@link #line} or {@link #block}.
*/
public boolean isAtLineStart() {
return atLineStart;
}
private void write(String s, CharMatcher escape) {
try {
if (rawEscapes.isEmpty() && escape == null) {
// Normal fast path
buffer.append(s);
} else {
for (int i = 0; i < s.length(); i++) {
append(s.charAt(i), escape);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
int length = s.length();
if (length != 0) {
lastChar = s.charAt(length - 1);
}
atLineStart = false;
}
private void write(char c) {
try {
append(c, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
lastChar = c;
atLineStart = false;
}
private void writePrefixes() {
if (!prefixes.isEmpty()) {
for (String prefix : prefixes) {
write(prefix, null);
}
}
}
/**
* If a block separator has been enqueued with {@link #block()} but not yet written, write it now.
*/
private void flushBlockSeparator() {
if (blockSeparator != 0) {
write('\n');
writePrefixes();
if (blockSeparator > 1) {
write('\n');
writePrefixes();
}
blockSeparator = 0;
}
}
private void append(char c, CharMatcher escape) throws IOException {
if (needsEscaping(c, escape)) {
if (c == '\n') {
// Can't escape this with \, use numeric character reference
buffer.append(" ");
} else {
buffer.append('\\');
buffer.append(c);
}
} else {
buffer.append(c);
}
}
private boolean isTight() {
return !tight.isEmpty() && tight.getLast();
}
private boolean needsEscaping(char c, CharMatcher escape) {
return (escape != null && escape.matches(c)) || rawNeedsEscaping(c);
}
private boolean rawNeedsEscaping(char c) {
for (CharMatcher rawEscape : rawEscapes) {
if (rawEscape.matches(c)) {
return true;
}
}
return false;
}
}
|
// Remember whether this should be a tight or loose separator now because tight could get changed in between
// this and the next flush.
blockSeparator = isTight() ? 1 : 2;
atLineStart = true;
| 1,823
| 59
| 1,882
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/renderer/text/TextContentRenderer.java
|
Builder
|
extensions
|
class Builder {
private boolean stripNewlines = false;
private List<TextContentNodeRendererFactory> nodeRendererFactories = new ArrayList<>();
/**
* @return the configured {@link TextContentRenderer}
*/
public TextContentRenderer build() {
return new TextContentRenderer(this);
}
/**
* Set the value of flag for stripping new lines.
*
* @param stripNewlines true for stripping new lines and render text as "single line",
* false for keeping all line breaks
* @return {@code this}
*/
public Builder stripNewlines(boolean stripNewlines) {
this.stripNewlines = stripNewlines;
return this;
}
/**
* Add a factory for instantiating a node renderer (done when rendering). This allows to override the rendering
* of node types or define rendering for custom node types.
* <p>
* If multiple node renderers for the same node type are created, the one from the factory that was added first
* "wins". (This is how the rendering for core node types can be overridden; the default rendering comes last.)
*
* @param nodeRendererFactory the factory for creating a node renderer
* @return {@code this}
*/
public Builder nodeRendererFactory(TextContentNodeRendererFactory nodeRendererFactory) {
this.nodeRendererFactories.add(nodeRendererFactory);
return this;
}
/**
* @param extensions extensions to use on this text content renderer
* @return {@code this}
*/
public Builder extensions(Iterable<? extends Extension> extensions) {<FILL_FUNCTION_BODY>}
}
|
for (Extension extension : extensions) {
if (extension instanceof TextContentRenderer.TextContentRendererExtension) {
TextContentRenderer.TextContentRendererExtension textContentRendererExtension =
(TextContentRenderer.TextContentRendererExtension) extension;
textContentRendererExtension.extend(this);
}
}
return this;
| 413
| 80
| 493
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/renderer/text/TextContentWriter.java
|
TextContentWriter
|
append
|
class TextContentWriter {
private final Appendable buffer;
private char lastChar;
public TextContentWriter(Appendable out) {
buffer = out;
}
public void whitespace() {
if (lastChar != 0 && lastChar != ' ') {
append(' ');
}
}
public void colon() {
if (lastChar != 0 && lastChar != ':') {
append(':');
}
}
public void line() {
if (lastChar != 0 && lastChar != '\n') {
append('\n');
}
}
public void writeStripped(String s) {
append(s.replaceAll("[\\r\\n\\s]+", " "));
}
public void write(String s) {
append(s);
}
public void write(char c) {
append(c);
}
private void append(String s) {<FILL_FUNCTION_BODY>}
private void append(char c) {
try {
buffer.append(c);
} catch (IOException e) {
throw new RuntimeException(e);
}
lastChar = c;
}
}
|
try {
buffer.append(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
int length = s.length();
if (length != 0) {
lastChar = s.charAt(length - 1);
}
| 320
| 74
| 394
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/text/AsciiMatcher.java
|
Builder
|
anyOf
|
class Builder {
private final BitSet set;
private Builder(BitSet set) {
this.set = set;
}
public Builder c(char c) {
if (c > 127) {
throw new IllegalArgumentException("Can only match ASCII characters");
}
set.set(c);
return this;
}
public Builder anyOf(String s) {
for (int i = 0; i < s.length(); i++) {
c(s.charAt(i));
}
return this;
}
public Builder anyOf(Set<Character> characters) {<FILL_FUNCTION_BODY>}
public Builder range(char from, char toInclusive) {
for (char c = from; c <= toInclusive; c++) {
c(c);
}
return this;
}
public AsciiMatcher build() {
return new AsciiMatcher(this);
}
}
|
for (Character c : characters) {
c(c);
}
return this;
| 251
| 27
| 278
|
<no_super_class>
|
commonmark_commonmark-java
|
commonmark-java/commonmark/src/main/java/org/commonmark/text/Characters.java
|
Characters
|
isPunctuationCodePoint
|
class Characters {
public static int find(char c, CharSequence s, int startIndex) {
int length = s.length();
for (int i = startIndex; i < length; i++) {
if (s.charAt(i) == c) {
return i;
}
}
return -1;
}
public static int findLineBreak(CharSequence s, int startIndex) {
int length = s.length();
for (int i = startIndex; i < length; i++) {
switch (s.charAt(i)) {
case '\n':
case '\r':
return i;
}
}
return -1;
}
/**
* @see <a href="https://spec.commonmark.org/0.31.2/#blank-line">blank line</a>
*/
public static boolean isBlank(CharSequence s) {
return skipSpaceTab(s, 0, s.length()) == s.length();
}
public static boolean hasNonSpace(CharSequence s) {
int length = s.length();
int skipped = skip(' ', s, 0, length);
return skipped != length;
}
public static boolean isLetter(CharSequence s, int index) {
int codePoint = Character.codePointAt(s, index);
return Character.isLetter(codePoint);
}
public static boolean isSpaceOrTab(CharSequence s, int index) {
if (index < s.length()) {
switch (s.charAt(index)) {
case ' ':
case '\t':
return true;
}
}
return false;
}
/**
* @see <a href="https://spec.commonmark.org/0.31.2/#unicode-punctuation-character">Unicode punctuation character</a>
*/
public static boolean isPunctuationCodePoint(int codePoint) {<FILL_FUNCTION_BODY>}
/**
* Check whether the provided code point is a Unicode whitespace character as defined in the spec.
*
* @see <a href="https://spec.commonmark.org/0.31.2/#unicode-whitespace-character">Unicode whitespace character</a>
*/
public static boolean isWhitespaceCodePoint(int codePoint) {
switch (codePoint) {
case ' ':
case '\t':
case '\n':
case '\f':
case '\r':
return true;
default:
return Character.getType(codePoint) == Character.SPACE_SEPARATOR;
}
}
public static int skip(char skip, CharSequence s, int startIndex, int endIndex) {
for (int i = startIndex; i < endIndex; i++) {
if (s.charAt(i) != skip) {
return i;
}
}
return endIndex;
}
public static int skipBackwards(char skip, CharSequence s, int startIndex, int lastIndex) {
for (int i = startIndex; i >= lastIndex; i--) {
if (s.charAt(i) != skip) {
return i;
}
}
return lastIndex - 1;
}
public static int skipSpaceTab(CharSequence s, int startIndex, int endIndex) {
for (int i = startIndex; i < endIndex; i++) {
switch (s.charAt(i)) {
case ' ':
case '\t':
break;
default:
return i;
}
}
return endIndex;
}
public static int skipSpaceTabBackwards(CharSequence s, int startIndex, int lastIndex) {
for (int i = startIndex; i >= lastIndex; i--) {
switch (s.charAt(i)) {
case ' ':
case '\t':
break;
default:
return i;
}
}
return lastIndex - 1;
}
}
|
switch (Character.getType(codePoint)) {
// General category "P" (punctuation)
case Character.DASH_PUNCTUATION:
case Character.START_PUNCTUATION:
case Character.END_PUNCTUATION:
case Character.CONNECTOR_PUNCTUATION:
case Character.OTHER_PUNCTUATION:
case Character.INITIAL_QUOTE_PUNCTUATION:
case Character.FINAL_QUOTE_PUNCTUATION:
// General category "S" (symbol)
case Character.MATH_SYMBOL:
case Character.CURRENCY_SYMBOL:
case Character.MODIFIER_SYMBOL:
case Character.OTHER_SYMBOL:
return true;
default:
switch (codePoint) {
case '$':
case '+':
case '<':
case '=':
case '>':
case '^':
case '`':
case '|':
case '~':
return true;
default:
return false;
}
}
| 1,039
| 290
| 1,329
|
<no_super_class>
|
crate_crate
|
crate/app/src/main/java/io/crate/bootstrap/CrateDB.java
|
CrateDB
|
execute
|
class CrateDB extends EnvironmentAwareCommand {
private final OptionSpecBuilder versionOption;
private CrateDB() {
super("starts CrateDB", "C", () -> { });
versionOption = parser.acceptsAll(Arrays.asList("V", "version"),
"Prints CrateDB version information and exits");
}
/**
* Main entry point for starting crate
*/
public static void main(final String[] args) throws Exception {
LogConfigurator.registerErrorListener();
try (CrateDB crate = new CrateDB()) {
int status = crate.main(args, Terminal.DEFAULT);
if (status != ExitCodes.OK) {
exit(status);
}
}
}
@Override
protected Environment createEnv(Map<String, String> cmdLineSettings) throws UserException {
// 1) Check that path.home is set on the command-line (mandatory)
String crateHomePath = cmdLineSettings.get("path.home");
if (crateHomePath == null) {
throw new IllegalArgumentException("Please set the environment variable CRATE_HOME or " +
"use -Cpath.home on the command-line.");
}
// 2) Remove path.conf from command-line settings but use it as a conf path if exists
// We need to remove it, because it was removed in ES6, but we want to keep the ability
// to set it as CLI argument and keep backwards compatibility.
String confPathCLI = cmdLineSettings.remove("path.conf");
final Path confPath;
if (confPathCLI != null) {
confPath = Paths.get(confPathCLI);
} else {
confPath = Paths.get(crateHomePath, "config");
}
return InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, cmdLineSettings, confPath, NodeNames::randomNodeName);
}
@Override
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Required method that's called by Apache Commons procrun when
* running as a service on Windows, when the service is stopped.
*
* http://commons.apache.org/proper/commons-daemon/procrun.html
*
* NOTE: If this method is renamed and/or moved, make sure to
* update crate.bat!
*/
static void close(String[] args) throws IOException {
BootstrapProxy.stop();
}
}
|
if (options.nonOptionArguments().isEmpty() == false) {
throw new UserException(ExitCodes.USAGE, "Positional arguments not allowed, found " + options.nonOptionArguments());
}
if (options.has(versionOption)) {
terminal.println("Version: " + Version.CURRENT
+ ", Build: " + Build.CURRENT.hashShort() + "/" + Build.CURRENT.timestamp()
+ ", JVM: " + JvmInfo.jvmInfo().version());
return;
}
try {
BootstrapProxy.init(env);
} catch (BootstrapException | RuntimeException e) {
// format exceptions to the console in a special way
// to avoid 2MB stacktraces from guice, etc.
throw new StartupExceptionProxy(e);
} catch (NodeValidationException e) {
throw new UserException(ExitCodes.CONFIG, e.getMessage());
}
| 647
| 231
| 878
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.lang.String, java.lang.Runnable) <variables>private final non-sealed OptionSpec<KeyValuePair> settingOption
|
crate_crate
|
crate/benchmarks/src/main/java/io/crate/analyze/PreExecutionBenchmark.java
|
PreExecutionBenchmark
|
setup
|
class PreExecutionBenchmark {
private Analyzer analyzer;
private Node node;
private Sessions sqlOperations;
private Planner planner;
private ClusterService clusterService;
private NodeContext nodeCtx;
@Setup
public void setup() throws Exception {<FILL_FUNCTION_BODY>}
@TearDown
public void teardown() throws Exception {
node.close();
}
@Benchmark
public Statement measure_parse_simple_select() throws Exception {
return SqlParser.createStatement("select name from users");
}
@Benchmark
public AnalyzedStatement measure_parse_and_analyze_simple_select() throws Exception {
String sql = "select name from users";
CoordinatorTxnCtx systemTransactionContext = CoordinatorTxnCtx.systemTransactionContext();
Analysis analysis = new Analysis(systemTransactionContext, ParamTypeHints.EMPTY, Cursors.EMPTY);
return analyzer.analyzedStatement(SqlParser.createStatement(sql), analysis);
}
@Benchmark
public Plan measure_parse_analyze_and_plan_simple_select() throws Exception {
String sql = "select name from users";
CoordinatorTxnCtx systemTransactionContext = CoordinatorTxnCtx.systemTransactionContext();
Analysis analysis = new Analysis(systemTransactionContext, ParamTypeHints.EMPTY, Cursors.EMPTY);
AnalyzedStatement analyzedStatement = analyzer.analyzedStatement(SqlParser.createStatement(sql), analysis);
var jobId = UUID.randomUUID();
var routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
var clusterState = clusterService.state();
var txnCtx = CoordinatorTxnCtx.systemTransactionContext();
var plannerContext = new PlannerContext(
clusterState,
routingProvider,
jobId,
txnCtx,
nodeCtx,
0,
null,
Cursors.EMPTY,
TransactionState.IDLE,
new PlanStats(nodeCtx, CoordinatorTxnCtx.systemTransactionContext(), new TableStats()),
planner::optimize
);
return planner.plan(analyzedStatement, plannerContext);
}
}
|
Path tempDir = Files.createTempDirectory("");
Settings settings = Settings.builder()
.put("path.home", tempDir.toAbsolutePath().toString())
.build();
Environment environment = new Environment(settings, tempDir);
node = new Node(
environment,
List.of(
Netty4Plugin.class
),
true
);
node.start();
Injector injector = node.injector();
sqlOperations = injector.getInstance(Sessions.class);
analyzer = injector.getInstance(Analyzer.class);
planner = injector.getInstance(Planner.class);
clusterService = injector.getInstance(ClusterService.class);
nodeCtx = injector.getInstance(NodeContext.class);
String statement = "create table users (id int primary key, name string, date timestamp, text string index using fulltext)";
var resultReceiver = new BaseResultReceiver();
try (Session session = sqlOperations.newSystemSession()) {
session.quickExec(statement, resultReceiver, Row.EMPTY);
}
resultReceiver.completionFuture().get(5, TimeUnit.SECONDS);
| 583
| 295
| 878
|
<no_super_class>
|
crate_crate
|
crate/benchmarks/src/main/java/io/crate/common/StringUtilsBenchmark.java
|
StringUtilsBenchmark
|
measure_StringUtils_tryParseLong_invalid
|
class StringUtilsBenchmark {
@Benchmark
public Long measure_Long_parseLong_valid() {
try {
return Long.parseLong("1658149133924");
} catch (NumberFormatException ex) {
return null;
}
}
@Benchmark
public Long measure_Long_parseLong_invalid() {
try {
return Long.parseLong("2022-07-18");
} catch (NumberFormatException ex) {
return null;
}
}
@Benchmark
public Long measure_StringUtils_tryParseLong_valid() {
long[] out = StringUtils.PARSE_LONG_BUFFER.get();
if (StringUtils.tryParseLong("1658149133924", out)) {
return out[0];
}
return null;
}
@Benchmark
public Long measure_StringUtils_tryParseLong_invalid() {<FILL_FUNCTION_BODY>}
}
|
long[] out = StringUtils.PARSE_LONG_BUFFER.get();
if (StringUtils.tryParseLong("2022-07-18", out)) {
return out[0];
}
return null;
| 269
| 63
| 332
|
<no_super_class>
|
crate_crate
|
crate/benchmarks/src/main/java/io/crate/execution/engine/aggregation/AggregateCollectorBenchmark.java
|
AggregateCollectorBenchmark
|
setup
|
class AggregateCollectorBenchmark {
private final List<Row1> rows = IntStream.range(0, 10_000).mapToObj(Row1::new).toList();
private AggregateCollector collector;
@SuppressWarnings("unchecked")
@Setup
public void setup() {<FILL_FUNCTION_BODY>}
@Benchmark
public Iterable<Row> measureAggregateCollector() {
Object[] state = collector.supplier().get();
BiConsumer<Object[], Row> accumulator = collector.accumulator();
Function<Object[], Iterable<Row>> finisher = collector.finisher();
for (int i = 0; i < rows.size(); i++) {
accumulator.accept(state, rows.get(i));
}
return finisher.apply(state);
}
}
|
RowCollectExpression inExpr0 = new RowCollectExpression(0);
Functions functions = Functions.load(Settings.EMPTY, new SessionSettingRegistry(Set.of()));
SumAggregation<?> sumAggregation = (SumAggregation<?>) functions.getQualified(
Signature.aggregate(
SumAggregation.NAME,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.LONG.getTypeSignature()
),
List.of(DataTypes.INTEGER),
DataTypes.INTEGER
);
var memoryManager = new OnHeapMemoryManager(bytes -> {});
collector = new AggregateCollector(
Collections.singletonList(inExpr0),
RamAccounting.NO_ACCOUNTING,
memoryManager,
Version.CURRENT,
AggregateMode.ITER_FINAL,
new AggregationFunction[] { sumAggregation },
Version.CURRENT,
new Input[][] { {inExpr0 } },
new Input[] { Literal.BOOLEAN_TRUE }
);
| 226
| 273
| 499
|
<no_super_class>
|
crate_crate
|
crate/benchmarks/src/main/java/io/crate/execution/engine/aggregation/GroupingLongCollectorBenchmark.java
|
GroupingLongCollectorBenchmark
|
measureGroupingOnNumericDocValues
|
class GroupingLongCollectorBenchmark {
private GroupingCollector<?> groupBySumCollector;
private List<Row> rows;
private long[] numbers;
private IndexSearcher searcher;
@Setup
public void createGroupingCollector() throws Exception {
try (IndexWriter iw =
new IndexWriter(new ByteBuffersDirectory(), new IndexWriterConfig(new StandardAnalyzer()))) {
Functions functions = Functions.load(Settings.EMPTY, new SessionSettingRegistry(Set.of()));
SumAggregation<?> sumAgg = (SumAggregation<?>) functions.getQualified(
Signature.aggregate(
SumAggregation.NAME,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.LONG.getTypeSignature()
),
List.of(DataTypes.INTEGER),
DataTypes.INTEGER
);
var memoryManager = new OnHeapMemoryManager(bytes -> {
});
groupBySumCollector = createGroupBySumCollector(sumAgg, memoryManager);
int size = 20_000_000;
rows = new ArrayList<>(size);
numbers = new long[size];
for (int i = 0; i < size; i++) {
long value = (long) i % 200;
rows.add(new Row1(value));
numbers[i] = value;
var doc = new Document();
doc.add(new NumericDocValuesField("x", value));
doc.add(new SortedNumericDocValuesField("y", value));
iw.addDocument(doc);
}
iw.commit();
iw.forceMerge(1, true);
searcher = new IndexSearcher(DirectoryReader.open(iw));
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private static GroupingCollector<?> createGroupBySumCollector(AggregationFunction<?, ?> sumAgg, MemoryManager memoryManager) {
RowCollectExpression keyInput = new RowCollectExpression(0);
List<Input<?>> keyInputs = List.of(keyInput);
CollectExpression[] collectExpressions = new CollectExpression[]{keyInput};
return GroupingCollector.singleKey(
collectExpressions,
AggregateMode.ITER_FINAL,
new AggregationFunction[] { sumAgg },
new Input[][] { new Input[] { keyInput }},
new Input[] { Literal.BOOLEAN_TRUE },
RamAccounting.NO_ACCOUNTING,
memoryManager,
Version.CURRENT,
keyInputs.getFirst(),
DataTypes.LONG,
Version.CURRENT
);
}
@Benchmark
public void measureGroupBySumLong(Blackhole blackhole) throws Exception {
var rowsIterator = InMemoryBatchIterator.of(rows, SENTINEL, true);
blackhole.consume(rowsIterator.collect(groupBySumCollector).get());
}
@Benchmark
public LongObjectHashMap<Long> measureGroupingOnNumericDocValues() throws Exception {<FILL_FUNCTION_BODY>}
@Benchmark
public LongObjectHashMap<Long> measureGroupingOnSortedNumericDocValues() throws Exception {
var weight = searcher.createWeight(new MatchAllDocsQuery(), ScoreMode.COMPLETE_NO_SCORES, 1.0f);
var leaf = searcher.getTopReaderContext().leaves().getFirst();
var scorer = weight.scorer(leaf);
var docValues = DocValues.getSortedNumeric(leaf.reader(), "y");
var docIt = scorer.iterator();
LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>();
for (int docId = docIt.nextDoc(); docId != DocIdSetIterator.NO_MORE_DOCS; docId = docIt.nextDoc()) {
if (docValues.advanceExact(docId)) {
if (docValues.docValueCount() == 1) {
long number = docValues.nextValue();
sumByKey.compute(number, (key, oldValue) -> {
if (oldValue == null) {
return number;
} else {
return oldValue + number;
}
});
}
}
}
return sumByKey;
}
/**
* To establish a base line on how fast it could go
*/
@Benchmark
public LongObjectHashMap<Long> measureGroupingOnLongArray() {
LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>();
for (long number : numbers) {
sumByKey.compute(number, (key, oldValue) -> {
if (oldValue == null) {
return number;
} else {
return oldValue + number;
}
});
}
return sumByKey;
}
}
|
Weight weight = searcher.createWeight(new MatchAllDocsQuery(), ScoreMode.COMPLETE_NO_SCORES, 1.0f);
LeafReaderContext leaf = searcher.getTopReaderContext().leaves().getFirst();
Scorer scorer = weight.scorer(leaf);
NumericDocValues docValues = DocValues.getNumeric(leaf.reader(), "x");
DocIdSetIterator docIt = scorer.iterator();
LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>();
for (int docId = docIt.nextDoc(); docId != DocIdSetIterator.NO_MORE_DOCS; docId = docIt.nextDoc()) {
if (docValues.advanceExact(docId)) {
long number = docValues.longValue();
sumByKey.compute(number, (key, oldValue) -> {
if (oldValue == null) {
return number;
} else {
return oldValue + number;
}
});
}
}
return sumByKey;
| 1,259
| 268
| 1,527
|
<no_super_class>
|
crate_crate
|
crate/benchmarks/src/main/java/io/crate/execution/engine/distribution/merge/SortedPagingIteratorBenchmark.java
|
SortedPagingIteratorBenchmark
|
measurePagingIteratorWithoutRepeat
|
class SortedPagingIteratorBenchmark {
private Comparator<Row> compareOnFirstColumn;
private Random rnd;
private List<Row> unsortedSecond;
private List<Row> unsortedFirst;
private List<Row> sortedFirst;
private List<Row> sortedSecond;
@Setup
public void prepareData() {
rnd = new Random(42);
compareOnFirstColumn = OrderingByPosition.rowOrdering(DataTypes.INTEGER, 0, false, false);
unsortedFirst = IntStream.range(0, 1_000_000).mapToObj(Row1::new).collect(Collectors.toList());
unsortedSecond = IntStream.range(500_000, 1_500_00).mapToObj(Row1::new).collect(Collectors.toList());
Collections.shuffle(unsortedFirst, rnd);
Collections.shuffle(unsortedSecond, rnd);
sortedFirst = new ArrayList<>(unsortedFirst);
sortedFirst.sort(compareOnFirstColumn);
sortedSecond = new ArrayList<>(unsortedSecond);
sortedSecond.sort(compareOnFirstColumn);
}
@Benchmark
public void measurePagingIteratorWithRepeat(Blackhole blackhole) {
PagingIterator<Integer, Row> pagingIterator = PagingIterator.createSorted(compareOnFirstColumn, true);
pagingIterator.merge(Arrays.asList(new KeyIterable<>(1, sortedFirst), new KeyIterable<>(2, sortedSecond)));
pagingIterator.finish();
while (pagingIterator.hasNext()) {
blackhole.consume(pagingIterator.next());
}
}
@Benchmark
public void measurePagingIteratorWithoutRepeat(Blackhole blackhole) {<FILL_FUNCTION_BODY>}
@Benchmark
public void measurePagingIteratorWithSort(Blackhole blackhole) throws Exception {
unsortedFirst.sort(compareOnFirstColumn);
unsortedSecond.sort(compareOnFirstColumn);
PagingIterator<Integer, Row> pagingIterator = PagingIterator.createSorted(compareOnFirstColumn, false);
pagingIterator.merge(Arrays.asList(new KeyIterable<>(1, sortedFirst), new KeyIterable<>(2, sortedSecond)));
pagingIterator.finish();
while (pagingIterator.hasNext()) {
blackhole.consume(pagingIterator.next());
}
Collections.shuffle(unsortedFirst, rnd);
Collections.shuffle(unsortedSecond, rnd);
}
@Benchmark
public void measureListSort(Blackhole blackhole) {
ArrayList<Row> allRows = new ArrayList<>(unsortedFirst);
allRows.addAll(unsortedSecond);
allRows.sort(compareOnFirstColumn);
for (Row row : allRows) {
blackhole.consume(row);
}
// reset to avoid sorting a already sorted list in the next iteration
Collections.shuffle(unsortedFirst, rnd);
Collections.shuffle(unsortedSecond, rnd);
}
}
|
PagingIterator<Integer, Row> pagingIterator = PagingIterator.createSorted(compareOnFirstColumn, false);
pagingIterator.merge(Arrays.asList(new KeyIterable<>(1, sortedFirst), new KeyIterable<>(2, sortedSecond)));
pagingIterator.finish();
while (pagingIterator.hasNext()) {
blackhole.consume(pagingIterator.next());
}
| 799
| 107
| 906
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.