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
|
quarkusio__quarkus
|
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/MessageBundleProcessor.java
|
{
"start": 13542,
"end": 13873
}
|
interface ____ extend a message bundle interface: " + localized);
}
} else {
throw new MessageBundleException("@Localized must be declared on an interface: " + localized);
}
}
}
// Generate implementations
// name -> impl
|
must
|
java
|
elastic__elasticsearch
|
x-pack/plugin/text-structure/src/main/java/org/elasticsearch/xpack/textstructure/structurefinder/TimeoutChecker.java
|
{
"start": 5092,
"end": 5725
}
|
class ____ more sense in the context of the find structure API
check(where);
}
}
private synchronized void setTimeoutExceeded() {
// Even though close() cancels the timer, it's possible that it can already be running when close()
// is called, so this check prevents the effects of this method occurring after close() returns
if (isClosed) {
return;
}
timeoutExceeded = true;
timeoutCheckerWatchdog.interruptLongRunningThreadIfRegistered(checkedThread);
}
/**
* An implementation of the type of watchdog used by the {@link Grok}
|
makes
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java
|
{
"start": 17602,
"end": 19797
}
|
class ____ {
// CHECKSTYLE DISABLE VisibilityModifier FOR 10 LINES
public String originMethodName;
public String methodName;
public String inputType;
public String outputType;
public boolean deprecated;
public boolean isManyInput;
public boolean isManyOutput;
public String reactiveCallsMethodName;
public String grpcCallsMethodName;
public int methodNumber;
public String javaDoc;
/**
* The HTTP request method
*/
public String httpMethod;
/**
* The HTTP request path
*/
public String path;
/**
* The message field that the HTTP request body mapping to
*/
public String body;
/**
* Whether the method has HTTP mapping
*/
public boolean hasMapping;
/**
* Whether the request body parameter need @GRequest annotation
*/
public boolean needRequestAnnotation;
// This method mimics the upper-casing method ogf gRPC to ensure compatibility
// See https://github.com/grpc/grpc-java/blob/v1.8.0/compiler/src/java_plugin/cpp/java_generator.cpp#L58
public String methodNameUpperUnderscore() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < methodName.length(); i++) {
char c = methodName.charAt(i);
s.append(Character.toUpperCase(c));
if ((i < methodName.length() - 1)
&& Character.isLowerCase(c)
&& Character.isUpperCase(methodName.charAt(i + 1))) {
s.append('_');
}
}
return s.toString();
}
public String methodNamePascalCase() {
String mn = methodName.replace("_", "");
return String.valueOf(Character.toUpperCase(mn.charAt(0))) + mn.substring(1);
}
public String methodNameCamelCase() {
String mn = methodName.replace("_", "");
return String.valueOf(Character.toLowerCase(mn.charAt(0))) + mn.substring(1);
}
}
}
|
MethodContext
|
java
|
micronaut-projects__micronaut-core
|
inject-java-test/src/test/groovy/io/micronaut/inject/visitor/beans/Message.java
|
{
"start": 229,
"end": 338
}
|
class ____ {
}
private Builder<BuilderT>.BuilderParentImpl meAsParent;
}
}
|
BuilderParentImpl
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java
|
{
"start": 3794,
"end": 21142
}
|
class ____ {
//TODO
private static int DEFAULT_RESOLVER_COUNT;
private static int DEFAULT_HANDLER_COUNT;
private ExceptionHandlerExceptionResolver resolver;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@BeforeAll
static void setupOnce() {
ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
resolver.afterPropertiesSet();
DEFAULT_RESOLVER_COUNT = resolver.getArgumentResolvers().getResolvers().size();
DEFAULT_HANDLER_COUNT = resolver.getReturnValueHandlers().getHandlers().size();
}
@BeforeEach
void setup() throws Exception {
this.resolver = new ExceptionHandlerExceptionResolver();
this.resolver.setWarnLogCategory(this.resolver.getClass().getName());
this.request = new MockHttpServletRequest("GET", "/");
this.request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
this.response = new MockHttpServletResponse();
}
@Test
void nullHandler() {
Object handler = null;
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handler, null);
assertThat(mav).as("Exception can be resolved only if there is a HandlerMethod").isNull();
}
@Test
void setCustomArgumentResolvers() {
HandlerMethodArgumentResolver argumentResolver = new ServletRequestMethodArgumentResolver();
this.resolver.setCustomArgumentResolvers(Collections.singletonList(argumentResolver));
this.resolver.afterPropertiesSet();
assertThat(this.resolver.getArgumentResolvers().getResolvers()).contains(argumentResolver);
assertMethodProcessorCount(DEFAULT_RESOLVER_COUNT + 1, DEFAULT_HANDLER_COUNT);
}
@Test
void setArgumentResolvers() {
HandlerMethodArgumentResolver argumentResolver = new ServletRequestMethodArgumentResolver();
this.resolver.setArgumentResolvers(Collections.singletonList(argumentResolver));
this.resolver.afterPropertiesSet();
assertMethodProcessorCount(1, DEFAULT_HANDLER_COUNT);
}
@Test
void setCustomReturnValueHandlers() {
HandlerMethodReturnValueHandler handler = new ViewNameMethodReturnValueHandler();
this.resolver.setCustomReturnValueHandlers(Collections.singletonList(handler));
this.resolver.afterPropertiesSet();
assertThat(this.resolver.getReturnValueHandlers().getHandlers()).contains(handler);
assertMethodProcessorCount(DEFAULT_RESOLVER_COUNT, DEFAULT_HANDLER_COUNT + 1);
}
@Test
void setResponseBodyAdvice() {
this.resolver.setResponseBodyAdvice(Collections.singletonList(new JsonViewResponseBodyAdvice()));
assertThat(this.resolver).extracting("responseBodyAdvice").asInstanceOf(LIST).hasSize(1);
this.resolver.setResponseBodyAdvice(Collections.singletonList(new CustomResponseBodyAdvice()));
assertThat(this.resolver).extracting("responseBodyAdvice").asInstanceOf(LIST).hasSize(2);
}
@Test
void setReturnValueHandlers() {
HandlerMethodReturnValueHandler handler = new ModelMethodProcessor();
this.resolver.setReturnValueHandlers(Collections.singletonList(handler));
this.resolver.afterPropertiesSet();
assertMethodProcessorCount(DEFAULT_RESOLVER_COUNT, 1);
}
@Test
void resolveNoExceptionHandlerForException() throws NoSuchMethodException {
Exception npe = new NullPointerException();
HandlerMethod handlerMethod = new HandlerMethod(new IoExceptionController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, npe);
assertThat(mav).as("NPE should not have been handled").isNull();
}
@Test
void resolveExceptionModelAndView() throws NoSuchMethodException {
IllegalArgumentException ex = new IllegalArgumentException("Bad argument");
HandlerMethod handlerMethod = new HandlerMethod(new ModelAndViewController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertThat(mav).isNotNull();
assertThat(mav.isEmpty()).isFalse();
assertThat(mav.getViewName()).isEqualTo("errorView");
assertThat(mav.getModel().get("detail")).isEqualTo("Bad argument");
}
@Test
void resolveExceptionResponseBody() throws UnsupportedEncodingException, NoSuchMethodException {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "IllegalArgumentException");
}
@Test // gh-26317
void resolveExceptionResponseBodyMatchingCauseLevel2() throws UnsupportedEncodingException, NoSuchMethodException {
Exception ex = new Exception(new Exception(new IllegalArgumentException()));
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "IllegalArgumentException");
}
@Test
void resolveExceptionResponseWriter() throws Exception {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseWriterController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "IllegalArgumentException");
}
@Test // SPR-13546
void resolveExceptionModelAtArgument() throws Exception {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new ModelArgumentController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertThat(mav).isNotNull();
assertThat(mav.getModelMap()).hasSize(1);
assertThat(mav.getModelMap().get("exceptionClassName")).isEqualTo("IllegalArgumentException");
}
@Test // SPR-14651
void resolveRedirectAttributesAtArgument() throws Exception {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new RedirectAttributesController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertThat(mav).isNotNull();
assertThat(mav.getViewName()).isEqualTo("redirect:/");
FlashMap flashMap = (FlashMap) this.request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE);
assertThat((Object) flashMap).as("output FlashMap should exist").isNotNull();
assertThat(flashMap.get("exceptionClassName")).isEqualTo("IllegalArgumentException");
}
@Test
void resolveExceptionGlobalHandler() throws Exception {
loadConfiguration(MyConfig.class);
IllegalAccessException ex = new IllegalAccessException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "AnotherTestExceptionResolver: IllegalAccessException");
}
@Test
void resolveExceptionGlobalHandlerForHandlerFunction() throws Exception {
loadConfiguration(MyConfig.class);
IllegalAccessException ex = new IllegalAccessException();
HandlerFunction<ServerResponse> handlerFunction = req -> {
throw new IllegalAccessException();
};
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerFunction, ex);
assertExceptionHandledAsBody(mav, "AnotherTestExceptionResolver: IllegalAccessException");
}
@Test
void resolveExceptionGlobalHandlerOrdered() throws Exception {
loadConfiguration(MyConfig.class);
IllegalStateException ex = new IllegalStateException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "TestExceptionResolver: IllegalStateException");
}
@Test // gh-26317
void resolveExceptionGlobalHandlerOrderedMatchingCauseLevel2() throws Exception {
loadConfiguration(MyConfig.class);
Exception ex = new Exception(new Exception(new IllegalStateException()));
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "TestExceptionResolver: IllegalStateException");
}
@Test // SPR-12605
void resolveExceptionWithHandlerMethodArg() throws Exception {
loadConfiguration(MyConfig.class);
ArrayIndexOutOfBoundsException ex = new ArrayIndexOutOfBoundsException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "HandlerMethod: handle");
}
@Test
void resolveExceptionWithAssertionError() throws Exception {
loadConfiguration(MyConfig.class);
AssertionError err = new AssertionError("argh");
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod,
new ServletException("Handler dispatch failed", err));
assertExceptionHandledAsBody(mav, err.toString());
}
@Test
void resolveExceptionWithAssertionErrorAsRootCause() throws Exception {
loadConfiguration(MyConfig.class);
AssertionError rootCause = new AssertionError("argh");
FatalBeanException cause = new FatalBeanException("wrapped", rootCause);
Exception ex = new Exception(cause); // gh-26317
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, rootCause.toString());
}
@Test //gh-27156
void resolveExceptionWithReasonResolvedByMessageSource() throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
StaticApplicationContext context = new StaticApplicationContext(ctx);
Locale locale = Locale.ENGLISH;
context.addMessage("gateway.timeout", locale, "Gateway Timeout");
context.refresh();
LocaleContextHolder.setLocale(locale);
this.resolver.setApplicationContext(context);
this.resolver.afterPropertiesSet();
SocketTimeoutException ex = new SocketTimeoutException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "");
assertThat(this.response.getStatus()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT.value());
assertThat(this.response.getErrorMessage()).isEqualTo("Gateway Timeout");
}
@Test
void resolveExceptionControllerAdviceHandler() throws Exception {
loadConfiguration(MyControllerAdviceConfig.class);
IllegalStateException ex = new IllegalStateException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "BasePackageTestExceptionResolver: IllegalStateException");
}
@Test // gh-26317
void resolveExceptionControllerAdviceHandlerMatchingCauseLevel2() throws Exception {
loadConfiguration(MyControllerAdviceConfig.class);
Exception ex = new Exception(new IllegalStateException());
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "BasePackageTestExceptionResolver: IllegalStateException");
}
@Test
void resolveExceptionControllerAdviceNoHandler() throws Exception {
loadConfiguration(MyControllerAdviceConfig.class);
IllegalStateException ex = new IllegalStateException();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, null, ex);
assertExceptionHandledAsBody(mav, "DefaultTestExceptionResolver: IllegalStateException");
}
@Test // SPR-16496
void resolveExceptionControllerAdviceAgainstProxy() throws Exception {
loadConfiguration(MyControllerAdviceConfig.class);
IllegalStateException ex = new IllegalStateException();
HandlerMethod handlerMethod = new HandlerMethod(new ProxyFactory(new ResponseBodyController()).getProxy(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "BasePackageTestExceptionResolver: IllegalStateException");
}
@Test // gh-22619
void resolveExceptionViaMappedHandler() throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class);
this.resolver.setMappedHandlerClasses(HttpRequestHandler.class);
this.resolver.setApplicationContext(ctx);
this.resolver.afterPropertiesSet();
IllegalStateException ex = new IllegalStateException();
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handler, ex);
assertExceptionHandledAsBody(mav, "DefaultTestExceptionResolver: IllegalStateException");
}
@Test // gh-26772
void resolveExceptionViaMappedHandlerPredicate() throws Exception {
Object handler = new Object();
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class);
this.resolver.setMappedHandlerPredicate(h -> h == handler);
this.resolver.setApplicationContext(ctx);
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(
this.request, this.response, handler, new IllegalStateException());
assertExceptionHandledAsBody(mav, "DefaultTestExceptionResolver: IllegalStateException");
}
@Test
void resolveExceptionAsyncRequestNotUsable() throws Exception {
HttpServletResponse response = mock();
given(response.getOutputStream()).willThrow(new AsyncRequestNotUsableException("Simulated I/O failure"));
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
this.resolver.afterPropertiesSet();
ModelAndView mav = this.resolver.resolveException(this.request, response, handlerMethod, ex);
assertThat(mav).isNotNull();
assertThat(mav.isEmpty()).isTrue();
}
@Test
void resolveExceptionJsonMediaType() throws UnsupportedEncodingException, NoSuchMethodException {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new MediaTypeController(), "handle");
this.resolver.afterPropertiesSet();
this.request.addHeader("Accept", "application/json");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertExceptionHandledAsBody(mav, "jsonBody");
}
@Test
void resolveExceptionHtmlMediaType() throws NoSuchMethodException {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new MediaTypeController(), "handle");
this.resolver.afterPropertiesSet();
this.request.addHeader("Accept", "text/html");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertThat(mav).isNotNull();
assertThat(mav.getViewName()).isEqualTo("htmlView");
}
@Test
void resolveExceptionDefaultMediaType() throws NoSuchMethodException {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new MediaTypeController(), "handle");
this.resolver.afterPropertiesSet();
this.request.addHeader("Accept", "*/*");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertThat(mav).isNotNull();
assertThat(mav.getViewName()).isEqualTo("htmlView");
}
private void assertMethodProcessorCount(int resolverCount, int handlerCount) {
assertThat(this.resolver.getArgumentResolvers().getResolvers()).hasSize(resolverCount);
assertThat(this.resolver.getReturnValueHandlers().getHandlers()).hasSize(handlerCount);
}
private void assertExceptionHandledAsBody(ModelAndView mav, String expectedBody) throws UnsupportedEncodingException {
assertThat(mav).as("Exception was not handled").isNotNull();
assertThat(mav.isEmpty()).isTrue();
assertThat(this.response.getContentAsString()).isEqualTo(expectedBody);
}
private void loadConfiguration(Class<?> configClass) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(configClass);
this.resolver.setApplicationContext(ctx);
this.resolver.afterPropertiesSet();
}
@Controller
static
|
ExceptionHandlerExceptionResolverTests
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java
|
{
"start": 9677,
"end": 9948
}
|
class ____ implements ConfigDataLoader<TestConfigDataResource> {
@Override
public ConfigData load(ConfigDataLoaderContext context, TestConfigDataResource location) throws IOException {
return createConfigData(this, location);
}
}
static
|
SpecificConfigDataLoader
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/PojoComparator.java
|
{
"start": 1530,
"end": 12616
}
|
class ____<T> extends CompositeTypeComparator<T>
implements java.io.Serializable {
private static final long serialVersionUID = 1L;
// Reflection fields for the comp fields
private transient Field[] keyFields;
private final TypeComparator<Object>[] comparators;
private final int[] normalizedKeyLengths;
private final int numLeadingNormalizableKeys;
private final int normalizableKeyPrefixLen;
private final boolean invertNormKey;
private TypeSerializer<T> serializer;
private final Class<T> type;
@SuppressWarnings("unchecked")
public PojoComparator(
Field[] keyFields,
TypeComparator<?>[] comparators,
TypeSerializer<T> serializer,
Class<T> type) {
this.keyFields = keyFields;
this.comparators = (TypeComparator<Object>[]) comparators;
this.type = type;
this.serializer = serializer;
// set up auxiliary fields for normalized key support
this.normalizedKeyLengths = new int[keyFields.length];
int nKeys = 0;
int nKeyLen = 0;
boolean inverted = false;
for (Field keyField : keyFields) {
keyField.setAccessible(true);
}
for (int i = 0; i < this.comparators.length; i++) {
TypeComparator<?> k = this.comparators[i];
if (k == null) {
throw new IllegalArgumentException("One of the passed comparators is null");
}
if (keyFields[i] == null) {
throw new IllegalArgumentException("One of the passed reflection fields is null");
}
// as long as the leading keys support normalized keys, we can build up the composite
// key
if (k.supportsNormalizedKey()) {
if (i == 0) {
// the first comparator decides whether we need to invert the key direction
inverted = k.invertNormalizedKey();
} else if (k.invertNormalizedKey() != inverted) {
// if a successor does not agree on the inversion direction, it cannot be part
// of the normalized key
break;
}
nKeys++;
final int len = k.getNormalizeKeyLen();
if (len < 0) {
throw new RuntimeException(
"Comparator "
+ k.getClass().getName()
+ " specifies an invalid length for the normalized key: "
+ len);
}
this.normalizedKeyLengths[i] = len;
nKeyLen += this.normalizedKeyLengths[i];
if (nKeyLen < 0) {
// overflow, which means we are out of budget for normalized key space anyways
nKeyLen = Integer.MAX_VALUE;
break;
}
} else {
break;
}
}
this.numLeadingNormalizableKeys = nKeys;
this.normalizableKeyPrefixLen = nKeyLen;
this.invertNormKey = inverted;
}
@SuppressWarnings("unchecked")
private PojoComparator(PojoComparator<T> toClone) {
this.keyFields = toClone.keyFields;
this.comparators = new TypeComparator[toClone.comparators.length];
for (int i = 0; i < toClone.comparators.length; i++) {
this.comparators[i] = toClone.comparators[i].duplicate();
}
this.normalizedKeyLengths = toClone.normalizedKeyLengths;
this.numLeadingNormalizableKeys = toClone.numLeadingNormalizableKeys;
this.normalizableKeyPrefixLen = toClone.normalizableKeyPrefixLen;
this.invertNormKey = toClone.invertNormKey;
this.type = toClone.type;
try {
this.serializer =
(TypeSerializer<T>)
InstantiationUtil.deserializeObject(
InstantiationUtil.serializeObject(toClone.serializer),
Thread.currentThread().getContextClassLoader());
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("Cannot copy serializer", e);
}
}
private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFoundException {
out.defaultWriteObject();
out.writeInt(keyFields.length);
for (Field field : keyFields) {
FieldSerializer.serializeField(field, out);
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
int numKeyFields = in.readInt();
keyFields = new Field[numKeyFields];
for (int i = 0; i < numKeyFields; i++) {
keyFields[i] = FieldSerializer.deserializeField(in);
}
}
public Field[] getKeyFields() {
return this.keyFields;
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void getFlatComparator(List<TypeComparator> flatComparators) {
for (int i = 0; i < comparators.length; i++) {
if (comparators[i] instanceof CompositeTypeComparator) {
((CompositeTypeComparator) comparators[i]).getFlatComparator(flatComparators);
} else {
flatComparators.add(comparators[i]);
}
}
}
/** This method is handling the IllegalAccess exceptions of Field.get() */
public final Object accessField(Field field, Object object) {
try {
object = field.get(object);
} catch (NullPointerException npex) {
throw new NullKeyFieldException(
"Unable to access field " + field + " on object " + object);
} catch (IllegalAccessException iaex) {
throw new RuntimeException(
"This should not happen since we call setAccesssible(true) in the ctor."
+ " fields: "
+ field
+ " obj: "
+ object);
}
return object;
}
@Override
public int hash(T value) {
int i = 0;
int code = 0;
for (; i < this.keyFields.length; i++) {
code *= TupleComparatorBase.HASH_SALT[i & 0x1F];
try {
code += this.comparators[i].hash(accessField(keyFields[i], value));
} catch (NullPointerException npe) {
throw new RuntimeException(
"A NullPointerException occurred while accessing a key field in a POJO. "
+ "Most likely, the value grouped/joined on is null. Field name: "
+ keyFields[i].getName(),
npe);
}
}
return code;
}
@Override
public void setReference(T toCompare) {
int i = 0;
for (; i < this.keyFields.length; i++) {
this.comparators[i].setReference(accessField(keyFields[i], toCompare));
}
}
@Override
public boolean equalToReference(T candidate) {
int i = 0;
for (; i < this.keyFields.length; i++) {
if (!this.comparators[i].equalToReference(accessField(keyFields[i], candidate))) {
return false;
}
}
return true;
}
@Override
public int compareToReference(TypeComparator<T> referencedComparator) {
PojoComparator<T> other = (PojoComparator<T>) referencedComparator;
int i = 0;
try {
for (; i < this.keyFields.length; i++) {
int cmp = this.comparators[i].compareToReference(other.comparators[i]);
if (cmp != 0) {
return cmp;
}
}
return 0;
} catch (NullPointerException npex) {
throw new NullKeyFieldException(this.keyFields[i].toString());
}
}
@Override
public int compare(T first, T second) {
int i = 0;
for (; i < keyFields.length; i++) {
int cmp =
comparators[i].compare(
accessField(keyFields[i], first), accessField(keyFields[i], second));
if (cmp != 0) {
return cmp;
}
}
return 0;
}
@Override
public int compareSerialized(DataInputView firstSource, DataInputView secondSource)
throws IOException {
T first = this.serializer.createInstance();
T second = this.serializer.createInstance();
first = this.serializer.deserialize(first, firstSource);
second = this.serializer.deserialize(second, secondSource);
return this.compare(first, second);
}
@Override
public boolean supportsNormalizedKey() {
return this.numLeadingNormalizableKeys > 0;
}
@Override
public int getNormalizeKeyLen() {
return this.normalizableKeyPrefixLen;
}
@Override
public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
return this.numLeadingNormalizableKeys < this.keyFields.length
|| this.normalizableKeyPrefixLen == Integer.MAX_VALUE
|| this.normalizableKeyPrefixLen > keyBytes;
}
@Override
public void putNormalizedKey(T value, MemorySegment target, int offset, int numBytes) {
int i = 0;
for (; i < this.numLeadingNormalizableKeys && numBytes > 0; i++) {
int len = this.normalizedKeyLengths[i];
len = numBytes >= len ? len : numBytes;
this.comparators[i].putNormalizedKey(
accessField(keyFields[i], value), target, offset, len);
numBytes -= len;
offset += len;
}
}
@Override
public boolean invertNormalizedKey() {
return this.invertNormKey;
}
@Override
public boolean supportsSerializationWithKeyNormalization() {
return false;
}
@Override
public void writeWithKeyNormalization(T record, DataOutputView target) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public T readWithKeyDenormalization(T reuse, DataInputView source) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public PojoComparator<T> duplicate() {
return new PojoComparator<T>(this);
}
@Override
public int extractKeys(Object record, Object[] target, int index) {
int localIndex = index;
for (int i = 0; i < comparators.length; i++) {
localIndex +=
comparators[i].extractKeys(
accessField(keyFields[i], record), target, localIndex);
}
return localIndex - index;
}
// --------------------------------------------------------------------------------------------
}
|
PojoComparator
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-proxyexchange-webmvc/src/test/java/org/springframework/cloud/gateway/mvc/config/ProxyExchangeArgumentResolverTest.java
|
{
"start": 2264,
"end": 3004
}
|
class ____ {
@Autowired
private TestRestTemplate rest;
@Autowired
private ProxyExchangeArgumentResolverTestApplication application;
@LocalServerPort
private int port;
@BeforeEach
public void setUp() throws Exception {
application.setHome(new URI("http://localhost:" + port));
rest.getRestTemplate().setRequestFactory(new SimpleClientHttpRequestFactory());
}
@Test
public void shouldProxyRequestWhenProxyExchangeArgumentResolverIsNotConfigured() {
final ResponseEntity<String> response = rest.getForEntity("/proxy", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).contains("Hello World");
}
@SpringBootApplication
static
|
ProxyExchangeArgumentResolverTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestServletFilter.java
|
{
"start": 1749,
"end": 2457
}
|
class ____ implements Filter {
private FilterConfig filterConfig = null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void destroy() {
this.filterConfig = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (filterConfig == null)
return;
uri = ((HttpServletRequest)request).getRequestURI();
LOG.info("filtering " + uri);
chain.doFilter(request, response);
}
/** Configuration for the filter */
static public
|
SimpleFilter
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/event/spi/PersistContext.java
|
{
"start": 644,
"end": 883
}
|
class ____ extends IdentityHashMap<Object,Object>
implements PersistContext {
Impl() {
super(10);
}
@Override
public boolean add(Object entity) {
return put(entity,entity)==null;
}
}
return new Impl();
}
}
|
Impl
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperatorV2.java
|
{
"start": 4284,
"end": 4429
}
|
class ____<OUT>
implements StreamOperator<OUT>, CheckpointedStreamOperator {
/** The logger used by the operator
|
AbstractStreamOperatorV2
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleUtils.java
|
{
"start": 6802,
"end": 12316
}
|
class ____ {
StringBuilder builder = new StringBuilder();
public CodeWriter declStmt(String varType, String varName, String value) {
return stmt(varType + " " + varName + " = " + value);
}
public CodeWriter declStmt(Class<?> clazz, String varName, String value) {
return declStmt(className(clazz), varName, value);
}
public CodeWriter declPrimitiveStmt(LogicalType logicalType, String varName, String value) {
return declStmt(primitiveTypeTermForType(logicalType), varName, value);
}
public CodeWriter declPrimitiveStmt(LogicalType logicalType, String varName) {
return declStmt(
primitiveTypeTermForType(logicalType),
varName,
primitiveDefaultValue(logicalType));
}
public CodeWriter declStmt(String varType, String varName) {
return stmt(varType + " " + varName);
}
public CodeWriter declStmt(Class<?> clazz, String varName) {
return declStmt(className(clazz), varName);
}
public CodeWriter assignStmt(String varName, String value) {
return stmt(varName + " = " + value);
}
public CodeWriter assignPlusStmt(String varName, String value) {
return stmt(varName + " += " + value);
}
public CodeWriter assignArrayStmt(String varName, String index, String value) {
return stmt(varName + "[" + index + "] = " + value);
}
public CodeWriter stmt(String stmt) {
builder.append(stmt).append(';').append('\n');
return this;
}
public CodeWriter forStmt(
String upperBound,
BiConsumer<String, CodeWriter> bodyWriterConsumer,
CodeGeneratorContext codeGeneratorContext) {
final String indexTerm = newName(codeGeneratorContext, "i");
final CodeWriter innerWriter = new CodeWriter();
builder.append("for (int ")
.append(indexTerm)
.append(" = 0; ")
.append(indexTerm)
.append(" < ")
.append(upperBound)
.append("; ")
.append(indexTerm)
.append("++) {\n");
bodyWriterConsumer.accept(indexTerm, innerWriter);
builder.append(innerWriter).append("}\n");
return this;
}
public CodeWriter breakStmt() {
builder.append("break;\n");
return this;
}
public CodeWriter ifStmt(String condition, Consumer<CodeWriter> bodyWriterConsumer) {
final CodeWriter innerWriter = new CodeWriter();
builder.append("if (").append(condition).append(") {\n");
bodyWriterConsumer.accept(innerWriter);
builder.append(innerWriter).append("}\n");
return this;
}
public CodeWriter ifStmt(
String condition,
Consumer<CodeWriter> thenWriterConsumer,
Consumer<CodeWriter> elseWriterConsumer) {
final CodeWriter thenWriter = new CodeWriter();
final CodeWriter elseWriter = new CodeWriter();
builder.append("if (").append(condition).append(") {\n");
thenWriterConsumer.accept(thenWriter);
builder.append(thenWriter).append("} else {\n");
elseWriterConsumer.accept(elseWriter);
builder.append(elseWriter).append("}\n");
return this;
}
public CodeWriter tryCatchStmt(
Consumer<CodeWriter> bodyWriterConsumer,
BiConsumer<String, CodeWriter> catchConsumer,
CodeGeneratorContext codeGeneratorContext) {
return tryCatchStmt(
bodyWriterConsumer, Throwable.class, catchConsumer, codeGeneratorContext);
}
public CodeWriter tryCatchStmt(
Consumer<CodeWriter> bodyWriterConsumer,
Class<? extends Throwable> catchClass,
BiConsumer<String, CodeWriter> catchConsumer,
CodeGeneratorContext codeGeneratorContext) {
final String exceptionTerm = newName(codeGeneratorContext, "e");
final CodeWriter bodyWriter = new CodeWriter();
final CodeWriter catchWriter = new CodeWriter();
builder.append("try {\n");
bodyWriterConsumer.accept(bodyWriter);
builder.append(bodyWriter)
.append("} catch (")
.append(className(catchClass))
.append(" ")
.append(exceptionTerm)
.append(") {\n");
catchConsumer.accept(exceptionTerm, catchWriter);
builder.append(catchWriter).append("}\n");
return this;
}
public CodeWriter append(CastCodeBlock codeBlock) {
builder.append(codeBlock.getCode());
return this;
}
public CodeWriter throwStmt(String expression) {
builder.append("throw ").append(expression).append(";");
return this;
}
public CodeWriter appendBlock(String codeBlock) {
builder.append(codeBlock);
return this;
}
@Override
public String toString() {
return builder.toString();
}
}
}
|
CodeWriter
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/synonyms/GetSynonymRuleAction.java
|
{
"start": 1138,
"end": 1458
}
|
class ____ extends ActionType<GetSynonymRuleAction.Response> {
public static final GetSynonymRuleAction INSTANCE = new GetSynonymRuleAction();
public static final String NAME = "cluster:admin/synonym_rules/get";
public GetSynonymRuleAction() {
super(NAME);
}
public static
|
GetSynonymRuleAction
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/aggregations/metrics/SpatialBounds.java
|
{
"start": 746,
"end": 1002
}
|
interface ____<T extends SpatialPoint> extends Aggregation {
/**
* Get the top-left location of the bounding box.
*/
T topLeft();
/**
* Get the bottom-right location of the bounding box.
*/
T bottomRight();
}
|
SpatialBounds
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/AbstractSlotSharingStrategyTest.java
|
{
"start": 5302,
"end": 6170
}
|
class ____ {
final JobVertex jobVertex = new JobVertex(null, new JobVertexID());
@Nonnull SlotSharingGroup slotSharingGroup;
@Nullable CoLocationGroup coLocationGroup;
int parallelism;
public TestingJobVertexInfo(
int parallelism,
@Nonnull SlotSharingGroup slotSharingGroup,
@Nullable CoLocationGroup coLocationGroup) {
Preconditions.checkArgument(parallelism > 0);
this.parallelism = parallelism;
this.slotSharingGroup = slotSharingGroup;
this.coLocationGroup = coLocationGroup;
this.slotSharingGroup.addVertexToGroup(jobVertex.getID());
if (this.coLocationGroup != null) {
((CoLocationGroupImpl) this.coLocationGroup).addVertex(jobVertex);
}
}
}
}
|
TestingJobVertexInfo
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/BindsMethodValidationTest.java
|
{
"start": 1481,
"end": 2267
}
|
class ____ {
@Parameters
public static ImmutableList<Object[]> data() {
return ImmutableList.copyOf(new Object[][] {{Module.class}, {ProducerModule.class}});
}
private final String moduleAnnotation;
private final String moduleDeclaration;
public BindsMethodValidationTest(Class<? extends Annotation> moduleAnnotation) {
this.moduleAnnotation = "@" + moduleAnnotation.getCanonicalName();
moduleDeclaration = this.moduleAnnotation + " abstract class %s { %s }";
}
@Test
public void noExtensionForBinds() {
Source module =
CompilerTests.kotlinSource(
"test.TestModule.kt",
"package test",
"",
"import dagger.Binds",
"",
moduleAnnotation,
"
|
BindsMethodValidationTest
|
java
|
processing__processing4
|
app/src/processing/app/RunnerListener.java
|
{
"start": 909,
"end": 1231
}
|
interface ____ {
public void statusError(String message);
public void statusError(Exception exception);
public void statusNotice(String message);
//
public void startIndeterminate();
public void stopIndeterminate();
//
public void statusHalt();
public boolean isHalted();
}
|
RunnerListener
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/refaster/UReturn.java
|
{
"start": 1054,
"end": 1835
}
|
class ____ extends USimpleStatement implements ReturnTree {
public static UReturn create(UExpression expression) {
return new AutoValue_UReturn(expression);
}
@Override
public abstract @Nullable UExpression getExpression();
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitReturn(this, data);
}
@Override
public Kind getKind() {
return Kind.RETURN;
}
@Override
public JCReturn inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Return(getExpression().inline(inliner));
}
@Override
public @Nullable Choice<Unifier> visitReturn(ReturnTree ret, @Nullable Unifier unifier) {
return unifyNullable(unifier, getExpression(), ret.getExpression());
}
}
|
UReturn
|
java
|
apache__kafka
|
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/distributed/WorkerGroupMember.java
|
{
"start": 3002,
"end": 11234
}
|
class ____ {
private static final String JMX_PREFIX = "kafka.connect";
private final Logger log;
private final String clientId;
private final ConsumerNetworkClient client;
private final Metrics metrics;
private final WorkerCoordinator coordinator;
private boolean stopped = false;
public WorkerGroupMember(DistributedConfig config,
String restUrl,
ConfigBackingStore configStorage,
WorkerRebalanceListener listener,
Time time,
String clientId,
LogContext logContext) {
try {
this.clientId = clientId;
this.log = logContext.logger(WorkerGroupMember.class);
Map<String, String> metricsTags = new LinkedHashMap<>();
metricsTags.put("client-id", clientId);
MetricConfig metricConfig = new MetricConfig().samples(config.getInt(CommonClientConfigs.METRICS_NUM_SAMPLES_CONFIG))
.timeWindow(config.getLong(CommonClientConfigs.METRICS_SAMPLE_WINDOW_MS_CONFIG), TimeUnit.MILLISECONDS)
.tags(metricsTags);
List<MetricsReporter> reporters = CommonClientConfigs.metricsReporters(clientId, config);
Map<String, Object> contextLabels = new HashMap<>(config.originalsWithPrefix(CommonClientConfigs.METRICS_CONTEXT_PREFIX));
contextLabels.put(WorkerConfig.CONNECT_KAFKA_CLUSTER_ID, config.kafkaClusterId());
contextLabels.put(WorkerConfig.CONNECT_GROUP_ID, config.getString(DistributedConfig.GROUP_ID_CONFIG));
MetricsContext metricsContext = new KafkaMetricsContext(JMX_PREFIX, contextLabels);
this.metrics = new Metrics(metricConfig, reporters, time, metricsContext);
long retryBackoffMs = config.getLong(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG);
long retryBackoffMaxMs = config.getLong(CommonClientConfigs.RETRY_BACKOFF_MAX_MS_CONFIG);
Metadata metadata = new Metadata(retryBackoffMs, retryBackoffMaxMs, config.getLong(CommonClientConfigs.METADATA_MAX_AGE_CONFIG),
logContext, new ClusterResourceListeners());
List<InetSocketAddress> addresses = ClientUtils.parseAndValidateAddresses(
config.getList(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG),
config.getString(CommonClientConfigs.CLIENT_DNS_LOOKUP_CONFIG));
metadata.bootstrap(addresses);
String metricGrpPrefix = "connect";
ChannelBuilder channelBuilder = ClientUtils.createChannelBuilder(config, time, logContext);
NetworkClient netClient = new NetworkClient(
new Selector(config.getLong(CommonClientConfigs.CONNECTIONS_MAX_IDLE_MS_CONFIG), metrics, time, metricGrpPrefix, channelBuilder, logContext),
metadata,
clientId,
100, // a fixed large enough value will suffice
config.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG),
config.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG),
config.getInt(CommonClientConfigs.SEND_BUFFER_CONFIG),
config.getInt(CommonClientConfigs.RECEIVE_BUFFER_CONFIG),
config.getInt(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG),
config.getLong(CommonClientConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG),
config.getLong(CommonClientConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG),
time,
true,
new ApiVersions(),
logContext,
config.getLong(CommonClientConfigs.METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_CONFIG),
MetadataRecoveryStrategy.forName(config.getString(CommonClientConfigs.METADATA_RECOVERY_STRATEGY_CONFIG))
);
this.client = new ConsumerNetworkClient(
logContext,
netClient,
metadata,
time,
retryBackoffMs,
config.getInt(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG),
Integer.MAX_VALUE);
this.coordinator = new WorkerCoordinator(
new GroupRebalanceConfig(config, GroupRebalanceConfig.ProtocolType.CONNECT),
logContext,
this.client,
metrics,
metricGrpPrefix,
time,
restUrl,
configStorage,
listener,
ConnectProtocolCompatibility.compatibility(config.getString(DistributedConfig.CONNECT_PROTOCOL_CONFIG)),
config.getInt(DistributedConfig.SCHEDULED_REBALANCE_MAX_DELAY_MS_CONFIG));
AppInfoParser.registerAppInfo(JMX_PREFIX, clientId, metrics, time.milliseconds());
log.debug("Connect group member created");
} catch (Throwable t) {
// call close methods if internal objects are already constructed
// this is to prevent resource leak. see KAFKA-2121
stop(true);
// now propagate the exception
throw new KafkaException("Failed to construct kafka consumer", t);
}
}
public void stop() {
if (stopped) return;
stop(false);
}
/**
* Ensure that the connection to the broker coordinator is up and that the worker is an
* active member of the group.
*/
public void ensureActive(Supplier<UncheckedCloseable> onPoll) {
coordinator.poll(0, onPoll);
}
public void poll(long timeout, Supplier<UncheckedCloseable> onPoll) {
if (timeout < 0)
throw new IllegalArgumentException("Timeout must not be negative");
coordinator.poll(timeout, onPoll);
}
/**
* Interrupt any running poll() calls, causing a WakeupException to be thrown in the thread invoking that method.
*/
public void wakeup() {
this.client.wakeup();
}
/**
* Get the member ID of this worker in the group of workers.
* <p>
* This ID is the unique member ID automatically generated.
*
* @return the member ID
*/
public String memberId() {
return coordinator.memberId();
}
public void requestRejoin() {
coordinator.requestRejoin("connect worker requested rejoin");
}
public void maybeLeaveGroup(String leaveReason) {
coordinator.maybeLeaveGroup(CloseOptions.GroupMembershipOperation.LEAVE_GROUP, leaveReason);
}
public String ownerUrl(String connector) {
return coordinator.ownerUrl(connector);
}
public String ownerUrl(ConnectorTaskId task) {
return coordinator.ownerUrl(task);
}
/**
* Get the version of the connect protocol that is currently active in the group of workers.
*
* @return the current connect protocol version
*/
public short currentProtocolVersion() {
return coordinator.currentProtocolVersion();
}
public void revokeAssignment(ExtendedAssignment assignment) {
coordinator.revokeAssignment(assignment);
}
private void stop(boolean swallowException) {
log.trace("Stopping the Connect group member.");
AtomicReference<Throwable> firstException = new AtomicReference<>();
this.stopped = true;
Utils.closeQuietly(coordinator, "coordinator", firstException);
Utils.closeQuietly(metrics, "consumer metrics", firstException);
Utils.closeQuietly(client, "consumer network client", firstException);
AppInfoParser.unregisterAppInfo(JMX_PREFIX, clientId, metrics);
if (firstException.get() != null && !swallowException)
throw new KafkaException("Failed to stop the Connect group member", firstException.get());
else
log.debug("The Connect group member has stopped.");
}
// Visible for testing
Metrics metrics() {
return this.metrics;
}
}
|
WorkerGroupMember
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheManagerTests.java
|
{
"start": 871,
"end": 5427
}
|
class ____ {
@Test
void testDynamicMode() {
ConcurrentMapCacheManager cm = new ConcurrentMapCacheManager();
Cache cache1 = cm.getCache("c1");
assertThat(cache1).isInstanceOf(ConcurrentMapCache.class);
Cache cache1again = cm.getCache("c1");
assertThat(cache1).isSameAs(cache1again);
Cache cache2 = cm.getCache("c2");
assertThat(cache2).isInstanceOf(ConcurrentMapCache.class);
Cache cache2again = cm.getCache("c2");
assertThat(cache2).isSameAs(cache2again);
Cache cache3 = cm.getCache("c3");
assertThat(cache3).isInstanceOf(ConcurrentMapCache.class);
Cache cache3again = cm.getCache("c3");
assertThat(cache3).isSameAs(cache3again);
cache1.put("key1", "value1");
assertThat(cache1.get("key1").get()).isEqualTo("value1");
cache1.put("key2", 2);
assertThat(cache1.get("key2").get()).isEqualTo(2);
cache1.put("key3", null);
assertThat(cache1.get("key3").get()).isNull();
cache1.put("key3", null);
assertThat(cache1.get("key3").get()).isNull();
cache1.evict("key3");
assertThat(cache1.get("key3")).isNull();
assertThat(cache1.putIfAbsent("key1", "value1x").get()).isEqualTo("value1");
assertThat(cache1.get("key1").get()).isEqualTo("value1");
assertThat(cache1.putIfAbsent("key2", 2.1).get()).isEqualTo(2);
assertThat(cache1.putIfAbsent("key3", null)).isNull();
assertThat(cache1.get("key3").get()).isNull();
assertThat(cache1.putIfAbsent("key3", null).get()).isNull();
assertThat(cache1.get("key3").get()).isNull();
cache1.evict("key3");
assertThat(cache1.get("key3")).isNull();
cm.removeCache("c1");
assertThat(cm.getCache("c1")).isNotSameAs(cache1);
assertThat(cm.getCache("c2")).isSameAs(cache2);
cm.resetCaches();
assertThat(cm.getCache("c1")).isNotSameAs(cache1);
assertThat(cm.getCache("c2")).isNotSameAs(cache2);
}
@Test
void testStaticMode() {
ConcurrentMapCacheManager cm = new ConcurrentMapCacheManager("c1", "c2");
Cache cache1 = cm.getCache("c1");
assertThat(cache1).isInstanceOf(ConcurrentMapCache.class);
Cache cache1again = cm.getCache("c1");
assertThat(cache1).isSameAs(cache1again);
Cache cache2 = cm.getCache("c2");
assertThat(cache2).isInstanceOf(ConcurrentMapCache.class);
Cache cache2again = cm.getCache("c2");
assertThat(cache2).isSameAs(cache2again);
Cache cache3 = cm.getCache("c3");
assertThat(cache3).isNull();
cache1.put("key1", "value1");
assertThat(cache1.get("key1").get()).isEqualTo("value1");
cache1.put("key2", 2);
assertThat(cache1.get("key2").get()).isEqualTo(2);
cache1.put("key3", null);
assertThat(cache1.get("key3").get()).isNull();
cache1.evict("key3");
assertThat(cache1.get("key3")).isNull();
cm.setAllowNullValues(false);
Cache cache1x = cm.getCache("c1");
assertThat(cache1x).isInstanceOf(ConcurrentMapCache.class);
assertThat(cache1x).isNotSameAs(cache1);
Cache cache2x = cm.getCache("c2");
assertThat(cache2x).isInstanceOf(ConcurrentMapCache.class);
assertThat(cache2x).isNotSameAs(cache2);
Cache cache3x = cm.getCache("c3");
assertThat(cache3x).isNull();
cache1x.put("key1", "value1");
assertThat(cache1x.get("key1").get()).isEqualTo("value1");
cache1x.put("key2", 2);
assertThat(cache1x.get("key2").get()).isEqualTo(2);
cm.setAllowNullValues(true);
Cache cache1y = cm.getCache("c1");
Cache cache2y = cm.getCache("c2");
cache1y.put("key3", null);
assertThat(cache1y.get("key3").get()).isNull();
cache1y.evict("key3");
assertThat(cache1y.get("key3")).isNull();
cache2y.put("key4", "value4");
assertThat(cache2y.get("key4").get()).isEqualTo("value4");
cm.removeCache("c1");
assertThat(cm.getCache("c1")).isNull();
assertThat(cm.getCache("c2")).isSameAs(cache2y);
assertThat(cache2y.get("key4").get()).isEqualTo("value4");
cm.resetCaches();
assertThat(cm.getCache("c1")).isNull();
assertThat(cm.getCache("c2")).isSameAs(cache2y);
assertThat(cache2y.get("key4")).isNull();
}
@Test
void testChangeStoreByValue() {
ConcurrentMapCacheManager cm = new ConcurrentMapCacheManager("c1", "c2");
assertThat(cm.isStoreByValue()).isFalse();
Cache cache1 = cm.getCache("c1");
assertThat(cache1).isInstanceOf(ConcurrentMapCache.class);
assertThat(((ConcurrentMapCache) cache1).isStoreByValue()).isFalse();
cache1.put("key", "value");
cm.setStoreByValue(true);
assertThat(cm.isStoreByValue()).isTrue();
Cache cache1x = cm.getCache("c1");
assertThat(cache1x).isInstanceOf(ConcurrentMapCache.class);
assertThat(cache1x).isNotSameAs(cache1);
assertThat(cache1x.get("key")).isNull();
}
}
|
ConcurrentMapCacheManagerTests
|
java
|
netty__netty
|
example/src/main/java/io/netty/example/http2/file/Http2StaticFileServerInitializer.java
|
{
"start": 965,
"end": 1551
}
|
class ____ extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
public Http2StaticFileServerInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
pipeline.addLast(Http2FrameCodecBuilder.forServer().build());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new Http2StaticFileServerHandler());
}
}
|
Http2StaticFileServerInitializer
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/observable/BlockingObservableNext.java
|
{
"start": 1242,
"end": 1686
}
|
class ____<T> implements Iterable<T> {
final ObservableSource<T> source;
public BlockingObservableNext(ObservableSource<T> source) {
this.source = source;
}
@Override
public Iterator<T> iterator() {
NextObserver<T> nextObserver = new NextObserver<>();
return new NextIterator<>(source, nextObserver);
}
// test needs to access the observer.waiting flag
static final
|
BlockingObservableNext
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java
|
{
"start": 202186,
"end": 203772
}
|
class ____ extends BooleanExpressionContext {
public List<ValueExpressionContext> valueExpression() {
return getRuleContexts(ValueExpressionContext.class);
}
public ValueExpressionContext valueExpression(int i) {
return getRuleContext(ValueExpressionContext.class,i);
}
public TerminalNode IN() { return getToken(EsqlBaseParser.IN, 0); }
public TerminalNode LP() { return getToken(EsqlBaseParser.LP, 0); }
public TerminalNode RP() { return getToken(EsqlBaseParser.RP, 0); }
public TerminalNode NOT() { return getToken(EsqlBaseParser.NOT, 0); }
public List<TerminalNode> COMMA() { return getTokens(EsqlBaseParser.COMMA); }
public TerminalNode COMMA(int i) {
return getToken(EsqlBaseParser.COMMA, i);
}
@SuppressWarnings("this-escape")
public LogicalInContext(BooleanExpressionContext ctx) { copyFrom(ctx); }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterLogicalIn(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitLogicalIn(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitLogicalIn(this);
else return visitor.visitChildren(this);
}
}
@SuppressWarnings("CheckReturnValue")
public static
|
LogicalInContext
|
java
|
google__dagger
|
javatests/artifacts/dagger-ksp/transitive-annotation-app/src/main/java/app/MyComponent.java
|
{
"start": 1103,
"end": 2374
}
|
class ____ extends MyBaseComponent {
abstract Foo foo();
abstract AssistedFoo.Factory assistedFooFactory();
@MyQualifier
abstract MyComponentModule.ScopedQualifiedBindsType scopedQualifiedBindsType();
abstract MyComponentModule.ScopedUnqualifiedBindsType scopedUnqualifiedBindsType();
@MyQualifier
abstract MyComponentModule.UnscopedQualifiedBindsType unscopedQualifiedBindsType();
abstract MyComponentModule.UnscopedUnqualifiedBindsType unscopedUnqualifiedBindsType();
@MyQualifier
abstract MyComponentModule.ScopedQualifiedProvidesType scopedQualifiedProvidesType();
abstract MyComponentModule.ScopedUnqualifiedProvidesType scopedUnqualifiedProvidesType();
@MyQualifier
abstract MyComponentModule.UnscopedQualifiedProvidesType unscopedQualifiedProvidesType();
abstract MyComponentModule.UnscopedUnqualifiedProvidesType unscopedUnqualifiedProvidesType();
abstract MySubcomponentWithFactory.Factory mySubcomponentWithFactory();
abstract MySubcomponentWithBuilder.Builder mySubcomponentWithBuilder();
@MyQualifier
abstract MyComponentDependencyBinding qualifiedMyComponentDependencyBinding();
abstract MyComponentDependencyBinding unqualifiedMyComponentDependencyBinding();
@Component.Factory
abstract static
|
MyComponent
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/test/entity/pagemodel/RegionEnum.java
|
{
"start": 147,
"end": 257
}
|
enum ____ {
SIDE, MAIN, EXTRA;
public String getId() {
return this.toString();
}
}
|
RegionEnum
|
java
|
apache__camel
|
tests/camel-itest/src/test/java/org/apache/camel/itest/quartz/FtpCronScheduledRoutePolicyManualTest.java
|
{
"start": 1840,
"end": 4170
}
|
class ____ extends CamelTestSupport {
protected FtpServer ftpServer;
private String ftp
= "ftp:localhost:20128/myapp?password=admin&username=admin&delay=5000&idempotent=false&localWorkDirectory=target/tmp";
@Test
void testFtpCronScheduledRoutePolicyTest() throws Exception {
template.sendBodyAndHeader("file:res/home/myapp", "Hello World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(10 * 1000 * 60);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
CronScheduledRoutePolicy policy = new CronScheduledRoutePolicy();
policy.setRouteStartTime("* 0/2 * * * ?");
policy.setRouteStopTime("* 1/2 * * * ?");
policy.setRouteStopGracePeriod(250);
policy.setTimeUnit(TimeUnit.SECONDS);
from(ftp)
.noAutoStartup().routePolicy(policy).shutdownRunningTask(ShutdownRunningTask.CompleteAllTasks)
.log("Processing ${file:name}")
.to("log:done");
}
};
}
@Override
@BeforeEach
public void doPostSetup() throws Exception {
deleteDirectory("res");
createDirectory("res/home/myapp");
initFtpServer();
ftpServer.start();
}
@Override
public void doPostTearDown() {
ftpServer.stop();
ftpServer = null;
}
protected void initFtpServer() {
FtpServerFactory serverFactory = new FtpServerFactory();
// setup user management to read our users.properties and use clear text passwords
File file = new File("src/test/resources/users.properties");
UserManager uman = new PropertiesUserManager(new ClearTextPasswordEncryptor(), file, "admin");
serverFactory.setUserManager(uman);
NativeFileSystemFactory fsf = new NativeFileSystemFactory();
fsf.setCreateHome(true);
serverFactory.setFileSystem(fsf);
ListenerFactory factory = new ListenerFactory();
factory.setPort(20128);
serverFactory.addListener("default", factory.createListener());
ftpServer = serverFactory.createServer();
}
}
|
FtpCronScheduledRoutePolicyManualTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/permission/ResourcePrivilegesTests.java
|
{
"start": 563,
"end": 2780
}
|
class ____ extends ESTestCase {
public void testBuilder() {
ResourcePrivileges instance = createInstance();
ResourcePrivileges expected = new ResourcePrivileges("*", Map.of("read", true, "write", false));
assertThat(instance, equalTo(expected));
}
public void testWhenSamePrivilegeExists() {
ResourcePrivileges.Builder builder = ResourcePrivileges.builder("*").addPrivilege("read", true);
Map<String, Boolean> mapWhereReadIsAllowed = Map.of("read", true);
builder.addPrivileges(mapWhereReadIsAllowed);
assertThat(builder.build().isAllowed("read"), is(true));
Map<String, Boolean> mapWhereReadIsDenied = Map.of("read", false);
builder.addPrivileges(mapWhereReadIsDenied);
assertThat(builder.build().isAllowed("read"), is(false));
}
public void testEqualsHashCode() {
ResourcePrivileges instance = createInstance();
EqualsHashCodeTestUtils.checkEqualsAndHashCode(instance, (original) -> {
return ResourcePrivileges.builder(original.getResource()).addPrivileges(original.getPrivileges()).build();
});
EqualsHashCodeTestUtils.checkEqualsAndHashCode(instance, (original) -> {
return ResourcePrivileges.builder(original.getResource()).addPrivileges(original.getPrivileges()).build();
}, ResourcePrivilegesTests::mutateTestItem);
}
private ResourcePrivileges createInstance() {
ResourcePrivileges instance = ResourcePrivileges.builder("*")
.addPrivilege("read", true)
.addPrivileges(Collections.singletonMap("write", false))
.build();
return instance;
}
private static ResourcePrivileges mutateTestItem(ResourcePrivileges original) {
return switch (randomIntBetween(0, 1)) {
case 0 -> ResourcePrivileges.builder(randomAlphaOfLength(6)).addPrivileges(original.getPrivileges()).build();
case 1 -> ResourcePrivileges.builder(original.getResource()).addPrivileges(Collections.emptyMap()).build();
default -> ResourcePrivileges.builder(randomAlphaOfLength(6)).addPrivileges(Collections.emptyMap()).build();
};
}
}
|
ResourcePrivilegesTests
|
java
|
google__guice
|
core/src/com/google/inject/internal/ProviderMethod.java
|
{
"start": 3320,
"end": 4352
}
|
class ____.
// TODO(lukes): In theory we could use a similar approach to the 'HiddenClassDefiner' and
// use Unsafe to access the trusted MethodHandles.Lookup object which allows us to access all
// methods. However, this is a dangerous and long term unstable approach. The better approach
// is to add a new API that allows users to pass us an appropriate MethodHandles.Lookup
// object. These objects act like `capabilities` which users can use to pass private access
// to us. e.g. `Binder.grantAccess(MethodHandles.Lookup lookup)` could allow callers to pass
// us a lookup object that allows us to access all their methods. Then they could mark their
// methods as private and still hit this case.
MethodHandle target = InternalMethodHandles.unreflect(method);
if (target != null) {
return new MethodHandleProviderMethod<T>(
key, method, instance, dependencies, scopeAnnotation, annotation, target);
}
// fall through to fast
|
generation
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java
|
{
"start": 58912,
"end": 59812
}
|
class ____ {
@Test
void injectsParametersIntoArgumentsProviderConstructor() {
execute(SpiParameterInjectionTestCase.class, "argumentsProviderWithConstructorParameter", String.class) //
.testEvents() //
.assertStatistics(it -> it.succeeded(1));
}
@Test
void injectsParametersIntoArgumentConverterConstructor() {
execute(SpiParameterInjectionTestCase.class, "argumentConverterWithConstructorParameter", String.class) //
.testEvents() //
.assertStatistics(it -> it.succeeded(1));
}
@Test
void injectsParametersIntoArgumentsAggregatorConstructor() {
execute(SpiParameterInjectionTestCase.class, "argumentsAggregatorWithConstructorParameter", String.class) //
.testEvents() //
.assertStatistics(it -> it.succeeded(1));
}
}
// -------------------------------------------------------------------------
static
|
SpiParameterInjectionIntegrationTests
|
java
|
apache__camel
|
components/camel-stream/src/test/java/org/apache/camel/component/stream/ScanStreamFileWithFilterTest.java
|
{
"start": 1285,
"end": 2839
}
|
class ____ extends CamelTestSupport {
private File file;
@Override
public void doPreSetup() throws Exception {
deleteDirectory("target/stream");
createDirectory("target/stream");
file = new File("target/stream/scanstreamfile.txt");
file.createNewFile();
}
@Test
public void testScanFile() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello Boy");
FileOutputStream fos = new FileOutputStream(file);
fos.write("Hello\n".getBytes());
Thread.sleep(150);
fos.write("World\n".getBytes());
Thread.sleep(150);
fos.write("Hello\n".getBytes());
Thread.sleep(150);
fos.write("World\n".getBytes());
Thread.sleep(150);
fos.write("Hello\n".getBytes());
Thread.sleep(150);
fos.write("World\n".getBytes());
Thread.sleep(150);
fos.write("Hello Boy\n".getBytes());
Thread.sleep(150);
fos.write("World\n".getBytes());
MockEndpoint.assertIsSatisfied(context);
fos.close();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("stream:file?fileName=target/stream/scanstreamfile.txt&scanStream=true&scanStreamDelay=100")
.filter(body().contains("Hello Boy"))
.to("mock:result");
}
};
}
}
|
ScanStreamFileWithFilterTest
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/ByteFieldTest.java
|
{
"start": 1969,
"end": 2174
}
|
class ____ {
private Byte value;
public Byte getValue() {
return value;
}
public void setValue(Byte value) {
this.value = value;
}
}
}
|
V0
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ConcreteProxyTest.java
|
{
"start": 16241,
"end": 16521
}
|
class ____ extends JoinedDiscBase {
private String child1Prop;
public JoinedDiscChild1() {
}
public JoinedDiscChild1(Long id, String child1Prop) {
super( id );
this.child1Prop = child1Prop;
}
}
@Entity(name = "JoinedDiscSubChild1")
public static
|
JoinedDiscChild1
|
java
|
elastic__elasticsearch
|
modules/lang-painless/src/main/java/org/elasticsearch/painless/LambdaBootstrap.java
|
{
"start": 7270,
"end": 7566
}
|
interface ____ that is called
* @param factoryMethodType The type of method to be linked to this CallSite; note that
* captured types are based on the parameters for this method
* @param interfaceMethodType The type of method representing the functional
|
method
|
java
|
apache__dubbo
|
dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java
|
{
"start": 19770,
"end": 20120
}
|
interface ____<T extends String, S> {
CompletableFuture<String> getFuture();
String getString();
T getT();
S getS();
CompletableFuture<List<String>> getListFuture();
CompletableFuture<T> getGenericWithUpperFuture();
CompletableFuture<S> getGenericFuture();
}
public static
|
TypeClass
|
java
|
grpc__grpc-java
|
xds/src/main/java/io/grpc/xds/client/LoadStatsManager2.java
|
{
"start": 14027,
"end": 14677
}
|
class ____ {
private final Map<String, Long> categorizedDrops;
private final long uncategorizedDrops;
private final long durationNano;
private ClusterDropStatsSnapshot(
Map<String, Long> categorizedDrops, long uncategorizedDrops, long durationNano) {
this.categorizedDrops = Collections.unmodifiableMap(
checkNotNull(categorizedDrops, "categorizedDrops"));
this.uncategorizedDrops = uncategorizedDrops;
this.durationNano = durationNano;
}
}
/**
* Recorder for client loads. One instance per locality (in cluster with edsService).
*/
@ThreadSafe
public final
|
ClusterDropStatsSnapshot
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TimeoutExtensionTests.java
|
{
"start": 29277,
"end": 29523
}
|
class ____ {
@Test
@Timeout(value = 100, unit = SECONDS, threadMode = SEPARATE_THREAD)
void test() {
throw new OutOfMemoryError();
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
static
|
UnrecoverableExceptionInSeparateThreadTestCase
|
java
|
spring-projects__spring-boot
|
module/spring-boot-security-oauth2-client/src/test/java/org/springframework/boot/security/oauth2/client/autoconfigure/reactive/ReactiveOAuth2ClientWebSecurityAutoConfigurationTests.java
|
{
"start": 6049,
"end": 6484
}
|
class ____ {
@Bean
InMemoryReactiveOAuth2AuthorizedClientService testAuthorizedClientService(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
}
}
@Configuration(proxyBeanMethods = false)
@Import(ReactiveOAuth2AuthorizedClientServiceConfiguration.class)
static
|
ReactiveOAuth2AuthorizedClientServiceConfiguration
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/IgnoreSnapshotException.java
|
{
"start": 948,
"end": 1043
}
|
class ____ extends IOException {
public IgnoreSnapshotException() {
}
}
|
IgnoreSnapshotException
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/WaitForIndexColorStep.java
|
{
"start": 1111,
"end": 5880
}
|
class ____ extends ClusterStateWaitStep {
public static final String NAME = "wait-for-index-color";
private static final Logger logger = LogManager.getLogger(WaitForIndexColorStep.class);
private final ClusterHealthStatus color;
private final BiFunction<String, LifecycleExecutionState, String> indexNameSupplier;
WaitForIndexColorStep(StepKey key, StepKey nextStepKey, ClusterHealthStatus color) {
this(key, nextStepKey, color, (index, lifecycleState) -> index);
}
WaitForIndexColorStep(StepKey key, StepKey nextStepKey, ClusterHealthStatus color, @Nullable String indexNamePrefix) {
this(key, nextStepKey, color, (index, lifecycleState) -> indexNamePrefix + index);
}
WaitForIndexColorStep(
StepKey key,
StepKey nextStepKey,
ClusterHealthStatus color,
BiFunction<String, LifecycleExecutionState, String> indexNameSupplier
) {
super(key, nextStepKey);
this.color = color;
this.indexNameSupplier = indexNameSupplier;
}
public ClusterHealthStatus getColor() {
return this.color;
}
BiFunction<String, LifecycleExecutionState, String> getIndexNameSupplier() {
return indexNameSupplier;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), this.color);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != getClass()) {
return false;
}
WaitForIndexColorStep other = (WaitForIndexColorStep) obj;
return super.equals(obj) && Objects.equals(this.color, other.color);
}
@Override
public Result isConditionMet(Index index, ProjectState currentState) {
LifecycleExecutionState lifecycleExecutionState = currentState.metadata().index(index.getName()).getLifecycleExecutionState();
String indexName = indexNameSupplier.apply(index.getName(), lifecycleExecutionState);
IndexMetadata indexMetadata = currentState.metadata().index(indexName);
// check if the (potentially) derived index exists
if (indexMetadata == null) {
String errorMessage = Strings.format(
"[%s] lifecycle action for index [%s] executed but the target index [%s] does not exist",
getKey().action(),
index.getName(),
indexName
);
logger.debug(errorMessage);
return new Result(false, new SingleMessageFieldInfo(errorMessage));
}
IndexRoutingTable indexRoutingTable = currentState.routingTable().index(indexMetadata.getIndex());
Result result = switch (this.color) {
case GREEN -> waitForGreen(indexRoutingTable);
case YELLOW -> waitForYellow(indexRoutingTable);
case RED -> waitForRed(indexRoutingTable);
};
return result;
}
@Override
public boolean isRetryable() {
return true;
}
private static Result waitForRed(IndexRoutingTable indexRoutingTable) {
if (indexRoutingTable == null) {
return new Result(true, new SingleMessageFieldInfo("index is red"));
}
return new Result(false, new SingleMessageFieldInfo("index is not red"));
}
private static Result waitForYellow(IndexRoutingTable indexRoutingTable) {
if (indexRoutingTable == null) {
return new Result(false, new SingleMessageFieldInfo("index is red; no indexRoutingTable"));
}
boolean indexIsAtLeastYellow = indexRoutingTable.allPrimaryShardsActive();
if (indexIsAtLeastYellow) {
return new Result(true, null);
} else {
return new Result(false, new SingleMessageFieldInfo("index is red; not all primary shards are active"));
}
}
private static Result waitForGreen(IndexRoutingTable indexRoutingTable) {
if (indexRoutingTable == null) {
return new Result(false, new SingleMessageFieldInfo("index is red; no indexRoutingTable"));
}
if (indexRoutingTable.allPrimaryShardsActive()) {
for (int i = 0; i < indexRoutingTable.size(); i++) {
boolean replicaIndexIsGreen = indexRoutingTable.shard(i).replicaShards().stream().allMatch(ShardRouting::active);
if (replicaIndexIsGreen == false) {
return new Result(false, new SingleMessageFieldInfo("index is yellow; not all replica shards are active"));
}
}
return new Result(true, null);
}
return new Result(false, new SingleMessageFieldInfo("index is not green; not all shards are active"));
}
}
|
WaitForIndexColorStep
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/OperationResponseBodyTests.java
|
{
"start": 960,
"end": 1383
}
|
class ____ {
@Test
void ofMapReturnsOperationResponseBody() {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("one", "1");
map.put("two", "2");
Map<String, String> mapDescriptor = OperationResponseBody.of(map);
assertThat(mapDescriptor).containsExactly(entry("one", "1"), entry("two", "2"));
assertThat(mapDescriptor).isInstanceOf(OperationResponseBody.class);
}
}
|
OperationResponseBodyTests
|
java
|
apache__logging-log4j2
|
log4j-1.2-api/src/main/java/org/apache/log4j/varia/NullAppender.java
|
{
"start": 993,
"end": 2307
}
|
class ____ extends AppenderSkeleton {
private static final NullAppender INSTANCE = new NullAppender();
/**
* Whenever you can, use this method to retreive an instance instead of instantiating a new one with <code>new</code>.
*/
public static NullAppender getNullAppender() {
return INSTANCE;
}
public NullAppender() {
// noop
}
/**
* There are no options to acticate.
*/
@Override
public void activateOptions() {
// noop
}
/**
* Does not do anything.
*/
@Override
protected void append(final LoggingEvent event) {
// noop
}
@Override
public void close() {
// noop
}
/**
* Does not do anything.
*/
@Override
public void doAppend(final LoggingEvent event) {
// noop
}
/**
* Whenever you can, use this method to retreive an instance instead of instantiating a new one with <code>new</code>.
*
* @deprecated Use getNullAppender instead. getInstance should have been static.
*/
@Deprecated
public NullAppender getInstance() {
return INSTANCE;
}
/**
* NullAppenders do not need a layout.
*/
@Override
public boolean requiresLayout() {
return false;
}
}
|
NullAppender
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/floats/Floats_assertIsPositive_Test.java
|
{
"start": 1102,
"end": 1979
}
|
class ____ extends FloatsBaseTest {
@Test
void should_succeed_since_actual_is_positive() {
floats.assertIsPositive(someInfo(), 6.0f);
}
@Test
void should_fail_since_actual_is_not_positive() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsPositive(someInfo(), -6.0f))
.withMessage("%nExpecting actual:%n -6.0f%nto be greater than:%n 0.0f%n".formatted());
}
@Test
void should_succeed_since_actual_is_positive_according_to_absolute_value_comparison_strategy() {
floatsWithAbsValueComparisonStrategy.assertIsPositive(someInfo(), (float) 6);
}
@Test
void should_succeed_since_actual_is_positive_according_to_absolute_value_comparison_strategy2() {
floatsWithAbsValueComparisonStrategy.assertIsPositive(someInfo(), -6.0f);
}
}
|
Floats_assertIsPositive_Test
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/BeanWithXPathInjectionTest.java
|
{
"start": 3191,
"end": 3624
}
|
class ____ {
public String body;
public String foo;
@Override
public String toString() {
return "MyBean[foo: " + foo + " body: " + body + "]";
}
public void read(String body, @XPath("/soap:Envelope/soap:Body/foo/text()") String foo) {
this.foo = foo;
this.body = body;
LOG.info("read() method called on {}", this);
}
}
}
|
MyBean
|
java
|
apache__flink
|
flink-table/flink-table-api-java/src/test/java/org/apache/flink/table/utils/UserDefinedFunctions.java
|
{
"start": 3060,
"end": 3525
}
|
class ____ extends TableFunction<Row> {
public void eval(String str, Long extra) {
for (String s : str.split(" ")) {
Row r = new Row(2);
r.setField(0, s);
r.setField(1, s.length() + extra);
collect(r);
}
}
@Override
public TypeInformation<Row> getResultType() {
return Types.ROW(Types.STRING(), Types.LONG());
}
}
}
|
TableUDF
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-gcp/src/main/java/org/apache/hadoop/fs/gs/GoogleCloudStorageItemInfo.java
|
{
"start": 2469,
"end": 6561
}
|
class ____ a bucket.
*/
static GoogleCloudStorageItemInfo createBucket(StorageResourceId resourceId,
long creationTime, long modificationTime, String location, String storageClass) {
checkNotNull(resourceId, "resourceId must not be null");
checkArgument(resourceId.isBucket(), "expected bucket but got '%s'", resourceId);
return new GoogleCloudStorageItemInfo(resourceId, creationTime, modificationTime,
/* size= */ 0, location, storageClass,
/* contentType= */ null,
/* contentEncoding= */ null,
/* metadata= */ null,
/* contentGeneration= */ 0,
/* metaGeneration= */ 0,
/* verificationAttributes= */ null);
}
/**
* Factory method for creating a GoogleCloudStorageItemInfo for an object.
*
* @param resourceId identifies either root, a Bucket, or a StorageObject
* @param creationTime Time when object was created (milliseconds since January 1, 1970
* UTC).
* @param size Size of the given object (number of bytes) or -1 if the object
* does not exist.
* @param metadata User-supplied object metadata for this object.
*/
static GoogleCloudStorageItemInfo createObject(StorageResourceId resourceId,
long creationTime, long modificationTime, long size, String contentType,
String contentEncoding, Map<String, byte[]> metadata, long contentGeneration,
long metaGeneration, VerificationAttributes verificationAttributes) {
checkNotNull(resourceId, "resourceId must not be null");
checkArgument(
!resourceId.isRoot(),
"expected object or directory but got '%s'", resourceId);
checkArgument(
!resourceId.isBucket(),
"expected object or directory but got '%s'", resourceId);
return new GoogleCloudStorageItemInfo(resourceId, creationTime, modificationTime, size,
/* location= */ null,
/* storageClass= */ null, contentType, contentEncoding, metadata, contentGeneration,
metaGeneration, verificationAttributes);
}
/**
* Factory method for creating a "found" GoogleCloudStorageItemInfo for an inferred directory.
*
* @param resourceId Resource ID that identifies an inferred directory
*/
static GoogleCloudStorageItemInfo createInferredDirectory(StorageResourceId resourceId) {
return new GoogleCloudStorageItemInfo(resourceId,
/* creationTime= */ 0,
/* modificationTime= */ 0,
/* size= */ 0,
/* location= */ null,
/* storageClass= */ null,
/* contentType= */ null,
/* contentEncoding= */ null,
/* metadata= */ null,
/* contentGeneration= */ 0,
/* metaGeneration= */ 0,
/* verificationAttributes= */ null);
}
/**
* Factory method for creating a "not found" GoogleCloudStorageItemInfo for a bucket or an object.
*
* @param resourceId Resource ID that identifies an inferred directory
*/
static GoogleCloudStorageItemInfo createNotFound(StorageResourceId resourceId) {
return new GoogleCloudStorageItemInfo(resourceId,
/* creationTime= */ 0,
/* modificationTime= */ 0,
/* size= */ -1,
/* location= */ null,
/* storageClass= */ null,
/* contentType= */ null,
/* contentEncoding= */ null,
/* metadata= */ null,
/* contentGeneration= */ 0,
/* metaGeneration= */ 0,
/* verificationAttributes= */ null);
}
// The Bucket and maybe StorageObject names of the GCS "item" referenced by this object. Not
// null.
private final StorageResourceId resourceId;
// Creation time of this item.
// Time is expressed as milliseconds since January 1, 1970 UTC.
private final long creationTime;
// Modification time of this item.
// Time is expressed as milliseconds since January 1, 1970 UTC.
private final long modificationTime;
// Size of an object (number of bytes).
// Size is -1 for items that do not exist.
private final long size;
// Location of this item.
private final String location;
// Storage
|
of
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/cache/CacheOnClassAndMethodsImplementationTest.java
|
{
"start": 2335,
"end": 2610
}
|
class ____ implements IResourceWithCache {
@Override
@Cache(noStore = true)
public String with() {
return "with";
}
@Override
public String without() {
return "without";
}
}
}
|
ResourceWithCache
|
java
|
apache__kafka
|
streams/src/test/java/org/apache/kafka/streams/state/internals/ChangeLoggingVersionedKeyValueBytesStoreTest.java
|
{
"start": 2405,
"end": 9084
}
|
class ____ {
private static final Serializer<String> STRING_SERIALIZER = new StringSerializer();
private static final Serializer<ValueAndTimestamp<String>> VALUE_AND_TIMESTAMP_SERIALIZER
= new ValueAndTimestampSerializer<>(STRING_SERIALIZER);
private static final long HISTORY_RETENTION = 1000L;
private final MockRecordCollector collector = new MockRecordCollector();
private InternalMockProcessorContext<String, Long> context;
private VersionedBytesStore inner;
private ChangeLoggingVersionedKeyValueBytesStore store;
@BeforeEach
public void before() {
inner = (VersionedBytesStore) new RocksDbVersionedKeyValueBytesStoreSupplier("bytes_store", HISTORY_RETENTION).get();
store = new ChangeLoggingVersionedKeyValueBytesStore(inner);
context = mockContext();
context.setTime(0);
store.init(context, store);
}
private InternalMockProcessorContext<String, Long> mockContext() {
return new InternalMockProcessorContext<>(
TestUtils.tempDirectory(),
Serdes.String(),
Serdes.Long(),
collector,
new ThreadCache(new LogContext("testCache "), 0, new MockStreamsMetrics(new Metrics()))
);
}
@AfterEach
public void after() {
store.close();
}
@Test
public void shouldThrowIfInnerIsNotVersioned() {
assertThrows(IllegalArgumentException.class,
() -> new ChangeLoggingVersionedKeyValueBytesStore(new InMemoryKeyValueStore("kv")));
}
@Test
public void shouldDelegateInit() {
// recreate store with mock inner
store.close();
final VersionedBytesStore mockInner = mock(VersionedBytesStore.class);
store = new ChangeLoggingVersionedKeyValueBytesStore(mockInner);
store.init(context, store);
verify(mockInner).init(context, store);
}
@Test
public void shouldPropagateAndLogOnPut() {
final Bytes rawKey = Bytes.wrap(rawBytes("k"));
final String value = "foo";
final long timestamp = 10L;
final long validTo = store.put(rawKey, rawBytes(value), timestamp);
assertThat(validTo, equalTo(PUT_RETURN_CODE_VALID_TO_UNDEFINED));
assertThat(inner.get(rawKey), equalTo(rawValueAndTimestamp(value, timestamp)));
assertThat(collector.collected().size(), equalTo(1));
assertThat(collector.collected().get(0).key(), equalTo(rawKey));
assertThat(collector.collected().get(0).value(), equalTo(rawBytes(value)));
assertThat(collector.collected().get(0).timestamp(), equalTo(timestamp));
}
@Test
public void shouldPropagateAndLogOnPutNull() {
final Bytes rawKey = Bytes.wrap(rawBytes("k"));
final long timestamp = 10L;
// put initial record to inner, so that later verification confirms that store.put() has an effect
inner.put(rawKey, rawBytes("foo"), timestamp - 1);
assertThat(inner.get(rawKey), equalTo(rawValueAndTimestamp("foo", timestamp - 1)));
final long validTo = store.put(rawKey, null, timestamp);
assertThat(validTo, equalTo(PUT_RETURN_CODE_VALID_TO_UNDEFINED));
assertThat(inner.get(rawKey), nullValue());
assertThat(collector.collected().size(), equalTo(1));
assertThat(collector.collected().get(0).key(), equalTo(rawKey));
assertThat(collector.collected().get(0).value(), nullValue());
assertThat(collector.collected().get(0).timestamp(), equalTo(timestamp));
}
@Test
public void shouldPropagateAndLogOnDeleteWithTimestamp() {
final Bytes rawKey = Bytes.wrap(rawBytes("k"));
final long timestamp = 10L;
final byte[] rawValueAndTimestamp = rawValueAndTimestamp("foo", timestamp - 1);
// put initial record to inner, so that later verification confirms that store.put() has an effect
inner.put(rawKey, rawBytes("foo"), timestamp - 1);
assertThat(inner.get(rawKey), equalTo(rawValueAndTimestamp));
final byte[] result = store.delete(rawKey, timestamp);
assertThat(result, equalTo(rawValueAndTimestamp));
assertThat(inner.get(rawKey), nullValue());
assertThat(collector.collected().size(), equalTo(1));
assertThat(collector.collected().get(0).key(), equalTo(rawKey));
assertThat(collector.collected().get(0).value(), nullValue());
assertThat(collector.collected().get(0).timestamp(), equalTo(timestamp));
}
@Test
public void shouldNotLogOnDeleteIfInnerStoreThrows() {
final Bytes rawKey = Bytes.wrap(rawBytes("k"));
assertThrows(UnsupportedOperationException.class, () -> inner.delete(rawKey));
assertThrows(UnsupportedOperationException.class, () -> store.delete(rawKey));
assertThat(collector.collected().size(), equalTo(0));
}
@Test
public void shouldNotLogOnPutAllIfInnerStoreThrows() {
final List<KeyValue<Bytes, byte[]>> entries = Collections.singletonList(KeyValue.pair(
Bytes.wrap(rawBytes("k")),
rawValueAndTimestamp("v", 12L)));
assertThrows(UnsupportedOperationException.class, () -> inner.putAll(entries));
assertThrows(UnsupportedOperationException.class, () -> store.putAll(entries));
assertThat(collector.collected().size(), equalTo(0));
}
@Test
public void shouldNotLogOnPutIfAbsentIfInnerStoreThrows() {
final Bytes rawKey = Bytes.wrap(rawBytes("k"));
final byte[] rawValue = rawBytes("v");
assertThrows(UnsupportedOperationException.class, () -> inner.putIfAbsent(rawKey, rawValue));
assertThrows(UnsupportedOperationException.class, () -> store.putIfAbsent(rawKey, rawValue));
assertThat(collector.collected().size(), equalTo(0));
}
@Test
public void shouldDelegateGet() {
final Bytes rawKey = Bytes.wrap(rawBytes("k"));
inner.put(rawKey, rawBytes("v"), 8L);
assertThat(store.get(rawKey), equalTo(rawValueAndTimestamp("v", 8L)));
}
@Test
public void shouldDelegateGetWithTimestamp() {
final Bytes rawKey = Bytes.wrap(rawBytes("k"));
inner.put(rawKey, rawBytes("v"), 8L);
assertThat(store.get(rawKey, 10L), equalTo(rawValueAndTimestamp("v", 8L)));
}
private static byte[] rawBytes(final String s) {
return STRING_SERIALIZER.serialize(null, s);
}
private static byte[] rawValueAndTimestamp(final String value, final long timestamp) {
return VALUE_AND_TIMESTAMP_SERIALIZER.serialize(null, ValueAndTimestamp.makeAllowNullable(value, timestamp));
}
}
|
ChangeLoggingVersionedKeyValueBytesStoreTest
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4410UsageHelpTest.java
|
{
"start": 1040,
"end": 1752
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that "mvn --help" outputs the usage help and stops the execution after that.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4410");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.addCliArgument("--help");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyTextInLog("--version");
verifier.verifyTextInLog("--debug");
verifier.verifyTextInLog("--batch-mode");
}
}
|
MavenITmng4410UsageHelpTest
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
|
{
"start": 56125,
"end": 57156
}
|
class ____ implements Validator {
private final List<Validator> validators;
private CompositeValidator(List<Validator> validators) {
this.validators = Collections.unmodifiableList(validators);
}
public static CompositeValidator of(Validator... validators) {
return new CompositeValidator(Arrays.asList(validators));
}
@Override
public void ensureValid(String name, Object value) {
for (Validator validator: validators) {
validator.ensureValid(name, value);
}
}
@Override
public String toString() {
if (validators == null) return "";
StringBuilder desc = new StringBuilder();
for (Validator v: validators) {
if (desc.length() > 0) {
desc.append(',').append(' ');
}
desc.append(v);
}
return desc.toString();
}
}
public static
|
CompositeValidator
|
java
|
apache__camel
|
dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/DependencyDownloaderClassResolver.java
|
{
"start": 4298,
"end": 4511
}
|
class
____ gav = knownDependenciesResolver.mavenGavForClass(name);
if (gav == null) {
// okay maybe its a known pojo-bean from the catalog
// lookup via
|
MavenGav
|
java
|
google__guice
|
core/test/com/google/inject/ProvisionListenerTest.java
|
{
"start": 19638,
"end": 20130
}
|
class ____ implements ProvisionListener {
int beforeProvision = 0;
int afterProvision = 0;
AtomicReference<RuntimeException> capture = new AtomicReference<>();
@Override
public <T> void onProvision(ProvisionInvocation<T> provision) {
beforeProvision++;
try {
provision.provision();
} catch (RuntimeException re) {
capture.set(re);
throw re;
}
afterProvision++;
}
}
private static
|
CountAndCaptureExceptionListener
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/ann/src/main/java/org/elasticsearch/compute/ann/Aggregator.java
|
{
"start": 2163,
"end": 2439
}
|
interface ____ {
IntermediateState[] value() default {};
/**
* Exceptions thrown by the `combine*(...)` methods to catch and convert
* into a warning and turn into a null value.
*/
Class<? extends Exception>[] warnExceptions() default {};
}
|
Aggregator
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stress/DrainTest.java
|
{
"start": 1218,
"end": 4019
}
|
class ____ {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(MyEndpoint.class, BytesData.class, Data.class, DataBodyWriter.class)
.addAsResource("server-keystore.jks"))
.overrideConfigKey("quarkus.http.ssl.certificate.key-store-file", "server-keystore.jks")
.overrideConfigKey("quarkus.http.ssl.certificate.key-store-password", "secret");
HttpClient client;
@Test
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
void testAsyncHttp1() {
client = createJavaHttpClient();
long before = System.currentTimeMillis();
var sum = IntStream.range(0, 10000)
.parallel()
.map(i -> get("https://localhost:8444/test/bytesAsync"))
.sum();
System.out.println("Request completed in " + (System.currentTimeMillis() - before) + " ms");
Assertions.assertThat(sum).isEqualTo(1000000000);
}
@Test
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
void testSyncHttp1() {
client = createJavaHttpClient();
long before = System.currentTimeMillis();
var sum = IntStream.range(0, 10000)
.parallel()
.map(i -> get("https://localhost:8444/test/bytesSync"))
.sum();
System.out.println("Request completed in " + (System.currentTimeMillis() - before) + " ms");
Assertions.assertThat(sum).isEqualTo(1000000000);
}
@Test
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
void testAsyncHttp2() {
client = createJavaHttp2Client();
long before = System.currentTimeMillis();
var sum = IntStream.range(0, 10000)
.parallel()
.map(i -> get("https://localhost:8444/test/bytesAsync"))
//.peek(i -> System.out.println(Instant.now() + " Got response: " + i))
.sum();
System.out.println("Request completed in " + (System.currentTimeMillis() - before) + " ms");
Assertions.assertThat(sum).isEqualTo(1000000000);
}
@Test
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
void testSyncHttp2() {
client = createJavaHttp2Client();
long before = System.currentTimeMillis();
var sum = IntStream.range(0, 10000)
.parallel()
.map(i -> get("https://localhost:8444/test/bytesSync"))
.sum();
System.out.println("Request completed in " + (System.currentTimeMillis() - before) + " ms");
Assertions.assertThat(sum).isEqualTo(1000000000);
}
public
|
DrainTest
|
java
|
dropwizard__dropwizard
|
dropwizard-util/src/test/java/io/dropwizard/util/JarLocationTest.java
|
{
"start": 124,
"end": 480
}
|
class ____ {
@Test
void isHumanReadable() throws Exception {
assertThat(new JarLocation(JarLocationTest.class))
.hasToString("project.jar");
}
@Test
void hasAVersion() throws Exception {
assertThat(new JarLocation(JarLocationTest.class).getVersion())
.isNotPresent();
}
}
|
JarLocationTest
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/PojoSerializerUpgradeTestSpecifications.java
|
{
"start": 13862,
"end": 14668
}
|
class ____ {
public int fieldValue;
public PojoWithIntField() {}
public PojoWithIntField(int fieldValue) {
this.fieldValue = fieldValue;
}
}
@Override
public TypeSerializer<PojoWithIntField> createPriorSerializer() {
TypeSerializer<PojoWithIntField> serializer =
TypeExtractor.createTypeInfo(PojoWithIntField.class)
.createSerializer(new SerializerConfigImpl());
assertThat(serializer.getClass()).isSameAs(PojoSerializer.class);
return serializer;
}
@Override
public PojoWithIntField createTestData() {
return new PojoWithIntField(911108);
}
}
public static final
|
PojoWithIntField
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/WrappedFile.java
|
{
"start": 862,
"end": 1103
}
|
interface ____<T> {
/**
* Gets the file.
*
* @return the file.
*/
T getFile();
/**
* Gets the content of the file.
*
* @return the content of the file.
*/
Object getBody();
}
|
WrappedFile
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/test/benchmark/decode/Map1000StringDecode.java
|
{
"start": 236,
"end": 722
}
|
class ____ extends BenchmarkCase {
private String text;
public Map1000StringDecode(){
super("Map100StringDecode");
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 1000; ++i) {
map.put("f" + i, Integer.toString(i));
}
this.text = JSON.toJSONString(map) + ' ';
}
@Override
public void execute(Codec codec) throws Exception {
codec.decodeObject(text);
}
}
|
Map1000StringDecode
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/inject/guice/OverridesGuiceInjectableMethodTest.java
|
{
"start": 2800,
"end": 2936
}
|
class ____ extends TestClass4 {
// BUG: Diagnostic contains: @Inject
public void foo() {}
}
/** Class that extends a
|
TestClass5
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/dynamic/ReactiveTypeAdapters.java
|
{
"start": 11790,
"end": 12132
}
|
enum ____ implements Function<Observable<?>, Single<?>> {
INSTANCE;
@Override
public Single<?> apply(Observable<?> source) {
return source.toSingle();
}
}
/**
* An adapter {@link Function} to adopt a {@link Single} to {@link Single}.
*/
public
|
RxJava1ObservableToSingleAdapter
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/config/AbstractPropertyLoadingBeanDefinitionParser.java
|
{
"start": 1195,
"end": 2600
}
|
class ____ extends AbstractSingleBeanDefinitionParser {
@Override
protected boolean shouldGenerateId() {
return true;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String location = element.getAttribute("location");
if (StringUtils.hasLength(location)) {
location = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(location);
String[] locations = StringUtils.commaDelimitedListToStringArray(location);
builder.addPropertyValue("locations", locations);
}
String propertiesRef = element.getAttribute("properties-ref");
if (StringUtils.hasLength(propertiesRef)) {
builder.addPropertyReference("properties", propertiesRef);
}
String fileEncoding = element.getAttribute("file-encoding");
if (StringUtils.hasLength(fileEncoding)) {
builder.addPropertyValue("fileEncoding", fileEncoding);
}
String order = element.getAttribute("order");
if (StringUtils.hasLength(order)) {
builder.addPropertyValue("order", Integer.valueOf(order));
}
builder.addPropertyValue("ignoreResourceNotFound",
Boolean.valueOf(element.getAttribute("ignore-resource-not-found")));
builder.addPropertyValue("localOverride",
Boolean.valueOf(element.getAttribute("local-override")));
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
}
}
|
AbstractPropertyLoadingBeanDefinitionParser
|
java
|
spring-projects__spring-framework
|
framework-docs/src/main/java/org/springframework/docs/integration/jms/jmsreceivingasyncmessagelisteneradapter/DefaultTextMessageDelegate.java
|
{
"start": 794,
"end": 948
}
|
class ____ implements TextMessageDelegate {
@Override
public void receive(TextMessage message) {
// ...
}
}
// end::snippet[]
|
DefaultTextMessageDelegate
|
java
|
grpc__grpc-java
|
binder/src/androidTest/java/io/grpc/binder/BinderSecurityTest.java
|
{
"start": 1941,
"end": 12396
}
|
class ____ {
private final Context appContext = ApplicationProvider.getApplicationContext();
String[] serviceNames = new String[] {"foo", "bar", "baz"};
List<ServerServiceDefinition> serviceDefinitions = new ArrayList<>();
@Nullable ManagedChannel channel;
Map<String, MethodDescriptor<Empty, Empty>> methods = new HashMap<>();
List<MethodDescriptor<Empty, Empty>> calls = new ArrayList<>();
CountingServerInterceptor countingServerInterceptor;
@Before
public void setupServiceDefinitionsAndMethods() {
MethodDescriptor.Marshaller<Empty> marshaller =
ProtoLiteUtils.marshaller(Empty.getDefaultInstance());
for (String serviceName : serviceNames) {
ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(serviceName);
for (int i = 0; i < 2; i++) {
// Add two methods to the service.
String name = serviceName + "/method" + i;
MethodDescriptor<Empty, Empty> method =
MethodDescriptor.newBuilder(marshaller, marshaller)
.setFullMethodName(name)
.setType(MethodDescriptor.MethodType.UNARY)
.setSampledToLocalTracing(true)
.build();
ServerCallHandler<Empty, Empty> callHandler =
ServerCalls.asyncUnaryCall(
(req, respObserver) -> {
calls.add(method);
respObserver.onNext(req);
respObserver.onCompleted();
});
builder.addMethod(method, callHandler);
methods.put(name, method);
}
serviceDefinitions.add(builder.build());
}
countingServerInterceptor = new CountingServerInterceptor();
}
@After
public void tearDown() throws Exception {
if (channel != null) {
channel.shutdownNow();
}
HostServices.awaitServiceShutdown();
}
private void createChannel() throws Exception {
createChannel(SecurityPolicies.serverInternalOnly(), SecurityPolicies.internalOnly());
}
private void createChannel(ServerSecurityPolicy serverPolicy, SecurityPolicy channelPolicy)
throws Exception {
AndroidComponentAddress addr = HostServices.allocateService(appContext);
HostServices.configureService(
addr,
HostServices.serviceParamsBuilder()
.setServerFactory((service, receiver) -> buildServer(addr, receiver, serverPolicy))
.build());
channel =
BinderChannelBuilder.forAddress(addr, appContext).securityPolicy(channelPolicy).build();
}
private Server buildServer(
AndroidComponentAddress listenAddr,
IBinderReceiver receiver,
ServerSecurityPolicy serverPolicy) {
BinderServerBuilder serverBuilder = BinderServerBuilder.forAddress(listenAddr, receiver);
serverBuilder.securityPolicy(serverPolicy);
serverBuilder.intercept(countingServerInterceptor);
for (ServerServiceDefinition serviceDefinition : serviceDefinitions) {
serverBuilder.addService(serviceDefinition);
}
return serverBuilder.build();
}
private void assertCallSuccess(MethodDescriptor<Empty, Empty> method) {
assertThat(
ClientCalls.blockingUnaryCall(
channel, method, CallOptions.DEFAULT, Empty.getDefaultInstance()))
.isNotNull();
}
@CanIgnoreReturnValue
private StatusRuntimeException assertCallFailure(
MethodDescriptor<Empty, Empty> method, Status status) {
try {
ClientCalls.blockingUnaryCall(channel, method, CallOptions.DEFAULT, null);
fail("Expected call to " + method.getFullMethodName() + " to fail but it succeeded.");
throw new AssertionError(); // impossible
} catch (StatusRuntimeException sre) {
assertThat(sre.getStatus().getCode()).isEqualTo(status.getCode());
return sre;
}
}
@Test
public void testAllowedCall() throws Exception {
createChannel();
assertThat(methods).isNotEmpty();
for (MethodDescriptor<Empty, Empty> method : methods.values()) {
assertCallSuccess(method);
}
}
@Test
public void testServerDisallowsCalls() throws Exception {
createChannel(
ServerSecurityPolicy.newBuilder()
.servicePolicy("foo", policy((uid) -> false))
.servicePolicy("bar", policy((uid) -> false))
.servicePolicy("baz", policy((uid) -> false))
.build(),
SecurityPolicies.internalOnly());
assertThat(methods).isNotEmpty();
for (MethodDescriptor<Empty, Empty> method : methods.values()) {
assertCallFailure(method, Status.PERMISSION_DENIED);
}
}
@Test
public void testFailedFuturesPropagateOriginalException() throws Exception {
String errorMessage = "something went wrong";
IllegalStateException originalException = new IllegalStateException(errorMessage);
createChannel(
ServerSecurityPolicy.newBuilder()
.servicePolicy(
"foo",
new AsyncSecurityPolicy() {
@Override
public ListenableFuture<Status> checkAuthorizationAsync(int uid) {
return Futures.immediateFailedFuture(originalException);
}
})
.build(),
SecurityPolicies.internalOnly());
MethodDescriptor<Empty, Empty> method = methods.get("foo/method0");
StatusRuntimeException sre = assertCallFailure(method, Status.INTERNAL);
assertThat(sre.getStatus().getDescription()).contains(errorMessage);
}
@Test
public void testFailedFuturesAreNotCachedPermanently() throws Exception {
AtomicReference<Boolean> firstAttempt = new AtomicReference<>(true);
createChannel(
ServerSecurityPolicy.newBuilder()
.servicePolicy(
"foo",
new AsyncSecurityPolicy() {
@Override
public ListenableFuture<Status> checkAuthorizationAsync(int uid) {
if (firstAttempt.getAndSet(false)) {
return Futures.immediateFailedFuture(new IllegalStateException());
}
return Futures.immediateFuture(Status.OK);
}
})
.build(),
SecurityPolicies.internalOnly());
MethodDescriptor<Empty, Empty> method = methods.get("foo/method0");
assertCallFailure(method, Status.INTERNAL);
assertCallSuccess(method);
}
@Test
public void testCancelledFuturesAreNotCachedPermanently() throws Exception {
AtomicReference<Boolean> firstAttempt = new AtomicReference<>(true);
createChannel(
ServerSecurityPolicy.newBuilder()
.servicePolicy(
"foo",
new AsyncSecurityPolicy() {
@Override
public ListenableFuture<Status> checkAuthorizationAsync(int uid) {
if (firstAttempt.getAndSet(false)) {
return Futures.immediateCancelledFuture();
}
return Futures.immediateFuture(Status.OK);
}
})
.build(),
SecurityPolicies.internalOnly());
MethodDescriptor<Empty, Empty> method = methods.get("foo/method0");
assertCallFailure(method, Status.INTERNAL);
assertCallSuccess(method);
}
@Test
public void testClientDoesntTrustServer() throws Exception {
createChannel(SecurityPolicies.serverInternalOnly(), policy((uid) -> false));
assertThat(methods).isNotEmpty();
for (MethodDescriptor<Empty, Empty> method : methods.values()) {
assertCallFailure(method, Status.PERMISSION_DENIED);
}
}
@Test
public void testPerServicePolicy() throws Exception {
createChannel(
ServerSecurityPolicy.newBuilder()
.servicePolicy("foo", policy((uid) -> true))
.servicePolicy("bar", policy((uid) -> false))
.build(),
SecurityPolicies.internalOnly());
assertThat(methods).isNotEmpty();
for (MethodDescriptor<Empty, Empty> method : methods.values()) {
if (method.getServiceName().equals("bar")) {
assertCallFailure(method, Status.PERMISSION_DENIED);
} else {
assertCallSuccess(method);
}
}
}
@Test
public void testPerServicePolicyAsync() throws Exception {
createChannel(
ServerSecurityPolicy.newBuilder()
.servicePolicy("foo", asyncPolicy((uid) -> Futures.immediateFuture(true)))
.servicePolicy("bar", asyncPolicy((uid) -> Futures.immediateFuture(false)))
.build(),
SecurityPolicies.internalOnly());
assertThat(methods).isNotEmpty();
for (MethodDescriptor<Empty, Empty> method : methods.values()) {
if (method.getServiceName().equals("bar")) {
assertCallFailure(method, Status.PERMISSION_DENIED);
} else {
assertCallSuccess(method);
}
}
}
@Test
public void testSecurityInterceptorIsClosestToTransport() throws Exception {
createChannel(
ServerSecurityPolicy.newBuilder()
.servicePolicy("foo", policy((uid) -> true))
.servicePolicy("bar", policy((uid) -> false))
.servicePolicy("baz", policy((uid) -> false))
.build(),
SecurityPolicies.internalOnly());
assertThat(countingServerInterceptor.numInterceptedCalls).isEqualTo(0);
for (MethodDescriptor<Empty, Empty> method : methods.values()) {
try {
ClientCalls.blockingUnaryCall(channel, method, CallOptions.DEFAULT, null);
} catch (StatusRuntimeException sre) {
// Ignore.
}
}
// Only the foo calls should have made it to the user interceptor.
assertThat(countingServerInterceptor.numInterceptedCalls).isEqualTo(2);
}
private static SecurityPolicy policy(Function<Integer, Boolean> func) {
return new SecurityPolicy() {
@Override
public Status checkAuthorization(int uid) {
return func.apply(uid) ? Status.OK : Status.PERMISSION_DENIED;
}
};
}
private static AsyncSecurityPolicy asyncPolicy(
Function<Integer, ListenableFuture<Boolean>> func) {
return new AsyncSecurityPolicy() {
@Override
public ListenableFuture<Status> checkAuthorizationAsync(int uid) {
return Futures.transform(
func.apply(uid),
allowed -> allowed ? Status.OK : Status.PERMISSION_DENIED,
MoreExecutors.directExecutor());
}
};
}
private final
|
BinderSecurityTest
|
java
|
apache__kafka
|
metadata/src/main/java/org/apache/kafka/image/LocalReplicaChanges.java
|
{
"start": 1081,
"end": 3547
}
|
class ____ {
// partitions for which the broker is not a replica anymore
private final Set<TopicPartition> deletes;
// partitions for which the broker is now a leader (leader epoch bump on the leader)
private final Map<TopicPartition, PartitionInfo> electedLeaders;
// partitions for which the isr or replicas change if the broker is a leader (partition epoch bump on the leader)
private final Map<TopicPartition, PartitionInfo> leaders;
// partitions for which the broker is now a follower or follower with isr or replica updates (partition epoch bump on follower)
private final Map<TopicPartition, PartitionInfo> followers;
// The topic name -> topic id map in leaders and followers changes
private final Map<String, Uuid> topicIds;
// partitions for which directory id changes or newly added to the broker
private final Map<TopicIdPartition, Uuid> directoryIds;
LocalReplicaChanges(
Set<TopicPartition> deletes,
Map<TopicPartition, PartitionInfo> electedLeaders,
Map<TopicPartition, PartitionInfo> leaders,
Map<TopicPartition, PartitionInfo> followers,
Map<String, Uuid> topicIds,
Map<TopicIdPartition, Uuid> directoryIds
) {
this.deletes = deletes;
this.electedLeaders = electedLeaders;
this.leaders = leaders;
this.followers = followers;
this.topicIds = topicIds;
this.directoryIds = directoryIds;
}
public Set<TopicPartition> deletes() {
return deletes;
}
public Map<TopicPartition, PartitionInfo> electedLeaders() {
return electedLeaders;
}
public Map<TopicPartition, PartitionInfo> leaders() {
return leaders;
}
public Map<TopicPartition, PartitionInfo> followers() {
return followers;
}
public Map<String, Uuid> topicIds() {
return topicIds;
}
public Map<TopicIdPartition, Uuid> directoryIds() {
return directoryIds;
}
@Override
public String toString() {
return String.format(
"LocalReplicaChanges(deletes = %s, newly elected leaders = %s, leaders = %s, followers = %s, topicIds = %s, directoryIds = %s)",
deletes,
electedLeaders,
leaders,
followers,
topicIds,
directoryIds
);
}
public record PartitionInfo(Uuid topicId, PartitionRegistration partition) {
}
}
|
LocalReplicaChanges
|
java
|
apache__camel
|
core/camel-management/src/main/java/org/apache/camel/management/InstrumentationInterceptStrategy.java
|
{
"start": 1488,
"end": 3025
}
|
class ____ implements ManagementInterceptStrategy {
private final Map<NamedNode, PerformanceCounter> registeredCounters;
private final Map<Processor, KeyValueHolder<NamedNode, InstrumentationProcessor<?>>> wrappedProcessors;
public InstrumentationInterceptStrategy(Map<NamedNode, PerformanceCounter> registeredCounters,
Map<Processor, KeyValueHolder<NamedNode, InstrumentationProcessor<?>>> wrappedProcessors) {
this.registeredCounters = registeredCounters;
this.wrappedProcessors = wrappedProcessors;
}
@Override
public InstrumentationProcessor<?> createProcessor(String type) {
return new DefaultInstrumentationProcessor(type);
}
@Override
public InstrumentationProcessor<?> createProcessor(NamedNode definition, Processor target) {
InstrumentationProcessor<?> instrumentationProcessor
= new DefaultInstrumentationProcessor(definition.getShortName(), target);
PerformanceCounter counter = registeredCounters.get(definition);
if (counter != null) {
// add it to the mapping of wrappers so we can later change it to a
// decorated counter when we register the processor
KeyValueHolder<NamedNode, InstrumentationProcessor<?>> holder
= new KeyValueHolder<>(definition, instrumentationProcessor);
wrappedProcessors.put(target, holder);
}
return instrumentationProcessor;
}
}
|
InstrumentationInterceptStrategy
|
java
|
apache__flink
|
flink-end-to-end-tests/flink-plugins-test/dummy-fs/src/main/java/org/apache/flink/fs/dummy/DummyFSFileStatus.java
|
{
"start": 926,
"end": 1662
}
|
class ____ implements FileStatus {
private final Path path;
private final int length;
DummyFSFileStatus(Path path, int length) {
this.path = path;
this.length = length;
}
@Override
public long getLen() {
return length;
}
@Override
public long getBlockSize() {
return length;
}
@Override
public short getReplication() {
return 0;
}
@Override
public long getModificationTime() {
return 0;
}
@Override
public long getAccessTime() {
return 0;
}
@Override
public boolean isDir() {
return false;
}
@Override
public Path getPath() {
return path;
}
}
|
DummyFSFileStatus
|
java
|
apache__avro
|
lang/java/mapred/src/test/java/org/apache/avro/mapreduce/TestAvroMultipleOutputs.java
|
{
"start": 6086,
"end": 6398
}
|
class ____ extends Mapper<AvroKey<TextStats>, NullWritable, AvroKey<TextStats>, NullWritable> {
@Override
protected void map(AvroKey<TextStats> key, NullWritable value, Context context)
throws IOException, InterruptedException {
context.write(key, value);
}
}
private static
|
SortMapper
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/checker/TestDatasetVolumeChecker.java
|
{
"start": 6907,
"end": 10578
}
|
class ____
implements AsyncChecker<VolumeCheckContext, VolumeCheckResult> {
@Override
public Optional<ListenableFuture<VolumeCheckResult>> schedule(
Checkable<VolumeCheckContext, VolumeCheckResult> target,
VolumeCheckContext context) {
try {
return Optional.of(
Futures.immediateFuture(target.check(context)));
} catch (Exception e) {
LOG.info("check routine threw exception " + e);
return Optional.of(Futures.immediateFailedFuture(e));
}
}
@Override
public void shutdownAndWait(long timeout, TimeUnit timeUnit)
throws InterruptedException {
// Nothing to cancel.
}
}
/**
* Create a dataset with the given volumes.
*/
static FsDatasetSpi<FsVolumeSpi> makeDataset(List<FsVolumeSpi> volumes)
throws Exception {
// Create dataset and init volume health.
final FsDatasetSpi<FsVolumeSpi> dataset = mock(FsDatasetSpi.class);
final FsDatasetSpi.FsVolumeReferences references = new
FsDatasetSpi.FsVolumeReferences(volumes);
when(dataset.getFsVolumeReferences()).thenReturn(references);
return dataset;
}
static List<FsVolumeSpi> makeVolumes(
int numVolumes, VolumeCheckResult health) throws Exception {
final List<FsVolumeSpi> volumes = new ArrayList<>(numVolumes);
for (int i = 0; i < numVolumes; ++i) {
final FsVolumeSpi volume = mock(FsVolumeSpi.class);
final FsVolumeReference reference = mock(FsVolumeReference.class);
final StorageLocation location = mock(StorageLocation.class);
when(reference.getVolume()).thenReturn(volume);
when(volume.obtainReference()).thenReturn(reference);
when(volume.getStorageLocation()).thenReturn(location);
if (health != null) {
when(volume.check(any())).thenReturn(health);
} else {
final DiskErrorException de = new DiskErrorException("Fake Exception");
when(volume.check(any())).thenThrow(de);
}
volumes.add(volume);
}
return volumes;
}
@ParameterizedTest(name="{0}")
@MethodSource("data")
public void testInvalidConfigurationValues(VolumeCheckResult pExpectedVolumeHealth)
throws Exception {
initTestDatasetVolumeChecker(pExpectedVolumeHealth);
HdfsConfiguration conf = new HdfsConfiguration();
conf.setInt(DFS_DATANODE_DISK_CHECK_TIMEOUT_KEY, 0);
intercept(HadoopIllegalArgumentException.class,
"Invalid value configured for dfs.datanode.disk.check.timeout"
+ " - 0 (should be > 0)",
() -> new DatasetVolumeChecker(conf, new FakeTimer()));
conf.unset(DFS_DATANODE_DISK_CHECK_TIMEOUT_KEY);
conf.setInt(DFS_DATANODE_DISK_CHECK_MIN_GAP_KEY, -1);
intercept(HadoopIllegalArgumentException.class,
"Invalid value configured for dfs.datanode.disk.check.min.gap"
+ " - -1 (should be >= 0)",
() -> new DatasetVolumeChecker(conf, new FakeTimer()));
conf.unset(DFS_DATANODE_DISK_CHECK_MIN_GAP_KEY);
conf.setInt(DFS_DATANODE_DISK_CHECK_TIMEOUT_KEY, -1);
intercept(HadoopIllegalArgumentException.class,
"Invalid value configured for dfs.datanode.disk.check.timeout"
+ " - -1 (should be > 0)",
() -> new DatasetVolumeChecker(conf, new FakeTimer()));
conf.unset(DFS_DATANODE_DISK_CHECK_TIMEOUT_KEY);
conf.setInt(DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY, -2);
intercept(HadoopIllegalArgumentException.class,
"Invalid value configured for dfs.datanode.failed.volumes.tolerated"
+ " - -2 should be greater than or equal to -1",
() -> new DatasetVolumeChecker(conf, new FakeTimer()));
}
}
|
DummyChecker
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/impl/FunctionsRaisingIOE.java
|
{
"start": 2169,
"end": 2245
}
|
interface ____<R> {
R apply() throws IOException;
}
}
|
CallableRaisingIOE
|
java
|
apache__camel
|
components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpAcknowledgementReceiveException.java
|
{
"start": 931,
"end": 2610
}
|
class ____ extends MllpAcknowledgementException {
static final String EXCEPTION_MESSAGE = "HL7 Acknowledgment Receipt Failed";
public MllpAcknowledgementReceiveException(byte[] hl7Message, boolean logPhi) {
super(EXCEPTION_MESSAGE, hl7Message, logPhi);
}
public MllpAcknowledgementReceiveException(byte[] hl7Message, byte[] hl7Acknowledgement, boolean logPhi) {
super(EXCEPTION_MESSAGE, hl7Message, hl7Acknowledgement, logPhi);
}
public MllpAcknowledgementReceiveException(byte[] hl7Message, Throwable cause, boolean logPhi) {
super(EXCEPTION_MESSAGE, hl7Message, cause, logPhi);
}
public MllpAcknowledgementReceiveException(byte[] hl7Message, byte[] hl7Acknowledgement, Throwable cause, boolean logPhi) {
super(EXCEPTION_MESSAGE, hl7Message, hl7Acknowledgement, cause, logPhi);
}
public MllpAcknowledgementReceiveException(String message, byte[] hl7Message, boolean logPhi) {
super(message, hl7Message, logPhi);
}
public MllpAcknowledgementReceiveException(String message, byte[] hl7Message, byte[] hl7Acknowledgement, boolean logPhi) {
super(message, hl7Message, hl7Acknowledgement, logPhi);
}
public MllpAcknowledgementReceiveException(String message, byte[] hl7Message, Throwable cause, boolean logPhi) {
super(message, hl7Message, cause, logPhi);
}
public MllpAcknowledgementReceiveException(String message, byte[] hl7Message, byte[] hl7Acknowledgement, Throwable cause,
boolean logPhi) {
super(message, hl7Message, hl7Acknowledgement, cause, logPhi);
}
}
|
MllpAcknowledgementReceiveException
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/execution/ExtensionContextStoreTests.java
|
{
"start": 1292,
"end": 3659
}
|
class ____ {
private static final String KEY = "key";
private static final String VALUE = "value";
private final NamespacedHierarchicalStore<Namespace> parentStore = new NamespacedHierarchicalStore<>(null);
private final NamespacedHierarchicalStore<Namespace> localStore = new NamespacedHierarchicalStore<>(parentStore);
private final Store store = new NamespaceAwareStore(localStore, Namespace.GLOBAL);
@Test
void getOrDefaultWithNoValuePresent() {
assertThat(store.get(KEY)).isNull();
assertThat(store.getOrDefault(KEY, boolean.class, true)).isTrue();
assertThat(store.getOrDefault(KEY, String.class, VALUE)).isEqualTo(VALUE);
}
@Test
void getOrDefaultRequestingIncompatibleType() {
localStore.put(Namespace.GLOBAL, KEY, VALUE);
assertThat(store.get(KEY)).isEqualTo(VALUE);
Exception exception = assertThrows(ExtensionContextException.class,
() -> store.getOrDefault(KEY, boolean.class, true));
assertThat(exception) //
.hasMessageContaining("is not of required type") //
.hasCauseInstanceOf(NamespacedHierarchicalStoreException.class) //
.hasStackTraceContaining(NamespacedHierarchicalStore.class.getName());
}
@Test
void getOrDefaultWithValueInLocalStore() {
localStore.put(Namespace.GLOBAL, KEY, VALUE);
assertThat(store.get(KEY)).isEqualTo(VALUE);
assertThat(store.getOrDefault(KEY, String.class, VALUE)).isEqualTo(VALUE);
}
@Test
void getOrDefaultWithValueInParentStore() {
parentStore.put(Namespace.GLOBAL, KEY, VALUE);
assertThat(store.get(KEY)).isEqualTo(VALUE);
assertThat(store.getOrDefault(KEY, String.class, VALUE)).isEqualTo(VALUE);
}
@SuppressWarnings("deprecation")
@Test
void getOrComputeIfAbsentWithFailingCreator() {
var invocations = new AtomicInteger();
var e1 = assertThrows(RuntimeException.class, () -> store.getOrComputeIfAbsent(KEY, __ -> {
invocations.incrementAndGet();
throw new RuntimeException();
}));
var e2 = assertThrows(RuntimeException.class, () -> store.get(KEY));
assertSame(e1, e2);
assertDoesNotThrow(localStore::close);
assertThat(invocations).hasValue(1);
}
@Test
void computeIfAbsentWithFailingCreator() {
assertThrows(RuntimeException.class, () -> store.computeIfAbsent(KEY, __ -> {
throw new RuntimeException();
}));
assertNull(store.get(KEY));
assertDoesNotThrow(localStore::close);
}
}
|
ExtensionContextStoreTests
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/beans/SyntheticInjectionPointMetadataInvalidTest.java
|
{
"start": 1273,
"end": 2039
}
|
class ____ implements BeanRegistrar {
@Override
public void register(RegistrationContext context) {
context.configure(List.class)
.addType(Type.create(DotName.createSimple(List.class.getName()), Kind.CLASS))
.addType(ParameterizedType.create(DotName.createSimple(List.class),
new Type[] { ClassType.create(DotName.createSimple(String.class)) }, null))
.creator(ListCreator.class)
.scope(ApplicationScoped.class)
// This is not legal!
.addInjectionPoint(ClassType.create(DotName.createSimple(InjectionPoint.class)))
.done();
}
}
public static
|
TestRegistrar
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/X509ConfigurerTests.java
|
{
"start": 10393,
"end": 10986
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.x509((x509) -> x509
.subjectPrincipalRegex("CN=(.*?)@example.com(?:,|$)")
);
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("rod")
.password("password")
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user);
}
}
@Configuration
@EnableWebSecurity
static
|
SubjectPrincipalRegexInLambdaConfig
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/diskbalancer/command/ExecuteCommand.java
|
{
"start": 1554,
"end": 4639
}
|
class ____ extends Command {
/**
* Constructs ExecuteCommand.
*
* @param conf - Configuration.
*/
public ExecuteCommand(Configuration conf) {
super(conf);
addValidCommandParameters(DiskBalancerCLI.EXECUTE,
"Executes a given plan.");
addValidCommandParameters(DiskBalancerCLI.SKIPDATECHECK,
"skips the date check and force execute the plan");
}
/**
* Executes the Client Calls.
*
* @param cmd - CommandLine
*/
@Override
public void execute(CommandLine cmd) throws Exception {
LOG.info("Executing \"execute plan\" command");
Preconditions.checkState(cmd.hasOption(DiskBalancerCLI.EXECUTE));
verifyCommandOptions(DiskBalancerCLI.EXECUTE, cmd);
String planFile = cmd.getOptionValue(DiskBalancerCLI.EXECUTE);
Preconditions.checkArgument(planFile != null && !planFile.isEmpty(),
"Invalid plan file specified.");
String planData = null;
try (FSDataInputStream plan = open(planFile)) {
planData = IOUtils.toString(plan, StandardCharsets.UTF_8);
}
boolean skipDateCheck = false;
if(cmd.hasOption(DiskBalancerCLI.SKIPDATECHECK)) {
skipDateCheck = true;
LOG.warn("Skipping date check on this plan. This could mean we are " +
"executing an old plan and may not be the right plan for this " +
"data node.");
}
submitPlan(planFile, planData, skipDateCheck);
}
/**
* Submits plan to a given data node.
*
* @param planFile - Plan file name
* @param planData - Plan data in json format
* @param skipDateCheck - skips date check
* @throws IOException
*/
private void submitPlan(final String planFile, final String planData,
boolean skipDateCheck)
throws IOException {
Preconditions.checkNotNull(planData);
NodePlan plan = NodePlan.parseJson(planData);
String dataNodeAddress = plan.getNodeName() + ":" + plan.getPort();
Preconditions.checkNotNull(dataNodeAddress);
ClientDatanodeProtocol dataNode = getDataNodeProxy(dataNodeAddress);
String planHash = DigestUtils.sha1Hex(planData);
try {
dataNode.submitDiskBalancerPlan(planHash, DiskBalancerCLI.PLAN_VERSION,
planFile, planData, skipDateCheck);
} catch (DiskBalancerException ex) {
LOG.error("Submitting plan on {} failed. Result: {}, Message: {}",
plan.getNodeName(), ex.getResult().toString(), ex.getMessage());
throw ex;
}
}
/**
* Gets extended help for this command.
*/
@Override
public void printHelp() {
String header = "Execute command runs a submits a plan for execution on " +
"the given data node.\n\n";
String footer = "\nExecute command submits the job to data node and " +
"returns immediately. The state of job can be monitored via query " +
"command. ";
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("hdfs diskbalancer -execute <planfile>",
header, DiskBalancerCLI.getExecuteOptions(), footer);
}
}
|
ExecuteCommand
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/resource/basic/resource/ResourceLocatorBaseResource.java
|
{
"start": 436,
"end": 2129
}
|
class ____ {
private static final Logger LOG = Logger.getLogger(ResourceLocatorBaseResource.class);
@Path("base/{param}/resources")
public Object getSubresource(@PathParam("param") String param, @Context UriInfo uri) {
LOG.debug("Here in BaseResource");
Assertions.assertEquals("1", param);
List<String> matchedURIs = uri.getMatchedURIs();
Assertions.assertEquals(2, matchedURIs.size());
Assertions.assertEquals("base/1/resources", matchedURIs.get(0));
Assertions.assertEquals("", matchedURIs.get(1));
for (String ancestor : matchedURIs)
LOG.debug(" " + ancestor);
LOG.debug("Uri Ancestors Object for Subresource.doGet():");
Assertions.assertEquals(1, uri.getMatchedResources().size());
Assertions.assertEquals(ResourceLocatorBaseResource.class, uri.getMatchedResources().get(0).getClass());
return new ResourceLocatorSubresource();
}
@Path("proxy")
public ResourceLocatorSubresource3Interface sub3() {
return (ResourceLocatorSubresource3Interface) Proxy.newProxyInstance(this.getClass().getClassLoader(),
new Class<?>[] { ResourceLocatorSubresource3Interface.class }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(new ResourceLocatorSubresource3(), args);
}
});
}
@Path("sub3/{param}/resources")
public ResourceLocatorSubresource getSubresource() {
return new ResourceLocatorSubresource();
}
}
|
ResourceLocatorBaseResource
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/hql/NestedSubqueryTest.java
|
{
"start": 1136,
"end": 4275
}
|
class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
short[] latestSQLStandards = {
2016,
2011,
2008
};
String[] comments = {
"great",
"excellent",
"awesome"
};
int post_id = 1;
int comment_id = 1;
for ( int i = 0; i < latestSQLStandards.length; i++ ) {
short sqlStandard = latestSQLStandards[i];
Post post = new Post()
.setId( post_id++ )
.setTitle( String.format( "SQL:%d", sqlStandard ) );
session.persist( post );
for ( int j = 0; j < comments.length - i; j++ ) {
session.persist(
new PostComment()
.setId( comment_id++ )
.setReview( String.format( "SQL:%d is %s!", sqlStandard, comments[j] ) )
.setPost( post )
);
}
}
session.persist(
new Post()
.setId( post_id++ )
.setTitle( "JPA 3.0" )
);
session.persist(
new Post()
.setId( post_id++ )
.setTitle( "JPA 2.2" )
);
session.persist(
new Post()
.setId( post_id++ )
.setTitle( "JPA 2.1" )
);
session.persist(
new Post()
.setId( post_id++ )
.setTitle( "JPA 2.0" )
);
session.persist(
new Post()
.setId( post_id )
.setTitle( "JPA 1.0" )
);
}
);
}
@Test
public void testNestedHqlSubQueries(SessionFactoryScope scope) {
String queryString =
" SELECT post_id AS post_id, post_title AS post_title, comment_id AS comment_id, comment_review AS comment_review "
+ " FROM ( "
+ " SELECT p.id AS post_id, p.title AS post_title, pc.id AS comment_id, pc.review AS comment_review "
+ " FROM PostComment pc JOIN pc.post p "
+ " WHERE p.title LIKE :title"
+ " ) p_pc"
+ " ORDER BY post_id, comment_id";
scope.inTransaction(
session -> {
List<Tuple> results = session.createQuery(
queryString,
Tuple.class
)
.setParameter( "title", "SQL%" )
.getResultList();
}
);
}
@Test
public void testNestedHqlSubQueries2(SessionFactoryScope scope) {
String queryString =
" SELECT post_id AS pid, post_title AS pt, comment_id AS cid, comment_review AS cr "
+ " FROM ( "
+ " SELECT post_id AS post_id, post_title AS post_title, comment_id AS comment_id,comment_review AS comment_review "
+ " FROM ( "
+ " SELECT p.id AS post_id, p.title AS post_title, pc.id AS comment_id, pc.review AS comment_review "
+ " FROM PostComment pc JOIN pc.post p WHERE p.title LIKE :title "
+ " ) p_pc"
+ " ) p_pc_r "
+ " WHERE comment_review like :review ORDER BY post_id, comment_id ";
scope.inTransaction(
session -> {
List<Tuple> results = session.createQuery(
queryString,
Tuple.class
)
.setParameter( "title", "SQL%" )
.setParameter( "review", "/%" )
.getResultList();
}
);
}
@Entity(name = "Post")
@Table(name = "post")
public static
|
NestedSubqueryTest
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/io/FileBench.java
|
{
"start": 9629,
"end": 10125
}
|
enum ____ {
seq(SequenceFileInputFormat.class, SequenceFileOutputFormat.class),
txt(TextInputFormat.class, TextOutputFormat.class);
Class<? extends InputFormat> inf;
Class<? extends OutputFormat> of;
Format(Class<? extends InputFormat> inf, Class<? extends OutputFormat> of) {
this.inf = inf;
this.of = of;
}
public void configure(JobConf job) {
if (null != inf) job.setInputFormat(inf);
if (null != of) job.setOutputFormat(of);
}
}
|
Format
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoader.java
|
{
"start": 1032,
"end": 1629
}
|
class ____ implements ConfigDataLoader<ConfigTreeConfigDataResource> {
@Override
public ConfigData load(ConfigDataLoaderContext context, ConfigTreeConfigDataResource resource)
throws IOException, ConfigDataResourceNotFoundException {
Path path = resource.getPath();
ConfigDataResourceNotFoundException.throwIfDoesNotExist(resource, path);
String name = "Config tree '" + path + "'";
ConfigTreePropertySource source = new ConfigTreePropertySource(name, path, Option.AUTO_TRIM_TRAILING_NEW_LINE);
return new ConfigData(Collections.singletonList(source));
}
}
|
ConfigTreeConfigDataLoader
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java
|
{
"start": 43139,
"end": 43299
}
|
interface ____ {
/**
* Called during the auto-detection process to decide whether
* a bean should be included.
* @param beanClass the
|
AutodetectCallback
|
java
|
google__error-prone
|
check_api/src/main/java/com/google/errorprone/scanner/ErrorProneInjector.java
|
{
"start": 1442,
"end": 1664
}
|
class ____ {
private final ClassToInstanceMap<Object> instances = MutableClassToInstanceMap.create();
/** Indicates that there was a runtime failure while providing an instance. */
public static final
|
ErrorProneInjector
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java
|
{
"start": 432,
"end": 1274
}
|
class ____ implements Foo {
@Override
public int bar(String baz, Object... args) {
return baz.length() + args.length;
}
}
@Test
public void should_call_method_with_varargs() throws Throwable {
ForwardsInvocations forwardsInvocations = new ForwardsInvocations(new FooImpl());
assertEquals(
4,
forwardsInvocations.answer(
invocationOf(Foo.class, "bar", "b", new Object[] {12, "3", 4.5})));
}
@Test
public void should_call_method_with_empty_varargs() throws Throwable {
ForwardsInvocations forwardsInvocations = new ForwardsInvocations(new FooImpl());
assertEquals(
1,
forwardsInvocations.answer(invocationOf(Foo.class, "bar", "b", new Object[] {})));
}
}
|
FooImpl
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/schema/ExpandingPreparingTable.java
|
{
"start": 1503,
"end": 3373
}
|
class ____ extends FlinkPreparingTableBase {
protected ExpandingPreparingTable(
@Nullable RelOptSchema relOptSchema,
RelDataType rowType,
Iterable<String> names,
FlinkStatistic statistic) {
super(relOptSchema, rowType, names, statistic);
}
/**
* Converts the table to a {@link RelNode}. Does not need to expand any nested scans of an
* {@link ExpandingPreparingTable}. Those will be expanded recursively.
*
* @return a relational tree
*/
protected abstract RelNode convertToRel(ToRelContext context);
@Override
public final RelNode toRel(RelOptTable.ToRelContext context) {
return expand(context);
}
private RelNode expand(RelOptTable.ToRelContext context) {
// view with hints is prohibited
if (context.getTableHints().size() > 0) {
throw new ValidationException(
String.format(
"View '%s' cannot be enriched with new options. "
+ "Hints can only be applied to tables.",
ObjectIdentifier.of(
super.names.get(0), super.names.get(1), super.names.get(2))));
}
final RelNode rel = convertToRel(context);
// Expand any views
return rel.accept(
new RelShuttleImpl() {
@Override
public RelNode visit(TableScan scan) {
final RelOptTable table = scan.getTable();
if (table instanceof ExpandingPreparingTable) {
return ((ExpandingPreparingTable) table).expand(context);
}
return super.visit(scan);
}
});
}
}
|
ExpandingPreparingTable
|
java
|
quarkusio__quarkus
|
core/deployment/src/test/java/io/quarkus/deployment/util/JandexUtilTest.java
|
{
"start": 7909,
"end": 7956
}
|
interface ____<T1, T2> {
}
public
|
Multiple
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleUsing.java
|
{
"start": 3016,
"end": 6208
}
|
class ____<T, U> extends
AtomicReference<Object> implements SingleObserver<T>, Disposable {
private static final long serialVersionUID = -5331524057054083935L;
final SingleObserver<? super T> downstream;
final Consumer<? super U> disposer;
final boolean eager;
Disposable upstream;
UsingSingleObserver(SingleObserver<? super T> actual, U resource, boolean eager,
Consumer<? super U> disposer) {
super(resource);
this.downstream = actual;
this.eager = eager;
this.disposer = disposer;
}
@Override
public void dispose() {
if (eager) {
disposeResource();
upstream.dispose();
upstream = DisposableHelper.DISPOSED;
} else {
upstream.dispose();
upstream = DisposableHelper.DISPOSED;
disposeResource();
}
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@SuppressWarnings("unchecked")
@Override
public void onSuccess(T value) {
upstream = DisposableHelper.DISPOSED;
if (eager) {
Object u = getAndSet(this);
if (u != this) {
try {
disposer.accept((U)u);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
downstream.onError(ex);
return;
}
} else {
return;
}
}
downstream.onSuccess(value);
if (!eager) {
disposeResource();
}
}
@SuppressWarnings("unchecked")
@Override
public void onError(Throwable e) {
upstream = DisposableHelper.DISPOSED;
if (eager) {
Object u = getAndSet(this);
if (u != this) {
try {
disposer.accept((U)u);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
e = new CompositeException(e, ex);
}
} else {
return;
}
}
downstream.onError(e);
if (!eager) {
disposeResource();
}
}
@SuppressWarnings("unchecked")
void disposeResource() {
Object u = getAndSet(this);
if (u != this) {
try {
disposer.accept((U)u);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
RxJavaPlugins.onError(ex);
}
}
}
}
}
|
UsingSingleObserver
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithBaseClassReferencingSubclass.java
|
{
"start": 2352,
"end": 2436
}
|
class ____ extends OwnedTable {
}
@Entity(name = "TableA")
public static
|
OwningTable
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest4.java
|
{
"start": 444,
"end": 974
}
|
class ____ {
private int id;
@JSONField(serialize = false)
private boolean m_flag;
@JSONField(serialize = false)
private int m_id2;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isFlag() {
return m_flag;
}
public void setFlag(boolean flag) {
this.m_flag = flag;
}
public int getId2() {
return m_id2;
}
public void setId2(int id2) {
this.m_id2 = id2;
}
}
}
|
VO
|
java
|
apache__camel
|
components/camel-metrics/src/test/java/org/apache/camel/component/metrics/TimerProducerTest.java
|
{
"start": 1699,
"end": 10697
}
|
class ____ {
private static final String METRICS_NAME = "metrics.name";
private static final String PROPERTY_NAME = "timer" + ":" + METRICS_NAME;
@Mock
private MetricsEndpoint endpoint;
@Mock
private Exchange exchange;
@Mock
private MetricRegistry registry;
@Mock
private Timer timer;
@Mock
private Timer.Context context;
@Mock
private Message in;
private TimerProducer producer;
@Mock
private InOrder inOrder;
@BeforeEach
public void setUp() {
producer = new TimerProducer(endpoint);
inOrder = Mockito.inOrder(endpoint, exchange, registry, timer, context, in);
lenient().when(registry.timer(METRICS_NAME)).thenReturn(timer);
lenient().when(timer.time()).thenReturn(context);
lenient().when(exchange.getIn()).thenReturn(in);
}
@Test
public void testTimerProducer() {
assertThat(producer, is(notNullValue()));
assertThat(producer.getEndpoint().equals(endpoint), is(true));
}
@Test
public void testProcessStart() throws Exception {
when(endpoint.getAction()).thenReturn(MetricsTimerAction.start);
when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class))
.thenReturn(MetricsTimerAction.start);
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(endpoint, times(1)).getAction();
inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verify(registry, times(1)).timer(METRICS_NAME);
inOrder.verify(timer, times(1)).time();
inOrder.verify(exchange, times(1)).setProperty(PROPERTY_NAME, context);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessStartWithOverride() throws Exception {
when(endpoint.getAction()).thenReturn(MetricsTimerAction.start);
when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class))
.thenReturn(MetricsTimerAction.stop);
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(endpoint, times(1)).getAction();
inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verify(context, times(1)).stop();
inOrder.verify(exchange, times(1)).removeProperty(PROPERTY_NAME);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessStop() throws Exception {
when(endpoint.getAction()).thenReturn(MetricsTimerAction.stop);
when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.stop, MetricsTimerAction.class))
.thenReturn(MetricsTimerAction.stop);
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(endpoint, times(1)).getAction();
inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.stop, MetricsTimerAction.class);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verify(context, times(1)).stop();
inOrder.verify(exchange, times(1)).removeProperty(PROPERTY_NAME);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessStopWithOverride() throws Exception {
when(endpoint.getAction()).thenReturn(MetricsTimerAction.stop);
when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.stop, MetricsTimerAction.class))
.thenReturn(MetricsTimerAction.start);
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(endpoint, times(1)).getAction();
inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.stop, MetricsTimerAction.class);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verify(registry, times(1)).timer(METRICS_NAME);
inOrder.verify(timer, times(1)).time();
inOrder.verify(exchange, times(1)).setProperty(PROPERTY_NAME, context);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessNoAction() throws Exception {
when(endpoint.getAction()).thenReturn(null);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(endpoint, times(1)).getAction();
inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, (Object) null, MetricsTimerAction.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessNoActionOverride() throws Exception {
Object action = null;
when(endpoint.getAction()).thenReturn(null);
when(in.getHeader(HEADER_TIMER_ACTION, action, MetricsTimerAction.class)).thenReturn(MetricsTimerAction.start);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(endpoint, times(1)).getAction();
inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, action, MetricsTimerAction.class);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verify(registry, times(1)).timer(METRICS_NAME);
inOrder.verify(timer, times(1)).time();
inOrder.verify(exchange, times(1)).setProperty(PROPERTY_NAME, context);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testHandleStart() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null);
producer.handleStart(exchange, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verify(registry, times(1)).timer(METRICS_NAME);
inOrder.verify(timer, times(1)).time();
inOrder.verify(exchange, times(1)).setProperty(PROPERTY_NAME, context);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testHandleStartAlreadyRunning() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
producer.handleStart(exchange, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testHandleStop() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
producer.handleStop(exchange, METRICS_NAME);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verify(context, times(1)).stop();
inOrder.verify(exchange, times(1)).removeProperty(PROPERTY_NAME);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testHandleStopContextNotFound() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null);
producer.handleStop(exchange, METRICS_NAME);
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetPropertyName() {
assertThat(producer.getPropertyName(METRICS_NAME), is("timer" + ":" + METRICS_NAME));
}
@Test
public void testGetTimerContextFromExchange() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
assertThat(producer.getTimerContextFromExchange(exchange, PROPERTY_NAME), is(context));
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetTimerContextFromExchangeNotFound() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null);
assertThat(producer.getTimerContextFromExchange(exchange, PROPERTY_NAME), is(nullValue()));
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verifyNoMoreInteractions();
}
}
|
TimerProducerTest
|
java
|
quarkusio__quarkus
|
extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/ListOfBeansTest.java
|
{
"start": 3722,
"end": 3870
}
|
class ____ {
@Bean
public Baz baz(List<Converter> converters) {
return new Baz(converters);
}
}
}
|
Configuration
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/intg/AdditionalMappingContributorTests.java
|
{
"start": 7083,
"end": 7591
}
|
class ____ {
@Id
private Integer id;
@Basic
private String name;
@SuppressWarnings("unused")
protected Entity3() {
// for use by Hibernate
}
public Entity3(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@SuppressWarnings("unused")
@Entity(name = "Entity4")
@Table(name = "Entity4")
public static
|
Entity3
|
java
|
elastic__elasticsearch
|
x-pack/plugin/blob-cache/src/main/java/org/elasticsearch/blobcache/BlobCacheUtils.java
|
{
"start": 709,
"end": 4760
}
|
class ____ {
/**
* We use {@code long} to represent offsets and lengths of files since they may be larger than 2GB, but {@code int} to represent
* offsets and lengths of arrays in memory which are limited to 2GB in size. We quite often need to convert from the file-based world
* of {@code long}s into the memory-based world of {@code int}s, knowing for certain that the result will not overflow. This method
* should be used to clarify that we're doing this.
*/
public static int toIntBytes(long l) {
return ByteSizeUnit.BYTES.toIntBytes(l);
}
/**
* Round down the size to the nearest aligned size <= size.
*/
public static long roundDownToAlignedSize(long size, long alignment) {
assert size >= 0;
assert alignment > 0;
return size / alignment * alignment;
}
/**
* Round up the size to the nearest aligned size >= size
*/
public static long roundUpToAlignedSize(long size, long alignment) {
assert size >= 0;
if (size == 0) {
return 0;
}
assert alignment > 0;
return (((size - 1) / alignment) + 1) * alignment;
}
/**
* Rounds the length up so that it is aligned on the next page size (defined by SharedBytes.PAGE_SIZE).
*/
public static long toPageAlignedSize(long length) {
int alignment = SharedBytes.PAGE_SIZE;
return roundUpToAlignedSize(length, alignment);
}
public static void throwEOF(long channelPos, long len) throws EOFException {
throw new EOFException(format("unexpected EOF reading [%d-%d]", channelPos, channelPos + len));
}
public static void ensureSeek(long pos, IndexInput input) throws IOException {
final long length = input.length();
if (pos > length) {
throw new EOFException("Reading past end of file [position=" + pos + ", length=" + input.length() + "] for " + input);
} else if (pos < 0L) {
throw new IOException("Seeking to negative position [" + pos + "] for " + input);
}
}
public static ByteRange computeRange(long rangeSize, long position, long size, long blobLength) {
return ByteRange.of(
roundDownToAlignedSize(position, rangeSize),
Math.min(roundUpToAlignedSize(position + size, rangeSize), blobLength)
);
}
public static ByteRange computeRange(long rangeSize, long position, long size) {
return ByteRange.of(roundDownToAlignedSize(position, rangeSize), roundUpToAlignedSize(position + size, rangeSize));
}
public static void ensureSlice(String sliceName, long sliceOffset, long sliceLength, IndexInput input) {
if (sliceOffset < 0 || sliceLength < 0 || sliceOffset + sliceLength > input.length()) {
throw new IllegalArgumentException(
"slice() "
+ sliceName
+ " out of bounds: offset="
+ sliceOffset
+ ",length="
+ sliceLength
+ ",fileLength="
+ input.length()
+ ": "
+ input
);
}
}
/**
* Perform a single {@code read()} from {@code inputStream} into {@code copyBuffer}, handling an EOF by throwing an {@link EOFException}
* rather than returning {@code -1}. Returns the number of bytes read, which is always positive.
*
* Most of its arguments are there simply to make the message of the {@link EOFException} more informative.
*/
public static int readSafe(InputStream inputStream, ByteBuffer copyBuffer, long rangeStart, long remaining) throws IOException {
final int len = (remaining < copyBuffer.remaining()) ? toIntBytes(remaining) : copyBuffer.remaining();
final int bytesRead = Streams.read(inputStream, copyBuffer, len);
if (bytesRead <= 0) {
throwEOF(rangeStart, remaining);
}
return bytesRead;
}
}
|
BlobCacheUtils
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/DefaultChannelSelectorTest.java
|
{
"start": 1235,
"end": 1934
}
|
class ____ {
/** This test checks the channel selection. */
@Test
void channelSelect() {
final StringValue dummyRecord = new StringValue("abc");
final RoundRobinChannelSelector<StringValue> selector = new RoundRobinChannelSelector<>();
selector.setup(2);
assertSelectedChannel(selector, dummyRecord, 0);
assertSelectedChannel(selector, dummyRecord, 1);
}
private void assertSelectedChannel(
ChannelSelector<StringValue> selector, StringValue record, int expectedChannel) {
int actualResult = selector.selectChannel(record);
assertThat(actualResult).isEqualTo(expectedChannel);
}
}
|
DefaultChannelSelectorTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/deployment/TrainedModelDeploymentTask.java
|
{
"start": 1630,
"end": 7634
}
|
class ____ extends CancellableTask implements StartTrainedModelDeploymentAction.TaskMatcher {
private static final Logger logger = LogManager.getLogger(TrainedModelDeploymentTask.class);
private volatile TaskParams params;
private final TrainedModelAssignmentNodeService trainedModelAssignmentNodeService;
private volatile boolean stopped;
private volatile boolean failed;
private final SetOnce<String> stoppedReasonHolder = new SetOnce<>();
private final SetOnce<InferenceConfig> inferenceConfigHolder = new SetOnce<>();
private final XPackLicenseState licenseState;
private final LicensedFeature.Persistent licensedFeature;
public TrainedModelDeploymentTask(
long id,
String type,
String action,
TaskId parentTask,
Map<String, String> headers,
TaskParams taskParams,
TrainedModelAssignmentNodeService trainedModelAssignmentNodeService,
XPackLicenseState licenseState,
LicensedFeature.Persistent licensedFeature
) {
super(id, type, action, MlTasks.trainedModelAssignmentTaskDescription(taskParams.getDeploymentId()), parentTask, headers);
this.params = Objects.requireNonNull(taskParams);
this.trainedModelAssignmentNodeService = ExceptionsHelper.requireNonNull(
trainedModelAssignmentNodeService,
"trainedModelAssignmentNodeService"
);
this.licenseState = licenseState;
this.licensedFeature = licensedFeature;
}
void init(InferenceConfig inferenceConfig) {
if (this.inferenceConfigHolder.trySet(inferenceConfig)) {
// track the model usage not the deployment Id
licensedFeature.startTracking(licenseState, "model-" + params.getModelId());
}
}
public void updateNumberOfAllocations(int numberOfAllocations) {
params = new TaskParams(
params.getModelId(),
params.getDeploymentId(),
params.getModelBytes(),
numberOfAllocations,
params.getThreadsPerAllocation(),
params.getQueueCapacity(),
params.getCacheSize().orElse(null),
params.getPriority(),
params.getPerDeploymentMemoryBytes(),
params.getPerAllocationMemoryBytes()
);
}
public String getModelId() {
return params.getModelId();
}
public String getDeploymentId() {
return params.getDeploymentId();
}
public long estimateMemoryUsageBytes() {
return params.estimateMemoryUsageBytes();
}
public TaskParams getParams() {
return params;
}
public void stop(String reason, boolean finishPendingWork, ActionListener<AcknowledgedResponse> listener) {
if (finishPendingWork) {
trainedModelAssignmentNodeService.gracefullyStopDeploymentAndNotify(this, reason, listener);
} else {
trainedModelAssignmentNodeService.stopDeploymentAndNotify(this, reason, listener);
}
}
public void markAsStopped(String reason) {
// stop tracking the model usage
licensedFeature.stopTracking(licenseState, "model-" + params.getModelId());
logger.debug("[{}] Stopping due to reason [{}]", getDeploymentId(), reason);
stoppedReasonHolder.trySet(reason);
stopped = true;
}
public boolean isStopped() {
return stopped;
}
public Optional<String> stoppedReason() {
return Optional.ofNullable(stoppedReasonHolder.get());
}
@Override
protected void onCancelled() {
String reason = getReasonCancelled();
logger.info("[{}] task cancelled due to reason [{}]", getDeploymentId(), reason);
stop(
reason,
true,
ActionListener.wrap(
acknowledgedResponse -> {},
e -> logger.error(() -> "[" + getDeploymentId() + "] error stopping the deployment after task cancellation", e)
)
);
}
public void infer(
NlpInferenceInput input,
InferenceConfigUpdate update,
boolean skipQueue,
TimeValue timeout,
TrainedModelPrefixStrings.PrefixType prefixType,
CancellableTask parentActionTask,
boolean chunkResponse,
ActionListener<InferenceResults> listener
) {
if (inferenceConfigHolder.get() == null) {
listener.onFailure(
ExceptionsHelper.conflictStatusException("Trained model deployment [{}] is not initialized", params.getDeploymentId())
);
return;
}
if (update.isSupported(inferenceConfigHolder.get()) == false) {
listener.onFailure(
new ElasticsearchStatusException(
"Trained model [{}] is configured for task [{}] but called with task [{}]",
RestStatus.FORBIDDEN,
params.getModelId(),
inferenceConfigHolder.get().getName(),
update.getName()
)
);
return;
}
var updatedConfig = update.isEmpty() ? inferenceConfigHolder.get() : inferenceConfigHolder.get().apply(update);
trainedModelAssignmentNodeService.infer(
this,
updatedConfig,
input,
skipQueue,
timeout,
prefixType,
parentActionTask,
chunkResponse,
listener
);
}
public Optional<ModelStats> modelStats() {
return trainedModelAssignmentNodeService.modelStats(this);
}
public void clearCache(ActionListener<AcknowledgedResponse> listener) {
trainedModelAssignmentNodeService.clearCache(this, listener);
}
public void setFailed(String reason) {
failed = true;
trainedModelAssignmentNodeService.failAssignment(this, reason);
}
public boolean isFailed() {
return failed;
}
}
|
TrainedModelDeploymentTask
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/huggingface/embeddings/HuggingFaceEmbeddingsModelTests.java
|
{
"start": 880,
"end": 3033
}
|
class ____ extends ESTestCase {
public void testThrowsURISyntaxException_ForInvalidUrl() {
var thrownException = expectThrows(IllegalArgumentException.class, () -> createModel("^^", "secret"));
assertThat(thrownException.getMessage(), containsString("unable to parse url [^^]"));
}
public static HuggingFaceEmbeddingsModel createModel(String url, String apiKey) {
return new HuggingFaceEmbeddingsModel(
"id",
TaskType.TEXT_EMBEDDING,
"service",
new HuggingFaceServiceSettings(url),
null,
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static HuggingFaceEmbeddingsModel createModel(String url, String apiKey, int tokenLimit) {
return new HuggingFaceEmbeddingsModel(
"id",
TaskType.TEXT_EMBEDDING,
"service",
new HuggingFaceServiceSettings(createUri(url), null, null, tokenLimit, null),
null,
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static HuggingFaceEmbeddingsModel createModel(String url, String apiKey, int tokenLimit, int dimensions) {
return new HuggingFaceEmbeddingsModel(
"id",
TaskType.TEXT_EMBEDDING,
"service",
new HuggingFaceServiceSettings(createUri(url), null, dimensions, tokenLimit, null),
null,
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static HuggingFaceEmbeddingsModel createModel(
String url,
String apiKey,
int tokenLimit,
int dimensions,
@Nullable SimilarityMeasure similarityMeasure
) {
return new HuggingFaceEmbeddingsModel(
"id",
TaskType.TEXT_EMBEDDING,
"service",
new HuggingFaceServiceSettings(createUri(url), similarityMeasure, dimensions, tokenLimit, null),
null,
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
}
|
HuggingFaceEmbeddingsModelTests
|
java
|
spring-projects__spring-boot
|
loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ExtractCommandTests.java
|
{
"start": 10318,
"end": 11486
}
|
class ____ {
@Test
void extractLibrariesAndCreatesApplication() throws IOException {
run(ExtractCommandTests.this.archive, "--layers");
List<String> filenames = listFilenames();
assertThat(filenames).contains("test/dependencies/lib/dependency-1.jar")
.contains("test/dependencies/lib/dependency-2.jar")
.contains("test/snapshot-dependencies/lib/dependency-3-SNAPSHOT.jar")
.contains("test/application/test.jar");
}
@Test
void extractsOnlySelectedLayers() throws IOException {
run(ExtractCommandTests.this.archive, "--layers", "dependencies");
List<String> filenames = listFilenames();
assertThat(filenames).contains("test/dependencies/lib/dependency-1.jar")
.contains("test/dependencies/lib/dependency-2.jar")
.doesNotContain("test/snapshot-dependencies/lib/dependency-3-SNAPSHOT.jar")
.doesNotContain("test/application/test.jar");
}
@Test
void failsIfLayersAreNotEnabled() throws IOException {
File archive = createArchive();
assertThatExceptionOfType(JarModeErrorException.class).isThrownBy(() -> run(archive, "--layers"))
.withMessage("Layers are not enabled");
}
}
@Nested
|
ExtractWithLayers
|
java
|
spring-projects__spring-boot
|
buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java
|
{
"start": 1946,
"end": 6307
}
|
class ____ {
private final String name;
private final String calendarName;
private final LibraryVersion version;
private final List<Group> groups;
private final String versionProperty;
private final UpgradePolicy upgradePolicy;
private final List<ProhibitedVersion> prohibitedVersions;
private final boolean considerSnapshots;
private final VersionAlignment versionAlignment;
private final BomAlignment bomAlignment;
private final String linkRootName;
private final Map<String, List<Link>> links;
/**
* Create a new {@code Library} with the given {@code name}, {@code version}, and
* {@code groups}.
* @param name name of the library
* @param calendarName name of the library as it appears in the Spring Calendar. May
* be {@code null} in which case the {@code name} is used.
* @param version version of the library
* @param groups groups in the library
* @param upgradePolicy the upgrade policy of the library, or {@code null} to use the
* containing bom's policy
* @param prohibitedVersions version of the library that are prohibited
* @param considerSnapshots whether to consider snapshots
* @param versionAlignment version alignment, if any, for the library
* @param bomAlignment the bom, if any, that this library should align with
* @param linkRootName the root name to use when generating link variable or
* {@code null} to generate one based on the library {@code name}
* @param links a list of HTTP links relevant to the library
*/
public Library(String name, String calendarName, LibraryVersion version, List<Group> groups,
UpgradePolicy upgradePolicy, List<ProhibitedVersion> prohibitedVersions, boolean considerSnapshots,
VersionAlignment versionAlignment, BomAlignment bomAlignment, String linkRootName,
Map<String, List<Link>> links) {
this.name = name;
this.calendarName = (calendarName != null) ? calendarName : name;
this.version = version;
this.groups = groups;
this.versionProperty = "Spring Boot".equals(name) ? null
: name.toLowerCase(Locale.ENGLISH).replace(' ', '-') + ".version";
this.upgradePolicy = upgradePolicy;
this.prohibitedVersions = prohibitedVersions;
this.considerSnapshots = considerSnapshots;
this.versionAlignment = versionAlignment;
this.bomAlignment = bomAlignment;
this.linkRootName = (linkRootName != null) ? linkRootName : generateLinkRootName(name);
this.links = (links != null) ? Collections.unmodifiableMap(new TreeMap<>(links)) : Collections.emptyMap();
}
private static String generateLinkRootName(String name) {
return name.replace("-", "").replace(" ", "-").toLowerCase(Locale.ROOT);
}
public String getName() {
return this.name;
}
public String getCalendarName() {
return this.calendarName;
}
public LibraryVersion getVersion() {
return this.version;
}
public List<Group> getGroups() {
return this.groups;
}
public String getVersionProperty() {
return this.versionProperty;
}
public UpgradePolicy getUpgradePolicy() {
return this.upgradePolicy;
}
public List<ProhibitedVersion> getProhibitedVersions() {
return this.prohibitedVersions;
}
public boolean isConsiderSnapshots() {
return this.considerSnapshots;
}
public VersionAlignment getVersionAlignment() {
return this.versionAlignment;
}
public String getLinkRootName() {
return this.linkRootName;
}
public BomAlignment getAlignsWithBom() {
return this.bomAlignment;
}
public Map<String, List<Link>> getLinks() {
return this.links;
}
public String getLinkUrl(String name) {
List<Link> links = getLinks(name);
if (links == null || links.isEmpty()) {
return null;
}
if (links.size() > 1) {
throw new IllegalStateException("Expected a single '%s' link for %s".formatted(name, getName()));
}
return links.get(0).url(this);
}
public List<Link> getLinks(String name) {
return this.links.get(name);
}
public String getNameAndVersion() {
return getName() + " " + getVersion();
}
public Library withVersion(LibraryVersion version) {
return new Library(this.name, this.calendarName, version, this.groups, this.upgradePolicy,
this.prohibitedVersions, this.considerSnapshots, this.versionAlignment, this.bomAlignment,
this.linkRootName, this.links);
}
/**
* A version or range of versions that are prohibited from being used in a bom.
*/
public static
|
Library
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/SetReadArgs.java
|
{
"start": 730,
"end": 1142
}
|
interface ____ {
/**
* Defines a weight multiplier for each ScoredSortedSet
*
* @param weights weight multiplier
* @return arguments object
*/
SetReadArgs weights(Double... weights);
/**
* Defines aggregation method
*
* @param aggregate score aggregation mode
* @return arguments object
*/
SetReadArgs aggregate(Aggregate aggregate);
}
|
SetReadArgs
|
java
|
spring-projects__spring-framework
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
|
{
"start": 29221,
"end": 34524
}
|
class ____ we're dealing with a FactoryBean.
if (FactoryBean.class.isAssignableFrom(beanClass)) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
// If it's a FactoryBean, we want to look at what it creates, not at the factory class.
beanClass = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();
}
}
else if (BeanFactoryUtils.isFactoryDereference(name)) {
return null;
}
}
if (beanClass == null) {
// Check decorated bean definition, if any: We assume it'll be easier
// to determine the decorated bean's type than the proxy's type.
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
return targetClass;
}
}
}
return beanClass;
}
@Override
public String[] getAliases(String name) {
String beanName = transformedBeanName(name);
List<String> aliases = new ArrayList<>();
boolean hasFactoryPrefix = (!name.isEmpty() && name.charAt(0) == BeanFactory.FACTORY_BEAN_PREFIX_CHAR);
String fullBeanName = beanName;
if (hasFactoryPrefix) {
fullBeanName = FACTORY_BEAN_PREFIX + beanName;
}
if (!fullBeanName.equals(name)) {
aliases.add(fullBeanName);
}
String[] retrievedAliases = super.getAliases(beanName);
String prefix = (hasFactoryPrefix ? FACTORY_BEAN_PREFIX : "");
for (String retrievedAlias : retrievedAliases) {
String alias = prefix + retrievedAlias;
if (!alias.equals(name)) {
aliases.add(alias);
}
}
if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null) {
aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));
}
}
return StringUtils.toStringArray(aliases);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory interface
//---------------------------------------------------------------------
@Override
public @Nullable BeanFactory getParentBeanFactory() {
return this.parentBeanFactory;
}
@Override
public boolean containsLocalBean(String name) {
String beanName = transformedBeanName(name);
return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
(!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}
//---------------------------------------------------------------------
// Implementation of ConfigurableBeanFactory interface
//---------------------------------------------------------------------
@Override
public void setParentBeanFactory(@Nullable BeanFactory parentBeanFactory) {
if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
}
if (this == parentBeanFactory) {
throw new IllegalStateException("Cannot set parent bean factory to self");
}
this.parentBeanFactory = parentBeanFactory;
}
@Override
public void setBeanClassLoader(@Nullable ClassLoader beanClassLoader) {
this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
}
@Override
public @Nullable ClassLoader getBeanClassLoader() {
return this.beanClassLoader;
}
@Override
public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) {
this.tempClassLoader = tempClassLoader;
}
@Override
public @Nullable ClassLoader getTempClassLoader() {
return this.tempClassLoader;
}
@Override
public void setCacheBeanMetadata(boolean cacheBeanMetadata) {
this.cacheBeanMetadata = cacheBeanMetadata;
}
@Override
public boolean isCacheBeanMetadata() {
return this.cacheBeanMetadata;
}
@Override
public void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver) {
this.beanExpressionResolver = resolver;
}
@Override
public @Nullable BeanExpressionResolver getBeanExpressionResolver() {
return this.beanExpressionResolver;
}
@Override
public void setConversionService(@Nullable ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public @Nullable ConversionService getConversionService() {
return this.conversionService;
}
@Override
public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
if (registrar.overridesDefaultEditors()) {
this.defaultEditorRegistrars.add(registrar);
}
else {
this.propertyEditorRegistrars.add(registrar);
}
}
/**
* Return the set of PropertyEditorRegistrars.
*/
public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {
return this.propertyEditorRegistrars;
}
@Override
public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
Assert.notNull(requiredType, "Required type must not be null");
Assert.notNull(propertyEditorClass, "PropertyEditor
|
whether
|
java
|
bumptech__glide
|
annotation/compiler/test/src/test/java/com/bumptech/glide/annotation/compiler/InvalidGlideExtensionTest.java
|
{
"start": 3965,
"end": 4681
}
|
class ____ {",
" private Extension() {}",
" public void doSomething() {}",
"}"));
assertThat(compilation).succeededWithoutWarnings();
}
@Test
public void compilation_withStaticMethod_succeeds() {
Compilation compilation =
javac()
.withProcessors(new GlideAnnotationProcessor())
.compile(
emptyAppModule(),
JavaFileObjects.forSourceLines(
"Extension",
"package com.bumptech.glide.test;",
"import com.bumptech.glide.annotation.GlideExtension;",
"@GlideExtension",
"public
|
Extension
|
java
|
spring-projects__spring-boot
|
module/spring-boot-mail/src/main/java/org/springframework/boot/mail/autoconfigure/MailProperties.java
|
{
"start": 1122,
"end": 3229
}
|
class ____ {
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* SMTP server host. For instance, 'smtp.example.com'.
*/
private @Nullable String host;
/**
* SMTP server port.
*/
private @Nullable Integer port;
/**
* Login user of the SMTP server.
*/
private @Nullable String username;
/**
* Login password of the SMTP server.
*/
private @Nullable String password;
/**
* Protocol used by the SMTP server.
*/
private String protocol = "smtp";
/**
* Default MimeMessage encoding.
*/
private Charset defaultEncoding = DEFAULT_CHARSET;
/**
* Additional JavaMail Session properties.
*/
private final Map<String, String> properties = new HashMap<>();
/**
* Session JNDI name. When set, takes precedence over other Session settings.
*/
private @Nullable String jndiName;
/**
* SSL configuration.
*/
private final Ssl ssl = new Ssl();
public @Nullable String getHost() {
return this.host;
}
public void setHost(@Nullable String host) {
this.host = host;
}
public @Nullable Integer getPort() {
return this.port;
}
public void setPort(@Nullable Integer port) {
this.port = port;
}
public @Nullable String getUsername() {
return this.username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public String getProtocol() {
return this.protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Charset getDefaultEncoding() {
return this.defaultEncoding;
}
public void setDefaultEncoding(Charset defaultEncoding) {
this.defaultEncoding = defaultEncoding;
}
public Map<String, String> getProperties() {
return this.properties;
}
public @Nullable String getJndiName() {
return this.jndiName;
}
public void setJndiName(@Nullable String jndiName) {
this.jndiName = jndiName;
}
public Ssl getSsl() {
return this.ssl;
}
public static
|
MailProperties
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/io/CloserTest.java
|
{
"start": 1299,
"end": 9834
}
|
class ____ extends TestCase {
private TestSuppressor suppressor;
@Override
protected void setUp() throws Exception {
suppressor = new TestSuppressor();
}
public void testNoExceptionsThrown() throws IOException {
Closer closer = new Closer(suppressor);
TestCloseable c1 = closer.register(TestCloseable.normal());
TestCloseable c2 = closer.register(TestCloseable.normal());
TestCloseable c3 = closer.register(TestCloseable.normal());
assertFalse(c1.isClosed());
assertFalse(c2.isClosed());
assertFalse(c3.isClosed());
closer.close();
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertTrue(c3.isClosed());
assertTrue(suppressor.suppressions.isEmpty());
}
public void testExceptionThrown_fromTryBlock() throws IOException {
Closer closer = new Closer(suppressor);
TestCloseable c1 = closer.register(TestCloseable.normal());
TestCloseable c2 = closer.register(TestCloseable.normal());
IOException exception = new IOException();
try {
try {
throw exception;
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
} catch (Throwable expected) {
assertSame(exception, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertTrue(suppressor.suppressions.isEmpty());
}
public void testExceptionThrown_whenCreatingCloseables() throws IOException {
Closer closer = new Closer(suppressor);
TestCloseable c1 = null;
TestCloseable c2 = null;
TestCloseable c3 = null;
try {
try {
c1 = closer.register(TestCloseable.normal());
c2 = closer.register(TestCloseable.normal());
c3 = closer.register(TestCloseable.throwsOnCreate());
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
} catch (Throwable expected) {
assertThat(expected).isInstanceOf(IOException.class);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertThat(c3).isNull();
assertTrue(suppressor.suppressions.isEmpty());
}
public void testExceptionThrown_whileClosingLastCloseable() throws IOException {
Closer closer = new Closer(suppressor);
IOException exception = new IOException();
// c1 is added first, closed last
TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(exception));
TestCloseable c2 = closer.register(TestCloseable.normal());
try {
closer.close();
} catch (Throwable expected) {
assertSame(exception, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertTrue(suppressor.suppressions.isEmpty());
}
public void testExceptionThrown_whileClosingFirstCloseable() throws IOException {
Closer closer = new Closer(suppressor);
IOException exception = new IOException();
// c2 is added last, closed first
TestCloseable c1 = closer.register(TestCloseable.normal());
TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(exception));
try {
closer.close();
} catch (Throwable expected) {
assertSame(exception, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertTrue(suppressor.suppressions.isEmpty());
}
public void testCloseExceptionsSuppressed_whenExceptionThrownFromTryBlock() throws IOException {
Closer closer = new Closer(suppressor);
IOException tryException = new IOException();
IOException c1Exception = new IOException();
IOException c2Exception = new IOException();
TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(c1Exception));
TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(c2Exception));
try {
try {
throw tryException;
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
} catch (Throwable expected) {
assertSame(tryException, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertSuppressed(
new Suppression(c2, tryException, c2Exception),
new Suppression(c1, tryException, c1Exception));
}
public void testCloseExceptionsSuppressed_whenExceptionThrownClosingFirstCloseable()
throws IOException {
Closer closer = new Closer(suppressor);
IOException c1Exception = new IOException();
IOException c2Exception = new IOException();
IOException c3Exception = new IOException();
TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(c1Exception));
TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(c2Exception));
TestCloseable c3 = closer.register(TestCloseable.throwsOnClose(c3Exception));
try {
closer.close();
} catch (Throwable expected) {
assertSame(c3Exception, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertTrue(c3.isClosed());
assertSuppressed(
new Suppression(c2, c3Exception, c2Exception),
new Suppression(c1, c3Exception, c1Exception));
}
public void testRuntimeExceptions() throws IOException {
Closer closer = new Closer(suppressor);
RuntimeException tryException = new RuntimeException();
RuntimeException c1Exception = new RuntimeException();
RuntimeException c2Exception = new RuntimeException();
TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(c1Exception));
TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(c2Exception));
try {
try {
throw tryException;
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
} catch (Throwable expected) {
assertSame(tryException, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertSuppressed(
new Suppression(c2, tryException, c2Exception),
new Suppression(c1, tryException, c1Exception));
}
public void testErrors() throws IOException {
Closer closer = new Closer(suppressor);
Error c1Exception = new Error();
Error c2Exception = new Error();
Error c3Exception = new Error();
TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(c1Exception));
TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(c2Exception));
TestCloseable c3 = closer.register(TestCloseable.throwsOnClose(c3Exception));
try {
closer.close();
} catch (Throwable expected) {
assertSame(c3Exception, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
assertTrue(c3.isClosed());
assertSuppressed(
new Suppression(c2, c3Exception, c2Exception),
new Suppression(c1, c3Exception, c1Exception));
}
public static void testSuppressingSuppressor() throws IOException {
Closer closer = Closer.create();
IOException thrownException = new IOException();
IOException c1Exception = new IOException();
RuntimeException c2Exception = new RuntimeException();
TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(c1Exception));
TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(c2Exception));
try {
try {
throw thrownException;
} catch (Throwable e) {
throw closer.rethrow(thrownException, IOException.class);
} finally {
assertThat(thrownException.getSuppressed()).isEmpty();
closer.close();
}
} catch (IOException expected) {
assertSame(thrownException, expected);
}
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
ImmutableSet<Throwable> suppressed = ImmutableSet.copyOf(thrownException.getSuppressed());
assertEquals(2, suppressed.size());
assertEquals(ImmutableSet.of(c1Exception, c2Exception), suppressed);
}
public void testNullCloseable() throws IOException {
Closer closer = Closer.create();
closer.register(null);
closer.close();
}
/**
* Asserts that an exception was thrown when trying to close each of the given throwables and that
* each such exception was suppressed because of the given thrown exception.
*/
private void assertSuppressed(Suppression... expected) {
assertEquals(ImmutableList.copyOf(expected), suppressor.suppressions);
}
// TODO(cpovirk): Just use addSuppressed+getSuppressed now that we can rely on it.
/** Suppressor that records suppressions. */
private static
|
CloserTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/query/ImplicitHbmResultSetMappingDescriptorBuilder.java
|
{
"start": 1181,
"end": 5204
}
|
class ____ {
private final String registrationName;
private final MetadataBuildingContext metadataBuildingContext;
private final List<ResultDescriptor> resultDescriptors;
private Map<String, Map<String, JoinDescriptor>> joinDescriptors;
private Map<String, HbmFetchParent> fetchParentByAlias;
private boolean foundEntityReturn;
private boolean foundCollectionReturn;
public ImplicitHbmResultSetMappingDescriptorBuilder(String queryRegistrationName, MetadataBuildingContext metadataBuildingContext) {
this.registrationName = queryRegistrationName;
BOOT_QUERY_LOGGER.tracef(
"Creating implicit HbmResultSetMappingDescriptor for named-native-query : %s",
registrationName
);
this.metadataBuildingContext = metadataBuildingContext;
this.resultDescriptors = new ArrayList<>();
}
public ImplicitHbmResultSetMappingDescriptorBuilder(String queryRegistrationName, int numberOfReturns, MetadataBuildingContext metadataBuildingContext) {
this.registrationName = queryRegistrationName;
this.metadataBuildingContext = metadataBuildingContext;
this.resultDescriptors = new ArrayList<>( numberOfReturns );
}
public String getRegistrationName() {
return registrationName;
}
public boolean hasAnyReturns() {
return ! resultDescriptors.isEmpty();
}
public ImplicitHbmResultSetMappingDescriptorBuilder addReturn(JaxbHbmNativeQueryScalarReturnType returnMapping) {
resultDescriptors.add(
new ScalarDescriptor(
returnMapping.getColumn(),
returnMapping.getType()
)
);
return this;
}
public ImplicitHbmResultSetMappingDescriptorBuilder addReturn(JaxbHbmNativeQueryReturnType returnMapping) {
foundEntityReturn = true;
final EntityResultDescriptor resultDescriptor = new EntityResultDescriptor(
returnMapping,
() -> joinDescriptors,
registrationName,
metadataBuildingContext
);
resultDescriptors.add( resultDescriptor );
if ( fetchParentByAlias == null ) {
fetchParentByAlias = new HashMap<>();
}
fetchParentByAlias.put( returnMapping.getAlias(), resultDescriptor );
return this;
}
public ImplicitHbmResultSetMappingDescriptorBuilder addReturn(JaxbHbmNativeQueryJoinReturnType returnMapping) {
if ( joinDescriptors == null ) {
joinDescriptors = new HashMap<>();
}
if ( fetchParentByAlias == null ) {
fetchParentByAlias = new HashMap<>();
}
collectJoinFetch(
returnMapping,
joinDescriptors,
fetchParentByAlias,
registrationName,
metadataBuildingContext
);
return this;
}
public ImplicitHbmResultSetMappingDescriptorBuilder addReturn(JaxbHbmNativeQueryCollectionLoadReturnType returnMapping) {
foundCollectionReturn = true;
final CollectionResultDescriptor resultDescriptor = new CollectionResultDescriptor(
returnMapping,
() -> joinDescriptors,
registrationName,
metadataBuildingContext
);
resultDescriptors.add( resultDescriptor );
if ( fetchParentByAlias == null ) {
fetchParentByAlias = new HashMap<>();
}
fetchParentByAlias.put( returnMapping.getAlias(), resultDescriptor );
return this;
}
public HbmResultSetMappingDescriptor build(HbmLocalMetadataBuildingContext context) {
if ( foundCollectionReturn && resultDescriptors.size() > 1 ) {
throw new MappingException(
"HBM return-collection ResultSet mapping cannot define entity or scalar returns : " + registrationName,
context.getOrigin()
);
}
if ( joinDescriptors != null ) {
if ( ! foundEntityReturn && ! foundCollectionReturn ) {
throw new MappingException(
"HBM return-join ResultSet mapping must be used in conjunction with root entity or collection return : " + registrationName,
context.getOrigin()
);
}
}
return new HbmResultSetMappingDescriptor(
registrationName,
resultDescriptors,
joinDescriptors != null
? joinDescriptors
: Collections.emptyMap(),
fetchParentByAlias != null
? fetchParentByAlias
: Collections.emptyMap()
);
}
}
|
ImplicitHbmResultSetMappingDescriptorBuilder
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.