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/index/shard/SparseVectorStats.java | {
"start": 891,
"end": 2297
} | class ____ implements Writeable, ToXContentFragment {
private long valueCount = 0;
public SparseVectorStats() {}
public SparseVectorStats(long count) {
this.valueCount = count;
}
public SparseVectorStats(StreamInput in) throws IOException {
this.valueCount = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(valueCount);
}
public void add(SparseVectorStats other) {
if (other == null) {
return;
}
this.valueCount += other.valueCount;
}
/**
* Returns the total number of dense vectors added in the index.
*/
public long getValueCount() {
return valueCount;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.NAME);
builder.field(Fields.VALUE_COUNT, valueCount);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SparseVectorStats that = (SparseVectorStats) o;
return valueCount == that.valueCount;
}
@Override
public int hashCode() {
return Objects.hash(valueCount);
}
static final | SparseVectorStats |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/multipart/FormDataParser.java | {
"start": 340,
"end": 1420
} | interface ____ extends Closeable {
/**
* Parse the form data asynchronously. If all the data cannot be read immediately then a read listener will be
* registered, and the data will be parsed by the read thread.
* <p>
* The method can either invoke the next handler directly, or may delegate to the IO thread
* to perform the parsing.
*/
void parse() throws Exception;
/**
* Parse the data, blocking the current thread until parsing is complete.
*
* @return The parsed form data
* @throws IOException If the data could not be read
*/
FormData parseBlocking() throws Exception;
/**
* Closes the parser, and removes and temporary files that may have been created.
*
* @throws IOException
*/
void close() throws IOException;
/**
* Sets the character encoding that will be used by this parser. If the request is already processed this will have
* no effect
*
* @param encoding The encoding
*/
void setCharacterEncoding(String encoding);
}
| FormDataParser |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderJavaType.java | {
"start": 402,
"end": 1183
} | class ____ extends AbstractClassJavaType<Gender> {
public static final GenderJavaType INSTANCE =
new GenderJavaType();
protected GenderJavaType() {
super(Gender.class);
}
public String toString(Gender value) {
return value == null ? null : value.name();
}
public Gender fromString(CharSequence string) {
return string == null ? null : Gender.valueOf(string.toString());
}
public <X> X unwrap(Gender value, Class<X> type, WrapperOptions options) {
return CharacterJavaType.INSTANCE.unwrap(
value == null ? null : value.getCode(),
type,
options
);
}
public <X> Gender wrap(X value, WrapperOptions options) {
return Gender.fromCode(
CharacterJavaType.INSTANCE.wrap( value, options)
);
}
}
//end::basic-enums-custom-type-example[]
| GenderJavaType |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ResourceHandlerFunction.java | {
"start": 1335,
"end": 2733
} | class ____ implements HandlerFunction<ServerResponse> {
private static final Set<HttpMethod> SUPPORTED_METHODS =
Set.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS);
private final Resource resource;
private final BiConsumer<Resource, HttpHeaders> headersConsumer;
public ResourceHandlerFunction(Resource resource, BiConsumer<Resource, HttpHeaders> headersConsumer) {
this.resource = resource;
this.headersConsumer = headersConsumer;
}
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
HttpMethod method = request.method();
if (HttpMethod.GET.equals(method)) {
return EntityResponse.fromObject(this.resource)
.headers(headers -> this.headersConsumer.accept(this.resource, headers))
.build()
.map(response -> response);
}
else if (HttpMethod.HEAD.equals(method)) {
Resource headResource = new HeadMethodResource(this.resource);
return EntityResponse.fromObject(headResource)
.headers(headers -> this.headersConsumer.accept(this.resource, headers))
.build()
.map(response -> response);
}
else if (HttpMethod.OPTIONS.equals(method)) {
return ServerResponse.ok()
.allow(SUPPORTED_METHODS)
.body(BodyInserters.empty());
}
return ServerResponse.status(HttpStatus.METHOD_NOT_ALLOWED)
.allow(SUPPORTED_METHODS)
.body(BodyInserters.empty());
}
private static | ResourceHandlerFunction |
java | apache__flink | flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/sstmerge/RocksDBManualCompactionManager.java | {
"start": 1368,
"end": 1606
} | class ____ compactions of one or more Column Families of a single RocksDB instance.
*
* <p>Note that "manual" means that the compactions are <b>requested</b> manually (by Flink), but
* they are still executed by RocksDB.
*/
public | manages |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/jdk/NumberSerTest.java | {
"start": 2720,
"end": 2977
} | class ____ {
private final BigDecimal value;
public BigDecimalHolder(String num) {
value = new BigDecimal(num);
}
public BigDecimal getValue() {
return value;
}
}
static | BigDecimalHolder |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/aop/lifecycle/LifeCycleAdviseSpec.java | {
"start": 254,
"end": 969
} | class ____ {
@Test
void testLifeCycleAdvise() {
try (ApplicationContext applicationContext = ApplicationContext.run()) {
// tag::test[]
final ProductService productService = applicationContext.getBean(ProductService.class);
Product product = applicationContext.createBean(Product.class, "Apple"); // <1>
assertTrue(product.isActive());
assertTrue(productService.findProduct("APPLE").isPresent());
applicationContext.destroyBean(product); // <2>
assertFalse(product.isActive());
assertFalse(productService.findProduct("APPLE").isPresent());
// end::test[]
}
}
}
| LifeCycleAdviseSpec |
java | elastic__elasticsearch | x-pack/plugin/logsdb/src/javaRestTest/java/org/elasticsearch/xpack/logsdb/qa/BulkDynamicMappingChallengeRestIT.java | {
"start": 357,
"end": 866
} | class ____ extends BulkChallengeRestIT {
public BulkDynamicMappingChallengeRestIT() {
super(new DataGenerationHelper(builder -> builder.withFullyDynamicMapping(true)));
}
@Override
public void contenderSettings(Settings.Builder builder) {
super.contenderSettings(builder);
// ignore_dynamic_beyond_limit is set in the template so it's always true
builder.put("index.mapping.total_fields.limit", randomIntBetween(1, 5000));
}
}
| BulkDynamicMappingChallengeRestIT |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/webapp/ContainerBlock.java | {
"start": 1923,
"end": 6491
} | class ____ extends HtmlBlock {
private static final Logger LOG =
LoggerFactory.getLogger(ContainerBlock.class);
protected ApplicationBaseProtocol appBaseProt;
@Inject
public ContainerBlock(ApplicationBaseProtocol appBaseProt, ViewContext ctx) {
super(ctx);
this.appBaseProt = appBaseProt;
}
@Override
protected void render(Block html) {
String containerid = $(CONTAINER_ID);
if (containerid.isEmpty()) {
puts("Bad request: requires container ID");
return;
}
ContainerId containerId = null;
try {
containerId = ContainerId.fromString(containerid);
} catch (IllegalArgumentException e) {
puts("Invalid container ID: " + containerid);
return;
}
UserGroupInformation callerUGI = getCallerUGI();
ContainerReport containerReport = null;
try {
final GetContainerReportRequest request =
GetContainerReportRequest.newInstance(containerId);
if (callerUGI == null) {
containerReport = getContainerReport(request);
} else {
containerReport = callerUGI.doAs(
new PrivilegedExceptionAction<ContainerReport> () {
@Override
public ContainerReport run() throws Exception {
return getContainerReport(request);
}
});
}
} catch (Exception e) {
String message = "Failed to read the container " + containerid + ".";
LOG.error(message, e);
html.p().__(message).__();
return;
}
if (containerReport == null) {
puts("Container not found: " + containerid);
return;
}
ContainerInfo container = new ContainerInfo(containerReport);
setTitle(join("Container ", containerid));
info("Container Overview")
.__(
"Container State:",
container.getContainerState() == null ? UNAVAILABLE : container
.getContainerState())
.__("Exit Status:", container.getContainerExitStatus())
.__(
"Node:",
container.getNodeHttpAddress() == null ? "#" : container
.getNodeHttpAddress(),
container.getNodeHttpAddress() == null ? "N/A" : container
.getNodeHttpAddress())
.__("Priority:", container.getPriority())
.__("Started:", Times.format(container.getStartedTime()))
.__(
"Elapsed:",
StringUtils.formatTime(Times.elapsed(container.getStartedTime(),
container.getFinishedTime())))
.__(
"Resource:", getResources(container))
.__("Logs:", container.getLogUrl() == null ? "#" : container.getLogUrl(),
container.getLogUrl() == null ? "N/A" : "Logs")
.__("Diagnostics:", container.getDiagnosticsInfo() == null ?
"" : container.getDiagnosticsInfo());
html.__(InfoBlock.class);
}
/**
* Creates a string representation of allocated resources to a container.
* Memory, followed with VCores are always the first two resources of
* the resulted string, followed with any custom resources, if any is present.
*/
@VisibleForTesting
String getResources(ContainerInfo container) {
Map<String, Long> allocatedResources = container.getAllocatedResources();
StringBuilder sb = new StringBuilder();
sb.append(getResourceAsString(ResourceInformation.MEMORY_URI,
allocatedResources.get(ResourceInformation.MEMORY_URI))).append(", ");
sb.append(getResourceAsString(ResourceInformation.VCORES_URI,
allocatedResources.get(ResourceInformation.VCORES_URI)));
if (container.hasCustomResources()) {
container.getAllocatedResources().forEach((key, value) -> {
if (!key.equals(ResourceInformation.MEMORY_URI) &&
!key.equals(ResourceInformation.VCORES_URI)) {
sb.append(", ");
sb.append(getResourceAsString(key, value));
}
});
}
return sb.toString();
}
private String getResourceAsString(String resourceName, long value) {
final String translatedResourceName;
switch (resourceName) {
case ResourceInformation.MEMORY_URI:
translatedResourceName = "Memory";
break;
case ResourceInformation.VCORES_URI:
translatedResourceName = "VCores";
break;
default:
translatedResourceName = resourceName;
break;
}
return String.valueOf(value) + " " + translatedResourceName;
}
protected ContainerReport getContainerReport(
final GetContainerReportRequest request)
throws YarnException, IOException {
return appBaseProt.getContainerReport(request).getContainerReport();
}
} | ContainerBlock |
java | apache__camel | components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromPropertyTest.java | {
"start": 1141,
"end": 2797
} | class ____ extends JqTestSupport {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
var jq = expression().jq().expression(".foo").source("property:Content").end();
from("direct:start")
.doTry()
.transform(jq)
.to("mock:result")
.doCatch(NoSuchPropertyException.class)
.to("mock:fail");
}
};
}
@Test
public void testExpressionFromProperty() throws Exception {
getMockEndpoint("mock:result")
.expectedBodiesReceived(new TextNode("bar"));
getMockEndpoint("mock:fail")
.expectedMessageCount(0);
ObjectNode node = MAPPER.createObjectNode();
node.put("foo", "bar");
fluentTemplate.to("direct:start")
.withProcessor(e -> e.setProperty("Content", node))
.send();
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testExpressionFromPropertyFail() throws Exception {
getMockEndpoint("mock:result")
.expectedMessageCount(0);
getMockEndpoint("mock:fail")
.expectedMessageCount(1);
ObjectNode node = MAPPER.createObjectNode();
node.put("foo", "bar");
fluentTemplate.to("direct:start")
.withProcessor(e -> e.getMessage().setBody(node))
.send();
MockEndpoint.assertIsSatisfied(context);
}
}
| JqExpressionFromPropertyTest |
java | quarkusio__quarkus | extensions/reactive-routes/runtime/src/main/java/io/quarkus/vertx/web/Route.java | {
"start": 5530,
"end": 6133
} | enum ____ {
/**
* A non-blocking request handler.
*
* @see io.vertx.ext.web.Route#handler(Handler)
*/
NORMAL,
/**
* A blocking request handler.
*
* @see io.vertx.ext.web.Route#blockingHandler(Handler)
*/
BLOCKING,
/**
* A failure handler can declare a single method parameter whose type extends {@link Throwable}. The type of the
* parameter is used to match the result of {@link RoutingContext#failure()}.
*
* <pre>
* <code>
* | HandlerType |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_306/Issue306Mapper.java | {
"start": 338,
"end": 732
} | class ____ {
public static final Issue306Mapper INSTANCE = Mappers.getMapper( Issue306Mapper.class );
public abstract Source targetToSource(Target target);
protected void dummy1( Set<String> arg ) {
throw new RuntimeException();
}
protected Set<Long> dummy2( Object object, @TargetType Class<?> clazz ) {
throw new RuntimeException();
}
}
| Issue306Mapper |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/apikey/InvalidateApiKeyResponse.java | {
"start": 1598,
"end": 6089
} | class ____ extends ActionResponse implements ToXContentObject, Writeable {
private final List<String> invalidatedApiKeys;
private final List<String> previouslyInvalidatedApiKeys;
private final List<ElasticsearchException> errors;
public InvalidateApiKeyResponse(StreamInput in) throws IOException {
this.invalidatedApiKeys = in.readCollectionAsList(StreamInput::readString);
this.previouslyInvalidatedApiKeys = in.readCollectionAsList(StreamInput::readString);
this.errors = in.readCollectionAsList(StreamInput::readException);
}
/**
* Constructor for API keys invalidation response
* @param invalidatedApiKeys list of invalidated API key ids
* @param previouslyInvalidatedApiKeys list of previously invalidated API key ids
* @param errors list of encountered errors while invalidating API keys
*/
public InvalidateApiKeyResponse(
List<String> invalidatedApiKeys,
List<String> previouslyInvalidatedApiKeys,
@Nullable List<ElasticsearchException> errors
) {
this.invalidatedApiKeys = Objects.requireNonNull(invalidatedApiKeys, "invalidated_api_keys must be provided");
this.previouslyInvalidatedApiKeys = Objects.requireNonNull(
previouslyInvalidatedApiKeys,
"previously_invalidated_api_keys must be provided"
);
if (null != errors) {
this.errors = errors;
} else {
this.errors = Collections.emptyList();
}
}
public static InvalidateApiKeyResponse emptyResponse() {
return new InvalidateApiKeyResponse(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
}
public List<String> getInvalidatedApiKeys() {
return invalidatedApiKeys;
}
public List<String> getPreviouslyInvalidatedApiKeys() {
return previouslyInvalidatedApiKeys;
}
public List<ElasticsearchException> getErrors() {
return errors;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject()
.array("invalidated_api_keys", invalidatedApiKeys.toArray(Strings.EMPTY_ARRAY))
.array("previously_invalidated_api_keys", previouslyInvalidatedApiKeys.toArray(Strings.EMPTY_ARRAY))
.field("error_count", errors.size());
if (errors.isEmpty() == false) {
builder.field("error_details");
builder.startArray();
for (ElasticsearchException e : errors) {
builder.startObject();
ElasticsearchException.generateThrowableXContent(builder, params, e);
builder.endObject();
}
builder.endArray();
}
return builder.endObject();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeStringCollection(invalidatedApiKeys);
out.writeStringCollection(previouslyInvalidatedApiKeys);
out.writeCollection(errors, StreamOutput::writeException);
}
@SuppressWarnings("unchecked")
static final ConstructingObjectParser<InvalidateApiKeyResponse, Void> PARSER = new ConstructingObjectParser<>(
"invalidate_api_key_response",
args -> {
return new InvalidateApiKeyResponse((List<String>) args[0], (List<String>) args[1], (List<ElasticsearchException>) args[3]);
}
);
static {
PARSER.declareStringArray(constructorArg(), new ParseField("invalidated_api_keys"));
PARSER.declareStringArray(constructorArg(), new ParseField("previously_invalidated_api_keys"));
// we parse error_count but ignore it while constructing response
PARSER.declareInt(constructorArg(), new ParseField("error_count"));
PARSER.declareObjectArray(
optionalConstructorArg(),
(p, c) -> ElasticsearchException.fromXContent(p),
new ParseField("error_details")
);
}
public static InvalidateApiKeyResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
@Override
public String toString() {
return "InvalidateApiKeyResponse [invalidatedApiKeys="
+ invalidatedApiKeys
+ ", previouslyInvalidatedApiKeys="
+ previouslyInvalidatedApiKeys
+ ", errors="
+ errors
+ "]";
}
}
| InvalidateApiKeyResponse |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest73.java | {
"start": 893,
"end": 1704
} | class ____ extends TestCase {
public void test_false() throws Exception {
WallProvider provider = new MySqlWallProvider();
provider.getConfig().setCommentAllow(true);
assertTrue(provider.checkValid(//
"DELETE FROM D1 USING PCHS_DETAIL D1 " +
" INNER JOIN (" +
" SELECT D.DETAIL_UID " +
" FROM PCHS_DETAIL D " +
" INNER JOIN PCHS_BILL B ON D.BILL_UID=B.BILL_UID " +
" WHERE B.COM_UID='0892E8A38EF83AB6B9E25C25D8085486' " +
" LIMIT 1000 " +
" ) D2 ON D1.DETAIL_UID=D2.DETAIL_UID"));
assertEquals(3, provider.getTableStats().size());
}
}
| MySqlWallTest73 |
java | netty__netty | codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliDecoder.java | {
"start": 1114,
"end": 1178
} | class ____ extends ByteToMessageDecoder {
private | BrotliDecoder |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/descriptors/DescriptorProperties.java | {
"start": 2848,
"end": 3614
} | class ____ having a unified string-based representation of Table API related classes such
* as TableSchema, TypeInformation, etc.
*
* <p>Note to implementers: Please try to reuse key names as much as possible. Key-names should be
* hierarchical and lower case. Use "-" instead of dots or camel case. E.g.,
* connector.schema.start-from = from-earliest. Try not to use the higher level in a key-name. E.g.,
* instead of connector.kafka.kafka-version use connector.kafka.version.
*
* <p>Properties with key normalization enabled contain only lower-case keys.
*
* @deprecated This utility will be dropped soon. {@link DynamicTableFactory} is based on {@link
* ConfigOption} and catalogs use {@link CatalogPropertiesUtil}.
*/
@Deprecated
@Internal
public | for |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/expressions/converter/converters/ThrowExceptionConverter.java | {
"start": 1572,
"end": 2230
} | class ____ extends CustomizedConverter {
@Override
public RexNode convert(CallExpression call, CallExpressionConvertRule.ConvertContext context) {
checkArgumentNumber(call, 2);
DataType type = ((TypeLiteralExpression) call.getChildren().get(1)).getOutputDataType();
SqlThrowExceptionFunction function =
new SqlThrowExceptionFunction(
context.getTypeFactory()
.createFieldTypeFromLogicalType(fromDataTypeToLogicalType(type)));
return context.getRelBuilder().call(function, context.toRexNode(call.getChildren().get(0)));
}
}
| ThrowExceptionConverter |
java | apache__flink | flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/ShowViewsOperation.java | {
"start": 1442,
"end": 3613
} | class ____ extends AbstractShowOperation {
private final @Nullable String databaseName;
public ShowViewsOperation(
@Nullable String catalogName,
@Nullable String databaseName,
@Nullable String preposition,
@Nullable ShowLikeOperator likeOp) {
super(catalogName, preposition, likeOp);
this.databaseName = databaseName;
}
public ShowViewsOperation(
@Nullable String catalogName,
@Nullable String databaseName,
@Nullable ShowLikeOperator likeOp) {
this(catalogName, databaseName, null, likeOp);
}
public ShowViewsOperation(@Nullable String catalogName, @Nullable String databaseName) {
this(catalogName, databaseName, null);
}
@Override
protected String getOperationName() {
return "SHOW VIEWS";
}
protected Set<String> retrieveDataForTableResult(Context ctx) {
final CatalogManager catalogManager = ctx.getCatalogManager();
final String qualifiedCatalogName = catalogManager.qualifyCatalog(catalogName);
final String qualifiedDatabaseName = catalogManager.qualifyDatabase(databaseName);
if (preposition == null) {
return catalogManager.listViews();
} else {
Catalog catalog = catalogManager.getCatalogOrThrowException(qualifiedCatalogName);
if (catalog.databaseExists(qualifiedDatabaseName)) {
return catalogManager.listViews(qualifiedCatalogName, qualifiedDatabaseName);
} else {
throw new ValidationException(
String.format(
"Database '%s'.'%s' doesn't exist.",
qualifiedCatalogName, qualifiedDatabaseName));
}
}
}
@Override
protected String getColumnName() {
return "view name";
}
@Override
public String getPrepositionSummaryString() {
if (databaseName == null) {
return super.getPrepositionSummaryString();
}
return super.getPrepositionSummaryString() + "." + databaseName;
}
}
| ShowViewsOperation |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/resourceplugin/deviceframework/TestDeviceMappingManager.java | {
"start": 3754,
"end": 12828
} | class ____ {
protected static final Logger LOG =
LoggerFactory.getLogger(TestDeviceMappingManager.class);
private String tempResourceTypesFile;
private DeviceMappingManager dmm;
private ExecutorService containerLauncher;
private Configuration conf;
private CGroupsHandler mockCGroupsHandler;
private PrivilegedOperationExecutor mockPrivilegedExecutor;
private Context mockCtx;
@BeforeEach
public void setup() throws Exception {
// setup resource-types.xml
conf = new YarnConfiguration();
ResourceUtils.resetResourceTypes();
String resourceTypesFile = "resource-types-pluggable-devices.xml";
this.tempResourceTypesFile =
TestResourceUtils.setupResourceTypes(this.conf, resourceTypesFile);
NodeManager.NMContext context = mock(NodeManager.NMContext.class);
NMStateStoreService storeService = mock(NMStateStoreService.class);
when(context.getNMStateStore()).thenReturn(storeService);
doNothing().when(storeService).storeAssignedResources(isA(Container.class),
isA(String.class),
isA(ArrayList.class));
dmm = new DeviceMappingManager(context);
int deviceCount = 100;
TreeSet<Device> r = new TreeSet<>();
for (int i = 0; i < deviceCount; i++) {
r.add(Device.Builder.newInstance()
.setId(i)
.setDevPath("/dev/hdwA" + i)
.setMajorNumber(243)
.setMinorNumber(i)
.setBusID("0000:65:00." + i)
.setHealthy(true)
.build());
}
TreeSet<Device> r1 = new TreeSet<>();
for (int i = 0; i < deviceCount; i++) {
r1.add(Device.Builder.newInstance()
.setId(i)
.setDevPath("/dev/cmp" + i)
.setMajorNumber(100)
.setMinorNumber(i)
.setBusID("0000:11:00." + i)
.setHealthy(true)
.build());
}
dmm.addDeviceSet("cmpA.com/hdwA", r);
dmm.addDeviceSet("cmp.com/cmp", r1);
containerLauncher =
Executors.newFixedThreadPool(10);
mockCGroupsHandler = mock(CGroupsHandler.class);
mockPrivilegedExecutor = mock(PrivilegedOperationExecutor.class);
mockCtx = mock(NodeManager.NMContext.class);
when(mockCtx.getConf()).thenReturn(conf);
}
@AfterEach
public void tearDown() throws IOException {
// cleanup resource-types.xml
File dest = new File(this.tempResourceTypesFile);
if (dest.exists()) {
boolean flag = dest.delete();
}
}
/**
* Simulate launch different containers requesting different resource.
* */
@Test
public void testAllocation()
throws InterruptedException, ResourceHandlerException {
int totalContainerCount = 10;
String resourceName1 = "cmpA.com/hdwA";
String resourceName2 = "cmp.com/cmp";
DeviceMappingManager dmmSpy = spy(dmm);
// generate a list of container
Map<String, Map<Container, Integer>> containerSet = new HashMap<>();
containerSet.put(resourceName1, new HashMap<>());
containerSet.put(resourceName2, new HashMap<>());
Long startTime = System.currentTimeMillis();
for (int i = 0; i < totalContainerCount; i++) {
// Random requeted device
int num = new Random().nextInt(5) + 1;
// Random requested resource type
String resourceName;
int seed = new Random().nextInt(5);
if (seed % 2 == 0) {
resourceName = resourceName1;
} else {
resourceName = resourceName2;
}
Container c = mockContainerWithDeviceRequest(i,
resourceName,
num, false);
containerSet.get(resourceName).put(c, num);
DevicePlugin myPlugin = new MyTestPlugin();
DevicePluginAdapter dpa = new DevicePluginAdapter(resourceName,
myPlugin, dmm);
DeviceResourceHandlerImpl dri = new DeviceResourceHandlerImpl(
resourceName, dpa,
dmmSpy, mockCGroupsHandler, mockPrivilegedExecutor, mockCtx);
Future<Integer> f = containerLauncher.submit(new MyContainerLaunch(
dri, c, i, false));
}
containerLauncher.shutdown();
while (!containerLauncher.awaitTermination(10, TimeUnit.SECONDS)) {
LOG.info("Wait for the threads to finish");
}
Long endTime = System.currentTimeMillis();
LOG.info("Each container preStart spends roughly: {} ms",
(endTime - startTime)/totalContainerCount);
// Ensure invocation times
verify(dmmSpy, times(totalContainerCount)).assignDevices(
anyString(), any(Container.class));
// Ensure used devices' count for each type is correct
int totalAllocatedCount = 0;
Map<Device, ContainerId> used1 =
dmm.getAllUsedDevices().get(resourceName1);
Map<Device, ContainerId> used2 =
dmm.getAllUsedDevices().get(resourceName2);
for (Map.Entry<Container, Integer> entry :
containerSet.get(resourceName1).entrySet()) {
totalAllocatedCount += entry.getValue();
}
for (Map.Entry<Container, Integer> entry :
containerSet.get(resourceName2).entrySet()) {
totalAllocatedCount += entry.getValue();
}
assertEquals(totalAllocatedCount, used1.size() + used2.size());
// Ensure each container has correct devices
for (Map.Entry<Container, Integer> entry :
containerSet.get(resourceName1).entrySet()) {
int containerWanted = entry.getValue();
int actualAllocated = dmm.getAllocatedDevices(resourceName1,
entry.getKey().getContainerId()).size();
assertEquals(containerWanted, actualAllocated);
}
for (Map.Entry<Container, Integer> entry :
containerSet.get(resourceName2).entrySet()) {
int containerWanted = entry.getValue();
int actualAllocated = dmm.getAllocatedDevices(resourceName2,
entry.getKey().getContainerId()).size();
assertEquals(containerWanted, actualAllocated);
}
}
/**
* Simulate launch containers and cleanup.
* */
@Test
public void testAllocationAndCleanup()
throws InterruptedException, ResourceHandlerException, IOException {
int totalContainerCount = 10;
String resourceName1 = "cmpA.com/hdwA";
String resourceName2 = "cmp.com/cmp";
DeviceMappingManager dmmSpy = spy(dmm);
// generate a list of container
Map<String, Map<Container, Integer>> containerSet = new HashMap<>();
containerSet.put(resourceName1, new HashMap<>());
containerSet.put(resourceName2, new HashMap<>());
for (int i = 0; i < totalContainerCount; i++) {
// Random requeted device
int num = new Random().nextInt(5) + 1;
// Random requested resource type
String resourceName;
int seed = new Random().nextInt(5);
if (seed % 2 == 0) {
resourceName = resourceName1;
} else {
resourceName = resourceName2;
}
Container c = mockContainerWithDeviceRequest(i,
resourceName,
num, false);
containerSet.get(resourceName).put(c, num);
DevicePlugin myPlugin = new MyTestPlugin();
DevicePluginAdapter dpa = new DevicePluginAdapter(resourceName,
myPlugin, dmm);
DeviceResourceHandlerImpl dri = new DeviceResourceHandlerImpl(
resourceName, dpa,
dmmSpy, mockCGroupsHandler, mockPrivilegedExecutor, mockCtx);
Future<Integer> f = containerLauncher.submit(new MyContainerLaunch(
dri, c, i, true));
}
containerLauncher.shutdown();
while (!containerLauncher.awaitTermination(10, TimeUnit.SECONDS)) {
LOG.info("Wait for the threads to finish");
}
// Ensure invocation times
verify(dmmSpy, times(totalContainerCount)).assignDevices(
anyString(), any(Container.class));
verify(dmmSpy, times(totalContainerCount)).cleanupAssignedDevices(
anyString(), any(ContainerId.class));
// Ensure all devices are back
assertEquals(0,
dmm.getAllUsedDevices().get(resourceName1).size());
assertEquals(0,
dmm.getAllUsedDevices().get(resourceName2).size());
}
private static Container mockContainerWithDeviceRequest(int id,
String resourceName,
int numDeviceRequest,
boolean dockerContainerEnabled) {
Container c = mock(Container.class);
when(c.getContainerId()).thenReturn(getContainerId(id));
Resource res = Resource.newInstance(1024, 1);
ResourceMappings resMapping = new ResourceMappings();
res.setResourceValue(resourceName, numDeviceRequest);
when(c.getResource()).thenReturn(res);
when(c.getResourceMappings()).thenReturn(resMapping);
ContainerLaunchContext clc = mock(ContainerLaunchContext.class);
Map<String, String> env = new HashMap<>();
if (dockerContainerEnabled) {
env.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE,
ContainerRuntimeConstants.CONTAINER_RUNTIME_DOCKER);
}
when(clc.getEnvironment()).thenReturn(env);
when(c.getLaunchContext()).thenReturn(clc);
return c;
}
private static ContainerId getContainerId(int id) {
return ContainerId.newContainerId(ApplicationAttemptId
.newInstance(ApplicationId.newInstance(1234L, 1), 1), id);
}
private static | TestDeviceMappingManager |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/jdbc/GeneratedDatabaseNamesTests.java | {
"start": 3563,
"end": 3704
} | class ____ extends AbstractTestCase {
@Configuration
@ImportResource(DATASOURCE_CONFIG_WITH_AUTO_GENERATED_DB_NAME_XML)
static | TestClass2A |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/RemoteExceptionData.java | {
"start": 1472,
"end": 1988
} | class ____ {
private String exception;
private String message;
private String javaClassName;
public RemoteExceptionData() {
}
public RemoteExceptionData(String excep, String message, String className) {
this.exception = excep;
this.message = message;
this.javaClassName = className;
}
public String getException() {
return exception;
}
public String getMessage() {
return message;
}
public String getJavaClassName() {
return javaClassName;
}
}
| RemoteExceptionData |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/JavaLogQuery.java | {
"start": 2835,
"end": 4697
} | class ____ implements Serializable {
private final int count;
private final int numBytes;
public Stats(int count, int numBytes) {
this.count = count;
this.numBytes = numBytes;
}
public Stats merge(Stats other) {
return new Stats(count + other.count, numBytes + other.numBytes);
}
@Override
public String toString() {
return String.format("bytes=%s\tn=%s", numBytes, count);
}
}
public static Tuple3<String, String, String> extractKey(String line) {
Matcher m = apacheLogRegex.matcher(line);
if (m.find()) {
String ip = m.group(1);
String user = m.group(3);
String query = m.group(5);
if (!user.equalsIgnoreCase("-")) {
return new Tuple3<>(ip, user, query);
}
}
return new Tuple3<>(null, null, null);
}
public static Stats extractStats(String line) {
Matcher m = apacheLogRegex.matcher(line);
if (m.find()) {
int bytes = Integer.parseInt(m.group(7));
return new Stats(1, bytes);
} else {
return new Stats(1, 0);
}
}
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("JavaLogQuery")
.getOrCreate();
JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());
JavaRDD<String> dataSet = (args.length == 1) ? jsc.textFile(args[0]) : jsc.parallelize(exampleApacheLogs);
JavaPairRDD<Tuple3<String, String, String>, Stats> extracted =
dataSet.mapToPair(s -> new Tuple2<>(extractKey(s), extractStats(s)));
JavaPairRDD<Tuple3<String, String, String>, Stats> counts = extracted.reduceByKey(Stats::merge);
List<Tuple2<Tuple3<String, String, String>, Stats>> output = counts.collect();
for (Tuple2<?,?> t : output) {
System.out.println(t._1() + "\t" + t._2());
}
spark.stop();
}
}
| Stats |
java | netty__netty | buffer/src/main/java/io/netty/buffer/SizeClasses.java | {
"start": 1138,
"end": 1760
} | class ____.
* log2Group: Log of group base size (no deltas added).
* log2Delta: Log of delta to previous size class.
* nDelta: Delta multiplier.
* isMultiPageSize: 'yes' if a multiple of the page size, 'no' otherwise.
* isSubPage: 'yes' if a subpage size class, 'no' otherwise.
* log2DeltaLookup: Same as log2Delta if a lookup table size class, 'no'
* otherwise.
* <p>
* nSubpages: Number of subpages size classes.
* nSizes: Number of size classes.
* nPSizes: Number of size classes that are multiples of pageSize.
*
* smallMaxSizeIdx: Maximum small size | index |
java | apache__camel | dsl/camel-endpointdsl/src/test/java/org/apache/camel/builder/endpoint/PahoTest.java | {
"start": 1249,
"end": 2322
} | class ____ extends BaseEndpointDslTest {
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testPaho() throws Exception {
context.start();
context.addRoutes(new EndpointRouteBuilder() {
@Override
public void configure() throws Exception {
PahoEndpointBuilderFactory.PahoEndpointBuilder builder
= paho("mytopic").brokerUrl("mybroker:1234").userName("myUser").password("myPassword");
Endpoint endpoint = builder.resolve(context);
assertNotNull(endpoint);
PahoEndpoint pe = assertIsInstanceOf(PahoEndpoint.class, endpoint);
assertEquals("mybroker:1234", pe.getConfiguration().getBrokerUrl());
assertEquals("myUser", pe.getConfiguration().getUserName());
assertEquals("myPassword", pe.getConfiguration().getPassword());
assertEquals("mytopic", pe.getTopic());
}
});
context.stop();
}
}
| PahoTest |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/util/HtmlCharacterEntityDecoder.java | {
"start": 854,
"end": 5025
} | class ____ {
private static final int MAX_REFERENCE_SIZE = 10;
private final HtmlCharacterEntityReferences characterEntityReferences;
private final String originalMessage;
private final StringBuilder decodedMessage;
private int currentPosition = 0;
private int nextPotentialReferencePosition = -1;
private int nextSemicolonPosition = -2;
public HtmlCharacterEntityDecoder(HtmlCharacterEntityReferences characterEntityReferences, String original) {
this.characterEntityReferences = characterEntityReferences;
this.originalMessage = original;
this.decodedMessage = new StringBuilder(original.length());
}
public String decode() {
while (this.currentPosition < this.originalMessage.length()) {
findNextPotentialReference(this.currentPosition);
copyCharactersTillPotentialReference();
processPossibleReference();
}
return this.decodedMessage.toString();
}
private void findNextPotentialReference(int startPosition) {
this.nextPotentialReferencePosition = Math.max(startPosition, this.nextSemicolonPosition - MAX_REFERENCE_SIZE);
do {
this.nextPotentialReferencePosition =
this.originalMessage.indexOf('&', this.nextPotentialReferencePosition);
if (this.nextSemicolonPosition != -1 &&
this.nextSemicolonPosition < this.nextPotentialReferencePosition) {
this.nextSemicolonPosition = this.originalMessage.indexOf(';', this.nextPotentialReferencePosition + 1);
}
if (this.nextPotentialReferencePosition == -1) {
break;
}
if (this.nextSemicolonPosition == -1) {
this.nextPotentialReferencePosition = -1;
break;
}
if (this.nextSemicolonPosition - this.nextPotentialReferencePosition < MAX_REFERENCE_SIZE) {
break;
}
this.nextPotentialReferencePosition = this.nextPotentialReferencePosition + 1;
}
while (this.nextPotentialReferencePosition != -1);
}
private void copyCharactersTillPotentialReference() {
if (this.nextPotentialReferencePosition != this.currentPosition) {
int skipUntilIndex = (this.nextPotentialReferencePosition != -1 ?
this.nextPotentialReferencePosition : this.originalMessage.length());
if (skipUntilIndex - this.currentPosition > 3) {
this.decodedMessage.append(this.originalMessage, this.currentPosition, skipUntilIndex);
this.currentPosition = skipUntilIndex;
}
else {
while (this.currentPosition < skipUntilIndex) {
this.decodedMessage.append(this.originalMessage.charAt(this.currentPosition++));
}
}
}
}
private void processPossibleReference() {
if (this.nextPotentialReferencePosition != -1) {
boolean isNumberedReference = (this.originalMessage.charAt(this.currentPosition + 1) == '#');
boolean wasProcessable = isNumberedReference ? processNumberedReference() : processNamedReference();
if (wasProcessable) {
this.currentPosition = this.nextSemicolonPosition + 1;
}
else {
char currentChar = this.originalMessage.charAt(this.currentPosition);
this.decodedMessage.append(currentChar);
this.currentPosition++;
}
}
}
private boolean processNumberedReference() {
char referenceChar = this.originalMessage.charAt(this.nextPotentialReferencePosition + 2);
boolean isHexNumberedReference = (referenceChar == 'x' || referenceChar == 'X');
try {
int value = (!isHexNumberedReference ?
Integer.parseInt(getReferenceSubstring(2)) :
Integer.parseInt(getReferenceSubstring(3), 16));
if (value > Character.MAX_CODE_POINT) {
return false;
}
this.decodedMessage.appendCodePoint(value);
return true;
}
catch (NumberFormatException ex) {
return false;
}
}
private boolean processNamedReference() {
String referenceName = getReferenceSubstring(1);
char mappedCharacter = this.characterEntityReferences.convertToCharacter(referenceName);
if (mappedCharacter != HtmlCharacterEntityReferences.CHAR_NULL) {
this.decodedMessage.append(mappedCharacter);
return true;
}
return false;
}
private String getReferenceSubstring(int referenceOffset) {
return this.originalMessage.substring(
this.nextPotentialReferencePosition + referenceOffset, this.nextSemicolonPosition);
}
}
| HtmlCharacterEntityDecoder |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-nfs/src/main/java/org/apache/hadoop/hdfs/nfs/nfs3/DFSClientCache.java | {
"start": 6715,
"end": 12123
} | class ____ implements Runnable {
@Override
public synchronized void run() {
try {
closeAll(true);
} catch (IOException e) {
LOG.info("DFSClientCache.closeAll() threw an exception", e);
}
}
}
@VisibleForTesting
public LoadingCache<DfsClientKey, DFSClient> getClientCache() {
return clientCache;
}
/**
* Close all DFSClient instances in the Cache.
* @param onlyAutomatic only close those that are marked for automatic closing
*/
synchronized void closeAll(boolean onlyAutomatic) throws IOException {
List<IOException> exceptions = new ArrayList<IOException>();
ConcurrentMap<DfsClientKey, DFSClient> map = clientCache.asMap();
for (Entry<DfsClientKey, DFSClient> item : map.entrySet()) {
final DFSClient client = item.getValue();
if (client != null) {
try {
client.close();
} catch (IOException ioe) {
exceptions.add(ioe);
}
}
}
if (!exceptions.isEmpty()) {
throw MultipleIOException.createIOException(exceptions);
}
}
private CacheLoader<DfsClientKey, DFSClient> clientLoader() {
return new CacheLoader<DfsClientKey, DFSClient>() {
@Override
public DFSClient load(final DfsClientKey key) throws Exception {
UserGroupInformation ugi = getUserGroupInformation(
key.userName, UserGroupInformation.getCurrentUser());
// Guava requires CacheLoader never returns null.
return ugi.doAs(new PrivilegedExceptionAction<DFSClient>() {
@Override
public DFSClient run() throws IOException {
URI namenodeURI = namenodeUriMap.get(key.namenodeId);
if (namenodeURI == null) {
throw new IOException("No namenode URI found for user:" +
key.userName + " namenodeId:" + key.namenodeId);
}
return new DFSClient(namenodeURI, config);
}
});
}
};
}
/**
* This method uses the currentUser, and real user to create a proxy.
* @param effectiveUser The user who is being proxied by the real user
* @param realUser The actual user who does the command
* @return Proxy UserGroupInformation
* @throws IOException If proxying fails
*/
UserGroupInformation getUserGroupInformation(
String effectiveUser,
UserGroupInformation realUser)
throws IOException {
Preconditions.checkNotNull(effectiveUser);
Preconditions.checkNotNull(realUser);
realUser.checkTGTAndReloginFromKeytab();
UserGroupInformation ugi =
UserGroupInformation.createProxyUser(effectiveUser, realUser);
LOG.debug("Created ugi: {} for username: {}", ugi, effectiveUser);
return ugi;
}
private RemovalListener<DfsClientKey, DFSClient> clientRemovalListener() {
return new RemovalListener<DfsClientKey, DFSClient>() {
@Override
public void onRemoval(
RemovalNotification<DfsClientKey, DFSClient> notification) {
DFSClient client = notification.getValue();
try {
client.close();
} catch (IOException e) {
LOG.warn(String.format(
"IOException when closing the DFSClient(%s), cause: %s", client,
e));
}
}
};
}
private RemovalListener
<DFSInputStreamCacheKey, FSDataInputStream> inputStreamRemovalListener() {
return new RemovalListener
<DFSClientCache.DFSInputStreamCacheKey, FSDataInputStream>() {
@Override
public void onRemoval(
RemovalNotification<DFSInputStreamCacheKey, FSDataInputStream>
notification) {
try {
notification.getValue().close();
} catch (IOException ignored) {
}
}
};
}
private CacheLoader<DFSInputStreamCacheKey, FSDataInputStream>
inputStreamLoader() {
return new CacheLoader<DFSInputStreamCacheKey, FSDataInputStream>() {
@Override
public FSDataInputStream
load(DFSInputStreamCacheKey key) throws Exception {
DFSClient client = getDfsClient(key.userId, key.namenodeId);
DFSInputStream dis = client.open(key.inodePath);
return client.createWrappedInputStream(dis);
}
};
}
DFSClient getDfsClient(String userName, int namenodeId) {
DFSClient client = null;
try {
client = clientCache.get(new DfsClientKey(userName, namenodeId));
} catch (ExecutionException e) {
LOG.error("Failed to create DFSClient for user: {}", userName, e);
}
return client;
}
FSDataInputStream getDfsInputStream(String userName, String inodePath,
int namenodeId) {
DFSInputStreamCacheKey k =
new DFSInputStreamCacheKey(userName, inodePath, namenodeId);
FSDataInputStream s = null;
try {
s = inputstreamCache.get(k);
} catch (ExecutionException e) {
LOG.warn("Failed to create DFSInputStream for user: {}", userName, e);
}
return s;
}
public void invalidateDfsInputStream(String userName, String inodePath,
int namenodeId) {
DFSInputStreamCacheKey k =
new DFSInputStreamCacheKey(userName, inodePath, namenodeId);
inputstreamCache.invalidate(k);
}
}
| CacheFinalizer |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MinaComponentBuilderFactory.java | {
"start": 1386,
"end": 1840
} | interface ____ {
/**
* Mina (camel-mina)
* Socket level networking using TCP or UDP with Apache Mina 2.x.
*
* Category: networking
* Since: 2.10
* Maven coordinates: org.apache.camel:camel-mina
*
* @return the dsl builder
*/
static MinaComponentBuilder mina() {
return new MinaComponentBuilderImpl();
}
/**
* Builder for the Mina component.
*/
| MinaComponentBuilderFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClashTest.java | {
"start": 3943,
"end": 4173
} | class ____ {
Super(Function<String, String> r) {}
}
""")
.addSourceLines(
"Test.java",
"""
import java.util.function.Consumer;
public | Super |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/validation/ChatCompletionModelValidatorTests.java | {
"start": 1173,
"end": 3918
} | class ____ extends ESTestCase {
private static final TimeValue TIMEOUT = TimeValue.ONE_MINUTE;
@Mock
private ServiceIntegrationValidator mockServiceIntegrationValidator;
@Mock
private InferenceService mockInferenceService;
@Mock
private InferenceServiceResults mockInferenceServiceResults;
@Mock
private Model mockModel;
@Mock
private ActionListener<Model> mockActionListener;
private ChatCompletionModelValidator underTest;
@Before
public void setup() {
openMocks(this);
underTest = new ChatCompletionModelValidator(mockServiceIntegrationValidator);
}
public void testValidate_ServiceIntegrationValidatorThrowsException() {
doThrow(ElasticsearchStatusException.class).when(mockServiceIntegrationValidator)
.validate(eq(mockInferenceService), eq(mockModel), eq(TIMEOUT), any());
assertThrows(
ElasticsearchStatusException.class,
() -> { underTest.validate(mockInferenceService, mockModel, TIMEOUT, mockActionListener); }
);
verify(mockServiceIntegrationValidator).validate(eq(mockInferenceService), eq(mockModel), eq(TIMEOUT), any());
verify(mockActionListener).delegateFailureAndWrap(any());
verifyNoMoreInteractions(
mockServiceIntegrationValidator,
mockInferenceService,
mockInferenceServiceResults,
mockModel,
mockActionListener
);
}
public void testValidate_ChatCompletionDetailsUpdated() {
when(mockActionListener.delegateFailureAndWrap(any())).thenCallRealMethod();
when(mockInferenceService.updateModelWithChatCompletionDetails(mockModel)).thenReturn(mockModel);
doAnswer(ans -> {
ActionListener<InferenceServiceResults> responseListener = ans.getArgument(3);
responseListener.onResponse(mockInferenceServiceResults);
return null;
}).when(mockServiceIntegrationValidator).validate(eq(mockInferenceService), eq(mockModel), eq(TIMEOUT), any());
underTest.validate(mockInferenceService, mockModel, TIMEOUT, mockActionListener);
verify(mockServiceIntegrationValidator).validate(eq(mockInferenceService), eq(mockModel), eq(TIMEOUT), any());
verify(mockActionListener).delegateFailureAndWrap(any());
verify(mockActionListener).onResponse(mockModel);
verify(mockInferenceService).updateModelWithChatCompletionDetails(mockModel);
verifyNoMoreInteractions(
mockServiceIntegrationValidator,
mockInferenceService,
mockInferenceServiceResults,
mockModel,
mockActionListener
);
}
}
| ChatCompletionModelValidatorTests |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/intarray/IntArrayAssert_containsSubsequence_Test.java | {
"start": 971,
"end": 1334
} | class ____ extends IntArrayAssertBaseTest {
@Override
protected IntArrayAssert invoke_api_method() {
return assertions.containsSubsequence(6, 8);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertContainsSubsequence(getInfo(assertions), getActual(assertions), arrayOf(6, 8));
}
}
| IntArrayAssert_containsSubsequence_Test |
java | apache__camel | test-infra/camel-test-infra-azure-storage-datalake/src/main/java/org/apache/camel/test/infra/azure/storage/datalake/services/AzureStorageDataLakeRemoteInfraService.java | {
"start": 1092,
"end": 2240
} | class ____ implements AzureInfraService {
@Override
public AzureCredentialsHolder azureCredentials() {
return new AzureCredentialsHolder() {
@Override
public String accountName() {
return System.getProperty(AzureConfigs.ACCOUNT_NAME);
}
@Override
public String accountKey() {
return System.getProperty(AzureConfigs.ACCOUNT_KEY);
}
};
}
@Override
public void registerProperties() {
}
@Override
public void initialize() {
registerProperties();
}
@Override
public void shutdown() {
}
@Override
public String host() {
return System.getProperty(AzureConfigs.HOST);
}
@Override
public int port() {
return Integer.valueOf(System.getProperty(AzureConfigs.PORT));
}
@Override
public String accountName() {
return System.getProperty(AzureConfigs.ACCOUNT_NAME);
}
@Override
public String accessKey() {
return System.getProperty(AzureConfigs.ACCOUNT_KEY);
}
}
| AzureStorageDataLakeRemoteInfraService |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/builder/ToStringStyleTest.java | {
"start": 1442,
"end": 4007
} | class ____ extends ToStringStyle {
private static final long serialVersionUID = 1L;
}
@Test
void testSetArrayEnd() {
final ToStringStyle style = new ToStringStyleImpl();
style.setArrayEnd(null);
assertEquals("", style.getArrayEnd());
}
@Test
void testSetArraySeparator() {
final ToStringStyle style = new ToStringStyleImpl();
style.setArraySeparator(null);
assertEquals("", style.getArraySeparator());
}
@Test
void testSetArrayStart() {
final ToStringStyle style = new ToStringStyleImpl();
style.setArrayStart(null);
assertEquals("", style.getArrayStart());
}
@Test
void testSetContentEnd() {
final ToStringStyle style = new ToStringStyleImpl();
style.setContentEnd(null);
assertEquals("", style.getContentEnd());
}
@Test
void testSetContentStart() {
final ToStringStyle style = new ToStringStyleImpl();
style.setContentStart(null);
assertEquals("", style.getContentStart());
}
@Test
void testSetFieldNameValueSeparator() {
final ToStringStyle style = new ToStringStyleImpl();
style.setFieldNameValueSeparator(null);
assertEquals("", style.getFieldNameValueSeparator());
}
@Test
void testSetFieldSeparator() {
final ToStringStyle style = new ToStringStyleImpl();
style.setFieldSeparator(null);
assertEquals("", style.getFieldSeparator());
}
@Test
void testSetNullText() {
final ToStringStyle style = new ToStringStyleImpl();
style.setNullText(null);
assertEquals("", style.getNullText());
}
@Test
void testSetSizeEndText() {
final ToStringStyle style = new ToStringStyleImpl();
style.setSizeEndText(null);
assertEquals("", style.getSizeEndText());
}
@Test
void testSetSizeStartText() {
final ToStringStyle style = new ToStringStyleImpl();
style.setSizeStartText(null);
assertEquals("", style.getSizeStartText());
}
@Test
void testSetSummaryObjectEndText() {
final ToStringStyle style = new ToStringStyleImpl();
style.setSummaryObjectEndText(null);
assertEquals("", style.getSummaryObjectEndText());
}
@Test
void testSetSummaryObjectStartText() {
final ToStringStyle style = new ToStringStyleImpl();
style.setSummaryObjectStartText(null);
assertEquals("", style.getSummaryObjectStartText());
}
}
| ToStringStyleImpl |
java | elastic__elasticsearch | x-pack/plugin/logstash/src/main/java/org/elasticsearch/xpack/logstash/action/PutPipelineResponse.java | {
"start": 568,
"end": 1424
} | class ____ extends ActionResponse {
private final RestStatus status;
public PutPipelineResponse(RestStatus status) {
this.status = Objects.requireNonNull(status);
}
public PutPipelineResponse(StreamInput in) throws IOException {
this.status = in.readEnum(RestStatus.class);
}
public RestStatus status() {
return status;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeEnum(status);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PutPipelineResponse that = (PutPipelineResponse) o;
return status == that.status;
}
@Override
public int hashCode() {
return Objects.hash(status);
}
}
| PutPipelineResponse |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/apikey/RestGrantApiKeyActionTests.java | {
"start": 642,
"end": 3323
} | class ____ extends ESTestCase {
public void testParseXContentForGrantApiKeyRequest() throws Exception {
final String grantType = randomAlphaOfLength(8);
final String username = randomAlphaOfLength(8);
final String password = randomAlphaOfLength(8);
final String accessToken = randomAlphaOfLength(8);
final String clientAuthenticationScheme = randomAlphaOfLength(8);
final String clientAuthenticationValue = randomAlphaOfLength(8);
final String apiKeyName = randomAlphaOfLength(8);
final var apiKeyExpiration = randomTimeValue();
final String runAs = randomAlphaOfLength(8);
try (
XContentParser content = createParser(
XContentFactory.jsonBuilder()
.startObject()
.field("grant_type", grantType)
.field("username", username)
.field("password", password)
.field("access_token", accessToken)
.startObject("client_authentication")
.field("scheme", clientAuthenticationScheme)
.field("value", clientAuthenticationValue)
.endObject()
.startObject("api_key")
.field("name", apiKeyName)
.field("expiration", apiKeyExpiration.getStringRep())
.endObject()
.field("run_as", runAs)
.endObject()
)
) {
GrantApiKeyRequest grantApiKeyRequest = RestGrantApiKeyAction.RequestTranslator.Default.fromXContent(content);
assertThat(grantApiKeyRequest.getGrant().getType(), is(grantType));
assertThat(grantApiKeyRequest.getGrant().getUsername(), is(username));
assertThat(grantApiKeyRequest.getGrant().getPassword(), is(new SecureString(password.toCharArray())));
assertThat(grantApiKeyRequest.getGrant().getAccessToken(), is(new SecureString(accessToken.toCharArray())));
assertThat(grantApiKeyRequest.getGrant().getClientAuthentication().scheme(), is(clientAuthenticationScheme));
assertThat(
grantApiKeyRequest.getGrant().getClientAuthentication().value(),
is(new SecureString(clientAuthenticationValue.toCharArray()))
);
assertThat(grantApiKeyRequest.getGrant().getRunAsUsername(), is(runAs));
assertThat(grantApiKeyRequest.getApiKeyRequest().getName(), is(apiKeyName));
assertThat(grantApiKeyRequest.getApiKeyRequest().getExpiration(), is(apiKeyExpiration));
}
}
}
| RestGrantApiKeyActionTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_909/Issue909Test.java | {
"start": 696,
"end": 1068
} | class ____ {
@ProcessorTest
public void properlyCreatesMapperWithValuesAsParameterName() {
ValuesHolder valuesHolder = new ValuesHolder();
valuesHolder.setValues( "values" );
ValuesHolderDto dto = Mappers.getMapper( ValuesMapper.class ).convert( valuesHolder );
assertThat( dto.getValues() ).isEqualTo( "values" );
}
}
| Issue909Test |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/RedisCommandBuilderUnitTests.java | {
"start": 801,
"end": 31718
} | class ____ {
public static final String MY_KEY = "hKey";
public static final String MY_FIELD1 = "hField1";
public static final String MY_FIELD2 = "hField2";
public static final String MY_FIELD3 = "hField3";
public static final String STREAM_KEY = "test-stream";
public static final String GROUP_NAME = "test-group";
public static final String MESSAGE_ID1 = "1234567890-0";
public static final String MESSAGE_ID2 = "1234567891-0";
public static final String MESSAGE_ID3 = "1234567892-0";
RedisCommandBuilder<String, String> sut = new RedisCommandBuilder<>(StringCodec.UTF8);
@Test()
void shouldCorrectlyConstructHello() {
Command<String, String, ?> command = sut.hello(3, "日本語", "日本語".toCharArray(), null);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*5\r\n" + "$5\r\n" + "HELLO\r\n" + "$1\r\n" + "3\r\n"
+ "$4\r\n" + "AUTH\r\n" + "$9\r\n" + "日本語\r\n" + "$9\r\n" + "日本語\r\n");
}
@Test
void shouldCorrectlyConstructXreadgroup() {
Command<String, String, ?> command = sut.xreadgroup(Consumer.from("a", "b"), new XReadArgs(),
XReadArgs.StreamOffset.latest("stream"));
assertThat(Unpooled.wrappedBuffer(command.getArgs().getFirstEncodedKey()).toString(StandardCharsets.UTF_8))
.isEqualTo("stream");
}
@Test
void shouldCorrectlyConstructHexpire() {
Command<String, String, ?> command = sut.hexpire(MY_KEY, 1, ExpireArgs.Builder.nx(), MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*9\r\n" + "$7\r\n" + "HEXPIRE\r\n" + "$4\r\n" + "hKey\r\n"
+ "$1\r\n" + "1\r\n" + "$2\r\n" + "NX\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "3\r\n" + "$7\r\n"
+ "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHexpireat() {
Command<String, String, ?> command = sut.hexpireat(MY_KEY, 1, ExpireArgs.Builder.nx(), MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*9\r\n" + "$9\r\n" + "HEXPIREAT\r\n" + "$4\r\n" + "hKey\r\n"
+ "$1\r\n" + "1\r\n" + "$2\r\n" + "NX\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "3\r\n" + "$7\r\n"
+ "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHexpiretime() {
Command<String, String, ?> command = sut.hexpiretime(MY_KEY, MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$11\r\n" + "HEXPIRETIME\r\n" + "$4\r\n" + "hKey\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n"
+ "3\r\n" + "$7\r\n" + "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHpersist() {
Command<String, String, ?> command = sut.hpersist(MY_KEY, MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$8\r\n" + "HPERSIST\r\n" + "$4\r\n" + "hKey\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n"
+ "3\r\n" + "$7\r\n" + "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHpexpire() {
Command<String, String, ?> command = sut.hpexpire(MY_KEY, 1, ExpireArgs.Builder.nx(), MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*9\r\n" + "$8\r\n" + "HPEXPIRE\r\n" + "$4\r\n" + "hKey\r\n"
+ "$1\r\n" + "1\r\n" + "$2\r\n" + "NX\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "3\r\n" + "$7\r\n"
+ "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHpexpireat() {
Command<String, String, ?> command = sut.hpexpireat(MY_KEY, 1, ExpireArgs.Builder.nx(), MY_FIELD1, MY_FIELD2,
MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*9\r\n" + "$10\r\n" + "HPEXPIREAT\r\n" + "$4\r\n"
+ "hKey\r\n" + "$1\r\n" + "1\r\n" + "$2\r\n" + "NX\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "3\r\n"
+ "$7\r\n" + "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHpexpiretime() {
Command<String, String, ?> command = sut.hpexpiretime(MY_KEY, MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$12\r\n" + "HPEXPIRETIME\r\n" + "$4\r\n" + "hKey\r\n" + "$6\r\n" + "FIELDS\r\n"
+ "$1\r\n" + "3\r\n" + "$7\r\n" + "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHttl() {
Command<String, String, ?> command = sut.httl(MY_KEY, MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$4\r\n" + "HTTL\r\n" + "$4\r\n" + "hKey\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n"
+ "3\r\n" + "$7\r\n" + "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHpttl() {
Command<String, String, ?> command = sut.hpttl(MY_KEY, MY_FIELD1, MY_FIELD2, MY_FIELD3);
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$5\r\n" + "HPTTL\r\n" + "$4\r\n" + "hKey\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n"
+ "3\r\n" + "$7\r\n" + "hField1\r\n" + "$7\r\n" + "hField2\r\n" + "$7\r\n" + "hField3\r\n");
}
@Test
void shouldCorrectlyConstructHgetdel() {
Command<String, String, ?> command = sut.hgetdel(MY_KEY, "one", "two");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*6\r\n" + "$7\r\n" + "HGETDEL\r\n" + "$4\r\n" + "hKey\r\n"
+ "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "2\r\n" + "$3\r\n" + "one\r\n" + "$3\r\n" + "two\r\n");
}
@Test
void shouldCorrectlyConstructHsetex() {
Command<String, String, ?> command = sut.hsetex(MY_KEY, Collections.singletonMap("one", "1"));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*6\r\n" + "$6\r\n" + "HSETEX\r\n" + "$4\r\n" + "hKey\r\n"
+ "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "1\r\n" + "$3\r\n" + "one\r\n" + "$1\r\n" + "1\r\n");
}
@Test
void shouldCorrectlyConstructHsetexWithArgs() {
Command<String, String, ?> command = sut.hsetex(MY_KEY, HSetExArgs.Builder.ex(Duration.ofSeconds(10)).fnx(),
Collections.singletonMap("one", "1"));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
String expected = "*9\r\n" + "$6\r\n" + "HSETEX\r\n" + "$4\r\n" + "hKey\r\n" + "$2\r\n" + "EX\r\n" + "$2\r\n" + "10\r\n"
+ "$3\r\n" + "FNX\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "1\r\n" + "$3\r\n" + "one\r\n" + "$1\r\n"
+ "1\r\n";
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*9\r\n" + "$6\r\n" + "HSETEX\r\n" + "$4\r\n" + "hKey\r\n"
+ "$2\r\n" + "EX\r\n" + "$2\r\n" + "10\r\n" + "$3\r\n" + "FNX\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n"
+ "1\r\n" + "$3\r\n" + "one\r\n" + "$1\r\n" + "1\r\n");
}
@Test
void shouldCorrectlyConstructHgetex() {
Command<String, String, ?> command = sut.hgetex(MY_KEY, "one");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*5\r\n" + "$6\r\n" + "HGETEX\r\n" + "$4\r\n" + "hKey\r\n"
+ "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "1\r\n" + "$3\r\n" + "one\r\n");
}
@Test
void shouldCorrectlyConstructHgetexWithArgs() {
Command<String, String, ?> command = sut.hgetex(MY_KEY, HGetExArgs.Builder.ex(Duration.ofSeconds(10)).persist(), "one");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo(
"*8\r\n" + "$6\r\n" + "HGETEX\r\n" + "$4\r\n" + "hKey\r\n" + "$2\r\n" + "EX\r\n" + "$2\r\n" + "10\r\n"
+ "$7\r\n" + "PERSIST\r\n" + "$6\r\n" + "FIELDS\r\n" + "$1\r\n" + "1\r\n" + "$3\r\n" + "one\r\n");
}
@Test
void shouldCorrectlyConstructClientTrackinginfo() {
Command<String, String, ?> command = sut.clientTrackinginfo();
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*2\r\n" + "$6\r\n" + "CLIENT\r\n" + "$12\r\n" + "TRACKINGINFO\r\n");
}
@Test
void shouldCorrectlyConstructClusterMyshardid() {
Command<String, String, ?> command = sut.clusterMyShardId();
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*2\r\n" + "$7\r\n" + "CLUSTER\r\n" + "$9\r\n" + "MYSHARDID\r\n");
}
@Test
void shouldCorrectlyConstructClusterLinks() {
Command<String, String, List<Map<String, Object>>> command = sut.clusterLinks();
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*2\r\n$7\r\nCLUSTER\r\n$5\r\nLINKS\r\n");
}
@Test
void shouldCorrectlyConstructBitopDiff() {
Command<String, String, ?> command = sut.bitopDiff("dest", "key1", "key2", "key3");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*6\r\n$5\r\nBITOP\r\n$4\r\nDIFF\r\n$4\r\ndest\r\n$4\r\nkey1\r\n$4\r\nkey2\r\n$4\r\nkey3\r\n");
}
@Test
void shouldCorrectlyConstructBitopDiff1() {
Command<String, String, ?> command = sut.bitopDiff1("dest", "key1", "key2", "key3");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*6\r\n$5\r\nBITOP\r\n$5\r\nDIFF1\r\n$4\r\ndest\r\n$4\r\nkey1\r\n$4\r\nkey2\r\n$4\r\nkey3\r\n");
}
@Test
void shouldCorrectlyConstructBitopAndor() {
Command<String, String, ?> command = sut.bitopAndor("dest", "key1", "key2", "key3");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*6\r\n$5\r\nBITOP\r\n$5\r\nANDOR\r\n$4\r\ndest\r\n$4\r\nkey1\r\n$4\r\nkey2\r\n$4\r\nkey3\r\n");
}
@Test
void shouldCorrectlyConstructBitopOne() {
Command<String, String, ?> command = sut.bitopOne("dest", "key1", "key2", "key3");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*6\r\n$5\r\nBITOP\r\n$3\r\nONE\r\n$4\r\ndest\r\n$4\r\nkey1\r\n$4\r\nkey2\r\n$4\r\nkey3\r\n");
}
@Test
void shouldCorrectlyConstructXackdel() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xackdel(STREAM_KEY, GROUP_NAME,
new String[] { MESSAGE_ID1, MESSAGE_ID2 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo(
"*7\r\n" + "$7\r\n" + "XACKDEL\r\n" + "$11\r\n" + "test-stream\r\n" + "$10\r\n" + "test-group\r\n" + "$3\r\n"
+ "IDS\r\n" + "$1\r\n" + "2\r\n" + "$12\r\n" + "1234567890-0\r\n" + "$12\r\n" + "1234567891-0\r\n");
}
@Test
void shouldCorrectlyConstructXackdelWithPolicy() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xackdel(STREAM_KEY, GROUP_NAME,
StreamDeletionPolicy.KEEP_REFERENCES, new String[] { MESSAGE_ID1, MESSAGE_ID2, MESSAGE_ID3 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*9\r\n" + "$7\r\n" + "XACKDEL\r\n" + "$11\r\n"
+ "test-stream\r\n" + "$10\r\n" + "test-group\r\n" + "$7\r\n" + "KEEPREF\r\n" + "$3\r\n" + "IDS\r\n" + "$1\r\n"
+ "3\r\n" + "$12\r\n" + "1234567890-0\r\n" + "$12\r\n" + "1234567891-0\r\n" + "$12\r\n" + "1234567892-0\r\n");
}
@Test
void shouldCorrectlyConstructXackdelWithDeleteReferencesPolicy() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xackdel(STREAM_KEY, GROUP_NAME,
StreamDeletionPolicy.DELETE_REFERENCES, new String[] { MESSAGE_ID1 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$7\r\n" + "XACKDEL\r\n" + "$11\r\n" + "test-stream\r\n" + "$10\r\n" + "test-group\r\n"
+ "$6\r\n" + "DELREF\r\n" + "$3\r\n" + "IDS\r\n" + "$1\r\n" + "1\r\n" + "$12\r\n" + "1234567890-0\r\n");
}
@Test
void shouldCorrectlyConstructXackdelWithAcknowledgedPolicy() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xackdel(STREAM_KEY, GROUP_NAME,
StreamDeletionPolicy.ACKNOWLEDGED, new String[] { MESSAGE_ID1, MESSAGE_ID2 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*8\r\n" + "$7\r\n" + "XACKDEL\r\n" + "$11\r\n"
+ "test-stream\r\n" + "$10\r\n" + "test-group\r\n" + "$5\r\n" + "ACKED\r\n" + "$3\r\n" + "IDS\r\n" + "$1\r\n"
+ "2\r\n" + "$12\r\n" + "1234567890-0\r\n" + "$12\r\n" + "1234567891-0\r\n");
}
@Test
void shouldCorrectlyConstructXdelex() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xdelex(STREAM_KEY,
new String[] { MESSAGE_ID1, MESSAGE_ID2 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*6\r\n" + "$6\r\n" + "XDELEX\r\n" + "$11\r\n" + "test-stream\r\n" + "$3\r\n" + "IDS\r\n" + "$1\r\n"
+ "2\r\n" + "$12\r\n" + "1234567890-0\r\n" + "$12\r\n" + "1234567891-0\r\n");
}
@Test
void shouldCorrectlyConstructXdelexWithSingleMessageId() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xdelex(STREAM_KEY, new String[] { MESSAGE_ID1 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*5\r\n" + "$6\r\n" + "XDELEX\r\n" + "$11\r\n"
+ "test-stream\r\n" + "$3\r\n" + "IDS\r\n" + "$1\r\n" + "1\r\n" + "$12\r\n" + "1234567890-0\r\n");
}
@Test
void shouldCorrectlyConstructXdelexWithPolicy() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xdelex(STREAM_KEY,
StreamDeletionPolicy.KEEP_REFERENCES, new String[] { MESSAGE_ID1, MESSAGE_ID2, MESSAGE_ID3 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*8\r\n" + "$6\r\n" + "XDELEX\r\n" + "$11\r\n"
+ "test-stream\r\n" + "$7\r\n" + "KEEPREF\r\n" + "$3\r\n" + "IDS\r\n" + "$1\r\n" + "3\r\n" + "$12\r\n"
+ "1234567890-0\r\n" + "$12\r\n" + "1234567891-0\r\n" + "$12\r\n" + "1234567892-0\r\n");
}
@Test
void shouldCorrectlyConstructXdelexWithDeleteReferencesPolicy() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xdelex(STREAM_KEY,
StreamDeletionPolicy.DELETE_REFERENCES, new String[] { MESSAGE_ID1 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*6\r\n" + "$6\r\n" + "XDELEX\r\n" + "$11\r\n" + "test-stream\r\n" + "$6\r\n" + "DELREF\r\n"
+ "$3\r\n" + "IDS\r\n" + "$1\r\n" + "1\r\n" + "$12\r\n" + "1234567890-0\r\n");
}
@Test
void shouldCorrectlyConstructXdelexWithAcknowledgedPolicy() {
Command<String, String, List<StreamEntryDeletionResult>> command = sut.xdelex(STREAM_KEY,
StreamDeletionPolicy.ACKNOWLEDGED, new String[] { MESSAGE_ID1, MESSAGE_ID2 });
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo(
"*7\r\n" + "$6\r\n" + "XDELEX\r\n" + "$11\r\n" + "test-stream\r\n" + "$5\r\n" + "ACKED\r\n" + "$3\r\n"
+ "IDS\r\n" + "$1\r\n" + "2\r\n" + "$12\r\n" + "1234567890-0\r\n" + "$12\r\n" + "1234567891-0\r\n");
}
@Test
void xackdelShouldRejectNullKey() {
assertThatThrownBy(() -> sut.xackdel(null, GROUP_NAME, new String[] { MESSAGE_ID1 }))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("Key must not be null");
}
@Test
void xackdelShouldRejectNullGroup() {
assertThatThrownBy(() -> sut.xackdel(STREAM_KEY, null, new String[] { MESSAGE_ID1 }))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("Group must not be null");
}
@Test
void xackdelShouldRejectEmptyMessageIds() {
assertThatThrownBy(() -> sut.xackdel(STREAM_KEY, GROUP_NAME, new String[] {}))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("MessageIds must not be empty");
}
@Test
void xackdelShouldRejectNullMessageIds() {
assertThatThrownBy(() -> sut.xackdel(STREAM_KEY, GROUP_NAME, (String[]) null))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("MessageIds must not be empty");
}
@Test
void xackdelShouldRejectNullElementsInMessageIds() {
assertThatThrownBy(() -> sut.xackdel(STREAM_KEY, GROUP_NAME, new String[] { MESSAGE_ID1, null, MESSAGE_ID2 }))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("MessageIds must not contain null elements");
}
@Test
void xackdelWithPolicyShouldRejectNullKey() {
assertThatThrownBy(
() -> sut.xackdel(null, GROUP_NAME, StreamDeletionPolicy.KEEP_REFERENCES, new String[] { MESSAGE_ID1 }))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("Key must not be null");
}
@Test
void xdelexShouldRejectNullKey() {
assertThatThrownBy(() -> sut.xdelex(null, new String[] { MESSAGE_ID1 })).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Key must not be null");
}
@Test
void xdelexShouldRejectEmptyMessageIds() {
assertThatThrownBy(() -> sut.xdelex(STREAM_KEY, new String[] {})).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("MessageIds must not be empty");
}
@Test
void xdelexShouldRejectNullMessageIds() {
assertThatThrownBy(() -> sut.xdelex(STREAM_KEY, (String[]) null)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("MessageIds must not be empty");
}
@Test
void xdelexShouldRejectNullElementsInMessageIds() {
assertThatThrownBy(() -> sut.xdelex(STREAM_KEY, new String[] { MESSAGE_ID1, null, MESSAGE_ID2 }))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("MessageIds must not contain null elements");
}
@Test
void xdelexWithPolicyShouldRejectNullKey() {
assertThatThrownBy(() -> sut.xdelex(null, StreamDeletionPolicy.KEEP_REFERENCES, new String[] { MESSAGE_ID1 }))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("Key must not be null");
}
@Test
void shouldCorrectlyConstructSetWithExAndIfeq() {
Command<String, String, ?> command = sut.set("mykey", "myvalue",
SetArgs.Builder.ex(100).compareCondition(CompareCondition.valueEq("oldvalue")));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$3\r\n" + "SET\r\n" + "$5\r\n" + "mykey\r\n" + "$7\r\n" + "myvalue\r\n" + "$2\r\n"
+ "EX\r\n" + "$3\r\n" + "100\r\n" + "$4\r\n" + "IFEQ\r\n" + "$8\r\n" + "oldvalue\r\n");
}
@Test
void shouldCorrectlyConstructSetWithExAtAndIfne() {
Command<String, String, ?> command = sut.set("mykey", "myvalue",
SetArgs.Builder.exAt(1234567890).compareCondition(CompareCondition.valueNe("wrongvalue")));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8))
.isEqualTo("*7\r\n" + "$3\r\n" + "SET\r\n" + "$5\r\n" + "mykey\r\n" + "$7\r\n" + "myvalue\r\n" + "$4\r\n"
+ "EXAT\r\n" + "$10\r\n" + "1234567890\r\n" + "$4\r\n" + "IFNE\r\n" + "$10\r\n" + "wrongvalue\r\n");
}
@Test
void shouldCorrectlyConstructSetGetWithPxAndIfdne() {
Command<String, String, ?> command = sut.setGet("mykey", "myvalue",
SetArgs.Builder.px(50000).compareCondition(CompareCondition.digestNe("0123456789abcdef")));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*8\r\n" + "$3\r\n" + "SET\r\n" + "$5\r\n" + "mykey\r\n"
+ "$7\r\n" + "myvalue\r\n" + "$2\r\n" + "PX\r\n" + "$5\r\n" + "50000\r\n" + "$5\r\n" + "IFDNE\r\n" + "$16\r\n"
+ "0123456789abcdef\r\n" + "$3\r\n" + "GET\r\n");
}
@Test
void shouldCorrectlyConstructSetGetWithPxAtAndIfdeq() {
Command<String, String, ?> command = sut.setGet("mykey", "myvalue",
SetArgs.Builder.pxAt(1234567890123L).compareCondition(CompareCondition.digestEq("fedcba9876543210")));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*8\r\n" + "$3\r\n" + "SET\r\n" + "$5\r\n" + "mykey\r\n"
+ "$7\r\n" + "myvalue\r\n" + "$4\r\n" + "PXAT\r\n" + "$13\r\n" + "1234567890123\r\n" + "$5\r\n" + "IFDEQ\r\n"
+ "$16\r\n" + "fedcba9876543210\r\n" + "$3\r\n" + "GET\r\n");
}
@Test
void shouldCorrectlyConstructDelexWithValueEq() {
Command<String, String, ?> command = sut.delex("mykey", CompareCondition.valueEq("expectedvalue"));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*4\r\n" + "$5\r\n" + "DELEX\r\n" + "$5\r\n" + "mykey\r\n"
+ "$4\r\n" + "IFEQ\r\n" + "$13\r\n" + "expectedvalue\r\n");
}
@Test
void shouldCorrectlyConstructDelexWithDigestNe() {
Command<String, String, ?> command = sut.delex("mykey", CompareCondition.digestNe("0011223344556677"));
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*4\r\n" + "$5\r\n" + "DELEX\r\n" + "$5\r\n" + "mykey\r\n"
+ "$5\r\n" + "IFDNE\r\n" + "$16\r\n" + "0011223344556677\r\n");
}
@Test
void shouldCorrectlyConstructDigestKey() {
Command<String, String, ?> command = sut.digestKey("mykey");
ByteBuf buf = Unpooled.directBuffer();
command.encode(buf);
assertThat(buf.toString(StandardCharsets.UTF_8)).isEqualTo("*2\r\n" + "$6\r\n" + "DIGEST\r\n" + "$5\r\n" + "mykey\r\n");
}
@Test
void msetex_nxThenEx_seconds_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
MSetExArgs a = MSetExArgs.Builder.nx().ex(Duration.ofSeconds(5));
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> EX 5 NX");
}
@Test
void msetex_xxThenKeepTtl_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
MSetExArgs a = MSetExArgs.Builder.xx().keepttl();
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> XX KEEPTTL");
}
@Test
void msetex_noConditionThenPx_millis_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
MSetExArgs a = MSetExArgs.Builder.px(Duration.ofMillis(500));
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> PX 500");
}
@Test
void msetex_noConditionThenPx_duration_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
MSetExArgs a = MSetExArgs.Builder.px(Duration.ofMillis(1234));
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> PX 1234");
}
@Test
void msetex_exAt_withInstant_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
Instant t = Instant.ofEpochSecond(1_234_567_890L);
MSetExArgs a = MSetExArgs.Builder.exAt(t);
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> EXAT 1234567890");
}
@Test
void msetex_pxAt_withInstant_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
Instant t = Instant.ofEpochMilli(4_000L);
MSetExArgs a = MSetExArgs.Builder.pxAt(t);
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> PXAT 4000");
}
@Test
void msetex_exAt_withLong_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
long epochSeconds = 1_234_567_890L;
MSetExArgs a = MSetExArgs.Builder.exAt(Instant.ofEpochSecond(epochSeconds));
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> EXAT 1234567890");
}
@Test
void msetex_pxAt_withLong_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
long epochMillis = 4_567L;
MSetExArgs a = MSetExArgs.Builder.pxAt(Instant.ofEpochMilli(epochMillis));
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> PXAT 4567");
}
@Test
void msetex_nxThenExAt_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
Instant t = Instant.ofEpochSecond(42L);
MSetExArgs a = MSetExArgs.Builder.nx().exAt(t);
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> EXAT 42 NX");
}
@Test
void msetex_xxThenPxAt_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
Instant t = Instant.ofEpochMilli(314L);
MSetExArgs a = MSetExArgs.Builder.xx().pxAt(t);
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> PXAT 314 XX");
}
@Test
void msetex_exAt_withDate_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
Date ts = new Date(1_234_567_890L * 1000L);
MSetExArgs a = MSetExArgs.Builder.exAt(ts.toInstant());
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> EXAT 1234567890");
}
@Test
void msetex_pxAt_withDate_emissionOrder() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
Date ts = new Date(9_999L);
MSetExArgs a = MSetExArgs.Builder.pxAt(ts.toInstant());
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v> PXAT 9999");
}
@Test
void msetex_noCondition_noExpiration_onlyMapAndCount() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k", "v");
Command<String, String, Boolean> cmd = sut.msetex(map, null);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("1 key<k> value<v>");
}
@Test
void msetex_twoPairs_keepttl_orderAndCount() {
Map<String, String> map = new LinkedHashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
MSetExArgs a = MSetExArgs.Builder.keepttl();
Command<String, String, Boolean> cmd = sut.msetex(map, a);
String s = cmd.getArgs().toCommandString();
assertThat(s).isEqualTo("2 key<k1> value<v1> key<k2> value<v2> KEEPTTL");
}
}
| RedisCommandBuilderUnitTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/entity/EntityMutabilityPlanTest.java | {
"start": 1156,
"end": 1252
} | class ____ {
@Id
private Long id;
private Date createdOn;
private String message;
}
}
| Event |
java | quarkusio__quarkus | extensions/security-webauthn/deployment/src/test/java/io/quarkus/security/webauthn/test/WebAuthnManualTestUserProvider.java | {
"start": 764,
"end": 1484
} | class ____ extends WebAuthnTestUserProvider {
@Override
public Uni<WebAuthnCredentialRecord> findByCredentialId(String credId) {
assertRequestContext();
return super.findByCredentialId(credId);
}
@Override
public Uni<List<WebAuthnCredentialRecord>> findByUsername(String userId) {
assertRequestContext();
return super.findByUsername(userId);
}
private void assertRequestContext() {
// allow this being used in the tests
if (TestUtil.isTestThread())
return;
if (!Arc.container().requestContext().isActive()) {
throw new AssertionError("Request context not active");
}
}
}
| WebAuthnManualTestUserProvider |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/floatarray/FloatArrayAssert_usingComparator_Test.java | {
"start": 1167,
"end": 1855
} | class ____ extends FloatArrayAssertBaseTest {
private Comparator<float[]> comparator = alwaysEqual();
private FloatArrays arraysBefore;
@BeforeEach
void before() {
arraysBefore = getArrays(assertions);
}
@Override
protected FloatArrayAssert invoke_api_method() {
// in that test, the comparator type is not important, we only check that we correctly switch of comparator
return assertions.usingComparator(comparator);
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions).getComparator()).isSameAs(comparator);
assertThat(getArrays(assertions)).isSameAs(arraysBefore);
}
}
| FloatArrayAssert_usingComparator_Test |
java | google__guava | android/guava-tests/test/com/google/common/collect/TableCollectorsTest.java | {
"start": 1533,
"end": 12446
} | class ____ extends TestCase {
public void testToImmutableTable() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue);
BiPredicate<ImmutableTable<String, String, Integer>, ImmutableTable<String, String, Integer>>
equivalence = pairwiseOnResultOf(ImmutableTable::cellSet);
CollectorTester.of(collector, equivalence)
.expectCollects(
new ImmutableTable.Builder<String, String, Integer>()
.put("one", "uno", 1)
.put("two", "dos", 2)
.put("three", "tres", 3)
.buildOrThrow(),
immutableCell("one", "uno", 1),
immutableCell("two", "dos", 2),
immutableCell("three", "tres", 3));
}
public void testToImmutableTableConflict() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue);
assertThrows(
IllegalArgumentException.class,
() ->
Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2))
.collect(collector));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when rowFunction result (null) is unboxed
@J2ktIncompatible
public void testToImmutableTableNullRowKey() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(t -> null, Cell::getColumnKey, Cell::getValue);
assertThrows(
NullPointerException.class,
() -> Stream.of(immutableCell("one", "uno", 1)).collect(collector));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when columnFunction result (null) is
// unboxed
@J2ktIncompatible
public void testToImmutableTableNullColumnKey() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(Cell::getRowKey, t -> null, Cell::getValue);
assertThrows(
NullPointerException.class,
() -> Stream.of(immutableCell("one", "uno", 1)).collect(collector));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when getValue result (null) is unboxed
@J2ktIncompatible
public void testToImmutableTableNullValue() {
{
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>>
collector = toImmutableTable(Cell::getRowKey, Cell::getColumnKey, t -> null);
assertThrows(
NullPointerException.class,
() -> Stream.of(immutableCell("one", "uno", 1)).collect(collector));
}
{
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>>
collector = toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue);
assertThrows(
NullPointerException.class,
() ->
Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", (Integer) null))
.collect(collector));
}
}
public void testToImmutableTableMerging() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue, Integer::sum);
BiPredicate<ImmutableTable<String, String, Integer>, ImmutableTable<String, String, Integer>>
equivalence = pairwiseOnResultOf(ImmutableTable::cellSet);
CollectorTester.of(collector, equivalence)
.expectCollects(
new ImmutableTable.Builder<String, String, Integer>()
.put("one", "uno", 1)
.put("two", "dos", 6)
.put("three", "tres", 3)
.buildOrThrow(),
immutableCell("one", "uno", 1),
immutableCell("two", "dos", 2),
immutableCell("three", "tres", 3),
immutableCell("two", "dos", 4));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when rowFunction result (null) is unboxed
@J2ktIncompatible
public void testToImmutableTableMergingNullRowKey() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(t -> null, Cell::getColumnKey, Cell::getValue, Integer::sum);
assertThrows(
NullPointerException.class,
() -> Stream.of(immutableCell("one", "uno", 1)).collect(collector));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when columnFunction result (null) is
// unboxed
@J2ktIncompatible
public void testToImmutableTableMergingNullColumnKey() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(Cell::getRowKey, t -> null, Cell::getValue, Integer::sum);
assertThrows(
NullPointerException.class,
() -> Stream.of(immutableCell("one", "uno", 1)).collect(collector));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when valueFunction result (null) is
// unboxed
@J2ktIncompatible
public void testToImmutableTableMergingNullValue() {
{
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>>
collector =
toImmutableTable(Cell::getRowKey, Cell::getColumnKey, t -> null, Integer::sum);
assertThrows(
NullPointerException.class,
() -> Stream.of(immutableCell("one", "uno", 1)).collect(collector));
}
{
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>>
collector =
toImmutableTable(
Cell::getRowKey,
Cell::getColumnKey,
Cell::getValue,
(i, j) -> MoreObjects.firstNonNull(i, 0) + MoreObjects.firstNonNull(j, 0));
assertThrows(
NullPointerException.class,
() ->
Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", (Integer) null))
.collect(collector));
}
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when mergeFunction result (null) is
// unboxed
@J2ktIncompatible
public void testToImmutableTableMergingNullMerge() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue, (v1, v2) -> null);
assertThrows(
NullPointerException.class,
() ->
Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2))
.collect(collector));
}
public void testToTable() {
Collector<Cell<String, String, Integer>, ?, Table<String, String, Integer>> collector =
TableCollectors.toTable(
Cell::getRowKey, Cell::getColumnKey, Cell::getValue, HashBasedTable::create);
BiPredicate<Table<String, String, Integer>, Table<String, String, Integer>> equivalence =
pairwiseOnResultOf(Table::cellSet);
CollectorTester.of(collector, equivalence)
.expectCollects(
new ImmutableTable.Builder<String, String, Integer>()
.put("one", "uno", 1)
.put("two", "dos", 2)
.put("three", "tres", 3)
.buildOrThrow(),
immutableCell("one", "uno", 1),
immutableCell("two", "dos", 2),
immutableCell("three", "tres", 3));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when mergeFunction result (null) is
// unboxed
@J2ktIncompatible
public void testToTableNullMerge() {
// TODO github.com/google/guava/issues/6824 - the null merge feature is not compatible with the
// current nullness annotation of the mergeFunction parameter. Work around with casts.
BinaryOperator<@Nullable Integer> mergeFunction = (v1, v2) -> null;
Collector<Cell<String, String, Integer>, ?, Table<String, String, Integer>> collector =
TableCollectors.toTable(
Cell::getRowKey,
Cell::getColumnKey,
Cell::getValue,
(BinaryOperator<Integer>) mergeFunction,
HashBasedTable::create);
BiPredicate<Table<String, String, Integer>, Table<String, String, Integer>> equivalence =
pairwiseOnResultOf(Table::cellSet);
CollectorTester.of(collector, equivalence)
.expectCollects(
ImmutableTable.of(), immutableCell("one", "uno", 1), immutableCell("one", "uno", 2));
}
// https://youtrack.jetbrains.com/issue/KT-58242/. Crash when getValue result (null) is unboxed
@J2ktIncompatible
public void testToTableNullValues() {
Collector<Cell<String, String, Integer>, ?, Table<String, String, Integer>> collector =
TableCollectors.toTable(
Cell::getRowKey,
Cell::getColumnKey,
Cell::getValue,
() -> {
Table<String, String, @Nullable Integer> table =
ArrayTable.create(ImmutableList.of("one"), ImmutableList.of("uno"));
return (Table<String, String, Integer>) table;
});
Cell<String, String, @Nullable Integer> cell = immutableCell("one", "uno", null);
assertThrows(
NullPointerException.class,
() -> Stream.of((Cell<String, String, Integer>) cell).collect(collector));
}
public void testToTableConflict() {
Collector<Cell<String, String, Integer>, ?, Table<String, String, Integer>> collector =
TableCollectors.toTable(
Cell::getRowKey, Cell::getColumnKey, Cell::getValue, HashBasedTable::create);
assertThrows(
IllegalStateException.class,
() ->
Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2))
.collect(collector));
}
public void testToTableMerging() {
Collector<Cell<String, String, Integer>, ?, Table<String, String, Integer>> collector =
TableCollectors.toTable(
Cell::getRowKey,
Cell::getColumnKey,
Cell::getValue,
Integer::sum,
HashBasedTable::create);
BiPredicate<Table<String, String, Integer>, Table<String, String, Integer>> equivalence =
pairwiseOnResultOf(Table::cellSet);
CollectorTester.of(collector, equivalence)
.expectCollects(
new ImmutableTable.Builder<String, String, Integer>()
.put("one", "uno", 1)
.put("two", "dos", 6)
.put("three", "tres", 3)
.buildOrThrow(),
immutableCell("one", "uno", 1),
immutableCell("two", "dos", 2),
immutableCell("three", "tres", 3),
immutableCell("two", "dos", 4));
}
// This function specifically returns a BiPredicate, because Guava7’s Equivalence | TableCollectorsTest |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/DslKeyValueParams.java | {
"start": 1039,
"end": 2353
} | class ____ {
private final String name;
private final boolean isTimestamped;
/**
* @param name the name of the store (cannot be {@code null})
* @param isTimestamped whether the returned stores should be timestamped, see ({@link TimestampedKeyValueStore}
*/
public DslKeyValueParams(final String name, final boolean isTimestamped) {
Objects.requireNonNull(name);
this.name = name;
this.isTimestamped = isTimestamped;
}
public String name() {
return name;
}
public boolean isTimestamped() {
return isTimestamped;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DslKeyValueParams that = (DslKeyValueParams) o;
return isTimestamped == that.isTimestamped
&& Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, isTimestamped);
}
@Override
public String toString() {
return "DslKeyValueParams{" +
"name='" + name + '\'' +
"isTimestamped=" + isTimestamped +
'}';
}
} | DslKeyValueParams |
java | spring-projects__spring-framework | spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java | {
"start": 18502,
"end": 19109
} | class ____ extends StoredProcedure {
public static final String SQL = "add_invoice";
public AddInvoiceUsingObjectArray(DataSource ds) {
setDataSource(ds);
setSql(SQL);
declareParameter(new SqlParameter("amount", Types.INTEGER));
declareParameter(new SqlParameter("custid", Types.INTEGER));
declareParameter(new SqlOutParameter("newid", Types.INTEGER));
compile();
}
public int execute(int amount, int custid) {
Map<String, Object> out = execute(new Object[] { amount, custid });
return ((Number) out.get("newid")).intValue();
}
}
private static | AddInvoiceUsingObjectArray |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/util/LatencyStatsTest.java | {
"start": 1663,
"end": 8686
} | class ____ {
private static final OperatorID OPERATOR_ID = new OperatorID();
private static final OperatorID SOURCE_ID_1 = new OperatorID();
private static final OperatorID SOURCE_ID_2 = new OperatorID();
private static final int OPERATOR_SUBTASK_INDEX = 64;
private static final String PARENT_GROUP_NAME = "parent";
@Test
void testLatencyStatsSingle() {
testLatencyStats(
LatencyStats.Granularity.SINGLE,
registrations -> {
assertThat(registrations).hasSize(1);
{
final Tuple2<String, Histogram> registration = registrations.get(0);
assertName(registration.f0);
assertThat(registration.f1.getCount()).isEqualTo(5);
}
});
}
@Test
void testLatencyStatsOperator() {
testLatencyStats(
LatencyStats.Granularity.OPERATOR,
registrations -> {
assertThat(registrations).hasSize(2);
{
final Tuple2<String, Histogram> registration = registrations.get(0);
assertName(registration.f0, SOURCE_ID_1);
assertThat(registration.f1.getCount()).isEqualTo(3);
}
{
final Tuple2<String, Histogram> registration = registrations.get(1);
assertName(registration.f0, SOURCE_ID_2);
assertThat(registration.f1.getCount()).isEqualTo(2);
}
});
}
@Test
void testLatencyStatsSubtask() {
testLatencyStats(
LatencyStats.Granularity.SUBTASK,
registrations -> {
assertThat(registrations).hasSize(4);
{
final Tuple2<String, Histogram> registration = registrations.get(0);
assertName(registration.f0, SOURCE_ID_1, 0);
assertThat(registration.f1.getCount()).isEqualTo(2);
}
{
final Tuple2<String, Histogram> registration = registrations.get(1);
assertName(registration.f0, SOURCE_ID_1, 1);
assertThat(registration.f1.getCount()).isOne();
}
{
final Tuple2<String, Histogram> registration = registrations.get(2);
assertName(registration.f0, SOURCE_ID_2, 2);
assertThat(registration.f1.getCount()).isOne();
}
{
final Tuple2<String, Histogram> registration = registrations.get(3);
assertName(registration.f0, SOURCE_ID_2, 3);
assertThat(registration.f1.getCount()).isOne();
}
});
}
private static void testLatencyStats(
final LatencyStats.Granularity granularity,
final Consumer<List<Tuple2<String, Histogram>>> verifier) {
final AbstractMetricGroup<?> dummyGroup =
UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup();
final List<Tuple2<String, Histogram>> latencyHistograms = new ArrayList<>(4);
final TestingMetricRegistry registry =
TestingMetricRegistry.builder()
.setRegisterConsumer(
(metric, metricName, group) -> {
if (metric instanceof Histogram) {
latencyHistograms.add(
Tuple2.of(
group.getMetricIdentifier(metricName),
(Histogram) metric));
}
})
.build();
final MetricGroup parentGroup =
new GenericMetricGroup(registry, dummyGroup, PARENT_GROUP_NAME);
final LatencyStats latencyStats =
new LatencyStats(
parentGroup,
MetricOptions.LATENCY_HISTORY_SIZE.defaultValue(),
OPERATOR_SUBTASK_INDEX,
OPERATOR_ID,
granularity);
latencyStats.reportLatency(new LatencyMarker(0L, SOURCE_ID_1, 0));
latencyStats.reportLatency(new LatencyMarker(0L, SOURCE_ID_1, 0));
latencyStats.reportLatency(new LatencyMarker(0L, SOURCE_ID_1, 1));
latencyStats.reportLatency(new LatencyMarker(0L, SOURCE_ID_2, 2));
latencyStats.reportLatency(new LatencyMarker(0L, SOURCE_ID_2, 3));
verifier.accept(latencyHistograms);
}
/** Removes all parts from the metric identifier preceding the latency-related parts. */
private static String sanitizeName(final String registrationName) {
return registrationName.substring(
registrationName.lastIndexOf(PARENT_GROUP_NAME) + PARENT_GROUP_NAME.length() + 1);
}
private static void assertName(final String registrationName) {
final String sanitizedName = sanitizeName(registrationName);
assertThat(sanitizedName)
.isEqualTo(
"operator_id."
+ OPERATOR_ID
+ ".operator_subtask_index."
+ OPERATOR_SUBTASK_INDEX
+ ".latency");
}
private static void assertName(final String registrationName, final OperatorID sourceId) {
final String sanitizedName = sanitizeName(registrationName);
assertThat(sanitizedName)
.isEqualTo(
"source_id."
+ sourceId
+ ".operator_id."
+ OPERATOR_ID
+ ".operator_subtask_index."
+ OPERATOR_SUBTASK_INDEX
+ ".latency");
}
private static void assertName(
final String registrationName, final OperatorID sourceId, final int sourceIndex) {
final String sanitizedName = sanitizeName(registrationName);
assertThat(sanitizedName)
.isEqualTo(
"source_id."
+ sourceId
+ ".source_subtask_index."
+ sourceIndex
+ ".operator_id."
+ OPERATOR_ID
+ ".operator_subtask_index."
+ OPERATOR_SUBTASK_INDEX
+ ".latency");
}
}
| LatencyStatsTest |
java | apache__spark | common/variant/src/main/java/org/apache/spark/types/variant/VariantShreddingWriter.java | {
"start": 1877,
"end": 12336
} | interface ____ {
ShreddedResult createEmpty(VariantSchema schema);
// If true, we will shred decimals to a different scale or to integers, as long as they are
// numerically equivalent. Similarly, integers will be allowed to shred to decimals.
boolean allowNumericScaleChanges();
}
/**
* Converts an input variant into shredded components. Returns the shredded result, as well
* as the original Variant with shredded fields removed.
* `dataType` must be a valid shredding schema, as described in
* https://github.com/apache/parquet-format/blob/master/VariantShredding.md.
*/
public static ShreddedResult castShredded(
Variant v,
VariantSchema schema,
ShreddedResultBuilder builder) {
VariantUtil.Type variantType = v.getType();
ShreddedResult result = builder.createEmpty(schema);
if (schema.topLevelMetadataIdx >= 0) {
result.addMetadata(v.getMetadata());
}
if (schema.arraySchema != null && variantType == VariantUtil.Type.ARRAY) {
// The array element is always a struct containing untyped and typed fields.
VariantSchema elementSchema = schema.arraySchema;
int size = v.arraySize();
ShreddedResult[] array = new ShreddedResult[size];
for (int i = 0; i < size; ++i) {
ShreddedResult shreddedArray = castShredded(v.getElementAtIndex(i), elementSchema, builder);
array[i] = shreddedArray;
}
result.addArray(array);
} else if (schema.objectSchema != null && variantType == VariantUtil.Type.OBJECT) {
VariantSchema.ObjectField[] objectSchema = schema.objectSchema;
ShreddedResult[] shreddedValues = new ShreddedResult[objectSchema.length];
// Create a variantBuilder for any field that exist in `v`, but not in the shredding schema.
VariantBuilder variantBuilder = new VariantBuilder(false);
ArrayList<VariantBuilder.FieldEntry> fieldEntries = new ArrayList<>();
// Keep track of which schema fields we actually found in the Variant value.
int numFieldsMatched = 0;
int start = variantBuilder.getWritePos();
for (int i = 0; i < v.objectSize(); ++i) {
Variant.ObjectField field = v.getFieldAtIndex(i);
Integer fieldIdx = schema.objectSchemaMap.get(field.key);
if (fieldIdx != null) {
// The field exists in the shredding schema. Recursively shred, and write the result.
ShreddedResult shreddedField = castShredded(
field.value, objectSchema[fieldIdx].schema, builder);
shreddedValues[fieldIdx] = shreddedField;
numFieldsMatched++;
} else {
// The field is not shredded. Put it in the untyped_value column.
int id = v.getDictionaryIdAtIndex(i);
fieldEntries.add(new VariantBuilder.FieldEntry(
field.key, id, variantBuilder.getWritePos() - start));
// shallowAppendVariant is needed for correctness, since we're relying on the metadata IDs
// being unchanged.
variantBuilder.shallowAppendVariant(field.value);
}
}
if (numFieldsMatched < objectSchema.length) {
// Set missing fields to non-null with all fields set to null.
for (int i = 0; i < objectSchema.length; ++i) {
if (shreddedValues[i] == null) {
VariantSchema.ObjectField fieldSchema = objectSchema[i];
ShreddedResult emptyChild = builder.createEmpty(fieldSchema.schema);
shreddedValues[i] = emptyChild;
numFieldsMatched += 1;
}
}
}
if (numFieldsMatched != objectSchema.length) {
// Since we just filled in all the null entries, this can only happen if we tried to write
// to the same field twice; i.e. the Variant contained duplicate fields, which is invalid.
throw VariantUtil.malformedVariant();
}
result.addObject(shreddedValues);
if (variantBuilder.getWritePos() != start) {
// We added something to the untyped value.
variantBuilder.finishWritingObject(start, fieldEntries);
result.addVariantValue(variantBuilder.valueWithoutMetadata());
}
} else if (schema.scalarSchema != null) {
VariantSchema.ScalarType scalarType = schema.scalarSchema;
Object typedValue = tryTypedShred(v, variantType, scalarType, builder);
if (typedValue != null) {
// Store the typed value.
result.addScalar(typedValue);
} else {
result.addVariantValue(v.getValue());
}
} else {
// Store in untyped.
result.addVariantValue(v.getValue());
}
return result;
}
/**
* Tries to cast a Variant into a typed value. If the cast fails, returns null.
*
* @param v
* @param variantType The Variant Type of v
* @param targetType The target type
* @return The scalar value, or null if the cast is not valid.
*/
private static Object tryTypedShred(
Variant v,
VariantUtil.Type variantType,
VariantSchema.ScalarType targetType,
ShreddedResultBuilder builder) {
switch (variantType) {
case LONG:
if (targetType instanceof VariantSchema.IntegralType integralType) {
// Check that the target type can hold the actual value.
VariantSchema.IntegralSize size = integralType.size;
long value = v.getLong();
switch (size) {
case BYTE:
if (value == (byte) value) {
return (byte) value;
}
break;
case SHORT:
if (value == (short) value) {
return (short) value;
}
break;
case INT:
if (value == (int) value) {
return (int) value;
}
break;
case LONG:
return value;
}
} else if (targetType instanceof VariantSchema.DecimalType decimalType &&
builder.allowNumericScaleChanges()) {
// If the integer can fit in the given decimal precision, allow it.
long value = v.getLong();
// Set to the requested scale, and check if the precision is large enough.
BigDecimal decimalValue = BigDecimal.valueOf(value);
BigDecimal scaledValue = decimalValue.setScale(decimalType.scale);
// The initial value should have scale 0, so rescaling shouldn't lose information.
assert(decimalValue.compareTo(scaledValue) == 0);
if (scaledValue.precision() <= decimalType.precision) {
return scaledValue;
}
}
break;
case DECIMAL:
if (targetType instanceof VariantSchema.DecimalType decimalType) {
// Use getDecimalWithOriginalScale so that we retain scale information if
// allowNumericScaleChanges() is false.
BigDecimal value = VariantUtil.getDecimalWithOriginalScale(v.value, v.pos);
if (value.precision() <= decimalType.precision &&
value.scale() == decimalType.scale) {
return value;
}
if (builder.allowNumericScaleChanges()) {
// Convert to the target scale, and see if it fits. Rounding mode doesn't matter,
// since we'll reject it if it turned out to require rounding.
BigDecimal scaledValue = value.setScale(decimalType.scale, RoundingMode.FLOOR);
if (scaledValue.compareTo(value) == 0 &&
scaledValue.precision() <= decimalType.precision) {
return scaledValue;
}
}
} else if (targetType instanceof VariantSchema.IntegralType integralType &&
builder.allowNumericScaleChanges()) {
// Check if the decimal happens to be an integer.
BigDecimal value = v.getDecimal();
VariantSchema.IntegralSize size = integralType.size;
// Try to cast to the appropriate type, and check if any information is lost.
switch (size) {
case BYTE:
if (value.compareTo(BigDecimal.valueOf(value.byteValue())) == 0) {
return value.byteValue();
}
break;
case SHORT:
if (value.compareTo(BigDecimal.valueOf(value.shortValue())) == 0) {
return value.shortValue();
}
break;
case INT:
if (value.compareTo(BigDecimal.valueOf(value.intValue())) == 0) {
return value.intValue();
}
break;
case LONG:
if (value.compareTo(BigDecimal.valueOf(value.longValue())) == 0) {
return value.longValue();
}
}
}
break;
case BOOLEAN:
if (targetType instanceof VariantSchema.BooleanType) {
return v.getBoolean();
}
break;
case STRING:
if (targetType instanceof VariantSchema.StringType) {
return v.getString();
}
break;
case DOUBLE:
if (targetType instanceof VariantSchema.DoubleType) {
return v.getDouble();
}
break;
case DATE:
if (targetType instanceof VariantSchema.DateType) {
return (int) v.getLong();
}
break;
case TIMESTAMP:
if (targetType instanceof VariantSchema.TimestampType) {
return v.getLong();
}
break;
case TIMESTAMP_NTZ:
if (targetType instanceof VariantSchema.TimestampNTZType) {
return v.getLong();
}
break;
case FLOAT:
if (targetType instanceof VariantSchema.FloatType) {
return v.getFloat();
}
break;
case BINARY:
if (targetType instanceof VariantSchema.BinaryType) {
return v.getBinary();
}
break;
case UUID:
if (targetType instanceof VariantSchema.UuidType) {
return v.getUuid();
}
break;
}
// The stored type does not match the requested shredding type. Return null, and the caller
// will store the result in untyped_value.
return null;
}
// Add the result to the shredding result.
private static void addVariantValueVariant(Variant variantResult,
VariantSchema schema, ShreddedResult result) {
result.addVariantValue(variantResult.getValue());
}
}
| ShreddedResultBuilder |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-actuator/src/main/java/smoketest/actuator/SampleLegacyEndpointWithDot.java | {
"start": 947,
"end": 1101
} | class ____ {
@ReadOperation
public Map<String, String> example() {
return Collections.singletonMap("legacy", "legacy");
}
}
| SampleLegacyEndpointWithDot |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/jta/JtaSessionClosedBeforeCommitTest.java | {
"start": 1470,
"end": 2732
} | class ____ {
private Integer entityId;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) throws Exception {
// We need to do this to obtain the SessionFactoryImplementor
final var emf = scope.getEntityManagerFactory();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
var entityManager = emf.createEntityManager();
try {
IntTestEntity ite = new IntTestEntity( 10 );
entityManager.persist( ite );
entityId = ite.getId();
// simulates spring JtaTransactionManager.triggerBeforeCompletion()
// this closes the entity manager prior to the JTA transaction.
entityManager.close();
}
finally {
TestingJtaPlatformImpl.tryCommit();
}
}
@Test
public void testRevisionCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( entityManager -> assertEquals(
Arrays.asList( 1 ),
AuditReaderFactory.get( entityManager ).getRevisions( IntTestEntity.class, entityId )
) );
}
@Test
public void testRevisionHistory(EntityManagerFactoryScope scope) {
scope.inEntityManager( entityManager -> assertEquals(
new IntTestEntity( 10, entityId ),
AuditReaderFactory.get( entityManager ).find( IntTestEntity.class, entityId, 1 )
) );
}
}
| JtaSessionClosedBeforeCommitTest |
java | google__dagger | javatests/dagger/functional/subcomponent/multibindings/MultibindingSubcomponents.java | {
"start": 6130,
"end": 6301
} | interface ____
extends ParentWithProvision, HasChildWithProvision {}
@Subcomponent(modules = ChildMultibindingModule.class)
| ParentWithProvisionHasChildWithProvision |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/impl/TestRequestFactory.java | {
"start": 5611,
"end": 13184
} | class ____
implements RequestFactoryImpl.PrepareRequest {
private final AtomicLong counter = new AtomicLong();
@Override
public void prepareRequest(final SdkRequest.Builder t) {
counter.addAndGet(1);
}
}
/**
* Analyze the request, log the output, return the info.
* @param builder request builder.
* @return value
*/
private AWSRequestAnalyzer.RequestInfo a(AwsRequest.Builder builder) {
AWSRequestAnalyzer.RequestInfo info = analyzer.analyze(builder.build());
LOG.info("{}", info);
requestsAnalyzed++;
return info;
}
/**
* Create objects through the factory.
* @param factory factory
*/
private void createFactoryObjects(RequestFactory factory) throws IOException {
String path = "path";
String path2 = "path2";
String id = "1";
a(factory.newAbortMultipartUploadRequestBuilder(path, id));
a(factory.newCompleteMultipartUploadRequestBuilder(path, id,
new ArrayList<>(), new PutObjectOptions("some class",
Collections.emptyMap(),
EnumSet.noneOf(WriteObjectFlags.class),
"")));
a(factory.newCopyObjectRequestBuilder(path, path2,
HeadObjectResponse.builder().build()));
a(factory.newDeleteObjectRequestBuilder(path));
a(factory.newBulkDeleteRequestBuilder(new ArrayList<>()));
a(factory.newDirectoryMarkerRequest(path));
a(factory.newGetObjectRequestBuilder(path));
a(factory.newHeadObjectRequestBuilder(path));
a(factory.newListMultipartUploadsRequestBuilder(path));
a(factory.newListObjectsV1RequestBuilder(path, "/", 1));
a(factory.newListObjectsV2RequestBuilder(path, "/", 1));
a(factory.newMultipartUploadRequestBuilder(path, null));
a(factory.newPutObjectRequestBuilder(path,
defaultOptions(), -1, true));
}
/**
* Multiparts are special so test on their own.
*/
@Test
public void testMultipartUploadRequest() throws Throwable {
CountRequests countRequests = new CountRequests();
RequestFactory factory = RequestFactoryImpl.builder()
.withBucket("bucket")
.withRequestPreparer(countRequests)
.withMultipartPartCountLimit(2)
.build();
String path = "path";
String id = "1";
a(factory.newUploadPartRequestBuilder(path, id, 1, false, 0));
a(factory.newUploadPartRequestBuilder(path, id, 2, false,
128_000_000));
// partNumber is past the limit
intercept(PathIOException.class, () ->
factory.newUploadPartRequestBuilder(path, id, 3, true,
128_000_000));
assertThat(countRequests.counter.get())
.describedAs("request preparation count")
.isEqualTo(requestsAnalyzed);
}
/**
* Assertion for Request timeouts.
* @param duration expected duration.
* @param request request.
*/
private void assertApiTimeouts(Duration duration, S3Request request) {
Assertions.assertThat(request.overrideConfiguration())
.describedAs("request %s", request)
.isNotEmpty();
final AwsRequestOverrideConfiguration override =
request.overrideConfiguration().get();
Assertions.assertThat(override.apiCallAttemptTimeout())
.describedAs("apiCallAttemptTimeout")
.hasValue(duration);
Assertions.assertThat(override.apiCallTimeout())
.describedAs("apiCallTimeout")
.hasValue(duration);
}
/**
* If not overridden timeouts are set to the default part upload timeout.
*/
@Test
public void testDefaultUploadTimeouts() throws Throwable {
RequestFactory factory = RequestFactoryImpl.builder()
.withBucket("bucket")
.withMultipartPartCountLimit(2)
.build();
final UploadPartRequest upload =
factory.newUploadPartRequestBuilder("path", "id", 2,
true, 128_000_000)
.build();
assertApiTimeouts(DEFAULT_PART_UPLOAD_TIMEOUT, upload);
}
/**
* Verify that when upload request timeouts are set,
* they are passed down.
*/
@Test
public void testUploadTimeouts() throws Throwable {
Duration partDuration = Duration.ofDays(1);
RequestFactory factory = RequestFactoryImpl.builder()
.withBucket("bucket")
.withPartUploadTimeout(partDuration)
.build();
String path = "path";
// A simple PUT
final PutObjectRequest put = factory.newPutObjectRequestBuilder(path,
defaultOptions(), 1024, false).build();
assertApiTimeouts(partDuration, put);
// multipart part
final UploadPartRequest upload = factory.newUploadPartRequestBuilder(path,
"1", 3, false, 128_000_000)
.build();
assertApiTimeouts(partDuration, upload);
}
@ParameterizedTest
@EnumSource(value = ChecksumAlgorithm.class, names = {"CRC32", "CRC32_C", "SHA1", "SHA256"})
public void testRequestFactoryWithChecksumAlgorithm(ChecksumAlgorithm checksumAlgorithm)
throws IOException {
String path = "path";
String path2 = "path2";
HeadObjectResponse md = HeadObjectResponse.builder().contentLength(128L).build();
RequestFactory factory = RequestFactoryImpl.builder()
.withBucket("bucket")
.withChecksumAlgorithm(checksumAlgorithm)
.build();
createFactoryObjects(factory);
final CopyObjectRequest copyObjectRequest = factory.newCopyObjectRequestBuilder(path,
path2, md).build();
Assertions.assertThat(copyObjectRequest.checksumAlgorithm()).isEqualTo(checksumAlgorithm);
final PutObjectRequest putObjectRequest = factory.newPutObjectRequestBuilder(path,
PutObjectOptions.defaultOptions(), 1024, false).build();
Assertions.assertThat(putObjectRequest.checksumAlgorithm()).isEqualTo(checksumAlgorithm);
final CreateMultipartUploadRequest multipartUploadRequest =
factory.newMultipartUploadRequestBuilder(path, null).build();
Assertions.assertThat(multipartUploadRequest.checksumAlgorithm()).isEqualTo(checksumAlgorithm);
final UploadPartRequest uploadPartRequest = factory.newUploadPartRequestBuilder(path,
"id", 2, true, 128_000_000).build();
Assertions.assertThat(uploadPartRequest.checksumAlgorithm()).isEqualTo(checksumAlgorithm);
}
@Test
public void testCompleteMultipartUploadRequestWithChecksumAlgorithmAndSSEC() throws IOException {
final byte[] encryptionKey = "encryptionKey".getBytes(StandardCharsets.UTF_8);
final String encryptionKeyBase64 = Base64.getEncoder()
.encodeToString(encryptionKey);
final String encryptionKeyMd5 = Md5Utils.md5AsBase64(encryptionKey);
final EncryptionSecrets encryptionSecrets = new EncryptionSecrets(S3AEncryptionMethods.SSE_C,
encryptionKeyBase64, null);
RequestFactory factory = RequestFactoryImpl.builder()
.withBucket("bucket")
.withChecksumAlgorithm(ChecksumAlgorithm.CRC32_C)
.withEncryptionSecrets(encryptionSecrets)
.build();
createFactoryObjects(factory);
PutObjectOptions putObjectOptions = new PutObjectOptions(
null,
null,
EnumSet.noneOf(WriteObjectFlags.class),
null);
final CompleteMultipartUploadRequest request =
factory.newCompleteMultipartUploadRequestBuilder("path", "1", new ArrayList<>(), putObjectOptions)
.build();
Assertions.assertThat(request.sseCustomerAlgorithm())
.isEqualTo(ServerSideEncryption.AES256.name());
Assertions.assertThat(request.sseCustomerKey()).isEqualTo(encryptionKeyBase64);
Assertions.assertThat(request.sseCustomerKeyMD5()).isEqualTo(encryptionKeyMd5);
}
}
| CountRequests |
java | apache__flink | flink-end-to-end-tests/flink-end-to-end-tests-common/src/test/java/org/apache/flink/dist/DynamicParameterITCase.java | {
"start": 6610,
"end": 7080
} | class ____ implements Predicate<String> {
private boolean inProgramArguments = false;
@Override
public boolean test(String s) {
if (s.contains("Program Arguments:")) {
inProgramArguments = true;
return false;
}
if (s.contains("Classpath:")) {
inProgramArguments = false;
}
return inProgramArguments;
}
}
}
| ProgramArgumentsFilter |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java | {
"start": 1011,
"end": 2827
} | class ____ extends EventObject {
private final String key;
private final String group;
private final String content;
private final ConfigChangeType changeType;
public ConfigChangedEvent(String key, String group, String content) {
this(key, group, content, ConfigChangeType.MODIFIED);
}
public ConfigChangedEvent(String key, String group, String content, ConfigChangeType changeType) {
super(key + "," + group);
this.key = key;
this.group = group;
this.content = content;
this.changeType = changeType;
}
public String getKey() {
return key;
}
public String getGroup() {
return group;
}
public String getContent() {
return content;
}
public ConfigChangeType getChangeType() {
return changeType;
}
@Override
public String toString() {
return "ConfigChangedEvent{" + "key='"
+ key + '\'' + ", group='"
+ group + '\'' + ", content='"
+ content + '\'' + ", changeType="
+ changeType + "} "
+ super.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ConfigChangedEvent)) {
return false;
}
ConfigChangedEvent that = (ConfigChangedEvent) o;
return Objects.equals(getKey(), that.getKey())
&& Objects.equals(getGroup(), that.getGroup())
&& Objects.equals(getContent(), that.getContent())
&& getChangeType() == that.getChangeType();
}
@Override
public int hashCode() {
return Objects.hash(getKey(), getGroup(), getContent(), getChangeType());
}
}
| ConfigChangedEvent |
java | quarkusio__quarkus | extensions/vertx/deployment/src/main/java/io/quarkus/vertx/core/deployment/CoreVertxBuildItem.java | {
"start": 170,
"end": 425
} | class ____ extends SimpleBuildItem {
private final Supplier<Vertx> vertx;
public CoreVertxBuildItem(Supplier<Vertx> vertx) {
this.vertx = vertx;
}
public Supplier<Vertx> getVertx() {
return vertx;
}
}
| CoreVertxBuildItem |
java | grpc__grpc-java | cronet/src/test/java/io/grpc/cronet/CronetWritableBufferAllocatorTest.java | {
"start": 838,
"end": 1445
} | class ____ {
@Test
public void testAllocate() throws Exception {
CronetWritableBufferAllocator allocator = new CronetWritableBufferAllocator();
WritableBuffer buffer = allocator.allocate(1000);
assertEquals(1000, buffer.writableBytes());
}
@Test
public void testAllocateLargeBuffer() throws Exception {
CronetWritableBufferAllocator allocator = new CronetWritableBufferAllocator();
// Ask for 1GB
WritableBuffer buffer = allocator.allocate(1024 * 1024 * 1024);
// Only get 1MB
assertEquals(1024 * 1024, buffer.writableBytes());
}
}
| CronetWritableBufferAllocatorTest |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/AbstractInitializableBeanDefinition.java | {
"start": 113349,
"end": 113490
} | class ____ all method reference information.
*/
@Internal
@SuppressWarnings("VisibilityModifier")
public static final | containing |
java | apache__camel | components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherUnits.java | {
"start": 913,
"end": 962
} | enum ____ {
IMPERIAL,
METRIC
}
| WeatherUnits |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/DefaultJdbcClient.java | {
"start": 12260,
"end": 12769
} | class ____<T extends @Nullable Object> implements MappedQuerySpec<T> {
private final RowMapper<T> rowMapper;
public IndexedParamMappedQuerySpec(RowMapper<T> rowMapper) {
this.rowMapper = rowMapper;
}
@Override
public Stream<T> stream() {
return classicOps.queryForStream(sql, this.rowMapper, indexedParams.toArray());
}
@Override
public List<T> list() {
return classicOps.query(sql, this.rowMapper, indexedParams.toArray());
}
}
private | IndexedParamMappedQuerySpec |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/azureopenai/AzureOpenAiSecretSettingsTests.java | {
"start": 1218,
"end": 8376
} | class ____ extends AbstractBWCWireSerializationTestCase<AzureOpenAiSecretSettings> {
public static AzureOpenAiSecretSettings createRandom() {
boolean isApiKeyNotEntraId = randomBoolean();
return new AzureOpenAiSecretSettings(
isApiKeyNotEntraId ? randomSecureStringOfLength(15) : null,
isApiKeyNotEntraId == false ? randomSecureStringOfLength(15) : null
);
}
public void testNewSecretSettingsApiKey() {
AzureOpenAiSecretSettings initialSettings = createRandom();
AzureOpenAiSecretSettings newSettings = new AzureOpenAiSecretSettings(randomSecureStringOfLength(15), null);
AzureOpenAiSecretSettings finalSettings = (AzureOpenAiSecretSettings) initialSettings.newSecretSettings(
Map.of(API_KEY, newSettings.apiKey().toString())
);
assertEquals(newSettings, finalSettings);
}
public void testNewSecretSettingsEntraId() {
AzureOpenAiSecretSettings initialSettings = createRandom();
AzureOpenAiSecretSettings newSettings = new AzureOpenAiSecretSettings(null, randomSecureStringOfLength(15));
AzureOpenAiSecretSettings finalSettings = (AzureOpenAiSecretSettings) initialSettings.newSecretSettings(
Map.of(ENTRA_ID, newSettings.entraId().toString())
);
assertEquals(newSettings, finalSettings);
}
public void testFromMap_ApiKey_Only() {
var serviceSettings = AzureOpenAiSecretSettings.fromMap(new HashMap<>(Map.of(AzureOpenAiSecretSettings.API_KEY, "abc")));
assertThat(new AzureOpenAiSecretSettings(new SecureString("abc".toCharArray()), null), is(serviceSettings));
}
public void testFromMap_EntraId_Only() {
var serviceSettings = AzureOpenAiSecretSettings.fromMap(new HashMap<>(Map.of(ENTRA_ID, "xyz")));
assertThat(new AzureOpenAiSecretSettings(null, new SecureString("xyz".toCharArray())), is(serviceSettings));
}
public void testFromMap_ReturnsNull_WhenMapIsNull() {
assertNull(AzureOpenAiSecretSettings.fromMap(null));
}
public void testFromMap_MissingApiKeyAndEntraId_ThrowsError() {
var thrownException = expectThrows(ValidationException.class, () -> AzureOpenAiSecretSettings.fromMap(new HashMap<>()));
assertThat(
thrownException.getMessage(),
containsString(
Strings.format(
"[secret_settings] must have either the [%s] or the [%s] key set",
AzureOpenAiSecretSettings.API_KEY,
ENTRA_ID
)
)
);
}
public void testFromMap_HasBothApiKeyAndEntraId_ThrowsError() {
var mapValues = getAzureOpenAiSecretSettingsMap("apikey", "entraid");
var thrownException = expectThrows(ValidationException.class, () -> AzureOpenAiSecretSettings.fromMap(mapValues));
assertThat(
thrownException.getMessage(),
containsString(
Strings.format(
"[secret_settings] must have only one of the [%s] or the [%s] key set",
AzureOpenAiSecretSettings.API_KEY,
ENTRA_ID
)
)
);
}
public void testFromMap_EmptyApiKey_ThrowsError() {
var thrownException = expectThrows(
ValidationException.class,
() -> AzureOpenAiSecretSettings.fromMap(new HashMap<>(Map.of(AzureOpenAiSecretSettings.API_KEY, "")))
);
assertThat(
thrownException.getMessage(),
containsString(
Strings.format(
"[secret_settings] Invalid value empty string. [%s] must be a non-empty string",
AzureOpenAiSecretSettings.API_KEY
)
)
);
}
public void testFromMap_EmptyEntraId_ThrowsError() {
var thrownException = expectThrows(
ValidationException.class,
() -> AzureOpenAiSecretSettings.fromMap(new HashMap<>(Map.of(ENTRA_ID, "")))
);
assertThat(
thrownException.getMessage(),
containsString(Strings.format("[secret_settings] Invalid value empty string. [%s] must be a non-empty string", ENTRA_ID))
);
}
// test toXContent
public void testToXContext_WritesApiKeyOnlyWhenEntraIdIsNull() throws IOException {
var testSettings = new AzureOpenAiSecretSettings(new SecureString("apikey"), null);
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
testSettings.toXContent(builder, null);
String xContentResult = Strings.toString(builder);
var expectedResult = Strings.format("{\"%s\":\"apikey\"}", API_KEY);
assertThat(xContentResult, is(expectedResult));
}
public void testToXContext_WritesEntraIdOnlyWhenApiKeyIsNull() throws IOException {
var testSettings = new AzureOpenAiSecretSettings(null, new SecureString("entraid"));
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
testSettings.toXContent(builder, null);
String xContentResult = Strings.toString(builder);
var expectedResult = Strings.format("{\"%s\":\"entraid\"}", ENTRA_ID);
assertThat(xContentResult, is(expectedResult));
}
@Override
protected Writeable.Reader<AzureOpenAiSecretSettings> instanceReader() {
return AzureOpenAiSecretSettings::new;
}
@Override
protected AzureOpenAiSecretSettings createTestInstance() {
return createRandom();
}
@Override
protected AzureOpenAiSecretSettings mutateInstance(AzureOpenAiSecretSettings instance) throws IOException {
SecureString apiKey = instance.apiKey();
SecureString entraId = instance.entraId();
if (apiKey == null || entraId == null) {
if (randomBoolean()) {
apiKey = randomValueOtherThan(instance.apiKey(), () -> randomSecureStringOfLength(15));
} else {
entraId = randomValueOtherThan(instance.entraId(), () -> randomSecureStringOfLength(15));
}
} else {
if (randomBoolean()) {
apiKey = randomBoolean() ? null : randomValueOtherThan(instance.apiKey(), () -> randomSecureStringOfLength(15));
} else {
entraId = randomBoolean() ? null : randomValueOtherThan(instance.entraId(), () -> randomSecureStringOfLength(15));
}
}
return new AzureOpenAiSecretSettings(apiKey, entraId);
}
@Override
protected AzureOpenAiSecretSettings mutateInstanceForVersion(AzureOpenAiSecretSettings instance, TransportVersion version) {
return instance;
}
public static Map<String, Object> getAzureOpenAiSecretSettingsMap(@Nullable String apiKey, @Nullable String entraId) {
var map = new HashMap<String, Object>();
if (apiKey != null) {
map.put(AzureOpenAiSecretSettings.API_KEY, apiKey);
}
if (entraId != null) {
map.put(ENTRA_ID, entraId);
}
return map;
}
}
| AzureOpenAiSecretSettingsTests |
java | spring-projects__spring-framework | spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJEnableCachingIsolatedTests.java | {
"start": 7389,
"end": 7768
} | class ____ implements CachingConfigurer {
@Override
@Bean
public CacheManager cacheManager() {
return new NoOpCacheManager();
}
@Override
@Bean
public KeyGenerator keyGenerator() {
return new SomeKeyGenerator();
}
@Override
@Bean
public CacheResolver cacheResolver() {
return new NamedCacheResolver(cacheManager(), "foo");
}
}
}
| FullCachingConfig |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/dynamic/DefaultMethodParametersAccessor.java | {
"start": 560,
"end": 2896
} | class ____ implements MethodParametersAccessor {
private final Parameters<? extends Parameter> parameters;
private final List<Object> values;
DefaultMethodParametersAccessor(Parameters<? extends Parameter> parameters, Object... values) {
LettuceAssert.notNull(parameters, "Parameters must not be null");
LettuceAssert.notNull(values, "Values must not be null");
this.parameters = parameters;
this.values = Arrays.asList(values);
}
public int getParameterCount() {
return parameters.getBindableParameters().size();
}
@Override
public Object getBindableValue(int index) {
return values.get(parameters.getBindableParameter(index).getParameterIndex());
}
@Override
public boolean isKey(int index) {
return parameters.getBindableParameter(index).findAnnotation(Key.class) != null;
}
@Override
public boolean isValue(int index) {
return parameters.getBindableParameter(index).findAnnotation(Value.class) != null;
}
@Override
public Iterator<Object> iterator() {
return new BindableParameterIterator(this);
}
@Override
public int resolveParameterIndex(String name) {
List<? extends Parameter> bindableParameters = parameters.getBindableParameters();
for (int i = 0; i < bindableParameters.size(); i++) {
if (name.equals(bindableParameters.get(i).getName())) {
return i;
}
}
throw new IllegalArgumentException(String.format("Cannot resolve named parameter %s", name));
}
public Parameters<? extends Parameter> getParameters() {
return parameters;
}
@Override
public boolean isBindableNullValue(int index) {
Parameter bindableParameter = parameters.getBindableParameter(index);
if (bindableParameter.isAssignableTo(Limit.class) || bindableParameter.isAssignableTo(io.lettuce.core.Value.class)
|| bindableParameter.isAssignableTo(KeyValue.class) || bindableParameter.isAssignableTo(ScoredValue.class)
|| bindableParameter.isAssignableTo(GeoCoordinates.class) || bindableParameter.isAssignableTo(Range.class)) {
return false;
}
return true;
}
/**
* Iterator | DefaultMethodParametersAccessor |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/support/opds/udf/SqlSyntaxCheck.java | {
"start": 350,
"end": 1257
} | class ____ extends UDF {
public Boolean evaluate(String sql) {
return evaluate(sql, null, false);
}
public Boolean evaluate(String sql, String dbTypeName) {
return evaluate(sql, dbTypeName, false);
}
public Boolean evaluate(String sql, String dbTypeName, boolean throwError) {
if (sql == null || sql.length() == 0) {
return null;
}
DbType dbType = dbTypeName == null ? null : DbType.valueOf(dbTypeName);
try {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType);
List<SQLStatement> statementList = parser.parseStatementList();
return true;
} catch (ParserException ex) {
if (throwError) {
throw new IllegalArgumentException("error sql : \n" + sql, ex);
}
return false;
}
}
}
| SqlSyntaxCheck |
java | google__guava | android/guava/src/com/google/common/collect/CollectSpliterators.java | {
"start": 18996,
"end": 19683
} | class ____<InElementT extends @Nullable Object>
extends FlatMapSpliteratorOfPrimitive<InElementT, Integer, IntConsumer, Spliterator.OfInt>
implements Spliterator.OfInt {
FlatMapSpliteratorOfInt(
Spliterator.@Nullable OfInt prefix,
Spliterator<InElementT> from,
Function<? super InElementT, Spliterator.@Nullable OfInt> function,
int characteristics,
long estimatedSize) {
super(prefix, from, function, FlatMapSpliteratorOfInt::new, characteristics, estimatedSize);
}
}
/** Implementation of {@link #flatMapToLong}. */
@IgnoreJRERequirement // see earlier comment about redundancy
static final | FlatMapSpliteratorOfInt |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/io/parsing/ResolvingGrammarGenerator.java | {
"start": 1569,
"end": 13569
} | class ____ extends ValidatingGrammarGenerator {
static {
Accessor.setAccessor(new ResolvingGrammarGeneratorAccessor() {
@Override
protected void encode(Encoder e, Schema s, JsonNode n) throws IOException {
ResolvingGrammarGenerator.encode(e, s, n);
}
});
}
/**
* Resolves the writer schema <tt>writer</tt> and the reader schema
* <tt>reader</tt> and returns the start symbol for the grammar generated.
*
* @param writer The schema used by the writer
* @param reader The schema used by the reader
* @return The start symbol for the resolving grammar
* @throws IOException
*/
public final Symbol generate(Schema writer, Schema reader) throws IOException {
Resolver.Action r = Resolver.resolve(writer, reader);
return Symbol.root(generate(r, new HashMap<>()));
}
/**
* Takes a {@link Resolver.Action} for resolving two schemas and returns the
* start symbol for a grammar that implements that resolution. If the action is
* for a record and there's already a symbol for that record in <tt>seen</tt>,
* then that symbol is returned. Otherwise a new symbol is generated and
* returned.
*
* @param action The resolver to be implemented
* @param seen The <Action> to symbol map of start symbols of resolving
* grammars so far.
* @return The start symbol for the resolving grammar
* @throws IOException
*/
private Symbol generate(Resolver.Action action, Map<Object, Symbol> seen) throws IOException {
if (action instanceof Resolver.DoNothing) {
return simpleGen(action.writer, seen);
} else if (action instanceof Resolver.ErrorAction) {
return Symbol.error(action.toString());
} else if (action instanceof Resolver.Skip) {
return Symbol.skipAction(simpleGen(action.writer, seen));
} else if (action instanceof Resolver.Promote) {
return Symbol.resolve(simpleGen(action.writer, seen), simpleGen(action.reader, seen));
} else if (action instanceof Resolver.ReaderUnion) {
Resolver.ReaderUnion ru = (Resolver.ReaderUnion) action;
Symbol s = generate(ru.actualAction, seen);
return Symbol.seq(Symbol.unionAdjustAction(ru.firstMatch, s), Symbol.UNION);
} else if (action.writer.getType() == Schema.Type.ARRAY) {
Symbol es = generate(((Resolver.Container) action).elementAction, seen);
return Symbol.seq(Symbol.repeat(Symbol.ARRAY_END, es), Symbol.ARRAY_START);
} else if (action.writer.getType() == Schema.Type.MAP) {
Symbol es = generate(((Resolver.Container) action).elementAction, seen);
return Symbol.seq(Symbol.repeat(Symbol.MAP_END, es, Symbol.STRING), Symbol.MAP_START);
} else if (action.writer.getType() == Schema.Type.UNION) {
if (((Resolver.WriterUnion) action).unionEquiv) {
return simpleGen(action.reader, seen);
}
Resolver.Action[] branches = ((Resolver.WriterUnion) action).actions;
Symbol[] symbols = new Symbol[branches.length];
String[] labels = new String[branches.length];
int i = 0;
for (Resolver.Action branch : branches) {
symbols[i] = generate(branch, seen);
labels[i] = action.writer.getTypes().get(i).getFullName();
i++;
}
return Symbol.seq(Symbol.alt(symbols, labels), Symbol.WRITER_UNION_ACTION);
} else if (action instanceof Resolver.EnumAdjust) {
Resolver.EnumAdjust e = (Resolver.EnumAdjust) action;
Object[] adjs = new Object[e.adjustments.length];
for (int i = 0; i < adjs.length; i++) {
adjs[i] = (0 <= e.adjustments[i] ? Integer.valueOf(e.adjustments[i])
: "No match for " + e.writer.getEnumSymbols().get(i));
}
return Symbol.seq(Symbol.enumAdjustAction(e.reader.getEnumSymbols().size(), adjs), Symbol.ENUM);
} else if (action instanceof Resolver.RecordAdjust) {
Symbol result = seen.get(action);
if (result == null) {
final Resolver.RecordAdjust ra = (Resolver.RecordAdjust) action;
int defaultCount = ra.readerOrder.length - ra.firstDefault;
int count = 1 + ra.fieldActions.length + 3 * defaultCount;
final Symbol[] production = new Symbol[count];
result = Symbol.seq(production);
seen.put(action, result);
production[--count] = Symbol.fieldOrderAction(ra.readerOrder);
final Resolver.Action[] actions = ra.fieldActions;
for (Resolver.Action wfa : actions) {
production[--count] = generate(wfa, seen);
}
for (int i = ra.firstDefault; i < ra.readerOrder.length; i++) {
final Schema.Field rf = ra.readerOrder[i];
byte[] bb = getBinary(rf.schema(), Accessor.defaultValue(rf));
production[--count] = Symbol.defaultStartAction(bb);
production[--count] = simpleGen(rf.schema(), seen);
production[--count] = Symbol.DEFAULT_END_ACTION;
}
}
return result;
}
throw new IllegalArgumentException("Unrecognized Resolver.Action: " + action);
}
private Symbol simpleGen(Schema s, Map<Object, Symbol> seen) {
switch (s.getType()) {
case NULL:
return Symbol.NULL;
case BOOLEAN:
return Symbol.BOOLEAN;
case INT:
return Symbol.INT;
case LONG:
return Symbol.LONG;
case FLOAT:
return Symbol.FLOAT;
case DOUBLE:
return Symbol.DOUBLE;
case BYTES:
return Symbol.BYTES;
case STRING:
return Symbol.STRING;
case FIXED:
return Symbol.seq(Symbol.intCheckAction(s.getFixedSize()), Symbol.FIXED);
case ENUM:
return Symbol.seq(Symbol.enumAdjustAction(s.getEnumSymbols().size(), null), Symbol.ENUM);
case ARRAY:
return Symbol.seq(Symbol.repeat(Symbol.ARRAY_END, simpleGen(s.getElementType(), seen)), Symbol.ARRAY_START);
case MAP:
return Symbol.seq(Symbol.repeat(Symbol.MAP_END, simpleGen(s.getValueType(), seen), Symbol.STRING),
Symbol.MAP_START);
case UNION: {
final List<Schema> subs = s.getTypes();
final Symbol[] symbols = new Symbol[subs.size()];
final String[] labels = new String[subs.size()];
int i = 0;
for (Schema b : s.getTypes()) {
symbols[i] = simpleGen(b, seen);
labels[i++] = b.getFullName();
}
return Symbol.seq(Symbol.alt(symbols, labels), Symbol.UNION);
}
case RECORD: {
Symbol result = seen.get(s);
if (result == null) {
final Symbol[] production = new Symbol[s.getFields().size() + 1];
result = Symbol.seq(production);
seen.put(s, result);
int i = production.length;
production[--i] = Symbol.fieldOrderAction(s.getFields().toArray(new Schema.Field[0]));
for (Field f : s.getFields()) {
production[--i] = simpleGen(f.schema(), seen);
}
// FieldOrderAction is needed even though the field-order hasn't changed,
// because the _reader_ doesn't know the field order hasn't changed, and
// thus it will probably call {@ ResolvingDecoder.fieldOrder} to find out.
}
return result;
}
default:
throw new IllegalArgumentException("Unexpected schema: " + s);
}
}
private final static EncoderFactory ENCODER_FACTORY = new EncoderFactory().configureBufferSize(32);
/**
* Returns the Avro binary encoded version of <tt>n</tt> according to the schema
* <tt>s</tt>.
*
* @param s The schema for encoding
* @param n The Json node that has the value to be encoded.
* @return The binary encoded version of <tt>n</tt>.
* @throws IOException
*/
private static byte[] getBinary(Schema s, JsonNode n) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Encoder e = ENCODER_FACTORY.binaryEncoder(out, null);
encode(e, s, n);
e.flush();
return out.toByteArray();
}
/**
* Encodes the given Json node <tt>n</tt> on to the encoder <tt>e</tt> according
* to the schema <tt>s</tt>.
*
* @param e The encoder to encode into.
* @param s The schema for the object being encoded.
* @param n The Json node to encode.
* @throws IOException
*/
public static void encode(Encoder e, Schema s, JsonNode n) throws IOException {
switch (s.getType()) {
case RECORD:
for (Field f : s.getFields()) {
String name = f.name();
JsonNode v = n.get(name);
if (v == null) {
v = Accessor.defaultValue(f);
}
if (v == null) {
throw new AvroTypeException("No default value for: " + name);
}
encode(e, f.schema(), v);
}
break;
case ENUM:
e.writeEnum(s.getEnumOrdinal(n.textValue()));
break;
case ARRAY:
e.writeArrayStart();
e.setItemCount(n.size());
Schema i = s.getElementType();
for (JsonNode node : n) {
e.startItem();
encode(e, i, node);
}
e.writeArrayEnd();
break;
case MAP:
e.writeMapStart();
e.setItemCount(n.size());
Schema v = s.getValueType();
for (Iterator<String> it = n.fieldNames(); it.hasNext();) {
e.startItem();
String key = it.next();
e.writeString(key);
encode(e, v, n.get(key));
}
e.writeMapEnd();
break;
case UNION:
int correctIndex = 0;
List<Schema> innerTypes = s.getTypes();
while (correctIndex < innerTypes.size() && !isCompatible(innerTypes.get(correctIndex).getType(), n)) {
correctIndex++;
}
if (correctIndex >= innerTypes.size()) {
throw new AvroTypeException("Not compatible default value for union: " + n);
}
e.writeIndex(correctIndex);
encode(e, innerTypes.get(correctIndex), n);
break;
case FIXED:
if (!n.isTextual())
throw new AvroTypeException("Non-string default value for fixed: " + n);
byte[] bb = n.textValue().getBytes(StandardCharsets.ISO_8859_1);
if (bb.length != s.getFixedSize()) {
bb = Arrays.copyOf(bb, s.getFixedSize());
}
e.writeFixed(bb);
break;
case STRING:
if (!n.isTextual())
throw new AvroTypeException("Non-string default value for string: " + n);
e.writeString(n.textValue());
break;
case BYTES:
if (!n.isTextual())
throw new AvroTypeException("Non-string default value for bytes: " + n);
e.writeBytes(n.textValue().getBytes(StandardCharsets.ISO_8859_1));
break;
case INT:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for int: " + n);
e.writeInt(n.intValue());
break;
case LONG:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for long: " + n);
e.writeLong(n.longValue());
break;
case FLOAT:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for float: " + n);
e.writeFloat((float) n.doubleValue());
break;
case DOUBLE:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for double: " + n);
e.writeDouble(n.doubleValue());
break;
case BOOLEAN:
if (!n.isBoolean())
throw new AvroTypeException("Non-boolean default for boolean: " + n);
e.writeBoolean(n.booleanValue());
break;
case NULL:
if (!n.isNull())
throw new AvroTypeException("Non-null default value for null type: " + n);
e.writeNull();
break;
}
}
private static boolean isCompatible(Schema.Type stype, JsonNode value) {
switch (stype) {
case RECORD:
case ENUM:
case ARRAY:
case MAP:
case UNION:
return true;
case FIXED:
case STRING:
case BYTES:
return value.isTextual();
case INT:
case LONG:
case FLOAT:
case DOUBLE:
return value.isNumber();
case BOOLEAN:
return value.isBoolean();
case NULL:
return value.isNull();
}
return true;
}
}
| ResolvingGrammarGenerator |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/workflow/DeleteRefreshWorkflow.java | {
"start": 1338,
"end": 1825
} | class ____<T extends RefreshHandler> implements RefreshWorkflow {
private final T refreshHandler;
public DeleteRefreshWorkflow(T refreshHandler) {
this.refreshHandler = refreshHandler;
}
/**
* Return {@link RefreshHandler} from corresponding {@link WorkflowScheduler} which provides
* meta info to points to the refresh workflow in scheduler service.
*/
public T getRefreshHandler() {
return refreshHandler;
}
}
| DeleteRefreshWorkflow |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/dto/generated/MSPTest.java | {
"start": 1549,
"end": 2126
} | class ____ extends AbstractSObjectBase {
public MSPTest() {
getAttributes().setType("MSPTest");
}
private MSPEnum[] MspField;
@JsonProperty("MspField")
@JsonSerialize(using = MultiSelectPicklistSerializer.class)
@JsonInclude(value = Include.ALWAYS)
public MSPEnum[] getMspField() {
return MspField;
}
@JsonProperty("MspField")
@JsonDeserialize(using = MultiSelectPicklistDeserializer.class)
public void setMspField(MSPEnum[] mspField) {
this.MspField = mspField;
}
@JsonDeserialize
public | MSPTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/SealedTypesWithTypedSerializationTest.java | {
"start": 2216,
"end": 2623
} | class ____, written as main-level property name
*/
@Test
public void testSimpleClassAsProperty() throws Exception
{
Map<String,Object> result = writeAndMap(MAPPER, new Cat("Beelzebub", "tabby"));
assertEquals(3, result.size());
assertEquals("Beelzebub", result.get("name"));
assertEquals("tabby", result.get("furColor"));
// should we try customized | name |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java | {
"start": 1250,
"end": 2299
} | class ____ {
@Test
void testSunnyDayPathLogsCorrectly() throws Throwable {
MethodInvocation mi = mock();
given(mi.getMethod()).willReturn(String.class.getMethod("toString"));
given(mi.getThis()).willReturn(this);
Log log = mock();
SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
interceptor.invokeUnderTrace(mi, log);
verify(log, times(2)).trace(anyString());
}
@Test
void testExceptionPathStillLogsCorrectly() throws Throwable {
MethodInvocation mi = mock();
given(mi.getMethod()).willReturn(String.class.getMethod("toString"));
given(mi.getThis()).willReturn(this);
IllegalArgumentException exception = new IllegalArgumentException();
given(mi.proceed()).willThrow(exception);
Log log = mock();
final SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invokeUnderTrace(mi, log));
verify(log).trace(anyString());
verify(log).trace(anyString(), eq(exception));
}
}
| SimpleTraceInterceptorTests |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/async/utils/AsyncCatchFunction.java | {
"start": 6882,
"end": 7686
} | class ____ representing the exception type to catch
* @return a new {@code CompletableFuture} that completes with the result of applying
* the catch function, or propagates the original exception if it does not match
* the specified type
*/
@Override
default CompletableFuture<R> apply(
CompletableFuture<R> in, Class<E> eClazz) {
return in.handle((r, e) -> {
if (e == null) {
return in;
}
Throwable readException = unWarpCompletionException(e);
if (eClazz.isInstance(readException)) {
try {
return async(r, (E) readException);
} catch (IOException ex) {
throw warpCompletionException(ex);
}
}
throw warpCompletionException(e);
}).thenCompose(result -> result);
}
}
| object |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/protocol/xpack/graph/VertexRequest.java | {
"start": 1099,
"end": 7347
} | class ____ implements ToXContentObject, Writeable {
public static final int DEFAULT_SIZE = 5;
public static final int DEFAULT_MIN_DOC_COUNT = 3;
public static final int DEFAULT_SHARD_MIN_DOC_COUNT = 2;
private String fieldName;
private int size = DEFAULT_SIZE;
private Map<String, TermBoost> includes;
private Set<String> excludes;
private int minDocCount = DEFAULT_MIN_DOC_COUNT;
private int shardMinDocCount = DEFAULT_SHARD_MIN_DOC_COUNT;
public VertexRequest() {
}
void readFrom(StreamInput in) throws IOException {
fieldName = in.readString();
size = in.readVInt();
minDocCount = in.readVInt();
shardMinDocCount = in.readVInt();
int numIncludes = in.readVInt();
if (numIncludes > 0) {
includes = new HashMap<>();
for (int i = 0; i < numIncludes; i++) {
TermBoost tb = new TermBoost();
tb.readFrom(in);
includes.put(tb.term, tb);
}
}
int numExcludes = in.readVInt();
if (numExcludes > 0) {
excludes = new HashSet<>();
for (int i = 0; i < numExcludes; i++) {
excludes.add(in.readString());
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(fieldName);
out.writeVInt(size);
out.writeVInt(minDocCount);
out.writeVInt(shardMinDocCount);
if (includes != null) {
out.writeCollection(includes.values());
} else {
out.writeVInt(0);
}
if (excludes != null) {
out.writeStringCollection(excludes);
} else {
out.writeVInt(0);
}
}
public String fieldName() {
return fieldName;
}
public VertexRequest fieldName(String fieldName) {
this.fieldName = fieldName;
return this;
}
public int size() {
return size;
}
/**
* @param size The maximum number of terms that should be returned from this field as part of this {@link Hop}
*/
public VertexRequest size(int size) {
this.size = size;
return this;
}
public boolean hasIncludeClauses() {
return includes != null && includes.size() > 0;
}
public boolean hasExcludeClauses() {
return excludes != null && excludes.size() > 0;
}
/**
* Adds a term that should be excluded from results
* @param term A term to be excluded
*/
public void addExclude(String term) {
if (includes != null) {
throw new IllegalArgumentException("Cannot have both include and exclude clauses");
}
if (excludes == null) {
excludes = new HashSet<>();
}
excludes.add(term);
}
/**
* Adds a term to the set of allowed values - the boost defines the relative
* importance when pursuing connections in subsequent {@link Hop}s. The boost value
* appears as part of the query.
* @param term a required term
* @param boost an optional boost
*/
public void addInclude(String term, float boost) {
if (excludes != null) {
throw new IllegalArgumentException("Cannot have both include and exclude clauses");
}
if (includes == null) {
includes = new HashMap<>();
}
includes.put(term, new TermBoost(term, boost));
}
public TermBoost[] includeValues() {
return includes.values().toArray(new TermBoost[includes.size()]);
}
public SortedSet<BytesRef> includeValuesAsSortedSet() {
SortedSet<BytesRef> set = new TreeSet<>();
for (String include : includes.keySet()) {
set.add(new BytesRef(include));
}
return set;
}
public SortedSet<BytesRef> excludesAsSortedSet() {
SortedSet<BytesRef> set = new TreeSet<>();
for (String include : excludes) {
set.add(new BytesRef(include));
}
return set;
}
public int minDocCount() {
return minDocCount;
}
/**
* A "certainty" threshold which defines the weight-of-evidence required before
* a term found in this field is identified as a useful connection
*
* @param value The minimum number of documents that contain this term found in the samples used across all shards
*/
public VertexRequest minDocCount(int value) {
minDocCount = value;
return this;
}
public int shardMinDocCount() {
return Math.min(shardMinDocCount, minDocCount);
}
/**
* A "certainty" threshold which defines the weight-of-evidence required before
* a term found in this field is identified as a useful connection
*
* @param value The minimum number of documents that contain this term found in the samples used across all shards
*/
public VertexRequest shardMinDocCount(int value) {
shardMinDocCount = value;
return this;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("field", fieldName);
if (size != DEFAULT_SIZE) {
builder.field("size", size);
}
if (minDocCount != DEFAULT_MIN_DOC_COUNT) {
builder.field("min_doc_count", minDocCount);
}
if (shardMinDocCount != DEFAULT_SHARD_MIN_DOC_COUNT) {
builder.field("shard_min_doc_count", shardMinDocCount);
}
if (includes != null) {
builder.startArray("include");
for (TermBoost tb : includes.values()) {
builder.startObject();
builder.field("term", tb.term);
builder.field("boost", tb.boost);
builder.endObject();
}
builder.endArray();
}
if (excludes != null) {
builder.startArray("exclude");
for (String value : excludes) {
builder.value(value);
}
builder.endArray();
}
builder.endObject();
return builder;
}
}
| VertexRequest |
java | apache__flink | flink-filesystems/flink-hadoop-fs/src/main/java/org/apache/flink/runtime/fs/hdfs/BaseHadoopFsRecoverableFsDataOutputStream.java | {
"start": 1215,
"end": 2487
} | class ____
extends CommitterFromPersistRecoverableFsDataOutputStream<HadoopFsRecoverable> {
protected FileSystem fs;
protected Path targetFile;
protected Path tempFile;
protected FSDataOutputStream out;
// In ABFS outputstream we need to add this to the current pos
protected long initialFileSize = 0;
public long getPos() throws IOException {
return out.getPos();
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
@Override
public void flush() throws IOException {
out.hflush();
}
@Override
public void sync() throws IOException {
out.hflush();
out.hsync();
}
@Override
public HadoopFsRecoverable persist() throws IOException {
sync();
return createHadoopFsRecoverable(getPos());
}
public HadoopFsRecoverable createHadoopFsRecoverable(long pos) {
return new HadoopFsRecoverable(targetFile, tempFile, pos + initialFileSize);
}
@Override
public void close() throws IOException {
out.close();
}
}
| BaseHadoopFsRecoverableFsDataOutputStream |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/PathParserException.java | {
"start": 864,
"end": 1222
} | class ____ extends RestException {
private static final long serialVersionUID = 1L;
public PathParserException(Messages message, Object... arguments) {
super(message, arguments);
}
public PathParserException(Messages message, Throwable cause, Object... arguments) {
super(cause, message, arguments);
}
}
| PathParserException |
java | apache__camel | components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaWithDBTransactionIT.java | {
"start": 2017,
"end": 15686
} | class ____ extends BaseKafkaTestSupport {
private static final String TOPIC_TX_1 = "transaction-1";
private static final String TOPIC_TX_2 = "transaction-2";
private static final String TOPIC_TX_3 = "transaction-3";
private static final String TOPIC_TX_4 = "transaction-4";
private static final String TOPIC_TX_5 = "transaction-5";
private static final String INSERT_SQL_1 = "insert into foo1(name) values (:#word)";
private static final String INSERT_SQL_2 = "insert into foo2(name) values (:#word)";
private static final String INSERT_SQL_3 = "insert into foo3(name) values (:#word)";
private static final String INSERT_SQL_4 = "insert into foo4(name) values (:#word)";
private static final String INSERT_SQL_5 = "insert into foo5(name) values (:#word)";
private static KafkaConsumer<String, String> stringsConsumerConn;
private static EmbeddedDatabase db;
private static JdbcTemplate jdbc;
protected volatile CamelContext context;
@BeforeAll
public static void before() {
stringsConsumerConn = createStringKafkaConsumer("KafkaWithDBTransactionIT");
}
@ContextFixture
public void configureContext(CamelContext context) {
db = new EmbeddedDatabaseBuilder()
.setName(getClass().getSimpleName())
.setType(EmbeddedDatabaseType.H2).build();
context.getRegistry().bind("testdb", db);
DataSourceTransactionManager txMgr = new DataSourceTransactionManager();
txMgr.setDataSource(db);
context.getRegistry().bind("txManager", txMgr);
jdbc = new JdbcTemplate(db);
jdbc.execute("create table foo1(id SERIAL PRIMARY KEY,name VARCHAR (10) NOT NULL unique);");
jdbc.execute("create table foo2(id SERIAL PRIMARY KEY,name VARCHAR (10) NOT NULL unique);");
jdbc.execute("create table foo3(id SERIAL PRIMARY KEY,name VARCHAR (10) NOT NULL unique);");
jdbc.execute("create table foo4(id SERIAL PRIMARY KEY,name VARCHAR (10) NOT NULL unique);");
jdbc.execute("create table foo5(id SERIAL PRIMARY KEY,name VARCHAR (10) NOT NULL unique);");
}
@AfterAll
public static void after() {
// clean all test topics
final List<String> topics = new ArrayList<>();
topics.add(TOPIC_TX_1);
topics.add(TOPIC_TX_2);
topics.add(TOPIC_TX_3);
topics.add(TOPIC_TX_4);
topics.add(TOPIC_TX_5);
kafkaAdminClient.deleteTopics(topics);
if (db != null) {
db.shutdown();
}
}
// No transaction - sends 1 message to kafka and 1 insert to the table
@Test
public void noTransactionProducerWithDBLast() throws Exception {
contextExtension.getContext().addRoutes(new RouteBuilder() {
public void configure() {
from("direct:startNoTx")
.to("kafka:" + TOPIC_TX_1)
.to("sql:" + INSERT_SQL_1);
}
});
ProducerTemplate producer = contextExtension.getProducerTemplate();
String bodyContent = "foobar";
producer.sendBodyAndHeader("direct:startNoTx", bodyContent, "word", bodyContent);
ConsumerRecords<String, String> records = getMessagesFromTopic(stringsConsumerConn, TOPIC_TX_1);
// verify kafka topic
assertEquals(1, records.count());
assertEquals(bodyContent, records.iterator().next().value());
// verify sql content
long count = jdbc.queryForObject("select count(*) from foo1 where name = '" + bodyContent + "'", Long.class);
assertEquals(1, count);
}
/*
* No transaction - sends two duplicate messages, for the second one the DB insert will fail, in the end there will
* be 2 messages in the topic and 1 row in the table, because there is no transaction, there is no rollback of the
* duplicated operation.
*/
@Test
public void noTransactionProducerDuplicatedWithDBLast() throws Exception {
contextExtension.getContext().addRoutes(new RouteBuilder() {
public void configure() {
from("direct:startNoTx2")
.onException(Exception.class)
.handled(true)
.log("Expected error when trying to insert duplicate values in the unique column.")
.end()
.to("kafka:" + TOPIC_TX_2)
.to("sql:" + INSERT_SQL_2);
}
});
ProducerTemplate producer = contextExtension.getProducerTemplate();
String bodyContent = "foobar";
producer.sendBodyAndHeader("direct:startNoTx2", bodyContent, "word", bodyContent);
producer.sendBodyAndHeader("direct:startNoTx2", bodyContent, "word", bodyContent);
ConsumerRecords<String, String> records = getMessagesFromTopic(stringsConsumerConn, TOPIC_TX_2);
// verify kafka topic
assertEquals(2, records.count());
assertEquals(bodyContent, records.iterator().next().value());
// verify sql content
long count = jdbc.queryForObject("select count(*) from foo2 where name = '" + bodyContent + "'", Long.class);
assertEquals(1, count);
}
/*
* With transaction - sends two duplicate messages, for the second one the DB insert will fail and the rollback will
* take place. in this case the SQL operation is the last endpoint after the message was sent to the kafka topic.
*/
// @Test
@ParameterizedTest
@ValueSource(strings = { "transacted=true", "transactionalId=my-foo1", "additionalProperties[transactional.id]=my-foo2" })
public void transactionProducerWithDBLast(String txParam) throws Exception {
String startEndpoint = "direct:startTxDBLast";
contextExtension.getContext().addRoutes(new RouteBuilder() {
public void configure() {
from(startEndpoint).routeId("tx-kafka-db-last")
.onException(Exception.class)
.handled(true)
.markRollbackOnly()
.end()
.to("kafka:" + TOPIC_TX_3 + "?" + txParam)
.to("sql:" + INSERT_SQL_3);
}
});
ProducerTemplate producer = contextExtension.getProducerTemplate();
String bodyContent = "foobar";
producer.sendBodyAndHeader(startEndpoint, bodyContent, "word", bodyContent);
producer.sendBodyAndHeader(startEndpoint, bodyContent, "word", bodyContent);
ConsumerRecords<String, String> records = getMessagesFromTopic(stringsConsumerConn, TOPIC_TX_3);
// verify kafka topic
assertEquals(1, records.count());
assertEquals(bodyContent, records.iterator().next().value());
// verify sql content
long count = jdbc.queryForObject("select count(*) from foo3 where name = '" + bodyContent + "'", Long.class);
assertEquals(1, count);
}
/**
* With transaction - Uses multiple kafka producers to send duplicate messages. One route with transacted=true and
* the other with no transactions.
*/
// @Test
@Test
public void transactionMultipleProducersWithDBLast() throws Exception {
contextExtension.getContext().addRoutes(new RouteBuilder() {
public void configure() {
from("direct:startTxDBLast2a")
.onException(Exception.class)
.handled(true)
.markRollbackOnly()
.end()
.to("kafka:" + TOPIC_TX_5 + "?transacted=true")
.to("sql:" + INSERT_SQL_5);
from("direct:startTxDBLast2b")
.onException(Exception.class)
.handled(true)
.markRollbackOnly()
.end()
.to("kafka:" + TOPIC_TX_5 + "?transacted=true")
.to("sql:" + INSERT_SQL_5);
from("direct:startTxDBLast2c")
.onException(Exception.class)
.handled(true)
.markRollbackOnly()
.end()
.to("kafka:" + TOPIC_TX_5)
.to("sql:" + INSERT_SQL_5);
}
});
ProducerTemplate producer = contextExtension.getProducerTemplate();
String bodyContent1 = "foobar1";
String bodyContent2 = "foobar2";
String bodyContent3 = "foobar3";
producer.sendBodyAndHeader("direct:startTxDBLast2a", bodyContent1, "word", bodyContent1);
producer.sendBodyAndHeader("direct:startTxDBLast2a", bodyContent1, "word", bodyContent1);
producer.sendBodyAndHeader("direct:startTxDBLast2b", bodyContent2, "word", bodyContent2);
producer.sendBodyAndHeader("direct:startTxDBLast2b", bodyContent2, "word", bodyContent2);
producer.sendBodyAndHeader("direct:startTxDBLast2c", bodyContent3, "word", bodyContent3);
producer.sendBodyAndHeader("direct:startTxDBLast2c", bodyContent3, "word", bodyContent3);
ConsumerRecords<String, String> records = getMessagesFromTopic(stringsConsumerConn, TOPIC_TX_5);
// verify kafka topic
Iterator<ConsumerRecord<String, String>> iter = records.iterator();
assertEquals(4, records.count());
assertEquals(bodyContent1, iter.next().value());
assertEquals(bodyContent2, iter.next().value());
assertEquals(bodyContent3, iter.next().value());
assertEquals(bodyContent3, iter.next().value());
// verify sql content
long count = jdbc.queryForObject("select count(*) from foo5 where name like 'foobar%'", Long.class);
assertEquals(3, count);
}
/**
* With transaction - sends two duplicate messages, for the second one the DB insert will fail and the rollback will
* take place. in this case the SQL operation is the first endpoint.
*/
@ParameterizedTest
@ValueSource(strings = { "transacted=true", "transactionalId=my-bar1", "additionalProperties[transactional.id]=my-bar2" })
public void transactionProducerWithDBFirst(String txParam) throws Exception {
String startEndpoint = "direct:startTxDBFirst";
contextExtension.getContext().addRoutes(new RouteBuilder() {
public void configure() {
from(startEndpoint).routeId("tx-kafka-db-first")
.onException(Exception.class)
.handled(true)
.log("Expected error when trying to insert duplicate values in the unique column.")
.end()
.to("sql:" + INSERT_SQL_4)
.to("kafka:" + TOPIC_TX_4 + "?" + txParam);
}
});
ProducerTemplate producer = contextExtension.getProducerTemplate();
String bodyContent = "foobar";
producer.sendBodyAndHeader(startEndpoint, bodyContent, "word", bodyContent);
producer.sendBodyAndHeader(startEndpoint, bodyContent, "word", bodyContent);
ConsumerRecords<String, String> records = getMessagesFromTopic(stringsConsumerConn, TOPIC_TX_4);
// verify kafka topic
assertEquals(1, records.count());
assertEquals(bodyContent, records.iterator().next().value());
// verify sql content
long count = jdbc.queryForObject("select count(*) from foo4 where name = '" + bodyContent + "'", Long.class);
assertEquals(1, count);
}
private ConsumerRecords<String, String> getMessagesFromTopic(KafkaConsumer<String, String> consumerConn, String topic) {
consumerConn.subscribe(Arrays.asList(topic));
ConsumerRecords<String, String> records = null;
for (int i = 0; i < 5; i++) {
records = consumerConn.poll(Duration.ofMillis(100));
if (records.count() > 0) {
break;
}
}
consumerConn.unsubscribe();
return records;
}
private static KafkaConsumer<String, String> createStringKafkaConsumer(final String groupId) {
Properties stringsProps = new Properties();
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, getBootstrapServers());
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.GROUP_ID_CONFIG, groupId);
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringDeserializer");
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringDeserializer");
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
return new KafkaConsumer<>(stringsProps);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// intentionally blank as we use the routes in each test
}
};
}
}
| KafkaWithDBTransactionIT |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/annotations/Param.java | {
"start": 998,
"end": 1280
} | interface ____ {
* @Select("SELECT id, name FROM users WHERE name = #{name}")
* User selectById(@Param("name") String value);
* }
* </pre>
*
* @author Clinton Begin
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @ | UserMapper |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/exceptionhandling/InterceptorExceptionHandlingTest.java | {
"start": 502,
"end": 3053
} | class ____ {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(ExceptionHandlingBean.class,
ExceptionHandlingInterceptor.class, ExceptionHandlingInterceptorBinding.class);
@Test
public void testProperlyThrowsDeclaredExceptions() throws MyDeclaredException {
ExceptionHandlingBean exceptionHandlingBean = Arc.container().instance(ExceptionHandlingBean.class).get();
assertTrue(exceptionHandlingBean instanceof Subclass);
assertThrows(MyDeclaredException.class, () -> exceptionHandlingBean.foo(ExceptionHandlingCase.DECLARED_EXCEPTION));
}
@Test
public void testProperlyThrowsRuntimeExceptions() throws MyDeclaredException {
ExceptionHandlingBean exceptionHandlingBean = Arc.container().instance(ExceptionHandlingBean.class).get();
assertTrue(exceptionHandlingBean instanceof Subclass);
assertThrows(MyRuntimeException.class, () -> exceptionHandlingBean.foo(ExceptionHandlingCase.RUNTIME_EXCEPTION));
}
@Test
public void testWrapsOtherExceptions() throws MyDeclaredException {
try {
ExceptionHandlingBean exceptionHandlingBean = Arc.container().instance(ExceptionHandlingBean.class).get();
assertTrue(exceptionHandlingBean instanceof Subclass);
exceptionHandlingBean.foo(ExceptionHandlingCase.OTHER_EXCEPTIONS);
fail("The method should have thrown a RuntimeException wrapping a MyOtherException but didn't throw any exception.");
} catch (RuntimeException e) {
// Let's check the cause is consistent with what we except.
assertEquals(MyOtherException.class, e.getCause().getClass());
} catch (Exception e) {
fail("The method should have thrown a RuntimeException wrapping a MyOtherException but threw: " + e);
}
}
@Test
public void testThrowsException() throws Exception {
ExceptionHandlingBean exceptionHandlingBean = Arc.container().instance(ExceptionHandlingBean.class).get();
assertTrue(exceptionHandlingBean instanceof Subclass);
assertThrows(Exception.class, () -> exceptionHandlingBean.bar());
}
@Test
public void testThrowsRuntimeException() {
ExceptionHandlingBean exceptionHandlingBean = Arc.container().instance(ExceptionHandlingBean.class).get();
assertTrue(exceptionHandlingBean instanceof Subclass);
assertThrows(RuntimeException.class, () -> exceptionHandlingBean.baz());
}
}
| InterceptorExceptionHandlingTest |
java | micronaut-projects__micronaut-core | core-reactive/src/main/java/io/micronaut/core/async/processor/SingleSubscriberProcessor.java | {
"start": 1239,
"end": 5336
} | class ____<T, R> extends CompletionAwareSubscriber<T> implements Processor<T, R> {
protected static final Subscription EMPTY_SUBSCRIPTION = new Subscription() {
@Override
public void request(long n) {
}
@Override
public void cancel() {
}
};
protected Subscription parentSubscription;
private final AtomicReference<Subscriber<? super R>> subscriber = new AtomicReference<>();
@Override
public final void subscribe(Subscriber<? super R> subscriber) {
Objects.requireNonNull(subscriber, "Subscriber cannot be null");
if (!this.subscriber.compareAndSet(null, subscriber)) {
subscriber.onSubscribe(EMPTY_SUBSCRIPTION);
subscriber.onError(new IllegalStateException("Only one subscriber allowed"));
} else {
doSubscribe(subscriber);
}
}
/**
* Override to implement {@link org.reactivestreams.Publisher#subscribe(Subscriber)}.
*
* @param subscriber The subscriber
* @see org.reactivestreams.Publisher#subscribe(Subscriber)
*/
protected abstract void doSubscribe(Subscriber<? super R> subscriber);
/**
* Get the current {@link Subscriber}.
*
* @return The {@link Subscriber}
* @throws IllegalStateException if the subscriber is not present
*/
protected Subscriber<? super R> getSubscriber() {
Subscriber<? super R> subscriber = this.subscriber.get();
verifyState(subscriber);
return subscriber;
}
/**
* Get the current {@link Subscriber}.
*
* @return An {@link Optional} subscriber
*/
protected Optional<Subscriber<? super R>> currentSubscriber() {
Subscriber<? super R> subscriber = this.subscriber.get();
return Optional.ofNullable(subscriber);
}
/**
* Called after {@link #doOnError(Throwable)} completes.
*
* @param throwable The error
*/
protected void doAfterOnError(Throwable throwable) {
// no-op
}
/**
* Called after {@link #doOnComplete()} completes.
*/
protected void doAfterComplete() {
// no-op
}
/**
* Called after {@link #doOnSubscribe(Subscription)} completes.
*
* @param subscription subscription
*/
protected void doAfterOnSubscribe(Subscription subscription) {
// no-op
}
/**
* Perform the actual subscription to the subscriber.
*
* @param subscription The subscription
* @param subscriber The subscriber (never null)
*/
protected void doOnSubscribe(Subscription subscription, Subscriber<? super R> subscriber) {
subscriber.onSubscribe(subscription);
}
@Override
protected final void doOnSubscribe(Subscription subscription) {
this.parentSubscription = subscription;
Subscriber<? super R> subscriber = this.subscriber.get();
if (!verifyState(subscriber)) {
return;
}
doOnSubscribe(subscription, subscriber);
doAfterOnSubscribe(subscription);
}
@Override
protected final void doOnError(Throwable t) {
try {
Subscriber<? super R> subscriber = getSubscriber();
parentSubscription.cancel();
subscriber.onError(t);
} finally {
doAfterOnError(t);
}
}
@Override
protected void doOnComplete() {
try {
Subscriber<? super R> subscriber = getSubscriber();
subscriber.onComplete();
} finally {
doAfterComplete();
}
}
private boolean verifyState(Subscriber<? super R> subscriber) {
if (subscriber == null) {
throw new IllegalStateException("No subscriber present!");
}
boolean hasParent = parentSubscription != null;
if (!hasParent) {
subscriber.onSubscribe(EMPTY_SUBSCRIPTION);
subscriber.onError(new IllegalStateException("Upstream publisher must be subscribed to first"));
}
return hasParent;
}
}
| SingleSubscriberProcessor |
java | quarkusio__quarkus | integration-tests/grpc-streaming/src/test/java/io/quarkus/grpc/example/streaming/LongStreamTest.java | {
"start": 107,
"end": 159
} | class ____ extends LongStreamTestBase {
}
| LongStreamTest |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/DailySchedule.java | {
"start": 748,
"end": 2147
} | class ____ extends CronnableSchedule {
public static final String TYPE = "daily";
public static final DayTimes[] DEFAULT_TIMES = new DayTimes[] { DayTimes.MIDNIGHT };
private final DayTimes[] times;
DailySchedule() {
this(DEFAULT_TIMES);
}
DailySchedule(DayTimes... times) {
super(crons(times));
this.times = times;
}
@Override
public String type() {
return TYPE;
}
public DayTimes[] times() {
return times;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (params.paramAsBoolean("normalize", false) && times.length == 1) {
builder.field(Parser.AT_FIELD.getPreferredName(), times[0], params);
} else {
builder.startArray(Parser.AT_FIELD.getPreferredName());
for (DayTimes dayTimes : times) {
dayTimes.toXContent(builder, params);
}
builder.endArray();
}
return builder.endObject();
}
public static Builder builder() {
return new Builder();
}
static String[] crons(DayTimes[] times) {
assert times.length > 0 : "at least one time must be defined";
return Arrays.stream(times).map(DayTimes::cron).toArray(String[]::new);
}
public static | DailySchedule |
java | alibaba__nacos | naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/ExpiredMetadataInfo.java | {
"start": 957,
"end": 2547
} | class ____ {
private final Service service;
private final String metadataId;
private final long createTime;
private ExpiredMetadataInfo(Service service, String metadataId) {
this.service = service;
this.metadataId = metadataId;
this.createTime = System.currentTimeMillis();
}
public static ExpiredMetadataInfo newExpiredServiceMetadata(Service service) {
return new ExpiredMetadataInfo(service, null);
}
public static ExpiredMetadataInfo newExpiredInstanceMetadata(Service service, String metadataId) {
return new ExpiredMetadataInfo(service, metadataId);
}
public Service getService() {
return service;
}
public String getMetadataId() {
return metadataId;
}
public long getCreateTime() {
return createTime;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ExpiredMetadataInfo)) {
return false;
}
ExpiredMetadataInfo that = (ExpiredMetadataInfo) o;
return Objects.equals(service, that.service) && Objects.equals(metadataId, that.metadataId);
}
@Override
public int hashCode() {
return Objects.hash(service, metadataId);
}
@Override
public String toString() {
return "ExpiredMetadataInfo{" + "service=" + service + ", metadataId='" + metadataId + '\'' + ", createTime="
+ new Date(createTime) + '}';
}
}
| ExpiredMetadataInfo |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/language/LanguageLoadScriptFromClasspathTest.java | {
"start": 982,
"end": 1813
} | class ____ extends ContextTestSupport {
@Test
public void testLanguage() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBody("direct:start", "World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// START SNIPPET: e1
from("direct:start")
// load the script from the classpath
.to("language:simple:classpath:org/apache/camel/component/language/mysimplescript.txt")
.to("mock:result");
// END SNIPPET: e1
}
};
}
}
| LanguageLoadScriptFromClasspathTest |
java | alibaba__fastjson | src/test/java/com/derbysoft/spitfire/fastjson/ABCTest.java | {
"start": 272,
"end": 1047
} | class ____ extends TestCase {
public void test_abc() throws Exception {
Field field = ParserConfig.class.getDeclaredField("denyList");
field.setAccessible(true);
String[] denyList = (String[]) field.get(ParserConfig.getGlobalInstance());
Arrays.sort(denyList);
for (int i = 0; i < denyList.length; ++i) {
if (i != 0) {
System.out.print(",");
}
System.out.print(denyList[i]);
}
for (int i = 0; i < denyList.length; ++i) {
// System.out.println("\"" + denyList[i] + "\",");
System.out.println(denyList[i]);
}
System.out.println();
System.out.println(Base64.encodeToString("\"@type".getBytes(), true));
}
}
| ABCTest |
java | quarkusio__quarkus | integration-tests/maven/src/test/resources-filtered/projects/rest-client-custom-headers-extension/runner/src/main/java/org/acme/FrontendService.java | {
"start": 193,
"end": 368
} | class ____ {
@Inject
@RestClient
DownstreamServiceClient client;
@GET
public String getHeaders() {
return client.getHeaders();
}
}
| FrontendService |
java | elastic__elasticsearch | build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/do_/ReplaceKeyInDo.java | {
"start": 925,
"end": 1513
} | class ____ extends ReplaceByKey {
public ReplaceKeyInDo(String replaceKey, String newKeyName, String testName) {
super(replaceKey, newKeyName, null, testName);
}
@Override
@Internal
public String getKeyToFind() {
return "do";
}
@Override
public void transformTest(ObjectNode doParent) {
ObjectNode doNode = (ObjectNode) doParent.get(getKeyToFind());
JsonNode previousValue = doNode.get(requiredChildKey());
doNode.remove(requiredChildKey());
doNode.set(getNewChildKey(), previousValue);
}
}
| ReplaceKeyInDo |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java | {
"start": 26342,
"end": 26417
} | class ____ {
}
}
}
@InheritedComposedAnnotation
static | InnerInnerClass |
java | qos-ch__slf4j | slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java | {
"start": 5219,
"end": 6677
} | class ____ resource named
* <code>"simplelogger.properties"</code>, and includes any matching definitions
* from this resource (if it exists).
*
*
* <p>
* With no configuration, the default output includes the relative time in
* milliseconds, thread name, the level, logger name, and the message followed
* by the line separator for the host. In log4j terms it amounts to the "%r [%t]
* %level %logger - %m%n" pattern.
*
* <p>
* Sample output follows.
*
*
* <pre>
* 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
* 225 [main] INFO examples.SortAlgo - Entered the sort method.
* 304 [main] INFO examples.SortAlgo - Dump of integer array:
* 317 [main] INFO examples.SortAlgo - Element [0] = 0
* 331 [main] INFO examples.SortAlgo - Element [1] = 1
* 343 [main] INFO examples.Sort - The next log statement should be an error message.
* 346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
* at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
* at org.log4j.examples.Sort.main(Sort.java:64)
* 467 [main] INFO examples.Sort - Exiting main method.
* </pre>
*
* <p>
* This implementation is heavily inspired by
* <a href="http://commons.apache.org/logging/">Apache Commons Logging</a>'s
* SimpleLog.
*
*
* @author Ceki Gülcü
* @author Scott Sanders
* @author Rod Waldhoff
* @author Robert Burrell Donkin
* @author Cédrik LIME
*/
public | loader |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/beans/visitor/BeanIntrospectionWriter.java | {
"start": 49446,
"end": 62307
} | class ____ implements DispatchWriter.DispatchTarget {
private final ClassTypeDef beanType;
private final List<BeanPropertyData> beanProperties;
private final DispatchWriter dispatchWriter;
private final MethodElement constructor;
private final Map<String, Integer> propertyNames = new HashMap<>();
private StatementDef statement;
private CopyConstructorDispatchTarget(ClassTypeDef beanType,
List<BeanPropertyData> beanProperties,
DispatchWriter dispatchWriter,
MethodElement constructor) {
this.beanType = beanType;
this.beanProperties = beanProperties;
this.dispatchWriter = dispatchWriter;
this.constructor = constructor;
}
@Override
public boolean supportsDispatchOne() {
return true;
}
@Override
public boolean supportsDispatchMulti() {
return false;
}
@Override
public StatementDef dispatchOne(int caseValue, ExpressionDef caseExpression, ExpressionDef target, ExpressionDef value) {
if (statement == null) {
// The unique statement provided for the switch case should produce one case
statement = createStatement(caseExpression, target, value);
}
return statement;
}
private StatementDef createStatement(ExpressionDef caseExpression, ExpressionDef target, ExpressionDef value) {
// In this case we have to do the copy constructor approach
Set<BeanPropertyData> constructorProps = new HashSet<>();
boolean isMutable = true;
String nonMutableMessage = null;
ParameterElement[] parameters = constructor.getParameters();
Object[] constructorArguments = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
ParameterElement parameter = parameters[i];
String parameterName = parameter.getName();
BeanPropertyData prop = beanProperties.stream()
.filter(bp -> bp.name.equals(parameterName))
.findAny().orElse(null);
int readDispatchIndex = prop == null ? -1 : prop.getDispatchIndex;
if (readDispatchIndex != -1) {
Object member;
ClassElement propertyType;
DispatchWriter.DispatchTarget dispatchTarget = dispatchWriter.getDispatchTargets().get(readDispatchIndex);
if (dispatchTarget instanceof DispatchWriter.MethodDispatchTarget methodDispatchTarget) {
MethodElement methodElement = methodDispatchTarget.getMethodElement();
propertyType = methodElement.getGenericReturnType();
member = methodElement;
} else if (dispatchTarget instanceof DispatchWriter.FieldGetDispatchTarget fieldGetDispatchTarget) {
FieldElement field = fieldGetDispatchTarget.getField();
propertyType = field.getGenericType();
member = field;
} else if (dispatchTarget instanceof DispatchWriter.FieldGetReflectionDispatchTarget fieldGetDispatchTarget) {
FieldElement field = fieldGetDispatchTarget.getField();
propertyType = field.getGenericType();
member = field;
} else {
throw new IllegalStateException();
}
if (propertyType.isAssignable(parameter.getGenericType())) {
constructorArguments[i] = member;
constructorProps.add(prop);
} else {
isMutable = false;
nonMutableMessage = "Cannot create copy of type [" + beanType.getName() + "]. Property of type [" + propertyType.getName() + "] is not assignable to constructor argument [" + parameterName + "]";
}
} else {
isMutable = false;
nonMutableMessage = "Cannot create copy of type [" + beanType.getName() + "]. Constructor contains argument [" + parameterName + "] that is not a readable property";
break;
}
}
if (isMutable) {
return target.cast(beanType).newLocal("prevBean", prevBeanVar -> {
List<ExpressionDef> values = new ArrayList<>(constructorArguments.length);
for (int i = 0; i < parameters.length; i++) {
ParameterElement parameter = parameters[i];
Object constructorArgument = constructorArguments[i];
ExpressionDef oldValueExp;
if (constructorArgument instanceof MethodElement readMethod) {
oldValueExp = prevBeanVar.invoke(readMethod);
} else {
oldValueExp = prevBeanVar.field((FieldElement) constructorArgument);
}
Integer propertyIndex = propertyNames.get(parameter.getName());
ExpressionDef paramExp;
if (propertyIndex != null) {
ExpressionDef.Cast newPropertyValue = value.cast(TypeDef.erasure(parameter.getType()));
if (propertyNames.size() == 1) {
paramExp = newPropertyValue;
} else {
paramExp = caseExpression.equalsStructurally(ExpressionDef.constant((int) propertyIndex)).doIfElse(
newPropertyValue,
oldValueExp
);
}
} else {
paramExp = oldValueExp;
}
values.add(paramExp);
}
// NOTE: It doesn't make sense to check defaults for the copy constructor
ExpressionDef newInstance = MethodGenUtils.invokeBeanConstructor(ClassElement.of(introspectionName), constructor, false, values);
return withSetSettersAndFields(newInstance, prevBeanVar, constructorProps);
});
} else {
// In this case the bean cannot be mutated via either copy constructor or setter so simply throw an exception
return ClassTypeDef.of(UnsupportedOperationException.class).instantiate(ExpressionDef.constant(nonMutableMessage)).doThrow();
}
}
@Override
public StatementDef dispatch(ExpressionDef target, ExpressionDef valuesArray) {
throw new IllegalStateException("Not supported");
}
private StatementDef withSetSettersAndFields(ExpressionDef newInstance,
VariableDef prevBeanVar,
Set<BeanPropertyData> constructorProps) {
List<BeanPropertyData> readWriteProps = beanProperties.stream()
.filter(bp -> bp.setDispatchIndex != -1 && bp.getDispatchIndex != -1 && !constructorProps.contains(bp)).toList();
if (readWriteProps.isEmpty()) {
return newInstance.returning();
}
return newInstance
.newLocal("newBean", newBeanVar -> {
List<StatementDef> statements = new ArrayList<>();
for (BeanPropertyData readWriteProp : readWriteProps) {
DispatchWriter.DispatchTarget readDispatch = dispatchWriter.getDispatchTargets().get(readWriteProp.getDispatchIndex);
ExpressionDef oldValueExp;
if (readDispatch instanceof DispatchWriter.MethodDispatchTarget methodDispatchTarget) {
MethodElement readMethod = methodDispatchTarget.getMethodElement();
oldValueExp = prevBeanVar.invoke(readMethod);
} else if (readDispatch instanceof DispatchWriter.FieldGetDispatchTarget fieldGetDispatchTarget) {
FieldElement fieldElement = fieldGetDispatchTarget.getField();
oldValueExp = prevBeanVar.field(fieldElement);
} else if (readDispatch instanceof DispatchWriter.FieldGetReflectionDispatchTarget fieldGetDispatchTarget) {
FieldElement fieldElement = fieldGetDispatchTarget.getField();
oldValueExp = prevBeanVar.field(fieldElement);
} else {
throw new IllegalStateException();
}
DispatchWriter.DispatchTarget writeDispatch = dispatchWriter.getDispatchTargets().get(readWriteProp.setDispatchIndex);
if (writeDispatch instanceof DispatchWriter.MethodDispatchTarget methodDispatchTarget) {
MethodElement writeMethod = methodDispatchTarget.getMethodElement();
statements.add(
newBeanVar.invoke(
writeMethod,
oldValueExp
)
);
} else if (writeDispatch instanceof DispatchWriter.FieldSetDispatchTarget fieldSetDispatchTarget) {
FieldElement fieldElement = fieldSetDispatchTarget.getField();
statements.add(
newBeanVar.field(fieldElement).assign(oldValueExp)
);
} else if (writeDispatch instanceof DispatchWriter.FieldSetReflectionDispatchTarget fieldSetDispatchTarget) {
FieldElement fieldElement = fieldSetDispatchTarget.getField();
statements.add(
newBeanVar.field(fieldElement).assign(oldValueExp)
);
} else {
throw new IllegalStateException();
}
}
statements.add(newBeanVar.returning());
return StatementDef.multi(statements);
});
}
@Override
public MethodElement getMethodElement() {
return null;
}
@Override
public TypedElement getDeclaringType() {
return constructor.getDeclaringType();
}
}
private record BeanMethodData(MethodElement methodElement, int dispatchIndex) {
}
/**
* @param name
* @param type
* @param readType
* @param writeType
* @param getDispatchIndex
* @param setDispatchIndex
* @param withMethodDispatchIndex
* @param isReadOnly
*/
private record BeanPropertyData(@NonNull String name,
@NonNull ClassElement type,
@Nullable ClassElement readType,
@Nullable ClassElement writeType,
int getDispatchIndex,
int setDispatchIndex,
int withMethodDispatchIndex,
boolean isReadOnly) {
}
/**
* index to be created.
*
* @param annotationName The annotation name
* @param value The annotation value
*/
private record AnnotationWithValue(@NonNull String annotationName, @Nullable String value) {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AnnotationWithValue that = (AnnotationWithValue) o;
return annotationName.equals(that.annotationName) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return annotationName.hashCode();
}
}
}
| CopyConstructorDispatchTarget |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdentityTest.java | {
"start": 5412,
"end": 5959
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private boolean employed;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEmployed() {
return employed;
}
public void setEmployed(boolean employed) {
this.employed = employed;
}
}
@Entity(name = "Doctor")
public static | Person |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/future/CompletableFutureAssert_isNotCompletedExceptionally_Test.java | {
"start": 1135,
"end": 2375
} | class ____ {
@Test
void should_pass_if_completable_future_is_not_completed_exceptionally() {
// GIVEN
CompletableFuture<String> completedFuture = completedFuture("done");
// THEN
then(completedFuture).isNotCompletedExceptionally();
}
@Test
void should_fail_when_completable_future_is_null() {
// GIVEN
CompletableFuture<String> future = null;
// WHEN
var assertionError = expectAssertionError(() -> assertThat(future).isNotCompletedExceptionally());
// THEN
then(assertionError).hasMessageStartingWith(actualIsNull());
}
@Test
void should_fail_if_completable_future_is_completed_exceptionally() {
// GIVEN
CompletableFuture<String> future = new CompletableFuture<>();
future.completeExceptionally(new RuntimeException());
// WHEN
var assertionError = expectAssertionError(() -> assertThat(future).isNotCompletedExceptionally());
// THEN
then(assertionError).hasMessageStartingWith("%nExpecting%n <CompletableFuture[Failed with the following stack trace:%njava.lang.RuntimeException".formatted())
.hasMessageEndingWith("to not be completed exceptionally.%n%s", WARNING);
}
}
| CompletableFutureAssert_isNotCompletedExceptionally_Test |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerSourceTaskTest.java | {
"start": 41132,
"end": 43506
} | class ____ extends SourceTask {
}
private void verifyCleanStartup() {
verify(offsetStore).start();
verify(sourceTask).initialize(any(SourceTaskContext.class));
verify(sourceTask).start(TASK_PROPS);
verify(statusListener).onStartup(taskId);
}
private void verifyClose() {
verify(producer).close(any(Duration.class));
verify(admin).close(any(Duration.class));
verify(transformationChain).close();
verify(offsetReader).close();
verify(offsetStore).stop();
try {
verify(headerConverter).close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void expectTopicCreation(String topic) {
if (config.topicCreationEnable()) {
when(admin.describeTopics(topic)).thenReturn(Map.of());
when(admin.createOrFindTopics(any(NewTopic.class))).thenReturn(createdTopic(topic));
}
}
private void verifyTopicCreation(String... topics) {
if (config.topicCreationEnable()) {
ArgumentCaptor<NewTopic> newTopicCapture = ArgumentCaptor.forClass(NewTopic.class);
verify(admin).createOrFindTopics(newTopicCapture.capture());
assertArrayEquals(topics, newTopicCapture.getAllValues()
.stream()
.map(NewTopic::name)
.toArray(String[]::new));
}
}
private void assertShouldSkipCommit() {
assertFalse(workerTask.shouldCommitOffsets());
try (LogCaptureAppender committerAppender = LogCaptureAppender.createAndRegister(SourceTaskOffsetCommitter.class);
LogCaptureAppender taskAppender = LogCaptureAppender.createAndRegister(WorkerSourceTask.class)) {
committerAppender.setClassLogger(SourceTaskOffsetCommitter.class, org.apache.logging.log4j.Level.TRACE);
taskAppender.setClassLogger(WorkerSourceTask.class, org.apache.logging.log4j.Level.TRACE);
SourceTaskOffsetCommitter.commit(workerTask);
assertEquals(List.of(), taskAppender.getMessages());
List<String> committerMessages = committerAppender.getMessages();
assertEquals(1, committerMessages.size());
assertTrue(committerMessages.get(0).contains("Skipping offset commit"));
}
}
}
| TestSourceTask |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/compress/Lz4CompressionTest.java | {
"start": 2347,
"end": 5448
} | class ____ {
private static final Random RANDOM = new Random(0);
@Test
public void testLz4FramingMagicV0() {
ByteBuffer buffer = ByteBuffer.allocate(256);
Lz4Compression compression = new Lz4Compression.Builder().build();
Lz4BlockOutputStream out = (Lz4BlockOutputStream) compression.wrapForOutput(
new ByteBufferOutputStream(buffer), RecordBatch.MAGIC_VALUE_V0);
assertTrue(out.useBrokenFlagDescriptorChecksum());
buffer.rewind();
ChunkedBytesStream in = (ChunkedBytesStream) compression.wrapForInput(buffer, RecordBatch.MAGIC_VALUE_V0, BufferSupplier.NO_CACHING);
assertTrue(((Lz4BlockInputStream) in.sourceStream()).ignoreFlagDescriptorChecksum());
}
@Test
public void testLz4FramingMagicV1() {
ByteBuffer buffer = ByteBuffer.allocate(256);
Lz4Compression compression = new Lz4Compression.Builder().build();
Lz4BlockOutputStream out = (Lz4BlockOutputStream) compression.wrapForOutput(
new ByteBufferOutputStream(buffer), RecordBatch.MAGIC_VALUE_V1);
assertFalse(out.useBrokenFlagDescriptorChecksum());
buffer.rewind();
ChunkedBytesStream in = (ChunkedBytesStream) compression.wrapForInput(buffer, RecordBatch.MAGIC_VALUE_V1, BufferSupplier.create());
assertFalse(((Lz4BlockInputStream) in.sourceStream()).ignoreFlagDescriptorChecksum());
}
@Test
public void testCompressionDecompression() throws IOException {
Lz4Compression.Builder builder = Compression.lz4();
byte[] data = String.join("", Collections.nCopies(256, "data")).getBytes(StandardCharsets.UTF_8);
for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
for (int level : Arrays.asList(LZ4.minLevel(), LZ4.defaultLevel(), LZ4.maxLevel())) {
Lz4Compression compression = builder.level(level).build();
ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
try (OutputStream out = compression.wrapForOutput(bufferStream, magic)) {
out.write(data);
out.flush();
}
bufferStream.buffer().flip();
try (InputStream inputStream = compression.wrapForInput(bufferStream.buffer(), magic, BufferSupplier.create())) {
byte[] result = new byte[data.length];
int read = inputStream.read(result);
assertEquals(data.length, read);
assertArrayEquals(data, result);
}
}
}
}
@Test
public void testCompressionLevels() {
Lz4Compression.Builder builder = Compression.lz4();
assertThrows(IllegalArgumentException.class, () -> builder.level(LZ4.minLevel() - 1));
assertThrows(IllegalArgumentException.class, () -> builder.level(LZ4.maxLevel() + 1));
builder.level(LZ4.minLevel());
builder.level(LZ4.maxLevel());
}
private static | Lz4CompressionTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_229.java | {
"start": 415,
"end": 628
} | class ____ {
private boolean value;
public boolean isValue() {
return value;
}
public void setValue(boolean value) {
this.value = value;
}
}
}
| VO |
java | quarkusio__quarkus | integration-tests/spring-di/src/main/java/io/quarkus/it/spring/AppConfiguration.java | {
"start": 461,
"end": 1439
} | class ____ {
@Bean(name = "cap")
public StringFunction capitalizer(@Qualifier("dumb") Dummy notUsedJustMakingSureDIInMethodsWorks,
OtherDummy alsoNotUsed) {
return String::toUpperCase;
}
@Bean
@Singleton
public SingletonBean explicitSingletonBean() {
return new SingletonBean();
}
@Bean
public SingletonBean implicitSingletonBean() {
return new SingletonBean();
}
@Bean
@RequestScope
public AnotherRequestBean requestBean() {
return new AnotherRequestBean();
}
@Bean
@CustomPrototype
public CustomPrototypeBean beanWithCustomPrototype() {
return new CustomPrototypeBean();
}
private AtomicInteger prototypeBeanCounter = new AtomicInteger(0);
@Bean
@Scope(scopeName = "prototype")
public PrototypeBean prototypeBean() {
return new PrototypeBean(prototypeBeanCounter.getAndIncrement());
}
private static | AppConfiguration |
java | google__dagger | java/dagger/example/atm/CommandsModule.java | {
"start": 868,
"end": 1322
} | interface ____ {
@Binds
@IntoMap
@StringKey("hello")
Command helloWorld(HelloWorldCommand command);
@Binds
@IntoMap
@StringKey("login")
Command login(LoginCommand command);
/**
* Declare an optional binding for {@link Account}. This allows other bindings to change their
* behavior depending on whether an {@link Account} is bound in the current (sub)component.
*/
@BindsOptionalOf
Account loggedInAccount();
}
| CommandsModule |
java | spring-projects__spring-boot | module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/autoconfigure/WebMvcAutoConfiguration.java | {
"start": 29154,
"end": 30814
} | class ____ implements ResourceHandlerRegistrationCustomizer {
private final Resources resourceProperties;
ResourceChainResourceHandlerRegistrationCustomizer(Resources resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Override
public void customize(ResourceHandlerRegistration registration) {
Resources.Chain properties = this.resourceProperties.getChain();
configureResourceChain(properties, registration.resourceChain(properties.isCache()));
}
private void configureResourceChain(Resources.Chain properties, ResourceChainRegistration chain) {
Strategy strategy = properties.getStrategy();
if (properties.isCompressed()) {
chain.addResolver(new EncodedResourceResolver());
}
if (strategy.getFixed().isEnabled() || strategy.getContent().isEnabled()) {
chain.addResolver(getVersionResourceResolver(strategy));
}
}
private ResourceResolver getVersionResourceResolver(Strategy properties) {
VersionResourceResolver resolver = new VersionResourceResolver();
if (properties.getFixed().isEnabled()) {
String version = properties.getFixed().getVersion();
String[] paths = properties.getFixed().getPaths();
Assert.state(version != null, "'version' must not be null");
resolver.addFixedVersionStrategy(version, paths);
}
if (properties.getContent().isEnabled()) {
String[] paths = properties.getContent().getPaths();
resolver.addContentVersionStrategy(paths);
}
return resolver;
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty("spring.mvc.problemdetails.enabled")
static | ResourceChainResourceHandlerRegistrationCustomizer |
java | micronaut-projects__micronaut-core | http-netty/src/main/java/io/micronaut/http/netty/channel/NettyThreadFactory.java | {
"start": 5109,
"end": 5814
} | class ____ extends DefaultThreadFactory {
private final boolean nonBlocking;
public CustomizedThreadFactory(boolean daemon, int priority, boolean nonBlocking) {
super("default-eventLoopGroup", daemon, priority);
this.nonBlocking = nonBlocking;
}
@Override
@SuppressWarnings("InstantiatingAThreadWithDefaultRunMethod")
protected Thread newThread(Runnable r, String name) {
if (nonBlocking) {
return new NonBlockingFastThreadLocalThread(threadGroup, r, name);
} else {
return super.newThread(r, name);
}
}
}
private static final | CustomizedThreadFactory |
java | elastic__elasticsearch | distribution/tools/server-cli/src/main/java/org/elasticsearch/server/cli/SecureSettingsLoader.java | {
"start": 887,
"end": 1850
} | interface ____ {
/**
* Loads an existing SecureSettings implementation
*/
LoadedSecrets load(Environment environment, Terminal terminal) throws Exception;
/**
* Loads an existing SecureSettings implementation, creates one if it doesn't exist
*/
SecureSettings bootstrap(Environment environment, SecureString password) throws Exception;
/**
* A load result for loading a SecureSettings implementation from a SecureSettingsLoader
* @param secrets the loaded secure settings
* @param password an optional password if the implementation required one
*/
record LoadedSecrets(SecureSettings secrets, Optional<SecureString> password) implements AutoCloseable {
@Override
public void close() throws Exception {
if (password.isPresent()) {
password.get().close();
}
}
}
boolean supportsSecurityAutoConfiguration();
}
| SecureSettingsLoader |
java | apache__rocketmq | remoting/src/test/java/org/apache/rocketmq/remoting/protocol/CheckpointFileTest.java | {
"start": 1455,
"end": 3430
} | class ____ implements CheckpointFile.CheckpointSerializer<EpochEntry> {
@Override
public String toLine(EpochEntry entry) {
if (entry != null) {
return String.format("%d-%d", entry.getEpoch(), entry.getStartOffset());
} else {
return null;
}
}
@Override
public EpochEntry fromLine(String line) {
final String[] arr = line.split("-");
if (arr.length == 2) {
final int epoch = Integer.parseInt(arr[0]);
final long startOffset = Long.parseLong(arr[1]);
return new EpochEntry(epoch, startOffset);
}
return null;
}
}
@Before
public void init() throws IOException {
this.entryList = new ArrayList<>();
entryList.add(new EpochEntry(7, 7000));
entryList.add(new EpochEntry(8, 8000));
this.checkpoint = new CheckpointFile<>(FILE_PATH, new EpochEntrySerializer());
this.checkpoint.write(entryList);
}
@After
public void destroy() {
UtilAll.deleteFile(new File(FILE_PATH));
UtilAll.deleteFile(new File(FILE_PATH + ".bak"));
}
@Test
public void testNormalWriteAndRead() throws IOException {
List<EpochEntry> listFromFile = checkpoint.read();
Assert.assertEquals(entryList, listFromFile);
checkpoint.write(entryList);
listFromFile = checkpoint.read();
Assert.assertEquals(entryList, listFromFile);
}
@Test
public void testAbNormalWriteAndRead() throws IOException {
this.checkpoint.write(entryList);
UtilAll.deleteFile(new File(FILE_PATH));
List<EpochEntry> listFromFile = checkpoint.read();
Assert.assertEquals(entryList, listFromFile);
checkpoint.write(entryList);
listFromFile = checkpoint.read();
Assert.assertEquals(entryList, listFromFile);
}
}
| EpochEntrySerializer |
java | quarkusio__quarkus | integration-tests/hibernate-orm-panache/src/test/java/io/quarkus/it/panache/defaultpu/DuplicateMethodTest.java | {
"start": 338,
"end": 919
} | class ____ {
@Inject
DuplicateRepository repository;
@Test
public void shouldNotDuplicateMethodsInRepository() {
assertThat(repository.findById(1)).isNotNull();
}
@Test
public void shouldNotDuplicateMethodsInEntity() {
DuplicateEntity entity = DuplicateEntity.findById(1);
assertThat(entity).isNotNull();
assertThatCode(entity::persist).doesNotThrowAnyException();
assertThatCode(() -> DuplicateEntity.update("foo", Parameters.with("a", 1)))
.doesNotThrowAnyException();
}
}
| DuplicateMethodTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ByteBufferPositionedReadable.java | {
"start": 1304,
"end": 3953
} | interface ____ {
/**
* Reads up to {@code buf.remaining()} bytes into buf from a given position
* in the file and returns the number of bytes read. Callers should use
* {@code buf.limit(...)} to control the size of the desired read and
* {@code buf.position(...)} to control the offset into the buffer the data
* should be written to.
* <p>
* After a successful call, {@code buf.position()} will be advanced by the
* number of bytes read and {@code buf.limit()} will be unchanged.
* <p>
* In the case of an exception, the state of the buffer (the contents of the
* buffer, the {@code buf.position()}, the {@code buf.limit()}, etc.) is
* undefined, and callers should be prepared to recover from this
* eventuality.
* <p>
* Callers should use {@link StreamCapabilities#hasCapability(String)} with
* {@link StreamCapabilities#PREADBYTEBUFFER} to check if the underlying
* stream supports this interface, otherwise they might get a
* {@link UnsupportedOperationException}.
* <p>
* Implementations should treat 0-length requests as legitimate, and must not
* signal an error upon their receipt.
* <p>
* This does not change the current offset of a file, and is thread-safe.
*
* @param position position within file
* @param buf the ByteBuffer to receive the results of the read operation.
* @return the number of bytes read, possibly zero, or -1 if reached
* end-of-stream
* @throws IOException if there is some error performing the read
*/
int read(long position, ByteBuffer buf) throws IOException;
/**
* Reads {@code buf.remaining()} bytes into buf from a given position in
* the file or until the end of the data was reached before the read
* operation completed. Callers should use {@code buf.limit(...)} to
* control the size of the desired read and {@code buf.position(...)} to
* control the offset into the buffer the data should be written to.
* <p>
* This operation provides similar semantics to
* {@link #read(long, ByteBuffer)}, the difference is that this method is
* guaranteed to read data until the {@link ByteBuffer} is full, or until
* the end of the data stream is reached.
*
* @param position position within file
* @param buf the ByteBuffer to receive the results of the read operation.
* @throws IOException if there is some error performing the read
* @throws EOFException the end of the data was reached before
* the read operation completed
* @see #read(long, ByteBuffer)
*/
void readFully(long position, ByteBuffer buf) throws IOException;
}
| ByteBufferPositionedReadable |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/core/Completable.java | {
"start": 108403,
"end": 109814
} | class ____ to send a Disposable to the downstream.
* // Note that relaying the upstream's Disposable directly is not allowed in RxJava
* @Override
* public void onSubscribe(Disposable d) {
* if (upstream != null) {
* d.dispose();
* } else {
* upstream = d;
* downstream.onSubscribe(this);
* }
* }
*
* // Some operators may handle the upstream's error while others
* // could just forward it to the downstream.
* @Override
* public void onError(Throwable throwable) {
* downstream.onError(throwable);
* }
*
* // When the upstream completes, usually the downstream should complete as well.
* // In completable, this could also mean doing some side-effects
* @Override
* public void onComplete() {
* System.out.println("Sequence completed");
* downstream.onComplete();
* }
*
* // Some operators may use their own resources which should be cleaned up if
* // the downstream disposes the flow before it completed. Operators without
* // resources can simply forward the dispose to the upstream.
* // In some cases, a disposed flag may be set by this method so that other parts
* // of this | has |
java | apache__flink | flink-formats/flink-csv/src/main/java/org/apache/flink/formats/csv/CsvToRowDataConverters.java | {
"start": 12657,
"end": 12887
} | class ____ extends RuntimeException {
private static final long serialVersionUID = 1L;
public CsvParseException(String message, Throwable cause) {
super(message, cause);
}
}
}
| CsvParseException |
java | spring-projects__spring-boot | module/spring-boot-jersey/src/test/java/org/springframework/boot/jersey/autoconfigure/actuate/web/JerseyChildManagementContextConfigurationTests.java | {
"start": 3842,
"end": 4032
} | class ____ {
@Bean
ManagementContextResourceConfigCustomizer resourceConfigCustomizer() {
return mock(ManagementContextResourceConfigCustomizer.class);
}
}
}
| CustomizerConfiguration |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/hateoas/JsonError.java | {
"start": 993,
"end": 1231
} | class ____ can be used to represent JSON errors that complies to Vnd.Error without the content type requirements.
*
* @author Graeme Rocher
* @since 1.1
*/
@Produces(MediaType.APPLICATION_JSON)
@ReflectiveAccess // for jackson
public | that |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.