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
apache__dubbo
dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ModuleConfig.java
{ "start": 856, "end": 1403 }
class ____ extends org.apache.dubbo.config.ModuleConfig { public ModuleConfig() {} public ModuleConfig(String name) { super(name); } public void setRegistry(com.alibaba.dubbo.config.RegistryConfig registry) { super.setRegistry(registry); } public void setMonitor(com.alibaba.dubbo.config.MonitorConfig monitor) { super.setMonitor(monitor); } @Override public void setMonitor(String monitor) { setMonitor(new com.alibaba.dubbo.config.MonitorConfig(monitor)); } }
ModuleConfig
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CriteriaQueryCacheIgnoreResultTransformerTest.java
{ "start": 361, "end": 1839 }
class ____ extends AbstractQueryCacheResultTransformerTest { @Override protected CacheMode getQueryCacheMode() { return CacheMode.IGNORE; } @Override protected void runTest( HqlExecutor hqlExecutor, CriteriaExecutor criteriaExecutor, ResultChecker checker, boolean isSingleResult, SessionFactoryScope scope) throws Exception { createData( scope ); try { if ( criteriaExecutor != null ) { runTest( criteriaExecutor, checker, isSingleResult, scope ); } } finally { deleteData( scope ); } } @Test @Override @FailureExpected(jiraKey = "N/A", reason = "Using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionList(SessionFactoryScope scope) throws Exception { super.testAliasToEntityMapNoProjectionList( scope ); } @Test @Override @FailureExpected(jiraKey = "N/A", reason = "Using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionMultiAndNullList(SessionFactoryScope scope) throws Exception { super.testAliasToEntityMapNoProjectionMultiAndNullList( scope ); } @Test @Override @FailureExpected(jiraKey = "N/A", reason = "Using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionNullAndNonNullAliasList(SessionFactoryScope scope) throws Exception { super.testAliasToEntityMapNoProjectionNullAndNonNullAliasList( scope ); } }
CriteriaQueryCacheIgnoreResultTransformerTest
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/profile/IfBuildProfileAllAnyTest.java
{ "start": 5449, "end": 5729 }
class ____ implements IfBuildProfileBean { @Override public String profile() { return "allOf-dev,anyOf-test"; } } // Active @ApplicationScoped @IfBuildProfile(allOf = "test", anyOf = "build") public static
AllOfDevAnyOfTestBean
java
google__gson
gson/src/test/java/com/google/gson/JsonArrayTest.java
{ "start": 949, "end": 10342 }
class ____ { @Test public void testEqualsOnEmptyArray() { MoreAsserts.assertEqualsAndHashCode(new JsonArray(), new JsonArray()); } @Test public void testEqualsNonEmptyArray() { JsonArray a = new JsonArray(); JsonArray b = new JsonArray(); new EqualsTester().addEqualityGroup(a).testEquals(); a.add(new JsonObject()); assertThat(a.equals(b)).isFalse(); assertThat(b.equals(a)).isFalse(); b.add(new JsonObject()); MoreAsserts.assertEqualsAndHashCode(a, b); a.add(new JsonObject()); assertThat(a.equals(b)).isFalse(); assertThat(b.equals(a)).isFalse(); b.add(JsonNull.INSTANCE); assertThat(a.equals(b)).isFalse(); assertThat(b.equals(a)).isFalse(); } @Test public void testRemove() { JsonArray array = new JsonArray(); assertThrows(IndexOutOfBoundsException.class, () -> array.remove(0)); JsonPrimitive a = new JsonPrimitive("a"); array.add(a); assertThat(array.remove(a)).isTrue(); assertThat(array).doesNotContain(a); array.add(a); array.add(new JsonPrimitive("b")); assertThat(array.remove(1).getAsString()).isEqualTo("b"); assertThat(array).hasSize(1); assertThat(array).contains(a); } @Test public void testSet() { JsonArray array = new JsonArray(); assertThrows(IndexOutOfBoundsException.class, () -> array.set(0, new JsonPrimitive(1))); JsonPrimitive a = new JsonPrimitive("a"); array.add(a); JsonPrimitive b = new JsonPrimitive("b"); JsonElement oldValue = array.set(0, b); assertThat(oldValue).isEqualTo(a); assertThat(array.get(0).getAsString()).isEqualTo("b"); oldValue = array.set(0, null); assertThat(oldValue).isEqualTo(b); assertThat(array.get(0)).isEqualTo(JsonNull.INSTANCE); oldValue = array.set(0, new JsonPrimitive("c")); assertThat(oldValue).isEqualTo(JsonNull.INSTANCE); assertThat(array.get(0).getAsString()).isEqualTo("c"); assertThat(array).hasSize(1); } @Test public void testDeepCopy() { JsonArray original = new JsonArray(); JsonArray firstEntry = new JsonArray(); original.add(firstEntry); JsonArray copy = original.deepCopy(); original.add(new JsonPrimitive("y")); assertThat(copy).hasSize(1); firstEntry.add(new JsonPrimitive("z")); assertThat(original.get(0).getAsJsonArray()).hasSize(1); assertThat(copy.get(0).getAsJsonArray()).hasSize(0); } @Test public void testIsEmpty() { JsonArray array = new JsonArray(); assertThat(array).isEmpty(); JsonPrimitive a = new JsonPrimitive("a"); array.add(a); assertThat(array).isNotEmpty(); array.remove(0); assertThat(array).isEmpty(); } @Test public void testFailedGetArrayValues() { JsonArray jsonArray = new JsonArray(); jsonArray.add( JsonParser.parseString( "{" + "\"key1\":\"value1\"," + "\"key2\":\"value2\"," + "\"key3\":\"value3\"," + "\"key4\":\"value4\"" + "}")); Exception e = assertThrows(UnsupportedOperationException.class, () -> jsonArray.getAsBoolean()); assertThat(e).hasMessageThat().isEqualTo("JsonObject"); e = assertThrows(IndexOutOfBoundsException.class, () -> jsonArray.get(-1)); assertThat(e).hasMessageThat().isEqualTo("Index -1 out of bounds for length 1"); e = assertThrows(UnsupportedOperationException.class, () -> jsonArray.getAsString()); assertThat(e).hasMessageThat().isEqualTo("JsonObject"); jsonArray.remove(0); jsonArray.add("hello"); e = assertThrows(NumberFormatException.class, () -> jsonArray.getAsDouble()); assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); e = assertThrows(NumberFormatException.class, () -> jsonArray.getAsInt()); assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); e = assertThrows(IllegalStateException.class, () -> jsonArray.get(0).getAsJsonArray()); assertThat(e).hasMessageThat().isEqualTo("Not a JSON Array: \"hello\""); e = assertThrows(IllegalStateException.class, () -> jsonArray.getAsJsonObject()); assertThat(e).hasMessageThat().isEqualTo("Not a JSON Object: [\"hello\"]"); e = assertThrows(NumberFormatException.class, () -> jsonArray.getAsLong()); assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); } @Test public void testGetAs_WrongArraySize() { JsonArray jsonArray = new JsonArray(); var e = assertThrows(IllegalStateException.class, () -> jsonArray.getAsByte()); assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 0"); jsonArray.add(true); jsonArray.add(false); e = assertThrows(IllegalStateException.class, () -> jsonArray.getAsByte()); assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 2"); } @Test public void testStringPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add("Hello"); jsonArray.add("Goodbye"); jsonArray.add("Thank you"); jsonArray.add((String) null); jsonArray.add("Yes"); assertThat(jsonArray.toString()) .isEqualTo("[\"Hello\",\"Goodbye\",\"Thank you\",null,\"Yes\"]"); } @Test public void testIntegerPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); int x = 1; jsonArray.add(x); x = 2; jsonArray.add(x); x = -3; jsonArray.add(x); jsonArray.add((Integer) null); x = 4; jsonArray.add(x); x = 0; jsonArray.add(x); assertThat(jsonArray.toString()).isEqualTo("[1,2,-3,null,4,0]"); } @Test public void testDoublePrimitiveAddition() { JsonArray jsonArray = new JsonArray(); double x = 1.0; jsonArray.add(x); x = 2.13232; jsonArray.add(x); x = 0.121; jsonArray.add(x); jsonArray.add((Double) null); x = -0.00234; jsonArray.add(x); jsonArray.add((Double) null); assertThat(jsonArray.toString()).isEqualTo("[1.0,2.13232,0.121,null,-0.00234,null]"); } @Test public void testBooleanPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add(true); jsonArray.add(true); jsonArray.add(false); jsonArray.add(false); jsonArray.add((Boolean) null); jsonArray.add(true); assertThat(jsonArray.toString()).isEqualTo("[true,true,false,false,null,true]"); } @Test public void testCharPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add('a'); jsonArray.add('e'); jsonArray.add('i'); jsonArray.add((char) 111); jsonArray.add((Character) null); jsonArray.add('u'); jsonArray.add("and sometimes Y"); assertThat(jsonArray.toString()) .isEqualTo("[\"a\",\"e\",\"i\",\"o\",null,\"u\",\"and sometimes Y\"]"); } @Test public void testMixedPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add('a'); jsonArray.add("apple"); jsonArray.add(12121); jsonArray.add((char) 111); jsonArray.add((Boolean) null); assertThat(jsonArray.get(jsonArray.size() - 1)).isEqualTo(JsonNull.INSTANCE); jsonArray.add((Character) null); assertThat(jsonArray.get(jsonArray.size() - 1)).isEqualTo(JsonNull.INSTANCE); jsonArray.add(12.232); jsonArray.add(BigInteger.valueOf(2323)); assertThat(jsonArray.toString()) .isEqualTo("[\"a\",\"apple\",12121,\"o\",null,null,12.232,2323]"); } @Test public void testNullPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add((Character) null); jsonArray.add((Boolean) null); jsonArray.add((Integer) null); jsonArray.add((Double) null); jsonArray.add((Float) null); jsonArray.add((BigInteger) null); jsonArray.add((String) null); jsonArray.add((Boolean) null); jsonArray.add((Number) null); assertThat(jsonArray.toString()).isEqualTo("[null,null,null,null,null,null,null,null,null]"); for (int i = 0; i < jsonArray.size(); i++) { // Verify that they are actually a JsonNull and not a Java null assertThat(jsonArray.get(i)).isEqualTo(JsonNull.INSTANCE); } } @Test public void testNullJsonElementAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add((JsonElement) null); assertThat(jsonArray.get(0)).isEqualTo(JsonNull.INSTANCE); } @Test public void testSameAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add('a'); jsonArray.add('a'); jsonArray.add(true); jsonArray.add(true); jsonArray.add(1212); jsonArray.add(1212); jsonArray.add(34.34); jsonArray.add(34.34); jsonArray.add((Boolean) null); jsonArray.add((Boolean) null); assertThat(jsonArray.toString()) .isEqualTo("[\"a\",\"a\",true,true,1212,1212,34.34,34.34,null,null]"); } @Test public void testToString() { JsonArray array = new JsonArray(); assertThat(array.toString()).isEqualTo("[]"); array.add(JsonNull.INSTANCE); array.add(Float.NaN); array.add("a\0"); JsonArray nestedArray = new JsonArray(); nestedArray.add('"'); array.add(nestedArray); JsonObject nestedObject = new JsonObject(); nestedObject.addProperty("n\0", 1); array.add(nestedObject); assertThat(array.toString()).isEqualTo("[null,NaN,\"a\\u0000\",[\"\\\"\"],{\"n\\u0000\":1}]"); } }
JsonArrayTest
java
google__dagger
javatests/dagger/internal/codegen/MultibindingTest.java
{ "start": 18522, "end": 19068 }
interface ____"); CompilerTests.daggerCompiler(parent, parentModule, myGenericInterface, myInterface, usage) .compile(subject -> subject.hasErrorCount(0)); } // Regression test for b/352142595. @Test public void testMultibindingMapProviderWithKotlinSource() { Source parent = CompilerTests.kotlinSource( "test.Parent.kt", "package test", "", "import dagger.Component", "", "@Component(modules = [ParentModule::class])", "
MyInterface
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/BaileyBorweinPlouffe.java
{ "start": 7720, "end": 8878 }
class ____ extends InputSplit implements Writable { private final static String[] EMPTY = {}; private long offset; private int size; /** Public default constructor for the Writable interface. */ public BbpSplit() { } private BbpSplit(int i, long offset, int size) { LOG.info("Map #" + i + ": workload=" + workload(offset, size) + ", offset=" + offset + ", size=" + size); this.offset = offset; this.size = size; } private long getOffset() { return offset; } /** {@inheritDoc} */ public long getLength() { return size; } /** No location is needed. */ public String[] getLocations() { return EMPTY; } /** {@inheritDoc} */ public void readFields(DataInput in) throws IOException { offset = in.readLong(); size = in.readInt(); } /** {@inheritDoc} */ public void write(DataOutput out) throws IOException { out.writeLong(offset); out.writeInt(size); } } /** * Input format for the {@link BbpMapper}. * Keys and values represent offsets and sizes, respectively. */ public static
BbpSplit
java
apache__camel
core/camel-util/src/main/java/org/apache/camel/util/StringHelper.java
{ "start": 8579, "end": 33827 }
class ____ */ public static boolean isClassName(String text) { if (text != null) { int lastIndexOf = text.lastIndexOf('.'); if (lastIndexOf <= 0) { return false; } return Character.isUpperCase(text.charAt(lastIndexOf + 1)); } return false; } /** * Does the expression have the language start token? * * @param expression the expression * @param language the name of the language, such as simple * @return <tt>true</tt> if the expression contains the start token, <tt>false</tt> otherwise */ public static boolean hasStartToken(String expression, String language) { if (expression == null) { return false; } // for the simple language, the expression start token could be "${" if ("simple".equalsIgnoreCase(language) && expression.contains("${")) { return true; } if (language != null && expression.contains("$" + language + "{")) { return true; } return false; } /** * Replaces the first from token in the given input string. * <p/> * This implementation is not recursive, not does it check for tokens in the replacement string. If from or to is * null, then the input string is returned as-is * * @param input the input string * @param from the from string * @param to the replacement string * @return the replaced string, or the input string if no replacement was needed * @throws IllegalArgumentException if the input arguments is invalid */ public static String replaceFirst(String input, String from, String to) { if (from == null || to == null) { return input; } int pos = input.indexOf(from); if (pos != -1) { int len = from.length(); return input.substring(0, pos) + to + input.substring(pos + len); } else { return input; } } /** * Creates a JSON tuple with the given name/value pair. * * @param name the name * @param value the value * @param isMap whether the tuple should be map * @return the json */ public static String toJson(String name, String value, boolean isMap) { if (isMap) { return "{ " + StringQuoteHelper.doubleQuote(name) + ": " + StringQuoteHelper.doubleQuote(value) + " }"; } else { return StringQuoteHelper.doubleQuote(name) + ": " + StringQuoteHelper.doubleQuote(value); } } /** * Asserts whether the string is <b>not</b> empty. * * @param value the string to test * @param name the key that resolved the value * @return the passed {@code value} as is * @throws IllegalArgumentException is thrown if assertion fails */ public static String notEmpty(String value, String name) { if (ObjectHelper.isEmpty(value)) { throw new IllegalArgumentException(name + " must be specified and not empty"); } return value; } /** * Asserts whether the string is <b>not</b> empty. * * @param value the string to test * @param on additional description to indicate where this problem occurred (appended as * toString()) * @param name the key that resolved the value * @return the passed {@code value} as is * @throws IllegalArgumentException is thrown if assertion fails */ public static String notEmpty(String value, String name, Object on) { if (on == null) { ObjectHelper.notNull(value, name); } else if (ObjectHelper.isEmpty(value)) { throw new IllegalArgumentException(name + " must be specified and not empty on: " + on); } return value; } public static String[] splitOnCharacter(String value, String needle, int count) { String[] rc = new String[count]; rc[0] = value; for (int i = 1; i < count; i++) { String v = rc[i - 1]; int p = v.indexOf(needle); if (p < 0) { return rc; } rc[i - 1] = v.substring(0, p); rc[i] = v.substring(p + 1); } return rc; } public static Iterator<String> splitOnCharacterAsIterator(String value, char needle, int count) { // skip leading and trailing needles int end = value.length() - 1; boolean skipStart = value.charAt(0) == needle; boolean skipEnd = value.charAt(end) == needle; if (skipStart && skipEnd) { value = value.substring(1, end); count = count - 2; } else if (skipStart) { value = value.substring(1); count = count - 1; } else if (skipEnd) { value = value.substring(0, end); count = count - 1; } final int size = count; final String text = value; return new Iterator<>() { int i; int pos; @Override public boolean hasNext() { return i < size; } @Override public String next() { if (i == size) { throw new NoSuchElementException(); } String answer; int end = text.indexOf(needle, pos); if (end != -1) { answer = text.substring(pos, end); pos = end + 1; } else { answer = text.substring(pos); // no more data i = size; } return answer; } }; } public static List<String> splitOnCharacterAsList(String value, char needle, int count) { // skip leading and trailing needles int end = value.length() - 1; boolean skipStart = value.charAt(0) == needle; boolean skipEnd = value.charAt(end) == needle; if (skipStart && skipEnd) { value = value.substring(1, end); count = count - 2; } else if (skipStart) { value = value.substring(1); count = count - 1; } else if (skipEnd) { value = value.substring(0, end); count = count - 1; } List<String> rc = new ArrayList<>(count); int pos = 0; for (int i = 0; i < count; i++) { end = value.indexOf(needle, pos); if (end != -1) { String part = value.substring(pos, end); pos = end + 1; rc.add(part); } else { rc.add(value.substring(pos)); break; } } return rc; } /** * Removes any starting characters on the given text which match the given character * * @param text the string * @param ch the initial characters to remove * @return either the original string or the new substring */ public static String removeStartingCharacters(String text, char ch) { int idx = 0; while (text.charAt(idx) == ch) { idx++; } if (idx > 0) { return text.substring(idx); } return text; } /** * Capitalize the string (upper case first character) * * @param text the string * @return the string capitalized (upper case first character) */ public static String capitalize(String text) { return capitalize(text, false); } /** * Capitalize the string (upper case first character) * * @param text the string * @param dashToCamelCase whether to also convert dash format into camel case (hello-great-world -> * helloGreatWorld) * @return the string capitalized (upper case first character) */ public static String capitalize(final String text, boolean dashToCamelCase) { String ret = text; if (dashToCamelCase) { ret = dashToCamelCase(text); } return doCapitalize(ret); } private static String doCapitalize(String ret) { if (ret == null) { return null; } final char[] chars = ret.toCharArray(); // We are OK with the limitations of Character.toUpperCase. The symbols and ideographs // for which it does not return the capitalized value should not be used here (this is // mostly used to capitalize setters/getters) chars[0] = Character.toUpperCase(chars[0]); return new String(chars); } /** * De-capitalize the string (lower case first character) * * @param text the string * @return the string decapitalized (lower case first character) */ public static String decapitalize(final String text) { if (text == null) { return null; } final char[] chars = text.toCharArray(); // We are OK with the limitations of Character.toLowerCase. The symbols and ideographs // for which it does not return the lower case value should not be used here (this isap // mostly used to convert part of setters/getters to properties) chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } /** * Whether the string contains dashes or not * * @param text the string to check * @return true if it contains dashes or false otherwise */ public static boolean isDashed(String text) { return !text.isEmpty() && text.indexOf('-') != -1; } /** * Converts the string from dash format into camel case (hello-great-world -> helloGreatWorld) * * @param text the string * @return the string camel cased */ public static String dashToCamelCase(final String text) { if (text == null) { return null; } if (!isDashed(text)) { return text; } // there is at least 1 dash so the capacity can be shorter int length = text.length(); StringBuilder sb = new StringBuilder(length - 1); boolean upper = false; for (int i = 0; i < length; i++) { char c = text.charAt(i); if (c == '-') { upper = true; } else { if (upper) { c = Character.toUpperCase(c); upper = false; } sb.append(c); } } return sb.toString(); } /** * Converts the string from dash format into camel case, using the special for skip mode where we should keep text * inside quotes or keys as-is. Where an input such as "camel.component.rabbitmq.args[queue.x-queue-type]" is * transformed into camel.component.rabbitmq.args[queue.xQueueType] * * @param text the string * @return the string camel cased */ private static String skippingDashToCamelCase(final String text) { if (text == null) { return null; } if (!isDashed(text)) { return text; } // there is at least 1 dash so the capacity can be shorter int length = text.length(); StringBuilder sb = new StringBuilder(length - 1); boolean upper = false; int singleQuotes = 0; int doubleQuotes = 0; boolean skip = false; for (int i = 0; i < length; i++) { char c = text.charAt(i); if (c == ']') { skip = false; } else if (c == '[') { skip = true; } else if (c == '\'') { singleQuotes++; } else if (c == '"') { doubleQuotes++; } if (singleQuotes > 0) { skip = singleQuotes % 2 == 1; } if (doubleQuotes > 0) { skip = doubleQuotes % 2 == 1; } if (skip) { sb.append(c); continue; } if (c == '-') { upper = true; } else { if (upper) { c = Character.toUpperCase(c); } sb.append(c); upper = false; } } return sb.toString(); } /** * Converts the string from dash format into camel case (hello-great-world -> helloGreatWorld) * * @param text the string * @param skipQuotedOrKeyed flag to skip converting within a quoted or keyed text * @return the string camel cased */ public static String dashToCamelCase(final String text, boolean skipQuotedOrKeyed) { if (!skipQuotedOrKeyed) { return dashToCamelCase(text); } else { return skippingDashToCamelCase(text); } } /** * Returns the string after the given token * * @param text the text * @param after the token * @return the text after the token, or <tt>null</tt> if text does not contain the token */ public static String after(String text, String after) { if (text == null) { return null; } int pos = text.indexOf(after); if (pos == -1) { return null; } return text.substring(pos + after.length()); } /** * Returns the string after the given token or the default value * * @param text the text * @param after the token * @param defaultValue the value to return if text does not contain the token * @return the text after the token, or the supplied defaultValue if text does not contain the token */ public static String after(String text, String after, String defaultValue) { String answer = after(text, after); return answer != null ? answer : defaultValue; } /** * Returns an object after the given token * * @param text the text * @param after the token * @param mapper a mapping function to convert the string after the token to type T * @return an Optional describing the result of applying a mapping function to the text after the token. */ public static <T> Optional<T> after(String text, String after, Function<String, T> mapper) { String result = after(text, after); if (result == null) { return Optional.empty(); } else { return Optional.ofNullable(mapper.apply(result)); } } /** * Returns the string after the last occurrence of the given token * * @param text the text * @param after the token * @return the text after the token, or <tt>null</tt> if text does not contain the token */ public static String afterLast(String text, String after) { if (text == null) { return null; } int pos = text.lastIndexOf(after); if (pos == -1) { return null; } return text.substring(pos + after.length()); } /** * Returns the string after the last occurrence of the given token, or the default value * * @param text the text * @param after the token * @param defaultValue the value to return if text does not contain the token * @return the text after the token, or the supplied defaultValue if text does not contain the token */ public static String afterLast(String text, String after, String defaultValue) { String answer = afterLast(text, after); return answer != null ? answer : defaultValue; } /** * Returns the string before the given token * * @param text the text * @param before the token * @return the text before the token, or <tt>null</tt> if text does not contain the token */ public static String before(String text, String before) { if (text == null) { return null; } int pos = text.indexOf(before); return pos == -1 ? null : text.substring(0, pos); } /** * Returns the string before the given token, or the default value * * @param text the text * @param before the token * @param defaultValue the value to return if text does not contain the token * @return the text before the token, or the supplied defaultValue if text does not contain the token */ public static String before(String text, String before, String defaultValue) { if (text == null) { return defaultValue; } int pos = text.indexOf(before); return pos == -1 ? defaultValue : text.substring(0, pos); } /** * Returns the string before the given token or the default value * * @param text the text * @param before the token * @param defaultValue the value to return if the text does not contain the token * @return the text before the token, or the supplied defaultValue if the text does not contain the * token */ public static String before(String text, char before, String defaultValue) { if (text == null) { return defaultValue; } int pos = text.indexOf(before); return pos == -1 ? defaultValue : text.substring(0, pos); } /** * Returns an object before the given token * * @param text the text * @param before the token * @param mapper a mapping function to convert the string before the token to type T * @return an Optional describing the result of applying a mapping function to the text before the token. */ public static <T> Optional<T> before(String text, String before, Function<String, T> mapper) { String result = before(text, before); if (result == null) { return Optional.empty(); } else { return Optional.ofNullable(mapper.apply(result)); } } /** * Returns the string before the last occurrence of the given token * * @param text the text * @param before the token * @return the text before the token, or <tt>null</tt> if the text does not contain the token */ public static String beforeLast(String text, String before) { if (text == null) { return null; } int pos = text.lastIndexOf(before); return pos == -1 ? null : text.substring(0, pos); } /** * Returns the string before the last occurrence of the given token, or the default value * * @param text the text * @param before the token * @param defaultValue the value to return if the text does not contain the token * @return the text before the token, or the supplied defaultValue if the text does not contain the * token */ public static String beforeLast(String text, String before, String defaultValue) { String answer = beforeLast(text, before); return answer != null ? answer : defaultValue; } /** * Returns the string between the given tokens * * @param text the text * @param after the before token * @param before the after token * @return the text between the tokens, or <tt>null</tt> if the text does not contain the tokens */ public static String between(final String text, String after, String before) { String ret = after(text, after); if (ret == null) { return null; } return before(ret, before); } /** * Returns an object between the given token * * @param text the text * @param after the before token * @param before the after token * @param mapper a mapping function to convert the string between the token to type T * @return an Optional describing the result of applying a mapping function to the text between the token. */ public static <T> Optional<T> between(String text, String after, String before, Function<String, T> mapper) { String result = between(text, after, before); if (result == null) { return Optional.empty(); } else { return Optional.ofNullable(mapper.apply(result)); } } /** * Returns the substring between the given head and tail * * @param text the text * @param head the head of the substring * @param tail the tail of the substring * @return the substring between the given head and tail */ public static String between(String text, int head, int tail) { int len = text.length(); if (head > 0) { if (head <= len) { text = text.substring(head); } else { text = ""; } len = text.length(); } if (tail > 0) { if (tail <= len) { text = text.substring(0, len - tail); } else { text = ""; } } return text; } /** * Returns the string between the most outer pair of tokens * <p/> * The number of token pairs must be even, e.g., there must be same number of before and after tokens, otherwise * <tt>null</tt> is returned * <p/> * This implementation skips matching when the text is either single or double-quoted. For example: * <tt>${body.matches("foo('bar')")</tt> Will not match the parenthesis from the quoted text. * * @param text the text * @param after the before token * @param before the after token * @return the text between the outer most tokens, or <tt>null</tt> if text does not contain the tokens */ public static String betweenOuterPair(String text, char before, char after) { if (text == null) { return null; } int pos = -1; int pos2 = -1; int count = 0; int count2 = 0; boolean singleQuoted = false; boolean doubleQuoted = false; for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (!doubleQuoted && ch == '\'') { singleQuoted = !singleQuoted; } else if (!singleQuoted && ch == '\"') { doubleQuoted = !doubleQuoted; } if (singleQuoted || doubleQuoted) { continue; } if (ch == before) { count++; } else if (ch == after) { count2++; } if (ch == before && pos == -1) { pos = i; } else if (ch == after) { pos2 = i; } } if (pos == -1 || pos2 == -1) { return null; } // must be even paris if (count != count2) { return null; } return text.substring(pos + 1, pos2); } /** * Returns an object between the most outer pair of tokens * * @param text the text * @param after the before token * @param before the after token * @param mapper a mapping function to convert the string between the most outer pair of tokens to type T * @return an Optional describing the result of applying a mapping function to the text between the most * outer pair of tokens. */ public static <T> Optional<T> betweenOuterPair(String text, char before, char after, Function<String, T> mapper) { String result = betweenOuterPair(text, before, after); if (result == null) { return Optional.empty(); } else { return Optional.ofNullable(mapper.apply(result)); } } /** * Returns true if the given name is a valid java identifier */ public static boolean isJavaIdentifier(String name) { if (name == null) { return false; } int size = name.length(); if (size < 1) { return false; } if (Character.isJavaIdentifierStart(name.charAt(0))) { for (int i = 1; i < size; i++) { if (!Character.isJavaIdentifierPart(name.charAt(i))) { return false; } } return true; } return false; } /** * Cleans the string to a pure Java identifier so we can use it for loading
name
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/key/JavaKeyStoreProvider.java
{ "start": 22184, "end": 22704 }
class ____ extends KeyProviderFactory { @Override public KeyProvider createProvider(URI providerName, Configuration conf) throws IOException { if (SCHEME_NAME.equals(providerName.getScheme())) { return new JavaKeyStoreProvider(providerName, conf); } return null; } } /** * An adapter between a KeyStore Key and our Metadata. This is used to store * the metadata in a KeyStore even though isn't really a key. */ public static
Factory
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/ItemJsonValuePublicMethod.java
{ "start": 175, "end": 495 }
class ____ { private final int value; @JsonCreator public ItemJsonValuePublicMethod(int value) { this.value = value; } public int getValue() { return this.value; } @JsonValue public String format() { return Integer.toString(value); } }
ItemJsonValuePublicMethod
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/syncjob/action/DeleteConnectorSyncJobAction.java
{ "start": 1525, "end": 4081 }
class ____ extends ConnectorSyncJobActionRequest implements ToXContentObject { public static final ParseField CONNECTOR_SYNC_JOB_ID_FIELD = new ParseField("connector_sync_job_id"); private final String connectorSyncJobId; public Request(StreamInput in) throws IOException { super(in); this.connectorSyncJobId = in.readString(); } public Request(String connectorSyncJobId) { this.connectorSyncJobId = connectorSyncJobId; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (Strings.isNullOrEmpty(connectorSyncJobId)) { validationException = addValidationError( ConnectorSyncJobConstants.EMPTY_CONNECTOR_SYNC_JOB_ID_ERROR_MESSAGE, validationException ); } return validationException; } public String getConnectorSyncJobId() { return connectorSyncJobId; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(connectorSyncJobId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request request = (Request) o; return Objects.equals(connectorSyncJobId, request.connectorSyncJobId); } @Override public int hashCode() { return Objects.hash(connectorSyncJobId); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(CONNECTOR_SYNC_JOB_ID_FIELD.getPreferredName(), connectorSyncJobId); builder.endObject(); return builder; } private static final ConstructingObjectParser<DeleteConnectorSyncJobAction.Request, Void> PARSER = new ConstructingObjectParser<>( "delete_connector_sync_job_request", false, (args) -> new Request((String) args[0]) ); static { PARSER.declareString(constructorArg(), CONNECTOR_SYNC_JOB_ID_FIELD); } public static DeleteConnectorSyncJobAction.Request parse(XContentParser parser) { return PARSER.apply(parser, null); } } }
Request
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java
{ "start": 23015, "end": 24628 }
class ____ extends DefaultStream { ConnectionStream() { super(0, CONNECTION_STREAM_ID, IDLE); } @Override public boolean isResetSent() { return false; } @Override DefaultEndpoint<? extends Http2FlowController> createdBy() { return null; } @Override public Http2Stream resetSent() { throw new UnsupportedOperationException(); } @Override public Http2Stream open(boolean halfClosed) { throw new UnsupportedOperationException(); } @Override public Http2Stream close() { throw new UnsupportedOperationException(); } @Override public Http2Stream closeLocalSide() { throw new UnsupportedOperationException(); } @Override public Http2Stream closeRemoteSide() { throw new UnsupportedOperationException(); } @Override public Http2Stream headersSent(boolean isInformational) { throw new UnsupportedOperationException(); } @Override public boolean isHeadersSent() { throw new UnsupportedOperationException(); } @Override public Http2Stream pushPromiseSent() { throw new UnsupportedOperationException(); } @Override public boolean isPushPromiseSent() { throw new UnsupportedOperationException(); } } /** * Simple endpoint implementation. */ private final
ConnectionStream
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/arbiters/ScriptArbiter.java
{ "start": 1850, "end": 2741 }
class ____ implements Arbiter { private final AbstractScript script; private final Configuration configuration; private ScriptArbiter(final Configuration configuration, final AbstractScript script) { this.configuration = configuration; this.script = script; } /** * Returns the boolean result of the Script. */ @Override public boolean isCondition() { final SimpleBindings bindings = new SimpleBindings(); bindings.putAll(configuration.getProperties()); bindings.put("substitutor", configuration.getStrSubstitutor()); final Object object = configuration.getScriptManager().execute(script.getId(), bindings); return Boolean.parseBoolean(object.toString()); } @PluginBuilderFactory public static Builder newBuilder() { return new Builder(); } public static
ScriptArbiter
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/IgniteQueueComponentBuilderFactory.java
{ "start": 1883, "end": 5699 }
interface ____ extends ComponentBuilder<IgniteQueueComponent> { /** * The resource from where to load the configuration. It can be a: URL, * String or InputStream type. * * The option is a: &lt;code&gt;java.lang.Object&lt;/code&gt; type. * * Group: producer * * @param configurationResource the value to set * @return the dsl builder */ default IgniteQueueComponentBuilder configurationResource(java.lang.Object configurationResource) { doSetProperty("configurationResource", configurationResource); return this; } /** * To use an existing Ignite instance. * * The option is a: &lt;code&gt;org.apache.ignite.Ignite&lt;/code&gt; * type. * * Group: producer * * @param ignite the value to set * @return the dsl builder */ default IgniteQueueComponentBuilder ignite(org.apache.ignite.Ignite ignite) { doSetProperty("ignite", ignite); return this; } /** * Allows the user to set a programmatic ignite configuration. * * The option is a: * &lt;code&gt;org.apache.ignite.configuration.IgniteConfiguration&lt;/code&gt; type. * * Group: producer * * @param igniteConfiguration the value to set * @return the dsl builder */ default IgniteQueueComponentBuilder igniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration igniteConfiguration) { doSetProperty("igniteConfiguration", igniteConfiguration); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default IgniteQueueComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default IgniteQueueComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } }
IgniteQueueComponentBuilder
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/SlowLogFields.java
{ "start": 640, "end": 1120 }
interface ____ { /** * Slow log fields for indexing events * @return map of field name to value */ Map<String, String> indexFields(); /** * Slow log fields for search events * @return map of field name to value */ Map<String, String> searchFields(); /** * Slow log fields for query * @return map of field name to value */ default Map<String, String> queryFields() { return Map.of(); } }
SlowLogFields
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/TopIntFloatAggregatorFunctionSupplier.java
{ "start": 650, "end": 1800 }
class ____ implements AggregatorFunctionSupplier { private final int limit; private final boolean ascending; public TopIntFloatAggregatorFunctionSupplier(int limit, boolean ascending) { this.limit = limit; this.ascending = ascending; } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return TopIntFloatAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return TopIntFloatGroupingAggregatorFunction.intermediateStateDesc(); } @Override public TopIntFloatAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { return TopIntFloatAggregatorFunction.create(driverContext, channels, limit, ascending); } @Override public TopIntFloatGroupingAggregatorFunction groupingAggregator(DriverContext driverContext, List<Integer> channels) { return TopIntFloatGroupingAggregatorFunction.create(channels, driverContext, limit, ascending); } @Override public String describe() { return "top_int of floats"; } }
TopIntFloatAggregatorFunctionSupplier
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/authzpolicy/NoAuthorizationPolicyResource.java
{ "start": 362, "end": 1207 }
class ____ { @Inject SecurityIdentity securityIdentity; @GET @Path("unsecured") public String unsecured() { return securityIdentity.getPrincipal().getName(); } @GET @Path("jax-rs-path-matching-http-perm") public String jaxRsPathMatchingHttpPerm(@Context SecurityContext securityContext) { return securityContext.getUserPrincipal().getName(); } @GET @Path("path-matching-http-perm") public String pathMatchingHttpPerm(@Context SecurityContext securityContext) { return securityContext.getUserPrincipal().getName(); } @RolesAllowed("admin") @GET @Path("roles-allowed-annotation") public String rolesAllowed(@Context SecurityContext securityContext) { return securityContext.getUserPrincipal().getName(); } }
NoAuthorizationPolicyResource
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneUnidirectionalTest.java
{ "start": 676, "end": 1147 }
class ____ { @Test public void testLifecycle(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Phone phone = new Phone( "123-456-7890" ); PhoneDetails details = new PhoneDetails( "T-Mobile", "GSM" ); phone.setDetails( details ); entityManager.persist( phone ); entityManager.persist( details ); } ); } //tag::associations-one-to-one-unidirectional-example[] @Entity(name = "Phone") public static
OneToOneUnidirectionalTest
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/PropertyMappingContextCustomizerFactoryTests.java
{ "start": 1780, "end": 5044 }
class ____ { private final PropertyMappingContextCustomizerFactory factory = new PropertyMappingContextCustomizerFactory(); @Test void getContextCustomizerWhenHasNoMappingShouldNotAddPropertySource() { ContextCustomizer customizer = this.factory.createContextCustomizer(NoMapping.class, Collections.emptyList()); ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); ConfigurableListableBeanFactory beanFactory = mock(ConfigurableListableBeanFactory.class); given(context.getEnvironment()).willReturn(environment); given(context.getBeanFactory()).willReturn(beanFactory); customizer.customizeContext(context, getMergedConfigConfiguration()); then(environment).shouldHaveNoInteractions(); } @Test void getContextCustomizerWhenHasTypeMappingShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(TypeMapping.class, Collections.emptyList()); assertThat(customizer).isNotNull(); } @Test void getContextCustomizerWhenHasAttributeMappingShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, Collections.emptyList()); assertThat(customizer).isNotNull(); } @Test void hashCodeAndEqualsShouldBeBasedOnPropertyValues() { ContextCustomizer customizer1 = this.factory.createContextCustomizer(TypeMapping.class, Collections.emptyList()); ContextCustomizer customizer2 = this.factory.createContextCustomizer(AttributeMapping.class, Collections.emptyList()); ContextCustomizer customizer3 = this.factory.createContextCustomizer(OtherMapping.class, Collections.emptyList()); assertThat(customizer1).hasSameHashCodeAs(customizer2); assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3); } @Test void prepareContextShouldAddPropertySource() { ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, Collections.emptyList()); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); customizer.customizeContext(context, getMergedConfigConfiguration()); assertThat(context.getEnvironment().getProperty("mapped")).isEqualTo("Mapped"); } @Test void propertyMappingShouldNotBeUsedWithComponent() { ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, Collections.emptyList()); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(ConfigMapping.class); customizer.customizeContext(context, getMergedConfigConfiguration()); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(context::refresh) .withMessageContaining("The @PropertyMapping annotation " + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " + "cannot be used in combination with the @Component annotation @Configuration"); } private MergedContextConfiguration getMergedConfigConfiguration() { return new MergedContextConfiguration(getClass(), null, null, null, mock(ContextLoader.class)); } @NoMappingAnnotation static
PropertyMappingContextCustomizerFactoryTests
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/javadoc/InvalidThrows.java
{ "start": 2208, "end": 3515 }
class ____ extends DocTreePathScanner<Void, Void> { private final VisitorState state; private final MethodTree methodTree; private ThrowsChecker(VisitorState state, MethodTree methodTree) { this.state = state; this.methodTree = methodTree; } @Override public Void visitThrows(ThrowsTree throwsTree, Void unused) { ReferenceTree exName = throwsTree.getExceptionName(); Element element = JavacTrees.instance(state.context).getElement(new DocTreePath(getCurrentPath(), exName)); if (element != null) { Type type = (Type) element.asType(); if (isCheckedException(type)) { if (methodTree.getThrows().stream().noneMatch(t -> isSubtype(type, getType(t), state))) { state.reportMatch( describeMatch( diagnosticPosition(getCurrentPath(), state), Utils.replace(throwsTree, "", state))); } } } return super.visitThrows(throwsTree, null); } private boolean isCheckedException(Type type) { return type.hasTag(TypeTag.CLASS) && !state.getTypes().isAssignable(type, state.getSymtab().errorType) && !state.getTypes().isAssignable(type, state.getSymtab().runtimeExceptionType); } } }
ThrowsChecker
java
quarkusio__quarkus
extensions/scheduler/api/src/main/java/io/quarkus/scheduler/SchedulerResumed.java
{ "start": 156, "end": 261 }
class ____ { public static final SchedulerResumed INSTANCE = new SchedulerResumed(); }
SchedulerResumed
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/SuggesterTest.java
{ "start": 6019, "end": 6580 }
class ____ { public static final String STR = "kurt"; @InlineMe(replacement = "Client.STR.length()", imports = "com.google.frobber.Client") @Deprecated public int stringLength() { return Client.STR.length(); } } """) .doTest(); } @Test public void protectedConstructor() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final
Client
java
apache__camel
components/camel-hl7/src/main/java/org/apache/camel/component/hl7/HL7DataFormat.java
{ "start": 4189, "end": 8606 }
class ____ extends ServiceSupport implements DataFormat, DataFormatName { private static final Map<String, String> HEADER_MAP = new HashMap<>(); private HapiContext hapiContext; private Parser parser; private boolean validate = true; static { HEADER_MAP.put(HL7_SENDING_APPLICATION, "MSH-3"); HEADER_MAP.put(HL7_SENDING_FACILITY, "MSH-4"); HEADER_MAP.put(HL7_RECEIVING_APPLICATION, "MSH-5"); HEADER_MAP.put(HL7_RECEIVING_FACILITY, "MSH-6"); HEADER_MAP.put(HL7_TIMESTAMP, "MSH-7"); HEADER_MAP.put(HL7_SECURITY, "MSH-8"); HEADER_MAP.put(HL7_MESSAGE_TYPE, "MSH-9-1"); HEADER_MAP.put(HL7_TRIGGER_EVENT, "MSH-9-2"); HEADER_MAP.put(HL7_MESSAGE_CONTROL, "MSH-10"); HEADER_MAP.put(HL7_PROCESSING_ID, "MSH-11"); HEADER_MAP.put(HL7_VERSION_ID, "MSH-12"); HEADER_MAP.put(HL7_CHARSET, "MSH-18"); } @Override public String getDataFormatName() { return "hl7"; } @Override public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception { Message message = ExchangeHelper.convertToMandatoryType(exchange, Message.class, body); String charsetName = HL7Charset.getCharsetName(message, exchange); String encoded = parser.encode(message); outputStream.write(encoded.getBytes(charsetName)); } @Override public Object unmarshal(Exchange exchange, InputStream inputStream) throws Exception { byte[] body = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, inputStream); String charsetName = HL7Charset.getCharsetName(body, guessCharsetName(body, exchange)); String bodyAsString = new String(body, charsetName); Message message = parser.parse(bodyAsString); // add MSH fields as message out headers Terser terser = new Terser(message); for (Map.Entry<String, String> entry : HEADER_MAP.entrySet()) { exchange.getOut().setHeader(entry.getKey(), terser.get(entry.getValue())); } exchange.getOut().setHeader(HL7_CONTEXT, hapiContext); exchange.getOut().setHeader(Exchange.CHARSET_NAME, charsetName); return message; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public HapiContext getHapiContext() { return hapiContext; } public void setHapiContext(HapiContext context) { this.hapiContext = context; } public Parser getParser() { return parser; } public void setParser(Parser parser) { this.parser = parser; } @Override protected void doStart() throws Exception { if (hapiContext == null) { ValidationContext validationContext; if (validate) { validationContext = ValidationContextFactory.defaultValidation(); } else { validationContext = ValidationContextFactory.noValidation(); } ParserConfiguration parserConfiguration; if (parser == null) { parserConfiguration = new ParserConfiguration(); parserConfiguration.setDefaultObx2Type("ST"); parserConfiguration.setInvalidObx2Type("ST"); parserConfiguration.setUnexpectedSegmentBehaviour(UnexpectedSegmentBehaviourEnum.ADD_INLINE); } else { parserConfiguration = parser.getParserConfiguration(); } hapiContext = new DefaultHapiContext(parserConfiguration, validationContext, new DefaultModelClassFactory()); } if (parser == null) { parser = hapiContext.getGenericParser(); } } @Override protected void doStop() throws Exception { // noop } /** * In HL7 the charset of the message can be set in MSH-18, but you need to decode the input stream in order to be * able to read MSH-18. This works well for differentiating e.g. between ASCII, UTF-8 and ISI-8859 charsets, but not * for multi-byte charsets like UTF-16, Big5 etc. * * This method is called to "guess" the initial encoding, and subclasses can overwrite it using 3rd party libraries * like ICU4J that provide a CharsetDetector. * * The implementation in this
HL7DataFormat
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/beans/BeanRegistrarTest.java
{ "start": 1924, "end": 2575 }
class ____ { public static volatile boolean beanDestroyerInvoked = false; @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(UselessBean.class, MyQualifier.class, NextQualifier.class, ListConsumer.class) .removeUnusedBeans(true) .addRemovalExclusion(b -> b.hasType(DotName.createSimple(ListConsumer.class.getName()))) .beanRegistrars(new TestRegistrar()).build(); @AfterAll public static void assertDestroyerInvoked() { Assertions.assertTrue(beanDestroyerInvoked); } @SuppressWarnings("serial") static
BeanRegistrarTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java
{ "start": 32000, "end": 32256 }
class ____ extends AbstractTestEventListener { @EventListener private void handleIt(TestEvent event) { collectEvent(event); } } @Component @Scope(scopeName = "custom", proxyMode = ScopedProxyMode.TARGET_CLASS) static
CglibProxyWithPrivateMethod
java
elastic__elasticsearch
modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/URLDecodeProcessorTests.java
{ "start": 612, "end": 2096 }
class ____ extends AbstractStringProcessorTestCase<String> { @Override protected String modifyInput(String input) { return "Hello%20G%C3%BCnter" + input; } @Override protected AbstractStringProcessor<String> newProcessor(String field, boolean ignoreMissing, String targetField) { return new URLDecodeProcessor(randomAlphaOfLength(10), null, field, ignoreMissing, targetField); } @Override protected String expectedResult(String input) { return "Hello Günter" + URLDecoder.decode(input, StandardCharsets.UTF_8); } @Override protected boolean isSupportedValue(Object value) { // some random strings produced by the randomized test framework contain invalid URL encodings if (value instanceof String) { return isValidUrlEncodedString((String) value); } else if (value instanceof List) { for (Object o : (List) value) { if ((o instanceof String) == false || isValidUrlEncodedString((String) o) == false) { return false; } } return true; } else { throw new IllegalArgumentException("unexpected type"); } } private static boolean isValidUrlEncodedString(String s) { try { URLDecoder.decode(s, StandardCharsets.UTF_8); return true; } catch (Exception e) { return false; } } }
URLDecodeProcessorTests
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/DefaultExecutionModeTests.java
{ "start": 7545, "end": 7604 }
class ____ { @Nested @TestInstance(PER_CLASS)
LevelOne
java
apache__rocketmq
filter/src/main/java/org/apache/rocketmq/filter/expression/Expression.java
{ "start": 1102, "end": 1350 }
interface ____ { /** * Calculate express result with context. * * @param context context of evaluation * @return the value of this expression */ Object evaluate(EvaluationContext context) throws Exception; }
Expression
java
apache__flink
flink-python/src/main/java/org/apache/flink/table/runtime/arrow/writers/DateWriter.java
{ "start": 2197, "end": 2687 }
class ____ extends DateWriter<RowData> { private DateWriterForRow(DateDayVector dateDayVector) { super(dateDayVector); } @Override boolean isNullAt(RowData in, int ordinal) { return in.isNullAt(ordinal); } @Override int readDate(RowData in, int ordinal) { return in.getInt(ordinal); } } /** {@link DateWriter} for {@link ArrayData} input. */ public static final
DateWriterForRow
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WeatherEndpointBuilderFactory.java
{ "start": 79435, "end": 80596 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final WeatherHeaderNameBuilder INSTANCE = new WeatherHeaderNameBuilder(); /** * Used by the producer to override the endpoint location and use the * location from this header instead. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code WeatherLocation}. */ public String weatherLocation() { return "CamelWeatherLocation"; } /** * The original query URL sent to the Open Weather Map site. * * The option is a: {@code String} type. * * Group: common * * @return the name of the header {@code WeatherQuery}. */ public String weatherQuery() { return "CamelWeatherQuery"; } } static WeatherEndpointBuilder endpointBuilder(String componentName, String path) {
WeatherHeaderNameBuilder
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.java
{ "start": 1082, "end": 1810 }
class ____ { @Test void testConsumer() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-registryNA-consumer.xml"); context.start(); HelloService helloService = context.getBean("helloService", HelloService.class); IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, () -> helloService.sayHello("dubbo")); Assertions.assertTrue(exception .getMessage() .contains("No such any registry to reference org.apache.dubbo.config.spring.api.HelloService")); } }
DubboXmlConsumerTest
java
apache__camel
components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/cookie/CookieConfiguration.java
{ "start": 1084, "end": 4005 }
class ____ { public static final String DEFAULT_PATH = "/"; public static final boolean DEFAULT_SECURE_FLAG = false; public static final boolean DEFAULT_HTTP_ONLY_FLAG = false; public static final CookieSameSite DEFAULT_SAME_SITE = CookieSameSite.LAX; @UriParam(defaultValue = "/") private String cookiePath = DEFAULT_PATH; @UriParam private String cookieDomain; @UriParam private Long cookieMaxAge; @UriParam(defaultValue = "false") private boolean cookieSecure = DEFAULT_SECURE_FLAG; @UriParam(defaultValue = "false") private boolean cookieHttpOnly = DEFAULT_HTTP_ONLY_FLAG; @UriParam(defaultValue = "Lax") private CookieSameSite cookieSameSite = DEFAULT_SAME_SITE; public CookieConfiguration() { } public CookieConfiguration(String cookiePath, String cookieDomain, Long cookieMaxAge, boolean cookieSecure, boolean cookieHttpOnly, CookieSameSite cookieSameSite) { this.cookiePath = cookiePath; this.cookieDomain = cookieDomain; this.cookieMaxAge = cookieMaxAge; this.cookieSecure = cookieSecure; this.cookieHttpOnly = cookieHttpOnly; this.cookieSameSite = cookieSameSite; } /** * Sets the URL path that must exist in the requested URL in order to send the Cookie. */ public void setCookiePath(String cookiePath) { this.cookiePath = cookiePath; } public String getCookiePath() { return cookiePath; } /** * Sets which server can receive cookies. */ public void setCookieDomain(String cookieDomain) { this.cookieDomain = cookieDomain; } public String getCookieDomain() { return cookieDomain; } /** * Sets the maximum cookie age in seconds. */ public void setCookieMaxAge(Long cookieMaxAge) { this.cookieMaxAge = cookieMaxAge; } public Long getCookieMaxAge() { return cookieMaxAge; } /** * Sets whether the cookie is only sent to the server with an encrypted request over HTTPS. */ public void setCookieSecure(boolean cookieSecure) { this.cookieSecure = cookieSecure; } public boolean isCookieSecure() { return cookieSecure; } /** * Sets whether to prevent client side scripts from accessing created cookies. */ public void setCookieHttpOnly(boolean cookieHttpOnly) { this.cookieHttpOnly = cookieHttpOnly; } public boolean isCookieHttpOnly() { return cookieHttpOnly; } /** * Sets whether to prevent the browser from sending cookies along with cross-site requests. */ public void setCookieSameSite(CookieSameSite cookieSameSite) { this.cookieSameSite = cookieSameSite; } public CookieSameSite getCookieSameSite() { return cookieSameSite; } public static
CookieConfiguration
java
apache__camel
components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppCommandTypeTest.java
{ "start": 1122, "end": 2574 }
class ____ { private Exchange exchange; @BeforeEach public void setUp() { exchange = new DefaultExchange(new DefaultCamelContext()); } @Test public void createSmppSubmitSmCommand() { assertSame(SmppCommandType.SUBMIT_SM, SmppCommandType.fromExchange(exchange)); } @Test public void createSmppSubmitMultiCommand() { exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitMulti"); assertSame(SmppCommandType.SUBMIT_MULTI, SmppCommandType.fromExchange(exchange)); } @Test public void createSmppDataSmCommand() { exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm"); assertSame(SmppCommandType.DATA_SHORT_MESSAGE, SmppCommandType.fromExchange(exchange)); } @Test public void createSmppReplaceSmCommand() { exchange.getIn().setHeader(SmppConstants.COMMAND, "ReplaceSm"); assertSame(SmppCommandType.REPLACE_SM, SmppCommandType.fromExchange(exchange)); } @Test public void createSmppQuerySmCommand() { exchange.getIn().setHeader(SmppConstants.COMMAND, "QuerySm"); assertSame(SmppCommandType.QUERY_SM, SmppCommandType.fromExchange(exchange)); } @Test public void createSmppCancelSmCommand() { exchange.getIn().setHeader(SmppConstants.COMMAND, "CancelSm"); assertSame(SmppCommandType.CANCEL_SM, SmppCommandType.fromExchange(exchange)); } }
SmppCommandTypeTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java
{ "start": 58652, "end": 58964 }
class ____ extends MethodCounter implements ThrowsAdvice { public void afterThrowing(IOException ex) { count(IOException.class.getName()); } public void afterThrowing(UncheckedException ex) { count(UncheckedException.class.getName()); } } @SuppressWarnings("serial") static
CountingThrowsAdvice
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/typehandlerinjection/Mapper.java
{ "start": 740, "end": 788 }
interface ____ { List<User> getUsers(); }
Mapper
java
google__dagger
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
{ "start": 13276, "end": 13584 }
class ____ {", " @Provides Map<String, String> stringMap() {", " return new HashMap<String, String>();", " }", " }", "", " @Module(includes = { TestModule1.class, TestModule2.class})", " abstract static
TestModule2
java
mockito__mockito
mockito-core/src/main/java/org/mockito/Spy.java
{ "start": 564, "end": 1690 }
class ____{ * //Instance for spying is created by calling constructor explicitly: * &#64;Spy Foo spyOnFoo = new Foo("argument"); * //Instance for spying is created by mockito via reflection (only default constructors supported): * &#64;Spy Bar spyOnBar; * private AutoCloseable closeable; * &#64;Before * public void init() { * closeable = MockitoAnnotations.openMocks(this); * } * &#64;After * public void release() throws Exception { * closeable.close(); * } * ... * } * </code></pre> * <p> * Same as doing: * * <pre class="code"><code class="java"> * Foo spyOnFoo = Mockito.spy(new Foo("argument")); * Bar spyOnBar = Mockito.spy(new Bar()); * </code></pre> * * <p> * <strong>A field annotated with &#064;Spy can be initialized explicitly at declaration point. * Alternatively, if you don't provide the instance Mockito will try to find zero argument constructor (even private) * and create an instance for you. * <u>But Mockito cannot instantiate inner classes, local classes, abstract classes and interfaces.</u></strong> * * For example this
Test
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/AnnotationMatcherTest.java
{ "start": 2457, "end": 3035 }
class ____ {} """); assertCompiles( nodeWithAnnotationMatches( /* shouldMatch= */ false, new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1")))); assertCompiles( nodeWithAnnotationMatches( /* shouldMatch= */ false, new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1")))); } @Test public void shouldMatchSingleAnnotationOnClass() { writeFile( "A.java", """ package com.google; @SampleAnnotation1 public
A
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/records/ElementCollectionOfRecordsTest.java
{ "start": 902, "end": 1930 }
class ____ { @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-18957" ) public void testInsertOrderOfRecordsInElementCollection(SessionFactoryScope scope) { scope.inTransaction( session -> { MainEntity me = new MainEntity(); me.setId( 1L ); me.addRecord( new Record( "c", "a", "b", 2L ) ); me.addRecord( new Record( "2c", "a2", "bb", 22L ) ); session.persist( me ); } ); scope.inTransaction( session -> { MainEntity me = session.find( MainEntity.class, 1L ); List<Record> records = me.getRecords(); assertEquals(2, records.size()); Record r = records.get( 0 ); assertEquals("a", r.aField); assertEquals("b", r.bField); assertEquals("c", r.cField); assertEquals(2L, r.longField); r = records.get( 1 ); assertEquals("a2", r.aField); assertEquals("bb", r.bField); assertEquals("2c", r.cField); assertEquals(22L, r.longField); } ); } @Entity(name = "MainEntity") public static
ElementCollectionOfRecordsTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/typeutils/DecimalDataTypeInfo.java
{ "start": 1378, "end": 3446 }
class ____ extends TypeInformation<DecimalData> implements DataTypeQueryable { private static final long serialVersionUID = 1L; public static DecimalDataTypeInfo of(int precision, int scale) { return new DecimalDataTypeInfo(precision, scale); } private final int precision; private final int scale; public DecimalDataTypeInfo(int precision, int scale) { this.precision = precision; this.scale = scale; } @Override public DataType getDataType() { return DataTypes.DECIMAL(precision, scale).bridgedTo(DecimalData.class); } @Override public boolean isBasicType() { return true; } @Override public boolean isTupleType() { return false; } @Override public int getArity() { return 1; } @Override public int getTotalFields() { return 1; } @Override public Class<DecimalData> getTypeClass() { return DecimalData.class; } @Override public boolean isKeyType() { return true; } @Override public TypeSerializer<DecimalData> createSerializer(SerializerConfig config) { return new DecimalDataSerializer(precision, scale); } @Override public String toString() { return String.format("Decimal(%d,%d)", precision, scale); } @Override public boolean equals(Object obj) { if (!(obj instanceof DecimalDataTypeInfo)) { return false; } DecimalDataTypeInfo that = (DecimalDataTypeInfo) obj; return this.precision == that.precision && this.scale == that.scale; } @Override public int hashCode() { int h0 = this.getClass().getCanonicalName().hashCode(); return Arrays.hashCode(new int[] {h0, precision, scale}); } @Override public boolean canEqual(Object obj) { return obj instanceof DecimalDataTypeInfo; } public int precision() { return precision; } public int scale() { return scale; } }
DecimalDataTypeInfo
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/formatstring/InlineFormatStringTest.java
{ "start": 2866, "end": 3220 }
class ____ { private static final String FORMAT = "hello %s"; void f(boolean b) { Preconditions.checkArgument(b, FORMAT, 42); } } """) .addOutputLines( "Test.java", """ import com.google.common.base.Preconditions;
Test
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/Option.java
{ "start": 5196, "end": 5525 }
interface ____<T> { /** * Updates the given {@link MessageDigest} with the bytes of the given key (to avoid incidental * value collisions when values are not particularly unique) and value. * * <p>If your {@link Option} shouldn't affect the disk cache key, you should not implement this *
CacheKeyUpdater
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/convert/MapConversionsTest.java
{ "start": 481, "end": 639 }
class ____ { public Integer A; public String B; } // [databind#287] @JsonSerialize(converter=RequestConverter.class) static
Bean
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/clusterframework/ApplicationStatusTest.java
{ "start": 1320, "end": 4772 }
class ____ { private static final int SUCCESS_EXIT_CODE = 0; @Test void succeededStatusMapsToSuccessExitCode() { int exitCode = ApplicationStatus.SUCCEEDED.processExitCode(); assertThat(exitCode).isEqualTo(SUCCESS_EXIT_CODE); } @Test void cancelledStatusMapsToSuccessExitCode() { int exitCode = ApplicationStatus.CANCELED.processExitCode(); assertThat(exitCode).isEqualTo(SUCCESS_EXIT_CODE); } @Test void notSucceededNorCancelledStatusMapsToNonSuccessExitCode() { Iterable<Integer> exitCodes = exitCodes(notSucceededNorCancelledStatus()); assertThat(exitCodes).doesNotContain(SUCCESS_EXIT_CODE); } @Test void testJobStatusFromSuccessApplicationStatus() { assertThat(ApplicationStatus.SUCCEEDED.deriveJobStatus()).isEqualTo(JobStatus.FINISHED); } @Test void testJobStatusFromFailedApplicationStatus() { assertThat(ApplicationStatus.FAILED.deriveJobStatus()).isEqualTo(JobStatus.FAILED); } @Test void testJobStatusFromCancelledApplicationStatus() { assertThat(ApplicationStatus.CANCELED.deriveJobStatus()).isEqualTo(JobStatus.CANCELED); } @Test void testJobStatusFailsFromUnknownApplicationStatuses() { assertThatThrownBy(ApplicationStatus.UNKNOWN::deriveJobStatus) .isInstanceOf(UnsupportedOperationException.class); } @Test void testSuccessApplicationStatusFromJobStatus() { assertThat(ApplicationStatus.fromJobStatus(JobStatus.FINISHED)) .isEqualTo(ApplicationStatus.SUCCEEDED); } @Test void testFailedApplicationStatusFromJobStatus() { assertThat(ApplicationStatus.fromJobStatus(JobStatus.FAILED)) .isEqualTo(ApplicationStatus.FAILED); } @Test void testCancelledApplicationStatusFromJobStatus() { assertThat(ApplicationStatus.fromJobStatus(JobStatus.CANCELED)) .isEqualTo(ApplicationStatus.CANCELED); } @ParameterizedTest @EnumSource( value = JobStatus.class, names = { "INITIALIZING", "CREATED", "RUNNING", "FAILING", "CANCELLING", "RESTARTING", "SUSPENDED", "RECONCILING" }) public void testUnknownApplicationStatusFromJobStatus(JobStatus jobStatus) { assertThat(ApplicationStatus.fromJobStatus(jobStatus)).isEqualTo(ApplicationStatus.UNKNOWN); } @Test void testUnknownApplicationStatusForMissingJobStatus() { assertThat(ApplicationStatus.fromJobStatus(null)).isEqualTo(ApplicationStatus.UNKNOWN); } private static Iterable<Integer> exitCodes(Iterable<ApplicationStatus> statuses) { return StreamSupport.stream(statuses.spliterator(), false) .map(ApplicationStatus::processExitCode) .collect(Collectors.toList()); } private static Iterable<ApplicationStatus> notSucceededNorCancelledStatus() { return Arrays.stream(ApplicationStatus.values()) .filter(ApplicationStatusTest::isNotSucceededNorCancelled) .collect(Collectors.toList()); } private static boolean isNotSucceededNorCancelled(ApplicationStatus status) { return status != ApplicationStatus.SUCCEEDED && status != ApplicationStatus.CANCELED; } }
ApplicationStatusTest
java
google__dagger
javatests/dagger/internal/codegen/ComponentCreatorTest.java
{ "start": 35269, "end": 35935 }
interface ____ {", " Supertype build();", " }", "}"); CompilerTests.daggerCompiler(foo, supertype, component) .withProcessingOptions(compilerOptions) .compile( subject -> { subject.hasErrorCount(0); subject.hasWarningCount(0); }); } @Test public void covariantFactoryMethodReturnType_hasNewMethod() { assume().that(compilerType).isEqualTo(JAVAC); Source foo = CompilerTests.javaSource( "test.Foo", "package test;", "", "import javax.inject.Inject;", "", "
Builder
java
quarkusio__quarkus
extensions/spring-boot-properties/deployment/src/main/java/io/quarkus/spring/boot/properties/deployment/ClassConfigurationPropertiesUtil.java
{ "start": 22403, "end": 28705 }
class ____ a default value for fields * by simply specifying the default value in its constructor * For such cases the strategy we follow is that when a requested property does not exist * we check the value from the corresponding getter (or read the field value if possible) * and if the value is not null we don't fail */ if (shouldCheckForDefaultValue(currentClassInHierarchy, field)) { ReadOptionalResponse readOptionalResponse = ConfigurationPropertiesUtil.createReadOptionalValueAndConvertIfNeeded( fullConfigName, fieldType, field.declaringClass().name(), methodCreator, mpConfig); // call the setter if the optional contained data createWriteValue(readOptionalResponse.getIsPresentTrue(), configObject, field, setter, useFieldAccess, readOptionalResponse.getValue()); } else { /* * In this case we want a missing property to cause an exception that we don't handle * So we call config.getValue making sure to handle collection values */ ResultHandle setterValue = ConfigurationPropertiesUtil.createReadMandatoryValueAndConvertIfNeeded( fullConfigName, fieldType, field.declaringClass().name(), methodCreator, mpConfig); createWriteValue(methodCreator, configObject, field, setter, useFieldAccess, setterValue); } if (field.type().kind() != Type.Kind.PRIMITIVE) { // the JVM assigns primitive types a default even though it doesn't show up in the bytecode configPropertyBuildItemCandidates .add(new ConfigPropertyBuildItemCandidate(field.name(), fullConfigName, fieldType)); } } private static String getFullConfigName(String prefixStr, ConfigMapping.NamingStrategy namingStrategy, FieldInfo field) { return prefixStr + "." + getEffectiveConfigName(namingStrategy, field); } private static String getEffectiveConfigName(ConfigMapping.NamingStrategy namingStrategy, FieldInfo field) { String nameToUse = field.name(); AnnotationInstance configPropertyAnnotation = field.annotation(DotNames.CONFIG_PROPERTY); if (configPropertyAnnotation != null) { AnnotationValue configPropertyNameValue = configPropertyAnnotation.value("name"); if ((configPropertyNameValue != null) && !configPropertyNameValue.asString().isEmpty()) { nameToUse = configPropertyNameValue.asString(); } } return getName(nameToUse, namingStrategy); } static String getName(String nameToUse, ConfigMapping.NamingStrategy namingStrategy) { switch (namingStrategy) { case KEBAB_CASE: return StringUtil.hyphenate(nameToUse); case VERBATIM: return nameToUse; case SNAKE_CASE: return String.join("_", new Iterable<String>() { @Override public Iterator<String> iterator() { return StringUtil.lowerCase(StringUtil.camelHumpsIterator(nameToUse)); } }); default: throw new IllegalArgumentException("Unsupported naming strategy: " + namingStrategy); } } private static void createWriteValue(BytecodeCreator bytecodeCreator, ResultHandle configObject, FieldInfo field, MethodInfo setter, boolean useFieldAccess, ResultHandle value) { if (useFieldAccess) { createFieldWrite(bytecodeCreator, configObject, field, value); } else { createSetterCall(bytecodeCreator, configObject, setter, value); } } private static void createSetterCall(BytecodeCreator bytecodeCreator, ResultHandle configObject, MethodInfo setter, ResultHandle value) { bytecodeCreator.invokeVirtualMethod( MethodDescriptor.of(setter), configObject, value); } private static void createFieldWrite(BytecodeCreator bytecodeCreator, ResultHandle configObject, FieldInfo field, ResultHandle value) { bytecodeCreator.writeInstanceField(FieldDescriptor.of(field), configObject, value); } private static boolean shouldCheckForDefaultValue(ClassInfo configPropertiesClassInfo, FieldInfo field) { String getterName = JavaBeanUtil.getGetterName(field.name(), field.type().name()); MethodInfo getterMethod = configPropertiesClassInfo.method(getterName); if (getterMethod != null) { return Modifier.isPublic(getterMethod.flags()); } return !Modifier.isFinal(field.flags()) && Modifier.isPublic(field.flags()); } /** * Create code that uses the validator in order to validate the entire object * If errors are found an IllegalArgumentException is thrown and the message * is constructed by calling the previously generated VIOLATION_SET_TO_STRING_METHOD */ private static void createValidationCodePath(MethodCreator bytecodeCreator, ResultHandle configObject, String configPrefix) { ResultHandle validationResult = bytecodeCreator.invokeInterfaceMethod( MethodDescriptor.ofMethod(VALIDATOR_CLASS, "validate", Set.class, Object.class, Class[].class), bytecodeCreator.getMethodParam(1), configObject, bytecodeCreator.newArray(Class.class, 0)); ResultHandle constraintSetIsEmpty = bytecodeCreator.invokeInterfaceMethod( MethodDescriptor.ofMethod(Set.class, "isEmpty", boolean.class), validationResult); BranchResult constraintSetIsEmptyBranch = bytecodeCreator.ifNonZero(constraintSetIsEmpty); constraintSetIsEmptyBranch.trueBranch().returnValue(configObject); BytecodeCreator constraintSetIsEmptyFalse = constraintSetIsEmptyBranch.falseBranch(); ResultHandle exception = constraintSetIsEmptyFalse.newInstance( MethodDescriptor.ofConstructor(CONSTRAINT_VIOLATION_EXCEPTION_CLASS, Set.class.getName()), validationResult); constraintSetIsEmptyFalse.throwException(exception); } }
defines
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoBuilderCompilationTest.java
{ "start": 23378, "end": 23767 }
interface ____ {", " abstract Baz build();", " }", "}"); Compilation compilation = javac().withProcessors(new AutoBuilderProcessor()).compile(javaFileObject); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining( "[AutoBuilderEnclosing] @AutoBuilder must specify ofClass=Something.
Builder
java
apache__camel
components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsPollingConsumer.java
{ "start": 1248, "end": 2982 }
class ____ extends PollingConsumerSupport { private final JmsOperations template; private final JmsEndpoint jmsEndpoint; public JmsPollingConsumer(JmsEndpoint endpoint, JmsOperations template) { super(endpoint); this.jmsEndpoint = endpoint; this.template = template; } @Override public JmsEndpoint getEndpoint() { return (JmsEndpoint) super.getEndpoint(); } @Override public Exchange receiveNoWait() { return receive(JmsDestinationAccessor.RECEIVE_TIMEOUT_NO_WAIT); } @Override public Exchange receive() { return receive(JmsDestinationAccessor.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } @Override public Exchange receive(long timeout) { setReceiveTimeout(timeout); Message message; // using the selector if (ObjectHelper.isNotEmpty(jmsEndpoint.getSelector())) { message = template.receiveSelected(jmsEndpoint.getSelector()); } else { message = template.receive(); } if (message != null) { return getEndpoint().createExchange(message, null); } return null; } @Override protected void doStart() throws Exception { // noop } @Override protected void doStop() throws Exception { // noop } protected void setReceiveTimeout(long timeout) { if (template instanceof JmsTemplate jmsTemplate) { jmsTemplate.setReceiveTimeout(timeout); } else { throw new IllegalArgumentException( "Cannot set the receiveTimeout property on unknown JmsOperations type: " + template.getClass().getName()); } } }
JmsPollingConsumer
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 109130, "end": 109243 }
class ____<T, B extends Builder<T, B>> { abstract B foo(T s); } } @AutoValue abstract static
Builder
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/NodeToLabelsInfo.java
{ "start": 1132, "end": 1695 }
class ____ { private HashMap<String, NodeLabelsInfo> nodeToLabels = new HashMap<String, NodeLabelsInfo>(); public NodeToLabelsInfo() { // JAXB needs this } public NodeToLabelsInfo(HashMap<String, NodeLabelsInfo> nodeToLabels) { if (nodeToLabels != null) { this.nodeToLabels.putAll(nodeToLabels); } } public HashMap<String, NodeLabelsInfo> getNodeToLabels() { return nodeToLabels; } public void setNodeToLabels(HashMap<String, NodeLabelsInfo> nodeToLabels) { this.nodeToLabels = nodeToLabels; } }
NodeToLabelsInfo
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/long_/LongAssert_isStrictlyBetween_Longs_Test.java
{ "start": 902, "end": 1247 }
class ____ extends LongAssertBaseTest { @Override protected LongAssert invoke_api_method() { return assertions.isStrictlyBetween(6L, 8L); } @Override protected void verify_internal_effects() { verify(longs).assertIsStrictlyBetween(getInfo(assertions), getActual(assertions), 6L, 8L); } }
LongAssert_isStrictlyBetween_Longs_Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/messages/GenericMessageTester.java
{ "start": 7846, "end": 8040 }
class ____ implements Instantiator<Float> { @Override public Float instantiate(Random rnd) { return rnd.nextFloat(); } } public static
FloatInstantiator
java
spring-projects__spring-boot
module/spring-boot-r2dbc/src/main/java/org/springframework/boot/r2dbc/autoconfigure/MultipleConnectionPoolConfigurationsFailureAnalyzer.java
{ "start": 996, "end": 1501 }
class ____ extends AbstractFailureAnalyzer<MultipleConnectionPoolConfigurationsException> { @Override protected FailureAnalysis analyze(Throwable rootFailure, MultipleConnectionPoolConfigurationsException cause) { return new FailureAnalysis(cause.getMessage(), "Update your configuration so that R2DBC connection pooling is configured using either the " + "spring.r2dbc.url property or the spring.r2dbc.pool.* properties", cause); } }
MultipleConnectionPoolConfigurationsFailureAnalyzer
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/seq/SequenceWriterTest.java
{ "start": 1611, "end": 1869 }
class ____ extends BareBase implements Closeable { public int c = 3; boolean closed = false; @Override public void close() throws IOException { closed = true; } } static
BareBaseCloseable
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java
{ "start": 32829, "end": 33368 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((requests) -> requests .anyRequest().authenticated()) .formLogin(withDefaults()) .csrf((csrf) -> csrf .disable()); // @formatter:on return http.build(); } @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(PasswordEncodedUser.user()); } } @Configuration @EnableWebSecurity static
DisableCsrfEnablesRequestCacheConfig
java
google__dagger
javatests/dagger/internal/codegen/KeywordValidatorTest.java
{ "start": 6753, "end": 7267 }
class ____ @Inject constructor(def: `goto`) {}", // "goto" is a Java keyword "", "class `goto` {}", ""); CompilerTests.daggerCompiler(componentSrc) .compile( subject -> { switch (CompilerTests.backend(subject)) { case KSP: subject .hasErrorContaining("The name 'goto' cannot be used because") .onSource(componentSrc) .onLineContaining("
MyClass
java
grpc__grpc-java
util/src/test/java/io/grpc/util/AdvancedTlsX509KeyManagerTest.java
{ "start": 1535, "end": 6146 }
class ____ { private static final String SERVER_0_KEY_FILE = "server0.key"; private static final String SERVER_0_PEM_FILE = "server0.pem"; private static final String CLIENT_0_KEY_FILE = "client.key"; private static final String CLIENT_0_PEM_FILE = "client.pem"; private static final String ALIAS = "default"; private ScheduledExecutorService executor; private File serverKey0File; private File serverCert0File; private File clientKey0File; private File clientCert0File; private PrivateKey serverKey0; private X509Certificate[] serverCert0; private PrivateKey clientKey0; private X509Certificate[] clientCert0; @Before public void setUp() throws Exception { executor = new FakeClock().getScheduledExecutorService(); serverKey0File = TestUtils.loadCert(SERVER_0_KEY_FILE); serverCert0File = TestUtils.loadCert(SERVER_0_PEM_FILE); clientKey0File = TestUtils.loadCert(CLIENT_0_KEY_FILE); clientCert0File = TestUtils.loadCert(CLIENT_0_PEM_FILE); serverKey0 = CertificateUtils.getPrivateKey(TlsTesting.loadCert(SERVER_0_KEY_FILE)); serverCert0 = CertificateUtils.getX509Certificates(TlsTesting.loadCert(SERVER_0_PEM_FILE)); clientKey0 = CertificateUtils.getPrivateKey(TlsTesting.loadCert(CLIENT_0_KEY_FILE)); clientCert0 = CertificateUtils.getX509Certificates(TlsTesting.loadCert(CLIENT_0_PEM_FILE)); } @Test public void updateTrustCredentials_replacesIssuers() throws Exception { // Overall happy path checking of public API. AdvancedTlsX509KeyManager serverKeyManager = new AdvancedTlsX509KeyManager(); serverKeyManager.updateIdentityCredentials(serverCert0, serverKey0); assertEquals(serverKey0, serverKeyManager.getPrivateKey(ALIAS)); assertArrayEquals(serverCert0, serverKeyManager.getCertificateChain(ALIAS)); serverKeyManager.updateIdentityCredentials(clientCert0File, clientKey0File); assertEquals(clientKey0, serverKeyManager.getPrivateKey(ALIAS)); assertArrayEquals(clientCert0, serverKeyManager.getCertificateChain(ALIAS)); serverKeyManager.updateIdentityCredentials(serverCert0File, serverKey0File,1, TimeUnit.MINUTES, executor); assertEquals(serverKey0, serverKeyManager.getPrivateKey(ALIAS)); assertArrayEquals(serverCert0, serverKeyManager.getCertificateChain(ALIAS)); serverKeyManager.updateIdentityCredentials(serverCert0, serverKey0); assertEquals(serverKey0, serverKeyManager.getPrivateKey(ALIAS)); assertArrayEquals(serverCert0, serverKeyManager.getCertificateChain(ALIAS)); } @Test public void credentialSettingParameterValidity() throws Exception { // Checking edge cases of public API parameter setting. AdvancedTlsX509KeyManager serverKeyManager = new AdvancedTlsX509KeyManager(); NullPointerException npe = assertThrows(NullPointerException.class, () -> serverKeyManager .updateIdentityCredentials(serverCert0, null)); assertEquals("key", npe.getMessage()); npe = assertThrows(NullPointerException.class, () -> serverKeyManager .updateIdentityCredentials(null, serverKey0)); assertEquals("certs", npe.getMessage()); npe = assertThrows(NullPointerException.class, () -> serverKeyManager .updateIdentityCredentials(null, serverKey0File)); assertEquals("certFile", npe.getMessage()); npe = assertThrows(NullPointerException.class, () -> serverKeyManager .updateIdentityCredentials(serverCert0File, null)); assertEquals("keyFile", npe.getMessage()); npe = assertThrows(NullPointerException.class, () -> serverKeyManager .updateIdentityCredentials(serverCert0File, serverKey0File, 1, null, executor)); assertEquals("unit", npe.getMessage()); npe = assertThrows(NullPointerException.class, () -> serverKeyManager .updateIdentityCredentials(serverCert0File, serverKey0File, 1, TimeUnit.MINUTES, null)); assertEquals("executor", npe.getMessage()); Logger log = Logger.getLogger(AdvancedTlsX509KeyManager.class.getName()); TestHandler handler = new TestHandler(); log.addHandler(handler); log.setUseParentHandlers(false); log.setLevel(Level.FINE); serverKeyManager.updateIdentityCredentials(serverCert0File, serverKey0File, -1, TimeUnit.SECONDS, executor); log.removeHandler(handler); for (LogRecord record : handler.getRecords()) { if (record.getMessage().contains("Default value of ")) { assertTrue(true); return; } } fail("Log message related to setting default values not found"); } private static
AdvancedTlsX509KeyManagerTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-session-data-redis-webflux/src/main/java/smoketest/session/SampleSessionWebFluxRedisApplication.java
{ "start": 1176, "end": 1682 }
class ____ { public static void main(String[] args) { SpringApplication.run(SampleSessionWebFluxRedisApplication.class); } @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((exchange) -> exchange.anyExchange().authenticated()); http.httpBasic((basic) -> basic.securityContextRepository(new WebSessionServerSecurityContextRepository())); http.formLogin(withDefaults()); return http.build(); } }
SampleSessionWebFluxRedisApplication
java
spring-projects__spring-security
saml2/saml2-service-provider/src/opensaml5Main/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml5AuthenticationProvider.java
{ "start": 23429, "end": 25830 }
class ____ implements Converter<ResponseToken, Saml2ResponseValidatorResult> { private static final List<Converter<ResponseToken, Saml2ResponseValidatorResult>> DEFAULTS = List .of(new InResponseToValidator(), new DestinationValidator(), new IssuerValidator()); private final List<Converter<ResponseToken, Saml2ResponseValidatorResult>> validators; @SafeVarargs public ResponseValidator(Converter<ResponseToken, Saml2ResponseValidatorResult>... validators) { this.validators = List.of(validators); Assert.notEmpty(this.validators, "validators cannot be empty"); } public static ResponseValidator withDefaults() { return new ResponseValidator(new InResponseToValidator(), new DestinationValidator(), new IssuerValidator()); } @SafeVarargs public static ResponseValidator withDefaults( Converter<ResponseToken, Saml2ResponseValidatorResult>... validators) { List<Converter<ResponseToken, Saml2ResponseValidatorResult>> defaults = new ArrayList<>(DEFAULTS); defaults.addAll(List.of(validators)); return new ResponseValidator(defaults.toArray(Converter[]::new)); } @Override public Saml2ResponseValidatorResult convert(ResponseToken responseToken) { Response response = responseToken.getResponse(); Collection<Saml2Error> errors = new ArrayList<>(); List<String> statusCodes = BaseOpenSamlAuthenticationProvider.getStatusCodes(response); if (!BaseOpenSamlAuthenticationProvider.isSuccess(statusCodes)) { for (String statusCode : statusCodes) { String message = String.format("Invalid status [%s] for SAML response [%s]", statusCode, response.getID()); errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, message)); } } for (Converter<ResponseToken, Saml2ResponseValidatorResult> validator : this.validators) { errors.addAll(validator.convert(responseToken).getErrors()); } if (response.getAssertions().isEmpty()) { errors.add(new Saml2Error(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, "No assertions found in response.")); } return Saml2ResponseValidatorResult.failure(errors); } } /** * A default implementation of {@link OpenSaml5AuthenticationProvider}'s assertion * validator. This does not check the signature as signature verification is performed * by a different component * * @author Josh Cummings * @since 6.5 */ public static final
ResponseValidator
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingComparatorForType_Test.java
{ "start": 1386, "end": 2756 }
class ____ extends ObjectArrayAssertBaseTest { private ObjectArrays arraysBefore; @BeforeEach void before() { arraysBefore = getArrays(assertions); } @Override protected ObjectArrayAssert<Object> invoke_api_method() { return assertions.usingComparatorForType(ALWAYS_EQUALS_STRING, String.class); } @Override protected void verify_internal_effects() { ObjectArrays arrays = getArrays(assertions); assertThat(arrays).isNotSameAs(arraysBefore); assertThat(arrays.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); ComparatorBasedComparisonStrategy strategy = (ComparatorBasedComparisonStrategy) arrays.getComparisonStrategy(); assertThat(strategy.getComparator()).isInstanceOf(ExtendedByTypesComparator.class); } @Test void should_be_able_to_use_a_comparator_for_specified_types() { // GIVEN Object[] array = array("some", "other", new BigDecimal(42)); // THEN then(array).usingComparatorForType(ALWAYS_EQUALS_STRING, String.class) .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class) .contains("other", "any", new BigDecimal("42.0")) .containsOnly("other", "any", new BigDecimal("42.00")) .containsExactly("other", "any", new BigDecimal("42.000")); } }
ObjectArrayAssert_usingComparatorForType_Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/jdk/TypedArraySerTest.java
{ "start": 1490, "end": 1682 }
interface ____ { } // for [JACKSON-341] @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT) @JsonSubTypes({ @JsonSubTypes.Type(B.class) })
WrapperMixIn
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/dynamicparameterized/DynamicParameterizedTypeTest.java
{ "start": 4056, "end": 4982 }
class ____ implements FunctionContributor { @Override public void contributeFunctions(FunctionContributions functionContributions) { functionContributions.getFunctionRegistry() .patternDescriptorBuilder( "test_func1", "?1" ) .setReturnTypeResolver(new FunctionReturnTypeResolver() { @Override public ReturnableType<?> resolveFunctionReturnType( ReturnableType<?> impliedType, @Nullable SqmToSqlAstConverter converter, List<? extends SqmTypedNode<?>> arguments, TypeConfiguration typeConfiguration) { assertInstanceOf(CustomType.class, arguments.get(0).getNodeType()); return null; } @Override public BasicValuedMapping resolveFunctionReturnType( Supplier<BasicValuedMapping> impliedTypeAccess, List<? extends SqlAstNode> arguments) { return null; } }) .register(); } } }
FunctionContributorImpl
java
google__dagger
javatests/dagger/hilt/android/testing/TestRootModulesTest.java
{ "start": 2990, "end": 3249 }
class ____ { @Provides @TestQualifier(4) static String provideString() { return "4"; } private AbstractModuleStaticProvides() {} } @Module @InstallIn(SingletonComponent.class) public abstract static
AbstractModuleStaticProvides
java
quarkusio__quarkus
independent-projects/tools/devtools-common/src/main/java/io/quarkus/maven/utilities/PomTransformer.java
{ "start": 7256, "end": 9350 }
class ____ { private final Path pomXmlPath; private final Document document; private final XPath xPath; private final String indentationString; public TransformationContext(Path pomXmlPath, Document document, String indentationString, XPath xPath) { super(); this.pomXmlPath = pomXmlPath; this.document = document; this.indentationString = indentationString; this.xPath = xPath; } /** * @return the path to the {@code pom.xml} file that is being transformed */ public Path getPomXmlPath() { return pomXmlPath; } /** * @return an {@link XPath} instance that can be used for querying the DOM of the transformed {@code pom.xml} * file */ public XPath getXPath() { return xPath; } /** * @return an indentation string (without newline characters) as it was autodetected using * {@link PomTransformer#detectIndentation(Node, XPath)} */ public String getIndentationString() { return indentationString; } /** * @param indentCount * @return a new indentation node containing a newline and {@code indentCount} times concatenated * {@link #indentationString} */ public Node indent(int indentCount) { final StringBuilder sb = new StringBuilder(1 + indentCount * indentationString.length()); sb.append('\n'); for (int i = 0; i < indentCount; i++) { sb.append(indentationString); } return document.createTextNode(sb.toString()); } public Node textElement(String elementName, String value) { final Node result = document.createElement(elementName); result.appendChild(document.createTextNode(value)); return result; } } /** * A transformation of a DOM */ public
TransformationContext
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/assumptions/AssumptionRunner.java
{ "start": 669, "end": 944 }
class ____<T> { protected final T actual; AssumptionRunner() { this.actual = null; } AssumptionRunner(T actual) { this.actual = actual; } protected abstract void runFailingAssumption(); protected abstract void runPassingAssumption(); }
AssumptionRunner
java
apache__kafka
server-common/src/test/java/org/apache/kafka/server/common/KRaftVersionTest.java
{ "start": 1191, "end": 4933 }
class ____ { @Test public void testFeatureLevel() { for (int i = 0; i < KRaftVersion.values().length; i++) { assertEquals(i, KRaftVersion.values()[i].featureLevel()); } } @Test public void testQuorumStateVersion() { for (int i = 0; i < KRaftVersion.values().length; i++) { assertEquals(i, KRaftVersion.values()[i].quorumStateVersion()); } } @Test public void testFromFeatureLevel() { for (int i = 0; i < KRaftVersion.values().length; i++) { assertEquals(KRaftVersion.values()[i], KRaftVersion.fromFeatureLevel((short) i)); } } @Test public void testBootstrapMetadataVersion() { for (int i = 0; i < KRaftVersion.values().length; i++) { MetadataVersion metadataVersion = KRaftVersion.values()[i].bootstrapMetadataVersion(); switch (i) { case 0: assertEquals(MetadataVersion.MINIMUM_VERSION, metadataVersion); break; case 1: assertEquals(MetadataVersion.IBP_3_9_IV0, metadataVersion); break; default: throw new RuntimeException("Unsupported value " + i); } } } @Test public void testKraftVersionRecordVersion() { for (KRaftVersion kraftVersion : KRaftVersion.values()) { switch (kraftVersion) { case KRAFT_VERSION_0: assertThrows( IllegalStateException.class, () -> kraftVersion.kraftVersionRecordVersion() ); break; case KRAFT_VERSION_1: assertEquals( ControlRecordUtils.KRAFT_VERSION_CURRENT_VERSION, kraftVersion.kraftVersionRecordVersion() ); break; default: throw new RuntimeException("Unsupported value " + kraftVersion); } } } @Test public void tesVotersRecordVersion() { for (KRaftVersion kraftVersion : KRaftVersion.values()) { switch (kraftVersion) { case KRAFT_VERSION_0: assertThrows( IllegalStateException.class, () -> kraftVersion.votersRecordVersion() ); break; case KRAFT_VERSION_1: assertEquals( ControlRecordUtils.KRAFT_VOTERS_CURRENT_VERSION, kraftVersion.votersRecordVersion() ); break; default: throw new RuntimeException("Unsupported value " + kraftVersion); } } } @Test public void testIsAtLeast() { assertTrue(KRaftVersion.KRAFT_VERSION_0.isAtLeast(KRaftVersion.KRAFT_VERSION_0)); assertFalse(KRaftVersion.KRAFT_VERSION_0.isAtLeast(KRaftVersion.KRAFT_VERSION_1)); assertTrue(KRaftVersion.KRAFT_VERSION_1.isAtLeast(KRaftVersion.KRAFT_VERSION_0)); assertTrue(KRaftVersion.KRAFT_VERSION_1.isAtLeast(KRaftVersion.KRAFT_VERSION_1)); } @Test public void testIsMoreThan() { assertFalse(KRaftVersion.KRAFT_VERSION_0.isMoreThan(KRaftVersion.KRAFT_VERSION_0)); assertFalse(KRaftVersion.KRAFT_VERSION_0.isMoreThan(KRaftVersion.KRAFT_VERSION_1)); assertTrue(KRaftVersion.KRAFT_VERSION_1.isMoreThan(KRaftVersion.KRAFT_VERSION_0)); assertFalse(KRaftVersion.KRAFT_VERSION_1.isMoreThan(KRaftVersion.KRAFT_VERSION_1)); } }
KRaftVersionTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/webapp/SCMMetricsInfo.java
{ "start": 1619, "end": 2908 }
class ____ { protected long totalDeletedFiles; protected long totalProcessedFiles; protected long cacheHits; protected long cacheMisses; protected long cacheReleases; protected long acceptedUploads; protected long rejectedUploads; public SCMMetricsInfo() { } public SCMMetricsInfo(CleanerMetrics cleanerMetrics, ClientSCMMetrics clientSCMMetrics, SharedCacheUploaderMetrics scmUploaderMetrics) { totalDeletedFiles = cleanerMetrics.getTotalDeletedFiles(); totalProcessedFiles = cleanerMetrics.getTotalProcessedFiles(); cacheHits = clientSCMMetrics.getCacheHits(); cacheMisses = clientSCMMetrics.getCacheMisses(); cacheReleases = clientSCMMetrics.getCacheReleases(); acceptedUploads = scmUploaderMetrics.getAcceptedUploads(); rejectedUploads = scmUploaderMetrics.getRejectUploads(); } public long getTotalDeletedFiles() { return totalDeletedFiles; } public long getTotalProcessedFiles() { return totalProcessedFiles; } public long getCacheHits() { return cacheHits; } public long getCacheMisses() { return cacheMisses; } public long getCacheReleases() { return cacheReleases; } public long getAcceptedUploads() { return acceptedUploads; } public long getRejectUploads() { return rejectedUploads; } }
SCMMetricsInfo
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/TestBZip2Codec.java
{ "start": 2161, "end": 7965 }
class ____ { private static final long HEADER_LEN = 2; private Configuration conf; private FileSystem fs; private BZip2Codec codec; private Decompressor decompressor; private Path tempFile; @BeforeEach public void setUp() throws Exception { conf = new Configuration(); Path workDir = new Path(System.getProperty("test.build.data", "target"), "data/" + getClass().getSimpleName()); Path inputDir = new Path(workDir, "input"); tempFile = new Path(inputDir, "test.txt.bz2"); fs = workDir.getFileSystem(conf); codec = new BZip2Codec(); codec.setConf(new Configuration(/* loadDefaults */ false)); decompressor = CodecPool.getDecompressor(codec); } @AfterEach public void tearDown() throws Exception { CodecPool.returnDecompressor(decompressor); fs.delete(tempFile, /* recursive */ false); } @Test public void createInputStreamWithStartAndEnd() throws Exception { byte[] data1 = newAlternatingByteArray(BLOCK_SIZE, 'a', 'b'); byte[] data2 = newAlternatingByteArray(BLOCK_SIZE, 'c', 'd'); byte[] data3 = newAlternatingByteArray(BLOCK_SIZE, 'e', 'f'); try (BZip2TextFileWriter writer = new BZip2TextFileWriter(tempFile, conf)) { writer.write(data1); writer.write(data2); writer.write(data3); } long fileSize = fs.getFileStatus(tempFile).getLen(); List<Long> nextBlockOffsets = BZip2Utils.getNextBlockMarkerOffsets(tempFile, conf); long block2Start = nextBlockOffsets.get(0); long block3Start = nextBlockOffsets.get(1); try (SplitCompressionInputStream stream = newCompressionStream(tempFile, 0, fileSize, BYBLOCK)) { assertEquals(0, stream.getPos()); assertCasesWhereReadDoesNotAdvanceStream(stream); assertReadingAtPositionZero(stream, data1); assertCasesWhereReadDoesNotAdvanceStream(stream); assertReadingPastEndOfBlock(stream, block2Start, data2); assertReadingPastEndOfBlock(stream, block3Start, data3); assertEquals(-1, stream.read()); } try (SplitCompressionInputStream stream = newCompressionStream(tempFile, 1, fileSize - 1, BYBLOCK)) { assertEquals(block2Start, stream.getPos()); assertCasesWhereReadDoesNotAdvanceStream(stream); assertReadingPastEndOfBlock(stream, block2Start, data2); assertCasesWhereReadDoesNotAdvanceStream(stream); assertReadingPastEndOfBlock(stream, block3Start, data3); assertEquals(-1, stream.read()); } // With continuous mode, only starting at or after the stream header is // supported. byte[] allData = Bytes.concat(data1, data2, data3); assertReadingWithContinuousMode(tempFile, 0, fileSize, allData); assertReadingWithContinuousMode(tempFile, HEADER_LEN, fileSize - HEADER_LEN, allData); } private void assertReadingWithContinuousMode(Path file, long start, long length, byte[] expectedData) throws IOException { try (SplitCompressionInputStream stream = newCompressionStream(file, start, length, CONTINUOUS)) { assertEquals(HEADER_LEN, stream.getPos()); assertRead(stream, expectedData); assertEquals(-1, stream.read()); // When specifying CONTINUOUS read mode, the position ends up not being // updated at all. assertEquals(HEADER_LEN, stream.getPos()); } } private SplitCompressionInputStream newCompressionStream(Path file, long start, long length, READ_MODE readMode) throws IOException { FSDataInputStream rawIn = fs.open(file); rawIn.seek(start); long end = start + length; return codec.createInputStream(rawIn, decompressor, start, end, readMode); } private static byte[] newAlternatingByteArray(int size, int... choices) { checkArgument(choices.length > 1); byte[] result = new byte[size]; for (int i = 0; i < size; i++) { result[i] = (byte) choices[i % choices.length]; } return result; } private static void assertCasesWhereReadDoesNotAdvanceStream(SplitCompressionInputStream in) throws IOException { long initialPos = in.getPos(); assertEquals(0, in.read(new byte[0])); assertThatNullPointerException().isThrownBy(() -> in.read(null, 0, 1)); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy( () -> in.read(new byte[5], -1, 2)); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy( () -> in.read(new byte[5], 0, -1)); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy( () -> in.read(new byte[5], 1, 5)); assertEquals(initialPos, in.getPos()); } private static void assertReadingAtPositionZero(SplitCompressionInputStream in, byte[] expectedData) throws IOException { byte[] buffer = new byte[expectedData.length]; assertEquals(1, in.read(buffer, 0, 1)); assertEquals(expectedData[0], buffer[0]); assertEquals(0, in.getPos()); IOUtils.readFully(in, buffer, 1, expectedData.length - 1); assertArrayEquals(expectedData, buffer); assertEquals(0, in.getPos()); } private static void assertReadingPastEndOfBlock(SplitCompressionInputStream in, long endOfBlockPos, byte[] expectedData) throws IOException { byte[] buffer = new byte[expectedData.length]; assertEquals(1, in.read(buffer)); assertEquals(expectedData[0], buffer[0]); assertEquals(endOfBlockPos + 1, in.getPos()); IOUtils.readFully(in, buffer, 1, expectedData.length - 1); assertArrayEquals(expectedData, buffer); assertEquals(endOfBlockPos + 1, in.getPos()); } private static void assertRead(InputStream in, byte[] expectedData) throws IOException { byte[] buffer = new byte[expectedData.length]; IOUtils.readFully(in, buffer); assertArrayEquals(expectedData, buffer); } }
TestBZip2Codec
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/injectionstrategy/shared/Gender.java
{ "start": 247, "end": 282 }
enum ____ { MALE, FEMALE }
Gender
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/TransportProvider.java
{ "start": 1769, "end": 2159 }
interface ____ extends Service { /** * Provides new {@link Transport} instance for given {@link RemoteRepository}, if possible. * * @throws TransportProviderException if passed in remote repository has invalid remote URL or unsupported protocol. */ @Nonnull Transport transport(@Nonnull Session session, @Nonnull RemoteRepository repository); }
TransportProvider
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TestJobImpl.java
{ "start": 50610, "end": 51258 }
class ____ extends StubbedOutputCommitter { CyclicBarrier syncBarrier; boolean shouldSucceed; public TestingOutputCommitter(CyclicBarrier syncBarrier, boolean shouldSucceed) { super(); this.syncBarrier = syncBarrier; this.shouldSucceed = shouldSucceed; } @Override public void commitJob(JobContext jobContext) throws IOException { try { syncBarrier.await(); } catch (BrokenBarrierException e) { } catch (InterruptedException e) { } if (!shouldSucceed) { throw new IOException("forced failure"); } } } private static
TestingOutputCommitter
java
grpc__grpc-java
api/src/main/java/io/grpc/DecompressorRegistry.java
{ "start": 4995, "end": 5276 }
class ____ { final Decompressor decompressor; final boolean advertised; DecompressorInfo(Decompressor decompressor, boolean advertised) { this.decompressor = checkNotNull(decompressor, "decompressor"); this.advertised = advertised; } } }
DecompressorInfo
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/visitor/SchemaStatVisitor.java
{ "start": 1834, "end": 15959 }
class ____ extends SQLASTVisitorAdapter { protected SchemaRepository repository; protected final List<SQLName> originalTables = new ArrayList<SQLName>(); protected final HashMap<TableStat.Name, TableStat> tableStats = new LinkedHashMap<TableStat.Name, TableStat>(); protected final Map<Long, Column> columns = new LinkedHashMap<Long, Column>(); protected final List<Condition> conditions = new ArrayList<Condition>(); protected final Set<Relationship> relationships = new LinkedHashSet<Relationship>(); protected final List<Column> orderByColumns = new ArrayList<Column>(); protected final Set<Column> groupByColumns = new LinkedHashSet<Column>(); protected final List<SQLAggregateExpr> aggregateFunctions = new ArrayList<SQLAggregateExpr>(); protected final List<SQLMethodInvokeExpr> functions = new ArrayList<SQLMethodInvokeExpr>(2); private List<Object> parameters; private Mode mode; protected DbType dbType; public SchemaStatVisitor() { this((DbType) null); } public SchemaStatVisitor(SchemaRepository repository) { if (repository != null) { this.dbType = repository.getDbType(); } this.repository = repository; } public SchemaStatVisitor(DbType dbType) { this(new SchemaRepository(dbType), new ArrayList<Object>()); this.dbType = dbType; } public SchemaStatVisitor(List<Object> parameters) { this((DbType) null, parameters); } public SchemaStatVisitor(DbType dbType, List<Object> parameters) { this(new SchemaRepository(dbType), parameters); this.parameters = parameters; } public SchemaStatVisitor(SchemaRepository repository, List<Object> parameters) { this.repository = repository; this.parameters = parameters; if (repository != null) { DbType dbType = repository.getDbType(); if (dbType != null && this.dbType == null) { this.dbType = dbType; } } } public SchemaRepository getRepository() { return repository; } public void setRepository(SchemaRepository repository) { this.repository = repository; } public List<Object> getParameters() { return parameters; } public void setParameters(List<Object> parameters) { this.parameters = parameters; } public TableStat getTableStat(String tableName) { tableName = handleName(tableName); TableStat.Name tableNameObj = new TableStat.Name(tableName); TableStat stat = tableStats.get(tableNameObj); if (stat == null) { stat = new TableStat(); tableStats.put(new TableStat.Name(tableName), stat); } return stat; } public TableStat getTableStat(SQLName tableName) { String strName; if (tableName instanceof SQLIdentifierExpr) { strName = ((SQLIdentifierExpr) tableName).normalizedName(); } else if (tableName instanceof SQLPropertyExpr) { strName = ((SQLPropertyExpr) tableName).normalizedName(); } else { strName = tableName.toString(); } long hashCode64 = tableName.hashCode64(); if (hashCode64 == FnvHash.Constants.DUAL) { return null; } originalTables.add(tableName); TableStat.Name tableNameObj = new TableStat.Name(strName, hashCode64); TableStat stat = tableStats.get(tableNameObj); if (stat == null) { stat = new TableStat(); tableStats.put(new TableStat.Name(strName, hashCode64), stat); } return stat; } protected Column addColumn(String tableName, String columnName) { Column c = new Column(tableName, columnName, dbType); Column column = this.columns.get(c.hashCode64()); if (column == null && columnName != null) { column = c; columns.put(c.hashCode64(), c); } return column; } protected Column addColumn(SQLName table, String columnName) { String tableName; if (table instanceof SQLIdentifierExpr) { tableName = ((SQLIdentifierExpr) table).normalizedName(); } else if (table instanceof SQLPropertyExpr) { tableName = ((SQLPropertyExpr) table).normalizedName(); } else { tableName = table.toString(); } long tableHashCode64 = table.hashCode64(); long basic = tableHashCode64; basic ^= '.'; basic *= FnvHash.PRIME; long columnHashCode64 = FnvHash.hashCode64(basic, columnName); Column column = this.columns.get(columnHashCode64); if (column == null && columnName != null) { column = new Column(tableName, columnName, columnHashCode64); columns.put(columnHashCode64, column); } return column; } private String handleName(String ident) { int len = ident.length(); if (ident.charAt(0) == '[' && ident.charAt(len - 1) == ']') { ident = ident.substring(1, len - 1); } else { boolean flag0 = false; boolean flag1 = false; boolean flag2 = false; boolean flag3 = false; for (int i = 0; i < len; ++i) { final char ch = ident.charAt(i); if (ch == '\"') { flag0 = true; } else if (ch == '`') { flag1 = true; } else if (ch == ' ') { flag2 = true; } else if (ch == '\'') { flag3 = true; } } if (flag0) { ident = ident.replaceAll("\"", ""); } if (flag1) { ident = ident.replaceAll("`", ""); } if (flag2) { ident = ident.replaceAll(" ", ""); } if (flag3) { ident = ident.replaceAll("'", ""); } } return ident; } protected Mode getMode() { return mode; } protected void setModeOrigin(SQLObject x) { Mode originalMode = (Mode) x.getAttribute("_original_use_mode"); mode = originalMode; } protected Mode setMode(SQLObject x, Mode mode) { Mode oldMode = this.mode; x.putAttribute("_original_use_mode", oldMode); this.mode = mode; return oldMode; } private boolean visitOrderBy(SQLIdentifierExpr x) { SQLTableSource tableSource = x.getResolvedTableSource(); if (tableSource == null && x.getParent() instanceof SQLSelectOrderByItem && x.getParent().getParent() instanceof SQLOrderBy && x.getParent().getParent().getParent() instanceof SQLSelectQueryBlock) { SQLSelectQueryBlock queryBlock = (SQLSelectQueryBlock) x.getParent().getParent().getParent(); SQLSelectItem selectItem = queryBlock.findSelectItem(x.nameHashCode64()); if (selectItem != null) { SQLExpr selectItemExpr = selectItem.getExpr(); if (selectItemExpr instanceof SQLIdentifierExpr) { x = (SQLIdentifierExpr) selectItemExpr; } else if (selectItemExpr instanceof SQLPropertyExpr) { return visitOrderBy((SQLPropertyExpr) selectItemExpr); } else { return false; } } } String tableName = null; if (tableSource instanceof SQLExprTableSource) { SQLExpr expr = ((SQLExprTableSource) tableSource).getExpr(); if (expr instanceof SQLIdentifierExpr) { SQLIdentifierExpr table = (SQLIdentifierExpr) expr; tableName = table.getName(); } else if (expr instanceof SQLPropertyExpr) { SQLPropertyExpr table = (SQLPropertyExpr) expr; tableName = table.toString(); } else if (expr instanceof SQLMethodInvokeExpr) { SQLMethodInvokeExpr methodInvokeExpr = (SQLMethodInvokeExpr) expr; if ("table".equalsIgnoreCase(methodInvokeExpr.getMethodName()) && methodInvokeExpr.getArguments().size() == 1 && methodInvokeExpr.getArguments().get(0) instanceof SQLName) { SQLName table = (SQLName) methodInvokeExpr.getArguments().get(0); if (table instanceof SQLPropertyExpr) { SQLPropertyExpr propertyExpr = (SQLPropertyExpr) table; SQLIdentifierExpr owner = (SQLIdentifierExpr) propertyExpr.getOwner(); if (propertyExpr.getResolvedTableSource() != null && propertyExpr.getResolvedTableSource() instanceof SQLExprTableSource) { SQLExpr resolveExpr = ((SQLExprTableSource) propertyExpr.getResolvedTableSource()).getExpr(); if (resolveExpr instanceof SQLName) { tableName = resolveExpr.toString() + "." + propertyExpr.getName(); } } } if (tableName == null) { tableName = table.toString(); } } } } else if (tableSource instanceof SQLWithSubqueryClause.Entry) { return false; } else if (tableSource instanceof SQLSubqueryTableSource) { SQLSelectQueryBlock queryBlock = ((SQLSubqueryTableSource) tableSource).getSelect().getQueryBlock(); if (queryBlock == null) { return false; } SQLSelectItem selectItem = queryBlock.findSelectItem(x.nameHashCode64()); if (selectItem == null) { return false; } SQLExpr selectItemExpr = selectItem.getExpr(); SQLTableSource columnTableSource = null; if (selectItemExpr instanceof SQLIdentifierExpr) { columnTableSource = ((SQLIdentifierExpr) selectItemExpr).getResolvedTableSource(); } else if (selectItemExpr instanceof SQLPropertyExpr) { columnTableSource = ((SQLPropertyExpr) selectItemExpr).getResolvedTableSource(); } if (columnTableSource instanceof SQLExprTableSource && ((SQLExprTableSource) columnTableSource).getExpr() instanceof SQLName) { SQLName tableExpr = (SQLName) ((SQLExprTableSource) columnTableSource).getExpr(); if (tableExpr instanceof SQLIdentifierExpr) { tableName = ((SQLIdentifierExpr) tableExpr).normalizedName(); } else if (tableExpr instanceof SQLPropertyExpr) { tableName = ((SQLPropertyExpr) tableExpr).normalizedName(); } } } else { boolean skip = false; for (SQLObject parent = x.getParent(); parent != null; parent = parent.getParent()) { if (parent instanceof SQLSelectQueryBlock) { SQLTableSource from = ((SQLSelectQueryBlock) parent).getFrom(); if (from instanceof SQLValuesTableSource) { skip = true; break; } } else if (parent instanceof SQLSelectQuery) { break; } } } String identName = x.getName(); if (tableName != null) { orderByAddColumn(tableName, identName, x); } else { orderByAddColumn("UNKNOWN", identName, x); } return false; } private boolean visitOrderBy(SQLPropertyExpr x) { if (isSubQueryOrParamOrVariant(x)) { return false; } String owner = null; SQLTableSource tableSource = x.getResolvedTableSource(); if (tableSource instanceof SQLExprTableSource) { SQLExpr tableSourceExpr = ((SQLExprTableSource) tableSource).getExpr(); if (tableSourceExpr instanceof SQLName) { owner = tableSourceExpr.toString(); } } if (owner == null && x.getOwner() instanceof SQLIdentifierExpr) { owner = ((SQLIdentifierExpr) x.getOwner()).getName(); } if (owner == null) { return false; } orderByAddColumn(owner, x.getName(), x); return false; } private boolean visitOrderBy(SQLIntegerExpr x) { SQLObject parent = x.getParent(); if (!(parent instanceof SQLSelectOrderByItem)) { return false; } if (parent.getParent() instanceof SQLSelectQueryBlock) { int selectItemIndex = x.getNumber().intValue() - 1; SQLSelectQueryBlock queryBlock = (SQLSelectQueryBlock) parent.getParent(); final List<SQLSelectItem> selectList = queryBlock.getSelectList(); if (selectItemIndex < 0 || selectItemIndex >= selectList.size()) { return false; } SQLExpr selectItemExpr = selectList.get(selectItemIndex).getExpr(); if (selectItemExpr instanceof SQLIdentifierExpr) { visitOrderBy((SQLIdentifierExpr) selectItemExpr); } else if (selectItemExpr instanceof SQLPropertyExpr) { visitOrderBy((SQLPropertyExpr) selectItemExpr); } } return false; } private void orderByAddColumn(String table, String columnName, SQLObject expr) { Column column = new Column(table, columnName, dbType); SQLObject parent = expr.getParent(); if (parent instanceof SQLSelectOrderByItem) { SQLOrderingSpecification type = ((SQLSelectOrderByItem) parent).getType(); column.getAttributes().put("orderBy.type", type); } orderByColumns.add(column); } protected
SchemaStatVisitor
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/contextualai/ContextualAiResponseHandler.java
{ "start": 859, "end": 2231 }
class ____ extends BaseResponseHandler { public ContextualAiResponseHandler(String requestType, ResponseParser parseFunction, boolean supportsStreaming) { super(requestType, parseFunction, ContextualAiErrorResponseEntity::fromResponse, supportsStreaming); } @Override protected void checkForFailureStatusCode(Request request, HttpResult result) throws RetryException { if (result.isSuccessfulResponse()) { return; } // handle error codes int statusCode = result.response().getStatusLine().getStatusCode(); if (statusCode == 500) { throw new RetryException(true, buildError(SERVER_ERROR, request, result)); } else if (statusCode > 500) { throw new RetryException(false, buildError(SERVER_ERROR, request, result)); } else if (statusCode == 429) { throw new RetryException(true, buildError(RATE_LIMIT, request, result)); } else if (statusCode == 401) { throw new RetryException(false, buildError(AUTHENTICATION, request, result)); } else if (statusCode >= 300 && statusCode < 400) { throw new RetryException(false, buildError(REDIRECTION, request, result)); } else { throw new RetryException(false, buildError(UNSUCCESSFUL, request, result)); } } }
ContextualAiResponseHandler
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/jsonFormatVisitors/JsonObjectFormatVisitor.java
{ "start": 395, "end": 1361 }
interface ____ extends JsonFormatVisitorWithSerializationContext { /** * Callback method called when a POJO property is being traversed. */ public void property(BeanProperty writer); /** * Callback method called when a non-POJO property (typically something * like an Enum entry of {@link java.util.EnumMap} type) is being * traversed. With POJOs, {@link #property(BeanProperty)} is called instead. */ public void property(String name, JsonFormatVisitable handler, JavaType propertyTypeHint); public void optionalProperty(BeanProperty writer); public void optionalProperty(String name, JsonFormatVisitable handler, JavaType propertyTypeHint); /** * Default "empty" implementation, useful as the base to start on; * especially as it is guaranteed to implement all the method * of the interface, even if new methods are getting added. */ public static
JsonObjectFormatVisitor
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/web/context/reactive/FilteredReactiveWebContextResource.java
{ "start": 1246, "end": 1988 }
class ____ extends AbstractResource { private final String path; FilteredReactiveWebContextResource(String path) { this.path = path; } @Override public boolean exists() { return false; } @Override public Resource createRelative(String relativePath) throws IOException { String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); return new FilteredReactiveWebContextResource(pathToUse); } @Override public String getDescription() { return "ReactiveWebContext resource [" + this.path + "]"; } @Override public InputStream getInputStream() throws IOException { throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } }
FilteredReactiveWebContextResource
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/serialization/entity/WithSimpleId.java
{ "start": 447, "end": 491 }
class ____ { @Id private Long id; }
WithSimpleId
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableGenerate.java
{ "start": 1035, "end": 1893 }
class ____<T, S> extends Flowable<T> { final Supplier<S> stateSupplier; final BiFunction<S, Emitter<T>, S> generator; final Consumer<? super S> disposeState; public FlowableGenerate(Supplier<S> stateSupplier, BiFunction<S, Emitter<T>, S> generator, Consumer<? super S> disposeState) { this.stateSupplier = stateSupplier; this.generator = generator; this.disposeState = disposeState; } @Override public void subscribeActual(Subscriber<? super T> s) { S state; try { state = stateSupplier.get(); } catch (Throwable e) { Exceptions.throwIfFatal(e); EmptySubscription.error(e, s); return; } s.onSubscribe(new GeneratorSubscription<>(s, generator, disposeState, state)); } static final
FlowableGenerate
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ValidatorEndpointBuilderFactory.java
{ "start": 1579, "end": 4397 }
interface ____ extends EndpointProducerBuilder { default AdvancedValidatorEndpointBuilder advanced() { return (AdvancedValidatorEndpointBuilder) this; } /** * Whether to fail if no body exists. * * The option is a: <code>boolean</code> type. * * Default: true * Group: producer * * @param failOnNullBody the value to set * @return the dsl builder */ default ValidatorEndpointBuilder failOnNullBody(boolean failOnNullBody) { doSetProperty("failOnNullBody", failOnNullBody); return this; } /** * Whether to fail if no body exists. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: producer * * @param failOnNullBody the value to set * @return the dsl builder */ default ValidatorEndpointBuilder failOnNullBody(String failOnNullBody) { doSetProperty("failOnNullBody", failOnNullBody); return this; } /** * Whether to fail if no header exists when validating against a header. * * The option is a: <code>boolean</code> type. * * Default: true * Group: producer * * @param failOnNullHeader the value to set * @return the dsl builder */ default ValidatorEndpointBuilder failOnNullHeader(boolean failOnNullHeader) { doSetProperty("failOnNullHeader", failOnNullHeader); return this; } /** * Whether to fail if no header exists when validating against a header. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: producer * * @param failOnNullHeader the value to set * @return the dsl builder */ default ValidatorEndpointBuilder failOnNullHeader(String failOnNullHeader) { doSetProperty("failOnNullHeader", failOnNullHeader); return this; } /** * To validate against a header instead of the message body. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param headerName the value to set * @return the dsl builder */ default ValidatorEndpointBuilder headerName(String headerName) { doSetProperty("headerName", headerName); return this; } } /** * Advanced builder for endpoint for the Validator component. */ public
ValidatorEndpointBuilder
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/api/CredProtectAuthenticationExtensionsClientInput.java
{ "start": 2238, "end": 2385 }
enum ____ { USER_VERIFICATION_OPTIONAL, USER_VERIFICATION_OPTIONAL_WITH_CREDENTIAL_ID_LIST, USER_VERIFICATION_REQUIRED } } }
ProtectionPolicy
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/ApplicationEvent.java
{ "start": 989, "end": 1367 }
class ____ extends AbstractEvent<ApplicationEventType> { private final ApplicationId applicationID; public ApplicationEvent(ApplicationId appID, ApplicationEventType appEventType) { super(appEventType, System.currentTimeMillis()); this.applicationID = appID; } public ApplicationId getApplicationID() { return this.applicationID; } }
ApplicationEvent
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/IdMappingConstant.java
{ "start": 891, "end": 1584 }
class ____ { /** Do user/group update every 15 minutes by default, minimum 1 minute */ public final static String USERGROUPID_UPDATE_MILLIS_KEY = "usergroupid.update.millis"; public final static long USERGROUPID_UPDATE_MILLIS_DEFAULT = 15 * 60 * 1000; // ms public final static long USERGROUPID_UPDATE_MILLIS_MIN = 1 * 60 * 1000; // ms public final static String UNKNOWN_USER = "nobody"; public final static String UNKNOWN_GROUP = "nobody"; // Used for finding the configured static mapping file. public static final String STATIC_ID_MAPPING_FILE_KEY = "static.id.mapping.file"; public static final String STATIC_ID_MAPPING_FILE_DEFAULT = "/etc/nfs.map"; }
IdMappingConstant
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_assertThat_with_primitive_char_Test.java
{ "start": 938, "end": 1153 }
class ____ { @Test void should_create_Assert() { AbstractCharacterAssert<?> assertions = Assertions.assertThat('a'); assertThat(assertions).isNotNull(); } }
Assertions_assertThat_with_primitive_char_Test
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/PortMapperImplTests.java
{ "start": 967, "end": 2829 }
class ____ { @Test public void testDefaultMappingsAreKnown() { PortMapperImpl portMapper = new PortMapperImpl(); assertThat(portMapper.lookupHttpPort(443)).isEqualTo(Integer.valueOf(80)); assertThat(Integer.valueOf(8080)).isEqualTo(portMapper.lookupHttpPort(8443)); assertThat(Integer.valueOf(443)).isEqualTo(portMapper.lookupHttpsPort(80)); assertThat(Integer.valueOf(8443)).isEqualTo(portMapper.lookupHttpsPort(8080)); } @Test public void testDetectsEmptyMap() { PortMapperImpl portMapper = new PortMapperImpl(); assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(new HashMap<>())); } @Test public void testDetectsNullMap() { PortMapperImpl portMapper = new PortMapperImpl(); assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(null)); } @Test public void testGetTranslatedPortMappings() { PortMapperImpl portMapper = new PortMapperImpl(); assertThat(portMapper.getTranslatedPortMappings()).hasSize(2); } @Test public void testRejectsOutOfRangeMappings() { PortMapperImpl portMapper = new PortMapperImpl(); Map<String, String> map = new HashMap<>(); map.put("79", "80559"); assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(map)); } @Test public void testReturnsNullIfHttpPortCannotBeFound() { PortMapperImpl portMapper = new PortMapperImpl(); assertThat(portMapper.lookupHttpPort(Integer.valueOf("34343")) == null).isTrue(); } @Test public void testSupportsCustomMappings() { PortMapperImpl portMapper = new PortMapperImpl(); Map<String, String> map = new HashMap<>(); map.put("79", "442"); portMapper.setPortMappings(map); assertThat(portMapper.lookupHttpPort(442)).isEqualTo(Integer.valueOf(79)); assertThat(Integer.valueOf(442)).isEqualTo(portMapper.lookupHttpsPort(79)); } }
PortMapperImplTests
java
apache__spark
sql/core/src/test/java/test/org/apache/spark/sql/JavaDatasetSuite.java
{ "start": 48204, "end": 48812 }
class ____ { private Integer field3_1 = 0; private Double field3_2 = 0.0; private String field3_3 = "value"; private Builder() { } public Builder field3_1(Integer field3_1) { this.field3_1 = field3_1; return this; } public Builder field3_2(Double field3_2) { this.field3_2 = field3_2; return this; } public Builder field3_3(String field3_3) { this.field3_3 = field3_3; return this; } public Nesting3 build() { return new Nesting3(this); } } } public static
Builder
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/MethodCallStaticMethodTest.java
{ "start": 1021, "end": 1827 }
class ____ extends ContextTestSupport { @Test public void testStaticMethod() throws Exception { getMockEndpoint("mock:result").expectedHeaderReceived("bar", "\"Hello World\""); getMockEndpoint("mock:result").expectedHeaderReceived("foo", "Hello World"); template.sendBodyAndHeader("direct:start", "The body", "bar", "\"Hello World\""); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").setHeader("foo", method(StringHelper.class, "removeLeadingAndEndingQuotes(${header.bar})")) .to("mock:result"); } }; } }
MethodCallStaticMethodTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggesterTest.java
{ "start": 19613, "end": 20112 }
class ____ { private String name; public Client setName(String name) { this.name = name; if (true) { return this; } return this; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.CanIgnoreReturnValue; public final
Client
java
apache__flink
flink-end-to-end-tests/flink-end-to-end-tests-common/src/main/java/org/apache/flink/tests/util/flink/JarAddition.java
{ "start": 920, "end": 1239 }
class ____ { private final Path jar; private final JarLocation target; JarAddition(Path jar, JarLocation target) { this.jar = jar; this.target = target; } public Path getJar() { return jar; } public JarLocation getTarget() { return target; } }
JarAddition
java
netty__netty
testsuite/src/main/java/io/netty/testsuite/transport/socket/DatagramUnicastTest.java
{ "start": 2439, "end": 2565 }
class ____ extends AbstractDatagramTest { private static final byte[] BYTES = {0, 1, 2, 3}; protected
DatagramUnicastTest
java
spring-projects__spring-framework
spring-core-test/src/test/java/com/example/PublicInterface.java
{ "start": 655, "end": 706 }
interface ____ { String perform(); }
PublicInterface
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxFilterFuseable.java
{ "start": 1140, "end": 1927 }
class ____<T> extends InternalFluxOperator<T, T> implements Fuseable { final Predicate<? super T> predicate; FluxFilterFuseable(Flux<? extends T> source, Predicate<? super T> predicate) { super(source); this.predicate = Objects.requireNonNull(predicate, "predicate"); } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { if (actual instanceof ConditionalSubscriber) { return new FilterFuseableConditionalSubscriber<>((ConditionalSubscriber<? super T>) actual, predicate); } return new FilterFuseableSubscriber<>(actual, predicate); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } static final
FluxFilterFuseable
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/settings/ApiKeySecrets.java
{ "start": 379, "end": 434 }
interface ____ { SecureString apiKey(); }
ApiKeySecrets
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 1281715, "end": 1285117 }
class ____ extends YamlDeserializerBase<XMLTokenizerExpression> { public XMLTokenizerExpressionDeserializer() { super(XMLTokenizerExpression.class); } @Override protected XMLTokenizerExpression newInstance() { return new XMLTokenizerExpression(); } @Override protected XMLTokenizerExpression newInstance(String value) { return new XMLTokenizerExpression(value); } @Override protected boolean setProperty(XMLTokenizerExpression target, String propertyKey, String propertyName, Node node) { propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey); switch(propertyKey) { case "expression": { String val = asText(node); target.setExpression(val); break; } case "group": { String val = asText(node); target.setGroup(val); break; } case "id": { String val = asText(node); target.setId(val); break; } case "mode": { String val = asText(node); target.setMode(val); break; } case "namespace": { java.util.List<org.apache.camel.model.PropertyDefinition> val = asFlatList(node, org.apache.camel.model.PropertyDefinition.class); target.setNamespace(val); break; } case "resultType": { String val = asText(node); target.setResultTypeName(val); break; } case "source": { String val = asText(node); target.setSource(val); break; } case "trim": { String val = asText(node); target.setTrim(val); break; } default: { ExpressionDefinition ed = target.getExpressionType(); if (ed != null) { throw new org.apache.camel.dsl.yaml.common.exception.DuplicateFieldException(node, propertyName, "as an expression"); } ed = ExpressionDeserializers.constructExpressionType(propertyKey, node); if (ed != null) { target.setExpressionType(ed); } else { return false; } } } return true; } } @YamlType( nodes = "xpath", inline = true, types = org.apache.camel.model.language.XPathExpression.class, order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1, displayName = "XPath", description = "Evaluates an XPath expression against an XML payload.", deprecated = false, properties = { @YamlProperty(name = "documentType", type = "string", description = "Name of
XMLTokenizerExpressionDeserializer
java
apache__spark
examples/src/main/java/org/apache/spark/examples/mllib/JavaRandomForestClassificationExample.java
{ "start": 1338, "end": 3387 }
class ____ { public static void main(String[] args) { // $example on$ SparkConf sparkConf = new SparkConf().setAppName("JavaRandomForestClassificationExample"); JavaSparkContext jsc = new JavaSparkContext(sparkConf); // Load and parse the data file. String datapath = "data/mllib/sample_libsvm_data.txt"; JavaRDD<LabeledPoint> data = MLUtils.loadLibSVMFile(jsc.sc(), datapath).toJavaRDD(); // Split the data into training and test sets (30% held out for testing) JavaRDD<LabeledPoint>[] splits = data.randomSplit(new double[]{0.7, 0.3}); JavaRDD<LabeledPoint> trainingData = splits[0]; JavaRDD<LabeledPoint> testData = splits[1]; // Train a RandomForest model. // Empty categoricalFeaturesInfo indicates all features are continuous. int numClasses = 2; Map<Integer, Integer> categoricalFeaturesInfo = new HashMap<>(); int numTrees = 3; // Use more in practice. String featureSubsetStrategy = "auto"; // Let the algorithm choose. String impurity = "gini"; int maxDepth = 5; int maxBins = 32; int seed = 12345; RandomForestModel model = RandomForest.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo, numTrees, featureSubsetStrategy, impurity, maxDepth, maxBins, seed); // Evaluate model on test instances and compute test error JavaPairRDD<Double, Double> predictionAndLabel = testData.mapToPair(p -> new Tuple2<>(model.predict(p.features()), p.label())); double testErr = predictionAndLabel.filter(pl -> !pl._1().equals(pl._2())).count() / (double) testData.count(); System.out.println("Test Error: " + testErr); System.out.println("Learned classification forest model:\n" + model.toDebugString()); // Save and load model model.save(jsc.sc(), "target/tmp/myRandomForestClassificationModel"); RandomForestModel sameModel = RandomForestModel.load(jsc.sc(), "target/tmp/myRandomForestClassificationModel"); // $example off$ jsc.stop(); } }
JavaRandomForestClassificationExample
java
apache__camel
components/camel-dapr/src/test/java/org/apache/camel/component/dapr/operations/DaprInvokeBindingTest.java
{ "start": 1844, "end": 4058 }
class ____ extends CamelTestSupport { @Mock private DaprClient client; @Mock private DaprEndpoint endpoint; @Test void testInvokeBinding() throws Exception { final byte[] mockResponse = "hello".getBytes(); when(endpoint.getClient()).thenReturn(client); when(client.invokeBinding(any(), any())).thenReturn(Mono.just(mockResponse)); DaprConfiguration configuration = new DaprConfiguration(); configuration.setOperation(DaprOperation.invokeBinding); configuration.setBindingName("myBinding"); configuration.setBindingOperation("myOperation"); DaprConfigurationOptionsProxy configurationOptionsProxy = new DaprConfigurationOptionsProxy(configuration); final Exchange exchange = new DefaultExchange(context); exchange.getMessage().setBody("myBody"); final DaprInvokeBindingHandler operation = new DaprInvokeBindingHandler(configurationOptionsProxy, endpoint); final DaprOperationResponse operationResponse = operation.handle(exchange); assertNotNull(operationResponse); assertEquals(mockResponse, operationResponse.getBody()); } @Test void testValidateConfiguration() { DaprConfiguration configuration = new DaprConfiguration(); configuration.setOperation(DaprOperation.invokeBinding); DaprConfigurationOptionsProxy configurationOptionsProxy = new DaprConfigurationOptionsProxy(configuration); final Exchange exchange = new DefaultExchange(context); final DaprInvokeBindingHandler operation = new DaprInvokeBindingHandler(configurationOptionsProxy, endpoint); // case 1: both bindingName and bindingOperation empty assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange)); // case 2: only bindingName set configuration.setBindingName("myBinding"); assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange)); // case 3: valid configuration configuration.setBindingOperation("myOperation"); assertDoesNotThrow(() -> operation.validateConfiguration(exchange)); } }
DaprInvokeBindingTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/XQueryEndpointBuilderFactory.java
{ "start": 26105, "end": 39926 }
interface ____ extends EndpointConsumerBuilder { default XQueryEndpointConsumerBuilder basic() { return (XQueryEndpointConsumerBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option is a: * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option will be converted to a * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder pollStrategy(String pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * To use a custom Saxon configuration. * * The option is a: <code>net.sf.saxon.Configuration</code> type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder configuration(net.sf.saxon.Configuration configuration) { doSetProperty("configuration", configuration); return this; } /** * To use a custom Saxon configuration. * * The option will be converted to a * <code>net.sf.saxon.Configuration</code> type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder configuration(String configuration) { doSetProperty("configuration", configuration); return this; } /** * To set custom Saxon configuration properties. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * * Group: advanced * * @param configurationProperties the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder configurationProperties(Map<java.lang.String, java.lang.Object> configurationProperties) { doSetProperty("configurationProperties", configurationProperties); return this; } /** * To set custom Saxon configuration properties. * * The option will be converted to a * <code>java.util.Map&lt;java.lang.String, java.lang.Object&gt;</code> * type. * * Group: advanced * * @param configurationProperties the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder configurationProperties(String configurationProperties) { doSetProperty("configurationProperties", configurationProperties); return this; } /** * To use the custom ModuleURIResolver. * * The option is a: <code>net.sf.saxon.lib.ModuleURIResolver</code> * type. * * Group: advanced * * @param moduleURIResolver the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder moduleURIResolver(net.sf.saxon.lib.ModuleURIResolver moduleURIResolver) { doSetProperty("moduleURIResolver", moduleURIResolver); return this; } /** * To use the custom ModuleURIResolver. * * The option will be converted to a * <code>net.sf.saxon.lib.ModuleURIResolver</code> type. * * Group: advanced * * @param moduleURIResolver the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder moduleURIResolver(String moduleURIResolver) { doSetProperty("moduleURIResolver", moduleURIResolver); return this; } /** * Additional parameters. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * * Group: advanced * * @param parameters the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder parameters(Map<java.lang.String, java.lang.Object> parameters) { doSetProperty("parameters", parameters); return this; } /** * Additional parameters. * * The option will be converted to a * <code>java.util.Map&lt;java.lang.String, java.lang.Object&gt;</code> * type. * * Group: advanced * * @param parameters the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder parameters(String parameters) { doSetProperty("parameters", parameters); return this; } /** * Properties to configure the serialization parameters. * * The option is a: <code>java.util.Properties</code> type. * * Group: advanced * * @param properties the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder properties(Properties properties) { doSetProperty("properties", properties); return this; } /** * Properties to configure the serialization parameters. * * The option will be converted to a <code>java.util.Properties</code> * type. * * Group: advanced * * @param properties the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder properties(String properties) { doSetProperty("properties", properties); return this; } /** * To use a custom Saxon StaticQueryContext. * * The option is a: <code>net.sf.saxon.query.StaticQueryContext</code> * type. * * Group: advanced * * @param staticQueryContext the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder staticQueryContext(net.sf.saxon.query.StaticQueryContext staticQueryContext) { doSetProperty("staticQueryContext", staticQueryContext); return this; } /** * To use a custom Saxon StaticQueryContext. * * The option will be converted to a * <code>net.sf.saxon.query.StaticQueryContext</code> type. * * Group: advanced * * @param staticQueryContext the value to set * @return the dsl builder */ default AdvancedXQueryEndpointConsumerBuilder staticQueryContext(String staticQueryContext) { doSetProperty("staticQueryContext", staticQueryContext); return this; } } /** * Builder for endpoint producers for the XQuery component. */ public
AdvancedXQueryEndpointConsumerBuilder
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/ContextResolverTest.java
{ "start": 1854, "end": 2334 }
class ____ { @Path("type/foo") @GET public Type foo() { return Type.FOO; } @Path("type/bar") @GET public Type bar() { return Type.BAR; } @Path("color/red") @GET public Color red() { return Color.RED; } @Path("color/black") @GET public Color black() { return Color.BLACK; } } public
EnumsResource
java
elastic__elasticsearch
x-pack/plugin/esql/qa/server/single-node/src/javaRestTest/java/org/elasticsearch/xpack/esql/qa/single_node/FieldExtractorIT.java
{ "start": 718, "end": 1173 }
class ____ extends FieldExtractorTestCase { @ClassRule public static ElasticsearchCluster cluster = Clusters.testCluster(); public FieldExtractorIT(MappedFieldType.FieldExtractPreference preference) { super(preference); } @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } @Override protected void canUsePragmasOk() { // always can use } }
FieldExtractorIT
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/EnumSerializerTest.java
{ "start": 1579, "end": 2274 }
class ____ { @Test void testPublicEnum() { testEnumSerializer(PrivateEnum.ONE, PrivateEnum.TWO, PrivateEnum.THREE); } @Test void testPrivateEnum() { testEnumSerializer( PublicEnum.FOO, PublicEnum.BAR, PublicEnum.PETER, PublicEnum.NATHANIEL, PublicEnum.EMMA, PublicEnum.PAULA); } @Test void testEmptyEnum() { assertThatThrownBy(() -> new EnumSerializer<>(EmptyEnum.class)) .isInstanceOf(IllegalArgumentException.class); } @Test void testReconfiguration() { // mock the previous ordering of
EnumSerializerTest
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/resource/DefaultThreadFactoryProvider.java
{ "start": 225, "end": 451 }
enum ____ implements ThreadFactoryProvider { INSTANCE; @Override public ThreadFactory getThreadFactory(String poolName) { return new DefaultThreadFactory(poolName, true); } }
DefaultThreadFactoryProvider
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorAnnotationNameTest.java
{ "start": 1296, "end": 1923 }
class ____ { @Id @GeneratedValue( strategy = SEQUENCE, generator = "explicit_product_sequence" ) private Long id; @Column(name = "product_name") private String name; //Getters and setters are omitted for brevity //end::identifiers-generators-sequence-mapping-example[] public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } //tag::identifiers-generators-sequence-mapping-example[] } //end::identifiers-generators-sequence-mapping-example[] }
Product