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 | elastic__elasticsearch | server/src/main/java/org/elasticsearch/inference/configuration/SettingsConfigurationFieldType.java | {
"start": 528,
"end": 1278
} | enum ____ {
STRING("str"),
INTEGER("int"),
LIST("list"),
BOOLEAN("bool"),
MAP("map");
private final String value;
SettingsConfigurationFieldType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
public static SettingsConfigurationFieldType fieldType(String type) {
for (SettingsConfigurationFieldType fieldType : SettingsConfigurationFieldType.values()) {
if (fieldType.value.equals(type)) {
return fieldType;
}
}
throw new IllegalArgumentException("Unknown " + SettingsConfigurationFieldType.class.getSimpleName() + " [" + type + "].");
}
}
| SettingsConfigurationFieldType |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_have_Test.java | {
"start": 957,
"end": 1427
} | class ____ extends AtomicReferenceArrayAssertBaseTest {
private Condition<Object> condition;
@BeforeEach
void before() {
condition = new TestCondition<>();
}
@Override
protected AtomicReferenceArrayAssert<Object> invoke_api_method() {
return assertions.doNotHave(condition);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertDoNotHave(info(), internalArray(), condition);
}
}
| AtomicReferenceArrayAssert_have_Test |
java | lettuce-io__lettuce-core | src/test/java/biz/paluch/redis/extensibility/MyRedisClusterConnection.java | {
"start": 1273,
"end": 1611
} | class ____<K, V> extends StatefulRedisClusterConnectionImpl<K, V> {
public MyRedisClusterConnection(RedisChannelWriter writer, ClusterPushHandler pushHandler, RedisCodec<K, V> codec,
Duration timeout, Supplier<JsonParser> parser) {
super(writer, pushHandler, codec, timeout, parser);
}
}
| MyRedisClusterConnection |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/service/TransportGetServiceAccountCredentialsAction.java | {
"start": 1055,
"end": 2066
} | class ____ extends HandledTransportAction<
GetServiceAccountCredentialsRequest,
GetServiceAccountCredentialsResponse> {
private final ServiceAccountService serviceAccountService;
@Inject
public TransportGetServiceAccountCredentialsAction(
TransportService transportService,
ActionFilters actionFilters,
ServiceAccountService serviceAccountService
) {
super(
GetServiceAccountCredentialsAction.NAME,
transportService,
actionFilters,
GetServiceAccountCredentialsRequest::new,
EsExecutors.DIRECT_EXECUTOR_SERVICE
);
this.serviceAccountService = serviceAccountService;
}
@Override
protected void doExecute(
Task task,
GetServiceAccountCredentialsRequest request,
ActionListener<GetServiceAccountCredentialsResponse> listener
) {
serviceAccountService.findTokensFor(request, listener);
}
}
| TransportGetServiceAccountCredentialsAction |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/IncidentEventContext.java | {
"start": 12822,
"end": 13165
} | interface ____ {
ParseField TYPE = new ParseField("type");
ParseField HREF = new ParseField("href");
// "link" context fields
ParseField TEXT = new ParseField("text");
// "image" context fields
ParseField SRC = new ParseField("src");
ParseField ALT = new ParseField("alt");
}
}
| XField |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByBinderTest.java | {
"start": 3041,
"end": 3295
} | class ____ {
final Super f = null;
Super g() {
return null;
}
final Object lock = new Object();
}
| Super |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/query/KvStateLocation.java | {
"start": 1463,
"end": 9840
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
/** JobID the KvState instances belong to. */
private final JobID jobId;
/** JobVertexID the KvState instances belong to. */
private final JobVertexID jobVertexId;
/** Number of key groups of the operator the KvState instances belong to. */
private final int numKeyGroups;
/** Name under which the KvState instances have been registered. */
private final String registrationName;
/** IDs for each KvState instance where array index corresponds to key group index. */
private final KvStateID[] kvStateIds;
/**
* Server address for each KvState instance where array index corresponds to key group index.
*/
private final InetSocketAddress[] kvStateAddresses;
/** Current number of registered key groups. */
private int numRegisteredKeyGroups;
/**
* Creates the location information.
*
* @param jobId JobID the KvState instances belong to
* @param jobVertexId JobVertexID the KvState instances belong to
* @param numKeyGroups Number of key groups of the operator
* @param registrationName Name under which the KvState instances have been registered
*/
public KvStateLocation(
JobID jobId, JobVertexID jobVertexId, int numKeyGroups, String registrationName) {
this.jobId = Preconditions.checkNotNull(jobId, "JobID");
this.jobVertexId = Preconditions.checkNotNull(jobVertexId, "JobVertexID");
Preconditions.checkArgument(numKeyGroups >= 0, "Negative number of key groups");
this.numKeyGroups = numKeyGroups;
this.registrationName = Preconditions.checkNotNull(registrationName, "Registration name");
this.kvStateIds = new KvStateID[numKeyGroups];
this.kvStateAddresses = new InetSocketAddress[numKeyGroups];
}
/**
* Returns the JobID the KvState instances belong to.
*
* @return JobID the KvState instances belong to
*/
public JobID getJobId() {
return jobId;
}
/**
* Returns the JobVertexID the KvState instances belong to.
*
* @return JobVertexID the KvState instances belong to
*/
public JobVertexID getJobVertexId() {
return jobVertexId;
}
/**
* Returns the number of key groups of the operator the KvState instances belong to.
*
* @return Number of key groups of the operator the KvState instances belong to
*/
public int getNumKeyGroups() {
return numKeyGroups;
}
/**
* Returns the name under which the KvState instances have been registered.
*
* @return Name under which the KvState instances have been registered.
*/
public String getRegistrationName() {
return registrationName;
}
/**
* Returns the current number of registered key groups.
*
* @return Number of registered key groups.
*/
public int getNumRegisteredKeyGroups() {
return numRegisteredKeyGroups;
}
/**
* Returns the registered KvStateID for the key group index or <code>null</code> if none is
* registered yet.
*
* @param keyGroupIndex Key group index to get ID for.
* @return KvStateID for the key group index or <code>null</code> if none is registered yet
* @throws IndexOutOfBoundsException If key group index < 0 or >= Number of key groups
*/
public KvStateID getKvStateID(int keyGroupIndex) {
if (keyGroupIndex < 0 || keyGroupIndex >= numKeyGroups) {
throw new IndexOutOfBoundsException("Key group index");
}
return kvStateIds[keyGroupIndex];
}
/**
* Returns the registered server address for the key group index or <code>null</code> if none is
* registered yet.
*
* @param keyGroupIndex Key group index to get server address for.
* @return the server address for the key group index or <code>null</code> if none is registered
* yet
* @throws IndexOutOfBoundsException If key group index < 0 or >= Number of key groups
*/
public InetSocketAddress getKvStateServerAddress(int keyGroupIndex) {
if (keyGroupIndex < 0 || keyGroupIndex >= numKeyGroups) {
throw new IndexOutOfBoundsException("Key group index");
}
return kvStateAddresses[keyGroupIndex];
}
/**
* Registers a KvState instance for the given key group index.
*
* @param keyGroupRange Key group range to register
* @param kvStateId ID of the KvState instance at the key group index.
* @param kvStateAddress Server address of the KvState instance at the key group index.
* @throws IndexOutOfBoundsException If key group range start < 0 or key group range end >=
* Number of key groups
*/
public void registerKvState(
KeyGroupRange keyGroupRange, KvStateID kvStateId, InetSocketAddress kvStateAddress) {
if (keyGroupRange.getStartKeyGroup() < 0
|| keyGroupRange.getEndKeyGroup() >= numKeyGroups) {
throw new IndexOutOfBoundsException("Key group index");
}
for (int kgIdx = keyGroupRange.getStartKeyGroup();
kgIdx <= keyGroupRange.getEndKeyGroup();
++kgIdx) {
if (kvStateIds[kgIdx] == null && kvStateAddresses[kgIdx] == null) {
numRegisteredKeyGroups++;
}
kvStateIds[kgIdx] = kvStateId;
kvStateAddresses[kgIdx] = kvStateAddress;
}
}
/**
* Registers a KvState instance for the given key group index.
*
* @param keyGroupRange Key group range to unregister.
* @throws IndexOutOfBoundsException If key group range start < 0 or key group range end >=
* Number of key groups
* @throws IllegalArgumentException If no location information registered for a key group index
* in the range.
*/
void unregisterKvState(KeyGroupRange keyGroupRange) {
if (keyGroupRange.getStartKeyGroup() < 0
|| keyGroupRange.getEndKeyGroup() >= numKeyGroups) {
throw new IndexOutOfBoundsException("Key group index");
}
for (int kgIdx = keyGroupRange.getStartKeyGroup();
kgIdx <= keyGroupRange.getEndKeyGroup();
++kgIdx) {
if (kvStateIds[kgIdx] == null || kvStateAddresses[kgIdx] == null) {
throw new IllegalArgumentException(
"Not registered. Probably registration/unregistration race.");
}
numRegisteredKeyGroups--;
kvStateIds[kgIdx] = null;
kvStateAddresses[kgIdx] = null;
}
}
@Override
public String toString() {
return "KvStateLocation{"
+ "jobId="
+ jobId
+ ", jobVertexId="
+ jobVertexId
+ ", parallelism="
+ numKeyGroups
+ ", kvStateIds="
+ Arrays.toString(kvStateIds)
+ ", kvStateAddresses="
+ Arrays.toString(kvStateAddresses)
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
KvStateLocation that = (KvStateLocation) o;
if (numKeyGroups != that.numKeyGroups) {
return false;
}
if (!jobId.equals(that.jobId)) {
return false;
}
if (!jobVertexId.equals(that.jobVertexId)) {
return false;
}
if (!registrationName.equals(that.registrationName)) {
return false;
}
if (!Arrays.equals(kvStateIds, that.kvStateIds)) {
return false;
}
return Arrays.equals(kvStateAddresses, that.kvStateAddresses);
}
@Override
public int hashCode() {
int result = jobId.hashCode();
result = 31 * result + jobVertexId.hashCode();
result = 31 * result + numKeyGroups;
result = 31 * result + registrationName.hashCode();
result = 31 * result + Arrays.hashCode(kvStateIds);
result = 31 * result + Arrays.hashCode(kvStateAddresses);
return result;
}
}
| KvStateLocation |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericManyToOneParameterTest.java | {
"start": 2985,
"end": 3038
} | interface ____ {
Long getId();
}
public | EntityWithId |
java | alibaba__nacos | config/src/main/java/com/alibaba/nacos/config/server/model/gray/GrayRule.java | {
"start": 741,
"end": 1691
} | interface ____ {
/**
* gray rule match labels or not.
*
* @date 2024/3/14
* @param labels conn labels.
* @return true if match, false otherwise.
*/
boolean match(Map<String, String> labels);
/**
* if the gray rule is valid.
*
* @date 2024/3/14
* @return true if valid, false otherwise.
*/
boolean isValid();
/**
* get gray rule type.
*
* @date 2024/3/14
* @return the gray rule type.
*/
String getType();
/**
* get gray rule version.
*
* @date 2024/3/14
* @return the gray rule version.
*/
String getVersion();
/**
* get gray rule priority.
*
* @date 2024/3/14
* @return the gray rule priority.
*/
int getPriority();
/**
* get raw String of gray rule.
*
* @date 2024/3/14
* @return the raw String of gray rule.
*/
String getRawGrayRuleExp();
}
| GrayRule |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/ldap/LdapSessionFactorySettings.java | {
"start": 695,
"end": 1289
} | class ____ {
public static final Setting.AffixSetting<List<String>> USER_DN_TEMPLATES_SETTING = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(LDAP_TYPE),
"user_dn_templates",
key -> Setting.stringListSetting(key, Setting.Property.NodeScope)
);
public static Set<Setting.AffixSetting<?>> getSettings() {
Set<Setting.AffixSetting<?>> settings = new HashSet<>();
settings.addAll(SessionFactorySettings.getSettings(LDAP_TYPE));
settings.add(USER_DN_TEMPLATES_SETTING);
return settings;
}
}
| LdapSessionFactorySettings |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/LiteEnumValueOfTest.java | {
"start": 2855,
"end": 3193
} | class ____ {
private TestEnum testMethod() {
return TestEnum.valueOf("FOO");
}
}
""")
.doTest();
}
@Test
public void negativeCaseJDK9OrAbove() {
compilationHelper
.addSourceLines(
"ProtoLiteEnum.java",
"""
| Usage |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java | {
"start": 6346,
"end": 8011
} | class ____
extends RemoteCalcSplitProjectionRuleBase<AsyncCalcSplitOnePerCalcRule.State> {
public AsyncCalcSplitOnePerCalcRule(RemoteCallFinder callFinder) {
super("AsyncCalcSplitOnePerCalcRule", callFinder);
}
@Override
public boolean matches(RelOptRuleCall call) {
FlinkLogicalCalc calc = call.rel(0);
List<RexNode> projects =
calc.getProgram().getProjectList().stream()
.map(calc.getProgram()::expandLocalRef)
.collect(Collectors.toList());
// If this has no nested calls, then this can be called to split up separate projections
// into two different calcs. We don't want the splitter to be called to with nested
// calls since it won't behave correctly, so this must be used in conjunction with the
// nested rule.
return !hasNestedCalls(projects)
&& projects.stream().filter(callFinder()::containsRemoteCall).count() >= 2;
}
@Override
public boolean needConvert(RexProgram program, RexNode node, Option<State> matchState) {
if (AsyncUtil.containsAsyncCall(node) && !matchState.get().foundMatch) {
matchState.get().foundMatch = true;
return true;
}
return false;
}
@Override
public Option<State> getMatchState() {
return Option.apply(new State());
}
/** State object used to keep track of whether a match has been found yet. */
public static | AsyncCalcSplitOnePerCalcRule |
java | elastic__elasticsearch | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/rest/action/RestStartTransformAction.java | {
"start": 1378,
"end": 3083
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, TransformField.REST_BASE_PATH_TRANSFORMS_BY_ID + "_start"));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) {
String id = restRequest.param(TransformField.ID.getPreferredName());
String fromAsString = restRequest.param(TransformField.FROM.getPreferredName());
Instant from = fromAsString != null ? parseDateOrThrow(fromAsString, TransformField.FROM, System::currentTimeMillis) : null;
TimeValue timeout = restRequest.paramAsTime(TransformField.TIMEOUT.getPreferredName(), AcknowledgedRequest.DEFAULT_ACK_TIMEOUT);
StartTransformAction.Request request = new StartTransformAction.Request(id, from, timeout);
return channel -> new RestCancellableNodeClient(client, restRequest.getHttpChannel()).execute(
StartTransformAction.INSTANCE,
request,
new RestToXContentListener<>(channel)
);
}
private static Instant parseDateOrThrow(String date, ParseField paramName, LongSupplier now) {
DateMathParser dateMathParser = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.toDateMathParser();
try {
return dateMathParser.parse(date, now);
} catch (Exception e) {
String msg = TransformMessages.getMessage(TransformMessages.FAILED_TO_PARSE_DATE, paramName.getPreferredName(), date);
throw new ElasticsearchParseException(msg, e);
}
}
@Override
public String getName() {
return "transform_start_transform_action";
}
}
| RestStartTransformAction |
java | micronaut-projects__micronaut-core | jackson-databind/src/main/java/io/micronaut/jackson/env/JsonPropertySourceLoader.java | {
"start": 1223,
"end": 2441
} | class ____ extends AbstractPropertySourceLoader {
/**
* File extension for property source loader.
*/
public static final String FILE_EXTENSION = "json";
public JsonPropertySourceLoader() {
}
public JsonPropertySourceLoader(boolean logEnabled) {
super(logEnabled);
}
@Override
public Set<String> getExtensions() {
return Collections.singleton(FILE_EXTENSION);
}
@Override
protected void processInput(String name, InputStream input, Map<String, Object> finalMap) throws IOException {
Map<String, Object> map = readJsonAsMap(input);
processMap(finalMap, map, "");
}
/**
* @param input The input stream
* @return map representation of the json
* @throws IOException If the input stream doesn't exist
*/
protected Map<String, Object> readJsonAsMap(InputStream input) throws IOException {
var objectMapper = new ObjectMapper(new JsonFactory());
TypeFactory factory = objectMapper.getTypeFactory();
MapType mapType = factory.constructMapType(LinkedHashMap.class, String.class, Object.class);
return objectMapper.readValue(input, mapType);
}
}
| JsonPropertySourceLoader |
java | micronaut-projects__micronaut-core | router/src/test/java/io/micronaut/web/router/uri/WhatwgParser.java | {
"start": 50180,
"end": 50649
} | enum ____ {
SCHEME_START,
SCHEME,
NO_SCHEME,
SPECIAL_RELATIVE_OR_AUTHORITY,
PATH_OR_AUTHORITY,
RELATIVE,
RELATIVE_SLASH,
SPECIAL_AUTHORITY_SLASHES,
SPECIAL_AUTHORITY_IGNORE_SLASHES,
AUTHORITY,
HOST,
HOSTNAME,
PORT,
FILE,
FILE_SLASH,
FILE_HOST,
PATH_START,
PATH,
OPAQUE_PATH,
QUERY,
FRAGMENT,
}
}
| State |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java | {
"start": 1954,
"end": 5484
} | class ____ extends AbstractTagTests {
public static final String COMMAND_NAME = "testBean";
private StringWriter writer;
private MockPageContext pageContext;
@BeforeEach
public final void setUp() throws Exception {
// set up a writer for the tag content to be written to
this.writer = new StringWriter();
// configure the page context
this.pageContext = createAndPopulatePageContext();
onSetUp();
}
protected MockPageContext createAndPopulatePageContext() throws JspException {
MockPageContext pageContext = createPageContext();
MockHttpServletRequest request = (MockHttpServletRequest) pageContext.getRequest();
((StaticWebApplicationContext) RequestContextUtils.findWebApplicationContext(request))
.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
extendRequest(request);
extendPageContext(pageContext);
RequestContext requestContext = new JspAwareRequestContext(pageContext);
pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, requestContext);
return pageContext;
}
protected void extendPageContext(MockPageContext pageContext) throws JspException {
}
protected void extendRequest(MockHttpServletRequest request) {
}
protected void onSetUp() {
}
protected MockPageContext getPageContext() {
return this.pageContext;
}
protected Writer getWriter() {
return this.writer;
}
protected String getOutput() {
return this.writer.toString();
}
protected final RequestContext getRequestContext() {
return (RequestContext) getPageContext().getAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE);
}
protected RequestDataValueProcessor getMockRequestDataValueProcessor() {
RequestDataValueProcessor mockProcessor = mock();
HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
WebApplicationContext wac = RequestContextUtils.findWebApplicationContext(request);
wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);
return mockProcessor;
}
protected void exposeBindingResult(Errors errors) {
// wrap errors in a Model
Map<String, Object> model = Collections.singletonMap(
BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors);
// replace the request context with one containing the errors
MockPageContext pageContext = getPageContext();
RequestContext context = new RequestContext((HttpServletRequest) pageContext.getRequest(), model);
pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, context);
}
protected final void assertContainsAttribute(String output, String attributeName, String attributeValue) {
String attributeString = attributeName + "=\"" + attributeValue + "\"";
assertThat(output).as("Expected to find attribute '" + attributeName +
"' with value '" + attributeValue +
"' in output + '" + output + "'").contains(attributeString);
}
protected final void assertAttributeNotPresent(String output, String attributeName) {
assertThat(output).as("Unexpected attribute '" + attributeName + "' in output '" + output + "'.")
.doesNotContain(attributeName + "=\"");
}
protected final void assertBlockTagContains(String output, String desiredContents) {
String contents = output.substring(output.indexOf(">") + 1, output.lastIndexOf('<'));
assertThat(contents).as("Expected to find '" + desiredContents + "' in the contents of block tag '" + output + "'")
.contains(desiredContents);
}
}
| AbstractHtmlElementTagTests |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/PublicApiNamedStreamShouldReturnStream.java | {
"start": 1758,
"end": 2744
} | class ____ extends BugChecker
implements MethodTreeMatcher {
private static final String STREAM = "stream";
private static final Matcher<MethodTree> CONFUSING_PUBLIC_API_STREAM_MATCHER =
allOf(
methodIsNamed(STREAM),
methodHasVisibility(MethodVisibility.Visibility.PUBLIC),
PublicApiNamedStreamShouldReturnStream::returnTypeDoesNotEndsWithStream);
private static boolean returnTypeDoesNotEndsWithStream(
MethodTree methodTree, VisitorState state) {
Type returnType = ASTHelpers.getSymbol(methodTree).getReturnType();
// Constructors have no return type.
return returnType != null && !returnType.tsym.getSimpleName().toString().endsWith("Stream");
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!CONFUSING_PUBLIC_API_STREAM_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
}
| PublicApiNamedStreamShouldReturnStream |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/EnableWebMvc.java | {
"start": 2078,
"end": 2755
} | class ____ have the
* {@code @EnableWebMvc} annotation to import the Spring Web MVC
* configuration. There can however be multiple {@code @Configuration} classes
* implementing {@code WebMvcConfigurer} in order to customize the provided
* configuration.
*
* <p>If {@link WebMvcConfigurer} does not expose some more advanced setting that
* needs to be configured, consider removing the {@code @EnableWebMvc}
* annotation and extending directly from {@link WebMvcConfigurationSupport}
* or {@link DelegatingWebMvcConfiguration}, for example:
*
* <pre class="code">
* @Configuration
* @ComponentScan(basePackageClasses = { MyConfiguration.class })
* public | may |
java | elastic__elasticsearch | test/framework/src/test/java/org/elasticsearch/test/test/LoggingListenerTests.java | {
"start": 15625,
"end": 15760
} | class ____ an invalid {@link TestLogging} annotation.
*/
@TestLogging(value = "abc", reason = "testing an invalid TestLogging | with |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToBase64Evaluator.java | {
"start": 4623,
"end": 5392
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory field;
private final Function<DriverContext, BytesRefBuilder> oScratch;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory field,
Function<DriverContext, BytesRefBuilder> oScratch) {
this.source = source;
this.field = field;
this.oScratch = oScratch;
}
@Override
public ToBase64Evaluator get(DriverContext context) {
return new ToBase64Evaluator(source, field.get(context), oScratch.apply(context), context);
}
@Override
public String toString() {
return "ToBase64Evaluator[" + "field=" + field + "]";
}
}
}
| Factory |
java | alibaba__nacos | config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigOpsControllerTest.java | {
"start": 2540,
"end": 6575
} | class ____ {
@InjectMocks
ConfigOpsController configOpsController;
@Mock
DumpService dumpService;
MockedStatic<DatasourceConfiguration> datasourceConfigurationMockedStatic;
MockedStatic<DynamicDataSource> dynamicDataSourceMockedStatic;
MockedStatic<ApplicationUtils> applicationUtilsMockedStatic;
private MockMvc mockMvc;
@Mock
private ServletContext servletContext;
@AfterEach
void after() {
datasourceConfigurationMockedStatic.close();
dynamicDataSourceMockedStatic.close();
applicationUtilsMockedStatic.close();
ConfigCommonConfig.getInstance().setDerbyOpsEnabled(false);
}
@BeforeEach
void init() {
when(servletContext.getContextPath()).thenReturn("/nacos");
ReflectionTestUtils.setField(configOpsController, "dumpService", dumpService);
mockMvc = MockMvcBuilders.standaloneSetup(configOpsController).build();
datasourceConfigurationMockedStatic = Mockito.mockStatic(DatasourceConfiguration.class);
dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class);
applicationUtilsMockedStatic = Mockito.mockStatic(ApplicationUtils.class);
}
@Test
void testUpdateLocalCacheFromStore() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.OPS_CONTROLLER_PATH + "/localCache");
int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus();
assertEquals(200, actualValue);
}
@Test
void testSetLogLevel() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put(Constants.OPS_CONTROLLER_PATH + "/log").param("logName", "test")
.param("logLevel", "test");
int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus();
assertEquals(200, actualValue);
}
@Test
void testDerbyOps() throws Exception {
ConfigCommonConfig.getInstance().setDerbyOpsEnabled(true);
datasourceConfigurationMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true);
DynamicDataSource dataSource = Mockito.mock(DynamicDataSource.class);
dynamicDataSourceMockedStatic.when(DynamicDataSource::getInstance).thenReturn(dataSource);
LocalDataSourceServiceImpl dataSourceService = Mockito.mock(LocalDataSourceServiceImpl.class);
when(dataSource.getDataSource()).thenReturn(dataSourceService);
JdbcTemplate template = Mockito.mock(JdbcTemplate.class);
when(dataSourceService.getJdbcTemplate()).thenReturn(template);
when(template.queryForList("SELECT * FROM TEST")).thenReturn(new ArrayList<>());
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.OPS_CONTROLLER_PATH + "/derby")
.param("sql", "SELECT * FROM TEST");
String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString();
assertEquals("200", JacksonUtils.toObj(actualValue).get("code").toString());
}
@Test
void testImportDerby() throws Exception {
ConfigCommonConfig.getInstance().setDerbyOpsEnabled(true);
datasourceConfigurationMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true);
applicationUtilsMockedStatic.when(() -> ApplicationUtils.getBean(DatabaseOperate.class))
.thenReturn(Mockito.mock(DatabaseOperate.class));
MockMultipartFile file = new MockMultipartFile("file", "test.zip", "application/zip", "test".getBytes());
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.OPS_CONTROLLER_PATH + "/data/removal")
.file(file);
int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus();
assertEquals(200, actualValue);
}
}
| ConfigOpsControllerTest |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderBuilderTest.java | {
"start": 1650,
"end": 5444
} | class ____ {
private HttpAppender.Builder<?> getBuilder() {
Configuration mockConfig = new DefaultConfiguration();
return HttpAppender.newBuilder().setConfiguration(mockConfig).setName("TestHttpAppender"); // Name is required
}
@Test
@UsingStatusListener
void testBuilderWithoutUrl(final ListStatusListener listener) throws Exception {
HttpAppender appender = HttpAppender.newBuilder()
.setConfiguration(new DefaultConfiguration())
.setName("TestAppender")
.setLayout(JsonLayout.createDefaultLayout()) // Providing a layout here
.build();
assertThat(listener.findStatusData(Level.ERROR))
.anyMatch(statusData ->
statusData.getMessage().getFormattedMessage().contains("HttpAppender requires URL to be set."));
}
@Test
@UsingStatusListener
void testBuilderWithUrlAndWithoutLayout(final ListStatusListener listener) throws Exception {
HttpAppender appender = HttpAppender.newBuilder()
.setConfiguration(new DefaultConfiguration())
.setName("TestAppender")
.setUrl(new URL("http://localhost:8080/logs"))
.build();
assertThat(listener.findStatusData(Level.ERROR)).anyMatch(statusData -> statusData
.getMessage()
.getFormattedMessage()
.contains("HttpAppender requires a layout to be set."));
}
@Test
void testBuilderWithValidConfiguration() throws Exception {
URL url = new URL("http://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout();
HttpAppender.Builder<?> builder = getBuilder().setUrl(url).setLayout(layout);
HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with valid configuration.");
}
@Test
void testBuilderWithCustomMethod() throws Exception {
URL url = new URL("http://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout();
String customMethod = "PUT";
HttpAppender.Builder<?> builder =
getBuilder().setUrl(url).setLayout(layout).setMethod(customMethod);
HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with a custom HTTP method.");
}
@Test
void testBuilderWithHeaders() throws Exception {
URL url = new URL("http://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout();
Property[] headers = new Property[] {
Property.createProperty("Header1", "Value1"), Property.createProperty("Header2", "Value2")
};
HttpAppender.Builder<?> builder =
getBuilder().setUrl(url).setLayout(layout).setHeaders(headers);
HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with headers.");
}
@Test
void testBuilderWithSslConfiguration() throws Exception {
URL url = new URL("https://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout();
// Use real SslConfiguration instead of Mockito mock
SslConfiguration sslConfig = SslConfiguration.createSSLConfiguration(null, null, null, false);
HttpAppender.Builder<?> builder =
getBuilder().setUrl(url).setLayout(layout).setSslConfiguration(sslConfig);
HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with SSL configuration.");
}
@Test
void testBuilderWithInvalidUrl() {
assertThrows(MalformedURLException.class, () -> new URL("invalid-url"));
}
}
| HttpAppenderBuilderTest |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/common/runtime/src/test/java/org/jboss/resteasy/reactive/common/util/EncodeTest.java | {
"start": 219,
"end": 878
} | class ____ {
@Test
void encodeEmoji() {
String emoji = "\uD83D\uDE00\uD83D\uDE00\uD83D\uDE00\uD83D\uDE00\uD83D\uDE00\uD83D\uDE00\uD83D\uDE00\uD83D\uDE00";
String encodedEmoji = URLEncoder.encode(emoji, StandardCharsets.UTF_8);
assertEquals(encodedEmoji, Encode.encodePath(emoji));
assertEquals(encodedEmoji, Encode.encodeQueryParam(emoji));
}
@Test
void encodeQuestionMarkQueryParameterValue() {
String uriQueryValue = "bar?a=b";
String encoded = URLEncoder.encode(uriQueryValue, StandardCharsets.UTF_8);
assertEquals(encoded, Encode.encodeQueryParam(uriQueryValue));
}
}
| EncodeTest |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/pkg/PackageConfig.java | {
"start": 6416,
"end": 10105
} | interface ____ {
/**
* Whether to automate the creation of AppCDS.
* Care must be taken to use the same exact JVM version when building and running the application.
*/
@WithDefault("false")
boolean enabled();
/**
* When AppCDS generation is enabled, if this property is set, then the JVM used to generate the AppCDS file
* will be the JVM present in the container image. The builder image is expected to have the 'java' binary
* on its PATH.
* This flag is useful when the JVM to be used at runtime is not the same exact JVM version as the one used to build
* the jar.
* Note that this property is consulted only when {@code quarkus.package.jar.appcds.enabled=true} and it requires
* having
* docker available during the build.
*/
Optional<String> builderImage();
/**
* Whether creation of the AppCDS archive should run in a container if available.
*
* <p>
* Normally, if either a suitable container image to use to create the AppCDS archive
* can be determined automatically or if one is explicitly set using the
* {@code quarkus.<package-type>.appcds.builder-image} setting, the AppCDS archive is generated by
* running the JDK contained in the image as a container.
*
* <p>
* If this option is set to {@code false}, a container will not be used to generate the
* AppCDS archive. Instead, the JDK used to build the application is also used to create the
* archive. Note that the exact same JDK version must be used to run the application in this
* case.
*
* <p>
* Ignored if {@code quarkus.package.jar.appcds.enabled} is set to {@code false}.
*/
@WithDefault("true")
boolean useContainer();
/**
* Whether to use <a href="https://openjdk.org/jeps/483">Ahead-of-Time Class Loading & Linking</a> introduced in JDK
* 24.
*/
@WithDefault("false")
boolean useAot();
}
/**
* This is an advanced option that only takes effect for development mode.
* <p>
* If this is specified a directory of this name will be created in the jar distribution. Users can place
* jar files in this directory, and when re-augmentation is performed these will be processed and added to the
* class-path.
* <p>
* Note that before reaugmentation has been performed these jars will be ignored, and if they are updated the app
* should be reaugmented again.
*/
Optional<String> userProvidersDirectory();
/**
* If this option is true then a list of all the coordinates of the artifacts that made up this image will be included
* in the quarkus-app directory. This list can be used by vulnerability scanners to determine
* if your application has any vulnerable dependencies.
* Only supported for the {@linkplain JarType#FAST_JAR fast JAR} and {@linkplain JarType#MUTABLE_JAR mutable JAR}
* output types.
*/
@WithDefault("true")
boolean includeDependencyList();
/**
* Decompiler configuration
*/
DecompilerConfig decompiler();
/**
* Configuration which applies to the JAR's manifest.
*/
@ConfigGroup
| AppcdsConfig |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointSedaInOnlyTest.java | {
"start": 1211,
"end": 3509
} | class ____ extends ContextTestSupport {
private static String beforeThreadName;
private static String afterThreadName;
private static String sedaThreadName;
private static String route = "";
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
route = "";
}
@Test
public void testAsyncEndpoint() throws Exception {
getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel");
getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel");
template.sendBody("direct:start", "Hello Camel");
// we should run before the async processor that sets B
route += "A";
assertMockEndpointsSatisfied();
assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads");
assertFalse(beforeThreadName.equalsIgnoreCase(sedaThreadName), "Should use different threads");
assertFalse(afterThreadName.equalsIgnoreCase(sedaThreadName), "Should use different threads");
assertEquals("AB", route);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
context.addComponent("async", new MyAsyncComponent());
from("direct:start").to("mock:before").process(new Processor() {
public void process(Exchange exchange) {
beforeThreadName = Thread.currentThread().getName();
}
}).to("async:bye:camel").process(new Processor() {
public void process(Exchange exchange) {
afterThreadName = Thread.currentThread().getName();
}
}).to("seda:foo");
from("seda:foo").to("mock:after").to("log:after").delay(1000).process(new Processor() {
public void process(Exchange exchange) {
route += "B";
sedaThreadName = Thread.currentThread().getName();
}
}).to("mock:result");
}
};
}
}
| AsyncEndpointSedaInOnlyTest |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/core/CompletableSource.java | {
"start": 859,
"end": 1212
} | interface ____ {
/**
* Subscribes the given {@link CompletableObserver} to this {@code CompletableSource} instance.
* @param observer the {@code CompletableObserver}, not {@code null}
* @throws NullPointerException if {@code observer} is {@code null}
*/
void subscribe(@NonNull CompletableObserver observer);
}
| CompletableSource |
java | alibaba__fastjson | src/test/java/com/alibaba/json/test/codec/SimpleJsonCodec.java | {
"start": 181,
"end": 1364
} | class ____ implements Codec {
private JSONParser parser = new JSONParser();
public String getName() {
return "simplejson";
}
public <T> T decodeObject(String text, Class<T> clazz) throws Exception {
return (T) parser.parse(text);
}
public <T> Collection<T> decodeArray(String text, Class<T> clazz) throws Exception {
return (Collection<T>) parser.parse(text);
}
public Object decodeObject(String text) throws Exception {
return parser.parse(text);
}
public Object decode(String text) throws Exception {
return parser.parse(text);
}
public String encode(Object object) throws Exception {
return JSONValue.toJSONString(object);
}
public <T> T decodeObject(byte[] input, Class<T> clazz) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public byte[] encodeToBytes(Object object) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public void encode(OutputStream out, Object object) throws Exception {
out.write(encodeToBytes(object));
}
}
| SimpleJsonCodec |
java | micronaut-projects__micronaut-core | inject-java-test/src/test/groovy/io/micronaut/inject/visitor/beans/Message.java | {
"start": 168,
"end": 229
} | class ____<BuilderT extends Builder<BuilderT>> {
| Builder |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/specification/internal/MutationSpecificationImpl.java | {
"start": 2022,
"end": 8007
} | enum ____ {
// INSERT,
UPDATE,
DELETE
}
final List<BiConsumer<SqmDeleteOrUpdateStatement<T>, SqmRoot<T>>> specifications = new ArrayList<>();
private final String hql;
private final Class<T> mutationTarget;
private final SqmDeleteOrUpdateStatement<T> deleteOrUpdateStatement;
private final MutationType type;
public MutationSpecificationImpl(String hql, Class<T> mutationTarget) {
this.hql = hql;
this.mutationTarget = mutationTarget;
this.deleteOrUpdateStatement = null;
this.type = null;
}
public MutationSpecificationImpl(CriteriaUpdate<T> criteriaQuery) {
this.deleteOrUpdateStatement = (SqmUpdateStatement<T>) criteriaQuery;
this.mutationTarget = deleteOrUpdateStatement.getTarget().getManagedType().getJavaType();
this.hql = null;
this.type = MutationType.UPDATE;
}
public MutationSpecificationImpl(CriteriaDelete<T> criteriaQuery) {
this.deleteOrUpdateStatement = (SqmDeleteStatement<T>) criteriaQuery;
this.mutationTarget = deleteOrUpdateStatement.getTarget().getManagedType().getJavaType();
this.hql = null;
this.type = MutationType.DELETE;
}
public MutationSpecificationImpl(MutationType type, Class<T> mutationTarget) {
this.deleteOrUpdateStatement = null;
this.mutationTarget = mutationTarget;
this.hql = null;
this.type = type;
}
@Override
public String getName() {
return null;
}
@Override
public Class<Void> getResultType() {
return null;
}
@Override
public Map<String,Object> getHints() {
return Collections.emptyMap();
}
@Override
public TypedQueryReference<Void> reference() {
return this;
}
@Override
public MutationSpecification<T> restrict(Restriction<? super T> restriction) {
specifications.add( (sqmStatement, mutationTargetRoot) -> {
final var sqmPredicate = (SqmPredicate)
restriction.toPredicate( mutationTargetRoot,
sqmStatement.nodeBuilder() );
sqmStatement.applyPredicate( sqmPredicate );
} );
return this;
}
@Override
public MutationSpecification<T> augment(Augmentation<T> augmentation) {
specifications.add( (sqmStatement, mutationTargetRoot) ->
augmentation.augment( sqmStatement.nodeBuilder(), sqmStatement, mutationTargetRoot ) );
return this;
}
@Override
public MutationQuery createQuery(Session session) {
return createQuery( (SharedSessionContract) session );
}
@Override
public MutationQuery createQuery(StatelessSession session) {
return createQuery( (SharedSessionContract) session );
}
public MutationQuery createQuery(SharedSessionContract session) {
final var sessionImpl = session.unwrap(SharedSessionContractImplementor.class);
final var sqmStatement = build( sessionImpl.getFactory().getQueryEngine() );
return new SqmQueryImpl<>( sqmStatement, false, null, sessionImpl );
}
private SqmDeleteOrUpdateStatement<T> build(QueryEngine queryEngine) {
final SqmDeleteOrUpdateStatement<T> sqmStatement;
final SqmRoot<T> mutationTargetRoot;
if ( hql != null ) {
sqmStatement = resolveSqmTree( hql, queryEngine );
mutationTargetRoot = resolveSqmRoot( sqmStatement, mutationTarget );
}
else if ( deleteOrUpdateStatement != null ) {
sqmStatement = (SqmDeleteOrUpdateStatement<T>) deleteOrUpdateStatement
.copy( simpleContext() );
mutationTargetRoot = resolveSqmRoot( sqmStatement,
sqmStatement.getTarget().getManagedType().getJavaType() );
}
else if ( type != null ) {
final var criteriaBuilder = queryEngine.getCriteriaBuilder();
sqmStatement = switch ( type ) {
case UPDATE -> criteriaBuilder.createCriteriaUpdate( mutationTarget );
case DELETE -> criteriaBuilder.createCriteriaDelete( mutationTarget );
};
mutationTargetRoot = sqmStatement.getTarget();
}
else {
throw new AssertionFailure( "No HQL or criteria" );
}
specifications.forEach( consumer -> consumer.accept( sqmStatement, mutationTargetRoot ) );
return sqmStatement;
}
@Override
public MutationQuery createQuery(EntityManager entityManager) {
return createQuery( (SharedSessionContract) entityManager );
}
@Override
public CommonAbstractCriteria buildCriteria(CriteriaBuilder builder) {
final var nodeBuilder = (NodeBuilder) builder;
return build( nodeBuilder.getQueryEngine() );
}
@Override
public MutationSpecification<T> validate(CriteriaBuilder builder) {
final var nodeBuilder = (NodeBuilder) builder;
final var statement = build( nodeBuilder.getQueryEngine() );
( (AbstractSqmDmlStatement<?>) statement ).validate( hql );
return this;
}
/**
* Used during construction to parse/interpret the incoming HQL
* and produce the corresponding SQM tree.
*/
private static <T> SqmDeleteOrUpdateStatement<T> resolveSqmTree(String hql, QueryEngine queryEngine) {
final var hqlInterpretation =
queryEngine.getInterpretationCache()
.<T>resolveHqlInterpretation( hql, null, queryEngine.getHqlTranslator() );
if ( !SqmUtil.isRestrictedMutation( hqlInterpretation.getSqmStatement() ) ) {
throw new IllegalMutationQueryException( "Expecting a delete or update query, but found '" + hql + "'", hql);
}
// NOTE: this copy is to isolate the actual AST tree from the
// one stored in the interpretation cache
return (SqmDeleteOrUpdateStatement<T>)
hqlInterpretation.getSqmStatement()
.copy( noParamCopyContext( SqmQuerySource.CRITERIA ) );
}
/**
* Used during construction. Mainly used to group extracting and
* validating the root.
*/
private static <T> SqmRoot<T> resolveSqmRoot(
SqmDeleteOrUpdateStatement<T> sqmStatement,
Class<T> mutationTarget) {
final var mutationTargetRoot = sqmStatement.getTarget();
final var javaType = mutationTargetRoot.getJavaType();
if ( javaType != null && !mutationTarget.isAssignableFrom( javaType ) ) {
throw new IllegalArgumentException(
String.format(
Locale.ROOT,
"Mutation target types do not match : %s / %s",
javaType.getName(),
mutationTarget.getName()
)
);
}
return mutationTargetRoot;
}
}
| MutationType |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/ModifiableClusterConfiguration.java | {
"start": 1079,
"end": 2486
} | class ____ {
private final boolean flattenConfig;
private final String configDir;
private final Properties dynamicProperties;
private final Properties removeKeyValues;
private final List<String> removeKeys;
private final List<Tuple3<String, String, String>> replaceKeyValues;
public ModifiableClusterConfiguration(
boolean flattenConfig,
String configDir,
Properties dynamicProperties,
Properties removeKeyValues,
List<String> removeKeys,
List<Tuple3<String, String, String>> replaceKeyValues) {
this.flattenConfig = flattenConfig;
this.configDir = configDir;
this.dynamicProperties = dynamicProperties;
this.removeKeyValues = removeKeyValues;
this.removeKeys = removeKeys;
this.replaceKeyValues = replaceKeyValues;
}
public boolean flattenConfig() {
return flattenConfig;
}
public Properties getRemoveKeyValues() {
return removeKeyValues;
}
public List<String> getRemoveKeys() {
return removeKeys;
}
public List<Tuple3<String, String, String>> getReplaceKeyValues() {
return replaceKeyValues;
}
public String getConfigDir() {
return configDir;
}
public Properties getDynamicProperties() {
return dynamicProperties;
}
}
| ModifiableClusterConfiguration |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/ArrayListSerializerSnapshot.java | {
"start": 1083,
"end": 2188
} | class ____<T>
extends CompositeTypeSerializerSnapshot<ArrayList<T>, ArrayListSerializer<T>> {
private static final int CURRENT_VERSION = 1;
/** Constructor for read instantiation. */
public ArrayListSerializerSnapshot() {}
/** Constructor for creating the snapshot for writing. */
public ArrayListSerializerSnapshot(ArrayListSerializer<T> arrayListSerializer) {
super(arrayListSerializer);
}
@Override
public int getCurrentOuterSnapshotVersion() {
return CURRENT_VERSION;
}
@Override
protected ArrayListSerializer<T> createOuterSerializerWithNestedSerializers(
TypeSerializer<?>[] nestedSerializers) {
@SuppressWarnings("unchecked")
TypeSerializer<T> elementSerializer = (TypeSerializer<T>) nestedSerializers[0];
return new ArrayListSerializer<>(elementSerializer);
}
@Override
protected TypeSerializer<?>[] getNestedSerializers(ArrayListSerializer<T> outerSerializer) {
return new TypeSerializer<?>[] {outerSerializer.getElementSerializer()};
}
}
| ArrayListSerializerSnapshot |
java | elastic__elasticsearch | plugins/mapper-murmur3/src/main/java/org/elasticsearch/index/mapper/murmur3/Murmur3FieldMapper.java | {
"start": 1833,
"end": 2825
} | class ____ extends FieldMapper.Builder {
final Parameter<Boolean> stored = Parameter.storeParam(m -> toType(m).fieldType().isStored(), false);
final Parameter<Map<String, String>> meta = Parameter.metaParam();
public Builder(String name) {
super(name);
}
@Override
protected Parameter<?>[] getParameters() {
return new Parameter<?>[] { stored, meta };
}
@Override
public Murmur3FieldMapper build(MapperBuilderContext context) {
return new Murmur3FieldMapper(
leafName(),
new Murmur3FieldType(context.buildFullName(leafName()), stored.getValue(), meta.getValue()),
builderParams(this, context)
);
}
}
public static final TypeParser PARSER = new TypeParser((n, c) -> new Builder(n));
// this only exists so a check can be done to match the field type to using murmur3 hashing...
public static | Builder |
java | junit-team__junit5 | junit-jupiter-api/src/main/java/org/junit/jupiter/api/DisplayNameGenerator.java | {
"start": 2182,
"end": 2607
} | class ____ the {@link DisplayNameGeneration @DisplayNameGeneration}
* annotation.
*
* <h2>Built-in Implementations</h2>
* <ul>
* <li>{@link Standard}</li>
* <li>{@link Simple}</li>
* <li>{@link ReplaceUnderscores}</li>
* <li>{@link IndicativeSentences}</li>
* </ul>
*
* @since 5.4
* @see DisplayName @DisplayName
* @see DisplayNameGeneration @DisplayNameGeneration
*/
@API(status = STABLE, since = "5.7")
public | via |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionProcessorInspectCausedExceptionTest.java | {
"start": 1242,
"end": 2713
} | class ____ extends ContextTestSupport {
@Test
public void testInspectExceptionByProcessor() throws Exception {
getMockEndpoint("mock:error").expectedMessageCount(0);
getMockEndpoint("mock:myerror").expectedMessageCount(1);
try {
template.sendBody("direct:start", "Hello World");
fail("Should throw exception");
} catch (Exception e) {
// ok
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
errorHandler(deadLetterChannel("mock:error").maximumRedeliveries(3));
// START SNIPPET: e1
// here we register exception cause for MyFunctionException
// when this exception occur we want it to be processed by our
// processor
onException(MyFunctionalException.class).process(new MyFunctionFailureHandler()).stop();
// END SNIPPET: e1
from("direct:start").process(new Processor() {
public void process(Exchange exchange) throws Exception {
throw new MyFunctionalException("Sorry you cannot do this");
}
});
}
};
}
// START SNIPPET: e2
public static | OnExceptionProcessorInspectCausedExceptionTest |
java | apache__logging-log4j2 | log4j-jpa/src/main/java/org/apache/logging/log4j/core/appender/db/jpa/BasicLogEventEntity.java | {
"start": 3106,
"end": 4264
} | class ____ the same annotations plus the
* {@link javax.persistence.Column @Column} annotation to specify the column name.<br>
* <br>
* The {@link #getContextMap()} and {@link #getContextStack()} attributes in this entity use the
* {@link ContextMapAttributeConverter} and {@link ContextStackAttributeConverter}, respectively. These convert the
* properties to simple strings that cannot be converted back to the properties. If you wish to instead convert these to
* a reversible JSON string, override these attributes with the same annotations but use the
* {@link org.apache.logging.log4j.core.appender.db.jpa.converter.ContextMapJsonAttributeConverter} and
* {@link org.apache.logging.log4j.core.appender.db.jpa.converter.ContextStackJsonAttributeConverter} instead.<br>
* <br>
* All other attributes in this entity use reversible converters that can be used for both persistence and retrieval. If
* there are any attributes you do not want persistent, you should override their accessor methods and annotate with
* {@link javax.persistence.Transient @Transient}.
*
* @see AbstractLogEventWrapperEntity
*/
@MappedSuperclass
public abstract | with |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/assignability/generics/PetrolEngine.java | {
"start": 127,
"end": 168
} | class ____ implements Engine {
}
| PetrolEngine |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/lib/Interns.java | {
"start": 3175,
"end": 4122
} | enum ____ {
INSTANCE;
final CacheWith2Keys<String, String, MetricsInfo> cache =
new CacheWith2Keys<String, String, MetricsInfo>() {
@Override protected boolean expireKey1At(int size) {
return size > MAX_INFO_NAMES;
}
@Override protected boolean expireKey2At(int size) {
return size > MAX_INFO_DESCS;
}
@Override protected MetricsInfo newValue(String name, String desc) {
return new MetricsInfoImpl(name, desc);
}
};
}
/**
* Get a metric info object.
* @param name Name of metric info object
* @param description Description of metric info object
* @return an interned metric info object
*/
public static MetricsInfo info(String name, String description) {
return Info.INSTANCE.cache.add(name, description);
}
// Sanity limits
static final int MAX_TAG_NAMES = 100;
static final int MAX_TAG_VALUES = 1000; // distinct per name
| Info |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestStorageBlockPoolUsageStdDev.java | {
"start": 1689,
"end": 6819
} | class ____ {
private final static int NUM_DATANODES = 5;
private final static int STORAGES_PER_DATANODE = 3;
private final static int DEFAULT_BLOCK_SIZE = 102400;
private final static int BUFFER_LENGTH = 1024;
private static Configuration conf;
private MiniDFSCluster cluster;
private FileSystem fs;
@BeforeEach
public void setup() throws Exception {
conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DEFAULT_BLOCK_SIZE);
// Ensure that each volume capacity is larger than the DEFAULT_BLOCK_SIZE.
long capacity = 8 * DEFAULT_BLOCK_SIZE;
long[][] capacities = new long[NUM_DATANODES][STORAGES_PER_DATANODE];
String[] hostnames = new String[5];
for (int i = 0; i < NUM_DATANODES; i++) {
hostnames[i] = i + "." + i + "." + i + "." + i;
for(int j = 0; j < STORAGES_PER_DATANODE; j++){
capacities[i][j]=capacity;
}
}
cluster = new MiniDFSCluster.Builder(conf)
.hosts(hostnames)
.numDataNodes(NUM_DATANODES)
.storagesPerDatanode(STORAGES_PER_DATANODE)
.storageCapacities(capacities).build();
cluster.waitActive();
fs = cluster.getFileSystem();
}
/**
* Create files of different sizes for each datanode.
* Ensure that the file size is smaller than the blocksize
* and only one block is generated. In this way, data will
* be written to only one volume.
*
* Using favoredNodes, we can write files of a specified size
* to specified datanodes to create a batch of datanodes with
* different storageBlockPoolUsageStdDev.
*
* Then, we assert the order of storageBlockPoolUsageStdDev.
*/
@SuppressWarnings("unchecked")
@Test
public void testStorageBlockPoolUsageStdDev() throws IOException {
// Create file for each datanode.
ArrayList<DataNode> dataNodes = cluster.getDataNodes();
DataNode dn0 = dataNodes.get(0);
DataNode dn1 = dataNodes.get(1);
DataNode dn2 = dataNodes.get(2);
DataNode dn3 = dataNodes.get(3);
DataNode dn4 = dataNodes.get(4);
DFSTestUtil.createFile(fs, new Path("/file0"), false, BUFFER_LENGTH, 1000,
DEFAULT_BLOCK_SIZE, (short) 1, 0, false,
new InetSocketAddress[]{dn0.getXferAddress()});
DFSTestUtil.createFile(fs, new Path("/file1"), false, BUFFER_LENGTH, 2000,
DEFAULT_BLOCK_SIZE, (short) 1, 0, false,
new InetSocketAddress[]{dn1.getXferAddress()});
DFSTestUtil.createFile(fs, new Path("/file2"), false, BUFFER_LENGTH, 4000,
DEFAULT_BLOCK_SIZE, (short) 1, 0, false,
new InetSocketAddress[]{dn2.getXferAddress()});
DFSTestUtil.createFile(fs, new Path("/file3"), false, BUFFER_LENGTH, 8000,
DEFAULT_BLOCK_SIZE, (short) 1, 0, false,
new InetSocketAddress[]{dn3.getXferAddress()});
DFSTestUtil.createFile(fs, new Path("/file4"), false, BUFFER_LENGTH, 16000,
DEFAULT_BLOCK_SIZE, (short) 1, 0, false,
new InetSocketAddress[]{dn4.getXferAddress()});
// Trigger Heartbeats.
cluster.triggerHeartbeats();
// Assert that the blockPoolUsedPercentStdDev on namenode
// and Datanode are the same.
String liveNodes = cluster.getNameNode().getNamesystem().getLiveNodes();
Map<String, Map<String, Object>> info =
(Map<String, Map<String, Object>>) JSON.parse(liveNodes);
// Create storageReports for datanodes.
FSNamesystem namesystem = cluster.getNamesystem();
String blockPoolId = namesystem.getBlockPoolId();
StorageReport[] storageReportsDn0 =
dn0.getFSDataset().getStorageReports(blockPoolId);
StorageReport[] storageReportsDn1 =
dn1.getFSDataset().getStorageReports(blockPoolId);
StorageReport[] storageReportsDn2 =
dn2.getFSDataset().getStorageReports(blockPoolId);
StorageReport[] storageReportsDn3 =
dn3.getFSDataset().getStorageReports(blockPoolId);
StorageReport[] storageReportsDn4 =
dn4.getFSDataset().getStorageReports(blockPoolId);
// A float or double may lose precision when being evaluated.
// When multiple values are operated on in different order,
// the results may be inconsistent, so we only take two decimal
// points to assert.
assertEquals(
Util.getBlockPoolUsedPercentStdDev(storageReportsDn0),
(double) info.get(dn0.getDisplayName()).get("blockPoolUsedPercentStdDev"),
0.01d);
assertEquals(
Util.getBlockPoolUsedPercentStdDev(storageReportsDn1),
(double) info.get(dn1.getDisplayName()).get("blockPoolUsedPercentStdDev"),
0.01d);
assertEquals(
Util.getBlockPoolUsedPercentStdDev(storageReportsDn2),
(double) info.get(dn2.getDisplayName()).get("blockPoolUsedPercentStdDev"),
0.01d);
assertEquals(
Util.getBlockPoolUsedPercentStdDev(storageReportsDn3),
(double) info.get(dn3.getDisplayName()).get("blockPoolUsedPercentStdDev"),
0.01d);
assertEquals(
Util.getBlockPoolUsedPercentStdDev(storageReportsDn4),
(double) info.get(dn4.getDisplayName()).get("blockPoolUsedPercentStdDev"),
0.01d);
}
}
| TestStorageBlockPoolUsageStdDev |
java | google__dagger | javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java | {
"start": 21307,
"end": 21473
} | class ____ {",
" @Provides A provideA() { return new A() {}; }",
" }",
"",
" @Module",
" static | Module01 |
java | google__dagger | javatests/dagger/functional/multipackage/grandsub/FooGrandchildComponent.java | {
"start": 825,
"end": 899
} | interface ____ {
Foo<FooGrandchildComponent> foo();
}
| FooGrandchildComponent |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/builder/TokenPairExpressionIterator.java | {
"start": 5791,
"end": 8961
} | class ____ implements Iterator<Object>, Closeable {
final String startToken;
String scanStartToken;
final String endToken;
String scanEndToken;
final boolean includeTokens;
final InputStream in;
final String charset;
Scanner scanner;
Object image;
TokenPairIterator(String startToken, String endToken, boolean includeTokens, InputStream in, String charset) {
this.startToken = startToken;
this.endToken = endToken;
this.includeTokens = includeTokens;
this.in = in;
this.charset = charset;
// make sure [ and ] is escaped as we use scanner which is reg exp based
// where [ and ] have special meaning
scanStartToken = startToken;
if (scanStartToken.startsWith("[")) {
scanStartToken = "\\" + scanStartToken;
}
if (scanStartToken.endsWith("]")) {
scanStartToken = scanStartToken.substring(0, startToken.length() - 1) + "\\]";
}
scanEndToken = endToken;
if (scanEndToken.startsWith("[")) {
scanEndToken = "\\" + scanEndToken;
}
if (scanEndToken.endsWith("]")) {
scanEndToken = scanEndToken.substring(0, scanEndToken.length() - 1) + "\\]";
}
}
void init() {
// use end token as delimiter
this.scanner = new Scanner(in, charset, scanEndToken);
// this iterator will do look ahead as we may have data
// after the last end token, which the scanner would find
// so we need to be one step ahead of the scanner
this.image = scanner.hasNext() ? next() : null;
}
@Override
public boolean hasNext() {
return image != null;
}
@Override
public Object next() {
Object answer = image;
// calculate next
if (scanner.hasNext()) {
image = getNext();
} else {
image = null;
}
if (answer == null) {
// first time the image may be null
answer = image;
}
return answer;
}
Object getNext() {
String next = scanner.next();
// only grab text after the start token
if (next.contains(startToken)) {
next = StringHelper.after(next, startToken);
// include tokens in answer
if (next != null && includeTokens) {
next = startToken + next + endToken;
}
} else {
// must have start token, otherwise we have reached beyond last tokens
// and should not return more data
return null;
}
return next;
}
@Override
public void remove() {
// noop
}
@Override
public void close() throws IOException {
scanner.close();
}
}
}
| TokenPairIterator |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SalesforceEndpointBuilderFactory.java | {
"start": 167623,
"end": 167960
} | class ____ extends AbstractEndpointBuilder implements SalesforceEndpointBuilder, AdvancedSalesforceEndpointBuilder {
public SalesforceEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new SalesforceEndpointBuilderImpl(path);
}
} | SalesforceEndpointBuilderImpl |
java | netty__netty | codec-http/src/test/java/io/netty/handler/codec/http/websocketx/extensions/WebSocketExtensionTestUtil.java | {
"start": 3335,
"end": 3588
} | class ____ extends WebSocketExtensionEncoder {
@Override
protected void encode(ChannelHandlerContext ctx, WebSocketFrame msg,
List<Object> out) throws Exception {
// unused
}
}
static | DummyEncoder |
java | google__guava | android/guava-tests/benchmark/com/google/common/collect/SetIterationBenchmark.java | {
"start": 1082,
"end": 1997
} | class ____ {
@Param({
"3", "6", "11", "23", "45", "91", "181", "362", "724", "1448", "2896", "5793", "11585", "23170",
"46341", "92682", "185364", "370728", "741455", "1482910", "2965821", "5931642"
})
private int size;
// "" means no fixed seed
@Param("1234")
private SpecialRandom random;
@Param({"ImmutableSetImpl", "HashSetImpl"})
private SetImpl impl;
// the following must be set during setUp
private Set<Element> setToTest;
@BeforeExperiment
void setUp() {
CollectionBenchmarkSampleData sampleData =
new CollectionBenchmarkSampleData(true, random, 0.8, size);
setToTest = (Set<Element>) impl.create(sampleData.getValuesInSet());
}
@Benchmark
int iteration(int reps) {
int x = 0;
for (int i = 0; i < reps; i++) {
for (Element y : setToTest) {
x ^= System.identityHashCode(y);
}
}
return x;
}
}
| SetIterationBenchmark |
java | quarkusio__quarkus | integration-tests/spring-data-jpa/src/main/java/io/quarkus/it/spring/data/jpa/OrderResource.java | {
"start": 263,
"end": 1160
} | class ____ {
private final OrderRepository orderRepository;
public OrderResource(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@GET
public List<Order> findAll() {
return this.orderRepository.findAll();
}
@GET
@Path("/customer/{id}")
public List<Order> findAllByUser(@PathParam("id") Long id) {
return this.orderRepository.findByCartCustomerId(id);
}
@GET
@Path("/{id}")
public Order findById(@PathParam("id") Long id) {
return this.orderRepository.findById(id).orElse(null);
}
@DELETE
@Path("/{id}")
public void delete(@PathParam("id") Long id) {
this.orderRepository.deleteById(id);
}
@GET
@Path("/exists/{id}")
public boolean existsById(@PathParam("id") Long id) {
return this.orderRepository.existsById(id);
}
}
| OrderResource |
java | apache__hadoop | hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/server/dns/ReverseZoneUtils.java | {
"start": 1579,
"end": 5771
} | class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(ReverseZoneUtils.class);
private static final long POW3 = (long) Math.pow(256, 3);
private static final long POW2 = (long) Math.pow(256, 2);
private static final long POW1 = (long) Math.pow(256, 1);
private ReverseZoneUtils() {
}
/**
* Given a baseIp, range and index, return the network address for the
* reverse zone.
*
* @param baseIp base ip address to perform calculations against.
* @param range number of ip addresses per subnet.
* @param index the index of the subnet to calculate.
* @return the calculated ip address.
* @throws UnknownHostException if an invalid ip is provided.
*/
protected static String getReverseZoneNetworkAddress(String baseIp, int range,
int index) throws UnknownHostException {
if (index < 0) {
throw new IllegalArgumentException(
String.format("Invalid index provided, must be positive: %d", index));
}
if (range < 0) {
throw new IllegalArgumentException(
String.format("Invalid range provided, cannot be negative: %d",
range));
}
return calculateIp(baseIp, range, index);
}
/**
* When splitting the reverse zone, return the number of subnets needed,
* given the range and netmask.
*
* @param conf the Hadoop configuration.
* @return The number of subnets given the range and netmask.
*/
protected static long getSubnetCountForReverseZones(Configuration conf) {
String subnet = conf.get(KEY_DNS_ZONE_SUBNET);
String mask = conf.get(KEY_DNS_ZONE_MASK);
String range = conf.get(KEY_DNS_SPLIT_REVERSE_ZONE_RANGE);
int parsedRange;
try {
parsedRange = Integer.parseInt(range);
} catch (NumberFormatException e) {
LOG.error("The supplied range is not a valid integer: Supplied range: ",
range);
throw e;
}
if (parsedRange < 0) {
String msg = String
.format("Range cannot be negative: Supplied range: %d", parsedRange);
LOG.error(msg);
throw new IllegalArgumentException(msg);
}
long ipCount;
try {
SubnetUtils subnetUtils = new SubnetUtils(subnet, mask);
subnetUtils.setInclusiveHostCount(true);
ipCount = subnetUtils.getInfo().getAddressCountLong();
} catch (IllegalArgumentException e) {
LOG.error("The subnet or mask is invalid: Subnet: {} Mask: {}", subnet,
mask);
throw e;
}
if (parsedRange == 0) {
return ipCount;
}
return ipCount / parsedRange;
}
private static String calculateIp(String baseIp, int range, int index)
throws UnknownHostException {
long[] ipParts = splitIp(baseIp);
long ipNum1 = POW3 * ipParts[0];
long ipNum2 = POW2 * ipParts[1];
long ipNum3 = POW1 * ipParts[2];
long ipNum4 = ipParts[3];
long ipNum = ipNum1 + ipNum2 + ipNum3 + ipNum4;
ArrayList<Long> ipPartsOut = new ArrayList<>();
// First octet
long temp = ipNum + range * (long) index;
ipPartsOut.add(0, temp / POW3);
// Second octet
temp = temp - ipPartsOut.get(0) * POW3;
ipPartsOut.add(1, temp / POW2);
// Third octet
temp = temp - ipPartsOut.get(1) * POW2;
ipPartsOut.add(2, temp / POW1);
// Fourth octet
temp = temp - ipPartsOut.get(2) * POW1;
ipPartsOut.add(3, temp);
return StringUtils.join(ipPartsOut, '.');
}
@VisibleForTesting
protected static long[] splitIp(String baseIp) throws UnknownHostException {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(baseIp);
} catch (UnknownHostException e) {
LOG.error("Base IP address is invalid");
throw e;
}
if (inetAddress instanceof Inet6Address) {
throw new IllegalArgumentException(
"IPv6 is not yet supported for " + "reverse zones");
}
byte[] octets = inetAddress.getAddress();
if (octets.length != 4) {
throw new IllegalArgumentException("Base IP address is invalid");
}
long[] results = new long[4];
for (int i = 0; i < octets.length; i++) {
results[i] = octets[i] & 0xff;
}
return results;
}
}
| ReverseZoneUtils |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/ConstantsTests.java | {
"start": 7528,
"end": 8043
} | class ____ {
public static final int DOG = 0;
public static final int CAT = 66;
public static final String S1 = "";
public static final int PREFIX_NO = 1;
public static final int PREFIX_YES = 2;
public static final int MY_PROPERTY_NO = 1;
public static final int MY_PROPERTY_YES = 2;
public static final int NO_PROPERTY = 3;
public static final int YES_PROPERTY = 4;
/** ignore these */
protected static final int P = -1;
protected boolean f;
static final Object o = new Object();
}
}
| A |
java | spring-projects__spring-boot | module/spring-boot-micrometer-metrics/src/main/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/atlas/AtlasMetricsExportAutoConfiguration.java | {
"start": 2293,
"end": 2668
} | class ____ {
@Bean
@ConditionalOnMissingBean
AtlasConfig atlasConfig(AtlasProperties atlasProperties) {
return new AtlasPropertiesConfigAdapter(atlasProperties);
}
@Bean
@ConditionalOnMissingBean
AtlasMeterRegistry atlasMeterRegistry(AtlasConfig atlasConfig, Clock clock) {
return new AtlasMeterRegistry(atlasConfig, clock);
}
}
| AtlasMetricsExportAutoConfiguration |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/procedure/NumericParameterTypeTests.java | {
"start": 1412,
"end": 4337
} | class ____ {
@Test
void testParameterBaseline(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
executeQuery( Integer.class, Integer.class, 1, 2, session );
} );
}
private void executeQuery(
Class<? extends Number> inArgType,
Class<? extends Number> outArgType,
Object inArgValue,
Object expectedOutArgValue,
SessionImplementor session) {
final StoredProcedureQuery query = session.createStoredProcedureQuery( "inoutproc" );
query.registerStoredProcedureParameter( "inarg", inArgType, ParameterMode.IN );
query.registerStoredProcedureParameter( "outarg", outArgType, ParameterMode.OUT );
query.setParameter( "inarg", inArgValue );
final Object result = query.getOutputParameterValue( "outarg" );
assertThat( result ).isEqualTo( expectedOutArgValue );
}
@Test
void testInputParameter(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
// Number is fine for IN parameters because we can ultimately look at the bind value type
executeQuery( Number.class, Integer.class, 1, 2, session );
// in addition to Integer/Integer, we can also have IN parameters defined as numerous "implicit conversion" types
executeQuery( Short.class, Integer.class, 1, 2, session );
executeQuery( BigInteger.class, Integer.class, BigInteger.ONE, 2, session );
executeQuery( Double.class, Integer.class, 1.0, 2, session );
executeQuery( BigDecimal.class, Integer.class, BigDecimal.ONE, 2, session );
} );
}
@Test
void testOutputParameter(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
try {
// Number is not fine for OUT parameters
executeQuery( Integer.class, Number.class, 1, 2, session );
fail( "Expected a ParameterTypeException" );
}
catch (ParameterTypeException expected) {
assertThat( expected.getMessage() ).contains( "outarg" );
}
// in addition to Integer/Integer, we can also have OUT parameters defined as numerous "implicit conversion" types
executeQuery( Integer.class, Short.class, 1, toShort( 2 ), session );
executeQuery( Integer.class, BigInteger.class, BigDecimal.ONE, BigInteger.valueOf( 2 ), session );
executeQuery( Integer.class, Double.class, 1, 2.0, session );
executeQuery( Integer.class, BigDecimal.class, 1, BigDecimal.valueOf( 2 ), session );
} );
}
@BeforeAll
void createProcedures(SessionFactoryScope scope) throws SQLException {
final String procedureStatement = "create procedure inoutproc (IN inarg numeric, OUT outarg numeric) " +
"begin atomic set outarg = inarg + 1;" +
"end";
Helper.withStatement( scope.getSessionFactory(), statement -> {
statement.execute( procedureStatement );
} );
}
@AfterAll
void dropProcedures(SessionFactoryScope scope) throws SQLException {
Helper.withStatement( scope.getSessionFactory(), statement -> {
statement.execute( "drop procedure inoutproc" );
} );
}
}
| NumericParameterTypeTests |
java | grpc__grpc-java | api/src/main/java/io/grpc/NameResolverProvider.java | {
"start": 1698,
"end": 3351
} | class ____ extends NameResolver.Factory {
/**
* Whether this provider is available for use, taking the current environment into consideration.
* If {@code false}, no other methods are safe to be called.
*
* @since 1.0.0
*/
protected abstract boolean isAvailable();
/**
* A priority, from 0 to 10 that this provider should be used, taking the current environment into
* consideration. 5 should be considered the default, and then tweaked based on environment
* detection. A priority of 0 does not imply that the provider wouldn't work; just that it should
* be last in line.
*
* @since 1.0.0
*/
protected abstract int priority();
/**
* Returns the scheme associated with the provider. The provider normally should only create a
* {@link NameResolver} when target URI scheme matches the provider scheme. It temporarily
* delegates to {@link Factory#getDefaultScheme()} before {@link NameResolver.Factory} is
* deprecated in https://github.com/grpc/grpc-java/issues/7133.
*
* <p>The scheme should be lower-case.
*
* @since 1.40.0
* */
protected String getScheme() {
return getDefaultScheme();
}
/**
* Returns the {@link SocketAddress} types this provider's name-resolver is capable of producing.
* This enables selection of the appropriate {@link ManagedChannelProvider} for a channel.
*
* @return the {@link SocketAddress} types this provider's name-resolver is capable of producing.
*/
public Collection<Class<? extends SocketAddress>> getProducedSocketAddressTypes() {
return Collections.singleton(InetSocketAddress.class);
}
}
| NameResolverProvider |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/SubtaskAccess.java | {
"start": 1703,
"end": 3768
} | interface ____ {
/**
* Creates a Callable that, when invoked, sends the event to the execution attempt of the
* subtask that this {@code SubtaskAccess} instance binds to. The resulting future from the
* sending is returned by the callable.
*
* <p>This lets the caller target the specific subtask without necessarily sending the event now
* (for example, the event may be sent at a later point due to checkpoint alignment through the
* {@link SubtaskGatewayImpl}).
*/
Callable<CompletableFuture<Acknowledge>> createEventSendAction(
SerializedValue<OperatorEvent> event);
/** Gets the parallel subtask index of the target subtask. */
int getSubtaskIndex();
/** Gets the execution attempt ID of the attempt that this instance is bound to. */
ExecutionAttemptID currentAttempt();
/**
* Gets a descriptive name of the operator's subtask , including name, subtask-id, parallelism,
* and execution attempt.
*/
String subtaskName();
/**
* The future returned here completes once the target subtask is in a running state. As running
* state classify the states {@link ExecutionState#RUNNING} and {@link
* ExecutionState#INITIALIZING}.
*/
CompletableFuture<?> hasSwitchedToRunning();
/**
* Checks whether the execution is still in a running state. See {@link #hasSwitchedToRunning()}
* for details.
*/
boolean isStillRunning();
/**
* Triggers a failover for the subtaks execution attempt that this access instance is bound to.
*/
void triggerTaskFailover(Throwable cause);
// ------------------------------------------------------------------------
/**
* While the {@link SubtaskAccess} is bound to an execution attempt of a subtask (like an {@link
* org.apache.flink.runtime.executiongraph.Execution}, this factory is bound to the operator as
* a whole (like in the scope of an {@link
* org.apache.flink.runtime.executiongraph.ExecutionJobVertex}.
*/
| SubtaskAccess |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskScheduler.java | {
"start": 3193,
"end": 11991
} | class ____ extends ConcurrentTaskExecutor implements TaskScheduler {
private static final TimeUnit NANO = TimeUnit.NANOSECONDS;
private static @Nullable Class<?> managedScheduledExecutorServiceClass;
static {
try {
managedScheduledExecutorServiceClass = ClassUtils.forName(
"jakarta.enterprise.concurrent.ManagedScheduledExecutorService",
ConcurrentTaskScheduler.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
// JSR-236 API not available...
managedScheduledExecutorServiceClass = null;
}
}
private @Nullable ScheduledExecutorService scheduledExecutor;
private boolean enterpriseConcurrentScheduler = false;
private @Nullable ErrorHandler errorHandler;
private Clock clock = Clock.systemDefaultZone();
/**
* Create a new ConcurrentTaskScheduler,
* using a single thread executor as default.
* @see java.util.concurrent.Executors#newSingleThreadScheduledExecutor()
* @deprecated in favor of {@link #ConcurrentTaskScheduler(ScheduledExecutorService)}
* with an externally provided Executor
*/
@Deprecated(since = "6.1")
public ConcurrentTaskScheduler() {
super();
this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
this.enterpriseConcurrentScheduler = false;
}
/**
* Create a new ConcurrentTaskScheduler, using the given
* {@link java.util.concurrent.ScheduledExecutorService} as shared delegate.
* <p>Autodetects a JSR-236 {@link jakarta.enterprise.concurrent.ManagedScheduledExecutorService}
* in order to use it for trigger-based scheduling if possible,
* instead of Spring's local trigger management.
* @param scheduledExecutor the {@link java.util.concurrent.ScheduledExecutorService}
* to delegate to for {@link org.springframework.scheduling.SchedulingTaskExecutor}
* as well as {@link TaskScheduler} invocations
*/
public ConcurrentTaskScheduler(@Nullable ScheduledExecutorService scheduledExecutor) {
super(scheduledExecutor);
if (scheduledExecutor != null) {
initScheduledExecutor(scheduledExecutor);
}
}
/**
* Create a new ConcurrentTaskScheduler, using the given {@link java.util.concurrent.Executor}
* and {@link java.util.concurrent.ScheduledExecutorService} as delegates.
* <p>Autodetects a JSR-236 {@link jakarta.enterprise.concurrent.ManagedScheduledExecutorService}
* in order to use it for trigger-based scheduling if possible,
* instead of Spring's local trigger management.
* @param concurrentExecutor the {@link java.util.concurrent.Executor} to delegate to
* for {@link org.springframework.scheduling.SchedulingTaskExecutor} invocations
* @param scheduledExecutor the {@link java.util.concurrent.ScheduledExecutorService}
* to delegate to for {@link TaskScheduler} invocations
*/
public ConcurrentTaskScheduler(Executor concurrentExecutor, ScheduledExecutorService scheduledExecutor) {
super(concurrentExecutor);
initScheduledExecutor(scheduledExecutor);
}
private void initScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
this.scheduledExecutor = scheduledExecutor;
this.enterpriseConcurrentScheduler = (managedScheduledExecutorServiceClass != null &&
managedScheduledExecutorServiceClass.isInstance(scheduledExecutor));
}
/**
* Specify the {@link java.util.concurrent.ScheduledExecutorService} to delegate to.
* <p>Autodetects a JSR-236 {@link jakarta.enterprise.concurrent.ManagedScheduledExecutorService}
* in order to use it for trigger-based scheduling if possible,
* instead of Spring's local trigger management.
* <p>Note: This will only apply to {@link TaskScheduler} invocations.
* If you want the given executor to apply to
* {@link org.springframework.scheduling.SchedulingTaskExecutor} invocations
* as well, pass the same executor reference to {@link #setConcurrentExecutor}.
* @see #setConcurrentExecutor
*/
public void setScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
initScheduledExecutor(scheduledExecutor);
}
private ScheduledExecutorService getScheduledExecutor() {
if (this.scheduledExecutor == null) {
throw new IllegalStateException("No ScheduledExecutor is configured");
}
return this.scheduledExecutor;
}
/**
* Provide an {@link ErrorHandler} strategy.
*/
public void setErrorHandler(ErrorHandler errorHandler) {
Assert.notNull(errorHandler, "ErrorHandler must not be null");
this.errorHandler = errorHandler;
}
/**
* Set the clock to use for scheduling purposes.
* <p>The default clock is the system clock for the default time zone.
* @since 5.3
* @see Clock#systemDefaultZone()
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "Clock must not be null");
this.clock = clock;
}
@Override
public Clock getClock() {
return this.clock;
}
@Override
public void execute(Runnable task) {
super.execute(TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, false));
}
@Override
public Future<?> submit(Runnable task) {
return super.submit(TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, false));
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return super.submit(new DelegatingErrorHandlingCallable<>(task, this.errorHandler));
}
@Override
public @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
ScheduledExecutorService scheduleExecutorToUse = getScheduledExecutor();
try {
if (this.enterpriseConcurrentScheduler) {
return new EnterpriseConcurrentTriggerScheduler().schedule(decorateTask(task, true), trigger);
}
else {
ErrorHandler errorHandler =
(this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
return new ReschedulingRunnable(
decorateTaskIfNecessary(task), trigger, this.clock, scheduleExecutorToUse, errorHandler)
.schedule();
}
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(scheduleExecutorToUse, task, ex);
}
}
@Override
public ScheduledFuture<?> schedule(Runnable task, Instant startTime) {
ScheduledExecutorService scheduleExecutorToUse = getScheduledExecutor();
Duration delay = Duration.between(this.clock.instant(), startTime);
try {
return scheduleExecutorToUse.schedule(decorateTask(task, false), NANO.convert(delay), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(scheduleExecutorToUse, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period) {
ScheduledExecutorService scheduleExecutorToUse = getScheduledExecutor();
Duration initialDelay = Duration.between(this.clock.instant(), startTime);
try {
return scheduleExecutorToUse.scheduleAtFixedRate(decorateTask(task, true),
NANO.convert(initialDelay), NANO.convert(period), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(scheduleExecutorToUse, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period) {
ScheduledExecutorService scheduleExecutorToUse = getScheduledExecutor();
try {
return scheduleExecutorToUse.scheduleAtFixedRate(decorateTask(task, true),
0, NANO.convert(period), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(scheduleExecutorToUse, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay) {
ScheduledExecutorService scheduleExecutorToUse = getScheduledExecutor();
Duration initialDelay = Duration.between(this.clock.instant(), startTime);
try {
return scheduleExecutorToUse.scheduleWithFixedDelay(decorateTask(task, true),
NANO.convert(initialDelay), NANO.convert(delay), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(scheduleExecutorToUse, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay) {
ScheduledExecutorService scheduleExecutorToUse = getScheduledExecutor();
try {
return scheduleExecutorToUse.scheduleWithFixedDelay(decorateTask(task, true),
0, NANO.convert(delay), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(scheduleExecutorToUse, task, ex);
}
}
private Runnable decorateTask(Runnable task, boolean isRepeatingTask) {
Runnable result = TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
result = decorateTaskIfNecessary(result);
if (this.enterpriseConcurrentScheduler) {
result = ManagedTaskBuilder.buildManagedTask(result, task.toString());
}
return result;
}
/**
* Delegate that adapts a Spring Trigger to a JSR-236 Trigger.
* Separated into an inner | ConcurrentTaskScheduler |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/core/annotation/UniqueSecurityAnnotationScannerTests.java | {
"start": 17155,
"end": 17289
} | class ____ {
@PreAuthorize("six")
String method() {
return "ok";
}
}
@PreAuthorize("seven")
private | AnnotationOnClassMethod |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/attr/EmbeddedAttributeProcessing.java | {
"start": 1287,
"end": 2720
} | class ____ {
public static MutableMemberDetails processEmbeddedAttribute(
JaxbEmbeddedImpl jaxbEmbedded,
MutableClassDetails declarer,
AccessType classAccessType,
XmlDocumentContext xmlDocumentContext) {
final AccessType accessType = coalesce( jaxbEmbedded.getAccess(), classAccessType );
final MutableMemberDetails memberDetails = XmlProcessingHelper.getAttributeMember(
jaxbEmbedded.getName(),
accessType,
declarer
);
memberDetails.applyAnnotationUsage(
JpaAnnotations.EMBEDDED,
xmlDocumentContext.getModelBuildingContext()
);
if ( StringHelper.isNotEmpty( jaxbEmbedded.getTarget() ) ) {
final TargetXmlAnnotation targetAnn = (TargetXmlAnnotation) memberDetails.applyAnnotationUsage(
XmlAnnotations.TARGET,
xmlDocumentContext.getModelBuildingContext()
);
targetAnn.value( determineTargetName( jaxbEmbedded.getTarget(), xmlDocumentContext ) );
}
applyAccess( accessType, memberDetails, xmlDocumentContext );
applyAttributeAccessor( jaxbEmbedded, memberDetails, xmlDocumentContext );
applyOptimisticLock( jaxbEmbedded, memberDetails, xmlDocumentContext );
XmlAnnotationHelper.applyAttributeOverrides( jaxbEmbedded.getAttributeOverrides(), memberDetails, xmlDocumentContext );
XmlAnnotationHelper.applyAssociationOverrides( jaxbEmbedded.getAssociationOverrides(), memberDetails, xmlDocumentContext );
return memberDetails;
}
}
| EmbeddedAttributeProcessing |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/Ordered.java | {
"start": 690,
"end": 1635
} | interface ____ can be implemented by objects that
* should be <em>orderable</em>, for example in a {@code Collection}.
*
* <p>The actual {@link #getOrder() order} can be interpreted as prioritization,
* with the first object (with the lowest order value) having the highest
* priority.
*
* <p>Note that there is also a <em>priority</em> marker for this interface:
* {@link PriorityOrdered}. Consult the Javadoc for {@code PriorityOrdered} for
* details on how {@code PriorityOrdered} objects are ordered relative to
* <em>plain</em> {@link Ordered} objects.
*
* <p>Consult the Javadoc for {@link OrderComparator} for details on the
* sort semantics for non-ordered objects.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 07.04.2003
* @see PriorityOrdered
* @see OrderComparator
* @see org.springframework.core.annotation.Order
* @see org.springframework.core.annotation.AnnotationAwareOrderComparator
*/
public | that |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/SealedTypesWithJsonTypeInfoSimpleClassName4061Test.java | {
"start": 1434,
"end": 1499
} | class ____ extends InnerSuper4061 {
}
static final | InnerSub4061A |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateDiscardOnFailureTest.java | {
"start": 4754,
"end": 5377
} | class ____ implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if ("Kaboom".equals(newExchange.getMessage().getBody())) {
throw new IllegalArgumentException("Forced");
}
if (oldExchange == null) {
return newExchange;
}
Object body = oldExchange.getMessage().getBody(String.class) + newExchange.getMessage().getBody(String.class);
oldExchange.getMessage().setBody(body);
return oldExchange;
}
}
}
| MyAggregationStrategy |
java | resilience4j__resilience4j | resilience4j-spring/src/test/java/io/github/resilience4j/bulkhead/configure/ReactorBulkheadAspectExtTest.java | {
"start": 1146,
"end": 2068
} | class ____ {
@Mock
ProceedingJoinPoint proceedingJoinPoint;
@InjectMocks
ReactorBulkheadAspectExt reactorBulkheadAspectExt;
@Test
public void testCheckTypes() {
assertThat(reactorBulkheadAspectExt.canHandleReturnType(Mono.class)).isTrue();
assertThat(reactorBulkheadAspectExt.canHandleReturnType(Flux.class)).isTrue();
}
@Test
public void testReactorTypes() throws Throwable {
Bulkhead bulkhead = Bulkhead.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Mono.just("Test"));
assertThat(reactorBulkheadAspectExt.handle(proceedingJoinPoint, bulkhead, "testMethod"))
.isNotNull();
when(proceedingJoinPoint.proceed()).thenReturn(Flux.just("Test"));
assertThat(reactorBulkheadAspectExt.handle(proceedingJoinPoint, bulkhead, "testMethod"))
.isNotNull();
}
} | ReactorBulkheadAspectExtTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrNonTransactionalTests.java | {
"start": 1376,
"end": 1727
} | class ____ {
@Autowired
CallCountingTransactionManager txManager;
@Test
void nonTransactionalTest() {
assertThat(txManager.begun).isEqualTo(0);
assertThat(txManager.inflight).isEqualTo(0);
assertThat(txManager.commits).isEqualTo(0);
assertThat(txManager.rollbacks).isEqualTo(0);
}
@Configuration
static | LookUpTxMgrNonTransactionalTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/ColumnSource.java | {
"start": 481,
"end": 2126
} | interface ____ extends RelationalValueSource {
/**
* Obtain the name of the column.
*
* @return The name of the column. Can be {@code null}, in which case a naming strategy is applied.
*/
String getName();
/**
* A SQL fragment to apply to the column value on read.
*
* @return The SQL read fragment
*/
String getReadFragment();
/**
* A SQL fragment to apply to the column value on write.
*
* @return The SQL write fragment
*/
String getWriteFragment();
/**
* Is this column nullable?
*
* @return {@code true} indicates it is nullable; {@code false} non-nullable.
*/
Boolean isNullable();
/**
* Obtain a specified default value for the column
*
* @return THe column default
*/
String getDefaultValue();
/**
* Obtain the free-hand definition of the column's type.
*
* @return The free-hand column type
*/
String getSqlType();
/**
* The deduced (and dialect convertible) type for this column
*
* @return The column's SQL data type.
*/
JdbcDataType getDatatype();
/**
* Obtain the source for the specified column size.
*
* @return The source for the column size.
*/
SizeSource getSizeSource();
/**
* Is this column unique?
*
* @return {@code true} indicates it is unique; {@code false} non-unique.
*/
boolean isUnique();
/**
* Obtain the specified check constraint condition
*
* @return Check constraint condition
*/
String getCheckCondition();
/**
* Obtain the specified SQL comment
*
* @return SQL comment
*/
String getComment();
Set<String> getIndexConstraintNames();
Set<String> getUniqueKeyConstraintNames();
}
| ColumnSource |
java | apache__flink | flink-formats/flink-json/src/main/java/org/apache/flink/formats/json/maxwell/MaxwellJsonDecodingFormat.java | {
"start": 2031,
"end": 5783
} | class ____
implements ProjectableDecodingFormat<DeserializationSchema<RowData>> {
// --------------------------------------------------------------------------------------------
// Mutable attributes
// --------------------------------------------------------------------------------------------
/** The requested metadata keys. */
private List<String> metadataKeys;
private final boolean ignoreParseErrors;
private final TimestampFormat timestampFormat;
public MaxwellJsonDecodingFormat(boolean ignoreParseErrors, TimestampFormat timestampFormat) {
this.ignoreParseErrors = ignoreParseErrors;
this.timestampFormat = timestampFormat;
this.metadataKeys = Collections.emptyList();
}
@Override
public DeserializationSchema<RowData> createRuntimeDecoder(
DynamicTableSource.Context context, DataType physicalDataType, int[][] projections) {
physicalDataType = Projection.of(projections).project(physicalDataType);
final List<ReadableMetadata> readableMetadata =
metadataKeys.stream()
.map(
k ->
Stream.of(ReadableMetadata.values())
.filter(rm -> rm.key.equals(k))
.findFirst()
.orElseThrow(
() ->
new IllegalStateException(
String.format(
"Could not find the requested metadata key: %s",
k))))
.collect(Collectors.toList());
final List<DataTypes.Field> metadataFields =
readableMetadata.stream()
.map(m -> DataTypes.FIELD(m.key, m.dataType))
.collect(Collectors.toList());
final DataType producedDataType =
DataTypeUtils.appendRowFields(physicalDataType, metadataFields);
final TypeInformation<RowData> producedTypeInfo =
context.createTypeInformation(producedDataType);
return new MaxwellJsonDeserializationSchema(
physicalDataType,
readableMetadata,
producedTypeInfo,
ignoreParseErrors,
timestampFormat);
}
@Override
public Map<String, DataType> listReadableMetadata() {
final Map<String, DataType> metadataMap = new LinkedHashMap<>();
Stream.of(ReadableMetadata.values())
.forEachOrdered(m -> metadataMap.put(m.key, m.dataType));
return metadataMap;
}
@Override
public void applyReadableMetadata(List<String> metadataKeys) {
this.metadataKeys = metadataKeys;
}
@Override
public ChangelogMode getChangelogMode() {
return ChangelogMode.newBuilder()
.addContainedKind(RowKind.INSERT)
.addContainedKind(RowKind.UPDATE_BEFORE)
.addContainedKind(RowKind.UPDATE_AFTER)
.addContainedKind(RowKind.DELETE)
.build();
}
// --------------------------------------------------------------------------------------------
// Metadata handling
// --------------------------------------------------------------------------------------------
/** List of metadata that can be read with this format. */
| MaxwellJsonDecodingFormat |
java | apache__maven | compat/maven-settings/src/main/java/org/apache/maven/settings/io/xpp3/SettingsXpp3Reader.java | {
"start": 1382,
"end": 3706
} | class ____ {
private final SettingsStaxReader delegate;
public SettingsXpp3Reader() {
delegate = new SettingsStaxReader();
}
public SettingsXpp3Reader(ContentTransformer contentTransformer) {
delegate = new SettingsStaxReader(contentTransformer::transform);
}
/**
* Returns the state of the "add default entities" flag.
*
* @return boolean
*/
public boolean getAddDefaultEntities() {
return delegate.getAddDefaultEntities();
}
/**
* Sets the state of the "add default entities" flag.
*
* @param addDefaultEntities a addDefaultEntities object.
*/
public void setAddDefaultEntities(boolean addDefaultEntities) {
delegate.setAddDefaultEntities(addDefaultEntities);
}
public Settings read(Reader reader, boolean strict) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(reader, strict, null));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
public Settings read(Reader reader) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(reader));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
public Settings read(InputStream in, boolean strict) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(in, strict, null));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
public Settings read(InputStream in) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(in));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
public Settings read(XMLStreamReader parser, boolean strict) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(parser, strict, null));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
public | SettingsXpp3Reader |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxMapFuseable.java | {
"start": 5376,
"end": 9038
} | class ____<T, R>
implements ConditionalSubscriber<T>, InnerOperator<T, R>,
QueueSubscription<R> {
final ConditionalSubscriber<? super R> actual;
final Function<? super T, ? extends @Nullable R> mapper;
boolean done;
@SuppressWarnings("NotNullFieldNotInitialized") // initialized in onSubscribe
QueueSubscription<T> s;
int sourceMode;
MapFuseableConditionalSubscriber(ConditionalSubscriber<? super R> actual,
Function<? super T, ? extends R> mapper) {
this.actual = actual;
this.mapper = mapper;
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) return s;
if (key == Attr.TERMINATED) return done;
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return InnerOperator.super.scanUnsafe(key);
}
@SuppressWarnings("unchecked")
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(this.s, s)) {
this.s = (QueueSubscription<T>) s;
actual.onSubscribe(this);
}
}
@SuppressWarnings("DataFlowIssue") // fusion passes nulls via onNext
@Override
public void onNext(T t) {
if (sourceMode == ASYNC) {
actual.onNext(null);
}
else {
if (done) {
Operators.onNextDropped(t, actual.currentContext());
return;
}
R v;
try {
v = mapper.apply(t);
if (v == null) {
throw new NullPointerException("The mapper [" + mapper.getClass().getName() + "] returned a null value.");
}
}
catch (Throwable e) {
Throwable e_ = Operators.onNextError(t, e, actual.currentContext(), s);
if (e_ != null) {
onError(e_);
}
else {
s.request(1);
}
return;
}
actual.onNext(v);
}
}
@Override
public boolean tryOnNext(T t) {
if (done) {
Operators.onNextDropped(t, actual.currentContext());
return true;
}
R v;
try {
v = mapper.apply(t);
if (v == null) {
throw new NullPointerException("The mapper [" + mapper.getClass().getName() + "] returned a null value.");
}
return actual.tryOnNext(v);
}
catch (Throwable e) {
Throwable e_ = Operators.onNextError(t, e, actual.currentContext(), s);
if (e_ != null) {
onError(e_);
return true;
}
else {
return false;
}
}
}
@Override
public void onError(Throwable t) {
if (done) {
Operators.onErrorDropped(t, actual.currentContext());
return;
}
done = true;
actual.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
actual.onComplete();
}
@Override
public CoreSubscriber<? super R> actual() {
return actual;
}
@Override
public void request(long n) {
s.request(n);
}
@Override
public void cancel() {
s.cancel();
}
@Override
public @Nullable R poll() {
for(;;) {
T v = s.poll();
if (v != null) {
try {
return Objects.requireNonNull(mapper.apply(v));
}
catch (Throwable t) {
RuntimeException e_ = Operators.onNextPollError(v, t, currentContext());
if (e_ != null) {
throw e_;
}
else {
continue;
}
}
}
return null;
}
}
@Override
public boolean isEmpty() {
return s.isEmpty();
}
@Override
public void clear() {
s.clear();
}
@Override
public int requestFusion(int requestedMode) {
int m;
if ((requestedMode & Fuseable.THREAD_BARRIER) != 0) {
return Fuseable.NONE;
}
else {
m = s.requestFusion(requestedMode);
}
sourceMode = m;
return m;
}
@Override
public int size() {
return s.size();
}
}
}
| MapFuseableConditionalSubscriber |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/mappingcontrol/CloningBeanMappingMapper.java | {
"start": 352,
"end": 573
} | interface ____ {
CloningBeanMappingMapper INSTANCE = Mappers.getMapper( CloningBeanMappingMapper.class );
@BeanMapping(mappingControl = DeepClone.class)
FridgeDTO clone(FridgeDTO in);
}
| CloningBeanMappingMapper |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/client/reactive/AbstractClientHttpResponse.java | {
"start": 2403,
"end": 3263
} | class ____<T> implements Publisher<T> {
private static final Subscription NO_OP_SUBSCRIPTION = new Subscription() {
@Override
public void request(long l) {
}
@Override
public void cancel() {
}
};
private final Publisher<T> delegate;
private final AtomicBoolean subscribed = new AtomicBoolean();
public SingleSubscriberPublisher(Publisher<T> delegate) {
this.delegate = delegate;
}
@Override
public void subscribe(Subscriber<? super T> subscriber) {
Objects.requireNonNull(subscriber, "Subscriber must not be null");
if (this.subscribed.compareAndSet(false, true)) {
this.delegate.subscribe(subscriber);
}
else {
subscriber.onSubscribe(NO_OP_SUBSCRIPTION);
subscriber.onError(new IllegalStateException("The client response body can only be consumed once"));
}
}
}
}
| SingleSubscriberPublisher |
java | quarkusio__quarkus | extensions/datasource/runtime/src/main/java/io/quarkus/datasource/runtime/DevServicesBuildTimeConfig.java | {
"start": 414,
"end": 5880
} | interface ____ {
/**
* Whether this Dev Service should start with the application in dev mode or tests.
*
* Dev Services are enabled by default
* unless connection configuration (e.g. the JDBC URL or reactive client URL) is set explicitly.
*
* @asciidoclet
*/
Optional<Boolean> enabled();
/**
* The container image name for container-based Dev Service providers.
*
* This has no effect if the provider is not a container-based database, such as H2 or Derby.
*
* Defaults depend on the configured `datasource`:
*
* * DB2: `{db2-image}`
* * MariaDB: `{mariadb-image}`
* * Microsoft SQL Server: `{mssql-image}`
* * MySQL: `{mysql-image}`
* * Oracle Express Edition: `{oracle-image}`
* * PostgreSQL: `{postgres-image}`
*
* @asciidoclet
*/
Optional<@WithConverter(TrimmedStringConverter.class) String> imageName();
/**
* Environment variables that are passed to the container.
*/
@ConfigDocMapKey("environment-variable-name")
Map<String, String> containerEnv();
/**
* Generic properties that are passed for additional container configuration.
* <p>
* Properties defined here are database-specific
* and are interpreted specifically in each database dev service implementation.
*/
@ConfigDocMapKey("property-key")
Map<String, String> containerProperties();
/**
* Generic properties that are added to the database connection URL.
*/
@ConfigDocMapKey("property-key")
Map<String, String> properties();
/**
* Optional fixed port the dev service will listen to.
* <p>
* If not defined, the port will be chosen randomly.
*/
OptionalInt port();
/**
* The container start command to use for container-based Dev Service providers.
* <p>
* This has no effect if the provider is not a container-based database, such as H2 or Derby.
*/
Optional<@WithConverter(TrimmedStringConverter.class) String> command();
/**
* The database name to use if this Dev Service supports overriding it.
*/
Optional<@WithConverter(TrimmedStringConverter.class) String> dbName();
/**
* The username to use if this Dev Service supports overriding it.
*/
Optional<String> username();
/**
* The password to use if this Dev Service supports overriding it.
*/
Optional<String> password();
/**
* The paths to SQL scripts to be loaded from the classpath and applied to the Dev Service database.
* <p>
* This has no effect if the provider is not a container-based database, such as H2 or Derby.
*/
Optional<List<@WithConverter(TrimmedStringConverter.class) String>> initScriptPath();
/**
* The paths to SQL scripts to be loaded from the classpath and applied to the Dev Service database using the SYS privileged
* user.
* Not all databases provide a privileged user. In these cases, the property is ignored.
* This has no effect if the provider is not a container-based database, such as H2 or Derby.
*/
Optional<List<@WithConverter(TrimmedStringConverter.class) String>> initPrivilegedScriptPath();
/**
* The volumes to be mapped to the container.
* <p>
* The map key corresponds to the host location; the map value is the container location.
* If the host location starts with "classpath:",
* the mapping loads the resource from the classpath with read-only permission.
* <p>
* When using a file system location, the volume will be generated with read-write permission,
* potentially leading to data loss or modification in your file system.
* <p>
* This has no effect if the provider is not a container-based database, such as H2 or Derby.
*/
@ConfigDocMapKey("host-path")
Map<String, String> volumes();
/**
* Whether to keep Dev Service containers running *after a dev mode session or test suite execution*
* to reuse them in the next dev mode session or test suite execution.
*
* Within a dev mode session or test suite execution,
* Quarkus will always reuse Dev Services as long as their configuration
* (username, password, environment, port bindings, ...) did not change.
* This feature is specifically about keeping containers running
* **when Quarkus is not running** to reuse them across runs.
*
* WARNING: This feature needs to be enabled explicitly in `testcontainers.properties`,
* may require changes to how you configure data initialization in dev mode and tests,
* and may leave containers running indefinitely, forcing you to stop and remove them manually.
* See xref:databases-dev-services.adoc#reuse[this section of the documentation] for more information.
*
* This configuration property is set to `true` by default,
* so it is mostly useful to *disable* reuse,
* if you enabled it in `testcontainers.properties`
* but only want to use it for some of your Quarkus applications or datasources.
*
* @asciidoclet
*/
@WithDefault("true")
boolean reuse();
/**
* Whether the logs should be consumed by the JBoss logger.
* <p>
* This has no effect if the provider is not a container-based database, such as H2 or Derby.
*/
@WithDefault("false")
boolean showLogs();
}
| DevServicesBuildTimeConfig |
java | elastic__elasticsearch | x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/collector/ml/JobStatsCollectorTests.java | {
"start": 2038,
"end": 9506
} | class ____ extends BaseCollectorTestCase {
public void testShouldCollectReturnsFalseIfNotMaster() {
// regardless of ML being enabled
final Settings settings = randomFrom(mlEnabledSettings(), mlDisabledSettings());
when(licenseState.isAllowed(MachineLearningField.ML_API_FEATURE)).thenReturn(randomBoolean());
// this controls the blockage
final boolean isElectedMaster = false;
final JobStatsCollector collector = new JobStatsCollector(settings, clusterService, licenseState, client);
assertThat(collector.shouldCollect(isElectedMaster), is(false));
}
public void testShouldCollectReturnsFalseIfMLIsDisabled() {
// this is controls the blockage
final Settings settings = mlDisabledSettings();
when(licenseState.isAllowed(MachineLearningField.ML_API_FEATURE)).thenReturn(randomBoolean());
final boolean isElectedMaster = randomBoolean();
whenLocalNodeElectedMaster(isElectedMaster);
final JobStatsCollector collector = new JobStatsCollector(settings, clusterService, licenseState, client);
assertThat(collector.shouldCollect(isElectedMaster), is(false));
}
public void testShouldCollectReturnsFalseIfMLIsNotAllowed() {
final Settings settings = randomFrom(mlEnabledSettings(), mlDisabledSettings());
// this is controls the blockage
when(licenseState.isAllowed(MachineLearningField.ML_API_FEATURE)).thenReturn(false);
final boolean isElectedMaster = randomBoolean();
whenLocalNodeElectedMaster(isElectedMaster);
final JobStatsCollector collector = new JobStatsCollector(settings, clusterService, licenseState, client);
assertThat(collector.shouldCollect(isElectedMaster), is(false));
}
public void testShouldCollectReturnsTrue() {
final Settings settings = mlEnabledSettings();
when(licenseState.isAllowed(MachineLearningField.ML_API_FEATURE)).thenReturn(true);
final boolean isElectedMaster = true;
final JobStatsCollector collector = new JobStatsCollector(settings, clusterService, licenseState, client);
assertThat(collector.shouldCollect(isElectedMaster), is(true));
}
public void testDoCollect() throws Exception {
final String clusterUuid = randomAlphaOfLength(5);
whenClusterStateWithUUID(clusterUuid);
final MonitoringDoc.Node node = randomMonitoringNode(random());
final Client client = mock(Client.class);
final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
final TimeValue timeout = TimeValue.timeValueSeconds(randomIntBetween(1, 120));
withCollectionTimeout(JobStatsCollector.JOB_STATS_TIMEOUT, timeout);
final JobStatsCollector collector = new JobStatsCollector(Settings.EMPTY, clusterService, licenseState, client, threadContext);
assertEquals(timeout, collector.getCollectionTimeout());
final List<JobStats> jobStats = mockJobStats();
@SuppressWarnings("unchecked")
final ActionFuture<Response> future = (ActionFuture<Response>) mock(ActionFuture.class);
final Response response = new Response(new QueryPage<>(jobStats, jobStats.size(), Job.RESULTS_FIELD));
when(client.execute(eq(GetJobsStatsAction.INSTANCE), eq(new Request(Metadata.ALL).setTimeout(timeout)))).thenReturn(future);
when(future.actionGet()).thenReturn(response);
final long interval = randomNonNegativeLong();
final List<MonitoringDoc> monitoringDocs = collector.doCollect(node, interval, clusterState);
verify(clusterState).metadata();
verify(metadata).clusterUUID();
assertThat(monitoringDocs, hasSize(jobStats.size()));
for (int i = 0; i < monitoringDocs.size(); ++i) {
final JobStatsMonitoringDoc jobStatsMonitoringDoc = (JobStatsMonitoringDoc) monitoringDocs.get(i);
final JobStats jobStat = jobStats.get(i);
assertThat(jobStatsMonitoringDoc.getCluster(), is(clusterUuid));
assertThat(jobStatsMonitoringDoc.getTimestamp(), greaterThan(0L));
assertThat(jobStatsMonitoringDoc.getIntervalMillis(), equalTo(interval));
assertThat(jobStatsMonitoringDoc.getNode(), equalTo(node));
assertThat(jobStatsMonitoringDoc.getSystem(), is(MonitoredSystem.ES));
assertThat(jobStatsMonitoringDoc.getType(), is(JobStatsMonitoringDoc.TYPE));
assertThat(jobStatsMonitoringDoc.getId(), nullValue());
assertThat(jobStatsMonitoringDoc.getJobStats(), is(jobStat));
}
assertWarnings(
"[xpack.monitoring.collection.ml.job.stats.timeout] setting was deprecated in Elasticsearch and will be removed "
+ "in a future release. See the deprecation documentation for the next major version."
);
}
public void testDoCollectThrowsTimeoutException() throws Exception {
final String clusterUuid = randomAlphaOfLength(5);
whenClusterStateWithUUID(clusterUuid);
final MonitoringDoc.Node node = randomMonitoringNode(random());
final Client client = mock(Client.class);
final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
final TimeValue timeout = TimeValue.timeValueSeconds(randomIntBetween(1, 120));
withCollectionTimeout(JobStatsCollector.JOB_STATS_TIMEOUT, timeout);
final JobStatsCollector collector = new JobStatsCollector(Settings.EMPTY, clusterService, licenseState, client, threadContext);
assertEquals(timeout, collector.getCollectionTimeout());
final List<JobStats> jobStats = mockJobStats();
@SuppressWarnings("unchecked")
final ActionFuture<Response> future = (ActionFuture<Response>) mock(ActionFuture.class);
final Response response = new Response(
List.of(),
List.of(new FailedNodeException("node", "msg", new ElasticsearchTimeoutException("test timeout"))),
new QueryPage<>(jobStats, jobStats.size(), Job.RESULTS_FIELD)
);
when(client.execute(eq(GetJobsStatsAction.INSTANCE), eq(new Request(Metadata.ALL).setTimeout(timeout)))).thenReturn(future);
when(future.actionGet()).thenReturn(response);
final long interval = randomNonNegativeLong();
expectThrows(ElasticsearchTimeoutException.class, () -> collector.doCollect(node, interval, clusterState));
assertWarnings(
"[xpack.monitoring.collection.ml.job.stats.timeout] setting was deprecated in Elasticsearch and will be removed "
+ "in a future release. See the deprecation documentation for the next major version."
);
}
private List<JobStats> mockJobStats() {
final int jobs = randomIntBetween(1, 5);
final List<JobStats> jobStats = new ArrayList<>(jobs);
for (int i = 0; i < jobs; ++i) {
jobStats.add(mock(JobStats.class));
}
return jobStats;
}
private Settings mlEnabledSettings() {
// since it's the default, we want to ensure we test both with/without it
return randomBoolean() ? Settings.EMPTY : Settings.builder().put(XPackSettings.MACHINE_LEARNING_ENABLED.getKey(), true).build();
}
private Settings mlDisabledSettings() {
return Settings.builder().put(XPackSettings.MACHINE_LEARNING_ENABLED.getKey(), false).build();
}
}
| JobStatsCollectorTests |
java | quarkusio__quarkus | extensions/funqy/funqy-amazon-lambda/runtime/src/main/java/io/quarkus/funqy/lambda/FunqyResponseImpl.java | {
"start": 126,
"end": 384
} | class ____ implements FunqyServerResponse {
protected Uni<?> output;
@Override
public Uni<?> getOutput() {
return output;
}
@Override
public void setOutput(Uni<?> output) {
this.output = output;
}
}
| FunqyResponseImpl |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/query/TermsQueryBuilderTests.java | {
"start": 1945,
"end": 17177
} | class ____ extends AbstractQueryTestCase<TermsQueryBuilder> {
private List<Object> randomTerms;
private String termsPath;
@Before
public void randomTerms() {
List<Object> randomTerms = new ArrayList<>();
String[] strings = generateRandomStringArray(10, 10, false, true);
for (String string : strings) {
randomTerms.add(string);
if (rarely()) {
randomTerms.add(null);
}
}
this.randomTerms = randomTerms;
termsPath = randomAlphaOfLength(10).replace('.', '_');
}
@Override
protected TermsQueryBuilder doCreateTestQueryBuilder() {
TermsQueryBuilder query;
// terms query or lookup query
if (randomBoolean()) {
// make between 0 and 5 different values of the same type
String fieldName = randomValueOtherThanMany(
choice -> choice.equals(GEO_POINT_FIELD_NAME)
|| choice.equals(BINARY_FIELD_NAME)
|| choice.equals(GEO_POINT_ALIAS_FIELD_NAME)
|| choice.equals(INT_RANGE_FIELD_NAME)
|| choice.equals(DATE_ALIAS_FIELD_NAME)
|| choice.equals(DATE_RANGE_FIELD_NAME)
|| choice.equals(DATE_NANOS_FIELD_NAME), // TODO: needs testing for date_nanos type
AbstractQueryTestCase::getRandomFieldName
);
Object[] values = new Object[randomInt(5)];
for (int i = 0; i < values.length; i++) {
values[i] = getRandomValueForFieldName(fieldName);
}
query = new TermsQueryBuilder(fieldName, values);
} else {
// right now the mock service returns us a list of strings
query = new TermsQueryBuilder(randomBoolean() ? randomAlphaOfLengthBetween(1, 10) : TEXT_FIELD_NAME, randomTermsLookup());
}
return query;
}
private TermsLookup randomTermsLookup() {
TermsLookup lookup = new TermsLookup(randomAlphaOfLength(10), randomAlphaOfLength(10), termsPath);
lookup.routing(randomBoolean() ? randomAlphaOfLength(10) : null);
return lookup;
}
@Override
protected void doAssertLuceneQuery(TermsQueryBuilder queryBuilder, Query query, SearchExecutionContext context) throws IOException {
if (queryBuilder.termsLookup() == null && (queryBuilder.values() == null || queryBuilder.values().isEmpty())) {
assertThat(query, instanceOf(MatchNoDocsQuery.class));
} else if (queryBuilder.termsLookup() != null && randomTerms.isEmpty()) {
assertThat(query, instanceOf(MatchNoDocsQuery.class));
} else {
assertThat(
query,
either(instanceOf(TermInSetQuery.class)).or(instanceOf(PointInSetQuery.class))
.or(instanceOf(ConstantScoreQuery.class))
.or(instanceOf(MatchNoDocsQuery.class))
);
// if (true) throw new IllegalArgumentException(randomTerms.toString());
if (query instanceof ConstantScoreQuery) {
assertThat(((ConstantScoreQuery) query).getQuery(), instanceOf(BooleanQuery.class));
}
// we only do the check below for string fields (otherwise we'd have to decode the values)
if (queryBuilder.fieldName().equals(INT_FIELD_NAME)
|| queryBuilder.fieldName().equals(INT_ALIAS_FIELD_NAME)
|| queryBuilder.fieldName().equals(DOUBLE_FIELD_NAME)
|| queryBuilder.fieldName().equals(BOOLEAN_FIELD_NAME)
|| queryBuilder.fieldName().equals(DATE_FIELD_NAME)) {
return;
}
// expected returned terms depending on whether we have a terms query or a terms lookup query
List<Object> terms;
if (queryBuilder.termsLookup() != null) {
terms = randomTerms;
} else {
terms = queryBuilder.values();
}
String fieldName = expectedFieldName(queryBuilder.fieldName());
Query expected;
if (context.getFieldType(fieldName) != null) {
expected = new TermInSetQuery(
fieldName,
terms.stream().filter(Objects::nonNull).map(Object::toString).map(BytesRef::new).toList()
);
} else {
expected = new MatchNoDocsQuery();
}
assertEquals(expected, query);
}
}
public void testEmptyFieldName() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder(null, "term"));
assertEquals("field name cannot be null.", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("", "term"));
assertEquals("field name cannot be null.", e.getMessage());
}
public void testEmptyTermsLookup() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (TermsLookup) null));
assertEquals("No value or termsLookup specified for terms query", e.getMessage());
}
public void testNullValues() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (String[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (int[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (long[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (float[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (double[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (Object[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
}
public void testBothValuesAndLookupSet() throws IOException {
String query = """
{
"terms": {
"field": [
"blue",
"pill"
],
"field_lookup": {
"index": "pills",
"type": "red",
"id": "3",
"path": "white rabbit"
}
}
}""";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(query));
assertThat(e.getMessage(), containsString("[" + TermsQueryBuilder.NAME + "] query does not support more than one field."));
}
@Override
public GetResponse executeGet(GetRequest getRequest) {
String json;
try {
XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
builder.startObject();
builder.array(termsPath, randomTerms.toArray(Object[]::new));
builder.endObject();
json = Strings.toString(builder);
} catch (IOException ex) {
throw new ElasticsearchException("boom", ex);
}
return new GetResponse(new GetResult(getRequest.index(), getRequest.id(), 0, 1, 0, true, new BytesArray(json), null, null));
}
public void testNumeric() throws IOException {
{
TermsQueryBuilder builder = new TermsQueryBuilder("foo", new int[] { 1, 3, 4 });
TermsQueryBuilder copy = (TermsQueryBuilder) assertSerialization(builder);
List<Object> values = copy.values();
assertEquals(Arrays.asList(1, 3, 4), values);
}
{
TermsQueryBuilder builder = new TermsQueryBuilder("foo", new double[] { 1, 3, 4 });
TermsQueryBuilder copy = (TermsQueryBuilder) assertSerialization(builder);
List<Object> values = copy.values();
assertEquals(Arrays.asList(1d, 3d, 4d), values);
}
{
TermsQueryBuilder builder = new TermsQueryBuilder("foo", new float[] { 1, 3, 4 });
TermsQueryBuilder copy = (TermsQueryBuilder) assertSerialization(builder);
List<Object> values = copy.values();
assertEquals(Arrays.asList(1f, 3f, 4f), values);
}
{
TermsQueryBuilder builder = new TermsQueryBuilder("foo", new long[] { 1, 3, 4 });
TermsQueryBuilder copy = (TermsQueryBuilder) assertSerialization(builder);
List<Object> values = copy.values();
assertEquals(Arrays.asList(1L, 3L, 4L), values);
}
}
public void testTermsQueryWithMultipleFields() throws IOException {
String query = Strings.toString(
XContentFactory.jsonBuilder().startObject().startObject("terms").array("foo", 123).array("bar", 456).endObject().endObject()
);
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(query));
assertEquals("[" + TermsQueryBuilder.NAME + "] query does not support multiple fields", e.getMessage());
}
public void testFromJson() throws IOException {
String json = """
{
"terms" : {
"user" : [ "kimchy", "elasticsearch" ],
"boost" : 1.0
}
}""";
TermsQueryBuilder parsed = (TermsQueryBuilder) parseQuery(json);
checkGeneratedJson(json, parsed);
assertEquals(json, 2, parsed.values().size());
}
@Override
public void testMustRewrite() throws IOException {
TermsQueryBuilder termsQueryBuilder = new TermsQueryBuilder(TEXT_FIELD_NAME, randomTermsLookup());
UnsupportedOperationException e = expectThrows(
UnsupportedOperationException.class,
() -> termsQueryBuilder.toQuery(createSearchExecutionContext())
);
assertEquals("query must be rewritten first", e.getMessage());
// terms lookup removes null values
List<Object> nonNullTerms = randomTerms.stream().filter(Objects::nonNull).toList();
QueryBuilder expected;
if (nonNullTerms.isEmpty()) {
expected = new MatchNoneQueryBuilder();
} else {
expected = new TermsQueryBuilder(TEXT_FIELD_NAME, nonNullTerms);
}
assertEquals(expected, rewriteAndFetch(termsQueryBuilder, createSearchExecutionContext()));
}
public void testGeo() throws Exception {
TermsQueryBuilder query = new TermsQueryBuilder(GEO_POINT_FIELD_NAME, "2,3");
SearchExecutionContext context = createSearchExecutionContext();
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> query.toQuery(context));
assertEquals(
"Geometry fields do not support exact searching, use dedicated geometry queries instead: [mapped_geo_point]",
e.getMessage()
);
}
public void testSerializationFailsUnlessFetched() throws IOException {
QueryBuilder builder = new TermsQueryBuilder(TEXT_FIELD_NAME, randomTermsLookup());
QueryBuilder termsQueryBuilder = Rewriteable.rewrite(builder, createSearchExecutionContext());
IllegalStateException ise = expectThrows(IllegalStateException.class, () -> termsQueryBuilder.writeTo(new BytesStreamOutput(10)));
assertEquals(ise.getMessage(), "supplier must be null, can't serialize suppliers, missing a rewriteAndFetch?");
builder = rewriteAndFetch(builder, createSearchExecutionContext());
builder.writeTo(new BytesStreamOutput(10));
}
public void testRewriteIndexQueryToMatchNone() throws IOException {
TermsQueryBuilder query = new TermsQueryBuilder("_index", "does_not_exist", "also_does_not_exist");
for (QueryRewriteContext context : new QueryRewriteContext[] { createSearchExecutionContext(), createQueryRewriteContext() }) {
QueryBuilder rewritten = query.rewrite(context);
assertThat(rewritten, instanceOf(MatchNoneQueryBuilder.class));
}
}
public void testRewriteIndexQueryToNotMatchNone() throws IOException {
// At least one name is good
TermsQueryBuilder query = new TermsQueryBuilder("_index", "does_not_exist", getIndex().getName());
for (QueryRewriteContext context : new QueryRewriteContext[] { createSearchExecutionContext(), createQueryRewriteContext() }) {
QueryBuilder rewritten = query.rewrite(context);
assertThat(rewritten, instanceOf(MatchAllQueryBuilder.class));
}
}
public void testLongTerm() throws IOException {
String longTerm = "a".repeat(IndexWriter.MAX_TERM_LENGTH + 1);
Exception e = expectThrows(IllegalArgumentException.class, () -> parseQuery(String.format(Locale.getDefault(), """
{ "terms" : { "foo" : [ "q", "%s" ] } }""", longTerm)));
assertThat(e.getMessage(), containsString("term starting with [aaaaa"));
}
public void testCoordinatorTierRewriteToMatchAll() throws IOException {
QueryBuilder query = new TermsQueryBuilder("_tier", "data_frozen");
final String timestampFieldName = "@timestamp";
long minTimestamp = 1685714000000L;
long maxTimestamp = 1685715000000L;
final CoordinatorRewriteContext coordinatorRewriteContext = createCoordinatorRewriteContext(
new DateFieldMapper.DateFieldType(timestampFieldName),
minTimestamp,
maxTimestamp,
"data_frozen"
);
QueryBuilder rewritten = query.rewrite(coordinatorRewriteContext);
assertThat(rewritten, CoreMatchers.instanceOf(MatchAllQueryBuilder.class));
}
public void testCoordinatorTierRewriteToMatchNone() throws IOException {
QueryBuilder query = QueryBuilders.boolQuery().mustNot(new TermsQueryBuilder("_tier", "data_frozen"));
final String timestampFieldName = "@timestamp";
long minTimestamp = 1685714000000L;
long maxTimestamp = 1685715000000L;
final CoordinatorRewriteContext coordinatorRewriteContext = createCoordinatorRewriteContext(
new DateFieldMapper.DateFieldType(timestampFieldName),
minTimestamp,
maxTimestamp,
"data_frozen"
);
QueryBuilder rewritten = query.rewrite(coordinatorRewriteContext);
assertThat(rewritten, CoreMatchers.instanceOf(MatchNoneQueryBuilder.class));
}
@Override
protected QueryBuilder parseQuery(XContentParser parser) throws IOException {
QueryBuilder query = super.parseQuery(parser);
assertThat(query, CoreMatchers.instanceOf(TermsQueryBuilder.class));
return query;
}
}
| TermsQueryBuilderTests |
java | apache__camel | dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/KnownReposResolver.java | {
"start": 963,
"end": 1982
} | class ____ {
private final Map<String, String> repos = new HashMap<>();
public KnownReposResolver() {
}
public void loadKnownDependencies() {
doLoadKnownRepos("/camel-main-known-repos.properties");
}
private void doLoadKnownRepos(String name) {
try {
InputStream is = getClass().getResourceAsStream(name);
if (is != null) {
Properties prop = new Properties();
prop.load(is);
Map<String, String> map = new HashMap<>();
for (String key : prop.stringPropertyNames()) {
String value = prop.getProperty(key);
map.put(key, value);
}
addRepos(map);
}
} catch (Exception e) {
// ignore
}
}
public void addRepos(Map<String, String> repos) {
this.repos.putAll(repos);
}
public String getRepo(String key) {
return repos.get(key);
}
}
| KnownReposResolver |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SlackEndpointBuilderFactory.java | {
"start": 36639,
"end": 37633
} | interface ____
extends
SlackEndpointConsumerBuilder,
SlackEndpointProducerBuilder {
default AdvancedSlackEndpointBuilder advanced() {
return (AdvancedSlackEndpointBuilder) this;
}
/**
* The token to access Slack. This app needs to have channels:history,
* groups:history, im:history, mpim:history, channels:read, groups:read,
* im:read and mpim:read permissions. The User OAuth Token is the kind
* of token needed.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param token the value to set
* @return the dsl builder
*/
default SlackEndpointBuilder token(String token) {
doSetProperty("token", token);
return this;
}
}
/**
* Advanced builder for endpoint for the Slack component.
*/
public | SlackEndpointBuilder |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/BeanMeta.java | {
"start": 8653,
"end": 10139
} | class ____ {
private final Constructor<?> constructor;
private final ConstructorParameterMeta[] parameters;
ConstructorMeta(RestToolKit toolKit, String prefix, Constructor<?> constructor) {
this.constructor = constructor;
parameters = initParameters(toolKit, prefix, constructor);
}
public ConstructorParameterMeta[] getParameters() {
return parameters;
}
private ConstructorParameterMeta[] initParameters(RestToolKit toolKit, String prefix, Constructor<?> ct) {
Parameter[] cps = ct.getParameters();
int len = cps.length;
if (len == 0) {
return new ConstructorParameterMeta[0];
}
String[] parameterNames = toolKit == null ? null : toolKit.getParameterNames(ct);
ConstructorParameterMeta[] parameters = new ConstructorParameterMeta[len];
for (int i = 0; i < len; i++) {
String parameterName = parameterNames == null ? null : parameterNames[i];
parameters[i] = new ConstructorParameterMeta(toolKit, cps[i], prefix, parameterName);
}
return parameters;
}
public Object newInstance(Object... args) {
try {
return constructor.newInstance(args);
} catch (Throwable t) {
throw ExceptionUtils.wrap(t);
}
}
}
public static final | ConstructorMeta |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportAnnotationDetectionTests.java | {
"start": 3559,
"end": 3678
} | interface ____ {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(Config2.class)
@ | MetaImport1 |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/testutil/compilation/model/CompilationOutcomeDescriptor.java | {
"start": 904,
"end": 5936
} | class ____ {
private CompilationResult compilationResult;
private List<DiagnosticDescriptor> diagnostics;
private List<String> notes;
private CompilationOutcomeDescriptor(CompilationResult compilationResult,
List<DiagnosticDescriptor> diagnostics,
List<String> notes) {
this.compilationResult = compilationResult;
this.diagnostics = diagnostics;
this.notes = notes;
}
public static CompilationOutcomeDescriptor forExpectedCompilationResult(
ExpectedCompilationOutcome expectedCompilationResult, ExpectedNote.ExpectedNotes expectedNotes,
ExpectedNote expectedNote) {
List<String> notes = new ArrayList<>();
if ( expectedNotes != null ) {
notes.addAll( Stream.of( expectedNotes.value() )
.map( ExpectedNote::value )
.collect( Collectors.toList() ) );
}
if ( expectedNote != null ) {
notes.add( expectedNote.value() );
}
if ( expectedCompilationResult == null ) {
return new CompilationOutcomeDescriptor(
CompilationResult.SUCCEEDED,
Collections.emptyList(),
notes
);
}
else {
List<DiagnosticDescriptor> diagnosticDescriptors = new ArrayList<>();
for ( org.mapstruct.ap.testutil.compilation.annotation.Diagnostic diagnostic :
expectedCompilationResult.diagnostics() ) {
diagnosticDescriptors.add( DiagnosticDescriptor.forDiagnostic( diagnostic ) );
}
return new CompilationOutcomeDescriptor( expectedCompilationResult.value(), diagnosticDescriptors, notes );
}
}
public static CompilationOutcomeDescriptor forResult(String sourceDir, boolean compilationSuccessful,
List<Diagnostic<? extends JavaFileObject>> diagnostics) {
CompilationResult compilationResult =
compilationSuccessful ? CompilationResult.SUCCEEDED : CompilationResult.FAILED;
List<String> notes = new ArrayList<>();
List<DiagnosticDescriptor> diagnosticDescriptors = new ArrayList<>();
for ( Diagnostic<? extends JavaFileObject> diagnostic : diagnostics ) {
//ignore notes created by the compiler
if ( diagnostic.getKind() != Kind.NOTE ) {
diagnosticDescriptors.add( DiagnosticDescriptor.forDiagnostic( sourceDir, diagnostic ) );
}
else {
notes.add( diagnostic.getMessage( null ) );
}
}
return new CompilationOutcomeDescriptor( compilationResult, diagnosticDescriptors, notes );
}
public static CompilationOutcomeDescriptor forResult(String sourceDir, CompilerResult compilerResult) {
CompilationResult compilationResult =
compilerResult.isSuccess() ? CompilationResult.SUCCEEDED : CompilationResult.FAILED;
List<DiagnosticDescriptor> diagnosticDescriptors = new ArrayList<>();
for ( CompilerMessage message : compilerResult.getCompilerMessages() ) {
if ( message.getKind() != CompilerMessage.Kind.NOTE ) {
diagnosticDescriptors.add( DiagnosticDescriptor.forCompilerMessage( sourceDir, message ) );
}
// the eclipse compiler does not support NOTE (it is never actually set).
}
return new CompilationOutcomeDescriptor( compilationResult, diagnosticDescriptors, Collections.emptyList() );
}
public CompilationResult getCompilationResult() {
return compilationResult;
}
public List<DiagnosticDescriptor> getDiagnostics() {
return diagnostics;
}
public List<String> getNotes() {
return notes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ( ( compilationResult == null ) ? 0 : compilationResult
.hashCode() );
result = prime * result
+ ( ( diagnostics == null ) ? 0 : diagnostics.hashCode() );
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
CompilationOutcomeDescriptor other = (CompilationOutcomeDescriptor) obj;
if ( compilationResult != other.compilationResult ) {
return false;
}
if ( !Objects.equals( diagnostics, other.diagnostics ) ) {
return false;
}
return true;
}
@Override
public String toString() {
return "CompilationResultDescriptor [compilationResult="
+ compilationResult + ", diagnostics=" + diagnostics + "]";
}
}
| CompilationOutcomeDescriptor |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/InvalidMetadataException.java | {
"start": 935,
"end": 1413
} | class ____ extends RefreshRetriableException {
private static final long serialVersionUID = 1L;
protected InvalidMetadataException() {
super();
}
protected InvalidMetadataException(String message) {
super(message);
}
protected InvalidMetadataException(String message, Throwable cause) {
super(message, cause);
}
protected InvalidMetadataException(Throwable cause) {
super(cause);
}
}
| InvalidMetadataException |
java | resilience4j__resilience4j | resilience4j-ratelimiter/src/test/java/io/github/resilience4j/ratelimiter/internal/InMemoryRateLimiterRegistryTest.java | {
"start": 1409,
"end": 7782
} | class ____ {
private static final int LIMIT = 50;
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private static final Duration REFRESH_PERIOD = Duration.ofNanos(500);
private static final String CONFIG_MUST_NOT_BE_NULL = "Config must not be null";
private static final String NAME_MUST_NOT_BE_NULL = "Name must not be null";
@Rule
public ExpectedException exception = ExpectedException.none();
private RateLimiterConfig config;
@Before
public void init() {
config = RateLimiterConfig.custom()
.timeoutDuration(TIMEOUT)
.limitRefreshPeriod(REFRESH_PERIOD)
.limitForPeriod(LIMIT)
.build();
}
@Test
public void rateLimiterPositive() throws Exception {
RateLimiterRegistry registry = RateLimiterRegistry.of(config);
RateLimiter firstRateLimiter = registry.rateLimiter("test");
RateLimiter anotherLimit = registry.rateLimiter("test1");
RateLimiter sameAsFirst = registry.rateLimiter("test");
then(firstRateLimiter).isEqualTo(sameAsFirst);
then(firstRateLimiter).isNotEqualTo(anotherLimit);
}
@Test
@SuppressWarnings("unchecked")
public void rateLimiterPositiveWithSupplier() throws Exception {
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
Supplier<RateLimiterConfig> rateLimiterConfigSupplier = mock(Supplier.class);
when(rateLimiterConfigSupplier.get())
.thenReturn(config);
RateLimiter firstRateLimiter = registry.rateLimiter("test", rateLimiterConfigSupplier);
verify(rateLimiterConfigSupplier, times(1)).get();
RateLimiter sameAsFirst = registry.rateLimiter("test", rateLimiterConfigSupplier);
verify(rateLimiterConfigSupplier, times(1)).get();
RateLimiter anotherLimit = registry.rateLimiter("test1", rateLimiterConfigSupplier);
verify(rateLimiterConfigSupplier, times(2)).get();
then(firstRateLimiter).isEqualTo(sameAsFirst);
then(firstRateLimiter).isNotEqualTo(anotherLimit);
}
@Test
public void rateLimiterConfigIsNull() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage(CONFIG_MUST_NOT_BE_NULL);
new InMemoryRateLimiterRegistry((RateLimiterConfig) null);
}
@Test
public void rateLimiterNewWithNullName() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage(NAME_MUST_NOT_BE_NULL);
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
registry.rateLimiter(null);
}
@Test
public void rateLimiterNewWithNullNonDefaultConfig() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage(CONFIG_MUST_NOT_BE_NULL);
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
RateLimiterConfig rateLimiterConfig = null;
registry.rateLimiter("name", rateLimiterConfig);
}
@Test
public void rateLimiterNewWithNullNameAndNonDefaultConfig() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage(NAME_MUST_NOT_BE_NULL);
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
registry.rateLimiter(null, config);
}
@Test
public void rateLimiterNewWithNullNameAndConfigSupplier() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage(NAME_MUST_NOT_BE_NULL);
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
registry.rateLimiter(null, () -> config);
}
@Test
public void rateLimiterNewWithNullConfigSupplier() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage("Supplier must not be null");
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
Supplier<RateLimiterConfig> rateLimiterConfigSupplier = null;
registry.rateLimiter("name", rateLimiterConfigSupplier);
}
@Test
public void rateLimiterGetAllRateLimiters() {
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
final RateLimiter rateLimiter = registry.rateLimiter("foo");
assertThat(registry.getAllRateLimiters().size()).isEqualTo(1);
assertThat(registry.getAllRateLimiters()).contains(rateLimiter);
}
@Test
public void shouldCreateRateLimiterRegistryWithRegistryStore() {
RegistryEventConsumer<RateLimiter> registryEventConsumer = getNoOpsRegistryEventConsumer();
List<RegistryEventConsumer<RateLimiter>> registryEventConsumers = new ArrayList<>();
registryEventConsumers.add(registryEventConsumer);
Map<String, RateLimiterConfig> configs = new HashMap<>();
final RateLimiterConfig defaultConfig = RateLimiterConfig.ofDefaults();
configs.put("default", defaultConfig);
final InMemoryRateLimiterRegistry inMemoryRateLimiterRegistry =
new InMemoryRateLimiterRegistry(configs, registryEventConsumers,
Map.of("Tag1", "Tag1Value"), new InMemoryRegistryStore<>());
AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry).isNotNull();
AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry.getDefaultConfig()).isEqualTo(defaultConfig);
AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry.getConfiguration("testNotFound")).isEmpty();
inMemoryRateLimiterRegistry.addConfiguration("testConfig", defaultConfig);
AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry.getConfiguration("testConfig")).isNotNull();
}
private RegistryEventConsumer<RateLimiter> getNoOpsRegistryEventConsumer() {
return new RegistryEventConsumer<RateLimiter>() {
@Override
public void onEntryAddedEvent(EntryAddedEvent<RateLimiter> entryAddedEvent) {
}
@Override
public void onEntryRemovedEvent(EntryRemovedEvent<RateLimiter> entryRemoveEvent) {
}
@Override
public void onEntryReplacedEvent(EntryReplacedEvent<RateLimiter> entryReplacedEvent) {
}
};
}
} | InMemoryRateLimiterRegistryTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/TriggerId.java | {
"start": 1889,
"end": 2288
} | class ____ extends AbstractID {
private static final long serialVersionUID = 1L;
public TriggerId() {}
private TriggerId(final byte[] bytes) {
super(bytes);
}
public static TriggerId fromHexString(String hexString) {
return new TriggerId(StringUtils.hexStringToByte(hexString));
}
/** JSON serializer for {@link TriggerId}. */
public static | TriggerId |
java | apache__kafka | connect/mirror/src/test/java/org/apache/kafka/connect/mirror/HeartbeatTest.java | {
"start": 1004,
"end": 1855
} | class ____ {
@Test
public void testSerde() {
Heartbeat heartbeat = new Heartbeat("source-1", "target-2", 1234567890L);
byte[] key = heartbeat.recordKey();
byte[] value = heartbeat.recordValue();
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("any-topic", 6, 7, key, value);
Heartbeat deserialized = Heartbeat.deserializeRecord(record);
assertEquals(heartbeat.sourceClusterAlias(), deserialized.sourceClusterAlias(),
"Failure on heartbeat sourceClusterAlias serde");
assertEquals(heartbeat.targetClusterAlias(), deserialized.targetClusterAlias(),
"Failure on heartbeat targetClusterAlias serde");
assertEquals(heartbeat.timestamp(), deserialized.timestamp(),
"Failure on heartbeat timestamp serde");
}
}
| HeartbeatTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/records/impl/pb/ApplicationFinishDataPBImpl.java | {
"start": 1786,
"end": 7014
} | class ____ extends ApplicationFinishData {
ApplicationFinishDataProto proto = ApplicationFinishDataProto
.getDefaultInstance();
ApplicationFinishDataProto.Builder builder = null;
boolean viaProto = false;
private ApplicationId applicationId;
public ApplicationFinishDataPBImpl() {
builder = ApplicationFinishDataProto.newBuilder();
}
public ApplicationFinishDataPBImpl(ApplicationFinishDataProto proto) {
this.proto = proto;
viaProto = true;
}
@Override
public ApplicationId getApplicationId() {
if (this.applicationId != null) {
return this.applicationId;
}
ApplicationFinishDataProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasApplicationId()) {
return null;
}
this.applicationId = convertFromProtoFormat(p.getApplicationId());
return this.applicationId;
}
@Override
public void setApplicationId(ApplicationId applicationId) {
maybeInitBuilder();
if (applicationId == null) {
builder.clearApplicationId();
}
this.applicationId = applicationId;
}
@Override
public long getFinishTime() {
ApplicationFinishDataProtoOrBuilder p = viaProto ? proto : builder;
return p.getFinishTime();
}
@Override
public void setFinishTime(long finishTime) {
maybeInitBuilder();
builder.setFinishTime(finishTime);
}
@Override
public String getDiagnosticsInfo() {
ApplicationFinishDataProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasDiagnosticsInfo()) {
return null;
}
return p.getDiagnosticsInfo();
}
@Override
public void setDiagnosticsInfo(String diagnosticsInfo) {
maybeInitBuilder();
if (diagnosticsInfo == null) {
builder.clearDiagnosticsInfo();
return;
}
builder.setDiagnosticsInfo(diagnosticsInfo);
}
@Override
public FinalApplicationStatus getFinalApplicationStatus() {
ApplicationFinishDataProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasFinalApplicationStatus()) {
return null;
}
return convertFromProtoFormat(p.getFinalApplicationStatus());
}
@Override
public void setFinalApplicationStatus(
FinalApplicationStatus finalApplicationStatus) {
maybeInitBuilder();
if (finalApplicationStatus == null) {
builder.clearFinalApplicationStatus();
return;
}
builder
.setFinalApplicationStatus(convertToProtoFormat(finalApplicationStatus));
}
@Override
public YarnApplicationState getYarnApplicationState() {
ApplicationFinishDataProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasYarnApplicationState()) {
return null;
}
return convertFromProtoFormat(p.getYarnApplicationState());
}
@Override
public void setYarnApplicationState(YarnApplicationState state) {
maybeInitBuilder();
if (state == null) {
builder.clearYarnApplicationState();
return;
}
builder.setYarnApplicationState(convertToProtoFormat(state));
}
public ApplicationFinishDataProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
private void mergeLocalToBuilder() {
if (this.applicationId != null
&& !((ApplicationIdPBImpl) this.applicationId).getProto().equals(
builder.getApplicationId())) {
builder.setApplicationId(convertToProtoFormat(this.applicationId));
}
}
private void mergeLocalToProto() {
if (viaProto) {
maybeInitBuilder();
}
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = ApplicationFinishDataProto.newBuilder(proto);
}
viaProto = false;
}
private ApplicationIdProto convertToProtoFormat(ApplicationId applicationId) {
return ((ApplicationIdPBImpl) applicationId).getProto();
}
private ApplicationIdPBImpl convertFromProtoFormat(
ApplicationIdProto applicationId) {
return new ApplicationIdPBImpl(applicationId);
}
private FinalApplicationStatus convertFromProtoFormat(
FinalApplicationStatusProto finalApplicationStatus) {
return ProtoUtils.convertFromProtoFormat(finalApplicationStatus);
}
private FinalApplicationStatusProto convertToProtoFormat(
FinalApplicationStatus finalApplicationStatus) {
return ProtoUtils.convertToProtoFormat(finalApplicationStatus);
}
private YarnApplicationStateProto convertToProtoFormat(
YarnApplicationState state) {
return ProtoUtils.convertToProtoFormat(state);
}
private YarnApplicationState convertFromProtoFormat(
YarnApplicationStateProto yarnApplicationState) {
return ProtoUtils.convertFromProtoFormat(yarnApplicationState);
}
}
| ApplicationFinishDataPBImpl |
java | apache__logging-log4j2 | log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestResultFormatter.java | {
"start": 1290,
"end": 1451
} | class ____ {
static final String LF = System.lineSeparator();
static final NumberFormat NUM = new DecimalFormat("#,##0");
static | PerfTestResultFormatter |
java | apache__flink | flink-connectors/flink-connector-files/src/test/java/org/apache/flink/connector/file/src/impl/DynamicFileSplitEnumeratorTest.java | {
"start": 6889,
"end": 7705
} | class ____ implements DynamicFileEnumerator {
private final List<String> remainingSplits;
private List<String> enumeratingSplits;
private TestDynamicFileEnumerator(String[] allSplits, String[] remainingSplits) {
this.remainingSplits = Arrays.asList(remainingSplits);
this.enumeratingSplits = Arrays.asList(allSplits);
}
@Override
public void setDynamicFilteringData(DynamicFilteringData data) {
// Mock filtering result
enumeratingSplits = remainingSplits;
}
@Override
public Collection<FileSourceSplit> enumerateSplits(Path[] paths, int minDesiredSplits) {
return enumeratingSplits.stream().map(TestSplit::new).collect(Collectors.toList());
}
}
}
| TestDynamicFileEnumerator |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/sql/SqlArrayConstructor.java | {
"start": 1339,
"end": 1913
} | class ____ extends SqlArrayValueConstructor {
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
RelDataType type =
getComponentType(opBinding.getTypeFactory(), opBinding.collectOperandTypes());
if (null == type) {
return null;
}
// explicit cast elements to component type if they are not same
SqlValidatorUtils.adjustTypeForArrayConstructor(type, opBinding);
return SqlTypeUtil.createArrayType(opBinding.getTypeFactory(), type, false);
}
}
| SqlArrayConstructor |
java | apache__camel | core/camel-console/src/main/java/org/apache/camel/impl/console/RouteDumpDevConsole.java | {
"start": 1783,
"end": 10515
} | class ____ extends AbstractDevConsole {
private static final Pattern XML_SOURCE_LOCATION_PATTERN = Pattern.compile("(\\ssourceLocation=\"(.*?)\")");
private static final Pattern XML_SOURCE_LINE_PATTERN = Pattern.compile("(\\ssourceLineNumber=\"(.*?)\")");
/**
* To output in either xml, yaml, or text format
*/
public static final String FORMAT = "format";
/**
* Filters the routes matching by route id, route uri, and source location
*/
public static final String FILTER = "filter";
/**
* Limits the number of entries displayed
*/
public static final String LIMIT = "limit";
/**
* Whether to expand URIs into separated key/value parameters
*/
public static final String URI_AS_PARAMETERS = "uriAsParameters";
public RouteDumpDevConsole() {
super("camel", "route-dump", "Route Dump", "Dump route in XML or YAML format");
}
@Override
protected String doCallText(Map<String, Object> options) {
final String uriAsParameters = (String) options.getOrDefault(URI_AS_PARAMETERS, "false");
final StringBuilder sb = new StringBuilder();
Function<ManagedRouteMBean, Object> task = mrb -> {
String dump = null;
try {
String format = (String) options.get(FORMAT);
if (format == null || "xml".equals(format)) {
dump = mrb.dumpRouteAsXml(true);
} else if ("yaml".equals(format)) {
dump = mrb.dumpRouteAsYaml(true, "true".equals(uriAsParameters));
}
} catch (Exception e) {
// ignore
}
sb.append(String.format(" Id: %s", mrb.getRouteId()));
if (mrb.getSourceLocation() != null) {
sb.append(String.format("\n Source: %s", mrb.getSourceLocation()));
}
if (dump != null && !dump.isEmpty()) {
sb.append("\n\n");
for (String line : dump.split("\n")) {
sb.append(" ").append(line).append("\n");
}
sb.append("\n");
}
sb.append("\n");
return null;
};
doCall(options, task);
return sb.toString();
}
@Override
protected JsonObject doCallJson(Map<String, Object> options) {
final String uriAsParameters = (String) options.getOrDefault(URI_AS_PARAMETERS, "false");
final JsonObject root = new JsonObject();
final List<JsonObject> list = new ArrayList<>();
Function<ManagedRouteMBean, Object> task = mrb -> {
JsonObject jo = new JsonObject();
list.add(jo);
jo.put("routeId", mrb.getRouteId());
jo.put("from", mrb.getEndpointUri());
if (mrb.getSourceLocation() != null) {
jo.put("source", mrb.getSourceLocation());
}
try {
String dump = null;
String format = (String) options.get(FORMAT);
if (format == null || "xml".equals(format)) {
jo.put("format", "xml");
dump = mrb.dumpRouteAsXml(true, false, true);
} else if ("yaml".equals(format)) {
jo.put("format", "yaml");
dump = mrb.dumpRouteAsYaml(true, "true".equals(uriAsParameters), false, true);
}
if (dump != null) {
List<JsonObject> code;
if (format == null || "xml".equals(format)) {
code = xmlLoadSourceAsJson(new StringReader(dump));
} else {
code = yamlLoadSourceAsJson(new StringReader(dump));
}
if (code != null) {
jo.put("code", code);
}
}
} catch (Exception e) {
// ignore
}
return null;
};
doCall(options, task);
root.put("routes", list);
return root;
}
protected void doCall(Map<String, Object> options, Function<ManagedRouteMBean, Object> task) {
String path = (String) options.get(Exchange.HTTP_PATH);
String subPath = path != null ? StringHelper.after(path, "/") : null;
String filter = (String) options.get(FILTER);
String limit = (String) options.get(LIMIT);
final int max = limit == null ? Integer.MAX_VALUE : Integer.parseInt(limit);
ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class);
if (mcc != null) {
List<Route> routes = getCamelContext().getRoutes();
routes.sort((o1, o2) -> o1.getRouteId().compareToIgnoreCase(o2.getRouteId()));
routes.stream()
.map(route -> mcc.getManagedRoute(route.getRouteId()))
.filter(Objects::nonNull)
.filter(r -> accept(r, filter))
.filter(r -> accept(r, subPath))
.sorted(RouteDumpDevConsole::sort)
.limit(max)
.forEach(task::apply);
}
}
private static boolean accept(ManagedRouteMBean mrb, String filter) {
if (filter == null || filter.isBlank()) {
return true;
}
String onlyName = LoggerHelper.sourceNameOnly(mrb.getSourceLocation());
return PatternHelper.matchPattern(mrb.getRouteId(), filter)
|| PatternHelper.matchPattern(mrb.getEndpointUri(), filter)
|| PatternHelper.matchPattern(mrb.getSourceLocationShort(), filter)
|| PatternHelper.matchPattern(onlyName, filter);
}
private static int sort(ManagedRouteMBean o1, ManagedRouteMBean o2) {
// sort by id
return o1.getRouteId().compareTo(o2.getRouteId());
}
private static List<JsonObject> xmlLoadSourceAsJson(Reader reader) {
List<JsonObject> code = new ArrayList<>();
try {
LineNumberReader lnr = new LineNumberReader(reader);
String t;
do {
t = lnr.readLine();
if (t != null) {
// extra source location from code line
String idx = null;
Matcher m = XML_SOURCE_LOCATION_PATTERN.matcher(t);
if (m.find()) {
t = m.replaceFirst("");
}
m = XML_SOURCE_LINE_PATTERN.matcher(t);
if (m.find()) {
idx = m.group(2);
t = m.replaceFirst("");
}
JsonObject c = new JsonObject();
c.put("line", idx != null ? Integer.parseInt(idx) : -1);
c.put("code", Jsoner.escape(t));
code.add(c);
}
} while (t != null);
IOHelper.close(lnr);
} catch (Exception e) {
// ignore
}
return code.isEmpty() ? null : code;
}
private static List<JsonObject> yamlLoadSourceAsJson(Reader reader) {
List<JsonObject> code = new ArrayList<>();
try {
LineNumberReader lnr = new LineNumberReader(reader);
String t;
do {
t = lnr.readLine();
if (t != null) {
// extra source location from code line
if (t.contains("sourceLocation: ")) {
// skip this line
} else if (t.contains("sourceLineNumber: ")) {
String idx = StringHelper.after(t, "sourceLineNumber: ").trim();
if (!code.isEmpty()) {
// assign line number to previous code line
JsonObject c = code.get(code.size() - 1);
try {
c.put("line", Integer.parseInt(idx));
} catch (NumberFormatException e) {
// ignore
}
}
} else {
JsonObject c = new JsonObject();
c.put("code", Jsoner.escape(t));
c.put("line", -1);
code.add(c);
}
}
} while (t != null);
IOHelper.close(lnr);
} catch (Exception e) {
// ignore
}
return code.isEmpty() ? null : code;
}
}
| RouteDumpDevConsole |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactoryExtension.java | {
"start": 1907,
"end": 9565
} | class ____
implements TestInstancePostProcessor, BeforeEachCallback, TestExecutionExceptionHandler {
private static final Logger log = Logger.getLogger( SessionFactoryExtension.class );
private static final String SESSION_FACTORY_KEY = SessionFactoryScope.class.getName();
/**
* Intended for use from external consumers. Will never create a scope, just
* attempt to consume an already created and stored one
*/
public static SessionFactoryScope findSessionFactoryScope(Object testInstance, ExtensionContext context) {
final ExtensionContext.Store store = locateExtensionStore( testInstance, context );
final SessionFactoryScope existing = (SessionFactoryScope) store.get( SESSION_FACTORY_KEY );
if ( existing != null ) {
return existing;
}
throw new RuntimeException( "Could not locate SessionFactoryScope : " + context.getDisplayName() );
}
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
log.tracef( "#postProcessTestInstance(%s, %s)", testInstance, context.getDisplayName() );
final Optional<SessionFactory> sfAnnRef = AnnotationSupport.findAnnotation(
context.getRequiredTestClass(),
SessionFactory.class
);
if ( sfAnnRef.isPresent()
|| SessionFactoryProducer.class.isAssignableFrom( context.getRequiredTestClass() ) ) {
final DomainModelScope domainModelScope = DomainModelExtension.getOrCreateDomainModelScope( testInstance, context );
final SessionFactoryScope created = createSessionFactoryScope( testInstance, sfAnnRef, domainModelScope, context );
locateExtensionStore( testInstance, context ).put( SESSION_FACTORY_KEY, created );
}
}
@Override
public void beforeEach(ExtensionContext context) {
final Optional<SessionFactory> sfAnnRef = AnnotationSupport.findAnnotation(
context.getRequiredTestMethod(),
SessionFactory.class
);
if ( sfAnnRef.isEmpty() ) {
// assume the annotations are defined on the class-level...
// will be validated by the parameter-resolver or SFS-extension
return;
}
final DomainModelScope domainModelScope = DomainModelExtension.resolveForMethodLevelSessionFactoryScope( context );
final SessionFactoryScope created = createSessionFactoryScope( context.getRequiredTestInstance(), sfAnnRef, domainModelScope, context );
final ExtensionContext.Store extensionStore = locateExtensionStore( context.getRequiredTestInstance(), context );
extensionStore.put( SESSION_FACTORY_KEY, created );
}
private static ExtensionContext.Store locateExtensionStore(Object testInstance, ExtensionContext context) {
return JUnitHelper.locateExtensionStore( SessionFactoryExtension.class, context, testInstance );
}
private static SessionFactoryScopeImpl createSessionFactoryScope(
Object testInstance,
Optional<SessionFactory> sfAnnRef,
DomainModelScope domainModelScope,
ExtensionContext context) {
SessionFactoryProducer producer = null;
if ( testInstance instanceof SessionFactoryProducer ) {
producer = (SessionFactoryProducer) testInstance;
}
else {
if ( context.getElement().isEmpty() ) {
throw new RuntimeException( "Unable to determine how to handle given ExtensionContext : " + context.getDisplayName() );
}
if ( sfAnnRef.isPresent() ) {
final SessionFactory sessionFactoryConfig = sfAnnRef.get();
producer = model -> {
try {
final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder();
if ( StringHelper.isNotEmpty( sessionFactoryConfig.sessionFactoryName() ) ) {
sessionFactoryBuilder.applyName( sessionFactoryConfig.sessionFactoryName() );
}
if ( sessionFactoryConfig.generateStatistics() ) {
sessionFactoryBuilder.applyStatisticsSupport( true );
}
if ( ! sessionFactoryConfig.interceptorClass().equals( Interceptor.class ) ) {
sessionFactoryBuilder.applyInterceptor( sessionFactoryConfig.interceptorClass().getDeclaredConstructor().newInstance() );
}
final Class<? extends StatementInspector> explicitInspectorClass = sessionFactoryConfig.statementInspectorClass();
if ( sessionFactoryConfig.useCollectingStatementInspector() ) {
sessionFactoryBuilder.applyStatementInspector( new SQLStatementInspector() );
}
else if ( ! explicitInspectorClass.equals( StatementInspector.class ) ) {
sessionFactoryBuilder.applyStatementInspector( explicitInspectorClass.getConstructor().newInstance() );
}
sessionFactoryBuilder.applyCollectionsInDefaultFetchGroup( sessionFactoryConfig.applyCollectionsInDefaultFetchGroup() );
sessionFactoryConfig.sessionFactoryConfigurer().getDeclaredConstructor().newInstance()
.accept( sessionFactoryBuilder );
final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) sessionFactoryBuilder.build();
if ( sessionFactoryConfig.exportSchema() ) {
prepareSchemaExport( sessionFactory, model, sessionFactoryConfig.createSecondarySchemas() );
}
return sessionFactory;
}
catch (Exception e) {
throw new RuntimeException( "Could not build SessionFactory: " + e.getMessage(), e );
}
};
}
}
if ( producer == null ) {
throw new IllegalStateException( "Could not determine SessionFactory producer" );
}
final SessionFactoryScopeImpl sfScope = new SessionFactoryScopeImpl( domainModelScope, producer );
if ( testInstance instanceof SessionFactoryScopeAware ) {
( (SessionFactoryScopeAware) testInstance ).injectSessionFactoryScope( sfScope );
}
return sfScope;
}
private static void prepareSchemaExport(
SessionFactoryImplementor sessionFactory,
MetadataImplementor model,
boolean createSecondarySchemas) {
final Map<String, Object> baseProperties = sessionFactory.getProperties();
final Set<ActionGrouping> groupings = ActionGrouping.interpret( model, baseProperties );
// if there are explicit setting for auto schema tooling then skip the annotation
if ( ! groupings.isEmpty() ) {
// the properties contained explicit settings for auto schema tooling - skip the annotation
return;
}
final HashMap<String,Object> settings = new HashMap<>( baseProperties );
settings.put( AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, Action.CREATE_DROP );
if ( createSecondarySchemas ) {
if ( !( model.getDatabase().getDialect().canCreateSchema() ) ) {
throw new UnsupportedOperationException(
model.getDatabase().getDialect() + " does not support schema creation" );
}
settings.put( AvailableSettings.JAKARTA_HBM2DDL_CREATE_SCHEMAS, true );
}
final StandardServiceRegistry serviceRegistry = model.getMetadataBuildingOptions().getServiceRegistry();
SchemaManagementToolCoordinator.process(
model,
serviceRegistry,
settings,
(action) -> sessionFactory.addObserver(
new SessionFactoryObserver() {
@Override
public void sessionFactoryClosing(org.hibernate.SessionFactory factory) {
action.perform( serviceRegistry );
}
}
)
);
}
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
log.tracef( "#handleTestExecutionException(%s, %s)", context.getDisplayName(), throwable );
try {
final Object testInstance = context.getRequiredTestInstance();
final ExtensionContext.Store store = locateExtensionStore( testInstance, context );
final SessionFactoryScopeImpl scope = (SessionFactoryScopeImpl) store.get( SESSION_FACTORY_KEY );
scope.releaseSessionFactory();
}
catch (Exception ignore) {
}
throw throwable;
}
private static | SessionFactoryExtension |
java | alibaba__nacos | naming/src/main/java/com/alibaba/nacos/naming/misc/ClientConfig.java | {
"start": 883,
"end": 1932
} | class ____ extends AbstractDynamicConfig {
private static final String NAMING_CLIENT = "NamingClient";
private static final ClientConfig INSTANCE = new ClientConfig();
private long clientExpiredTime = ClientConstants.DEFAULT_CLIENT_EXPIRED_TIME;
private ClientConfig() {
super(NAMING_CLIENT);
resetConfig();
}
public static ClientConfig getInstance() {
return INSTANCE;
}
public long getClientExpiredTime() {
return clientExpiredTime;
}
public void setClientExpiredTime(long clientExpiredTime) {
this.clientExpiredTime = clientExpiredTime;
}
@Override
protected void getConfigFromEnv() {
clientExpiredTime = EnvUtil.getProperty(ClientConstants.CLIENT_EXPIRED_TIME_CONFIG_KEY, Long.class,
ClientConstants.DEFAULT_CLIENT_EXPIRED_TIME);
}
@Override
protected String printConfig() {
return "ClientConfig{" + "clientExpiredTime=" + clientExpiredTime + '}';
}
}
| ClientConfig |
java | apache__camel | components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/XRayTrace.java | {
"start": 1523,
"end": 1584
} | interface ____ {
String metricName() default "";
}
| XRayTrace |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java | {
"start": 9545,
"end": 9683
} | class ____ {
}
@Conditional(OnMissingBeanCondition.class)
@EnableSomeConfiguration("foo")
@Configuration
public static | ConfigurationOne |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/indices/IndexingMemoryController.java | {
"start": 1836,
"end": 13219
} | class ____ implements IndexingOperationListener, Closeable {
private static final Logger logger = LogManager.getLogger(IndexingMemoryController.class);
/** How much heap (% or bytes) we will share across all actively indexing shards on this node (default: 10%). */
public static final Setting<ByteSizeValue> INDEX_BUFFER_SIZE_SETTING = Setting.memorySizeSetting(
"indices.memory.index_buffer_size",
"10%",
Property.NodeScope
);
/** Only applies when <code>indices.memory.index_buffer_size</code> is a %,
* to set a floor on the actual size in bytes (default: 48 MB). */
public static final Setting<ByteSizeValue> MIN_INDEX_BUFFER_SIZE_SETTING = Setting.byteSizeSetting(
"indices.memory.min_index_buffer_size",
ByteSizeValue.of(48, ByteSizeUnit.MB),
ByteSizeValue.ZERO,
ByteSizeValue.ofBytes(Long.MAX_VALUE),
Property.NodeScope
);
/** Only applies when <code>indices.memory.index_buffer_size</code> is a %,
* to set a ceiling on the actual size in bytes (default: not set). */
public static final Setting<ByteSizeValue> MAX_INDEX_BUFFER_SIZE_SETTING = Setting.byteSizeSetting(
"indices.memory.max_index_buffer_size",
ByteSizeValue.MINUS_ONE,
ByteSizeValue.MINUS_ONE,
ByteSizeValue.ofBytes(Long.MAX_VALUE),
Property.NodeScope
);
/** If we see no indexing operations after this much time for a given shard,
* we consider that shard inactive (default: 5 minutes). */
public static final Setting<TimeValue> SHARD_INACTIVE_TIME_SETTING = Setting.positiveTimeSetting(
"indices.memory.shard_inactive_time",
TimeValue.timeValueMinutes(5),
Property.NodeScope
);
/** How frequently we check indexing memory usage (default: 5 seconds). */
public static final Setting<TimeValue> SHARD_MEMORY_INTERVAL_TIME_SETTING = Setting.positiveTimeSetting(
"indices.memory.interval",
TimeValue.timeValueSeconds(5),
Property.NodeScope
);
/* Currently, indexing is throttled due to memory pressure in stateful/stateless or disk pressure in stateless.
* This limits the number of indexing threads to 1 per shard. However, this might not be enough when the number of
* shards that need indexing is larger than the number of threads. So we might opt to pause indexing completely.
* The default value for this setting is false, but it can be set to true in stateless.
* Note that this should only be enabled in stateless. In stateful clusters, where we have
* indexing replicas, if pause throttling gets enabled on replicas, it will indirectly
* pause the primary as well which might prevent us from relocating the primary shard.
*/
public static final Setting<Boolean> PAUSE_INDEXING_ON_THROTTLE = Setting.boolSetting(
"indices.pause.on.throttle",
false,
Property.NodeScope
);
private final ThreadPool threadPool;
private final Iterable<IndexShard> indexShards;
private final long indexingBuffer;
private final TimeValue inactiveTime;
private final TimeValue interval;
/** Contains shards currently being throttled because we can't write segments quickly enough */
private final Set<IndexShard> throttled = new HashSet<>();
private final Cancellable scheduler;
private static final EnumSet<IndexShardState> CAN_WRITE_INDEX_BUFFER_STATES = EnumSet.of(
IndexShardState.RECOVERING,
IndexShardState.POST_RECOVERY,
IndexShardState.STARTED
);
private final ShardsIndicesStatusChecker statusChecker;
private final Set<IndexShard> pendingWriteIndexingBufferSet = ConcurrentCollections.newConcurrentSet();
private final Deque<IndexShard> pendingWriteIndexingBufferQueue = new ConcurrentLinkedDeque<>();
IndexingMemoryController(Settings settings, ThreadPool threadPool, Iterable<IndexShard> indexServices) {
this.indexShards = indexServices;
ByteSizeValue indexingBuffer = INDEX_BUFFER_SIZE_SETTING.get(settings);
String indexingBufferSetting = settings.get(INDEX_BUFFER_SIZE_SETTING.getKey());
// null means we used the default (10%)
if (indexingBufferSetting == null || indexingBufferSetting.endsWith("%")) {
// We only apply the min/max when % value was used for the index buffer:
ByteSizeValue minIndexingBuffer = MIN_INDEX_BUFFER_SIZE_SETTING.get(settings);
ByteSizeValue maxIndexingBuffer = MAX_INDEX_BUFFER_SIZE_SETTING.get(settings);
if (indexingBuffer.getBytes() < minIndexingBuffer.getBytes()) {
indexingBuffer = minIndexingBuffer;
}
if (maxIndexingBuffer.getBytes() != -1 && indexingBuffer.getBytes() > maxIndexingBuffer.getBytes()) {
indexingBuffer = maxIndexingBuffer;
}
}
this.indexingBuffer = indexingBuffer.getBytes();
this.inactiveTime = SHARD_INACTIVE_TIME_SETTING.get(settings);
// we need to have this relatively small to free up heap quickly enough
this.interval = SHARD_MEMORY_INTERVAL_TIME_SETTING.get(settings);
this.statusChecker = new ShardsIndicesStatusChecker();
logger.debug(
"using indexing buffer size [{}] with {} [{}], {} [{}]",
this.indexingBuffer,
SHARD_INACTIVE_TIME_SETTING.getKey(),
this.inactiveTime,
SHARD_MEMORY_INTERVAL_TIME_SETTING.getKey(),
this.interval
);
this.scheduler = scheduleTask(threadPool);
// Need to save this so we can later launch async "write indexing buffer to disk" on shards:
this.threadPool = threadPool;
}
protected Cancellable scheduleTask(ThreadPool threadPool) {
// it's fine to run it on the scheduler thread, no busy work
return threadPool.scheduleWithFixedDelay(statusChecker, interval, EsExecutors.DIRECT_EXECUTOR_SERVICE);
}
@Override
public void close() {
scheduler.cancel();
}
/**
* returns the current budget for the total amount of indexing buffers of
* active shards on this node
*/
long indexingBufferSize() {
return indexingBuffer;
}
protected List<IndexShard> availableShards() {
List<IndexShard> availableShards = new ArrayList<>();
for (IndexShard shard : indexShards) {
if (CAN_WRITE_INDEX_BUFFER_STATES.contains(shard.state())) {
availableShards.add(shard);
}
}
return availableShards;
}
/** returns how much heap this shard is using for its indexing buffer */
protected long getIndexBufferRAMBytesUsed(IndexShard shard) {
return shard.getIndexBufferRAMBytesUsed();
}
/** returns how many bytes this shard is currently writing to disk */
protected long getShardWritingBytes(IndexShard shard) {
return shard.getWritingBytes();
}
/** Record that the given shard needs to write its indexing buffer. */
protected void enqueueWriteIndexingBuffer(IndexShard shard) {
if (pendingWriteIndexingBufferSet.add(shard)) {
pendingWriteIndexingBufferQueue.addLast(shard);
}
// Else there is already a queued task for the same shard and there is no evidence that adding another one is required since we'd
// need the first one to start running to know about the number of bytes still not being written.
}
/**
* Write pending indexing buffers. This should run on indexing threads in order to naturally apply back pressure on indexing. Lucene has
* similar logic in DocumentsWriter#postUpdate.
*/
private boolean writePendingIndexingBuffers() {
boolean wrotePendingIndexingBuffer = false;
for (IndexShard shard = pendingWriteIndexingBufferQueue.pollFirst(); shard != null; shard = pendingWriteIndexingBufferQueue
.pollFirst()) {
// Remove the shard from the set first, so that multiple threads can run writeIndexingBuffer concurrently on the same shard.
pendingWriteIndexingBufferSet.remove(shard);
// Calculate the time taken to write the indexing buffers so it can be accounted for in the index write load
long startTime = System.nanoTime();
shard.writeIndexingBuffer();
long took = System.nanoTime() - startTime;
shard.addWriteIndexBuffersToIndexThreadsTime(took);
wrotePendingIndexingBuffer = true;
}
return wrotePendingIndexingBuffer;
}
private void writePendingIndexingBuffersAsync() {
for (IndexShard shard = pendingWriteIndexingBufferQueue.pollFirst(); shard != null; shard = pendingWriteIndexingBufferQueue
.pollFirst()) {
final IndexShard finalShard = shard;
threadPool.executor(ThreadPool.Names.REFRESH).execute(() -> {
// Remove the shard from the set first, so that multiple threads can run writeIndexingBuffer concurrently on the same shard.
pendingWriteIndexingBufferSet.remove(finalShard);
finalShard.writeIndexingBuffer();
});
}
}
/** force checker to run now */
void forceCheck() {
statusChecker.run();
}
/** Asks this shard to throttle indexing to one thread. If the PAUSE_INDEXING_ON_THROTTLE seeting is set to true,
* throttling will pause indexing completely for the throttled shard.
*/
protected void activateThrottling(IndexShard shard) {
shard.activateThrottling();
}
/** Asks this shard to stop throttling indexing to one thread */
protected void deactivateThrottling(IndexShard shard) {
shard.deactivateThrottling();
}
@Override
public void postIndex(ShardId shardId, Engine.Index index, Engine.IndexResult result) {
postOperation(index, result);
}
@Override
public void postDelete(ShardId shardId, Engine.Delete delete, Engine.DeleteResult result) {
postOperation(delete, result);
}
private void postOperation(Engine.Operation operation, Engine.Result result) {
recordOperationBytes(operation, result);
// Piggy back on indexing threads to write segments. We're not submitting a task to the index threadpool because we want memory to
// be reclaimed rapidly. This has the downside of increasing the latency of _bulk requests though. Lucene does the same thing in
// DocumentsWriter#postUpdate, flushing a segment because the size limit on the RAM buffer was reached happens on the call to
// IndexWriter#addDocument.
while (writePendingIndexingBuffers()) {
// If we just wrote segments, then run the checker again if not already running to check if we released enough memory.
if (statusChecker.tryRun() == false) {
break;
}
}
}
/** called by IndexShard to record estimated bytes written to translog for the operation */
private void recordOperationBytes(Engine.Operation operation, Engine.Result result) {
if (result.getResultType() == Engine.Result.Type.SUCCESS) {
statusChecker.bytesWritten(operation.estimatedSizeInBytes());
}
}
private static final | IndexingMemoryController |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SuperCallToObjectMethodTest.java | {
"start": 930,
"end": 1091
} | class ____ {
@Test
public void positive() {
helper()
.addSourceLines(
"Foo.java",
"""
| SuperCallToObjectMethodTest |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/invalid/ProducerMethodBeanInvokerTest.java | {
"start": 1533,
"end": 1654
} | class ____ {
@Produces
MyService produce() {
return new MyService();
}
}
}
| MyProducer |
java | jhy__jsoup | src/test/java/org/jsoup/nodes/AttributeTest.java | {
"start": 276,
"end": 4351
} | class ____ {
@Test
public void html() {
Attribute attr = new Attribute("key", "value &");
assertEquals("key=\"value &\"", attr.html());
assertEquals(attr.html(), attr.toString());
}
@Test
public void htmlWithLtAndGtInValue() {
Attribute attr = new Attribute("key", "<value>");
assertEquals("key=\"<value>\"", attr.html());
}
@Test public void testWithSupplementaryCharacterInAttributeKeyAndValue() {
String s = new String(Character.toChars(135361));
Attribute attr = new Attribute(s, "A" + s + "B");
assertEquals(s + "=\"A" + s + "B\"", attr.html());
assertEquals(attr.html(), attr.toString());
}
@Test public void validatesKeysNotEmpty() {
assertThrows(IllegalArgumentException.class, () -> new Attribute(" ", "Check"));
}
@Test public void validatesKeysNotEmptyViaSet() {
assertThrows(IllegalArgumentException.class, () -> {
Attribute attr = new Attribute("One", "Check");
attr.setKey(" ");
});
}
@Test public void booleanAttributesAreEmptyStringValues() {
Document doc = Jsoup.parse("<div hidden>");
Attributes attributes = doc.body().child(0).attributes();
assertEquals("", attributes.get("hidden"));
Attribute first = attributes.iterator().next();
assertEquals("hidden", first.getKey());
assertEquals("", first.getValue());
assertFalse(first.hasDeclaredValue());
assertTrue(Attribute.isBooleanAttribute(first.getKey()));
}
@Test public void settersOnOrphanAttribute() {
Attribute attr = new Attribute("one", "two");
attr.setKey("three");
String oldVal = attr.setValue("four");
assertEquals("two", oldVal);
assertEquals("three", attr.getKey());
assertEquals("four", attr.getValue());
assertNull(attr.parent);
}
@Test void settersAfterParentRemoval() {
// tests key and value set on a retained attribute after disconnected from parent
Attributes attrs = new Attributes();
attrs.put("foo", "bar");
Attribute attr = attrs.attribute("foo");
assertNotNull(attr);
attrs.remove("foo");
assertEquals("foo", attr.getKey());
assertEquals("bar", attr.getValue());
attr.setKey("new");
attr.setValue("newer");
assertEquals("new", attr.getKey());
assertEquals("newer", attr.getValue());
}
@Test public void hasValue() {
Attribute a1 = new Attribute("one", "");
Attribute a2 = new Attribute("two", null);
Attribute a3 = new Attribute("thr", "thr");
assertTrue(a1.hasDeclaredValue());
assertFalse(a2.hasDeclaredValue());
assertTrue(a3.hasDeclaredValue());
}
@Test public void canSetValueToNull() {
Attribute attr = new Attribute("one", "val");
String oldVal = attr.setValue(null);
assertEquals("one", attr.html());
assertEquals("val", oldVal);
oldVal = attr.setValue("foo");
assertEquals("", oldVal); // string, not null
}
@Test void booleanAttributesAreNotCaseSensitive() {
// https://github.com/jhy/jsoup/issues/1656
assertTrue(Attribute.isBooleanAttribute("required"));
assertTrue(Attribute.isBooleanAttribute("REQUIRED"));
assertTrue(Attribute.isBooleanAttribute("rEQUIREd"));
assertFalse(Attribute.isBooleanAttribute("random string"));
String html = "<a href=autofocus REQUIRED>One</a>";
Document doc = Jsoup.parse(html);
assertEquals("<a href=\"autofocus\" required>One</a>", doc.selectFirst("a").outerHtml());
Document doc2 = Jsoup.parse(html, Parser.htmlParser().settings(ParseSettings.preserveCase));
assertEquals("<a href=\"autofocus\" REQUIRED>One</a>", doc2.selectFirst("a").outerHtml());
}
@Test void orphanNamespace() {
Attribute attr = new Attribute("one", "two");
assertEquals("", attr.namespace());
}
}
| AttributeTest |
java | apache__flink | flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarDeleteHeaders.java | {
"start": 1264,
"end": 2523
} | class ____
implements RuntimeMessageHeaders<
EmptyRequestBody, EmptyResponseBody, JarDeleteMessageParameters> {
private static final JarDeleteHeaders INSTANCE = new JarDeleteHeaders();
@Override
public Class<EmptyResponseBody> getResponseClass() {
return EmptyResponseBody.class;
}
@Override
public HttpResponseStatus getResponseStatusCode() {
return HttpResponseStatus.OK;
}
@Override
public Class<EmptyRequestBody> getRequestClass() {
return EmptyRequestBody.class;
}
@Override
public JarDeleteMessageParameters getUnresolvedMessageParameters() {
return new JarDeleteMessageParameters();
}
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.DELETE;
}
@Override
public String getTargetRestEndpointURL() {
return "/jars/:" + JarIdPathParameter.KEY;
}
public static JarDeleteHeaders getInstance() {
return INSTANCE;
}
@Override
public String operationId() {
return "deleteJar";
}
@Override
public String getDescription() {
return "Deletes a jar previously uploaded via '" + JarUploadHeaders.URL + "'.";
}
}
| JarDeleteHeaders |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdTest.java | {
"start": 6357,
"end": 6636
} | class ____ {
public long rawDate;
public AsValueThingy(long l) { rawDate = l; }
public AsValueThingy() { }
@JsonValue public Date serialization() {
return new Date(rawDate);
}
}
// [databind#222]
static | AsValueThingy |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/RedirectTests.java | {
"start": 2147,
"end": 4087
} | class ____ {
private MockMvc mockMvc;
@BeforeEach
public void setup() {
this.mockMvc = standaloneSetup(new PersonController()).build();
}
@Test
public void save() throws Exception {
this.mockMvc.perform(post("/persons").param("name", "Andy"))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/persons/Joe"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("name"))
.andExpect(flash().attributeCount(1))
.andExpect(flash().attribute("message", "success!"));
}
@Test
public void saveSpecial() throws Exception {
this.mockMvc.perform(post("/people").param("name", "Andy"))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/persons/Joe"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("name"))
.andExpect(flash().attributeCount(1))
.andExpect(flash().attribute("message", "success!"));
}
@Test
public void saveWithErrors() throws Exception {
this.mockMvc.perform(post("/persons"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("persons/add"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(flash().attributeCount(0));
}
@Test
public void saveSpecialWithErrors() throws Exception {
this.mockMvc.perform(post("/people"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("persons/add"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(flash().attributeCount(0));
}
@Test
public void getPerson() throws Exception {
this.mockMvc.perform(get("/persons/Joe").flashAttr("message", "success!"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("persons/index"))
.andExpect(model().size(2))
.andExpect(model().attribute("person", new Person("Joe")))
.andExpect(model().attribute("message", "success!"))
.andExpect(flash().attributeCount(0));
}
@Controller
private static | RedirectTests |
java | apache__camel | components/camel-platform-http-vertx/src/main/java/org/apache/camel/component/platform/http/vertx/VertxPlatformHttpSupport.java | {
"start": 2097,
"end": 2193
} | class ____ the platform-http-vertx component.
*
* Please note that many of the methods in this | for |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerInterceptEmptyFileTest.java | {
"start": 1102,
"end": 2388
} | class ____ extends ContextTestSupport {
@Test
public void testExcludeZeroLengthFiles() throws Exception {
MockEndpoint mock1 = getMockEndpoint("mock:result");
mock1.expectedBodiesReceivedInAnyOrder("Hello World", "Bye World");
MockEndpoint mock2 = getMockEndpoint("mock:skip");
mock2.expectedMessageCount(2);
sendFiles();
assertMockEndpointsSatisfied();
}
private void sendFiles() {
template.sendBodyAndHeader(fileUri(), "Hello World", Exchange.FILE_NAME, "hello.xml");
template.sendBodyAndHeader(fileUri(), "", Exchange.FILE_NAME, "empty1.txt");
template.sendBodyAndHeader(fileUri(), "Bye World", Exchange.FILE_NAME, "secret.txt");
template.sendBodyAndHeader(fileUri(), "", Exchange.FILE_NAME, "empty2.txt");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
interceptFrom().onWhen(simple("${file:length} == 0")).to("mock:skip").stop();
from(fileUri("?initialDelay=10&delay=10"))
.convertBodyTo(String.class).to("log:test")
.to("mock:result");
}
};
}
}
| FileConsumerInterceptEmptyFileTest |
java | apache__camel | components/camel-jackson/src/main/java/org/apache/camel/component/jackson/AbstractJacksonDataFormat.java | {
"start": 4526,
"end": 5459
} | class ____ specify properties to be included during marshalling. See also
* https://github.com/FasterXML/jackson-annotations/blob/master/src/main/java/com/fasterxml/jackson/annotation/JsonView.java
*/
protected AbstractJacksonDataFormat(Class<?> unmarshalType, Class<?> jsonView) {
this.unmarshalType = unmarshalType;
this.jsonView = jsonView;
}
/**
* Use a custom Jackson mapper and and unmarshal type
*
* @param mapper the custom mapper
* @param unmarshalType the custom unmarshal type
*/
protected AbstractJacksonDataFormat(ObjectMapper mapper, Class<?> unmarshalType) {
this(mapper, unmarshalType, null);
}
/**
* Use a custom Jackson mapper, unmarshal type and JSON view
*
* @param mapper the custom mapper
* @param unmarshalType the custom unmarshal type
* @param jsonView marker | to |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/ContainerUpdateRequest.java | {
"start": 1492,
"end": 2781
} | class ____ {
@Public
@Unstable
public static ContainerUpdateRequest newInstance(
List<Token> containersToIncrease) {
ContainerUpdateRequest request =
Records.newRecord(ContainerUpdateRequest.class);
request.setContainersToUpdate(containersToIncrease);
return request;
}
/**
* Get a list of container tokens to be used for authorization during
* container resource update.
* <p>
* Note: {@link NMToken} will be used for authenticating communication with
* {@code NodeManager}.
* @return the list of container tokens to be used for authorization during
* container resource update.
* @see NMToken
*/
@Public
@Unstable
public abstract List<Token> getContainersToUpdate();
/**
* Set container tokens to be used during container resource increase.
* The token is acquired from
* <code>AllocateResponse.getUpdatedContainers</code>.
* The token contains the container id and resource capability required for
* container resource update.
* @param containersToUpdate the list of container tokens to be used
* for container resource increase.
*/
@Public
@Unstable
public abstract void setContainersToUpdate(
List<Token> containersToUpdate);
}
| ContainerUpdateRequest |
java | elastic__elasticsearch | x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/execution/sequence/CircuitBreakerTests.java | {
"start": 17059,
"end": 17387
} | class ____ used by {@code CircuitBreakerTests#testMemoryClearedOnSuccessfulRequest()} and
* {@code CircuitBreakerTests#testMemoryClearedOnShardsException()} methods to test the circuit breaker memory usage
* in case of a successful sequence request but also for a failed sequence request.
*/
private abstract | is |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/NumberFieldTest.java | {
"start": 276,
"end": 5833
} | class ____ extends TestCase {
public void test_codec() throws Exception {
V0 v = new V0();
v.setValue(1001L);
String text = JSON.toJSONString(v);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(v1.getValue().intValue(), v.getValue().intValue());
}
public void test_codec_no_asm() throws Exception {
V0 v = new V0();
v.setValue(1001L);
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":1001}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(Integer.valueOf(1001), v1.getValue());
}
public void test_codec_null() throws Exception {
V0 v = new V0();
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":null}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(v1.getValue(), v.getValue());
}
public void test_codec_2_no_asm() throws Exception {
V0 v = new V0();
v.setValue(Long.MAX_VALUE);
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":" + Long.MAX_VALUE + "}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(new Long(Long.MAX_VALUE), v1.getValue());
}
public void test_codec_2_asm() throws Exception {
V0 v = new V0();
v.setValue(Long.MAX_VALUE);
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(true);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":" + Long.MAX_VALUE + "}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(new Long(Long.MAX_VALUE), v1.getValue());
}
public void test_codec_3_no_asm() throws Exception {
V0 v = new V0();
v.setValue(new BigDecimal("3.2"));
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":3.2}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(new BigDecimal("3.2"), v1.getValue());
}
public void test_codec_3_asm() throws Exception {
V0 v = new V0();
v.setValue(new BigDecimal("3.2"));
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(true);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":3.2}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(new BigDecimal("3.2"), v1.getValue());
}
public void test_codec_min_no_asm() throws Exception {
V0 v = new V0();
v.setValue(Long.MIN_VALUE);
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":" + Long.MIN_VALUE + "}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(new Long(Long.MIN_VALUE), v1.getValue());
}
public void test_codec_min_asm() throws Exception {
V0 v = new V0();
v.setValue(Long.MIN_VALUE);
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(true);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue);
Assert.assertEquals("{\"value\":" + Long.MIN_VALUE + "}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(new Long(Long.MIN_VALUE), v1.getValue());
}
public void test_codec_null_1() throws Exception {
V0 v = new V0();
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero);
Assert.assertEquals("{\"value\":0}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(Integer.valueOf(0), v1.getValue());
}
public void test_codec_null_1_asm() throws Exception {
V0 v = new V0();
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(true);
String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero);
Assert.assertEquals("{\"value\":0}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(Integer.valueOf(0), v1.getValue());
}
public void test_codec_cast() throws Exception {
V0 v1 = JSON.parseObject("{\"value\":\"12.3\"}", V0.class);
Assert.assertEquals(new BigDecimal("12.3"), v1.getValue());
}
public static | NumberFieldTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.