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-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java | {
"start": 1510,
"end": 3077
} | class ____ implements Metric {
private String applicationName;
private String threadPoolName;
public ThreadPoolRejectMetric(String applicationName, String threadPoolName) {
this.applicationName = applicationName;
this.threadPoolName = threadPoolName;
}
public String getThreadPoolName() {
return threadPoolName;
}
public void setThreadPoolName(String threadPoolName) {
this.threadPoolName = threadPoolName;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ThreadPoolRejectMetric that = (ThreadPoolRejectMetric) o;
return Objects.equals(applicationName, that.applicationName)
&& Objects.equals(threadPoolName, that.threadPoolName);
}
@Override
public int hashCode() {
return Objects.hash(applicationName, threadPoolName);
}
@Override
public Map<String, String> getTags() {
Map<String, String> tags = new HashMap<>();
tags.put(TAG_IP, getLocalHost());
tags.put(TAG_PID, ConfigUtils.getPid() + "");
tags.put(TAG_HOSTNAME, getLocalHostName());
tags.put(TAG_APPLICATION_NAME, applicationName);
tags.put(TAG_THREAD_NAME, threadPoolName);
return tags;
}
}
| ThreadPoolRejectMetric |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/Int2DArrayAssert.java | {
"start": 1388,
"end": 9399
} | class ____ extends Abstract2DArrayAssert<Int2DArrayAssert, int[][], Integer> {
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
protected Int2DArrays int2dArrays = Int2DArrays.instance();
private final Failures failures = Failures.instance();
public Int2DArrayAssert(int[][] actual) {
super(actual, Int2DArrayAssert.class);
}
/** {@inheritDoc} */
@Override
public Int2DArrayAssert isDeepEqualTo(int[][] expected) {
if (actual == expected) return myself;
isNotNull();
if (expected.length != actual.length) {
throw failures.failure(info, shouldHaveSameSizeAs(actual, expected, actual.length, expected.length));
}
for (int i = 0; i < actual.length; i++) {
int[] actualSubArray = actual[i];
int[] expectedSubArray = expected[i];
if (actualSubArray == expectedSubArray) continue;
if (actualSubArray == null) throw failures.failure(info, shouldNotBeNull("actual[" + i + "]"));
if (expectedSubArray.length != actualSubArray.length) {
throw failures.failure(info, subarraysShouldHaveSameSize(actual, expected, actualSubArray, actualSubArray.length,
expectedSubArray, expectedSubArray.length, i),
info.representation().toStringOf(actual), info.representation().toStringOf(expected));
}
for (int j = 0; j < actualSubArray.length; j++) {
if (actualSubArray[j] != expectedSubArray[j]) {
throw failures.failure(info, elementShouldBeEqual(actualSubArray[j], expectedSubArray[j], i, j),
info.representation().toStringOf(actual), info.representation().toStringOf(expected));
}
}
}
return myself;
}
/**
* Verifies that the actual {@code int[][]} is equal to the given one.
* <p>
* <b>WARNING!</b> This method will use {@code equals} to compare (it will compare arrays references only).<br>
* Unless you specify a comparator with {@link #usingComparator(Comparator)}, it is advised to use
* {@link #isDeepEqualTo(int[][])} instead.
* <p>
* Example:
* <pre><code class='java'> int[][] array = {{1, 2}, {3, 4}};
*
* // assertion will pass
* assertThat(array).isEqualTo(array);
*
* // assertion will fail as isEqualTo calls equals which compares arrays references only.
* assertThat(array).isEqualTo(new int[][] {{1, 2}, {3, 4}});</code></pre>
*
* @param expected the given value to compare the actual {@code int[][]} to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code int[][]} is not equal to the given one.
*/
@Override
public Int2DArrayAssert isEqualTo(Object expected) {
return super.isEqualTo(expected);
}
/** {@inheritDoc} */
@Override
public void isNullOrEmpty() {
int2dArrays.assertNullOrEmpty(info, actual);
}
/** {@inheritDoc} */
@Override
public void isEmpty() {
int2dArrays.assertEmpty(info, actual);
}
/** {@inheritDoc} */
@Override
public Int2DArrayAssert isNotEmpty() {
int2dArrays.assertNotEmpty(info, actual);
return myself;
}
/** {@inheritDoc} */
@Override
public Int2DArrayAssert hasDimensions(int expectedFirstDimension, int expectedSecondDimension) {
int2dArrays.assertHasDimensions(info, actual, expectedFirstDimension, expectedSecondDimension);
return myself;
}
/**
* Verifies that the actual two-dimensional array has the given number of rows.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat(new int[][] {{1, 2, 3}, {4, 5, 6}}).hasNumberOfRows(2);
* assertThat(new int[][] {{1}, {1, 2}, {1, 2, 3}}).hasNumberOfRows(3);
*
* // assertions will fail
* assertThat(new int[][] { }).hasNumberOfRows(1);
* assertThat(new int[][] {{1, 2, 3}, {4, 5, 6}}).hasNumberOfRows(3);
* assertThat(new int[][] {{1, 2, 3}, {4, 5, 6, 7}}).hasNumberOfRows(1); </code></pre>
*
* @param expected the expected number of rows of the two-dimensional array.
* @return {@code this} assertion object.
* @throws AssertionError if the actual number of rows are not equal to the given one.
*/
@Override
public Int2DArrayAssert hasNumberOfRows(int expected) {
int2dArrays.assertNumberOfRows(info, actual, expected);
return myself;
}
/**
* Verifies that the actual {@code int[][]} has the same dimensions as the given array.
* <p>
* Parameter is declared as Object to accept both Object and primitive arrays.
* </p>
* Example:
* <pre><code class='java'> int[][] intArray = {{1, 2, 3}, {4, 5, 6}};
* char[][] charArray = {{'a', 'b', 'c'}, {'d', 'e', 'f'}};
*
* // assertion will pass
* assertThat(intArray).hasSameDimensionsAs(charArray);
*
* // assertions will fail
* assertThat(intArray).hasSameDimensionsAs(new int[][] {{'a', 'b'}, {'c', 'd'}, {'e', 'f'}});
* assertThat(intArray).hasSameDimensionsAs(new int[][] {{'a', 'b'}, {'c', 'd', 'e'}});
* assertThat(intArray).hasSameDimensionsAs(new int[][] {{'a', 'b', 'c'}, {'d', 'e'}});</code></pre>
*
* @param array the array to compare dimensions with actual {@code int[][]}.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code int[][]} is {@code null}.
* @throws AssertionError if the array parameter is {@code null} or is not a true array.
* @throws AssertionError if actual {@code int[][]} and given array don't have the same dimensions.
*/
@Override
public Int2DArrayAssert hasSameDimensionsAs(Object array) {
int2dArrays.assertHasSameDimensionsAs(info, actual, array);
return myself;
}
/**
* Verifies that the actual array contains the given int[] at the given index.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat(new int[][] {{1, 2}, {3, 4}, {5, 6}}).contains(new int[] {3, 4}, atIndex(1));
*
* // assertions will fail
* assertThat(new int[][] {{1, 2}, {3, 4}, {5, 6}}).contains(new int[] {3, 4}, atIndex(0));
* assertThat(new int[][] {{1, 2}, {3, 4}, {5, 6}}).contains(new int[] {7, 8}, atIndex(2));</code></pre>
*
* @param value the value to look for.
* @param index the index where the value should be stored in the actual array.
* @return myself assertion object.
* @throws AssertionError if the actual array is {@code null} or empty.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of
* the actual array.
* @throws AssertionError if the actual array does not contain the given value at the given index.
*/
public Int2DArrayAssert contains(int[] value, Index index) {
int2dArrays.assertContains(info, actual, value, index);
return myself;
}
/**
* Verifies that the actual array does not contain the given value at the given index.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat(new int[][] {{1, 2}, {3, 4}, {5, 6}}).doesNotContain(new int[] {3, 4}, atIndex(0));
* assertThat(new int[][] {{1, 2}, {3, 4}, {5, 6}}).doesNotContain(new int[] {7, 8}, atIndex(2));
*
* // assertion will fail
* assertThat(new int[][] {{1, 2}, {3, 4}, {5, 6}}).doesNotContain(new int[] {3, 4}, atIndex(1));</code></pre>
*
* @param value the value to look for.
* @param index the index where the value should be stored in the actual array.
* @return myself assertion object.
* @throws AssertionError if the actual array is {@code null}.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws AssertionError if the actual array contains the given value at the given index.
*/
public Int2DArrayAssert doesNotContain(int[] value, Index index) {
int2dArrays.assertDoesNotContain(info, actual, value, index);
return myself;
}
}
| Int2DArrayAssert |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/processor/internals/GlobalStateManager.java | {
"start": 942,
"end": 1324
} | interface ____ extends StateManager {
void setGlobalProcessorContext(final InternalProcessorContext<?, ?> processorContext);
/**
* @throws IllegalStateException If store gets registered after initialized is already finished
* @throws StreamsException if the store's change log does not contain the partition
*/
Set<String> initialize();
}
| GlobalStateManager |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webmvc/src/test/java/org/springframework/cloud/gateway/server/mvc/config/FunctionHandlerConfigTests.java | {
"start": 2525,
"end": 2718
} | class ____ {
@Bean
Function<String, String> upper() {
return s -> s.toUpperCase(Locale.ROOT);
}
@Bean
Supplier<String> hello() {
return () -> "hello";
}
}
}
| TestConfiguration |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/EvaluatorImplementer.java | {
"start": 13565,
"end": 18705
} | class ____ {
final ExecutableElement function;
final List<Argument> args;
private final BuilderArgument builderArg;
private final List<TypeMirror> warnExceptions;
private boolean hasBlockType;
ProcessFunction(javax.lang.model.util.Types types, ExecutableElement function, List<TypeMirror> warnExceptions) {
this.function = function;
args = new ArrayList<>();
BuilderArgument builderArg = null;
hasBlockType = false;
for (VariableElement v : function.getParameters()) {
Argument arg = Argument.fromParameter(types, v);
if (arg instanceof BuilderArgument ba) {
if (builderArg != null) {
throw new IllegalArgumentException("only one builder allowed");
}
builderArg = ba;
} else if (arg instanceof BlockArgument) {
hasBlockType = true;
}
args.add(arg);
}
this.builderArg = builderArg;
this.warnExceptions = warnExceptions;
}
TypeName returnType() {
return TypeName.get(function.getReturnType());
}
ClassName resultDataType(boolean blockStyle) {
if (builderArg != null) {
return builderArg.type().enclosingClassName();
}
boolean useBlockStyle = blockStyle || warnExceptions.isEmpty() == false;
return useBlockStyle ? blockType(returnType()) : vectorType(returnType());
}
String appendMethod() {
return Methods.appendMethod(returnType());
}
@Override
public String toString() {
return "ProcessFunction{"
+ "function="
+ function
+ ", args="
+ args
+ ", builderArg="
+ builderArg
+ ", warnExceptions="
+ warnExceptions
+ ", hasBlockType="
+ hasBlockType
+ '}';
}
MethodSpec toStringMethod(ClassName implementation) {
MethodSpec.Builder builder = MethodSpec.methodBuilder("toString").addAnnotation(Override.class);
builder.addModifiers(Modifier.PUBLIC).returns(String.class);
StringBuilder pattern = new StringBuilder();
List<Object> args = new ArrayList<>();
pattern.append("return $S");
args.add(implementation.simpleName() + "[");
this.args.forEach(a -> a.buildToStringInvocation(pattern, args, args.size() > 2 ? ", " : ""));
pattern.append(" + $S");
args.add("]");
builder.addStatement(pattern.toString(), args.toArray());
return builder.build();
}
MethodSpec factoryCtor() {
MethodSpec.Builder builder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
builder.addParameter(SOURCE, "source");
builder.addStatement("this.source = source");
args.forEach(a -> a.implementFactoryCtor(builder));
return builder.build();
}
MethodSpec factoryGet(ClassName implementation) {
MethodSpec.Builder builder = MethodSpec.methodBuilder("get").addAnnotation(Override.class);
builder.addModifiers(Modifier.PUBLIC);
builder.addParameter(DRIVER_CONTEXT, "context");
builder.returns(implementation);
List<String> args = new ArrayList<>();
args.add("source");
for (Argument arg : this.args) {
String invocation = arg.factoryInvocation(builder);
if (invocation != null) {
args.add(invocation);
}
}
args.add("context");
builder.addStatement("return new $T($L)", implementation, String.join(", ", args));
return builder.build();
}
MethodSpec close() {
MethodSpec.Builder builder = MethodSpec.methodBuilder("close").addAnnotation(Override.class);
builder.addModifiers(Modifier.PUBLIC);
List<String> invocations = args.stream().map(Argument::closeInvocation).filter(Objects::nonNull).toList();
if (invocations.isEmpty() == false) {
builder.addStatement("$T.closeExpectNoException(" + String.join(", ", invocations) + ")", Types.RELEASABLES);
}
return builder.build();
}
MethodSpec baseRamBytesUsed() {
MethodSpec.Builder builder = MethodSpec.methodBuilder("baseRamBytesUsed").addAnnotation(Override.class);
builder.addModifiers(Modifier.PUBLIC).returns(TypeName.LONG);
builder.addStatement("long baseRamBytesUsed = BASE_RAM_BYTES_USED");
for (Argument arg : args) {
arg.sumBaseRamBytesUsed(builder);
}
builder.addStatement("return baseRamBytesUsed");
return builder.build();
}
}
}
| ProcessFunction |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/UnmarshalDefinition.java | {
"start": 4106,
"end": 11679
} | class ____ extends NoOutputDefinition<UnmarshalDefinition> implements DataFormatDefinitionAware {
@XmlElements({
@XmlElement(name = "asn1", type = ASN1DataFormat.class),
@XmlElement(name = "avro", type = AvroDataFormat.class),
@XmlElement(name = "barcode", type = BarcodeDataFormat.class),
@XmlElement(name = "base64", type = Base64DataFormat.class),
@XmlElement(name = "beanio", type = BeanioDataFormat.class),
@XmlElement(name = "bindy", type = BindyDataFormat.class),
@XmlElement(name = "cbor", type = CBORDataFormat.class),
@XmlElement(name = "crypto", type = CryptoDataFormat.class),
@XmlElement(name = "csv", type = CsvDataFormat.class),
@XmlElement(name = "custom", type = CustomDataFormat.class),
@XmlElement(name = "dfdl", type = DfdlDataFormat.class),
@XmlElement(name = "fhirJson", type = FhirJsonDataFormat.class),
@XmlElement(name = "fhirXml", type = FhirXmlDataFormat.class),
@XmlElement(name = "flatpack", type = FlatpackDataFormat.class),
@XmlElement(name = "fory", type = ForyDataFormat.class),
@XmlElement(name = "grok", type = GrokDataFormat.class),
@XmlElement(name = "groovyXml", type = GroovyXmlDataFormat.class),
@XmlElement(name = "gzipDeflater", type = GzipDeflaterDataFormat.class),
@XmlElement(name = "hl7", type = HL7DataFormat.class),
@XmlElement(name = "ical", type = IcalDataFormat.class),
@XmlElement(name = "iso8583", type = Iso8583DataFormat.class),
@XmlElement(name = "jacksonXml", type = JacksonXMLDataFormat.class),
@XmlElement(name = "jaxb", type = JaxbDataFormat.class),
@XmlElement(name = "json", type = JsonDataFormat.class),
@XmlElement(name = "jsonApi", type = JsonApiDataFormat.class),
@XmlElement(name = "lzf", type = LZFDataFormat.class),
@XmlElement(name = "mimeMultipart", type = MimeMultipartDataFormat.class),
@XmlElement(name = "parquetAvro", type = ParquetAvroDataFormat.class),
@XmlElement(name = "protobuf", type = ProtobufDataFormat.class),
@XmlElement(name = "rss", type = RssDataFormat.class),
@XmlElement(name = "smooks", type = SmooksDataFormat.class),
@XmlElement(name = "soap", type = SoapDataFormat.class),
@XmlElement(name = "swiftMt", type = SwiftMtDataFormat.class),
@XmlElement(name = "swiftMx", type = SwiftMxDataFormat.class),
@XmlElement(name = "syslog", type = SyslogDataFormat.class),
@XmlElement(name = "tarFile", type = TarFileDataFormat.class),
@XmlElement(name = "thrift", type = ThriftDataFormat.class),
@XmlElement(name = "univocityCsv", type = UniVocityCsvDataFormat.class),
@XmlElement(name = "univocityFixed", type = UniVocityFixedDataFormat.class),
@XmlElement(name = "univocityTsv", type = UniVocityTsvDataFormat.class),
@XmlElement(name = "xmlSecurity", type = XMLSecurityDataFormat.class),
@XmlElement(name = "pgp", type = PGPDataFormat.class),
@XmlElement(name = "yaml", type = YAMLDataFormat.class),
@XmlElement(name = "zipDeflater", type = ZipDeflaterDataFormat.class),
@XmlElement(name = "zipFile", type = ZipFileDataFormat.class) })
private DataFormatDefinition dataFormatType;
@XmlAttribute
private String variableSend;
@XmlAttribute
private String variableReceive;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String allowNullBody;
public UnmarshalDefinition() {
}
protected UnmarshalDefinition(UnmarshalDefinition source) {
super(source);
this.variableSend = source.variableSend;
this.variableReceive = source.variableReceive;
this.allowNullBody = source.allowNullBody;
this.dataFormatType = source.dataFormatType != null ? source.dataFormatType.copyDefinition() : null;
}
public UnmarshalDefinition(DataFormatDefinition dataFormatType) {
this.dataFormatType = dataFormatType;
}
@Override
public UnmarshalDefinition copyDefinition() {
return new UnmarshalDefinition(this);
}
@Override
public String toString() {
return "Unmarshal[" + description() + "]";
}
protected String description() {
if (dataFormatType != null) {
return dataFormatType.toString();
} else {
return "";
}
}
@Override
public String getShortName() {
return "unmarshal";
}
@Override
public String getLabel() {
return "unmarshal[" + description() + "]";
}
@Override
public DataFormatDefinition getDataFormatType() {
return dataFormatType;
}
/**
* The data format to be used
*/
@Override
public void setDataFormatType(DataFormatDefinition dataFormatType) {
this.dataFormatType = dataFormatType;
}
public String getVariableSend() {
return variableSend;
}
public void setVariableSend(String variableSend) {
this.variableSend = variableSend;
}
public String getVariableReceive() {
return variableReceive;
}
public void setVariableReceive(String variableReceive) {
this.variableReceive = variableReceive;
}
public String getAllowNullBody() {
return allowNullBody;
}
/**
* Indicates whether {@code null} is allowed as value of a body to unmarshall.
*/
public void setAllowNullBody(String allowNullBody) {
this.allowNullBody = allowNullBody;
}
// Fluent API
// -------------------------------------------------------------------------
/**
* To use a variable to store the received message body (only body, not headers). This makes it handy to use
* variables for user data and to easily control what data to use for sending and receiving.
*
* Important: When using receive variable then the received body is stored only in this variable and not on the
* current message.
*/
public UnmarshalDefinition variableReceive(String variableReceive) {
setVariableReceive(variableReceive);
return this;
}
/**
* To use a variable as the source for the message body to send. This makes it handy to use variables for user data
* and to easily control what data to use for sending and receiving.
*
* Important: When using send variable then the message body is taken from this variable instead of the current
* message, however the headers from the message will still be used as well. In other words, the variable is used
* instead of the message body, but everything else is as usual.
*/
public UnmarshalDefinition variableSend(String variableSend) {
setVariableSend(variableSend);
return this;
}
/**
* Indicates whether {@code null} is allowed as value of a body to unmarshall.
*
* @param allowNullBody {@code true} if {@code null} is allowed as value of a body to unmarshall, {@code false}
* otherwise
* @return the builder
*/
public UnmarshalDefinition allowNullBody(boolean allowNullBody) {
setAllowNullBody(Boolean.toString(allowNullBody));
return this;
}
}
| UnmarshalDefinition |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java | {
"start": 11780,
"end": 11885
} | interface ____ {
List<String> translate(List<String> messages);
}
abstract static | Translator |
java | apache__camel | components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/pojos/StringTool.java | {
"start": 973,
"end": 1272
} | class ____ {
@Tool("Converts text to uppercase")
public String toUpperCase(@P("Text to convert") String text) {
return text.toUpperCase();
}
@Tool("Gets the length of a string")
public int getLength(@P("Text") String text) {
return text.length();
}
}
| StringTool |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/cloud/ZooKeeperServiceCallServiceDiscoveryConfiguration.java | {
"start": 1333,
"end": 6078
} | class ____ extends ServiceCallServiceDiscoveryConfiguration {
@XmlAttribute(required = true)
private String nodes;
@XmlAttribute
private String namespace;
@XmlAttribute
private String reconnectBaseSleepTime;
@XmlAttribute
private String reconnectMaxSleepTime;
@XmlAttribute
private String reconnectMaxRetries;
@XmlAttribute
private String sessionTimeout;
@XmlAttribute
private String connectionTimeout;
@XmlAttribute(required = true)
private String basePath;
public ZooKeeperServiceCallServiceDiscoveryConfiguration() {
this(null);
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration(ServiceCallDefinition parent) {
super(parent, "zookeeper-service-discovery");
}
// *************************************************************************
// Getter/Setter
// *************************************************************************
public String getNodes() {
return nodes;
}
/**
* A comma separate list of servers to connect to in the form host:port
*/
public void setNodes(String nodes) {
this.nodes = nodes;
}
public String getNamespace() {
return namespace;
}
/**
* As ZooKeeper is a shared space, users of a given cluster should stay within a pre-defined namespace. If a
* namespace is set here, all paths will get pre-pended with the namespace
*/
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getReconnectBaseSleepTime() {
return reconnectBaseSleepTime;
}
/**
* Initial amount of time to wait between retries.
*/
public void setReconnectBaseSleepTime(String reconnectBaseSleepTime) {
this.reconnectBaseSleepTime = reconnectBaseSleepTime;
}
public String getReconnectMaxSleepTime() {
return reconnectMaxSleepTime;
}
/**
* Max time in ms to sleep on each retry
*/
public void setReconnectMaxSleepTime(String reconnectMaxSleepTime) {
this.reconnectMaxSleepTime = reconnectMaxSleepTime;
}
public String getReconnectMaxRetries() {
return reconnectMaxRetries;
}
/**
* Max number of times to retry
*/
public void setReconnectMaxRetries(String reconnectMaxRetries) {
this.reconnectMaxRetries = reconnectMaxRetries;
}
public String getSessionTimeout() {
return sessionTimeout;
}
/**
* Session timeout.
*/
public void setSessionTimeout(String sessionTimeout) {
this.sessionTimeout = sessionTimeout;
}
public String getConnectionTimeout() {
return connectionTimeout;
}
/**
* Connection timeout.
*/
public void setConnectionTimeout(String connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public String getBasePath() {
return basePath;
}
/**
* Set the base path to store in ZK
*/
public void setBasePath(String basePath) {
this.basePath = basePath;
}
// *************************************************************************
// Fluent API
// *************************************************************************
public ZooKeeperServiceCallServiceDiscoveryConfiguration nodes(String nodes) {
setNodes(nodes);
return this;
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration namespace(String namespace) {
setNamespace(namespace);
return this;
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration reconnectBaseSleepTime(String reconnectBaseSleepTime) {
setReconnectBaseSleepTime(reconnectBaseSleepTime);
return this;
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration reconnectMaxSleepTime(String reconnectMaxSleepTime) {
setReconnectMaxSleepTime(reconnectMaxSleepTime);
return this;
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration reconnectMaxRetries(int reconnectMaxRetries) {
setReconnectMaxRetries(Integer.toString(reconnectMaxRetries));
return this;
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration sessionTimeout(String sessionTimeout) {
setSessionTimeout(sessionTimeout);
return this;
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration connectionTimeout(String connectionTimeout) {
setConnectionTimeout(connectionTimeout);
return this;
}
public ZooKeeperServiceCallServiceDiscoveryConfiguration basePath(String basePath) {
setBasePath(basePath);
return this;
}
}
| ZooKeeperServiceCallServiceDiscoveryConfiguration |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MethodCanBeStaticTest.java | {
"start": 5439,
"end": 5872
} | class ____<T> {
// BUG: Diagnostic contains: private static <T> T f(
private <T> T f(int x, int y) {
return null;
}
}
""")
.doTest();
}
@Test
public void negativeSuppressedByKeep() {
testHelper
.addSourceLines(
"Test.java",
"""
import com.google.errorprone.annotations.Keep;
| Test |
java | apache__logging-log4j2 | log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/junit/LoggerContextResolver.java | {
"start": 6789,
"end": 8946
} | class ____ implements AutoCloseable, LoggerContextAccessor {
private final LoggerContext context;
private final ReconfigurationPolicy reconfigurationPolicy;
private final long shutdownTimeout;
private final TimeUnit unit;
private LoggerContextConfig(final LoggerContextSource source, final ExtensionContext extensionContext) {
final String displayName = extensionContext.getDisplayName();
final ClassLoader classLoader =
extensionContext.getRequiredTestClass().getClassLoader();
context = Configurator.initialize(displayName, classLoader, getConfigLocation(source, extensionContext));
reconfigurationPolicy = source.reconfigure();
shutdownTimeout = source.timeout();
unit = source.unit();
}
private static String getConfigLocation(
final LoggerContextSource source, final ExtensionContext extensionContext) {
final String value = source.value();
if (value.isEmpty()) {
Class<?> clazz = extensionContext.getRequiredTestClass();
while (clazz != null) {
final URL url = clazz.getResource(clazz.getSimpleName() + ".xml");
if (url != null) {
try {
return url.toURI().toString();
} catch (URISyntaxException e) {
throw new ExtensionContextException("An error occurred accessing the configuration.", e);
}
}
clazz = clazz.getSuperclass();
}
return extensionContext.getRequiredTestClass().getName().replaceAll("[.$]", "/") + ".xml";
}
return value;
}
@Override
public LoggerContext getLoggerContext() {
return context;
}
public void reconfigure() {
context.reconfigure();
}
@Override
public void close() {
context.stop(shutdownTimeout, unit);
}
}
}
| LoggerContextConfig |
java | spring-projects__spring-framework | spring-jms/src/test/java/org/springframework/jms/annotation/EnableJmsTests.java | {
"start": 11923,
"end": 12114
} | class ____ {
@JmsListener(destination = "myQueue")
public void handle(String msg) {
}
}
@JmsListener(destination = "orderQueue")
@Retention(RetentionPolicy.RUNTIME)
private @ | LazyBean |
java | apache__camel | catalog/camel-catalog/src/main/java/org/apache/camel/catalog/VersionHelper.java | {
"start": 950,
"end": 3029
} | class ____ {
private static volatile String version;
public synchronized String getVersion() {
if (version != null) {
return version;
}
// First, try to load from maven properties
InputStream is = null;
try {
Properties p = new Properties();
is = getClass().getResourceAsStream("/META-INF/maven/org.apache.camel/camel-catalog/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
// ignore
}
}
}
// Next, try to load from version.properties
if (version == null) {
try {
Properties p = new Properties();
is = getClass().getResourceAsStream("/META-INF/version.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
// ignore
}
}
}
}
// Fallback to using Java API
if (version == null) {
Package aPackage = getClass().getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return version;
}
}
| VersionHelper |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/config/dialect/DbVersionInvalidTest.java | {
"start": 496,
"end": 2606
} | class ____ {
private static final String ACTUAL_H2_VERSION = DialectVersions.Defaults.H2;
// We will set the DB version to something higher than the actual version: this is invalid.
private static final String CONFIGURED_DB_VERSION = "999.999";
static {
assertThat(ACTUAL_H2_VERSION)
.as("Test setup - we need the required version to be different from the actual one")
.doesNotStartWith(CONFIGURED_DB_VERSION);
}
private static final String CONFIGURED_DB_VERSION_REPORTED;
static {
// For some reason Hibernate ORM infers a micro version of 0; no big deal.
CONFIGURED_DB_VERSION_REPORTED = CONFIGURED_DB_VERSION + ".0";
}
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClass(MyEntity.class))
.withConfigurationResource("application.properties")
.overrideConfigKey("quarkus.datasource.db-version", "999.999")
.assertException(throwable -> assertThat(throwable)
.rootCause()
.hasMessageContainingAll(
"Persistence unit '<default>' was configured to run with a database version"
+ " of at least '" + CONFIGURED_DB_VERSION_REPORTED + "', but the actual version is '"
+ ACTUAL_H2_VERSION + "'",
"Consider upgrading your database",
"Alternatively, rebuild your application with 'quarkus.datasource.db-version="
+ ACTUAL_H2_VERSION + "'",
"this may disable some features and/or impact performance negatively",
"disable the check with 'quarkus.hibernate-orm.database.version-check.enabled=false'"));
@Inject
SessionFactory sessionFactory;
@Inject
Session session;
@Test
public void test() {
Assertions.fail("Bootstrap should have failed");
}
}
| DbVersionInvalidTest |
java | quarkusio__quarkus | extensions/mailer/deployment/src/test/java/io/quarkus/mailer/InjectionTest.java | {
"start": 3654,
"end": 4006
} | class ____ {
@Inject
io.quarkus.mailer.reactive.ReactiveMailer mailer;
CompletionStage<Void> verify() {
return mailer.send(Mail.withText("quarkus@quarkus.io", "test mailer", "reactive test!"))
.subscribeAsCompletionStage();
}
}
@ApplicationScoped
static | BeanUsingReactiveMailer |
java | apache__camel | components/camel-dapr/src/test/java/org/apache/camel/component/dapr/operations/DaprLockTest.java | {
"start": 2042,
"end": 7207
} | class ____ extends CamelTestSupport {
@Mock
private DaprPreviewClient client;
@Mock
private DaprEndpoint endpoint;
@Test
@SuppressWarnings("unchecked")
void testTryLock() throws Exception {
Boolean mockResult = Boolean.TRUE;
when(endpoint.getPreviewClient()).thenReturn(client);
when(client.tryLock(any(LockRequest.class))).thenReturn(Mono.just(mockResult));
DaprConfiguration configuration = new DaprConfiguration();
configuration.setOperation(DaprOperation.lock);
configuration.setStoreName("myStore");
configuration.setResourceId("myResouce");
configuration.setLockOwner("me");
configuration.setExpiryInSeconds(100);
DaprConfigurationOptionsProxy configurationOptionsProxy = new DaprConfigurationOptionsProxy(configuration);
final Exchange exchange = new DefaultExchange(context);
DaprLockHandler operation = new DaprLockHandler(configurationOptionsProxy, endpoint);
DaprOperationResponse response = operation.handle(exchange);
Boolean lockResult = (Boolean) response.getBody();
assertNotNull(response);
assertNotNull(lockResult);
assertEquals(mockResult, lockResult);
}
@Test
void testTryLockConfiguration() throws Exception {
DaprConfiguration configuration = new DaprConfiguration();
configuration.setOperation(DaprOperation.lock);
configuration.setLockOperation(LockOperation.tryLock);
DaprConfigurationOptionsProxy configurationOptionsProxy = new DaprConfigurationOptionsProxy(configuration);
final Exchange exchange = new DefaultExchange(context);
// case 1: storeName, resourceId, lockOwner and expiryInSeconds empty
final DaprLockHandler operation = new DaprLockHandler(configurationOptionsProxy, endpoint);
assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange));
// case 2: resourceId, lockOwner and expiryInSeconds empty
configuration.setStoreName("myStore");
assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange));
// case 3: lockOwner and expiryInSeconds empty
configuration.setResourceId("myResource");
assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange));
// case 4: expiryInSeconds empty
configuration.setLockOwner("me");
assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange));
// case 5: valid configuration
configuration.setExpiryInSeconds(100);
assertDoesNotThrow(() -> operation.validateConfiguration(exchange));
}
@Test
void testUnlock() throws Exception {
UnlockResponseStatus mockResult = UnlockResponseStatus.SUCCESS;
when(endpoint.getPreviewClient()).thenReturn(client);
when(client.unlock(any(UnlockRequest.class))).thenReturn(Mono.just(mockResult));
DaprConfiguration configuration = new DaprConfiguration();
configuration.setOperation(DaprOperation.lock);
configuration.setLockOperation(LockOperation.unlock);
configuration.setStoreName("myStore");
configuration.setResourceId("myResouce");
configuration.setLockOwner("me");
DaprConfigurationOptionsProxy configurationOptionsProxy = new DaprConfigurationOptionsProxy(configuration);
final Exchange exchange = new DefaultExchange(context);
DaprLockHandler operation = new DaprLockHandler(configurationOptionsProxy, endpoint);
DaprOperationResponse response = operation.handle(exchange);
UnlockResponseStatus unlockResponse = (UnlockResponseStatus) response.getBody();
assertNotNull(response);
assertNotNull(unlockResponse);
assertEquals(mockResult, unlockResponse);
}
@Test
void testUnlockConfiguration() throws Exception {
DaprConfiguration configuration = new DaprConfiguration();
configuration.setOperation(DaprOperation.lock);
configuration.setLockOperation(LockOperation.unlock);
DaprConfigurationOptionsProxy configurationOptionsProxy = new DaprConfigurationOptionsProxy(configuration);
final Exchange exchange = new DefaultExchange(context);
// case 1: storeName, resourceId and lockOwner empty
final DaprLockHandler operation = new DaprLockHandler(configurationOptionsProxy, endpoint);
assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange));
// case 2: resourceId and empty
configuration.setStoreName("myStore");
assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange));
// case 3: lockOwner empty
configuration.setResourceId("myResource");
assertThrows(IllegalArgumentException.class, () -> operation.validateConfiguration(exchange));
// case 4: valid configuration
configuration.setLockOwner("me");
assertDoesNotThrow(() -> operation.validateConfiguration(exchange));
}
}
| DaprLockTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/TreatedLeftJoinInheritanceTest.java | {
"start": 8381,
"end": 8544
} | class ____ {
@Id
@GeneratedValue
private Long id;
}
@SuppressWarnings("unused")
@Entity( name = "TablePerClassSubEntity" )
public static | TablePerClassEntity |
java | apache__camel | test-infra/camel-test-infra-cassandra/src/test/java/org/apache/camel/test/infra/cassandra/services/CassandraServiceFactory.java | {
"start": 1752,
"end": 1855
} | class ____ extends RemoteCassandraInfraService implements CassandraService {
}
}
| RemoteCassandraService |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/gaussdb/parser/GaussDbLexer.java | {
"start": 352,
"end": 1251
} | class ____ extends PGLexer {
static final Keywords GAUSSDB_KEYWORDS;
static {
Map<String, Token> map = new HashMap<>();
map.put("DISTRIBUTE", Token.DISTRIBUTE);
map.put("SET", Token.SET);
map.put("PARTITION", Token.PARTITION);
map.put("START", Token.START);
map.put("PARTIAL", Token.PARTIAL);
map.put("KEY", Token.KEY);
map.put("OVERWRITE", Token.OVERWRITE);
map.put("LOCAL", Token.LOCAL);
map.putAll(PGLexer.PG_KEYWORDS.getKeywords());
map.remove("LANGUAGE"); // GaussDB does not consider it as a reserved keyword
GAUSSDB_KEYWORDS = new Keywords(map);
}
@Override
protected Keywords loadKeywords() {
return GAUSSDB_KEYWORDS;
}
public GaussDbLexer(String input, SQLParserFeature... features) {
super(input);
dbType = DbType.gaussdb;
}
}
| GaussDbLexer |
java | quarkusio__quarkus | extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/LoggingBeanSupportProcessor.java | {
"start": 261,
"end": 624
} | class ____ {
@BuildStep
public void discoveredComponents(BuildProducer<BeanDefiningAnnotationBuildItem> beanDefiningAnnotationProducer) {
beanDefiningAnnotationProducer.produce(new BeanDefiningAnnotationBuildItem(
LoggingResourceProcessor.LOGGING_FILTER, BuiltinScope.SINGLETON.getName(), false));
}
}
| LoggingBeanSupportProcessor |
java | netty__netty | resolver-dns/src/main/java/io/netty/resolver/dns/SingletonDnsServerAddresses.java | {
"start": 711,
"end": 1608
} | class ____ extends DnsServerAddresses {
private final InetSocketAddress address;
private final DnsServerAddressStream stream = new DnsServerAddressStream() {
@Override
public InetSocketAddress next() {
return address;
}
@Override
public int size() {
return 1;
}
@Override
public DnsServerAddressStream duplicate() {
return this;
}
@Override
public String toString() {
return SingletonDnsServerAddresses.this.toString();
}
};
SingletonDnsServerAddresses(InetSocketAddress address) {
this.address = address;
}
@Override
public DnsServerAddressStream stream() {
return stream;
}
@Override
public String toString() {
return "singleton(" + address + ")";
}
}
| SingletonDnsServerAddresses |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerPreMoveWithProbeContentTypeTest.java | {
"start": 1065,
"end": 1921
} | class ____ extends ContextTestSupport {
@Test
public void testContentTypeWithPremoveAndProbeContentTypeOptions() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived(Exchange.FILE_CONTENT_TYPE, "txt");
template.sendBodyAndHeader(fileUri(), "Hello World", Exchange.FILE_NAME, "hello.txt");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from(fileUri("?probeContentType=true&preMove=work/work-${file:name}&initialDelay=0&delay=10"))
.to("mock:result");
}
};
}
}
| FileConsumerPreMoveWithProbeContentTypeTest |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ssl/JksSslBundleProperties.java | {
"start": 1337,
"end": 2347
} | class ____ {
/**
* Type of the store to create, e.g. JKS.
*/
private @Nullable String type;
/**
* Provider for the store.
*/
private @Nullable String provider;
/**
* Location of the resource containing the store content.
*/
private @Nullable String location;
/**
* Password used to access the store.
*/
private @Nullable String password;
public @Nullable String getType() {
return this.type;
}
public void setType(@Nullable String type) {
this.type = type;
}
public @Nullable String getProvider() {
return this.provider;
}
public void setProvider(@Nullable String provider) {
this.provider = provider;
}
public @Nullable String getLocation() {
return this.location;
}
public void setLocation(@Nullable String location) {
this.location = location;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
}
}
| Store |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java | {
"start": 38748,
"end": 39028
} | class ____ {
public void doTest() {
Client client = new Client();
client.before(false);
}
}
""")
.addOutputLines(
"out/Caller.java",
"""
public final | Caller |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentInjectionTest.java | {
"start": 7815,
"end": 8208
} | class ____ extends PreferenceActivity {}")
.doTest();
}
@Test
public void noIsValidFragmentOnAbstractSuperClassOrImplementation() {
compilationHelper
.addSourceLines(
"MyAbstractPrefActivity.java",
"import android.preference.PreferenceActivity;",
// Don't emit warning since it's abstract.
"abstract | MyAbstractPrefActivity |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/AdminStatesBaseTest.java | {
"start": 2440,
"end": 17630
} | class ____ {
public static final Logger LOG =
LoggerFactory.getLogger(AdminStatesBaseTest.class);
static final long seed = 0xDEADBEEFL;
static final int blockSize = 8192;
static final int fileSize = 16384;
static final int HEARTBEAT_INTERVAL = 1; // heartbeat interval in seconds
static final int BLOCKREPORT_INTERVAL_MSEC = 1000; //block report in msec
static final int NAMENODE_REPLICATION_INTERVAL = 1; //replication interval
final private Random myrand = new Random();
@SuppressWarnings("checkstyle:VisibilityModifier")
@TempDir
public java.nio.file.Path baseDir;
private HostsFileWriter hostsFileWriter;
private Configuration conf;
private MiniDFSCluster cluster = null;
private boolean useCombinedHostFileManager = false;
protected void setUseCombinedHostFileManager() {
useCombinedHostFileManager = true;
}
protected Configuration getConf() {
return conf;
}
protected MiniDFSCluster getCluster() {
return cluster;
}
@BeforeEach
public void setup() throws IOException {
// Set up the hosts/exclude files.
hostsFileWriter = new HostsFileWriter();
conf = new HdfsConfiguration();
if (useCombinedHostFileManager) {
conf.setClass(DFSConfigKeys.DFS_NAMENODE_HOSTS_PROVIDER_CLASSNAME_KEY,
CombinedHostFileManager.class, HostConfigManager.class);
}
// Setup conf
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_CONSIDERLOAD_KEY,
false);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY,
200);
conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, HEARTBEAT_INTERVAL);
conf.setInt(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY,
BLOCKREPORT_INTERVAL_MSEC);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY,
NAMENODE_REPLICATION_INTERVAL);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY, 1);
hostsFileWriter.initialize(conf, "temp/admin");
}
@AfterEach
public void teardown() throws IOException {
hostsFileWriter.cleanup();
shutdownCluster();
}
static public FSDataOutputStream writeIncompleteFile(FileSystem fileSys,
Path name, short repl, short numOfBlocks) throws IOException {
return writeFile(fileSys, name, repl, numOfBlocks, false);
}
static protected void writeFile(FileSystem fileSys, Path name, int repl)
throws IOException {
writeFile(fileSys, name, repl, 2);
}
static protected void writeFile(FileSystem fileSys, Path name, int repl,
int numOfBlocks) throws IOException {
writeFile(fileSys, name, repl, numOfBlocks, true);
}
static protected FSDataOutputStream writeFile(FileSystem fileSys, Path name,
int repl, int numOfBlocks, boolean completeFile)
throws IOException {
// create and write a file that contains two blocks of data
FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf()
.getInt(CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096),
(short) repl, blockSize);
byte[] buffer = new byte[blockSize*numOfBlocks];
Random rand = new Random(seed);
rand.nextBytes(buffer);
stm.write(buffer);
LOG.info("Created file " + name + " with " + repl + " replicas.");
if (completeFile) {
stm.close();
return null;
} else {
stm.flush();
// Do not close stream, return it
// so that it is not garbage collected
return stm;
}
}
/**
* Decommission or perform Maintenance for DataNodes and wait for them to
* reach the expected state.
*
* @param nnIndex NameNode index
* @param datanodeUuid DataNode to decommission/maintenance, or a random
* DataNode if null
* @param maintenanceExpirationInMS Maintenance expiration time
* @param decommissionedNodes List of DataNodes already decommissioned
* @param waitForState Await for this state for datanodeUuid DataNode
* @return DatanodeInfo DataNode taken out of service
* @throws IOException
*/
protected DatanodeInfo takeNodeOutofService(int nnIndex,
String datanodeUuid, long maintenanceExpirationInMS,
ArrayList<DatanodeInfo> decommissionedNodes,
AdminStates waitForState) throws IOException {
return takeNodeOutofService(nnIndex, datanodeUuid,
maintenanceExpirationInMS, decommissionedNodes, null, waitForState);
}
/**
* Decommission or perform Maintenance for DataNodes and wait for them to
* reach the expected state.
*
* @param nnIndex NameNode index
* @param datanodeUuid DataNode to decommission/maintenance, or a random
* DataNode if null
* @param maintenanceExpirationInMS Maintenance expiration time
* @param decommissionedNodes List of DataNodes already decommissioned
* @param inMaintenanceNodes Map of DataNodes already entering/in maintenance
* @param waitForState Await for this state for datanodeUuid DataNode
* @return DatanodeInfo DataNode taken out of service
* @throws IOException
*/
protected DatanodeInfo takeNodeOutofService(int nnIndex,
String datanodeUuid, long maintenanceExpirationInMS,
List<DatanodeInfo> decommissionedNodes,
Map<DatanodeInfo, Long> inMaintenanceNodes, AdminStates waitForState)
throws IOException {
return takeNodeOutofService(nnIndex, (datanodeUuid != null ?
Lists.newArrayList(datanodeUuid) : null),
maintenanceExpirationInMS, decommissionedNodes, inMaintenanceNodes,
waitForState).get(0);
}
/**
* Decommission or perform Maintenance for DataNodes and wait for them to
* reach the expected state.
*
* @param nnIndex NameNode index
* @param dataNodeUuids DataNodes to decommission/maintenance, or a random
* DataNode if null
* @param maintenanceExpirationInMS Maintenance expiration time
* @param decommissionedNodes List of DataNodes already decommissioned
* @param inMaintenanceNodes Map of DataNodes already entering/in maintenance
* @param waitForState Await for this state for datanodeUuid DataNode
* @return DatanodeInfo DataNode taken out of service
* @throws IOException
*/
protected List<DatanodeInfo> takeNodeOutofService(int nnIndex,
List<String> dataNodeUuids, long maintenanceExpirationInMS,
List<DatanodeInfo> decommissionedNodes,
Map<DatanodeInfo, Long> inMaintenanceNodes, AdminStates waitForState)
throws IOException {
DFSClient client = getDfsClient(nnIndex);
DatanodeInfo[] info = client.datanodeReport(DatanodeReportType.ALL);
boolean isDecommissionRequest =
waitForState == AdminStates.DECOMMISSION_INPROGRESS ||
waitForState == AdminStates.DECOMMISSIONED;
List<String> dataNodeNames = new ArrayList<>();
List<DatanodeInfo> datanodeInfos = new ArrayList<>();
// pick one DataNode randomly unless the caller specifies one.
if (dataNodeUuids == null) {
boolean found = false;
while (!found) {
int index = myrand.nextInt(info.length);
if ((isDecommissionRequest && !info[index].isDecommissioned()) ||
(!isDecommissionRequest && !info[index].isInMaintenance())) {
dataNodeNames.add(info[index].getXferAddr());
datanodeInfos.add(NameNodeAdapter.getDatanode(
cluster.getNamesystem(nnIndex), info[index]));
found = true;
}
}
} else {
// The caller specified a DataNode
for (String datanodeUuid : dataNodeUuids) {
boolean found = false;
for (int index = 0; index < info.length; index++) {
if (info[index].getDatanodeUuid().equals(datanodeUuid)) {
dataNodeNames.add(info[index].getXferAddr());
datanodeInfos.add(NameNodeAdapter.getDatanode(
cluster.getNamesystem(nnIndex), info[index]));
found = true;
break;
}
}
if (!found) {
throw new IOException("invalid datanodeUuid " + datanodeUuid);
}
}
}
LOG.info("Taking node: " + Arrays.toString(dataNodeNames.toArray())
+ " out of service");
ArrayList<String> decommissionNodes = new ArrayList<String>();
if (decommissionedNodes != null) {
for (DatanodeInfo dn : decommissionedNodes) {
decommissionNodes.add(dn.getName());
}
}
Map<String, Long> maintenanceNodes = new HashMap<>();
if (inMaintenanceNodes != null) {
for (Map.Entry<DatanodeInfo, Long> dn :
inMaintenanceNodes.entrySet()) {
maintenanceNodes.put(dn.getKey().getName(), dn.getValue());
}
}
if (isDecommissionRequest) {
for (String dataNodeName : dataNodeNames) {
decommissionNodes.add(dataNodeName);
}
} else {
for (String dataNodeName : dataNodeNames) {
maintenanceNodes.put(dataNodeName, maintenanceExpirationInMS);
}
}
// write node names into the json host file.
hostsFileWriter.initOutOfServiceHosts(decommissionNodes, maintenanceNodes);
refreshNodes(nnIndex);
waitNodeState(datanodeInfos, waitForState);
return datanodeInfos;
}
/* Ask a specific NN to put the datanode in service and wait for it
* to reach the NORMAL state.
*/
protected void putNodeInService(int nnIndex,
DatanodeInfo outOfServiceNode) throws IOException {
LOG.info("Putting node: " + outOfServiceNode + " in service");
ArrayList<String> decommissionNodes = new ArrayList<>();
Map<String, Long> maintenanceNodes = new HashMap<>();
DatanodeManager dm =
cluster.getNamesystem(nnIndex).getBlockManager().getDatanodeManager();
List<DatanodeDescriptor> nodes =
dm.getDatanodeListForReport(DatanodeReportType.ALL);
for (DatanodeDescriptor node : nodes) {
if (node.isMaintenance()) {
maintenanceNodes.put(node.getName(),
node.getMaintenanceExpireTimeInMS());
} else if (node.isDecommissionInProgress() || node.isDecommissioned()) {
decommissionNodes.add(node.getName());
}
}
decommissionNodes.remove(outOfServiceNode.getName());
maintenanceNodes.remove(outOfServiceNode.getName());
hostsFileWriter.initOutOfServiceHosts(decommissionNodes, maintenanceNodes);
refreshNodes(nnIndex);
waitNodeState(outOfServiceNode, AdminStates.NORMAL);
}
protected void putNodeInService(int nnIndex,
String datanodeUuid) throws IOException {
DatanodeInfo datanodeInfo =
getDatanodeDesriptor(cluster.getNamesystem(nnIndex), datanodeUuid);
putNodeInService(nnIndex, datanodeInfo);
}
/**
* Wait till DataNode is transitioned to the expected state.
*/
protected void waitNodeState(DatanodeInfo node, AdminStates state) {
waitNodeState(Lists.newArrayList(node), state);
}
/**
* Wait till all DataNodes are transitioned to the expected state.
*/
protected void waitNodeState(List<DatanodeInfo> nodes, AdminStates state) {
for (DatanodeInfo node : nodes) {
boolean done = (state == node.getAdminState());
while (!done) {
LOG.info("Waiting for node " + node + " to change state to "
+ state + " current state: " + node.getAdminState());
try {
Thread.sleep(HEARTBEAT_INTERVAL * 500);
} catch (InterruptedException e) {
// nothing
}
done = (state == node.getAdminState());
}
LOG.info("node " + node + " reached the state " + state);
}
}
protected void initIncludeHost(String hostNameAndPort) throws IOException {
hostsFileWriter.initIncludeHost(hostNameAndPort);
}
protected void initIncludeHosts(String[] hostNameAndPorts)
throws IOException {
hostsFileWriter.initIncludeHosts(hostNameAndPorts);
}
protected void initExcludeHost(String hostNameAndPort) throws IOException {
hostsFileWriter.initExcludeHost(hostNameAndPort);
}
protected void initExcludeHosts(List<String> hostNameAndPorts)
throws IOException {
hostsFileWriter.initExcludeHosts(hostNameAndPorts);
}
/* Get DFSClient to the namenode */
protected DFSClient getDfsClient(final int nnIndex) throws IOException {
return new DFSClient(cluster.getNameNode(nnIndex).getNameNodeAddress(),
conf);
}
/* Validate cluster has expected number of datanodes */
protected static void validateCluster(DFSClient client, int numDNs)
throws IOException {
DatanodeInfo[] info = client.datanodeReport(DatanodeReportType.LIVE);
assertEquals(numDNs, info.length, "Number of Datanodes ");
}
/** Start a MiniDFSCluster.
* @throws IOException */
protected void startCluster(int numNameNodes, int numDatanodes,
boolean setupHostsFile, long[] nodesCapacity,
boolean checkDataNodeHostConfig) throws IOException {
startCluster(numNameNodes, numDatanodes, setupHostsFile, nodesCapacity,
checkDataNodeHostConfig, true);
}
protected void startCluster(int numNameNodes, int numDatanodes,
boolean setupHostsFile, long[] nodesCapacity,
boolean checkDataNodeHostConfig, boolean federation) throws IOException {
MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf, baseDir.toFile())
.numDataNodes(numDatanodes);
if (federation) {
builder.nnTopology(
MiniDFSNNTopology.simpleFederatedTopology(numNameNodes));
}
if (setupHostsFile) {
builder.setupHostsFile(setupHostsFile);
}
if (nodesCapacity != null) {
builder.simulatedCapacities(nodesCapacity);
}
if (checkDataNodeHostConfig) {
builder.checkDataNodeHostConfig(checkDataNodeHostConfig);
}
cluster = builder.build();
cluster.waitActive();
for (int i = 0; i < numNameNodes; i++) {
DFSClient client = getDfsClient(i);
validateCluster(client, numDatanodes);
}
}
protected void startCluster(int numNameNodes, int numDatanodes)
throws IOException {
startCluster(numNameNodes, numDatanodes, false, null, false);
}
protected void startSimpleCluster(int numNameNodes, int numDatanodes)
throws IOException {
startCluster(numNameNodes, numDatanodes, false, null, false, false);
}
protected void startSimpleHACluster(int numDatanodes) throws IOException {
cluster = new MiniDFSCluster.Builder(conf, baseDir.toFile())
.nnTopology(MiniDFSNNTopology.simpleHATopology()).numDataNodes(
numDatanodes).build();
cluster.transitionToActive(0);
cluster.waitActive();
}
protected void shutdownCluster() {
if (cluster != null) {
cluster.shutdown(true);
}
}
protected void refreshNodes(final int nnIndex) throws IOException {
cluster.getNamesystem(nnIndex).getBlockManager().getDatanodeManager().
refreshNodes(conf);
}
static DatanodeDescriptor getDatanodeDesriptor(
final FSNamesystem ns, final String datanodeUuid) {
return ns.getBlockManager().getDatanodeManager().getDatanode(datanodeUuid);
}
static public void cleanupFile(FileSystem fileSys, Path name)
throws IOException {
assertTrue(fileSys.exists(name));
fileSys.delete(name, true);
assertFalse(fileSys.exists(name));
}
}
| AdminStatesBaseTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableRetryTest.java | {
"start": 1569,
"end": 4292
} | class ____ extends RxJavaTest {
@Test
public void iterativeBackoff() {
Subscriber<String> consumer = TestHelper.mockSubscriber();
Flowable<String> producer = Flowable.unsafeCreate(new Publisher<String>() {
private AtomicInteger count = new AtomicInteger(4);
long last = System.currentTimeMillis();
@Override
public void subscribe(Subscriber<? super String> t1) {
t1.onSubscribe(new BooleanSubscription());
System.out.println(count.get() + " @ " + String.valueOf(last - System.currentTimeMillis()));
last = System.currentTimeMillis();
if (count.getAndDecrement() == 0) {
t1.onNext("hello");
t1.onComplete();
} else {
t1.onError(new RuntimeException());
}
}
});
TestSubscriber<String> ts = new TestSubscriber<>(consumer);
producer.retryWhen(new Function<Flowable<? extends Throwable>, Flowable<Object>>() {
@Override
public Flowable<Object> apply(Flowable<? extends Throwable> attempts) {
// Worker w = Schedulers.computation().createWorker();
return attempts
.map(new Function<Throwable, Tuple>() {
@Override
public Tuple apply(Throwable n) {
return new Tuple(1L, n);
}})
.scan(new BiFunction<Tuple, Tuple, Tuple>() {
@Override
public Tuple apply(Tuple t, Tuple n) {
return new Tuple(t.count + n.count, n.n);
}})
.flatMap(new Function<Tuple, Flowable<Object>>() {
@Override
public Flowable<Object> apply(Tuple t) {
System.out.println("Retry # " + t.count);
return t.count > 20 ?
Flowable.<Object>error(t.n) :
Flowable.timer(t.count * 1L, TimeUnit.MILLISECONDS)
.cast(Object.class);
}});
}
}).subscribe(ts);
ts.awaitDone(5, TimeUnit.SECONDS);
ts.assertNoErrors();
InOrder inOrder = inOrder(consumer);
inOrder.verify(consumer, never()).onError(any(Throwable.class));
inOrder.verify(consumer, times(1)).onNext("hello");
inOrder.verify(consumer, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
public static | FlowableRetryTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/spatial/SpatialNoLicenseTestCase.java | {
"start": 2099,
"end": 2494
} | class ____ extends EsqlPlugin {
protected XPackLicenseState getLicenseState() {
return SpatialNoLicenseTestCase.getLicenseState();
}
}
/**
* Test plugin that provides a license state that does not allow spatial features.
* This is used to test the behavior of spatial functions when no valid license is present.
*/
public static | TestEsqlPlugin |
java | netty__netty | codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java | {
"start": 2799,
"end": 15097
} | class ____ implements FileRegion {
@Override
public long position() {
return 0;
}
@Override
public long transfered() {
return 0;
}
@Override
public long transferred() {
return 0;
}
@Override
public long count() {
return INTEGER_OVERFLOW;
}
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public FileRegion touch(Object hint) {
return this;
}
@Override
public FileRegion touch() {
return this;
}
@Override
public FileRegion retain() {
return this;
}
@Override
public FileRegion retain(int increment) {
return this;
}
@Override
public int refCnt() {
return 1;
}
@Override
public boolean release() {
return false;
}
@Override
public boolean release(int decrement) {
return false;
}
}
@Test
public void testEmptyBufferBypass() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
// Test writing an empty buffer works when the encoder is at ST_INIT.
channel.writeOutbound(Unpooled.EMPTY_BUFFER);
ByteBuf buffer = channel.readOutbound();
assertSame(Unpooled.EMPTY_BUFFER, buffer);
// Leave the ST_INIT state.
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
assertTrue(channel.writeOutbound(response));
buffer = channel.readOutbound();
assertEquals("HTTP/1.1 200 OK\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII));
buffer.release();
// Test writing an empty buffer works when the encoder is not at ST_INIT.
channel.writeOutbound(Unpooled.EMPTY_BUFFER);
buffer = channel.readOutbound();
assertSame(Unpooled.EMPTY_BUFFER, buffer);
assertFalse(channel.finish());
}
@Test
public void testEmptyContentChunked() throws Exception {
testEmptyContent(true);
}
@Test
public void testEmptyContentNotChunked() throws Exception {
testEmptyContent(false);
}
private static void testEmptyContent(boolean chunked) throws Exception {
String content = "netty rocks";
ByteBuf contentBuffer = Unpooled.copiedBuffer(content, CharsetUtil.US_ASCII);
int length = contentBuffer.readableBytes();
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
if (!chunked) {
HttpUtil.setContentLength(response, length);
}
assertTrue(channel.writeOutbound(response));
assertTrue(channel.writeOutbound(new DefaultHttpContent(Unpooled.EMPTY_BUFFER)));
assertTrue(channel.writeOutbound(new DefaultLastHttpContent(contentBuffer)));
ByteBuf buffer = channel.readOutbound();
if (!chunked) {
assertEquals("HTTP/1.1 200 OK\r\ncontent-length: " + length + "\r\n\r\n",
buffer.toString(CharsetUtil.US_ASCII));
} else {
assertEquals("HTTP/1.1 200 OK\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII));
}
buffer.release();
// Test writing an empty buffer works when the encoder is not at ST_INIT.
buffer = channel.readOutbound();
assertEquals(0, buffer.readableBytes());
buffer.release();
buffer = channel.readOutbound();
assertEquals(length, buffer.readableBytes());
buffer.release();
assertFalse(channel.finish());
}
@Test
public void testStatusNoContent() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
assertEmptyResponse(channel, HttpResponseStatus.NO_CONTENT, null, false);
assertFalse(channel.finish());
}
@Test
public void testStatusNoContentContentLength() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
assertEmptyResponse(channel, HttpResponseStatus.NO_CONTENT, HttpHeaderNames.CONTENT_LENGTH, true);
assertFalse(channel.finish());
}
@Test
public void testStatusNoContentTransferEncoding() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
assertEmptyResponse(channel, HttpResponseStatus.NO_CONTENT, HttpHeaderNames.TRANSFER_ENCODING, true);
assertFalse(channel.finish());
}
@Test
public void testStatusNotModified() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
assertEmptyResponse(channel, HttpResponseStatus.NOT_MODIFIED, null, false);
assertFalse(channel.finish());
}
@Test
public void testStatusNotModifiedContentLength() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
assertEmptyResponse(channel, HttpResponseStatus.NOT_MODIFIED, HttpHeaderNames.CONTENT_LENGTH, false);
assertFalse(channel.finish());
}
@Test
public void testStatusNotModifiedTransferEncoding() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
assertEmptyResponse(channel, HttpResponseStatus.NOT_MODIFIED, HttpHeaderNames.TRANSFER_ENCODING, false);
assertFalse(channel.finish());
}
@Test
public void testStatusInformational() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
for (int code = 100; code < 200; code++) {
HttpResponseStatus status = HttpResponseStatus.valueOf(code);
assertEmptyResponse(channel, status, null, false);
}
assertFalse(channel.finish());
}
@Test
public void testStatusInformationalContentLength() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
for (int code = 100; code < 200; code++) {
HttpResponseStatus status = HttpResponseStatus.valueOf(code);
assertEmptyResponse(channel, status, HttpHeaderNames.CONTENT_LENGTH, code != 101);
}
assertFalse(channel.finish());
}
@Test
public void testStatusInformationalTransferEncoding() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
for (int code = 100; code < 200; code++) {
HttpResponseStatus status = HttpResponseStatus.valueOf(code);
assertEmptyResponse(channel, status, HttpHeaderNames.TRANSFER_ENCODING, code != 101);
}
assertFalse(channel.finish());
}
private static void assertEmptyResponse(EmbeddedChannel channel, HttpResponseStatus status,
CharSequence headerName, boolean headerStripped) {
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
if (HttpHeaderNames.CONTENT_LENGTH.contentEquals(headerName)) {
response.headers().set(headerName, "0");
} else if (HttpHeaderNames.TRANSFER_ENCODING.contentEquals(headerName)) {
response.headers().set(headerName, HttpHeaderValues.CHUNKED);
}
assertTrue(channel.writeOutbound(response));
assertTrue(channel.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT));
ByteBuf buffer = channel.readOutbound();
StringBuilder responseText = new StringBuilder();
responseText.append(HttpVersion.HTTP_1_1).append(' ').append(status.toString()).append("\r\n");
if (!headerStripped && headerName != null) {
responseText.append(headerName).append(": ");
if (HttpHeaderNames.CONTENT_LENGTH.contentEquals(headerName)) {
responseText.append('0');
} else {
responseText.append(HttpHeaderValues.CHUNKED);
}
responseText.append("\r\n");
}
responseText.append("\r\n");
assertEquals(responseText.toString(), buffer.toString(CharsetUtil.US_ASCII));
buffer.release();
buffer = channel.readOutbound();
buffer.release();
}
@Test
public void testEmptyContentsChunked() throws Exception {
testEmptyContents(true, false);
}
@Test
public void testEmptyContentsChunkedWithTrailers() throws Exception {
testEmptyContents(true, true);
}
@Test
public void testEmptyContentsNotChunked() throws Exception {
testEmptyContents(false, false);
}
@Test
public void testEmptyContentNotsChunkedWithTrailers() throws Exception {
testEmptyContents(false, true);
}
private void testEmptyContents(boolean chunked, boolean trailers) throws Exception {
HttpResponseEncoder encoder = new HttpResponseEncoder();
EmbeddedChannel channel = new EmbeddedChannel(encoder);
HttpResponse request = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
if (chunked) {
HttpUtil.setTransferEncodingChunked(request, true);
}
assertTrue(channel.writeOutbound(request));
ByteBuf contentBuffer = Unpooled.buffer();
assertTrue(channel.writeOutbound(new DefaultHttpContent(contentBuffer)));
ByteBuf lastContentBuffer = Unpooled.buffer();
LastHttpContent last = new DefaultLastHttpContent(lastContentBuffer);
if (trailers) {
last.trailingHeaders().set("X-Netty-Test", "true");
}
assertTrue(channel.writeOutbound(last));
// Ensure we only produce ByteBuf instances.
ByteBuf head = channel.readOutbound();
assertTrue(head.release());
ByteBuf content = channel.readOutbound();
content.release();
ByteBuf lastContent = channel.readOutbound();
lastContent.release();
assertFalse(channel.finish());
}
@Test
public void testStatusResetContentTransferContentLength() {
testStatusResetContentTransferContentLength0(HttpHeaderNames.CONTENT_LENGTH, Unpooled.buffer().writeLong(8));
}
@Test
public void testStatusResetContentTransferEncoding() {
testStatusResetContentTransferContentLength0(HttpHeaderNames.TRANSFER_ENCODING, Unpooled.buffer().writeLong(8));
}
private static void testStatusResetContentTransferContentLength0(CharSequence headerName, ByteBuf content) {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.RESET_CONTENT);
if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(headerName)) {
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
} else {
response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
}
assertTrue(channel.writeOutbound(response));
assertTrue(channel.writeOutbound(new DefaultHttpContent(content)));
assertTrue(channel.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT));
StringBuilder responseText = new StringBuilder();
responseText.append(HttpVersion.HTTP_1_1).append(' ')
.append(HttpResponseStatus.RESET_CONTENT).append("\r\n");
responseText.append(HttpHeaderNames.CONTENT_LENGTH).append(": 0\r\n");
responseText.append("\r\n");
StringBuilder written = new StringBuilder();
for (;;) {
ByteBuf buffer = channel.readOutbound();
if (buffer == null) {
break;
}
written.append(buffer.toString(CharsetUtil.US_ASCII));
buffer.release();
}
assertEquals(responseText.toString(), written.toString());
assertFalse(channel.finish());
}
}
| DummyLongFileRegion |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/batch/RefreshAndBatchTest.java | {
"start": 644,
"end": 1707
} | class ____ {
private static final Long ENTITY1_ID = 1l;
private static final Long ENTITY2_ID = 2l;
@BeforeAll
public void setUp(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
TestEntity entity1 = new TestEntity( ENTITY1_ID, "Entity 1" );
entityManager.persist( entity1 );
TestEntity entity2 = new TestEntity( ENTITY2_ID, "Entity 2" );
entityManager.persist( entity2 );
}
);
}
@Test
public void testRefresh(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
TestEntity entity1 = entityManager.find( TestEntity.class, ENTITY1_ID );
TestEntity entity2 = entityManager.getReference( TestEntity.class, ENTITY2_ID );
assertEquals( ENTITY1_ID, entity1.getId() );
assertEquals( ENTITY2_ID, entity2.getId() );
entityManager.refresh( entity1 );
assertEquals( ENTITY1_ID, entity1.getId() );
assertEquals( ENTITY2_ID, entity2.getId() );
}
);
}
@Entity(name = "TestEntity")
@BatchSize(size = 100)
public static | RefreshAndBatchTest |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryTests.java | {
"start": 42188,
"end": 42436
} | class ____ {
@Test
void nested() {
assertNotNull(tempDir);
assertTrue(tempDir.exists());
assertSame(initialTempDir, tempDir);
}
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
@DisplayName("class")
static | NestedTestClass |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/FetchGraphTest.java | {
"start": 4799,
"end": 5061
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
@ManyToOne
LedgerRecord ledgerRecord;
@ManyToOne
FinanceEntity financeEntity;
}
@Entity(name = "BudgetRecord")
@Table(name = "BudgetRecord")
static | LedgerRecordItem |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-jackson/runtime/src/main/java/io/quarkus/resteasy/reactive/jackson/runtime/serialisers/FullyFeaturedServerJacksonMessageBodyReader.java | {
"start": 10310,
"end": 11425
} | class ____ implements Function<String, ObjectReader> {
private final Class<? extends BiFunction<ObjectMapper, Type, ObjectReader>> clazz;
private final Type genericType;
private final ObjectMapper originalMapper;
public MethodObjectReaderFunction(Class<? extends BiFunction<ObjectMapper, Type, ObjectReader>> clazz, Type genericType,
ObjectMapper originalMapper) {
this.clazz = clazz;
this.genericType = genericType;
this.originalMapper = originalMapper;
}
@Override
public ObjectReader apply(String methodId) {
try {
BiFunction<ObjectMapper, Type, ObjectReader> biFunctionInstance = clazz.getDeclaredConstructor().newInstance();
ObjectReader objectReader = biFunctionInstance.apply(originalMapper, genericType);
setNecessaryJsonFactoryConfig(objectReader.getFactory());
return objectReader;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| MethodObjectReaderFunction |
java | apache__kafka | connect/transforms/src/main/java/org/apache/kafka/connect/transforms/HeaderFrom.java | {
"start": 1997,
"end": 4534
} | class ____<R extends ConnectRecord<R>> implements Transformation<R>, Versioned {
public static final String FIELDS_FIELD = "fields";
public static final String HEADERS_FIELD = "headers";
public static final String OPERATION_FIELD = "operation";
private static final String MOVE_OPERATION = "move";
private static final String COPY_OPERATION = "copy";
public static final String REPLACE_NULL_WITH_DEFAULT_FIELD = "replace.null.with.default";
public static final String OVERVIEW_DOC =
"Moves or copies fields in the key/value of a record into that record's headers. " +
"Corresponding elements of <code>" + FIELDS_FIELD + "</code> and " +
"<code>" + HEADERS_FIELD + "</code> together identify a field and the header it should be " +
"moved or copied to. " +
"Use the concrete transformation type designed for the record " +
"key (<code>" + Key.class.getName() + "</code>) or value (<code>" + Value.class.getName() + "</code>).";
public static final ConfigDef CONFIG_DEF = new ConfigDef()
.define(FIELDS_FIELD, ConfigDef.Type.LIST,
NO_DEFAULT_VALUE, new NonEmptyListValidator(),
ConfigDef.Importance.HIGH,
"Field names in the record whose values are to be copied or moved to headers.")
.define(HEADERS_FIELD, ConfigDef.Type.LIST,
NO_DEFAULT_VALUE, new NonEmptyListValidator(),
ConfigDef.Importance.HIGH,
"Header names, in the same order as the field names listed in the fields configuration property.")
.define(OPERATION_FIELD, ConfigDef.Type.STRING, NO_DEFAULT_VALUE,
ConfigDef.ValidString.in(MOVE_OPERATION, COPY_OPERATION), ConfigDef.Importance.HIGH,
"Either <code>move</code> if the fields are to be moved to the headers (removed from the key/value), " +
"or <code>copy</code> if the fields are to be copied to the headers (retained in the key/value).")
.define(REPLACE_NULL_WITH_DEFAULT_FIELD, ConfigDef.Type.BOOLEAN, true, ConfigDef.Importance.MEDIUM,
"Whether to replace fields that have a default value and that are null to the default value. When set to true, the default value is used, otherwise null is used.");
private final Cache<Schema, Schema> moveSchemaCache = new SynchronizedCache<>(new LRUCache<>(16));
| HeaderFrom |
java | quarkusio__quarkus | integration-tests/jpa-mysql/src/test/java/io/quarkus/it/jpa/mysql/XaConnectionInGraalITCase.java | {
"start": 119,
"end": 181
} | class ____ extends XaConnectionTest {
}
| XaConnectionInGraalITCase |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/tofix/ReaderForUpdating5281Test.java | {
"start": 653,
"end": 1466
} | class ____ {
// Works when annotated with...
// @JsonMerge
Collection<String> values;
public ArrayListHolder(String... values) {
this.values = new ArrayList<>();
this.values.addAll(Arrays.asList(values));
}
public void setValues(Collection<String> values) {
this.values = values;
}
}
@JacksonTestFailureExpected
@Test
public void readsIntoCreator() throws Exception {
ObjectMapper mapper = JsonMapper.builder().build();
ArrayListHolder holder = mapper.readerForUpdating(new ArrayListHolder("A"))
.readValue("{ \"values\" : [ \"A\", \"B\" ]}");
assertThat(holder.values).hasSize(3)
.containsAll(Arrays.asList("A", "A", "B"));
}
}
| ArrayListHolder |
java | junit-team__junit5 | junit-platform-commons/src/main/java/org/junit/platform/commons/util/AnnotationUtils.java | {
"start": 2037,
"end": 6235
} | class ____ {
private AnnotationUtils() {
/* no-op */
}
private static final ConcurrentHashMap<Class<? extends Annotation>, Boolean> repeatableAnnotationContainerCache = //
new ConcurrentHashMap<>(16);
/**
* Determine if an annotation of {@code annotationType} is either
* <em>present</em> or <em>meta-present</em> on the supplied optional
* {@code element}.
*
* @see #findAnnotation(Optional, Class)
* @see org.junit.platform.commons.support.AnnotationSupport#isAnnotated(Optional, Class)
*/
@SuppressWarnings("NullableOptional")
@Contract("null, _ -> false")
public static boolean isAnnotated(@Nullable Optional<? extends AnnotatedElement> element,
Class<? extends Annotation> annotationType) {
return findAnnotation(element, annotationType).isPresent();
}
/**
* @since 1.8
* @see #findAnnotation(Parameter, int, Class)
*/
public static boolean isAnnotated(Parameter parameter, int index, Class<? extends Annotation> annotationType) {
return findAnnotation(parameter, index, annotationType).isPresent();
}
/**
* Determine if an annotation of {@code annotationType} is either
* <em>present</em> or <em>meta-present</em> on the supplied
* {@code element}.
*
* @param element the element on which to search for the annotation; may be
* {@code null}
* @param annotationType the annotation type to search for; never {@code null}
* @return {@code true} if the annotation is present or meta-present
* @see #findAnnotation(AnnotatedElement, Class)
* @see org.junit.platform.commons.support.AnnotationSupport#isAnnotated(AnnotatedElement, Class)
*/
@Contract("null, _ -> false")
public static boolean isAnnotated(@Nullable AnnotatedElement element, Class<? extends Annotation> annotationType) {
return findAnnotation(element, annotationType).isPresent();
}
/**
* @see org.junit.platform.commons.support.AnnotationSupport#findAnnotation(Optional, Class)
*/
@SuppressWarnings({ "OptionalAssignedToNull", "NullableOptional" })
public static <A extends Annotation> Optional<A> findAnnotation(
@Nullable Optional<? extends AnnotatedElement> element, Class<A> annotationType) {
if (element == null || element.isEmpty()) {
return Optional.empty();
}
return findAnnotation(element.get(), annotationType);
}
/**
* @since 1.8
* @see #findAnnotation(AnnotatedElement, Class)
*/
public static <A extends Annotation> Optional<A> findAnnotation(Parameter parameter, int index,
Class<A> annotationType) {
return findAnnotation(getEffectiveAnnotatedParameter(parameter, index), annotationType);
}
/**
* @see org.junit.platform.commons.support.AnnotationSupport#findAnnotation(AnnotatedElement, Class)
*/
public static <A extends Annotation> Optional<A> findAnnotation(@Nullable AnnotatedElement element,
Class<A> annotationType) {
Preconditions.notNull(annotationType, "annotationType must not be null");
boolean inherited = annotationType.isAnnotationPresent(Inherited.class);
return findAnnotation(element, annotationType, inherited, new HashSet<>());
}
private static <A extends Annotation> Optional<A> findAnnotation(@Nullable AnnotatedElement element,
Class<A> annotationType, boolean inherited, Set<Annotation> visited) {
Preconditions.notNull(annotationType, "annotationType must not be null");
if (element == null) {
return Optional.empty();
}
// Directly present?
A annotation = element.getDeclaredAnnotation(annotationType);
if (annotation != null) {
return Optional.of(annotation);
}
// Meta-present on directly present annotations?
Optional<A> directMetaAnnotation = findMetaAnnotation(annotationType, element.getDeclaredAnnotations(),
inherited, visited);
if (directMetaAnnotation.isPresent()) {
return directMetaAnnotation;
}
if (element instanceof Class<?> clazz) {
// Search on interfaces
for (Class<?> ifc : clazz.getInterfaces()) {
if (ifc != Annotation.class) {
Optional<A> annotationOnInterface = findAnnotation(ifc, annotationType, inherited, visited);
if (annotationOnInterface.isPresent()) {
return annotationOnInterface;
}
}
}
// Indirectly present?
// Search in | AnnotationUtils |
java | apache__camel | components/camel-ai/camel-kserve/src/test/java/org/apache/camel/component/kserve/it/KServeITSupport.java | {
"start": 1198,
"end": 1713
} | class ____ extends CamelTestSupport {
@RegisterExtension
static TritonService service = TritonServiceFactory.createService();
@Override
protected CamelContext createCamelContext() throws Exception {
var context = super.createCamelContext();
var component = context.getComponent("kserve", KServeComponent.class);
var configuration = component.getConfiguration();
configuration.setTarget("localhost:" + service.grpcPort());
return context;
}
}
| KServeITSupport |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/bytearray/ByteArrayAssert_isNullOrEmpty_Test.java | {
"start": 935,
"end": 1387
} | class ____ extends ByteArrayAssertBaseTest {
@Override
protected ByteArrayAssert invoke_api_method() {
assertions.isNullOrEmpty();
return null;
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertNullOrEmpty(getInfo(assertions), getActual(assertions));
}
@Override
@Test
public void should_return_this() {
// Disable this test since isNullOrEmpty is void
}
}
| ByteArrayAssert_isNullOrEmpty_Test |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsCpuResourceHandlerImpl.java | {
"start": 2265,
"end": 14384
} | class ____ {
private CGroupsHandler mockCGroupsHandler;
private CGroupsCpuResourceHandlerImpl cGroupsCpuResourceHandler;
private ResourceCalculatorPlugin plugin;
final int numProcessors = 4;
@BeforeEach
public void setup() {
mockCGroupsHandler = mock(CGroupsHandler.class);
when(mockCGroupsHandler.getPathForCGroup(any(), any())).thenReturn(".");
cGroupsCpuResourceHandler =
new CGroupsCpuResourceHandlerImpl(mockCGroupsHandler);
plugin = mock(ResourceCalculatorPlugin.class);
Mockito.doReturn(numProcessors).when(plugin).getNumProcessors();
Mockito.doReturn(numProcessors).when(plugin).getNumCores();
}
@Test
public void testBootstrap() throws Exception {
Configuration conf = new YarnConfiguration();
List<PrivilegedOperation> ret =
cGroupsCpuResourceHandler.bootstrap(plugin, conf);
verify(mockCGroupsHandler, times(1))
.initializeCGroupController(CGroupsHandler.CGroupController.CPU);
verify(mockCGroupsHandler, times(0))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_PERIOD_US, "");
verify(mockCGroupsHandler, times(0))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_QUOTA_US, "");
assertNull(ret);
}
@Test
public void testBootstrapLimits() throws Exception {
Configuration conf = new YarnConfiguration();
int cpuPerc = 80;
conf.setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT,
cpuPerc);
int period = (CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US * 100) / (cpuPerc
* numProcessors);
List<PrivilegedOperation> ret =
cGroupsCpuResourceHandler.bootstrap(plugin, conf);
verify(mockCGroupsHandler, times(1))
.initializeCGroupController(CGroupsHandler.CGroupController.CPU);
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_PERIOD_US, String.valueOf(period));
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_QUOTA_US,
String.valueOf(CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US));
assertNull(ret);
}
@Test
public void testBootstrapExistingLimits() throws Exception {
File existingLimit = new File(CGroupsHandler.CGroupController.CPU.getName()
+ "." + CGroupsHandler.CGROUP_CPU_QUOTA_US);
try {
FileUtils.write(existingLimit, "10000"); // value doesn't matter
when(mockCGroupsHandler
.getPathForCGroup(CGroupsHandler.CGroupController.CPU, ""))
.thenReturn(".");
Configuration conf = new YarnConfiguration();
List<PrivilegedOperation> ret =
cGroupsCpuResourceHandler.bootstrap(plugin, conf);
verify(mockCGroupsHandler, times(1))
.initializeCGroupController(CGroupsHandler.CGroupController.CPU);
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_QUOTA_US, "-1");
assertNull(ret);
} finally {
FileUtils.deleteQuietly(existingLimit);
}
}
@Test
public void testPreStart() throws Exception {
String id = "container_01_01";
String path = "test-path/" + id;
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
Container mockContainer = mock(Container.class);
when(mockContainer.getContainerId()).thenReturn(mockContainerId);
when(mockCGroupsHandler
.getPathForCGroupTasks(CGroupsHandler.CGroupController.CPU, id))
.thenReturn(path);
when(mockContainer.getResource()).thenReturn(Resource.newInstance(1024, 2));
List<PrivilegedOperation> ret =
cGroupsCpuResourceHandler.preStart(mockContainer);
verify(mockCGroupsHandler, times(1))
.createCGroup(CGroupsHandler.CGroupController.CPU, id);
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_SHARES, String
.valueOf(CGroupsCpuResourceHandlerImpl.CPU_DEFAULT_WEIGHT * 2));
// don't set quota or period
verify(mockCGroupsHandler, never())
.updateCGroupParam(eq(CGroupsHandler.CGroupController.CPU), eq(id),
eq(CGroupsHandler.CGROUP_CPU_PERIOD_US), anyString());
verify(mockCGroupsHandler, never())
.updateCGroupParam(eq(CGroupsHandler.CGroupController.CPU), eq(id),
eq(CGroupsHandler.CGROUP_CPU_QUOTA_US), anyString());
assertNotNull(ret);
assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List<String> args = op.getArguments();
assertEquals(1, args.size());
assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@Test
public void testPreStartStrictUsage() throws Exception {
String id = "container_01_01";
String path = "test-path/" + id;
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
Container mockContainer = mock(Container.class);
when(mockContainer.getContainerId()).thenReturn(mockContainerId);
when(mockCGroupsHandler
.getPathForCGroupTasks(CGroupsHandler.CGroupController.CPU, id))
.thenReturn(path);
when(mockContainer.getResource()).thenReturn(Resource.newInstance(1024, 1));
Configuration conf = new YarnConfiguration();
conf.setBoolean(
YarnConfiguration.NM_LINUX_CONTAINER_CGROUPS_STRICT_RESOURCE_USAGE,
true);
cGroupsCpuResourceHandler.bootstrap(plugin, conf);
int defaultVCores = 8;
float share = (float) numProcessors / (float) defaultVCores;
List<PrivilegedOperation> ret =
cGroupsCpuResourceHandler.preStart(mockContainer);
verify(mockCGroupsHandler, times(1))
.createCGroup(CGroupsHandler.CGroupController.CPU, id);
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_SHARES,
String.valueOf(CGroupsCpuResourceHandlerImpl.CPU_DEFAULT_WEIGHT));
// set quota and period
InOrder cpuLimitOrder = inOrder(mockCGroupsHandler);
cpuLimitOrder.verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_PERIOD_US,
String.valueOf(CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US));
cpuLimitOrder.verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_QUOTA_US, String.valueOf(
(int) (CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US * share)));
assertNotNull(ret);
assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List<String> args = op.getArguments();
assertEquals(1, args.size());
assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@Test
public void testPreStartRestrictedContainers() throws Exception {
String id = "container_01_01";
String path = "test-path/" + id;
int defaultVCores = 8;
Configuration conf = new YarnConfiguration();
conf.setBoolean(
YarnConfiguration.NM_LINUX_CONTAINER_CGROUPS_STRICT_RESOURCE_USAGE,
true);
int cpuPerc = 75;
conf.setInt(YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT,
cpuPerc);
cGroupsCpuResourceHandler.bootstrap(plugin, conf);
InOrder cpuLimitOrder = inOrder(mockCGroupsHandler);
cpuLimitOrder.verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_PERIOD_US, String.valueOf("333333"));
cpuLimitOrder.verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_QUOTA_US,
String.valueOf(CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US));
float yarnCores = (cpuPerc * numProcessors) / 100;
int[] containerVCores = { 2, 4 };
for (int cVcores : containerVCores) {
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
Container mockContainer = mock(Container.class);
when(mockContainer.getContainerId()).thenReturn(mockContainerId);
when(mockCGroupsHandler
.getPathForCGroupTasks(CGroupsHandler.CGroupController.CPU, id))
.thenReturn(path);
when(mockContainer.getResource())
.thenReturn(Resource.newInstance(1024, cVcores));
when(mockCGroupsHandler
.getPathForCGroupTasks(CGroupsHandler.CGroupController.CPU, id))
.thenReturn(path);
float share = (cVcores * yarnCores) / defaultVCores;
int quotaUS;
int periodUS;
if (share > 1.0f) {
quotaUS = CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US;
periodUS =
(int) ((float) CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US / share);
} else {
quotaUS = (int) (CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US * share);
periodUS = CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US;
}
cGroupsCpuResourceHandler.preStart(mockContainer);
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_SHARES, String.valueOf(
CGroupsCpuResourceHandlerImpl.CPU_DEFAULT_WEIGHT * cVcores));
// set quota and period
cpuLimitOrder.verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_PERIOD_US, String.valueOf(periodUS));
cpuLimitOrder.verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_QUOTA_US, String.valueOf(quotaUS));
}
}
@Test
public void testReacquireContainer() throws Exception {
ContainerId containerIdMock = mock(ContainerId.class);
assertNull(
cGroupsCpuResourceHandler.reacquireContainer(containerIdMock));
}
@Test
public void testPostComplete() throws Exception {
String id = "container_01_01";
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
assertNull(cGroupsCpuResourceHandler.postComplete(mockContainerId));
verify(mockCGroupsHandler, times(1))
.deleteCGroup(CGroupsHandler.CGroupController.CPU, id);
}
@Test
public void testTeardown() throws Exception {
assertNull(cGroupsCpuResourceHandler.teardown());
}
@Test
public void testStrictResourceUsage() throws Exception {
assertNull(cGroupsCpuResourceHandler.teardown());
}
@Test
public void testOpportunistic() throws Exception {
Configuration conf = new YarnConfiguration();
cGroupsCpuResourceHandler.bootstrap(plugin, conf);
ContainerTokenIdentifier tokenId = mock(ContainerTokenIdentifier.class);
when(tokenId.getExecutionType()).thenReturn(ExecutionType.OPPORTUNISTIC);
Container container = mock(Container.class);
String id = "container_01_01";
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
when(container.getContainerId()).thenReturn(mockContainerId);
when(container.getContainerTokenIdentifier()).thenReturn(tokenId);
when(container.getResource()).thenReturn(Resource.newInstance(1024, 2));
cGroupsCpuResourceHandler.preStart(container);
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_SHARES, "2");
}
}
| TestCGroupsCpuResourceHandlerImpl |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/index/seqno/GlobalCheckpointSyncIT.java | {
"start": 1493,
"end": 11646
} | class ____ extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Stream.concat(super.nodePlugins().stream(), Stream.of(InternalSettingsPlugin.class, MockTransportService.TestPlugin.class))
.toList();
}
public void testGlobalCheckpointSyncWithAsyncDurability() throws Exception {
internalCluster().ensureAtLeastNumDataNodes(2);
prepareCreate(
"test",
Settings.builder()
.put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), "1s")
.put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.ASYNC)
.put(IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING.getKey(), "1s")
.put("index.number_of_replicas", 1)
).get();
for (int j = 0; j < 10; j++) {
final String id = Integer.toString(j);
prepareIndex("test").setId(id).setSource("{\"foo\": " + id + "}", XContentType.JSON).get();
}
assertBusy(() -> {
SeqNoStats seqNoStats = indicesAdmin().prepareStats("test").get().getIndex("test").getShards()[0].getSeqNoStats();
assertThat(seqNoStats.getGlobalCheckpoint(), equalTo(seqNoStats.getMaxSeqNo()));
});
}
public void testPostOperationGlobalCheckpointSync() throws Exception {
// set the sync interval high so it does not execute during this test. This only allows the global checkpoint to catch up
// on a post-operation background sync if translog durability is set to sync. Async durability relies on a scheduled global
// checkpoint sync to allow the information about persisted local checkpoints to be transferred to the primary.
runGlobalCheckpointSyncTest(
TimeValue.timeValueHours(24),
client -> client.admin()
.indices()
.prepareUpdateSettings("test")
.setSettings(Settings.builder().put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.REQUEST))
.get(),
client -> {}
);
}
/*
* This test swallows the post-operation global checkpoint syncs, and then restores the ability to send these requests at the end of the
* test so that a background sync can fire and sync the global checkpoint.
*/
public void testBackgroundGlobalCheckpointSync() throws Exception {
runGlobalCheckpointSyncTest(TimeValue.timeValueSeconds(randomIntBetween(1, 3)), client -> {
// prevent global checkpoint syncs between all nodes
final DiscoveryNodes nodes = client.admin().cluster().prepareState(TEST_REQUEST_TIMEOUT).get().getState().getNodes();
for (final DiscoveryNode node : nodes) {
for (final DiscoveryNode other : nodes) {
if (node == other) {
continue;
}
MockTransportService.getInstance(node.getName())
.addSendBehavior(
MockTransportService.getInstance(other.getName()),
(connection, requestId, action, request, options) -> {
if ("indices:admin/seq_no/global_checkpoint_sync[r]".equals(action)) {
throw new IllegalStateException("blocking indices:admin/seq_no/global_checkpoint_sync[r]");
} else {
connection.sendRequest(requestId, action, request, options);
}
}
);
}
}
}, client -> {
// restore global checkpoint syncs between all nodes
final DiscoveryNodes nodes = client.admin().cluster().prepareState(TEST_REQUEST_TIMEOUT).get().getState().getNodes();
for (final DiscoveryNode node : nodes) {
for (final DiscoveryNode other : nodes) {
if (node == other) {
continue;
}
MockTransportService.getInstance(node.getName()).clearOutboundRules(MockTransportService.getInstance(other.getName()));
}
}
});
}
private void runGlobalCheckpointSyncTest(
final TimeValue globalCheckpointSyncInterval,
final Consumer<Client> beforeIndexing,
final Consumer<Client> afterIndexing
) throws Exception {
final int numberOfReplicas = randomIntBetween(1, 4);
internalCluster().ensureAtLeastNumDataNodes(1 + numberOfReplicas);
prepareCreate(
"test",
Settings.builder()
.put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), globalCheckpointSyncInterval)
.put("index.number_of_replicas", numberOfReplicas)
).get();
if (randomBoolean()) {
ensureGreen();
}
beforeIndexing.accept(client());
final int numberOfDocuments = randomIntBetween(0, 256);
final int numberOfThreads = randomIntBetween(1, 4);
// start concurrent indexing threads
startInParallel(numberOfThreads, index -> {
for (int j = 0; j < numberOfDocuments; j++) {
final String id = Integer.toString(index * numberOfDocuments + j);
prepareIndex("test").setId(id).setSource("{\"foo\": " + id + "}", XContentType.JSON).get();
}
});
afterIndexing.accept(client());
assertBusy(() -> {
for (IndicesService indicesService : internalCluster().getDataNodeInstances(IndicesService.class)) {
for (IndexService indexService : indicesService) {
for (IndexShard shard : indexService) {
if (shard.routingEntry().primary()) {
try {
final SeqNoStats seqNoStats = shard.seqNoStats();
assertThat(
"shard " + shard.routingEntry() + " seq_no [" + seqNoStats + "]",
seqNoStats.getGlobalCheckpoint(),
equalTo(seqNoStats.getMaxSeqNo())
);
} catch (AlreadyClosedException e) {
logger.error(
"received unexpected AlreadyClosedException when fetching stats for shard: {}, shard state: {}",
shard.shardId(),
shard.state()
);
throw e;
}
}
}
}
}
}, 60, TimeUnit.SECONDS);
ensureGreen("test");
}
public void testPersistGlobalCheckpoint() throws Exception {
internalCluster().ensureAtLeastNumDataNodes(2);
Settings.Builder indexSettings = Settings.builder()
.put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), randomTimeValue(100, 1000, TimeUnit.MILLISECONDS))
.put("index.number_of_replicas", randomIntBetween(0, 1));
if (randomBoolean()) {
indexSettings.put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.ASYNC)
.put(IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING.getKey(), randomTimeValue(100, 1000, TimeUnit.MILLISECONDS));
}
prepareCreate("test", indexSettings).get();
if (randomBoolean()) {
ensureGreen("test");
}
int numDocs = randomIntBetween(1, 20);
for (int i = 0; i < numDocs; i++) {
prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get();
}
ensureGreen("test");
assertBusy(() -> {
for (IndicesService indicesService : internalCluster().getDataNodeInstances(IndicesService.class)) {
for (IndexService indexService : indicesService) {
for (IndexShard shard : indexService) {
final SeqNoStats seqNoStats = shard.seqNoStats();
assertThat(seqNoStats.getLocalCheckpoint(), equalTo(seqNoStats.getMaxSeqNo()));
assertThat(shard.getLastKnownGlobalCheckpoint(), equalTo(seqNoStats.getMaxSeqNo()));
assertThat(shard.getLastSyncedGlobalCheckpoint(), equalTo(seqNoStats.getMaxSeqNo()));
}
}
}
});
}
public void testPersistLocalCheckpoint() {
internalCluster().ensureAtLeastNumDataNodes(2);
Settings.Builder indexSettings = indexSettings(1, randomIntBetween(0, 1)).put(
IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(),
"10m"
).put(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING.getKey(), Translog.Durability.REQUEST);
prepareCreate("test", indexSettings).get();
ensureGreen("test");
int numDocs = randomIntBetween(1, 20);
logger.info("numDocs {}", numDocs);
long maxSeqNo = 0;
for (int i = 0; i < numDocs; i++) {
maxSeqNo = prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get().getSeqNo();
logger.info("got {}", maxSeqNo);
}
for (IndicesService indicesService : internalCluster().getDataNodeInstances(IndicesService.class)) {
for (IndexService indexService : indicesService) {
for (IndexShard shard : indexService) {
final SeqNoStats seqNoStats = shard.seqNoStats();
assertThat(maxSeqNo, equalTo(seqNoStats.getMaxSeqNo()));
assertThat(seqNoStats.getLocalCheckpoint(), equalTo(seqNoStats.getMaxSeqNo()));
;
}
}
}
}
}
| GlobalCheckpointSyncIT |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java | {
"start": 3949,
"end": 4075
} | class ____ {
void test(@Selector String[] one, @Selector(match = Match.ALL_REMAINING) String[] two) {
}
}
}
| ValidSelectors |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemFactory.java | {
"start": 938,
"end": 1102
} | interface ____ {
/**
* Return a logging system implementation or {@code null} if no logging system is
* available.
* @param classLoader the | LoggingSystemFactory |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/TestWritable.java | {
"start": 4455,
"end": 8108
} | class ____ implements WritableComparable<Frob> {
static { // register default comparator
WritableComparator.define(Frob.class, new FrobComparator());
}
@Override public void write(DataOutput out) throws IOException {}
@Override public void readFields(DataInput in) throws IOException {}
@Override public int compareTo(Frob o) { return 0; }
}
/** Test that comparator is defined and configured. */
public static void testGetComparator() throws Exception {
Configuration conf = new Configuration();
// Without conf.
WritableComparator frobComparator = WritableComparator.get(Frob.class);
assert(frobComparator instanceof FrobComparator);
assertNotNull(frobComparator.getConf());
assertNull(frobComparator.getConf().get(TEST_CONFIG_PARAM));
// With conf.
conf.set(TEST_CONFIG_PARAM, TEST_CONFIG_VALUE);
frobComparator = WritableComparator.get(Frob.class, conf);
assert(frobComparator instanceof FrobComparator);
assertNotNull(frobComparator.getConf());
assertEquals(conf.get(TEST_CONFIG_PARAM), TEST_CONFIG_VALUE);
// Without conf. should reuse configuration.
frobComparator = WritableComparator.get(Frob.class);
assert(frobComparator instanceof FrobComparator);
assertNotNull(frobComparator.getConf());
assertEquals(conf.get(TEST_CONFIG_PARAM), TEST_CONFIG_VALUE);
// New conf. should use new configuration.
frobComparator = WritableComparator.get(Frob.class, new Configuration());
assert(frobComparator instanceof FrobComparator);
assertNotNull(frobComparator.getConf());
assertNull(frobComparator.getConf().get(TEST_CONFIG_PARAM));
}
/**
* Test a user comparator that relies on deserializing both arguments for each
* compare.
*/
@Test
public void testShortWritableComparator() throws Exception {
ShortWritable writable1 = new ShortWritable((short)256);
ShortWritable writable2 = new ShortWritable((short) 128);
ShortWritable writable3 = new ShortWritable((short) 256);
final String SHOULD_NOT_MATCH_WITH_RESULT_ONE = "Result should be 1, should not match the writables";
assertTrue(writable1.compareTo(writable2) == 1,
SHOULD_NOT_MATCH_WITH_RESULT_ONE);
assertTrue(WritableComparator.get(
ShortWritable.class).compare(writable1, writable2) == 1,
SHOULD_NOT_MATCH_WITH_RESULT_ONE);
final String SHOULD_NOT_MATCH_WITH_RESULT_MINUS_ONE = "Result should be -1, should not match the writables";
assertTrue(writable2.compareTo(writable1) == -1,
SHOULD_NOT_MATCH_WITH_RESULT_MINUS_ONE);
assertTrue(WritableComparator.get(
ShortWritable.class).compare(writable2, writable1) == -1,
SHOULD_NOT_MATCH_WITH_RESULT_MINUS_ONE);
final String SHOULD_MATCH = "Result should be 0, should match the writables";
assertTrue(writable1.compareTo(writable1) == 0, SHOULD_MATCH);
assertTrue(WritableComparator.get(ShortWritable.class)
.compare(writable1, writable3) == 0, SHOULD_MATCH);
}
/**
* Test that Writable's are configured by Comparator.
*/
@Test
public void testConfigurableWritableComparator() throws Exception {
Configuration conf = new Configuration();
conf.set(TEST_WRITABLE_CONFIG_PARAM, TEST_WRITABLE_CONFIG_VALUE);
WritableComparator wc = WritableComparator.get(SimpleWritableComparable.class, conf);
SimpleWritableComparable key = ((SimpleWritableComparable)wc.newKey());
assertNotNull(wc.getConf());
assertNotNull(key.getConf());
assertEquals(key.getConf().get(TEST_WRITABLE_CONFIG_PARAM), TEST_WRITABLE_CONFIG_VALUE);
}
}
| Frob |
java | elastic__elasticsearch | modules/data-streams/src/internalClusterTest/java/org/elasticsearch/datastreams/SystemDataStreamSnapshotIT.java | {
"start": 2293,
"end": 12420
} | class ____ extends AbstractSnapshotIntegTestCase {
public static final String REPO = "repo";
public static final String SNAPSHOT = "snap";
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return List.of(MockRepository.Plugin.class, DataStreamsPlugin.class, SystemDataStreamTestPlugin.class);
}
public void testSystemDataStreamInGlobalState() throws Exception {
Path location = randomRepoPath();
createRepository(REPO, "fs", location);
{
CreateDataStreamAction.Request request = new CreateDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
SYSTEM_DATA_STREAM_NAME
);
final AcknowledgedResponse response = client().execute(CreateDataStreamAction.INSTANCE, request).get();
assertTrue(response.isAcknowledged());
}
// Index a doc so that a concrete backing index will be created
DocWriteResponse indexRepsonse = prepareIndex(SYSTEM_DATA_STREAM_NAME).setId("42")
.setSource("{ \"@timestamp\": \"2099-03-08T11:06:07.000Z\", \"name\": \"my-name\" }", XContentType.JSON)
.setOpType(DocWriteRequest.OpType.CREATE)
.get();
assertThat(indexRepsonse.status().getStatus(), oneOf(200, 201));
{
GetDataStreamAction.Request request = new GetDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { SYSTEM_DATA_STREAM_NAME }
);
GetDataStreamAction.Response response = client().execute(GetDataStreamAction.INSTANCE, request).get();
assertThat(response.getDataStreams(), hasSize(1));
assertTrue(response.getDataStreams().get(0).getDataStream().isSystem());
}
assertSuccessful(
clusterAdmin().prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, REPO, SNAPSHOT)
.setWaitForCompletion(true)
.setIncludeGlobalState(true)
.execute()
);
// We have to delete the data stream directly, as the feature reset API doesn't clean up system data streams yet
// See https://github.com/elastic/elasticsearch/issues/75818
{
DeleteDataStreamAction.Request request = new DeleteDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { SYSTEM_DATA_STREAM_NAME }
);
AcknowledgedResponse response = client().execute(DeleteDataStreamAction.INSTANCE, request).get();
assertTrue(response.isAcknowledged());
}
{
GetIndexResponse indicesRemaining = indicesAdmin().prepareGetIndex(TEST_REQUEST_TIMEOUT).addIndices("_all").get();
assertThat(indicesRemaining.indices(), arrayWithSize(0));
assertSystemDataStreamDoesNotExist();
}
// Make sure requesting the data stream by name throws.
// For some reason, expectThrows() isn't working for me here, hence the try/catch.
try {
clusterAdmin().prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, REPO, SNAPSHOT)
.setIndices(".test-data-stream")
.setWaitForCompletion(true)
.setRestoreGlobalState(randomBoolean()) // this shouldn't matter
.get();
} catch (Exception e) {
assertThat(e, instanceOf(IllegalArgumentException.class));
assertThat(
e.getMessage(),
equalTo(
"requested system data stream [.test-data-stream], but system data streams can only be restored as part of a feature "
+ "state"
)
);
}
assertSystemDataStreamDoesNotExist();
// Now actually restore the data stream
RestoreSnapshotResponse restoreSnapshotResponse = clusterAdmin().prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, REPO, SNAPSHOT)
.setWaitForCompletion(true)
.setRestoreGlobalState(true)
.get();
assertEquals(restoreSnapshotResponse.getRestoreInfo().totalShards(), restoreSnapshotResponse.getRestoreInfo().successfulShards());
{
GetDataStreamAction.Request request = new GetDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { SYSTEM_DATA_STREAM_NAME }
);
GetDataStreamAction.Response response = client().execute(GetDataStreamAction.INSTANCE, request).get();
assertThat(response.getDataStreams(), hasSize(1));
assertTrue(response.getDataStreams().get(0).getDataStream().isSystem());
}
// Attempting to restore again without specifying indices or global/feature states should work, as the wildcard should not be
// resolved to system indices/data streams.
clusterAdmin().prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, REPO, SNAPSHOT)
.setWaitForCompletion(true)
.setRestoreGlobalState(false)
.get();
assertEquals(restoreSnapshotResponse.getRestoreInfo().totalShards(), restoreSnapshotResponse.getRestoreInfo().successfulShards());
}
private void assertSystemDataStreamDoesNotExist() {
try {
GetDataStreamAction.Request request = new GetDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { SYSTEM_DATA_STREAM_NAME }
);
GetDataStreamAction.Response response = client().execute(GetDataStreamAction.INSTANCE, request).get();
assertThat(response.getDataStreams(), hasSize(0));
} catch (Exception e) {
Throwable ex = e;
while (ex instanceof IndexNotFoundException == false) {
ex = ex.getCause();
assertNotNull("expected to find an IndexNotFoundException somewhere in the causes, did not", e);
}
}
}
public void testSystemDataStreamInFeatureState() throws Exception {
Path location = randomRepoPath();
createRepository(REPO, "fs", location);
{
CreateDataStreamAction.Request request = new CreateDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
SYSTEM_DATA_STREAM_NAME
);
final AcknowledgedResponse response = client().execute(CreateDataStreamAction.INSTANCE, request).get();
assertTrue(response.isAcknowledged());
}
// Index a doc so that a concrete backing index will be created
DocWriteResponse indexToDataStreamResponse = prepareIndex(SYSTEM_DATA_STREAM_NAME).setId("42")
.setSource("{ \"@timestamp\": \"2099-03-08T11:06:07.000Z\", \"name\": \"my-name\" }", XContentType.JSON)
.setOpType(DocWriteRequest.OpType.CREATE)
.get();
assertThat(indexToDataStreamResponse.status().getStatus(), oneOf(200, 201));
// Index a doc so that a concrete backing index will be created
DocWriteResponse indexResponse = prepareIndex("my-index").setId("42")
.setSource("{ \"name\": \"my-name\" }", XContentType.JSON)
.setOpType(DocWriteRequest.OpType.CREATE)
.get();
assertThat(indexResponse.status().getStatus(), oneOf(200, 201));
{
GetDataStreamAction.Request request = new GetDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { SYSTEM_DATA_STREAM_NAME }
);
GetDataStreamAction.Response response = client().execute(GetDataStreamAction.INSTANCE, request).get();
assertThat(response.getDataStreams(), hasSize(1));
assertTrue(response.getDataStreams().get(0).getDataStream().isSystem());
}
SnapshotInfo snapshotInfo = assertSuccessful(
clusterAdmin().prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, REPO, SNAPSHOT)
.setIndices("my-index")
.setFeatureStates(SystemDataStreamTestPlugin.class.getSimpleName())
.setWaitForCompletion(true)
.setIncludeGlobalState(false)
.execute()
);
assertThat(snapshotInfo.dataStreams(), not(empty()));
// We have to delete the data stream directly, as the feature reset API doesn't clean up system data streams yet
// See https://github.com/elastic/elasticsearch/issues/75818
{
DeleteDataStreamAction.Request request = new DeleteDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { SYSTEM_DATA_STREAM_NAME }
);
AcknowledgedResponse response = client().execute(DeleteDataStreamAction.INSTANCE, request).get();
assertTrue(response.isAcknowledged());
}
assertAcked(indicesAdmin().prepareDelete("my-index"));
{
GetIndexResponse indicesRemaining = indicesAdmin().prepareGetIndex(TEST_REQUEST_TIMEOUT).addIndices("_all").get();
assertThat(indicesRemaining.indices(), arrayWithSize(0));
}
RestoreSnapshotResponse restoreSnapshotResponse = clusterAdmin().prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, REPO, SNAPSHOT)
.setWaitForCompletion(true)
.setIndices("my-index")
.setFeatureStates(SystemDataStreamTestPlugin.class.getSimpleName())
.get();
assertEquals(restoreSnapshotResponse.getRestoreInfo().totalShards(), restoreSnapshotResponse.getRestoreInfo().successfulShards());
{
GetDataStreamAction.Request request = new GetDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { SYSTEM_DATA_STREAM_NAME }
);
GetDataStreamAction.Response response = client().execute(GetDataStreamAction.INSTANCE, request).get();
assertThat(response.getDataStreams(), hasSize(1));
assertTrue(response.getDataStreams().get(0).getDataStream().isSystem());
}
}
public static | SystemDataStreamSnapshotIT |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/sql/function/JpaFunctionTest.java | {
"start": 935,
"end": 2145
} | class ____ {
@BeforeAll
protected void afterEntityManagerFactoryBuilt(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
Event event = new Event();
event.setId( 1L );
event.setMessage( "ABC" );
event.setCreatedOn( Timestamp.valueOf( "9999-12-31 00:00:00" ) );
entityManager.persist( event );
}
);
}
@Test
public void testWithoutComma(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager ->
entityManager.createQuery(
"select FUNCTION('now') " +
"from Event " +
"where id = :id", Date.class )
.setParameter( "id", 1L )
.getSingleResult()
);
}
@Test
public void testWithoutCommaFail(EntityManagerFactoryScope scope) {
Exception exception = assertThrows( Exception.class, () ->
scope.inTransaction( entityManager ->
entityManager.createQuery(
"select FUNCTION('substring' 'abc', 1,2) " +
"from Event " +
"where id = :id", String.class )
.setParameter( "id", 1L )
.getSingleResult()
) );
assertThat( exception.getCause() ).isInstanceOf( SyntaxException.class );
}
@Entity(name = "Event")
public static | JpaFunctionTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest60.java | {
"start": 1026,
"end": 4327
} | class ____ extends OracleTest {
public void test_types() throws Exception {
String sql = //
" CREATE TABLE \"SC_001\".\"TB_001\" \n" +
" ( \"MEMBER_ID\" VARCHAR2(32) NOT NULL ENABLE, \n" +
" \"CATEGORY_LEVEL2_ID\" NUMBER NOT NULL ENABLE, \n" +
" \"CATEGORY_LEVEL2_DESC\" VARCHAR2(128), \n" +
" \"AVG_INQUIRY_CNT\" NUMBER, \n" +
" \"AVG_INQUIRY_CNT_TOP10\" NUMBER\n" +
" ) SEGMENT CREATION IMMEDIATE \n" +
" PCTFREE 0 PCTUSED 40 INITRANS 1 MAXTRANS 255 COMPRESS BASIC LOGGING\n" +
" STORAGE(INITIAL 50331648 NEXT 4194304 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" +
" TABLESPACE \"ZEUS_IND\" ";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
assertEquals("CREATE TABLE \"SC_001\".\"TB_001\" (\n" +
"\t\"MEMBER_ID\" VARCHAR2(32) NOT NULL ENABLE,\n" +
"\t\"CATEGORY_LEVEL2_ID\" NUMBER NOT NULL ENABLE,\n" +
"\t\"CATEGORY_LEVEL2_DESC\" VARCHAR2(128),\n" +
"\t\"AVG_INQUIRY_CNT\" NUMBER,\n" +
"\t\"AVG_INQUIRY_CNT_TOP10\" NUMBER\n" +
")\n" +
"PCTFREE 0\n" +
"PCTUSED 40\n" +
"INITRANS 1\n" +
"MAXTRANS 255\n" +
"COMPRESS\n" +
"LOGGING\n" +
"TABLESPACE \"ZEUS_IND\"\n" +
"STORAGE (\n" +
"\tINITIAL 50331648\n" +
"\tNEXT 4194304\n" +
"\tMINEXTENTS 1\n" +
"\tMAXEXTENTS 2147483645\n" +
"\tPCTINCREASE 0\n" +
"\tFREELISTS 1\n" +
"\tFREELIST GROUPS 1\n" +
"\tBUFFER_POOL DEFAULT\n" +
"\tFLASH_CACHE DEFAULT\n" +
"\tCELL_FLASH_CACHE DEFAULT\n" +
")",
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(5, visitor.getColumns().size());
assertTrue(visitor.containsColumn("SC_001.TB_001", "MEMBER_ID"));
}
}
| OracleCreateTableTest60 |
java | apache__flink | flink-table/flink-table-code-splitter/src/test/resources/function/expected/TestRewriteInnerClass.java | {
"start": 959,
"end": 1960
} | class ____ {
boolean myFunHasReturned$1;
public void myFun(int[] a, int[] b) throws RuntimeException {
myFunHasReturned$1 = false;
myFun_split6(a, b);
if (myFunHasReturned$1) { return; }
myFun_split7(a, b);
myFun_split8(a, b);
if (myFunHasReturned$1) { return; }
myFun_split9(a, b);
}
void myFun_split6(int[] a, int[] b) throws RuntimeException {
if (a[0] != 0) {
a[0] += b[0];
b[0] += a[1];
{ myFunHasReturned$1 = true; return; }
}
}
void myFun_split7(int[] a, int[] b) throws RuntimeException {
a[1] += b[1];
b[1] += a[2];
}
void myFun_split8(int[] a, int[] b) throws RuntimeException {
if (a[2] != 0) {
a[2] += b[2];
b[2] += a[3];
{ myFunHasReturned$1 = true; return; }
}
}
void myFun_split9(int[] a, int[] b) throws RuntimeException {
a[3] += b[3];
b[3] += a[4];
}
}
}
| InnerClass |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/EmbeddableAsElementCollectionWithUpdatableFalseTest.java | {
"start": 3215,
"end": 3601
} | class ____ {
@Id
@GeneratedValue
private Integer id;
@ElementCollection(fetch = FetchType.LAZY)
private List<MyEmbeddable> myEmbeddables = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<MyEmbeddable> getMyEmbeddables() {
return myEmbeddables;
}
}
@Embeddable
public static | MyEntity |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/InternalOrder.java | {
"start": 20564,
"end": 22495
} | class ____ {
/**
* Parse a {@link BucketOrder} from {@link XContent}.
*
* @param parser for parsing {@link XContent} that contains the order.
* @return bucket ordering strategy
* @throws IOException on error a {@link XContent} parsing error.
*/
public static BucketOrder parseOrderParam(XContentParser parser) throws IOException {
XContentParser.Token token;
String orderKey = null;
boolean orderAsc = false;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
orderKey = parser.currentName();
} else if (token == XContentParser.Token.VALUE_STRING) {
String dir = parser.text();
if ("asc".equalsIgnoreCase(dir)) {
orderAsc = true;
} else if ("desc".equalsIgnoreCase(dir)) {
orderAsc = false;
} else {
throw new ParsingException(parser.getTokenLocation(), "Unknown order direction [" + dir + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(), "Unexpected token [" + token + "] for [order]");
}
}
if (orderKey == null) {
throw new ParsingException(parser.getTokenLocation(), "Must specify at least one field for [order]");
}
return switch (orderKey) {
case "_key" -> orderAsc ? KEY_ASC : KEY_DESC;
case "_count" -> orderAsc ? COUNT_ASC : COUNT_DESC;
default -> // assume all other orders are sorting on a sub-aggregation. Validation occurs later.
aggregation(orderKey, orderAsc);
};
}
}
}
| Parser |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-proxyexchange-webmvc/src/main/java/org/springframework/cloud/gateway/mvc/ProxyExchange.java | {
"start": 19483,
"end": 19862
} | class ____ converts an incoming request input stream into a form that can
* be easily deserialized to a Java object using Spring message converters. It is only
* used in a local forward dispatch, in which case there is a danger that the request body
* will need to be read and analysed more than once. Apart from using the message
* converters the other main feature of this | that |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/QueuePlacementPolicy.java | {
"start": 2662,
"end": 3054
} | class ____ {
private final Class<? extends PlacementRule> ruleClass;
private final String terminal;
private RuleMap(Class<? extends PlacementRule> clazz, String terminate) {
this.ruleClass = clazz;
this.terminal = terminate;
}
}
// The list of known rules:
// key to the map is the name in the configuration.
// for each name the mapping contains the | RuleMap |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/sort/ShardDocSortField.java | {
"start": 962,
"end": 3230
} | class ____ extends SortField {
public static final String NAME = "_shard_doc";
private final int shardRequestIndex;
public ShardDocSortField(int shardRequestIndex, boolean reverse) {
super(NAME, Type.LONG, reverse);
assert shardRequestIndex >= 0;
this.shardRequestIndex = shardRequestIndex;
}
int getShardRequestIndex() {
return shardRequestIndex;
}
@Override
public FieldComparator<?> getComparator(int numHits, Pruning enableSkipping) {
final DocComparator delegate = new DocComparator(numHits, getReverse(), Pruning.NONE);
return new FieldComparator<Long>() {
@Override
public int compare(int slot1, int slot2) {
return delegate.compare(slot1, slot2);
}
@Override
public int compareValues(Long first, Long second) {
return Long.compare(first, second);
}
@Override
public void setTopValue(Long value) {
int topShardIndex = (int) (value >> 32);
if (shardRequestIndex == topShardIndex) {
delegate.setTopValue(value.intValue());
} else if (shardRequestIndex < topShardIndex) {
delegate.setTopValue(Integer.MAX_VALUE);
} else {
delegate.setTopValue(-1);
}
}
@Override
public Long value(int slot) {
return encodeShardAndDoc(shardRequestIndex, delegate.value(slot));
}
@Override
public LeafFieldComparator getLeafComparator(LeafReaderContext context) {
return delegate.getLeafComparator(context);
}
};
}
/**
* Get the doc id encoded in the sort value.
*/
public static int decodeDoc(long value) {
return (int) value;
}
/**
* Get the shard request index encoded in the sort value.
*/
public static int decodeShardRequestIndex(long value) {
return (int) (value >> 32);
}
public static long encodeShardAndDoc(int shardIndex, int doc) {
return (((long) shardIndex) << 32) | (doc & 0xFFFFFFFFL);
}
}
| ShardDocSortField |
java | apache__camel | components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/IncomingDocument.java | {
"start": 1077,
"end": 2686
} | class ____ {
@JsonProperty("file_id")
private String fileId;
@JsonProperty("thumb")
private IncomingPhotoSize thumb;
@JsonProperty("file_name")
private String fileName;
@JsonProperty("mime_type")
private String mimeType;
@JsonProperty("file_size")
private Long fileSize;
public IncomingDocument() {
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public IncomingPhotoSize getThumb() {
return thumb;
}
public void setThumb(IncomingPhotoSize thumb) {
this.thumb = thumb;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("IncomingDocument{");
sb.append("fileId='").append(fileId).append('\'');
sb.append(", thumbSize='").append(thumb).append('\'');
sb.append(", fileName='").append(fileName).append('\'');
sb.append(", mimeType='").append(mimeType).append('\'');
sb.append(", fileSize=").append(fileSize);
sb.append('}');
return sb.toString();
}
}
| IncomingDocument |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/type/AbstractNamedEnumTest.java | {
"start": 3500,
"end": 3696
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@ManyToOne(cascade = CascadeType.PERSIST)
Activity activity;
}
public | Timeslot |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/profile/SearchProfileResults.java | {
"start": 1229,
"end": 6644
} | class ____ implements Writeable, ToXContentFragment {
private static final Logger logger = LogManager.getLogger(SearchProfileResults.class);
public static final String ID_FIELD = "id";
private static final String NODE_ID_FIELD = "node_id";
private static final String CLUSTER_FIELD = "cluster";
private static final String INDEX_NAME_FIELD = "index";
private static final String SHARD_ID_FIELD = "shard_id";
public static final String SHARDS_FIELD = "shards";
public static final String PROFILE_FIELD = "profile";
// map key is the composite "id" of form [nodeId][(clusterName:)indexName][shardId] created from SearchShardTarget.toString
private final Map<String, SearchProfileShardResult> shardResults;
public SearchProfileResults(Map<String, SearchProfileShardResult> shardResults) {
this.shardResults = Collections.unmodifiableMap(shardResults);
}
public SearchProfileResults(StreamInput in) throws IOException {
shardResults = in.readMap(SearchProfileShardResult::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeMap(shardResults, StreamOutput::writeWriteable);
}
public Map<String, SearchProfileShardResult> getShardResults() {
return shardResults;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(PROFILE_FIELD).startArray(SHARDS_FIELD);
// shardResults is a map, but we print entries in a json array, which is ordered.
// we sort the keys of the map, so that toXContent always prints out the same array order
TreeSet<String> sortedKeys = new TreeSet<>(shardResults.keySet());
for (String key : sortedKeys) {
builder.startObject();
builder.field(ID_FIELD, key);
ShardProfileId shardProfileId = parseCompositeProfileShardId(key);
if (shardProfileId != null) {
builder.field(NODE_ID_FIELD, shardProfileId.nodeId());
builder.field(SHARD_ID_FIELD, shardProfileId.shardId());
builder.field(INDEX_NAME_FIELD, shardProfileId.indexName());
String cluster = shardProfileId.clusterName();
if (cluster == null) {
cluster = "(local)";
}
builder.field(CLUSTER_FIELD, cluster);
}
SearchProfileShardResult shardResult = shardResults.get(key);
shardResult.toXContent(builder, params);
builder.endObject();
}
builder.endArray().endObject();
return builder;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
SearchProfileResults other = (SearchProfileResults) obj;
return shardResults.equals(other.shardResults);
}
@Override
public int hashCode() {
return shardResults.hashCode();
}
@Override
public String toString() {
return Strings.toString(this);
}
/**
* Parsed representation of a composite id used for shards in a profile.
* The composite id format is specified/created via the {@code SearchShardTarget} method.
* @param nodeId nodeId that the shard is on
* @param indexName index being profiled
* @param shardId shard id being profiled
* @param clusterName if a CCS search, the remote clusters will have a name in the id. Local clusters will be null.
*/
record ShardProfileId(String nodeId, String indexName, int shardId, @Nullable String clusterName) {}
private static final Pattern SHARD_ID_DECOMPOSITION = Pattern.compile("\\[([^]]+)\\]\\[([^]]+)\\]\\[(\\d+)\\]");
/**
* Parse the composite "shard id" from the profiles output, which comes from the
* {@code SearchShardTarget.toString()} method, into its separate components.
* <p>
* One of two expected patterns is accepted:
* <p>
* 1) [nodeId][indexName][shardId]
* example: [2m7SW9oIRrirdrwirM1mwQ][blogs][1]
* <p>
* 2) [nodeId][clusterName:indexName][shardId]
* example: [UngEVXTBQL-7w5j_tftGAQ][remote1:blogs][0]
*
* @param compositeId see above for accepted formats
* @return ShardProfileId with parsed components or null if the compositeId has an unsupported format
*/
static ShardProfileId parseCompositeProfileShardId(String compositeId) {
assert Strings.isNullOrEmpty(compositeId) == false : "An empty id should not be passed to parseCompositeProfileShardId";
Matcher m = SHARD_ID_DECOMPOSITION.matcher(compositeId);
if (m.find()) {
String nodeId = m.group(1);
String[] tokens = RemoteClusterAware.splitIndexName(m.group(2));
String cluster = tokens[0];
String indexName = tokens[1];
int shardId = Integer.parseInt(m.group(3));
return new ShardProfileId(nodeId, indexName, shardId, cluster);
} else {
assert false : "Unable to match input against expected pattern of [nodeId][indexName][shardId]. Input: " + compositeId;
logger.warn("Unable to match input against expected pattern of [nodeId][indexName][shardId]. Input: {}", compositeId);
return null;
}
}
}
| SearchProfileResults |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java | {
"start": 138917,
"end": 139053
} | class ____ {
}
@ImplicitAliasesTestConfiguration
@Retention(RetentionPolicy.RUNTIME)
@ | ImplicitAliasesForAliasPairTestConfigurationClass |
java | dropwizard__dropwizard | dropwizard-migrations/src/test/java/io/dropwizard/migrations/DbRollbackCommandTest.java | {
"start": 680,
"end": 8671
} | class ____ {
private final String migrationsFileName = "migrations-ddl.xml";
private final DbRollbackCommand<TestMigrationConfiguration> rollbackCommand = new DbRollbackCommand<>(
new TestMigrationDatabaseConfiguration(), TestMigrationConfiguration.class, migrationsFileName);
private final DbMigrateCommand<TestMigrationConfiguration> migrateCommand = new DbMigrateCommand<>(
new TestMigrationDatabaseConfiguration(), TestMigrationConfiguration.class, migrationsFileName);
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private TestMigrationConfiguration conf;
private Jdbi dbi;
@BeforeEach
void setUp() {
final String databaseUrl = MigrationTestSupport.getDatabaseUrl();
conf = MigrationTestSupport.createConfiguration(databaseUrl);
dbi = Jdbi.create(databaseUrl, "sa", "");
}
@Test
void testRollbackNChanges() throws Exception {
// Migrate some DDL changes to the database
migrateCommand.run(null, new Namespace(Map.of()), conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.columnExists(handle, "PERSONS", "EMAIL"))
.isTrue();
}
// Rollback the last one (the email field)
rollbackCommand.run(null, new Namespace(Map.of("count", 1)), conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.columnExists(handle, "PERSONS", "EMAIL"))
.isFalse();
}
}
@Test
void testRollbackNChangesAsDryRun() throws Exception {
// Migrate some DDL changes to the database
migrateCommand.run(null, new Namespace(Map.of()), conf);
// Print out the change that rollbacks the second change
rollbackCommand.setOutputStream(new PrintStream(baos, true));
rollbackCommand.run(null, new Namespace(Map.of("count", 1, "dry-run", true)), conf);
assertThat(baos.toString(UTF_8))
.containsIgnoringCase("ALTER TABLE PUBLIC.persons DROP COLUMN email;");
}
@Test
void testRollbackToDate() throws Exception {
// Migrate some DDL changes to the database
long migrationDate = System.currentTimeMillis();
migrateCommand.run(null, new Namespace(Map.of()), conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.tableExists(handle, "PERSONS"))
.isTrue();
}
// Rollback both changes (they're tearDown the migration date)
rollbackCommand.run(null, new Namespace(Map.of("date", new Date(migrationDate - 1000))),
conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.tableExists(handle, "PERSONS"))
.isFalse();
}
}
@Test
void testRollbackToDateAsDryRun() throws Exception {
// Migrate some DDL changes to the database
long migrationDate = System.currentTimeMillis();
migrateCommand.run(null, new Namespace(Map.of()), conf);
// Print out a rollback script for both changes tearDown the migration date
rollbackCommand.setOutputStream(new PrintStream(baos, true));
rollbackCommand.run(null, new Namespace(Map.of(
"date", new Date(migrationDate - 1000),
"dry-run", true)),
conf);
assertThat(baos.toString(UTF_8))
.containsIgnoringCase("ALTER TABLE PUBLIC.persons DROP COLUMN email;")
.containsIgnoringCase("DROP TABLE PUBLIC.persons;");
}
@Test
void testRollbackToTag() throws Exception {
// Migrate the first DDL change to the database
migrateCommand.run(null, new Namespace(Map.of("count", 1)), conf);
// Tag it
final DbTagCommand<TestMigrationConfiguration> tagCommand = new DbTagCommand<>(
new TestMigrationDatabaseConfiguration(), TestMigrationConfiguration.class, migrationsFileName);
tagCommand.run(null, new Namespace(Map.of("tag-name", List.of("v1"))), conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.columnExists(handle, "PERSONS", "EMAIL"))
.isFalse();
}
// Migrate the second change
migrateCommand.run(null, new Namespace(Map.of()), conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.columnExists(handle, "PERSONS", "EMAIL"))
.isTrue();
}
// Rollback to the first change
rollbackCommand.run(null, new Namespace(Map.of("tag", "v1")), conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.columnExists(handle, "PERSONS", "EMAIL"))
.isFalse();
}
}
@Test
void testRollbackToTagAsDryRun() throws Exception {
// Migrate the first DDL change to the database
migrateCommand.run(null, new Namespace(Map.of("count", 1)), conf);
// Tag it
final DbTagCommand<TestMigrationConfiguration> tagCommand = new DbTagCommand<>(
new TestMigrationDatabaseConfiguration(), TestMigrationConfiguration.class, migrationsFileName);
tagCommand.run(null, new Namespace(Map.of("tag-name", List.of("v1"))), conf);
// Migrate the second change
migrateCommand.run(null, new Namespace(Map.of()), conf);
// Print out the rollback script for the second change
rollbackCommand.setOutputStream(new PrintStream(baos, true));
rollbackCommand.run(null, new Namespace(Map.of("tag", "v1", "dry-run", true)), conf);
assertThat(baos.toString(UTF_8))
.containsIgnoringCase("ALTER TABLE PUBLIC.persons DROP COLUMN email;");
}
@Test
void testPrintHelp() throws Exception {
MigrationTestSupport.createSubparser(rollbackCommand).printHelp(new PrintWriter(new OutputStreamWriter(baos, UTF_8), true));
assertThat(baos.toString(UTF_8)).isEqualToNormalizingNewlines(
"usage: db rollback [-h] [--migrations MIGRATIONS-FILE] [--catalog CATALOG]\n" +
" [--schema SCHEMA] [--analytics-enabled ANALYTICS-ENABLED] [-n]\n" +
" [-t TAG] [-d DATE] [-c COUNT] [-i CONTEXTS] [file]\n" +
"\n" +
"Rollback the database schema to a previous version.\n" +
"\n" +
"positional arguments:\n" +
" file application configuration file\n" +
"\n" +
"named arguments:\n" +
" -h, --help show this help message and exit\n" +
" --migrations MIGRATIONS-FILE\n" +
" the file containing the Liquibase migrations for\n" +
" the application\n" +
" --catalog CATALOG Specify the database catalog (use database\n" +
" default if omitted)\n" +
" --schema SCHEMA Specify the database schema (use database default\n" +
" if omitted)\n" +
" --analytics-enabled ANALYTICS-ENABLED\n" +
" This turns on analytics gathering for that single\n" +
" occurrence of a command.\n" +
" -n, --dry-run Output the DDL to stdout, don't run it\n" +
" -t TAG, --tag TAG Rollback to the given tag\n" +
" -d DATE, --date DATE Rollback to the given date\n" +
" -c COUNT, --count COUNT\n" +
" Rollback the specified number of change sets\n" +
" -i CONTEXTS, --include CONTEXTS\n" +
" include change sets from the given context\n");
}
}
| DbRollbackCommandTest |
java | netty__netty | transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollRecvByteAllocatorStreamingHandle.java | {
"start": 722,
"end": 1406
} | class ____ extends EpollRecvByteAllocatorHandle {
EpollRecvByteAllocatorStreamingHandle(RecvByteBufAllocator.ExtendedHandle handle) {
super(handle);
}
@Override
boolean maybeMoreDataToRead() {
/**
* For stream oriented descriptors we can assume we are done reading if the last read attempt didn't produce
* a full buffer (see Q9 in <a href="https://man7.org/linux/man-pages/man7/epoll.7.html">epoll man</a>).
*
* If EPOLLRDHUP has been received we must read until we get a read error.
*/
return lastBytesRead() == attemptedBytesRead() || isReceivedRdHup();
}
}
| EpollRecvByteAllocatorStreamingHandle |
java | apache__camel | components/camel-velocity/src/main/java/org/apache/camel/component/velocity/VelocityEndpoint.java | {
"start": 3065,
"end": 10564
} | class ____ as a property so we can access it from CamelVelocityClasspathResourceLoader
velocityEngine.addProperty("CamelClassResolver", getCamelContext().getClassResolver());
// set default properties
Properties properties = new Properties();
properties.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, isLoaderCache() ? "true" : "false");
properties.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file, class");
properties.setProperty("resource.loader.class.description", "Camel Velocity Classpath Resource Loader");
properties.setProperty("resource.loader.class.class", CamelVelocityClasspathResourceLoader.class.getName());
final Logger velocityLogger = LoggerFactory.getLogger("org.apache.camel.maven.Velocity");
properties.setProperty(RuntimeConstants.RUNTIME_LOG_NAME, velocityLogger.getName());
// load the velocity properties from property file which may overrides the default ones
if (ObjectHelper.isNotEmpty(getPropertiesFile())) {
InputStream reader
= ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), getPropertiesFile());
try {
properties.load(reader);
log.info("Loaded the velocity configuration file {}", getPropertiesFile());
} finally {
IOHelper.close(reader, getPropertiesFile(), log);
}
}
log.debug("Initializing VelocityEngine with properties {}", properties);
// help the velocityEngine to load the CamelVelocityClasspathResourceLoader
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
ClassLoader delegate = new CamelVelocityDelegateClassLoader(old);
Thread.currentThread().setContextClassLoader(delegate);
velocityEngine.init(properties);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
return velocityEngine;
} finally {
getInternalLock().unlock();
}
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public boolean isAllowTemplateFromHeader() {
return allowTemplateFromHeader;
}
/**
* Whether to allow to use resource template from header or not (default false).
*
* Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential
* security vulnerability if the header is coming from a malicious user, so use this with care.
*/
public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) {
this.allowTemplateFromHeader = allowTemplateFromHeader;
}
public boolean isLoaderCache() {
return loaderCache;
}
/**
* Enables / disables the velocity resource loader cache which is enabled by default
*/
public void setLoaderCache(boolean loaderCache) {
this.loaderCache = loaderCache;
}
/**
* Character encoding of the resource content.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getEncoding() {
return encoding;
}
/**
* The URI of the properties file which is used for VelocityEngine initialization.
*/
public void setPropertiesFile(String file) {
propertiesFile = file;
}
public String getPropertiesFile() {
return propertiesFile;
}
public VelocityEndpoint findOrCreateEndpoint(String uri, String newResourceUri) {
String newUri = uri.replace(getResourceUri(), newResourceUri);
log.debug("Getting endpoint with URI: {}", newUri);
return getCamelContext().getEndpoint(newUri, VelocityEndpoint.class);
}
@Override
protected void onExchange(Exchange exchange) throws Exception {
String path = getResourceUri();
ObjectHelper.notNull(path, "resourceUri");
if (allowTemplateFromHeader) {
String newResourceUri = exchange.getIn().getHeader(VelocityConstants.VELOCITY_RESOURCE_URI, String.class);
if (newResourceUri != null) {
exchange.getIn().removeHeader(VelocityConstants.VELOCITY_RESOURCE_URI);
log.debug("{} set to {} creating new endpoint to handle exchange", VelocityConstants.VELOCITY_RESOURCE_URI,
newResourceUri);
VelocityEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
newEndpoint.onExchange(exchange);
return;
}
}
Reader reader;
String content = null;
if (allowTemplateFromHeader) {
content = exchange.getIn().getHeader(VelocityConstants.VELOCITY_TEMPLATE, String.class);
}
if (content != null) {
// use content from header
reader = new StringReader(content);
if (log.isDebugEnabled()) {
log.debug("Velocity content read from header {} for endpoint {}", VelocityConstants.VELOCITY_TEMPLATE,
getEndpointUri());
}
// remove the header to avoid it being propagated in the routing
exchange.getIn().removeHeader(VelocityConstants.VELOCITY_TEMPLATE);
} else {
if (log.isDebugEnabled()) {
log.debug("Velocity content read from resource {} with resourceUri: {} for endpoint {}", getResourceUri(), path,
getEndpointUri());
}
reader = getEncoding() != null
? new InputStreamReader(getResourceAsInputStream(), getEncoding())
: new InputStreamReader(getResourceAsInputStream());
}
// getResourceAsInputStream also considers the content cache
StringWriter buffer = new StringWriter();
String logTag = getClass().getName();
Context velocityContext = null;
if (allowTemplateFromHeader) {
velocityContext = exchange.getIn().getHeader(VelocityConstants.VELOCITY_CONTEXT, Context.class);
}
if (velocityContext == null) {
Map<String, Object> variableMap = ExchangeHelper.createVariableMap(exchange, isAllowContextMapAll());
if (allowTemplateFromHeader) {
@SuppressWarnings("unchecked")
Map<String, Object> supplementalMap
= exchange.getIn().getHeader(VelocityConstants.VELOCITY_SUPPLEMENTAL_CONTEXT, Map.class);
if (supplementalMap != null) {
variableMap.putAll(supplementalMap);
}
}
velocityContext = new VelocityContext(variableMap);
}
// let velocity parse and generate the result in buffer
VelocityEngine engine = getVelocityEngine();
log.debug("Velocity is evaluating using velocity context: {}", velocityContext);
engine.evaluate(velocityContext, buffer, logTag, reader);
// now lets output the results to the exchange
ExchangeHelper.setInOutBodyPatternAware(exchange, buffer.toString());
}
}
| resolver |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/testutil/BrokenStringWriter.java | {
"start": 68,
"end": 655
} | class ____
extends FilterWriter
{
final String _message;
public BrokenStringWriter(String msg) {
super(new StringWriter());
_message = msg;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException
{
throw new IOException(_message);
}
@Override
public void write(int c) throws IOException
{
throw new IOException(_message);
}
@Override
public void write(String str, int off, int len) throws IOException
{
throw new IOException(_message);
}
}
| BrokenStringWriter |
java | google__error-prone | core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java | {
"start": 17599,
"end": 18010
} | class ____ {
@SomeAnnotation Void nullable = null;
@SomeAnnotation
Void foo() {
return null;
}
}
""")
.doTest();
}
@Test
public void qualifyType_importType() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/AddAnnotation.java",
"""
| AddAnnotation |
java | spring-projects__spring-boot | module/spring-boot-data-jpa/src/main/java/org/springframework/boot/data/jpa/autoconfigure/DataJpaRepositoriesAutoConfiguration.java | {
"start": 4215,
"end": 5188
} | class ____ {
@Bean
@Conditional(BootstrapExecutorCondition.class)
EntityManagerFactoryBuilderCustomizer entityManagerFactoryBootstrapExecutorCustomizer(
Map<String, AsyncTaskExecutor> taskExecutors) {
return (builder) -> {
AsyncTaskExecutor bootstrapExecutor = determineBootstrapExecutor(taskExecutors);
if (bootstrapExecutor != null) {
builder.setBootstrapExecutor(bootstrapExecutor);
}
};
}
@Bean
static LazyInitializationExcludeFilter eagerJpaMetamodelCacheCleanup() {
return (name, definition, type) -> "org.springframework.data.jpa.util.JpaMetamodelCacheCleanup".equals(name);
}
private @Nullable AsyncTaskExecutor determineBootstrapExecutor(Map<String, AsyncTaskExecutor> taskExecutors) {
if (taskExecutors.size() == 1) {
return taskExecutors.values().iterator().next();
}
return taskExecutors.get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME);
}
private static final | DataJpaRepositoriesAutoConfiguration |
java | netty__netty | transport-classes-io_uring/src/main/java/io/netty/channel/uring/IoUringFileRegion.java | {
"start": 990,
"end": 5175
} | class ____ implements FileRegion {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(IoUringFileRegion.class);
private static final short SPLICE_TO_PIPE = 1;
private static final short SPLICE_TO_SOCKET = 2;
final DefaultFileRegion fileRegion;
private FileDescriptor[] pipe;
private int transferred;
private int pipeLen = -1;
IoUringFileRegion(DefaultFileRegion fileRegion) {
this.fileRegion = fileRegion;
}
void open() throws IOException {
fileRegion.open();
if (pipe == null) {
pipe = FileDescriptor.pipe();
}
}
IoUringIoOps splice(int fd) {
if (pipeLen == -1) {
return spliceToPipe();
}
return spliceToSocket(fd, pipeLen);
}
IoUringIoOps spliceToPipe() {
int fileRegionFd = Native.getFd(fileRegion);
int len = (int) (count() - transferred());
int offset = (int) (position() + transferred());
return IoUringIoOps.newSplice(
fileRegionFd, offset,
pipe[1].intValue(), -1L,
len, Native.SPLICE_F_MOVE, SPLICE_TO_PIPE);
}
private IoUringIoOps spliceToSocket(int socket, int len) {
return IoUringIoOps.newSplice(
pipe[0].intValue(), -1L,
socket, -1L,
len, Native.SPLICE_F_MOVE, SPLICE_TO_SOCKET);
}
/**
* Handle splice result
*
* @param result the result
* @param data the data that was submitted as part of the SPLICE.
* @return the number of bytes that should be considered to be transferred.
*/
int handleResult(int result, short data) {
assert result >= 0;
if (data == SPLICE_TO_PIPE) {
// This is the result for spliceToPipe
transferred += result;
pipeLen = result;
return 0;
}
if (data == SPLICE_TO_SOCKET) {
// This is the result for spliceToSocket
pipeLen -= result;
assert pipeLen >= 0;
if (pipeLen == 0) {
if (transferred() >= count()) {
// We transferred the whole file
return -1;
}
pipeLen = -1;
}
return result;
}
throw new IllegalArgumentException("Unknown data: " + data);
}
@Override
public long position() {
return fileRegion.position();
}
@Override
public long transfered() {
return transferred;
}
@Override
public long transferred() {
return transferred;
}
@Override
public long count() {
return fileRegion.count();
}
@Override
public long transferTo(WritableByteChannel target, long position) {
throw new UnsupportedOperationException();
}
@Override
public FileRegion retain() {
fileRegion.retain();
return this;
}
@Override
public FileRegion retain(int increment) {
fileRegion.retain(increment);
return this;
}
@Override
public FileRegion touch() {
fileRegion.touch();
return this;
}
@Override
public FileRegion touch(Object hint) {
fileRegion.touch(hint);
return this;
}
@Override
public int refCnt() {
return fileRegion.refCnt();
}
@Override
public boolean release() {
if (fileRegion.release()) {
closePipeIfNeeded();
return true;
}
return false;
}
@Override
public boolean release(int decrement) {
if (fileRegion.release(decrement)) {
closePipeIfNeeded();
return true;
}
return false;
}
private void closePipeIfNeeded() {
if (pipe != null) {
closeSilently(pipe[0]);
closeSilently(pipe[1]);
}
}
private static void closeSilently(FileDescriptor fd) {
try {
fd.close();
} catch (IOException e) {
logger.debug("Error while closing a pipe", e);
}
}
}
| IoUringFileRegion |
java | spring-projects__spring-boot | module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/CompositeTextMapPropagatorTests.java | {
"start": 4737,
"end": 5010
} | class ____ {
private final Map<String, ContextKey<Object>> contextKeys = new HashMap<>();
private ContextKey<Object> get(String name) {
return this.contextKeys.computeIfAbsent(name, (ignore) -> ContextKey.named(name));
}
}
private static final | ContextKeyRegistry |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/SealedTypesWithTypedSerializationTest.java | {
"start": 1372,
"end": 1558
} | class ____ {
public Animal animal;
public AnimalWrapper(Animal a) { animal = a; }
}
@JsonTypeInfo(use=Id.MINIMAL_CLASS, include=As.WRAPPER_OBJECT)
| AnimalWrapper |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PhysicalPlan.java | {
"start": 815,
"end": 1303
} | class ____ extends QueryPlan<PhysicalPlan> implements Executable {
private Schema lazySchema;
public PhysicalPlan(Source source, List<PhysicalPlan> children) {
super(source, children);
}
public Schema schema() {
if (lazySchema == null) {
lazySchema = Rows.schema(output());
}
return lazySchema;
}
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object obj);
}
| PhysicalPlan |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java | {
"start": 65689,
"end": 68139
} | class ____ {
/**
* Sets the {@link ReactiveSessionRegistry} to use.
* @param reactiveSessionRegistry the {@link ReactiveSessionRegistry} to use
* @return the {@link ConcurrentSessionsSpec} to continue customizing
*/
public ConcurrentSessionsSpec sessionRegistry(ReactiveSessionRegistry reactiveSessionRegistry) {
SessionManagementSpec.this.sessionRegistry = reactiveSessionRegistry;
return this;
}
/**
* Sets the maximum number of sessions allowed for any user. You can use
* {@link SessionLimit#of(int)} to specify a positive integer or
* {@link SessionLimit#UNLIMITED} to allow unlimited sessions. To customize
* the maximum number of sessions on a per-user basis, you can provide a
* custom {@link SessionLimit} implementation, like so: <pre>
* http
* .sessionManagement((sessions) -> sessions
* .concurrentSessions((concurrency) -> concurrency
* .maximumSessions((authentication) -> {
* if (authentication.getName().equals("admin")) {
* return Mono.empty() // unlimited sessions for admin
* }
* return Mono.just(1); // one session for every other user
* })
* )
* )
* </pre>
* @param sessionLimit the maximum number of sessions allowed for any user
* @return the {@link ConcurrentSessionsSpec} to continue customizing
*/
public ConcurrentSessionsSpec maximumSessions(SessionLimit sessionLimit) {
Assert.notNull(sessionLimit, "sessionLimit cannot be null");
SessionManagementSpec.this.sessionLimit = sessionLimit;
return this;
}
/**
* Sets the {@link ServerMaximumSessionsExceededHandler} to use when the
* maximum number of sessions is exceeded.
* @param maximumSessionsExceededHandler the
* {@link ServerMaximumSessionsExceededHandler} to use
* @return the {@link ConcurrentSessionsSpec} to continue customizing
*/
public ConcurrentSessionsSpec maximumSessionsExceededHandler(
ServerMaximumSessionsExceededHandler maximumSessionsExceededHandler) {
Assert.notNull(maximumSessionsExceededHandler, "maximumSessionsExceededHandler cannot be null");
SessionManagementSpec.this.maximumSessionsExceededHandler = maximumSessionsExceededHandler;
return this;
}
}
private static final | ConcurrentSessionsSpec |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/env/CommandLinePropertySource.java | {
"start": 828,
"end": 2225
} | class ____ {@link PropertySource} implementations backed by command line
* arguments. The parameterized type {@code T} represents the underlying source of command
* line options.
*
* <h3>Purpose and General Usage</h3>
*
* For use in standalone Spring-based applications, i.e. those that are bootstrapped via
* a traditional {@code main} method accepting a {@code String[]} of arguments from the
* command line. In many cases, processing command-line arguments directly within the
* {@code main} method may be sufficient, but in other cases, it may be desirable to
* inject arguments as values into Spring beans. It is this latter set of cases in which
* a {@code CommandLinePropertySource} becomes useful. A {@code CommandLinePropertySource}
* will typically be added to the {@link Environment} of the Spring
* {@code ApplicationContext}, at which point all command line arguments become available
* through the {@link Environment#getProperty(String)} family of methods. For example:
*
* <pre class="code">
* public static void main(String[] args) {
* CommandLinePropertySource clps = ...;
* AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
* ctx.getEnvironment().getPropertySources().addFirst(clps);
* ctx.register(AppConfig.class);
* ctx.refresh();
* }</pre>
*
* With the bootstrap logic above, the {@code AppConfig} | for |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/operators/StreamSourceOperatorWatermarksTest.java | {
"start": 6048,
"end": 6253
} | class ____<T> extends RichSourceFunction<T> {
@Override
public void run(SourceContext<T> ctx) {}
@Override
public void cancel() {}
}
private static final | FiniteSource |
java | apache__camel | components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConstants.java | {
"start": 898,
"end": 4978
} | class ____ {
@Metadata(label = "producer", description = "Explicitly specify the partition", javaType = "Integer")
public static final String PARTITION_KEY = "kafka.PARTITION_KEY";
@Metadata(label = "consumer", description = "The partition where the message was stored", javaType = "Integer",
important = true)
public static final String PARTITION = "kafka.PARTITION";
@Metadata(description = "Producer: The key of the message in order to ensure that all related message goes in the same partition. "
+ "Consumer: The key of the message if configured",
javaType = "Object", required = true, important = true)
public static final String KEY = "kafka.KEY";
@Metadata(label = "consumer", description = "The topic from where the message originated", javaType = "String",
important = true)
public static final String TOPIC = "kafka.TOPIC";
@Metadata(label = "producer",
description = "The topic to which send the message (override and takes precedence), and the header is not preserved.",
javaType = "String")
public static final String OVERRIDE_TOPIC = "kafka.OVERRIDE_TOPIC";
@Metadata(label = "consumer", description = "The offset of the message", javaType = "Long", important = true)
public static final String OFFSET = "kafka.OFFSET";
@Metadata(label = "consumer", description = "The record headers", javaType = "org.apache.kafka.common.header.Headers")
public static final String HEADERS = "kafka.HEADERS";
@Metadata(label = "consumer",
description = "Whether or not it's the last record before commit (only available if `autoCommitEnable` endpoint parameter is `false`)",
javaType = "Boolean")
public static final String LAST_RECORD_BEFORE_COMMIT = "kafka.LAST_RECORD_BEFORE_COMMIT";
@Metadata(label = "consumer", description = "Indicates the last record within the current poll request " +
"(only available if `autoCommitEnable` endpoint parameter is `false` or `allowManualCommit` is `true`)",
javaType = "Boolean")
public static final String LAST_POLL_RECORD = "kafka.LAST_POLL_RECORD";
@Metadata(label = "consumer", description = "The timestamp of the message", javaType = "Long")
public static final String TIMESTAMP = "kafka.TIMESTAMP";
@Metadata(label = "producer", description = "The ProducerRecord also has an associated timestamp. " +
"If the user did provide a timestamp, the producer will stamp the record with the provided timestamp and the header is not preserved.",
javaType = "Long")
public static final String OVERRIDE_TIMESTAMP = "kafka.OVERRIDE_TIMESTAMP";
@Deprecated
public static final String KAFKA_DEFAULT_ENCODER = "kafka.serializer.DefaultEncoder";
@Deprecated
public static final String KAFKA_STRING_ENCODER = "kafka.serializer.StringEncoder";
public static final String KAFKA_DEFAULT_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer";
public static final String KAFKA_DEFAULT_DESERIALIZER = "org.apache.kafka.common.serialization.StringDeserializer";
public static final String PARTITIONER_RANGE_ASSIGNOR = "org.apache.kafka.clients.consumer.RangeAssignor";
@Metadata(label = "producer",
description = "The metadata (only configured if `recordMetadata` endpoint parameter is `true`)",
javaType = "List<RecordMetadata>")
public static final String KAFKA_RECORD_META = "kafka.RECORD_META";
@Metadata(label = "consumer", description = "Can be used for forcing manual offset commit when using Kafka consumer.",
javaType = "org.apache.camel.component.kafka.consumer.KafkaManualCommit")
public static final String MANUAL_COMMIT = "CamelKafkaManualCommit";
public static final String KAFKA_SUBSCRIBE_ADAPTER = "subscribeAdapter";
private KafkaConstants() {
// Utility class
}
}
| KafkaConstants |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java | {
"start": 10234,
"end": 11410
} | class ____ implements DeferredResultProcessingInterceptor {
@Override
public <S> boolean handleTimeout(NativeWebRequest request, DeferredResult<S> result) {
boolean continueProcessing = true;
try {
if (timeoutCallback != null) {
timeoutCallback.run();
}
}
finally {
Object value = timeoutResult.get();
if (value != RESULT_NONE) {
continueProcessing = false;
try {
setResultInternal(value);
}
catch (Throwable ex) {
logger.debug("Failed to handle timeout result", ex);
}
}
}
return continueProcessing;
}
@Override
public <S> boolean handleError(NativeWebRequest request, DeferredResult<S> result, Throwable t) {
try {
if (errorCallback != null) {
errorCallback.accept(t);
}
}
finally {
try {
setResultInternal(t);
}
catch (Throwable ex) {
logger.debug("Failed to handle error result", ex);
}
}
return false;
}
@Override
public <S> void afterCompletion(NativeWebRequest request, DeferredResult<S> result) {
expired = true;
if (completionCallback != null) {
completionCallback.run();
}
}
}
}
| LifecycleInterceptor |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Email.java | {
"start": 1365,
"end": 9466
} | class ____ implements ToXContentObject {
private static final DateFormatter DATE_TIME_FORMATTER = DateFormatter.forPattern("strict_date_time").withZone(ZoneOffset.UTC);
final String id;
final Address from;
final AddressList replyTo;
final Priority priority;
final ZonedDateTime sentDate;
final AddressList to;
final AddressList cc;
final AddressList bcc;
final String subject;
final String textBody;
final String htmlBody;
final Map<String, Attachment> attachments;
public Email(
String id,
Address from,
AddressList replyTo,
Priority priority,
ZonedDateTime sentDate,
AddressList to,
AddressList cc,
AddressList bcc,
String subject,
String textBody,
String htmlBody,
Map<String, Attachment> attachments
) {
this.id = id;
this.from = from;
this.replyTo = replyTo;
this.priority = priority;
this.sentDate = sentDate != null ? sentDate : ZonedDateTime.now(ZoneOffset.UTC);
this.to = to;
this.cc = cc;
this.bcc = bcc;
this.subject = subject;
this.textBody = textBody;
this.htmlBody = htmlBody;
this.attachments = attachments;
}
public String id() {
return id;
}
public Address from() {
return from;
}
public AddressList replyTo() {
return replyTo;
}
public Priority priority() {
return priority;
}
public ZonedDateTime sentDate() {
return sentDate;
}
public AddressList to() {
return to;
}
public AddressList cc() {
return cc;
}
public AddressList bcc() {
return bcc;
}
public String subject() {
return subject;
}
public String textBody() {
return textBody;
}
public String htmlBody() {
return htmlBody;
}
public Map<String, Attachment> attachments() {
return attachments;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Field.ID.getPreferredName(), id);
if (from != null) {
builder.field(Field.FROM.getPreferredName(), from.toUnicodeString());
}
if (replyTo != null) {
builder.field(Field.REPLY_TO.getPreferredName(), replyTo, params);
}
if (priority != null) {
builder.field(Field.PRIORITY.getPreferredName(), priority.value());
}
builder.timestampField(Field.SENT_DATE.getPreferredName(), sentDate);
if (to != null) {
builder.field(Field.TO.getPreferredName(), to, params);
}
if (cc != null) {
builder.field(Field.CC.getPreferredName(), cc, params);
}
if (bcc != null) {
builder.field(Field.BCC.getPreferredName(), bcc, params);
}
builder.field(Field.SUBJECT.getPreferredName(), subject);
if (textBody != null || htmlBody != null) {
builder.startObject(Field.BODY.getPreferredName());
if (textBody != null) {
builder.field(Field.BODY_TEXT.getPreferredName(), textBody);
}
if (htmlBody != null) {
builder.field(Field.BODY_HTML.getPreferredName(), htmlBody);
}
builder.endObject();
}
return builder.endObject();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Email email = (Email) o;
if (id.equals(email.id) == false) return false;
return true;
}
@Override
public int hashCode() {
return id.hashCode();
}
public static Builder builder() {
return new Builder();
}
public static Email parse(XContentParser parser) throws IOException {
Builder email = new Builder();
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if ((token.isValue() || token == XContentParser.Token.START_OBJECT || token == XContentParser.Token.START_ARRAY)
&& currentFieldName != null) {
if (Field.ID.match(currentFieldName, parser.getDeprecationHandler())) {
email.id(parser.text());
} else if (Field.FROM.match(currentFieldName, parser.getDeprecationHandler())) {
email.from(Address.parse(currentFieldName, token, parser));
} else if (Field.REPLY_TO.match(currentFieldName, parser.getDeprecationHandler())) {
email.replyTo(AddressList.parse(currentFieldName, token, parser));
} else if (Field.TO.match(currentFieldName, parser.getDeprecationHandler())) {
email.to(AddressList.parse(currentFieldName, token, parser));
} else if (Field.CC.match(currentFieldName, parser.getDeprecationHandler())) {
email.cc(AddressList.parse(currentFieldName, token, parser));
} else if (Field.BCC.match(currentFieldName, parser.getDeprecationHandler())) {
email.bcc(AddressList.parse(currentFieldName, token, parser));
} else if (Field.PRIORITY.match(currentFieldName, parser.getDeprecationHandler())) {
email.priority(Email.Priority.resolve(parser.text()));
} else if (Field.SENT_DATE.match(currentFieldName, parser.getDeprecationHandler())) {
email.sentDate(DateFormatters.from(DATE_TIME_FORMATTER.parse(parser.text())));
} else if (Field.SUBJECT.match(currentFieldName, parser.getDeprecationHandler())) {
email.subject(parser.text());
} else if (Field.BODY.match(currentFieldName, parser.getDeprecationHandler())) {
String bodyField = currentFieldName;
if (parser.currentToken() == XContentParser.Token.VALUE_STRING) {
email.textBody(parser.text());
} else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (currentFieldName == null) {
throw new ElasticsearchParseException("could not parse email. empty [{}] field", bodyField);
} else if (Email.Field.BODY_TEXT.match(currentFieldName, parser.getDeprecationHandler())) {
email.textBody(parser.text());
} else if (Email.Field.BODY_HTML.match(currentFieldName, parser.getDeprecationHandler())) {
email.htmlBody(parser.text());
} else {
throw new ElasticsearchParseException(
"could not parse email. unexpected field [{}.{}] field",
bodyField,
currentFieldName
);
}
}
}
} else {
throw new ElasticsearchParseException("could not parse email. unexpected field [{}]", currentFieldName);
}
}
}
return email.build();
}
public static | Email |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/loading/WeightLoadable.java | {
"start": 1162,
"end": 1710
} | interface ____ {
/**
* Get the loading weight.
*
* @return An implementation object of {@link LoadingWeight}.
*/
@Nonnull
LoadingWeight getLoading();
static <T extends WeightLoadable> List<T> sortByLoadingDescend(Collection<T> weightLoadables) {
return weightLoadables.stream()
.sorted(
(leftReq, rightReq) ->
rightReq.getLoading().compareTo(leftReq.getLoading()))
.collect(Collectors.toList());
}
}
| WeightLoadable |
java | micronaut-projects__micronaut-core | inject-java/src/main/java/io/micronaut/annotation/processing/JavaNativeElementsHelper.java | {
"start": 1406,
"end": 3723
} | class ____ extends NativeElementsHelper<TypeElement, ExecutableElement> {
private final Elements elementUtils;
private final Types typeUtils;
public JavaNativeElementsHelper(Elements elementUtils, Types typeUtils) {
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
public Collection<ExecutableElement> findOverriddenMethods(ExecutableElement methodElement) {
return findOverriddenMethods((TypeElement) methodElement.getEnclosingElement(), methodElement);
}
@Override
protected boolean overrides(ExecutableElement m1, ExecutableElement m2, TypeElement typeElement) {
return elementUtils.overrides(m1, m2, typeElement);
}
@NonNull
@Override
protected String getMethodName(ExecutableElement element) {
return element.getSimpleName().toString();
}
@Override
protected TypeElement getSuperClass(TypeElement classNode) {
TypeMirror superclass = classNode.getSuperclass();
if (superclass.getKind() == TypeKind.NONE) {
return null;
}
DeclaredType kind = (DeclaredType) superclass;
return (TypeElement) kind.asElement();
}
@NonNull
@Override
protected Collection<TypeElement> getInterfaces(TypeElement classNode) {
List<? extends TypeMirror> interfacesMirrors = classNode.getInterfaces();
var interfaces = new ArrayList<TypeElement>(interfacesMirrors.size());
for (TypeMirror anInterface : interfacesMirrors) {
final Element e = typeUtils.asElement(anInterface);
if (e instanceof TypeElement te) {
interfaces.add(te);
}
}
return interfaces;
}
@NonNull
@Override
protected List<ExecutableElement> getMethods(TypeElement classNode) {
return ElementFilter.methodsIn(classNode.getEnclosedElements());
}
@Override
protected boolean excludeClass(TypeElement classNode) {
return classNode.getQualifiedName().toString().equals(Object.class.getName())
|| classNode.getQualifiedName().toString().equals(Enum.class.getName());
}
@Override
protected boolean isInterface(TypeElement classNode) {
return classNode.getKind() == ElementKind.INTERFACE;
}
}
| JavaNativeElementsHelper |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/ExponentiallyWeightedMovingAverage.java | {
"start": 665,
"end": 716
} | class ____ safe to share between threads.
*/
public | is |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/reflection/typeparam/Level2Mapper.java | {
"start": 759,
"end": 857
} | interface ____ extends Level1Mapper<Date, Integer>, Serializable, Comparable<Integer> {
}
| Level2Mapper |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/userguide/util/GetIdentifierTest.java | {
"start": 705,
"end": 3381
} | class ____ {
@AfterEach
public void tearDown(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
}
@Test
public void testSimpleId(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Book book = new Book();
entityManager.persist( book );
entityManager.flush();
assertEquals( book.getId(), entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( book ) );
} );
}
@Test
@JiraKey(value = "HHH-7561")
public void testProxyObject(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Book book = new Book();
entityManager.persist( book );
entityManager.flush();
entityManager.clear(); // Clear persistence context to receive proxy object below.
Book proxy = entityManager.getReference( Book.class, book.getId() );
assertInstanceOf( HibernateProxy.class, proxy );
assertEquals( book.getId(), entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( proxy ) );
} );
scope.inTransaction( entityManager -> {
Author author = new Author();
Article article = new Article( author );
entityManager.persist( author );
entityManager.persist( article );
entityManager.flush();
entityManager.clear(); // Clear persistence context to receive proxy relation below.
article = entityManager.find( Article.class, article.getId() );
assertInstanceOf( HibernateProxy.class, article.getAuthor() );
assertEquals(
author.getId(),
entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( article.getAuthor() )
);
} );
}
@Test
public void testEmbeddedId(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Umbrella umbrella = new Umbrella();
umbrella.setId( new Umbrella.PK() );
umbrella.getId().setBrand( "Burberry" );
umbrella.getId().setModel( "Red Hat" );
entityManager.persist( umbrella );
entityManager.flush();
assertEquals(
umbrella.getId(),
entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( umbrella )
);
} );
}
@Test
public void testIdClass(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Sickness sick = new Sickness();
sick.setClassification( "H1N1" );
sick.setType( "Flu" );
entityManager.persist( sick );
entityManager.flush();
Sickness.PK id = new Sickness.PK();
id.setClassification( sick.getClassification() );
id.setType( sick.getType() );
assertEquals( id, entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( sick ) );
} );
}
}
| GetIdentifierTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/DateQueryParameterTest.java | {
"start": 2501,
"end": 2837
} | class ____ {
@Id
@GeneratedValue
private Integer id;
private Date timestamp;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
}
| DateEntity |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/tokenizers/WordPieceAnalyzer.java | {
"start": 585,
"end": 2669
} | class ____ extends Analyzer {
private final List<String> vocabulary;
private final List<String> neverSplit;
private final boolean doLowerCase;
private final boolean doTokenizeCjKChars;
private final boolean doStripAccents;
private WordPieceTokenFilter innerTokenFilter;
private final String unknownToken;
public WordPieceAnalyzer(
List<String> vocabulary,
List<String> neverSplit,
boolean doLowerCase,
boolean doTokenizeCjKChars,
boolean doStripAccents,
String unknownToken
) {
this.vocabulary = vocabulary;
this.neverSplit = neverSplit;
this.doLowerCase = doLowerCase;
this.doTokenizeCjKChars = doTokenizeCjKChars;
this.doStripAccents = doStripAccents;
this.unknownToken = unknownToken;
}
protected Tokenizer createTokenizer() {
return new WhitespaceTokenizer(512);
}
@Override
protected TokenStreamComponents createComponents(String fieldName) {
try {
Tokenizer tokenizer = createTokenizer();
innerTokenFilter = WordPieceTokenFilter.build(
doLowerCase,
doTokenizeCjKChars,
doStripAccents,
neverSplit,
vocabulary,
unknownToken,
100,
tokenizer
);
return new TokenStreamComponents(tokenizer, innerTokenFilter);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public List<WordPieceTokenFilter.WordPieceToken> getTokens() {
if (innerTokenFilter != null) {
return innerTokenFilter.getTokenizedValues();
} else {
return List.of();
}
}
@Override
protected Reader initReader(String fieldName, Reader reader) {
return new ControlCharFilter(reader);
}
@Override
protected Reader initReaderForNormalization(String fieldName, Reader reader) {
return new ControlCharFilter(reader);
}
}
| WordPieceAnalyzer |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java | {
"start": 26441,
"end": 26611
} | class ____ extends DevConfig {
@Bean
public Object derivedDevBean() {
return new Object();
}
}
@Profile("(p1 & p2) | p3")
@Configuration
static | DerivedDevConfig |
java | google__guava | android/guava/src/com/google/common/util/concurrent/InterruptibleTask.java | {
"start": 2082,
"end": 9123
} | class ____ implements Runnable {
@Override
public void run() {}
}
// The thread executing the task publishes itself to the superclass' reference and the thread
// interrupting sets DONE when it has finished interrupting.
private static final Runnable DONE = new DoNothingRunnable();
private static final Runnable PARKED = new DoNothingRunnable();
// Why 1000? WHY NOT!
private static final int MAX_BUSY_WAIT_SPINS = 1000;
@Override
public final void run() {
/*
* Set runner thread before checking isDone(). If we were to check isDone() first, the task
* might be cancelled before we set the runner thread. That would make it impossible to
* interrupt, yet it will still run, since interruptTask will leave the runner value null,
* allowing the CAS below to succeed.
*/
Thread currentThread = Thread.currentThread();
if (!compareAndSet(null, currentThread)) {
return; // someone else has run or is running.
}
boolean run = !isDone();
T result = null;
Throwable error = null;
try {
if (run) {
result = runInterruptibly();
}
} catch (Throwable t) {
restoreInterruptIfIsInterruptedException(t);
error = t;
} finally {
// Attempt to set the task as done so that further attempts to interrupt will fail.
if (!compareAndSet(currentThread, DONE)) {
waitForInterrupt(currentThread);
}
if (run) {
if (error == null) {
// The cast is safe because of the `run` and `error` checks.
afterRanInterruptiblySuccess(uncheckedCastNullableTToT(result));
} else {
afterRanInterruptiblyFailure(error);
}
}
}
}
@SuppressWarnings({
"Interruption", // We are restoring an interrupt on this thread.
"ThreadPriorityCheck", // TODO: b/175898629 - Consider onSpinWait.
})
private void waitForInterrupt(Thread currentThread) {
/*
* If someone called cancel(true), it is possible that the interrupted bit hasn't been set yet.
* Wait for the interrupting thread to set DONE. (See interruptTask().) We want to wait so that
* the interrupting thread doesn't interrupt the _next_ thing to run on this thread.
*
* Note: We don't reset the interrupted bit, just wait for it to be set. If this is a thread
* pool thread, the thread pool will reset it for us. Otherwise, the interrupted bit may have
* been intended for something else, so don't clear it.
*/
boolean restoreInterruptedBit = false;
int spinCount = 0;
// Interrupting Cow Says:
// ______
// < Spin >
// ------
// \ ^__^
// \ (oo)\_______
// (__)\ )\/\
// ||----w |
// || ||
Runnable state = get();
Blocker blocker = null;
while (state instanceof Blocker || state == PARKED) {
if (state instanceof Blocker) {
blocker = (Blocker) state;
}
spinCount++;
if (spinCount > MAX_BUSY_WAIT_SPINS) {
/*
* If we have spun a lot, just park ourselves. This will save CPU while we wait for a slow
* interrupting thread. In theory, interruptTask() should be very fast, but due to
* InterruptibleChannel and JavaLangAccess.blockedOn(Thread, Interruptible), it isn't
* predictable what work might be done. (e.g., close a file and flush buffers to disk). To
* protect ourselves from this, we park ourselves and tell our interrupter that we did so.
*/
if (state == PARKED || compareAndSet(state, PARKED)) {
// Interrupting Cow Says:
// ______
// < Park >
// ------
// \ ^__^
// \ (oo)\_______
// (__)\ )\/\
// ||----w |
// || ||
// We need to clear the interrupted bit prior to calling park and maintain it in case we
// wake up spuriously.
restoreInterruptedBit = Thread.interrupted() || restoreInterruptedBit;
LockSupport.park(blocker);
}
} else {
Thread.yield();
}
state = get();
}
if (restoreInterruptedBit) {
currentThread.interrupt();
}
/*
* TODO(cpovirk): Clear interrupt status here? We currently don't, which means that an interrupt
* before, during, or after runInterruptibly() (unless it produced an InterruptedException
* caught above) can linger and affect listeners.
*/
}
/**
* Called before runInterruptibly - if true, runInterruptibly and afterRanInterruptibly will not
* be called.
*/
abstract boolean isDone();
/**
* Do interruptible work here - do not complete Futures here, as their listeners could be
* interrupted.
*/
@ParametricNullness
abstract T runInterruptibly() throws Exception;
/**
* Any interruption that happens as a result of calling interruptTask will arrive before this
* method is called. Complete Futures here.
*/
abstract void afterRanInterruptiblySuccess(@ParametricNullness T result);
/**
* Any interruption that happens as a result of calling interruptTask will arrive before this
* method is called. Complete Futures here.
*/
abstract void afterRanInterruptiblyFailure(Throwable error);
/**
* Interrupts the running task. Because this internally calls {@link Thread#interrupt()} which can
* in turn invoke arbitrary code it is not safe to call while holding a lock.
*/
@SuppressWarnings("Interruption") // We are implementing a user-requested interrupt.
final void interruptTask() {
// Since the Thread is replaced by DONE before run() invokes listeners or returns, if we succeed
// in this CAS, there's no risk of interrupting the wrong thread or interrupting a thread that
// isn't currently executing this task.
Runnable currentRunner = get();
if (currentRunner instanceof Thread) {
Blocker blocker = new Blocker(this);
blocker.setOwner(Thread.currentThread());
if (compareAndSet(currentRunner, blocker)) {
// Thread.interrupt can throw arbitrary exceptions due to the nio InterruptibleChannel API
// This will make sure that tasks don't get stuck busy waiting.
// Some of this is fixed in jdk11 (see https://bugs.openjdk.org/browse/JDK-8198692) but
// not all. See the test cases for examples on how this can happen.
try {
((Thread) currentRunner).interrupt();
} finally {
Runnable prev = getAndSet(DONE);
if (prev == PARKED) {
LockSupport.unpark((Thread) currentRunner);
}
}
}
}
}
/**
* Using this as the blocker object allows introspection and debugging tools to see that the
* currentRunner thread is blocked on the progress of the interruptor thread, which can help
* identify deadlocks.
*/
@VisibleForTesting
static final | DoNothingRunnable |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestStat.java | {
"start": 1700,
"end": 5598
} | class ____ {
final String doesNotExist;
final String directory;
final String file;
final String[] symlinks;
final String stickydir;
StatOutput(String doesNotExist, String directory, String file,
String[] symlinks, String stickydir) {
this.doesNotExist = doesNotExist;
this.directory = directory;
this.file = file;
this.symlinks = symlinks;
this.stickydir = stickydir;
}
void test() throws Exception {
BufferedReader br;
FileStatus status;
try {
br = new BufferedReader(new StringReader(doesNotExist));
stat.parseExecResult(br);
} catch (FileNotFoundException e) {
// expected
}
br = new BufferedReader(new StringReader(directory));
stat.parseExecResult(br);
status = stat.getFileStatusForTesting();
assertTrue(status.isDirectory());
br = new BufferedReader(new StringReader(file));
stat.parseExecResult(br);
status = stat.getFileStatusForTesting();
assertTrue(status.isFile());
for (String symlink : symlinks) {
br = new BufferedReader(new StringReader(symlink));
stat.parseExecResult(br);
status = stat.getFileStatusForTesting();
assertTrue(status.isSymlink());
}
br = new BufferedReader(new StringReader(stickydir));
stat.parseExecResult(br);
status = stat.getFileStatusForTesting();
assertTrue(status.isDirectory());
assertTrue(status.getPermission().getStickyBit());
}
}
@Test
@Timeout(value = 10)
public void testStatLinux() throws Exception {
String[] symlinks = new String[] {
"6,symbolic link,1373584236,1373584236,777,andrew,andrew,`link' -> `target'",
"6,symbolic link,1373584236,1373584236,777,andrew,andrew,'link' -> 'target'"
};
StatOutput linux = new StatOutput(
"stat: cannot stat `watermelon': No such file or directory",
"4096,directory,1373584236,1373586485,755,andrew,root,`.'",
"0,regular empty file,1373584228,1373584228,644,andrew,andrew,`target'",
symlinks,
"4096,directory,1374622334,1375124212,1755,andrew,andrew,`stickydir'");
linux.test();
}
@Test
@Timeout(value = 10)
public void testStatFreeBSD() throws Exception {
String[] symlinks = new String[] {
"6,Symbolic Link,1373508941,1373508941,120755,awang,awang,`link' -> `target'"
};
StatOutput freebsd = new StatOutput(
"stat: symtest/link: stat: No such file or directory",
"512,Directory,1373583695,1373583669,40755,awang,awang,`link' -> `'",
"0,Regular File,1373508937,1373508937,100644,awang,awang,`link' -> `'",
symlinks,
"512,Directory,1375139537,1375139537,41755,awang,awang,`link' -> `'");
freebsd.test();
}
@Test
@Timeout(value = 10)
public void testStatFileNotFound() throws Exception {
assumeTrue(Stat.isAvailable());
try {
stat.getFileStatus();
fail("Expected FileNotFoundException");
} catch (FileNotFoundException e) {
// expected
}
}
@Test
@Timeout(value = 10)
public void testStatEnvironment() throws Exception {
assertEquals("C", stat.getEnvironment("LANG"));
}
@Test
@Timeout(value = 10)
public void testStat() throws Exception {
assumeTrue(Stat.isAvailable());
FileSystem fs = FileSystem.getLocal(new Configuration());
Path testDir = new Path(getTestRootPath(fs), "teststat");
fs.mkdirs(testDir);
Path sub1 = new Path(testDir, "sub1");
Path sub2 = new Path(testDir, "sub2");
fs.mkdirs(sub1);
fs.createSymlink(sub1, sub2, false);
FileStatus stat1 = new Stat(sub1, 4096l, false, fs).getFileStatus();
FileStatus stat2 = new Stat(sub2, 0, false, fs).getFileStatus();
assertTrue(stat1.isDirectory());
assertFalse(stat2.isDirectory());
fs.delete(testDir, true);
}
}
| StatOutput |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/annotation/FunctionHint.java | {
"start": 4065,
"end": 4237
} | class ____ extends ScalarFunction {
* Row eval(int i) { ... }
* Row eval(boolean b) { ... }
* }
*
* // accepts (ROW<f BOOLEAN>...) or (BOOLEAN...) and returns INT
* | X |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/util/constraint/PlacementConstraintParser.java | {
"start": 20428,
"end": 27205
} | class ____ {
private String tag;
private int num;
private SourceTags(String sourceTag, int number) {
this.tag = sourceTag;
this.num = number;
}
public static SourceTags emptySourceTags() {
return new SourceTags("", 0);
}
public boolean isEmpty() {
return Strings.isNullOrEmpty(tag) && num == 0;
}
public String getTag() {
return this.tag;
}
public int getNumOfAllocations() {
return this.num;
}
/**
* Parses source tags from expression "sourceTags(numOfAllocations)".
* @param expr expression string.
* @return source tags, see {@link SourceTags}
* @throws PlacementConstraintParseException when the placement constraint parser
* fails to parse an expression.
*/
public static SourceTags parseFrom(String expr)
throws PlacementConstraintParseException {
SourceTagsTokenizer stt = new SourceTagsTokenizer(expr);
stt.validate();
// During validation we already checked the number of parsed elements.
String allocTag = stt.nextElement();
int allocNum = Integer.parseInt(stt.nextElement());
return new SourceTags(allocTag, allocNum);
}
}
/**
* Parses a given constraint expression to a {@link AbstractConstraint},
* this expression can be any valid form of constraint expressions.
*
* @param constraintStr expression string
* @return a parsed {@link AbstractConstraint}
* @throws PlacementConstraintParseException when given expression
* is malformed
*/
public static AbstractConstraint parseExpression(String constraintStr)
throws PlacementConstraintParseException {
// Try parse given expression with all allowed constraint parsers,
// fails if no one could parse it.
TargetConstraintParser tp = new TargetConstraintParser(constraintStr);
Optional<AbstractConstraint> constraintOptional =
Optional.ofNullable(tp.tryParse());
if (!constraintOptional.isPresent()) {
CardinalityConstraintParser cp =
new CardinalityConstraintParser(constraintStr);
constraintOptional = Optional.ofNullable(cp.tryParse());
if (!constraintOptional.isPresent()) {
ConjunctionConstraintParser jp =
new ConjunctionConstraintParser(constraintStr);
constraintOptional = Optional.ofNullable(jp.tryParse());
}
if (!constraintOptional.isPresent()) {
NodeConstraintParser np =
new NodeConstraintParser(constraintStr);
constraintOptional = Optional.ofNullable(np.tryParse());
}
if (!constraintOptional.isPresent()) {
throw new PlacementConstraintParseException(
"Invalid constraint expression " + constraintStr);
}
}
return constraintOptional.get();
}
/**
* Parses a placement constraint specification. A placement constraint spec
* is a composite expression which is composed by multiple sub constraint
* expressions delimited by ":". With following syntax:
*
* <p>Tag1(N1),P1:Tag2(N2),P2:...:TagN(Nn),Pn</p>
*
* where <b>TagN(Nn)</b> is a key value pair to determine the source
* allocation tag and the number of allocations, such as:
*
* <p>foo(3)</p>
*
* Optional when using NodeAttribute Constraint.
*
* and where <b>Pn</b> can be any form of a valid constraint expression,
* such as:
*
* <ul>
* <li>in,node,foo,bar</li>
* <li>notin,node,foo,bar,1,2</li>
* <li>and(notin,node,foo:notin,node,bar)</li>
* </ul>
*
* and NodeAttribute Constraint such as
*
* <ul>
* <li>yarn.rm.io/foo=true</li>
* <li>java=1.7,1.8</li>
* </ul>
* @param expression expression string.
* @return a map of source tags to placement constraint mapping.
* @throws PlacementConstraintParseException when the placement constraint parser
* fails to parse an expression.
*/
public static Map<SourceTags, PlacementConstraint> parsePlacementSpec(
String expression) throws PlacementConstraintParseException {
// Continue handling for application tag based constraint otherwise.
// Respect insertion order.
Map<SourceTags, PlacementConstraint> result = new LinkedHashMap<>();
PlacementConstraintParser.ConstraintTokenizer tokenizer =
new PlacementConstraintParser.MultipleConstraintsTokenizer(expression);
tokenizer.validate();
while (tokenizer.hasMoreElements()) {
String specStr = tokenizer.nextElement();
// each spec starts with sourceAllocationTag(numOfContainers) and
// followed by a constraint expression.
// foo(4),Pn
final SourceTags st;
PlacementConstraint constraint;
String delimiter = new String(new char[]{'[', BRACKET_END, ']',
EXPRESSION_VAL_DELIM});
String[] splitted = specStr.split(delimiter, 2);
if (splitted.length == 2) {
st = SourceTags.parseFrom(splitted[0] + String.valueOf(BRACKET_END));
constraint = PlacementConstraintParser.parseExpression(splitted[1]).
build();
} else if (splitted.length == 1) {
// Either Node Attribute Constraint or Source Allocation Tag alone
NodeConstraintParser np = new NodeConstraintParser(specStr);
Optional<AbstractConstraint> constraintOptional =
Optional.ofNullable(np.tryParse());
if (constraintOptional.isPresent()) {
st = SourceTags.emptySourceTags();
constraint = constraintOptional.get().build();
} else {
st = SourceTags.parseFrom(specStr);
constraint = null;
}
} else {
throw new PlacementConstraintParseException(
"Unexpected placement constraint expression " + specStr);
}
result.put(st, constraint);
}
// Validation
Set<SourceTags> sourceTagSet = result.keySet();
if (sourceTagSet.stream()
.filter(sourceTags -> sourceTags.isEmpty())
.findAny()
.isPresent()) {
// Source tags, e.g foo(3), is optional for a node-attribute constraint,
// but when source tags is absent, the parser only accept single
// constraint expression to avoid ambiguous semantic. This is because
// DS AM is requesting number of containers per the number specified
// in the source tags, we do overwrite when there is no source tags
// with num_containers argument from commandline. If that is partially
// missed in the constraints, we don't know if it is ought to
// overwritten or not.
if (result.size() != 1) {
throw new PlacementConstraintParseException(
"Source allocation tags is required for a multi placement"
+ " constraint expression.");
}
}
return result;
}
}
| SourceTags |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/source/event/IsProcessingBacklogEvent.java | {
"start": 1032,
"end": 2005
} | class ____ implements OperatorEvent {
private static final long serialVersionUID = 1L;
private final boolean isProcessingBacklog;
public IsProcessingBacklogEvent(boolean isProcessingBacklog) {
this.isProcessingBacklog = isProcessingBacklog;
}
public boolean isProcessingBacklog() {
return isProcessingBacklog;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final IsProcessingBacklogEvent that = (IsProcessingBacklogEvent) o;
return Objects.equals(isProcessingBacklog, that.isProcessingBacklog);
}
@Override
public int hashCode() {
return Objects.hash(isProcessingBacklog);
}
@Override
public String toString() {
return String.format("BacklogEvent (backlog='%s')", isProcessingBacklog);
}
}
| IsProcessingBacklogEvent |
java | apache__kafka | group-coordinator/src/main/java/org/apache/kafka/coordinator/group/classic/ClassicGroupMember.java | {
"start": 1406,
"end": 2336
} | class ____ a classic group member's metadata.
*
* Member metadata contains the following:
*
* Heartbeat metadata:
* 1. negotiated heartbeat session timeout
* 2. timestamp of the latest heartbeat
*
* Protocol metadata:
* 1. the list of supported protocols (ordered by preference)
* 2. the metadata associated with each protocol
*
* In addition, it also contains the following state information:
*
* 1. Awaiting rebalance future: when the group is in the prepare-rebalance state,
* its rebalance future will be kept in the metadata if the
* member has sent the join group request
* 2. Awaiting sync future: when the group is in the awaiting-sync state, its sync future
* is kept in metadata until the leader provides the group assignment
* and the group transitions to stable
*/
public | encapsulates |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/specification/UpdateSpecification.java | {
"start": 1224,
"end": 3196
} | interface ____<T> extends MutationSpecification<T> {
/**
* Add an assigment to a field or property of the target entity.
*
* @param assignment The assignment to add
*
* @return {@code this} for method chaining.
*/
UpdateSpecification<T> assign(Assignment<? super T> assignment);
/**
* Sets the assignments to fields or properties of the target entity.
* If assignments were already specified, this method drops the previous
* assignments in favor of the passed {@code assignments}.
*
* @param assignments The new assignments
*
* @return {@code this} for method chaining.
*/
UpdateSpecification<T> reassign(List<? extends Assignment<? super T>> assignments);
@Override
UpdateSpecification<T> restrict(Restriction<? super T> restriction);
@Override
UpdateSpecification<T> augment(Augmentation<T> augmentation);
@Override
UpdateSpecification<T> validate(CriteriaBuilder builder);
/**
* Returns a specification reference which can be used to programmatically,
* iteratively build a {@linkplain org.hibernate.query.MutationQuery} which
* updates the given entity type.
*
* @param targetEntityClass The target entity type
*
* @param <T> The root entity type for the mutation (the "target").
*/
static <T> UpdateSpecification<T> create(Class<T> targetEntityClass) {
return new UpdateSpecificationImpl<>( targetEntityClass );
}
/**
* Returns a specification reference which can be used to programmatically,
* iteratively build a {@linkplain org.hibernate.query.MutationQuery} based
* on the given criteria update, allowing the addition of
* {@linkplain #restrict restrictions} and {@linkplain #assign assignments}.
*
* @param criteriaUpdate The criteria update query
*
* @param <T> The root entity type for the mutation (the "target").
*/
static <T> UpdateSpecification<T> create(CriteriaUpdate<T> criteriaUpdate) {
return new UpdateSpecificationImpl<>( criteriaUpdate );
}
}
| UpdateSpecification |
java | apache__camel | test-infra/camel-test-infra-aws-v2/src/main/java/org/apache/camel/test/infra/aws2/clients/KinesisUtils.java | {
"start": 2670,
"end": 11567
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(KinesisUtils.class);
private KinesisUtils() {
}
private static void doCreateStream(KinesisClient kinesisClient, String streamName, int shardCount) {
CreateStreamRequest request = CreateStreamRequest.builder()
.streamName(streamName)
.shardCount(shardCount)
.build();
try {
CreateStreamResponse response = kinesisClient.createStream(request);
if (response.sdkHttpResponse().isSuccessful()) {
LOG.info("Stream created successfully");
} else {
// TODO How to fail without JUnit?
// fail("Failed to create the stream");
}
} catch (KinesisException e) {
LOG.error("Unable to create stream: {}", e.getMessage(), e);
// TODO How to fail without JUnit?
// fail("Unable to create stream");
}
}
public static void createStream(KinesisClient kinesisClient, String streamName) {
createStream(kinesisClient, streamName, 1);
}
public static void createStream(KinesisClient kinesisClient, String streamName, int shardCount) {
try {
LOG.info("Checking whether the stream exists already");
int status = getStreamStatus(kinesisClient, streamName);
LOG.info("Kinesis stream check result: {}", status);
} catch (KinesisException e) {
if (LOG.isTraceEnabled()) {
LOG.trace("The stream does not exist, auto creating it: {}", e.getMessage(), e);
} else {
LOG.info("The stream does not exist, auto creating it: {}", e.getMessage());
}
doCreateStream(kinesisClient, streamName, shardCount);
TestUtils.waitFor(() -> {
try {
GetRecordsRequest getRecordsRequest = KinesisUtils.getGetRecordsRequest(kinesisClient, streamName);
GetRecordsResponse response = kinesisClient.getRecords(getRecordsRequest);
List<Record> recordList = response.records();
LOG.debug("Checking for stream creation by reading {} records: SUCCESS!", recordList.size());
return true;
} catch (Exception exc) {
LOG.debug("Checking for stream creation by reading records: FAILURE, retrying..");
return false;
}
});
} catch (SdkClientException e) {
LOG.info("SDK Error when getting the stream: {}", e.getMessage());
}
}
private static int getStreamStatus(KinesisClient kinesisClient, String streamName) {
DescribeStreamRequest request = DescribeStreamRequest.builder()
.streamName(streamName)
.build();
DescribeStreamResponse response = kinesisClient.describeStream(request);
return response.sdkHttpResponse().statusCode();
}
public static void doDeleteStream(KinesisClient kinesisClient, String streamName) {
DeleteStreamRequest request = DeleteStreamRequest.builder()
.streamName(streamName)
.build();
DeleteStreamResponse response = kinesisClient.deleteStream(request);
if (response.sdkHttpResponse().isSuccessful()) {
LOG.info("Stream deleted successfully");
} else {
// TODO How to fail without JUnit?
// fail("Failed to delete the stream");
}
}
public static void deleteStream(KinesisClient kinesisClient, String streamName) {
try {
LOG.info("Checking whether the stream exists already");
DescribeStreamRequest request = DescribeStreamRequest.builder()
.streamName(streamName)
.build();
DescribeStreamResponse response = kinesisClient.describeStream(request);
if (response.sdkHttpResponse().isSuccessful()) {
LOG.info("Kinesis stream check result");
doDeleteStream(kinesisClient, streamName);
}
} catch (ResourceNotFoundException e) {
LOG.info("The stream does not exist, skipping deletion");
} catch (ResourceInUseException e) {
LOG.info("The stream exist but cannot be deleted because it's in use");
doDeleteStream(kinesisClient, streamName);
}
}
public static List<PutRecordsResponse> putRecords(KinesisClient kinesisClient, String streamName, int count) {
return putRecords(kinesisClient, streamName, count, null);
}
public static List<PutRecordsResponse> putRecords(
KinesisClient kinesisClient, String streamName, int count,
Consumer<PutRecordsRequest.Builder> customizer) {
List<PutRecordsRequestEntry> putRecordsRequestEntryList = new ArrayList<>();
LOG.debug("Adding data to the Kinesis stream");
for (int i = 0; i < count; i++) {
String partition = String.format("partitionKey-%d", i);
PutRecordsRequestEntry putRecordsRequestEntry = PutRecordsRequestEntry.builder()
.data(SdkBytes.fromByteArray(String.valueOf(i).getBytes()))
.partitionKey(partition)
.build();
LOG.debug("Added data {} (as bytes) to partition {}", i, partition);
putRecordsRequestEntryList.add(putRecordsRequestEntry);
}
LOG.debug("Done creating the data records");
final PutRecordsRequest.Builder requestBuilder = PutRecordsRequest
.builder();
requestBuilder
.streamName(streamName)
.records(putRecordsRequestEntryList);
if (customizer != null) {
customizer.accept(requestBuilder);
}
PutRecordsRequest putRecordsRequest = requestBuilder.build();
List<PutRecordsResponse> replies = new ArrayList<>(count);
int retries = 5;
do {
try {
replies.add(kinesisClient.putRecords(putRecordsRequest));
break;
} catch (AwsServiceException e) {
retries--;
/*
This works around the "... Cannot deserialize instance of `...AmazonKinesisException` out of NOT_AVAILABLE token
It may take some time for the local Kinesis backend to be fully up - even though the container is
reportedly up and running. Therefore, it tries a few more times
*/
LOG.trace("Failed to put the records: {}. Retrying in 2 seconds ...", e.getMessage());
if (retries == 0) {
LOG.error("Failed to put the records: {}", e.getMessage(), e);
throw e;
}
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
} catch (InterruptedException ex) {
break;
}
}
} while (retries > 0);
return replies;
}
private static boolean hasShards(KinesisClient kinesisClient, DescribeStreamRequest describeStreamRequest) {
DescribeStreamResponse streamRes = kinesisClient.describeStream(describeStreamRequest);
return !streamRes.streamDescription().shards().isEmpty();
}
private static List<Shard> getAllShards(KinesisClient kinesisClient, DescribeStreamRequest describeStreamRequest) {
List<Shard> shards = new ArrayList<>();
DescribeStreamResponse streamRes;
do {
streamRes = kinesisClient.describeStream(describeStreamRequest);
shards.addAll(streamRes.streamDescription().shards());
} while (streamRes.streamDescription().hasMoreShards());
return shards;
}
public static GetRecordsRequest getGetRecordsRequest(KinesisClient kinesisClient, String streamName) {
DescribeStreamRequest describeStreamRequest = DescribeStreamRequest.builder()
.streamName(streamName)
.build();
TestUtils.waitFor(() -> hasShards(kinesisClient, describeStreamRequest));
List<Shard> shards = getAllShards(kinesisClient, describeStreamRequest);
GetShardIteratorRequest iteratorRequest = GetShardIteratorRequest.builder()
.streamName(streamName)
.shardId(shards.get(0).shardId())
.shardIteratorType("TRIM_HORIZON")
.build();
GetShardIteratorResponse iteratorResponse = kinesisClient.getShardIterator(iteratorRequest);
return GetRecordsRequest
.builder()
.shardIterator(iteratorResponse.shardIterator())
.build();
}
}
| KinesisUtils |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/testers/TestExceptions.java | {
"start": 809,
"end": 858
} | class ____ extends Error {}
static final | SomeError |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/dynamic/DynMethods.java | {
"start": 12683,
"end": 13157
} | class ____ name.
* <p>
* The name passed to the constructor is the method name used.
* @param className name of a class
* @param argClasses argument classes for the method
* @return this Builder for method chaining
*/
public Builder hiddenImpl(String className, Class<?>... argClasses) {
hiddenImpl(className, name, argClasses);
return this;
}
/**
* Checks for a method implementation.
* @param targetClass the | by |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/dev/CompilationProvider.java | {
"start": 1500,
"end": 5944
} | class ____ {
private final String name;
private final Set<File> classpath;
private final Set<File> reloadableClasspath;
private final File projectDirectory;
private final File sourceDirectory;
private final File outputDirectory;
private final Charset sourceEncoding;
private final Map<String, Set<String>> compilerOptions;
private final String releaseJavaVersion;
private final String sourceJavaVersion;
private final String targetJvmVersion;
private final List<String> compilePluginArtifacts;
private final List<String> compilerPluginOptions;
private final boolean ignoreModuleInfo;
private final File generatedSourcesDirectory;
private final Set<File> annotationProcessorPaths;
private final List<String> annotationProcessors;
public Context(
String name,
Set<File> classpath,
Set<File> reloadableClasspath,
File projectDirectory,
File sourceDirectory,
File outputDirectory,
String sourceEncoding,
Map<String, Set<String>> compilerOptions,
String releaseJavaVersion,
String sourceJavaVersion,
String targetJvmVersion,
List<String> compilePluginArtifacts,
List<String> compilerPluginOptions,
File generatedSourcesDirectory,
Set<File> annotationProcessorPaths,
List<String> annotationProcessors,
String ignoreModuleInfo) {
this.name = name;
this.classpath = classpath;
this.reloadableClasspath = reloadableClasspath;
this.projectDirectory = projectDirectory;
this.sourceDirectory = sourceDirectory;
this.outputDirectory = outputDirectory;
this.sourceEncoding = sourceEncoding == null ? StandardCharsets.UTF_8 : Charset.forName(sourceEncoding);
this.compilerOptions = compilerOptions == null ? new HashMap<>() : compilerOptions;
this.releaseJavaVersion = releaseJavaVersion;
this.sourceJavaVersion = sourceJavaVersion;
this.targetJvmVersion = targetJvmVersion;
this.compilePluginArtifacts = compilePluginArtifacts;
this.compilerPluginOptions = compilerPluginOptions;
this.ignoreModuleInfo = Boolean.parseBoolean(ignoreModuleInfo);
this.generatedSourcesDirectory = generatedSourcesDirectory;
this.annotationProcessorPaths = annotationProcessorPaths;
this.annotationProcessors = annotationProcessors;
}
public String getName() {
return name;
}
public Set<File> getClasspath() {
return classpath;
}
public Set<File> getReloadableClasspath() {
return reloadableClasspath;
}
public Set<File> getAnnotationProcessorPaths() {
return annotationProcessorPaths;
}
public List<String> getAnnotationProcessors() {
return annotationProcessors;
}
public File getProjectDirectory() {
return projectDirectory;
}
public File getSourceDirectory() {
return sourceDirectory;
}
public File getOutputDirectory() {
return outputDirectory;
}
public Charset getSourceEncoding() {
return sourceEncoding;
}
public Set<String> getCompilerOptions(String key) {
return compilerOptions.getOrDefault(key, Collections.emptySet());
}
public String getReleaseJavaVersion() {
return releaseJavaVersion;
}
public String getSourceJavaVersion() {
return sourceJavaVersion;
}
public String getTargetJvmVersion() {
return targetJvmVersion;
}
public List<String> getCompilePluginArtifacts() {
return compilePluginArtifacts;
}
public List<String> getCompilerPluginOptions() {
return compilerPluginOptions;
}
public boolean ignoreModuleInfo() {
return ignoreModuleInfo;
}
public File getGeneratedSourcesDirectory() {
return generatedSourcesDirectory;
}
}
}
| Context |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/oauthbearer/internals/OAuthBearerSaslClient.java | {
"start": 2715,
"end": 7226
} | enum ____ {
SEND_CLIENT_FIRST_MESSAGE, RECEIVE_SERVER_FIRST_MESSAGE, RECEIVE_SERVER_MESSAGE_AFTER_FAILURE, COMPLETE, FAILED
}
private State state;
public OAuthBearerSaslClient(AuthenticateCallbackHandler callbackHandler) {
this.callbackHandler = Objects.requireNonNull(callbackHandler);
setState(State.SEND_CLIENT_FIRST_MESSAGE);
}
public CallbackHandler callbackHandler() {
return callbackHandler;
}
@Override
public String getMechanismName() {
return OAuthBearerLoginModule.OAUTHBEARER_MECHANISM;
}
@Override
public boolean hasInitialResponse() {
return true;
}
@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
try {
OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback();
switch (state) {
case SEND_CLIENT_FIRST_MESSAGE:
if (challenge != null && challenge.length != 0)
throw new SaslException("Expected empty challenge");
callbackHandler().handle(new Callback[] {callback});
SaslExtensions extensions = retrieveCustomExtensions();
setState(State.RECEIVE_SERVER_FIRST_MESSAGE);
return new OAuthBearerClientInitialResponse(callback.token().value(), extensions).toBytes();
case RECEIVE_SERVER_FIRST_MESSAGE:
if (challenge != null && challenge.length != 0) {
String jsonErrorResponse = new String(challenge, StandardCharsets.UTF_8);
if (log.isDebugEnabled())
log.debug("Sending %%x01 response to server after receiving an error: {}",
jsonErrorResponse);
setState(State.RECEIVE_SERVER_MESSAGE_AFTER_FAILURE);
return new byte[] {BYTE_CONTROL_A};
}
callbackHandler().handle(new Callback[] {callback});
if (log.isDebugEnabled())
log.debug("Successfully authenticated as {}", callback.token().principalName());
setState(State.COMPLETE);
return null;
default:
throw new IllegalSaslStateException("Unexpected challenge in Sasl client state " + state);
}
} catch (SaslException e) {
setState(State.FAILED);
throw e;
} catch (IOException | UnsupportedCallbackException e) {
setState(State.FAILED);
throw new SaslException(e.getMessage(), e);
}
}
@Override
public boolean isComplete() {
return state == State.COMPLETE;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len) {
if (!isComplete())
throw new IllegalStateException("Authentication exchange has not completed");
throw new IllegalStateException("OAUTHBEARER supports neither integrity nor privacy");
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len) {
if (!isComplete())
throw new IllegalStateException("Authentication exchange has not completed");
throw new IllegalStateException("OAUTHBEARER supports neither integrity nor privacy");
}
@Override
public Object getNegotiatedProperty(String propName) {
if (!isComplete())
throw new IllegalStateException("Authentication exchange has not completed");
return null;
}
@Override
public void dispose() {
}
private void setState(State state) {
log.debug("Setting SASL/{} client state to {}", OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, state);
this.state = state;
}
private SaslExtensions retrieveCustomExtensions() throws SaslException {
SaslExtensionsCallback extensionsCallback = new SaslExtensionsCallback();
try {
callbackHandler().handle(new Callback[] {extensionsCallback});
} catch (UnsupportedCallbackException e) {
log.debug("Extensions callback is not supported by client callback handler {}, no extensions will be added",
callbackHandler());
} catch (Exception e) {
throw new SaslException("SASL extensions could not be obtained", e);
}
return extensionsCallback.extensions();
}
public static | State |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java | {
"start": 1194,
"end": 2523
} | class ____ {
@Test
void testSuffixAndPrefixAssignment() {
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor();
assertThat(interceptor.getPrefix()).isNotNull();
assertThat(interceptor.getSuffix()).isNotNull();
interceptor.setPrefix(null);
interceptor.setSuffix(null);
assertThat(interceptor.getPrefix()).isNotNull();
assertThat(interceptor.getSuffix()).isNotNull();
}
@Test
void testSunnyDayPathLogsPerformanceMetricsCorrectly() throws Throwable {
MethodInvocation mi = mock();
given(mi.getMethod()).willReturn(String.class.getMethod("toString"));
Log log = mock();
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
interceptor.invokeUnderTrace(mi, log);
verify(log).trace(anyString());
}
@Test
void testExceptionPathStillLogsPerformanceMetricsCorrectly() throws Throwable {
MethodInvocation mi = mock();
given(mi.getMethod()).willReturn(String.class.getMethod("toString"));
given(mi.proceed()).willThrow(new IllegalArgumentException());
Log log = mock();
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invokeUnderTrace(mi, log));
verify(log).trace(anyString());
}
}
| PerformanceMonitorInterceptorTests |
java | apache__flink | flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/row/ParquetRowDataWriter.java | {
"start": 15735,
"end": 17493
} | class ____ implements FieldWriter {
private String elementName;
private FieldWriter elementWriter;
private String repeatedGroupName;
private ArrayWriter(LogicalType t, GroupType groupType) {
// Get the internal array structure
GroupType repeatedType = groupType.getType(0).asGroupType();
this.repeatedGroupName = repeatedType.getName();
Type elementType = repeatedType.getType(0);
this.elementName = elementType.getName();
this.elementWriter = createWriter(t, elementType);
}
@Override
public void write(RowData row, int ordinal) {
writeArrayData(row.getArray(ordinal));
}
@Override
public void write(ArrayData arrayData, int ordinal) {
writeArrayData(arrayData.getArray(ordinal));
}
private void writeArrayData(ArrayData arrayData) {
recordConsumer.startGroup();
int listLength = arrayData.size();
if (listLength > 0) {
recordConsumer.startField(repeatedGroupName, 0);
for (int i = 0; i < listLength; i++) {
recordConsumer.startGroup();
if (!arrayData.isNullAt(i)) {
recordConsumer.startField(elementName, 0);
elementWriter.write(arrayData, i);
recordConsumer.endField(elementName, 0);
}
recordConsumer.endGroup();
}
recordConsumer.endField(repeatedGroupName, 0);
}
recordConsumer.endGroup();
}
}
/** It writes a row type field to parquet. */
private | ArrayWriter |
java | grpc__grpc-java | android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/LoadBalancerStatsServiceGrpc.java | {
"start": 9553,
"end": 11280
} | class ____
extends io.grpc.stub.AbstractAsyncStub<LoadBalancerStatsServiceStub> {
private LoadBalancerStatsServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected LoadBalancerStatsServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new LoadBalancerStatsServiceStub(channel, callOptions);
}
/**
* <pre>
* Gets the backend distribution for RPCs sent by a test client.
* </pre>
*/
public void getClientStats(io.grpc.testing.integration.Messages.LoadBalancerStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerStatsResponse> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetClientStatsMethod(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Gets the accumulated stats for RPCs sent by a test client.
* </pre>
*/
public void getClientAccumulatedStats(io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsRequest request,
io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.LoadBalancerAccumulatedStatsResponse> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetClientAccumulatedStatsMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service LoadBalancerStatsService.
* <pre>
* A service used to obtain stats for verifying LB behavior.
* </pre>
*/
public static final | LoadBalancerStatsServiceStub |
java | apache__camel | components/camel-twilio/src/main/java/org/apache/camel/component/twilio/TwilioConverter.java | {
"start": 1027,
"end": 1331
} | class ____ {
private TwilioConverter() {
//Utility Class
}
@Converter
public static Endpoint toPhoneNumber(String value) {
return new PhoneNumber(value);
}
@Converter
public static Sip toSip(String value) {
return new Sip(value);
}
}
| TwilioConverter |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsPushDownJoin.java | {
"start": 2781,
"end": 3159
} | class ____ when there are duplicated names coming from 2 sides of the join
* operator.
* <br>
* Holds information of original output name and the alias of the new output.
*/
record ColumnWithAlias(String colName, String alias) {
public String prettyString() {
if (alias == null) return colName;
else return colName + " AS " + alias;
}
}
}
| used |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/admin/internals/AdminMetadataManager.java | {
"start": 5096,
"end": 11221
} | enum ____ {
QUIESCENT,
UPDATE_REQUESTED,
UPDATE_PENDING
}
public AdminMetadataManager(
LogContext logContext,
long refreshBackoffMs,
long metadataExpireMs,
boolean usingBootstrapControllers
) {
this.log = logContext.logger(AdminMetadataManager.class);
this.refreshBackoffMs = refreshBackoffMs;
this.metadataExpireMs = metadataExpireMs;
this.usingBootstrapControllers = usingBootstrapControllers;
this.updater = new AdminMetadataUpdater();
}
public boolean usingBootstrapControllers() {
return usingBootstrapControllers;
}
public AdminMetadataUpdater updater() {
return updater;
}
public boolean isReady() {
if (fatalException != null) {
log.debug("Metadata is not usable: failed to get metadata.", fatalException);
throw fatalException;
}
if (cluster.nodes().isEmpty()) {
log.trace("Metadata is not ready: bootstrap nodes have not been " +
"initialized yet.");
return false;
}
if (cluster.isBootstrapConfigured()) {
log.trace("Metadata is not ready: we have not fetched metadata from " +
"the bootstrap nodes yet.");
return false;
}
log.trace("Metadata is ready to use.");
return true;
}
public Node controller() {
return cluster.controller();
}
public Node nodeById(int nodeId) {
return cluster.nodeById(nodeId);
}
public void requestUpdate() {
if (state == State.QUIESCENT) {
state = State.UPDATE_REQUESTED;
log.debug("Requesting metadata update.");
}
}
public void clearController() {
if (cluster.controller() != null) {
log.trace("Clearing cached controller node {}.", cluster.controller());
this.cluster = new Cluster(cluster.clusterResource().clusterId(),
cluster.nodes(),
Collections.emptySet(),
Collections.emptySet(),
Collections.emptySet(),
null);
}
}
/**
* Determine if the AdminClient should fetch new metadata.
*/
public long metadataFetchDelayMs(long now) {
switch (state) {
case QUIESCENT:
// Calculate the time remaining until the next periodic update.
// We want to avoid making many metadata requests in a short amount of time,
// so there is a metadata refresh backoff period.
return Math.max(delayBeforeNextAttemptMs(now), delayBeforeNextExpireMs(now));
case UPDATE_REQUESTED:
// Respect the backoff, even if an update has been requested
return delayBeforeNextAttemptMs(now);
default:
// An update is already pending, so we don't need to initiate another one.
return Long.MAX_VALUE;
}
}
private long delayBeforeNextExpireMs(long now) {
long timeSinceUpdate = now - lastMetadataUpdateMs;
return Math.max(0, metadataExpireMs - timeSinceUpdate);
}
private long delayBeforeNextAttemptMs(long now) {
long timeSinceAttempt = now - lastMetadataFetchAttemptMs;
return Math.max(0, refreshBackoffMs - timeSinceAttempt);
}
public boolean needsRebootstrap(long now, long rebootstrapTriggerMs) {
return metadataAttemptStartMs.filter(startMs -> now - startMs > rebootstrapTriggerMs).isPresent();
}
/**
* Transition into the UPDATE_PENDING state. Updates lastMetadataFetchAttemptMs.
*/
public void transitionToUpdatePending(long now) {
this.state = State.UPDATE_PENDING;
this.lastMetadataFetchAttemptMs = now;
if (metadataAttemptStartMs.isEmpty())
metadataAttemptStartMs = Optional.of(now);
}
public void updateFailed(Throwable exception) {
// We depend on pending calls to request another metadata update
this.state = State.QUIESCENT;
if (RequestUtils.isFatalException(exception)) {
log.warn("Fatal error during metadata update", exception);
// avoid unchecked/unconfirmed cast to ApiException
if (exception instanceof ApiException) {
this.fatalException = (ApiException) exception;
}
if (exception instanceof UnsupportedVersionException) {
if (usingBootstrapControllers) {
log.warn("The remote node is not a CONTROLLER that supports the KIP-919 " +
"DESCRIBE_CLUSTER api.", exception);
} else {
log.warn("The remote node is not a BROKER that supports the METADATA api.", exception);
}
}
} else {
log.info("Metadata update failed", exception);
}
}
/**
* Receive new metadata, and transition into the QUIESCENT state.
* Updates lastMetadataUpdateMs, cluster, and authException.
*/
public void update(Cluster cluster, long now) {
if (cluster.isBootstrapConfigured()) {
log.debug("Setting bootstrap cluster metadata {}.", cluster);
bootstrapCluster = cluster;
} else {
log.debug("Updating cluster metadata to {}", cluster);
this.lastMetadataUpdateMs = now;
}
this.state = State.QUIESCENT;
this.fatalException = null;
this.metadataAttemptStartMs = Optional.empty();
if (!cluster.nodes().isEmpty()) {
this.cluster = cluster;
}
}
public void initiateRebootstrap() {
this.metadataAttemptStartMs = Optional.of(0L);
}
/**
* Rebootstrap metadata with the cluster previously used for bootstrapping.
*/
public void rebootstrap(long now) {
log.info("Rebootstrapping with {}", this.bootstrapCluster);
update(bootstrapCluster, now);
this.metadataAttemptStartMs = Optional.of(now);
}
}
| State |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/type/EnumSetConverterTest.java | {
"start": 8344,
"end": 8938
} | class ____ {
@Id
private Long id;
@Convert(converter = MyEnumConverter.class)
@Column( name = "the_set" )
private Set<MySpecialEnum> theSet;
public TableWithEnumSetConverter() {
}
public TableWithEnumSetConverter(Long id, Set<MySpecialEnum> theSet) {
this.id = id;
this.theSet = theSet;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<MySpecialEnum> getTheSet() {
return theSet;
}
public void setTheSet(Set<MySpecialEnum> theSet) {
this.theSet = theSet;
}
}
public | TableWithEnumSetConverter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.