language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/AllocateAction.java
{ "start": 1064, "end": 8993 }
class ____ implements LifecycleAction { public static final String NAME = "allocate"; public static final ParseField NUMBER_OF_REPLICAS_FIELD = new ParseField("number_of_replicas"); public static final ParseField TOTAL_SHARDS_PER_NODE_FIELD = new ParseField("total_shards_per_node"); public static final ParseField INCLUDE_FIELD = new ParseField("include"); public static final ParseField EXCLUDE_FIELD = new ParseField("exclude"); public static final ParseField REQUIRE_FIELD = new ParseField("require"); @SuppressWarnings("unchecked") private static final ConstructingObjectParser<AllocateAction, Void> PARSER = new ConstructingObjectParser<>( NAME, a -> new AllocateAction( (Integer) a[0], (Integer) a[1], (Map<String, String>) a[2], (Map<String, String>) a[3], (Map<String, String>) a[4] ) ); static { PARSER.declareInt(ConstructingObjectParser.optionalConstructorArg(), NUMBER_OF_REPLICAS_FIELD); PARSER.declareInt(ConstructingObjectParser.optionalConstructorArg(), TOTAL_SHARDS_PER_NODE_FIELD); PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.mapStrings(), INCLUDE_FIELD); PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.mapStrings(), EXCLUDE_FIELD); PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.mapStrings(), REQUIRE_FIELD); } private final Integer numberOfReplicas; private final Integer totalShardsPerNode; private final Map<String, String> include; private final Map<String, String> exclude; private final Map<String, String> require; public static AllocateAction parse(XContentParser parser) { return PARSER.apply(parser, null); } public AllocateAction( Integer numberOfReplicas, Integer totalShardsPerNode, Map<String, String> include, Map<String, String> exclude, Map<String, String> require ) { if (include == null) { this.include = Map.of(); } else { this.include = include; } if (exclude == null) { this.exclude = Map.of(); } else { this.exclude = exclude; } if (require == null) { this.require = Map.of(); } else { this.require = require; } if (this.include.isEmpty() && this.exclude.isEmpty() && this.require.isEmpty() && numberOfReplicas == null && totalShardsPerNode == null) { throw new IllegalArgumentException( "At least one of " + INCLUDE_FIELD.getPreferredName() + ", " + EXCLUDE_FIELD.getPreferredName() + " or " + REQUIRE_FIELD.getPreferredName() + " must contain attributes for action " + NAME + ". Otherwise the " + NUMBER_OF_REPLICAS_FIELD.getPreferredName() + " or the " + TOTAL_SHARDS_PER_NODE_FIELD.getPreferredName() + " options must be configured." ); } if (numberOfReplicas != null && numberOfReplicas < 0) { throw new IllegalArgumentException("[" + NUMBER_OF_REPLICAS_FIELD.getPreferredName() + "] must be >= 0"); } this.numberOfReplicas = numberOfReplicas; if (totalShardsPerNode != null && totalShardsPerNode < -1) { throw new IllegalArgumentException("[" + TOTAL_SHARDS_PER_NODE_FIELD.getPreferredName() + "] must be >= -1"); } this.totalShardsPerNode = totalShardsPerNode; } @SuppressWarnings("unchecked") public AllocateAction(StreamInput in) throws IOException { this( in.readOptionalVInt(), in.readOptionalInt(), (Map<String, String>) in.readGenericValue(), (Map<String, String>) in.readGenericValue(), (Map<String, String>) in.readGenericValue() ); } public Integer getNumberOfReplicas() { return numberOfReplicas; } public Integer getTotalShardsPerNode() { return totalShardsPerNode; } public Map<String, String> getInclude() { return include; } public Map<String, String> getExclude() { return exclude; } public Map<String, String> getRequire() { return require; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalVInt(numberOfReplicas); out.writeOptionalInt(totalShardsPerNode); out.writeGenericValue(include); out.writeGenericValue(exclude); out.writeGenericValue(require); } @Override public String getWriteableName() { return NAME; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); if (numberOfReplicas != null) { builder.field(NUMBER_OF_REPLICAS_FIELD.getPreferredName(), numberOfReplicas); } if (totalShardsPerNode != null) { builder.field(TOTAL_SHARDS_PER_NODE_FIELD.getPreferredName(), totalShardsPerNode); } builder.stringStringMap(INCLUDE_FIELD.getPreferredName(), include); builder.stringStringMap(EXCLUDE_FIELD.getPreferredName(), exclude); builder.stringStringMap(REQUIRE_FIELD.getPreferredName(), require); builder.endObject(); return builder; } @Override public boolean isSafeAction() { return true; } @Override public List<Step> toSteps(Client client, String phase, StepKey nextStepKey) { StepKey allocateKey = new StepKey(phase, NAME, NAME); StepKey allocationRoutedKey = new StepKey(phase, NAME, AllocationRoutedStep.NAME); Settings.Builder newSettings = Settings.builder(); if (numberOfReplicas != null) { newSettings.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, numberOfReplicas); } include.forEach((key, value) -> newSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + key, value)); exclude.forEach((key, value) -> newSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + key, value)); require.forEach((key, value) -> newSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + key, value)); if (totalShardsPerNode != null) { newSettings.put(ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), totalShardsPerNode); } UpdateSettingsStep allocateStep = new UpdateSettingsStep(allocateKey, allocationRoutedKey, client, newSettings.build()); AllocationRoutedStep routedCheckStep = new AllocationRoutedStep(allocationRoutedKey, nextStepKey); return List.of(allocateStep, routedCheckStep); } @Override public int hashCode() { return Objects.hash(numberOfReplicas, totalShardsPerNode, include, exclude, require); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != getClass()) { return false; } AllocateAction other = (AllocateAction) obj; return Objects.equals(numberOfReplicas, other.numberOfReplicas) && Objects.equals(totalShardsPerNode, other.totalShardsPerNode) && Objects.equals(include, other.include) && Objects.equals(exclude, other.exclude) && Objects.equals(require, other.require); } @Override public String toString() { return Strings.toString(this); } }
AllocateAction
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/support/ServletConfigPropertySource.java
{ "start": 1099, "end": 1538 }
class ____ extends EnumerablePropertySource<ServletConfig> { public ServletConfigPropertySource(String name, ServletConfig servletConfig) { super(name, servletConfig); } @Override public String[] getPropertyNames() { return StringUtils.toStringArray(this.source.getInitParameterNames()); } @Override public @Nullable String getProperty(String name) { return this.source.getInitParameter(name); } }
ServletConfigPropertySource
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/util/OperatorMatrixGenerator.java
{ "start": 1054, "end": 42254 }
class ____ { private OperatorMatrixGenerator() { throw new IllegalStateException("No instances!"); } static final String PRESENT = "![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)"; static final String ABSENT = "![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png)"; static final String TBD = "![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)"; static final Class<?>[] CLASSES = { Flowable.class, Observable.class, Maybe.class, Single.class, Completable.class }; static String header(String type) { return "![" + type + "](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmatrix-" + type.toLowerCase() + ".png)"; } public static void main(String[] args) throws IOException { Set<String> operatorSet = new HashSet<>(); Map<Class<?>, Set<String>> operatorMap = new HashMap<>(); for (Class<?> clazz : CLASSES) { Set<String> set = operatorMap.computeIfAbsent(clazz, c -> new HashSet<>()); for (Method m : clazz.getMethods()) { String name = m.getName(); if (!name.equals("bufferSize") && m.getDeclaringClass() == clazz && !m.isSynthetic()) { operatorSet.add(m.getName()); set.add(m.getName()); } } } List<String> sortedOperators = new ArrayList<>(operatorSet); sortedOperators.sort(Comparator.naturalOrder()); try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Paths.get("docs", "Operator-Matrix.md"), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING))) { out.print("Operator |"); for (Class<?> clazz : CLASSES) { out.print(" "); out.print(header(clazz.getSimpleName())); out.print(" |"); } out.println(); out.print("-----|"); for (int i = 0; i < CLASSES.length; i++) { out.print("---|"); } out.println(); Map<String, Integer> notesMap = new HashMap<>(); List<String> notesList = new ArrayList<>(); List<String> tbdList = new ArrayList<>(); int[] counters = new int[CLASSES.length]; for (String operatorName : sortedOperators) { out.print("<a name='"); out.print(operatorName); out.print("'></a>`"); out.print(operatorName); out.print("`|"); int m = 0; for (Class<?> clazz : CLASSES) { if (operatorMap.get(clazz).contains(operatorName)) { out.print(PRESENT); counters[m]++; } else { String notes = findNotes(clazz.getSimpleName(), operatorName); if (notes != null) { out.print(ABSENT); Integer index = notesMap.get(notes); if (index == null) { index = notesMap.size() + 1; notesMap.put(notes, index); notesList.add(notes); } out.print(" <sup title='"); out.print(notes.replace("`", "").replace("[", "").replace("]", "").replaceAll("\\(#.+\\)", "")); out.print("'>(["); out.print(index); out.print("](#notes-"); out.print(index); out.print("))</sup>"); } else { out.print(TBD); tbdList.add(clazz.getSimpleName() + "." + operatorName + "()"); } } out.print("|"); m++; } out.println(); } out.print("<a name='total'></a>**"); out.print(sortedOperators.size()); out.print(" operators** |"); for (int m = 0; m < counters.length; m++) { out.print(" **"); out.print(counters[m]); out.print("** |"); } out.println(); if (!notesList.isEmpty()) { out.println(); out.println("#### Notes"); for (int i = 0; i < notesList.size(); i++) { out.print("<a name='notes-"); out.print(i + 1); out.print("'></a><sup>"); out.print(i + 1); out.print("</sup> "); out.print(notesList.get(i)); out.println("<br/>"); } } if (tbdList.isEmpty()) { out.println(); out.println("#### Under development"); out.println(); out.println("*Currently, all intended operators are implemented.*"); } else { out.println(); out.println("#### Under development"); out.println(); for (int i = 0; i < tbdList.size(); i++) { out.print(i + 1); out.print(". "); out.println(tbdList.get(i)); } } } } static String findNotes(String clazzName, String operatorName) { Map<String, String> classNotes = NOTES_MAP.get(operatorName); if (classNotes != null) { return classNotes.get(clazzName.substring(0, 1)); } switch (operatorName) { case "empty": { if ("Completable".equals(clazzName)) { return "Use [`complete()`](#complete)."; } if ("Single".equals(clazzName)) { return "Never empty."; } break; } } return null; } static final String[] NOTES = { // Format // FOMSC methodName note " MS all Use [`contains()`](#contains).", " C all Always empty.", "FOMS andThen Use [`concatWith`](#concatWith).", " MS any Use [`contains()`](#contains).", " C any Always empty.", "FO blockingAwait Use [`blockingFirst()`](#blockingFirst), [`blockingSingle()`](#blockingSingle) or [`blockingLast()`](#blockingLast).", " MS blockingAwait Use [`blockingGet()`](#blockingGet).", " MS blockingFirst At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingFirst No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MSC blockingForEach Use [`blockingSubscribe()`](#blockingSubscribe)", "FO blockingGet Use [`blockingFirst()`](#blockingFirst), [`blockingSingle()`](#blockingSingle) or [`blockingLast()`](#blockingLast).", " C blockingGet No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MS blockingIterable At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingIterable No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MS blockingLast At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingLast No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MS blockingLatest At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingLatest No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MS blockingMostRecent At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingMostRecent No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MS blockingNext At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingNext No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MS blockingSingle At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingSingle No elements to get. Use [`blockingAwait()`](#blockingAwait).", " MS blockingStream At most one element to get. Use [`blockingGet()`](#blockingGet).", " C blockingStream No elements to get. Use [`blockingAwait()`](#blockingAwait).", " M buffer Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a list/collection.", " S buffer Use [`map()`](#map) to transform into a list/collection.", " C buffer Always empty. Use [`andThen()`](#andThen) to bring in a list/collection.", " MSC cacheWithInitialCapacity At most one element to store. Use [`cache()`](#cache).", " C cast Always empty.", " M collect At most one element to collect. Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a list/collection.", " S collect One element to collect. Use [`map()`](#map) to transform into a list/collection.", " C collect Always empty. Use [`andThen()`](#andThen) to bring in a collection.", " M collectInto At most one element to collect. Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a list/collection.", " S collectInto One element to collect. Use [`map()`](#map) to transform into a list/collection.", " C collectInto Always empty. Use [`andThen()`](#andThen) to bring in a collection.", " MS combineLatest At most one element per source. Use [`zip()`](#zip).", " C combineLatest Always empty. Use [`merge()`](#merge).", " MS combineLatestArray At most one element per source. Use [`zipArray()`](#zipArray).", " C combineLatestArray Always empty. Use [`mergeArray()`](#mergeArray).", " MS combineLatestDelayError At most one element per source. Use [`zip()`](#zip).", " C combineLatestDelayError Always empty. Use [`mergeDelayError()`](#mergeDelayError).", " MS combineLatestArrayDelayError At most one element per source. Use [`zipArray()`](#zipArray).", " C combineLatestArrayDelayError Always empty. Use [`mergeArrayDelayError()`](#mergeArrayDelayError).", "FOM complete Use [`empty()`](#empty).", " S complete Never empty.", " C concatArrayEager No items to keep ordered. Use [`mergeArray()`](#mergeArray).", " C concatArrayEagerDelayError No items to keep ordered. Use [`mergeArrayDelayError()`](#mergeArrayDelayError).", " C concatEager No items to keep ordered. Use [`merge()`](#merge).", " C concatEagerDelayError No items to keep ordered. Use [`mergeDelayError()`](#mergeDelayError).", " C concatMap Always empty thus no items to map.", " C concatMapCompletable Always empty thus no items to map.", " MS concatMapCompletableDelayError Either the upstream fails (thus no inner) or the mapped-in source, but never both. Use [`concatMapCompletable`](#concatMapCompletable).", " C concatMapCompletableDelayError Always empty thus no items to map.", " MS concatMapDelayError Either the upstream fails (thus no inner) or the mapped-in source, but never both. Use [`concatMap`](#concatMap).", " C concatMapDelayError Always empty thus no items to map.", " MS concatMapEager At most one item to map. Use [`concatMap()`](#concatMap).", " C concatMapEager Always empty thus no items to map.", " MS concatMapEagerDelayError At most one item to map. Use [`concatMap()`](#concatMap).", " C concatMapEagerDelayError Always empty thus no items to map.", " C concatMapIterable Always empty thus no items to map.", " M concatMapMaybe Use [`concatMap`](#concatMap).", " C concatMapMaybe Always empty thus no items to map.", " MS concatMapMaybeDelayError Either the upstream fails (thus no inner) or the mapped-in source, but never both. Use [`concatMapMaybe`](#concatMapMaybe).", " C concatMapMaybeDelayError Always empty thus no items to map.", " S concatMapSingle Use [`concatMap()`](#concatMap).", " C concatMapSingle Always empty thus no items to map.", " MS concatMapSingleDelayError Either the upstream fails (thus no inner) or the mapped-in source, but never both. Use [`concatMapSingle`](#concatMapSingle).", " C concatMapSingleDelayError Always empty thus no items to map.", " C concatMapStream Always empty thus no items to map.", " MS concatMapIterable At most one item. Use [`flattenAsFlowable`](#flattenAsFlowable) or [`flattenAsObservable`](#flattenAsObservable).", " MS concatMapStream At most one item. Use [`flattenStreamAsFlowable`](#flattenStreamAsFlowable) or [`flattenStreamAsObservable`](#flattenStreamAsObservable).", " C contains Always empty.", " S count Never empty thus always 1.", " C count Always empty thus always 0.", " MS debounce At most one item signaled so no subsequent items to work with.", " C debounce Always empty thus no items to work with.", " S defaultIfEmpty Never empty.", " C defaultIfEmpty Always empty. Use [`andThen()`](#andThen) to chose the follow-up sequence.", " C dematerialize Always empty thus no items to work with.", " MS distinct At most one item, always distinct.", " C distinct Always empty thus no items to work with.", " MS distinctUntilChanged At most one item, always distinct.", " C distinctUntilChanged Always empty thus no items to work with.", " MS doAfterNext Different terminology. Use [`doAfterSuccess()`](#doAfterSuccess).", " C doAfterNext Always empty.", "FO doAfterSuccess Different terminology. Use [`doAfterNext()`](#doAfterNext).", " C doAfterSuccess Always empty thus no items to work with.", " OMSC doOnCancel Different terminology. Use [`doOnDispose()`](#doOnDispose).", " S doOnComplete Always succeeds or fails, there is no `onComplete` signal.", "F doOnDispose Different terminology. Use [`doOnCancel()`](#doOnCancel).", " MS doOnEach At most one item. Use [`doOnEvent()`](#doOnEvent).", " C doOnEach Always empty thus no items to work with.", "FO doOnEvent Use [`doOnEach()`](#doOnEach).", " MS doOnNext Different terminology. Use [`doOnSuccess()`](#doOnSuccess).", " C doOnNext Always empty thus no items to work with.", " OMSC doOnRequest Backpressure related and not supported outside `Flowable`.", "FO doOnSuccess Different terminology. Use [`doOnNext()`](#doOnNext).", " C doOnSuccess Always empty thus no items to work with.", " M elementAt At most one item with index 0. Use [`defaultIfEmpty`](#defaultIfEmpty).", " S elementAt Always one item with index 0.", " C elementAt Always empty thus no items to work with.", " M elementAtOrError At most one item with index 0. Use [`toSingle`](#toSingle).", " S elementAtOrError Always one item with index 0.", " C elementAtOrError Always empty thus no items to work with.", " S empty Never empty.", " C empty Use [`complete()`](#complete).", " C filter Always empty thus no items to work with.", " M first At most one item. Use [`defaultIfEmpty`](#defaultIfEmpty).", " S first Always one item.", " C first Always empty. Use [`andThen()`](#andThen) to chose the follow-up sequence.", " M firstElement At most one item, would be no-op.", " S firstElement Always one item, would be no-op.", " C firstElement Always empty.", " M firstOrError At most one item, would be no-op.", " S firstOrError Always one item, would be no-op.", " C firstOrError Always empty. Use [`andThen()`](#andThen) and [`error()`](#error).", " MS firstOrErrorStage At most one item. Use [`toCompletionStage()`](#toCompletionStage).", " C firstOrErrorStage Always empty. Use [`andThen()`](#andThen), [`error()`](#error) and [`toCompletionStage()`](#toCompletionStage).", " MSC firstStage At most one item. Use [`toCompletionStage()`](#toCompletionStage).", " C flatMap Always empty thus no items to map.", " C flatMapCompletable Always empty thus no items to map.", " C flatMapCompletableDelayError Always empty thus no items to map.", " C flatMapIterable Always empty thus no items to map.", " M flatMapMaybe Use [`flatMap()`](#flatMap).", " C flatMapMaybe Always empty thus no items to map.", " C flatMapMaybeDelayError Always empty thus no items to map.", " S flatMapSingle Use [`flatMap()`](#flatMap).", " C flatMapSingle Always empty thus no items to map.", " C flatMapStream Always empty thus no items to map.", " MS flatMapIterable At most one item. Use [`flattenAsFlowable`](#flattenAsFlowable) or [`flattenAsObservable`](#flattenAsObservable).", " MS flatMapStream At most one item. Use [`flattenStreamAsFlowable`](#flattenStreamAsFlowable) or [`flattenStreamAsObservable`](#flattenStreamAsObservable).", "F flatMapObservable Not supported. Use [`flatMap`](#flatMap) and [`toFlowable()`](#toFlowable).", " O flatMapObservable Use [`flatMap`](#flatMap).", " C flatMapObservable Always empty thus no items to map.", " O flatMapPublisher Not supported. Use [`flatMap`](#flatMap) and [`toObservable()`](#toFlowable).", "F flatMapPublisher Use [`flatMap`](#flatMap).", " C flatMapPublisher Always empty thus no items to map.", "FO flatMapSingleElement Use [`flatMapSingle`](#flatMapSingle).", " S flatMapSingleElement Use [`flatMap`](#flatMap).", " C flatMapSingleElement Always empty thus no items to map.", "FO flattenAsFlowable Use [`flatMapIterable()`](#flatMapIterable).", " C flattenAsFlowable Always empty thus no items to map.", "FO flattenAsObservable Use [`flatMapIterable()`](#flatMapIterable).", " C flattenAsObservable Always empty thus no items to map.", "FO flattenStreamAsFlowable Use [`flatMapStream()`](#flatMapStream).", " C flattenStreamAsFlowable Always empty thus no items to map.", "FO flattenStreamAsObservable Use [`flatMapStream()`](#flatMapStream).", " C flattenStreamAsObservable Always empty thus no items to map.", " MSC forEach Use [`subscribe()`](#subscribe).", " MSC forEachWhile Use [`subscribe()`](#subscribe).", " S fromAction Never empty.", " M fromArray At most one item. Use [`just()`](#just) or [`empty()`](#empty).", " S fromArray Always one item. Use [`just()`](#just).", " C fromArray Always empty. Use [`complete()`](#complete).", " S fromCompletable Always error.", " C fromCompletable Use [`wrap()`](#wrap).", " M fromIterable At most one item. Use [`just()`](#just) or [`empty()`](#empty).", " S fromIterable Always one item. Use [`just()`](#just).", " C fromIterable Always empty. Use [`complete()`](#complete).", " M fromMaybe Use [`wrap()`](#wrap).", " O fromObservable Use [`wrap()`](#wrap).", " S fromOptional Always one item. Use [`just()`](#just).", " C fromOptional Always empty. Use [`complete()`](#complete).", " S fromRunnable Never empty.", " S fromSingle Use [`wrap()`](#wrap).", " M fromStream At most one item. Use [`just()`](#just) or [`empty()`](#empty).", " S fromStream Always one item. Use [`just()`](#just).", " C fromStream Always empty. Use [`complete()`](#complete).", " MSC generate Use [`fromSupplier()`](#fromSupplier).", " MS groupBy At most one item.", " C groupBy Always empty thus no items to group.", " MS groupJoin At most one item.", " C groupJoin Always empty thus no items to join.", "FO ignoreElement Use [`ignoreElements()`](#ignoreElements).", " C ignoreElement Always empty.", " MS ignoreElements Use [`ignoreElement()`](#ignoreElement).", " C ignoreElements Always empty.", " MSC interval At most one item. Use [`timer()`](#timer).", " MSC intervalRange At most one item. Use [`timer()`](#timer).", " S isEmpty Always one item.", " C isEmpty Always empty.", " MS join At most one item. Use [`zip()`](#zip)", " C join Always empty thus no items to join.", " C just Always empty.", " M last At most one item. Use [`defaultIfEmpty`](#defaultIfEmpty).", " S last Always one item.", " C last Always empty. Use [`andThen()`](#andThen) to chose the follow-up sequence.", " M lastElement At most one item, would be no-op.", " S lastElement Always one item, would be no-op.", " C lastElement Always empty.", " M lastOrError At most one item, would be no-op.", " S lastOrError Always one item, would be no-op.", " C lastOrError Always empty. Use [`andThen()`](#andThen) and [`error()`](#error).", " MS lastOrErrorStage At most one item. Use [`toCompletionStage()`](#toCompletionStage).", " C lastOrErrorStage Always empty. Use [`andThen()`](#andThen), [`error()`](#error) and [`toCompletionStage()`](#toCompletionStage).", " MSC lastStage At most one item. Use [`toCompletionStage()`](#toCompletionStage).", " C map Always empty thus no items to map.", " C mapOptional Always empty thus no items to map.", " C ofType Always empty thus no items to filter.", " OMSC onBackpressureBuffer Backpressure related and not supported outside `Flowable`.", " OMSC onBackpressureDrop Backpressure related and not supported outside `Flowable`.", " OMSC onBackpressureLatest Backpressure related and not supported outside `Flowable`.", " OMSC parallel Needs backpressure thus not supported outside `Flowable`.", " M publish Connectable sources not supported outside `Flowable` and `Observable`. Use a `MaybeSubject`.", " S publish Connectable sources not supported outside `Flowable` and `Observable`. Use a `SingleSubject`.", " C publish Connectable sources not supported outside `Flowable` and `Observable`. Use a `ConnectableSubject`.", " MS range At most one item. Use [`just()`](#just).", " C range Always empty. Use [`complete()`](#complete).", " MS rangeLong At most one item. Use [`just()`](#just).", " C rangeLong Always empty. Use [`complete()`](#complete).", " OMSC rebatchRequests Backpressure related and not supported outside `Flowable`.", " MS reduce At most one item. Use [`map()`](#map).", " C reduce Always empty thus no items to reduce.", " MS reduceWith At most one item. Use [`map()`](#map).", " C reduceWith Always empty thus no items to reduce.", " M replay Connectable sources not supported outside `Flowable` and `Observable`. Use a `MaybeSubject`.", " S replay Connectable sources not supported outside `Flowable` and `Observable`. Use a `SingleSubject`.", " C replay Connectable sources not supported outside `Flowable` and `Observable`. Use a `ConnectableSubject`.", " MS sample At most one item, would be no-op.", " C sample Always empty thus no items to work with.", " MS scan At most one item. Use [`map()`](#map).", " C scan Always empty thus no items to reduce.", " MS scanWith At most one item. Use [`map()`](#map).", " C scanWith Always empty thus no items to reduce.", " MSC serialize At most one signal type.", " M share Connectable sources not supported outside `Flowable` and `Observable`. Use a `MaybeSubject`.", " S share Connectable sources not supported outside `Flowable` and `Observable`. Use a `SingleSubject`.", " C share Connectable sources not supported outside `Flowable` and `Observable`. Use a `ConnectableSubject`.", " M single At most one item. Use [`defaultIfEmpty`](#defaultIfEmpty).", " S single Always one item.", " C single Always empty. Use [`andThen()`](#andThen) to chose the follow-up sequence.", " M singleElement At most one item, would be no-op.", " S singleElement Always one item, would be no-op.", " C singleElement Always empty.", " M singleOrError At most one item, would be no-op.", " S singleOrError Always one item, would be no-op.", " C singleOrError Always empty. Use [`andThen()`](#andThen) and [`error()`](#error).", " MS singleOrErrorStage At most one item. Use [`toCompletionStage()`](#toCompletionStage).", " C singleOrErrorStage Always empty. Use [`andThen()`](#andThen), [`error()`](#error) and [`toCompletionStage()`](#toCompletionStage).", " MSC singleStage At most one item. Use [`toCompletionStage()`](#toCompletionStage).", " MSC skip At most one item, would be no-op.", " MSC skipLast At most one item, would be no-op.", " MS skipWhile At most one item. Use [`filter()`](#filter).", " C skipWhile Always empty.", " MSC skipUntil At most one item. Use [`takeUntil()`](#takeUntil).", " MSC sorted At most one item.", " MSC startWithArray Use [`startWith()`](#startWith) and [`fromArray()`](#fromArray) of `Flowable` or `Observable`.", " MSC startWithItem Use [`startWith()`](#startWith) and [`just()`](#just) of another reactive type.", " MSC startWithIterable Use [`startWith()`](#startWith) and [`fromIterable()`](#fromArray) of `Flowable` or `Observable`.", " S switchIfEmpty Never empty.", " C switchIfEmpty Always empty. Use [`defaultIfEmpty()`](#defaultIfEmpty).", " MS switchMap At most one item. Use [`flatMap()`](#flatMap).", " C switchMap Always empty thus no items to map.", " MS switchMapDelayError At most one item. Use [`flatMap()`](#flatMap).", " C switchMapDelayError Always empty thus no items to map.", " MS switchMapCompletable At most one item. Use [`flatMap()`](#flatMap).", " C switchMapCompletable Always empty thus no items to map.", " MS switchMapCompletableDelayError At most one item. Use [`flatMap()`](#flatMap).", " C switchMapCompletableDelayError Always empty thus no items to map.", " MS switchMapMaybe At most one item. Use [`flatMap()`](#flatMap).", " C switchMapMaybe Always empty thus no items to map.", " MS switchMapMaybeDelayError At most one item. Use [`flatMap()`](#flatMap).", " C switchMapMaybeDelayError Always empty thus no items to map.", " MS switchMapSingle At most one item. Use [`flatMap()`](#flatMap).", " C switchMapSingle Always empty thus no items to map.", " MS switchMapSingleDelayError At most one item. Use [`flatMap()`](#flatMap).", " C switchMapSingleDelayError Always empty thus no items to map.", " MSC take At most one item, would be no-op.", " MSC takeLast At most one item, would be no-op.", " MS takeWhile At most one item. Use [`filter()`](#filter).", " C takeWhile Always empty.", " MS throttleFirst At most one item signaled so no subsequent items to work with.", " C throttleFirst Always empty thus no items to work with.", " MS throttleLast At most one item signaled so no subsequent items to work with.", " C throttleLast Always empty thus no items to work with.", " MS throttleLatest At most one item signaled so no subsequent items to work with.", " C throttleLatest Always empty thus no items to work with.", " MS throttleWithTimeout At most one item signaled so no subsequent items to work with.", " C throttleWithTimeout Always empty thus no items to work with.", " C timeInterval Always empty thus no items to work with.", " C timestamp Always empty thus no items to work with.", "FO toCompletionStage Use [`firstStage`](#firstStage), [`lastStage`](#lastStage) or [`singleStage`](#singleStage).", "F toFlowable Would be no-op.", " M toList At most one element to collect. Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a list/collection.", " S toList One element to collect. Use [`map()`](#map) to transform into a list/collection.", " C toList Always empty. Use [`andThen()`](#andThen) to bring in a collection.", " M toMap At most one element to collect. Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a list/collection.", " S toMap One element to collect. Use [`map()`](#map) to transform into a list/collection.", " C toMap Always empty. Use [`andThen()`](#andThen) to bring in a collection.", " M toMultimap At most one element to collect. Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a list/collection.", " S toMultimap One element to collect. Use [`map()`](#map) to transform into a list/collection.", " C toMultimap Always empty. Use [`andThen()`](#andThen) to bring in a collection.", "FO toMaybe Use [`firstElement`](#firstElement), [`lastElement`](#lastElement) or [`singleElement`](#singleElement).", " M toMaybe Would be no-op.", " O toObservable Would be no-op.", "FO toSingle Use [`firstOrError`](#firstOrError), [`lastOrError`](#lastOrError) or [`singleOrError`](#singleOrError).", " S toSingle Would be no-op.", "FO toSingleDefault Use [`first`](#first), [`last`](#last) or [`single`](#single).", " M toSingleDefault Use [`defaultIfEmpty()`](#defaultIfEmpty).", " S toSingleDefault Would be no-op.", " M toSortedList At most one element to collect. Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a list/collection.", " S toSortedList One element to collect. Use [`map()`](#map) to transform into a list/collection.", " C toSortedList Always empty. Use [`andThen()`](#andThen) to bring in a collection.", " M window Use [`map()`](#map) and [`switchIfEmpty()`](#switchIfEmpty) to transform into a nested source.", " S window Use [`map()`](#map) to transform into a nested source.", " C window Always empty. Use [`andThen()`](#andThen) to bring in a nested source.", " MS withLatestFrom At most one element per source. Use [`zip()`](#zip).", " C withLatestFrom Always empty. Use [`merge()`](#merge).", "F wrap Use [`fromPublisher()`](#fromPublisher).", " C zip Use [`merge()`](#merge).", " C zipArray Use [`mergeArray()`](#mergeArray).", " C zipWith Use [`mergeWith()`](#mergeWith).", }; static final Map<String, Map<String, String>> NOTES_MAP; static { NOTES_MAP = new HashMap<>(); for (String s : NOTES) { char[] classes = s.substring(0, 5).trim().toCharArray(); int idx = s.indexOf(' ', 7); String method = s.substring(6, idx); String note = s.substring(idx).trim(); for (char c : classes) { NOTES_MAP.computeIfAbsent(method, v -> new HashMap<>()) .put(String.valueOf(c), note); } } } }
OperatorMatrixGenerator
java
google__dagger
java/dagger/testing/golden/GoldenFileRule.java
{ "start": 1153, "end": 6501 }
class ____ implements TestRule { /** The generated import used in the golden files */ private static final String GOLDEN_GENERATED_IMPORT = "import javax.annotation.processing.Generated;"; /** The generated import used with the current jdk version */ private static final String JDK_GENERATED_IMPORT = isBeforeJava9() ? "import javax.annotation.Generated;" : "import javax.annotation.processing.Generated;"; private static boolean isBeforeJava9() { try { Class.forName("java.lang.Module"); return false; } catch (ClassNotFoundException e) { return true; } } // Parameterized arguments in junit4 are added in brackets to the end of test methods, e.g. // `myTestMethod[testParam1=FOO,testParam2=BAR]`. This pattern captures theses into two separate // groups, `<GROUP1>[<GROUP2>]` to make it easier when generating the golden file name. private static final Pattern JUNIT_PARAMETERIZED_METHOD = Pattern.compile("(.*?)\\[(.*?)\\]"); private Description description; @Override public Statement apply(Statement base, Description description) { this.description = description; return base; } /** * Returns the golden file as a {@link Source} containing the file's content. * * <p>If the golden file does not exist, the returned file object contains an error message * pointing to the location of the missing golden file. This can be used with scripting tools to * output the correct golden file in the proper location. */ public Source goldenSource(String generatedFilePath) { return goldenSource(generatedFilePath, /* isKotlin= */ false); } /** * Returns the golden file as a {@link Source} containing the file's content. * * <p>If the golden file does not exist, the returned file object contains an error message * pointing to the location of the missing golden file. This can be used with scripting tools to * output the correct golden file in the proper location. */ public Source goldenSource(String generatedFilePath, boolean isKotlin) { // Note: we wrap the IOException in a RuntimeException so that this can be called from within // the lambda required by XProcessing's testing APIs. We could avoid this by calling this method // outside of the lambda, but that seems like an non-worthwile hit to readability. String qualifiedName = generatedFilePath.replace('/', '.'); try { return isKotlin ? Source.Companion.kotlin(generatedFilePath + ".kt", goldenFileContent(qualifiedName)) : Source.Companion.java(generatedFilePath, goldenFileContent(qualifiedName)); } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns the golden file as a {@link JavaFileObject} containing the file's content. * * If the golden file does not exist, the returned file object contain an error message pointing * to the location of the missing golden file. This can be used with scripting tools to output * the correct golden file in the proper location. */ public JavaFileObject goldenFile(String qualifiedName) throws IOException { return JavaFileObjects.forSourceLines(qualifiedName, goldenFileContent(qualifiedName)); } /** * Returns the golden file content. * * If the golden file does not exist, the returned content contains an error message pointing * to the location of the missing golden file. This can be used with scripting tools to output * the correct golden file in the proper location. */ private String goldenFileContent(String qualifiedName) throws IOException { String fileName = relativeGoldenFileName(description, qualifiedName); String resourceName = "goldens/" + fileName; URL url = description.getTestClass().getResource(resourceName); if (url == null) { url = description.getTestClass().getClassLoader().getResource(resourceName); } return url == null // If the golden file does not exist, create a fake file with a comment pointing to the // missing golden file. This is helpful for scripts that need to generate golden files from // the test failures. ? "// Error: Missing golden file for goldens/" + fileName // The goldens are generated using jdk 11, so we use this replacement to allow the // goldens to also work when compiling using jdk < 9. : Resources.toString(url, StandardCharsets.UTF_8) .replace(GOLDEN_GENERATED_IMPORT, JDK_GENERATED_IMPORT); } /** Returns the relative name for the golden file. */ private static String relativeGoldenFileName(Description description, String qualifiedName) { // If this is a parameterized test, the parameters will be appended to the end of the method // name. We use a matcher to separate them out for the golden file name. Matcher matcher = JUNIT_PARAMETERIZED_METHOD.matcher(description.getMethodName()); boolean isParameterized = matcher.find(); String methodName = isParameterized ? matcher.group(1) : description.getMethodName(); String fileName = isParameterized ? qualifiedName + "_" + matcher.group(2) : qualifiedName; return String.format( "%s/%s/%s", description.getTestClass().getSimpleName(), methodName, fileName); } }
GoldenFileRule
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/client/RestClient.java
{ "start": 42037, "end": 42235 }
interface ____<S extends RequestHeadersSpec<S>> extends UriSpec<S>, RequestHeadersSpec<S> { } /** * Contract for specifying request headers, body and URI for a request. */
RequestHeadersUriSpec
java
apache__spark
common/unsafe/src/main/java/org/apache/spark/sql/catalyst/util/CollationAwareUTF8String.java
{ "start": 1590, "end": 18083 }
class ____ { /** * The constant value to indicate that the match is not found when searching for a pattern * string in a target string. */ private static final int MATCH_NOT_FOUND = -1; /** * `COMBINED_ASCII_SMALL_I_COMBINING_DOT` is an internal representation of the combined * lowercase code point for ASCII lowercase letter i with an additional combining dot character * (U+0307). This integer value is not a valid code point itself, but rather an artificial code * point marker used to represent the two lowercase characters that are the result of converting * the uppercase Turkish dotted letter I with a combining dot character (U+0130) to lowercase. */ private static final int COMBINED_ASCII_SMALL_I_COMBINING_DOT = SpecialCodePointConstants.ASCII_SMALL_I << 16 | SpecialCodePointConstants.COMBINING_DOT; /** * Returns whether the target string starts with the specified prefix, starting from the * specified position (0-based index referring to character position in UTF8String), with respect * to the UTF8_LCASE collation. The method assumes that the prefix is already lowercased prior * to method call to avoid the overhead of lowercasing the same prefix string multiple times. * * @param target the string to be searched in * @param lowercasePattern the string to be searched for * @param startPos the start position for searching (in the target string) * @return whether the target string starts with the specified prefix in UTF8_LCASE */ private static boolean lowercaseMatchFrom( final UTF8String target, final UTF8String lowercasePattern, int startPos) { return lowercaseMatchLengthFrom(target, lowercasePattern, startPos) != MATCH_NOT_FOUND; } /** * Returns the length of the substring of the target string that starts with the specified * prefix, starting from the specified position (0-based index referring to character position * in UTF8String), with respect to the UTF8_LCASE collation. The method assumes that the * prefix is already lowercased. The method only considers the part of target string that * starts from the specified (inclusive) position (that is, the method does not look at UTF8 * characters of the target string at or after position `endPos`). If the prefix is not found, * MATCH_NOT_FOUND is returned. * * @param target the string to be searched in * @param lowercasePattern the string to be searched for * @param startPos the start position for searching (in the target string) * @return length of the target substring that starts with the specified prefix in lowercase */ private static int lowercaseMatchLengthFrom( final UTF8String target, final UTF8String lowercasePattern, int startPos) { assert startPos >= 0; // Use code point iterators for efficient string search. Iterator<Integer> targetIterator = target.codePointIterator(); Iterator<Integer> patternIterator = lowercasePattern.codePointIterator(); // Skip to startPos in the target string. for (int i = 0; i < startPos; ++i) { if (targetIterator.hasNext()) { targetIterator.next(); } else { return MATCH_NOT_FOUND; } } // Compare the characters in the target and pattern strings. int matchLength = 0, codePointBuffer = -1, targetCodePoint, patternCodePoint; while ((targetIterator.hasNext() || codePointBuffer != -1) && patternIterator.hasNext()) { if (codePointBuffer != -1) { targetCodePoint = codePointBuffer; codePointBuffer = -1; } else { // Use buffered lowercase code point iteration to handle one-to-many case mappings. targetCodePoint = getLowercaseCodePoint(targetIterator.next()); if (targetCodePoint == COMBINED_ASCII_SMALL_I_COMBINING_DOT) { targetCodePoint = SpecialCodePointConstants.ASCII_SMALL_I; codePointBuffer = SpecialCodePointConstants.COMBINING_DOT; } ++matchLength; } patternCodePoint = patternIterator.next(); if (targetCodePoint != patternCodePoint) { return MATCH_NOT_FOUND; } } // If the pattern string has more characters, or the match is found at the middle of a // character that maps to multiple characters in lowercase, then match is not found. if (patternIterator.hasNext() || codePointBuffer != -1) { return MATCH_NOT_FOUND; } // If all characters are equal, return the length of the match in the target string. return matchLength; } /** * Returns the position of the first occurrence of the pattern string in the target string, * starting from the specified position (0-based index referring to character position in * UTF8String), with respect to the UTF8_LCASE collation. The method assumes that the * pattern string is already lowercased prior to call. If the pattern is not found, * MATCH_NOT_FOUND is returned. * * @param target the string to be searched in * @param lowercasePattern the string to be searched for * @param startPos the start position for searching (in the target string) * @return the position of the first occurrence of pattern in target */ private static int lowercaseFind( final UTF8String target, final UTF8String lowercasePattern, int startPos) { assert startPos >= 0; for (int i = startPos; i <= target.numChars(); ++i) { if (lowercaseMatchFrom(target, lowercasePattern, i)) { return i; } } return MATCH_NOT_FOUND; } /** * Returns whether the target string ends with the specified suffix, ending at the specified * position (0-based index referring to character position in UTF8String), with respect to the * UTF8_LCASE collation. The method assumes that the suffix is already lowercased prior * to method call to avoid the overhead of lowercasing the same suffix string multiple times. * * @param target the string to be searched in * @param lowercasePattern the string to be searched for * @param endPos the end position for searching (in the target string) * @return whether the target string ends with the specified suffix in lowercase */ private static boolean lowercaseMatchUntil( final UTF8String target, final UTF8String lowercasePattern, int endPos) { return lowercaseMatchLengthUntil(target, lowercasePattern, endPos) != MATCH_NOT_FOUND; } /** * Returns the length of the substring of the target string that ends with the specified * suffix, ending at the specified position (0-based index referring to character position in * UTF8String), with respect to the UTF8_LCASE collation. The method assumes that the * suffix is already lowercased. The method only considers the part of target string that ends * at the specified (non-inclusive) position (that is, the method does not look at UTF8 * characters of the target string at or after position `endPos`). If the suffix is not found, * MATCH_NOT_FOUND is returned. * * @param target the string to be searched in * @param lowercasePattern the string to be searched for * @param endPos the end position for searching (in the target string) * @return length of the target substring that ends with the specified suffix in lowercase */ private static int lowercaseMatchLengthUntil( final UTF8String target, final UTF8String lowercasePattern, int endPos) { assert endPos >= 0; // Use code point iterators for efficient string search. Iterator<Integer> targetIterator = target.reverseCodePointIterator(); Iterator<Integer> patternIterator = lowercasePattern.reverseCodePointIterator(); // Skip to startPos in the target string. for (int i = endPos; i < target.numChars(); ++i) { if (targetIterator.hasNext()) { targetIterator.next(); } else { return MATCH_NOT_FOUND; } } // Compare the characters in the target and pattern strings. int matchLength = 0, codePointBuffer = -1, targetCodePoint, patternCodePoint; while ((targetIterator.hasNext() || codePointBuffer != -1) && patternIterator.hasNext()) { if (codePointBuffer != -1) { targetCodePoint = codePointBuffer; codePointBuffer = -1; } else { // Use buffered lowercase code point iteration to handle one-to-many case mappings. targetCodePoint = getLowercaseCodePoint(targetIterator.next()); if (targetCodePoint == COMBINED_ASCII_SMALL_I_COMBINING_DOT) { targetCodePoint = SpecialCodePointConstants.COMBINING_DOT; codePointBuffer = SpecialCodePointConstants.ASCII_SMALL_I; } ++matchLength; } patternCodePoint = patternIterator.next(); if (targetCodePoint != patternCodePoint) { return MATCH_NOT_FOUND; } } // If the pattern string has more characters, or the match is found at the middle of a // character that maps to multiple characters in lowercase, then match is not found. if (patternIterator.hasNext() || codePointBuffer != -1) { return MATCH_NOT_FOUND; } // If all characters are equal, return the length of the match in the target string. return matchLength; } /** * Returns the position of the last occurrence of the pattern string in the target string, * ending at the specified position (0-based index referring to character position in * UTF8String), with respect to the UTF8_LCASE collation. The method assumes that the * pattern string is already lowercased prior to call. If the pattern is not found, * MATCH_NOT_FOUND is returned. * * @param target the string to be searched in * @param lowercasePattern the string to be searched for * @param endPos the end position for searching (in the target string) * @return the position of the last occurrence of pattern in target */ private static int lowercaseRFind( final UTF8String target, final UTF8String lowercasePattern, int endPos) { assert endPos <= target.numChars(); for (int i = endPos; i >= 0; --i) { if (lowercaseMatchUntil(target, lowercasePattern, i)) { return i; } } return MATCH_NOT_FOUND; } /** * Lowercase UTF8String comparison used for UTF8_LCASE collation. This method uses lowercased * code points to compare the strings in a case-insensitive manner using ICU rules, taking into * account special rules for one-to-many case mappings (see: lowerCaseCodePoints). * * @param left The first UTF8String to compare. * @param right The second UTF8String to compare. * @return An integer representing the comparison result. */ public static int compareLowerCase(final UTF8String left, final UTF8String right) { // Only if both strings are ASCII, we can use faster comparison (no string allocations). if (left.isFullAscii() && right.isFullAscii()) { return compareLowerCaseAscii(left, right); } return compareLowerCaseSlow(left, right); } /** * Fast version of the `compareLowerCase` method, used when both arguments are ASCII strings. * * @param left The first ASCII UTF8String to compare. * @param right The second ASCII UTF8String to compare. * @return An integer representing the comparison result. */ private static int compareLowerCaseAscii(final UTF8String left, final UTF8String right) { int leftBytes = left.numBytes(), rightBytes = right.numBytes(); for (int curr = 0; curr < leftBytes && curr < rightBytes; curr++) { int lowerLeftByte = Character.toLowerCase(left.getByte(curr)); int lowerRightByte = Character.toLowerCase(right.getByte(curr)); if (lowerLeftByte != lowerRightByte) { return lowerLeftByte - lowerRightByte; } } return leftBytes - rightBytes; } /** * Slow version of the `compareLowerCase` method, used when both arguments are non-ASCII strings. * * @param left The first non-ASCII UTF8String to compare. * @param right The second non-ASCII UTF8String to compare. * @return An integer representing the comparison result. */ private static int compareLowerCaseSlow(final UTF8String left, final UTF8String right) { return lowerCaseCodePoints(left).binaryCompare(lowerCaseCodePoints(right)); } /** * Performs string replacement for ICU collations by searching for instances of the search * string in the `target` string, with respect to the specified collation, and then replacing * them with the replace string. The method returns a new UTF8String with all instances of the * search string replaced using the replace string. Similar to UTF8String.findInSet behavior * used for UTF8_BINARY, the method returns the `target` string if the `search` string is empty. * * @param target the string to be searched in * @param search the string to be searched for * @param replace the string to be used as replacement * @param collationId the collation ID to use for string search * @return the position of the first occurrence of `match` in `set` */ public static UTF8String replace(final UTF8String target, final UTF8String search, final UTF8String replace, final int collationId) { // This collation aware implementation is based on existing implementation on UTF8String if (target.numBytes() == 0 || search.numBytes() == 0) { return target; } String targetStr = target.toValidString(); String searchStr = search.toValidString(); StringSearch stringSearch = CollationFactory.getStringSearch(targetStr, searchStr, collationId); StringBuilder sb = new StringBuilder(); int start = 0; int matchStart = stringSearch.first(); while (matchStart != StringSearch.DONE) { sb.append(targetStr, start, matchStart); sb.append(replace.toValidString()); start = matchStart + stringSearch.getMatchLength(); matchStart = stringSearch.next(); } sb.append(targetStr, start, targetStr.length()); return UTF8String.fromString(sb.toString()); } /** * Performs string replacement for UTF8_LCASE collation by searching for instances of the search * string in the target string, with respect to lowercased string versions, and then replacing * them with the replace string. The method returns a new UTF8String with all instances of the * search string replaced using the replace string. Similar to UTF8String.findInSet behavior * used for UTF8_BINARY, the method returns the `target` string if the `search` string is empty. * * @param target the string to be searched in * @param search the string to be searched for * @param replace the string to be used as replacement * @return the position of the first occurrence of `match` in `set` */ public static UTF8String lowercaseReplace(final UTF8String target, final UTF8String search, final UTF8String replace) { if (target.numBytes() == 0 || search.numBytes() == 0) { return target; } UTF8String lowercaseSearch = lowerCaseCodePoints(search); int start = 0; int end = lowercaseFind(target, lowercaseSearch, start); if (end == -1) { // Search string was not found, so string is unchanged. return target; } // At least one match was found. Estimate space needed for result. // The 16x multiplier here is chosen to match commons-lang3's implementation. int increase = Math.max(0, replace.numBytes() - search.numBytes()) * 16; final UTF8StringBuilder buf = new UTF8StringBuilder(target.numBytes() + increase); while (end != -1) { buf.append(target.substring(start, end)); buf.append(replace); // Update character positions start = end + lowercaseMatchLengthFrom(target, lowercaseSearch, end); end = lowercaseFind(target, lowercaseSearch, start); } buf.append(target.substring(start, target.numChars())); return buf.build(); } /** * Convert the input string to uppercase using the ICU root locale rules. * * @param target the input string * @return the uppercase string */ public static UTF8String toUpperCase(final UTF8String target) { if (target.isFullAscii()) return target.toUpperCaseAscii(); return toUpperCaseSlow(target); } private static UTF8String toUpperCaseSlow(final UTF8String target) { // Note: In order to achieve the desired behavior, we use the ICU UCharacter
CollationAwareUTF8String
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/fulltext/FullTextFunction.java
{ "start": 4288, "end": 4615 }
class ____ full-text functions that use ES queries to match documents. * These functions needs to be pushed down to Lucene queries to be executed - there’s no Evaluator for them, but depend on * {@link org.elasticsearch.xpack.esql.optimizer.LocalPhysicalPlanOptimizer} to rewrite them into Lucene queries. */ public abstract
for
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/fault/NetworkPartitionFaultController.java
{ "start": 1023, "end": 1540 }
class ____ implements TaskController { private final List<Set<String>> partitionSets; public NetworkPartitionFaultController(List<Set<String>> partitionSets) { this.partitionSets = partitionSets; } @Override public Set<String> targetNodes(Topology topology) { Set<String> targetNodes = new HashSet<>(); for (Set<String> partitionSet : partitionSets) { targetNodes.addAll(partitionSet); } return targetNodes; } }
NetworkPartitionFaultController
java
google__auto
common/src/test/java/com/google/auto/common/MoreElementsTest.java
{ "start": 14690, "end": 14925 }
class ____<B extends Builder<B>> extends AbstractMessageLite.Builder { @Override @SuppressWarnings("unchecked") B internalMergeFrom(AbstractMessageLite other) { return (B) this; } } } static
Builder
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java
{ "start": 16521, "end": 17773 }
class ____ construct, not {@code null}. * @param args the array of arguments, {@code null} treated as empty. * @param parameterTypes the array of parameter types, {@code null} treated as empty. * @return new instance of {@code cls}, not {@code null}. * @throws NullPointerException Thrown if {@code cls} is {@code null}. * @throws NoSuchMethodException Thrown if a matching constructor cannot be found. * @throws IllegalAccessException Thrown if the found {@code Constructor} is enforcing Java language access control and the underlying constructor is * inaccessible. * @throws IllegalArgumentException Thrown if: * <ul> * <li>the number of actual and formal parameters differ; or</li> * <li>an unwrapping conversion for primitive arguments fails; or</li> * <li>after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a * method invocation conversion; if this constructor pertains to an
to
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/records/impl/pb/CountersPBImpl.java
{ "start": 1525, "end": 6091 }
class ____ extends ProtoBase<CountersProto> implements Counters { CountersProto proto = CountersProto.getDefaultInstance(); CountersProto.Builder builder = null; boolean viaProto = false; private Map<String, CounterGroup> counterGroups = null; public CountersPBImpl() { builder = CountersProto.newBuilder(); } public CountersPBImpl(CountersProto proto) { this.proto = proto; viaProto = true; } public CountersProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void mergeLocalToBuilder() { if (this.counterGroups != null) { addCounterGroupsToProto(); } } private void mergeLocalToProto() { if (viaProto) maybeInitBuilder(); mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = CountersProto.newBuilder(proto); } viaProto = false; } @Override public Map<String, CounterGroup> getAllCounterGroups() { initCounterGroups(); return this.counterGroups; } @Override public CounterGroup getCounterGroup(String key) { initCounterGroups(); return this.counterGroups.get(key); } @Override public Counter getCounter(Enum<?> key) { CounterGroup group = getCounterGroup(key.getDeclaringClass().getName()); return group == null ? null : group.getCounter(key.name()); } @Override public void incrCounter(Enum<?> key, long amount) { String groupName = key.getDeclaringClass().getName(); if (getCounterGroup(groupName) == null) { CounterGroup cGrp = new CounterGroupPBImpl(); cGrp.setName(groupName); cGrp.setDisplayName(groupName); setCounterGroup(groupName, cGrp); } if (getCounterGroup(groupName).getCounter(key.name()) == null) { Counter c = new CounterPBImpl(); c.setName(key.name()); c.setDisplayName(key.name()); c.setValue(0l); getCounterGroup(groupName).setCounter(key.name(), c); } Counter counter = getCounterGroup(groupName).getCounter(key.name()); counter.setValue(counter.getValue() + amount); } private void initCounterGroups() { if (this.counterGroups != null) { return; } CountersProtoOrBuilder p = viaProto ? proto : builder; List<StringCounterGroupMapProto> list = p.getCounterGroupsList(); this.counterGroups = new HashMap<String, CounterGroup>(); for (StringCounterGroupMapProto c : list) { this.counterGroups.put(c.getKey(), convertFromProtoFormat(c.getValue())); } } @Override public void addAllCounterGroups(final Map<String, CounterGroup> counterGroups) { if (counterGroups == null) return; initCounterGroups(); this.counterGroups.putAll(counterGroups); } private void addCounterGroupsToProto() { maybeInitBuilder(); builder.clearCounterGroups(); if (counterGroups == null) return; Iterable<StringCounterGroupMapProto> iterable = new Iterable<StringCounterGroupMapProto>() { @Override public Iterator<StringCounterGroupMapProto> iterator() { return new Iterator<StringCounterGroupMapProto>() { Iterator<String> keyIter = counterGroups.keySet().iterator(); @Override public void remove() { throw new UnsupportedOperationException(); } @Override public StringCounterGroupMapProto next() { String key = keyIter.next(); return StringCounterGroupMapProto.newBuilder().setKey(key).setValue(convertToProtoFormat(counterGroups.get(key))).build(); } @Override public boolean hasNext() { return keyIter.hasNext(); } }; } }; builder.addAllCounterGroups(iterable); } @Override public void setCounterGroup(String key, CounterGroup val) { initCounterGroups(); this.counterGroups.put(key, val); } @Override public void removeCounterGroup(String key) { initCounterGroups(); this.counterGroups.remove(key); } @Override public void clearCounterGroups() { initCounterGroups(); this.counterGroups.clear(); } private CounterGroupPBImpl convertFromProtoFormat(CounterGroupProto p) { return new CounterGroupPBImpl(p); } private CounterGroupProto convertToProtoFormat(CounterGroup t) { return ((CounterGroupPBImpl)t).getProto(); } }
CountersPBImpl
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/multipart/FormParserFactory.java
{ "start": 600, "end": 1486 }
class ____ { private final ParserDefinition[] parserDefinitions; FormParserFactory(final List<ParserDefinition> parserDefinitions) { this.parserDefinitions = parserDefinitions.toArray(new ParserDefinition[0]); } /** * Creates a form data parser for this request. * * @param exchange The exchange * @param fileFormNames * @return A form data parser, or null if there is no parser registered for the request content type */ public FormDataParser createParser(final ResteasyReactiveRequestContext exchange, Set<String> fileFormNames) { for (int i = 0; i < parserDefinitions.length; ++i) { FormDataParser parser = parserDefinitions[i].create(exchange, fileFormNames); if (parser != null) { return parser; } } return null; } public
FormParserFactory
java
apache__camel
components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchProducer.java
{ "start": 25376, "end": 26715 }
class ____ { private final Exchange exchange; private final AsyncCallback callback; private final ElasticsearchTransport transport; private final boolean configIndexName; private final boolean configWaitForActiveShards; ActionContext(Exchange exchange, AsyncCallback callback, ElasticsearchTransport transport, boolean configIndexName, boolean configWaitForActiveShards) { this.exchange = exchange; this.callback = callback; this.transport = transport; this.configIndexName = configIndexName; this.configWaitForActiveShards = configWaitForActiveShards; } ElasticsearchTransport getTransport() { return transport; } ElasticsearchAsyncClient getClient() { return new ElasticsearchAsyncClient(transport); } boolean isConfigIndexName() { return configIndexName; } boolean isConfigWaitForActiveShards() { return configWaitForActiveShards; } Exchange getExchange() { return exchange; } AsyncCallback getCallback() { return callback; } Message getMessage() { return exchange.getIn(); } } }
ActionContext
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/link/OneToOneLinkTest.java
{ "start": 1041, "end": 3186 }
class ____ { @Test @SkipForDialect(dialectClass = OracleDialect.class, reason = "oracle12c returns time in getDate. For now, skip.") @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsNoColumnInsert.class) public void testOneToOneViaAssociationTable(SessionFactoryScope scope) { scope.inTransaction( session -> { Person p = new Person(); p.setName( "Gavin King" ); p.setDob( new Date() ); Employee e = new Employee(); p.setEmployee( e ); e.setPerson( p ); session.persist( p ); } ); scope.inTransaction( session -> { Employee e = (Employee) session.createQuery( "from Employee e where e.person.name like 'Gavin%'" ) .uniqueResult(); assertEquals( e.getPerson().getName(), "Gavin King" ); assertFalse( Hibernate.isInitialized( e.getPerson() ) ); assertNull( e.getPerson().getCustomer() ); session.clear(); e = (Employee) session.createQuery( "from Employee e where e.person.dob = :date" ) .setParameter( "date", new Date(), StandardBasicTypes.DATE ) .uniqueResult(); assertEquals( e.getPerson().getName(), "Gavin King" ); assertFalse( Hibernate.isInitialized( e.getPerson() ) ); assertNull( e.getPerson().getCustomer() ); session.clear(); } ); scope.inTransaction( session -> { Employee e = (Employee) session.createQuery( "from Employee e join fetch e.person p left join fetch p.customer" ) .uniqueResult(); assertTrue( Hibernate.isInitialized( e.getPerson() ) ); assertNull( e.getPerson().getCustomer() ); Customer c = new Customer(); e.getPerson().setCustomer( c ); c.setPerson( e.getPerson() ); } ); scope.inTransaction( session -> { Employee e = (Employee) session.createQuery( "from Employee e join fetch e.person p left join fetch p.customer" ) .uniqueResult(); assertTrue( Hibernate.isInitialized( e.getPerson() ) ); assertTrue( Hibernate.isInitialized( e.getPerson().getCustomer() ) ); assertNotNull( e.getPerson().getCustomer() ); session.remove( e ); } ); } }
OneToOneLinkTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/test/java/org/apache/hadoop/yarn/server/sharedcachemanager/DummyAppChecker.java
{ "start": 1168, "end": 1489 }
class ____ extends AppChecker { @Override @Private public boolean isApplicationActive(ApplicationId id) throws YarnException { return false; } @Override @Private public Collection<ApplicationId> getActiveApplications() throws YarnException { return new ArrayList<ApplicationId>(); } }
DummyAppChecker
java
google__dagger
javatests/dagger/functional/generictypes/GenericComponent.java
{ "start": 1089, "end": 1658 }
interface ____ { ReferencesGeneric referencesGeneric(); GenericDoubleReferences<A> doubleGenericA(); GenericDoubleReferences<B> doubleGenericB(); ComplexGenerics complexGenerics(); GenericNoDeps<A> noDepsA(); GenericNoDeps<B> noDepsB(); void injectA(GenericChild<A> childA); void injectB(GenericChild<B> childB); Exposed exposed(); PublicSubclass publicSubclass(); Iterable<Integer> iterableInt(); Iterable<Double> iterableDouble(); Provider<List<String>> stringsProvider(); // b/71595104 // b/71595104 @Module abstract
GenericComponent
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/GelfLayout.java
{ "start": 28273, "end": 31445 }
class ____ implements TriConsumer<String, Object, StringBuilder> { private final ListChecker checker; private final String prefix; FieldWriter(final ListChecker checker, final String prefix) { this.checker = checker; this.prefix = prefix; } @Override public void accept(final String key, final Object value, final StringBuilder stringBuilder) { final String stringValue = String.valueOf(value); if (checker.check(key) && (Strings.isNotEmpty(stringValue) || !omitEmptyFields)) { stringBuilder.append(QU); JsonUtils.quoteAsString(Strings.concat(prefix, key), stringBuilder); stringBuilder.append("\":\""); JsonUtils.quoteAsString(toNullSafeString(stringValue), stringBuilder); stringBuilder.append(QC); } } public ListChecker getChecker() { return checker; } } private static final ThreadLocal<StringBuilder> messageStringBuilder = new ThreadLocal<>(); private static StringBuilder getMessageStringBuilder() { StringBuilder result = messageStringBuilder.get(); if (result == null) { result = new StringBuilder(DEFAULT_STRING_BUILDER_SIZE); messageStringBuilder.set(result); } result.setLength(0); return result; } private static CharSequence toNullSafeString(final CharSequence s) { return s == null ? Strings.EMPTY : s; } /** * Non-private to make it accessible from unit test. */ static CharSequence formatTimestamp(final long timeMillis) { if (timeMillis < 1000) { return "0"; } final StringBuilder builder = getTimestampStringBuilder(); builder.append(timeMillis); builder.insert(builder.length() - 3, '.'); return builder; } private static final ThreadLocal<StringBuilder> timestampStringBuilder = new ThreadLocal<>(); private static StringBuilder getTimestampStringBuilder() { StringBuilder result = timestampStringBuilder.get(); if (result == null) { result = new StringBuilder(20); timestampStringBuilder.set(result); } result.setLength(0); return result; } /** * http://en.wikipedia.org/wiki/Syslog#Severity_levels */ private int formatLevel(final Level level) { return Severity.getSeverity(level).getCode(); } /** * Non-private to make it accessible from unit test. */ @SuppressFBWarnings( value = "INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE", justification = "Log4j prints stacktraces only to logs, which should be private.") static CharSequence formatThrowable(final Throwable throwable) { // stack traces are big enough to provide a reasonably large initial capacity here final StringWriter sw = new StringWriter(2048); final PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); pw.flush(); return sw.getBuffer(); } }
FieldWriter
java
junit-team__junit5
documentation/src/test/java/example/TestingAStackDemo.java
{ "start": 1012, "end": 1597 }
class ____ { Stack<Object> stack; @BeforeEach void createNewStack() { stack = new Stack<>(); } @Test @DisplayName("is empty") void isEmpty() { assertTrue(stack.isEmpty()); } @Test @DisplayName("throws EmptyStackException when popped") void throwsExceptionWhenPopped() { assertThrows(EmptyStackException.class, stack::pop); } @Test @DisplayName("throws EmptyStackException when peeked") void throwsExceptionWhenPeeked() { assertThrows(EmptyStackException.class, stack::peek); } @Nested @DisplayName("after pushing an element")
WhenNew
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/jaxrs/RequestImpl.java
{ "start": 648, "end": 8307 }
class ____ implements Request { private final ResteasyReactiveRequestContext requestContext; private final String httpMethod; private String varyHeader; public RequestImpl(ResteasyReactiveRequestContext requestContext) { this.requestContext = requestContext; this.httpMethod = requestContext.serverRequest().getRequestMethod(); } @Override public String getMethod() { return requestContext.serverRequest().getRequestMethod(); } private boolean isRfc7232preconditions() { return true;//todo: do we need config for this? } @Override public Variant selectVariant(List<Variant> variants) throws IllegalArgumentException { if (variants == null || variants.size() == 0) throw new IllegalArgumentException("Variant list must not be empty"); ServerDrivenNegotiation negotiation = new ServerDrivenNegotiation(); MultivaluedMap<String, String> requestHeaders = requestContext.getHttpHeaders().getRequestHeaders(); negotiation.setAcceptHeaders(requestHeaders.get(HttpHeaders.ACCEPT)); negotiation.setAcceptCharsetHeaders(requestHeaders.get(HttpHeaders.ACCEPT_CHARSET)); negotiation.setAcceptEncodingHeaders(requestHeaders.get(HttpHeaders.ACCEPT_ENCODING)); negotiation.setAcceptLanguageHeaders(requestHeaders.get(HttpHeaders.ACCEPT_LANGUAGE)); varyHeader = AbstractResponseBuilder.createVaryHeader(variants); requestContext.serverResponse().setResponseHeader(HttpHeaders.VARY, varyHeader); //response.getOutputHeaders().add(VARY, varyHeader); return negotiation.getBestMatch(variants); } private List<EntityTag> convertEtag(List<String> tags) { ArrayList<EntityTag> result = new ArrayList<EntityTag>(); for (String tag : tags) { String[] split = tag.split(","); for (String etag : split) { result.add(EntityTag.valueOf(etag.trim())); } } return result; } private Response.ResponseBuilder ifMatch(List<EntityTag> ifMatch, EntityTag eTag) { boolean match = false; for (EntityTag tag : ifMatch) { if (tag.equals(eTag) || tag.getValue().equals("*")) { match = true; break; } } if (match) return null; return Response.status(Response.Status.PRECONDITION_FAILED).tag(eTag); } private Response.ResponseBuilder ifNoneMatch(List<EntityTag> ifMatch, EntityTag eTag) { boolean match = false; for (EntityTag tag : ifMatch) { if (tag.equals(eTag) || tag.getValue().equals("*")) { match = true; break; } } if (match) { if ("GET".equals(httpMethod) || "HEAD".equals(httpMethod)) { return Response.notModified(eTag); } return Response.status(Response.Status.PRECONDITION_FAILED).tag(eTag); } return null; } @Override public Response.ResponseBuilder evaluatePreconditions(EntityTag eTag) { if (eTag == null) throw new IllegalArgumentException("ETag was null"); Response.ResponseBuilder builder = null; List<String> ifMatch = requestContext.getHttpHeaders().getRequestHeaders().get(HttpHeaders.IF_MATCH); if (ifMatch != null && ifMatch.size() > 0) { builder = ifMatch(convertEtag(ifMatch), eTag); } if (builder == null) { List<String> ifNoneMatch = requestContext.getHttpHeaders().getRequestHeaders().get(HttpHeaders.IF_NONE_MATCH); if (ifNoneMatch != null && ifNoneMatch.size() > 0) { builder = ifNoneMatch(convertEtag(ifNoneMatch), eTag); } } if (builder != null) { builder.tag(eTag); } if (builder != null && varyHeader != null) builder.header(HttpHeaders.VARY, varyHeader); return builder; } private Response.ResponseBuilder ifModifiedSince(String strDate, Date lastModified) { Date date = DateUtil.parseDate(strDate); if (date.getTime() >= millisecondsWithSecondsPrecision(lastModified)) { return Response.notModified(); } return null; } private Response.ResponseBuilder ifUnmodifiedSince(String strDate, Date lastModified) { Date date = DateUtil.parseDate(strDate); if (date.getTime() >= millisecondsWithSecondsPrecision(lastModified)) { return null; } return Response.status(Response.Status.PRECONDITION_FAILED).lastModified(lastModified); } /** * We must compare header dates (seconds-precision) with dates that have the same precision, * otherwise they may include milliseconds and they will never match the Last-Modified * values that we generate from them (since we drop their milliseconds when we write the headers) */ private long millisecondsWithSecondsPrecision(Date lastModified) { return (lastModified.getTime() / 1000) * 1000; } @Override public Response.ResponseBuilder evaluatePreconditions(Date lastModified) { if (lastModified == null) throw new IllegalArgumentException("Param cannot be null"); Response.ResponseBuilder builder = null; MultivaluedMap<String, String> headers = requestContext.getHttpHeaders().getRequestHeaders(); String ifModifiedSince = headers.getFirst(HttpHeaders.IF_MODIFIED_SINCE); if (ifModifiedSince != null && (!isRfc7232preconditions() || (!headers.containsKey(HttpHeaders.IF_NONE_MATCH)))) { builder = ifModifiedSince(ifModifiedSince, lastModified); } if (builder == null) { String ifUnmodifiedSince = headers.getFirst(HttpHeaders.IF_UNMODIFIED_SINCE); if (ifUnmodifiedSince != null && (!isRfc7232preconditions() || (!headers.containsKey(HttpHeaders.IF_MATCH)))) { builder = ifUnmodifiedSince(ifUnmodifiedSince, lastModified); } } if (builder != null && varyHeader != null) builder.header(HttpHeaders.VARY, varyHeader); return builder; } @Override public Response.ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag eTag) { if (lastModified == null) throw new IllegalArgumentException("Last modified was null"); if (eTag == null) throw new IllegalArgumentException("etag was null"); Response.ResponseBuilder rtn = null; Response.ResponseBuilder lastModifiedBuilder = evaluatePreconditions(lastModified); Response.ResponseBuilder etagBuilder = evaluatePreconditions(eTag); if (lastModifiedBuilder == null && etagBuilder == null) rtn = null; else if (lastModifiedBuilder != null && etagBuilder == null) rtn = lastModifiedBuilder; else if (lastModifiedBuilder == null && etagBuilder != null) rtn = etagBuilder; else { rtn = lastModifiedBuilder; rtn.tag(eTag); } if (rtn != null && varyHeader != null) rtn.header(HttpHeaders.VARY, varyHeader); return rtn; } @Override public Response.ResponseBuilder evaluatePreconditions() { List<String> ifMatch = requestContext.getHttpHeaders().getRequestHeaders().get(HttpHeaders.IF_MATCH); if (ifMatch == null || ifMatch.size() == 0) { return null; } return Response.status(Response.Status.PRECONDITION_FAILED); } }
RequestImpl
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/StatusAssertionTests.java
{ "start": 2102, "end": 3319 }
class ____ { private final WebTestClient testClient = MockMvcWebTestClient.bindToController(new StatusController()).build(); @Test void statusInt() { testClient.get().uri("/teaPot").exchange().expectStatus().isEqualTo(EXPECTATION_FAILED.value()); testClient.get().uri("/created").exchange().expectStatus().isEqualTo(CREATED.value()); testClient.get().uri("/createdWithComposedAnnotation").exchange().expectStatus().isEqualTo(CREATED.value()); testClient.get().uri("/badRequest").exchange().expectStatus().isEqualTo(BAD_REQUEST.value()); testClient.get().uri("/throwsException").exchange().expectStatus().isEqualTo(EXPECTATION_FAILED.value()); } @Test void httpStatus() { testClient.get().uri("/created").exchange().expectStatus().isCreated(); testClient.get().uri("/createdWithComposedAnnotation").exchange().expectStatus().isCreated(); testClient.get().uri("/badRequest").exchange().expectStatus().isBadRequest(); } @Test void matcher() { testClient.get().uri("/badRequest").exchange().expectStatus() .value(status -> MatcherAssert.assertThat(status, equalTo(BAD_REQUEST.value()))); } @RequestMapping @ResponseStatus @Retention(RetentionPolicy.RUNTIME) @
StatusAssertionTests
java
redisson__redisson
redisson/src/test/java/org/redisson/RedissonSetTest.java
{ "start": 725, "end": 30254 }
class ____ implements Serializable { private Long lng; public Long getLng() { return lng; } public void setLng(Long lng) { this.lng = lng; } } @Test public void testContainsEach() { RSet<Integer> set = redisson.getSet("list", IntegerCodec.INSTANCE); set.add(0); set.add(1); assertThat(set.containsEach(Collections.emptySet())).isEmpty(); assertThat(set.containsEach(Arrays.asList(0, 1))) .hasSize(2) .containsOnly(0, 1); assertThat(set.containsEach(Arrays.asList(0, 1, 2))) .hasSize(2) .containsOnly(0, 1); assertThat(set.containsEach(Arrays.asList(0, 1, 0, 2))) .hasSize(3) .containsOnly(0, 1, 0); assertThat(set.containsEach(Arrays.asList(2, 3, 4))) .hasSize(0); } @Test public void testRemoveAllCounted() { RSet<Integer> set = redisson.getSet("list", IntegerCodec.INSTANCE); set.add(0); set.add(1); set.add(2); set.add(3); assertThat(set.removeAllCounted(Arrays.asList(1, 2, 3, 4, 5))).isEqualTo(3); } @Test public void testTryAdd() { RSet<String> set = redisson.getSet("list", IntegerCodec.INSTANCE); Set<String> names = new HashSet<>(); int elements = 200000; for (int i = 0; i < elements; i++) { names.add("name" + i); } boolean s = set.tryAdd(names.toArray(new String[]{})); assertThat(s).isTrue(); assertThat(set.size()).isEqualTo(elements); Set<String> names2 = new HashSet<>(); for (int i = elements+1; i < elements + 10000; i++) { names2.add("name" + i); } names2.add("name10"); boolean r = set.tryAdd(names2.toArray(new String[]{})); assertThat(r).isFalse(); assertThat(set.size()).isEqualTo(elements); } @Test public void testSortOrder() { RSet<Integer> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add(1); list.add(2); list.add(3); Set<Integer> descSort = list.readSort(SortOrder.DESC); assertThat(descSort).containsExactly(3, 2, 1); Set<Integer> ascSort = list.readSort(SortOrder.ASC); assertThat(ascSort).containsExactly(1, 2, 3); } @Test public void testSortOrderLimit() { RSet<Integer> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add(1); list.add(2); list.add(3); Set<Integer> descSort = list.readSort(SortOrder.DESC, 1, 2); assertThat(descSort).containsExactly(2, 1); Set<Integer> ascSort = list.readSort(SortOrder.ASC, 1, 2); assertThat(ascSort).containsExactly(2, 3); } @Test public void testSortOrderByPattern() { RSet<Integer> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add(1); list.add(2); list.add(3); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(3); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(2); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(1); Set<Integer> descSort = list.readSort("test*", SortOrder.DESC); assertThat(descSort).containsExactly(1, 2, 3); Set<Integer> ascSort = list.readSort("test*", SortOrder.ASC); assertThat(ascSort).containsExactly(3, 2, 1); } @Test public void testSortOrderByPatternLimit() { RSet<Integer> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add(1); list.add(2); list.add(3); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(3); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(2); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(1); Set<Integer> descSort = list.readSort("test*", SortOrder.DESC, 1, 2); assertThat(descSort).containsExactly(2, 3); Set<Integer> ascSort = list.readSort("test*", SortOrder.ASC, 1, 2); assertThat(ascSort).containsExactly(2, 1); } @Test public void testSortOrderByPatternGet() { RSet<String> list = redisson.getSet("list", StringCodec.INSTANCE); list.add("1"); list.add("2"); list.add("3"); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(1); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(2); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(3); redisson.getBucket("tester1", StringCodec.INSTANCE).set("obj1"); redisson.getBucket("tester2", StringCodec.INSTANCE).set("obj2"); redisson.getBucket("tester3", StringCodec.INSTANCE).set("obj3"); Collection<String> descSort = list.readSort("test*", Arrays.asList("tester*"), SortOrder.DESC); assertThat(descSort).containsExactly("obj3", "obj2", "obj1"); Collection<String> ascSort = list.readSort("test*", Arrays.asList("tester*"), SortOrder.ASC); assertThat(ascSort).containsExactly("obj1", "obj2", "obj3"); } @Test public void testSortOrderByPatternGetLimit() { RSet<String> list = redisson.getSet("list", StringCodec.INSTANCE); list.add("1"); list.add("2"); list.add("3"); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(1); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(2); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(3); redisson.getBucket("tester1", StringCodec.INSTANCE).set("obj1"); redisson.getBucket("tester2", StringCodec.INSTANCE).set("obj2"); redisson.getBucket("tester3", StringCodec.INSTANCE).set("obj3"); Collection<String> descSort = list.readSort("test*", Arrays.asList("tester*"), SortOrder.DESC, 1, 2); assertThat(descSort).containsExactly("obj2", "obj1"); Collection<String> ascSort = list.readSort("test*", Arrays.asList("tester*"), SortOrder.ASC, 1, 2); assertThat(ascSort).containsExactly("obj2", "obj3"); } @Test public void testSortOrderAlpha(){ RSet<String> set = redisson.getSet("list", StringCodec.INSTANCE); set.add("1"); set.add("3"); set.add("12"); assertThat(set.readSortAlpha(SortOrder.ASC)) .containsExactly("1", "12", "3"); assertThat(set.readSortAlpha(SortOrder.DESC)) .containsExactly("3", "12", "1"); } @Test public void testSortOrderLimitAlpha(){ RSet<String> set = redisson.getSet("list", StringCodec.INSTANCE); set.add("1"); set.add("3"); set.add("12"); assertThat(set.readSortAlpha(SortOrder.DESC, 0, 2)) .containsExactly("3", "12"); assertThat(set.readSortAlpha(SortOrder.DESC, 1, 2)) .containsExactly("12", "1"); } @Test public void testSortOrderByPatternAlpha(){ RSet<Integer> set = redisson.getSet("list", IntegerCodec.INSTANCE); set.add(1); set.add(2); set.add(3); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(12); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(3); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(1); Collection<Integer> descSort = set .readSortAlpha("test*", SortOrder.DESC); assertThat(descSort).containsExactly(2, 1, 3); Collection<Integer> ascSort = set .readSortAlpha("test*", SortOrder.ASC); assertThat(ascSort).containsExactly(3, 1, 2); } @Test public void testSortOrderByPatternAlphaLimit(){ RSet<Integer> set = redisson.getSet("list", IntegerCodec.INSTANCE); set.add(1); set.add(2); set.add(3); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(12); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(3); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(1); Collection<Integer> descSort = set .readSortAlpha("test*", SortOrder.DESC,1, 2); assertThat(descSort).containsExactly(1, 3); Collection<Integer> ascSort = set .readSortAlpha("test*", SortOrder.ASC,1, 2); assertThat(ascSort).containsExactly(1, 2); } @Test public void testSortOrderByPatternGetAlpha() { RSet<String> set = redisson.getSet("list", StringCodec.INSTANCE); set.add("1"); set.add("2"); set.add("3"); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(12); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(3); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(1); redisson.getBucket("tester1", StringCodec.INSTANCE).set("obj1"); redisson.getBucket("tester2", StringCodec.INSTANCE).set("obj2"); redisson.getBucket("tester3", StringCodec.INSTANCE).set("obj3"); Collection<String> descSort = set .readSortAlpha("test*", Arrays.asList("tester*"), SortOrder.DESC); assertThat(descSort).containsExactly("obj2", "obj1", "obj3"); Collection<String> ascSort = set .readSortAlpha("test*", Arrays.asList("tester*"), SortOrder.ASC); assertThat(ascSort).containsExactly("obj3", "obj1", "obj2"); } @Test public void testSortOrderByPatternGetAlphaLimit() { RSet<String> set = redisson.getSet("list", StringCodec.INSTANCE); set.add("1"); set.add("2"); set.add("3"); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(12); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(3); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(1); redisson.getBucket("tester1", StringCodec.INSTANCE).set("obj1"); redisson.getBucket("tester2", StringCodec.INSTANCE).set("obj2"); redisson.getBucket("tester3", StringCodec.INSTANCE).set("obj3"); Collection<String> descSort = set .readSortAlpha("test*", Arrays.asList("tester*"), SortOrder.DESC,1, 2); assertThat(descSort).containsExactly("obj1", "obj3"); Collection<String> ascSort = set .readSortAlpha("test*", Arrays.asList("tester*"), SortOrder.ASC,1, 2); assertThat(ascSort).containsExactly("obj1", "obj2"); } @Test public void testSortTo() { RSet<String> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add("1"); list.add("2"); list.add("3"); assertThat(list.sortTo("test3", SortOrder.DESC)).isEqualTo(3); RList<String> list2 = redisson.getList("test3", StringCodec.INSTANCE); assertThat(list2).containsExactly("3", "2", "1"); assertThat(list.sortTo("test4", SortOrder.ASC)).isEqualTo(3); RList<String> list3 = redisson.getList("test4", StringCodec.INSTANCE); assertThat(list3).containsExactly("1", "2", "3"); } @Test public void testSortToLimit() { RSet<Integer> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add(1); list.add(2); list.add(3); assertThat(list.sortTo("test3", SortOrder.DESC, 1, 2)).isEqualTo(2); RList<String> list2 = redisson.getList("test3", StringCodec.INSTANCE); assertThat(list2).containsExactly("2", "1"); assertThat(list.sortTo("test4", SortOrder.ASC, 1, 2)).isEqualTo(2); RList<String> list3 = redisson.getList("test4", StringCodec.INSTANCE); assertThat(list3).containsExactly("2", "3"); } @Test public void testSortToByPattern() { RSet<Integer> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add(1); list.add(2); list.add(3); redisson.getBucket("test1", IntegerCodec.INSTANCE).set(3); redisson.getBucket("test2", IntegerCodec.INSTANCE).set(2); redisson.getBucket("test3", IntegerCodec.INSTANCE).set(1); assertThat(list.sortTo("tester3", "test*", SortOrder.DESC, 1, 2)).isEqualTo(2); RList<String> list2 = redisson.getList("tester3", StringCodec.INSTANCE); assertThat(list2).containsExactly("2", "3"); assertThat(list.sortTo("tester4", "test*", SortOrder.ASC, 1, 2)).isEqualTo(2); RList<String> list3 = redisson.getList("tester4", StringCodec.INSTANCE); assertThat(list3).containsExactly("2", "1"); } @Test public void testRemoveRandom() { RSet<Integer> set = redisson.getSet("simple"); set.add(1); set.add(2); set.add(3); assertThat(set.removeRandom()).isIn(1, 2, 3); assertThat(set.removeRandom()).isIn(1, 2, 3); assertThat(set.removeRandom()).isIn(1, 2, 3); assertThat(set.removeRandom()).isNull(); } @Test public void testRemoveRandomAmount() { RSet<Integer> set = redisson.getSet("simple"); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); set.add(6); assertThat(set.removeRandom(3)).isSubsetOf(1, 2, 3, 4, 5, 6).hasSize(3); assertThat(set.removeRandom(2)).isSubsetOf(1, 2, 3, 4, 5, 6).hasSize(2); assertThat(set.removeRandom(1)).isSubsetOf(1, 2, 3, 4, 5, 6).hasSize(1); assertThat(set.removeRandom(4)).isEmpty(); } @Test public void testRandomLimited() { RSet<Integer> set = redisson.getSet("simple"); for (int i = 0; i < 10; i++) { set.add(i); } assertThat(set.random(3)).containsAnyElementsOf(set.readAll()).hasSize(3); } @Test public void testRandom() { RSet<Integer> set = redisson.getSet("simple"); set.add(1); set.add(2); set.add(3); assertThat(set.random()).isIn(1, 2, 3); assertThat(set.random()).isIn(1, 2, 3); assertThat(set.random()).isIn(1, 2, 3); assertThat(set).containsOnly(1, 2, 3); } @Test public void testAddBean() throws InterruptedException, ExecutionException { SimpleBean sb = new SimpleBean(); sb.setLng(1L); RSet<SimpleBean> set = redisson.getSet("simple"); set.add(sb); Assertions.assertEquals(sb.getLng(), set.iterator().next().getLng()); } @Test public void testAddLong() throws InterruptedException, ExecutionException { Long sb = 1l; RSet<Long> set = redisson.getSet("simple_longs"); set.add(sb); for (Long l : set) { Assertions.assertEquals(sb.getClass(), l.getClass()); } Object[] arr = set.toArray(); for (Object o : arr) { Assertions.assertEquals(sb.getClass(), o.getClass()); } } @Test public void testAddAsync() throws InterruptedException, ExecutionException { RSet<Integer> set = redisson.getSet("simple"); RFuture<Boolean> future = set.addAsync(2); Assertions.assertTrue(future.get()); Assertions.assertTrue(set.contains(2)); } @Test public void testRemoveAsync() throws InterruptedException, ExecutionException { RSet<Integer> set = redisson.getSet("simple"); set.add(1); set.add(3); set.add(7); Assertions.assertTrue(set.removeAsync(1).get()); Assertions.assertFalse(set.contains(1)); assertThat(set).containsOnly(3, 7); Assertions.assertFalse(set.removeAsync(1).get()); assertThat(set).containsOnly(3, 7); set.removeAsync(3).get(); Assertions.assertFalse(set.contains(3)); assertThat(set).contains(7); } @Test public void testIteratorRemove() { Set<String> list = redisson.getSet("list"); list.add("1"); list.add("4"); list.add("2"); list.add("5"); list.add("3"); for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { String value = iterator.next(); if (value.equals("2")) { iterator.remove(); } } assertThat(list).containsOnly("1", "4", "5", "3"); int iteration = 0; for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { iterator.next(); iterator.remove(); iteration++; } Assertions.assertEquals(4, iteration); Assertions.assertEquals(0, list.size()); Assertions.assertTrue(list.isEmpty()); } @Test public void testIteratorSequence() { Set<Long> set = redisson.getSet("set"); for (int i = 0; i < 1000; i++) { set.add(Long.valueOf(i)); } Set<Long> setCopy = new HashSet<Long>(); for (int i = 0; i < 1000; i++) { setCopy.add(Long.valueOf(i)); } checkIterator(set, setCopy); } private void checkIterator(Set<Long> set, Set<Long> setCopy) { for (Iterator<Long> iterator = set.iterator(); iterator.hasNext();) { Long value = iterator.next(); if (!setCopy.remove(value)) { Assertions.fail(); } } Assertions.assertEquals(0, setCopy.size()); } @Test public void testIteratorAsync() { RSet<Long> set = redisson.getSet("set"); for (int i = 0; i < 1000; i++) { set.add(Long.valueOf(i)); } AsyncIterator<Long> iterator = set.iteratorAsync(5); Set<Long> set2 = new HashSet<>(); CompletionStage<Void> f = iterateAll(iterator, set2); f.toCompletableFuture().join(); Assertions.assertEquals(1000, set2.size()); } public CompletionStage<Void> iterateAll(AsyncIterator<Long> iterator, Set<Long> set) { return iterator.hasNext().thenCompose(r -> { if (r) { return iterator.next().thenCompose(k -> { set.add(k); return iterateAll(iterator, set); }); } else { return CompletableFuture.completedFuture(null); } }); } @Test public void testLong() { Set<Long> set = redisson.getSet("set"); set.add(1L); set.add(2L); assertThat(set).containsOnly(1L, 2L); } @Test public void testRetainAll() { Set<Integer> set = redisson.getSet("set"); for (int i = 0; i < 20000; i++) { set.add(i); } Assertions.assertTrue(set.retainAll(Arrays.asList(1, 2))); assertThat(set).containsOnly(1, 2); Assertions.assertEquals(2, set.size()); } @Test public void testClusteredIterator() { testInCluster(redisson -> { int size = 10000; RSet<String> set = redisson.getSet("{test"); for (int i = 0; i < size; i++) { set.add("" + i); } Set<String> keys = new HashSet<>(); for (String key : set) { keys.add(key); } assertThat(keys).hasSize(size); }); } @Test public void testIteratorRemoveHighVolume() { Set<Integer> set = redisson.getSet("set") /*new HashSet<Integer>()*/; for (int i = 0; i < 10000; i++) { set.add(i); } int cnt = 0; Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()) { Integer integer = iterator.next(); iterator.remove(); cnt++; } Assertions.assertEquals(0, set.size()); Assertions.assertEquals(10000, cnt); } @Test public void testContainsAll() { Set<Integer> set = redisson.getSet("set"); for (int i = 0; i < 200; i++) { set.add(i); } Assertions.assertTrue(set.containsAll(Collections.emptyList())); Assertions.assertTrue(set.containsAll(Arrays.asList(30, 11))); Assertions.assertFalse(set.containsAll(Arrays.asList(30, 711, 11))); } @Test public void testToArray() { Set<String> set = redisson.getSet("set"); set.add("1"); set.add("4"); set.add("2"); set.add("5"); set.add("3"); assertThat(set.toArray()).containsOnly("1", "2", "4", "5", "3"); String[] strs = set.toArray(new String[0]); assertThat(strs).containsOnly("1", "2", "4", "5", "3"); } @Test public void testContains() { Set<TestObject> set = redisson.getSet("set"); set.add(new TestObject("1", "2")); set.add(new TestObject("1", "2")); set.add(new TestObject("2", "3")); set.add(new TestObject("3", "4")); set.add(new TestObject("5", "6")); Assertions.assertTrue(set.contains(new TestObject("2", "3"))); Assertions.assertTrue(set.contains(new TestObject("1", "2"))); Assertions.assertFalse(set.contains(new TestObject("1", "9"))); } @Test public void testDuplicates() { Set<TestObject> set = redisson.getSet("set"); set.add(new TestObject("1", "2")); set.add(new TestObject("1", "2")); set.add(new TestObject("2", "3")); set.add(new TestObject("3", "4")); set.add(new TestObject("5", "6")); Assertions.assertEquals(4, set.size()); } @Test public void testSize() { Set<Integer> set = redisson.getSet("set"); set.add(1); set.add(2); set.add(3); set.add(3); set.add(4); set.add(5); set.add(5); Assertions.assertEquals(5, set.size()); } @Test public void testRetainAllEmpty() { Set<Integer> set = redisson.getSet("set"); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); Assertions.assertTrue(set.retainAll(Collections.<Integer>emptyList())); Assertions.assertEquals(0, set.size()); } @Test public void testRetainAllNoModify() { Set<Integer> set = redisson.getSet("set"); set.add(1); set.add(2); Assertions.assertFalse(set.retainAll(Arrays.asList(1, 2))); // nothing changed assertThat(set).containsOnly(1, 2); } @Test public void testUnion() { RSet<Integer> set = redisson.getSet("set"); set.add(5); set.add(6); RSet<Integer> set1 = redisson.getSet("set1"); set1.add(1); set1.add(2); RSet<Integer> set2 = redisson.getSet("set2"); set2.add(3); set2.add(4); assertThat(set.union("set1", "set2")).isEqualTo(4); assertThat(set).containsOnly(1, 2, 3, 4); } @Test public void testReadUnion() { RSet<Integer> set = redisson.getSet("set"); set.add(5); set.add(6); RSet<Integer> set1 = redisson.getSet("set1"); set1.add(1); set1.add(2); RSet<Integer> set2 = redisson.getSet("set2"); set2.add(3); set2.add(4); assertThat(set.readUnion("set1", "set2")).containsOnly(1, 2, 3, 4, 5, 6); assertThat(set).containsOnly(5, 6); } @Test public void testDiff() { RSet<Integer> set = redisson.getSet("set"); set.add(5); set.add(6); RSet<Integer> set1 = redisson.getSet("set1"); set1.add(1); set1.add(2); set1.add(3); RSet<Integer> set2 = redisson.getSet("set2"); set2.add(3); set2.add(4); set2.add(5); assertThat(set.diff("set1", "set2")).isEqualTo(2); assertThat(set).containsOnly(1, 2); } @Test public void testReadDiff() { RSet<Integer> set = redisson.getSet("set"); set.add(5); set.add(7); set.add(6); RSet<Integer> set1 = redisson.getSet("set1"); set1.add(1); set1.add(2); set1.add(5); RSet<Integer> set2 = redisson.getSet("set2"); set2.add(3); set2.add(4); set2.add(5); assertThat(set.readDiff("set1", "set2")).containsOnly(7, 6); assertThat(set).containsOnly(6, 5, 7); } @Test public void testIntersection() { RSet<Integer> set = redisson.getSet("set"); set.add(5); set.add(6); RSet<Integer> set1 = redisson.getSet("set1"); set1.add(1); set1.add(2); set1.add(3); RSet<Integer> set2 = redisson.getSet("set2"); set2.add(3); set2.add(4); set2.add(5); assertThat(set.intersection("set1", "set2")).isEqualTo(1); assertThat(set).containsOnly(3); } @Test public void testReadIntersection() { RSet<Integer> set = redisson.getSet("set"); set.add(5); set.add(7); set.add(6); RSet<Integer> set1 = redisson.getSet("set1"); set1.add(1); set1.add(2); set1.add(5); RSet<Integer> set2 = redisson.getSet("set2"); set2.add(3); set2.add(4); set2.add(5); assertThat(set.readIntersection("set1", "set2")).containsOnly(5); assertThat(set).containsOnly(6, 5, 7); } @Test public void testMove() throws Exception { RSet<Integer> set = redisson.getSet("set"); RSet<Integer> otherSet = redisson.getSet("otherSet"); set.add(1); set.add(2); assertThat(set.move("otherSet", 1)).isTrue(); assertThat(set.size()).isEqualTo(1); assertThat(set).contains(2); assertThat(otherSet.size()).isEqualTo(1); assertThat(otherSet).contains(1); } @Test public void testMoveNoMember() throws Exception { RSet<Integer> set = redisson.getSet("set"); RSet<Integer> otherSet = redisson.getSet("otherSet"); set.add(1); Assertions.assertFalse(set.move("otherSet", 2)); Assertions.assertEquals(1, set.size()); Assertions.assertEquals(0, otherSet.size()); } @Test public void testRemoveAllEmpty() { Set<Integer> list = redisson.getSet("list"); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); Assertions.assertFalse(list.removeAll(Collections.emptyList())); Assertions.assertFalse(Arrays.asList(1).removeAll(Collections.emptyList())); } @Test public void testRemoveAll() { Set<Integer> list = redisson.getSet("list"); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); Assertions.assertFalse(list.removeAll(Collections.emptyList())); Assertions.assertTrue(list.removeAll(Arrays.asList(3, 2, 10, 6))); assertThat(list).containsExactlyInAnyOrder(1, 4, 5); Assertions.assertTrue(list.removeAll(Arrays.asList(4))); assertThat(list).containsExactlyInAnyOrder(1, 5); Assertions.assertTrue(list.removeAll(Arrays.asList(1, 5, 1, 5))); Assertions.assertTrue(list.isEmpty()); } @Test public void testDistributedIterator() { RSet<String> set = redisson.getSet("set", StringCodec.INSTANCE); // populate set with elements List<String> stringsOne = IntStream.range(0, 128).mapToObj(i -> "one-" + i).collect(Collectors.toList()); List<String> stringsTwo = IntStream.range(0, 128).mapToObj(i -> "two-" + i).collect(Collectors.toList()); set.addAll(stringsOne); set.addAll(stringsTwo); Iterator<String> stringIterator = set.distributedIterator("iterator_{set}", "one*", 10); // read some elements using iterator List<String> strings = new ArrayList<>(); for (int i = 0; i < 64; i++) { if (stringIterator.hasNext()) { strings.add(stringIterator.next()); } } // create another iterator instance using the same name RSet<String> set2 = redisson.getSet("set", StringCodec.INSTANCE); Iterator<String> stringIterator2 = set2.distributedIterator("iterator_{set}", "one*", 10); Assertions.assertTrue(stringIterator2.hasNext()); // read all remaining elements stringIterator2.forEachRemaining(strings::add); stringIterator.forEachRemaining(strings::add); assertThat(strings).containsAll(stringsOne); assertThat(strings).hasSize(stringsOne.size()); } @Test public void testAddAndContainsInTransactionShouldNotShowResourceLeak() { new MockUp<ResourceLeakDetector<?>>() { @Mock void reportTracedLeak(Invocation invocation, String resourceType, String records) { invocation.proceed(); Assertions.fail(); } @Mock void reportUntracedLeak(Invocation invocation, String resourceType) { invocation.proceed(); Assertions.fail(); } }; RTransaction tx = redisson.createTransaction(TransactionOptions.defaults()); RSet<Integer> testSet = tx.getSet("testSet"); for (int index = 0; index < 1000; index++) { testSet.add(index); if (testSet.contains(index)) { // do nothing } } tx.commit(); } }
SimpleBean
java
bumptech__glide
annotation/compiler/test/src/test/resources/AppGlideModuleWithLibraryInPackageTest/GeneratedAppGlideModuleImpl.java
{ "start": 272, "end": 1704 }
class ____ extends GeneratedAppGlideModule { private final AppModuleWithLibraryInPackage appGlideModule; public GeneratedAppGlideModuleImpl(Context context) { appGlideModule = new AppModuleWithLibraryInPackage(); if (Log.isLoggable("Glide", Log.DEBUG)) { Log.d("Glide", "Discovered AppGlideModule from annotation: com.bumptech.glide.test.AppModuleWithLibraryInPackage"); Log.d("Glide", "AppGlideModule excludes LibraryGlideModule from annotation: com.bumptech.glide.test._package.LibraryModuleInPackage"); } } @Override public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) { appGlideModule.applyOptions(context, builder); } @Override public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) { appGlideModule.registerComponents(context, glide, registry); } @Override public boolean isManifestParsingEnabled() { return appGlideModule.isManifestParsingEnabled(); } @Override @NonNull public Set<Class<?>> getExcludedModuleClasses() { Set<Class<?>> excludedClasses = new HashSet<Class<?>>(); excludedClasses.add(com.bumptech.glide.test._package.LibraryModuleInPackage.class); return excludedClasses; } @Override @NonNull GeneratedRequestManagerFactory getRequestManagerFactory() { return new GeneratedRequestManagerFactory(); } }
GeneratedAppGlideModuleImpl
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/converter/stream/SourceCacheTest.java
{ "start": 1081, "end": 1621 }
class ____ extends ContextTestSupport { @Test public void testSourceCache() throws Exception { SourceCache cache = new SourceCache("<foo>bar</foo>"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); cache.writeTo(bos); String s = context.getTypeConverter().convertTo(String.class, bos); assertEquals("<foo>bar</foo>", s); cache.reset(); s = context.getTypeConverter().convertTo(String.class, cache); assertEquals("<foo>bar</foo>", s); } }
SourceCacheTest
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfSystemPropertyConditionTests.java
{ "start": 851, "end": 3879 }
class ____ extends AbstractExecutionConditionTests { @Override protected ExecutionCondition getExecutionCondition() { return new EnabledIfSystemPropertyCondition(); } @Override protected Class<?> getTestClass() { return EnabledIfSystemPropertyIntegrationTests.class; } @BeforeAll static void setSystemProperties() { EnabledIfSystemPropertyIntegrationTests.setSystemProperties(); } @AfterAll static void clearSystemProperties() { EnabledIfSystemPropertyIntegrationTests.clearSystemProperties(); } /** * @see EnabledIfSystemPropertyIntegrationTests#enabledBecauseAnnotationIsNotPresent() */ @Test void enabledBecauseAnnotationIsNotPresent() { evaluateCondition(); assertEnabled(); assertReasonContains("No @EnabledIfSystemProperty conditions resulting in 'disabled' execution encountered"); } /** * @see EnabledIfSystemPropertyIntegrationTests#blankNamedAttribute() */ @Test void blankNamedAttribute() { assertPreconditionViolationNotBlankFor("The 'named' attribute", this::evaluateCondition); } /** * @see EnabledIfSystemPropertyIntegrationTests#blankMatchesAttribute() */ @Test void blankMatchesAttribute() { assertPreconditionViolationNotBlankFor("The 'matches' attribute", this::evaluateCondition); } /** * @see EnabledIfSystemPropertyIntegrationTests#enabledBecauseSystemPropertyMatchesExactly() */ @Test void enabledBecauseSystemPropertyMatchesExactly() { evaluateCondition(); assertEnabled(); assertReasonContains("No @EnabledIfSystemProperty conditions resulting in 'disabled' execution encountered"); } /** * @see EnabledIfSystemPropertyIntegrationTests#enabledBecauseBothSystemPropertiesMatchExactly() */ @Test void enabledBecauseBothSystemPropertiesMatchExactly() { evaluateCondition(); assertEnabled(); assertReasonContains("No @EnabledIfSystemProperty conditions resulting in 'disabled' execution encountered"); } /** * @see EnabledIfSystemPropertyIntegrationTests#enabledBecauseSystemPropertyMatchesPattern() */ @Test void enabledBecauseSystemPropertyMatchesPattern() { evaluateCondition(); assertEnabled(); assertReasonContains("No @EnabledIfSystemProperty conditions resulting in 'disabled' execution encountered"); } /** * @see EnabledIfSystemPropertyIntegrationTests#disabledBecauseSystemPropertyDoesNotMatch() */ @Test void disabledBecauseSystemPropertyDoesNotMatch() { evaluateCondition(); assertDisabled(); assertReasonContains("does not match regular expression"); assertCustomDisabledReasonIs("Not bogus"); } @Test void disabledBecauseSystemPropertyForComposedAnnotationDoesNotMatch() { evaluateCondition(); assertDisabled(); assertReasonContains("does not match regular expression"); } /** * @see EnabledIfSystemPropertyIntegrationTests#disabledBecauseSystemPropertyDoesNotExist() */ @Test void disabledBecauseSystemPropertyDoesNotExist() { evaluateCondition(); assertDisabled(); assertReasonContains("does not exist"); } }
EnabledIfSystemPropertyConditionTests
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/testjar/ClassWordCount.java
{ "start": 1406, "end": 1539 }
class ____ extends WordCount.MapClass implements Mapper<LongWritable, Text, Text, IntWritable> { } /** * A reducer
MapClass
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesReader.java
{ "start": 2732, "end": 3299 }
class ____ { private static final AuditJoinTableData DEFAULT_AUDIT_JOIN_TABLE = new AuditJoinTableData(); public static final String NO_PREFIX = ""; private final PersistentPropertiesSource persistentPropertiesSource; private final AuditedPropertiesHolder auditedPropertiesHolder; private final EnversMetadataBuildingContext metadataBuildingContext; private final String propertyNamePrefix; private final Map<String, String> propertyAccessedPersistentProperties; private final Set<String> fieldAccessedPersistentProperties; // Mapping
AuditedPropertiesReader
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithBidirectionalOneToOne.java
{ "start": 1879, "end": 2165 }
class ____ { @Id @Column(name = "ID", nullable = false) @SequenceGenerator(name = "ID", sequenceName = "ADDRESS_SEQ") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID") private Long id; private String name; @OneToOne private Address address; } }
Person
java
square__javapoet
src/main/java/com/squareup/javapoet/FieldSpec.java
{ "start": 3610, "end": 5530 }
class ____ { private final TypeName type; private final String name; private final CodeBlock.Builder javadoc = CodeBlock.builder(); private CodeBlock initializer = null; public final List<AnnotationSpec> annotations = new ArrayList<>(); public final List<Modifier> modifiers = new ArrayList<>(); private Builder(TypeName type, String name) { this.type = type; this.name = name; } public Builder addJavadoc(String format, Object... args) { javadoc.add(format, args); return this; } public Builder addJavadoc(CodeBlock block) { javadoc.add(block); return this; } public Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs) { checkArgument(annotationSpecs != null, "annotationSpecs == null"); for (AnnotationSpec annotationSpec : annotationSpecs) { this.annotations.add(annotationSpec); } return this; } public Builder addAnnotation(AnnotationSpec annotationSpec) { this.annotations.add(annotationSpec); return this; } public Builder addAnnotation(ClassName annotation) { this.annotations.add(AnnotationSpec.builder(annotation).build()); return this; } public Builder addAnnotation(Class<?> annotation) { return addAnnotation(ClassName.get(annotation)); } public Builder addModifiers(Modifier... modifiers) { Collections.addAll(this.modifiers, modifiers); return this; } public Builder initializer(String format, Object... args) { return initializer(CodeBlock.of(format, args)); } public Builder initializer(CodeBlock codeBlock) { checkState(this.initializer == null, "initializer was already set"); this.initializer = checkNotNull(codeBlock, "codeBlock == null"); return this; } public FieldSpec build() { return new FieldSpec(this); } } }
Builder
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySingleQuoteStartWordCsvUnmarshallTest.java
{ "start": 2379, "end": 2731 }
class ____ extends RouteBuilder { BindyCsvDataFormat camelDataFormat = new BindyCsvDataFormat(org.apache.camel.dataformat.bindy.model.simple.oneclass.Order.class); @Override public void configure() { from(URI_DIRECT_START).unmarshal(camelDataFormat).to(URI_MOCK_RESULT); } } }
ContextConfig
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/protocolPB/RouterRefreshUserMappingsProtocolServerSideTranslatorPB.java
{ "start": 1782, "end": 3628 }
class ____ extends RefreshUserMappingsProtocolServerSideTranslatorPB { private final RouterRpcServer server; private final boolean isAsyncRpc; private final static RefreshUserToGroupsMappingsResponseProto VOID_REFRESH_USER_GROUPS_MAPPING_RESPONSE = RefreshUserToGroupsMappingsResponseProto.newBuilder().build(); private final static RefreshSuperUserGroupsConfigurationResponseProto VOID_REFRESH_SUPERUSER_GROUPS_CONFIGURATION_RESPONSE = RefreshSuperUserGroupsConfigurationResponseProto.newBuilder() .build(); public RouterRefreshUserMappingsProtocolServerSideTranslatorPB( RefreshUserMappingsProtocol impl) { super(impl); this.server = (RouterRpcServer) impl; this.isAsyncRpc = server.isAsync(); } @Override public RefreshUserToGroupsMappingsResponseProto refreshUserToGroupsMappings( RpcController controller, RefreshUserToGroupsMappingsRequestProto request) throws ServiceException { if (!isAsyncRpc) { return super.refreshUserToGroupsMappings(controller, request); } asyncRouterServer(() -> { server.refreshUserToGroupsMappings(); return null; }, result -> VOID_REFRESH_USER_GROUPS_MAPPING_RESPONSE); return null; } @Override public RefreshSuperUserGroupsConfigurationResponseProto refreshSuperUserGroupsConfiguration( RpcController controller, RefreshSuperUserGroupsConfigurationRequestProto request) throws ServiceException { if (!isAsyncRpc) { return super.refreshSuperUserGroupsConfiguration(controller, request); } asyncRouterServer(() -> { server.refreshSuperUserGroupsConfiguration(); return null; }, result -> VOID_REFRESH_SUPERUSER_GROUPS_CONFIGURATION_RESPONSE); return null; } }
RouterRefreshUserMappingsProtocolServerSideTranslatorPB
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MathAbsoluteNegativeTest.java
{ "start": 2559, "end": 2901 }
class ____ { void f() { long random = Math.round(Math.random() * 10000); } } """) .doTest(); } @Test public void negativeDouble() { helper .addSourceLines( "Test.java", """ import java.util.Random;
Test
java
spring-projects__spring-framework
spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java
{ "start": 19320, "end": 27291 }
interface ____ proceed with", ex); } } } /** * Delegate an incoming invocation from the proxy, dispatching to EntityManagerFactoryInfo * or the native EntityManagerFactory accordingly. */ Object invokeProxyMethod(Method method, Object @Nullable [] args) throws Throwable { if (method.getDeclaringClass().isAssignableFrom(EntityManagerFactoryInfo.class)) { return method.invoke(this, args); } else if (method.getName().equals("createEntityManager") && args != null && args.length > 0 && args[0] == SynchronizationType.SYNCHRONIZED) { // JPA 2.1's createEntityManager(SynchronizationType, Map) // Redirect to plain createEntityManager and add synchronization semantics through Spring proxy EntityManager rawEntityManager = (args.length > 1 ? getNativeEntityManagerFactory().createEntityManager((Map<?, ?>) args[1]) : getNativeEntityManagerFactory().createEntityManager()); postProcessEntityManager(rawEntityManager); return ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, true); } // Look for Query arguments, primarily JPA 2.1's addNamedQuery(String, Query) if (args != null) { for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg instanceof Query query && Proxy.isProxyClass(arg.getClass())) { // Assumably a Spring-generated proxy from SharedEntityManagerCreator: // since we're passing it back to the native EntityManagerFactory, // let's unwrap it to the original Query object from the provider. try { args[i] = query.unwrap(null); } catch (RuntimeException ex) { // Ignore - simply proceed with given Query object then } } } } // Standard delegation to the native factory, just post-processing EntityManager return values Object retVal = method.invoke(getNativeEntityManagerFactory(), args); if (retVal instanceof EntityManager rawEntityManager) { // Any other createEntityManager variant - expecting non-synchronized semantics postProcessEntityManager(rawEntityManager); retVal = ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, false); } return retVal; } /** * Subclasses must implement this method to create the EntityManagerFactory * that will be returned by the {@code getObject()} method. * @return the EntityManagerFactory instance returned by this FactoryBean * @throws PersistenceException if the EntityManager cannot be created */ protected abstract EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException; /** * Implementation of the PersistenceExceptionTranslator interface, as * autodetected by Spring's PersistenceExceptionTranslationPostProcessor. * <p>Uses the dialect's conversion if possible; otherwise falls back to * standard JPA exception conversion. * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor * @see JpaDialect#translateExceptionIfPossible * @see EntityManagerFactoryUtils#convertJpaAccessExceptionIfPossible */ @Override public @Nullable DataAccessException translateExceptionIfPossible(RuntimeException ex) { JpaDialect jpaDialect = getJpaDialect(); return (jpaDialect != null ? jpaDialect.translateExceptionIfPossible(ex) : EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex)); } @Override public EntityManagerFactory getNativeEntityManagerFactory() { if (this.nativeEntityManagerFactory != null) { return this.nativeEntityManagerFactory; } else { Assert.state(this.nativeEntityManagerFactoryFuture != null, "No native EntityManagerFactory available"); try { return this.nativeEntityManagerFactoryFuture.get(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted during initialization of native EntityManagerFactory", ex); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof PersistenceException persistenceException) { // Rethrow a provider configuration exception (possibly with a nested cause) directly throw persistenceException; } throw new IllegalStateException("Failed to asynchronously initialize native EntityManagerFactory: " + ex.getMessage(), cause); } } } @Override public EntityManager createNativeEntityManager(@Nullable Map<?, ?> properties) { EntityManager rawEntityManager = (!CollectionUtils.isEmpty(properties) ? getNativeEntityManagerFactory().createEntityManager(properties) : getNativeEntityManagerFactory().createEntityManager()); postProcessEntityManager(rawEntityManager); return rawEntityManager; } /** * Optional callback for post-processing the native EntityManager * before active use. * <p>The default implementation delegates to * {@link JpaVendorAdapter#postProcessEntityManager}, if available. * @param rawEntityManager the EntityManager to post-process * @since 5.3 * @see #createNativeEntityManager * @see JpaVendorAdapter#postProcessEntityManager */ protected void postProcessEntityManager(EntityManager rawEntityManager) { JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter(); if (jpaVendorAdapter != null) { jpaVendorAdapter.postProcessEntityManager(rawEntityManager); } Consumer<EntityManager> customizer = this.entityManagerInitializer; if (customizer != null) { customizer.accept(rawEntityManager); } } @Override public @Nullable PersistenceUnitInfo getPersistenceUnitInfo() { return null; } @Override public @Nullable DataSource getDataSource() { return null; } /** * Return the singleton EntityManagerFactory. */ @Override public @Nullable EntityManagerFactory getObject() { return this.entityManagerFactory; } @Override public Class<? extends EntityManagerFactory> getObjectType() { return (this.entityManagerFactory != null ? this.entityManagerFactory.getClass() : EntityManagerFactory.class); } /** * Return either the singleton EntityManagerFactory or the shared EntityManager proxy. */ @Override public <S> @Nullable S getObject(Class<S> type) throws Exception { if (EntityManager.class.isAssignableFrom(type)) { return (type.isInstance(this.sharedEntityManager) ? type.cast(this.sharedEntityManager) : null); } return SmartFactoryBean.super.getObject(type); } @Override public boolean supportsType(Class<?> type) { if (EntityManager.class.isAssignableFrom(type)) { return type.isInstance(this.sharedEntityManager); } return SmartFactoryBean.super.supportsType(type); } /** * Close the EntityManagerFactory on bean factory shutdown. */ @Override public void destroy() { if (this.entityManagerFactory != null) { if (logger.isInfoEnabled()) { logger.info("Closing JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'"); } this.entityManagerFactory.close(); } } //--------------------------------------------------------------------- // Serialization support //--------------------------------------------------------------------- private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { throw new NotSerializableException("An EntityManagerFactoryBean itself is not deserializable - " + "just a SerializedEntityManagerFactoryBeanReference is"); } protected Object writeReplace() throws ObjectStreamException { if (this.beanFactory != null && this.beanName != null) { return new SerializedEntityManagerFactoryBeanReference(this.beanFactory, this.beanName); } else { throw new NotSerializableException("EntityManagerFactoryBean does not run within a BeanFactory"); } } /** * Minimal bean reference to the surrounding AbstractEntityManagerFactoryBean. * Resolved to the actual AbstractEntityManagerFactoryBean instance on deserialization. */ @SuppressWarnings("serial") private static
to
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-guava-tests/src/test/java/org/assertj/tests/guava/api/MultimapAssertBaseTest.java
{ "start": 823, "end": 1307 }
class ____ { protected Multimap<String, String> actual; public MultimapAssertBaseTest() { super(); } @BeforeEach public void setUp() { actual = LinkedListMultimap.create(); actual.putAll("Lakers", List.of("Kobe Bryant", "Magic Johnson", "Kareem Abdul Jabbar")); actual.putAll("Bulls", List.of("Michael Jordan", "Scottie Pippen", "Derrick Rose")); actual.putAll("Spurs", List.of("Tony Parker", "Tim Duncan", "Manu Ginobili")); } }
MultimapAssertBaseTest
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/oscar/ast/stmt/OscarDeleteStatement.java
{ "start": 965, "end": 2266 }
class ____ extends SQLDeleteStatement implements OscarStatement { private boolean returning; public OscarDeleteStatement() { super(DbType.oscar); } public boolean isReturning() { return returning; } public void setReturning(boolean returning) { this.returning = returning; } public String getAlias() { if (tableSource == null) { return null; } return tableSource.getAlias(); } public void setAlias(String alias) { this.tableSource.setAlias(alias); } protected void accept0(SQLASTVisitor visitor) { if (visitor instanceof PGASTVisitor) { accept0((PGASTVisitor) visitor); } else { super.accept0(visitor); } } @Override public void accept0(OscarASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, with); acceptChild(visitor, tableSource); acceptChild(visitor, using); acceptChild(visitor, where); } visitor.endVisit(this); } public OscarDeleteStatement clone() { OscarDeleteStatement x = new OscarDeleteStatement(); cloneTo(x); x.returning = returning; return x; } }
OscarDeleteStatement
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/component/extension/verifier/ResultBuilder.java
{ "start": 1204, "end": 5524 }
class ____ { private ComponentVerifierExtension.Scope scope; private ComponentVerifierExtension.Result.Status status; private List<ComponentVerifierExtension.VerificationError> verificationErrors; public ResultBuilder() { this.scope = null; this.status = null; } // ********************************** // Accessors // ********************************** public ResultBuilder scope(ComponentVerifierExtension.Scope scope) { this.scope = scope; return this; } public ResultBuilder status(ComponentVerifierExtension.Result.Status status) { this.status = status; return this; } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Deprecated public ResultBuilder error(Optional<ComponentVerifierExtension.VerificationError> verificationError) { return error(verificationError.orElse(null)); } public ResultBuilder error(ComponentVerifierExtension.VerificationError verificationError) { if (verificationError != null) { if (this.verificationErrors == null) { this.verificationErrors = new ArrayList<>(); } this.verificationErrors.add(verificationError); this.status = ComponentVerifierExtension.Result.Status.ERROR; } return this; } public ResultBuilder error(Supplier<ComponentVerifierExtension.VerificationError> supplier) { return error(supplier.get()); } public ResultBuilder error(ThrowingConsumer<ResultBuilder, Exception> consumer) { try { consumer.accept(this); } catch (NoSuchOptionException e) { error(ResultErrorBuilder.withMissingOption(e.getOptionName()).build()); } catch (IllegalOptionException e) { error(ResultErrorBuilder.withIllegalOption(e.getOptionName(), e.getOptionValue()).build()); } catch (Exception e) { error(ResultErrorBuilder.withException(e).build()); } return this; } public <T> ResultBuilder error(T data, ThrowingBiConsumer<ResultBuilder, T, Exception> consumer) { try { consumer.accept(this, data); } catch (NoSuchOptionException e) { error(ResultErrorBuilder.withMissingOption(e.getOptionName()).build()); } catch (IllegalOptionException e) { error(ResultErrorBuilder.withIllegalOption(e.getOptionName(), e.getOptionValue()).build()); } catch (Exception e) { error(ResultErrorBuilder.withException(e).build()); } return this; } public ResultBuilder errors(List<ComponentVerifierExtension.VerificationError> verificationErrors) { verificationErrors.forEach(this::error); return this; } // ********************************** // Build // ********************************** public ComponentVerifierExtension.Result build() { return new DefaultResult( scope != null ? scope : ComponentVerifierExtension.Scope.PARAMETERS, status != null ? status : ComponentVerifierExtension.Result.Status.UNSUPPORTED, verificationErrors != null ? Collections.unmodifiableList(verificationErrors) : Collections.emptyList()); } // ********************************** // Helpers // ********************************** public static ResultBuilder withStatus(ComponentVerifierExtension.Result.Status status) { return new ResultBuilder().status(status); } public static ResultBuilder withStatusAndScope( ComponentVerifierExtension.Result.Status status, ComponentVerifierExtension.Scope scope) { return new ResultBuilder().status(status).scope(scope); } public static ResultBuilder withScope(ComponentVerifierExtension.Scope scope) { return new ResultBuilder().scope(scope); } public static ResultBuilder unsupported() { return withStatusAndScope(ComponentVerifierExtension.Result.Status.UNSUPPORTED, ComponentVerifierExtension.Scope.PARAMETERS); } public static ResultBuilder unsupportedScope(ComponentVerifierExtension.Scope scope) { return withStatusAndScope(ComponentVerifierExtension.Result.Status.UNSUPPORTED, scope); } }
ResultBuilder
java
google__auto
value/src/it/gwtserializer/src/test/java/com/google/auto/value/client/GwtSerializerTest.java
{ "start": 1194, "end": 1576 }
interface ____ extends RemoteService { Simple echo(Simple simple); SimpleWithBuilder echo(SimpleWithBuilder simple); Nested echo(Nested nested); NestedWithBuilder echo(NestedWithBuilder nested); Generics<Simple> echo(Generics<Simple> generics); GenericsWithBuilder<SimpleWithBuilder> echo(GenericsWithBuilder<SimpleWithBuilder> generics); }
TestService
java
apache__camel
core/camel-xml-io/src/main/java/org/apache/camel/xml/in/BaseParser.java
{ "start": 20897, "end": 21058 }
interface ____<T> { boolean accept(T definition, String name, String value) throws IOException, XmlPullParserException; } protected
AttributeHandler
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/HeaderFilterStrategyComponentTest.java
{ "start": 1815, "end": 3417 }
class ____ extends DefaultEndpoint implements HeaderFilterStrategyAware { private HeaderFilterStrategy strategy; @Override public HeaderFilterStrategy getHeaderFilterStrategy() { return strategy; } @Override public void setHeaderFilterStrategy(HeaderFilterStrategy strategy) { this.strategy = strategy; } @Override public Producer createProducer() { return null; } @Override public Consumer createConsumer(Processor processor) { return null; } @Override public boolean isSingleton() { return true; } } @Test public void testHeaderFilterStrategyComponent() { MyComponent comp = new MyComponent(MyEndpoint.class); assertNull(comp.getHeaderFilterStrategy()); HeaderFilterStrategy strategy = new DefaultHeaderFilterStrategy(); comp.setHeaderFilterStrategy(strategy); assertSame(strategy, comp.getHeaderFilterStrategy()); } @Test public void testHeaderFilterStrategyAware() { MyComponent comp = new MyComponent(MyEndpoint.class); assertNull(comp.getHeaderFilterStrategy()); HeaderFilterStrategy strategy = new DefaultHeaderFilterStrategy(); comp.setHeaderFilterStrategy(strategy); MyEndpoint my = new MyEndpoint(); comp.setEndpointHeaderFilterStrategy(my); assertSame(strategy, my.getHeaderFilterStrategy()); assertSame(strategy, comp.getHeaderFilterStrategy()); } }
MyEndpoint
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/authentication/ui/DefaultResourcesFilterTests.java
{ "start": 2274, "end": 3247 }
class ____ { private final DefaultResourcesFilter webauthnFilter = DefaultResourcesFilter.webauthn(); private final MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()) .addFilters(this.webauthnFilter) .build(); @Test void doFilterThenRender() throws Exception { this.mockMvc.perform(get("/login/webauthn.js")) .andExpect(status().isOk()) .andExpect(content().contentType("text/javascript;charset=UTF-8")) .andExpect(content().string(containsString("async function authenticate("))); } @Test void doFilterWhenPathDoesNotMatchThenCallsThrough() throws Exception { this.mockMvc.perform(get("/does-not-match")).andExpect(status().isNotFound()); } @Test void toStringPrintsPathAndResource() { assertThat(this.webauthnFilter.toString()).isEqualTo( "DefaultResourcesFilter [matcher=PathPattern [GET /login/webauthn.js], resource=org/springframework/security/spring-security-webauthn.js]"); } } }
WebAuthnFilter
java
netty__netty
codec-base/src/main/java/io/netty/handler/codec/serialization/ClassResolvers.java
{ "start": 1370, "end": 1499 }
class ____ been deprecated with no replacement, * because serialization can be a security liability */ @Deprecated public final
has
java
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/annotation/Client.java
{ "start": 5171, "end": 5800 }
interface ____ type. */ SERVER; /** * Returns true, if this definition type is {@link DefinitionType.CLIENT}. * * @return true, if this definition type is {@link DefinitionType.CLIENT}. */ public boolean isClient() { return this == CLIENT; } /** * Returns true, if this definition type is {@link DefinitionType.SERVER}. * * @return true, if this definition type is {@link DefinitionType.SERVER}. */ public boolean isServer() { return this == SERVER; } } }
definition
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/CorrelatedPluralJoinInheritanceTest.java
{ "start": 5705, "end": 5808 }
class ____ extends DataEntity { } @Entity( name = "StoredContinuousData" ) public static
ContinuousData
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/registration/RetryingRegistration.java
{ "start": 2138, "end": 15973 }
class ____< F extends Serializable, G extends RpcGateway, S extends RegistrationResponse.Success, R extends RegistrationResponse.Rejection> { // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ private final Logger log; private final RpcService rpcService; private final String targetName; private final Class<G> targetType; private final String targetAddress; private final F fencingToken; private final CompletableFuture<RetryingRegistrationResult<G, S, R>> completionFuture; private final RetryingRegistrationConfiguration retryingRegistrationConfiguration; private volatile boolean canceled; // ------------------------------------------------------------------------ public RetryingRegistration( Logger log, RpcService rpcService, String targetName, Class<G> targetType, String targetAddress, F fencingToken, RetryingRegistrationConfiguration retryingRegistrationConfiguration) { this.log = checkNotNull(log); this.rpcService = checkNotNull(rpcService); this.targetName = checkNotNull(targetName); this.targetType = checkNotNull(targetType); this.targetAddress = checkNotNull(targetAddress); this.fencingToken = checkNotNull(fencingToken); this.retryingRegistrationConfiguration = checkNotNull(retryingRegistrationConfiguration); this.completionFuture = new CompletableFuture<>(); } // ------------------------------------------------------------------------ // completion and cancellation // ------------------------------------------------------------------------ public CompletableFuture<RetryingRegistrationResult<G, S, R>> getFuture() { return completionFuture; } /** Cancels the registration procedure. */ public void cancel() { canceled = true; completionFuture.cancel(false); } /** * Checks if the registration was canceled. * * @return True if the registration was canceled, false otherwise. */ public boolean isCanceled() { return canceled; } // ------------------------------------------------------------------------ // registration // ------------------------------------------------------------------------ protected abstract CompletableFuture<RegistrationResponse> invokeRegistration( G gateway, F fencingToken, long timeoutMillis) throws Exception; /** * This method resolves the target address to a callable gateway and starts the registration * after that. */ @SuppressWarnings("unchecked") public void startRegistration() { if (canceled) { // we already got canceled return; } try { // trigger resolution of the target address to a callable gateway final CompletableFuture<G> rpcGatewayFuture; if (FencedRpcGateway.class.isAssignableFrom(targetType)) { rpcGatewayFuture = (CompletableFuture<G>) rpcService.connect( targetAddress, fencingToken, targetType.asSubclass(FencedRpcGateway.class)); } else { rpcGatewayFuture = rpcService.connect(targetAddress, targetType); } // upon success, start the registration attempts CompletableFuture<Void> rpcGatewayAcceptFuture = rpcGatewayFuture.thenAcceptAsync( (G rpcGateway) -> { log.info("Resolved {} address, beginning registration", targetName); register( rpcGateway, 1, retryingRegistrationConfiguration .getInitialRegistrationTimeoutMillis()); }, rpcService.getScheduledExecutor()); // upon failure, retry, unless this is cancelled rpcGatewayAcceptFuture.whenCompleteAsync( (Void v, Throwable failure) -> { if (failure != null && !canceled) { final Throwable strippedFailure = ExceptionUtils.stripCompletionException(failure); if (log.isDebugEnabled()) { log.debug( "Could not resolve {} address {}, retrying in {} ms.", targetName, targetAddress, retryingRegistrationConfiguration.getErrorDelayMillis(), strippedFailure); } else { log.info( "Could not resolve {} address {}, retrying in {} ms: {}", targetName, targetAddress, retryingRegistrationConfiguration.getErrorDelayMillis(), strippedFailure.getMessage()); } startRegistrationLater( retryingRegistrationConfiguration.getErrorDelayMillis()); } }, rpcService.getScheduledExecutor()); } catch (Throwable t) { completionFuture.completeExceptionally(t); cancel(); } } /** * This method performs a registration attempt and triggers either a success notification or a * retry, depending on the result. */ @SuppressWarnings("unchecked") private void register(final G gateway, final int attempt, final long timeoutMillis) { // eager check for canceling to avoid some unnecessary work if (canceled) { return; } try { log.debug( "Registration at {} attempt {} (timeout={}ms)", targetName, attempt, timeoutMillis); CompletableFuture<RegistrationResponse> registrationFuture = invokeRegistration(gateway, fencingToken, timeoutMillis); // if the registration was successful, let the TaskExecutor know CompletableFuture<Void> registrationAcceptFuture = registrationFuture.thenAcceptAsync( (RegistrationResponse result) -> { if (!isCanceled()) { if (result instanceof RegistrationResponse.Success) { log.debug( "Registration with {} at {} was successful.", targetName, targetAddress); S success = (S) result; completionFuture.complete( RetryingRegistrationResult.success( gateway, success)); } else if (result instanceof RegistrationResponse.Rejection) { log.debug( "Registration with {} at {} was rejected.", targetName, targetAddress); R rejection = (R) result; completionFuture.complete( RetryingRegistrationResult.rejection(rejection)); } else { // registration failure if (result instanceof RegistrationResponse.Failure) { RegistrationResponse.Failure failure = (RegistrationResponse.Failure) result; log.info( "Registration failure at {} occurred.", targetName, failure.getReason()); } else { log.error( "Received unknown response to registration attempt: {}", result); } log.info( "Pausing and re-attempting registration in {} ms", retryingRegistrationConfiguration .getRefusedDelayMillis()); registerLater( gateway, 1, retryingRegistrationConfiguration .getInitialRegistrationTimeoutMillis(), retryingRegistrationConfiguration .getRefusedDelayMillis()); } } }, rpcService.getScheduledExecutor()); // upon failure, retry registrationAcceptFuture.whenCompleteAsync( (Void v, Throwable failure) -> { if (failure != null && !isCanceled()) { if (ExceptionUtils.stripCompletionException(failure) instanceof TimeoutException) { // we simply have not received a response in time. maybe the timeout // was // very low (initial fast registration attempts), maybe the target // endpoint is // currently down. if (log.isDebugEnabled()) { log.debug( "Registration at {} ({}) attempt {} timed out after {} ms", targetName, targetAddress, attempt, timeoutMillis); } long newTimeoutMillis = Math.min( 2 * timeoutMillis, retryingRegistrationConfiguration .getMaxRegistrationTimeoutMillis()); register(gateway, attempt + 1, newTimeoutMillis); } else { // a serious failure occurred. we still should not give up, but keep // trying log.error( "Registration at {} failed due to an error", targetName, failure); log.info( "Pausing and re-attempting registration in {} ms", retryingRegistrationConfiguration.getErrorDelayMillis()); registerLater( gateway, 1, retryingRegistrationConfiguration .getInitialRegistrationTimeoutMillis(), retryingRegistrationConfiguration.getErrorDelayMillis()); } } }, rpcService.getScheduledExecutor()); } catch (Throwable t) { completionFuture.completeExceptionally(t); cancel(); } } private void registerLater( final G gateway, final int attempt, final long timeoutMillis, long delay) { rpcService .getScheduledExecutor() .schedule( () -> register(gateway, attempt, timeoutMillis), delay, TimeUnit.MILLISECONDS); } private void startRegistrationLater(final long delay) { rpcService .getScheduledExecutor() .schedule(this::startRegistration, delay, TimeUnit.MILLISECONDS); } static final
RetryingRegistration
java
google__dagger
javatests/dagger/internal/codegen/IgnoreProvisionKeyWildcardsTest.java
{ "start": 15903, "end": 16206 }
interface ____ {", " @Multibinds Map<String, Foo<? extends Bar>> mapExtends();", " @Multibinds Map<String, Foo<Bar>> map();", "}"), /* kotlinComponentClass = */ NEW_LINES.join( "@Component(modules = [MyModule::class])", "
MyModule
java
quarkusio__quarkus
extensions/reactive-oracle-client/deployment/src/test/java/io/quarkus/reactive/oracle/client/DevModeResource.java
{ "start": 455, "end": 1937 }
class ____ { @Inject Pool client; @GET @Path("/error") @Produces(MediaType.TEXT_PLAIN) public CompletionStage<Response> checkConnectionFailure() throws SQLException { CompletableFuture<Response> future = new CompletableFuture<>(); client.query("SELECT 1 FROM DUAL").execute(ar -> { Class<?> expectedExceptionClass = OracleException.class; if (ar.succeeded()) { future.complete(Response.serverError().entity("Expected SQL query to fail").build()); } else if (!expectedExceptionClass.isAssignableFrom(ar.cause().getClass())) { future.complete(Response.serverError() .entity("Expected " + expectedExceptionClass + ", got " + ar.cause().getClass()).build()); } else { future.complete(Response.ok().build()); } }); return future; } @GET @Path("/connected") @Produces(MediaType.TEXT_PLAIN) public CompletionStage<Response> checkConnectionSuccess() throws SQLException { CompletableFuture<Response> future = new CompletableFuture<>(); client.query("SELECT 1 FROM DUAL").execute(ar -> { if (ar.succeeded()) { future.complete(Response.ok().build()); } else { future.complete(Response.serverError().entity(ar.cause().getMessage()).build()); } }); return future; } }
DevModeResource
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/MultiJoinSemanticTests.java
{ "start": 1213, "end": 3146 }
class ____ extends SemanticTestBase { @Override protected void applyDefaultEnvironmentOptions(TableConfig config) { config.set( OptimizerConfigOptions.TABLE_OPTIMIZER_NONDETERMINISTIC_UPDATE_STRATEGY, OptimizerConfigOptions.NonDeterministicUpdateStrategy.TRY_RESOLVE) .set(OptimizerConfigOptions.TABLE_OPTIMIZER_MULTI_JOIN_ENABLED, true); } @Override public List<TableTestProgram> programs() { return List.of( MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_INNER_JOIN, MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_LEFT_OUTER_JOIN, MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_LEFT_OUTER_JOIN_UPDATING, MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_LEFT_OUTER_JOIN_WITH_WHERE, MultiJoinTestPrograms.MULTI_JOIN_FOUR_WAY_COMPLEX, MultiJoinTestPrograms.MULTI_JOIN_WITH_TIME_ATTRIBUTES_MATERIALIZATION, MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_INNER_JOIN_NO_JOIN_KEY, MultiJoinTestPrograms.MULTI_JOIN_FOUR_WAY_NO_COMMON_JOIN_KEY, MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_LEFT_OUTER_JOIN_WITH_CTE, MultiJoinTestPrograms.MULTI_JOIN_MIXED_CHANGELOG_MODES, MultiJoinTestPrograms.MULTI_JOIN_LEFT_OUTER_WITH_NULL_KEYS, MultiJoinTestPrograms.MULTI_JOIN_NULL_SAFE_JOIN_WITH_NULL_KEYS, MultiJoinTestPrograms.MULTI_JOIN_WITH_TIME_ATTRIBUTES_IN_CONDITIONS_MATERIALIZATION, MultiJoinTestPrograms.MULTI_JOIN_TWO_WAY_INNER_JOIN_WITH_WHERE_IN, MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_INNER_JOIN_MULTI_KEY_TYPES, MultiJoinTestPrograms.MULTI_JOIN_FOUR_WAY_MIXED_JOIN_MULTI_KEY_TYPES_SHUFFLED, MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_INNER_JOIN_WITH_HINT); } }
MultiJoinSemanticTests
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/client/WebSocketConnectionManagerTests.java
{ "start": 2929, "end": 3999 }
class ____ implements WebSocketClient, Lifecycle { private boolean running; private WebSocketHandler webSocketHandler; private HttpHeaders headers; private URI uri; public TestLifecycleWebSocketClient(boolean running) { this.running = running; } @Override public void start() { this.running = true; } @Override public void stop() { this.running = false; } @Override public boolean isRunning() { return this.running; } @Override public CompletableFuture<WebSocketSession> execute(WebSocketHandler handler, String uriTemplate, @Nullable Object... uriVars) { URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri(); return execute(handler, null, uri); } @Override public CompletableFuture<WebSocketSession> execute(WebSocketHandler handler, WebSocketHttpHeaders headers, URI uri) { this.webSocketHandler = handler; this.headers = headers; this.uri = uri; return CompletableFuture.supplyAsync(() -> null); } } }
TestLifecycleWebSocketClient
java
apache__camel
core/camel-management/src/test/java/org/apache/camel/management/ManagedCamelContextDumpStatsAsXmlTest.java
{ "start": 1276, "end": 2918 }
class ____ extends ManagementTestSupport { @Test public void testPerformanceCounterStats() throws Exception { // get the stats for the route MBeanServer mbeanServer = getMBeanServer(); ObjectName on = getContextObjectName(); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(2); template.asyncSendBody("direct:start", "Hello World"); template.asyncSendBody("direct:bar", "Hi World"); template.asyncSendBody("direct:bar", "Bye World"); assertMockEndpointsSatisfied(); String xml = (String) mbeanServer.invoke(on, "dumpRoutesStatsAsXml", new Object[] { false, true }, new String[] { "boolean", "boolean" }); log.info(xml); // should be valid XML Document doc = context.getTypeConverter().convertTo(Document.class, xml); assertNotNull(doc); int processors = doc.getDocumentElement().getElementsByTagName("processorStat").getLength(); assertEquals(5, processors); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").routeId("foo") .to("log:foo").id("a") .delay(100).id("b") .to("mock:foo").id("c"); from("direct:bar").routeId("bar") .to("log:bar").id("d") .to("mock:bar").id("e"); } }; } }
ManagedCamelContextDumpStatsAsXmlTest
java
apache__camel
components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConsumer.java
{ "start": 7928, "end": 9927 }
class ____ extends SynchronizationAdapter { private final ServiceBusReceivedMessageContext messageContext; private ConsumerOnCompletion(ServiceBusReceivedMessageContext messageContext) { this.messageContext = messageContext; } @Override public void onComplete(Exchange exchange) { super.onComplete(exchange); if (getConfiguration().getServiceBusReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { messageContext.complete(); } } @Override public void onFailure(Exchange exchange) { final Exception cause = exchange.getException(); if (cause != null) { getExceptionHandler().handleException("Error during processing exchange.", exchange, cause); } if (getConfiguration().getServiceBusReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { if (getConfiguration().isEnableDeadLettering() && (ObjectHelper.isEmpty(getConfiguration().getSubQueue()) || ObjectHelper.equal(getConfiguration().getSubQueue(), SubQueue.NONE))) { DeadLetterOptions deadLetterOptions = new DeadLetterOptions(); if (cause != null) { deadLetterOptions .setDeadLetterReason(String.format("%s: %s", cause.getClass().getName(), cause.getMessage())); deadLetterOptions.setDeadLetterErrorDescription(Arrays.stream(cause.getStackTrace()) .map(StackTraceElement::toString) .collect(Collectors.joining("\n"))); messageContext.deadLetter(deadLetterOptions); } else { messageContext.deadLetter(); } } else { messageContext.abandon(); } } } } }
ConsumerOnCompletion
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/graal/RegisterServicesForReflectionFeature.java
{ "start": 409, "end": 1387 }
class ____ implements Feature { @Override public String getDescription() { return "Makes methods of reachable Hibernate services accessible through Class#getMethods()"; } // The {@code duringAnalysis} method is invoked multiple times and increases the set of reachable types, thus we // need to invoke {@link DuringAnalysisAccess#requireAnalysisIteration()} each time we register new methods. private static final int ANTICIPATED_SERVICES = 100; private static final Set<Class<?>> registeredClasses = new HashSet<>(ANTICIPATED_SERVICES); @Override public void duringAnalysis(DuringAnalysisAccess access) { for (Class<?> service : access.reachableSubtypes(org.hibernate.service.Service.class)) { if (registeredClasses.add(service)) { RuntimeReflection.registerAllMethods(service); access.requireAnalysisIteration(); } } } }
RegisterServicesForReflectionFeature
java
google__auto
value/src/main/java/com/google/auto/value/extension/AutoValueExtension.java
{ "start": 10615, "end": 10696 }
interface ____ { /** * Returns the {@code @AutoValue.Builder}
BuilderContext
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/DelegatingCreatorImplicitNamesTest.java
{ "start": 2468, "end": 3295 }
class ____ { final String part1; final String part2; // this creator is considered a source of settable bean properties, // used during deserialization @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public Data2543(@JsonProperty("part1") String part1, @JsonProperty("part2") String part2) { this.part1 = part1; this.part2 = part2; } // no properties should be collected from this creator, // even though it has an argument with an implicit name @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static Data2543 fromFullData(String fullData) { String[] parts = fullData.split("\\s+", 2); return new Data2543(parts[0], parts[1]); } } static
Data2543
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/IdentityCipherSuiteFilter.java
{ "start": 865, "end": 2260 }
class ____ implements CipherSuiteFilter { /** * Defaults to default ciphers when provided ciphers are null */ public static final IdentityCipherSuiteFilter INSTANCE = new IdentityCipherSuiteFilter(true); /** * Defaults to supported ciphers when provided ciphers are null */ public static final IdentityCipherSuiteFilter INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS = new IdentityCipherSuiteFilter(false); private final boolean defaultToDefaultCiphers; private IdentityCipherSuiteFilter(boolean defaultToDefaultCiphers) { this.defaultToDefaultCiphers = defaultToDefaultCiphers; } @Override public String[] filterCipherSuites(Iterable<String> ciphers, List<String> defaultCiphers, Set<String> supportedCiphers) { if (ciphers == null) { return defaultToDefaultCiphers ? defaultCiphers.toArray(EmptyArrays.EMPTY_STRINGS) : supportedCiphers.toArray(EmptyArrays.EMPTY_STRINGS); } else { List<String> newCiphers = new ArrayList<String>(supportedCiphers.size()); for (String c : ciphers) { if (c == null) { break; } newCiphers.add(c); } return newCiphers.toArray(EmptyArrays.EMPTY_STRINGS); } } }
IdentityCipherSuiteFilter
java
google__auto
value/src/main/java/com/google/auto/value/extension/toprettystring/processor/ToPrettyStringValidator.java
{ "start": 5158, "end": 5494 }
class ____ { private final ExecutableElement method; private final Messager messager; ErrorReporter(ExecutableElement method, Messager messager) { this.method = method; this.messager = messager; } void reportError(String error) { messager.printMessage(ERROR, error, method); } } }
ErrorReporter
java
square__moshi
moshi/src/test/java/com/squareup/moshi/MoshiTest.java
{ "start": 52590, "end": 52711 }
enum ____ { ROCK, PAPER, @Json(name = "scr") SCISSORS } @Retention(RUNTIME) @JsonQualifier @
Roshambo
java
apache__camel
components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppConfiguration.java
{ "start": 23968, "end": 26974 }
interface ____ to be used in the binding request with the SMSC. The following values are allowed, * as defined in the SMPP protocol (and the underlying implementation using the jSMPP library, respectively): * "legacy" (0x00), "3.3" (0x33), "3.4" (0x34), and "5.0" (0x50). The default (fallback) value is version 3.4. */ public void setInterfaceVersion(String interfaceVersion) { this.interfaceVersion = interfaceVersion; } public InterfaceVersion getInterfaceVersionByte() { return switch (interfaceVersion) { case "legacy" -> InterfaceVersion.IF_00; case "3.3" -> InterfaceVersion.IF_33; case "3.4" -> InterfaceVersion.IF_34; case "5.0" -> InterfaceVersion.IF_50; default -> InterfaceVersion.IF_34; }; } @Override public String toString() { return "SmppConfiguration[usingSSL=" + usingSSL + ", enquireLinkTimer=" + enquireLinkTimer + ", host=" + host + ", password=" + password + ", port=" + port + ", systemId=" + systemId + ", systemType=" + systemType + ", dataCoding=" + dataCoding + ", alphabet=" + alphabet + ", encoding=" + encoding + ", transactionTimer=" + transactionTimer + ", pduProcessorQueueCapacity=" + pduProcessorQueueCapacity + ", pduProcessorDegree=" + pduProcessorDegree + ", registeredDelivery=" + registeredDelivery + ", singleDLR=" + singleDLR + ", serviceType=" + serviceType + ", sourceAddrTon=" + sourceAddrTon + ", destAddrTon=" + destAddrTon + ", sourceAddrNpi=" + sourceAddrNpi + ", destAddrNpi=" + destAddrNpi + ", addressRange=" + addressRange + ", protocolId=" + protocolId + ", priorityFlag=" + priorityFlag + ", replaceIfPresentFlag=" + replaceIfPresentFlag + ", sourceAddr=" + sourceAddr + ", destAddr=" + destAddr + ", typeOfNumber=" + typeOfNumber + ", numberingPlanIndicator=" + numberingPlanIndicator + ", initialReconnectDelay=" + initialReconnectDelay + ", reconnectDelay=" + reconnectDelay + ", maxReconnect=" + maxReconnect + ", lazySessionCreation=" + lazySessionCreation + ", messageReceiverRouteId=" + messageReceiverRouteId + ", httpProxyHost=" + httpProxyHost + ", httpProxyPort=" + httpProxyPort + ", httpProxyUsername=" + httpProxyUsername + ", httpProxyPassword=" + httpProxyPassword + ", splittingPolicy=" + splittingPolicy + ", proxyHeaders=" + proxyHeaders + ", interfaceVersion=" + interfaceVersion + "]"; } }
version
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/Enhancer.java
{ "start": 478, "end": 611 }
class ____ parallel: the * Enhancer implementations are not required to guard against this. * * @param className The name of the
in
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java
{ "start": 1383, "end": 9030 }
class ____ { private static final Pattern CLUSTER_NAME_PATTERN = Pattern.compile(CLUSTER_NAME_PATTERN_STRING); private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_PATTERN_STRING); /** * Returns a combined string with serviceName and groupName. serviceName can not be nil. * * <p>In most cases, serviceName can not be nil. In other cases, for search or anything, See {@link * com.alibaba.nacos.api.naming.utils.NamingUtils#getGroupedNameOptional(String, String)} * * <p>etc: * <p>serviceName | groupName | result</p> * <p>serviceA | groupA | groupA@@serviceA</p> * <p>nil | groupA | threw IllegalArgumentException</p> * * @return 'groupName@@serviceName' */ public static String getGroupedName(final String serviceName, final String groupName) { if (StringUtils.isBlank(serviceName)) { throw new IllegalArgumentException("Param 'serviceName' is illegal, serviceName is blank"); } if (StringUtils.isBlank(groupName)) { throw new IllegalArgumentException("Param 'groupName' is illegal, groupName is blank"); } final String resultGroupedName = groupName + Constants.SERVICE_INFO_SPLITER + serviceName; return resultGroupedName.intern(); } public static String getServiceKey(String namespace, String group, String serviceName) { if (StringUtils.isBlank(namespace)) { namespace = DEFAULT_NAMESPACE_ID; } return namespace + Constants.SERVICE_INFO_SPLITER + group + Constants.SERVICE_INFO_SPLITER + serviceName; } /** * parse service key items for serviceKey. item[0] for namespace item[1] for group item[2] for service name * * @param serviceKey serviceKey. * @return */ public static String[] parseServiceKey(String serviceKey) { return serviceKey.split(Constants.SERVICE_INFO_SPLITER); } public static String getServiceName(final String serviceNameWithGroup) { if (StringUtils.isBlank(serviceNameWithGroup)) { return StringUtils.EMPTY; } if (!serviceNameWithGroup.contains(Constants.SERVICE_INFO_SPLITER)) { return serviceNameWithGroup; } return serviceNameWithGroup.split(Constants.SERVICE_INFO_SPLITER)[1]; } public static String getGroupName(final String serviceNameWithGroup) { if (StringUtils.isBlank(serviceNameWithGroup)) { return StringUtils.EMPTY; } if (!serviceNameWithGroup.contains(Constants.SERVICE_INFO_SPLITER)) { return Constants.DEFAULT_GROUP; } return serviceNameWithGroup.split(Constants.SERVICE_INFO_SPLITER)[0]; } /** * Check serviceName is compatibility mode or not. * * @param serviceName serviceName * @return if serviceName is compatibility mode, return true */ public static boolean isServiceNameCompatibilityMode(final String serviceName) { return !StringUtils.isBlank(serviceName) && serviceName.contains(Constants.SERVICE_INFO_SPLITER); } /** * check combineServiceName format. the serviceName can't be blank. * <pre> * serviceName = "@@"; the length = 0; illegal * serviceName = "group@@"; the length = 1; illegal * serviceName = "@@serviceName"; the length = 2; illegal * serviceName = "group@@serviceName"; the length = 2; legal * </pre> * * @param combineServiceName such as: groupName@@serviceName */ public static void checkServiceNameFormat(String combineServiceName) { String[] split = combineServiceName.split(Constants.SERVICE_INFO_SPLITER); if (split.length <= 1) { throw new IllegalArgumentException( "Param 'serviceName' is illegal, it should be format as 'groupName@@serviceName'"); } if (split[0].isEmpty()) { throw new IllegalArgumentException("Param 'serviceName' is illegal, groupName can't be empty"); } } /** * Returns a combined string with serviceName and groupName. Such as 'groupName@@serviceName' * <p>This method works similar with {@link com.alibaba.nacos.api.naming.utils.NamingUtils#getGroupedName} But not * verify any parameters. * * </p> etc: * <p>serviceName | groupName | result</p> * <p>serviceA | groupA | groupA@@serviceA</p> * <p>nil | groupA | groupA@@</p> * <p>nil | nil | @@</p> * * @return 'groupName@@serviceName' */ public static String getGroupedNameOptional(final String serviceName, final String groupName) { return groupName + Constants.SERVICE_INFO_SPLITER + serviceName; } /** * <p>Check instance param about keep alive.</p> * * <pre> * heart beat timeout must > heart beat interval * ip delete timeout must > heart beat interval * </pre> * * @param instance need checked instance * @throws NacosException if check failed, throw exception */ public static void checkInstanceIsLegal(Instance instance) throws NacosException { if (null == instance) { throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR, "Instance can not be null."); } if (instance.getInstanceHeartBeatTimeOut() < instance.getInstanceHeartBeatInterval() || instance.getIpDeleteTimeout() < instance.getInstanceHeartBeatInterval()) { throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR, "Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'."); } if (!StringUtils.isEmpty(instance.getClusterName()) && !CLUSTER_NAME_PATTERN.matcher(instance.getClusterName()) .matches()) { throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR, String.format("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: %s)", instance.getClusterName())); } } /** * check batch register is Ephemeral. * * @param instance instance * @throws NacosException NacosException */ public static void checkInstanceIsEphemeral(Instance instance) throws NacosException { if (!instance.isEphemeral()) { throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR, String.format("Batch registration does not allow persistent instance registration , Instance:%s", instance)); } } /** * Batch verify the validity of instances. * * @param instances List of instances to be registered * @throws NacosException Nacos */ public static void batchCheckInstanceIsLegal(List<Instance> instances) throws NacosException { Set<Instance> newInstanceSet = new HashSet<>(instances); for (Instance instance : newInstanceSet) { checkInstanceIsEphemeral(instance); checkInstanceIsLegal(instance); } } /** * Check string is a number or not. * * @param str a string of digits * @return if it is a string of digits, return true */ public static boolean isNumber(String str) { return !StringUtils.isEmpty(str) && NUMBER_PATTERN.matcher(str).matches(); } }
NamingUtils
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/SelfEqualsTest.java
{ "start": 7408, "end": 8936 }
class ____ { private String field = ""; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SelfEqualsGuavaPositiveCase other = (SelfEqualsGuavaPositiveCase) o; boolean retVal; // BUG: Diagnostic contains: Objects.equal(field, other.field) retVal = Objects.equal(field, field); // BUG: Diagnostic contains: Objects.equal(other.field, this.field) retVal &= Objects.equal(field, this.field); // BUG: Diagnostic contains: Objects.equal(this.field, other.field) retVal &= Objects.equal(this.field, field); // BUG: Diagnostic contains: Objects.equal(this.field, other.field) retVal &= Objects.equal(this.field, this.field); return retVal; } @Override public int hashCode() { return Objects.hashCode(field); } public static void test() { ForTesting tester = new ForTesting(); // BUG: Diagnostic contains: Objects.equal(tester.testing.testing, tester.testing) Objects.equal(tester.testing.testing, tester.testing.testing); } private static
SelfEqualsGuavaPositiveCase
java
google__dagger
javatests/artifacts/dagger-ksp/transitive-annotation-app/library1/src/main/java/library1/AssistedFoo.java
{ "start": 3279, "end": 3603 }
interface ____ { @MyTransitiveAnnotation @MyAnnotation(MyTransitiveType.VALUE) @MyOtherAnnotation(MyTransitiveType.class) AssistedFoo create( @MyTransitiveAnnotation @MyAnnotation(MyTransitiveType.VALUE) @MyOtherAnnotation(MyTransitiveType.class) int i); } }
Factory
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/ir/FlipArrayIndexNode.java
{ "start": 616, "end": 1135 }
class ____ extends UnaryNode { /* ---- begin visitor ---- */ @Override public <Scope> void visit(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) { irTreeVisitor.visitFlipArrayIndex(this, scope); } @Override public <Scope> void visitChildren(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) { getChildNode().visit(irTreeVisitor, scope); } /* ---- end visitor ---- */ public FlipArrayIndexNode(Location location) { super(location); } }
FlipArrayIndexNode
java
grpc__grpc-java
protobuf-lite/src/test/java/io/grpc/protobuf/lite/ProtoLiteUtilsTest.java
{ "start": 1845, "end": 11470 }
class ____ { private final Marshaller<Type> marshaller = ProtoLiteUtils.marshaller(Type.getDefaultInstance()); private Type proto = Type.newBuilder().setName("name").build(); @Test public void testPassthrough() { assertSame(proto, marshaller.parse(marshaller.stream(proto))); } @Test public void testRoundtrip() throws Exception { InputStream is = marshaller.stream(proto); is = new ByteArrayInputStream(ByteStreams.toByteArray(is)); assertEquals(proto, marshaller.parse(is)); } @Test public void testInvalidatedMessage() throws Exception { InputStream is = marshaller.stream(proto); // Invalidates message, and drains all bytes byte[] unused = ByteStreams.toByteArray(is); try { ((ProtoInputStream) is).message(); fail("Expected exception"); } catch (IllegalStateException ex) { // expected } // Zero bytes is the default message assertEquals(Type.getDefaultInstance(), marshaller.parse(is)); } @Test public void parseInvalid() { InputStream is = new ByteArrayInputStream(new byte[] {-127}); try { marshaller.parse(is); fail("Expected exception"); } catch (StatusRuntimeException ex) { assertEquals(Status.Code.INTERNAL, ex.getStatus().getCode()); assertNotNull(((InvalidProtocolBufferException) ex.getCause()).getUnfinishedMessage()); } } @Test public void testMismatch() { Marshaller<Enum> enumMarshaller = ProtoLiteUtils.marshaller(Enum.getDefaultInstance()); // Enum's name and Type's name are both strings with tag 1. Enum altProto = Enum.newBuilder().setName(proto.getName()).build(); assertEquals(proto, marshaller.parse(enumMarshaller.stream(altProto))); } @Test public void introspection() { Marshaller<Enum> enumMarshaller = ProtoLiteUtils.marshaller(Enum.getDefaultInstance()); PrototypeMarshaller<Enum> prototypeMarshaller = (PrototypeMarshaller<Enum>) enumMarshaller; assertSame(Enum.getDefaultInstance(), prototypeMarshaller.getMessagePrototype()); assertSame(Enum.class, prototypeMarshaller.getMessageClass()); } @Test public void marshallerShouldNotLimitProtoSize() throws Exception { // The default limit is 64MB. Using a larger proto to verify that the limit is not enforced. byte[] bigName = new byte[70 * 1024 * 1024]; Arrays.fill(bigName, (byte) 32); proto = Type.newBuilder().setNameBytes(ByteString.copyFrom(bigName)).build(); // Just perform a round trip to verify that it works. testRoundtrip(); } @Test public void testAvailable() throws Exception { InputStream is = marshaller.stream(proto); assertEquals(proto.getSerializedSize(), is.available()); is.read(); assertEquals(proto.getSerializedSize() - 1, is.available()); while (is.read() != -1) {} assertEquals(-1, is.read()); assertEquals(0, is.available()); } @Test public void testEmpty() throws IOException { Marshaller<Empty> marshaller = ProtoLiteUtils.marshaller(Empty.getDefaultInstance()); InputStream is = marshaller.stream(Empty.getDefaultInstance()); assertEquals(0, is.available()); byte[] b = new byte[10]; assertEquals(-1, is.read(b)); assertArrayEquals(new byte[10], b); // Do the same thing again, because the internal state may be different assertEquals(-1, is.read(b)); assertArrayEquals(new byte[10], b); assertEquals(-1, is.read()); assertEquals(0, is.available()); } @Test public void testDrainTo_all() throws Exception { byte[] golden = ByteStreams.toByteArray(marshaller.stream(proto)); InputStream is = marshaller.stream(proto); Drainable d = (Drainable) is; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int drained = d.drainTo(baos); assertEquals(baos.size(), drained); assertArrayEquals(golden, baos.toByteArray()); assertEquals(0, is.available()); } @Test public void testDrainTo_partial() throws Exception { final byte[] golden; { InputStream is = marshaller.stream(proto); is.read(); golden = ByteStreams.toByteArray(is); } InputStream is = marshaller.stream(proto); is.read(); Drainable d = (Drainable) is; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int drained = d.drainTo(baos); assertEquals(baos.size(), drained); assertArrayEquals(golden, baos.toByteArray()); assertEquals(0, is.available()); } @Test public void testDrainTo_none() throws Exception { InputStream is = marshaller.stream(proto); byte[] unused = ByteStreams.toByteArray(is); Drainable d = (Drainable) is; ByteArrayOutputStream baos = new ByteArrayOutputStream(); assertEquals(0, d.drainTo(baos)); assertArrayEquals(new byte[0], baos.toByteArray()); assertEquals(0, is.available()); } @Test public void metadataMarshaller_roundtrip() { Metadata.BinaryMarshaller<Type> metadataMarshaller = ProtoLiteUtils.metadataMarshaller(Type.getDefaultInstance()); assertEquals(proto, metadataMarshaller.parseBytes(metadataMarshaller.toBytes(proto))); } @Test public void metadataMarshaller_invalid() { Metadata.BinaryMarshaller<Type> metadataMarshaller = ProtoLiteUtils.metadataMarshaller(Type.getDefaultInstance()); try { metadataMarshaller.parseBytes(new byte[] {-127}); fail("Expected exception"); } catch (IllegalArgumentException ex) { assertNotNull(((InvalidProtocolBufferException) ex.getCause()).getUnfinishedMessage()); } } @Test public void extensionRegistry_notNull() { NullPointerException e = assertThrows(NullPointerException.class, () -> ProtoLiteUtils.setExtensionRegistry(null)); assertThat(e).hasMessageThat().isEqualTo("newRegistry"); } @Test public void parseFromKnowLengthInputStream() { Marshaller<Type> marshaller = ProtoLiteUtils.marshaller(Type.getDefaultInstance()); Type expect = Type.newBuilder().setName("expected name").build(); Type result = marshaller.parse(new CustomKnownLengthInputStream(expect.toByteArray())); assertEquals(expect, result); } @Test public void defaultMaxMessageSize() { assertEquals(GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE, ProtoLiteUtils.DEFAULT_MAX_MESSAGE_SIZE); } @Test public void testNullDefaultInstance() { String expectedMessage = "defaultInstance cannot be null"; assertThrows(expectedMessage, NullPointerException.class, () -> ProtoLiteUtils.marshaller(null)); assertThrows(expectedMessage, NullPointerException.class, () -> ProtoLiteUtils.marshallerWithRecursionLimit(null, 10) ); } @Test public void givenPositiveLimit_testRecursionLimitExceeded() throws IOException { Marshaller<SimpleRecursiveMessage> marshaller = ProtoLiteUtils.marshallerWithRecursionLimit( SimpleRecursiveMessage.getDefaultInstance(), 10); SimpleRecursiveMessage message = buildRecursiveMessage(12); assertRecursionLimitExceeded(marshaller, message); } @Test public void givenZeroLimit_testRecursionLimitExceeded() throws IOException { Marshaller<SimpleRecursiveMessage> marshaller = ProtoLiteUtils.marshallerWithRecursionLimit( SimpleRecursiveMessage.getDefaultInstance(), 0); SimpleRecursiveMessage message = buildRecursiveMessage(1); assertRecursionLimitExceeded(marshaller, message); } @Test public void givenPositiveLimit_testRecursionLimitNotExceeded() throws IOException { Marshaller<SimpleRecursiveMessage> marshaller = ProtoLiteUtils.marshallerWithRecursionLimit( SimpleRecursiveMessage.getDefaultInstance(), 15); SimpleRecursiveMessage message = buildRecursiveMessage(12); assertRecursionLimitNotExceeded(marshaller, message); } @Test public void givenZeroLimit_testRecursionLimitNotExceeded() throws IOException { Marshaller<SimpleRecursiveMessage> marshaller = ProtoLiteUtils.marshallerWithRecursionLimit( SimpleRecursiveMessage.getDefaultInstance(), 0); SimpleRecursiveMessage message = buildRecursiveMessage(0); assertRecursionLimitNotExceeded(marshaller, message); } @Test public void testDefaultRecursionLimit() throws IOException { Marshaller<SimpleRecursiveMessage> marshaller = ProtoLiteUtils.marshaller( SimpleRecursiveMessage.getDefaultInstance()); SimpleRecursiveMessage message = buildRecursiveMessage(100); assertRecursionLimitNotExceeded(marshaller, message); } private static void assertRecursionLimitExceeded(Marshaller<SimpleRecursiveMessage> marshaller, SimpleRecursiveMessage message) throws IOException { InputStream is = marshaller.stream(message); ByteArrayInputStream bais = new ByteArrayInputStream(ByteStreams.toByteArray(is)); assertThrows(StatusRuntimeException.class, () -> marshaller.parse(bais)); } private static void assertRecursionLimitNotExceeded(Marshaller<SimpleRecursiveMessage> marshaller, SimpleRecursiveMessage message) throws IOException { InputStream is = marshaller.stream(message); ByteArrayInputStream bais = new ByteArrayInputStream(ByteStreams.toByteArray(is)); assertEquals(message, marshaller.parse(bais)); } private static SimpleRecursiveMessage buildRecursiveMessage(int depth) { SimpleRecursiveMessage.Builder builder = SimpleRecursiveMessage.newBuilder() .setValue("depth-" + depth); for (int i = depth; i > 0; i--) { builder = SimpleRecursiveMessage.newBuilder() .setValue("depth-" + i) .setMessage(builder.build()); } return builder.build(); } private static
ProtoLiteUtilsTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/conversion/StructuredObjectConverter.java
{ "start": 2333, "end": 15058 }
class ____<T> implements DataStructureConverter<RowData, T> { private static final long serialVersionUID = 1L; private final DataStructureConverter<Object, Object>[] fieldConverters; private final RowData.FieldGetter[] fieldGetters; private final String generatedName; private final String generatedCode; private transient DataStructureConverter<RowData, T> generatedConverter; private StructuredObjectConverter( DataStructureConverter<Object, Object>[] fieldConverters, RowData.FieldGetter[] fieldGetters, String generatedName, String generatedCode) { this.fieldConverters = fieldConverters; this.fieldGetters = fieldGetters; this.generatedName = generatedName; this.generatedCode = generatedCode; } @Override public void open(ClassLoader classLoader) { for (DataStructureConverter<Object, Object> fieldConverter : fieldConverters) { fieldConverter.open(classLoader); } try { final Class<?> compiledConverter = CompileUtils.compile(classLoader, generatedName, generatedCode); generatedConverter = (DataStructureConverter<RowData, T>) compiledConverter .getConstructor( RowData.FieldGetter[].class, DataStructureConverter[].class) .newInstance(fieldGetters, fieldConverters); } catch (Throwable t) { throw new TableException("Error while generating structured type converter.", t); } generatedConverter.open(classLoader); } @Override public RowData toInternal(T external) { return generatedConverter.toInternal(external); } @Override public T toExternal(RowData internal) { return generatedConverter.toExternal(internal); } // -------------------------------------------------------------------------------------------- // Factory method // -------------------------------------------------------------------------------------------- private static final AtomicInteger nextUniqueClassId = new AtomicInteger(); public static StructuredObjectConverter<?> create(DataType dataType) { try { return createOrError(dataType); } catch (Throwable t) { throw new TableException( String.format("Could not create converter for structured type '%s'.", dataType), t); } } /** * Creates a {@link DataStructureConverter} for the given structured type. * * <p>Note: We do not perform validation if data type and structured type implementation match. * This must have been done earlier in the {@link DataTypeFactory}. */ @SuppressWarnings("RedundantCast") private static StructuredObjectConverter<?> createOrError(DataType dataType) { final List<DataType> fields = dataType.getChildren(); final DataStructureConverter<Object, Object>[] fieldConverters = fields.stream() .map( dt -> (DataStructureConverter<Object, Object>) DataStructureConverters.getConverter(dt)) .toArray(DataStructureConverter[]::new); final RowData.FieldGetter[] fieldGetters = IntStream.range(0, fields.size()) .mapToObj( pos -> RowData.createFieldGetter( fields.get(pos).getLogicalType(), pos)) .toArray(RowData.FieldGetter[]::new); final Class<?>[] fieldClasses = fields.stream().map(DataType::getConversionClass).toArray(Class[]::new); final StructuredType structuredType = (StructuredType) dataType.getLogicalType(); final Class<?> implementationClass = structuredType.getImplementationClass().orElseThrow(IllegalStateException::new); final int uniqueClassId = nextUniqueClassId.getAndIncrement(); final String converterName = String.format( "%s$%s$Converter", implementationClass.getName().replace('.', '$'), uniqueClassId); final String converterCode = generateCode( converterName, implementationClass, getFieldNames(structuredType).toArray(new String[0]), fieldClasses); return new StructuredObjectConverter<>( fieldConverters, fieldGetters, converterName, converterCode); } private static String generateCode( String converterName, Class<?> clazz, String[] fieldNames, Class<?>[] fieldClasses) { final int fieldCount = fieldClasses.length; final StringBuilder sb = new StringBuilder(); // we ignore checkstyle here for readability and preserving indention line( sb, "public class ", converterName, " implements ", DataStructureConverter.class, " {"); line(sb, " private final ", RowData.FieldGetter.class, "[] fieldGetters;"); line(sb, " private final ", DataStructureConverter.class, "[] fieldConverters;"); line( sb, " public ", converterName, "(", RowData.FieldGetter.class, "[] fieldGetters, ", DataStructureConverter.class, "[] fieldConverters) {"); line(sb, " this.fieldGetters = fieldGetters;"); line(sb, " this.fieldConverters = fieldConverters;"); line(sb, " }"); line(sb, " public ", Object.class, " toInternal(", Object.class, " o) {"); line(sb, " final ", clazz, " external = (", clazz, ") o;"); line( sb, " final ", GenericRowData.class, " genericRow = new ", GenericRowData.class, "(", fieldCount, ");"); for (int pos = 0; pos < fieldCount; pos++) { line(sb, " ", getterExpr(clazz, pos, fieldNames[pos], fieldClasses[pos]), ";"); } line(sb, " return genericRow;"); line(sb, " }"); line(sb, " public ", Object.class, " toExternal(", Object.class, " o) {"); line(sb, " final ", RowData.class, " internal = (", RowData.class, ") o;"); if (hasInvokableConstructor(clazz, fieldClasses)) { line(sb, " final ", clazz, " structured = new ", clazz, "("); for (int pos = 0; pos < fieldCount; pos++) { line( sb, " ", parameterExpr(pos, fieldClasses[pos]), (pos < fieldCount - 1) ? ", " : ""); } line(sb, " );"); } else { line(sb, " final ", clazz, " structured = new ", clazz, "();"); for (int pos = 0; pos < fieldCount; pos++) { line(sb, " ", setterExpr(clazz, pos, fieldNames[pos]), ";"); } } line(sb, " return structured;"); line(sb, " }"); line(sb, "}"); return sb.toString(); } private static String getterExpr( Class<?> implementationClass, int pos, String fieldName, Class<?> fieldClass) { final Field field = getStructuredField(implementationClass, fieldName); String accessExpr; if (isStructuredFieldDirectlyReadable(field)) { // field is accessible without getter accessExpr = expr("external.", field.getName()); } else { // field is accessible with a getter final Method getter = getStructuredFieldGetter(implementationClass, field) .orElseThrow( () -> fieldNotReadableException( implementationClass, fieldName)); accessExpr = expr("external.", getter.getName(), "()"); } accessExpr = castExpr(accessExpr, fieldClass); return expr( "genericRow.setField(", pos, ", fieldConverters[", pos, "].toInternalOrNull(", accessExpr, "))"); } private static IllegalStateException fieldNotReadableException( Class<?> implementationClass, String fieldName) { return new IllegalStateException( String.format( "Could not find a getter for field '%s' in class '%s'. " + "Make sure that the field is readable (via public visibility or getter).", fieldName, implementationClass.getName())); } private static IllegalStateException fieldNotWritableException( Class<?> implementationClass, String fieldName) { return new IllegalStateException( String.format( "Could not find a setter for field '%s' in class '%s'. " + "Make sure that the field is writable (via public visibility, " + "setter, or full constructor).", fieldName, implementationClass.getName())); } private static String parameterExpr(int pos, Class<?> fieldClass) { final String conversionExpr = expr( "fieldConverters[", pos, "].toExternalOrNull(fieldGetters[", pos, "].getFieldOrNull(internal))"); return castExpr(conversionExpr, fieldClass); } private static String setterExpr(Class<?> implementationClass, int pos, String fieldName) { final Field field = getStructuredField(implementationClass, fieldName); final String conversionExpr = expr( "fieldConverters[", pos, "].toExternalOrNull(fieldGetters[", pos, "].getFieldOrNull(internal))"); if (isStructuredFieldDirectlyWritable(field)) { // field is accessible without setter return expr( "structured.", field.getName(), " = ", castExpr(conversionExpr, field.getType())); } else { // field is accessible with a setter final Method setter = getStructuredFieldSetter(implementationClass, field) .orElseThrow( () -> fieldNotWritableException( implementationClass, fieldName)); return expr( "structured.", setter.getName(), "(", castExpr(conversionExpr, setter.getParameterTypes()[0]), ")"); } } private static String castExpr(String expr, Class<?> clazz) { // help Janino to box primitive types and fix missing generics return expr("((", primitiveToWrapper(clazz), ") ", expr, ")"); } private static String expr(Object... parts) { final StringBuilder sb = new StringBuilder(); for (Object part : parts) { if (part instanceof Class) { sb.append(((Class<?>) part).getCanonicalName()); } else { sb.append(part); } } return sb.toString(); } private static void line(StringBuilder sb, Object... parts) { for (Object part : parts) { if (part instanceof Class) { sb.append(((Class<?>) part).getCanonicalName()); } else { sb.append(part); } } sb.append("\n"); } }
StructuredObjectConverter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MisleadingEmptyVarargsTest.java
{ "start": 821, "end": 1271 }
class ____ { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(MisleadingEmptyVarargs.class, getClass()); @Test public void positive() { helper .addSourceLines( "Test.java", """ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
MisleadingEmptyVarargsTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TypeParameterUnusedInFormalsTest.java
{ "start": 1992, "end": 2413 }
class ____ { // BUG: Diagnostic contains: static <T, U extends Object> T doCast(U o) { T t = (T) o; return t; } } """) .doTest(); } @Test public void leadingAndTrailingParam() { compilationHelper .addSourceLines( "Test.java", """ package foo.bar;
Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ThrowNullTest.java
{ "start": 1127, "end": 1471 }
class ____ { void f() { // BUG: Diagnostic contains: throw new NullPointerException(); throw null; } } """) .doTest(); } @Test public void negative() { testHelper .addSourceLines( "Test.java", """
Test
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/jackson/src/main/java/org/jboss/resteasy/reactive/server/jackson/JacksonMessageBodyWriterUtil.java
{ "start": 691, "end": 3329 }
class ____ { private JacksonMessageBodyWriterUtil() { } public static ObjectWriter createDefaultWriter(ObjectMapper mapper) { // we don't want the ObjectWriter to close the stream automatically, as we want to handle closing manually at the proper points JsonFactory jsonFactory = mapper.getFactory(); if (JacksonMessageBodyWriterUtil.needsNewFactory(jsonFactory)) { jsonFactory = jsonFactory.copy(); JacksonMessageBodyWriterUtil.setNecessaryJsonFactoryConfig(jsonFactory); jsonFactory.setCodec(mapper); return mapper.writer().with(jsonFactory); } else { return mapper.writer(); } } private static boolean needsNewFactory(JsonFactory jsonFactory) { return jsonFactory.isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET) || jsonFactory.isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM); } public static void setNecessaryJsonFactoryConfig(JsonFactory jsonFactory) { jsonFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); jsonFactory.configure(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM, false); } public static void doLegacyWrite(Object o, Annotation[] annotations, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream, ObjectWriter defaultWriter) throws IOException { setContentTypeIfNecessary(httpHeaders); if ((o instanceof String) && (!(entityStream instanceof StreamingOutputStream))) { // YUK: done in order to avoid adding extra quotes... when we are not streaming a result entityStream.write(((String) o).getBytes(StandardCharsets.UTF_8)); } else { if (annotations != null) { for (Annotation annotation : annotations) { if (JsonView.class.equals(annotation.annotationType())) { if (handleJsonView(((JsonView) annotation), o, entityStream, defaultWriter)) { return; } } } } entityStream.write(defaultWriter.writeValueAsString(o).getBytes(StandardCharsets.UTF_8)); } } private static boolean handleJsonView(JsonView jsonView, Object o, OutputStream stream, ObjectWriter defaultWriter) throws IOException { if ((jsonView != null) && (jsonView.value().length > 0)) { defaultWriter.withView(jsonView.value()[0]).writeValue(stream, o); return true; } return false; } }
JacksonMessageBodyWriterUtil
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleTakeUntil.java
{ "start": 3922, "end": 5073 }
class ____ extends AtomicReference<Subscription> implements FlowableSubscriber<Object> { private static final long serialVersionUID = 5170026210238877381L; final TakeUntilMainObserver<?> parent; TakeUntilOtherSubscriber(TakeUntilMainObserver<?> parent) { this.parent = parent; } @Override public void onSubscribe(Subscription s) { SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override public void onNext(Object t) { if (SubscriptionHelper.cancel(this)) { parent.otherError(new CancellationException()); } } @Override public void onError(Throwable t) { parent.otherError(t); } @Override public void onComplete() { if (get() != SubscriptionHelper.CANCELLED) { lazySet(SubscriptionHelper.CANCELLED); parent.otherError(new CancellationException()); } } public void dispose() { SubscriptionHelper.cancel(this); } } }
TakeUntilOtherSubscriber
java
lettuce-io__lettuce-core
src/test/jmh/io/lettuce/core/protocol/CommandHandlerBenchmark.java
{ "start": 1416, "end": 5391 }
class ____ { private static final ByteArrayCodec CODEC = new ByteArrayCodec(); private static final ClientOptions CLIENT_OPTIONS = ClientOptions.create(); private static final EmptyContext CHANNEL_HANDLER_CONTEXT = new EmptyContext(); private static final byte[] KEY = "key".getBytes(); private static final String VALUE = "value\r\n"; private final EmptyPromise PROMISE = new EmptyPromise(); private CommandHandler commandHandler; private ByteBuf reply1; private ByteBuf reply10; private ByteBuf reply100; private ByteBuf reply1000; private List<Command> commands1; private List<Command> commands10; private List<Command> commands100; private List<Command> commands1000; @Setup public void setup() throws Exception { commandHandler = new CommandHandler(CLIENT_OPTIONS, EmptyClientResources.INSTANCE, new DefaultEndpoint(CLIENT_OPTIONS, EmptyClientResources.INSTANCE)); commandHandler.channelRegistered(CHANNEL_HANDLER_CONTEXT); commandHandler.setState(CommandHandler.LifecycleState.CONNECTED); reply1 = createByteBuf(String.format("+%s", VALUE)); reply10 = createByteBuf(createBulkReply(10)); reply100 = createByteBuf(createBulkReply(100)); reply1000 = createByteBuf(createBulkReply(1000)); commands1 = createCommands(1); commands10 = createCommands(10); commands100 = createCommands(100); commands1000 = createCommands(1000); } @TearDown public void tearDown() throws Exception { commandHandler.channelUnregistered(CHANNEL_HANDLER_CONTEXT); Arrays.asList(reply1, reply10, reply100, reply1000).forEach(ByteBuf::release); } private static List<Command> createCommands(int count) { return IntStream.range(0, count).mapToObj(i -> createCommand()).collect(Collectors.toList()); } private static ByteBuf createByteBuf(String str) { ByteBuf buf = CHANNEL_HANDLER_CONTEXT.alloc().directBuffer(); buf.writeBytes(str.getBytes()); return buf; } private static String createBulkReply(int numOfReplies) { String baseReply = String.format("$%d\r\n%s\r\n", VALUE.length(), VALUE); return String.join("", Collections.nCopies(numOfReplies, baseReply)); } @SuppressWarnings("unchecked") private static Command createCommand() { return new Command(CommandType.GET, new ValueOutput<>(CODEC), new CommandArgs(CODEC).addKey(KEY)) { @Override public boolean isDone() { return false; } }; } @Benchmark public void measureNettyWriteAndRead() throws Exception { Command command = createCommand(); commandHandler.write(CHANNEL_HANDLER_CONTEXT, command, PROMISE); int index = reply1.readerIndex(); reply1.retain(); commandHandler.channelRead(CHANNEL_HANDLER_CONTEXT, reply1); // cleanup reply1.readerIndex(index); } @Benchmark public void measureNettyWriteAndReadBatch1() throws Exception { doBenchmark(commands1, reply1); } @Benchmark public void measureNettyWriteAndReadBatch10() throws Exception { doBenchmark(commands10, reply10); } @Benchmark public void measureNettyWriteAndReadBatch100() throws Exception { doBenchmark(commands100, reply100); } @Benchmark public void measureNettyWriteAndReadBatch1000() throws Exception { doBenchmark(commands1000, reply1000); } private void doBenchmark(List<Command> commandStack, ByteBuf response) throws Exception { commandHandler.write(CHANNEL_HANDLER_CONTEXT, commandStack, PROMISE); int index = response.readerIndex(); response.retain(); commandHandler.channelRead(CHANNEL_HANDLER_CONTEXT, response); // cleanup response.readerIndex(index); } }
CommandHandlerBenchmark
java
qos-ch__slf4j
slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java
{ "start": 1353, "end": 14094 }
class ____ { Integer i1 = Integer.valueOf(1); Integer i2 = Integer.valueOf(2); Integer i3 = Integer.valueOf(3); Integer[] ia0 = new Integer[] { i1, i2, i3 }; Integer[] ia1 = new Integer[] { Integer.valueOf(10), Integer.valueOf(20), Integer.valueOf(30) }; String result; @Test public void testNull() { result = MessageFormatter.format(null, i1).getMessage(); assertEquals(null, result); } @Test public void testParamaterContainingAnAnchor() { result = MessageFormatter.format("Value is {}.", "[{}]").getMessage(); assertEquals("Value is [{}].", result); result = MessageFormatter.format("Values are {} and {}.", i1, "[{}]").getMessage(); assertEquals("Values are 1 and [{}].", result); } @Test public void nullParametersShouldBeHandledWithoutBarfing() { result = MessageFormatter.format("Value is {}.", null).getMessage(); assertEquals("Value is null.", result); result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null).getMessage(); assertEquals("Val1 is null, val2 is null.", result); result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null).getMessage(); assertEquals("Val1 is 1, val2 is null.", result); result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2).getMessage(); assertEquals("Val1 is null, val2 is 2.", result); result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, null }).getMessage(); assertEquals("Val1 is null, val2 is null, val3 is null", result); result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, i2, i3 }).getMessage(); assertEquals("Val1 is null, val2 is 2, val3 is 3", result); result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, i3 }).getMessage(); assertEquals("Val1 is null, val2 is null, val3 is 3", result); } @Test public void verifyOneParameterIsHandledCorrectly() { result = MessageFormatter.format("Value is {}.", i3).getMessage(); assertEquals("Value is 3.", result); result = MessageFormatter.format("Value is {", i3).getMessage(); assertEquals("Value is {", result); result = MessageFormatter.format("{} is larger than 2.", i3).getMessage(); assertEquals("3 is larger than 2.", result); result = MessageFormatter.format("No subst", i3).getMessage(); assertEquals("No subst", result); result = MessageFormatter.format("Incorrect {subst", i3).getMessage(); assertEquals("Incorrect {subst", result); result = MessageFormatter.format("Value is {bla} {}", i3).getMessage(); assertEquals("Value is {bla} 3", result); result = MessageFormatter.format("Escaped \\{} subst", i3).getMessage(); assertEquals("Escaped {} subst", result); result = MessageFormatter.format("{Escaped", i3).getMessage(); assertEquals("{Escaped", result); result = MessageFormatter.format("\\{}Escaped", i3).getMessage(); assertEquals("{}Escaped", result); result = MessageFormatter.format("File name is {{}}.", "App folder.zip").getMessage(); assertEquals("File name is {App folder.zip}.", result); // escaping the escape character result = MessageFormatter.format("File name is C:\\\\{}.", "App folder.zip").getMessage(); assertEquals("File name is C:\\App folder.zip.", result); } @Test public void testTwoParameters() { result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2).getMessage(); assertEquals("Value 1 is smaller than 2.", result); result = MessageFormatter.format("Value {} is smaller than {}", i1, i2).getMessage(); assertEquals("Value 1 is smaller than 2", result); result = MessageFormatter.format("{}{}", i1, i2).getMessage(); assertEquals("12", result); result = MessageFormatter.format("Val1={}, Val2={", i1, i2).getMessage(); assertEquals("Val1=1, Val2={", result); result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2).getMessage(); assertEquals("Value 1 is smaller than {}", result); result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, i2).getMessage(); assertEquals("Value 1 is smaller than {} tail", result); result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2).getMessage(); assertEquals("Value 1 is smaller than \\{", result); result = MessageFormatter.format("Value {} is smaller than {tail", i1, i2).getMessage(); assertEquals("Value 1 is smaller than {tail", result); result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2).getMessage(); assertEquals("Value {} is smaller than 1", result); } @Test public void testExceptionIn_toString() { Object o = new Object() { public String toString() { throw new IllegalStateException("a"); } }; result = MessageFormatter.format("Troublesome object {}", o).getMessage(); assertEquals("Troublesome object [FAILED toString()]", result); } @Test public void testNullArray() { String msg0 = "msg0"; String msg1 = "msg1 {}"; String msg2 = "msg2 {} {}"; String msg3 = "msg3 {} {} {}"; Object[] args = null; result = MessageFormatter.arrayFormat(msg0, args).getMessage(); assertEquals(msg0, result); result = MessageFormatter.arrayFormat(msg1, args).getMessage(); assertEquals(msg1, result); result = MessageFormatter.arrayFormat(msg2, args).getMessage(); assertEquals(msg2, result); result = MessageFormatter.arrayFormat(msg3, args).getMessage(); assertEquals(msg3, result); } // tests the case when the parameters are supplied in a single array @Test public void testArrayFormat() { result = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia0).getMessage(); assertEquals("Value 1 is smaller than 2 and 3.", result); result = MessageFormatter.arrayFormat("{}{}{}", ia0).getMessage(); assertEquals("123", result); result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0).getMessage(); assertEquals("Value 1 is smaller than 2.", result); result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0).getMessage(); assertEquals("Value 1 is smaller than 2", result); result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage(); assertEquals("Val=1, {, Val=2", result); result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage(); assertEquals("Val=1, {, Val=2", result); result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0).getMessage(); assertEquals("Val1=1, Val2={", result); } @Test public void testArrayValues() { Integer p0 = i1; Integer[] p1 = new Integer[] { i2, i3 }; result = MessageFormatter.format("{}{}", p0, p1).getMessage(); assertEquals("1[2, 3]", result); // Integer[] result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }).getMessage(); assertEquals("a[2, 3]", result); // byte[] result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new byte[] { 1, 2 } }).getMessage(); assertEquals("a[1, 2]", result); // int[] result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new int[] { 1, 2 } }).getMessage(); assertEquals("a[1, 2]", result); // float[] result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new float[] { 1, 2 } }).getMessage(); assertEquals("a[1.0, 2.0]", result); // double[] result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new double[] { 1, 2 } }).getMessage(); assertEquals("a[1.0, 2.0]", result); } @Test public void testMultiDimensionalArrayValues() { Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 }; result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntegerA }).getMessage(); assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } }; result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntA }).getMessage(); assertEquals("a[[1, 2], [10, 20]]", result); float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } }; result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiFloatA }).getMessage(); assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result); Object[][] multiOA = new Object[][] { ia0, ia1 }; result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiOA }).getMessage(); assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); Object[][][] _3DOA = new Object[][][] { multiOA, multiOA }; result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }).getMessage(); assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", result); } @Test public void testCyclicArrays() { { Object[] cyclicA = new Object[1]; cyclicA[0] = cyclicA; assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA).getMessage()); } { Object[] a = new Object[2]; a[0] = i1; Object[] c = new Object[] { i3, a }; Object[] b = new Object[] { i2, c }; a[1] = b; assertEquals("1[2, [3, [1, [...]]]]", MessageFormatter.arrayFormat("{}{}", a).getMessage()); } } @Test public void testArrayThrowable() { FormattingTuple ft; Throwable t = new Throwable(); Object[] ia = new Object[] { i1, i2, i3, t }; Object[] iaWitness = new Object[] { i1, i2, i3 }; ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia); assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("{}{}{}", ia); assertEquals("123", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia); assertEquals("Value 1 is smaller than 2.", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia); assertEquals("Value 1 is smaller than 2", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia); assertEquals("Val=1, {, Val=2", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("Val={}, \\{, Val={}", ia); assertEquals("Val=1, \\{, Val=2", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("Val1={}, Val2={", ia); assertEquals("Val1=1, Val2={", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia); assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("{}{}{}{}", ia); assertEquals("123{}", ft.getMessage()); assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); assertEquals(t, ft.getThrowable()); ft = MessageFormatter.arrayFormat("1={}", new Object[] { i1 }, t); assertEquals("1=1", ft.getMessage()); assertTrue(Arrays.equals(new Object[] { i1 }, ft.getArgArray())); assertEquals(t, ft.getThrowable()); } }
MessageFormatterTest
java
apache__flink
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/ConfigurableRocksDBOptionsFactory.java
{ "start": 957, "end": 1070 }
interface ____ options factory that pick up additional parameters from a configuration. */ @PublicEvolving public
for
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/kotlin/Issue1524.java
{ "start": 246, "end": 906 }
class ____ extends TestCase { public void test_user() throws Exception { ExtClassLoader classLoader = new ExtClassLoader(); Class clazz = classLoader.loadClass("DataClass"); Constructor constructor = clazz.getConstructor(String.class, String.class); Object object = constructor.newInstance("ccc", "ddd"); String json = JSON.toJSONString(object); assertEquals("{\"Id\":\"ccc\",\"Name\":\"ddd\"}", json); Object object2 = JSON.parseObject(json, clazz); String json2 = JSON.toJSONString(object2); assertEquals("{\"Id\":\"ccc\",\"Name\":\"ddd\"}", json2); } public static
Issue1524
java
spring-projects__spring-boot
module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/error/ErrorAttributes.java
{ "start": 1238, "end": 2259 }
interface ____ { /** * Return a {@link Map} of the error attributes. The map can be used as the model of * an error page, or returned as a {@link ServerResponse} body. * @param request the source request * @param options options for error attribute contents * @return a map of error attributes */ default Map<String, @Nullable Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) { return Collections.emptyMap(); } /** * Return the underlying cause of the error or {@code null} if the error cannot be * extracted. * @param request the source ServerRequest * @return the {@link Exception} that caused the error or {@code null} */ @Nullable Throwable getError(ServerRequest request); /** * Store the given error information in the current {@link ServerWebExchange}. * @param error the {@link Exception} that caused the error * @param exchange the source exchange */ void storeErrorInformation(Throwable error, ServerWebExchange exchange); }
ErrorAttributes
java
apache__camel
components/camel-jsonpath/src/main/java/org/apache/camel/jsonpath/JsonPath.java
{ "start": 1591, "end": 2412 }
interface ____ { String value(); /** * Whether to suppress exceptions such as PathNotFoundException */ boolean suppressExceptions() default false; /** * Whether to allow in inlined simple exceptions in the JsonPath expression */ boolean allowSimple() default true; /** * To configure the JsonPath options to use */ Option[] options() default {}; /** * The desired return type. */ Class<?> resultType() default Object.class; /** * Source to use, instead of message body. You can prefix with variable:, header:, or property: to specify kind of * source. Otherwise, the source is assumed to be a variable. Use empty or null to use default source, which is the * message body. */ String source() default ""; }
JsonPath
java
quarkusio__quarkus
extensions/spring-security/deployment/src/test/java/io/quarkus/spring/security/deployment/BeanMethodCheckTest.java
{ "start": 1414, "end": 5782 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses( Person.class, PersonChecker.class, PersonCheckerImpl.class, PrincipalChecker.class, BeanWithBeanMethodChecks.class, SomeInterface.class, SomeInterfaceImpl.class, SpringConfiguration.class, IdentityMock.class, AuthData.class, SecurityTestUtils.class)); @Inject BeanWithBeanMethodChecks beanWithBeanMethodChecks; @Inject SomeInterface someInterface; @Test public void testNoParamsAlwaysPasses() { assertSuccess(() -> beanWithBeanMethodChecks.noParamsAlwaysPasses(), "noParamsAlwaysPasses", ANONYMOUS); assertSuccess(() -> beanWithBeanMethodChecks.noParamsAlwaysPasses(), "noParamsAlwaysPasses", ADMIN); assertSuccess(() -> beanWithBeanMethodChecks.noParamsAlwaysPasses(), "noParamsAlwaysPasses", USER); } @Test public void testNoParamsNeverPasses() { assertFailureFor(() -> beanWithBeanMethodChecks.noParamsNeverPasses(), UnauthorizedException.class, ANONYMOUS); assertFailureFor(() -> beanWithBeanMethodChecks.noParamsNeverPasses(), ForbiddenException.class, USER); assertFailureFor(() -> beanWithBeanMethodChecks.noParamsNeverPasses(), ForbiddenException.class, ADMIN); } @Test public void testWithParams() { assertFailureFor(() -> beanWithBeanMethodChecks.withParams("other", new Person("geo")), UnauthorizedException.class, ANONYMOUS); assertSuccess(() -> beanWithBeanMethodChecks.withParams("geo", new Person("geo")), "withParams", ANONYMOUS); assertFailureFor(() -> beanWithBeanMethodChecks.withParams("other", new Person("geo")), ForbiddenException.class, USER); assertSuccess(() -> beanWithBeanMethodChecks.withParams("geo", new Person("geo")), "withParams", USER); } // the reason for having this test is to ensure that caching of the generated classes doesn't mess up anything @Test public void testAnotherWithParams() { assertFailureFor(() -> beanWithBeanMethodChecks.withParams("other", new Person("geo")), UnauthorizedException.class, ANONYMOUS); assertSuccess(() -> beanWithBeanMethodChecks.withParams("geo", new Person("geo")), "withParams", ANONYMOUS); assertFailureFor(() -> beanWithBeanMethodChecks.withParams("other", new Person("geo")), ForbiddenException.class, USER); assertSuccess(() -> beanWithBeanMethodChecks.withParams("geo", new Person("geo")), "withParams", USER); } @Test public void testWithParamsAndConstant() { assertSuccess(() -> beanWithBeanMethodChecks.withParamAndConstant(new Person("geo")), "withParamAndConstant", ANONYMOUS); assertFailureFor(() -> beanWithBeanMethodChecks.withParamAndConstant(new Person("other")), ForbiddenException.class, USER); assertSuccess(() -> beanWithBeanMethodChecks.withParamAndConstant(new Person("geo")), "withParamAndConstant", USER); } @Test public void testWithExtraUnusedParam() { assertFailureFor(() -> someInterface.doSomething("other", 1, new Person("geo")), UnauthorizedException.class, ANONYMOUS); assertSuccess(() -> someInterface.doSomething("geo", 1, new Person("geo")), "doSomething", ANONYMOUS); assertFailureFor(() -> someInterface.doSomething("other", -1, new Person("geo")), ForbiddenException.class, USER); assertSuccess(() -> someInterface.doSomething("geo", -1, new Person("geo")), "doSomething", USER); } @Test public void testPrincipalUsername() { assertFailureFor(() -> beanWithBeanMethodChecks.principalChecker("user"), UnauthorizedException.class, ANONYMOUS); assertFailureFor(() -> beanWithBeanMethodChecks.principalChecker("other"), ForbiddenException.class, USER); assertSuccess(() -> beanWithBeanMethodChecks.principalChecker("user"), "principalChecker", USER); } }
BeanMethodCheckTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/store/DataBlocks.java
{ "start": 5435, "end": 5548 }
class ____ well. * When closed, any stream is closed. Any source file is untouched. */ public static final
as
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/jackson/CredProtectAuthenticationExtensionsClientInputJackson2Serializer.java
{ "start": 1452, "end": 2757 }
class ____ extends StdSerializer<CredProtectAuthenticationExtensionsClientInput> { protected CredProtectAuthenticationExtensionsClientInputJackson2Serializer() { super(CredProtectAuthenticationExtensionsClientInput.class); } @Override public void serialize(CredProtectAuthenticationExtensionsClientInput input, JsonGenerator jgen, SerializerProvider provider) throws IOException { CredProtectAuthenticationExtensionsClientInput.CredProtect credProtect = input.getInput(); String policy = toString(credProtect.getCredProtectionPolicy()); jgen.writeObjectField("credentialProtectionPolicy", policy); jgen.writeObjectField("enforceCredentialProtectionPolicy", credProtect.isEnforceCredentialProtectionPolicy()); } private static String toString(CredProtectAuthenticationExtensionsClientInput.CredProtect.ProtectionPolicy policy) { switch (policy) { case USER_VERIFICATION_OPTIONAL: return "userVerificationOptional"; case USER_VERIFICATION_OPTIONAL_WITH_CREDENTIAL_ID_LIST: return "userVerificationOptionalWithCredentialIdList"; case USER_VERIFICATION_REQUIRED: return "userVerificationRequired"; default: throw new IllegalArgumentException("Unsupported ProtectionPolicy " + policy); } } }
CredProtectAuthenticationExtensionsClientInputJackson2Serializer
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/StatelessSessionLazyDelegator.java
{ "start": 1194, "end": 15084 }
class ____ implements StatelessSession { private final Supplier<StatelessSession> delegate; public StatelessSessionLazyDelegator(Supplier<StatelessSession> delegate) { this.delegate = delegate; } @Override public void close() { delegate.get().close(); } @Override public Object insert(Object entity) { return delegate.get().insert(entity); } @Override public Object insert(String entityName, Object entity) { return delegate.get().insert(entityName, entity); } @Override public void insertMultiple(List<?> entities) { delegate.get().insertMultiple(entities); } @Override public void update(Object entity) { delegate.get().update(entity); } @Override public void update(String entityName, Object entity) { delegate.get().update(entityName, entity); } @Override public void updateMultiple(List<?> entities) { delegate.get().updateMultiple(entities); } @Override public void delete(Object entity) { delegate.get().delete(entity); } @Override public void delete(String entityName, Object entity) { delegate.get().delete(entityName, entity); } @Override public void deleteMultiple(List<?> entities) { delegate.get().deleteMultiple(entities); } @Override public Object get(String entityName, Object id) { return delegate.get().get(entityName, id); } @Override public <T> T get(Class<T> entityClass, Object id) { return delegate.get().get(entityClass, id); } @Override public Object get(String entityName, Object id, LockMode lockMode) { return delegate.get().get(entityName, id, lockMode); } @Override public <T> T get(Class<T> entityClass, Object id, LockMode lockMode) { return delegate.get().get(entityClass, id, lockMode); } @Override public <T> T get(EntityGraph<T> graph, Object id) { return delegate.get().get(graph, id); } @Override public <T> T get(EntityGraph<T> graph, Object id, LockMode lockMode) { return delegate.get().get(graph, id, lockMode); } @Override public <T> List<T> getMultiple(Class<T> entityClass, List<?> ids) { return delegate.get().getMultiple(entityClass, ids); } @Override public <T> List<T> getMultiple(Class<T> entityClass, List<?> ids, LockMode lockMode) { return delegate.get().getMultiple(entityClass, ids, lockMode); } @Override public <T> List<T> getMultiple(EntityGraph<T> entityGraph, List<?> ids) { return delegate.get().getMultiple(entityGraph, ids); } @Override public <T> List<T> getMultiple(EntityGraph<T> entityGraph, GraphSemantic graphSemantic, List<?> ids) { return delegate.get().getMultiple(entityGraph, graphSemantic, ids); } @Override public Filter enableFilter(String filterName) { return delegate.get().enableFilter(filterName); } @Override public Filter getEnabledFilter(String filterName) { return delegate.get().getEnabledFilter(filterName); } @Override public void disableFilter(String filterName) { delegate.get().disableFilter(filterName); } @Override public void refresh(Object entity) { delegate.get().refresh(entity); } @Override public void refresh(String entityName, Object entity) { delegate.get().refresh(entityName, entity); } @Override public void refresh(Object entity, LockMode lockMode) { delegate.get().refresh(entity, lockMode); } @Override public void refresh(String entityName, Object entity, LockMode lockMode) { delegate.get().refresh(entityName, entity, lockMode); } @Override public void fetch(Object association) { delegate.get().fetch(association); } @Override public Object getIdentifier(Object entity) { return delegate.get().getIdentifier(entity); } @Override public String getTenantIdentifier() { return delegate.get().getTenantIdentifier(); } @Override public Object getTenantIdentifierValue() { return delegate.get().getTenantIdentifier(); } @Override public boolean isOpen() { return delegate.get().isOpen(); } @Override public boolean isConnected() { return delegate.get().isConnected(); } @Override public Transaction beginTransaction() { return delegate.get().beginTransaction(); } @Override public Transaction getTransaction() { return delegate.get().getTransaction(); } @Override public void joinTransaction() { delegate.get().joinTransaction(); } @Override public boolean isJoinedToTransaction() { return delegate.get().isJoinedToTransaction(); } @Override public ProcedureCall getNamedProcedureCall(String name) { return delegate.get().getNamedProcedureCall(name); } @Override public ProcedureCall createStoredProcedureCall(String procedureName) { return delegate.get().createStoredProcedureCall(procedureName); } @Override public ProcedureCall createStoredProcedureCall(String procedureName, Class<?>... resultClasses) { return delegate.get().createStoredProcedureCall(procedureName, resultClasses); } @Override public ProcedureCall createStoredProcedureCall(String procedureName, String... resultSetMappings) { return delegate.get().createStoredProcedureCall(procedureName, resultSetMappings); } @Override public ProcedureCall createNamedStoredProcedureQuery(String name) { return delegate.get().createNamedStoredProcedureQuery(name); } @Override public ProcedureCall createStoredProcedureQuery(String procedureName) { return delegate.get().createStoredProcedureQuery(procedureName); } @Override public ProcedureCall createStoredProcedureQuery(String procedureName, Class<?>... resultClasses) { return delegate.get().createStoredProcedureQuery(procedureName, resultClasses); } @Override public ProcedureCall createStoredProcedureQuery(String procedureName, String... resultSetMappings) { return delegate.get().createStoredProcedureQuery(procedureName, resultSetMappings); } @Override public Integer getJdbcBatchSize() { return delegate.get().getJdbcBatchSize(); } @Override public void setJdbcBatchSize(Integer jdbcBatchSize) { delegate.get().setJdbcBatchSize(jdbcBatchSize); } @Override public HibernateCriteriaBuilder getCriteriaBuilder() { return delegate.get().getCriteriaBuilder(); } @Override public void doWork(Work work) throws HibernateException { delegate.get().doWork(work); } @Override public <T> T doReturningWork(ReturningWork<T> work) throws HibernateException { return delegate.get().doReturningWork(work); } @Override @Deprecated(since = "6.0") public Query createQuery(String queryString) { return delegate.get().createQuery(queryString); } @Override public <R> Query<R> createQuery(String queryString, Class<R> resultClass) { return delegate.get().createQuery(queryString, resultClass); } @Override public <R> Query<R> createQuery(CriteriaQuery<R> criteriaQuery) { return delegate.get().createQuery(criteriaQuery); } @Override @Deprecated(since = "6.0") public Query createQuery(CriteriaUpdate updateQuery) { return delegate.get().createQuery(updateQuery); } @Override @Deprecated(since = "6.0") public Query createQuery(CriteriaDelete deleteQuery) { return delegate.get().createQuery(deleteQuery); } @Override public <R> Query<R> createQuery(TypedQueryReference<R> typedQueryReference) { return delegate.get().createQuery(typedQueryReference); } @Override @Deprecated(since = "6.0") public NativeQuery createNativeQuery(String sqlString) { return delegate.get().createNativeQuery(sqlString); } @Override public <R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass) { return delegate.get().createNativeQuery(sqlString, resultClass); } @Override public <R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass, String tableAlias) { return delegate.get().createNativeQuery(sqlString, resultClass, tableAlias); } @Override @Deprecated(since = "6.0") public NativeQuery createNativeQuery(String sqlString, String resultSetMappingName) { return delegate.get().createNativeQuery(sqlString, resultSetMappingName); } @Override public <R> NativeQuery<R> createNativeQuery(String sqlString, String resultSetMappingName, Class<R> resultClass) { return delegate.get().createNativeQuery(sqlString, resultSetMappingName, resultClass); } @Override public SelectionQuery<?> createSelectionQuery(String hqlString) { return delegate.get().createSelectionQuery(hqlString); } @Override public <R> SelectionQuery<R> createSelectionQuery(String hqlString, Class<R> resultType) { return delegate.get().createSelectionQuery(hqlString, resultType); } @Override public <R> SelectionQuery<R> createSelectionQuery(CriteriaQuery<R> criteria) { return delegate.get().createSelectionQuery(criteria); } @Override public <R> SelectionQuery<R> createSelectionQuery(String hqlString, EntityGraph<R> resultGraph) { return delegate.get().createSelectionQuery(hqlString, resultGraph); } @Override public MutationQuery createMutationQuery(String hqlString) { return delegate.get().createMutationQuery(hqlString); } @Override public MutationQuery createMutationQuery(CriteriaUpdate updateQuery) { return delegate.get().createMutationQuery(updateQuery); } @Override public MutationQuery createMutationQuery(CriteriaDelete deleteQuery) { return delegate.get().createMutationQuery(deleteQuery); } @Override public MutationQuery createMutationQuery(JpaCriteriaInsert insert) { return delegate.get().createMutationQuery(insert); } @Override public MutationQuery createNativeMutationQuery(String sqlString) { return delegate.get().createNativeMutationQuery(sqlString); } @Override @Deprecated(since = "6.0") public Query createNamedQuery(String name) { return delegate.get().createNamedQuery(name); } @Override public <R> Query<R> createNamedQuery(String name, Class<R> resultClass) { return delegate.get().createNamedQuery(name, resultClass); } @Override public SelectionQuery<?> createNamedSelectionQuery(String name) { return delegate.get().createNamedSelectionQuery(name); } @Override public <R> SelectionQuery<R> createNamedSelectionQuery(String name, Class<R> resultType) { return delegate.get().createNamedSelectionQuery(name, resultType); } @Override public MutationQuery createNamedMutationQuery(String name) { return delegate.get().createNamedMutationQuery(name); } @Override @Deprecated(since = "6.0") public Query getNamedQuery(String queryName) { return delegate.get().getNamedQuery(queryName); } @Override @Deprecated(since = "6.0") public NativeQuery getNamedNativeQuery(String name) { return delegate.get().getNamedNativeQuery(name); } @Override @Deprecated(since = "6.0") public NativeQuery getNamedNativeQuery(String name, String resultSetMapping) { return delegate.get().getNamedNativeQuery(name, resultSetMapping); } @Override public <T> RootGraph<T> createEntityGraph(Class<T> rootType) { return delegate.get().createEntityGraph(rootType); } @Override public RootGraph<?> createEntityGraph(String graphName) { return delegate.get().createEntityGraph(graphName); } @Override public <T> RootGraph<T> createEntityGraph(Class<T> rootType, String graphName) { return delegate.get().createEntityGraph(rootType, graphName); } @Override public RootGraph<?> getEntityGraph(String graphName) { return delegate.get().getEntityGraph(graphName); } @Override public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) { return delegate.get().getEntityGraphs(entityClass); } @Override public SessionFactory getFactory() { return delegate.get().getFactory(); } @Override public void upsert(Object entity) { delegate.get().upsert(entity); } @Override public void upsert(String entityName, Object entity) { delegate.get().upsert(entityName, entity); } @Override public void upsertMultiple(List<?> entities) { delegate.get().upsertMultiple(entities); } @Override public <T> T get(EntityGraph<T> graph, GraphSemantic graphSemantic, Object id) { return delegate.get().get(graph, graphSemantic, id); } @Override public <T> T get(EntityGraph<T> graph, GraphSemantic graphSemantic, Object id, LockMode lockMode) { return delegate.get().get(graph, graphSemantic, id, lockMode); } @Override public CacheMode getCacheMode() { return delegate.get().getCacheMode(); } @Override public void setCacheMode(CacheMode cacheMode) { delegate.get().setCacheMode(cacheMode); } @Override public <T> T unwrap(Class<T> type) { return delegate.get().unwrap(type); } }
StatelessSessionLazyDelegator
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/ClassAssertBaseTest.java
{ "start": 1361, "end": 1442 }
interface ____ { } @MyAnnotation @AnotherAnnotation public
AnotherAnnotation
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/AddressEntry.java
{ "start": 312, "end": 1474 }
class ____ { private AddressEntryPk person; private String street; private String city; private AddressBook book; private AlphabeticalDirectory directory; public boolean equals(Object o) { if ( this == o ) return true; if ( !( o instanceof AddressEntry ) ) return false; final AddressEntry addressEntry = (AddressEntry) o; if ( !person.equals( addressEntry.person ) ) return false; return true; } public int hashCode() { return person.hashCode(); } @EmbeddedId public AddressEntryPk getPerson() { return person; } public void setPerson(AddressEntryPk person) { this.person = person; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @ManyToOne public AddressBook getBook() { return book; } public void setBook(AddressBook book) { this.book = book; } @ManyToOne public AlphabeticalDirectory getDirectory() { return directory; } public void setDirectory(AlphabeticalDirectory directory) { this.directory = directory; } }
AddressEntry
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/PolymorphicDeductionObjectVsArrayTest.java
{ "start": 1299, "end": 1650 }
class ____ extends ArrayList<DataItem> implements Data { private static final long serialVersionUID = 1L; @JsonCreator DataArray(Collection<DataItem> items) { super(new ArrayList<>(items)); } @Override public boolean isObject() { return false; } } static
DataArray
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ProtoTruthMixedDescriptorsTest.java
{ "start": 992, "end": 1588 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(ProtoTruthMixedDescriptors.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Test.java", """ import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage; final
ProtoTruthMixedDescriptorsTest
java
elastic__elasticsearch
plugins/analysis-kuromoji/src/yamlRestTest/java/org/elasticsearch/index/analysis/KuromojiClientYamlTestSuiteIT.java
{ "start": 874, "end": 1480 }
class ____ extends ESClientYamlSuiteTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local().plugin("analysis-kuromoji").build(); public KuromojiClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return ESClientYamlSuiteTestCase.createParameters(); } @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } }
KuromojiClientYamlTestSuiteIT
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/superclass/auditparents/TotalAuditParentsTest.java
{ "start": 1507, "end": 3515 }
class ____ { private long babyCompleteId = 1L; private Integer siteCompleteId = null; @BeforeClassTemplate public void initData(SessionFactoryScope scope) { scope.inTransaction( session -> { StrIntTestEntity siteComplete = new StrIntTestEntity( "data 1", 1 ); session.persist( siteComplete ); session.persist( new BabyCompleteEntity( babyCompleteId, "grandparent 1", "notAudited 1", "parent 1", "child 1", siteComplete, "baby 1" ) ); session.flush(); siteCompleteId = siteComplete.getId(); } ); } @Test public void testCreatedAuditTable(DomainModelScope scope) { final var expectedColumns = Set.of( "baby", "child", "parent", "relation_id", "grandparent", "id" ); final var unexpectedColumns = Set.of( "notAudited" ); final var table = scope.getDomainModel().getEntityBinding( "org.hibernate.orm.test.envers.integration.superclass.auditparents.BabyCompleteEntity_AUD" ).getTable(); for ( String columnName : expectedColumns ) { // Check whether expected column exists. assertNotNull( table.getColumn( new Column( columnName ) ) ); } for ( String columnName : unexpectedColumns ) { // Check whether unexpected column does not exist. assertNull( table.getColumn( new Column( columnName ) ) ); } } @Test public void testCompleteAuditParents(SessionFactoryScope scope) { scope.inSession( em -> { // expectedBaby.notAudited shall be null, because it is not audited. BabyCompleteEntity expectedBaby = new BabyCompleteEntity( babyCompleteId, "grandparent 1", null, "parent 1", "child 1", new StrIntTestEntity( "data 1", 1, siteCompleteId ), "baby 1" ); BabyCompleteEntity baby = AuditReaderFactory.get( em ).find( BabyCompleteEntity.class, babyCompleteId, 1 ); assertEquals( expectedBaby, baby ); assertEquals( expectedBaby.getRelation().getId(), baby.getRelation().getId() ); } ); } }
TotalAuditParentsTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_415.java
{ "start": 293, "end": 1198 }
class ____ extends TestCase { protected void setUp() throws Exception { ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_issue_415."); } public void test_for_issue() throws Exception { Teacher t = new Teacher(); Address addr = new Address(); addr.setAddrDetail("中国上海南京路"); Student s1 = new Student(); s1.setName("张三"); s1.setAddr(addr); Student s2 = new Student(); s2.setName("李四"); s2.setAddr(addr); t.setStudentList(Arrays.asList(s1, s2)); String json = JSON.toJSONString(t,SerializerFeature.WriteClassName); //@1 打印序列化的时候json串 Teacher t2 = (Teacher) JSON.parse(json); for (Student s : t2.getStudentList()) { Assert.assertNotNull(s); Assert.assertNotNull(s.getAddr()); } } public static
Bug_for_issue_415
java
google__auto
common/src/test/java/com/google/auto/common/AnnotationMirrorsTest.java
{ "start": 5790, "end": 8258 }
class ____ {} @Test public void testGetDefaultValuesUnset() { assertThat(annotationOn(StringyUnset.class).getElementValues()).isEmpty(); Iterable<AnnotationValue> values = AnnotationMirrors.getAnnotationValuesWithDefaults(annotationOn(StringyUnset.class)) .values(); String value = getOnlyElement(values) .accept( new SimpleAnnotationValueVisitor6<String, Void>() { @Override public String visitString(String value, Void ignored) { return value; } }, null); assertThat(value).isEqualTo("default"); } @Test public void testGetDefaultValuesSet() { Iterable<AnnotationValue> values = AnnotationMirrors.getAnnotationValuesWithDefaults(annotationOn(StringySet.class)).values(); String value = getOnlyElement(values) .accept( new SimpleAnnotationValueVisitor6<String, Void>() { @Override public String visitString(String value, Void ignored) { return value; } }, null); assertThat(value).isEqualTo("foo"); } @Test public void testGetValueEntry() { Map.Entry<ExecutableElement, AnnotationValue> elementValue = AnnotationMirrors.getAnnotationElementAndValue(annotationOn(TestClassBlah.class), "value"); assertThat(elementValue.getKey().getSimpleName().toString()).isEqualTo("value"); assertThat(elementValue.getValue().getValue()).isInstanceOf(VariableElement.class); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationOn(TestClassBlah.class), "value"); assertThat(value.getValue()).isInstanceOf(VariableElement.class); } @Test public void testGetValueEntryFailure() { try { AnnotationMirrors.getAnnotationValue(annotationOn(TestClassBlah.class), "a"); } catch (IllegalArgumentException e) { assertThat(e) .hasMessageThat() .isEqualTo( "@com.google.auto.common.AnnotationMirrorsTest.Outer does not define an element a()"); return; } fail("Should have thrown."); } private AnnotationMirror annotationOn(Class<?> clazz) { return getOnlyElement(elements.getTypeElement(clazz.getCanonicalName()).getAnnotationMirrors()); } @Retention(RetentionPolicy.RUNTIME) private @
StringySet
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java
{ "start": 8517, "end": 8930 }
class ____ { @Autowired void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); // @formatter:on } @Bean PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } } @Configuration @EnableWebSecurity static
PasswordEncoderGlobalConfig
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2233/ProgramDto.java
{ "start": 260, "end": 647 }
class ____ { private final String name; private final String number; public ProgramDto(String name, String number) { this.name = name; this.number = number; } public Optional<String> getName() { return Optional.ofNullable( name ); } public Optional<String> getNumber() { return Optional.ofNullable( number ); } }
ProgramDto
java
quarkusio__quarkus
extensions/hibernate-search-orm-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/orm/elasticsearch/runtime/HibernateSearchConfigUtil.java
{ "start": 461, "end": 3394 }
class ____ { public static <T> void addConfig(BiConsumer<String, Object> propertyCollector, String configPath, T value) { propertyCollector.accept(configPath, value); } public static void addConfig(BiConsumer<String, Object> propertyCollector, String configPath, Optional<?> value) { if (value.isPresent()) { propertyCollector.accept(configPath, value.get()); } } public static <T> void addBackendConfig(BiConsumer<String, Object> propertyCollector, String backendName, String configPath, T value) { propertyCollector.accept(BackendSettings.backendKey(backendName, configPath), value); } public static void addBackendConfig(BiConsumer<String, Object> propertyCollector, String backendName, String configPath, Optional<?> value) { addBackendConfig(propertyCollector, backendName, configPath, value, Optional::isPresent, Optional::get); } public static void addBackendConfig(BiConsumer<String, Object> propertyCollector, String backendName, String configPath, OptionalInt value) { addBackendConfig(propertyCollector, backendName, configPath, value, OptionalInt::isPresent, OptionalInt::getAsInt); } public static <T> void addBackendConfig(BiConsumer<String, Object> propertyCollector, String backendName, String configPath, T value, Function<T, Boolean> shouldBeAdded, Function<T, ?> getValue) { if (shouldBeAdded.apply(value)) { addBackendConfig(propertyCollector, backendName, configPath, getValue.apply(value)); } } public static void addBackendIndexConfig(BiConsumer<String, Object> propertyCollector, String backendName, String indexName, String configPath, Optional<?> value) { addBackendIndexConfig(propertyCollector, backendName, indexName, configPath, value, Optional::isPresent, Optional::get); } public static void addBackendIndexConfig(BiConsumer<String, Object> propertyCollector, String backendName, String indexName, String configPath, OptionalInt value) { addBackendIndexConfig(propertyCollector, backendName, indexName, configPath, value, OptionalInt::isPresent, OptionalInt::getAsInt); } public static <T> void addBackendIndexConfig(BiConsumer<String, Object> propertyCollector, String backendName, String indexName, String configPath, T value, Function<T, Boolean> shouldBeAdded, Function<T, ?> getValue) { if (shouldBeAdded.apply(value)) { if (indexName != null) { propertyCollector.accept( IndexSettings.indexKey(backendName, indexName, configPath), getValue.apply(value)); } else { addBackendConfig(propertyCollector, backendName, configPath, getValue.apply(value)); } } } }
HibernateSearchConfigUtil
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/convert/threeten/Jsr310JpaConverters.java
{ "start": 2074, "end": 2426 }
class ____ the list of mapped classes. In Spring environments, you * can simply register the package of this class (i.e. {@code org.springframework.data.jpa.convert.threeten}) as package * to be scanned on e.g. the {@link LocalContainerEntityManagerFactoryBean}. * * @author Oliver Gierke * @author Kevin Peters * @author Greg Turnquist */ public
in
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpSecurityDeferAddFilterTests.java
{ "start": 5993, "end": 6271 }
class ____ implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(servletRequest, servletResponse); } } static
MyFilter
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/field/vectors/KnnDenseVectorDocValuesField.java
{ "start": 1003, "end": 3123 }
class ____ extends DenseVectorDocValuesField { protected final FloatVectorValues input; // null if no vectors protected final KnnVectorValues.DocIndexIterator iterator; protected float[] vector; protected final int dims; public KnnDenseVectorDocValuesField(@Nullable FloatVectorValues input, String name, int dims) { super(name, ElementType.FLOAT); this.dims = dims; this.input = input; this.iterator = input == null ? null : input.iterator(); } @Override public void setNextDocId(int docId) throws IOException { if (input == null) { return; } int currentDoc = iterator.docID(); if (currentDoc == NO_MORE_DOCS || docId < currentDoc) { vector = null; } else if (docId == currentDoc) { vector = input.vectorValue(iterator.index()); } else { currentDoc = iterator.advance(docId); if (currentDoc == docId) { vector = input.vectorValue(iterator.index()); } else { vector = null; } } } @Override public DenseVectorScriptDocValues toScriptDocValues() { return new DenseVectorScriptDocValues(this, dims); } public boolean isEmpty() { return vector == null; } @Override public DenseVector get() { if (isEmpty()) { return DenseVector.EMPTY; } if (input instanceof DenormalizedCosineFloatVectorValues normalized) { return new KnnDenseVector(vector, normalized.magnitude()); } return new KnnDenseVector(vector); } @Override public DenseVector get(DenseVector defaultValue) { if (isEmpty()) { return defaultValue; } if (input instanceof DenormalizedCosineFloatVectorValues normalized) { return new KnnDenseVector(vector, normalized.magnitude()); } return new KnnDenseVector(vector); } @Override public DenseVector getInternal() { return get(null); } }
KnnDenseVectorDocValuesField
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java
{ "start": 93666, "end": 94498 }
class ____ { private final TransactionalRequestResult result; private final State state; private final String operation; private PendingStateTransition( TransactionalRequestResult result, State state, String operation ) { this.result = result; this.state = state; this.operation = operation; } } /** * Returns a ProducerIdAndEpoch object containing the producer ID and epoch * of the ongoing transaction. * This is used when preparing a transaction for a two-phase commit. * * @return a ProducerIdAndEpoch with the current producer ID and epoch. */ public ProducerIdAndEpoch preparedTransactionState() { return this.preparedTxnState; } }
PendingStateTransition
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/extension/duplicated/impl/DuplicatedOverriddenExt2.java
{ "start": 947, "end": 1108 }
class ____ implements DuplicatedOverriddenExt { @Override public String echo() { return "DuplicatedOverriddenExt2"; } }
DuplicatedOverriddenExt2
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/configuration/BeanConfigurationRequest.java
{ "start": 3598, "end": 5005 }
class ____ to load referenced types from, may be {@code null}. * @return This request for chaining, never {@code null}. */ BeanConfigurationRequest setClassLoader(ClassLoader classLoader); /** * Gets the optional preprocessor for configuration values. * * @return The preprocessor for configuration values or {@code null} if none. */ BeanConfigurationValuePreprocessor getValuePreprocessor(); /** * Sets the optional preprocessor for configuration values. * * @param valuePreprocessor The preprocessor for configuration values, may be {@code null} if unneeded. * @return This request for chaining, never {@code null}. */ BeanConfigurationRequest setValuePreprocessor(BeanConfigurationValuePreprocessor valuePreprocessor); /** * Gets the optional path translator for configuration values unmarshalled to files. * * @return The path translator for files or {@code null} if none. */ BeanConfigurationPathTranslator getPathTranslator(); /** * Sets the optional path translator for configuration values unmarshalled to files. * * @param pathTranslator The path translator for files, may be {@code null} if unneeded. * @return This request for chaining, never {@code null}. */ BeanConfigurationRequest setPathTranslator(BeanConfigurationPathTranslator pathTranslator); }
loader
java
google__guava
guava/src/com/google/common/collect/Streams.java
{ "start": 28441, "end": 28721 }
interface ____<T extends @Nullable Object, R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(@ParametricNullness T from, long index); } private abstract static
FunctionWithIndex
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/EclipseLinkProxyIdAccessorTests.java
{ "start": 1264, "end": 1446 }
class ____ {} /** * Do not execute the test as EclipseLink does not create a lazy-loading proxy as expected. */ @Override @Disabled public void testname() {} }
EclipseLinkConfig
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveScanningProcessor.java
{ "start": 7420, "end": 23700 }
class ____ the annotation was placed as the exception to be unwrapped AnnotationTarget target = instance.target(); if (target.kind() != AnnotationTarget.Kind.CLASS) { throw new IllegalStateException( "@UnwrapException is only supported on classes. Offending target is: " + target); } ClassInfo classInfo = target.asClass(); ClassInfo toCheck = classInfo; boolean isException = false; while (true) { DotName superDotName = toCheck.superName(); if (EXCEPTION.equals(superDotName) || RUNTIME_EXCEPTION.equals(superDotName)) { isException = true; break; } toCheck = index.getClassByName(superDotName); if (toCheck == null) { break; } } if (!isException) { throw new IllegalArgumentException( "Using @UnwrapException without a value is only supported on exception classes. Offending target is '" + classInfo.name() + "'."); } producer.produce(new UnwrappedExceptionBuildItem(classInfo.name().toString(), strategy)); } else { Type[] exceptionTypes = value.asClassArray(); for (Type exceptionType : exceptionTypes) { producer.produce(new UnwrappedExceptionBuildItem(exceptionType.name().toString(), strategy)); } } } } private static ExceptionUnwrapStrategy toExceptionUnwrapStrategy(AnnotationValue strategyValue) { if (strategyValue != null) { return ExceptionUnwrapStrategy.valueOf(strategyValue.asEnum()); } return ExceptionUnwrapStrategy.UNWRAP_IF_NO_MATCH; } @BuildStep public ExceptionMappersBuildItem scanForExceptionMappers(CombinedIndexBuildItem combinedIndexBuildItem, ApplicationResultBuildItem applicationResultBuildItem, BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer, List<ExceptionMapperBuildItem> mappers, List<UnwrappedExceptionBuildItem> unwrappedExceptions, Capabilities capabilities) { AdditionalBeanBuildItem.Builder beanBuilder = AdditionalBeanBuildItem.builder().setUnremovable(); ExceptionMapping exceptions = ResteasyReactiveExceptionMappingScanner .scanForExceptionMappers(combinedIndexBuildItem.getComputingIndex(), applicationResultBuildItem.getResult()); exceptions.addBlockingProblem(BlockingOperationNotAllowedException.class); exceptions.addBlockingProblem(BlockingNotAllowedException.class); for (UnwrappedExceptionBuildItem bi : unwrappedExceptions) { exceptions.addUnwrappedException(bi.getThrowableClassName(), bi.getStrategy()); } if (capabilities.isPresent(Capability.HIBERNATE_REACTIVE)) { exceptions.addNonBlockingProblem( new ExceptionMapping.ExceptionTypeAndMessageContainsPredicate(IllegalStateException.class, "HR000068")); } for (Map.Entry<String, ResourceExceptionMapper<? extends Throwable>> i : exceptions.getMappers() .entrySet()) { beanBuilder.addBeanClass(i.getValue().getClassName()); } for (ExceptionMapperBuildItem additionalExceptionMapper : mappers) { if (additionalExceptionMapper.isRegisterAsBean()) { beanBuilder.addBeanClass(additionalExceptionMapper.getClassName()); } else { reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(additionalExceptionMapper.getClassName()) .build()); } int priority = Priorities.USER; if (additionalExceptionMapper.getPriority() != null) { priority = additionalExceptionMapper.getPriority(); } ResourceExceptionMapper<Throwable> mapper = new ResourceExceptionMapper<>(); mapper.setPriority(priority); mapper.setClassName(additionalExceptionMapper.getClassName()); addRuntimeCheckIfNecessary(additionalExceptionMapper, mapper); exceptions.addExceptionMapper(additionalExceptionMapper.getHandledExceptionName(), mapper); } additionalBeanBuildItemBuildProducer.produce(beanBuilder.build()); return new ExceptionMappersBuildItem(exceptions); } private static void addRuntimeCheckIfNecessary(ExceptionMapperBuildItem additionalExceptionMapper, ResourceExceptionMapper<Throwable> mapper) { ClassInfo declaringClass = additionalExceptionMapper.getDeclaringClass(); if (declaringClass != null) { boolean needsRuntimeCheck = false; List<AnnotationInstance> classAnnotations = declaringClass.declaredAnnotations(); for (AnnotationInstance classAnnotation : classAnnotations) { if (CONDITIONAL_BEAN_ANNOTATIONS.contains(classAnnotation.name())) { needsRuntimeCheck = true; break; } } if (needsRuntimeCheck) { mapper.setDiscardAtRuntime(new ResourceExceptionMapper.DiscardAtRuntimeIfBeanIsUnavailable( declaringClass.name().toString())); } } } @BuildStep public ParamConverterProvidersBuildItem scanForParamConverters( BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer, List<ParamConverterBuildItem> paramConverterBuildItems) { AdditionalBeanBuildItem.Builder beanBuilder = AdditionalBeanBuildItem.builder().setUnremovable(); ParamConverterProviders paramConverterProviders = new ParamConverterProviders(); for (ParamConverterBuildItem additionalParamConverter : paramConverterBuildItems) { if (additionalParamConverter.isRegisterAsBean()) { beanBuilder.addBeanClass(additionalParamConverter.getClassName()); } else { reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(additionalParamConverter.getClassName()) .build()); } int priority = Priorities.USER; if (additionalParamConverter.getPriority() != null) { priority = additionalParamConverter.getPriority(); } ResourceParamConverterProvider provider = new ResourceParamConverterProvider(); provider.setPriority(priority); provider.setClassName(additionalParamConverter.getClassName()); paramConverterProviders.addParamConverterProviders(provider); } additionalBeanBuildItemBuildProducer.produce(beanBuilder.build()); return new ParamConverterProvidersBuildItem(paramConverterProviders); } @BuildStep public void scanForDynamicFeatures(CombinedIndexBuildItem combinedIndexBuildItem, ApplicationResultBuildItem applicationResultBuildItem, BuildProducer<DynamicFeatureBuildItem> dynamicFeatureBuildItemBuildProducer) { IndexView index = combinedIndexBuildItem.getComputingIndex(); Set<String> features = ResteasyReactiveFeatureScanner.scanForDynamicFeatures(index, applicationResultBuildItem.getResult()); for (String dynamicFeatureClass : features) { dynamicFeatureBuildItemBuildProducer .produce(new DynamicFeatureBuildItem(dynamicFeatureClass, true)); } } @BuildStep public void scanForFeatures(CombinedIndexBuildItem combinedIndexBuildItem, ApplicationResultBuildItem applicationResultBuildItem, BuildProducer<JaxrsFeatureBuildItem> featureBuildItemBuildProducer) { IndexView index = combinedIndexBuildItem.getComputingIndex(); Set<String> features = ResteasyReactiveFeatureScanner.scanForFeatures(index, applicationResultBuildItem.getResult()); for (String feature : features) { featureBuildItemBuildProducer .produce(new JaxrsFeatureBuildItem(feature, true)); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @BuildStep public ContextResolversBuildItem scanForContextResolvers(CombinedIndexBuildItem combinedIndexBuildItem, ApplicationResultBuildItem applicationResultBuildItem, BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer, List<ContextResolverBuildItem> additionalResolvers) { IndexView index = combinedIndexBuildItem.getComputingIndex(); AdditionalBeanBuildItem.Builder beanBuilder = AdditionalBeanBuildItem.builder().setUnremovable(); ContextResolvers resolvers = ResteasyReactiveContextResolverScanner.scanForContextResolvers(index, applicationResultBuildItem.getResult()); for (Map.Entry<Class<?>, List<ResourceContextResolver>> entry : resolvers.getResolvers().entrySet()) { for (ResourceContextResolver i : entry.getValue()) { beanBuilder.addBeanClass(i.getClassName()); } } for (ContextResolverBuildItem i : additionalResolvers) { if (i.isRegisterAsBean()) { beanBuilder.addBeanClass(i.getClassName()); } else { reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(i.getClassName()) .build()); } ResourceContextResolver resolver = new ResourceContextResolver(); resolver.setClassName(i.getClassName()); resolver.setMediaTypeStrings(i.getMediaTypes()); try { resolvers.addContextResolver((Class) Class.forName(i.getProvidedType(), false, Thread.currentThread().getContextClassLoader()), resolver); } catch (ClassNotFoundException e) { throw new RuntimeException( "Unable to load handled exception type " + i.getProvidedType(), e); } } additionalBeanBuildItemBuildProducer.produce(beanBuilder.build()); return new ContextResolversBuildItem(resolvers); } @BuildStep public void scanForParamConverters(CombinedIndexBuildItem combinedIndexBuildItem, ApplicationResultBuildItem applicationResultBuildItem, BuildProducer<ParamConverterBuildItem> paramConverterBuildItemBuildProducer) { IndexView index = combinedIndexBuildItem.getComputingIndex(); Collection<ClassInfo> paramConverterProviders = index .getAllKnownImplementors(ResteasyReactiveDotNames.PARAM_CONVERTER_PROVIDER); for (ClassInfo converterClass : paramConverterProviders) { ApplicationScanningResult.KeepProviderResult keepProviderResult = applicationResultBuildItem.getResult() .keepProvider(converterClass); if (keepProviderResult != ApplicationScanningResult.KeepProviderResult.DISCARD) { AnnotationInstance priorityInstance = converterClass.declaredAnnotation(ResteasyReactiveDotNames.PRIORITY); paramConverterBuildItemBuildProducer.produce(new ParamConverterBuildItem(converterClass.name().toString(), priorityInstance != null ? priorityInstance.value().asInt() : Priorities.USER, true)); } } } @BuildStep public void handleCustomAnnotatedMethods( Optional<ResourceScanningResultBuildItem> resourceScanningResultBuildItem, CombinedIndexBuildItem combinedIndexBuildItem, BuildProducer<GeneratedBeanBuildItem> generatedBean, List<CustomContainerRequestFilterBuildItem> customContainerRequestFilters, List<CustomContainerResponseFilterBuildItem> customContainerResponseFilters, List<CustomExceptionMapperBuildItem> customExceptionMappers, BuildProducer<ContainerRequestFilterBuildItem> additionalContainerRequestFilters, BuildProducer<ContainerResponseFilterBuildItem> additionalContainerResponseFilters, BuildProducer<ExceptionMapperBuildItem> additionalExceptionMappers, BuildProducer<AdditionalBeanBuildItem> additionalBean) { IndexView index = combinedIndexBuildItem.getComputingIndex(); AdditionalBeanBuildItem.Builder additionalBeans = AdditionalBeanBuildItem.builder(); // if we have custom filters, we need to index these classes if (!customContainerRequestFilters.isEmpty() || !customContainerResponseFilters.isEmpty() || !customExceptionMappers.isEmpty()) { Indexer indexer = new Indexer(); Set<DotName> additionalIndex = new HashSet<>(); //we have to use the non-computing index here //the logic checks if the bean is already indexed, so the computing one breaks this for (CustomContainerRequestFilterBuildItem filter : customContainerRequestFilters) { IndexingUtil.indexClass(filter.getClassName(), indexer, combinedIndexBuildItem.getIndex(), additionalIndex, Thread.currentThread().getContextClassLoader()); } for (CustomContainerResponseFilterBuildItem filter : customContainerResponseFilters) { IndexingUtil.indexClass(filter.getClassName(), indexer, combinedIndexBuildItem.getIndex(), additionalIndex, Thread.currentThread().getContextClassLoader()); } for (CustomExceptionMapperBuildItem mapper : customExceptionMappers) { IndexingUtil.indexClass(mapper.getClassName(), indexer, combinedIndexBuildItem.getIndex(), additionalIndex, Thread.currentThread().getContextClassLoader()); } index = CompositeIndex.create(index, indexer.complete()); } List<FilterGeneration.GeneratedFilter> generatedFilters = FilterGeneration.generate(index, Set.of(HTTP_SERVER_REQUEST, HTTP_SERVER_RESPONSE, ROUTING_CONTEXT), Set.of(Unremovable.class.getName()), (methodInfo -> { List<AnnotationInstance> methodAnnotations = methodInfo.annotations(); for (AnnotationInstance methodAnnotation : methodAnnotations) { if (CONDITIONAL_BEAN_ANNOTATIONS.contains(methodAnnotation.name())) { throw new RuntimeException("The combination of '@" + methodAnnotation.name().withoutPackagePrefix() + "' and '@ServerRequestFilter' or '@ServerResponseFilter' is not allowed. Offending method is '" + methodInfo.name() + "' of class '" + methodInfo.declaringClass().name() + "'"); } } List<AnnotationInstance> classAnnotations = methodInfo.declaringClass().declaredAnnotations(); for (AnnotationInstance classAnnotation : classAnnotations) { if (CONDITIONAL_BEAN_ANNOTATIONS.contains(classAnnotation.name())) { return true; } } return false; })); for (var generated : generatedFilters) { for (var i : generated.getGeneratedClasses()) { generatedBean.produce(new GeneratedBeanBuildItem(i.getName(), i.getData())); } if (generated.isRequestFilter()) { // the user
where
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/arrays2d/Arrays2D_assertHasDimensions_Test.java
{ "start": 1360, "end": 3014 }
class ____ extends Arrays2D_BaseTest { private char[][] actual = new char[][] { { 'a', 'b', 'c' }, { 'd', 'e', 'f' } }; @Test void should_fail_if_actual_is_null() { // GIVEN char[][] actual = null; // WHEN var assertionError = expectAssertionError(() -> arrays.assertHasDimensions(someInfo(), failures, actual, 2, 3)); // THEN then(assertionError).hasMessage(shouldNotBeNull().create()); } @Test void should_fail_if_first_dimension_size_of_actual_is_not_equal_to_expected_size() { // GIVEN int expectedFirstDimensionSize = 10; // WHEN var assertionError = expectAssertionError(() -> arrays.assertHasDimensions(someInfo(), failures, actual, expectedFirstDimensionSize, 3)); // THEN then(assertionError).hasMessage(shouldHaveFirstDimension(actual, actual.length, expectedFirstDimensionSize).create()); } @Test void should_fail_if_second_dimension_size_of_actual_is_not_equal_to_expected_size() { // GIVEN int expectedSecondDimensionSize = 10; // WHEN var assertionError = expectAssertionError(() -> arrays.assertHasDimensions(someInfo(), failures, actual, 2, expectedSecondDimensionSize)); // THEN then(assertionError).hasMessage(shouldHaveSize(new char[] { 'a', 'b', 'c' }, 3, expectedSecondDimensionSize, 0).create()); } @Test void should_pass_if_size_of_actual_is_equal_to_expected_size() { arrays.assertHasDimensions(someInfo(), failures, actual, 2, 3); } }
Arrays2D_assertHasDimensions_Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/InetSocketAddressFieldTest.java
{ "start": 1456, "end": 1702 }
class ____ { private InetSocketAddress value; public InetSocketAddress getValue() { return value; } public void setValue(InetSocketAddress value) { this.value = value; } } }
User