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__camel | tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/JavaSourceParser.java | {
"start": 2842,
"end": 4355
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(JavaSourceParser.class);
private String errorMessage;
private String classDoc;
private final List<String> methodSignatures = new ArrayList<>();
private final Map<String, String> methodDocs = new HashMap<>();
private final Map<String, Map<String, String>> parameterTypes = new LinkedHashMap<>();
private final Map<String, Map<String, String>> parameterDocs = new LinkedHashMap<>();
private final Map<String, Map<String, String>> setterMethods = new LinkedHashMap<>();
private final Map<String, Map<String, String>> setterDocs = new LinkedHashMap<>();
private final ClassLoader classLoader;
public JavaSourceParser(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public void parse(InputStream in, String innerClass) throws IOException {
parse(new String(in.readAllBytes()), innerClass, false);
}
public void parse(InputStream in, String innerClass, boolean includeSetters) throws IOException {
parse(new String(in.readAllBytes()), innerClass, includeSetters);
}
@SuppressWarnings("unchecked")
public synchronized void parse(String in, String innerClass, boolean includeSetters) {
AbstractGenericCapableJavaSource rootClazz = (AbstractGenericCapableJavaSource) Roaster.parse(in);
AbstractGenericCapableJavaSource clazz = rootClazz;
if (innerClass != null) {
// we want the inner | JavaSourceParser |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopDoubleFloatAggregator.java | {
"start": 1430,
"end": 3169
} | class ____ {
public static SingleState initSingle(BigArrays bigArrays, int limit, boolean ascending) {
return new SingleState(bigArrays, limit, ascending);
}
public static void combine(SingleState state, double v, float outputValue) {
state.add(v, outputValue);
}
public static void combineIntermediate(SingleState state, DoubleBlock values, FloatBlock outputValues) {
int start = values.getFirstValueIndex(0);
int end = start + values.getValueCount(0);
for (int i = start; i < end; i++) {
combine(state, values.getDouble(i), outputValues.getFloat(i));
}
}
public static Block evaluateFinal(SingleState state, DriverContext driverContext) {
return state.toBlock(driverContext.blockFactory());
}
public static GroupingState initGrouping(BigArrays bigArrays, int limit, boolean ascending) {
return new GroupingState(bigArrays, limit, ascending);
}
public static void combine(GroupingState state, int groupId, double v, float outputValue) {
state.add(groupId, v, outputValue);
}
public static void combineIntermediate(GroupingState state, int groupId, DoubleBlock values, FloatBlock outputValues, int position) {
int start = values.getFirstValueIndex(position);
int end = start + values.getValueCount(position);
for (int i = start; i < end; i++) {
combine(state, groupId, values.getDouble(i), outputValues.getFloat(i));
}
}
public static Block evaluateFinal(GroupingState state, IntVector selected, GroupingAggregatorEvaluationContext ctx) {
return state.toBlock(ctx.blockFactory(), selected);
}
public static | TopDoubleFloatAggregator |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/translog/TranslogDeletionPolicy.java | {
"start": 849,
"end": 4837
} | class ____ {
private final Map<Object, RuntimeException> openTranslogRef;
public void assertNoOpenTranslogRefs() {
if (Assertions.ENABLED && openTranslogRef.isEmpty() == false) {
AssertionError e = new AssertionError("not all translog generations have been released");
openTranslogRef.values().forEach(e::addSuppressed);
throw e;
}
}
/**
* Records how many retention locks are held against each
* translog generation
*/
private final Map<Long, Counter> translogRefCounts = new HashMap<>();
private long localCheckpointOfSafeCommit = SequenceNumbers.NO_OPS_PERFORMED;
public TranslogDeletionPolicy() {
if (Assertions.ENABLED) {
openTranslogRef = new ConcurrentHashMap<>();
} else {
openTranslogRef = null;
}
}
public synchronized void setLocalCheckpointOfSafeCommit(long newCheckpoint) {
if (newCheckpoint < this.localCheckpointOfSafeCommit) {
throw new IllegalArgumentException(
"local checkpoint of the safe commit can't go backwards: "
+ "current ["
+ this.localCheckpointOfSafeCommit
+ "] new ["
+ newCheckpoint
+ "]"
);
}
this.localCheckpointOfSafeCommit = newCheckpoint;
}
/**
* acquires the basis generation for a new snapshot. Any translog generation above, and including, the returned generation
* will not be deleted until the returned {@link Releasable} is closed.
*/
synchronized Releasable acquireTranslogGen(final long translogGen) {
translogRefCounts.computeIfAbsent(translogGen, l -> Counter.newCounter(false)).addAndGet(1);
final AtomicBoolean closed = new AtomicBoolean();
assert assertAddTranslogRef(closed);
return () -> {
if (closed.compareAndSet(false, true)) {
releaseTranslogGen(translogGen);
assert assertRemoveTranslogRef(closed);
}
};
}
private boolean assertAddTranslogRef(Object reference) {
final RuntimeException existing = openTranslogRef.put(reference, new RuntimeException());
if (existing != null) {
throw new AssertionError("double adding of closing reference", existing);
}
return true;
}
private boolean assertRemoveTranslogRef(Object reference) {
return openTranslogRef.remove(reference) != null;
}
/** returns the number of generations that were acquired for snapshots */
synchronized int pendingTranslogRefCount() {
return translogRefCounts.size();
}
/**
* releases a generation that was acquired by {@link #acquireTranslogGen(long)}
*/
private synchronized void releaseTranslogGen(long translogGen) {
Counter current = translogRefCounts.get(translogGen);
if (current == null || current.get() <= 0) {
throw new IllegalArgumentException("translog gen [" + translogGen + "] wasn't acquired");
}
if (current.addAndGet(-1) == 0) {
translogRefCounts.remove(translogGen);
}
}
/**
* Returns the minimum translog generation that is still required by the locks (via {@link #acquireTranslogGen(long)}.
*/
synchronized long getMinTranslogGenRequiredByLocks() {
return translogRefCounts.keySet().stream().reduce(Math::min).orElse(Long.MAX_VALUE);
}
/**
* Returns the local checkpoint of the safe commit. This value is used to calculate the min required generation for recovery.
*/
public synchronized long getLocalCheckpointOfSafeCommit() {
return localCheckpointOfSafeCommit;
}
synchronized long getTranslogRefCount(long gen) {
final Counter counter = translogRefCounts.get(gen);
return counter == null ? 0 : counter.get();
}
}
| TranslogDeletionPolicy |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Olingo4EndpointBuilderFactory.java | {
"start": 68958,
"end": 69725
} | class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final Olingo4HeaderNameBuilder INSTANCE = new Olingo4HeaderNameBuilder();
/**
* The response Http headers.
*
* The option is a: {@code Map<String, String>} type.
*
* Group: producer
*
* @return the name of the header {@code Olingo4.responseHttpHeaders}.
*/
public String olingo4Responsehttpheaders() {
return "CamelOlingo4.responseHttpHeaders";
}
}
static Olingo4EndpointBuilder endpointBuilder(String componentName, String path) {
| Olingo4HeaderNameBuilder |
java | apache__flink | flink-end-to-end-tests/flink-python-test/src/main/java/org/apache/flink/python/tests/util/AddOne.java | {
"start": 941,
"end": 1048
} | class ____ extends ScalarFunction {
public long eval(Long input) {
return input + 1;
}
}
| AddOne |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/analysis/NormalizingCharFilterFactory.java | {
"start": 710,
"end": 878
} | interface ____ extends CharFilterFactory {
@Override
default Reader normalize(Reader reader) {
return create(reader);
}
}
| NormalizingCharFilterFactory |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/assignability/generics/Vehicle.java | {
"start": 110,
"end": 224
} | class ____<T extends Engine> {
@Inject
T eng;
public T getEngine() {
return eng;
}
}
| Vehicle |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inlineme/ValidatorTest.java | {
"start": 16774,
"end": 17485
} | class ____ {
@InlineMe(
replacement = "this.after(Duration.ZERO)",
imports = {"java.time.Duration"})
@Deprecated
public void before() {
after(Duration.ZERO);
}
public void after(Duration duration) {}
}
""")
.doTest();
}
@Test
public void instanceMethod_withConstantStaticallyImported() {
helper
.addSourceLines(
"Client.java",
"""
import static java.time.Duration.ZERO;
import com.google.errorprone.annotations.InlineMe;
import java.time.Duration;
public final | Client |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpsServerExplicitTLSWithoutClientAuthTestSupport.java | {
"start": 1293,
"end": 1586
} | class ____ extends FtpsServerTestSupport {
@RegisterExtension
static FtpsEmbeddedService service = FtpServiceFactory
.createSecureEmbeddedService(new EmbeddedConfiguration.SecurityConfiguration(false, AUTH_VALUE_TLS, false));
}
| FtpsServerExplicitTLSWithoutClientAuthTestSupport |
java | junit-team__junit5 | junit-platform-commons/src/main/java/org/junit/platform/commons/util/ModuleUtils.java | {
"start": 9229,
"end": 10292
} | class ____ {
private final ClassFilter classFilter;
private final ClassLoader classLoader;
ModuleReferenceClassScanner(ClassFilter classFilter, ClassLoader classLoader) {
this.classFilter = classFilter;
this.classLoader = classLoader;
}
/**
* Scan module reference for classes that potentially contain testable methods.
*/
List<Class<?>> scan(ModuleReference reference) {
try (ModuleReader reader = reference.open()) {
try (Stream<String> names = reader.list()) {
// @formatter:off
return names.filter(name -> !name.endsWith("/")) // remove directories
.map(Path::of)
.filter(SearchPathUtils::isClassOrSourceFile)
.map(SearchPathUtils::determineFullyQualifiedClassName)
.filter(classFilter::match)
.<Class<?>> map(this::loadClassUnchecked)
.filter(classFilter::match)
.toList();
// @formatter:on
}
}
catch (IOException e) {
throw new JUnitException("Failed to read contents of " + reference + ".", e);
}
}
/**
* Load | ModuleReferenceClassScanner |
java | elastic__elasticsearch | modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextGeneratorCommon.java | {
"start": 1444,
"end": 7758
} | class ____ {
@SuppressForbidden(reason = "retrieving data from an internal API not exposed as part of the REST client")
@SuppressWarnings("unchecked")
public static List<PainlessContextInfo> getContextInfos() throws IOException {
URLConnection getContextNames = new URL("http://" + System.getProperty("cluster.uri") + "/_scripts/painless/_context")
.openConnection();
List<String> contextNames;
try (
XContentParser parser = JsonXContent.jsonXContent.createParser(
XContentParserConfiguration.EMPTY,
getContextNames.getInputStream()
)
) {
parser.nextToken();
parser.nextToken();
contextNames = (List<String>) (Object) parser.list();
}
((HttpURLConnection) getContextNames).disconnect();
List<PainlessContextInfo> contextInfos = new ArrayList<>();
for (String contextName : contextNames) {
URLConnection getContextInfo = new URL(
"http://" + System.getProperty("cluster.uri") + "/_scripts/painless/_context?context=" + contextName
).openConnection();
try (var parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY, getContextInfo.getInputStream())) {
contextInfos.add(PainlessContextInfo.fromXContent(parser));
((HttpURLConnection) getContextInfo).disconnect();
}
}
contextInfos.sort(Comparator.comparing(PainlessContextInfo::getName));
return contextInfos;
}
public static String getType(Map<String, String> javaNamesToDisplayNames, String javaType) {
if (javaType.endsWith("[]") == false) {
return javaNamesToDisplayNames.getOrDefault(javaType, javaType);
}
int bracePosition = javaType.indexOf('[');
String braces = javaType.substring(bracePosition);
String type = javaType.substring(0, bracePosition);
if (javaNamesToDisplayNames.containsKey(type)) {
return javaNamesToDisplayNames.get(type) + braces;
}
return javaType;
}
private static Map<String, String> getDisplayNames(Collection<PainlessContextInfo> contextInfos) {
Map<String, String> javaNamesToDisplayNames = new HashMap<>();
for (PainlessContextInfo contextInfo : contextInfos) {
for (PainlessContextClassInfo classInfo : contextInfo.getClasses()) {
String className = classInfo.getName();
if (javaNamesToDisplayNames.containsKey(className) == false) {
if (classInfo.isImported()) {
javaNamesToDisplayNames.put(className, className.substring(className.lastIndexOf('.') + 1).replace('$', '.'));
} else {
javaNamesToDisplayNames.put(className, className.replace('$', '.'));
}
}
}
}
return javaNamesToDisplayNames;
}
public static List<PainlessContextClassInfo> sortClassInfos(Collection<PainlessContextClassInfo> unsortedClassInfos) {
List<PainlessContextClassInfo> classInfos = new ArrayList<>(unsortedClassInfos);
classInfos.removeIf(ContextGeneratorCommon::isExcludedClassInfo);
return sortFilteredClassInfos(classInfos);
}
static boolean isExcludedClassInfo(PainlessContextClassInfo v) {
return "void".equals(v.getName())
|| "boolean".equals(v.getName())
|| "byte".equals(v.getName())
|| "short".equals(v.getName())
|| "char".equals(v.getName())
|| "int".equals(v.getName())
|| "long".equals(v.getName())
|| "float".equals(v.getName())
|| "double".equals(v.getName())
|| "org.elasticsearch.painless.lookup.def".equals(v.getName())
|| isInternalClass(v.getName());
}
static List<PainlessContextClassInfo> sortFilteredClassInfos(List<PainlessContextClassInfo> classInfos) {
classInfos.sort((c1, c2) -> {
String n1 = c1.getName();
String n2 = c2.getName();
boolean i1 = c1.isImported();
boolean i2 = c2.isImported();
String p1 = n1.substring(0, n1.lastIndexOf('.'));
String p2 = n2.substring(0, n2.lastIndexOf('.'));
int compare = p1.compareTo(p2);
if (compare == 0) {
if (i1 && i2) {
compare = n1.substring(n1.lastIndexOf('.') + 1).compareTo(n2.substring(n2.lastIndexOf('.') + 1));
} else if (i1 == false && i2 == false) {
compare = n1.compareTo(n2);
} else {
compare = Boolean.compare(i1, i2) * -1;
}
}
return compare;
});
return classInfos;
}
private static boolean isInternalClass(String javaName) {
return javaName.equals("org.elasticsearch.script.ScoreScript")
|| javaName.equals("org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape")
|| javaName.equals("org.elasticsearch.xpack.sql.expression.function.scalar.whitelist.InternalSqlScriptUtils")
|| javaName.equals("org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime")
|| javaName.equals("org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth")
|| javaName.equals("org.elasticsearch.xpack.eql.expression.function.scalar.whitelist.InternalEqlScriptUtils")
|| javaName.equals("org.elasticsearch.xpack.ql.expression.function.scalar.InternalQlScriptUtils")
|| javaName.equals("org.elasticsearch.xpack.ql.expression.function.scalar.whitelist.InternalQlScriptUtils")
|| javaName.equals("org.elasticsearch.script.ScoreScript$ExplanationHolder");
}
public static List<PainlessContextClassInfo> excludeCommonClassInfos(
Set<PainlessContextClassInfo> exclude,
List<PainlessContextClassInfo> classInfos
) {
List<PainlessContextClassInfo> uniqueClassInfos = new ArrayList<>(classInfos);
uniqueClassInfos.removeIf(exclude::contains);
return uniqueClassInfos;
}
public static | ContextGeneratorCommon |
java | quarkusio__quarkus | extensions/panache/mongodb-rest-data-panache/deployment/src/main/java/io/quarkus/mongodb/rest/data/panache/deployment/EntityDataAccessImplementor.java | {
"start": 433,
"end": 5077
} | class ____ implements DataAccessImplementor {
private final String entityClassName;
EntityDataAccessImplementor(String entityClassName) {
this.entityClassName = entityClassName;
}
@Override
public ResultHandle findById(BytecodeCreator creator, ResultHandle id) {
return creator.invokeStaticMethod(
ofMethod(entityClassName, "findById", PanacheMongoEntityBase.class, Object.class), id);
}
/**
* Implements <code>Entity.findAll().page(page).list()</code>
*/
@Override
public ResultHandle findAll(BytecodeCreator creator, ResultHandle page) {
ResultHandle panacheQuery = creator.invokeStaticMethod(ofMethod(entityClassName, "findAll", PanacheQuery.class));
creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "page", PanacheQuery.class, Page.class), panacheQuery,
page);
return creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "list", List.class), panacheQuery);
}
/**
* Implements <code>Entity.findAll(sort).page(page).list()</code>
*/
@Override
public ResultHandle findAll(BytecodeCreator creator, ResultHandle page, ResultHandle sort) {
ResultHandle panacheQuery = creator.invokeStaticMethod(
ofMethod(entityClassName, "findAll", PanacheQuery.class, Sort.class),
sort);
creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "page", PanacheQuery.class, Page.class), panacheQuery,
page);
return creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "list", List.class), panacheQuery);
}
@Override
public ResultHandle findAll(BytecodeCreator creator, ResultHandle page, ResultHandle query, ResultHandle queryParams) {
ResultHandle panacheQuery = creator.invokeStaticMethod(
ofMethod(entityClassName, "find", PanacheQuery.class, String.class, Map.class),
query, queryParams);
creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "page", PanacheQuery.class, Page.class), panacheQuery,
page);
return creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "list", List.class), panacheQuery);
}
@Override
public ResultHandle findAll(BytecodeCreator creator, ResultHandle page, ResultHandle sort, ResultHandle query,
ResultHandle queryParams) {
ResultHandle panacheQuery = creator.invokeStaticMethod(
ofMethod(entityClassName, "find", PanacheQuery.class, String.class, Sort.class, Map.class),
query, sort, queryParams);
creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "page", PanacheQuery.class, Page.class), panacheQuery,
page);
return creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "list", List.class), panacheQuery);
}
@Override
public ResultHandle persist(BytecodeCreator creator, ResultHandle entity) {
creator.invokeVirtualMethod(ofMethod(entityClassName, "persist", void.class), entity);
return entity;
}
@Override
public ResultHandle persistOrUpdate(BytecodeCreator creator, ResultHandle entity) {
creator.invokeVirtualMethod(ofMethod(entityClassName, "persistOrUpdate", void.class), entity);
return entity;
}
@Override
public ResultHandle deleteById(BytecodeCreator creator, ResultHandle id) {
return creator.invokeStaticMethod(ofMethod(entityClassName, "deleteById", boolean.class, Object.class), id);
}
@Override
public ResultHandle pageCount(BytecodeCreator creator, ResultHandle page, ResultHandle query, ResultHandle queryParams) {
ResultHandle panacheQuery = creator.invokeStaticMethod(ofMethod(entityClassName, "find", PanacheQuery.class,
String.class, Map.class), query, queryParams);
creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "page", PanacheQuery.class, Page.class), panacheQuery,
page);
return creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "pageCount", int.class), panacheQuery);
}
@Override
public ResultHandle pageCount(BytecodeCreator creator, ResultHandle page) {
ResultHandle panacheQuery = creator.invokeStaticMethod(ofMethod(entityClassName, "findAll", PanacheQuery.class));
creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "page", PanacheQuery.class, Page.class), panacheQuery,
page);
return creator.invokeInterfaceMethod(ofMethod(PanacheQuery.class, "pageCount", int.class), panacheQuery);
}
}
| EntityDataAccessImplementor |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerIntegrationTests.java | {
"start": 3033,
"end": 7436
} | class ____ {
private static final String THREAD_NAME_PREFIX = "Test-";
private static final CountDownLatch countDownLatch = new CountDownLatch(1);
private final TestContextManager testContextManager = new TestContextManager(ExampleTestCase.class);
private final TestContext testContext = testContextManager.getTestContext();
// Note that the following invocation of getApplicationContext() forces eager
// loading of the test's ApplicationContext which consequently results in the
// publication of all test execution events. Otherwise, TestContext#publishEvent
// would never fire any events for ExampleTestCase.
private final TestExecutionListener listener = testContext.getApplicationContext().getBean(TestExecutionListener.class);
private final Object testInstance = new ExampleTestCase();
private final Method traceableTestMethod = ReflectionUtils.findMethod(ExampleTestCase.class, "traceableTest");
@AfterEach
public void closeApplicationContext() {
this.testContext.markApplicationContextDirty(null);
}
@Test
public void beforeTestClassAnnotation() throws Exception {
testContextManager.beforeTestClass();
verify(listener, only()).beforeTestClass(testContext);
}
@Test
public void prepareTestInstanceAnnotation() throws Exception {
testContextManager.prepareTestInstance(testInstance);
verify(listener, only()).prepareTestInstance(testContext);
}
@Test
public void beforeTestMethodAnnotation() throws Exception {
testContextManager.beforeTestMethod(testInstance, traceableTestMethod);
verify(listener, only()).beforeTestMethod(testContext);
}
/**
* The {@code @BeforeTestMethod} condition in
* {@link TestEventListenerConfiguration#beforeTestMethod(BeforeTestMethodEvent)}
* only matches if the test method is annotated with {@code @Traceable}, and
* {@link ExampleTestCase#standardTest()} is not.
*/
@Test
public void beforeTestMethodAnnotationWithFailingCondition() throws Exception {
Method standardTest = ReflectionUtils.findMethod(ExampleTestCase.class, "standardTest");
testContextManager.beforeTestMethod(testInstance, standardTest);
verify(listener, never()).beforeTestMethod(testContext);
}
/**
* An exception thrown from an event listener executed in the current thread
* should fail the test method.
*/
@Test
public void beforeTestMethodAnnotationWithFailingEventListener() throws Exception {
Method method = ReflectionUtils.findMethod(ExampleTestCase.class, "testWithFailingEventListener");
assertThatRuntimeException()
.isThrownBy(() -> testContextManager.beforeTestMethod(testInstance, method))
.withMessageContaining("Boom!");
verify(listener, only()).beforeTestMethod(testContext);
}
/**
* An exception thrown from an event listener that is executed asynchronously
* should not fail the test method.
*/
@Test
public void beforeTestMethodAnnotationWithFailingAsyncEventListener() throws Exception {
TrackingAsyncUncaughtExceptionHandler.asyncException = null;
String methodName = "testWithFailingAsyncEventListener";
Method method = ReflectionUtils.findMethod(ExampleTestCase.class, methodName);
testContextManager.beforeTestMethod(testInstance, method);
assertThat(countDownLatch.await(2, TimeUnit.SECONDS)).isTrue();
verify(listener, only()).beforeTestMethod(testContext);
assertThat(TrackingAsyncUncaughtExceptionHandler.asyncException.getMessage())
.startsWith("Asynchronous exception for test method [" + methodName + "] in thread [" + THREAD_NAME_PREFIX);
}
@Test
public void beforeTestExecutionAnnotation() throws Exception {
testContextManager.beforeTestExecution(testInstance, traceableTestMethod);
verify(listener, only()).beforeTestExecution(testContext);
}
@Test
public void afterTestExecutionAnnotation() throws Exception {
testContextManager.afterTestExecution(testInstance, traceableTestMethod, null);
verify(listener, only()).afterTestExecution(testContext);
}
@Test
public void afterTestMethodAnnotation() throws Exception {
testContextManager.afterTestMethod(testInstance, traceableTestMethod, null);
verify(listener, only()).afterTestMethod(testContext);
}
@Test
public void afterTestClassAnnotation() throws Exception {
testContextManager.afterTestClass();
verify(listener, only()).afterTestClass(testContext);
}
@Target(METHOD)
@Retention(RUNTIME)
@ | EventPublishingTestExecutionListenerIntegrationTests |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/MimeType.java | {
"start": 1816,
"end": 22415
} | class ____ implements Comparable<MimeType>, Serializable {
private static final long serialVersionUID = 4085923477777865903L;
protected static final String WILDCARD_TYPE = "*";
private static final String PARAM_CHARSET = "charset";
private static final BitSet TOKEN;
static {
// variable names refer to RFC 2616, section 2.2
BitSet ctl = new BitSet(128);
for (int i = 0; i <= 31; i++) {
ctl.set(i);
}
ctl.set(127);
BitSet separators = new BitSet(128);
separators.set('(');
separators.set(')');
separators.set('<');
separators.set('>');
separators.set('@');
separators.set(',');
separators.set(';');
separators.set(':');
separators.set('\\');
separators.set('\"');
separators.set('/');
separators.set('[');
separators.set(']');
separators.set('?');
separators.set('=');
separators.set('{');
separators.set('}');
separators.set(' ');
separators.set('\t');
TOKEN = new BitSet(128);
TOKEN.set(0, 128);
TOKEN.andNot(ctl);
TOKEN.andNot(separators);
}
private final String type;
private final String subtype;
@SuppressWarnings("serial")
private final Map<String, String> parameters;
private transient @Nullable Charset resolvedCharset;
private volatile @Nullable String toStringValue;
/**
* Create a new {@code MimeType} for the given primary type.
* <p>The {@linkplain #getSubtype() subtype} is set to <code>"*"</code>,
* and the parameters are empty.
* @param type the primary type
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type) {
this(type, WILDCARD_TYPE);
}
/**
* Create a new {@code MimeType} for the given primary type and subtype.
* <p>The parameters are empty.
* @param type the primary type
* @param subtype the subtype
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type, String subtype) {
this(type, subtype, Collections.emptyMap());
}
/**
* Create a new {@code MimeType} for the given type, subtype, and character set.
* @param type the primary type
* @param subtype the subtype
* @param charset the character set
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type, String subtype, Charset charset) {
this(type, subtype, Collections.singletonMap(PARAM_CHARSET, charset.name()));
this.resolvedCharset = charset;
}
/**
* Copy-constructor that copies the type, subtype, parameters of the given {@code MimeType},
* and allows to set the specified character set.
* @param other the other MimeType
* @param charset the character set
* @throws IllegalArgumentException if any of the parameters contains illegal characters
* @since 4.3
*/
public MimeType(MimeType other, Charset charset) {
this(other.getType(), other.getSubtype(), addCharsetParameter(charset, other.getParameters()));
this.resolvedCharset = charset;
}
/**
* Copy-constructor that copies the type and subtype of the given {@code MimeType},
* and allows for different parameter.
* @param other the other MimeType
* @param parameters the parameters (may be {@code null})
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(MimeType other, @Nullable Map<String, String> parameters) {
this(other.getType(), other.getSubtype(), parameters);
}
/**
* Create a new {@code MimeType} for the given type, subtype, and parameters.
* @param type the primary type
* @param subtype the subtype
* @param parameters the parameters (may be {@code null})
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type, String subtype, @Nullable Map<String, String> parameters) {
Assert.hasLength(type, "'type' must not be empty");
Assert.hasLength(subtype, "'subtype' must not be empty");
checkToken(type);
checkToken(subtype);
this.type = type.toLowerCase(Locale.ROOT);
this.subtype = subtype.toLowerCase(Locale.ROOT);
if (!CollectionUtils.isEmpty(parameters)) {
Map<String, String> map = new LinkedCaseInsensitiveMap<>(parameters.size(), Locale.ROOT);
parameters.forEach((parameter, value) -> {
checkParameters(parameter, value);
map.put(parameter, value);
});
this.parameters = Collections.unmodifiableMap(map);
}
else {
this.parameters = Collections.emptyMap();
}
}
/**
* Copy-constructor that copies the type, subtype and parameters of the given {@code MimeType},
* skipping checks performed in other constructors.
* @param other the other MimeType
* @since 5.3
*/
protected MimeType(MimeType other) {
this.type = other.type;
this.subtype = other.subtype;
this.parameters = other.parameters;
this.resolvedCharset = other.resolvedCharset;
this.toStringValue = other.toStringValue;
}
/**
* Checks the given token string for illegal characters, as defined in RFC 2616,
* section 2.2.
* @throws IllegalArgumentException in case of illegal characters
* @see <a href="https://tools.ietf.org/html/rfc2616#section-2.2">HTTP 1.1, section 2.2</a>
*/
private void checkToken(String token) {
for (int i = 0; i < token.length(); i++) {
char ch = token.charAt(i);
if (!TOKEN.get(ch)) {
throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + token + "\"");
}
}
}
protected void checkParameters(String parameter, String value) {
Assert.hasLength(parameter, "'parameter' must not be empty");
Assert.hasLength(value, "'value' must not be empty");
checkToken(parameter);
if (PARAM_CHARSET.equals(parameter)) {
if (this.resolvedCharset == null) {
this.resolvedCharset = Charset.forName(unquote(value));
}
}
else if (!isQuotedString(value)) {
checkToken(value);
}
}
private boolean isQuotedString(String s) {
if (s.length() < 2) {
return false;
}
return ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'")));
}
protected String unquote(String s) {
return (isQuotedString(s) ? s.substring(1, s.length() - 1) : s);
}
/**
* Indicates whether the {@linkplain #getType() type} is the wildcard character
* <code>*</code> or not.
*/
public boolean isWildcardType() {
return WILDCARD_TYPE.equals(getType());
}
/**
* Indicates whether the {@linkplain #getSubtype() subtype} is the wildcard
* character <code>*</code> or the wildcard character followed by a suffix
* (for example, <code>*+xml</code>).
* @return whether the subtype is a wildcard
*/
public boolean isWildcardSubtype() {
String subtype = getSubtype();
return (WILDCARD_TYPE.equals(subtype) || subtype.startsWith("*+"));
}
/**
* Indicates whether this MIME Type is concrete, i.e. whether neither the type
* nor the subtype is a wildcard character <code>*</code>.
* @return whether this MIME Type is concrete
*/
public boolean isConcrete() {
return !isWildcardType() && !isWildcardSubtype();
}
/**
* Return the primary type.
*/
public String getType() {
return this.type;
}
/**
* Return the subtype.
*/
public String getSubtype() {
return this.subtype;
}
/**
* Return the subtype suffix as defined in RFC 6839.
* @since 5.3
*/
public @Nullable String getSubtypeSuffix() {
int suffixIndex = this.subtype.lastIndexOf('+');
if (suffixIndex != -1 && this.subtype.length() > suffixIndex) {
return this.subtype.substring(suffixIndex + 1);
}
return null;
}
/**
* Return the character set, as indicated by a {@code charset} parameter, if any.
* @return the character set, or {@code null} if not available
* @since 4.3
*/
public @Nullable Charset getCharset() {
return this.resolvedCharset;
}
/**
* Return a generic parameter value, given a parameter name.
* @param name the parameter name
* @return the parameter value, or {@code null} if not present
*/
public @Nullable String getParameter(String name) {
return this.parameters.get(name);
}
/**
* Return all generic parameter values.
* @return a read-only map (possibly empty, never {@code null})
*/
public Map<String, String> getParameters() {
return this.parameters;
}
/**
* Indicate whether this MIME Type includes the given MIME Type.
* <p>For instance, {@code text/*} includes {@code text/plain} and {@code text/html},
* and {@code application/*+xml} includes {@code application/soap+xml}, etc.
* This method is <b>not</b> symmetric.
* @param other the reference MIME Type with which to compare
* @return {@code true} if this MIME Type includes the given MIME Type;
* {@code false} otherwise
*/
public boolean includes(@Nullable MimeType other) {
if (other == null) {
return false;
}
if (isWildcardType()) {
// */* includes anything
return true;
}
else if (getType().equals(other.getType())) {
if (getSubtype().equals(other.getSubtype())) {
return true;
}
if (isWildcardSubtype()) {
// Wildcard with suffix, for example, application/*+xml
int thisPlusIdx = getSubtype().lastIndexOf('+');
if (thisPlusIdx == -1) {
return true;
}
else {
// application/*+xml includes application/soap+xml
int otherPlusIdx = other.getSubtype().lastIndexOf('+');
if (otherPlusIdx != -1) {
String thisSubtypeNoSuffix = getSubtype().substring(0, thisPlusIdx);
String thisSubtypeSuffix = getSubtype().substring(thisPlusIdx + 1);
String otherSubtypeSuffix = other.getSubtype().substring(otherPlusIdx + 1);
if (thisSubtypeSuffix.equals(otherSubtypeSuffix) && WILDCARD_TYPE.equals(thisSubtypeNoSuffix)) {
return true;
}
}
}
}
}
return false;
}
/**
* Indicate whether this MIME Type is compatible with the given MIME Type.
* <p>For instance, {@code text/*} is compatible with {@code text/plain},
* {@code text/html}, and vice versa. In effect, this method is similar to
* {@link #includes}, except that it <b>is</b> symmetric.
* @param other the reference MIME Type with which to compare
* @return {@code true} if this MIME Type is compatible with the given MIME Type;
* {@code false} otherwise
*/
public boolean isCompatibleWith(@Nullable MimeType other) {
if (other == null) {
return false;
}
if (isWildcardType() || other.isWildcardType()) {
return true;
}
else if (getType().equals(other.getType())) {
if (getSubtype().equals(other.getSubtype())) {
return true;
}
if (isWildcardSubtype() || other.isWildcardSubtype()) {
String thisSuffix = getSubtypeSuffix();
String otherSuffix = other.getSubtypeSuffix();
if (getSubtype().equals(WILDCARD_TYPE) || other.getSubtype().equals(WILDCARD_TYPE)) {
return true;
}
else if (isWildcardSubtype() && thisSuffix != null) {
return (thisSuffix.equals(other.getSubtype()) || thisSuffix.equals(otherSuffix));
}
else if (other.isWildcardSubtype() && otherSuffix != null) {
return (getSubtype().equals(otherSuffix) || otherSuffix.equals(thisSuffix));
}
}
}
return false;
}
/**
* Similar to {@link #equals(Object)} but based on the type and subtype
* only, i.e. ignoring parameters.
* @param other the other mime type to compare to
* @return whether the two mime types have the same type and subtype
* @since 5.1.4
*/
public boolean equalsTypeAndSubtype(@Nullable MimeType other) {
if (other == null) {
return false;
}
return this.type.equalsIgnoreCase(other.type) && this.subtype.equalsIgnoreCase(other.subtype);
}
/**
* Unlike {@link Collection#contains(Object)} which relies on
* {@link MimeType#equals(Object)}, this method only checks the type and the
* subtype, but otherwise ignores parameters.
* @param mimeTypes the list of mime types to perform the check against
* @return whether the list contains the given mime type
* @since 5.1.4
*/
public boolean isPresentIn(Collection<? extends MimeType> mimeTypes) {
for (MimeType mimeType : mimeTypes) {
if (mimeType.equalsTypeAndSubtype(this)) {
return true;
}
}
return false;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof MimeType otherType &&
this.type.equalsIgnoreCase(otherType.type) &&
this.subtype.equalsIgnoreCase(otherType.subtype) &&
parametersAreEqual(otherType)));
}
/**
* Determine if the parameters in this {@code MimeType} and the supplied
* {@code MimeType} are equal, performing case-insensitive comparisons
* for {@link Charset Charsets}.
* @since 4.2
*/
private boolean parametersAreEqual(MimeType other) {
if (this.parameters.size() != other.parameters.size()) {
return false;
}
for (Map.Entry<String, String> entry : this.parameters.entrySet()) {
String key = entry.getKey();
if (!other.parameters.containsKey(key)) {
return false;
}
if (PARAM_CHARSET.equals(key)) {
if (!ObjectUtils.nullSafeEquals(getCharset(), other.getCharset())) {
return false;
}
}
else if (!ObjectUtils.nullSafeEquals(entry.getValue(), other.parameters.get(key))) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int result = this.type.hashCode();
result = 31 * result + this.subtype.hashCode();
result = 31 * result + this.parameters.hashCode();
return result;
}
@Override
public String toString() {
String value = this.toStringValue;
if (value == null) {
StringBuilder builder = new StringBuilder();
appendTo(builder);
value = builder.toString();
this.toStringValue = value;
}
return value;
}
protected void appendTo(StringBuilder builder) {
builder.append(this.type);
builder.append('/');
builder.append(this.subtype);
appendTo(this.parameters, builder);
}
private void appendTo(Map<String, String> map, StringBuilder builder) {
map.forEach((key, val) -> {
builder.append(';');
builder.append(key);
builder.append('=');
builder.append(val);
});
}
/**
* Compares this MIME Type to another alphabetically.
* @param other the MIME Type to compare to
*/
@Override
public int compareTo(MimeType other) {
int comp = getType().compareToIgnoreCase(other.getType());
if (comp != 0) {
return comp;
}
comp = getSubtype().compareToIgnoreCase(other.getSubtype());
if (comp != 0) {
return comp;
}
comp = getParameters().size() - other.getParameters().size();
if (comp != 0) {
return comp;
}
TreeSet<String> thisAttributes = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
thisAttributes.addAll(getParameters().keySet());
TreeSet<String> otherAttributes = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
otherAttributes.addAll(other.getParameters().keySet());
Iterator<String> thisAttributesIterator = thisAttributes.iterator();
Iterator<String> otherAttributesIterator = otherAttributes.iterator();
while (thisAttributesIterator.hasNext()) {
String thisAttribute = thisAttributesIterator.next();
String otherAttribute = otherAttributesIterator.next();
comp = thisAttribute.compareToIgnoreCase(otherAttribute);
if (comp != 0) {
return comp;
}
if (PARAM_CHARSET.equals(thisAttribute)) {
Charset thisCharset = getCharset();
Charset otherCharset = other.getCharset();
if (thisCharset != otherCharset) {
if (thisCharset == null) {
return -1;
}
if (otherCharset == null) {
return 1;
}
comp = thisCharset.compareTo(otherCharset);
if (comp != 0) {
return comp;
}
}
}
else {
String thisValue = getParameters().get(thisAttribute);
String otherValue = other.getParameters().get(otherAttribute);
Assert.notNull(thisValue, "Parameter for " + thisAttribute + " must not be null");
if (otherValue == null) {
otherValue = "";
}
comp = thisValue.compareTo(otherValue);
if (comp != 0) {
return comp;
}
}
}
return 0;
}
/**
* Indicates whether this {@code MimeType} is more specific than the given
* type.
* <ol>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code false}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code true}.</li>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code false}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code true}.</li>
* <li>if the two mime types have identical {@linkplain #getType() type} and
* {@linkplain #getSubtype() subtype}, then the mime type with the most
* parameters is more specific than the other.</li>
* <li>Otherwise, this method returns {@code false}.</li>
* </ol>
* @param other the {@code MimeType} to be compared
* @return the result of the comparison
* @since 6.0
* @see #isLessSpecific(MimeType)
* @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">HTTP 1.1: Semantics
* and Content, section 5.3.2</a>
*/
public boolean isMoreSpecific(MimeType other) {
Assert.notNull(other, "Other must not be null");
boolean thisWildcard = isWildcardType();
boolean otherWildcard = other.isWildcardType();
if (thisWildcard && !otherWildcard) { // */* > audio/*
return false;
}
else if (!thisWildcard && otherWildcard) { // audio/* < */*
return true;
}
else {
boolean thisWildcardSubtype = isWildcardSubtype();
boolean otherWildcardSubtype = other.isWildcardSubtype();
if (thisWildcardSubtype && !otherWildcardSubtype) { // audio/* > audio/basic
return false;
}
else if (!thisWildcardSubtype && otherWildcardSubtype) { // audio/basic < audio/*
return true;
}
else if (getType().equals(other.getType()) && getSubtype().equals(other.getSubtype())) {
int paramsSize1 = getParameters().size();
int paramsSize2 = other.getParameters().size();
return paramsSize1 > paramsSize2;
}
else {
return false;
}
}
}
/**
* Indicates whether this {@code MimeType} is less specific than the given type.
* <ol>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code true}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code false}.</li>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code true}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code false}.</li>
* <li>if the two mime types have identical {@linkplain #getType() type} and
* {@linkplain #getSubtype() subtype}, then the mime type with the least
* parameters is less specific than the other.</li>
* <li>Otherwise, this method returns {@code false}.</li>
* </ol>
* @param other the {@code MimeType} to be compared
* @return the result of the comparison
* @since 6.0
* @see #isMoreSpecific(MimeType)
* @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">HTTP 1.1: Semantics
* and Content, section 5.3.2</a>
*/
public boolean isLessSpecific(MimeType other) {
Assert.notNull(other, "Other must not be null");
return other.isMoreSpecific(this);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Rely on default serialization, just initialize state after deserialization.
ois.defaultReadObject();
// Initialize transient fields.
String charsetName = getParameter(PARAM_CHARSET);
if (charsetName != null) {
this.resolvedCharset = Charset.forName(unquote(charsetName));
}
}
/**
* Parse the given String value into a {@code MimeType} object,
* with this method name following the 'valueOf' naming convention
* (as supported by {@link org.springframework.core.convert.ConversionService}).
* @see MimeTypeUtils#parseMimeType(String)
*/
public static MimeType valueOf(String value) {
return MimeTypeUtils.parseMimeType(value);
}
private static Map<String, String> addCharsetParameter(Charset charset, Map<String, String> parameters) {
Map<String, String> map = new LinkedHashMap<>(parameters);
map.put(PARAM_CHARSET, charset.name());
return map;
}
}
| MimeType |
java | google__guava | android/guava/src/com/google/common/collect/StandardTable.java | {
"start": 22380,
"end": 23775
} | class ____ extends AbstractIterator<C> {
// Use the same map type to support TreeMaps with comparators that aren't
// consistent with equals().
final Map<C, V> seen = factory.get();
final Iterator<Map<C, V>> mapIterator = backingMap.values().iterator();
Iterator<Entry<C, V>> entryIterator = emptyIterator();
@Override
protected @Nullable C computeNext() {
while (true) {
if (entryIterator.hasNext()) {
Entry<C, V> entry = entryIterator.next();
if (!seen.containsKey(entry.getKey())) {
seen.put(entry.getKey(), entry.getValue());
return entry.getKey();
}
} else if (mapIterator.hasNext()) {
entryIterator = mapIterator.next().entrySet().iterator();
} else {
return endOfData();
}
}
}
}
/**
* {@inheritDoc}
*
* <p>The collection's iterator traverses the values for the first row, the values for the second
* row, and so on.
*/
@Override
public Collection<V> values() {
return super.values();
}
@LazyInit private transient @Nullable Map<R, Map<C, V>> rowMap;
@Override
public Map<R, Map<C, V>> rowMap() {
Map<R, Map<C, V>> result = rowMap;
return (result == null) ? rowMap = createRowMap() : result;
}
Map<R, Map<C, V>> createRowMap() {
return new RowMap();
}
@WeakOuter
| ColumnKeyIterator |
java | apache__flink | flink-connectors/flink-file-sink-common/src/main/java/org/apache/flink/streaming/api/functions/sink/filesystem/RecordWiseCompactingFileWriter.java | {
"start": 1078,
"end": 1387
} | interface ____<IN> extends CompactingFileWriter {
/**
* Write an element to the compacting file.
*
* @param element the element to be written.
* @throws IOException Thrown if writing the element fails.
*/
void write(IN element) throws IOException;
}
| RecordWiseCompactingFileWriter |
java | spring-projects__spring-boot | module/spring-boot-resttestclient/src/test/java/org/springframework/boot/resttestclient/autoconfigure/RestTestClientAutoConfigurationTests.java | {
"start": 5143,
"end": 5410
} | class ____ implements LocalTestWebServer.Provider {
@Override
public @Nullable LocalTestWebServer getLocalTestWebServer() {
return LocalTestWebServer.of(Scheme.HTTPS, 8182);
}
}
@Configuration(proxyBeanMethods = false)
static | TestLocalTestWebServerProvider |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/spi/StandardLevel.java | {
"start": 943,
"end": 1002
} | enum ____ used as a parameter in any public APIs.
*/
public | is |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/StringJoinTest.java | {
"start": 1379,
"end": 1642
} | class ____ {
private static final String JOINED = "";
}
""")
.doTest();
}
@Test
public void twoCharSequenceParams() {
testHelper
.addInputLines(
"Test.java",
"""
| Test |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/long_/LongAssert_isCloseTo_long_Test.java | {
"start": 874,
"end": 1292
} | class ____ extends LongAssertBaseTest {
private final Offset<Long> offset = offset(5L);
private final Long value = 8L;
@Override
protected LongAssert invoke_api_method() {
return assertions.isCloseTo(value, offset);
}
@Override
protected void verify_internal_effects() {
verify(longs).assertIsCloseTo(getInfo(assertions), getActual(assertions), value, offset);
}
}
| LongAssert_isCloseTo_long_Test |
java | apache__camel | components/camel-debezium/camel-debezium-sqlserver/src/generated/java/org/apache/camel/component/debezium/sqlserver/configuration/SqlServerConnectorEmbeddedDebeziumConfiguration.java | {
"start": 49459,
"end": 61997
} | class ____ should be used to store and
* recover database schema changes. The configuration properties for the
* history are prefixed with the 'schema.history.internal.' string.
*/
public void setSchemaHistoryInternal(String schemaHistoryInternal) {
this.schemaHistoryInternal = schemaHistoryInternal;
}
public String getSchemaHistoryInternal() {
return schemaHistoryInternal;
}
/**
* This property can be used to reduce the connector memory usage footprint
* when changes are streamed from multiple tables per database.
*/
public void setMaxIterationTransactions(int maxIterationTransactions) {
this.maxIterationTransactions = maxIterationTransactions;
}
public int getMaxIterationTransactions() {
return maxIterationTransactions;
}
/**
* Regular expressions matching columns to exclude from change events
*/
public void setColumnExcludeList(String columnExcludeList) {
this.columnExcludeList = columnExcludeList;
}
public String getColumnExcludeList() {
return columnExcludeList;
}
/**
* Resolvable hostname or IP address of the database server.
*/
public void setDatabaseHostname(String databaseHostname) {
this.databaseHostname = databaseHostname;
}
public String getDatabaseHostname() {
return databaseHostname;
}
/**
* Specify how schema names should be adjusted for compatibility with the
* message converter used by the connector, including: 'avro' replaces the
* characters that cannot be used in the Avro type name with underscore;
* 'avro_unicode' replaces the underscore or characters that cannot be used
* in the Avro type name with corresponding unicode like _uxxxx. Note: _ is
* an escape sequence like backslash in Java;'none' does not apply any
* adjustment (default)
*/
public void setSchemaNameAdjustmentMode(String schemaNameAdjustmentMode) {
this.schemaNameAdjustmentMode = schemaNameAdjustmentMode;
}
public String getSchemaNameAdjustmentMode() {
return schemaNameAdjustmentMode;
}
/**
* The tables for which changes are to be captured
*/
public void setTableIncludeList(String tableIncludeList) {
this.tableIncludeList = tableIncludeList;
}
public String getTableIncludeList() {
return tableIncludeList;
}
/**
* The maximum time in milliseconds to wait for connection validation to
* complete. Defaults to 60 seconds.
*/
public void setConnectionValidationTimeoutMs(
long connectionValidationTimeoutMs) {
this.connectionValidationTimeoutMs = connectionValidationTimeoutMs;
}
public long getConnectionValidationTimeoutMs() {
return connectionValidationTimeoutMs;
}
@Override
protected Configuration createConnectorConfiguration() {
final Configuration.Builder configBuilder = Configuration.create();
addPropertyIfNotNull(configBuilder, "message.key.columns", messageKeyColumns);
addPropertyIfNotNull(configBuilder, "transaction.metadata.factory", transactionMetadataFactory);
addPropertyIfNotNull(configBuilder, "streaming.delay.ms", streamingDelayMs);
addPropertyIfNotNull(configBuilder, "custom.metric.tags", customMetricTags);
addPropertyIfNotNull(configBuilder, "openlineage.integration.job.namespace", openlineageIntegrationJobNamespace);
addPropertyIfNotNull(configBuilder, "database.query.timeout.ms", databaseQueryTimeoutMs);
addPropertyIfNotNull(configBuilder, "data.query.mode", dataQueryMode);
addPropertyIfNotNull(configBuilder, "signal.enabled.channels", signalEnabledChannels);
addPropertyIfNotNull(configBuilder, "database.instance", databaseInstance);
addPropertyIfNotNull(configBuilder, "include.schema.changes", includeSchemaChanges);
addPropertyIfNotNull(configBuilder, "heartbeat.action.query", heartbeatActionQuery);
addPropertyIfNotNull(configBuilder, "poll.interval.ms", pollIntervalMs);
addPropertyIfNotNull(configBuilder, "guardrail.collections.max", guardrailCollectionsMax);
addPropertyIfNotNull(configBuilder, "signal.data.collection", signalDataCollection);
addPropertyIfNotNull(configBuilder, "converters", converters);
addPropertyIfNotNull(configBuilder, "heartbeat.topics.prefix", heartbeatTopicsPrefix);
addPropertyIfNotNull(configBuilder, "snapshot.fetch.size", snapshotFetchSize);
addPropertyIfNotNull(configBuilder, "openlineage.integration.job.tags", openlineageIntegrationJobTags);
addPropertyIfNotNull(configBuilder, "snapshot.lock.timeout.ms", snapshotLockTimeoutMs);
addPropertyIfNotNull(configBuilder, "database.user", databaseUser);
addPropertyIfNotNull(configBuilder, "datatype.propagate.source.type", datatypePropagateSourceType);
addPropertyIfNotNull(configBuilder, "database.names", databaseNames);
addPropertyIfNotNull(configBuilder, "snapshot.tables.order.by.row.count", snapshotTablesOrderByRowCount);
addPropertyIfNotNull(configBuilder, "incremental.snapshot.watermarking.strategy", incrementalSnapshotWatermarkingStrategy);
addPropertyIfNotNull(configBuilder, "snapshot.select.statement.overrides", snapshotSelectStatementOverrides);
addPropertyIfNotNull(configBuilder, "heartbeat.interval.ms", heartbeatIntervalMs);
addPropertyIfNotNull(configBuilder, "snapshot.mode.configuration.based.snapshot.on.schema.error", snapshotModeConfigurationBasedSnapshotOnSchemaError);
addPropertyIfNotNull(configBuilder, "incremental.snapshot.allow.schema.changes", incrementalSnapshotAllowSchemaChanges);
addPropertyIfNotNull(configBuilder, "schema.history.internal.skip.unparseable.ddl", schemaHistoryInternalSkipUnparseableDdl);
addPropertyIfNotNull(configBuilder, "column.include.list", columnIncludeList);
addPropertyIfNotNull(configBuilder, "column.propagate.source.type", columnPropagateSourceType);
addPropertyIfNotNull(configBuilder, "errors.max.retries", errorsMaxRetries);
addPropertyIfNotNull(configBuilder, "streaming.fetch.size", streamingFetchSize);
addPropertyIfNotNull(configBuilder, "table.exclude.list", tableExcludeList);
addPropertyIfNotNull(configBuilder, "database.password", databasePassword);
addPropertyIfNotNull(configBuilder, "max.batch.size", maxBatchSize);
addPropertyIfNotNull(configBuilder, "skipped.operations", skippedOperations);
addPropertyIfNotNull(configBuilder, "openlineage.integration.job.description", openlineageIntegrationJobDescription);
addPropertyIfNotNull(configBuilder, "topic.naming.strategy", topicNamingStrategy);
addPropertyIfNotNull(configBuilder, "snapshot.mode", snapshotMode);
addPropertyIfNotNull(configBuilder, "snapshot.mode.configuration.based.snapshot.data", snapshotModeConfigurationBasedSnapshotData);
addPropertyIfNotNull(configBuilder, "extended.headers.enabled", extendedHeadersEnabled);
addPropertyIfNotNull(configBuilder, "max.queue.size", maxQueueSize);
addPropertyIfNotNull(configBuilder, "guardrail.collections.limit.action", guardrailCollectionsLimitAction);
addPropertyIfNotNull(configBuilder, "incremental.snapshot.chunk.size", incrementalSnapshotChunkSize);
addPropertyIfNotNull(configBuilder, "openlineage.integration.job.owners", openlineageIntegrationJobOwners);
addPropertyIfNotNull(configBuilder, "openlineage.integration.config.file.path", openlineageIntegrationConfigFilePath);
addPropertyIfNotNull(configBuilder, "retriable.restart.connector.wait.ms", retriableRestartConnectorWaitMs);
addPropertyIfNotNull(configBuilder, "snapshot.delay.ms", snapshotDelayMs);
addPropertyIfNotNull(configBuilder, "executor.shutdown.timeout.ms", executorShutdownTimeoutMs);
addPropertyIfNotNull(configBuilder, "provide.transaction.metadata", provideTransactionMetadata);
addPropertyIfNotNull(configBuilder, "schema.history.internal.store.only.captured.tables.ddl", schemaHistoryInternalStoreOnlyCapturedTablesDdl);
addPropertyIfNotNull(configBuilder, "schema.history.internal.store.only.captured.databases.ddl", schemaHistoryInternalStoreOnlyCapturedDatabasesDdl);
addPropertyIfNotNull(configBuilder, "snapshot.mode.configuration.based.snapshot.on.data.error", snapshotModeConfigurationBasedSnapshotOnDataError);
addPropertyIfNotNull(configBuilder, "schema.history.internal.file.filename", schemaHistoryInternalFileFilename);
addPropertyIfNotNull(configBuilder, "tombstones.on.delete", tombstonesOnDelete);
addPropertyIfNotNull(configBuilder, "topic.prefix", topicPrefix);
addPropertyIfNotNull(configBuilder, "decimal.handling.mode", decimalHandlingMode);
addPropertyIfNotNull(configBuilder, "binary.handling.mode", binaryHandlingMode);
addPropertyIfNotNull(configBuilder, "include.schema.comments", includeSchemaComments);
addPropertyIfNotNull(configBuilder, "sourceinfo.struct.maker", sourceinfoStructMaker);
addPropertyIfNotNull(configBuilder, "openlineage.integration.dataset.kafka.bootstrap.servers", openlineageIntegrationDatasetKafkaBootstrapServers);
addPropertyIfNotNull(configBuilder, "table.ignore.builtin", tableIgnoreBuiltin);
addPropertyIfNotNull(configBuilder, "incremental.snapshot.option.recompile", incrementalSnapshotOptionRecompile);
addPropertyIfNotNull(configBuilder, "openlineage.integration.enabled", openlineageIntegrationEnabled);
addPropertyIfNotNull(configBuilder, "snapshot.include.collection.list", snapshotIncludeCollectionList);
addPropertyIfNotNull(configBuilder, "snapshot.mode.configuration.based.start.stream", snapshotModeConfigurationBasedStartStream);
addPropertyIfNotNull(configBuilder, "max.queue.size.in.bytes", maxQueueSizeInBytes);
addPropertyIfNotNull(configBuilder, "snapshot.mode.configuration.based.snapshot.schema", snapshotModeConfigurationBasedSnapshotSchema);
addPropertyIfNotNull(configBuilder, "time.precision.mode", timePrecisionMode);
addPropertyIfNotNull(configBuilder, "signal.poll.interval.ms", signalPollIntervalMs);
addPropertyIfNotNull(configBuilder, "post.processors", postProcessors);
addPropertyIfNotNull(configBuilder, "notification.enabled.channels", notificationEnabledChannels);
addPropertyIfNotNull(configBuilder, "event.processing.failure.handling.mode", eventProcessingFailureHandlingMode);
addPropertyIfNotNull(configBuilder, "snapshot.isolation.mode", snapshotIsolationMode);
addPropertyIfNotNull(configBuilder, "snapshot.max.threads", snapshotMaxThreads);
addPropertyIfNotNull(configBuilder, "database.port", databasePort);
addPropertyIfNotNull(configBuilder, "notification.sink.topic.name", notificationSinkTopicName);
addPropertyIfNotNull(configBuilder, "snapshot.mode.custom.name", snapshotModeCustomName);
addPropertyIfNotNull(configBuilder, "schema.history.internal", schemaHistoryInternal);
addPropertyIfNotNull(configBuilder, "max.iteration.transactions", maxIterationTransactions);
addPropertyIfNotNull(configBuilder, "column.exclude.list", columnExcludeList);
addPropertyIfNotNull(configBuilder, "database.hostname", databaseHostname);
addPropertyIfNotNull(configBuilder, "schema.name.adjustment.mode", schemaNameAdjustmentMode);
addPropertyIfNotNull(configBuilder, "table.include.list", tableIncludeList);
addPropertyIfNotNull(configBuilder, "connection.validation.timeout.ms", connectionValidationTimeoutMs);
return configBuilder.build();
}
@Override
protected Class configureConnectorClass() {
return SqlServerConnector.class;
}
@Override
protected ConfigurationValidation validateConnectorConfiguration() {
if (isFieldValueNotSet(databasePassword)) {
return ConfigurationValidation.notValid("Required field 'databasePassword' must be set.");
}
if (isFieldValueNotSet(topicPrefix)) {
return ConfigurationValidation.notValid("Required field 'topicPrefix' must be set.");
}
return ConfigurationValidation.valid();
}
@Override
public String getConnectorDatabaseType() {
return "sqlserver";
}
} | that |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/JSON_toJavaObject_test.java | {
"start": 727,
"end": 770
} | class ____ extends A implements IB {
}
}
| B |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/connector/source/util/ratelimit/RateLimiter.java | {
"start": 1086,
"end": 1225
} | interface ____ rate limit execution of methods.
*
* @param <SplitT> The type of the source splits.
*/
@NotThreadSafe
@Experimental
public | to |
java | elastic__elasticsearch | x-pack/plugin/analytics/src/main/java/org/elasticsearch/xpack/analytics/stringstats/InternalStringStats.java | {
"start": 1037,
"end": 1098
} | class ____ extends InternalAggregation {
| InternalStringStats |
java | spring-projects__spring-boot | core/spring-boot-test/src/test/java/org/springframework/boot/test/http/client/DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactoryTests.java | {
"start": 1231,
"end": 1531
} | class ____ {
@Autowired
private ReactorResourceFactory reactorResourceFactory;
@Test
void disablesUseGlobalResources() {
assertThat(this.reactorResourceFactory.isUseGlobalResources()).isFalse();
}
@Configuration
static | DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactoryTests |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 74154,
"end": 74582
} | class ____ {
private @Nullable FooEnum theValue;
private @Nullable List<FooEnum> theValues;
void setTheValue(@Nullable FooEnum value) {
this.theValue = value;
}
@Nullable FooEnum getTheValue() {
return this.theValue;
}
@Nullable List<FooEnum> getTheValues() {
return this.theValues;
}
void setTheValues(@Nullable List<FooEnum> theValues) {
this.theValues = theValues;
}
}
| WithEnumProperties |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContextTransient.java | {
"start": 812,
"end": 3572
} | class ____<T> {
private final String key;
private final Class<T> type;
private ThreadContextTransient(String key, Class<T> type) {
this.key = key;
this.type = type;
}
/**
* @return The key/name of the transient header
*/
public String getKey() {
return key;
}
/**
* @return {@code true} if the thread context contains a non-null value for this {@link #getKey() key}
*/
public boolean exists(ThreadContext threadContext) {
return threadContext.getTransient(key) != null;
}
/**
* @return The current value for this {@link #getKey() key}. May be {@code null}.
*/
@Nullable
public T get(ThreadContext threadContext) {
final Object val = threadContext.getTransient(key);
if (val == null) {
return null;
}
if (this.type.isInstance(val)) {
return this.type.cast(val);
} else {
final String message = Strings.format(
"Found object of type [%s] as transient [%s] in thread-context, but expected it to be [%s]",
val.getClass(),
key,
type
);
assert false : message;
throw new IllegalStateException(message);
}
}
/**
* @return The current value for this {@link #getKey() key}. May not be {@code null}
* @throws IllegalStateException if the thread context does not contain a value (or contains {@code null}).
*/
public T require(ThreadContext threadContext) {
final T value = get(threadContext);
if (value == null) {
throw new IllegalStateException("Cannot find value for [" + key + "] in thread-context");
}
return value;
}
/**
* Set the value for the this {@link #getKey() key}.
* Because transient headers cannot be overwritten, this method will throw an exception if a value already exists
* @see ThreadContext#putTransient(String, Object)
*/
public void set(ThreadContext threadContext, T value) {
threadContext.putTransient(this.key, value);
}
/**
* Set the value for the this {@link #getKey() key}, if and only if there is no current value
* @return {@code true} if the value was set, {@code false} otherwise
*/
public boolean setIfEmpty(ThreadContext threadContext, T value) {
if (exists(threadContext) == false) {
set(threadContext, value);
return true;
} else {
return false;
}
}
public static <T> ThreadContextTransient<T> transientValue(String key, Class<T> type) {
return new ThreadContextTransient<>(key, type);
}
}
| ThreadContextTransient |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableChange.java | {
"start": 1579,
"end": 10818
} | interface ____ {
/**
* Create a TableChange for setting a table property.
* <p>
* If the property already exists, it will be replaced with the new value.
*
* @param property the property name
* @param value the new property value
* @return a TableChange for the addition
*/
static TableChange setProperty(String property, String value) {
return new SetProperty(property, value);
}
/**
* Create a TableChange for removing a table property.
* <p>
* If the property does not exist, the change will succeed.
*
* @param property the property name
* @return a TableChange for the addition
*/
static TableChange removeProperty(String property) {
return new RemoveProperty(property);
}
/**
* Create a TableChange for adding an optional column.
* <p>
* If the field already exists, the change will result in an {@link IllegalArgumentException}.
* If the new field is nested and its parent does not exist or is not a struct, the change will
* result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the new column
* @param dataType the new column's data type
* @return a TableChange for the addition
*/
static TableChange addColumn(String[] fieldNames, DataType dataType) {
return new AddColumn(fieldNames, dataType, true, null, null, null);
}
/**
* Create a TableChange for adding a column.
* <p>
* If the field already exists, the change will result in an {@link IllegalArgumentException}.
* If the new field is nested and its parent does not exist or is not a struct, the change will
* result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the new column
* @param dataType the new column's data type
* @param isNullable whether the new column can contain null
* @return a TableChange for the addition
*/
static TableChange addColumn(String[] fieldNames, DataType dataType, boolean isNullable) {
return new AddColumn(fieldNames, dataType, isNullable, null, null, null);
}
/**
* Create a TableChange for adding a column.
* <p>
* If the field already exists, the change will result in an {@link IllegalArgumentException}.
* If the new field is nested and its parent does not exist or is not a struct, the change will
* result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the new column
* @param dataType the new column's data type
* @param isNullable whether the new column can contain null
* @param comment the new field's comment string
* @return a TableChange for the addition
*/
static TableChange addColumn(
String[] fieldNames,
DataType dataType,
boolean isNullable,
String comment) {
return new AddColumn(fieldNames, dataType, isNullable, comment, null, null);
}
/**
* Create a TableChange for adding a column.
* <p>
* If the field already exists, the change will result in an {@link IllegalArgumentException}.
* If the new field is nested and its parent does not exist or is not a struct, the change will
* result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the new column
* @param dataType the new column's data type
* @param isNullable whether the new column can contain null
* @param comment the new field's comment string
* @param position the new columns's position
* @param defaultValue default value to return when scanning from the new column, if any
* @return a TableChange for the addition
*/
static TableChange addColumn(
String[] fieldNames,
DataType dataType,
boolean isNullable,
String comment,
ColumnPosition position,
ColumnDefaultValue defaultValue) {
return new AddColumn(fieldNames, dataType, isNullable, comment, position, defaultValue);
}
/**
* Create a TableChange for renaming a field.
* <p>
* The name is used to find the field to rename. The new name will replace the leaf field name.
* For example, renameColumn(["a", "b", "c"], "x") should produce column a.b.x.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames the current field names
* @param newName the new name
* @return a TableChange for the rename
*/
static TableChange renameColumn(String[] fieldNames, String newName) {
return new RenameColumn(fieldNames, newName);
}
/**
* Create a TableChange for updating the type of a field that is nullable.
* <p>
* The field names are used to find the field to update.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the column to update
* @param newDataType the new data type
* @return a TableChange for the update
*/
static TableChange updateColumnType(String[] fieldNames, DataType newDataType) {
return new UpdateColumnType(fieldNames, newDataType);
}
/**
* Create a TableChange for updating the nullability of a field.
* <p>
* The name is used to find the field to update.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the column to update
* @param nullable the nullability
* @return a TableChange for the update
*/
static TableChange updateColumnNullability(String[] fieldNames, boolean nullable) {
return new UpdateColumnNullability(fieldNames, nullable);
}
/**
* Create a TableChange for updating the comment of a field.
* <p>
* The name is used to find the field to update.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the column to update
* @param newComment the new comment
* @return a TableChange for the update
*/
static TableChange updateColumnComment(String[] fieldNames, String newComment) {
return new UpdateColumnComment(fieldNames, newComment);
}
/**
* Create a TableChange for updating the position of a field.
* <p>
* The name is used to find the field to update.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the column to update
* @param newPosition the new position
* @return a TableChange for the update
*/
static TableChange updateColumnPosition(String[] fieldNames, ColumnPosition newPosition) {
return new UpdateColumnPosition(fieldNames, newPosition);
}
/**
* Create a TableChange for updating the default value of a field.
* <p>
* The name is used to find the field to update.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the column to update
* @param newDefaultValue the new default value SQL string (Spark SQL dialect).
* @return a TableChange for the update
*
* @deprecated Please use {@link #updateColumnDefaultValue(String[], DefaultValue)} instead.
*/
@Deprecated(since = "4.1.0")
static TableChange updateColumnDefaultValue(String[] fieldNames, String newDefaultValue) {
return new UpdateColumnDefaultValue(fieldNames, new ColumnDefaultValue(newDefaultValue, null));
}
/**
* Create a TableChange for updating the default value of a field.
* <p>
* The name is used to find the field to update.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the column to update
* @param newDefaultValue the new default value SQL (Spark SQL dialect and
* V2 expression representation if it can be converted).
* Null indicates dropping column default value
* @return a TableChange for the update
*/
static TableChange updateColumnDefaultValue(String[] fieldNames, DefaultValue newDefaultValue) {
return new UpdateColumnDefaultValue(fieldNames, newDefaultValue);
}
/**
* Create a TableChange for deleting a field.
* <p>
* If the field does not exist, the change will result in an {@link IllegalArgumentException}.
*
* @param fieldNames field names of the column to delete
* @param ifExists silence the error if column doesn't exist during drop
* @return a TableChange for the delete
*/
static TableChange deleteColumn(String[] fieldNames, Boolean ifExists) {
return new DeleteColumn(fieldNames, ifExists);
}
/**
* Create a TableChange for changing clustering columns for a table.
*
* @param clusteringColumns clustering columns to change to. Each clustering column represents
* field names.
* @return a TableChange for this assignment
*/
static TableChange clusterBy(NamedReference[] clusteringColumns) {
return new ClusterBy(clusteringColumns);
}
/**
* A TableChange to set a table property.
* <p>
* If the property already exists, it must be replaced with the new value.
*/
final | TableChange |
java | resilience4j__resilience4j | resilience4j-spring/src/main/java/io/github/resilience4j/utils/RxJava3OnClasspathCondition.java | {
"start": 354,
"end": 1238
} | class ____ implements Condition {
private static final Logger logger = LoggerFactory.getLogger(RxJava3OnClasspathCondition.class);
private static final String CLASS_TO_CHECK = "io.reactivex.rxjava3.core.Flowable";
private static final String R4J_RXJAVA3 = "io.github.resilience4j.rxjava3.AbstractSubscriber";
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return AspectUtil.checkClassIfFound(context, CLASS_TO_CHECK, (e) -> logger.debug(
"RxJava3 related Aspect extensions are not activated, because RxJava3 is not on the classpath."))
&& AspectUtil.checkClassIfFound(context, R4J_RXJAVA3, (e) -> logger.debug(
"RxJava3 related Aspect extensions are not activated because Resilience4j RxJava3 module is not on the classpath."));
}
}
| RxJava3OnClasspathCondition |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestFileContext.java | {
"start": 1173,
"end": 3396
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(TestFileContext
.class);
@Test
public void testDefaultURIWithoutScheme() throws Exception {
final Configuration conf = new Configuration();
conf.set(FileSystem.FS_DEFAULT_NAME_KEY, "/");
try {
FileContext.getFileContext(conf);
fail(UnsupportedFileSystemException.class + " not thrown!");
} catch (UnsupportedFileSystemException ufse) {
LOG.info("Expected exception: ", ufse);
}
}
@Test
public void testConfBasedAndAPIBasedSetUMask() throws Exception {
Configuration conf = new Configuration();
String defaultlUMask =
conf.get(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY);
assertEquals("022", defaultlUMask, "Default UMask changed!");
URI uri1 = new URI("file://mydfs:50070/");
URI uri2 = new URI("file://tmp");
FileContext fc1 = FileContext.getFileContext(uri1, conf);
FileContext fc2 = FileContext.getFileContext(uri2, conf);
assertEquals(022, fc1.getUMask().toShort(), "Umask for fc1 is incorrect");
assertEquals(022, fc2.getUMask().toShort(), "Umask for fc2 is incorrect");
// Till a user explicitly calls FileContext.setUMask(), the updates through
// configuration should be reflected..
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "011");
assertEquals(011, fc1.getUMask().toShort(), "Umask for fc1 is incorrect");
assertEquals(011, fc2.getUMask().toShort(), "Umask for fc2 is incorrect");
// Stop reflecting the conf update for specific FileContexts, once an
// explicit setUMask is done.
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "066");
fc1.setUMask(FsPermission.createImmutable((short) 00033));
assertEquals(033, fc1.getUMask().toShort(), "Umask for fc1 is incorrect");
assertEquals(066, fc2.getUMask().toShort(), "Umask for fc2 is incorrect");
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077");
fc2.setUMask(FsPermission.createImmutable((short) 00044));
assertEquals(033, fc1.getUMask().toShort(), "Umask for fc1 is incorrect");
assertEquals(044, fc2.getUMask().toShort(), "Umask for fc2 is incorrect");
}
}
| TestFileContext |
java | apache__camel | components/camel-nats/src/generated/java/org/apache/camel/component/nats/NatsEndpointUriFactory.java | {
"start": 514,
"end": 3391
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":topic";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(37);
props.add("bridgeErrorHandler");
props.add("connection");
props.add("connectionTimeout");
props.add("consumerConfiguration");
props.add("credentialsFilePath");
props.add("durableName");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("flushConnection");
props.add("flushTimeout");
props.add("headerFilterStrategy");
props.add("jetstreamAsync");
props.add("jetstreamEnabled");
props.add("jetstreamName");
props.add("lazyStartProducer");
props.add("maxMessages");
props.add("maxPingsOut");
props.add("maxReconnectAttempts");
props.add("noEcho");
props.add("noRandomizeServers");
props.add("pedantic");
props.add("pingInterval");
props.add("poolSize");
props.add("pullSubscription");
props.add("queueName");
props.add("reconnect");
props.add("reconnectTimeWait");
props.add("replySubject");
props.add("replyToDisabled");
props.add("requestCleanupInterval");
props.add("requestTimeout");
props.add("secure");
props.add("servers");
props.add("sslContextParameters");
props.add("topic");
props.add("traceConnection");
props.add("verbose");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
SECRET_PROPERTY_NAMES = Collections.emptySet();
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "nats".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "topic", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
| NatsEndpointUriFactory |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmCreationOptionsStandard.java | {
"start": 285,
"end": 1024
} | class ____ implements SqmCreationOptions {
private final QueryEngineOptions queryEngineOptions;
public SqmCreationOptionsStandard(QueryEngineOptions queryEngineOptions) {
this.queryEngineOptions = queryEngineOptions;
}
@Override
public boolean useStrictJpaCompliance() {
return queryEngineOptions.getJpaCompliance().isJpaQueryComplianceEnabled();
}
@Override
public boolean isJsonFunctionsEnabled() {
return queryEngineOptions.isJsonFunctionsEnabled();
}
@Override
public boolean isXmlFunctionsEnabled() {
return queryEngineOptions.isXmlFunctionsEnabled();
}
@Override
public boolean isPortableIntegerDivisionEnabled() {
return queryEngineOptions.isPortableIntegerDivisionEnabled();
}
}
| SqmCreationOptionsStandard |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/node/ANode.java | {
"start": 697,
"end": 2001
} | class ____ {
private final int identifier;
private final Location location;
/**
* Standard constructor with location used for error tracking.
*/
public ANode(int identifier, Location location) {
this.identifier = identifier;
this.location = Objects.requireNonNull(location);
}
/**
* An unique id for the node. This is guaranteed to be smallest possible
* value so it can be used for value caching in an array instead of a
* hash look up.
*/
public int getIdentifier() {
return identifier;
}
/**
* The identifier of the script and character offset used for debugging and errors.
*/
public Location getLocation() {
return location;
}
/**
* Create an error with location information pointing to this node.
*/
public RuntimeException createError(RuntimeException exception) {
return location.createError(exception);
}
/**
* Callback to visit a user tree node.
*/
public abstract <Scope> void visit(UserTreeVisitor<Scope> userTreeVisitor, Scope scope);
/**
* Visits all child user tree nodes for this user tree node.
*/
public abstract <Scope> void visitChildren(UserTreeVisitor<Scope> userTreeVisitor, Scope scope);
}
| ANode |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanGenerator.java | {
"start": 83392,
"end": 99049
} | class ____ {
void generate(BlockCreator bc, Var instance) {
// PreDestroy callbacks
// possibly wrapped into Runnable so that PreDestroy interceptors can proceed() correctly
List<MethodInfo> preDestroyCallbacks = Beans.getCallbacks(
bean.getTarget().get().asClass(), DotNames.PRE_DESTROY,
bean.getDeployment().getBeanArchiveIndex());
for (MethodInfo callback : preDestroyCallbacks) {
if (isReflectionFallbackNeeded(callback, targetPackage)) {
if (Modifier.isPrivate(callback.flags())) {
privateMembers.add(isApplicationClass,
String.format("@PreDestroy callback %s#%s()",
callback.declaringClass().name(), callback.name()));
}
reflectionRegistration.registerMethod(callback);
bc.invokeStatic(MethodDescs.REFLECTIONS_INVOKE_METHOD,
Const.of(classDescOf(callback.declaringClass())),
Const.of(callback.name()),
bc.newEmptyArray(Class.class, 0),
instance,
bc.newEmptyArray(Object.class, 0));
} else {
// instance.superCoolDestroyCallback()
bc.invokeVirtual(methodDescOf(callback), instance);
}
}
}
}
if (bean.getLifecycleInterceptors(InterceptionType.PRE_DESTROY).isEmpty()) {
// if there's no `@PreDestroy` interceptor, we'll generate code to invoke `@PreDestroy` callbacks
// directly into the `doDestroy` method:
//
// private void doDestroy(MyBean var1, CreationalContext var2) {
// var1.myPreDestroyCallback();
// var2.release();
// }
new PreDestroyGenerator().generate(b1, instance);
} else {
ClassDesc subclass = ClassDesc.of(SubclassGenerator.generatedName(
bean.getProviderType().name(), baseName));
// if there _is_ some `@PreDestroy` interceptor, however, we'll reify the chain of `@PreDestroy`
// callbacks into a `Runnable` that we pass into the interceptor chain to be called
// by the last `proceed()` call:
//
// private void doDestroy(MyBean var1, CreationalContext var2) {
// // this is a `Runnable` that calls `MyBean.myPreDestroyCallback()`
// MyBean_Bean$$function$$2 var3 = new MyBean_Bean$$function$$2(var1);
// ((MyBean_Subclass)var1).arc$destroy((Runnable)var3);
// var2.release();
// }
Expr runnable = b1.lambda(Runnable.class, lc -> {
Var capturedInstance = lc.capture(instance);
lc.body(lbc -> {
new PreDestroyGenerator().generate(lbc, capturedInstance);
lbc.return_();
});
});
b1.invokeVirtual(ClassMethodDesc.of(subclass, SubclassGenerator.DESTROY_METHOD_NAME,
void.class, Runnable.class), instance, runnable);
}
}
// ctx.release()
b1.invokeInterface(MethodDescs.CREATIONAL_CTX_RELEASE, ccParam);
b1.return_();
} else if (bean.getDisposer() != null) {
// Invoke the disposer method
// declaringProvider.get(new CreationalContextImpl<>()).dispose()
MethodInfo disposerMethod = bean.getDisposer().getDisposerMethod();
boolean isStatic = Modifier.isStatic(disposerMethod.flags());
Expr declaringProviderSupplier = cc.this_().field(
FieldDesc.of(cc.type(), FIELD_NAME_DECLARING_PROVIDER_SUPPLIER, Supplier.class));
LocalVar declaringProvider = b1.localVar("declaringProvider",
b1.invokeInterface(MethodDescs.SUPPLIER_GET, declaringProviderSupplier));
LocalVar parentCC = b1.localVar("parentCC",
b1.new_(ConstructorDesc.of(CreationalContextImpl.class, Contextual.class),
Const.ofNull(Contextual.class)));
// for static disposers, we don't need to obtain the value
// `null` will only be used for reflective invocation in case the disposer is `private`, which is OK
LocalVar declaringProviderInstance = b1.localVar("declaringProviderInstance",
Const.ofNull(Object.class));
if (!isStatic) {
b1.set(declaringProviderInstance, b1.invokeInterface(
MethodDescs.INJECTABLE_REF_PROVIDER_GET, declaringProvider, parentCC));
if (bean.getDeclaringBean().getScope().isNormal()) {
// We need to unwrap the client proxy
b1.set(declaringProviderInstance, b1.invokeInterface(
MethodDescs.CLIENT_PROXY_GET_CONTEXTUAL_INSTANCE,
declaringProviderInstance));
}
}
Var[] disposerArgs = new Var[disposerMethod.parametersCount()];
int disposedParamPosition = bean.getDisposer().getDisposedParameter().position();
Iterator<InjectionPointInfo> injectionPointsIterator = bean.getDisposer()
.getInjection().injectionPoints.iterator();
for (int i = 0; i < disposerMethod.parametersCount(); i++) {
if (i == disposedParamPosition) {
disposerArgs[i] = providerParam;
} else {
InjectionPointInfo injectionPoint = injectionPointsIterator.next();
Expr providerSupplier = cc.this_().field(injectionPointToProviderField.get(injectionPoint));
Expr provider = b1.invokeInterface(MethodDescs.SUPPLIER_GET, providerSupplier);
Expr childCC = b1.invokeStatic(MethodDescs.CREATIONAL_CTX_CHILD_CONTEXTUAL,
declaringProvider, parentCC);
LocalVar injection = b1.localVar("injection" + i,
b1.invokeInterface(MethodDescs.INJECTABLE_REF_PROVIDER_GET, provider, childCC));
checkPrimitiveInjection(b1, injectionPoint, injection);
disposerArgs[i] = injection;
}
}
if (Modifier.isPrivate(disposerMethod.flags())) {
privateMembers.add(isApplicationClass, String.format("Disposer %s#%s",
disposerMethod.declaringClass().name(), disposerMethod.name()));
reflectionRegistration.registerMethod(disposerMethod);
LocalVar paramTypesArray = b1.localVar("paramTypes",
b1.newEmptyArray(Class.class, disposerArgs.length));
LocalVar argsArray = b1.localVar("args",
b1.newEmptyArray(Object.class, disposerArgs.length));
for (int i = 0; i < disposerArgs.length; i++) {
b1.set(paramTypesArray.elem(i), Const.of(classDescOf(disposerMethod.parameterType(i))));
b1.set(argsArray.elem(i), disposerArgs[i]);
}
b1.invokeStatic(MethodDescs.REFLECTIONS_INVOKE_METHOD,
Const.of(classDescOf(disposerMethod.declaringClass())),
Const.of(disposerMethod.name()), paramTypesArray,
declaringProviderInstance, argsArray);
} else {
if (isStatic) {
b1.invokeStatic(methodDescOf(disposerMethod), disposerArgs);
} else {
b1.invokeVirtual(methodDescOf(disposerMethod), declaringProviderInstance, disposerArgs);
}
}
// Destroy @Dependent instances injected into method parameters of a disposer method
b1.invokeInterface(MethodDescs.CREATIONAL_CTX_RELEASE, parentCC);
// If the declaring bean is `@Dependent` and the disposer is not `static`, we must destroy the instance afterwards
if (BuiltinScope.DEPENDENT.is(bean.getDisposer().getDeclaringBean().getScope()) && !isStatic) {
b1.invokeInterface(MethodDescs.INJECTABLE_BEAN_DESTROY, declaringProvider,
declaringProviderInstance, parentCC);
}
// ctx.release()
b1.invokeInterface(MethodDescs.CREATIONAL_CTX_RELEASE, ccParam);
b1.return_();
} else if (bean.isSynthetic()) {
bean.getDestroyerConsumer().accept(new BeanConfiguratorBase.DestroyGeneration() {
@Override
public ClassCreator beanClass() {
return cc;
}
@Override
public BlockCreator destroyMethod() {
return b1;
}
@Override
public Var destroyedInstance() {
return providerParam;
}
@Override
public Var creationalContext() {
return ccParam;
}
});
}
});
tc.catch_(Throwable.class, "e", (b1, e) -> {
Const error = Const.of("Error occurred while destroying instance of " + bean);
LocalVar logger = b1.localVar("logger",
Expr.staticField(FieldDesc.of(UncaughtExceptions.class, "LOGGER")));
Expr isDebugEnabled = b1.invokeVirtual(MethodDesc.of(Logger.class, "isDebugEnabled", boolean.class),
logger);
b1.ifElse(isDebugEnabled, b2 -> {
b2.invokeVirtual(MethodDesc.of(Logger.class, "error", void.class, Object.class, Throwable.class),
logger, error, e);
}, b2 -> {
b2.invokeVirtual(MethodDesc.of(Logger.class, "error", void.class, Object.class), logger,
StringBuilderGen.ofNew(b2).append(error).append(": ").append(e).toString_());
});
});
});
b0.return_();
});
});
if (!ClassType.OBJECT_TYPE.equals(bean.getProviderType())) {
// Bridge method needed
cc.method("destroy", mc -> {
mc.addFlag(ModifierFlag.BRIDGE);
mc.returning(void.class);
ParamVar provider = mc.parameter("provider", Object.class);
ParamVar creationalContext = mc.parameter("creationalContext", CreationalContext.class);
mc.body(bc -> {
bc.return_(bc.invokeVirtual(destroyDesc, cc.this_(), provider, creationalContext));
});
});
}
}
protected void generateSupplierGet(ClassCreator cc) {
cc.method("get", mc -> {
mc.returning(Object.class);
mc.body(bc -> {
bc.return_(cc.this_());
});
});
}
protected void generateInjectableReferenceProviderGet(BeanInfo bean, ClassCreator cc, String baseName) {
ClassDesc providerType = classDescOf(bean.getProviderType());
MethodDesc getDesc = cc.method("get", mc -> {
mc.returning(providerType);
ParamVar creationalContextParam = mc.parameter("creationalContext", CreationalContext.class);
mc.body(b0 -> {
if (bean.getDeployment().hasRuntimeDeferredUnproxyableError(bean)) {
b0.throw_(UnproxyableResolutionException.class, "Bean not proxyable: " + bean);
} else if (BuiltinScope.DEPENDENT.is(bean.getScope())) {
// @Dependent pseudo-scope
// Foo instance = create(ctx)
LocalVar instance = b0.localVar("instance", b0.invokeVirtual(ClassMethodDesc.of(cc.type(), "create",
MethodTypeDesc.of(providerType, Reflection2Gizmo.classDescOf(CreationalContext.class))),
cc.this_(), creationalContextParam));
// We can optimize if:
// 1) | PreDestroyGenerator |
java | grpc__grpc-java | interop-testing/src/test/java/io/grpc/testing/integration/TrafficControlProxy.java | {
"start": 7668,
"end": 8213
} | class ____ implements Delayed {
long sendTime;
byte[] message;
int messageLength;
Message(long sendTime, byte[] message, int messageLength) {
this.sendTime = sendTime;
this.message = message;
this.messageLength = messageLength;
}
@Override
public int compareTo(Delayed o) {
return ((Long) sendTime).compareTo(((Message) o).sendTime);
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(sendTime - System.nanoTime(), TimeUnit.NANOSECONDS);
}
}
}
| Message |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGeneratorTests.java | {
"start": 24837,
"end": 24950
} | class ____ implements Initializable {
@Override
public void initialize() {
}
}
public | InitializableTestBean |
java | spring-projects__spring-security | webauthn/src/main/java/org/springframework/security/web/webauthn/management/ImmutablePublicKeyCredentialRequestOptionsRequest.java | {
"start": 797,
"end": 1212
} | class ____ implements PublicKeyCredentialRequestOptionsRequest {
private final @Nullable Authentication authentication;
public ImmutablePublicKeyCredentialRequestOptionsRequest(@Nullable Authentication authentication) {
this.authentication = authentication;
}
@Override
public @Nullable Authentication getAuthentication() {
return this.authentication;
}
}
| ImmutablePublicKeyCredentialRequestOptionsRequest |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/issues/SampleRouteBuilderContainer.java | {
"start": 957,
"end": 1285
} | class ____ implements InitializingBean {
private RouteBuilder routeBuilder;
public void setRouteBuilder(RouteBuilder routeBuilder) {
this.routeBuilder = routeBuilder;
}
@Override
public void afterPropertiesSet() throws Exception {
routeBuilder.configure();
}
}
| SampleRouteBuilderContainer |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/InodeTree.java | {
"start": 3910,
"end": 3972
} | class ____ INode tree.
* @param <T>
*/
abstract static | for |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Issue79.java | {
"start": 705,
"end": 791
} | class ____ {
public List<PresentRecord> records;
}
public static | Present |
java | quarkusio__quarkus | independent-projects/tools/codestarts/src/main/java/io/quarkus/devtools/codestarts/core/reader/QuteCodestartFileReader.java | {
"start": 4500,
"end": 4818
} | class ____ implements TemplateLocator.TemplateLocation {
@Override
public Reader read() {
return new StringReader("");
}
@Override
public Optional<Variant> getVariant() {
return Optional.empty();
}
}
private static | FallbackTemplateLocation |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/PluginRegistry.java | {
"start": 6256,
"end": 12177
} | class ____ {}", loader);
} else {
cache.loadCacheFiles(resources);
}
} catch (final IOException ioe) {
LOGGER.warn("Unable to preload plugins", ioe);
}
final Map<String, List<PluginType<?>>> newPluginsByCategory = new HashMap<>();
int pluginCount = 0;
for (final Map.Entry<String, Map<String, PluginEntry>> outer :
cache.getAllCategories().entrySet()) {
final String categoryLowerCase = outer.getKey();
final List<PluginType<?>> types = new ArrayList<>(outer.getValue().size());
newPluginsByCategory.put(categoryLowerCase, types);
for (final Map.Entry<String, PluginEntry> inner : outer.getValue().entrySet()) {
final PluginEntry entry = inner.getValue();
final String className = entry.getClassName();
try {
final Class<?> clazz = loader.loadClass(className);
final PluginType<?> type = new PluginType<>(entry, clazz, entry.getName());
types.add(type);
++pluginCount;
} catch (final ClassNotFoundException e) {
LOGGER.info("Plugin [{}] could not be loaded due to missing classes.", className, e);
} catch (final LinkageError e) {
LOGGER.info("Plugin [{}] could not be loaded due to linkage error.", className, e);
}
}
}
final int numPlugins = pluginCount;
LOGGER.debug(() -> {
final long endTime = System.nanoTime();
final DecimalFormat numFormat = new DecimalFormat("#0.000000");
return "Took " + numFormat.format((endTime - startTime) * 1e-9) + " seconds to load " + numPlugins
+ " plugins from " + loader;
});
return newPluginsByCategory;
}
/**
* @since 2.1
*/
public Map<String, List<PluginType<?>>> loadFromPackage(final String pkg) {
if (Strings.isBlank(pkg)) {
// happens when splitting an empty string
return Collections.emptyMap();
}
Map<String, List<PluginType<?>>> existing = pluginsByCategoryByPackage.get(pkg);
if (existing != null) {
// already loaded this package
return existing;
}
final long startTime = System.nanoTime();
final ResolverUtil resolver = new ResolverUtil();
final ClassLoader classLoader = Loader.getClassLoader();
if (classLoader != null) {
resolver.setClassLoader(classLoader);
}
resolver.findInPackage(new PluginTest(), pkg);
final Map<String, List<PluginType<?>>> newPluginsByCategory = new HashMap<>();
for (final Class<?> clazz : resolver.getClasses()) {
final Plugin plugin = clazz.getAnnotation(Plugin.class);
final String categoryLowerCase = toRootLowerCase(plugin.category());
List<PluginType<?>> list = newPluginsByCategory.get(categoryLowerCase);
if (list == null) {
newPluginsByCategory.put(categoryLowerCase, list = new ArrayList<>());
}
final PluginEntry mainEntry = new PluginEntry();
final String mainElementName =
plugin.elementType().equals(Plugin.EMPTY) ? plugin.name() : plugin.elementType();
mainEntry.setKey(toRootLowerCase(plugin.name()));
mainEntry.setName(plugin.name());
mainEntry.setCategory(plugin.category());
mainEntry.setClassName(clazz.getName());
mainEntry.setPrintable(plugin.printObject());
mainEntry.setDefer(plugin.deferChildren());
final PluginType<?> mainType = new PluginType<>(mainEntry, clazz, mainElementName);
list.add(mainType);
final PluginAliases pluginAliases = clazz.getAnnotation(PluginAliases.class);
if (pluginAliases != null) {
for (final String alias : pluginAliases.value()) {
final PluginEntry aliasEntry = new PluginEntry();
final String aliasElementName =
plugin.elementType().equals(Plugin.EMPTY) ? alias.trim() : plugin.elementType();
aliasEntry.setKey(toRootLowerCase(alias.trim()));
aliasEntry.setName(plugin.name());
aliasEntry.setCategory(plugin.category());
aliasEntry.setClassName(clazz.getName());
aliasEntry.setPrintable(plugin.printObject());
aliasEntry.setDefer(plugin.deferChildren());
final PluginType<?> aliasType = new PluginType<>(aliasEntry, clazz, aliasElementName);
list.add(aliasType);
}
}
}
LOGGER.debug(() -> {
final long endTime = System.nanoTime();
final StringBuilder sb = new StringBuilder("Took ");
final DecimalFormat numFormat = new DecimalFormat("#0.000000");
sb.append(numFormat.format((endTime - startTime) * 1e-9));
sb.append(" seconds to load ").append(resolver.getClasses().size());
sb.append(" plugins from package ").append(pkg);
return sb.toString();
});
// Note multiple threads could be calling this method concurrently. Both will do the work,
// but only one will be allowed to store the result in the outer map.
// Return the inner map produced by whichever thread won the race, so all callers will get the same result.
existing = pluginsByCategoryByPackage.putIfAbsent(pkg, newPluginsByCategory);
if (existing != null) {
return existing;
}
return newPluginsByCategory;
}
/**
* A Test that checks to see if each | loader |
java | quarkusio__quarkus | extensions/panache/hibernate-reactive-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/reactive/rest/data/panache/deployment/entity/AbstractItem.java | {
"start": 246,
"end": 532
} | class ____<IdType extends Number> extends AbstractEntity<IdType> {
public String name;
@ManyToOne
public Collection collection;
@JsonbTransient // Avoid infinite loop when serializing
public Collection getCollection() {
return collection;
}
}
| AbstractItem |
java | quarkusio__quarkus | extensions/keycloak-authorization/runtime/src/main/java/io/quarkus/keycloak/pep/runtime/KeycloakPolicyEnforcerTenantConfig.java | {
"start": 4017,
"end": 4553
} | interface ____ {
/**
* The name of the HTTP method
*/
String method();
/**
* An array of strings with the scopes associated with the method
*/
List<String> scopes();
/**
* A string referencing the enforcement mode for the scopes associated with a method
*/
@WithDefault("all")
ScopeEnforcementMode scopesEnforcementMode();
}
@ConfigGroup
| MethodConfig |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/config/FilterProperties.java | {
"start": 1115,
"end": 2547
} | class ____ {
@NotNull
private @Nullable String name;
private Map<String, String> args = new LinkedHashMap<>();
public FilterProperties() {
}
public FilterProperties(String text) {
int eqIdx = text.indexOf('=');
if (eqIdx <= 0) {
setName(text);
return;
}
setName(text.substring(0, eqIdx));
String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ",");
for (int i = 0; i < args.length; i++) {
this.args.put(NameUtils.generateName(i), args[i]);
}
}
public @Nullable String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getArgs() {
return args;
}
public void setArgs(Map<String, String> args) {
this.args = args;
}
public void addArg(String key, String value) {
this.args.put(key, value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FilterProperties that = (FilterProperties) o;
return Objects.equals(name, that.name) && Objects.equals(args, that.args);
}
@Override
public int hashCode() {
return Objects.hash(name, args);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("FilterDefinition{");
sb.append("name='").append(name).append('\'');
sb.append(", args=").append(args);
sb.append('}');
return sb.toString();
}
}
| FilterProperties |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 43294,
"end": 43860
} | class ____ {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Query("key") int[] keys) {
return null;
}
}
int[] values = {1, 2, 3, 1};
Request request = buildRequest(Example.class, new Object[] {values});
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isEqualTo(0);
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=3&key=1");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryNameParam() {
| Example |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1200/Issue1281.java | {
"start": 259,
"end": 575
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
Type type1 = new TypeReference<Result<Map<String, Object>>>() {}.getType();
Type type2 = new TypeReference<Result<Map<String, Object>>>() {}.getType();
assertSame(type1, type2);
}
public static | Issue1281 |
java | apache__flink | flink-core/src/test/java/org/apache/flink/util/FileUtilsTest.java | {
"start": 2177,
"end": 26379
} | class ____ {
@TempDir private java.nio.file.Path temporaryFolder;
// ------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------
@Test
void testReadAllBytes() throws Exception {
File tempFile =
TempDirUtils.newFolder(Paths.get(this.getClass().getResource("/").getPath()));
final int fileSize = 1024;
final String testFilePath =
tempFile.toPath()
.resolve(this.getClass().getSimpleName() + "_" + fileSize + ".txt")
.toString();
{
String expectedMD5 = generateTestFile(testFilePath, 1024);
final byte[] data = FileUtils.readAllBytes((new File(testFilePath)).toPath());
assertThat(md5Hex(data)).isEqualTo(expectedMD5);
}
{
String expectedMD5 = generateTestFile(testFilePath, 4096);
final byte[] data = FileUtils.readAllBytes((new File(testFilePath)).toPath());
assertThat(md5Hex(data)).isEqualTo(expectedMD5);
}
{
String expectedMD5 = generateTestFile(testFilePath, 5120);
final byte[] data = FileUtils.readAllBytes((new File(testFilePath)).toPath());
assertThat(md5Hex(data)).isEqualTo(expectedMD5);
}
}
@Test
void testDeleteQuietly() throws Exception {
// should ignore the call
FileUtils.deleteDirectoryQuietly(null);
File doesNotExist = TempDirUtils.newFolder(temporaryFolder, "abc");
FileUtils.deleteDirectoryQuietly(doesNotExist);
File cannotDeleteParent = TempDirUtils.newFolder(temporaryFolder);
File cannotDeleteChild = new File(cannotDeleteParent, "child");
try {
assertThat(cannotDeleteChild.createNewFile()).isTrue();
assertThat(cannotDeleteParent.setWritable(false)).isTrue();
assertThat(cannotDeleteChild.setWritable(false)).isTrue();
FileUtils.deleteDirectoryQuietly(cannotDeleteParent);
} finally {
//noinspection ResultOfMethodCallIgnored
cannotDeleteParent.setWritable(true);
//noinspection ResultOfMethodCallIgnored
cannotDeleteChild.setWritable(true);
}
}
@Test
void testDeleteNonExistentDirectory() throws Exception {
// deleting a non-existent file should not cause an error
File doesNotExist = TempDirUtils.newFolder(temporaryFolder, "abc");
FileUtils.deleteDirectory(doesNotExist);
}
@Tag("org.apache.flink.testutils.junit.FailsInGHAContainerWithRootUser")
@Test
void testDeleteProtectedDirectory() throws Exception {
// deleting a write protected file should throw an error
File cannotDeleteParent = TempDirUtils.newFolder(temporaryFolder);
File cannotDeleteChild = new File(cannotDeleteParent, "child");
try {
assumeThat(cannotDeleteChild.createNewFile()).isTrue();
assumeThat(cannotDeleteParent.setWritable(false)).isTrue();
assumeThat(cannotDeleteChild.setWritable(false)).isTrue();
assertThatThrownBy(() -> FileUtils.deleteDirectory(cannotDeleteParent))
.isInstanceOf(AccessDeniedException.class);
} finally {
//noinspection ResultOfMethodCallIgnored
cannotDeleteParent.setWritable(true);
//noinspection ResultOfMethodCallIgnored
cannotDeleteChild.setWritable(true);
}
}
@Test
void testDeleteDirectoryWhichIsAFile() throws Exception {
// deleting a directory that is actually a file should fails
File file = TempDirUtils.newFile(temporaryFolder);
assertThatThrownBy(() -> FileUtils.deleteDirectory(file))
.withFailMessage("this should fail with an exception")
.isInstanceOf(IOException.class);
}
/** Deleting a symbolic link directory should not delete the files in it. */
@Test
void testDeleteSymbolicLinkDirectory() throws Exception {
// creating a directory to which the test creates a symbolic link
File linkedDirectory = TempDirUtils.newFolder(temporaryFolder);
File fileInLinkedDirectory = new File(linkedDirectory, "child");
assertThat(fileInLinkedDirectory.createNewFile()).isTrue();
File symbolicLink = new File(temporaryFolder.toString(), "symLink");
try {
Files.createSymbolicLink(symbolicLink.toPath(), linkedDirectory.toPath());
} catch (FileSystemException e) {
// this operation can fail under Windows due to: "A required privilege is not held by
// the client."
assumeThat(OperatingSystem.isWindows())
.withFailMessage("This test does not work properly under Windows")
.isFalse();
throw e;
}
FileUtils.deleteDirectory(symbolicLink);
assertThat(fileInLinkedDirectory).exists();
}
@Test
void testDeleteDirectoryConcurrently() throws Exception {
final File parent = TempDirUtils.newFolder(temporaryFolder);
generateRandomDirs(parent, 20, 5, 3);
// start three concurrent threads that delete the contents
CheckedThread t1 = new Deleter(parent);
CheckedThread t2 = new Deleter(parent);
CheckedThread t3 = new Deleter(parent);
t1.start();
t2.start();
t3.start();
t1.sync();
t2.sync();
t3.sync();
// assert is empty
assertThat(parent).doesNotExist();
}
@Test
void testCompressionOnAbsolutePath() throws IOException {
final java.nio.file.Path testDir =
TempDirUtils.newFolder(temporaryFolder, "compressDir").toPath();
verifyDirectoryCompression(testDir, testDir);
}
@Test
void testCompressionOnRelativePath() throws IOException {
final java.nio.file.Path testDir =
TempDirUtils.newFolder(temporaryFolder, "compressDir").toPath();
final java.nio.file.Path relativeCompressDir =
Paths.get(new File("").getAbsolutePath()).relativize(testDir);
verifyDirectoryCompression(testDir, relativeCompressDir);
}
@Test
void testListFilesInPathWithoutAnyFileReturnEmptyList() throws IOException {
final java.nio.file.Path testDir =
TempDirUtils.newFolder(temporaryFolder, "_test_0").toPath();
assertThat(FileUtils.listFilesInDirectory(testDir, FileUtils::isJarFile)).isEmpty();
}
@Test
void testListFilesInPath() throws IOException {
final java.nio.file.Path testDir =
TempDirUtils.newFolder(temporaryFolder, "_test_1").toPath();
final Collection<java.nio.file.Path> testFiles = prepareTestFiles(testDir);
final Collection<java.nio.file.Path> filesInDirectory =
FileUtils.listFilesInDirectory(testDir, FileUtils::isJarFile);
assertThat(filesInDirectory).containsExactlyInAnyOrderElementsOf(testFiles);
}
@Test
void testRelativizeOfAbsolutePath() throws IOException {
final java.nio.file.Path absolutePath =
TempDirUtils.newFolder(temporaryFolder).toPath().toAbsolutePath();
final java.nio.file.Path rootPath = temporaryFolder.getRoot();
final java.nio.file.Path relativePath = FileUtils.relativizePath(rootPath, absolutePath);
assertThat(relativePath).isRelative();
assertThat(absolutePath).isEqualTo(rootPath.resolve(relativePath));
}
@Test
void testRelativizeOfRelativePath() {
final java.nio.file.Path path = Paths.get("foobar");
assertThat(path).isRelative();
final java.nio.file.Path relativePath =
FileUtils.relativizePath(temporaryFolder.getRoot(), path);
assertThat(path).isEqualTo(relativePath);
}
@Test
void testAbsolutePathToURL() throws MalformedURLException {
final java.nio.file.Path absolutePath = temporaryFolder.getRoot().toAbsolutePath();
final URL absoluteURL = FileUtils.toURL(absolutePath);
final java.nio.file.Path transformedURL = Paths.get(absoluteURL.getPath());
assertThat(transformedURL).isEqualTo(absolutePath);
}
@Test
void testRelativePathToURL() throws MalformedURLException {
final java.nio.file.Path relativePath = Paths.get("foobar");
assertThat(relativePath).isRelative();
final URL relativeURL = FileUtils.toURL(relativePath);
final java.nio.file.Path transformedPath = Paths.get(relativeURL.getPath());
assertThat(transformedPath).isEqualTo(relativePath);
}
@Test
void testListDirFailsIfDirectoryDoesNotExist() {
final String fileName = "_does_not_exists_file";
assertThatThrownBy(
() ->
FileUtils.listFilesInDirectory(
temporaryFolder.getRoot().resolve(fileName),
FileUtils::isJarFile))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void testListAFileFailsBecauseDirectoryIsExpected() throws IOException {
final String fileName = "a.jar";
final File file = TempDirUtils.newFile(temporaryFolder, fileName);
assertThatThrownBy(
() -> FileUtils.listFilesInDirectory(file.toPath(), FileUtils::isJarFile))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void testFollowSymbolicDirectoryLink() throws IOException {
final File directory = TempDirUtils.newFolder(temporaryFolder, "a");
final File file = new File(directory, "a.jar");
assertThat(file.createNewFile()).isTrue();
final File otherDirectory = TempDirUtils.newFolder(temporaryFolder);
java.nio.file.Path linkPath = Paths.get(otherDirectory.getPath(), "a.lnk");
Files.createSymbolicLink(linkPath, directory.toPath());
Collection<java.nio.file.Path> paths =
FileUtils.listFilesInDirectory(linkPath, FileUtils::isJarFile);
assertThat(paths).containsExactlyInAnyOrder(linkPath.resolve(file.getName()));
}
@Test
void testGetTargetPathNotContainsSymbolicPath() throws IOException {
java.nio.file.Path testPath = Paths.get("parent", "child");
java.nio.file.Path targetPath = FileUtils.getTargetPathIfContainsSymbolicPath(testPath);
assertThat(targetPath).isEqualTo(testPath);
}
@Test
void testGetTargetPathContainsSymbolicPath() throws IOException {
File linkedDir = TempDirUtils.newFolder(temporaryFolder, "linked");
java.nio.file.Path symlink = Paths.get(temporaryFolder.toString(), "symlink");
java.nio.file.Path dirInLinked =
TempDirUtils.newFolder(linkedDir.toPath(), "one", "two").toPath().toRealPath();
Files.createSymbolicLink(symlink, linkedDir.toPath());
java.nio.file.Path targetPath =
FileUtils.getTargetPathIfContainsSymbolicPath(
symlink.resolve("one").resolve("two"));
assertThat(targetPath).isEqualTo(dirInLinked);
}
@Test
void testGetTargetPathContainsMultipleSymbolicPath() throws IOException {
File linked1Dir = TempDirUtils.newFolder(temporaryFolder, "linked1");
java.nio.file.Path symlink1 = Paths.get(temporaryFolder.toString(), "symlink1");
Files.createSymbolicLink(symlink1, linked1Dir.toPath());
java.nio.file.Path symlink2 = Paths.get(symlink1.toString(), "symlink2");
File linked2Dir = TempDirUtils.newFolder(temporaryFolder, "linked2");
Files.createSymbolicLink(symlink2, linked2Dir.toPath());
java.nio.file.Path dirInLinked2 =
TempDirUtils.newFolder(linked2Dir.toPath(), "one").toPath().toRealPath();
// symlink3 point to another symbolic link: symlink2
java.nio.file.Path symlink3 = Paths.get(symlink1.toString(), "symlink3");
Files.createSymbolicLink(symlink3, symlink2);
java.nio.file.Path targetPath =
FileUtils.getTargetPathIfContainsSymbolicPath(
// path contains multiple symlink : xxx/symlink1/symlink3/one
symlink3.resolve("one"));
assertThat(targetPath).isEqualTo(dirInLinked2);
}
@Test
void testGetDirectorySize() throws Exception {
final File parent = TempDirUtils.newFolder(temporaryFolder);
// Empty directory should have size 0
assertThat(FileUtils.getDirectoryFilesSize(parent.toPath())).isZero();
// Expected size: (20*5^0 + 20*5^1 + 20*5^2 + 20*5^3) * 1 byte = 3120 bytes
generateRandomDirs(parent, 20, 5, 3);
assertThat(FileUtils.getDirectoryFilesSize(parent.toPath())).isEqualTo(3120);
}
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
private static void assertDirEquals(java.nio.file.Path expected, java.nio.file.Path actual)
throws IOException {
assertThat(Files.isDirectory(actual)).isEqualTo(Files.isDirectory(expected));
assertThat(actual.getFileName()).isEqualTo(expected.getFileName());
if (Files.isDirectory(expected)) {
List<java.nio.file.Path> expectedContents;
try (Stream<java.nio.file.Path> files = Files.list(expected)) {
expectedContents =
files.sorted(Comparator.comparing(java.nio.file.Path::toString))
.collect(Collectors.toList());
}
List<java.nio.file.Path> actualContents;
try (Stream<java.nio.file.Path> files = Files.list(actual)) {
actualContents =
files.sorted(Comparator.comparing(java.nio.file.Path::toString))
.collect(Collectors.toList());
}
assertThat(actualContents).hasSameSizeAs(expectedContents);
for (int x = 0; x < expectedContents.size(); x++) {
assertDirEquals(expectedContents.get(x), actualContents.get(x));
}
} else {
byte[] expectedBytes = Files.readAllBytes(expected);
byte[] actualBytes = Files.readAllBytes(actual);
assertThat(actualBytes).isEqualTo(expectedBytes);
}
}
private static void generateRandomDirs(File dir, int numFiles, int numDirs, int depth)
throws IOException {
// generate the random files
for (int i = 0; i < numFiles; i++) {
File file = new File(dir, new AbstractID().toString());
try (FileOutputStream out = new FileOutputStream(file)) {
out.write(1);
}
}
if (depth > 0) {
// generate the directories
for (int i = 0; i < numDirs; i++) {
File subdir = new File(dir, new AbstractID().toString());
assertThat(subdir.mkdir()).isTrue();
generateRandomDirs(subdir, numFiles, numDirs, depth - 1);
}
}
}
/**
* Generate some files in the directory {@code dir}.
*
* @param dir the directory where the files are generated
* @return The list of generated files
* @throws IOException if I/O error occurs while generating the files
*/
public static Collection<java.nio.file.Path> prepareTestFiles(final java.nio.file.Path dir)
throws IOException {
final java.nio.file.Path jobSubDir1 = Files.createDirectory(dir.resolve("_sub_dir1"));
final java.nio.file.Path jobSubDir2 = Files.createDirectory(dir.resolve("_sub_dir2"));
final java.nio.file.Path jarFile1 = Files.createFile(dir.resolve("file1.jar"));
final java.nio.file.Path jarFile2 = Files.createFile(dir.resolve("file2.jar"));
final java.nio.file.Path jarFile3 = Files.createFile(jobSubDir1.resolve("file3.jar"));
final java.nio.file.Path jarFile4 = Files.createFile(jobSubDir2.resolve("file4.jar"));
final Collection<java.nio.file.Path> jarFiles = new ArrayList<>();
Files.createFile(dir.resolve("file1.txt"));
Files.createFile(jobSubDir2.resolve("file2.txt"));
jarFiles.add(jarFile1);
jarFiles.add(jarFile2);
jarFiles.add(jarFile3);
jarFiles.add(jarFile4);
return jarFiles;
}
/**
* Generate some directories in a original directory based on the {@code testDir}.
*
* @param testDir the path of the directory where the test directories are generated
* @param compressDir the path of directory to be verified
* @throws IOException if I/O error occurs while generating the directories
*/
private void verifyDirectoryCompression(
final java.nio.file.Path testDir, final java.nio.file.Path compressDir)
throws IOException {
final String testFileContent =
"Goethe - Faust: Der Tragoedie erster Teil\n"
+ "Prolog im Himmel.\n"
+ "Der Herr. Die himmlischen Heerscharen. Nachher Mephistopheles. Die drei\n"
+ "Erzengel treten vor.\n"
+ "RAPHAEL: Die Sonne toent, nach alter Weise, In Brudersphaeren Wettgesang,\n"
+ "Und ihre vorgeschriebne Reise Vollendet sie mit Donnergang. Ihr Anblick\n"
+ "gibt den Engeln Staerke, Wenn keiner Sie ergruenden mag; die unbegreiflich\n"
+ "hohen Werke Sind herrlich wie am ersten Tag.\n"
+ "GABRIEL: Und schnell und unbegreiflich schnelle Dreht sich umher der Erde\n"
+ "Pracht; Es wechselt Paradieseshelle Mit tiefer, schauervoller Nacht. Es\n"
+ "schaeumt das Meer in breiten Fluessen Am tiefen Grund der Felsen auf, Und\n"
+ "Fels und Meer wird fortgerissen Im ewig schnellem Sphaerenlauf.\n"
+ "MICHAEL: Und Stuerme brausen um die Wette Vom Meer aufs Land, vom Land\n"
+ "aufs Meer, und bilden wuetend eine Kette Der tiefsten Wirkung rings umher.\n"
+ "Da flammt ein blitzendes Verheeren Dem Pfade vor des Donnerschlags. Doch\n"
+ "deine Boten, Herr, verehren Das sanfte Wandeln deines Tags.";
final java.nio.file.Path extractDir =
TempDirUtils.newFolder(temporaryFolder, "extractDir").toPath();
final java.nio.file.Path originalDir = Paths.get("rootDir");
final java.nio.file.Path emptySubDir = originalDir.resolve("emptyDir");
final java.nio.file.Path fullSubDir = originalDir.resolve("fullDir");
final java.nio.file.Path file1 = originalDir.resolve("file1");
final java.nio.file.Path file2 = originalDir.resolve("file2");
final java.nio.file.Path file3 = fullSubDir.resolve("file3");
Files.createDirectory(testDir.resolve(originalDir));
Files.createDirectory(testDir.resolve(emptySubDir));
Files.createDirectory(testDir.resolve(fullSubDir));
Files.copy(
new ByteArrayInputStream(testFileContent.getBytes(StandardCharsets.UTF_8)),
testDir.resolve(file1));
Files.createFile(testDir.resolve(file2));
Files.copy(
new ByteArrayInputStream(testFileContent.getBytes(StandardCharsets.UTF_8)),
testDir.resolve(file3));
final Path zip =
FileUtils.compressDirectory(
new Path(compressDir.resolve(originalDir).toString()),
new Path(compressDir.resolve(originalDir) + ".zip"));
FileUtils.expandDirectory(zip, new Path(extractDir.toAbsolutePath().toString()));
assertDirEquals(compressDir.resolve(originalDir), extractDir.resolve(originalDir));
}
/**
* Generates zip archive, containing path to file/dir passed in, un-archives the generated zip
* using {@link org.apache.flink.util.FileUtils#expandDirectory(org.apache.flink.core.fs.Path,
* org.apache.flink.core.fs.Path)} and returns path to expanded folder.
*
* @param prefix prefix to use for creating source and destination folders
* @param path path to contents of zip
* @return Path to folder containing unzipped contents
* @throws IOException if I/O error in file creation, un-archiving detects unsafe access outside
* target folder
*/
private Path writeZipAndFetchExpandedPath(String prefix, String path) throws IOException {
// random source folder
String sourcePath = prefix + "src";
String dstPath = prefix + "dst";
java.nio.file.Path srcFolder = TempDirUtils.newFolder(temporaryFolder, sourcePath).toPath();
java.nio.file.Path zippedFile = srcFolder.resolve("file.zip");
ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zippedFile));
ZipEntry e1 = new ZipEntry(path);
out.putNextEntry(e1);
out.close();
java.nio.file.Path dstFolder = TempDirUtils.newFolder(temporaryFolder, dstPath).toPath();
return FileUtils.expandDirectory(
new Path(zippedFile.toString()), new Path(dstFolder.toString()));
}
@Test
void testExpandDirWithValidPaths() throws IOException {
writeZipAndFetchExpandedPath("t0", "/level1/level2/");
writeZipAndFetchExpandedPath("t1", "/level1/level2/file.txt");
writeZipAndFetchExpandedPath("t2", "/level1/../level1/file.txt");
writeZipAndFetchExpandedPath("t3", "/level1/level2/level3/../");
assertThatThrownBy(() -> writeZipAndFetchExpandedPath("t2", "/level1/level2/../../pass"))
.isInstanceOf(IOException.class);
}
@Test
void testExpandDirWithForbiddenEscape() {
assertThatThrownBy(() -> writeZipAndFetchExpandedPath("t1", "/../../"))
.isInstanceOf(IOException.class);
assertThatThrownBy(() -> writeZipAndFetchExpandedPath("t2", "../"))
.isInstanceOf(IOException.class);
}
/**
* Generates a random content file.
*
* @param outputFile the path of the output file
* @param length the size of content to generate
* @return MD5 of the output file
* @throws IOException
* @throws NoSuchAlgorithmException
*/
private static String generateTestFile(String outputFile, int length)
throws IOException, NoSuchAlgorithmException {
Path outputFilePath = new Path(outputFile);
final FileSystem fileSystem = outputFilePath.getFileSystem();
try (final FSDataOutputStream fsDataOutputStream =
fileSystem.create(outputFilePath, FileSystem.WriteMode.OVERWRITE)) {
return writeRandomContent(fsDataOutputStream, length);
}
}
private static String writeRandomContent(OutputStream out, int length)
throws IOException, NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
Random random = new Random();
char startChar = 32, endChar = 127;
for (int i = 0; i < length; i++) {
int rnd = random.nextInt(endChar - startChar);
byte b = (byte) (startChar + rnd);
out.write(b);
messageDigest.update(b);
}
byte[] b = messageDigest.digest();
return org.apache.flink.util.StringUtils.byteToHexString(b);
}
private static String md5Hex(byte[] data) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(data);
byte[] b = messageDigest.digest();
return org.apache.flink.util.StringUtils.byteToHexString(b);
}
// ------------------------------------------------------------------------
private static | FileUtilsTest |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverter.java | {
"start": 1060,
"end": 1370
} | class ____ extends StringToIterableConverter<Deque> {
public StringToDequeConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Deque createMultiValue(int size, Class<?> multiValueType) {
return new ArrayDeque(size);
}
}
| StringToDequeConverter |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/transport/StubbableTransport.java | {
"start": 11049,
"end": 11370
} | interface ____ {
void openConnection(
Transport transport,
DiscoveryNode discoveryNode,
ConnectionProfile profile,
ActionListener<Connection> listener
);
default void clearCallback() {}
}
@FunctionalInterface
public | OpenConnectionBehavior |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableSkipTest.java | {
"start": 1153,
"end": 6516
} | class ____ extends RxJavaTest {
@Test(expected = IllegalArgumentException.class)
public void skipNegativeElements() {
Flowable<String> skip = Flowable.just("one", "two", "three").skip(-99);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
skip.subscribe(subscriber);
verify(subscriber, times(1)).onNext("one");
verify(subscriber, times(1)).onNext("two");
verify(subscriber, times(1)).onNext("three");
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipZeroElements() {
Flowable<String> skip = Flowable.just("one", "two", "three").skip(0);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
skip.subscribe(subscriber);
verify(subscriber, times(1)).onNext("one");
verify(subscriber, times(1)).onNext("two");
verify(subscriber, times(1)).onNext("three");
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipOneElement() {
Flowable<String> skip = Flowable.just("one", "two", "three").skip(1);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
skip.subscribe(subscriber);
verify(subscriber, never()).onNext("one");
verify(subscriber, times(1)).onNext("two");
verify(subscriber, times(1)).onNext("three");
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipTwoElements() {
Flowable<String> skip = Flowable.just("one", "two", "three").skip(2);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
skip.subscribe(subscriber);
verify(subscriber, never()).onNext("one");
verify(subscriber, never()).onNext("two");
verify(subscriber, times(1)).onNext("three");
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipEmptyStream() {
Flowable<String> w = Flowable.empty();
Flowable<String> skip = w.skip(1);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
skip.subscribe(subscriber);
verify(subscriber, never()).onNext(any(String.class));
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipMultipleObservers() {
Flowable<String> skip = Flowable.just("one", "two", "three")
.skip(2);
Subscriber<String> subscriber1 = TestHelper.mockSubscriber();
skip.subscribe(subscriber1);
Subscriber<String> subscriber2 = TestHelper.mockSubscriber();
skip.subscribe(subscriber2);
verify(subscriber1, times(1)).onNext(any(String.class));
verify(subscriber1, never()).onError(any(Throwable.class));
verify(subscriber1, times(1)).onComplete();
verify(subscriber2, times(1)).onNext(any(String.class));
verify(subscriber2, never()).onError(any(Throwable.class));
verify(subscriber2, times(1)).onComplete();
}
@Test
public void skipError() {
Exception e = new Exception();
Flowable<String> ok = Flowable.just("one");
Flowable<String> error = Flowable.error(e);
Flowable<String> skip = Flowable.concat(ok, error).skip(100);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
skip.subscribe(subscriber);
verify(subscriber, never()).onNext(any(String.class));
verify(subscriber, times(1)).onError(e);
verify(subscriber, never()).onComplete();
}
@Test
public void backpressureMultipleSmallAsyncRequests() throws InterruptedException {
final AtomicLong requests = new AtomicLong(0);
TestSubscriber<Long> ts = new TestSubscriber<>(0L);
Flowable.interval(100, TimeUnit.MILLISECONDS)
.doOnRequest(new LongConsumer() {
@Override
public void accept(long n) {
requests.addAndGet(n);
}
}).skip(4).subscribe(ts);
Thread.sleep(100);
ts.request(1);
ts.request(1);
Thread.sleep(100);
ts.cancel();
ts.assertNoErrors();
assertEquals(6, requests.get());
}
@Test
public void requestOverflowDoesNotOccur() {
TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(Long.MAX_VALUE - 1);
Flowable.range(1, 10).skip(5).subscribe(ts);
ts.assertTerminated();
ts.assertComplete();
ts.assertNoErrors();
assertEquals(Arrays.asList(6, 7, 8, 9, 10), ts.values());
}
@Test
public void dispose() {
TestHelper.checkDisposed(Flowable.just(1).skip(2));
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() {
@Override
public Flowable<Object> apply(Flowable<Object> f)
throws Exception {
return f.skip(1);
}
});
}
}
| FlowableSkipTest |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/ast/SimpleClassElement.java | {
"start": 2879,
"end": 3351
} | class ____ produced by from an array");
}
@NonNull
@Override
public String getName() {
return typeName;
}
@Override
public boolean isPackagePrivate() {
return false;
}
@Override
public boolean isProtected() {
return false;
}
@Override
public boolean isPublic() {
return false;
}
@NonNull
@Override
public Object getNativeType() {
return typeName;
}
}
| elements |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/DataFormatCustomizer.java | {
"start": 1203,
"end": 3327
} | interface ____ extends Ordered {
/**
* Create a generic {@link Builder}.
*
* @return the {@link Builder}
*/
static Builder<DataFormat> builder() {
return builder(DataFormat.class);
}
/**
* Create a typed {@link Builder} that can process a concrete data format type instance.
*
* @param type the concrete type of the {@link Component}
* @return the {@link ComponentCustomizer.Builder}
*/
static <T extends DataFormat> Builder<T> builder(Class<T> type) {
return new Builder<>(type);
}
/**
* Create a {@link DataFormatCustomizer} that can process a concrete data format type instance.
*
* @param type the concrete type of the {@link DataFormat}
* @param consumer the {@link DataFormat} configuration logic
* @return the {@link DataFormatCustomizer}
*/
static <T extends DataFormat> DataFormatCustomizer forType(Class<T> type, ThrowingConsumer<T, Exception> consumer) {
return builder(type).build(consumer);
}
/**
* Customize the specified {@link DataFormat}.
*
* @param name the unique name of the data format
* @param target the data format to configure
*/
void configure(String name, DataFormat target);
/**
* Checks whether this customizer should be applied to the given {@link DataFormat}.
*
* @param name the unique name of the data format
* @param target the data format to configure
* @return <tt>true</tt> if the customizer should be applied
*/
default boolean isEnabled(String name, DataFormat target) {
return true;
}
@Override
default int getOrder() {
return 0;
}
// ***************************************
//
// Filter
//
// ***************************************
/**
* Used as additional filer mechanism to control if customizers need to be applied or not. Each of this filter is
* applied before any of the discovered {@link DataFormatCustomizer} is invoked.
* </p>
* This | DataFormatCustomizer |
java | apache__flink | flink-table/flink-sql-jdbc-driver/src/main/java/org/apache/flink/table/jdbc/ColumnInfo.java | {
"start": 2335,
"end": 9664
} | class ____ {
private static final int VARBINARY_MAX = 1024 * 1024 * 1024;
private static final int TIME_ZONE_MAX = 40; // current longest time zone is 32
private static final int TIME_MAX = "HH:mm:ss.SSS".length();
private static final int TIMESTAMP_MAX = "yyyy-MM-dd HH:mm:ss.SSS".length();
private static final int TIMESTAMP_WITH_TIME_ZONE_MAX = TIMESTAMP_MAX + TIME_ZONE_MAX;
private static final int DATE_MAX = "yyyy-MM-dd".length();
private static final int STRUCT_MAX = 100 * 1024 * 1024;
private final int columnType;
private final String columnTypeName;
private final boolean nullable;
private final boolean signed;
private final int precision;
private final int scale;
private final int columnDisplaySize;
private final String columnName;
private ColumnInfo(
int columnType,
String columnTypeName,
boolean nullable,
boolean signed,
int precision,
int scale,
int columnDisplaySize,
String columnName) {
this.columnType = columnType;
this.columnTypeName = columnTypeName;
this.nullable = nullable;
this.signed = signed;
this.precision = precision;
this.scale = scale;
this.columnDisplaySize = columnDisplaySize;
this.columnName = checkNotNull(columnName, "column name cannot be null");
}
public int getColumnType() {
return columnType;
}
public boolean isSigned() {
return signed;
}
public int getPrecision() {
return precision;
}
public int getScale() {
return scale;
}
public int getColumnDisplaySize() {
return columnDisplaySize;
}
public String getColumnName() {
return columnName;
}
public boolean isNullable() {
return nullable;
}
public String columnTypeName() {
return columnTypeName;
}
/**
* Build column info from given logical type.
*
* @param columnName the column name
* @param type the logical type
* @return the result column info
*/
public static ColumnInfo fromLogicalType(String columnName, LogicalType type) {
Builder builder =
new Builder()
.columnName(columnName)
.nullable(type.isNullable())
.signed(type.is(LogicalTypeFamily.NUMERIC))
.columnTypeName(type.asSummaryString());
if (type instanceof BooleanType) {
// "true" or "false"
builder.columnType(Types.BOOLEAN).columnDisplaySize(5);
} else if (type instanceof TinyIntType) {
builder.columnType(Types.TINYINT).precision(3).scale(0).columnDisplaySize(4);
} else if (type instanceof SmallIntType) {
builder.columnType(Types.SMALLINT).precision(5).scale(0).columnDisplaySize(6);
} else if (type instanceof IntType) {
builder.columnType(Types.INTEGER).precision(10).scale(0).columnDisplaySize(11);
} else if (type instanceof BigIntType) {
builder.columnType(Types.BIGINT).precision(19).scale(0).columnDisplaySize(20);
} else if (type instanceof FloatType) {
builder.columnType(Types.FLOAT).precision(9).scale(0).columnDisplaySize(16);
} else if (type instanceof DoubleType) {
builder.columnType(Types.DOUBLE).precision(17).scale(0).columnDisplaySize(24);
} else if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
builder.columnType(Types.DECIMAL)
.columnDisplaySize(decimalType.getPrecision() + 2) // dot and sign
.precision(decimalType.getPrecision())
.scale(decimalType.getScale());
} else if (type instanceof CharType) {
CharType charType = (CharType) type;
builder.columnType(Types.CHAR)
.scale(0)
.precision(charType.getLength())
.columnDisplaySize(charType.getLength());
} else if (type instanceof VarCharType) {
builder.columnType(Types.VARCHAR)
.scale(0)
.precision(VARBINARY_MAX)
.columnDisplaySize(VARBINARY_MAX);
} else if (type instanceof BinaryType) {
BinaryType binaryType = (BinaryType) type;
builder.columnType(Types.BINARY)
.scale(0)
.precision(binaryType.getLength())
.columnDisplaySize(binaryType.getLength());
} else if (type instanceof VarBinaryType) {
builder.columnType(Types.VARBINARY)
.scale(0)
.precision(VARBINARY_MAX)
.columnDisplaySize(VARBINARY_MAX);
} else if (type instanceof DateType) {
builder.columnType(Types.DATE).scale(0).columnDisplaySize(DATE_MAX);
} else if (type instanceof TimeType) {
TimeType timeType = (TimeType) type;
builder.columnType(Types.TIME)
.precision(timeType.getPrecision())
.scale(0)
.columnDisplaySize(TIME_MAX);
} else if (type instanceof TimestampType) {
TimestampType timestampType = (TimestampType) type;
builder.columnType(Types.TIMESTAMP)
.precision(timestampType.getPrecision())
.scale(0)
.columnDisplaySize(TIMESTAMP_MAX);
} else if (type instanceof LocalZonedTimestampType) {
LocalZonedTimestampType localZonedTimestampType = (LocalZonedTimestampType) type;
builder.columnType(Types.TIMESTAMP)
.precision(localZonedTimestampType.getPrecision())
.scale(0)
.columnDisplaySize(TIMESTAMP_MAX);
} else if (type instanceof ZonedTimestampType) {
ZonedTimestampType zonedTimestampType = (ZonedTimestampType) type;
builder.columnType(Types.TIMESTAMP_WITH_TIMEZONE)
.precision(zonedTimestampType.getPrecision())
.scale(0)
.columnDisplaySize(TIMESTAMP_WITH_TIME_ZONE_MAX);
} else if (type instanceof ArrayType) {
builder.columnType(Types.ARRAY)
.scale(0)
.precision(STRUCT_MAX)
.columnDisplaySize(STRUCT_MAX);
} else if (type instanceof MapType) {
// Use java object for map while there's no map in Types at the moment
builder.columnType(Types.JAVA_OBJECT)
.scale(0)
.precision(STRUCT_MAX)
.columnDisplaySize(STRUCT_MAX);
} else if (type instanceof RowType) {
builder.columnType(Types.STRUCT)
.precision(STRUCT_MAX)
.scale(0)
.columnDisplaySize(STRUCT_MAX);
} else {
throw new RuntimeException(String.format("Not supported type[%s]", type));
}
return builder.build();
}
/** Builder to build {@link ColumnInfo} from {@link LogicalType}. */
private static | ColumnInfo |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/ScheduleNowTransformAction.java | {
"start": 1297,
"end": 1659
} | class ____ extends ActionType<ScheduleNowTransformAction.Response> {
public static final ScheduleNowTransformAction INSTANCE = new ScheduleNowTransformAction();
public static final String NAME = "cluster:admin/transform/schedule_now";
private ScheduleNowTransformAction() {
super(NAME);
}
public static final | ScheduleNowTransformAction |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/annotation/Put.java | {
"start": 1273,
"end": 3222
} | interface ____ {
/**
* @return The URI of the PUT route
*/
@AliasFor(annotation = HttpMethodMapping.class, member = "value")
@AliasFor(annotation = UriMapping.class, member = "value")
String value() default UriMapping.DEFAULT_URI;
/**
* @return The URI of the PUT route
*/
@AliasFor(annotation = HttpMethodMapping.class, member = "value")
@AliasFor(annotation = UriMapping.class, member = "value")
String uri() default UriMapping.DEFAULT_URI;
/**
* Only to be used in the context of a server.
*
* @return The URIs of the PUT route
*/
@AliasFor(annotation = HttpMethodMapping.class, member = "uris")
@AliasFor(annotation = UriMapping.class, member = "uris")
String[] uris() default {UriMapping.DEFAULT_URI};
/**
* @return The default consumes, otherwise override from controller
*/
@AliasFor(annotation = Consumes.class, member = "value")
String[] consumes() default {};
/**
* @return The default produces, otherwise override from controller
*/
@AliasFor(annotation = Produces.class, member = "value")
String[] produces() default {};
/**
* Shortcut that allows setting both the {@link #consumes()} and {@link #produces()} settings to the same media type.
*
* @return The media type this method processes
*/
@AliasFor(annotation = Produces.class, member = "value")
@AliasFor(annotation = Consumes.class, member = "value")
String[] processes() default {};
/**
* Shortcut that allows setting both the {@link Consumes} and {@link Produces} single settings.
*
* @return Whether a single or multiple items are produced/consumed
*/
@AliasFor(annotation = Produces.class, member = "single")
@AliasFor(annotation = Consumes.class, member = "single")
@AliasFor(annotation = SingleResult.class, member = "value")
boolean single() default false;
}
| Put |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_311_issue.java | {
"start": 707,
"end": 1565
} | class ____
extends MysqlTest {
public void test_join() throws Exception {
String sql = "create view 054839e135a0be669145f2b90c4e8fcf5af46b as select 1";
// SQLStatement statement = SQLUtils.parseSingleMysqlStatement(sql);
// assertEquals("SELECT *\n" +
// "FROM abif.mob_rpt_retail_touch_d a\n" +
// "\tJOIN (\n" +
// "\t\tSELECT DISTINCT split_value, split_index\n" +
// "\t\tFROM abif.ysf_mercury_split_index_mapping\n" +
// "\t\tWHERE split_key = 'retailid'\n" +
// "\t\t\tAND rule_id = '1'\n" +
// "\t) b\n" +
// "\tON a.retail_id = b.split_value\n" +
// "\t\tAND a.ds = 20200201\n" +
// "\t\tAND a.aid IS NOT NULL", statement.toString());
}
}
| MySqlSelectTest_311_issue |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/alternatives/priority/AlternativePriorityResolutionTest.java | {
"start": 1398,
"end": 1651
} | class ____ {
@Produces
@Singleton
@Alternative
@Priority(4)
public MessageBean createBar() {
return new MessageBean("jar");
};
}
@Singleton
static | NoParentAlternativePriorityProducer1 |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/base64/Base64BinaryParsingTest.java | {
"start": 657,
"end": 17159
} | class ____
extends JacksonCoreTestBase
{
private final JsonFactory JSON_F = newStreamFactory();
@Test
void base64UsingInputStream() throws Exception
{
_testBase64Text(MODE_INPUT_STREAM);
_testBase64Text(MODE_INPUT_STREAM_THROTTLED);
_testBase64Text(MODE_DATA_INPUT);
}
@Test
void base64UsingReader() throws Exception
{
_testBase64Text(MODE_READER);
}
@Test
void streaming() throws IOException
{
_testStreaming(MODE_INPUT_STREAM);
_testStreaming(MODE_INPUT_STREAM_THROTTLED);
_testStreaming(MODE_DATA_INPUT);
_testStreaming(MODE_READER);
}
@Test
void simple() throws IOException
{
for (int mode : ALL_MODES) {
// [core#414]: Allow leading/trailign white-space, ensure it is accepted
_testSimple(mode, false, false);
_testSimple(mode, true, false);
_testSimple(mode, false, true);
_testSimple(mode, true, true);
}
}
@Test
void inArray() throws IOException
{
for (int mode : ALL_MODES) {
_testInArray(mode);
}
}
@Test
void withEscaped() throws IOException {
for (int mode : ALL_MODES) {
_testEscaped(mode);
}
}
@Test
void withEscapedPadding() throws IOException {
for (int mode : ALL_MODES) {
_testEscapedPadding(mode);
}
}
@Test
void invalidTokenForBase64() throws IOException
{
for (int mode : ALL_MODES) {
// First: illegal padding
JsonParser p = createParser(JSON_F, mode, "[ ]");
assertToken(JsonToken.START_ARRAY, p.nextToken());
try {
p.getBinaryValue();
fail("Should not pass");
} catch (StreamReadException e) {
verifyException(e, "current token");
verifyException(e, "cannot access as binary");
}
p.close();
}
}
@Test
void invalidChar() throws IOException
{
for (int mode : ALL_MODES) {
// First: illegal padding
JsonParser p = createParser(JSON_F, mode, q("a==="));
assertToken(JsonToken.VALUE_STRING, p.nextToken());
try {
p.getBinaryValue(Base64Variants.MIME);
fail("Should not pass");
} catch (StreamReadException e) {
verifyException(e, "padding only legal");
}
p.close();
// second: invalid space within
p = createParser(JSON_F, mode, q("ab de"));
assertToken(JsonToken.VALUE_STRING, p.nextToken());
try {
p.getBinaryValue(Base64Variants.MIME);
fail("Should not pass");
} catch (StreamReadException e) {
verifyException(e, "illegal white space");
}
p.close();
// third: something else
p = createParser(JSON_F, mode, q("ab#?"));
assertToken(JsonToken.VALUE_STRING, p.nextToken());
try {
p.getBinaryValue(Base64Variants.MIME);
fail("Should not pass");
} catch (StreamReadException e) {
verifyException(e, "illegal character '#'");
}
p.close();
}
}
@Test
void okMissingPadding() throws IOException {
final byte[] DOC1 = new byte[] { (byte) 0xAD };
_testOkMissingPadding(DOC1, MODE_INPUT_STREAM);
_testOkMissingPadding(DOC1, MODE_INPUT_STREAM_THROTTLED);
_testOkMissingPadding(DOC1, MODE_READER);
_testOkMissingPadding(DOC1, MODE_DATA_INPUT);
final byte[] DOC2 = new byte[] { (byte) 0xAC, (byte) 0xDC };
_testOkMissingPadding(DOC2, MODE_INPUT_STREAM);
_testOkMissingPadding(DOC2, MODE_INPUT_STREAM_THROTTLED);
_testOkMissingPadding(DOC2, MODE_READER);
_testOkMissingPadding(DOC2, MODE_DATA_INPUT);
}
private void _testOkMissingPadding(byte[] input, int mode)
{
final Base64Variant b64 = Base64Variants.MODIFIED_FOR_URL;
final String encoded = b64.encode(input, false);
JsonParser p = createParser(JSON_F, mode, q(encoded));
// 1 byte -> 2 encoded chars; 2 bytes -> 3 encoded chars
assertEquals(input.length+1, encoded.length());
assertToken(JsonToken.VALUE_STRING, p.nextToken());
byte[] actual = p.getBinaryValue(b64);
assertArrayEquals(input, actual);
p.close();
}
@Test
void failDueToMissingPadding() throws IOException {
final String DOC1 = q("fQ"); // 1 bytes, no padding
_testFailDueToMissingPadding(DOC1, MODE_INPUT_STREAM);
_testFailDueToMissingPadding(DOC1, MODE_INPUT_STREAM_THROTTLED);
_testFailDueToMissingPadding(DOC1, MODE_READER);
_testFailDueToMissingPadding(DOC1, MODE_DATA_INPUT);
final String DOC2 = q("A/A"); // 2 bytes, no padding
_testFailDueToMissingPadding(DOC2, MODE_INPUT_STREAM);
_testFailDueToMissingPadding(DOC2, MODE_INPUT_STREAM_THROTTLED);
_testFailDueToMissingPadding(DOC2, MODE_READER);
_testFailDueToMissingPadding(DOC2, MODE_DATA_INPUT);
}
private void _testFailDueToMissingPadding(String doc, int mode) {
final String EXP_EXCEPTION_MATCH = "Unexpected end of base64-encoded String: base64 variant 'MIME' expects padding";
// First, without getting text value first:
JsonParser p = createParser(JSON_F, mode, doc);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
try {
/*byte[] b =*/ p.getBinaryValue(Base64Variants.MIME);
fail("Should not pass");
} catch (StreamReadException e) {
verifyException(e, EXP_EXCEPTION_MATCH);
}
p.close();
// second, access String first
p = createParser(JSON_F, mode, doc);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
/*String str =*/ p.getString();
try {
/*byte[] b =*/ p.getBinaryValue(Base64Variants.MIME);
fail("Should not pass");
} catch (StreamReadException e) {
verifyException(e, EXP_EXCEPTION_MATCH);
}
p.close();
}
/*
/**********************************************************
/* Test helper methods
/**********************************************************
*/
@SuppressWarnings("resource")
void _testBase64Text(int mode) throws Exception
{
// let's actually iterate over sets of encoding modes, lengths
final int[] LENS = { 1, 2, 3, 4, 7, 9, 32, 33, 34, 35 };
final Base64Variant[] VARIANTS = {
Base64Variants.MIME,
Base64Variants.MIME_NO_LINEFEEDS,
Base64Variants.MODIFIED_FOR_URL,
Base64Variants.PEM
};
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter chars = null;
for (int len : LENS) {
byte[] input = new byte[len];
for (int i = 0; i < input.length; ++i) {
input[i] = (byte) i;
}
for (Base64Variant variant : VARIANTS) {
JsonGenerator g;
if (mode == MODE_READER) {
chars = new StringWriter();
g = JSON_F.createGenerator(ObjectWriteContext.empty(), chars);
} else {
bytes.reset();
g = JSON_F.createGenerator(ObjectWriteContext.empty(), bytes, JsonEncoding.UTF8);
}
g.writeBinary(variant, input, 0, input.length);
g.close();
JsonParser p;
if (mode == MODE_READER) {
p = JSON_F.createParser(ObjectReadContext.empty(), chars.toString());
} else {
p = createParser(JSON_F, mode, bytes.toByteArray());
}
assertToken(JsonToken.VALUE_STRING, p.nextToken());
// minor twist: for even-length values, force access as String first:
if ((len & 1) == 0) {
assertNotNull(p.getString());
}
byte[] data = null;
try {
data = p.getBinaryValue(variant);
} catch (Exception e) {
RuntimeException ioException = new RuntimeException("Failed (variant "+variant+", data length "+len+"): "+e.getMessage());
ioException.initCause(e);
throw ioException;
}
assertNotNull(data);
assertArrayEquals(data, input);
if (mode != MODE_DATA_INPUT) { // no look-ahead for DataInput
assertNull(p.nextToken());
}
p.close();
}
}
}
private byte[] _generateData(int size)
{
byte[] result = new byte[size];
for (int i = 0; i < size; ++i) {
result[i] = (byte) (i % 255);
}
return result;
}
private void _testStreaming(int mode)
{
final int[] SIZES = new int[] {
1, 2, 3, 4, 5, 6,
7, 8, 12,
100, 350, 1900, 6000, 19000, 65000,
139000
};
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter chars = null;
for (int size : SIZES) {
byte[] data = _generateData(size);
JsonGenerator g;
if (mode == MODE_READER) {
chars = new StringWriter();
g = JSON_F.createGenerator(ObjectWriteContext.empty(), chars);
} else {
bytes.reset();
g = JSON_F.createGenerator(ObjectWriteContext.empty(), bytes, JsonEncoding.UTF8);
}
g.writeStartObject();
g.writeName("b");
g.writeBinary(data);
g.writeEndObject();
g.close();
// and verify
JsonParser p;
if (mode == MODE_READER) {
p = JSON_F.createParser(ObjectReadContext.empty(), chars.toString());
} else {
p = createParser(JSON_F, mode, bytes.toByteArray());
}
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("b", p.currentName());
assertToken(JsonToken.VALUE_STRING, p.nextToken());
ByteArrayOutputStream result = new ByteArrayOutputStream(size);
int gotten = p.readBinaryValue(result);
assertEquals(size, gotten);
assertArrayEquals(data, result.toByteArray());
assertToken(JsonToken.END_OBJECT, p.nextToken());
if (mode != MODE_DATA_INPUT) { // no look-ahead for DataInput
assertNull(p.nextToken());
}
p.close();
}
}
private void _testSimple(int mode, boolean leadingWS, boolean trailingWS)
{
// The usual sample input string, from Thomas Hobbes's "Leviathan"
// (via Wikipedia)
final String RESULT = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
final byte[] RESULT_BYTES = RESULT.getBytes(StandardCharsets.US_ASCII);
// And here's what should produce it...
String INPUT_STR =
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
+"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
+"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
+"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
+"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
;
if (leadingWS) {
INPUT_STR = " "+INPUT_STR;
}
if (leadingWS) {
INPUT_STR = INPUT_STR+" ";
}
final String DOC = "\""+INPUT_STR+"\"";
JsonParser p = createParser(JSON_F, mode, DOC);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
byte[] data = p.getBinaryValue();
assertNotNull(data);
assertArrayEquals(RESULT_BYTES, data);
p.close();
}
private void _testInArray(int mode)
{
final int entryCount = 7;
StringWriter sw = new StringWriter();
JsonGenerator jg = JSON_F.createGenerator(ObjectWriteContext.empty(), sw);
jg.writeStartArray();
byte[][] entries = new byte[entryCount][];
for (int i = 0; i < entryCount; ++i) {
byte[] b = new byte[200 + i * 100];
for (int x = 0; x < b.length; ++x) {
b[x] = (byte) (i + x);
}
entries[i] = b;
jg.writeBinary(b);
}
jg.writeEndArray();
jg.close();
JsonParser p = createParser(JSON_F, mode, sw.toString());
assertToken(JsonToken.START_ARRAY, p.nextToken());
for (int i = 0; i < entryCount; ++i) {
assertToken(JsonToken.VALUE_STRING, p.nextToken());
byte[] b = p.getBinaryValue();
assertArrayEquals(entries[i], b);
}
assertToken(JsonToken.END_ARRAY, p.nextToken());
p.close();
}
private void _testEscaped(int mode) throws IOException
{
// Input: "Test!" -> "VGVzdCE="
// First, try with embedded linefeed half-way through:
String DOC = q("VGVz\\ndCE="); // note: must double-quote to get linefeed
JsonParser p = createParser(JSON_F, mode, DOC);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
byte[] b = p.getBinaryValue();
assertEquals("Test!", new String(b, "US-ASCII"));
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
// and then with escaped chars
// DOC = quote("V\\u0047V\\u007AdCE="); // note: must escape backslash...
DOC = q("V\\u0047V\\u007AdCE="); // note: must escape backslash...
p = createParser(JSON_F, mode, DOC);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
b = p.getBinaryValue();
assertEquals("Test!", new String(b, "US-ASCII"));
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
}
private void _testEscapedPadding(int mode) throws IOException
{
// Input: "Test!" -> "VGVzdCE="
final String DOC = q("VGVzdCE\\u003d");
// 06-Sep-2018, tatu: actually one more, test escaping of padding
JsonParser p = createParser(JSON_F, mode, DOC);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
assertEquals("Test!", new String(p.getBinaryValue(), "US-ASCII"));
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
// also, try out alternate access method
p = createParser(JSON_F, mode, DOC);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
assertEquals("Test!", new String(_readBinary(p), "US-ASCII"));
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
// and then different padding; "X" -> "WA=="
final String DOC2 = q("WA\\u003D\\u003D");
p = createParser(JSON_F, mode, DOC2);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
assertEquals("X", new String(p.getBinaryValue(), "US-ASCII"));
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
p = createParser(JSON_F, mode, DOC2);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
assertEquals("X", new String(_readBinary(p), "US-ASCII"));
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
}
private byte[] _readBinary(JsonParser p)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
p.readBinaryValue(bytes);
return bytes.toByteArray();
}
}
| Base64BinaryParsingTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/ListFloatFieldTest.java | {
"start": 619,
"end": 847
} | class ____ {
private List<Float> value;
public List<Float> getValue() {
return value;
}
public void setValue(List<Float> value) {
this.value = value;
}
}
}
| User |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/engine/SearchBasedChangesSnapshot.java | {
"start": 1757,
"end": 2002
} | class ____ provides a snapshot mechanism to retrieve operations from a live Lucene index
* within a specified range of sequence numbers. Subclasses are expected to define the
* method to fetch the next batch of operations.
*/
public abstract | that |
java | netty__netty | transport/src/main/java/io/netty/channel/oio/OioEventLoopGroup.java | {
"start": 1241,
"end": 3688
} | class ____ extends ThreadPerChannelEventLoopGroup {
/**
* Create a new {@link OioEventLoopGroup} with no limit in place.
*/
public OioEventLoopGroup() {
this(0);
}
/**
* Create a new {@link OioEventLoopGroup}.
*
* @param maxChannels the maximum number of channels to handle with this instance. Once you try to register
* a new {@link Channel} and the maximum is exceed it will throw an
* {@link ChannelException} on the {@link #register(Channel)} and
* {@link #register(ChannelPromise)} method.
* Use {@code 0} to use no limit
*/
public OioEventLoopGroup(int maxChannels) {
this(maxChannels, (ThreadFactory) null);
}
/**
* Create a new {@link OioEventLoopGroup}.
*
* @param maxChannels the maximum number of channels to handle with this instance. Once you try to register
* a new {@link Channel} and the maximum is exceed it will throw an
* {@link ChannelException} on the {@link #register(Channel)} and
* {@link #register(ChannelPromise)} method.
* Use {@code 0} to use no limit
* @param executor the {@link Executor} used to create new {@link Thread} instances that handle the
* registered {@link Channel}s
*/
public OioEventLoopGroup(int maxChannels, Executor executor) {
super(maxChannels, executor);
}
/**
* Create a new {@link OioEventLoopGroup}.
*
* @param maxChannels the maximum number of channels to handle with this instance. Once you try to register
* a new {@link Channel} and the maximum is exceed it will throw an
* {@link ChannelException} on the {@link #register(Channel)} and
* {@link #register(ChannelPromise)} method.
* Use {@code 0} to use no limit
* @param threadFactory the {@link ThreadFactory} used to create new {@link Thread} instances that handle the
* registered {@link Channel}s
*/
public OioEventLoopGroup(int maxChannels, ThreadFactory threadFactory) {
super(maxChannels, threadFactory);
}
}
| OioEventLoopGroup |
java | quarkusio__quarkus | integration-tests/elytron-resteasy-reactive/src/test/java/io/quarkus/it/resteasy/reactive/elytron/StreamingOutputErrorHandlingIT.java | {
"start": 135,
"end": 217
} | class ____ extends StreamingOutputErrorHandlingTest {
}
| StreamingOutputErrorHandlingIT |
java | apache__camel | components/camel-quartz/src/test/java/org/apache/camel/component/quartz/SpringQuartzPersistentStoreRestartRouteTest.java | {
"start": 1275,
"end": 2294
} | class ____ extends CamelSpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return newAppContext("SpringQuartzPersistentStoreTest.xml");
}
@Test
public void testQuartzPersistentStore() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(2);
MockEndpoint.assertIsSatisfied(context);
// restart route
context().getRouteController().stopRoute("myRoute");
mock.reset();
mock.expectedMessageCount(0);
// wait a bit
Awaitility.await().atMost(2, TimeUnit.SECONDS)
.untilAsserted(() -> MockEndpoint.assertIsSatisfied(context));
// start route, and we got messages again
mock.reset();
mock.expectedMinimumMessageCount(2);
context().getRouteController().startRoute("myRoute");
MockEndpoint.assertIsSatisfied(context);
}
}
| SpringQuartzPersistentStoreRestartRouteTest |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/inheritance/deep/DeepInheritanceTest.java | {
"start": 702,
"end": 788
} | class ____
* does not declare an id
*
* @author Igor Vaynberg
*/
@CompilationTest
| that |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/join/InnerJoinRecordReader.java | {
"start": 1233,
"end": 1826
} | class ____<K extends WritableComparable<?>>
extends JoinRecordReader<K> {
InnerJoinRecordReader(int id, Configuration conf, int capacity,
Class<? extends WritableComparator> cmpcl) throws IOException {
super(id, conf, capacity, cmpcl);
}
/**
* Return true iff the tuple is full (all data sources contain this key).
*/
protected boolean combine(Object[] srcs, TupleWritable dst) {
assert srcs.length == dst.size();
for (int i = 0; i < srcs.length; ++i) {
if (!dst.has(i)) {
return false;
}
}
return true;
}
}
| InnerJoinRecordReader |
java | mockito__mockito | mockito-extensions/mockito-android/src/main/java/org/mockito/android/internal/creation/AndroidLoadingStrategy.java | {
"start": 1110,
"end": 1565
} | class ____",
"This location must be in private scope for most API versions, for example:",
"",
"MyActivity.this.getDir(\"target\", Context.MODE_PRIVATE)",
"or",
"getInstrumentation().getTargetContext().getCacheDir().getPath()"));
}
return new AndroidClassLoadingStrategy.Injecting(target);
}
}
| files |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/MainBytecodeRecorderBuildItem.java | {
"start": 479,
"end": 563
} | class ____ {@link #generatedStartupContextClassName}.</li>
* </ul>
*/
public final | via |
java | apache__camel | components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/customresources/KubernetesCustomResourcesEndpoint.java | {
"start": 1740,
"end": 2427
} | class ____ extends AbstractKubernetesEndpoint {
public KubernetesCustomResourcesEndpoint(String uri, KubernetesCustomResourcesComponent component,
KubernetesConfiguration config) {
super(uri, component, config);
}
@Override
public Producer createProducer() throws Exception {
return new KubernetesCustomResourcesProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
Consumer consumer = new KubernetesCustomResourcesConsumer(this, processor);
configureConsumer(consumer);
return consumer;
}
}
| KubernetesCustomResourcesEndpoint |
java | google__guava | android/guava/src/com/google/common/reflect/Types.java | {
"start": 8657,
"end": 11528
} | class ____ implements ParameterizedType, Serializable {
private final @Nullable Type ownerType;
private final ImmutableList<Type> argumentsList;
private final Class<?> rawType;
ParameterizedTypeImpl(@Nullable Type ownerType, Class<?> rawType, Type[] typeArguments) {
checkNotNull(rawType);
checkArgument(typeArguments.length == rawType.getTypeParameters().length);
disallowPrimitiveType(typeArguments, "type parameter");
this.ownerType = ownerType;
this.rawType = rawType;
this.argumentsList = JavaVersion.CURRENT.usedInGenericType(typeArguments);
}
@Override
public Type[] getActualTypeArguments() {
return toArray(argumentsList);
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public @Nullable Type getOwnerType() {
return ownerType;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (ownerType != null && JavaVersion.CURRENT.jdkTypeDuplicatesOwnerName()) {
builder.append(JavaVersion.CURRENT.typeName(ownerType)).append('.');
}
return builder
.append(rawType.getName())
.append('<')
.append(COMMA_JOINER.join(transform(argumentsList, JavaVersion.CURRENT::typeName)))
.append('>')
.toString();
}
@Override
public int hashCode() {
return (ownerType == null ? 0 : ownerType.hashCode())
^ argumentsList.hashCode()
^ rawType.hashCode();
}
@Override
public boolean equals(@Nullable Object other) {
if (!(other instanceof ParameterizedType)) {
return false;
}
ParameterizedType that = (ParameterizedType) other;
return getRawType().equals(that.getRawType())
&& Objects.equals(getOwnerType(), that.getOwnerType())
&& Arrays.equals(getActualTypeArguments(), that.getActualTypeArguments());
}
private static final long serialVersionUID = 0;
}
private static <D extends GenericDeclaration> TypeVariable<D> newTypeVariableImpl(
D genericDeclaration, String name, Type[] bounds) {
TypeVariableImpl<D> typeVariableImpl = new TypeVariableImpl<>(genericDeclaration, name, bounds);
@SuppressWarnings("unchecked")
TypeVariable<D> typeVariable =
Reflection.newProxy(
TypeVariable.class, new TypeVariableInvocationHandler(typeVariableImpl));
return typeVariable;
}
/**
* Invocation handler to work around a compatibility problem between Android and Java.
*
* <p>Java 8 introduced a new method {@code getAnnotatedBounds()} in the {@link TypeVariable}
* interface, whose return type {@code AnnotatedType[]} is also new in Java 8. As of 2025, Android
* has not added {@link AnnotatedType}. That means that we cannot implement that | ParameterizedTypeImpl |
java | apache__camel | components/camel-ignite/src/test/java/org/apache/camel/component/ignite/IgniteCacheTest.java | {
"start": 1644,
"end": 10705
} | class ____ extends AbstractIgniteTest {
@Override
protected String getScheme() {
return "ignite-cache";
}
@Override
protected AbstractIgniteComponent createComponent() {
return IgniteCacheComponent.fromConfiguration(createConfiguration());
}
@Test
public void testAddEntry() {
template.requestBodyAndHeader("ignite-cache:" + resourceUid + "?operation=PUT", "1234",
IgniteConstants.IGNITE_CACHE_KEY, "abcd");
Assertions.assertThat(ignite().cache(resourceUid).size(CachePeekMode.ALL)).isEqualTo(1);
Assertions.assertThat(ignite().cache(resourceUid).get("abcd")).isEqualTo("1234");
}
@Test
public void testAddEntrySet() {
template.requestBody("ignite-cache:" + resourceUid + "?operation=PUT", ImmutableMap.of("abcd", "1234", "efgh", "5678"));
Assertions.assertThat(ignite().cache(resourceUid).size(CachePeekMode.ALL)).isEqualTo(2);
Assertions.assertThat(ignite().cache(resourceUid).get("abcd")).isEqualTo("1234");
Assertions.assertThat(ignite().cache(resourceUid).get("efgh")).isEqualTo("5678");
}
@Test
public void testGetOne() {
testAddEntry();
String result = template.requestBody("ignite-cache:" + resourceUid + "?operation=GET", "abcd", String.class);
Assertions.assertThat(result).isEqualTo("1234");
result = template.requestBodyAndHeader("ignite-cache:" + resourceUid + "?operation=GET", "this value won't be used",
IgniteConstants.IGNITE_CACHE_KEY, "abcd",
String.class);
Assertions.assertThat(result).isEqualTo("1234");
}
@Test
@SuppressWarnings("unchecked")
public void testGetMany() {
IgniteCache<String, String> cache = ignite().getOrCreateCache(resourceUid);
Set<String> keys = new HashSet<>();
for (int i = 0; i < 100; i++) {
cache.put("k" + i, "v" + i);
keys.add("k" + i);
}
Map<String, String> result = template.requestBody("ignite-cache:" + resourceUid + "?operation=GET", keys, Map.class);
for (String k : keys) {
Assertions.assertThat(result.get(k)).isEqualTo(k.replace("k", "v"));
}
}
@Test
public void testGetSize() {
IgniteCache<String, String> cache = ignite().getOrCreateCache(resourceUid);
Set<String> keys = new HashSet<>();
for (int i = 0; i < 100; i++) {
cache.put("k" + i, "v" + i);
keys.add("k" + i);
}
Integer result = template.requestBody("ignite-cache:" + resourceUid + "?operation=SIZE", keys, Integer.class);
Assertions.assertThat(result).isEqualTo(100);
}
@Test
public void testQuery() {
IgniteCache<String, String> cache = ignite().getOrCreateCache(resourceUid);
Set<String> keys = new HashSet<>();
for (int i = 0; i < 100; i++) {
cache.put("k" + i, "v" + i);
keys.add("k" + i);
}
Query<Entry<String, String>> query = new ScanQuery<>(new IgniteBiPredicate<String, String>() {
private static final long serialVersionUID = 1L;
@Override
public boolean apply(String key, String value) {
return Integer.parseInt(key.replace("k", "")) >= 50;
}
});
List<?> results = template.requestBodyAndHeader("ignite-cache:" + resourceUid + "?operation=QUERY", keys,
IgniteConstants.IGNITE_CACHE_QUERY, query, List.class);
Assertions.assertThat(results.size()).isEqualTo(50);
}
@Test
public void testGetManyTreatCollectionsAsCacheObjects() {
IgniteCache<Object, String> cache = ignite().getOrCreateCache(resourceUid);
Set<String> keys = new HashSet<>();
for (int i = 0; i < 100; i++) {
cache.put("k" + i, "v" + i);
keys.add("k" + i);
}
// Also add a cache entry with the entire Set as a key.
cache.put(keys, "---");
String result = template.requestBody(
"ignite-cache:" + resourceUid + "?operation=GET&treatCollectionsAsCacheObjects=true", keys, String.class);
Assertions.assertThat(result).isEqualTo("---");
}
@Test
public void testRemoveEntry() {
IgniteCache<String, String> cache = ignite().getOrCreateCache(resourceUid);
cache.put("abcd", "1234");
cache.put("efgh", "5678");
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(2);
template.requestBody("ignite-cache:" + resourceUid + "?operation=REMOVE", "abcd");
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(1);
Assertions.assertThat(cache.get("abcd")).isNull();
template.requestBodyAndHeader("ignite-cache:" + resourceUid + "?operation=REMOVE", "this value won't be used",
IgniteConstants.IGNITE_CACHE_KEY, "efgh");
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(0);
Assertions.assertThat(cache.get("efgh")).isNull();
}
@Test
public void testReplaceEntry() {
template.requestBodyAndHeader("ignite-cache:" + resourceUid + "?operation=REPLACE", "5678",
IgniteConstants.IGNITE_CACHE_KEY, "abcd");
IgniteCache<String, String> cache = ignite().getOrCreateCache(resourceUid);
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(0);
cache.put("abcd", "1234");
template.requestBodyAndHeader("ignite-cache:" + resourceUid + "?operation=REPLACE", "5678",
IgniteConstants.IGNITE_CACHE_KEY, "abcd");
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(1);
Assertions.assertThat(cache.get("abcd")).isEqualTo("5678");
Map<String, Object> headers
= Map.of(IgniteConstants.IGNITE_CACHE_KEY, "abcd", IgniteConstants.IGNITE_CACHE_OLD_VALUE, "1234");
template.requestBodyAndHeaders("ignite-cache:" + resourceUid + "?operation=REPLACE", "9", headers);
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(1);
Assertions.assertThat(cache.get("abcd")).isEqualTo("5678");
headers = Map.of(IgniteConstants.IGNITE_CACHE_KEY, "abcd", IgniteConstants.IGNITE_CACHE_OLD_VALUE, "5678");
template.requestBodyAndHeaders("ignite-cache:" + resourceUid + "?operation=REPLACE", "9", headers);
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(1);
Assertions.assertThat(cache.get("abcd")).isEqualTo("9");
}
@Test
public void testClearCache() {
IgniteCache<String, String> cache = ignite().getOrCreateCache(resourceUid);
for (int i = 0; i < 100; i++) {
cache.put("k" + i, "v" + i);
}
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(100);
template.requestBody("ignite-cache:" + resourceUid + "?operation=CLEAR", "this value won't be used");
Assertions.assertThat(cache.size(CachePeekMode.ALL)).isEqualTo(0);
}
@Test
public void testHeaderSetRemoveEntry() {
testAddEntry();
String result = template.requestBody("ignite-cache:" + resourceUid + "?operation=GET", "abcd", String.class);
Assertions.assertThat(result).isEqualTo("1234");
result = template.requestBodyAndHeader("ignite-cache:" + resourceUid + "?operation=GET", "abcd",
IgniteConstants.IGNITE_CACHE_OPERATION, IgniteCacheOperation.REMOVE,
String.class);
// The body has not changed, but the cache entry is gone.
Assertions.assertThat(result).isEqualTo("abcd");
Assertions.assertThat(ignite().cache(resourceUid).size(CachePeekMode.ALL)).isEqualTo(0);
}
@Test
public void testAddEntryNoCacheCreation() {
try {
template.requestBodyAndHeader("ignite-cache:testcache2?operation=PUT&failIfInexistentCache=true", "1234",
IgniteConstants.IGNITE_CACHE_KEY, "abcd");
} catch (Exception e) {
Assertions.assertThat(ObjectHelper.getException(CamelException.class, e).getMessage())
.startsWith("Ignite cache testcache2 doesn't exist");
return;
}
fail("Should have thrown an exception");
}
@Test
public void testAddEntryDoNotPropagateIncomingBody() {
Object result = template.requestBodyAndHeader(
"ignite-cache:" + resourceUid + "?operation=PUT&propagateIncomingBodyIfNoReturnValue=false", "1234",
IgniteConstants.IGNITE_CACHE_KEY, "abcd", Object.class);
Assertions.assertThat(ignite().cache(resourceUid).size(CachePeekMode.ALL)).isEqualTo(1);
Assertions.assertThat(ignite().cache(resourceUid).get("abcd")).isEqualTo("1234");
Assertions.assertThat(result).isNull();
}
@AfterEach
public void deleteCaches() {
IgniteCache<?, ?> cache = ignite().cache(resourceUid);
if (cache != null) {
cache.clear();
}
}
}
| IgniteCacheTest |
java | processing__processing4 | java/libraries/net/src/processing/net/Server.java | {
"start": 1842,
"end": 9924
} | class ____ implements Runnable {
PApplet parent;
Method serverEventMethod;
volatile Thread thread;
ServerSocket server;
int port;
protected final Object clientsLock = new Object[0];
/** Number of clients currently connected. */
public int clientCount;
/** Array of client objects, useful length is determined by clientCount. */
public Client[] clients;
/**
* @param parent typically use "this"
* @param port port used to transfer data
*/
public Server(PApplet parent, int port) {
this(parent, port, null);
}
/**
* @param parent typically use "this"
* @param port port used to transfer data
* @param host when multiple NICs are in use, the ip (or name) to bind from
*/
public Server(PApplet parent, int port, String host) {
this.parent = parent;
this.port = port;
try {
if (host == null) {
server = new ServerSocket(this.port);
} else {
server = new ServerSocket(this.port, 10, InetAddress.getByName(host));
}
//clients = new Vector();
clients = new Client[10];
thread = new Thread(this);
thread.start();
parent.registerMethod("dispose", this);
// reflection to check whether host sketch has a call for
// public void serverEvent(Server s, Client c);
// which is called when a new guy connects
try {
serverEventMethod =
parent.getClass().getMethod("serverEvent", Server.class, Client.class);
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
} catch (IOException e) {
//e.printStackTrace();
thread = null;
throw new RuntimeException(e);
//errorMessage("<init>", e);
}
}
/**
*
* Disconnect a particular client.
*
* @webref server
* @webBrief Disconnect a particular client
* @param client the client to disconnect
*/
public void disconnect(Client client) {
client.stop();
synchronized (clientsLock) {
int index = clientIndex(client);
if (index != -1) {
removeIndex(index);
}
}
}
protected void removeIndex(int index) {
synchronized (clientsLock) {
clientCount--;
// shift down the remaining clients
for (int i = index; i < clientCount; i++) {
clients[i] = clients[i + 1];
}
// mark last empty var for garbage collection
clients[clientCount] = null;
}
}
protected void disconnectAll() {
synchronized (clientsLock) {
for (int i = 0; i < clientCount; i++) {
try {
clients[i].stop();
} catch (Exception e) {
// ignore
}
clients[i] = null;
}
clientCount = 0;
}
}
protected void addClient(Client client) {
synchronized (clientsLock) {
if (clientCount == clients.length) {
clients = (Client[]) PApplet.expand(clients);
}
clients[clientCount++] = client;
}
}
protected int clientIndex(Client client) {
synchronized (clientsLock) {
for (int i = 0; i < clientCount; i++) {
if (clients[i] == client) {
return i;
}
}
return -1;
}
}
/**
*
* Returns <b>true</b> if this server is still active and hasn't run
* into any trouble.
*
* @webref server
* @webBrief Return <b>true</b> if this server is still active
*/
public boolean active() {
return thread != null;
}
static public String ip() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
}
// the last index used for available. can't just cycle through
// the clients in order from 0 each time, because if client 0 won't
// shut up, then the rest of the clients will never be heard from.
int lastAvailable = -1;
/**
*
* Returns the next client in line with a new message.
*
* @webref server
* @webBrief Returns the next client in line with a new message
* @usage application
*/
public Client available() {
synchronized (clientsLock) {
int index = lastAvailable + 1;
if (index >= clientCount) index = 0;
for (int i = 0; i < clientCount; i++) {
int which = (index + i) % clientCount;
Client client = clients[which];
//Check for valid client
if (!client.active()){
removeIndex(which); //Remove dead client
i--; //Don't skip the next client
//If the client has data make sure lastAvailable
//doesn't end up skipping the next client
which--;
//fall through to allow data from dead clients
//to be retreived.
}
if (client.available() > 0) {
lastAvailable = which;
return client;
}
}
}
return null;
}
/**
*
* Disconnects all clients and stops the server.
*
* <h3>Advanced</h3>
* Use this to shut down the server if you finish using it while your sketch
* is still running. Otherwise, it will be automatically be shut down by the
* host PApplet using dispose(), which is identical.
* @webref server
* @webBrief Disconnects all clients and stops the server
* @usage application
*/
public void stop() {
dispose();
}
/**
* Disconnect all clients and stop the server: internal use only.
*/
public void dispose() {
thread = null;
if (clients != null) {
disconnectAll();
clientCount = 0;
clients = null;
}
try {
if (server != null) {
server.close();
server = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (Thread.currentThread() == thread) {
try {
Socket socket = server.accept();
Client client = new Client(parent, socket);
synchronized (clientsLock) {
addClient(client);
if (serverEventMethod != null) {
try {
serverEventMethod.invoke(parent, this, client);
} catch (Exception e) {
System.err.println("Disabling serverEvent() for port " + port);
Throwable cause = e;
// unwrap the exception if it came from the user code
if (e instanceof InvocationTargetException && e.getCause() != null) {
cause = e.getCause();
}
cause.printStackTrace();
serverEventMethod = null;
}
}
}
} catch (SocketException e) {
//thrown when server.close() is called and server is waiting on accept
System.err.println("Server SocketException: " + e.getMessage());
thread = null;
} catch (IOException e) {
//errorMessage("run", e);
e.printStackTrace();
thread = null;
}
}
}
/**
*
* Writes a value to all the connected clients. It sends bytes out from the
* Server object.
*
* @webref server
* @webBrief Writes data to all connected clients
* @param data data to write
*/
public void write(int data) { // will also cover char
synchronized (clientsLock) {
int index = 0;
while (index < clientCount) {
if (clients[index].active()) {
clients[index].write(data);
index++;
} else {
removeIndex(index);
}
}
}
}
public void write(byte data[]) {
synchronized (clientsLock) {
int index = 0;
while (index < clientCount) {
if (clients[index].active()) {
clients[index].write(data);
index++;
} else {
removeIndex(index);
}
}
}
}
public void write(String data) {
synchronized (clientsLock) {
int index = 0;
while (index < clientCount) {
if (clients[index].active()) {
clients[index].write(data);
index++;
} else {
removeIndex(index);
}
}
}
}
}
| Server |
java | reactor__reactor-core | benchmarks/src/main/java/reactor/core/scrabble/FluxCharSequence.java | {
"start": 369,
"end": 697
} | class ____ extends Flux<Integer> implements Fuseable {
final CharSequence string;
FluxCharSequence(CharSequence string) {
this.string = string;
}
@Override
public void subscribe(CoreSubscriber<? super Integer> actual) {
actual.onSubscribe(new CharSequenceSubscription(actual, string));
}
static final | FluxCharSequence |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/internal/util/collections/BoundedConcurrentHashMap.java | {
"start": 1315,
"end": 3351
} | class ____ fully
* interoperable with {@code Hashtable} in programs that rely on its
* thread safety but not on its synchronization details.
* <p>
* <p> Retrieval operations (including {@code get}) generally do not
* block, so may overlap with update operations (including
* {@code put} and {@code remove}). Retrievals reflect the results
* of the most recently <em>completed</em> update operations holding
* upon their onset. For aggregate operations such as {@code putAll}
* and {@code clear}, concurrent retrievals may reflect insertion or
* removal of only some entries. Similarly, Iterators and
* Enumerations return elements reflecting the state of the hash table
* at some point at or since the creation of the iterator/enumeration.
* They do <em>not</em> throw {@link java.util.ConcurrentModificationException}.
* However, iterators are designed to be used by only one thread at a time.
* <p>
* <p> The allowed concurrency among update operations is guided by
* the optional {@code concurrencyLevel} constructor argument
* (default {@code 16}), which is used as a hint for internal sizing. The
* table is internally partitioned to try to permit the indicated
* number of concurrent updates without contention. Because placement
* in hash tables is essentially random, the actual concurrency will
* vary. Ideally, you should choose a value to accommodate as many
* threads as will ever concurrently modify the table. Using a
* significantly higher value than you need can waste space and time,
* and a significantly lower value can lead to thread contention. But
* overestimates and underestimates within an order of magnitude do
* not usually have much noticeable impact. A value of one is
* appropriate when it is known that only one thread will modify and
* all others will only read. Also, resizing this or any other kind of
* hash table is a relatively slow operation, so, when possible, it is
* a good idea to provide estimates of expected table sizes in
* constructors.
* <p>
* <p>This | is |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/Tracer.java | {
"start": 1057,
"end": 5454
} | interface ____ extends StaticService {
/**
* Whether or not to trace the given processor definition.
*
* @param definition the processor definition
* @return <tt>true</tt> to trace, <tt>false</tt> to skip tracing
*/
boolean shouldTrace(NamedNode definition);
/**
* Trace before the route (eg input to route)
*
* @param route the route EIP
* @param exchange the exchange
*/
void traceBeforeRoute(NamedRoute route, Exchange exchange);
/**
* Trace before the given node
*
* @param node the node EIP
* @param exchange the exchange
*/
void traceBeforeNode(NamedNode node, Exchange exchange);
/**
* Trace after the given node
*
* @param node the node EIP
* @param exchange the exchange
*/
void traceAfterNode(NamedNode node, Exchange exchange);
/**
* Trace when an Exchange was sent to a given endpoint
*
* @param node the node EIP
* @param exchange the exchange
* @param endpoint the endpoint the exchange was sent to
* @param elapsed time in millis for sending the exchange
*/
void traceSentNode(NamedNode node, Exchange exchange, Endpoint endpoint, long elapsed);
/**
* Trace after the route (eg output from route)
*
* @param route the route EIP
* @param exchange the exchange
*/
void traceAfterRoute(NamedRoute route, Exchange exchange);
/**
* Number of traced messages
*/
long getTraceCounter();
/**
* Reset trace counter
*/
void resetTraceCounter();
/**
* Whether the tracer is enabled
*/
boolean isEnabled();
/**
* Whether the tracer is enabled
*/
void setEnabled(boolean enabled);
/**
* Whether the tracer is standby.
* <p>
* If a tracer is in standby then the tracer is activated during startup and are ready to be enabled manually via
* JMX or calling the enabled method.
*/
boolean isStandby();
/**
* Whether the tracer is standby.
* <p>
* If a tracer is in standby then the tracer is activated during startup and are ready to be enabled manually via
* JMX or calling the enabled method.
*/
void setStandby(boolean standby);
/**
* Whether to trace routes that is created from Rest DSL.
*/
boolean isTraceRests();
/**
* Whether to trace routes that is created from route templates or kamelets.
*/
void setTraceRests(boolean traceRests);
/**
* Whether tracing should trace inner details from route templates (or kamelets). Turning this off can reduce the
* verbosity of tracing when using many route templates, and allow to focus on tracing your own Camel routes only.
*/
boolean isTraceTemplates();
/**
* Whether tracing should trace inner details from route templates (or kamelets). Turning this off can reduce the
* verbosity of tracing when using many route templates, and allow to focus on tracing your own Camel routes only.
*/
void setTraceTemplates(boolean traceTemplates);
/**
* Tracing pattern to match which node EIPs to trace. For example to match all To EIP nodes, use to*. The pattern
* matches by node and route id's Multiple patterns can be separated by comma.
*/
String getTracePattern();
/**
* Tracing pattern to match which node EIPs to trace. For example to match all To EIP nodes, use to*. The pattern
* matches by node and route id's Multiple patterns can be separated by comma.
*/
void setTracePattern(String tracePattern);
/**
* Whether to include tracing of before/after routes to trace the input and responses of routes.
*/
boolean isTraceBeforeAndAfterRoute();
/**
* Whether to include tracing of before/after routes to trace the input and responses of routes.
*/
void setTraceBeforeAndAfterRoute(boolean traceBeforeAndAfterRoute);
/**
* To use a custom exchange formatter for formatting the output of the {@link Exchange} in the trace logs.
*/
ExchangeFormatter getExchangeFormatter();
/**
* To use a custom exchange formatter for formatting the output of the {@link Exchange} in the trace logs.
*/
void setExchangeFormatter(ExchangeFormatter exchangeFormatter);
}
| Tracer |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/jsontype/DefaultBaseTypeLimitingValidator.java | {
"start": 719,
"end": 1237
} | class ____
* implementation and override either {@link #validateSubClassName} or
* {@link #validateSubType} to implement use-case specific validation.
*<p>
* Note that when using potentially unsafe base type like {@link java.lang.Object} a custom
* implementation (or subtype with override) is needed. Most commonly subclasses would
* override both {@link #isUnsafeBaseType} and {@link #isSafeSubType}: former to allow
* all (or just more) base types, and latter to add actual validation of subtype.
*/
public | this |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenIT0085TransitiveSystemScopeTest.java | {
"start": 992,
"end": 2266
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that system-scoped dependencies get resolved with system scope
* when they are resolved transitively via another (non-system)
* dependency. Inherited scope should not apply in the case of
* system-scoped dependencies, no matter where they are.
*
* @throws Exception in case of failure
*/
@Test
public void testit0085() throws Exception {
File testDir = extractResources("/it0085");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.deleteArtifacts("org.apache.maven.its.it0085");
verifier.getSystemProperties().setProperty("test.home", testDir.getAbsolutePath());
verifier.filterFile("settings-template.xml", "settings.xml");
verifier.addCliArgument("--settings");
verifier.addCliArgument("settings.xml");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Collection<String> lines = verifier.loadLines("target/test.txt");
assertTrue(lines.contains("system.jar"), lines.toString());
}
}
| MavenIT0085TransitiveSystemScopeTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/records/RecordUpdate3079Test.java | {
"start": 368,
"end": 1196
} | class ____ {
public IdNameRecord value;
protected IdNameWrapper() { }
public IdNameWrapper(IdNameRecord v) { value = v; }
}
private final ObjectMapper MAPPER = newJsonMapper();
// [databind#3079]: also: should be able to Record valued property
@Test
public void testRecordAsPropertyUpdate() throws Exception
{
IdNameRecord origRecord = new IdNameRecord(123, "Bob");
IdNameWrapper orig = new IdNameWrapper(origRecord);
IdNameWrapper delta = new IdNameWrapper(new IdNameRecord(200, "Gary"));
IdNameWrapper result = MAPPER.updateValue(orig, delta);
assertEquals(200, result.value.id());
assertEquals("Gary", result.value.name());
assertSame(orig, result);
assertNotSame(origRecord, result.value);
}
}
| IdNameWrapper |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/comments/TestEntity2.java | {
"start": 287,
"end": 587
} | class ____ {
@Id
private String id;
@Column(name = "val")
private String value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| TestEntity2 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSetTest.java | {
"start": 793,
"end": 1687
} | class ____ {
@Test
public void testLifecycle(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Person person = new Person(1L);
person.getPhones().add(new Phone(1L, "landline", "028-234-9876"));
person.getPhones().add(new Phone(2L, "mobile", "072-122-9876"));
entityManager.persist(person);
});
scope.inTransaction( entityManager -> {
Person person = entityManager.find(Person.class, 1L);
Set<Phone> phones = person.getPhones();
assertEquals(2, phones.size());
phones.remove(phones.iterator().next());
assertEquals(1, phones.size());
});
scope.inTransaction( entityManager -> {
Person person = entityManager.find(Person.class, 1L);
Set<Phone> phones = person.getPhones();
assertEquals(1, phones.size());
});
}
//tag::collections-unidirectional-set-example[]
@Entity(name = "Person")
public static | UnidirectionalSetTest |
java | micronaut-projects__micronaut-core | management/src/main/java/io/micronaut/management/health/indicator/client/ServiceHttpClientHealthIndicator.java | {
"start": 1962,
"end": 3577
} | class ____ implements HealthIndicator {
private final ServiceHttpClientConfiguration configuration;
private final Collection<URI> loadBalancerUrls;
private final Collection<URI> originalUrls;
private final HealthResult.Builder serviceHealthBuilder;
/**
* @param configuration Configuration for the individual service http client.
* @param instanceList Instance List for the individual service http client. Used to obtain available load balancer URLs.
*/
public ServiceHttpClientHealthIndicator(@Parameter ServiceHttpClientConfiguration configuration, @Parameter StaticServiceInstanceList instanceList) {
this.configuration = configuration;
this.loadBalancerUrls = instanceList.getLoadBalancedURIs();
this.originalUrls = configuration.getUrls();
this.serviceHealthBuilder = HealthResult.builder(configuration.getServiceId());
}
@Override
public Publisher<HealthResult> getResult() {
if (!configuration.isHealthCheck()) {
return Publishers.empty();
}
return Publishers.just(determineServiceHealth());
}
private HealthResult determineServiceHealth() {
Map<String, Object> details = new LinkedHashMap<>(2);
details.put("all_urls", originalUrls);
details.put("available_urls", loadBalancerUrls);
if (loadBalancerUrls.isEmpty()) {
return serviceHealthBuilder.status(HealthStatus.DOWN).details(details).build();
}
return serviceHealthBuilder.status(HealthStatus.UP).details(details).build();
}
}
| ServiceHttpClientHealthIndicator |
java | dropwizard__dropwizard | dropwizard-util/src/main/java/io/dropwizard/util/DataSizeUnit.java | {
"start": 334,
"end": 5888
} | enum ____ {
/**
* Bytes (8 bits).
*/
BYTES(8L),
// OSI Decimal Size Units
/**
* Kilobytes (1000 bytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Kilo-">Kilo-</a>
*/
KILOBYTES(8L * 1000L),
/**
* Megabytes (1000 kilobytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Mega-">Mega-</a>
*/
MEGABYTES(8L * 1000L * 1000L),
/**
* Gigabytes (1000 megabytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Giga-">Giga-</a>
*/
GIGABYTES(8L * 1000L * 1000L * 1000L),
/**
* Terabytes (1000 gigabytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Tera-">Tera-</a>
*/
TERABYTES(8L * 1000L * 1000L * 1000L * 1000L),
/**
* Petabytes (1000 terabytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Peta-">Peta-</a>
*/
PETABYTES(8L * 1000L * 1000L * 1000L * 1000L * 1000L),
// IEC Binary Size Units
/**
* Kibibytes (1024 bytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Kibi-">Kibi-</a>
*/
KIBIBYTES(8L * 1024L),
/**
* Mebibytes (1024 kibibytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Mebi-">Mebi-</a>
*/
MEBIBYTES(8L * 1024L * 1024L),
/**
* Gibibytes (1024 mebibytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Gibi-">Gibi-</a>
*/
GIBIBYTES(8L * 1024L * 1024L * 1024L),
/**
* Tebibytes (1024 gibibytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Tebi-">Tebi-</a>
*/
TEBIBYTES(8L * 1024L * 1024L * 1024L * 1024L),
/**
* Pebibytes (1024 tebibytes).
*
* @see <a href="https://en.wikipedia.org/wiki/Pebi-">Pebi-</a>
*/
PEBIBYTES(8L * 1024L * 1024L * 1024L * 1024L * 1024L);
private final long bits;
DataSizeUnit(long bits) {
this.bits = bits;
}
/**
* Converts a size of the given unit into the current unit.
*
* @param size the magnitude of the size
* @param unit the unit of the size
* @return the given size in the current unit.
*/
public long convert(long size, DataSizeUnit unit) {
return (size * unit.bits) / bits;
}
/**
* Converts the given number of the current units into bytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in bytes
*/
public long toBytes(long l) {
return BYTES.convert(l, this);
}
/**
* Converts the given number of the current units into kilobytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in kilobytes
*/
public long toKilobytes(long l) {
return KILOBYTES.convert(l, this);
}
/**
* Converts the given number of the current units into megabytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in megabytes
*/
public long toMegabytes(long l) {
return MEGABYTES.convert(l, this);
}
/**
* Converts the given number of the current units into gigabytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in gigabytes
*/
public long toGigabytes(long l) {
return GIGABYTES.convert(l, this);
}
/**
* Converts the given number of the current units into terabytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in terabytes
*/
public long toTerabytes(long l) {
return TERABYTES.convert(l, this);
}
/**
* Converts the given number of the current units into petabytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in petabytes
*/
public long toPetabytes(long l) {
return PETABYTES.convert(l, this);
}
/**
* Converts the given number of the current units into kibibytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in kibibytes
*/
public long toKibibytes(long l) {
return KIBIBYTES.convert(l, this);
}
/**
* Converts the given number of the current units into mebibytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in mebibytes
*/
public long toMebibytes(long l) {
return MEBIBYTES.convert(l, this);
}
/**
* Converts the given number of the current units into gibibytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in gibibytes
*/
public long toGibibytes(long l) {
return GIBIBYTES.convert(l, this);
}
/**
* Converts the given number of the current units into tebibytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in tebibytes
*/
public long toTebibytes(long l) {
return TEBIBYTES.convert(l, this);
}
/**
* Converts the given number of the current units into pebibytes.
*
* @param l the magnitude of the size in the current unit
* @return {@code l} of the current units in pebibytes
*/
public long toPebibytes(long l) {
return PEBIBYTES.convert(l, this);
}
} | DataSizeUnit |
java | elastic__elasticsearch | modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/direct/RestDeleteDatabaseConfigurationAction.java | {
"start": 1071,
"end": 1870
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(DELETE, "/_ingest/ip_location/database/{id}"), new Route(DELETE, "/_ingest/geoip/database/{id}"));
}
@Override
public String getName() {
return "geoip_delete_database_configuration";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
final var req = new DeleteDatabaseConfigurationAction.Request(
getMasterNodeTimeout(request),
getAckTimeout(request),
request.param("id")
);
return channel -> client.execute(DeleteDatabaseConfigurationAction.INSTANCE, req, new RestToXContentListener<>(channel));
}
}
| RestDeleteDatabaseConfigurationAction |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/pool/ConcurrentTest2.java | {
"start": 844,
"end": 3854
} | class ____ extends TestCase {
private String jdbcUrl;
private String user;
private String password;
private String driverClass;
private int minPoolSize = 1;
private int maxPoolSize = 8;
private int maxActive = 500;
protected void setUp() throws Exception {
// jdbcUrl =
// "jdbc:mysql://a.b.c.d/dragoon_v25masterdb?useUnicode=true&characterEncoding=UTF-8";
// user = "dragoon25";
// password = "dragoon25";
// driverClass = "com.mysql.jdbc.Driver";
jdbcUrl = "jdbc:fake:dragoon_v25masterdb";
user = "dragoon25";
password = "dragoon25";
driverClass = "com.alibaba.druid.mock.MockDriver";
}
public void test_concurrent_2() throws Exception {
final DruidDataSource dataSource = new DruidDataSource();
Class.forName("com.alibaba.druid.mock.MockDriver");
dataSource.setInitialSize(10);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(minPoolSize);
dataSource.setMaxIdle(maxPoolSize);
dataSource.setPoolPreparedStatements(true);
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(jdbcUrl);
dataSource.setPoolPreparedStatements(true);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setMaxWait(1000 * 60 * 1);
final int THREAD_COUNT = 50;
final int LOOP_COUNT = 1000 * 10;
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
final CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {
@Override
public void run() {
dataSource.shrink();
}
});
for (int threadIndex = 0; threadIndex < THREAD_COUNT; ++threadIndex) {
Thread thread = new Thread() {
public void run() {
try {
startLatch.await();
for (int i = 0; i < LOOP_COUNT; ++i) {
Connection conn = dataSource.getConnection();
conn.close();
barrier.await(10, TimeUnit.SECONDS);
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
endLatch.countDown();
}
}
};
thread.start();
}
startLatch.countDown();
endLatch.await();
System.out.println("connectCount : " + dataSource.getConnectCount());
// Assert.assertEquals(THREAD_COUNT * LOOP_COUNT, dataSource.getConnectCount());
// Assert.assertEquals(THREAD_COUNT * LOOP_COUNT, dataSource.getCloseCount());
// Assert.assertEquals(0, dataSource.getConnectErrorCount());
// Assert.assertEquals(0, dataSource.getActiveCount());
}
}
| ConcurrentTest2 |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/ClientImpl.java | {
"start": 26642,
"end": 33443
} | class ____ implements HttpClient {
private final Supplier<HttpClient> supplier;
private volatile HttpClient supplied = null;
LazyHttpClient(Supplier<HttpClient> supplier) {
this.supplier = supplier;
}
private HttpClient getDelegate() {
if (supplied == null) {
supplied = supplier.get();
}
return supplied;
}
@Override
public void request(RequestOptions options,
Handler<AsyncResult<HttpClientRequest>> handler) {
getDelegate().request(options, handler);
}
@Override
public Future<HttpClientRequest> request(RequestOptions options) {
return getDelegate().request(options);
}
@Override
public void request(HttpMethod method, int port, String host, String requestURI,
Handler<AsyncResult<HttpClientRequest>> handler) {
getDelegate().request(method, port, host, requestURI, handler);
}
@Override
public Future<HttpClientRequest> request(HttpMethod method, int port, String host, String requestURI) {
return getDelegate().request(method, port, host, requestURI);
}
@Override
public void request(HttpMethod method, String host, String requestURI,
Handler<AsyncResult<HttpClientRequest>> handler) {
getDelegate().request(method, host, requestURI, handler);
}
@Override
public Future<HttpClientRequest> request(HttpMethod method, String host, String requestURI) {
return getDelegate().request(method, host, requestURI);
}
@Override
public void request(HttpMethod method, String requestURI,
Handler<AsyncResult<HttpClientRequest>> handler) {
getDelegate().request(method, requestURI, handler);
}
@Override
public Future<HttpClientRequest> request(HttpMethod method, String requestURI) {
return getDelegate().request(method, requestURI);
}
@Override
public void webSocket(int port, String host, String requestURI,
Handler<AsyncResult<WebSocket>> handler) {
getDelegate().webSocket(port, host, requestURI, handler);
}
@Override
public Future<WebSocket> webSocket(int port, String host, String requestURI) {
return getDelegate().webSocket(port, host, requestURI);
}
@Override
public void webSocket(String host, String requestURI,
Handler<AsyncResult<WebSocket>> handler) {
getDelegate().webSocket(host, requestURI, handler);
}
@Override
public Future<WebSocket> webSocket(String host, String requestURI) {
return getDelegate().webSocket(host, requestURI);
}
@Override
public void webSocket(String requestURI,
Handler<AsyncResult<WebSocket>> handler) {
getDelegate().webSocket(requestURI, handler);
}
@Override
public Future<WebSocket> webSocket(String requestURI) {
return getDelegate().webSocket(requestURI);
}
@Override
public void webSocket(WebSocketConnectOptions options,
Handler<AsyncResult<WebSocket>> handler) {
getDelegate().webSocket(options, handler);
}
@Override
public Future<WebSocket> webSocket(WebSocketConnectOptions options) {
return getDelegate().webSocket(options);
}
@Override
public void webSocketAbs(String url, MultiMap headers, WebsocketVersion version,
List<String> subProtocols,
Handler<AsyncResult<WebSocket>> handler) {
getDelegate().webSocketAbs(url, headers, version, subProtocols, handler);
}
@Override
public Future<WebSocket> webSocketAbs(String url, MultiMap headers, WebsocketVersion version,
List<String> subProtocols) {
return getDelegate().webSocketAbs(url, headers, version, subProtocols);
}
@Override
public Future<Boolean> updateSSLOptions(SSLOptions options) {
return getDelegate().updateSSLOptions(options);
}
@Override
public void updateSSLOptions(SSLOptions options, Handler<AsyncResult<Boolean>> handler) {
getDelegate().updateSSLOptions(options, handler);
}
@Override
public Future<Boolean> updateSSLOptions(SSLOptions options, boolean force) {
return getDelegate().updateSSLOptions(options, force);
}
@Override
public void updateSSLOptions(SSLOptions options, boolean force, Handler<AsyncResult<Boolean>> handler) {
getDelegate().updateSSLOptions(options, force, handler);
}
@Override
public HttpClient connectionHandler(Handler<HttpConnection> handler) {
return getDelegate().connectionHandler(handler);
}
@Override
public HttpClient redirectHandler(
Function<HttpClientResponse, Future<RequestOptions>> handler) {
return getDelegate().redirectHandler(handler);
}
@Override
public Function<HttpClientResponse, Future<RequestOptions>> redirectHandler() {
return getDelegate().redirectHandler();
}
@Override
public void close(Handler<AsyncResult<Void>> handler) {
if (supplied != null) { // no need to close if we never obtained a reference
getDelegate().close(handler);
}
if (handler != null) {
handler.handle(Future.succeededFuture());
}
}
@Override
public Future<Void> close() {
if (supplied != null) { // no need to close if we never obtained a reference
return getDelegate().close();
}
return Future.succeededFuture();
}
@Override
public boolean isMetricsEnabled() {
return getDelegate().isMetricsEnabled();
}
}
}
}
| LazyHttpClient |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/NativeImageSystemPropertyBuildItem.java | {
"start": 188,
"end": 568
} | class ____ extends MultiBuildItem {
private final String key;
private final String value;
public NativeImageSystemPropertyBuildItem(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
| NativeImageSystemPropertyBuildItem |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/IdentifierNameTest.java | {
"start": 15392,
"end": 15563
} | class ____ {",
"}")
.doTest();
}
@Test
public void enumName() {
helper
.addSourceLines(
"Test.java", //
" | Foo_Bar |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/builder/SQLSelectBuilder.java | {
"start": 727,
"end": 1448
} | interface ____ {
SQLSelectStatement getSQLSelectStatement();
SQLSelectBuilder select(String... column);
SQLSelectBuilder selectWithAlias(String column, String alias);
SQLSelectBuilder from(String table);
SQLSelectBuilder from(String table, String alias);
SQLSelectBuilder orderBy(String... columns);
SQLSelectBuilder groupBy(String expr);
SQLSelectBuilder having(String expr);
SQLSelectBuilder into(String expr);
SQLSelectBuilder limit(int rowCount);
SQLSelectBuilder limit(int rowCount, int offset);
SQLSelectBuilder where(String sql);
SQLSelectBuilder whereAnd(String sql);
SQLSelectBuilder whereOr(String sql);
String toString();
}
| SQLSelectBuilder |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/transformations/TransformationWithLineage.java | {
"start": 1283,
"end": 3081
} | class ____<T> extends PhysicalTransformation<T> {
private LineageVertex lineageVertex;
/**
* Creates a new {@code Transformation} with the given name, output type and parallelism.
*
* @param name The name of the {@code Transformation}, this will be shown in Visualizations and
* the Log
* @param outputType The output type of this {@code Transformation}
* @param parallelism The parallelism of this {@code Transformation}
*/
TransformationWithLineage(String name, TypeInformation<T> outputType, int parallelism) {
super(name, outputType, parallelism);
}
/**
* Creates a new {@code Transformation} with the given name, output type and parallelism.
*
* @param name The name of the {@code Transformation}, this will be shown in Visualizations and
* the Log
* @param outputType The output type of this {@code Transformation}
* @param parallelism The parallelism of this {@code Transformation}
* @param parallelismConfigured If true, the parallelism of the transformation is explicitly set
* and should be respected. Otherwise the parallelism can be changed at runtime.
*/
TransformationWithLineage(
String name,
TypeInformation<T> outputType,
int parallelism,
boolean parallelismConfigured) {
super(name, outputType, parallelism, parallelismConfigured);
}
/** Returns the lineage vertex of this {@code Transformation}. */
public LineageVertex getLineageVertex() {
return lineageVertex;
}
/** Change the lineage vertex of this {@code Transformation}. */
public void setLineageVertex(LineageVertex lineageVertex) {
this.lineageVertex = lineageVertex;
}
}
| TransformationWithLineage |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/BaseTestTemplate.java | {
"start": 1917,
"end": 2143
} | class ____ the same package (
* {@link BigDecimalAssertBaseTest}). To avoid cluttering the main package with hundreds of classes, the concrete tests reside in
* a subpackage ({@link org.assertj.core.api.bigdecimal}). The base | in |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java | {
"start": 3838,
"end": 4607
} | class ____ implements TimeStamped, ITester {
@Override
public void foo() {
}
@Override
public long getTimeStamp() {
return t;
}
}
DelegatingIntroductionInterceptor ii = new DelegatingIntroductionInterceptor(new Tester());
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii));
//assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1);
TimeStamped ts = (TimeStamped) pf.getProxy();
assertThat(ts.getTimeStamp()).isEqualTo(t);
((ITester) ts).foo();
((ITestBean) ts).getAge();
}
@Test
void testAutomaticInterfaceRecognitionInSubclass() throws Exception {
final long t = 1001L;
@SuppressWarnings("serial")
| Tester |
java | dropwizard__dropwizard | dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/MutableValidatorFactory.java | {
"start": 273,
"end": 854
} | class ____ implements ConstraintValidatorFactory {
private ConstraintValidatorFactory validatorFactory = new ConstraintValidatorFactoryImpl();
@Override
public final <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
return validatorFactory.getInstance(key);
}
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
// Nothing to do
}
public void setValidatorFactory(ConstraintValidatorFactory validatorFactory) {
this.validatorFactory = validatorFactory;
}
}
| MutableValidatorFactory |
java | hibernate__hibernate-orm | hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/mariadb/MariaDBTestSupport.java | {
"start": 636,
"end": 1225
} | class ____ extends TestSupport {
@Override
public TestData createTestData(TestDataPurpose purpose) {
return TestData.fromFile( "mariadb/test-mariadb-functions-data-set.xml" );
}
@Override
public NativeSQLTemplates templates() {
return new MySqlNativeSqlTemplates();
}
@Override
public Map<CommonSpatialFunction, String> hqlOverrides() {
return super.hqlOverrides();
}
@Override
public PredicateRegexes predicateRegexes() {
return new PredicateRegexes("st_geomfromtext");
}
@Override
public GeomCodec codec() {
return in -> (Geometry<?>) in;
}
}
| MariaDBTestSupport |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java | {
"start": 67184,
"end": 70937
} | class ____
extends RegisteredRpcConnection<
ResourceManagerId,
ResourceManagerGateway,
JobMasterRegistrationSuccess,
RegistrationResponse.Rejection> {
private final JobID jobID;
private final ResourceID jobManagerResourceID;
private final String jobManagerRpcAddress;
private final JobMasterId jobMasterId;
ResourceManagerConnection(
final Logger log,
final JobID jobID,
final ResourceID jobManagerResourceID,
final String jobManagerRpcAddress,
final JobMasterId jobMasterId,
final String resourceManagerAddress,
final ResourceManagerId resourceManagerId,
final Executor executor) {
super(log, resourceManagerAddress, resourceManagerId, executor);
this.jobID = checkNotNull(jobID);
this.jobManagerResourceID = checkNotNull(jobManagerResourceID);
this.jobManagerRpcAddress = checkNotNull(jobManagerRpcAddress);
this.jobMasterId = checkNotNull(jobMasterId);
}
@Override
protected RetryingRegistration<
ResourceManagerId,
ResourceManagerGateway,
JobMasterRegistrationSuccess,
RegistrationResponse.Rejection>
generateRegistration() {
return new RetryingRegistration<
ResourceManagerId,
ResourceManagerGateway,
JobMasterRegistrationSuccess,
RegistrationResponse.Rejection>(
log,
getRpcService(),
"ResourceManager",
ResourceManagerGateway.class,
getTargetAddress(),
getTargetLeaderId(),
jobMasterConfiguration.getRetryingRegistrationConfiguration()) {
@Override
protected CompletableFuture<RegistrationResponse> invokeRegistration(
ResourceManagerGateway gateway,
ResourceManagerId fencingToken,
long timeoutMillis) {
Duration timeout = Duration.ofMillis(timeoutMillis);
return gateway.registerJobMaster(
jobMasterId,
jobManagerResourceID,
jobManagerRpcAddress,
jobID,
timeout);
}
};
}
@Override
protected void onRegistrationSuccess(final JobMasterRegistrationSuccess success) {
runAsync(
() -> {
// filter out outdated connections
//noinspection ObjectEquality
if (this == resourceManagerConnection) {
establishResourceManagerConnection(success);
}
});
}
@Override
protected void onRegistrationRejection(RegistrationResponse.Rejection rejection) {
handleJobMasterError(
new IllegalStateException(
"The ResourceManager should never reject a JobMaster registration."));
}
@Override
protected void onRegistrationFailure(final Throwable failure) {
handleJobMasterError(failure);
}
}
// ----------------------------------------------------------------------------------------------
private | ResourceManagerConnection |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DirectInvocationOnMockTest.java | {
"start": 3699,
"end": 4191
} | class ____ {
@Mock public Test test;
public void test() {
// BUG: Diagnostic contains:
test.test();
}
}
""")
.doTest();
}
@Test
public void directInvocationOnMockAnnotatedField_mockHasExtraOptions_noFinding() {
helper
.addSourceLines(
"Test.java",
"""
import org.mockito.Answers;
import org.mockito.Mock;
| Test |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/type/classreading/MergedAnnotationMetadataVisitorTests.java | {
"start": 8511,
"end": 8671
} | interface ____ {
String value() default "";
}
@ClassAnnotation(classValue = InputStream.class, classArrayValue = OutputStream.class)
static | NestedAnnotation |
java | elastic__elasticsearch | x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/plugin/EqlAsyncGetStatusAction.java | {
"start": 408,
"end": 711
} | class ____ extends ActionType<QlStatusResponse> {
public static final EqlAsyncGetStatusAction INSTANCE = new EqlAsyncGetStatusAction();
public static final String NAME = "cluster:monitor/eql/async/status";
private EqlAsyncGetStatusAction() {
super(NAME);
}
}
| EqlAsyncGetStatusAction |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/aot/ReflectiveProcessorAotContributionBuilder.java | {
"start": 2961,
"end": 3470
} | class ____ candidate if it uses {@link Reflective} directly or via a
* meta-annotation. Type, fields, constructors, methods and enclosed types
* are inspected.
* @param classes the classes to inspect
*/
public ReflectiveProcessorAotContributionBuilder withClasses(Class<?>[] classes) {
return withClasses(Arrays.asList(classes));
}
/**
* Scan the given {@code packageNames} and their sub-packages for classes
* that uses {@link Reflective}.
* <p>This performs a "deep scan" by loading every | is |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullableTest.java | {
"start": 7597,
"end": 8232
} | class ____ {
static {
new Bystander<@Nullable Void>() {};
}
}
""")
.doTest();
}
@Test
public void negativeTypeArgumentNotVoid() {
aggressiveCompilationHelper
.addSourceLines(
"Nullable.java",
"""
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @ | Test |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-tomcat-multi-connectors/src/main/java/smoketest/tomcat/multiconnector/web/SampleController.java | {
"start": 818,
"end": 921
} | class ____ {
@GetMapping("/hello")
public String helloWorld() {
return "hello";
}
}
| SampleController |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.