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 | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/scripting/config/ScriptingDefaultsParser.java | {
"start": 1262,
"end": 2206
} | class ____ implements BeanDefinitionParser {
private static final String REFRESH_CHECK_DELAY_ATTRIBUTE = "refresh-check-delay";
private static final String PROXY_TARGET_CLASS_ATTRIBUTE = "proxy-target-class";
@Override
public @Nullable BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinition bd =
LangNamespaceUtils.registerScriptFactoryPostProcessorIfNecessary(parserContext.getRegistry());
String refreshCheckDelay = element.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
if (StringUtils.hasText(refreshCheckDelay)) {
bd.getPropertyValues().add("defaultRefreshCheckDelay", Long.valueOf(refreshCheckDelay));
}
String proxyTargetClass = element.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE);
if (StringUtils.hasText(proxyTargetClass)) {
bd.getPropertyValues().add("defaultProxyTargetClass", new TypedStringValue(proxyTargetClass, Boolean.class));
}
return null;
}
}
| ScriptingDefaultsParser |
java | quarkusio__quarkus | extensions/logging-json/deployment/src/test/java/io/quarkus/logging/json/SocketJsonFormatterGCPConfigTest.java | {
"start": 851,
"end": 6462
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(SocketJsonFormatterDefaultConfigTest.class)
.addAsResource(new StringAsset("""
quarkus.log.level=INFO
quarkus.log.socket.enabled=true
quarkus.log.socket.level=WARNING
quarkus.log.socket.json.enabled=true
quarkus.log.socket.json.pretty-print=true
quarkus.log.socket.json.date-format=d MMM uuuu
quarkus.log.socket.json.record-delimiter=\\n;
quarkus.log.socket.json.zone-id=UTC+05:00
quarkus.log.socket.json.exception-output-type=DETAILED_AND_FORMATTED
quarkus.log.socket.json.print-details=true
quarkus.log.socket.json.key-overrides=level=HEY
quarkus.log.socket.json.excluded-keys=timestamp,sequence
quarkus.log.socket.json.additional-field.foo.value=42
quarkus.log.socket.json.additional-field.foo.type=int
quarkus.log.socket.json.additional-field.bar.value=baz
quarkus.log.socket.json.additional-field.bar.type=string
quarkus.log.socket.json.log-format=gcp
"""), "application.properties"));
@Test
public void jsonFormatterCustomConfigurationTest() {
JsonFormatter jsonFormatter = getJsonFormatter();
assertThat(jsonFormatter.isPrettyPrint()).isTrue();
assertThat(jsonFormatter.getDateTimeFormatter().toString())
.isEqualTo("Value(DayOfMonth)' 'Text(MonthOfYear,SHORT)' 'Value(Year,4,19,EXCEEDS_PAD)");
assertThat(jsonFormatter.getDateTimeFormatter().getZone()).isEqualTo(ZoneId.of("UTC+05:00"));
assertThat(jsonFormatter.getExceptionOutputType())
.isEqualTo(StructuredFormatter.ExceptionOutputType.DETAILED_AND_FORMATTED);
assertThat(jsonFormatter.getRecordDelimiter()).isEqualTo("\n;");
assertThat(jsonFormatter.isPrintDetails()).isTrue();
assertThat(jsonFormatter.getExcludedKeys()).containsExactlyInAnyOrder("timestamp", "sequence");
assertThat(jsonFormatter.getAdditionalFields().size()).isEqualTo(5);
assertThat(jsonFormatter.getAdditionalFields().containsKey("foo")).isTrue();
assertThat(jsonFormatter.getAdditionalFields().get("foo").type()).isEqualTo(AdditionalFieldConfig.Type.INT);
assertThat(jsonFormatter.getAdditionalFields().get("foo").value()).isEqualTo("42");
assertThat(jsonFormatter.getAdditionalFields().containsKey("bar")).isTrue();
assertThat(jsonFormatter.getAdditionalFields().get("bar").type()).isEqualTo(AdditionalFieldConfig.Type.STRING);
assertThat(jsonFormatter.getAdditionalFields().get("bar").value()).isEqualTo("baz");
assertThat(jsonFormatter.getAdditionalFields().containsKey("trace")).isTrue();
assertThat(jsonFormatter.getAdditionalFields().get("trace").type()).isEqualTo(AdditionalFieldConfig.Type.STRING);
assertThat(jsonFormatter.getAdditionalFields().containsKey("spanId")).isTrue();
assertThat(jsonFormatter.getAdditionalFields().get("spanId").type()).isEqualTo(AdditionalFieldConfig.Type.STRING);
assertThat(jsonFormatter.getAdditionalFields().containsKey("traceSampled")).isTrue();
assertThat(jsonFormatter.getAdditionalFields().get("traceSampled").type()).isEqualTo(AdditionalFieldConfig.Type.STRING);
}
@Test
public void jsonFormatterOutputTest() throws Exception {
VertxMDC instance = VertxMDC.INSTANCE;
instance.put("traceId", "aaaaaaaaaaaaaaaaaaaaaaaa");
instance.put("spanId", "bbbbbbbbbbbbbb");
instance.put("sampled", "true");
JsonFormatter jsonFormatter = getJsonFormatter();
String line = jsonFormatter.format(new LogRecord(Level.INFO, "Hello, World!"));
JsonNode node = new ObjectMapper().readTree(line);
// "level" has been renamed to HEY
Assertions.assertThat(node.has("level")).isFalse();
Assertions.assertThat(node.has("HEY")).isTrue();
Assertions.assertThat(node.get("HEY").asText()).isEqualTo("INFO");
// excluded fields
Assertions.assertThat(node.has("timestamp")).isFalse();
Assertions.assertThat(node.has("sequence")).isFalse();
// additional fields
Assertions.assertThat(node.has("foo")).isTrue();
Assertions.assertThat(node.get("foo").asInt()).isEqualTo(42);
Assertions.assertThat(node.has("bar")).isTrue();
Assertions.assertThat(node.get("bar").asText()).isEqualTo("baz");
Assertions.assertThat(node.get("message").asText()).isEqualTo("Hello, World!");
Assertions.assertThat(node.get("trace").asText())
.isEqualTo("projects/quarkus-logging-json-deployment/traces/aaaaaaaaaaaaaaaaaaaaaaaa");
Assertions.assertThat(node.has("spanId")).isTrue();
Assertions.assertThat(node.get("spanId").asText()).isEqualTo("bbbbbbbbbbbbbb");
Assertions.assertThat(node.has("traceSampled")).isTrue();
Assertions.assertThat(node.get("traceSampled").asText()).isEqualTo("true");
instance.remove("traceId");
instance.remove("spanId");
instance.remove("sampled");
}
}
| SocketJsonFormatterGCPConfigTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/FeatureParserTest.java | {
"start": 286,
"end": 2570
} | class ____ extends TestCase {
public void test_AllowSingleQuotes_0() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{'a':3}");
parser.config(Feature.AllowSingleQuotes, true);
JSONObject json = (JSONObject) parser.parse();
Assert.assertEquals(1, json.size());
Assert.assertEquals(new Integer(3), (Integer) json.getInteger("a"));
}
public void test_AllowSingleQuotes_1() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{'a':'3'}");
parser.config(Feature.AllowSingleQuotes, true);
JSONObject json = (JSONObject) parser.parse();
Assert.assertEquals(1, json.size());
Assert.assertEquals("3", (String) json.get("a"));
}
public void test_AllowUnQuotedFieldNames_0() throws Exception {
DefaultJSONParser parser = new DefaultJSONParser("{a:3}");
parser.config(Feature.AllowUnQuotedFieldNames, true);
JSONObject json = (JSONObject) parser.parse();
Assert.assertEquals(1, json.size());
Assert.assertEquals(new Integer(3), (Integer) json.getInteger("a"));
}
public void test_error_0() throws Exception {
JSONException error = null;
try {
DefaultJSONParser parser = new DefaultJSONParser("{'a':3}");
parser.config(Feature.AllowSingleQuotes, false);
parser.parse();
} catch (JSONException e) {
error = e;
}
Assert.assertNotNull(error);
}
public void test_error_1() throws Exception {
JSONException error = null;
try {
DefaultJSONParser parser = new DefaultJSONParser("{\"a\":'3'}");
parser.config(Feature.AllowSingleQuotes, false);
parser.parse();
} catch (JSONException e) {
error = e;
}
Assert.assertNotNull(error);
}
public void test_error_2() throws Exception {
JSONException error = null;
try {
DefaultJSONParser parser = new DefaultJSONParser("{a:3}");
parser.config(Feature.AllowUnQuotedFieldNames, false);
parser.parse();
} catch (JSONException e) {
error = e;
}
Assert.assertNotNull(error);
}
}
| FeatureParserTest |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessor.java | {
"start": 2911,
"end": 11848
} | class ____ implements HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler {
protected final Log logger = LogFactory.getLog(getClass());
private final boolean annotationNotRequired;
/**
* Class constructor.
* @param annotationNotRequired if "true", non-simple method arguments and
* return values are considered model attributes with or without a
* {@code @ModelAttribute} annotation
*/
public ModelAttributeMethodProcessor(boolean annotationNotRequired) {
this.annotationNotRequired = annotationNotRequired;
}
/**
* Returns {@code true} if the parameter is annotated with
* {@link ModelAttribute} or, if in default resolution mode, for any
* method parameter that is not a simple type.
*/
@Override
public boolean supportsParameter(MethodParameter parameter) {
return (parameter.hasParameterAnnotation(ModelAttribute.class) ||
(this.annotationNotRequired && !BeanUtils.isSimpleProperty(parameter.getParameterType())));
}
/**
* Resolve the argument from the model or if not found instantiate it with
* its default if it is available. The model attribute is then populated
* with request values via data binding and optionally validated
* if {@code @java.validation.Valid} is present on the argument.
* @throws BindException if data binding and validation result in an error
* and the next method parameter is not of type {@link Errors}
* @throws Exception if WebDataBinder initialization fails
*/
@Override
public final @Nullable Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");
String name = ModelFactory.getNameForParameter(parameter);
ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
if (ann != null) {
mavContainer.setBinding(name, ann.binding());
}
Object attribute;
BindingResult bindingResult = null;
if (mavContainer.containsAttribute(name)) {
attribute = mavContainer.getModel().get(name);
if (attribute == null || ObjectUtils.unwrapOptional(attribute) == null) {
bindingResult = binderFactory.createBinder(webRequest, null, name).getBindingResult();
attribute = wrapAsOptionalIfNecessary(parameter, null);
}
}
else {
try {
// Mainly to allow subclasses alternative to create attribute
attribute = createAttribute(name, parameter, binderFactory, webRequest);
}
catch (MethodArgumentNotValidException ex) {
if (isBindExceptionRequired(parameter)) {
throw ex;
}
attribute = wrapAsOptionalIfNecessary(parameter, ex.getTarget());
bindingResult = ex.getBindingResult();
}
}
// No BindingResult yet, proceed with binding and validation
if (bindingResult == null) {
ResolvableType type = ResolvableType.forMethodParameter(parameter);
WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name, type);
if (attribute == null) {
constructAttribute(binder, webRequest);
attribute = wrapAsOptionalIfNecessary(parameter, binder.getTarget());
}
if (!binder.getBindingResult().hasErrors()) {
if (!mavContainer.isBindingDisabled(name)) {
bindRequestParameters(binder, webRequest);
}
validateIfApplicable(binder, parameter);
}
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
}
// Value type adaptation, also covering java.util.Optional
if (!parameter.getParameterType().isInstance(attribute)) {
attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
}
bindingResult = binder.getBindingResult();
}
// Add resolved attribute and BindingResult at the end of the model
Map<String, Object> bindingResultModel = bindingResult.getModel();
mavContainer.removeAttributes(bindingResultModel);
mavContainer.addAllAttributes(bindingResultModel);
return attribute;
}
private static @Nullable Object wrapAsOptionalIfNecessary(MethodParameter parameter, @Nullable Object target) {
return (parameter.getParameterType() == Optional.class ? Optional.ofNullable(target) : target);
}
/**
* Extension point to create the model attribute if not found in the model,
* with subsequent parameter binding through bean properties (unless suppressed).
* <p>By default, as of 6.1 this method returns {@code null} in which case
* {@link org.springframework.validation.DataBinder#construct} is used instead
* to create the model attribute. The main purpose of this method then is to
* allow to create the model attribute in some other, alternative way.
* @param attributeName the name of the attribute (never {@code null})
* @param parameter the method parameter declaration
* @param binderFactory for creating WebDataBinder instance
* @param request the current request
* @return the created model attribute, or {@code null}
*/
protected @Nullable Object createAttribute(String attributeName, MethodParameter parameter,
WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
return null;
}
/**
* Extension point to create the attribute, binding the request to constructor args.
* @param binder the data binder instance to use for the binding
* @param request the current request
* @since 6.1
*/
protected void constructAttribute(WebDataBinder binder, NativeWebRequest request) {
((WebRequestDataBinder) binder).construct(request);
}
/**
* Extension point to bind the request to the target object via setters/fields.
* @param binder the data binder instance to use for the binding
* @param request the current request
*/
protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {
((WebRequestDataBinder) binder).bind(request);
}
/**
* Validate the model attribute if applicable.
* <p>The default implementation checks for {@code @jakarta.validation.Valid},
* Spring's {@link org.springframework.validation.annotation.Validated},
* and custom annotations whose name starts with "Valid".
* @param binder the DataBinder to be used
* @param parameter the method parameter declaration
* @see WebDataBinder#validate(Object...)
* @see SmartValidator#validate(Object, Errors, Object...)
*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
for (Annotation ann : parameter.getParameterAnnotations()) {
Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann);
if (validationHints != null) {
binder.validate(validationHints);
break;
}
}
}
/**
* Whether to raise a fatal bind exception on validation errors.
* <p>The default implementation delegates to {@link #isBindExceptionRequired(MethodParameter)}.
* @param binder the data binder used to perform data binding
* @param parameter the method parameter declaration
* @return {@code true} if the next method parameter is not of type {@link Errors}
* @see #isBindExceptionRequired(MethodParameter)
*/
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) {
return isBindExceptionRequired(parameter);
}
/**
* Whether to raise a fatal bind exception on validation errors.
* @param parameter the method parameter declaration
* @return {@code true} if the next method parameter is not of type {@link Errors}
* @since 5.0
*/
protected boolean isBindExceptionRequired(MethodParameter parameter) {
int i = parameter.getParameterIndex();
Class<?>[] paramTypes = parameter.getExecutable().getParameterTypes();
boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
return !hasBindingResult;
}
/**
* Return {@code true} if there is a method-level {@code @ModelAttribute}
* or, in default resolution mode, for any return value type that is not
* a simple type.
*/
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return (returnType.hasMethodAnnotation(ModelAttribute.class) ||
(this.annotationNotRequired && !BeanUtils.isSimpleProperty(returnType.getParameterType())));
}
/**
* Add non-null return values to the {@link ModelAndViewContainer}.
*/
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue != null) {
String name = ModelFactory.getNameForReturnValue(returnValue, returnType);
mavContainer.addAttribute(name, returnValue);
}
}
}
| ModelAttributeMethodProcessor |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 85745,
"end": 86237
} | class ____ implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(String.class, Person.class));
}
@Override
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
String[] content = StringUtils.split((String) source, " ");
assertThat(content).isNotNull();
return new Person(content[0], content[1]);
}
}
static | GenericPersonConverter |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java | {
"start": 28085,
"end": 29477
} | class ____ implements BoundedType {
private final WildcardType wildcard;
public WildCardBoundedType(WildcardType wildcard) {
this.wildcard = wildcard;
}
/** @return The first bound, either a type or a reference to a TypeVariable */
@Override
public Type firstBound() {
Type[] lowerBounds = wildcard.getLowerBounds();
Type[] upperBounds = wildcard.getUpperBounds();
return lowerBounds.length != 0 ? lowerBounds[0] : upperBounds[0];
}
/** @return An empty array as, wildcard don't support multiple bounds. */
@Override
public Type[] interfaceBounds() {
return new Type[0];
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return wildcard.equals(((TypeVarBoundedType) o).typeVariable);
}
@Override
public int hashCode() {
return wildcard.hashCode();
}
@Override
public String toString() {
return "{firstBound=" + firstBound() + ", interfaceBounds=[]}";
}
public WildcardType wildCard() {
return wildcard;
}
}
}
| WildCardBoundedType |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/arithmetic/MulLongsEvaluator.java | {
"start": 1127,
"end": 5125
} | class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(MulLongsEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator lhs;
private final EvalOperator.ExpressionEvaluator rhs;
private final DriverContext driverContext;
private Warnings warnings;
public MulLongsEvaluator(Source source, EvalOperator.ExpressionEvaluator lhs,
EvalOperator.ExpressionEvaluator rhs, DriverContext driverContext) {
this.source = source;
this.lhs = lhs;
this.rhs = rhs;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (LongBlock lhsBlock = (LongBlock) lhs.eval(page)) {
try (LongBlock rhsBlock = (LongBlock) rhs.eval(page)) {
LongVector lhsVector = lhsBlock.asVector();
if (lhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
LongVector rhsVector = rhsBlock.asVector();
if (rhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
return eval(page.getPositionCount(), lhsVector, rhsVector);
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += lhs.baseRamBytesUsed();
baseRamBytesUsed += rhs.baseRamBytesUsed();
return baseRamBytesUsed;
}
public LongBlock eval(int positionCount, LongBlock lhsBlock, LongBlock rhsBlock) {
try(LongBlock.Builder result = driverContext.blockFactory().newLongBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (lhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (rhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
long lhs = lhsBlock.getLong(lhsBlock.getFirstValueIndex(p));
long rhs = rhsBlock.getLong(rhsBlock.getFirstValueIndex(p));
try {
result.appendLong(Mul.processLongs(lhs, rhs));
} catch (ArithmeticException e) {
warnings().registerException(e);
result.appendNull();
}
}
return result.build();
}
}
public LongBlock eval(int positionCount, LongVector lhsVector, LongVector rhsVector) {
try(LongBlock.Builder result = driverContext.blockFactory().newLongBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
long lhs = lhsVector.getLong(p);
long rhs = rhsVector.getLong(p);
try {
result.appendLong(Mul.processLongs(lhs, rhs));
} catch (ArithmeticException e) {
warnings().registerException(e);
result.appendNull();
}
}
return result.build();
}
}
@Override
public String toString() {
return "MulLongsEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(lhs, rhs);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static | MulLongsEvaluator |
java | elastic__elasticsearch | x-pack/plugin/migrate/src/main/java/org/elasticsearch/xpack/migrate/rest/RestGetMigrationReindexStatusAction.java | {
"start": 711,
"end": 1454
} | class ____ extends BaseRestHandler {
@Override
public String getName() {
return "get_migration_reindex_status_action";
}
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_migration/reindex/{index}/_status"));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String index = request.param("index");
GetMigrationReindexStatusAction.Request getTaskRequest = new GetMigrationReindexStatusAction.Request(index);
return channel -> client.execute(GetMigrationReindexStatusAction.INSTANCE, getTaskRequest, new RestToXContentListener<>(channel));
}
}
| RestGetMigrationReindexStatusAction |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerCoordinator.java | {
"start": 83935,
"end": 84978
} | class ____ {
private final Set<String> racks;
PartitionRackInfo(Optional<String> clientRack, PartitionInfo partition) {
if (clientRack.isPresent() && partition.replicas() != null) {
racks = Arrays.stream(partition.replicas()).map(Node::rack).collect(Collectors.toSet());
} else {
racks = Collections.emptySet();
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PartitionRackInfo)) {
return false;
}
PartitionRackInfo rackInfo = (PartitionRackInfo) o;
return Objects.equals(racks, rackInfo.racks);
}
@Override
public int hashCode() {
return Objects.hash(racks);
}
@Override
public String toString() {
return racks.isEmpty() ? "NO_RACKS" : "racks=" + racks;
}
}
private static | PartitionRackInfo |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/table/EmptyRowInTableLookup.java | {
"start": 624,
"end": 1186
} | class ____ extends RowInTableLookup {
private final BlockFactory blockFactory;
public EmptyRowInTableLookup(BlockFactory blockFactory) {
this.blockFactory = blockFactory;
}
@Override
public ReleasableIterator<IntBlock> lookup(Page page, ByteSizeValue targetBlockSize) {
return ReleasableIterator.single((IntBlock) blockFactory.newConstantNullBlock(page.getPositionCount()));
}
@Override
public void close() {}
@Override
public String toString() {
return "EmptyLookup";
}
}
| EmptyRowInTableLookup |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboContextPostProcessor.java | {
"start": 1894,
"end": 3909
} | class ____
implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware, EnvironmentAware {
/**
* The bean name of {@link DubboConfigConfigurationRegistrar}
*/
public static final String BEAN_NAME = "dubboContextPostProcessor";
private ApplicationContext applicationContext;
private ConfigurableEnvironment environment;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
ApplicationModel applicationModel = DubboBeanUtils.getApplicationModel(beanFactory);
ModuleModel moduleModel = DubboBeanUtils.getModuleModel(beanFactory);
// Initialize SpringExtensionInjector
SpringExtensionInjector.get(applicationModel).init(applicationContext);
SpringExtensionInjector.get(moduleModel).init(applicationContext);
DubboBeanUtils.getInitializationContext(beanFactory).setApplicationContext(applicationContext);
// Initialize dubbo Environment before ConfigManager
// Extract dubbo props from Spring env and put them to app config
SortedMap<String, String> dubboProperties = EnvironmentUtils.filterDubboProperties(environment);
applicationModel.getModelEnvironment().getAppConfigMap().putAll(dubboProperties);
// register ConfigManager singleton
beanFactory.registerSingleton(ConfigManager.BEAN_NAME, applicationModel.getApplicationConfigManager());
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
DubboSpringInitializer.initialize(beanDefinitionRegistry);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = (ConfigurableEnvironment) environment;
}
}
| DubboContextPostProcessor |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBGenericOptionsToDbOptionsColumnFamilyOptionsAdapter.java | {
"start": 2455,
"end": 2579
} | class ____ the translation between generic {@link Options} into {@link DBOptions} and {@link ColumnFamilyOptions}.
*/
public | do |
java | spring-projects__spring-framework | spring-jdbc/src/test/java/org/springframework/jdbc/core/BeanPropertyRowMapperTests.java | {
"start": 7054,
"end": 7118
} | interface ____ {
String value();
}
private static | MyColumnName |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ActiveMQ6EndpointBuilderFactory.java | {
"start": 24064,
"end": 25087
} | class ____ is
* good enough as subscription name). Only makes sense when listening to
* a topic (pub-sub domain), therefore this method switches the
* pubSubDomain flag as well.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param subscriptionDurable the value to set
* @return the dsl builder
*/
default ActiveMQ6EndpointConsumerBuilder subscriptionDurable(boolean subscriptionDurable) {
doSetProperty("subscriptionDurable", subscriptionDurable);
return this;
}
/**
* Set whether to make the subscription durable. The durable
* subscription name to be used can be specified through the
* subscriptionName property. Default is false. Set this to true to
* register a durable subscription, typically in combination with a
* subscriptionName value (unless your message listener | name |
java | google__guava | android/guava/src/com/google/common/io/ByteProcessor.java | {
"start": 1260,
"end": 1999
} | interface ____<T extends @Nullable Object> {
/**
* This method will be called for each chunk of bytes in an input stream. The implementation
* should process the bytes from {@code buf[off]} through {@code buf[off + len - 1]} (inclusive).
*
* @param buf the byte array containing the data to process
* @param off the initial offset into the array
* @param len the length of data to be processed
* @return true to continue processing, false to stop
*/
@CanIgnoreReturnValue // some uses know that their processor never returns false
boolean processBytes(byte[] buf, int off, int len) throws IOException;
/** Return the result of processing all the bytes. */
@ParametricNullness
T getResult();
}
| ByteProcessor |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/RestChunkedToXContentListener.java | {
"start": 1078,
"end": 2054
} | class ____<Response extends ChunkedToXContent> extends RestActionListener<Response> {
private final ToXContent.Params params;
public RestChunkedToXContentListener(RestChannel channel) {
this(channel, channel.request());
}
public RestChunkedToXContentListener(RestChannel channel, ToXContent.Params params) {
super(channel);
this.params = params;
}
@Override
protected void processResponse(Response response) throws IOException {
channel.sendResponse(
RestResponse.chunked(
getRestStatus(response),
ChunkedRestResponseBodyPart.fromXContent(response, params, channel),
releasableFromResponse(response)
)
);
}
protected Releasable releasableFromResponse(Response response) {
return null;
}
protected RestStatus getRestStatus(Response response) {
return RestStatus.OK;
}
}
| RestChunkedToXContentListener |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/cmd/DeployCommandDeclarationBuildItem.java | {
"start": 206,
"end": 455
} | class ____ extends MultiBuildItem {
private final String name;
public DeployCommandDeclarationBuildItem(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| DeployCommandDeclarationBuildItem |
java | google__guava | android/guava/src/com/google/common/collect/EmptyContiguousSet.java | {
"start": 3363,
"end": 4237
} | class ____<C extends Comparable> implements Serializable {
private final DiscreteDomain<C> domain;
private SerializedForm(DiscreteDomain<C> domain) {
this.domain = domain;
}
private Object readResolve() {
return new EmptyContiguousSet<>(domain);
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
@GwtIncompatible
@J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm<>(domain);
}
@GwtIncompatible
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@GwtIncompatible // NavigableSet
@Override
ImmutableSortedSet<C> createDescendingSet() {
return ImmutableSortedSet.emptySet(Ordering.<C>natural().reverse());
}
}
| SerializedForm |
java | quarkusio__quarkus | integration-tests/logging-panache/src/test/java/io/quarkus/logging/LoggingBean.java | {
"start": 3274,
"end": 3361
} | interface ____<T, U, V> {
void accept(T t, U u, V v);
}
static | TriConsumer |
java | elastic__elasticsearch | x-pack/plugin/kql/src/test/java/org/elasticsearch/xpack/kql/parser/KqlParserBooleanQueryTests.java | {
"start": 847,
"end": 10291
} | class ____ extends AbstractKqlParserTestCase {
public void testParseNotQuery() throws IOException {
for (String baseQuery : readQueries(SUPPORTED_QUERY_FILE_PATH)) {
if (BOOLEAN_QUERY_FILTER.test(baseQuery)) {
baseQuery = wrapWithRandomWhitespaces("(") + baseQuery + wrapWithRandomWhitespaces(")");
}
String notQuery = wrapWithRandomWhitespaces("NOT ") + baseQuery;
BoolQueryBuilder parsedQuery = asInstanceOf(BoolQueryBuilder.class, parseKqlQuery(notQuery));
assertThat(parsedQuery.filter(), empty());
assertThat(parsedQuery.should(), empty());
assertThat(parsedQuery.must(), empty());
assertThat(parsedQuery.mustNot(), hasSize(1));
assertThat(parsedQuery.mustNot(), hasItem(equalTo((parseKqlQuery(baseQuery)))));
assertThat(
parseKqlQuery("NOT" + wrapWithRandomWhitespaces("(") + baseQuery + wrapWithRandomWhitespaces(")")),
equalTo(parsedQuery)
);
}
}
public void testParseOrQuery() throws IOException {
List<String> supportedQueries = readQueries(SUPPORTED_QUERY_FILE_PATH);
for (int runs = 0; runs < 100; runs++) {
String queryA = randomFrom(supportedQueries);
String queryB = randomFrom(supportedQueries);
String orQuery = queryA + wrapWithRandomWhitespaces(randomFrom(" or ", " OR ", " Or ", " oR ")) + queryB;
BoolQueryBuilder parsedQuery = asInstanceOf(BoolQueryBuilder.class, parseKqlQuery(orQuery));
if (Stream.of(queryA, queryB).noneMatch(BOOLEAN_QUERY_FILTER)) {
// If one of the subquery is a boolean query, it is impossible to test the content of the generated query because
// operator precedence rules are applied. There are specific tests for it in testOperatorPrecedence.
assertThat(parsedQuery.filter(), empty());
assertThat(parsedQuery.must(), empty());
assertThat(parsedQuery.mustNot(), empty());
assertThat(parsedQuery.should(), hasSize(2));
assertThat(parsedQuery.minimumShouldMatch(), equalTo("1"));
assertThat(
parsedQuery.should(),
allOf(hasItem(equalTo((parseKqlQuery(queryA)))), hasItem(equalTo((parseKqlQuery(queryB)))))
);
}
}
for (int runs = 0; runs < 100; runs++) {
String queryA = randomFrom(supportedQueries);
String queryB = randomFrom(supportedQueries);
String queryC = randomFrom(supportedQueries);
String orQuery = Strings.format("%s OR %s OR %s", queryA, queryB, queryC);
BoolQueryBuilder parsedQuery = asInstanceOf(BoolQueryBuilder.class, parseKqlQuery(orQuery));
if (Stream.of(queryA, queryB, queryC).noneMatch(BOOLEAN_QUERY_FILTER)) {
// If one of the subquery is a boolean query, it is impossible to test the content of the generated query because
// operator precedence rules are applied. There are specific tests for it in testOperatorPrecedence.
assertThat(parsedQuery.should(), hasSize(3));
assertThat(
parsedQuery.should(),
allOf(
hasItem(equalTo((parseKqlQuery(queryA)))),
hasItem(equalTo((parseKqlQuery(queryB)))),
hasItem(equalTo((parseKqlQuery(queryC))))
)
);
}
}
}
public void testParseAndQuery() throws IOException {
List<String> supportedQueries = readQueries(SUPPORTED_QUERY_FILE_PATH);
for (int runs = 0; runs < 100; runs++) {
String queryA = randomFrom(supportedQueries);
String queryB = randomFrom(supportedQueries);
String andQuery = queryA + wrapWithRandomWhitespaces(randomFrom(" and ", " AND ", " And ", " anD ")) + queryB;
BoolQueryBuilder parsedQuery = asInstanceOf(BoolQueryBuilder.class, parseKqlQuery(andQuery));
if (Stream.of(queryA, queryB).noneMatch(BOOLEAN_QUERY_FILTER)) {
// If one of the subquery is a boolean query, it is impossible to test the content of the generated query because
// operator precedence rules are applied. There are specific tests for it in testOperatorPrecedence.
assertThat(parsedQuery.filter(), empty());
assertThat(parsedQuery.should(), empty());
assertThat(parsedQuery.mustNot(), empty());
assertThat(parsedQuery.must(), hasSize(2));
assertThat(parsedQuery.must(), allOf(hasItem(equalTo((parseKqlQuery(queryA)))), hasItem(equalTo((parseKqlQuery(queryB))))));
}
}
for (int runs = 0; runs < 100; runs++) {
String queryA = randomFrom(supportedQueries);
String queryB = randomFrom(supportedQueries);
String queryC = randomFrom(supportedQueries);
String andQuery = Strings.format("%s AND %s AND %s", queryA, queryB, queryC);
if (Stream.of(queryA, queryB, queryC).noneMatch(BOOLEAN_QUERY_FILTER)) {
// If one of the subquery is a boolean query, it is impossible to test the content of the generated query because
// operator precedence rules are applied. There are specific tests for it in testOperatorPrecedence.
BoolQueryBuilder parsedQuery = asInstanceOf(BoolQueryBuilder.class, parseKqlQuery(andQuery));
assertThat(parsedQuery.must(), hasSize(3));
assertThat(
parsedQuery.must(),
allOf(
hasItem(equalTo((parseKqlQuery(queryA)))),
hasItem(equalTo((parseKqlQuery(queryB)))),
hasItem(equalTo((parseKqlQuery(queryC))))
)
);
}
}
}
public void testOperatorPrecedence() throws IOException {
List<String> supportedQueries = readQueries(SUPPORTED_QUERY_FILE_PATH, Predicate.not(BOOLEAN_QUERY_FILTER));
for (int runs = 0; runs < 100; runs++) {
String queryA = randomFrom(supportedQueries);
String queryB = randomFrom(supportedQueries);
String queryC = randomFrom(supportedQueries);
// <QueryA> AND <QueryB> OR <QueryC> is equivalent to <QueryA> AND (<QueryB> OR <QueryC>)
{
QueryBuilder parsedQuery = parseKqlQuery(Strings.format("%s AND %s OR %s", queryA, queryB, queryC));
assertThat(
parsedQuery,
equalTo(
QueryBuilders.boolQuery()
.must(parseKqlQuery(queryA))
.must(
QueryBuilders.boolQuery().minimumShouldMatch(1).should(parseKqlQuery(queryB)).should(parseKqlQuery(queryC))
)
)
);
assertThat(parsedQuery, equalTo(parseKqlQuery(Strings.format("%s AND (%s OR %s)", queryA, queryB, queryC))));
}
// <QueryA> OR <QueryB> AND <QueryC> is equivalent to <QueryA> OR (<QueryB> AND <QueryC>)
{
QueryBuilder parsedQuery = parseKqlQuery(Strings.format("%s OR %s AND %s", queryA, queryB, queryC));
assertThat(
parsedQuery,
equalTo(
QueryBuilders.boolQuery()
.minimumShouldMatch(1)
.should(parseKqlQuery(queryA))
.should(QueryBuilders.boolQuery().must(parseKqlQuery(queryB)).must(parseKqlQuery(queryC)))
)
);
assertThat(parsedQuery, equalTo(parseKqlQuery(Strings.format("%s OR (%s AND %s)", queryA, queryB, queryC))));
}
// <QueryA> AND <QueryB> is equivalent to (NOT <QueryA>) AND <QueryB>
{
QueryBuilder parsedQuery = parseKqlQuery(Strings.format("NOT %s AND %s", queryA, queryB));
assertThat(
parsedQuery,
equalTo(
QueryBuilders.boolQuery().must(QueryBuilders.boolQuery().mustNot(parseKqlQuery(queryA))).must(parseKqlQuery(queryB))
)
);
assertThat(parsedQuery, equalTo(parseKqlQuery(Strings.format("(NOT %s) AND %s", queryA, queryB))));
}
// <QueryA> OR <QueryB> is equivalent to (NOT <QueryA>) OR <QueryB>
{
QueryBuilder parsedQuery = parseKqlQuery(Strings.format("NOT %s OR %s", queryA, queryB));
assertThat(
parsedQuery,
equalTo(
QueryBuilders.boolQuery()
.minimumShouldMatch(1)
.should(QueryBuilders.boolQuery().mustNot(parseKqlQuery(queryA)))
.should(parseKqlQuery(queryB))
)
);
assertThat(parsedQuery, equalTo(parseKqlQuery(Strings.format("(NOT %s) OR %s", queryA, queryB))));
}
}
}
}
| KqlParserBooleanQueryTests |
java | apache__camel | components/camel-azure/camel-azure-storage-blob/src/test/java/org/apache/camel/component/azure/storage/blob/integration/BlobChangeFeedOperationsIT.java | {
"start": 1772,
"end": 3833
} | class ____ extends Base {
private BlobChangefeedClient client;
private BlobContainerClient containerClient;
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
private String resultName = "mock:result";
@BeforeAll
public void setupClient() {
client = new BlobChangefeedClientBuilder(serviceClient)
.buildClient();
// create test container
containerClient = serviceClient.getBlobContainerClient(containerName);
containerClient.create();
}
@Test
@Disabled("It is disabled due to changefeed support in the default test account")
void testGetChangeFeed() throws IOException, InterruptedException {
// create test blobs
final String blobName = RandomStringUtils.randomAlphabetic(10);
final String data = "Hello world from my awesome tests!";
final InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
containerClient.getBlobClient(blobName).getBlockBlobClient().upload(dataStream,
BlobUtils.getInputStreamLength(dataStream));
result.expectedMessageCount(1);
// test feed
template.send("direct:getChangeFeed", exchange -> {
exchange.getIn().setHeader(BlobConstants.BLOB_NAME, blobName);
exchange.getIn().setBody("test");
});
result.assertIsSatisfied(1000);
// we have events
assertNotNull(result.getExchanges().get(0).getMessage().getBody());
}
@AfterAll
public void deleteClient() {
containerClient.delete();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:getChangeFeed")
.to("azure-storage-blob://cameldev?operation=getChangeFeed")
.to(resultName);
}
};
}
}
| BlobChangeFeedOperationsIT |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/TestVisibleTypeId.java | {
"start": 2193,
"end": 2440
} | class ____ {
public int a = 3;
@JsonTypeId
public String type = "SomeType";
}
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT,
property="type")
static | TypeIdFromFieldArray |
java | apache__camel | components/camel-micrometer-observability/src/test/java/org/apache/camel/micrometer/observability/SpanPropagationUpstreamTest.java | {
"start": 1434,
"end": 3207
} | class ____ extends MicrometerObservabilityTracerPropagationTestSupport {
@Test
void testPropagateUpstreamTraceRequest() throws IOException {
template.requestBodyAndHeader("direct:start", "sample body",
"traceparent", "00-0af044aea5c127fd5ab5f839de2b8ae2-d362a8a943c2b289-01");
Map<String, OtelTrace> traces = otelExtension.getTraces();
assertEquals(1, traces.size());
checkTrace(traces.values().iterator().next());
}
private void checkTrace(OtelTrace trace) {
List<SpanData> spans = trace.getSpans();
assertEquals(3, spans.size());
SpanData testProducer = spans.get(0);
SpanData direct = spans.get(1);
SpanData log = spans.get(2);
// Validate span completion
assertTrue(testProducer.hasEnded());
assertTrue(direct.hasEnded());
assertTrue(log.hasEnded());
// Validate same trace
assertEquals("0af044aea5c127fd5ab5f839de2b8ae2", testProducer.getTraceId());
assertEquals(testProducer.getTraceId(), direct.getTraceId());
assertEquals(direct.getTraceId(), log.getTraceId());
// Validate hierarchy
assertEquals("d362a8a943c2b289", testProducer.getParentSpanId());
assertEquals(testProducer.getSpanId(), direct.getParentSpanId());
assertEquals(direct.getSpanId(), log.getParentSpanId());
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.routeId("start")
.log("A message")
.to("log:info");
}
};
}
}
| SpanPropagationUpstreamTest |
java | google__dagger | javatests/dagger/hilt/android/UsesSharedComponent2Test.java | {
"start": 4015,
"end": 4152
} | class ____ extends Hilt_UsesSharedComponent2Test_TestActivity {
@Inject @UsesComponentQualifier String activityString;
}
}
| TestActivity |
java | apache__rocketmq | store/src/main/java/org/apache/rocketmq/store/CommitLogDispatcher.java | {
"start": 921,
"end": 1233
} | interface ____ {
/**
* Dispatch messages from store to build consume queues, indexes, and filter data
* @param request dispatch message request
* @throws RocksDBException only in rocksdb mode
*/
void dispatch(final DispatchRequest request) throws RocksDBException;
}
| CommitLogDispatcher |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/AclSetuserArgs.java | {
"start": 20141,
"end": 20603
} | class ____ implements Argument {
private final ProtocolKeyword value;
public KeywordArgument(ProtocolKeyword value) {
this.value = value;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {
args.add(value);
}
@Override
public String toString() {
return getClass().getSimpleName() + ": " + value.toString();
}
}
static | KeywordArgument |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java | {
"start": 9313,
"end": 9659
} | class ____ {
}
LauncherDiscoveryRequest request = builder.applySelectorsAndFiltersFromSuite(Suite.class).build();
List<PackageNameFilter> filters = request.getFiltersByType(PackageNameFilter.class);
assertTrue(exactlyOne(filters).apply("com.example.testcases").included());
}
@Test
void includeTags() {
@IncludeTags("test-tag")
| Suite |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java | {
"start": 263199,
"end": 263321
} | class ____ {
public String getServletPath() {
return "wibble";
}
}
// Here the declaring | HttpServletRequestWrapper |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ResourceClassOutput.java | {
"start": 1291,
"end": 2318
} | class ____ returning
* the {@link SpecialType} of the class (or {@code null})
* @param generateSource whether to also generate textual representation of the code
*/
public ResourceClassOutput(boolean applicationClass, Function<String, SpecialType> specialTypeFunction,
boolean generateSource) {
this.applicationClass = applicationClass;
this.specialTypeFunction = specialTypeFunction;
// Note that ResourceClassOutput is never used concurrently
}
@Override
public void write(String name, byte[] data) {
if (name.endsWith(".class")) {
// Gizmo 2 calls `write()` with the full file path
name = name.substring(0, name.length() - ".class".length());
}
String className = name.replace('/', '.');
resources.add(ResourceImpl.javaClass(name, data, specialTypeFunction.apply(className),
applicationClass, null));
}
List<Resource> getResources() {
return resources;
}
}
| and |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/index/seqno/RetentionLeaseUtils.java | {
"start": 642,
"end": 1611
} | class ____ {
private RetentionLeaseUtils() {
// only static methods
}
/**
* A utility method to convert a retention lease collection to a map from retention lease ID to retention lease and exclude
* the automatically-added peer-recovery retention leases
*
* @param retentionLeases the retention lease collection
* @return the map from retention lease ID to retention lease
*/
public static Map<String, RetentionLease> toMapExcludingPeerRecoveryRetentionLeases(final RetentionLeases retentionLeases) {
return retentionLeases.leases()
.stream()
.filter(l -> ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE.equals(l.source()) == false)
.collect(Collectors.toMap(RetentionLease::id, Function.identity(), (o1, o2) -> {
throw new AssertionError("unexpectedly merging " + o1 + " and " + o2);
}, LinkedHashMap::new));
}
}
| RetentionLeaseUtils |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/auth/ITestAssumeRole.java | {
"start": 25622,
"end": 34039
} | class ____ commit to "
+ path, ex);
}
}
/**
* Write some CSV data to a local file.
* @param localSrc local file
* @throws IOException failure
*/
public void writeCSVData(final File localSrc) throws IOException {
try(FileOutputStream fo = new FileOutputStream(localSrc)) {
fo.write("1, true".getBytes());
}
}
@Test
public void testPartialDelete() throws Throwable {
describe("delete with part of the child tree read only; multidelete");
skipIfS3ExpressBucket(getConfiguration());
executePartialDelete(createAssumedRoleConfig(), false);
}
@Test
public void testPartialDeleteSingleDelete() throws Throwable {
describe("delete with part of the child tree read only");
skipIfS3ExpressBucket(getConfiguration());
executePartialDelete(createAssumedRoleConfig(), true);
}
@Test
public void testBulkDeleteOnReadOnlyAccess() throws Throwable {
describe("Bulk delete with part of the child tree read only");
executeBulkDeleteOnReadOnlyFiles(createAssumedRoleConfig());
}
@Test
public void testBulkDeleteWithReadWriteAccess() throws Throwable {
describe("Bulk delete with read write access");
skipIfS3ExpressBucket(getConfiguration());
executeBulkDeleteOnSomeReadOnlyFiles(createAssumedRoleConfig());
}
/**
* Execute bulk delete on read only files and some read write files.
*/
private void executeBulkDeleteOnReadOnlyFiles(Configuration assumedRoleConfig) throws Exception {
Path destDir = methodPath();
Path readOnlyDir = new Path(destDir, "readonlyDir");
// the full FS
S3AFileSystem fs = getFileSystem();
WrappedIO.bulkDelete_delete(fs, destDir, new ArrayList<>());
bindReadOnlyRolePolicy(assumedRoleConfig, readOnlyDir);
roleFS = (S3AFileSystem) destDir.getFileSystem(assumedRoleConfig);
int bulkDeletePageSize = WrappedIO.bulkDelete_pageSize(roleFS, destDir);
int range = bulkDeletePageSize == 1 ? bulkDeletePageSize : 10;
touchFiles(fs, readOnlyDir, range);
touchFiles(roleFS, destDir, range);
FileStatus[] fileStatuses = roleFS.listStatus(readOnlyDir);
List<Path> pathsToDelete = Arrays.stream(fileStatuses)
.map(FileStatus::getPath)
.collect(Collectors.toList());
// bulk delete in the read only FS should fail.
BulkDelete bulkDelete = roleFS.createBulkDelete(readOnlyDir);
assertAccessDeniedForEachPath(bulkDelete.bulkDelete(pathsToDelete));
BulkDelete bulkDelete2 = roleFS.createBulkDelete(destDir);
assertAccessDeniedForEachPath(bulkDelete2.bulkDelete(pathsToDelete));
// delete the files in the original FS should succeed.
BulkDelete bulkDelete3 = fs.createBulkDelete(readOnlyDir);
assertSuccessfulBulkDelete(bulkDelete3.bulkDelete(pathsToDelete));
FileStatus[] fileStatusesUnderDestDir = roleFS.listStatus(destDir);
List<Path> pathsToDeleteUnderDestDir = Arrays.stream(fileStatusesUnderDestDir)
.map(FileStatus::getPath)
.collect(Collectors.toList());
BulkDelete bulkDelete4 = fs.createBulkDelete(destDir);
assertSuccessfulBulkDelete(bulkDelete4.bulkDelete(pathsToDeleteUnderDestDir));
}
/**
* Execute bulk delete on some read only files and some read write files.
*/
private void executeBulkDeleteOnSomeReadOnlyFiles(Configuration assumedRoleConfig)
throws IOException {
Path destDir = methodPath();
Path readOnlyDir = new Path(destDir, "readonlyDir");
bindReadOnlyRolePolicy(assumedRoleConfig, readOnlyDir);
roleFS = (S3AFileSystem) destDir.getFileSystem(assumedRoleConfig);
S3AFileSystem fs = getFileSystem();
if (WrappedIO.bulkDelete_pageSize(fs, destDir) == 1) {
String msg = "Skipping as this test requires more than one path to be deleted in bulk";
LOG.debug(msg);
skip(msg);
}
WrappedIO.bulkDelete_delete(fs, destDir, new ArrayList<>());
// creating 5 files in the read only dir.
int readOnlyRange = 5;
int readWriteRange = 3;
touchFiles(fs, readOnlyDir, readOnlyRange);
// creating 3 files in the base destination dir.
touchFiles(roleFS, destDir, readWriteRange);
RemoteIterator<LocatedFileStatus> locatedFileStatusRemoteIterator = roleFS.listFiles(destDir, true);
List<Path> pathsToDelete2 = new ArrayList<>();
while (locatedFileStatusRemoteIterator.hasNext()) {
pathsToDelete2.add(locatedFileStatusRemoteIterator.next().getPath());
}
Assertions.assertThat(pathsToDelete2.size())
.describedAs("Number of paths to delete in base destination dir")
.isEqualTo(readOnlyRange + readWriteRange);
BulkDelete bulkDelete5 = roleFS.createBulkDelete(destDir);
List<Map.Entry<Path, String>> entries = bulkDelete5.bulkDelete(pathsToDelete2);
Assertions.assertThat(entries.size())
.describedAs("Number of error entries in bulk delete result")
.isEqualTo(readOnlyRange);
assertAccessDeniedForEachPath(entries);
// delete the files in the original FS should succeed.
BulkDelete bulkDelete6 = fs.createBulkDelete(destDir);
assertSuccessfulBulkDelete(bulkDelete6.bulkDelete(pathsToDelete2));
}
/**
* Bind a read only role policy to a directory to the FS conf.
*/
private static void bindReadOnlyRolePolicy(Configuration assumedRoleConfig,
Path readOnlyDir)
throws JsonProcessingException {
bindRolePolicyStatements(assumedRoleConfig, STATEMENT_ALLOW_KMS_RW,
statement(true, S3_ALL_BUCKETS, S3_ALL_OPERATIONS),
STATEMENT_S3EXPRESS,
new Statement(Effects.Deny)
.addActions(S3_PATH_WRITE_OPERATIONS)
.addResources(directory(readOnlyDir))
);
}
/**
* Validate delete results for each path in the list
* has access denied error.
*/
private void assertAccessDeniedForEachPath(List<Map.Entry<Path, String>> entries) {
for (Map.Entry<Path, String> entry : entries) {
Assertions.assertThat(entry.getValue())
.describedAs("Error message for path %s is %s", entry.getKey(), entry.getValue())
.contains("AccessDenied");
}
}
/**
* Have a directory with full R/W permissions, but then remove
* write access underneath, and try to delete it.
* @param conf FS configuration
* @param singleDelete flag to indicate this is a single delete operation
*/
public void executePartialDelete(final Configuration conf,
final boolean singleDelete)
throws Exception {
conf.setBoolean(ENABLE_MULTI_DELETE, !singleDelete);
Path destDir = methodPath();
Path readOnlyDir = new Path(destDir, "readonlyDir");
// the full FS
S3AFileSystem fs = getFileSystem();
fs.delete(destDir, true);
bindReadOnlyRolePolicy(conf, readOnlyDir);
roleFS = (S3AFileSystem) destDir.getFileSystem(conf);
int range = 10;
touchFiles(fs, readOnlyDir, range);
touchFiles(roleFS, destDir, range);
forbidden("", () -> roleFS.delete(readOnlyDir, true));
forbidden("", () -> roleFS.delete(destDir, true));
// and although you can't delete under the path, if the file doesn't
// exist, the delete call fails fast.
Path pathWhichDoesntExist = new Path(readOnlyDir, "no-such-path");
assertFalse(roleFS.delete(pathWhichDoesntExist, true),
"deleting " + pathWhichDoesntExist);
}
/**
* Block access to bucket locations and verify that {@code getBucketLocation}
* fails -but that the bucket-info command recovers from this.
*/
@Test
public void testBucketLocationForbidden() throws Throwable {
describe("Restrict role to read only");
Configuration conf = createAssumedRoleConfig();
bindRolePolicyStatements(conf, STATEMENT_ALLOW_KMS_RW,
statement(true, S3_ALL_BUCKETS, S3_ALL_OPERATIONS),
statement(false, S3_ALL_BUCKETS, S3_GET_BUCKET_LOCATION));
Path path = methodPath();
roleFS = (S3AFileSystem) path.getFileSystem(conf);
// getBucketLocation fails with error
assumeNotS3ExpressFileSystem(roleFS);
forbidden("",
() -> roleFS.getBucketLocation());
S3GuardTool.BucketInfo infocmd = new S3GuardTool.BucketInfo(conf);
URI fsUri = getFileSystem().getUri();
String info = exec(infocmd, S3GuardTool.BucketInfo.NAME,
fsUri.toString());
Assertions.assertThat(info)
.contains(S3GuardTool.BucketInfo.LOCATION_UNKNOWN);
}
}
| for |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java | {
"start": 6271,
"end": 6416
} | interface ____ {@link CacheOperation} instance(s) based on
* a given {@link CacheAnnotationParser}.
*/
@FunctionalInterface
protected | providing |
java | apache__camel | components/camel-quartz/src/test/java/org/apache/camel/routepolicy/quartz/RouteAutoStopFalseCronScheduledPolicyTest.java | {
"start": 1149,
"end": 1956
} | class ____ extends CamelTestSupport {
@Test
public void testCronPolicy() throws Exception {
// send a message on the seda queue so we have a message to start with
template.sendBody("seda:foo", "Hello World");
getMockEndpoint("mock:foo").expectedMessageCount(1);
final CronScheduledRoutePolicy policy = new CronScheduledRoutePolicy();
policy.setRouteStartTime("*/5 * * * * ?");
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("seda:foo").routeId("foo").noAutoStartup()
.routePolicy(policy)
.to("mock:foo");
}
});
MockEndpoint.assertIsSatisfied(context);
}
}
| RouteAutoStopFalseCronScheduledPolicyTest |
java | apache__camel | components/camel-test/camel-test-main-junit5/src/main/java/org/apache/camel/test/main/junit5/Configure.java | {
"start": 1349,
"end": 1832
} | class ____/or its parent classes can be
* annotated.
* <p/>
* Be aware that only a specific signature is supported, indeed any annotated methods must have only one parameter of
* type {@link MainConfigurationProperties}.
* <p/>
* In the next example, the annotation {@code Configure} on the method {@code configureRoutesBuilder} indicates the test
* framework to call it while initializing the Camel context used for the test.
*
* <pre>
* <code>
*
* @CamelMainTest
* | and |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/HasherTests.java | {
"start": 679,
"end": 16932
} | class ____ extends ESTestCase {
public void testBcryptFamilySelfGenerated() throws Exception {
testHasherSelfGenerated(Hasher.BCRYPT);
testHasherSelfGenerated(Hasher.BCRYPT4);
testHasherSelfGenerated(Hasher.BCRYPT5);
testHasherSelfGenerated(Hasher.BCRYPT6);
testHasherSelfGenerated(Hasher.BCRYPT7);
testHasherSelfGenerated(Hasher.BCRYPT8);
testHasherSelfGenerated(Hasher.BCRYPT9);
testHasherSelfGenerated(Hasher.BCRYPT10);
testHasherSelfGenerated(Hasher.BCRYPT11);
testHasherSelfGenerated(Hasher.BCRYPT12);
testHasherSelfGenerated(Hasher.BCRYPT13);
testHasherSelfGenerated(Hasher.BCRYPT14);
}
public void testBcryptFromExternalSources() throws Exception {
check("$2b$12$0313KXrdhWp6HLREsKxW/OWJQCxy2uYprv44b8MBk6dOj3PY6WSFG", "my-password", true);
check("$2b$12$0313KXrdhWp6HLREsKxW/OWJQCxy2uYprv44b8MBk6dOj3PY6WSFG", "not-the-password", false);
check("$2b$12$4bf6s1NIUhyA5FtLn1UrpuZTByjNCC7f0r5OFJP9ra8U2LtcpcK7C", "changeme", true);
check("$2b$12$4bf6s1NIUhyA5FtLn1UrpuZTByjNCC7f0r5OFJP9ra8U2LtcpcK7C", "changed-it", false);
check("$2b$09$OLrfKSXQJxohtFnkU.VZCO1gKywaTSFi4KPHqhuyY3qetAbI8v6/S", "NjJmOWRmMjJmODEyZmQ1NjFhNWVmZmIwOWMwNjk4MmMK", true);
check("$2b$09$OLrfKSXQJxohtFnkU.VZCO1gKywaTSFi4KPHqhuyY3qetAbI8v6/S", "nJjMowrMmJjModeYzMq1nJfHnwvMzMiWowmWnJK4mMmk", false);
check("$2b$14$azbTD0EotrQtoSsxFpbx/.HG8hCAojDFmN4hsD8khuevk/9j0yPlK", "python 3.9.6; bcrypt 3.2.0", true);
check("$2a$06$aQVRp5ajsIn3fzx2MnXKy.KlhxFLHaCOh8jSElqCtmYFbRkmTy..C", "https://bcrypt-generator.com/", true);
check("$2y$10$flKBxak./o.7Hql0il/98ejdZyob67TmPhHbRy3qOnMtCBosAVSRy", "php", true);
}
public void testPBKDF2FamilySelfGenerated() throws Exception {
testHasherSelfGenerated(Hasher.PBKDF2);
testHasherSelfGenerated(Hasher.PBKDF2_1000);
testHasherSelfGenerated(Hasher.PBKDF2_10000);
testHasherSelfGenerated(Hasher.PBKDF2_50000);
testHasherSelfGenerated(Hasher.PBKDF2_100000);
testHasherSelfGenerated(Hasher.PBKDF2_500000);
testHasherSelfGenerated(Hasher.PBKDF2_1000000);
testHasherSelfGenerated(Hasher.PBKDF2_STRETCH);
testHasherSelfGenerated(Hasher.PBKDF2_STRETCH_1000);
testHasherSelfGenerated(Hasher.PBKDF2_STRETCH_10000);
testHasherSelfGenerated(Hasher.PBKDF2_STRETCH_50000);
testHasherSelfGenerated(Hasher.PBKDF2_STRETCH_100000);
testHasherSelfGenerated(Hasher.PBKDF2_STRETCH_500000);
testHasherSelfGenerated(Hasher.PBKDF2_STRETCH_1000000);
}
public void testMd5SelfGenerated() throws Exception {
testHasherSelfGenerated(Hasher.MD5);
}
public void testSha1SelfGenerated() throws Exception {
testHasherSelfGenerated(Hasher.SHA1);
}
public void testSSHA256SelfGenerated() throws Exception {
testHasherSelfGenerated(Hasher.SSHA256);
}
public void testSHA256SelfGenerated() throws Exception {
testHasherSelfGenerated(Hasher.SHA256);
}
public void testNoopSelfGenerated() throws Exception {
testHasherSelfGenerated(Hasher.NOOP);
}
public void testResolve() {
assertThat(Hasher.resolve("bcrypt"), sameInstance(Hasher.BCRYPT));
assertThat(Hasher.resolve("bcrypt4"), sameInstance(Hasher.BCRYPT4));
assertThat(Hasher.resolve("bcrypt5"), sameInstance(Hasher.BCRYPT5));
assertThat(Hasher.resolve("bcrypt6"), sameInstance(Hasher.BCRYPT6));
assertThat(Hasher.resolve("bcrypt7"), sameInstance(Hasher.BCRYPT7));
assertThat(Hasher.resolve("bcrypt8"), sameInstance(Hasher.BCRYPT8));
assertThat(Hasher.resolve("bcrypt9"), sameInstance(Hasher.BCRYPT9));
assertThat(Hasher.resolve("bcrypt10"), sameInstance(Hasher.BCRYPT));
assertThat(Hasher.resolve("bcrypt11"), sameInstance(Hasher.BCRYPT11));
assertThat(Hasher.resolve("bcrypt12"), sameInstance(Hasher.BCRYPT12));
assertThat(Hasher.resolve("bcrypt13"), sameInstance(Hasher.BCRYPT13));
assertThat(Hasher.resolve("bcrypt14"), sameInstance(Hasher.BCRYPT14));
assertThat(Hasher.resolve("pbkdf2"), sameInstance(Hasher.PBKDF2));
assertThat(Hasher.resolve("pbkdf2_1000"), sameInstance(Hasher.PBKDF2_1000));
assertThat(Hasher.resolve("pbkdf2_10000"), sameInstance(Hasher.PBKDF2));
assertThat(Hasher.resolve("pbkdf2_50000"), sameInstance(Hasher.PBKDF2_50000));
assertThat(Hasher.resolve("pbkdf2_100000"), sameInstance(Hasher.PBKDF2_100000));
assertThat(Hasher.resolve("pbkdf2_500000"), sameInstance(Hasher.PBKDF2_500000));
assertThat(Hasher.resolve("pbkdf2_1000000"), sameInstance(Hasher.PBKDF2_1000000));
assertThat(Hasher.resolve("pbkdf2_stretch"), sameInstance(Hasher.PBKDF2_STRETCH));
assertThat(Hasher.resolve("pbkdf2_stretch_1000"), sameInstance(Hasher.PBKDF2_STRETCH_1000));
assertThat(Hasher.resolve("pbkdf2_stretch_10000"), sameInstance(Hasher.PBKDF2_STRETCH_10000));
assertThat(Hasher.resolve("pbkdf2_stretch_50000"), sameInstance(Hasher.PBKDF2_STRETCH_50000));
assertThat(Hasher.resolve("pbkdf2_stretch_100000"), sameInstance(Hasher.PBKDF2_STRETCH_100000));
assertThat(Hasher.resolve("pbkdf2_stretch_500000"), sameInstance(Hasher.PBKDF2_STRETCH_500000));
assertThat(Hasher.resolve("pbkdf2_stretch_1000000"), sameInstance(Hasher.PBKDF2_STRETCH_1000000));
assertThat(Hasher.resolve("sha1"), sameInstance(Hasher.SHA1));
assertThat(Hasher.resolve("md5"), sameInstance(Hasher.MD5));
assertThat(Hasher.resolve("ssha256"), sameInstance(Hasher.SSHA256));
assertThat(Hasher.resolve("noop"), sameInstance(Hasher.NOOP));
assertThat(Hasher.resolve("clear_text"), sameInstance(Hasher.NOOP));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { Hasher.resolve("unknown_hasher"); });
assertThat(e.getMessage(), containsString("unknown hash function "));
}
public void testResolveFromHash() {
assertThat(
Hasher.resolveFromHash("$2a$10$1oZj.8KmlwiCy4DWKvDH3OU0Ko4WRF4FknyvCh3j/ZtaRCNYA6Xzm".toCharArray()),
sameInstance(Hasher.BCRYPT)
);
assertThat(
Hasher.resolveFromHash("$2a$04$GwJtIQiGMHASEYphMiCpjeZh1cDyYC5U.DKfNKa4i/y0IbOvc2LiG".toCharArray()),
sameInstance(Hasher.BCRYPT4)
);
assertThat(
Hasher.resolveFromHash("$2a$05$xLmwSB7Nw7PcqP.6hXdc4eUZbT.4.iAZ3CTPzSaUibrrYjC6Vwq1m".toCharArray()),
sameInstance(Hasher.BCRYPT5)
);
assertThat(
Hasher.resolveFromHash("$2a$06$WQX1MALAjVOhR2YKmLcHYed2oROzBl3OZPtvq3FkVZYwm9X2LVKYm".toCharArray()),
sameInstance(Hasher.BCRYPT6)
);
assertThat(
Hasher.resolveFromHash("$2a$07$Satxnu2fCvwYXpHIk8A2sO2uwROrsV7WrNiRJPq1oXEl5lc9FE.7S".toCharArray()),
sameInstance(Hasher.BCRYPT7)
);
assertThat(
Hasher.resolveFromHash("$2a$08$LLfkTt2C9TUl5sDtgqmE3uRw9nHt748d3eMSGfbFYgQQQhjbXHFo2".toCharArray()),
sameInstance(Hasher.BCRYPT8)
);
assertThat(
Hasher.resolveFromHash("$2a$09$.VCWA3yFVdd6gfI526TUrufb4TvxMuhW0jIuMfhd4/fy1Ak/zrSFe".toCharArray()),
sameInstance(Hasher.BCRYPT9)
);
assertThat(
Hasher.resolveFromHash("$2a$10$OEiXFrUUY02Nm7YsEgzFuuJ3yO3HAYzJUU7omseluy28s7FYaictu".toCharArray()),
sameInstance(Hasher.BCRYPT)
);
assertThat(
Hasher.resolveFromHash("$2a$11$Ya53LCozFlKABu05xsAbj.9xmrczyuAY/fTvxKkDiHOJc5GYcaNRy".toCharArray()),
sameInstance(Hasher.BCRYPT11)
);
assertThat(
Hasher.resolveFromHash("$2a$12$oUW2hiWBHYwbJamWi6YDPeKS2NBCvD4GR50zh9QZCcgssNFcbpg/a".toCharArray()),
sameInstance(Hasher.BCRYPT12)
);
assertThat(
Hasher.resolveFromHash("$2a$13$0PDx6mxKK4bLSgpc5H6eaeylWub7UFghjxV03lFYSz4WS4slDT30q".toCharArray()),
sameInstance(Hasher.BCRYPT13)
);
assertThat(
Hasher.resolveFromHash("$2a$14$lFyXmX7p9/FHr7W4nxTnfuCkjAoBHv6awQlv8jlKZ/YCMI65i38e6".toCharArray()),
sameInstance(Hasher.BCRYPT14)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2}1000$oNl3JWiDZhXqhrpk9Kl+T0tKpVNNV3UHNxENPePpo2M=$g9lERDX5op20eX534bHdQy7ySRwobxwtaxxsz3AYPIU=".toCharArray()
),
sameInstance(Hasher.PBKDF2_1000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2}10000$UrwrHBY4GA1na9KxRpoFkUiICTeZe+mMZCZOg6bRSLc=$1Wl32wRQ9Q3Sv1IFoNwgSrUa5YifLv0MoxAO6leyip8=".toCharArray()
),
sameInstance(Hasher.PBKDF2)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2}50000$mxa5m9AlgtKLUXKi/pE5+4w7ZexGSOtlUHD043NHVdc=$LE5Ncph672M8PtugfRgk2k3ue9qY2cKgiguuAd+e3I0=".toCharArray()
),
sameInstance(Hasher.PBKDF2_50000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2}100000$qFs8H0FjietnI7sgr/1Av4H+Z7d/9dehfZ2ptU474jk=$OFj40Ha0XcHWUXSspRx6EeXnTcuN0Nva2/i2c/hvnZE=".toCharArray()
),
sameInstance(Hasher.PBKDF2_100000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2}500000$wyttuDlppd5KYD35uDZN6vudB50Cjshm5efZhOxZZQI=$ADZpOHY6llJZsjupZCn6s4Eocg0dKKdBiNjDBYqhlzA=".toCharArray()
),
sameInstance(Hasher.PBKDF2_500000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2}1000000$UuyhtjDEzWmE2wyY80akZKPWWpy2r2X50so41YML82U=$WFasYLelqbjQwt3EqFlUcwHiC38EZC45Iu/Iz0xL1GQ=".toCharArray()
),
sameInstance(Hasher.PBKDF2_1000000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2_STRETCH}1000$sTyix9e0zNINzq2aDZ+GD5+QlO94xVyf/bv4pWNhBxo=$4KuzGPy9HXnhY3ANHn8rcIRQuJHPB6cEtLwnOhDI5d4="
.toCharArray()
),
sameInstance(Hasher.PBKDF2_STRETCH_1000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2_STRETCH}10000$8M9+Ww0xkdY250CROEutsd8UP6CrJESw7ZAFu1NGORo=$ai0gxBPtHTfZU/nbNGwL5zjC+eo2/ANQM17L/tllVeo="
.toCharArray()
),
sameInstance(Hasher.PBKDF2_STRETCH)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2_STRETCH}50000$uupwXiq8W0+jrLtC3/aqzuvyZlRarlmx1+CQGEnomlk=$by8q/+oRPPWwDE6an7B9/ndz7UZ1UQpaGY4CGurtPTI="
.toCharArray()
),
sameInstance(Hasher.PBKDF2_STRETCH_50000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2_STRETCH}100000$E9VqtV76PcrQuCZ6wOMMNvs4CMPcANTpzRw8Wjd24PU=$j56uKUvwbvmgQgNFkbV7SRQVZ2QOarokAgBeA8xcFD8="
.toCharArray()
),
sameInstance(Hasher.PBKDF2_STRETCH_100000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2_STRETCH}500000$4dpTEbu4jfjhDOjWY6xdsnxuQs4dg4QbNzZJ0Z1Tm4s=$Us/yrlCxVaW7mz0go1qIygFqGgcfUMgCZfIl2AvI4I8="
.toCharArray()
),
sameInstance(Hasher.PBKDF2_STRETCH_500000)
);
assertThat(
Hasher.resolveFromHash(
"{PBKDF2_STRETCH}1000000$eKeQvMztiIcqBynTNDFBseOBww3GBpHDZI6EPPVHYUw=$4587yrxUa02RZ1jeW1WOaMjRn5qT9iQ5/DIHk0nW2bE="
.toCharArray()
),
sameInstance(Hasher.PBKDF2_STRETCH_1000000)
);
assertThat(Hasher.resolveFromHash("notavalidhashformat".toCharArray()), sameInstance(Hasher.NOOP));
}
public void testPbkdf2ArbitrarySaltAndKeyLengths() {
// In FIPS 140 mode, passwords for PBKDF2 need to be at least 14 chars (112 bits)
assumeFalse("This should not run in FIPS mode", inFipsJvm());
// PBKDF2withHMACSHA512, 16 byte salt, 512 bits key
check(
"{PBKDF2}10000$"
+ "NUG78+T6yahKzMHPgTbFmw==$"
+ "Ohp+ZCG936Q+w1XTquEz5SmQmDUJVv5ZxilRaDPpHFRzHNDMjeFl8btefZd/0yNtfQPwpfhe5DSDFlPP9WMxEQ==",
"passw0rd",
true
);
check(
"{PBKDF2}10000$"
+ "NUG78+T6yahKzMHPgTbFmw==$"
+ "Ohp+ZCG936Q+w1XTquEz5SmQmDUJVv5ZxilRaDPpHFRzHNDMjeFl8btefZd/0yNtfQPwpfhe5DSDFlPP9WMxEQ==",
"admin",
false
);
check(
"{PBKDF2}100000$"
+ "V+G8sM59pOTQ77ElFvIvbQ==$"
+ "alomPA4LKmmu5d/y8BZI1fb5SnxxI6ClTFqe6vH3JJaz3cxrWfki5EO6Wy5eLuNr2BAdMVN0jnHGdsZzS+k+vw==",
"ginger",
true
);
// PBKDF2withHMACSHA512, 8 byte salt, 128 bits key
check("{PBKDF2}10000$vT/GxENkGSc=$4/b2cEHvSeAqzEoTM+RAYA==", "s3cr3t", true);
// PBKDF2withHMACSHA512, 64 byte salt, 512 bits key
check(
"{PBKDF2}1000$"
+ "yJ1Mdnp6AEQfWKNdo6jw6BTy1KpxsthgaOHWQGhYWrzw826GZjX9vRN6h/4jRM750WWVhju2hxAZwP7yPzYdtA==$"
+ "U1PnM55HWq6VKk/G0EpmTZJIRAfNMVpi78/cOc0I2qEGs68Ozg1Am4frXnSpb5lbundzkLxl+cg7MmAvM14JSQ==",
"somelongpasswordwith$peci@lch\u00E4rs!",
true
);
// PBKDF2withHMACSHA512, 32 byte salt, 256 bits key
check(
"{PBKDF2}50000$bjxn3/UGdT7zNtCVfgRp0REhPvLkIv4PZm9fullIQxc=$wuSFQZeOxifopubSzKbIE2xAGdxJlEcUVlqvjFU1TTI=",
"Tr0ub4dor&3",
true
);
// 12345 iterations are not supported
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
check("{PBKDF2}12345$Rvr0LPiggps=$qBVD7TdDG3mgnLI5yZuR2g==", "s3cr3t", true);
});
assertThat(e.getMessage(), containsString("unknown hash function [pbkdf2_12345]"));
// salt smaller than 8 bytes is not supported
ElasticsearchException ee = expectThrows(ElasticsearchException.class, () -> {
check("{PBKDF2}10000$erwUfw==$Pv/wuOn49EH5nY88LOtY2g==", "s3cr3t", true);
});
assertThat(ee.getMessage(), containsString("PBKDF2 salt must be at least [8 bytes] long"));
// derived key length is not multiple of 128 bits
ee = expectThrows(ElasticsearchException.class, () -> { check("{PBKDF2}10000$0jtIBOnhz7Q=$njOn++ANoMAXn0gi", "s3cr3t", true); });
assertThat(ee.getMessage(), containsString("PBKDF2 key length must be positive and multiple of [128 bits]"));
}
public void testPbkdf2WithShortPasswordThrowsInFips() {
assumeTrue("This should run only in FIPS mode", inFipsJvm());
SecureString passwd = new SecureString(randomAlphaOfLength(between(6, 13)).toCharArray());
Hasher pbkdfHasher = randomFrom(Hasher.PBKDF2, Hasher.PBKDF2_50000, Hasher.PBKDF2_1000000);
ElasticsearchException e = expectThrows(ElasticsearchException.class, () -> pbkdfHasher.hash(passwd));
assertThat(e.getMessage(), containsString("Error using PBKDF2 implementation from the selected Security Provider"));
}
private static void testHasherSelfGenerated(Hasher hasher) {
// In FIPS 140 mode, passwords for PBKDF2 need to be at least 14 chars
SecureString passwd = new SecureString(randomAlphaOfLength(between(14, 18)).toCharArray());
char[] hash = hasher.hash(passwd);
assertTrue(hasher.verify(passwd, hash));
SecureString incorrectPasswd = randomValueOtherThan(
passwd,
() -> new SecureString(randomAlphaOfLength(between(14, 18)).toCharArray())
);
assertFalse(hasher.verify(incorrectPasswd, hash));
}
private void check(String hash, String password, boolean shouldMatch) {
char[] hashChars = hash.toCharArray();
Hasher hasher = Hasher.resolveFromHash(hashChars);
assertThat(
"Verify " + password + " against " + hash + " using " + hasher.name(),
hasher.verify(new SecureString(password.toCharArray()), hashChars),
equalTo(shouldMatch)
);
}
}
| HasherTests |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSingleSingle.java | {
"start": 1399,
"end": 3324
} | class ____<T> implements Observer<T>, Disposable {
final SingleObserver<? super T> downstream;
final T defaultValue;
Disposable upstream;
T value;
boolean done;
SingleElementObserver(SingleObserver<? super T> actual, T defaultValue) {
this.downstream = actual;
this.defaultValue = defaultValue;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void dispose() {
upstream.dispose();
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public void onNext(T t) {
if (done) {
return;
}
if (value != null) {
done = true;
upstream.dispose();
downstream.onError(new IllegalArgumentException("Sequence contains more than one element!"));
return;
}
value = t;
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
done = true;
downstream.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
T v = value;
value = null;
if (v == null) {
v = defaultValue;
}
if (v != null) {
downstream.onSuccess(v);
} else {
downstream.onError(new NoSuchElementException());
}
}
}
}
| SingleElementObserver |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/config/filter/IConfigFilter.java | {
"start": 945,
"end": 1625
} | interface ____ {
/**
* Init.
*
* @param properties Filter Config
*/
void init(Properties properties);
/**
* do filter.
*
* @param request request
* @param response response
* @param filterChain filter Chain
* @throws NacosException exception
*/
void doFilter(IConfigRequest request, IConfigResponse response, IConfigFilterChain filterChain)
throws NacosException;
/**
* Get order.
*
* @return order number
*/
int getOrder();
/**
* Get filterName.
*
* @return filter name
*/
String getFilterName();
}
| IConfigFilter |
java | grpc__grpc-java | api/src/main/java/io/grpc/ManagedChannelBuilder.java | {
"start": 947,
"end": 1157
} | class ____<T extends ManagedChannelBuilder<T>> {
/**
* Creates a channel with the target's address and port number.
*
* <p>Note that there is an open JDK bug on {@link java.net.URI} | ManagedChannelBuilder |
java | quarkusio__quarkus | independent-projects/tools/analytics-common/src/test/java/io/quarkus/analytics/AnonymousUserIdTest.java | {
"start": 274,
"end": 639
} | class ____ {
@Test
void createWithNullLogger() throws IOException {
TestFileLocationsImpl fileLocations = new TestFileLocationsImpl();
fileLocations.setUuidFile(null);
AnonymousUserId anonymousUserId = AnonymousUserId.getInstance(fileLocations, MessageWriter.info());
assertNotNull(anonymousUserId);
}
}
| AnonymousUserIdTest |
java | apache__camel | components/camel-reactive-streams/src/test/java/org/apache/camel/component/reactive/streams/tck/CamelPublisherConversionVerificationTest.java | {
"start": 1369,
"end": 3189
} | class ____ extends PublisherVerification<Long> {
private CamelContext context;
public CamelPublisherConversionVerificationTest() {
super(new TestEnvironment(2000L));
}
@Override
public Publisher<Long> createPublisher(long l) {
init();
RouteBuilder builder = new RouteBuilder() {
@Override
public void configure() {
from("timer:tick?delay=500&period=50&repeatCount=" + l)
.setBody().simple("${random(1000)}")
.to("reactive-streams:prod");
}
};
try {
builder.addRoutesToCamelContext(context);
context.start();
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
Publisher<Long> pub = CamelReactiveStreams.get(context).fromStream("prod", Long.class);
return pub;
}
@Override
public long maxElementsFromPublisher() {
// It's an active publisher
return publisherUnableToSignalOnComplete(); // == Long.MAX_VALUE == unbounded
}
@Override
public Publisher<Long> createFailedPublisher() {
return null;
}
protected void init() {
tearDown();
this.context = new DefaultCamelContext();
DefaultShutdownStrategy shutdownStrategy = new DefaultShutdownStrategy();
shutdownStrategy.setShutdownNowOnTimeout(true);
shutdownStrategy.setTimeout(1);
this.context.setShutdownStrategy(shutdownStrategy);
}
@AfterTest
protected void tearDown() {
try {
if (this.context != null) {
this.context.stop();
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
| CamelPublisherConversionVerificationTest |
java | apache__flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/async/queue/StreamElementQueue.java | {
"start": 1343,
"end": 3087
} | interface ____<OUT> {
/**
* Tries to put the given element in the queue. This operation succeeds if the queue has
* capacity left and fails if the queue is full.
*
* <p>This method returns a handle to the inserted element that allows to set the result of the
* computation.
*
* @param streamElement the element to be inserted.
* @return A handle to the element if successful or {@link Optional#empty()} otherwise.
*/
Optional<ResultFuture<OUT>> tryPut(StreamElement streamElement);
/**
* Emits one completed element from the head of this queue into the given output.
*
* <p>Will not emit any element if no element has been completed (check {@link
* #hasCompletedElements()} before entering any critical section).
*
* @param output the output into which to emit
*/
void emitCompletedElement(TimestampedCollector<OUT> output);
/**
* Checks if there is at least one completed head element.
*
* @return True if there is a completed head element.
*/
boolean hasCompletedElements();
/**
* Returns the collection of {@link StreamElement} currently contained in this queue for
* checkpointing.
*
* <p>This includes all non-emitted, completed and non-completed elements.
*
* @return List of currently contained {@link StreamElement}.
*/
List<StreamElement> values();
/**
* True if the queue is empty; otherwise false.
*
* @return True if the queue is empty; otherwise false.
*/
boolean isEmpty();
/**
* Return the size of the queue.
*
* @return The number of elements contained in this queue.
*/
int size();
}
| StreamElementQueue |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/process/internal/VersionResolution.java | {
"start": 1063,
"end": 4950
} | class ____<E> implements BasicValue.Resolution<E> {
// todo (6.0) : support explicit JTD?
// todo (6.0) : support explicit STD?
public static <E> VersionResolution<E> from(
Function<TypeConfiguration, java.lang.reflect.Type> implicitJavaTypeAccess,
TimeZoneStorageType timeZoneStorageType,
MetadataBuildingContext context) {
// todo (6.0) : add support for Dialect-specific interpretation?
final var typeConfiguration = context.getBootstrapContext().getTypeConfiguration();
final var implicitJavaType = implicitJavaTypeAccess.apply( typeConfiguration );
final JavaType<E> registered = typeConfiguration.getJavaTypeRegistry().getDescriptor( implicitJavaType );
final var basicJavaType = (BasicJavaType<E>) registered;
final var recommendedJdbcType = basicJavaType.getRecommendedJdbcType(
new JdbcTypeIndicators() {
@Override
public TypeConfiguration getTypeConfiguration() {
return typeConfiguration;
}
@Override
public TemporalType getTemporalPrecision() {
// if it is a temporal version, it needs to be a TIMESTAMP
return TemporalType.TIMESTAMP;
}
@Override
public boolean isPreferJavaTimeJdbcTypesEnabled() {
return context.isPreferJavaTimeJdbcTypesEnabled();
}
@Override
public boolean isPreferNativeEnumTypesEnabled() {
return context.isPreferNativeEnumTypesEnabled();
}
@Override
public TimeZoneStorageStrategy getDefaultTimeZoneStorageStrategy() {
return BasicValue.timeZoneStorageStrategy( timeZoneStorageType, context );
}
@Override
public int getPreferredSqlTypeCodeForBoolean() {
return context.getPreferredSqlTypeCodeForBoolean();
}
@Override
public int getPreferredSqlTypeCodeForDuration() {
return context.getPreferredSqlTypeCodeForDuration();
}
@Override
public int getPreferredSqlTypeCodeForUuid() {
return context.getPreferredSqlTypeCodeForUuid();
}
@Override
public int getPreferredSqlTypeCodeForInstant() {
return context.getPreferredSqlTypeCodeForInstant();
}
@Override
public int getPreferredSqlTypeCodeForArray() {
return context.getPreferredSqlTypeCodeForArray();
}
@Override
public Dialect getDialect() {
return context.getMetadataCollector().getDatabase().getDialect();
}
}
);
final var basicTypeRegistry = typeConfiguration.getBasicTypeRegistry();
final var basicType = basicTypeRegistry.resolve( basicJavaType, recommendedJdbcType );
final var legacyType = basicTypeRegistry.getRegisteredType( basicJavaType.getJavaTypeClass() );
assert legacyType.getJdbcType().getDefaultSqlTypeCode() == recommendedJdbcType.getDefaultSqlTypeCode();
return new VersionResolution<>( basicJavaType, recommendedJdbcType, basicType, legacyType );
}
private final JavaType<E> javaType;
private final JdbcType jdbcType;
private final JdbcMapping jdbcMapping;
private final BasicType<E> legacyType;
public VersionResolution(
JavaType<E> javaType,
JdbcType jdbcType,
JdbcMapping jdbcMapping,
BasicType<E> legacyType) {
this.javaType = javaType;
this.jdbcType = jdbcType;
this.jdbcMapping = jdbcMapping;
this.legacyType = legacyType;
}
@Override
public JdbcMapping getJdbcMapping() {
return jdbcMapping;
}
@Override
public BasicType<E> getLegacyResolvedBasicType() {
return legacyType;
}
@Override
public JavaType<E> getDomainJavaType() {
return javaType;
}
@Override
public JavaType<?> getRelationalJavaType() {
return javaType;
}
@Override
public JdbcType getJdbcType() {
return jdbcType;
}
@Override
public BasicValueConverter<E,?> getValueConverter() {
return legacyType.getValueConverter();
}
@Override
public MutabilityPlan<E> getMutabilityPlan() {
return ImmutableMutabilityPlan.instance();
}
}
| VersionResolution |
java | apache__maven | compat/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/reflection/ClassMap.java | {
"start": 11786,
"end": 12045
} | class ____ method is sought
* @param name the name of the method
* @param paramTypes the classes of method parameters
*/
private static Method getPublicMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
// if this | whose |
java | quarkusio__quarkus | extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/keys/ReactiveKeyCommands.java | {
"start": 476,
"end": 16889
} | interface ____<K> extends ReactiveRedisCommands {
/**
* Execute the command <a href="https://redis.io/commands/copy">COPY</a>.
* Summary: Copy a key
* Group: generic
* Requires Redis 6.2.0
*
* @param source the key
* @param destination the key
* @return {@code true} source was copied. {@code false} source was not copied.
**/
Uni<Boolean> copy(K source, K destination);
/**
* Execute the command <a href="https://redis.io/commands/copy">COPY</a>.
* Summary: Copy a key
* Group: generic
* Requires Redis 6.2.0
*
* @param source the key
* @param destination the key
* @param copyArgs the additional arguments
* @return {@code true} source was copied. {@code false} source was not copied.
**/
Uni<Boolean> copy(K source, K destination, CopyArgs copyArgs);
/**
* Execute the command <a href="https://redis.io/commands/del">DEL</a>.
* Summary: Delete one or multiple keys
* Group: generic
* Requires Redis 1.0.0
*
* @param keys the keys.
* @return The number of keys that were removed.
**/
Uni<Integer> del(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/dump">DUMP</a>.
* Summary: Return a serialized version of the value stored at the specified key.
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @return the serialized value.
**/
Uni<String> dump(K key);
/**
* Execute the command <a href="https://redis.io/commands/exists">EXISTS</a>.
* Summary: Determine if a key exists
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key to check
* @return {@code true} if the key exists, {@code false} otherwise
**/
Uni<Boolean> exists(K key);
/**
* Execute the command <a href="https://redis.io/commands/exists">EXISTS</a>.
* Summary: Determine if a key exists
* Group: generic
* Requires Redis 1.0.0
*
* @param keys the keys to check
* @return the number of keys that exist from those specified as arguments.
**/
Uni<Integer> exists(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/expire">EXPIRE</a>.
* Summary: Set a key's time to live in seconds
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param seconds the new TTL
* @param expireArgs the {@code EXPIRE} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist,
* or operation skipped due to the provided arguments.
**/
Uni<Boolean> expire(K key, long seconds, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/expire">EXPIRE</a>.
* Summary: Set a key's time to live in seconds
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param duration the new TTL
* @param expireArgs the {@code EXPIRE} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist,
* or operation skipped due to the provided arguments.
**/
Uni<Boolean> expire(K key, Duration duration, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/expire">EXPIRE</a>.
* Summary: Set a key's time to live in seconds
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param seconds the new TTL
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> expire(K key, long seconds);
/**
* Execute the command <a href="https://redis.io/commands/expire">EXPIRE</a>.
* Summary: Set a key's time to live in seconds
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param duration the new TTL
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> expire(K key, Duration duration);
/**
* Execute the command <a href="https://redis.io/commands/expireat">EXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 1.2.0
*
* @param key the key
* @param timestamp the timestamp
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> expireat(K key, long timestamp);
/**
* Execute the command <a href="https://redis.io/commands/expireat">EXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 1.2.0
*
* @param key the key
* @param timestamp the timestamp
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> expireat(K key, Instant timestamp);
/**
* Execute the command <a href="https://redis.io/commands/expireat">EXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 1.2.0
*
* @param key the key
* @param timestamp the timestamp
* @param expireArgs the {@code EXPIREAT} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist, or
* operation skipped due to the provided arguments.
**/
Uni<Boolean> expireat(K key, long timestamp, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/expireat">EXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 1.2.0
*
* @param key the key
* @param timestamp the timestamp
* @param expireArgs the {@code EXPIREAT} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist, or
* operation skipped due to the provided arguments.
**/
Uni<Boolean> expireat(K key, Instant timestamp, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/expiretime">EXPIRETIME</a>.
* Summary: Get the expiration Unix timestamp for a key
* Group: generic
* Requires Redis 7.0.0
*
* @param key the key
* @return the expiration Unix timestamp in seconds, {@code -1} if the key exists but has no associated expire.
* The Uni produces a {@link RedisKeyNotFoundException} if the key does not exist.
**/
Uni<Long> expiretime(K key);
/**
* Execute the command <a href="https://redis.io/commands/keys">KEYS</a>.
* Summary: Find all keys matching the given pattern
* Group: generic
* Requires Redis 1.0.0
*
* @param pattern the glob-style pattern
* @return the list of keys matching pattern.
**/
Uni<List<K>> keys(String pattern);
/**
* Execute the command <a href="https://redis.io/commands/move">MOVE</a>.
* Summary: Move a key to another database
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @return {@code true} key was moved. {@code false} key was not moved.
**/
Uni<Boolean> move(K key, long db);
/**
* Execute the command <a href="https://redis.io/commands/persist">PERSIST</a>.
* Summary: Remove the expiration from a key
* Group: generic
* Requires Redis 2.2.0
*
* @param key the key
* @return {@code true} the timeout was removed. {@code false} key does not exist or does not have an associated timeout.
**/
Uni<Boolean> persist(K key);
/**
* Execute the command <a href="https://redis.io/commands/pexpire">PEXPIRE</a>.
* Summary: Set a key's time to live in milliseconds
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param duration the new TTL
* @param expireArgs the {@code PEXPIRE} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist,
* or operation skipped due to the provided arguments.
**/
Uni<Boolean> pexpire(K key, Duration duration, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/pexpire">PEXPIRE</a>.
* Summary: Set a key's time to live in milliseconds
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param ms the new TTL
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> pexpire(K key, long ms);
/**
* Execute the command <a href="https://redis.io/commands/pexpire">PEXPIRE</a>.
* Summary: Set a key's time to live in milliseconds
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param duration the new TTL
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> pexpire(K key, Duration duration);
/**
* Execute the command <a href="https://redis.io/commands/pexpire">PEXPIRE</a>.
* Summary: Set a key's time to live in milliseconds
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param milliseconds the new TTL
* @param expireArgs the {@code PEXPIRE} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> pexpire(K key, long milliseconds, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/pexpireat">PEXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param timestamp the timestamp
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> pexpireat(K key, long timestamp);
/**
* Execute the command <a href="https://redis.io/commands/pexpireat">PEXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param timestamp the timestamp
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist.
**/
Uni<Boolean> pexpireat(K key, Instant timestamp);
/**
* Execute the command <a href="https://redis.io/commands/pexpireat">PEXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param timestamp the timestamp
* @param expireArgs the {@code EXPIREAT} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist, or
* operation skipped due to the provided arguments.
**/
Uni<Boolean> pexpireat(K key, long timestamp, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/pexpireat">PEXPIREAT</a>.
* Summary: Set the expiration for a key as a UNIX timestamp
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @param timestamp the timestamp
* @param expireArgs the {@code EXPIREAT} command extra-arguments
* @return {@code true} the timeout was set. {@code false} the timeout was not set. e.g. key doesn't exist, or
* operation skipped due to the provided arguments.
**/
Uni<Boolean> pexpireat(K key, Instant timestamp, ExpireArgs expireArgs);
/**
* Execute the command <a href="https://redis.io/commands/pexpiretime">PEXPIRETIME</a>.
* Summary: Get the expiration Unix timestamp for a key
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @return the expiration Unix timestamp in milliseconds, {@code -1} if the key exists but has no associated expire.
* The Uni produces a {@link RedisKeyNotFoundException} if the key does not exist.
**/
Uni<Long> pexpiretime(K key);
/**
* Execute the command <a href="https://redis.io/commands/pttl">PTTL</a>.
* Summary: Get the time to live for a key in milliseconds
* Group: generic
* Requires Redis 2.6.0
*
* @param key the key
* @return TTL in milliseconds, {@code -1} if the key exists but has no associated expire. The Uni produces a
* {@link RedisKeyNotFoundException} if the key does not exist.
**/
Uni<Long> pttl(K key);
/**
* Execute the command <a href="https://redis.io/commands/randomkey">RANDOMKEY</a>.
* Summary: Return a random key from the keyspace
* Group: generic
* Requires Redis 1.0.0
*
* @return the random key, or {@code null} when the database is empty.
**/
Uni<K> randomkey();
/**
* Execute the command <a href="https://redis.io/commands/rename">RENAME</a>.
* Summary: Rename a key
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param newkey the new key
* @return a Uni completed with {@code null} when the operation completes successfully. Emits a failure is something
* wrong happens.
**/
Uni<Void> rename(K key, K newkey);
/**
* Execute the command <a href="https://redis.io/commands/renamenx">RENAMENX</a>.
* Summary: Rename a key, only if the new key does not exist
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param newkey the new key
* @return {@code true} if {@code key} was renamed to {@code newkey}. {@code false} if {@code newkey} already exists.
**/
Uni<Boolean> renamenx(K key, K newkey);
/**
* Execute the command <a href="https://redis.io/commands/scan">SCAN</a>.
* Summary: Incrementally iterate the keys space
* Group: generic
* Requires Redis 2.8.0
*
* @return the cursor.
**/
ReactiveKeyScanCursor<K> scan();
/**
* Execute the command <a href="https://redis.io/commands/scan">SCAN</a>.
* Summary: Incrementally iterate the keys space
* Group: generic
* Requires Redis 2.8.0
*
* @param args the extra arguments
* @return the cursor.
**/
ReactiveKeyScanCursor<K> scan(KeyScanArgs args);
/**
* Execute the command <a href="https://redis.io/commands/touch">TOUCH</a>.
* Summary: Alters the last access time of a key(s). Returns the number of existing keys specified.
* Group: generic
* Requires Redis 3.2.1
*
* @param keys the keys
* @return The number of keys that were touched.
**/
Uni<Integer> touch(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/ttl">TTL</a>.
* Summary: Get the time to live for a key in seconds
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @return TTL in seconds, {@code -1} if the key exists but has no associated expire. The Uni produces a
* {@link RedisKeyNotFoundException} if the key does not exist
**/
Uni<Long> ttl(K key);
/**
* Execute the command <a href="https://redis.io/commands/type">TYPE</a>.
* Summary: Determine the type stored at key
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @return type of key, or {@code NONE} when key does not exist.
**/
Uni<RedisValueType> type(K key);
/**
* Execute the command <a href="https://redis.io/commands/unlink">UNLINK</a>.
* Summary: Delete a key asynchronously in another thread. Otherwise, it is just as {@code DEL}, but non-blocking.
* Group: generic
* Requires Redis 4.0.0
*
* @param keys the keys
* @return The number of keys that were unlinked.
**/
Uni<Integer> unlink(K... keys);
}
| ReactiveKeyCommands |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cascade/RefreshLazyOneToManyTest.java | {
"start": 2881,
"end": 3360
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "description")
private String description;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "invoice_id")
private Invoice invoice;
public Line() {
}
public Line(String description, Invoice invoice) {
this.description = description;
this.invoice = invoice;
}
}
@Entity
@Table(name = "invoice_tax")
public static | Line |
java | alibaba__nacos | plugin/config/src/main/java/com/alibaba/nacos/plugin/config/spi/ConfigChangePluginService.java | {
"start": 1687,
"end": 2276
} | enum ____ {@link ConfigChangeConstants}.
*
* @return service type
*/
String getServiceType();
/**
* when pointcut the same method,according to order to load plugin service. order is lower,prior is higher.
*
* @return order
*/
int getOrder();
/**
* the ConfigChangeTypes {@link ConfigChangePointCutTypes} of need to pointcut.
*
* <p>
* ConfigChangeTypes mean the relevant pointcut method.
* </p>
*
* @return array of pointcut the methods
*/
ConfigChangePointCutTypes[] pointcutMethodNames();
}
| in |
java | google__dagger | javatests/dagger/internal/codegen/FullBindingGraphValidationTest.java | {
"start": 15146,
"end": 15856
} | interface ____");
});
}
@Test
public void moduleWithSubcomponentWithErrors_validationTypeWarning() {
CompilerTests.daggerCompiler(
MODULE_WITH_SUBCOMPONENT_WITH_ERRORS, SUBCOMPONENT_WITH_ERRORS, A_MODULE)
.withProcessingOptions(ImmutableMap.of("dagger.fullBindingGraphValidation", "WARNING"))
.compile(
subject -> {
subject.hasErrorCount(0);
subject.hasWarningCount(2);
subject.hasWarningContainingMatch(
MODULE_WITH_SUBCOMPONENT_WITH_ERRORS_MESSAGE.pattern())
.onSource(MODULE_WITH_SUBCOMPONENT_WITH_ERRORS)
.onLineContaining(" | SubcomponentWithErrors |
java | apache__camel | components/camel-jaxb/src/test/java/org/apache/camel/converter/jaxb/NonXmlFilterReaderTest.java | {
"start": 1633,
"end": 3420
} | class ____ {
private NonXmlFilterReader nonXmlFilterReader;
@Mock
private NonXmlCharFilterer nonXmlCharFiltererMock;
@Mock
private Reader readerMock;
@BeforeEach
public void setUp() {
nonXmlFilterReader = new NonXmlFilterReader(readerMock);
nonXmlFilterReader.nonXmlCharFilterer = nonXmlCharFiltererMock;
}
@Test
public void testRead() throws IOException {
char[] buffer = new char[10];
when(readerMock.read(same(buffer), eq(3), eq(5))).thenAnswer(new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
try (ConstantReader reader = new ConstantReader(new char[] { 'a', 'b', 'c' })) {
Object[] args = invocation.getArguments();
return reader.read((char[]) args[0], (Integer) args[1], (Integer) args[2]);
}
}
});
int result = nonXmlFilterReader.read(buffer, 3, 5);
verify(readerMock).read(same(buffer), eq(3), eq(5));
verify(nonXmlCharFiltererMock).filter(same(buffer), eq(3), eq(3));
assertEquals(3, result, "Unexpected number of chars read");
assertArrayEquals(new char[] { 0, 0, 0, 'a', 'b', 'c', 0, 0, 0, 0 }, buffer, "Wrong buffer contents");
}
@Test
public void testReadEOS() throws IOException {
char[] buffer = new char[10];
when(readerMock.read(any(char[].class), anyInt(), anyInt())).thenReturn(-1);
int result = nonXmlFilterReader.read(buffer, 3, 5);
assertEquals(-1, result, "Unexpected number of chars read");
assertArrayEquals(new char[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, buffer, "Buffer should not have been affected");
}
static | NonXmlFilterReaderTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/AnnotationConverterAndEmbeddableTest2.java | {
"start": 2110,
"end": 2891
} | class ____ {
@Id
private Integer id;
private String name;
@Embedded
@Convert(attributeName = "street", converter = AnnotationConverterAndEmbeddableTest2.StreetConverter.class)
private Address address;
public Person() {
}
public Person(Integer id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@Embeddable
@Access(AccessType.PROPERTY)
public static | Person |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/messaging/amqp/sending/MyBean.java | {
"start": 856,
"end": 1281
} | class ____ {
private final AmqpAdmin amqpAdmin;
private final AmqpTemplate amqpTemplate;
public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
this.amqpAdmin = amqpAdmin;
this.amqpTemplate = amqpTemplate;
}
// @fold:on // ...
public void someMethod() {
this.amqpAdmin.getQueueInfo("someQueue");
}
public void someOtherMethod() {
this.amqpTemplate.convertAndSend("hello");
}
// @fold:off
}
| MyBean |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesIndexFieldData.java | {
"start": 2302,
"end": 2485
} | class ____ extends AbstractIndexOrdinalsFieldData {
private final double minFrequency, maxFrequency;
private final int minSegmentSize;
public static | PagedBytesIndexFieldData |
java | apache__logging-log4j2 | src/site/antora/modules/ROOT/examples/manual/lookups/MainArgsExample.java | {
"start": 919,
"end": 1588
} | class ____ implements Runnable {
// tag::usage[]
private final Logger logger = LogManager.getLogger(); // <1>
public static void main(final String[] args) {
try { // <2>
Class.forName("org.apache.logging.log4j.core.lookup.MainMapLookup")
.getDeclaredMethod("setMainArguments", String[].class)
.invoke(null, (Object) args);
} catch (final ReflectiveOperationException e) {
// Log4j Core is not used.
}
new MainArgsExample().run();
}
// end::usage[]
@Override
public void run() {
logger.info("Hello `main` lookup!");
}
}
| MainArgsExample |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/NodeShutdownAllocationDecider.java | {
"start": 1193,
"end": 4296
} | class ____ extends AllocationDecider {
private static final String NAME = "node_shutdown";
private static final Decision YES_EMPTY_SHUTDOWN_METADATA = Decision.single(Decision.Type.YES, NAME, "no nodes are shutting down");
private static final Decision YES_NODE_NOT_SHUTTING_DOWN = Decision.single(Decision.Type.YES, NAME, "this node is not shutting down");
/**
* Determines if a shard can be allocated to a particular node, based on whether that node is shutting down or not.
*/
@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
return getDecision(allocation, node.nodeId(), false);
}
/**
* Applies the same rules as {@link NodeShutdownAllocationDecider#canAllocate(ShardRouting, RoutingNode, RoutingAllocation)} to
* determine if shards can remain on their current node.
*/
@Override
public Decision canRemain(IndexMetadata indexMetadata, ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
return canAllocate(shardRouting, node, allocation);
}
/**
* Prevents indices from being auto-expanded to nodes which are in the process of shutting down, regardless of whether they're shutting
* down for restart or removal.
*/
@Override
public Decision shouldAutoExpandToNode(IndexMetadata indexMetadata, DiscoveryNode node, RoutingAllocation allocation) {
return getDecision(allocation, node.getId(), true);
}
private static Decision getDecision(RoutingAllocation allocation, String nodeId, boolean canAllocateBeforeReplacementIsReady) {
final var nodeShutdowns = allocation.metadata().nodeShutdowns().getAll();
if (nodeShutdowns.isEmpty()) {
return YES_EMPTY_SHUTDOWN_METADATA;
}
final SingleNodeShutdownMetadata thisNodeShutdownMetadata = nodeShutdowns.get(nodeId);
if (thisNodeShutdownMetadata == null) {
return YES_NODE_NOT_SHUTTING_DOWN;
}
return switch (thisNodeShutdownMetadata.getType()) {
case REMOVE, SIGTERM -> allocation.decision(Decision.NO, NAME, "node [%s] is preparing to be removed from the cluster", nodeId);
case REPLACE -> canAllocateBeforeReplacementIsReady
&& allocation.getClusterState().getNodes().hasByName(thisNodeShutdownMetadata.getTargetNodeName()) == false
? allocation.decision(
Decision.YES,
NAME,
"node [%s] is preparing to be removed from the cluster, but replacement is not yet present",
nodeId
)
: allocation.decision(Decision.NO, NAME, "node [%s] is preparing to be removed from the cluster", nodeId);
case RESTART -> allocation.decision(
Decision.YES,
NAME,
"node [%s] is preparing to restart, but will remain in the cluster",
nodeId
);
};
}
}
| NodeShutdownAllocationDecider |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/RandomModInteger.java | {
"start": 1455,
"end": 2422
} | class ____ extends BugChecker implements BinaryTreeMatcher {
private static final Matcher<ExpressionTree> RANDOM_NEXT_INT =
Matchers.instanceMethod()
.onDescendantOf("java.util.Random")
.named("nextInt")
.withNoParameters();
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
if (tree.getKind() == Kind.REMAINDER
&& tree.getLeftOperand() instanceof MethodInvocationTree
&& RANDOM_NEXT_INT.matches(tree.getLeftOperand(), state)) {
ExpressionTree randomExpr = ASTHelpers.getReceiver(tree.getLeftOperand());
ExpressionTree modulus = tree.getRightOperand();
return describeMatch(
tree,
SuggestedFix.replace(
tree,
String.format(
"%s.nextInt(%s)",
state.getSourceForNode(randomExpr), state.getSourceForNode(modulus))));
}
return Description.NO_MATCH;
}
}
| RandomModInteger |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ReflectiveScan.java | {
"start": 2359,
"end": 3157
} | interface ____ {
/**
* Alias for {@link #basePackages}.
* <p>Allows for more concise annotation declarations if no other attributes
* are needed — for example, {@code @ReflectiveScan("org.my.pkg")}
* instead of {@code @ReflectiveScan(basePackages = "org.my.pkg")}.
*/
@AliasFor("basePackages")
String[] value() default {};
/**
* Base packages to scan for reflective usage.
* <p>{@link #value} is an alias for (and mutually exclusive with) this
* attribute.
* <p>Use {@link #basePackageClasses} for a type-safe alternative to
* String-based package names.
*/
@AliasFor("value")
String[] basePackages() default {};
/**
* Type-safe alternative to {@link #basePackages} for specifying the packages
* to scan for reflection usage. The package of each | ReflectiveScan |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/type/OracleSqlArrayTest.java | {
"start": 1569,
"end": 4133
} | class ____ {
@AfterEach
void tearDown(SessionFactoryScope factoryScope) {
factoryScope.dropData();
}
@Test public void test(SessionFactoryScope scope) {
Container container = new Container();
container.activityKinds = new ActivityKind[] { ActivityKind.Work, ActivityKind.Play };
container.bigIntegers = new BigInteger[] { new BigInteger("123"), new BigInteger("345") };
scope.inTransaction( s -> s.persist( container ) );
Container c = scope.fromTransaction( s-> s.createQuery("from ContainerWithArrays where bigIntegers = ?1", Container.class ).setParameter(1, new BigInteger[] { new BigInteger("123"), new BigInteger("345") }).getSingleResult() );
assertArrayEquals( new ActivityKind[] { ActivityKind.Work, ActivityKind.Play }, c.activityKinds );
assertArrayEquals( new BigInteger[] { new BigInteger("123"), new BigInteger("345") }, c.bigIntegers );
c = scope.fromTransaction( s-> s.createQuery("from ContainerWithArrays where activityKinds = ?1", Container.class ).setParameter(1, new ActivityKind[] { ActivityKind.Work, ActivityKind.Play }).getSingleResult() );
}
@Test public void testSchema(SessionFactoryScope scope) {
scope.inSession( s -> {
Connection c;
try {
c = s.getJdbcConnectionAccess().obtainConnection();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
try {
ResultSet tableInfo = c.getMetaData().getColumns(null, null, "CONTAINERWITHARRAYS", "BIGINTEGERS" );
while ( tableInfo.next() ) {
String type = tableInfo.getString(6);
assertEquals( "BIGINTEGERBIGDECIMALARRAY", type );
return;
}
fail("named array column not exported");
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
try {
s.getJdbcConnectionAccess().releaseConnection(c);
}
catch (SQLException e) {
}
}
});
scope.inSession( s -> {
Connection c;
try {
c = s.getJdbcConnectionAccess().obtainConnection();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
try {
ResultSet tableInfo = c.getMetaData().getColumns(null, null, "CONTAINERWITHARRAYS", "ACTIVITYKINDS" );
while ( tableInfo.next() ) {
String type = tableInfo.getString(6);
assertEquals( "ACTIVITYKINDBYTEARRAY", type );
return;
}
fail("named array column not exported");
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
try {
s.getJdbcConnectionAccess().releaseConnection(c);
}
catch (SQLException e) {
}
}
});
}
public | OracleSqlArrayTest |
java | netty__netty | codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java | {
"start": 958,
"end": 9852
} | class ____ {
static StringBuilder appendQuery(StringBuilder buf, DnsQuery query) {
appendQueryHeader(buf, query);
appendAllRecords(buf, query);
return buf;
}
static StringBuilder appendResponse(StringBuilder buf, DnsResponse response) {
appendResponseHeader(buf, response);
appendAllRecords(buf, response);
return buf;
}
static StringBuilder appendRecordClass(StringBuilder buf, int dnsClass) {
final String name;
switch (dnsClass &= 0xFFFF) {
case DnsRecord.CLASS_IN:
name = "IN";
break;
case DnsRecord.CLASS_CSNET:
name = "CSNET";
break;
case DnsRecord.CLASS_CHAOS:
name = "CHAOS";
break;
case DnsRecord.CLASS_HESIOD:
name = "HESIOD";
break;
case DnsRecord.CLASS_NONE:
name = "NONE";
break;
case DnsRecord.CLASS_ANY:
name = "ANY";
break;
default:
name = null;
break;
}
if (name != null) {
buf.append(name);
} else {
buf.append("UNKNOWN(").append(dnsClass).append(')');
}
return buf;
}
private static void appendQueryHeader(StringBuilder buf, DnsQuery msg) {
buf.append(StringUtil.simpleClassName(msg))
.append('(');
appendAddresses(buf, msg)
.append("id: ")
.append(msg.id())
.append(", ")
.append(msg.opCode());
if (msg.isRecursionDesired()) {
buf.append(", RD");
}
if (msg.z() != 0) {
buf.append(", Z: ")
.append(msg.z());
}
buf.append(')');
}
private static void appendResponseHeader(StringBuilder buf, DnsResponse msg) {
buf.append(StringUtil.simpleClassName(msg))
.append('(');
appendAddresses(buf, msg)
.append("id: ")
.append(msg.id())
.append(", ")
.append(msg.opCode())
.append(", ")
.append(msg.code())
.append(',');
boolean hasComma = true;
if (msg.isRecursionDesired()) {
hasComma = false;
buf.append(" RD");
}
if (msg.isAuthoritativeAnswer()) {
hasComma = false;
buf.append(" AA");
}
if (msg.isTruncated()) {
hasComma = false;
buf.append(" TC");
}
if (msg.isRecursionAvailable()) {
hasComma = false;
buf.append(" RA");
}
if (msg.z() != 0) {
if (!hasComma) {
buf.append(',');
}
buf.append(" Z: ")
.append(msg.z());
}
if (hasComma) {
buf.setCharAt(buf.length() - 1, ')');
} else {
buf.append(')');
}
}
private static StringBuilder appendAddresses(StringBuilder buf, DnsMessage msg) {
if (!(msg instanceof AddressedEnvelope)) {
return buf;
}
@SuppressWarnings("unchecked")
AddressedEnvelope<?, SocketAddress> envelope = (AddressedEnvelope<?, SocketAddress>) msg;
SocketAddress addr = envelope.sender();
if (addr != null) {
buf.append("from: ")
.append(addr)
.append(", ");
}
addr = envelope.recipient();
if (addr != null) {
buf.append("to: ")
.append(addr)
.append(", ");
}
return buf;
}
private static void appendAllRecords(StringBuilder buf, DnsMessage msg) {
appendRecords(buf, msg, DnsSection.QUESTION);
appendRecords(buf, msg, DnsSection.ANSWER);
appendRecords(buf, msg, DnsSection.AUTHORITY);
appendRecords(buf, msg, DnsSection.ADDITIONAL);
}
private static void appendRecords(StringBuilder buf, DnsMessage message, DnsSection section) {
final int count = message.count(section);
for (int i = 0; i < count; i ++) {
buf.append(StringUtil.NEWLINE)
.append(StringUtil.TAB)
.append(message.<DnsRecord>recordAt(section, i));
}
}
static DnsQuery decodeDnsQuery(DnsRecordDecoder decoder, ByteBuf buf, DnsQueryFactory supplier) throws Exception {
DnsQuery query = newQuery(buf, supplier);
boolean success = false;
try {
int questionCount = buf.readUnsignedShort();
int answerCount = buf.readUnsignedShort();
int authorityRecordCount = buf.readUnsignedShort();
int additionalRecordCount = buf.readUnsignedShort();
decodeQuestions(decoder, query, buf, questionCount);
decodeRecords(decoder, query, DnsSection.ANSWER, buf, answerCount);
decodeRecords(decoder, query, DnsSection.AUTHORITY, buf, authorityRecordCount);
decodeRecords(decoder, query, DnsSection.ADDITIONAL, buf, additionalRecordCount);
success = true;
return query;
} finally {
if (!success) {
query.release();
}
}
}
private static DnsQuery newQuery(ByteBuf buf, DnsQueryFactory supplier) {
int id = buf.readUnsignedShort();
int flags = buf.readUnsignedShort();
if (flags >> 15 == 1) {
throw new CorruptedFrameException("not a query");
}
DnsQuery query = supplier.newQuery(id, DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)));
query.setRecursionDesired((flags >> 8 & 1) == 1);
query.setZ(flags >> 4 & 0x7);
return query;
}
private static void decodeQuestions(DnsRecordDecoder decoder,
DnsQuery query, ByteBuf buf, int questionCount) throws Exception {
for (int i = questionCount; i > 0; --i) {
query.addRecord(DnsSection.QUESTION, decoder.decodeQuestion(buf));
}
}
private static void decodeRecords(DnsRecordDecoder decoder,
DnsQuery query, DnsSection section, ByteBuf buf, int count) throws Exception {
for (int i = count; i > 0; --i) {
DnsRecord r = decoder.decodeRecord(buf);
if (r == null) {
break;
}
query.addRecord(section, r);
}
}
static void encodeDnsResponse(DnsRecordEncoder encoder, DnsResponse response, ByteBuf buf) throws Exception {
boolean success = false;
try {
encodeHeader(response, buf);
encodeQuestions(encoder, response, buf);
encodeRecords(encoder, response, DnsSection.ANSWER, buf);
encodeRecords(encoder, response, DnsSection.AUTHORITY, buf);
encodeRecords(encoder, response, DnsSection.ADDITIONAL, buf);
success = true;
} finally {
if (!success) {
buf.release();
}
}
}
/**
* Encodes the header that is always 12 bytes long.
*
* @param response the response header being encoded
* @param buf the buffer the encoded data should be written to
*/
private static void encodeHeader(DnsResponse response, ByteBuf buf) {
buf.writeShort(response.id());
int flags = 32768;
flags |= (response.opCode().byteValue() & 0xFF) << 11;
if (response.isAuthoritativeAnswer()) {
flags |= 1 << 10;
}
if (response.isTruncated()) {
flags |= 1 << 9;
}
if (response.isRecursionDesired()) {
flags |= 1 << 8;
}
if (response.isRecursionAvailable()) {
flags |= 1 << 7;
}
flags |= response.z() << 4;
flags |= response.code().intValue();
buf.writeShort(flags);
buf.writeShort(response.count(DnsSection.QUESTION));
buf.writeShort(response.count(DnsSection.ANSWER));
buf.writeShort(response.count(DnsSection.AUTHORITY));
buf.writeShort(response.count(DnsSection.ADDITIONAL));
}
private static void encodeQuestions(DnsRecordEncoder encoder, DnsResponse response, ByteBuf buf) throws Exception {
int count = response.count(DnsSection.QUESTION);
for (int i = 0; i < count; ++i) {
encoder.encodeQuestion(response.<DnsQuestion>recordAt(DnsSection.QUESTION, i), buf);
}
}
private static void encodeRecords(DnsRecordEncoder encoder,
DnsResponse response, DnsSection section, ByteBuf buf) throws Exception {
int count = response.count(section);
for (int i = 0; i < count; ++i) {
encoder.encodeRecord(response.recordAt(section, i), buf);
}
}
| DnsMessageUtil |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/AnnotationTypeMappingsTests.java | {
"start": 25093,
"end": 25219
} | interface ____ {
String test() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@ | AliasForWithIncompatibleReturnTypesTarget |
java | elastic__elasticsearch | x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/authn/SuccessfulAuthenticationResponseMessageBuilder.java | {
"start": 2429,
"end": 15499
} | class ____ {
private static final Logger logger = LogManager.getLogger(SuccessfulAuthenticationResponseMessageBuilder.class);
private final Clock clock;
private final SamlIdentityProvider idp;
private final SamlFactory samlFactory;
public SuccessfulAuthenticationResponseMessageBuilder(SamlFactory samlFactory, Clock clock, SamlIdentityProvider idp) {
SamlInit.initialize();
this.samlFactory = samlFactory;
this.clock = clock;
this.idp = idp;
}
/**
* Builds and signs a SAML Response Message with a single assertion for the provided user
*
* @param user The user who is authenticated (actually a combination of user+sp)
* @param authnState The authentication state as presented in the SAML request (or {@code null})
* @return A SAML Response
*/
public Response build(UserServiceAuthentication user, @Nullable SamlAuthenticationState authnState) {
return build(user, authnState, null);
}
/**
* Builds and signs a SAML Response Message with a single assertion for the provided user
*
* @param user The user who is authenticated (actually a combination of user+sp)
* @param authnState The authentication state as presented in the SAML request (or {@code null})
* @param customAttributes Optional custom attributes to include in the response (or {@code null})
* @return A SAML Response
*/
public Response build(
UserServiceAuthentication user,
@Nullable SamlAuthenticationState authnState,
@Nullable SamlInitiateSingleSignOnAttributes customAttributes
) {
logger.debug("Building success response for [{}] from [{}]", user, authnState);
final Instant now = clock.instant();
final SamlServiceProvider serviceProvider = user.getServiceProvider();
final Response response = samlFactory.object(Response.class, Response.DEFAULT_ELEMENT_NAME);
response.setID(samlFactory.secureIdentifier());
if (authnState != null && authnState.getAuthnRequestId() != null) {
response.setInResponseTo(authnState.getAuthnRequestId());
}
response.setIssuer(buildIssuer());
response.setIssueInstant(now);
response.setStatus(buildStatus());
response.setDestination(serviceProvider.getAssertionConsumerService().toString());
final Assertion assertion = samlFactory.object(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);
assertion.setID(samlFactory.secureIdentifier());
assertion.setIssuer(buildIssuer());
assertion.setIssueInstant(now);
assertion.setConditions(buildConditions(now, serviceProvider));
assertion.setSubject(buildSubject(now, user, authnState));
final AuthnStatement authnStatement = buildAuthnStatement(now, user);
assertion.getAuthnStatements().add(authnStatement);
final AttributeStatement attributeStatement = buildAttributes(user, customAttributes);
if (attributeStatement != null) {
assertion.getAttributeStatements().add(attributeStatement);
}
response.getAssertions().add(assertion);
return sign(response);
}
private Response sign(Response response) {
final SamlObjectSigner signer = new SamlObjectSigner(samlFactory, idp);
return SamlFactory.buildXmlObject(signer.sign(response), Response.class);
}
private Conditions buildConditions(Instant now, SamlServiceProvider serviceProvider) {
final Audience spAudience = samlFactory.object(Audience.class, Audience.DEFAULT_ELEMENT_NAME);
spAudience.setURI(serviceProvider.getEntityId());
final AudienceRestriction restriction = samlFactory.object(AudienceRestriction.class, AudienceRestriction.DEFAULT_ELEMENT_NAME);
restriction.getAudiences().add(spAudience);
final Conditions conditions = samlFactory.object(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME);
conditions.setNotBefore(now);
conditions.setNotOnOrAfter(now.plus(serviceProvider.getAuthnExpiry()));
conditions.getAudienceRestrictions().add(restriction);
return conditions;
}
private Subject buildSubject(Instant now, UserServiceAuthentication user, SamlAuthenticationState authnState) {
final SamlServiceProvider serviceProvider = user.getServiceProvider();
final NameID nameID = buildNameId(user, authnState);
final Subject subject = samlFactory.object(Subject.class, Subject.DEFAULT_ELEMENT_NAME);
subject.setNameID(nameID);
final SubjectConfirmationData data = samlFactory.object(
SubjectConfirmationData.class,
SubjectConfirmationData.DEFAULT_ELEMENT_NAME
);
if (authnState != null && authnState.getAuthnRequestId() != null) {
data.setInResponseTo(authnState.getAuthnRequestId());
}
data.setNotBefore(now);
data.setNotOnOrAfter(now.plus(serviceProvider.getAuthnExpiry()));
data.setRecipient(serviceProvider.getAssertionConsumerService().toString());
final SubjectConfirmation confirmation = samlFactory.object(SubjectConfirmation.class, SubjectConfirmation.DEFAULT_ELEMENT_NAME);
confirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
confirmation.setSubjectConfirmationData(data);
subject.getSubjectConfirmations().add(confirmation);
return subject;
}
private AuthnStatement buildAuthnStatement(Instant now, UserServiceAuthentication user) {
final SamlServiceProvider serviceProvider = user.getServiceProvider();
final AuthnStatement statement = samlFactory.object(AuthnStatement.class, AuthnStatement.DEFAULT_ELEMENT_NAME);
statement.setAuthnInstant(now);
statement.setSessionNotOnOrAfter(now.plus(serviceProvider.getAuthnExpiry()));
final AuthnContext context = samlFactory.object(AuthnContext.class, AuthnContext.DEFAULT_ELEMENT_NAME);
final AuthnContextClassRef classRef = samlFactory.object(AuthnContextClassRef.class, AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
classRef.setURI(resolveAuthnClass(user.getAuthenticationMethods(), user.getNetworkControls()));
context.setAuthnContextClassRef(classRef);
statement.setAuthnContext(context);
return statement;
}
private static String resolveAuthnClass(Set<AuthenticationMethod> authenticationMethods, Set<NetworkControl> networkControls) {
if (authenticationMethods.contains(AuthenticationMethod.PASSWORD)) {
if (networkControls.contains(NetworkControl.IP_FILTER)) {
return AuthnContext.IP_PASSWORD_AUTHN_CTX;
} else if (networkControls.contains(NetworkControl.TLS)) {
return AuthnContext.PPT_AUTHN_CTX;
} else {
return AuthnContext.PASSWORD_AUTHN_CTX;
}
} else if (authenticationMethods.contains(AuthenticationMethod.KERBEROS)) {
return AuthnContext.KERBEROS_AUTHN_CTX;
} else if (authenticationMethods.contains(AuthenticationMethod.TLS_CLIENT_AUTH) && networkControls.contains(NetworkControl.TLS)) {
return AuthnContext.TLS_CLIENT_AUTHN_CTX;
} else if (authenticationMethods.contains(AuthenticationMethod.PRIOR_SESSION)) {
return AuthnContext.PREVIOUS_SESSION_AUTHN_CTX;
} else if (networkControls.contains(NetworkControl.IP_FILTER)) {
return AuthnContext.IP_AUTHN_CTX;
} else {
return AuthnContext.UNSPECIFIED_AUTHN_CTX;
}
}
private AttributeStatement buildAttributes(
UserServiceAuthentication user,
@Nullable SamlInitiateSingleSignOnAttributes customAttributes
) {
final SamlServiceProvider serviceProvider = user.getServiceProvider();
final AttributeStatement statement = samlFactory.object(AttributeStatement.class, AttributeStatement.DEFAULT_ELEMENT_NAME);
final List<Attribute> attributes = new ArrayList<>();
final SamlServiceProvider.AttributeNames attributeNames = serviceProvider.getAttributeNames();
final Attribute roles = buildAttribute(attributeNames.roles, "roles", user.getRoles());
if (roles != null) {
attributes.add(roles);
}
final Attribute principal = buildAttribute(attributeNames.principal, "principal", user.getPrincipal());
if (principal != null) {
attributes.add(principal);
}
final Attribute email = buildAttribute(attributeNames.email, "email", user.getEmail());
if (email != null) {
attributes.add(email);
}
final Attribute name = buildAttribute(attributeNames.name, "name", user.getName());
if (name != null) {
attributes.add(name);
}
// Add custom attributes if provided
if (customAttributes != null && customAttributes.getAttributes().isEmpty() == false) {
for (Map.Entry<String, List<String>> entry : customAttributes.getAttributes().entrySet()) {
final String attributeName = entry.getKey();
if (attributeNames.isAllowedExtension(attributeName)) {
Attribute attribute = buildAttribute(attributeName, null, entry.getValue());
if (attribute != null) {
attributes.add(attribute);
}
} else {
throw new IllegalArgumentException(
"the custom attribute ["
+ attributeName
+ "] is not permitted for the Service Provider ["
+ serviceProvider.getName()
+ "], allowed attribute names are ["
+ collectionToCommaDelimitedString(attributeNames.allowedExtensions)
+ "]"
);
}
}
}
if (attributes.isEmpty()) {
return null;
}
statement.getAttributes().addAll(attributes);
return statement;
}
private Attribute buildAttribute(String formalName, @Nullable String friendlyName, String value) {
if (Strings.isNullOrEmpty(value)) {
return null;
}
return buildAttribute(formalName, friendlyName, List.of(value));
}
private Attribute buildAttribute(String formalName, @Nullable String friendlyName, Collection<String> values) {
if (values.isEmpty() || Strings.isNullOrEmpty(formalName)) {
return null;
}
final Attribute attribute = samlFactory.object(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
attribute.setName(formalName);
if (Strings.isNullOrEmpty(friendlyName) == false) {
attribute.setFriendlyName(friendlyName);
}
attribute.setNameFormat(Attribute.URI_REFERENCE);
for (String val : values) {
final XSString string = samlFactory.object(XSString.class, AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
string.setValue(val);
attribute.getAttributeValues().add(string);
}
return attribute;
}
private Issuer buildIssuer() {
final Issuer issuer = samlFactory.object(Issuer.class, Issuer.DEFAULT_ELEMENT_NAME);
issuer.setValue(this.idp.getEntityId());
return issuer;
}
private Status buildStatus() {
final StatusCode code = samlFactory.object(StatusCode.class, StatusCode.DEFAULT_ELEMENT_NAME);
code.setValue(StatusCode.SUCCESS);
final Status status = samlFactory.object(Status.class, Status.DEFAULT_ELEMENT_NAME);
status.setStatusCode(code);
return status;
}
private NameID buildNameId(UserServiceAuthentication user, @Nullable SamlAuthenticationState authnState) {
final SamlServiceProvider serviceProvider = user.getServiceProvider();
final NameID nameID = samlFactory.object(NameID.class, NameID.DEFAULT_ELEMENT_NAME);
final String nameIdFormat;
if (authnState != null && authnState.getRequestedNameidFormat() != null) {
nameIdFormat = authnState.getRequestedNameidFormat();
} else {
nameIdFormat = serviceProvider.getAllowedNameIdFormat() != null
? serviceProvider.getAllowedNameIdFormat()
: idp.getServiceProviderDefaults().nameIdFormat;
}
nameID.setFormat(nameIdFormat);
nameID.setValue(getNameIdValueForFormat(nameIdFormat, user));
return nameID;
}
private String getNameIdValueForFormat(String format, UserServiceAuthentication user) {
return switch (format) {
case TRANSIENT ->
// See SAML 2.0 Core 8.3.8 & 1.3.4
samlFactory.secureIdentifier();
default -> throw new IllegalStateException("Unsupported NameID Format: " + format);
};
}
}
| SuccessfulAuthenticationResponseMessageBuilder |
java | alibaba__nacos | api/src/test/java/com/alibaba/nacos/api/naming/pojo/maintainer/ClientSummaryInfoTest.java | {
"start": 1072,
"end": 3869
} | class ____ {
private ObjectMapper mapper;
private ClientSummaryInfo clientSummaryInfo;
@BeforeEach
void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
clientSummaryInfo = new ClientSummaryInfo();
clientSummaryInfo.setClientId("clientId");
clientSummaryInfo.setEphemeral(true);
clientSummaryInfo.setLastUpdatedTime(1000L);
clientSummaryInfo.setClientType("connection");
clientSummaryInfo.setConnectType("grpc");
clientSummaryInfo.setAppName("appName");
clientSummaryInfo.setVersion("version");
clientSummaryInfo.setClientIp("1.1.1.1");
clientSummaryInfo.setClientPort(8080);
}
@Test
void testSerialize() throws JsonProcessingException {
String json = mapper.writeValueAsString(clientSummaryInfo);
assertTrue(json.contains("\"clientId\":\"clientId\""));
assertTrue(json.contains("\"ephemeral\":true"));
assertTrue(json.contains("\"lastUpdatedTime\":1000"));
assertTrue(json.contains("\"clientType\":\"connection\""));
assertTrue(json.contains("\"connectType\":\"grpc\""));
assertTrue(json.contains("\"appName\":\"appName\""));
assertTrue(json.contains("\"version\":\"version\""));
assertTrue(json.contains("\"clientIp\":\"1.1.1.1\""));
assertTrue(json.contains("\"clientPort\":8080"));
}
@Test
void testDeserialize() throws IOException {
String jsonString = "{\"clientId\":\"clientId\",\"ephemeral\":true,\"lastUpdatedTime\":1000,"
+ "\"clientType\":\"connection\",\"connectType\":\"grpc\",\"appName\":\"appName\","
+ "\"version\":\"version\",\"clientIp\":\"1.1.1.1\",\"clientPort\":8080}";
ClientSummaryInfo clientSummaryInfo1 = mapper.readValue(jsonString, ClientSummaryInfo.class);
assertEquals(clientSummaryInfo.getClientId(), clientSummaryInfo1.getClientId());
assertEquals(clientSummaryInfo.isEphemeral(), clientSummaryInfo1.isEphemeral());
assertEquals(clientSummaryInfo.getLastUpdatedTime(), clientSummaryInfo1.getLastUpdatedTime());
assertEquals(clientSummaryInfo.getClientType(), clientSummaryInfo1.getClientType());
assertEquals(clientSummaryInfo.getConnectType(), clientSummaryInfo1.getConnectType());
assertEquals(clientSummaryInfo.getAppName(), clientSummaryInfo1.getAppName());
assertEquals(clientSummaryInfo.getVersion(), clientSummaryInfo1.getVersion());
assertEquals(clientSummaryInfo.getClientIp(), clientSummaryInfo1.getClientIp());
assertEquals(clientSummaryInfo.getClientPort(), clientSummaryInfo1.getClientPort());
}
} | ClientSummaryInfoTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/Customer.java | {
"start": 218,
"end": 520
} | class ____ extends Person {
private Employee contactOwner;
public Customer() {
}
public Customer(String name) {
super( name );
}
public Employee getContactOwner() {
return contactOwner;
}
public void setContactOwner(Employee contactOwner) {
this.contactOwner = contactOwner;
}
}
| Customer |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/VertexInputInfoStore.java | {
"start": 1433,
"end": 2907
} | class ____ {
private final Map<JobVertexID, Map<IntermediateDataSetID, JobVertexInputInfo>>
jobVertexInputInfos = new HashMap<>();
/**
* Put a {@link JobVertexInputInfo}.
*
* @param jobVertexId the job vertex id
* @param resultId the intermediate result id
* @param info the {@link JobVertexInputInfo} to put
*/
public void put(
JobVertexID jobVertexId, IntermediateDataSetID resultId, JobVertexInputInfo info) {
checkNotNull(jobVertexId);
checkNotNull(resultId);
checkNotNull(info);
jobVertexInputInfos.compute(
jobVertexId,
(ignored, inputInfos) -> {
if (inputInfos == null) {
inputInfos = new HashMap<>();
}
inputInfos.putIfAbsent(resultId, info);
return inputInfos;
});
}
/**
* Get a {@link JobVertexInputInfo}.
*
* @param jobVertexId the job vertex id
* @param resultId the intermediate result id
* @return the {@link JobVertexInputInfo} identified by the job vertex id and intermediate
* result id
*/
public JobVertexInputInfo get(JobVertexID jobVertexId, IntermediateDataSetID resultId) {
checkNotNull(jobVertexId);
checkNotNull(resultId);
return checkNotNull(jobVertexInputInfos.get(jobVertexId).get(resultId));
}
}
| VertexInputInfoStore |
java | dropwizard__dropwizard | dropwizard-e2e/src/main/java/com/example/httpsessions/HttpSessionsResource.java | {
"start": 230,
"end": 428
} | class ____ {
@GET
@Path("session")
public Response isSessionInjected(@Session HttpSession httpSession) {
return Response.ok(httpSession != null).build();
}
}
| HttpSessionsResource |
java | quarkusio__quarkus | extensions/security/runtime/src/main/java/io/quarkus/security/runtime/interceptor/SecurityHandler.java | {
"start": 2583,
"end": 3059
} | class ____ implements Function<Object, Multi<?>> {
private final InvocationContext ic;
public MultiContinuation(InvocationContext invocationContext) {
ic = invocationContext;
}
@Override
public Multi<?> apply(Object o) {
try {
return (Multi<?>) ic.proceed();
} catch (Exception e) {
return Multi.createFrom().failure(e);
}
}
}
}
| MultiContinuation |
java | elastic__elasticsearch | modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IpDataLookupFactories.java | {
"start": 1122,
"end": 1227
} | class ____ {
private IpDataLookupFactories() {
// utility class
}
| IpDataLookupFactories |
java | spring-projects__spring-security | ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsService.java | {
"start": 1540,
"end": 2802
} | class ____ implements UserDetailsService {
private final LdapUserSearch userSearch;
private final LdapAuthoritiesPopulator authoritiesPopulator;
private UserDetailsContextMapper userDetailsMapper = new LdapUserDetailsMapper();
public LdapUserDetailsService(LdapUserSearch userSearch) {
this(userSearch, new NullLdapAuthoritiesPopulator());
}
public LdapUserDetailsService(LdapUserSearch userSearch, LdapAuthoritiesPopulator authoritiesPopulator) {
Assert.notNull(userSearch, "userSearch must not be null");
Assert.notNull(authoritiesPopulator, "authoritiesPopulator must not be null");
this.userSearch = userSearch;
this.authoritiesPopulator = authoritiesPopulator;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
DirContextOperations userData = this.userSearch.searchForUser(username);
return this.userDetailsMapper.mapUserFromContext(userData, username,
this.authoritiesPopulator.getGrantedAuthorities(userData, username));
}
public void setUserDetailsMapper(UserDetailsContextMapper userDetailsMapper) {
Assert.notNull(userDetailsMapper, "userDetailsMapper must not be null");
this.userDetailsMapper = userDetailsMapper;
}
private static final | LdapUserDetailsService |
java | apache__avro | lang/java/ipc/src/test/java/org/apache/avro/io/Perf.java | {
"start": 44952,
"end": 45238
} | class ____ extends GenericTest {
public GenericOneTimeDecoderUse() throws IOException {
super("GenericOneTimeDecoderUse_");
isWriteTest = false;
}
@Override
protected Decoder getDecoder() {
return newDecoder();
}
}
static | GenericOneTimeDecoderUse |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/utils/FederationMembershipStateStoreInputValidator.java | {
"start": 1664,
"end": 1816
} | class ____ validate the inputs to
* {@code FederationMembershipStateStore}, allows a fail fast mechanism for
* invalid user inputs.
*
*/
public final | to |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/lucene/spatial/ShapeDocValuesQuery.java | {
"start": 1432,
"end": 8983
} | class ____<GEOMETRY> extends Query {
private final String field;
private final CoordinateEncoder encoder;
private final ShapeField.QueryRelation relation;
private final GEOMETRY[] geometries;
ShapeDocValuesQuery(String field, CoordinateEncoder encoder, ShapeField.QueryRelation relation, GEOMETRY[] geometries) {
if (field == null) {
throw new IllegalArgumentException("field must not be null");
}
this.field = field;
this.encoder = encoder;
this.relation = relation;
this.geometries = geometries;
}
protected abstract Component2D create(GEOMETRY geometry);
protected abstract Component2D create(GEOMETRY[] geometries);
/** Override if special cases, like dateline support, should be considered */
protected void add(List<Component2D> components2D, GEOMETRY geometry) {
components2D.add(create(geometry));
}
@Override
public String toString(String otherField) {
StringBuilder sb = new StringBuilder();
if (this.field.equals(otherField) == false) {
sb.append(this.field);
sb.append(':');
sb.append(relation);
sb.append(':');
}
sb.append(Arrays.toString(geometries));
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (sameClassAs(obj) == false) {
return false;
}
ShapeDocValuesQuery<?> other = (ShapeDocValuesQuery<?>) obj;
return field.equals(other.field) && relation == other.relation && Arrays.equals(geometries, other.geometries);
}
@Override
public int hashCode() {
int h = classHash();
h = 31 * h + field.hashCode();
h = 31 * h + relation.hashCode();
h = 31 * h + Arrays.hashCode(geometries);
return h;
}
@Override
public void visit(QueryVisitor visitor) {
if (visitor.acceptField(field)) {
visitor.visitLeaf(this);
}
}
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) {
if (relation == ShapeField.QueryRelation.CONTAINS) {
return getContainsWeight(scoreMode, boost);
} else {
return getStandardWeight(scoreMode, boost);
}
}
private ConstantScoreWeight getStandardWeight(ScoreMode scoreMode, float boost) {
final Component2D component2D = create(geometries);
return new ConstantScoreWeight(this, boost) {
@Override
public ScorerSupplier scorerSupplier(LeafReaderContext context) {
// implement ScorerSupplier, since we do some expensive stuff to make a scorer
return new ScorerSupplier() {
@Override
public Scorer get(long leadCost) throws IOException {
// binary doc values allocate an array upfront, lets only allocate it if we are going to use it
final BinaryDocValues values = context.reader().getBinaryDocValues(field);
if (values == null) {
return new ConstantScoreScorer(0f, scoreMode, DocIdSetIterator.empty());
}
final GeometryDocValueReader reader = new GeometryDocValueReader();
final Component2DVisitor visitor = Component2DVisitor.getVisitor(component2D, relation, encoder);
final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {
@Override
public boolean matches() throws IOException {
reader.reset(values.binaryValue());
visitor.reset();
reader.visit(visitor);
return visitor.matches();
}
@Override
public float matchCost() {
return 1000f; // TODO: what should it be?
}
};
return new ConstantScoreScorer(score(), scoreMode, iterator);
}
@Override
public long cost() {
return context.reader().maxDoc();
}
};
}
@Override
public boolean isCacheable(LeafReaderContext ctx) {
return DocValues.isCacheable(ctx, field);
}
};
}
private ConstantScoreWeight getContainsWeight(ScoreMode scoreMode, float boost) {
final List<Component2D> components2D = new ArrayList<>(geometries.length);
for (GEOMETRY geometry : geometries) {
add(components2D, geometry);
}
return new ConstantScoreWeight(this, boost) {
@Override
public ScorerSupplier scorerSupplier(LeafReaderContext context) {
// implement ScorerSupplier, since we do some expensive stuff to make a scorer
return new ScorerSupplier() {
@Override
public Scorer get(long leadCost) throws IOException {
// binary doc values allocate an array upfront, lets only allocate it if we are going to use it
final BinaryDocValues values = context.reader().getBinaryDocValues(field);
if (values == null) {
return new ConstantScoreScorer(0f, scoreMode, DocIdSetIterator.empty());
}
final Component2DVisitor[] visitors = new Component2DVisitor[components2D.size()];
for (int i = 0; i < components2D.size(); i++) {
visitors[i] = Component2DVisitor.getVisitor(components2D.get(i), relation, encoder);
}
final GeometryDocValueReader reader = new GeometryDocValueReader();
final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {
@Override
public boolean matches() throws IOException {
reader.reset(values.binaryValue());
for (Component2DVisitor visitor : visitors) {
visitor.reset();
reader.visit(visitor);
if (visitor.matches() == false) {
return false;
}
}
return true;
}
@Override
public float matchCost() {
return 1000f; // TODO: what should it be?
}
};
return new ConstantScoreScorer(score(), scoreMode, iterator);
}
@Override
public long cost() {
return context.reader().maxDoc();
}
};
}
@Override
public boolean isCacheable(LeafReaderContext ctx) {
return DocValues.isCacheable(ctx, field);
}
};
}
}
| ShapeDocValuesQuery |
java | netty__netty | transport/src/main/java/io/netty/channel/nio/NioIoHandler.java | {
"start": 12584,
"end": 30597
} | class ____ implements IoRegistration {
private final AtomicBoolean canceled = new AtomicBoolean();
private final NioIoHandle handle;
private volatile SelectionKey key;
DefaultNioRegistration(ThreadAwareExecutor executor, NioIoHandle handle, NioIoOps initialOps, Selector selector)
throws IOException {
this.handle = handle;
key = handle.selectableChannel().register(selector, initialOps.value, this);
}
NioIoHandle handle() {
return handle;
}
void register(Selector selector) throws IOException {
SelectionKey newKey = handle.selectableChannel().register(selector, key.interestOps(), this);
key.cancel();
key = newKey;
}
@SuppressWarnings("unchecked")
@Override
public <T> T attachment() {
return (T) key;
}
@Override
public boolean isValid() {
return !canceled.get() && key.isValid();
}
@Override
public long submit(IoOps ops) {
if (!isValid()) {
return -1;
}
int v = cast(ops).value;
key.interestOps(v);
return v;
}
@Override
public boolean cancel() {
if (!canceled.compareAndSet(false, true)) {
return false;
}
key.cancel();
cancelledKeys++;
if (cancelledKeys >= CLEANUP_INTERVAL) {
cancelledKeys = 0;
needsToSelectAgain = true;
}
handle.unregistered();
return true;
}
void close() {
cancel();
try {
handle.close();
} catch (Exception e) {
logger.debug("Exception during closing " + handle, e);
}
}
void handle(int ready) {
if (!isValid()) {
return;
}
handle.handle(this, NioIoOps.eventOf(ready));
}
}
@Override
public IoRegistration register(IoHandle handle)
throws Exception {
NioIoHandle nioHandle = nioHandle(handle);
NioIoOps ops = NioIoOps.NONE;
boolean selected = false;
for (;;) {
try {
IoRegistration registration = new DefaultNioRegistration(executor, nioHandle, ops, unwrappedSelector());
handle.registered();
return registration;
} catch (CancelledKeyException e) {
if (!selected) {
// Force the Selector to select now as the "canceled" SelectionKey may still be
// cached and not removed because no Select.select(..) operation was called yet.
selectNow();
selected = true;
} else {
// We forced a select operation on the selector before but the SelectionKey is still cached
// for whatever reason. JDK bug ?
throw e;
}
}
}
}
@Override
public int run(IoHandlerContext context) {
int handled = 0;
try {
try {
switch (selectStrategy.calculateStrategy(selectNowSupplier, !context.canBlock())) {
case SelectStrategy.CONTINUE:
if (context.shouldReportActiveIoTime()) {
context.reportActiveIoTime(0); // Report zero as we did no I/O.
}
return 0;
case SelectStrategy.BUSY_WAIT:
// fall-through to SELECT since the busy-wait is not supported with NIO
case SelectStrategy.SELECT:
select(context, wakenUp.getAndSet(false));
// 'wakenUp.compareAndSet(false, true)' is always evaluated
// before calling 'selector.wakeup()' to reduce the wake-up
// overhead. (Selector.wakeup() is an expensive operation.)
//
// However, there is a race condition in this approach.
// The race condition is triggered when 'wakenUp' is set to
// true too early.
//
// 'wakenUp' is set to true too early if:
// 1) Selector is waken up between 'wakenUp.set(false)' and
// 'selector.select(...)'. (BAD)
// 2) Selector is waken up between 'selector.select(...)' and
// 'if (wakenUp.get()) { ... }'. (OK)
//
// In the first case, 'wakenUp' is set to true and the
// following 'selector.select(...)' will wake up immediately.
// Until 'wakenUp' is set to false again in the next round,
// 'wakenUp.compareAndSet(false, true)' will fail, and therefore
// any attempt to wake up the Selector will fail, too, causing
// the following 'selector.select(...)' call to block
// unnecessarily.
//
// To fix this problem, we wake up the selector again if wakenUp
// is true immediately after selector.select(...).
// It is inefficient in that it wakes up the selector for both
// the first case (BAD - wake-up required) and the second case
// (OK - no wake-up required).
if (wakenUp.get()) {
selector.wakeup();
}
// fall through
default:
}
} catch (IOException e) {
// If we receive an IOException here its because the Selector is messed up. Let's rebuild
// the selector and retry. https://github.com/netty/netty/issues/8566
rebuildSelector0();
handleLoopException(e);
return 0;
}
cancelledKeys = 0;
needsToSelectAgain = false;
if (context.shouldReportActiveIoTime()) {
// We start the timer after the blocking select() call has returned.
long activeIoStartTimeNanos = System.nanoTime();
handled = processSelectedKeys();
long activeIoEndTimeNanos = System.nanoTime();
context.reportActiveIoTime(activeIoEndTimeNanos - activeIoStartTimeNanos);
} else {
handled = processSelectedKeys();
}
} catch (Error e) {
throw e;
} catch (Throwable t) {
handleLoopException(t);
}
return handled;
}
private static void handleLoopException(Throwable t) {
logger.warn("Unexpected exception in the selector loop.", t);
// Prevent possible consecutive immediate failures that lead to
// excessive CPU consumption.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore.
}
}
private int processSelectedKeys() {
if (selectedKeys != null) {
return processSelectedKeysOptimized();
} else {
return processSelectedKeysPlain(selector.selectedKeys());
}
}
@Override
public void destroy() {
try {
selector.close();
} catch (IOException e) {
logger.warn("Failed to close a selector.", e);
}
}
private int processSelectedKeysPlain(Set<SelectionKey> selectedKeys) {
// check if the set is empty and if so just return to not create garbage by
// creating a new Iterator every time even if there is nothing to process.
// See https://github.com/netty/netty/issues/597
if (selectedKeys.isEmpty()) {
return 0;
}
Iterator<SelectionKey> i = selectedKeys.iterator();
int handled = 0;
for (;;) {
final SelectionKey k = i.next();
i.remove();
processSelectedKey(k);
++handled;
if (!i.hasNext()) {
break;
}
if (needsToSelectAgain) {
selectAgain();
selectedKeys = selector.selectedKeys();
// Create the iterator again to avoid ConcurrentModificationException
if (selectedKeys.isEmpty()) {
break;
} else {
i = selectedKeys.iterator();
}
}
}
return handled;
}
private int processSelectedKeysOptimized() {
int handled = 0;
for (int i = 0; i < selectedKeys.size; ++i) {
final SelectionKey k = selectedKeys.keys[i];
// null out entry in the array to allow to have it GC'ed once the Channel close
// See https://github.com/netty/netty/issues/2363
selectedKeys.keys[i] = null;
processSelectedKey(k);
++handled;
if (needsToSelectAgain) {
// null out entries in the array to allow to have it GC'ed once the Channel close
// See https://github.com/netty/netty/issues/2363
selectedKeys.reset(i + 1);
selectAgain();
i = -1;
}
}
return handled;
}
private void processSelectedKey(SelectionKey k) {
final DefaultNioRegistration registration = (DefaultNioRegistration) k.attachment();
if (!registration.isValid()) {
try {
registration.handle.close();
} catch (Exception e) {
logger.debug("Exception during closing " + registration.handle, e);
}
return;
}
registration.handle(k.readyOps());
}
@Override
public void prepareToDestroy() {
selectAgain();
Set<SelectionKey> keys = selector.keys();
Collection<DefaultNioRegistration> registrations = new ArrayList<>(keys.size());
for (SelectionKey k: keys) {
DefaultNioRegistration handle = (DefaultNioRegistration) k.attachment();
registrations.add(handle);
}
for (DefaultNioRegistration reg: registrations) {
reg.close();
}
}
@Override
public void wakeup() {
if (!executor.isExecutorThread(Thread.currentThread()) && wakenUp.compareAndSet(false, true)) {
selector.wakeup();
}
}
@Override
public boolean isCompatible(Class<? extends IoHandle> handleType) {
return NioIoHandle.class.isAssignableFrom(handleType);
}
Selector unwrappedSelector() {
return unwrappedSelector;
}
private void select(IoHandlerContext runner, boolean oldWakenUp) throws IOException {
Selector selector = this.selector;
try {
int selectCnt = 0;
long currentTimeNanos = System.nanoTime();
long selectDeadLineNanos = currentTimeNanos + runner.delayNanos(currentTimeNanos);
for (;;) {
long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L;
if (timeoutMillis <= 0) {
if (selectCnt == 0) {
selector.selectNow();
selectCnt = 1;
}
break;
}
// If a task was submitted when wakenUp value was true, the task didn't get a chance to call
// Selector#wakeup. So we need to check task queue again before executing select operation.
// If we don't, the task might be pended until select operation was timed out.
// It might be pended until idle timeout if IdleStateHandler existed in pipeline.
if (!runner.canBlock() && wakenUp.compareAndSet(false, true)) {
selector.selectNow();
selectCnt = 1;
break;
}
int selectedKeys = selector.select(timeoutMillis);
selectCnt ++;
if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || !runner.canBlock()) {
// - Selected something,
// - waken up by user, or
// - the task queue has a pending task.
// - a scheduled task is ready for processing
break;
}
if (Thread.interrupted()) {
// Thread was interrupted so reset selected keys and break so we not run into a busy loop.
// As this is most likely a bug in the handler of the user or it's client library we will
// also log it.
//
// See https://github.com/netty/netty/issues/2426
if (logger.isDebugEnabled()) {
logger.debug("Selector.select() returned prematurely because " +
"Thread.currentThread().interrupt() was called. Use " +
"NioHandler.shutdownGracefully() to shutdown the NioHandler.");
}
selectCnt = 1;
break;
}
long time = System.nanoTime();
if (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) >= currentTimeNanos) {
// timeoutMillis elapsed without anything selected.
selectCnt = 1;
} else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 &&
selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) {
// The code exists in an extra method to ensure the method is not too big to inline as this
// branch is not very likely to get hit very frequently.
selector = selectRebuildSelector(selectCnt);
selectCnt = 1;
break;
}
currentTimeNanos = time;
}
if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) {
if (logger.isDebugEnabled()) {
logger.debug("Selector.select() returned prematurely {} times in a row for Selector {}.",
selectCnt - 1, selector);
}
}
} catch (CancelledKeyException e) {
if (logger.isDebugEnabled()) {
logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector {} - JDK bug?",
selector, e);
}
// Harmless exception - log anyway
}
}
int selectNow() throws IOException {
try {
return selector.selectNow();
} finally {
// restore wakeup state if needed
if (wakenUp.get()) {
selector.wakeup();
}
}
}
private Selector selectRebuildSelector(int selectCnt) throws IOException {
// The selector returned prematurely many times in a row.
// Rebuild the selector to work around the problem.
logger.warn(
"Selector.select() returned prematurely {} times in a row; rebuilding Selector {}.",
selectCnt, selector);
rebuildSelector0();
Selector selector = this.selector;
// Select again to populate selectedKeys.
selector.selectNow();
return selector;
}
private void selectAgain() {
needsToSelectAgain = false;
try {
selector.selectNow();
} catch (Throwable t) {
logger.warn("Failed to update SelectionKeys.", t);
}
}
/**
* Returns a new {@link IoHandlerFactory} that creates {@link NioIoHandler} instances
*
* @return factory the {@link IoHandlerFactory}.
*/
public static IoHandlerFactory newFactory() {
return newFactory(SelectorProvider.provider(), DefaultSelectStrategyFactory.INSTANCE);
}
/**
* Returns a new {@link IoHandlerFactory} that creates {@link NioIoHandler} instances.
*
* @param selectorProvider the {@link SelectorProvider} to use.
* @return factory the {@link IoHandlerFactory}.
*/
public static IoHandlerFactory newFactory(SelectorProvider selectorProvider) {
return newFactory(selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
}
/**
* Returns a new {@link IoHandlerFactory} that creates {@link NioIoHandler} instances.
*
* @param selectorProvider the {@link SelectorProvider} to use.
* @param selectStrategyFactory the {@link SelectStrategyFactory} to use.
* @return factory the {@link IoHandlerFactory}.
*/
public static IoHandlerFactory newFactory(final SelectorProvider selectorProvider,
final SelectStrategyFactory selectStrategyFactory) {
ObjectUtil.checkNotNull(selectorProvider, "selectorProvider");
ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory");
return new IoHandlerFactory() {
@Override
public IoHandler newHandler(ThreadAwareExecutor executor) {
return new NioIoHandler(executor, selectorProvider, selectStrategyFactory.newSelectStrategy());
}
@Override
public boolean isChangingThreadSupported() {
return true;
}
};
}
}
| DefaultNioRegistration |
java | apache__dubbo | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockThreadPool.java | {
"start": 978,
"end": 1109
} | class ____ implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
return null;
}
}
| MockThreadPool |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/http/HttpConnection.java | {
"start": 1184,
"end": 9435
} | interface ____ {
/**
* @return the current connection window size or {@code -1} for HTTP/1.x
*/
default int getWindowSize() {
return -1;
}
/**
* Update the current connection wide window size to a new size.
* <p/>
* Increasing this value, gives better performance when several data streams are multiplexed
* <p/>
* This is not implemented for HTTP/1.x.
*
* @param windowSize the new window size
* @return a reference to this, so the API can be used fluently
*/
@Fluent
default HttpConnection setWindowSize(int windowSize) {
return this;
}
/**
* Like {@link #goAway(long, int)} with a last stream id {@code -1} which means to disallow any new stream creation.
*/
@Fluent
default HttpConnection goAway(long errorCode) {
return goAway(errorCode, -1);
}
/**
* Like {@link #goAway(long, int, Buffer)} with no buffer.
*/
@Fluent
default HttpConnection goAway(long errorCode, int lastStreamId) {
return goAway(errorCode, lastStreamId, null);
}
/**
* Send a go away frame to the remote endpoint of the connection.
* <p/>
* <ul>
* <li>a {@literal GOAWAY} frame is sent to the to the remote endpoint with the {@code errorCode} and {@code debugData}</li>
* <li>any stream created after the stream identified by {@code lastStreamId} will be closed</li>
* <li>for an {@literal errorCode} is different than {@code 0} when all the remaining streams are closed this connection will be closed automatically</li>
* </ul>
* <p/>
* This is not implemented for HTTP/1.x.
*
* @param errorCode the {@literal GOAWAY} error code
* @param lastStreamId the last stream id
* @param debugData additional debug data sent to the remote endpoint
* @return a reference to this, so the API can be used fluently
*/
@Fluent
HttpConnection goAway(long errorCode, int lastStreamId, Buffer debugData);
/**
* Set an handler called when a {@literal GOAWAY} frame is received.
* <p/>
* This is not implemented for HTTP/1.x.
*
* @param handler the handler
* @return a reference to this, so the API can be used fluently
*/
@Fluent
HttpConnection goAwayHandler(@Nullable Handler<GoAway> handler);
/**
* Set a {@code handler} notified when the HTTP connection is shutdown: the client or server will close the connection
* within a certain amount of time. This gives the opportunity to the {@code handler} to close the current requests in progress
* gracefully before the HTTP connection is forcefully closed.
*
* @param handler the handler
* @return a reference to this, so the API can be used fluently
*/
@Fluent
HttpConnection shutdownHandler(@Nullable Handler<Void> handler);
/**
* Shutdown with a 30 seconds timeout ({@code shutdown(30, TimeUnit.SECONDS)}).
*
* @return a future completed when shutdown has completed
*/
default Future<Void> shutdown() {
return shutdown(30, TimeUnit.SECONDS);
}
/**
* Initiate a graceful connection shutdown, the connection is taken out of service and closed when all the inflight requests
* are processed, otherwise after a {@code timeout} the connection will be closed. Client connection are immediately removed
* from the pool.
*
* <ul>
* <li>HTTP/2 connections will send a go away frame immediately to signal the other side the connection will close.</li>
* <li>HTTP/1.x connection will be closed.</li>
* </ul>
*
* @param timeout the amount of time after which all resources are forcibly closed
* @param unit the of the timeout
* @return a future completed when shutdown has completed
*/
Future<Void> shutdown(long timeout, TimeUnit unit);
/**
* Set a close handler. The handler will get notified when the connection is closed.
*
* @param handler the handler to be notified
* @return a reference to this, so the API can be used fluently
*/
@Fluent
HttpConnection closeHandler(Handler<Void> handler);
/**
* Close immediately ({@code shutdown(0, TimeUnit.SECONDS}).
*
* @return a future notified when the client is closed
*/
default Future<Void> close() {
return shutdown(0, TimeUnit.SECONDS);
}
/**
* @return the latest server settings acknowledged by the remote endpoint - this is not implemented for HTTP/1.x
*/
Http2Settings settings();
/**
* Send to the remote endpoint an update of this endpoint settings
* <p/>
* The {@code completionHandler} will be notified when the remote endpoint has acknowledged the settings.
* <p/>
* This is not implemented for HTTP/1.x.
*
* @param settings the new settings
* @return a future completed when the settings have been acknowledged by the remote endpoint
*/
Future<Void> updateSettings(Http2Settings settings);
/**
* @return the current remote endpoint settings for this connection - this is not implemented for HTTP/1.x
*/
Http2Settings remoteSettings();
/**
* Set an handler that is called when remote endpoint {@link Http2Settings} are updated.
* <p/>
* This is not implemented for HTTP/1.x.
*
* @param handler the handler for remote endpoint settings
* @return a reference to this, so the API can be used fluently
*/
@Fluent
HttpConnection remoteSettingsHandler(Handler<Http2Settings> handler);
/**
* Send a {@literal PING} frame to the remote endpoint.
* <p/>
* This is not implemented for HTTP/1.x.
*
* @param data the 8 bytes data of the frame
* @return a future notified with the pong reply or the failure
*/
Future<Buffer> ping(Buffer data);
/**
* Set an handler notified when a {@literal PING} frame is received from the remote endpoint.
* <p/>
* This is not implemented for HTTP/1.x.
*
* @param handler the handler to be called when a {@literal PING} is received
* @return a reference to this, so the API can be used fluently
*/
@Fluent
HttpConnection pingHandler(@Nullable Handler<Buffer> handler);
/**
* Set an handler called when a connection error happens
*
* @param handler the handler
* @return a reference to this, so the API can be used fluently
*/
@Fluent
HttpConnection exceptionHandler(Handler<Throwable> handler);
/**
* @return the remote address for this connection, possibly {@code null} (e.g a server bound on a domain socket).
* If {@code useProxyProtocol} is set to {@code true}, the address returned will be of the actual connecting client.
*/
@CacheReturn
SocketAddress remoteAddress();
/**
* Like {@link #remoteAddress()} but returns the proxy remote address when {@code real} is {@code true}
*/
SocketAddress remoteAddress(boolean real);
/**
* @return the local address for this connection, possibly {@code null} (e.g a server bound on a domain socket)
* If {@code useProxyProtocol} is set to {@code true}, the address returned will be of the proxy.
*/
@CacheReturn
SocketAddress localAddress();
/**
* Like {@link #localAddress()} ()} but returns the server local address when {@code real} is {@code true}
*/
SocketAddress localAddress(boolean real);
/**
* @return true if this {@link io.vertx.core.http.HttpConnection} is encrypted via SSL/TLS.
*/
boolean isSsl();
/**
* @return SSLSession associated with the underlying socket. Returns null if connection is
* not SSL.
* @see javax.net.ssl.SSLSession
*/
@GenIgnore(GenIgnore.PERMITTED_TYPE)
SSLSession sslSession();
/**
* @return an ordered list of the peer certificates. Returns null if connection is
* not SSL.
* @throws javax.net.ssl.SSLPeerUnverifiedException SSL peer's identity has not been verified.
* @see SSLSession#getPeerCertificates() ()
* @see #sslSession()
*/
@GenIgnore()
default List<Certificate> peerCertificates() throws SSLPeerUnverifiedException {
SSLSession session = sslSession();
if (session != null) {
return Arrays.asList(session.getPeerCertificates());
} else {
return null;
}
}
/**
* Returns the SNI server name presented during the SSL handshake by the client.
*
* @return the indicated server name
*/
String indicatedServerName();
}
| HttpConnection |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/TransactionAbortableException.java | {
"start": 847,
"end": 1166
} | class ____ extends ApiException {
private static final long serialVersionUID = 1L;
public TransactionAbortableException(String message, Throwable cause) {
super(message, cause);
}
public TransactionAbortableException(String message) {
super(message);
}
}
| TransactionAbortableException |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AMQPEndpointBuilderFactory.java | {
"start": 305549,
"end": 308101
} | interface ____ {
/**
* AMQP (camel-amqp)
* Messaging with AMQP protocol using Apache QPid Client.
*
* Category: messaging
* Since: 1.2
* Maven coordinates: org.apache.camel:camel-amqp
*
* @return the dsl builder for the headers' name.
*/
default AMQPHeaderNameBuilder amqp() {
return AMQPHeaderNameBuilder.INSTANCE;
}
/**
* AMQP (camel-amqp)
* Messaging with AMQP protocol using Apache QPid Client.
*
* Category: messaging
* Since: 1.2
* Maven coordinates: org.apache.camel:camel-amqp
*
* Syntax: <code>amqp:destinationType:destinationName</code>
*
* Path parameter: destinationType
* The kind of destination to use
* Default value: queue
* There are 4 enums and the value can be one of: queue, topic,
* temp-queue, temp-topic
*
* Path parameter: destinationName (required)
* Name of the queue or topic to use as destination
*
* @param path destinationType:destinationName
* @return the dsl builder
*/
default AMQPEndpointBuilder amqp(String path) {
return AMQPEndpointBuilderFactory.endpointBuilder("amqp", path);
}
/**
* AMQP (camel-amqp)
* Messaging with AMQP protocol using Apache QPid Client.
*
* Category: messaging
* Since: 1.2
* Maven coordinates: org.apache.camel:camel-amqp
*
* Syntax: <code>amqp:destinationType:destinationName</code>
*
* Path parameter: destinationType
* The kind of destination to use
* Default value: queue
* There are 4 enums and the value can be one of: queue, topic,
* temp-queue, temp-topic
*
* Path parameter: destinationName (required)
* Name of the queue or topic to use as destination
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path destinationType:destinationName
* @return the dsl builder
*/
default AMQPEndpointBuilder amqp(String componentName, String path) {
return AMQPEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the AMQP component.
*/
public static | AMQPBuilders |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/ToDynamicVariableTest.java | {
"start": 973,
"end": 3609
} | class ____ extends ContextTestSupport {
@Test
public void testSend() throws Exception {
getMockEndpoint("mock:before").expectedBodiesReceived("World");
getMockEndpoint("mock:before").expectedVariableReceived("hello", "Camel");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel");
getMockEndpoint("mock:result").expectedVariableReceived("hello", "Camel");
template.sendBodyAndHeader("direct:send", "World", "where", "foo");
assertMockEndpointsSatisfied();
}
@Test
public void testReceive() throws Exception {
getMockEndpoint("mock:after").expectedBodiesReceived("World");
getMockEndpoint("mock:after").expectedVariableReceived("bye", "Bye World");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:result").expectedVariableReceived("bye", "Bye World");
template.sendBodyAndHeader("direct:receive", "World", "where", "foo");
assertMockEndpointsSatisfied();
}
@Test
public void testSendAndReceive() throws Exception {
getMockEndpoint("mock:before").expectedBodiesReceived("World");
getMockEndpoint("mock:before").expectedVariableReceived("hello", "Camel");
getMockEndpoint("mock:result").expectedBodiesReceived("World");
getMockEndpoint("mock:result").expectedVariableReceived("bye", "Bye Camel");
template.sendBodyAndHeader("direct:sendAndReceive", "World", "where", "foo");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:send")
.setVariable("hello", simple("Camel"))
.to("mock:before")
.toD("direct:${header.where}", "hello", null)
.to("mock:result");
from("direct:receive")
.toD("direct:${header.where}", null, "bye")
.to("mock:after")
.setBody(simple("${variable:bye}"))
.to("mock:result");
from("direct:sendAndReceive")
.setVariable("hello", simple("Camel"))
.to("mock:before")
.toD("direct:${header.where}", "hello", "bye")
.to("mock:result");
from("direct:foo")
.transform().simple("Bye ${body}");
}
};
}
}
| ToDynamicVariableTest |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/commit/TestMagicCommitPaths.java | {
"start": 1333,
"end": 6649
} | class ____ extends Assertions {
private static final List<String> MAGIC_AT_ROOT =
list(MAGIC_PATH_PREFIX);
private static final List<String> MAGIC_AT_ROOT_WITH_CHILD =
list(MAGIC_PATH_PREFIX, "child");
private static final List<String> MAGIC_WITH_CHILD =
list("parent", MAGIC_PATH_PREFIX, "child");
private static final List<String> MAGIC_AT_WITHOUT_CHILD =
list("parent", MAGIC_PATH_PREFIX);
private static final List<String> DEEP_MAGIC =
list("parent1", "parent2", MAGIC_PATH_PREFIX, "child1", "child2");
public static final String[] EMPTY = {};
@Test
public void testSplitPathEmpty() throws Throwable {
intercept(IllegalArgumentException.class,
() -> splitPathToElements(new Path("")));
}
@Test
public void testSplitPathDoubleBackslash() {
assertPathSplits("//", EMPTY);
}
@Test
public void testSplitRootPath() {
assertPathSplits("/", EMPTY);
}
@Test
public void testSplitBasic() {
assertPathSplits("/a/b/c",
new String[]{"a", "b", "c"});
}
@Test
public void testSplitTrailingSlash() {
assertPathSplits("/a/b/c/",
new String[]{"a", "b", "c"});
}
@Test
public void testSplitShortPath() {
assertPathSplits("/a",
new String[]{"a"});
}
@Test
public void testSplitShortPathTrailingSlash() {
assertPathSplits("/a/",
new String[]{"a"});
}
@Test
public void testParentsMagicRoot() {
assertParents(EMPTY, MAGIC_AT_ROOT);
}
@Test
public void testChildrenMagicRoot() {
assertChildren(EMPTY, MAGIC_AT_ROOT);
}
@Test
public void testParentsMagicRootWithChild() {
assertParents(EMPTY, MAGIC_AT_ROOT_WITH_CHILD);
}
@Test
public void testChildMagicRootWithChild() {
assertChildren(a("child"), MAGIC_AT_ROOT_WITH_CHILD);
}
@Test
public void testChildrenMagicWithoutChild() {
assertChildren(EMPTY, MAGIC_AT_WITHOUT_CHILD);
}
@Test
public void testChildMagicWithChild() {
assertChildren(a("child"), MAGIC_WITH_CHILD);
}
@Test
public void testParentMagicWithChild() {
assertParents(a("parent"), MAGIC_WITH_CHILD);
}
@Test
public void testParentDeepMagic() {
assertParents(a("parent1", "parent2"), DEEP_MAGIC);
}
@Test
public void testChildrenDeepMagic() {
assertChildren(a("child1", "child2"), DEEP_MAGIC);
}
@Test
public void testLastElementEmpty() throws Throwable {
intercept(IllegalArgumentException.class,
() -> lastElement(new ArrayList<>(0)));
}
@Test
public void testLastElementSingle() {
assertEquals("first", lastElement(l("first")));
}
@Test
public void testLastElementDouble() {
assertEquals("2", lastElement(l("first", "2")));
}
@Test
public void testFinalDestinationNoMagic() {
assertEquals(l("first", "2"),
finalDestination(l("first", "2")));
}
@Test
public void testFinalDestinationMagic1() {
assertEquals(l("first", "2"),
finalDestination(l("first", MAGIC_PATH_PREFIX, "2")));
}
@Test
public void testFinalDestinationMagic2() {
assertEquals(l("first", "3.txt"),
finalDestination(l("first", MAGIC_PATH_PREFIX, "2", "3.txt")));
}
@Test
public void testFinalDestinationRootMagic2() {
assertEquals(l("3.txt"),
finalDestination(l(MAGIC_PATH_PREFIX, "2", "3.txt")));
}
@Test
public void testFinalDestinationMagicNoChild() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
finalDestination(l(MAGIC_PATH_PREFIX));
});
}
@Test
public void testFinalDestinationBaseDirectChild() {
finalDestination(l(MAGIC_PATH_PREFIX, BASE, "3.txt"));
}
@Test
public void testFinalDestinationBaseNoChild() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
assertEquals(l(), finalDestination(l(MAGIC_PATH_PREFIX, BASE)));
});
}
@Test
public void testFinalDestinationBaseSubdirsChild() {
assertEquals(l("2", "3.txt"),
finalDestination(l(MAGIC_PATH_PREFIX, "4", BASE, "2", "3.txt")));
}
/**
* If the base is above the magic dir, it's ignored.
*/
@Test
public void testFinalDestinationIgnoresBaseBeforeMagic() {
assertEquals(l(BASE, "home", "3.txt"),
finalDestination(l(BASE, "home", MAGIC_PATH_PREFIX, "2", "3.txt")));
}
/** varargs to array. */
private static String[] a(String... str) {
return str;
}
/** list to array. */
private static List<String> l(String... str) {
return Arrays.asList(str);
}
/**
* Varags to list.
* @param args arguments
* @return a list
*/
private static List<String> list(String... args) {
return Lists.newArrayList(args);
}
public void assertParents(String[] expected, List<String> elements) {
assertListEquals(expected, magicPathParents(elements));
}
public void assertChildren(String[] expected, List<String> elements) {
assertListEquals(expected, magicPathChildren(elements));
}
private void assertPathSplits(String pathString, String[] expected) {
Path path = new Path(pathString);
assertArrayEquals(expected,
splitPathToElements(path).toArray(), "From path " + path);
}
private void assertListEquals(String[] expected, List<String> actual) {
assertArrayEquals(expected, actual.toArray());
}
}
| TestMagicCommitPaths |
java | quarkusio__quarkus | integration-tests/gradle/src/test/java/io/quarkus/gradle/nativeimage/NativeIntegrationTestIT.java | {
"start": 472,
"end": 2231
} | class ____ extends QuarkusNativeGradleITBase {
@InjectSoftAssertions
SoftAssertions soft;
@Test
public void nativeTestShouldRunIntegrationTest() throws Exception {
File projectDir = getProjectDir("it-test-basic-project");
BuildResult testResult = runGradleWrapper(projectDir, "clean", "testNative");
soft.assertThat(testResult.getTasks().get(":testNative")).isIn(BuildResult.SUCCESS_OUTCOME, BuildResult.FROM_CACHE);
soft.assertThat(projectDir.toPath().resolve("build/code-with-quarkus-1.0.0-SNAPSHOT-runner")).isRegularFile()
.isExecutable();
}
@Test
public void runNativeTestsWithOutputName() throws Exception {
final File projectDir = getProjectDir("it-test-basic-project");
final BuildResult testResult = runGradleWrapper(projectDir, "clean", "testNative",
"-Dquarkus.package.output-name=test");
soft.assertThat(testResult.getTasks().get(":testNative")).isIn(BuildResult.SUCCESS_OUTCOME, BuildResult.FROM_CACHE);
soft.assertThat(projectDir.toPath().resolve("build/test-runner")).isRegularFile().isExecutable();
}
@Test
public void runNativeTestsWithoutRunnerSuffix() throws Exception {
final File projectDir = getProjectDir("it-test-basic-project");
final BuildResult testResult = runGradleWrapper(projectDir, "clean", "testNative",
"-Dquarkus.package.jar.add-runner-suffix=false");
soft.assertThat(testResult.getTasks().get(":testNative")).isIn(BuildResult.SUCCESS_OUTCOME, BuildResult.FROM_CACHE);
soft.assertThat(projectDir.toPath().resolve("build/code-with-quarkus-1.0.0-SNAPSHOT")).isRegularFile()
.isExecutable();
}
}
| NativeIntegrationTestIT |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/TestDFSIO.java | {
"start": 22461,
"end": 25043
} | class ____ extends IOStatMapper {
private ThreadLocalRandom rnd;
private long fileSize;
private long skipSize;
@Override // Mapper
public void configure(JobConf conf) {
super.configure(conf);
skipSize = conf.getLong("test.io.skip.size", 0);
}
public RandomReadMapper() {
rnd = ThreadLocalRandom.current();
}
@Override // IOMapperBase
public Closeable getIOStream(String name) throws IOException {
Path filePath = new Path(getDataDir(getConf()), name);
this.fileSize = fs.getFileStatus(filePath).getLen();
InputStream in = fs.open(filePath);
if(compressionCodec != null)
in = new FSDataInputStream(compressionCodec.createInputStream(in));
LOG.info("in = " + in.getClass().getName());
LOG.info("skipSize = " + skipSize);
return in;
}
@Override // IOMapperBase
public Long doIO(Reporter reporter,
String name,
long totalSize // in bytes
) throws IOException {
PositionedReadable in = (PositionedReadable)this.stream;
long actualSize = 0;
for(long pos = nextOffset(-1);
actualSize < totalSize; pos = nextOffset(pos)) {
int curSize = in.read(pos, buffer, 0, bufferSize);
if(curSize < 0) break;
actualSize += curSize;
reporter.setStatus("reading " + name + "@" +
actualSize + "/" + totalSize
+ " ::host = " + hostName);
}
return Long.valueOf(actualSize);
}
/**
* Get next offset for reading.
* If current < 0 then choose initial offset according to the read type.
*
* @param current offset
* @return
*/
private long nextOffset(long current) {
if (skipSize == 0)
return rnd.nextLong(fileSize);
if(skipSize > 0)
return (current < 0) ? 0 : (current + bufferSize + skipSize);
// skipSize < 0
return (current < 0) ? Math.max(0, fileSize - bufferSize) :
Math.max(0, current + skipSize);
}
}
private long randomReadTest(FileSystem fs) throws IOException {
Path readDir = getRandomReadDir(config);
fs.delete(readDir, true);
long tStart = System.currentTimeMillis();
runIOTest(RandomReadMapper.class, readDir);
long execTime = System.currentTimeMillis() - tStart;
return execTime;
}
/**
* Truncate mapper class.
* The mapper truncates given file to the newLength, specified by -size.
*/
public static | RandomReadMapper |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RedeliverToSubRouteTest.java | {
"start": 2543,
"end": 2957
} | class ____ implements Processor {
private int counter;
@Override
public void process(Exchange exchange) throws Exception {
// use a processor to simulate error in the first 2 calls
if (counter++ < 2) {
throw new IOException("Forced");
}
exchange.getIn().setBody("Bye World");
}
}
// END SNIPPET: e2
}
| MyProcessor |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/index/IndexResolution.java | {
"start": 514,
"end": 4848
} | class ____ {
/**
* @param index EsIndex encapsulating requested index expression, resolved mappings and index modes from field-caps.
* @param resolvedIndices Set of concrete indices resolved by field-caps. (This information is not always present in the EsIndex).
* @param failures failures occurred during field-caps.
* @return valid IndexResolution
*/
public static IndexResolution valid(EsIndex index, Set<String> resolvedIndices, Map<String, List<FieldCapabilitiesFailure>> failures) {
Objects.requireNonNull(index, "index must not be null if it was found");
Objects.requireNonNull(resolvedIndices, "resolvedIndices must not be null");
Objects.requireNonNull(failures, "failures must not be null");
return new IndexResolution(index, null, resolvedIndices, failures);
}
/**
* Use this method only if the set of concrete resolved indices is the same as EsIndex#concreteIndices().
*/
public static IndexResolution valid(EsIndex index) {
return valid(index, index.concreteQualifiedIndices(), Map.of());
}
public static IndexResolution empty(String indexPattern) {
return valid(new EsIndex(indexPattern, Map.of(), Map.of(), Map.of(), Map.of(), Set.of()));
}
public static IndexResolution invalid(String invalid) {
Objects.requireNonNull(invalid, "invalid must not be null to signal that the index is invalid");
return new IndexResolution(null, invalid, Set.of(), Map.of());
}
public static IndexResolution notFound(String name) {
Objects.requireNonNull(name, "name must not be null");
return invalid("Unknown index [" + name + "]");
}
private final EsIndex index;
@Nullable
private final String invalid;
// all indices found by field-caps
private final Set<String> resolvedIndices;
// map from cluster alias to failures that occurred during field-caps.
private final Map<String, List<FieldCapabilitiesFailure>> failures;
private IndexResolution(
EsIndex index,
@Nullable String invalid,
Set<String> resolvedIndices,
Map<String, List<FieldCapabilitiesFailure>> failures
) {
this.index = index;
this.invalid = invalid;
this.resolvedIndices = resolvedIndices;
this.failures = failures;
}
public boolean matches(String indexName) {
return isValid() && this.index.name().equals(indexName);
}
/**
* Get the {@linkplain EsIndex}
* @throws MappingException if the index is invalid for use with ql
*/
public EsIndex get() {
if (invalid != null) {
throw new MappingException(invalid);
}
return index;
}
/**
* Is the index valid for use with ql?
* @return {@code false} if the index wasn't found.
*/
public boolean isValid() {
return invalid == null;
}
/**
* @return Map from cluster alias to failures that occurred during field-caps.
*/
public Map<String, List<FieldCapabilitiesFailure>> failures() {
return failures;
}
/**
* @return all indices found by field-caps (regardless of whether they had any mappings)
*/
public Set<String> resolvedIndices() {
return resolvedIndices;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
IndexResolution other = (IndexResolution) obj;
return Objects.equals(index, other.index)
&& Objects.equals(invalid, other.invalid)
&& Objects.equals(resolvedIndices, other.resolvedIndices)
&& Objects.equals(failures, other.failures);
}
@Override
public int hashCode() {
return Objects.hash(index, invalid, resolvedIndices, failures);
}
@Override
public String toString() {
return invalid != null
? invalid
: "IndexResolution{"
+ "index="
+ index
+ ", invalid='"
+ invalid
+ '\''
+ ", resolvedIndices="
+ resolvedIndices
+ ", unavailableClusters="
+ failures
+ '}';
}
}
| IndexResolution |
java | apache__camel | components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaPreConsumedTest.java | {
"start": 1092,
"end": 2306
} | class ____ extends AbstractJpaTest {
protected static final String SELECT_ALL_STRING = "select x from " + SendEmail.class.getName() + " x";
@Test
public void testPreConsumed() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBody("direct:start", new SendEmail("dummy"));
MockEndpoint.assertIsSatisfied(context);
// @PreConsumed should change the dummy address
SendEmail email = mock.getReceivedExchanges().get(0).getIn().getBody(SendEmail.class);
assertEquals("dummy@somewhere.org", email.getAddress());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").to("jpa://" + SendEmail.class.getName());
from("jpa://" + SendEmail.class.getName()).to("mock:result");
}
};
}
@Override
protected String routeXml() {
return "org/apache/camel/processor/jpa/springJpaRouteTest.xml";
}
@Override
protected String selectAllString() {
return SELECT_ALL_STRING;
}
}
| JpaPreConsumedTest |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractor.java | {
"start": 1312,
"end": 4448
} | class ____ implements BucketExtractor {
static final String NAME = "th";
private final String name;
private final DataType fieldDataType;
private final ZoneId zoneId;
public TopHitsAggExtractor(String name, DataType fieldDataType, ZoneId zoneId) {
this.name = name;
this.fieldDataType = fieldDataType;
this.zoneId = zoneId;
}
TopHitsAggExtractor(StreamInput in) throws IOException {
name = in.readString();
fieldDataType = SqlDataTypes.fromTypeName(in.readString());
zoneId = SqlStreamInput.asSqlStream(in).zoneId();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeString(fieldDataType.typeName());
}
String name() {
return name;
}
DataType fieldDataType() {
return fieldDataType;
}
ZoneId zoneId() {
return zoneId;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public Object extract(Bucket bucket) {
InternalTopHits agg = bucket.getAggregations().get(name);
if (agg == null) {
throw new SqlIllegalArgumentException("Cannot find an aggregation named {}", name);
}
if (agg.getHits().getTotalHits() == null || agg.getHits().getTotalHits().value() == 0) {
return null;
}
Object value = agg.getHits().getAt(0).getDocumentFields().values().iterator().next().getValue();
if (fieldDataType == DATETIME || fieldDataType == DATE) {
return DateUtils.asDateTimeWithNanos(value.toString()).withZoneSameInstant(zoneId());
} else if (SqlDataTypes.isTimeBased(fieldDataType)) {
return DateUtils.asTimeOnly(Long.parseLong(value.toString()), zoneId);
} else if (fieldDataType == UNSIGNED_LONG) {
if (value == null) {
return null;
} else if (value instanceof Number number) {
// values can be returned either as unsigned_longs or longs (if range allows), which can lead to cast exceptions
// when sorting rows locally -> upcast to BigInteger
return toUnsignedLong(number);
} else {
throw new SqlIllegalArgumentException("Invalid unsigned_long key returned: {}", value);
}
} else {
return value;
}
}
@Override
public int hashCode() {
return Objects.hash(name, fieldDataType, zoneId);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
TopHitsAggExtractor other = (TopHitsAggExtractor) obj;
return Objects.equals(name, other.name)
&& Objects.equals(fieldDataType, other.fieldDataType)
&& Objects.equals(zoneId, other.zoneId);
}
@Override
public String toString() {
return "TopHits>" + name + "[" + fieldDataType + "]@" + zoneId;
}
}
| TopHitsAggExtractor |
java | quarkusio__quarkus | extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/customized/QuarkusConnectionProvider.java | {
"start": 317,
"end": 1824
} | class ____ implements ConnectionProvider {
private final AgroalDataSource dataSource;
public QuarkusConnectionProvider(final AgroalDataSource dataSource) {
this.dataSource = dataSource;
}
public AgroalDataSource getDataSource() {
return dataSource;
}
@Override
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
@Override
public void closeConnection(final Connection connection) throws SQLException {
connection.close();
}
@Override
public boolean supportsAggressiveRelease() {
return true;
}
@Override
public boolean isUnwrappableAs(final Class unwrapType) {
return ConnectionProvider.class.equals(unwrapType) ||
QuarkusConnectionProvider.class.isAssignableFrom(unwrapType) ||
DataSource.class.isAssignableFrom(unwrapType) ||
AgroalDataSource.class.isAssignableFrom(unwrapType);
}
@Override
public <T> T unwrap(final Class<T> unwrapType) {
if (ConnectionProvider.class.equals(unwrapType) ||
QuarkusConnectionProvider.class.isAssignableFrom(unwrapType)) {
return (T) this;
} else if (DataSource.class.isAssignableFrom(unwrapType) || AgroalDataSource.class.isAssignableFrom(unwrapType)) {
return (T) dataSource;
} else {
throw new UnknownUnwrapTypeException(unwrapType);
}
}
}
| QuarkusConnectionProvider |
java | google__guava | guava-tests/test/com/google/common/collect/ImmutableSortedMultisetTest.java | {
"start": 21457,
"end": 22396
} | class ____<E> extends HashSet<E> {
boolean toArrayCalled = false;
@Override
public Object[] toArray() {
toArrayCalled = true;
return super.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
toArrayCalled = true;
return super.toArray(a);
}
}
// Test that toArray() is used to make a defensive copy in copyOf(), so concurrently modified
// synchronized collections can be safely copied.
SortedMultiset<String> toCopy = mock(SortedMultiset.class);
TestHashSet<Entry<String>> entrySet = new TestHashSet<>();
when((Comparator<Comparable<String>>) toCopy.comparator())
.thenReturn(Ordering.<Comparable<String>>natural());
when(toCopy.entrySet()).thenReturn(entrySet);
ImmutableSortedMultiset<String> unused = ImmutableSortedMultiset.copyOfSorted(toCopy);
assertTrue(entrySet.toArrayCalled);
}
private static | TestHashSet |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/resource/ResultSetReleaseWithStatementDelegationTest.java | {
"start": 2549,
"end": 2669
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
}
}
| Foo |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TaskTest.java | {
"start": 57259,
"end": 57757
} | class ____ extends AbstractInvokable {
public InvokableWithExceptionInInvoke(Environment environment) {
super(environment);
}
@Override
public void invoke() throws Exception {
throw new Exception("test");
}
@Override
public void cleanUp(Throwable throwable) throws Exception {
wasCleanedUp = true;
super.cleanUp(throwable);
}
}
private static final | InvokableWithExceptionInInvoke |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8594AtFileTest.java | {
"start": 1107,
"end": 2326
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify Maven picks up params/goals from atFile.
*/
@Test
void testIt() throws Exception {
Path basedir = extractResources("/mng-8594").getAbsoluteFile().toPath();
Verifier verifier = newVerifier(basedir.toString());
verifier.addCliArgument("-af");
verifier.addCliArgument("cmd.txt");
verifier.addCliArgument("-Dcolor1=green");
verifier.addCliArgument("-Dcolor2=blue");
verifier.addCliArgument("clean");
verifier.execute();
verifier.verifyErrorFreeLog();
// clean did run
verifier.verifyTextInLog("(default-clean) @ root");
// validate bound plugin did run
verifier.verifyTextInLog("(eval) @ root");
// validate properties
List<String> properties = verifier.loadLines("target/pom.properties");
assertTrue(properties.contains("session.executionProperties.color1=green")); // CLI only
assertTrue(properties.contains("session.executionProperties.color2=blue")); // both
assertTrue(properties.contains("session.executionProperties.color3=yellow")); // cmd.txt only
}
}
| MavenITmng8594AtFileTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/action/UnifiedCompletionAction.java | {
"start": 855,
"end": 1190
} | class ____ extends ActionType<InferenceAction.Response> {
public static final UnifiedCompletionAction INSTANCE = new UnifiedCompletionAction();
public static final String NAME = "cluster:internal/xpack/inference/unified";
public UnifiedCompletionAction() {
super(NAME);
}
public static | UnifiedCompletionAction |
java | apache__camel | components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpServer.java | {
"start": 1786,
"end": 9334
} | class ____ extends ServiceSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(KnativeHttpServer.class);
private final CamelContext context;
private final String host;
private final int port;
private final String path;
private final BlockingQueue<HttpServerRequest> requests;
private final Handler<RoutingContext> handler;
private Vertx vertx;
private Router router;
private ExecutorService executor;
private HttpServer server;
public KnativeHttpServer(CamelContext context) {
this(context, "localhost", AvailablePortFinder.getNextAvailable(), "/", null);
}
public KnativeHttpServer(CamelContext context, int port) {
this(context, "localhost", port, "/", null);
}
public KnativeHttpServer(CamelContext context, int port, Handler<RoutingContext> handler) {
this(context, "localhost", port, "/", handler);
}
public KnativeHttpServer(CamelContext context, Handler<RoutingContext> handler) {
this(context, "localhost", AvailablePortFinder.getNextAvailable(), "/", handler);
}
public KnativeHttpServer(CamelContext context, String host, int port, String path) {
this(context, host, port, path, null);
}
public KnativeHttpServer(CamelContext context, String host, String path) {
this(context, host, AvailablePortFinder.getNextAvailable(), path, null);
}
public KnativeHttpServer(CamelContext context, String host, String path, Handler<RoutingContext> handler) {
this(context, host, AvailablePortFinder.getNextAvailable(), path, handler);
}
public KnativeHttpServer(CamelContext context, String host, int port, String path, Handler<RoutingContext> handler) {
this.context = context;
this.host = host;
this.port = port;
this.path = path;
this.requests = new LinkedBlockingQueue<>();
this.handler = handler != null
? handler
: event -> {
event.response().setStatusCode(200);
event.response().end();
};
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getPath() {
return path;
}
public HttpServerRequest poll(int timeout, TimeUnit unit) throws InterruptedException {
return requests.poll(timeout, unit);
}
@Override
protected void doStart() {
this.executor = context.getExecutorServiceManager().newSingleThreadExecutor(this, "knative-http-server");
this.vertx = Vertx.vertx();
this.server = vertx.createHttpServer(getServerOptions());
this.router = Router.router(vertx);
this.router.route(path)
.handler(event -> {
event.request().resume();
BodyHandler.create().handle(event);
})
.handler(event -> {
boolean success = this.requests.offer(event.request());
if (success) {
event.next();
} else {
event.fail(new RuntimeCamelException("Failed to save request to in-memory storage"));
}
})
.handler(handler);
CompletableFuture.runAsync(
() -> {
CountDownLatch latch = new CountDownLatch(1);
server.requestHandler(router).listen(port, host, result -> {
try {
if (result.failed()) {
LOGGER.warn("Failed to start Vert.x HttpServer on {}:{}, reason: {}",
host,
port,
result.cause().getMessage());
throw new RuntimeException(result.cause());
}
LOGGER.info("Vert.x HttpServer started on {}:{}", host, port);
} finally {
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
},
executor).toCompletableFuture().join();
}
@Override
protected void doStop() throws Exception {
try {
if (server != null) {
CompletableFuture.runAsync(
() -> {
CountDownLatch latch = new CountDownLatch(1);
// remove the platform-http component
context.removeComponent(PlatformHttpConstants.PLATFORM_HTTP_COMPONENT_NAME);
server.close(result -> {
try {
if (result.failed()) {
LOGGER.warn("Failed to close Vert.x HttpServer reason: {}",
result.cause().getMessage());
throw new RuntimeException(result.cause());
}
LOGGER.info("Vert.x HttpServer stopped");
} finally {
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
},
executor).toCompletableFuture().join();
}
} finally {
this.server = null;
}
if (vertx != null) {
Future<?> future = executor.submit(
() -> {
CountDownLatch latch = new CountDownLatch(1);
vertx.close(result -> {
try {
if (result.failed()) {
LOGGER.warn("Failed to close Vert.x reason: {}",
result.cause().getMessage());
throw new RuntimeException(result.cause());
}
LOGGER.info("Vert.x stopped");
} finally {
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
try {
future.get();
} finally {
vertx = null;
}
}
if (executor != null) {
context.getExecutorServiceManager().shutdown(executor);
executor = null;
}
}
protected HttpServerOptions getServerOptions() {
return new HttpServerOptions();
}
public int getNumberOfRequestsRemaining() {
return requests.size();
}
}
| KnativeHttpServer |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/deployment/TaskDeploymentDescriptorTestUtils.java | {
"start": 1728,
"end": 3836
} | class ____ {
public static ShuffleDescriptor[] deserializeShuffleDescriptors(
List<MaybeOffloaded<ShuffleDescriptorGroup>> maybeOffloaded,
JobID jobId,
TestingBlobWriter blobWriter)
throws IOException, ClassNotFoundException {
Map<Integer, ShuffleDescriptor> shuffleDescriptorsMap = new HashMap<>();
int maxIndex = 0;
for (MaybeOffloaded<ShuffleDescriptorGroup> sd : maybeOffloaded) {
ShuffleDescriptorGroup shuffleDescriptorGroup;
if (sd instanceof NonOffloaded) {
shuffleDescriptorGroup =
((NonOffloaded<ShuffleDescriptorGroup>) sd)
.serializedValue.deserializeValue(
ClassLoader.getSystemClassLoader());
} else {
final CompressedSerializedValue<ShuffleDescriptorGroup> compressedSerializedValue =
CompressedSerializedValue.fromBytes(
blobWriter.getBlob(
jobId,
((Offloaded<ShuffleDescriptorGroup>) sd)
.serializedValueKey));
shuffleDescriptorGroup =
compressedSerializedValue.deserializeValue(
ClassLoader.getSystemClassLoader());
}
for (ShuffleDescriptorAndIndex shuffleDescriptorAndIndex :
shuffleDescriptorGroup.getShuffleDescriptors()) {
int index = shuffleDescriptorAndIndex.getIndex();
maxIndex = Math.max(maxIndex, shuffleDescriptorAndIndex.getIndex());
shuffleDescriptorsMap.put(index, shuffleDescriptorAndIndex.getShuffleDescriptor());
}
}
ShuffleDescriptor[] shuffleDescriptors = new ShuffleDescriptor[maxIndex + 1];
shuffleDescriptorsMap.forEach((key, value) -> shuffleDescriptors[key] = value);
return shuffleDescriptors;
}
}
| TaskDeploymentDescriptorTestUtils |
java | netty__netty | transport/src/main/java/io/netty/channel/socket/DatagramChannel.java | {
"start": 3556,
"end": 3813
} | interface ____ notifies the {@link ChannelFuture} once the
* operation completes.
*/
ChannelFuture leaveGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface);
/**
* Leaves a multicast group on a specified local | and |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/availability/ReadinessState.java | {
"start": 1033,
"end": 1251
} | enum ____ implements AvailabilityState {
/**
* The application is ready to receive traffic.
*/
ACCEPTING_TRAFFIC,
/**
* The application is not willing to receive traffic.
*/
REFUSING_TRAFFIC
}
| ReadinessState |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/BeanLiteModeTests.java | {
"start": 2416,
"end": 2533
} | class ____ extends BaseConfig {
@Bean
@Override
String bean2() {
return "xyz";
}
}
static | OverridingConfig |
java | google__guice | core/src/com/google/inject/internal/util/SourceProvider.java | {
"start": 3044,
"end": 3405
} | class ____ cannot be null.");
for (final String moduleClassName : moduleClassNames) {
if (!shouldBeSkipped(moduleClassName)) {
return new StackTraceElement(moduleClassName, "configure", null, -1);
}
}
return UNKNOWN_SOURCE;
}
private static CallerFinder loadCallerFinder() {
return new DirectStackWalkerFinder();
}
}
| names |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest.java | {
"start": 247,
"end": 1215
} | class ____ extends TestCase {
public void test_factory() throws Exception {
VO vo = JSON.parseObject("{\"b\":true,\"i\":33,\"l\":34,\"f\":45.}", VO.class);
Assert.assertEquals(true, vo.isB());
Assert.assertEquals(33, vo.getI());
Assert.assertEquals(34L, vo.getL());
Assert.assertTrue(45f == vo.getF());
JSON.parseObject("{\"b\":1,\"i\":33,\"l\":34,\"f\":45.}", VO.class);
}
public void test_factory1() throws Exception {
V1 vo = JSON.parseObject("{\"b\":true,\"i\":33,\"l\":34,\"f\":45.}", V1.class);
Assert.assertEquals(true, vo.isB());
Assert.assertEquals(33, vo.getI());
Assert.assertEquals(34L, vo.getL());
Assert.assertTrue(45f == vo.getF());
JSON.parseObject("{\"b\":1,\"i\":33,\"l\":34,\"f\":45.}", V1.class);
// JSON.parseObject("{\"b\":true,\"i\":33,\"l\":34,\"f\":45.}").toJavaObject(V1.class);
}
public static | FactoryTest |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/api/Schema.java | {
"start": 2740,
"end": 2992
} | class ____ basic validation,
* however, the main validation happens during the resolution. Thus, an unresolved schema can be
* incomplete and might be enriched or merged with a different schema at a later stage.
*
* <p>Since an instance of this | perform |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ComparableTypeTest.java | {
"start": 1999,
"end": 2293
} | class ____ implements Comparable<Double>, Comparator<Double> {
@Override
public int compareTo(Double o) {
return 0;
}
@Override
public int compare(Double o1, Double o2) {
return 0;
}
}
// BUG: Diagnostic contains: [ComparableType]
public static | BadClass |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java | {
"start": 12186,
"end": 13399
} | interface ____ on a super parameterized type's type arguments. This method is the inverse of
* {@link #getTypeArguments(Type, Class)} which gets a class/interface's type arguments based on a subtype. It is far more limited in determining the type
* arguments for the subject class's type variables in that it can only determine those parameters that map from the subject {@link Class} object to the
* supertype.
*
* <p>
* Example: {@link java.util.TreeSet TreeSet} sets its parameter as the parameter for {@link java.util.NavigableSet NavigableSet}, which in turn sets the
* parameter of {@link java.util.SortedSet}, which in turn sets the parameter of {@link Set}, which in turn sets the parameter of
* {@link java.util.Collection}, which in turn sets the parameter of {@link Iterable}. Since {@link TreeSet}'s parameter maps (indirectly) to
* {@link Iterable}'s parameter, it will be able to determine that based on the super type {@code Iterable<? extends
* Map<Integer, ? extends Collection<?>>>}, the parameter of {@link TreeSet} is {@code ? extends Map<Integer, ? extends
* Collection<?>>}.
* </p>
*
* @param cls the | based |
java | spring-projects__spring-framework | spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java | {
"start": 24585,
"end": 24659
} | class ____ {
public int getAge() {
return 10;
}
}
static | TestBean5 |
java | apache__camel | components/camel-leveldb/src/test/java/org/apache/camel/component/leveldb/LevelDBAggregateRecoverWithRedeliveryPolicyTest.java | {
"start": 1436,
"end": 4569
} | class ____ extends LevelDBTestSupport {
private static Map<SerializerType, AtomicInteger> counters = new ConcurrentHashMap();
private static AtomicInteger getCounter(SerializerType serializerType) {
AtomicInteger counter = counters.get(serializerType);
if (counter == null) {
counter = new AtomicInteger();
counters.put(serializerType, counter);
}
return counter;
}
@Override
public void doPreSetup() throws Exception {
deleteDirectory("target/data");
// enable recovery
getRepo().setUseRecovery(true);
// check faster
getRepo().setRecoveryInterval(500, TimeUnit.MILLISECONDS);
}
@Test
public void testLevelDBAggregateRecover() throws Exception {
getMockEndpoint("mock:aggregated").setResultWaitTime(20000);
getMockEndpoint("mock:result").setResultWaitTime(20000);
// should fail the first 3 times and then recover
getMockEndpoint("mock:aggregated").expectedMessageCount(4);
getMockEndpoint("mock:result").expectedBodiesReceived("ABCDE");
// should be marked as redelivered
getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERED).isEqualTo(Boolean.TRUE);
// on the 2nd redelivery attempt we success
getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERY_COUNTER).isEqualTo(3);
getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERY_MAX_COUNTER).isNull();
template.sendBodyAndHeader("direct:start", "A", "id", 123);
template.sendBodyAndHeader("direct:start", "B", "id", 123);
template.sendBodyAndHeader("direct:start", "C", "id", 123);
template.sendBodyAndHeader("direct:start", "D", "id", 123);
template.sendBodyAndHeader("direct:start", "E", "id", 123);
MockEndpoint.assertIsSatisfied(context, 30, TimeUnit.SECONDS);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.aggregate(header("id"), new StringAggregationStrategy())
.completionSize(5).aggregationRepository(getRepo())
// this is the output from the aggregator
.log("aggregated exchange id ${exchangeId} with ${body}")
.to("mock:aggregated")
// simulate errors the first three times
.process(new Processor() {
public void process(Exchange exchange) {
int count = getCounter(getSerializerType()).incrementAndGet();
if (count <= 3) {
throw new IllegalArgumentException("Damn");
}
}
})
.to("mock:result")
.end();
}
};
}
}
| LevelDBAggregateRecoverWithRedeliveryPolicyTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.