language
stringclasses 1
value | repo
stringclasses 60
values | path
stringlengths 22
294
| class_span
dict | source
stringlengths 13
1.16M
| target
stringlengths 1
113
|
|---|---|---|---|---|---|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/producer/staticProducers/DependentStaticProducerTest.java
|
{
"start": 1472,
"end": 1907
}
|
class ____ {
static int creationCount = 0;
static int destructionCount = 0;
@Produces
static Long produceLong() {
return 42L;
}
@Produces
static String stringField = "foobar";
@PostConstruct
void create() {
creationCount++;
}
@PreDestroy
void destroy() {
destructionCount++;
}
}
}
|
MyProducer
|
java
|
apache__logging-log4j2
|
log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java
|
{
"start": 1360,
"end": 1434
}
|
class ____ implements LevelConverter {
static final
|
DefaultLevelConverter
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/PhysicalSlotTestUtils.java
|
{
"start": 1450,
"end": 2356
}
|
class ____ {
public static PhysicalSlot createPhysicalSlot() {
return createPhysicalSlot(ResourceProfile.ANY);
}
public static PhysicalSlot createPhysicalSlot(ResourceProfile resourceProfile) {
return new AllocatedSlot(
new AllocationID(),
new LocalTaskManagerLocation(),
0,
resourceProfile,
new SimpleAckingTaskManagerGateway());
}
public static LogicalSlot occupyPhysicalSlot(
final PhysicalSlot physicalSlot, final boolean slotWillBeOccupiedIndefinitely) {
return SingleLogicalSlot.allocateFromPhysicalSlot(
new SlotRequestId(),
physicalSlot,
Locality.UNKNOWN,
new TestingSlotOwner(),
slotWillBeOccupiedIndefinitely);
}
private PhysicalSlotTestUtils() {}
}
|
PhysicalSlotTestUtils
|
java
|
apache__kafka
|
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/assignor/CurrentAssignmentBuilderBenchmark.java
|
{
"start": 2219,
"end": 6350
}
|
class ____ {
@Param({"5", "50"})
private int partitionsPerTopic;
@Param({"10", "100", "1000"})
private int topicCount;
private List<String> topicNames;
private List<Uuid> topicIds;
private CoordinatorMetadataImage metadataImage;
private ConsumerGroupMember member;
private ConsumerGroupMember memberWithUnsubscribedTopics;
private Assignment targetAssignment;
@Setup(Level.Trial)
public void setup() {
setupTopics();
setupMember();
setupTargetAssignment();
}
private void setupTopics() {
topicNames = AssignorBenchmarkUtils.createTopicNames(topicCount);
topicIds = new ArrayList<>(topicCount);
metadataImage = AssignorBenchmarkUtils.createMetadataImage(topicNames, partitionsPerTopic);
for (String topicName : topicNames) {
Uuid topicId = metadataImage.topicMetadata(topicName).get().id();
topicIds.add(topicId);
}
}
private void setupMember() {
Map<Uuid, Set<Integer>> assignedPartitions = new HashMap<>();
for (Uuid topicId : topicIds) {
Set<Integer> partitions = IntStream.range(0, partitionsPerTopic)
.boxed()
.collect(Collectors.toSet());
assignedPartitions.put(topicId, partitions);
}
ConsumerGroupMember.Builder memberBuilder = new ConsumerGroupMember.Builder("member")
.setState(MemberState.STABLE)
.setMemberEpoch(10)
.setPreviousMemberEpoch(10)
.setSubscribedTopicNames(topicNames)
.setAssignedPartitions(assignedPartitions);
member = memberBuilder.build();
memberWithUnsubscribedTopics = memberBuilder
.setSubscribedTopicNames(topicNames.subList(0, topicNames.size() - 1))
.build();
}
private void setupTargetAssignment() {
Map<Uuid, Set<Integer>> assignedPartitions = new HashMap<>();
for (Uuid topicId : topicIds) {
Set<Integer> partitions = IntStream.range(0, partitionsPerTopic)
.boxed()
.collect(Collectors.toSet());
assignedPartitions.put(topicId, partitions);
}
targetAssignment = new Assignment(assignedPartitions);
}
@Benchmark
@Threads(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public ConsumerGroupMember stableToStableWithNoChange() {
return new CurrentAssignmentBuilder(member)
.withMetadataImage(metadataImage)
.withTargetAssignment(member.memberEpoch(), targetAssignment)
.withCurrentPartitionEpoch((topicId, partitionId) -> -1)
.build();
}
@Benchmark
@Threads(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public ConsumerGroupMember stableToStableWithNewTargetAssignment() {
return new CurrentAssignmentBuilder(member)
.withMetadataImage(metadataImage)
.withTargetAssignment(member.memberEpoch() + 1, targetAssignment)
.withCurrentPartitionEpoch((topicId, partitionId) -> -1)
.build();
}
@Benchmark
@Threads(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public ConsumerGroupMember stableToStableWithSubscriptionChange() {
return new CurrentAssignmentBuilder(member)
.withMetadataImage(metadataImage)
.withTargetAssignment(member.memberEpoch(), targetAssignment)
.withHasSubscriptionChanged(true)
.withCurrentPartitionEpoch((topicId, partitionId) -> -1)
.build();
}
@Benchmark
@Threads(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public ConsumerGroupMember stableToUnrevokedPartitionsWithSubscriptionChange() {
return new CurrentAssignmentBuilder(memberWithUnsubscribedTopics)
.withMetadataImage(metadataImage)
.withTargetAssignment(memberWithUnsubscribedTopics.memberEpoch(), targetAssignment)
.withHasSubscriptionChanged(true)
.withCurrentPartitionEpoch((topicId, partitionId) -> -1)
.build();
}
}
|
CurrentAssignmentBuilderBenchmark
|
java
|
apache__camel
|
components/camel-http-common/src/main/java/org/apache/camel/http/common/HttpRegistry.java
|
{
"start": 1279,
"end": 1562
}
|
interface ____ {
void register(HttpConsumer consumer);
void unregister(HttpConsumer consumer);
void register(HttpRegistryProvider provider);
void unregister(HttpRegistryProvider provider);
HttpRegistryProvider getCamelServlet(String servletName);
}
|
HttpRegistry
|
java
|
quarkusio__quarkus
|
integration-tests/devtools/src/test/java/io/quarkus/devtools/codestarts/quarkus/FunqyHttpCodestartTest.java
|
{
"start": 376,
"end": 1076
}
|
class ____ {
@RegisterExtension
public static QuarkusCodestartTest codestartTest = QuarkusCodestartTest.builder()
.codestarts("funqy-http")
.languages(JAVA)
.build();
@Test
void testContent() throws Throwable {
codestartTest.checkGeneratedSource("org.acme.MyFunctions");
codestartTest.checkGeneratedTestSource("org.acme.MyFunctionsTest");
codestartTest.checkGeneratedTestSource("org.acme.MyFunctionsIT");
}
@Test
@EnabledIfSystemProperty(named = "build-projects", matches = "true")
void buildAllProjectsForLocalUse() throws Throwable {
codestartTest.buildAllProjects();
}
}
|
FunqyHttpCodestartTest
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/scope/JobManagerScopeFormat.java
|
{
"start": 970,
"end": 1335
}
|
class ____ extends ScopeFormat {
public JobManagerScopeFormat(String format) {
super(format, null, new String[] {SCOPE_HOST});
}
public String[] formatScope(String hostname) {
final String[] template = copyTemplate();
final String[] values = {hostname};
return bindVariables(template, values);
}
}
|
JobManagerScopeFormat
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/io/InputFormat.java
|
{
"start": 2748,
"end": 5969
}
|
interface ____<OT, T extends InputSplit> extends InputSplitSource<T>, Serializable {
/**
* Configures this input format. Since input formats are instantiated generically and hence
* parameterless, this method is the place where the input formats set their basic fields based
* on configuration values.
*
* <p>This method is always called first on a newly instantiated input format.
*
* @param parameters The configuration with all parameters (note: not the Flink config but the
* TaskConfig).
*/
void configure(Configuration parameters);
/**
* Gets the basic statistics from the input described by this format. If the input format does
* not know how to create those statistics, it may return null. This method optionally gets a
* cached version of the statistics. The input format may examine them and decide whether it
* directly returns them without spending effort to re-gather the statistics.
*
* <p>When this method is called, the input format is guaranteed to be configured.
*
* @param cachedStatistics The statistics that were cached. May be null.
* @return The base statistics for the input, or null, if not available.
*/
BaseStatistics getStatistics(BaseStatistics cachedStatistics) throws IOException;
// --------------------------------------------------------------------------------------------
@Override
T[] createInputSplits(int minNumSplits) throws IOException;
@Override
InputSplitAssigner getInputSplitAssigner(T[] inputSplits);
// --------------------------------------------------------------------------------------------
/**
* Opens a parallel instance of the input format to work on a split.
*
* <p>When this method is called, the input format it guaranteed to be configured.
*
* @param split The split to be opened.
* @throws IOException Thrown, if the spit could not be opened due to an I/O problem.
*/
void open(T split) throws IOException;
/**
* Method used to check if the end of the input is reached.
*
* <p>When this method is called, the input format it guaranteed to be opened.
*
* @return True if the end is reached, otherwise false.
* @throws IOException Thrown, if an I/O error occurred.
*/
boolean reachedEnd() throws IOException;
/**
* Reads the next record from the input.
*
* <p>When this method is called, the input format it guaranteed to be opened.
*
* @param reuse Object that may be reused.
* @return Read record.
* @throws IOException Thrown, if an I/O error occurred.
*/
OT nextRecord(OT reuse) throws IOException;
/**
* Method that marks the end of the life-cycle of an input split. Should be used to close
* channels and streams and release resources. After this method returns without an error, the
* input is assumed to be correctly read.
*
* <p>When this method is called, the input format it guaranteed to be opened.
*
* @throws IOException Thrown, if the input could not be closed properly.
*/
void close() throws IOException;
}
|
InputFormat
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSEditLogOp.java
|
{
"start": 131992,
"end": 133488
}
|
class ____ extends FSEditLogOp {
List<XAttr> xAttrs;
String src;
RemoveXAttrOp() {
super(OP_REMOVE_XATTR);
}
static RemoveXAttrOp getInstance(OpInstanceCache cache) {
return cache.get(OP_REMOVE_XATTR);
}
@Override
void resetSubFields() {
xAttrs = null;
src = null;
}
@Override
void readFields(DataInputStream in, int logVersion) throws IOException {
XAttrEditLogProto p = XAttrEditLogProto.parseDelimitedFrom(in);
src = p.getSrc();
xAttrs = PBHelperClient.convertXAttrs(p.getXAttrsList());
readRpcIds(in, logVersion);
}
@Override
public void writeFields(DataOutputStream out) throws IOException {
XAttrEditLogProto.Builder b = XAttrEditLogProto.newBuilder();
if (src != null) {
b.setSrc(src);
}
b.addAllXAttrs(PBHelperClient.convertXAttrProto(xAttrs));
b.build().writeDelimitedTo(out);
// clientId and callId
writeRpcIds(rpcClientId, rpcCallId, out);
}
@Override
protected void toXml(ContentHandler contentHandler) throws SAXException {
XMLUtils.addSaxString(contentHandler, "SRC", src);
appendXAttrsToXml(contentHandler, xAttrs);
appendRpcIdsToXml(contentHandler, rpcClientId, rpcCallId);
}
@Override
void fromXml(Stanza st) throws InvalidXmlException {
src = st.getValue("SRC");
xAttrs = readXAttrsFromXml(st);
readRpcIdsFromXml(st);
}
}
static
|
RemoveXAttrOp
|
java
|
apache__flink
|
flink-yarn/src/main/java/org/apache/flink/yarn/YarnResourceManagerDriver.java
|
{
"start": 3888,
"end": 28751
}
|
class ____ extends AbstractResourceManagerDriver<YarnWorkerNode> {
/**
* Environment variable name of the hostname given by YARN. In task executor we use the
* hostnames given by YARN consistently throughout pekko
*/
static final String ENV_FLINK_NODE_ID = "_FLINK_NODE_ID";
static final String ERROR_MESSAGE_ON_SHUTDOWN_REQUEST =
"Received shutdown request from YARN ResourceManager.";
private final YarnConfiguration yarnConfig;
/** The process environment variables. */
private final YarnResourceManagerDriverConfiguration configuration;
/** Default heartbeat interval between this resource manager and the YARN ResourceManager. */
private final int yarnHeartbeatIntervalMillis;
/** The heartbeat interval while the resource master is waiting for containers. */
private final int containerRequestHeartbeatIntervalMillis;
/** Request resource futures, keyed by container's TaskExecutorProcessSpec. */
private final Map<TaskExecutorProcessSpec, Queue<CompletableFuture<YarnWorkerNode>>>
requestResourceFutures;
private final RegisterApplicationMasterResponseReflector
registerApplicationMasterResponseReflector;
private final YarnResourceManagerClientFactory yarnResourceManagerClientFactory;
private final YarnNodeManagerClientFactory yarnNodeManagerClientFactory;
/** Client to communicate with the Resource Manager (YARN's master). */
private AMRMClientAsync<AMRMClient.ContainerRequest> resourceManagerClient;
/** Client to communicate with the Node manager and launch TaskExecutor processes. */
private NMClientAsync nodeManagerClient;
private TaskExecutorProcessSpecContainerResourcePriorityAdapter
taskExecutorProcessSpecContainerResourcePriorityAdapter;
private String taskManagerNodeLabel;
private final Phaser trackerOfReleasedResources;
private final Set<String> lastBlockedNodes = new HashSet<>();
private volatile boolean isRunning = false;
public YarnResourceManagerDriver(
Configuration flinkConfig,
YarnResourceManagerDriverConfiguration configuration,
YarnResourceManagerClientFactory yarnResourceManagerClientFactory,
YarnNodeManagerClientFactory yarnNodeManagerClientFactory) {
super(flinkConfig, GlobalConfiguration.loadConfiguration(configuration.getCurrentDir()));
this.yarnConfig = Utils.getYarnAndHadoopConfiguration(flinkConfig);
this.requestResourceFutures = new HashMap<>();
this.configuration = configuration;
final int yarnHeartbeatIntervalMS =
flinkConfig.get(YarnConfigOptions.HEARTBEAT_DELAY_SECONDS) * 1000;
final long yarnExpiryIntervalMS =
yarnConfig.getLong(
YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS,
YarnConfiguration.DEFAULT_RM_AM_EXPIRY_INTERVAL_MS);
if (yarnHeartbeatIntervalMS >= yarnExpiryIntervalMS) {
log.warn(
"The heartbeat interval of the Flink Application master ({}) is greater "
+ "than YARN's expiry interval ({}). The application is likely to be killed by YARN.",
yarnHeartbeatIntervalMS,
yarnExpiryIntervalMS);
}
yarnHeartbeatIntervalMillis = yarnHeartbeatIntervalMS;
containerRequestHeartbeatIntervalMillis =
Math.toIntExact(
flinkConfig
.get(
YarnConfigOptions
.CONTAINER_REQUEST_HEARTBEAT_INTERVAL_MILLISECONDS)
.toMillis());
this.taskManagerNodeLabel = flinkConfig.get(YarnConfigOptions.TASK_MANAGER_NODE_LABEL);
this.registerApplicationMasterResponseReflector =
new RegisterApplicationMasterResponseReflector(log);
this.yarnResourceManagerClientFactory = yarnResourceManagerClientFactory;
this.yarnNodeManagerClientFactory = yarnNodeManagerClientFactory;
this.trackerOfReleasedResources = new Phaser();
}
// ------------------------------------------------------------------------
// ResourceManagerDriver
// ------------------------------------------------------------------------
@Override
protected void initializeInternal() throws Exception {
isRunning = true;
try {
resourceManagerClient =
yarnResourceManagerClientFactory.createResourceManagerClient(
yarnHeartbeatIntervalMillis, new AMRMCallbackHandler());
resourceManagerClient.init(yarnConfig);
resourceManagerClient.start();
final RegisterApplicationMasterResponse registerApplicationMasterResponse =
registerApplicationMaster();
getContainersFromPreviousAttempts(registerApplicationMasterResponse);
taskExecutorProcessSpecContainerResourcePriorityAdapter =
new TaskExecutorProcessSpecContainerResourcePriorityAdapter(
registerApplicationMasterResponse.getMaximumResourceCapability(),
ExternalResourceUtils.getExternalResourceConfigurationKeys(
flinkConfig,
YarnConfigOptions.EXTERNAL_RESOURCE_YARN_CONFIG_KEY_SUFFIX));
} catch (Exception e) {
throw new ResourceManagerException("Could not start resource manager client.", e);
}
nodeManagerClient =
yarnNodeManagerClientFactory.createNodeManagerClient(new NMCallbackHandler());
nodeManagerClient.init(yarnConfig);
nodeManagerClient.start();
}
@Override
public void terminate() throws Exception {
isRunning = false;
// wait for all containers to stop
trackerOfReleasedResources.register();
trackerOfReleasedResources.arriveAndAwaitAdvance();
// shut down all components
Exception exception = null;
if (resourceManagerClient != null) {
try {
resourceManagerClient.stop();
} catch (Exception e) {
exception = e;
}
}
if (nodeManagerClient != null) {
try {
nodeManagerClient.stop();
} catch (Exception e) {
exception = ExceptionUtils.firstOrSuppressed(e, exception);
}
}
if (exception != null) {
throw exception;
}
}
@Override
public void deregisterApplication(
ApplicationStatus finalStatus, @Nullable String optionalDiagnostics) {
// first, de-register from YARN
final FinalApplicationStatus yarnStatus = getYarnStatus(finalStatus);
log.info(
"Unregister application from the YARN Resource Manager with final status {}.",
yarnStatus);
final Optional<URL> historyServerURL = HistoryServerUtils.getHistoryServerURL(flinkConfig);
final String appTrackingUrl = historyServerURL.map(URL::toString).orElse("");
try {
resourceManagerClient.unregisterApplicationMaster(
yarnStatus, optionalDiagnostics, appTrackingUrl);
} catch (YarnException | IOException e) {
log.error("Could not unregister the application master.", e);
}
Utils.deleteApplicationFiles(configuration.getYarnFiles());
}
@Override
public CompletableFuture<YarnWorkerNode> requestResource(
TaskExecutorProcessSpec taskExecutorProcessSpec) {
checkInitialized();
final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>();
final Optional<TaskExecutorProcessSpecContainerResourcePriorityAdapter.PriorityAndResource>
priorityAndResourceOpt =
taskExecutorProcessSpecContainerResourcePriorityAdapter
.getPriorityAndResource(taskExecutorProcessSpec);
if (!priorityAndResourceOpt.isPresent()) {
requestResourceFuture.completeExceptionally(
new ResourceManagerException(
String.format(
"Could not compute the container Resource from the given TaskExecutorProcessSpec %s. "
+ "This usually indicates the requested resource is larger than Yarn's max container resource limit.",
taskExecutorProcessSpec)));
} else {
final Priority priority = priorityAndResourceOpt.get().getPriority();
final Resource resource = priorityAndResourceOpt.get().getResource();
FutureUtils.assertNoException(
requestResourceFuture.handle(
(ignore, t) -> {
if (t == null) {
return null;
}
if (t instanceof CancellationException) {
final Queue<CompletableFuture<YarnWorkerNode>>
pendingRequestResourceFutures =
requestResourceFutures.getOrDefault(
taskExecutorProcessSpec,
new LinkedList<>());
Preconditions.checkState(
pendingRequestResourceFutures.remove(
requestResourceFuture));
log.info(
"cancelling pending request with priority {}, remaining {} pending container requests.",
priority,
pendingRequestResourceFutures.size());
int pendingRequestsSizeBeforeCancel =
pendingRequestResourceFutures.size() + 1;
final Iterator<AMRMClient.ContainerRequest>
pendingContainerRequestIterator =
getPendingRequestsAndCheckConsistency(
priority,
resource,
pendingRequestsSizeBeforeCancel)
.iterator();
Preconditions.checkState(
pendingContainerRequestIterator.hasNext());
final AMRMClient.ContainerRequest pendingRequest =
pendingContainerRequestIterator.next();
removeContainerRequest(pendingRequest);
if (pendingRequestResourceFutures.isEmpty()) {
requestResourceFutures.remove(taskExecutorProcessSpec);
}
if (getNumRequestedNotAllocatedWorkers() <= 0) {
resourceManagerClient.setHeartbeatInterval(
yarnHeartbeatIntervalMillis);
}
} else {
log.error("Error completing resource request.", t);
ExceptionUtils.rethrow(t);
}
return null;
}));
addContainerRequest(resource, priority);
// make sure we transmit the request fast and receive fast news of granted allocations
resourceManagerClient.setHeartbeatInterval(containerRequestHeartbeatIntervalMillis);
requestResourceFutures
.computeIfAbsent(taskExecutorProcessSpec, ignore -> new LinkedList<>())
.add(requestResourceFuture);
log.info(
"Requesting new TaskExecutor container with resource {}, priority {}.",
taskExecutorProcessSpec,
priority);
}
return requestResourceFuture;
}
private void tryUpdateApplicationBlockList() {
Set<String> currentBlockedNodes = getBlockedNodeRetriever().getAllBlockedNodeIds();
if (!currentBlockedNodes.equals(lastBlockedNodes)) {
AMRMClientAsyncReflector.INSTANCE.tryUpdateBlockList(
resourceManagerClient,
new ArrayList<>(getDifference(currentBlockedNodes, lastBlockedNodes)),
new ArrayList<>(getDifference(lastBlockedNodes, currentBlockedNodes)));
this.lastBlockedNodes.clear();
this.lastBlockedNodes.addAll(currentBlockedNodes);
}
}
private static Set<String> getDifference(Set<String> setA, Set<String> setB) {
Set<String> difference = new HashSet<>(setA);
difference.removeAll(setB);
return difference;
}
@Override
public void releaseResource(YarnWorkerNode workerNode) {
final Container container = workerNode.getContainer();
log.info("Stopping container {}.", workerNode.getResourceID().getStringWithMetadata());
trackerOfReleasedResources.register();
nodeManagerClient.stopContainerAsync(container.getId(), container.getNodeId());
resourceManagerClient.releaseAssignedContainer(container.getId());
}
// ------------------------------------------------------------------------
// Internal
// ------------------------------------------------------------------------
private void onContainersOfPriorityAllocated(Priority priority, List<Container> containers) {
final Optional<
TaskExecutorProcessSpecContainerResourcePriorityAdapter
.TaskExecutorProcessSpecAndResource>
taskExecutorProcessSpecAndResourceOpt =
taskExecutorProcessSpecContainerResourcePriorityAdapter
.getTaskExecutorProcessSpecAndResource(priority);
Preconditions.checkState(
taskExecutorProcessSpecAndResourceOpt.isPresent(),
"Receive %s containers with unrecognized priority %s. This should not happen.",
containers.size(),
priority.getPriority());
final TaskExecutorProcessSpec taskExecutorProcessSpec =
taskExecutorProcessSpecAndResourceOpt.get().getTaskExecutorProcessSpec();
final Resource resource = taskExecutorProcessSpecAndResourceOpt.get().getResource();
final Queue<CompletableFuture<YarnWorkerNode>> pendingRequestResourceFutures =
requestResourceFutures.getOrDefault(taskExecutorProcessSpec, new LinkedList<>());
log.info(
"Received {} containers with priority {}, {} pending container requests.",
containers.size(),
priority,
pendingRequestResourceFutures.size());
final Iterator<Container> containerIterator = containers.iterator();
final Iterator<AMRMClient.ContainerRequest> pendingContainerRequestIterator =
getPendingRequestsAndCheckConsistency(
priority, resource, pendingRequestResourceFutures.size())
.iterator();
int numAccepted = 0;
while (containerIterator.hasNext() && pendingContainerRequestIterator.hasNext()) {
final Container container = containerIterator.next();
final AMRMClient.ContainerRequest pendingRequest =
pendingContainerRequestIterator.next();
final ResourceID resourceId = getContainerResourceId(container);
final CompletableFuture<YarnWorkerNode> requestResourceFuture =
pendingRequestResourceFutures.poll();
Preconditions.checkState(requestResourceFuture != null);
if (pendingRequestResourceFutures.isEmpty()) {
requestResourceFutures.remove(taskExecutorProcessSpec);
}
requestResourceFuture.complete(new YarnWorkerNode(container, resourceId));
startTaskExecutorInContainerAsync(container, taskExecutorProcessSpec, resourceId);
removeContainerRequest(pendingRequest);
numAccepted++;
}
int numExcess = 0;
while (containerIterator.hasNext()) {
returnExcessContainer(containerIterator.next());
numExcess++;
}
log.info(
"Accepted {} requested containers, returned {} excess containers, {} pending container requests of resource {}.",
numAccepted,
numExcess,
pendingRequestResourceFutures.size(),
resource);
}
private int getNumRequestedNotAllocatedWorkers() {
return requestResourceFutures.values().stream().mapToInt(Queue::size).sum();
}
private void addContainerRequest(Resource resource, Priority priority) {
// update blocklist
tryUpdateApplicationBlockList();
AMRMClient.ContainerRequest containerRequest =
ContainerRequestReflector.INSTANCE.getContainerRequest(
resource, priority, taskManagerNodeLabel);
resourceManagerClient.addContainerRequest(containerRequest);
}
private void removeContainerRequest(AMRMClient.ContainerRequest pendingContainerRequest) {
log.info("Removing container request {}.", pendingContainerRequest);
resourceManagerClient.removeContainerRequest(pendingContainerRequest);
}
private void returnExcessContainer(Container excessContainer) {
log.info("Returning excess container {}.", excessContainer.getId());
resourceManagerClient.releaseAssignedContainer(excessContainer.getId());
}
private void startTaskExecutorInContainerAsync(
Container container,
TaskExecutorProcessSpec taskExecutorProcessSpec,
ResourceID resourceId) {
final CompletableFuture<ContainerLaunchContext> containerLaunchContextFuture =
FutureUtils.supplyAsync(
() ->
createTaskExecutorLaunchContext(
resourceId,
container.getNodeId().getHost(),
taskExecutorProcessSpec),
getIoExecutor());
FutureUtils.assertNoException(
containerLaunchContextFuture.handleAsync(
(context, exception) -> {
if (exception == null) {
nodeManagerClient.startContainerAsync(container, context);
} else {
getResourceEventHandler()
.onWorkerTerminated(resourceId, exception.getMessage());
}
return null;
},
getMainThreadExecutor()));
}
private Collection<AMRMClient.ContainerRequest> getPendingRequestsAndCheckConsistency(
Priority priority, Resource resource, int expectedNum) {
final List<AMRMClient.ContainerRequest> matchingRequests =
resourceManagerClient
.getMatchingRequests(priority, ResourceRequest.ANY, resource)
.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
Preconditions.checkState(
matchingRequests.size() == expectedNum,
"The RMClient's and YarnResourceManagers internal state about the number of pending container requests for priority %s has diverged. "
+ "Number client's pending container requests %s != Number RM's pending container requests %s.",
priority.getPriority(),
matchingRequests.size(),
expectedNum);
return matchingRequests;
}
private ContainerLaunchContext createTaskExecutorLaunchContext(
ResourceID containerId, String host, TaskExecutorProcessSpec taskExecutorProcessSpec)
throws Exception {
// init the ContainerLaunchContext
final String currDir = configuration.getCurrentDir();
final ContaineredTaskManagerParameters taskManagerParameters =
ContaineredTaskManagerParameters.create(flinkConfig, taskExecutorProcessSpec);
log.info(
"TaskExecutor {} will be started on {} with {}.",
containerId.getStringWithMetadata(),
host,
taskExecutorProcessSpec);
final Configuration taskManagerConfig = BootstrapTools.cloneConfiguration(flinkConfig);
taskManagerConfig.set(
TaskManagerOptions.TASK_MANAGER_RESOURCE_ID, containerId.getResourceIdString());
taskManagerConfig.set(
TaskManagerOptionsInternal.TASK_MANAGER_RESOURCE_ID_METADATA,
containerId.getMetadata());
final String taskManagerDynamicProperties =
BootstrapTools.getDynamicPropertiesAsString(flinkClientConfig, taskManagerConfig);
log.debug("TaskManager configuration: {}", taskManagerConfig);
final ContainerLaunchContext taskExecutorLaunchContext =
Utils.createTaskExecutorContext(
flinkConfig,
yarnConfig,
configuration,
taskManagerParameters,
taskManagerDynamicProperties,
currDir,
YarnTaskExecutorRunner.class,
log);
taskExecutorLaunchContext.getEnvironment().put(ENV_FLINK_NODE_ID, host);
return taskExecutorLaunchContext;
}
@VisibleForTesting
Optional<Resource> getContainerResource(TaskExecutorProcessSpec taskExecutorProcessSpec) {
Optional<TaskExecutorProcessSpecContainerResourcePriorityAdapter.PriorityAndResource> opt =
taskExecutorProcessSpecContainerResourcePriorityAdapter.getPriorityAndResource(
taskExecutorProcessSpec);
if (!opt.isPresent()) {
return Optional.empty();
}
return Optional.of(opt.get().getResource());
}
private RegisterApplicationMasterResponse registerApplicationMaster() throws Exception {
return resourceManagerClient.registerApplicationMaster(
configuration.getRpcAddress(),
ResourceManagerUtils.parseRestBindPortFromWebInterfaceUrl(
configuration.getWebInterfaceUrl()),
configuration.getWebInterfaceUrl());
}
private void getContainersFromPreviousAttempts(
final RegisterApplicationMasterResponse registerApplicationMasterResponse) {
final List<Container> containersFromPreviousAttempts =
registerApplicationMasterResponseReflector.getContainersFromPreviousAttempts(
registerApplicationMasterResponse);
final List<YarnWorkerNode> recoveredWorkers = new ArrayList<>();
log.info(
"Recovered {} containers from previous attempts ({}).",
containersFromPreviousAttempts.size(),
containersFromPreviousAttempts);
for (Container container : containersFromPreviousAttempts) {
final YarnWorkerNode worker =
new YarnWorkerNode(container, getContainerResourceId(container));
recoveredWorkers.add(worker);
}
getResourceEventHandler().onPreviousAttemptWorkersRecovered(recoveredWorkers);
}
// ------------------------------------------------------------------------
// Utility methods
// ------------------------------------------------------------------------
/**
* Converts a Flink application status
|
YarnResourceManagerDriver
|
java
|
spring-projects__spring-boot
|
module/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/logging/OpenTelemetryLoggingAutoConfigurationTests.java
|
{
"start": 5528,
"end": 5870
}
|
class ____ {
@Bean
BatchLogRecordProcessor customBatchLogRecordProcessor() {
return BatchLogRecordProcessor.builder(new NoopLogRecordExporter()).build();
}
@Bean
SdkLoggerProvider customSdkLoggerProvider() {
return SdkLoggerProvider.builder().build();
}
}
@Configuration(proxyBeanMethods = false)
static
|
UserConfiguration
|
java
|
apache__camel
|
components/camel-jgroups-raft/src/generated/java/org/apache/camel/component/jgroups/raft/JGroupsRaftEndpointUriFactory.java
|
{
"start": 522,
"end": 2309
}
|
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":clusterName";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(6);
props.add("bridgeErrorHandler");
props.add("clusterName");
props.add("enableRoleChangeEvents");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("lazyStartProducer");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
SECRET_PROPERTY_NAMES = Collections.emptySet();
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "jgroups-raft".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "clusterName", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
|
JGroupsRaftEndpointUriFactory
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/admin/DeleteShareGroupsResult.java
|
{
"start": 1075,
"end": 1863
}
|
class ____ {
private final Map<String, KafkaFuture<Void>> futures;
DeleteShareGroupsResult(final Map<String, KafkaFuture<Void>> futures) {
this.futures = futures;
}
/**
* Return a map from group id to futures which can be used to check the status of
* individual deletions.
*/
public Map<String, KafkaFuture<Void>> deletedGroups() {
Map<String, KafkaFuture<Void>> deletedGroups = new HashMap<>(futures.size());
deletedGroups.putAll(futures);
return deletedGroups;
}
/**
* Return a future which succeeds only if all the share group deletions succeed.
*/
public KafkaFuture<Void> all() {
return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture<?>[0]));
}
}
|
DeleteShareGroupsResult
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/stubbing/CloningParameterTest.java
|
{
"start": 3659,
"end": 3839
}
|
interface ____ {
void sendEmail(int i, Person person);
void sendGroupEmail(int i, Person[] persons);
List<?> getAllEmails(Person person);
}
}
|
EmailSender
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/operator/topn/ValueExtractorForBoolean.java
|
{
"start": 2208,
"end": 3008
}
|
class ____ extends ValueExtractorForBoolean {
private final BooleanBlock block;
ForBlock(TopNEncoder encoder, boolean inKey, BooleanBlock block) {
super(encoder, inKey);
this.block = block;
}
@Override
public void writeValue(BreakingBytesRefBuilder values, int position) {
int size = block.getValueCount(position);
writeCount(values, size);
if (size == 1 && inKey) {
// Will read results from the key
return;
}
int start = block.getFirstValueIndex(position);
int end = start + size;
for (int i = start; i < end; i++) {
actualWriteValue(values, block.getBoolean(i));
}
}
}
}
|
ForBlock
|
java
|
elastic__elasticsearch
|
x-pack/plugin/enrich/src/main/java/org/elasticsearch/xpack/enrich/action/EnrichCoordinatorStatsAction.java
|
{
"start": 1733,
"end": 2197
}
|
class ____ extends ActionType<EnrichCoordinatorStatsAction.Response> {
public static final EnrichCoordinatorStatsAction INSTANCE = new EnrichCoordinatorStatsAction();
public static final String NAME = "cluster:monitor/xpack/enrich/coordinator_stats";
private EnrichCoordinatorStatsAction() {
super(NAME);
}
// This always executes on all ingest nodes, hence no node ids need to be provided.
public static
|
EnrichCoordinatorStatsAction
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/LocalSASKeyGeneratorImpl.java
|
{
"start": 2084,
"end": 2147
}
|
class ____ typically used for testing purposes.
*
*/
public
|
gets
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/MediaTypesWithSuffixHandlingTest.java
|
{
"start": 5745,
"end": 8020
}
|
class ____ implements ServerMessageBodyWriter<Object>, ServerMessageBodyReader<Object> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) {
return true;
}
@Override
public void writeResponse(Object o, Type genericType, ServerRequestContext context)
throws WebApplicationException, IOException {
String response = (String) o;
response += " - suffix writer";
context.getOrCreateOutputStream().write(response.getBytes(StandardCharsets.UTF_8));
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
throw new IllegalStateException("should never have been called");
}
@Override
public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
throw new IllegalStateException("should never have been called");
}
@Override
public boolean isReadable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo lazyMethod,
MediaType mediaType) {
return true;
}
@Override
public Object readFrom(Class<Object> type, Type genericType, MediaType mediaType,
ServerRequestContext context) throws WebApplicationException {
return "from reader suffix";
}
@Override
public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
throw new IllegalStateException("should never have been called");
}
@Override
public Object readFrom(Class<Object> aClass, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> multivaluedMap, InputStream inputStream)
throws WebApplicationException {
throw new IllegalStateException("should never have been called");
}
}
}
|
SuffixMessageBodyWriter
|
java
|
spring-projects__spring-boot
|
module/spring-boot-zipkin/src/main/java/org/springframework/boot/zipkin/autoconfigure/ZipkinHttpClientBuilderCustomizer.java
|
{
"start": 740,
"end": 956
}
|
interface ____ can be implemented by beans wishing to customize the
* {@link Builder HttpClient.Builder} used to send spans to Zipkin.
*
* @author Moritz Halbritter
* @since 4.0.0
*/
@FunctionalInterface
public
|
that
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__nextToken.java
|
{
"start": 199,
"end": 3820
}
|
class ____ extends TestCase {
public void test_next() throws Exception {
String text = "\"aaa\"";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.LITERAL_INT);
Assert.assertEquals(JSONToken.LITERAL_STRING, lexer.token());
}
public void test_next_1() throws Exception {
String text = "[";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.LITERAL_INT);
Assert.assertEquals(JSONToken.LBRACKET, lexer.token());
}
public void test_next_2() throws Exception {
String text = "{";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.LITERAL_INT);
Assert.assertEquals(JSONToken.LBRACE, lexer.token());
}
public void test_next_3() throws Exception {
String text = "{";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.LBRACKET);
Assert.assertEquals(JSONToken.LBRACE, lexer.token());
}
public void test_next_4() throws Exception {
String text = "";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.LBRACKET);
Assert.assertEquals(JSONToken.EOF, lexer.token());
}
public void test_next_5() throws Exception {
String text = " \n\r\t\f\b 1";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.LBRACKET);
Assert.assertEquals(JSONToken.LITERAL_INT, lexer.token());
}
public void test_next_6() throws Exception {
String text = "";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.EOF);
Assert.assertEquals(JSONToken.EOF, lexer.token());
}
public void test_next_7() throws Exception {
String text = "{";
JSONScanner lexer = new JSONScanner(text);
lexer.nextToken(JSONToken.EOF);
Assert.assertEquals(JSONToken.LBRACE, lexer.token());
}
public void test_next_8() throws Exception {
String text = "\n\r\t\f\b :{";
JSONScanner lexer = new JSONScanner(text);
lexer.nextTokenWithColon(JSONToken.LBRACE);
Assert.assertEquals(JSONToken.LBRACE, lexer.token());
}
public void test_next_9() throws Exception {
String text = "\n\r\t\f\b :[";
JSONScanner lexer = new JSONScanner(text);
lexer.nextTokenWithColon(JSONToken.LBRACE);
Assert.assertEquals(JSONToken.LBRACKET, lexer.token());
}
public void test_next_10() throws Exception {
String text = "\n\r\t\f\b :";
JSONScanner lexer = new JSONScanner(text);
lexer.nextTokenWithColon(JSONToken.LBRACE);
Assert.assertEquals(JSONToken.EOF, lexer.token());
}
public void test_next_11() throws Exception {
String text = "\n\r\t\f\b :{";
JSONScanner lexer = new JSONScanner(text);
lexer.nextTokenWithColon(JSONToken.LBRACKET);
Assert.assertEquals(JSONToken.LBRACE, lexer.token());
}
public void test_next_12() throws Exception {
String text = "\n\r\t\f\b :";
JSONScanner lexer = new JSONScanner(text);
lexer.nextTokenWithColon(JSONToken.LBRACKET);
Assert.assertEquals(JSONToken.EOF, lexer.token());
}
public void test_next_13() throws Exception {
String text = "\n\r\t\f\b :\n\r\t\f\b ";
JSONScanner lexer = new JSONScanner(text);
lexer.nextTokenWithColon(JSONToken.LBRACKET);
Assert.assertEquals(JSONToken.EOF, lexer.token());
}
}
|
JSONScannerTest__nextToken
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/delete/DeleteRequestTests.java
|
{
"start": 773,
"end": 1403
}
|
class ____ extends ESTestCase {
public void testValidation() {
{
final DeleteRequest request = new DeleteRequest("index4", "0");
final ActionRequestValidationException validate = request.validate();
assertThat(validate, nullValue());
}
{
final DeleteRequest request = new DeleteRequest("index4", null);
final ActionRequestValidationException validate = request.validate();
assertThat(validate, not(nullValue()));
assertThat(validate.validationErrors(), hasItems("id is missing"));
}
}
}
|
DeleteRequestTests
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/OpenshiftBuildConfigsEndpointBuilderFactory.java
|
{
"start": 15514,
"end": 18698
}
|
interface ____ {
/**
* OpenShift Build Config (camel-kubernetes)
* Perform operations on OpenShift Build Configs.
*
* Category: container,cloud
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-kubernetes
*
* @return the dsl builder for the headers' name.
*/
default OpenshiftBuildConfigsHeaderNameBuilder openshiftBuildConfigs() {
return OpenshiftBuildConfigsHeaderNameBuilder.INSTANCE;
}
/**
* OpenShift Build Config (camel-kubernetes)
* Perform operations on OpenShift Build Configs.
*
* Category: container,cloud
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-kubernetes
*
* Syntax: <code>openshift-build-configs:masterUrl</code>
*
* Path parameter: masterUrl (required)
* URL to a remote Kubernetes API server. This should only be used when
* your Camel application is connecting from outside Kubernetes. If you
* run your Camel application inside Kubernetes, then you can use local
* or client as the URL to tell Camel to run in local mode. If you
* connect remotely to Kubernetes, then you may also need some of the
* many other configuration options for secured connection with
* certificates, etc.
*
* @param path masterUrl
* @return the dsl builder
*/
default OpenshiftBuildConfigsEndpointBuilder openshiftBuildConfigs(String path) {
return OpenshiftBuildConfigsEndpointBuilderFactory.endpointBuilder("openshift-build-configs", path);
}
/**
* OpenShift Build Config (camel-kubernetes)
* Perform operations on OpenShift Build Configs.
*
* Category: container,cloud
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-kubernetes
*
* Syntax: <code>openshift-build-configs:masterUrl</code>
*
* Path parameter: masterUrl (required)
* URL to a remote Kubernetes API server. This should only be used when
* your Camel application is connecting from outside Kubernetes. If you
* run your Camel application inside Kubernetes, then you can use local
* or client as the URL to tell Camel to run in local mode. If you
* connect remotely to Kubernetes, then you may also need some of the
* many other configuration options for secured connection with
* certificates, etc.
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path masterUrl
* @return the dsl builder
*/
default OpenshiftBuildConfigsEndpointBuilder openshiftBuildConfigs(String componentName, String path) {
return OpenshiftBuildConfigsEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the OpenShift Build Config component.
*/
public static
|
OpenshiftBuildConfigsBuilders
|
java
|
apache__camel
|
core/camel-support/src/main/java/org/apache/camel/support/DefaultAutoMockInterceptStrategy.java
|
{
"start": 955,
"end": 1621
}
|
class ____ implements AutoMockInterceptStrategy {
private String pattern;
private boolean skip;
public DefaultAutoMockInterceptStrategy(String pattern, boolean skip) {
this.pattern = pattern;
this.skip = skip;
}
public DefaultAutoMockInterceptStrategy() {
}
@Override
public String getPattern() {
return pattern;
}
@Override
public void setPattern(String pattern) {
this.pattern = pattern;
}
@Override
public boolean isSkip() {
return skip;
}
@Override
public void setSkip(boolean skip) {
this.skip = skip;
}
}
|
DefaultAutoMockInterceptStrategy
|
java
|
google__guava
|
android/guava/src/com/google/common/collect/StandardTable.java
|
{
"start": 24556,
"end": 25815
}
|
class ____ extends TableSet<Entry<R, Map<C, V>>> {
@Override
public Iterator<Entry<R, Map<C, V>>> iterator() {
return asMapEntryIterator(backingMap.keySet(), StandardTable.this::row);
}
@Override
public int size() {
return backingMap.size();
}
@Override
public boolean contains(@Nullable Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return entry.getKey() != null
&& entry.getValue() instanceof Map
&& Collections2.safeContains(backingMap.entrySet(), entry);
}
return false;
}
@Override
public boolean remove(@Nullable Object obj) {
if (obj instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) obj;
return entry.getKey() != null
&& entry.getValue() instanceof Map
&& backingMap.entrySet().remove(entry);
}
return false;
}
}
}
@LazyInit private transient @Nullable ColumnMap columnMap;
@Override
public Map<C, Map<R, V>> columnMap() {
ColumnMap result = columnMap;
return (result == null) ? columnMap = new ColumnMap() : result;
}
@WeakOuter
private final
|
EntrySet
|
java
|
google__dagger
|
javatests/dagger/functional/producers/subcomponent/UsesProducerModuleSubcomponents.java
|
{
"start": 2462,
"end": 2572
}
|
interface ____
extends UsesProducerModuleSubcomponents {}
}
|
ParentIncludesProductionSubcomponentTransitively
|
java
|
apache__camel
|
components/camel-aws/camel-aws-bedrock/src/test/java/org/apache/camel/component/aws2/bedrock/agentruntime/BedrockAgentRuntimeClientFactoryTest.java
|
{
"start": 1635,
"end": 4096
}
|
class ____ {
@Test
public void getStandardBedrockAgentRuntimeClientDefault() {
BedrockAgentRuntimeConfiguration bedrockConfiguration = new BedrockAgentRuntimeConfiguration();
BedrockAgentRuntimeInternalClient bedrockClient
= BedrockAgentRuntimeClientFactory.getBedrockAgentRuntimeClient(bedrockConfiguration);
assertTrue(bedrockClient instanceof BedrockAgentRuntimeClientStandardImpl);
}
@Test
public void getStandardDefaultBedrockAgentRuntimeClient() {
BedrockAgentRuntimeConfiguration bedrockConfiguration = new BedrockAgentRuntimeConfiguration();
bedrockConfiguration.setUseDefaultCredentialsProvider(false);
BedrockAgentRuntimeInternalClient bedrockClient
= BedrockAgentRuntimeClientFactory.getBedrockAgentRuntimeClient(bedrockConfiguration);
assertTrue(bedrockClient instanceof BedrockAgentRuntimeClientStandardImpl);
}
@Test
public void getIAMOptimizedBedrockAgentRuntimeClient() {
BedrockAgentRuntimeConfiguration bedrockConfiguration = new BedrockAgentRuntimeConfiguration();
bedrockConfiguration.setUseDefaultCredentialsProvider(true);
BedrockAgentRuntimeInternalClient bedrockClient
= BedrockAgentRuntimeClientFactory.getBedrockAgentRuntimeClient(bedrockConfiguration);
assertTrue(bedrockClient instanceof BedrockAgentRuntimeClientIAMOptimizedImpl);
}
@Test
public void getSessionTokenBedrockAgentRuntimeClient() {
BedrockAgentRuntimeConfiguration bedrockConfiguration = new BedrockAgentRuntimeConfiguration();
bedrockConfiguration.setUseSessionCredentials(true);
BedrockAgentRuntimeInternalClient bedrockClient
= BedrockAgentRuntimeClientFactory.getBedrockAgentRuntimeClient(bedrockConfiguration);
assertTrue(bedrockClient instanceof BedrockAgentRuntimeClientSessionTokenImpl);
}
@Test
public void getProfileBedrockAgentRuntimeClient() {
BedrockAgentRuntimeConfiguration bedrockConfiguration = new BedrockAgentRuntimeConfiguration();
bedrockConfiguration.setUseProfileCredentialsProvider(true);
BedrockAgentRuntimeInternalClient bedrockClient
= BedrockAgentRuntimeClientFactory.getBedrockAgentRuntimeClient(bedrockConfiguration);
assertTrue(bedrockClient instanceof BedrockAgentRuntimeClientIAMProfileOptimizedImpl);
}
}
|
BedrockAgentRuntimeClientFactoryTest
|
java
|
apache__flink
|
flink-state-backends/flink-statebackend-forst/src/test/java/org/apache/flink/state/forst/ForStStateTestBase.java
|
{
"start": 2158,
"end": 2279
}
|
class ____ all forst state tests, providing building the AEC and StateBackend logic, and
* some tool methods.
*/
public
|
for
|
java
|
apache__camel
|
components/camel-bean/src/generated/java/org/apache/camel/component/bean/BeanEndpointConfigurer.java
|
{
"start": 731,
"end": 2875
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
BeanEndpoint target = (BeanEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "method": target.setMethod(property(camelContext, java.lang.String.class, value)); return true;
case "parameters": target.setParameters(property(camelContext, java.util.Map.class, value)); return true;
case "scope": target.setScope(property(camelContext, org.apache.camel.BeanScope.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "method": return java.lang.String.class;
case "parameters": return java.util.Map.class;
case "scope": return org.apache.camel.BeanScope.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
BeanEndpoint target = (BeanEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "method": return target.getMethod();
case "parameters": return target.getParameters();
case "scope": return target.getScope();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "parameters": return java.lang.Object.class;
default: return null;
}
}
}
|
BeanEndpointConfigurer
|
java
|
spring-projects__spring-security
|
web/src/test/java/org/springframework/security/web/authentication/session/ChangeSessionIdAuthenticationStrategyTests.java
|
{
"start": 887,
"end": 1237
}
|
class ____ {
@Test
public void applySessionFixation() {
MockHttpServletRequest request = new MockHttpServletRequest();
String id = request.getSession().getId();
new ChangeSessionIdAuthenticationStrategy().applySessionFixation(request);
assertThat(request.getSession().getId()).isNotEqualTo(id);
}
}
|
ChangeSessionIdAuthenticationStrategyTests
|
java
|
junit-team__junit5
|
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java
|
{
"start": 15061,
"end": 15161
}
|
class ____ {
}
@SelectMethod(value = "SomeClass#someMethod", name = "testMethod")
|
ValueAndTypeName
|
java
|
quarkusio__quarkus
|
integration-tests/openapi/src/main/java/io/quarkus/it/openapi/spring/ByteArrayResource.java
|
{
"start": 735,
"end": 2754
}
|
class ____ {
@GetMapping("/justByteArray/{fileName}")
public byte[] justByteArray(@PathVariable("fileName") String filename) {
return toByteArray(filename);
}
@PostMapping("/justByteArray")
public byte[] justByteArray(byte[] inputStream) {
return inputStream;
}
@GetMapping("/responseEntityByteArray/{fileName}")
public ResponseEntity<byte[]> responseEntityByteArray(@PathVariable("fileName") String filename) {
return ResponseEntity.ok(toByteArray(filename));
}
@PostMapping("/responseEntityByteArray")
public ResponseEntity<byte[]> responseEntityByteArray(byte[] inputStream) {
return ResponseEntity.ok(inputStream);
}
@GetMapping("/optionalByteArray/{fileName}")
public Optional<byte[]> optionalByteArray(@PathVariable("fileName") String filename) {
return Optional.of(toByteArray(filename));
}
@PostMapping("/optionalByteArray")
public Optional<byte[]> optionalByteArray(Optional<byte[]> inputStream) {
return inputStream;
}
@GetMapping("/uniByteArray/{fileName}")
public Uni<byte[]> uniByteArray(@PathVariable("fileName") String filename) {
return Uni.createFrom().item(toByteArray(filename));
}
@GetMapping("/completionStageByteArray/{fileName}")
public CompletionStage<byte[]> completionStageByteArray(@PathVariable("fileName") String filename) {
return CompletableFuture.completedStage(toByteArray(filename));
}
@GetMapping("/completedFutureByteArray/{fileName}")
public CompletableFuture<byte[]> completedFutureByteArray(@PathVariable("fileName") String filename) {
return CompletableFuture.completedFuture(toByteArray(filename));
}
private byte[] toByteArray(String filename) {
try {
String f = URLDecoder.decode(filename, "UTF-8");
return Files.readAllBytes(Paths.get(f));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
|
ByteArrayResource
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/StaticQualifiedUsingExpressionTest.java
|
{
"start": 2089,
"end": 2199
}
|
class ____ {
static MyClass myClass = new MyClass();
}
public
|
MyStaticClass
|
java
|
apache__kafka
|
streams/src/test/java/org/apache/kafka/streams/state/internals/InMemoryWindowStoreTest.java
|
{
"start": 1965,
"end": 8519
}
|
class ____ extends AbstractWindowBytesStoreTest {
private static final String STORE_NAME = "InMemoryWindowStore";
@Override
<K, V> WindowStore<K, V> buildWindowStore(final long retentionPeriod,
final long windowSize,
final boolean retainDuplicates,
final Serde<K> keySerde,
final Serde<V> valueSerde) {
return Stores.windowStoreBuilder(
Stores.inMemoryWindowStore(
STORE_NAME,
ofMillis(retentionPeriod),
ofMillis(windowSize),
retainDuplicates),
keySerde,
valueSerde)
.build();
}
@SuppressWarnings("unchecked")
@Test
public void shouldRestore() {
// should be empty initially
assertFalse(windowStore.all().hasNext());
final StateSerdes<Integer, String> serdes = new StateSerdes<>("", Serdes.Integer(),
Serdes.String());
final List<KeyValue<byte[], byte[]>> restorableEntries = new LinkedList<>();
restorableEntries
.add(new KeyValue<>(toStoreKeyBinary(1, 0L, 0, serdes).get(), serdes.rawValue("one")));
restorableEntries.add(new KeyValue<>(toStoreKeyBinary(2, WINDOW_SIZE, 0, serdes).get(),
serdes.rawValue("two")));
restorableEntries.add(new KeyValue<>(toStoreKeyBinary(3, 2 * WINDOW_SIZE, 0, serdes).get(),
serdes.rawValue("three")));
context.restore(STORE_NAME, restorableEntries);
try (final KeyValueIterator<Windowed<Integer>, String> iterator = windowStore
.fetchAll(0L, 2 * WINDOW_SIZE)) {
assertEquals(windowedPair(1, "one", 0L), iterator.next());
assertEquals(windowedPair(2, "two", WINDOW_SIZE), iterator.next());
assertEquals(windowedPair(3, "three", 2 * WINDOW_SIZE), iterator.next());
assertFalse(iterator.hasNext());
}
}
@Test
public void shouldNotExpireFromOpenIterator() {
windowStore.put(1, "one", 0L);
windowStore.put(1, "two", 10L);
windowStore.put(2, "one", 5L);
windowStore.put(2, "two", 15L);
final WindowStoreIterator<String> iterator1 = windowStore.fetch(1, 0L, 50L);
final WindowStoreIterator<String> iterator2 = windowStore.fetch(2, 0L, 50L);
// This put expires all four previous records, but they should still be returned from already open iterators
windowStore.put(1, "four", 2 * RETENTION_PERIOD);
assertEquals(new KeyValue<>(0L, "one"), iterator1.next());
assertEquals(new KeyValue<>(5L, "one"), iterator2.next());
assertEquals(new KeyValue<>(15L, "two"), iterator2.next());
assertEquals(new KeyValue<>(10L, "two"), iterator1.next());
assertFalse(iterator1.hasNext());
assertFalse(iterator2.hasNext());
iterator1.close();
iterator2.close();
// Make sure expired records are removed now that open iterators are closed
assertFalse(windowStore.fetch(1, 0L, 50L).hasNext());
}
@Test
public void testExpiration() {
long currentTime = 0;
windowStore.put(1, "one", currentTime);
currentTime += RETENTION_PERIOD / 4;
windowStore.put(1, "two", currentTime);
currentTime += RETENTION_PERIOD / 4;
windowStore.put(1, "three", currentTime);
currentTime += RETENTION_PERIOD / 4;
windowStore.put(1, "four", currentTime);
// increase current time to the full RETENTION_PERIOD to expire first record
currentTime = currentTime + RETENTION_PERIOD / 4;
windowStore.put(1, "five", currentTime);
KeyValueIterator<Windowed<Integer>, String> iterator = windowStore
.fetchAll(0L, currentTime);
// effect of this put (expires next oldest record, adds new one) should not be reflected in the already fetched results
currentTime = currentTime + RETENTION_PERIOD / 4;
windowStore.put(1, "six", currentTime);
// should only have middle 4 values, as (only) the first record was expired at the time of the fetch
// and the last was inserted after the fetch
assertEquals(windowedPair(1, "two", RETENTION_PERIOD / 4), iterator.next());
assertEquals(windowedPair(1, "three", RETENTION_PERIOD / 2), iterator.next());
assertEquals(windowedPair(1, "four", 3 * (RETENTION_PERIOD / 4)), iterator.next());
assertEquals(windowedPair(1, "five", RETENTION_PERIOD), iterator.next());
assertFalse(iterator.hasNext());
iterator = windowStore.fetchAll(0L, currentTime);
// If we fetch again after the last put, the second oldest record should have expired and newest should appear in results
assertEquals(windowedPair(1, "three", RETENTION_PERIOD / 2), iterator.next());
assertEquals(windowedPair(1, "four", 3 * (RETENTION_PERIOD / 4)), iterator.next());
assertEquals(windowedPair(1, "five", RETENTION_PERIOD), iterator.next());
assertEquals(windowedPair(1, "six", 5 * (RETENTION_PERIOD / 4)), iterator.next());
assertFalse(iterator.hasNext());
}
@Test
public void shouldMatchPositionAfterPut() {
final MeteredWindowStore<Integer, String> meteredSessionStore = (MeteredWindowStore<Integer, String>) windowStore;
final ChangeLoggingWindowBytesStore changeLoggingSessionBytesStore = (ChangeLoggingWindowBytesStore) meteredSessionStore.wrapped();
final InMemoryWindowStore inMemoryWindowStore = (InMemoryWindowStore) changeLoggingSessionBytesStore.wrapped();
context.setRecordContext(new ProcessorRecordContext(0, 1, 0, "", new RecordHeaders()));
windowStore.put(0, "0", SEGMENT_INTERVAL);
context.setRecordContext(new ProcessorRecordContext(0, 2, 0, "", new RecordHeaders()));
windowStore.put(1, "1", SEGMENT_INTERVAL);
context.setRecordContext(new ProcessorRecordContext(0, 3, 0, "", new RecordHeaders()));
windowStore.put(2, "2", SEGMENT_INTERVAL);
context.setRecordContext(new ProcessorRecordContext(0, 4, 0, "", new RecordHeaders()));
windowStore.put(3, "3", SEGMENT_INTERVAL);
final Position expected = Position.fromMap(mkMap(mkEntry("", mkMap(mkEntry(0, 4L)))));
final Position actual = inMemoryWindowStore.getPosition();
assertEquals(expected, actual);
}
}
|
InMemoryWindowStoreTest
|
java
|
grpc__grpc-java
|
api/src/main/java/io/grpc/ClientInterceptors.java
|
{
"start": 7424,
"end": 9459
}
|
class ____<ReqT, RespT>
extends io.grpc.ForwardingClientCall<ReqT, RespT> {
private ClientCall<ReqT, RespT> delegate;
/**
* Subclasses implement the start logic here that would normally belong to {@code start()}.
*
* <p>Implementation should call {@code this.delegate().start()} in the normal path. Exceptions
* may safely be thrown prior to calling {@code this.delegate().start()}. Such exceptions will
* be handled by {@code CheckedForwardingClientCall} and be delivered to {@code
* responseListener}. Exceptions <em>must not</em> be thrown after calling {@code
* this.delegate().start()}, as this can result in {@link ClientCall.Listener#onClose} being
* called multiple times.
*/
protected abstract void checkedStart(Listener<RespT> responseListener, Metadata headers)
throws Exception;
protected CheckedForwardingClientCall(ClientCall<ReqT, RespT> delegate) {
this.delegate = delegate;
}
@Override
protected final ClientCall<ReqT, RespT> delegate() {
return delegate;
}
@Override
@SuppressWarnings("unchecked")
public final void start(Listener<RespT> responseListener, Metadata headers) {
try {
checkedStart(responseListener, headers);
} catch (Exception e) {
// Because start() doesn't throw, the caller may still try to call other methods on this
// call object. Passing these invocations to the original delegate will cause
// IllegalStateException because delegate().start() was not called. We switch the delegate
// to a NO-OP one to prevent the IllegalStateException. The user will finally get notified
// about the error through the listener.
delegate = (ClientCall<ReqT, RespT>) NOOP_CALL;
Metadata trailers = Status.trailersFromThrowable(e);
responseListener.onClose(
Status.fromThrowable(e),
trailers != null ? trailers : new Metadata()
);
}
}
}
}
|
CheckedForwardingClientCall
|
java
|
apache__camel
|
test-infra/camel-test-infra-jdbc/src/test/java/org/apache/camel/test/infra/jdbc/services/JDBCServiceBuilder.java
|
{
"start": 999,
"end": 2031
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(JDBCServiceBuilder.class);
private JdbcDatabaseContainer<?> container;
protected JDBCServiceBuilder() {
}
public static JDBCServiceBuilder newBuilder() {
JDBCServiceBuilder jdbcServiceBuilder = new JDBCServiceBuilder();
return jdbcServiceBuilder;
}
public JDBCServiceBuilder withContainer(JdbcDatabaseContainer<?> container) {
this.container = container;
return this;
}
public JDBCService build() {
String instanceType = System.getProperty("jdbc.instance.type");
if (instanceType == null || instanceType.isEmpty()) {
LOG.info("Creating a new messaging local container service");
return new JDBCLocalContainerService(container);
}
if (instanceType.equals("remote")) {
return new JDBCRemoteService();
}
throw new UnsupportedOperationException("Invalid messaging instance type");
}
}
|
JDBCServiceBuilder
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/processor/assignment/KafkaStreamsAssignment.java
|
{
"start": 1303,
"end": 5120
}
|
class ____ {
private final ProcessId processId;
private final Map<TaskId, AssignedTask> tasks;
private final Optional<Instant> followupRebalanceDeadline;
/**
* Construct an instance of KafkaStreamsAssignment with this processId and the given set of
* assigned tasks. If you want this KafkaStreams client to request a followup rebalance, you
* can set the followupRebalanceDeadline via the {@link #withFollowupRebalance(Instant)} API.
*
* @param processId the processId for the KafkaStreams client that should receive this assignment
* @param assignment the set of tasks to be assigned to this KafkaStreams client
*
* @return a new KafkaStreamsAssignment object with the given processId and assignment
*/
public static KafkaStreamsAssignment of(final ProcessId processId, final Set<AssignedTask> assignment) {
final Map<TaskId, AssignedTask> tasks = assignment.stream().collect(Collectors.toMap(AssignedTask::id, Function.identity()));
return new KafkaStreamsAssignment(processId, tasks, Optional.empty());
}
/**
* This API can be used to request that a followup rebalance be triggered by the KafkaStreams client
* receiving this assignment. The followup rebalance will be initiated after the provided deadline
* has passed, although it will always wait until it has finished the current rebalance before
* triggering a new one. This request will last until the new rebalance, and will be erased if a
* new rebalance begins before the scheduled followup rebalance deadline has elapsed. The next
* assignment must request the followup rebalance again if it still wants to schedule one for
* the given instant, otherwise no additional rebalance will be triggered after that.
*
* @param rebalanceDeadline the instant after which this KafkaStreams client will trigger a followup rebalance
*
* @return a new KafkaStreamsAssignment object with the same processId and assignment but with the given rebalanceDeadline
*/
public KafkaStreamsAssignment withFollowupRebalance(final Instant rebalanceDeadline) {
return new KafkaStreamsAssignment(this.processId(), this.tasks(), Optional.of(rebalanceDeadline));
}
private KafkaStreamsAssignment(final ProcessId processId,
final Map<TaskId, AssignedTask> tasks,
final Optional<Instant> followupRebalanceDeadline) {
this.processId = processId;
this.tasks = tasks;
this.followupRebalanceDeadline = followupRebalanceDeadline;
}
/**
*
* @return the {@code ProcessID} associated with this {@code KafkaStreamsAssignment}
*/
public ProcessId processId() {
return processId;
}
/**
*
* @return a read-only set of assigned tasks that are part of this {@code KafkaStreamsAssignment}
*/
public Map<TaskId, AssignedTask> tasks() {
return unmodifiableMap(tasks);
}
public void assignTask(final AssignedTask newTask) {
tasks.put(newTask.id(), newTask);
}
public void removeTask(final AssignedTask removedTask) {
tasks.remove(removedTask.id());
}
/**
* @return the followup rebalance deadline in epoch time, after which this KafkaStreams
* client will trigger a new rebalance.
*/
public Optional<Instant> followupRebalanceDeadline() {
return followupRebalanceDeadline;
}
@Override
public String toString() {
return String.format(
"KafkaStreamsAssignment{%s, %s, %s}",
processId,
Arrays.toString(tasks.values().toArray(new AssignedTask[0])),
followupRebalanceDeadline
);
}
public static
|
KafkaStreamsAssignment
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/jdk/MapKeyAnnotationsTest.java
|
{
"start": 1394,
"end": 1567
}
|
enum ____ {
A, B, C;
@JsonValue
public String toLC() {
return name().toLowerCase();
}
}
// [databind#2306]
static
|
AbcLC
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiff.java
|
{
"start": 2070,
"end": 4702
}
|
class ____ unsupported. */
boolean isMemberUnsupported(String className, ClassMemberKey memberKey) {
return unsupportedMembersByClass().containsEntry(className, memberKey)
|| unsupportedMembersByClass()
.containsEntry(className, ClassMemberKey.create(memberKey.identifier(), ""));
}
public static ApiDiff fromMembers(
Set<String> unsupportedClasses, Multimap<String, ClassMemberKey> unsupportedMembersByClass) {
return new ApiDiff(
ImmutableSet.copyOf(unsupportedClasses),
ImmutableSetMultimap.copyOf(unsupportedMembersByClass));
}
/** Converts a {@link Diff} to a {@link ApiDiff}. */
public static ApiDiff fromProto(Diff diff) {
ImmutableSet.Builder<String> unsupportedClasses = ImmutableSet.builder();
ImmutableSetMultimap.Builder<String, ClassMemberKey> unsupportedMembersByClass =
ImmutableSetMultimap.builder();
for (ApiDiffProto.ClassDiff c : diff.getClassDiffList()) {
switch (c.getDiffCase()) {
case EVERYTHING_DIFF -> unsupportedClasses.add(c.getEverythingDiff().getClassName());
case MEMBER_DIFF -> {
ApiDiffProto.MemberDiff memberDiff = c.getMemberDiff();
for (ApiDiffProto.ClassMember member : memberDiff.getMemberList()) {
unsupportedMembersByClass.put(
memberDiff.getClassName(),
ClassMemberKey.create(member.getIdentifier(), member.getMemberDescriptor()));
}
}
default -> throw new AssertionError(c.getDiffCase());
}
}
return new ApiDiff(unsupportedClasses.build(), unsupportedMembersByClass.build());
}
/** Converts a {@link ApiDiff} to a {@link ApiDiffProto.Diff}. */
public Diff toProto() {
ApiDiffProto.Diff.Builder builder = ApiDiffProto.Diff.newBuilder();
for (String className : unsupportedClasses()) {
builder.addClassDiff(
ApiDiffProto.ClassDiff.newBuilder()
.setEverythingDiff(ApiDiffProto.EverythingDiff.newBuilder().setClassName(className)));
}
for (String className : unsupportedMembersByClass().keySet()) {
ApiDiffProto.MemberDiff.Builder memberDiff =
ApiDiffProto.MemberDiff.newBuilder().setClassName(className);
for (ClassMemberKey member : unsupportedMembersByClass().get(className)) {
memberDiff.addMember(
ApiDiffProto.ClassMember.newBuilder()
.setIdentifier(member.identifier())
.setMemberDescriptor(member.descriptor()));
}
builder.addClassDiff(ApiDiffProto.ClassDiff.newBuilder().setMemberDiff(memberDiff));
}
return builder.build();
}
}
|
is
|
java
|
greenrobot__greendao
|
DaoCore/src/main/java/org/greenrobot/greendao/query/AbstractQueryData.java
|
{
"start": 881,
"end": 3318
}
|
class ____<T, Q extends AbstractQuery<T>> {
final String sql;
final AbstractDao<T, ?> dao;
final String[] initialValues;
final Map<Long, WeakReference<Q>> queriesForThreads;
AbstractQueryData(AbstractDao<T, ?> dao, String sql, String[] initialValues) {
this.dao = dao;
this.sql = sql;
this.initialValues = initialValues;
queriesForThreads = new HashMap<>();
}
/**
* Just an optimized version, which performs faster if the current thread is already the query's owner thread.
* Note: all parameters are reset to their initial values specified in {@link QueryBuilder}.
*/
Q forCurrentThread(Q query) {
if (Thread.currentThread() == query.ownerThread) {
System.arraycopy(initialValues, 0, query.parameters, 0, initialValues.length);
return query;
} else {
return forCurrentThread();
}
}
/**
* Note: all parameters are reset to their initial values specified in {@link QueryBuilder}.
*/
Q forCurrentThread() {
// Process.myTid() seems to have issues on some devices (see Github #376) and Robolectric (#171):
// We use currentThread().getId() instead (unfortunately return a long, can not use SparseArray).
// PS.: thread ID may be reused, which should be fine because old thread will be gone anyway.
long threadId = Thread.currentThread().getId();
synchronized (queriesForThreads) {
WeakReference<Q> queryRef = queriesForThreads.get(threadId);
Q query = queryRef != null ? queryRef.get() : null;
if (query == null) {
gc();
query = createQuery();
queriesForThreads.put(threadId, new WeakReference<Q>(query));
} else {
System.arraycopy(initialValues, 0, query.parameters, 0, initialValues.length);
}
return query;
}
}
abstract protected Q createQuery();
void gc() {
synchronized (queriesForThreads) {
Iterator<Entry<Long, WeakReference<Q>>> iterator = queriesForThreads.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Long, WeakReference<Q>> entry = iterator.next();
if (entry.getValue().get() == null) {
iterator.remove();
}
}
}
}
}
|
AbstractQueryData
|
java
|
apache__avro
|
lang/java/mapred/src/main/java/org/apache/avro/hadoop/io/AvroSequenceFile.java
|
{
"start": 7500,
"end": 7834
}
|
class ____ be automatically set to
* {@link org.apache.avro.mapred.AvroKey}.
* </p>
*
* @param keyClass The key class.
* @return This options instance.
*/
public Options withKeyClass(Class<?> keyClass) {
if (null == keyClass) {
throw new IllegalArgumentException("Key
|
will
|
java
|
dropwizard__dropwizard
|
dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProviderTest.java
|
{
"start": 2935,
"end": 3464
}
|
enum ____ {
A("1"),
B("2");
private final String code;
ExplicitFromStringNonStatic(String code) {
this.code = code;
}
@Nullable
public ExplicitFromStringNonStatic fromString(String str) {
for (ExplicitFromStringNonStatic e : ExplicitFromStringNonStatic.values()) {
if (str.equals(e.code)) {
return e;
}
}
return null;
}
}
private
|
ExplicitFromStringNonStatic
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/querydsl/container/AttributeSort.java
|
{
"start": 400,
"end": 1272
}
|
class ____ extends Sort {
private final Attribute attribute;
public AttributeSort(Attribute attribute, Direction direction, Missing missing) {
super(direction, missing);
this.attribute = attribute;
}
public Attribute attribute() {
return attribute;
}
@Override
public int hashCode() {
return Objects.hash(attribute, direction(), missing());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AttributeSort other = (AttributeSort) obj;
return Objects.equals(direction(), other.direction())
&& Objects.equals(missing(), other.missing())
&& Objects.equals(attribute, other.attribute);
}
}
|
AttributeSort
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/processor/internals/ClientUtils.java
|
{
"start": 2299,
"end": 2481
}
|
class ____ extends StreamsConfig {
public QuietStreamsConfig(final Map<?, ?> props) {
super(props, false);
}
}
public static final
|
QuietStreamsConfig
|
java
|
quarkusio__quarkus
|
integration-tests/openapi/src/main/java/io/quarkus/it/openapi/jaxrs/FileResource.java
|
{
"start": 490,
"end": 2300
}
|
class ____ {
@GET
@Path("/justFile/{fileName}")
public File justFile(@PathParam("fileName") String filename) {
return toFile(filename);
}
@POST
@Path("/justFile")
public File justFile(File file) {
return file;
}
@GET
@Path("/restResponseFile/{fileName}")
public RestResponse<File> restResponseFile(@PathParam("fileName") String filename) {
return RestResponse.ok(toFile(filename));
}
@POST
@Path("/restResponseFile")
public RestResponse<File> restResponseFile(File file) {
return RestResponse.ok(file);
}
@GET
@Path("/optionalFile/{fileName}")
public Optional<File> optionalFile(@PathParam("fileName") String filename) {
return Optional.of(toFile(filename));
}
@POST
@Path("/optionalFile")
public Optional<File> optionalFile(Optional<File> file) {
return file;
}
@GET
@Path("/uniFile/{fileName}")
public Uni<File> uniFile(@PathParam("fileName") String filename) {
return Uni.createFrom().item(toFile(filename));
}
@GET
@Path("/completionStageFile/{fileName}")
public CompletionStage<File> completionStageFile(@PathParam("fileName") String filename) {
return CompletableFuture.completedStage(toFile(filename));
}
@GET
@Path("/completedFutureFile/{fileName}")
public CompletableFuture<File> completedFutureFile(@PathParam("fileName") String filename) {
return CompletableFuture.completedFuture(toFile(filename));
}
private File toFile(String filename) {
try {
String f = URLDecoder.decode(filename, "UTF-8");
return new File(f);
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
}
|
FileResource
|
java
|
apache__hadoop
|
hadoop-cloud-storage-project/hadoop-huaweicloud/src/main/java/org/apache/hadoop/fs/obs/SseWrapper.java
|
{
"start": 1152,
"end": 2522
}
|
class ____ {
/**
* SSE-KMS: Server-Side Encryption with Key Management Service.
*/
private static final String SSE_KMS = "sse-kms";
/**
* SSE-C: Server-Side Encryption with Customer-Provided Encryption Keys.
*/
private static final String SSE_C = "sse-c";
/**
* SSE-C header.
*/
private SseCHeader sseCHeader;
/**
* SSE-KMS header.
*/
private SseKmsHeader sseKmsHeader;
@SuppressWarnings("deprecation")
SseWrapper(final Configuration conf) {
String sseType = conf.getTrimmed(SSE_TYPE);
if (null != sseType) {
String sseKey = conf.getTrimmed(SSE_KEY);
if (sseType.equalsIgnoreCase(SSE_C) && null != sseKey) {
sseCHeader = new SseCHeader();
sseCHeader.setSseCKeyBase64(sseKey);
sseCHeader.setAlgorithm(
com.obs.services.model.ServerAlgorithm.AES256);
} else if (sseType.equalsIgnoreCase(SSE_KMS)) {
sseKmsHeader = new SseKmsHeader();
sseKmsHeader.setEncryption(
com.obs.services.model.ServerEncryption.OBS_KMS);
sseKmsHeader.setKmsKeyId(sseKey);
}
}
}
boolean isSseCEnable() {
return sseCHeader != null;
}
boolean isSseKmsEnable() {
return sseKmsHeader != null;
}
SseCHeader getSseCHeader() {
return sseCHeader;
}
SseKmsHeader getSseKmsHeader() {
return sseKmsHeader;
}
}
|
SseWrapper
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/QuickfixjEndpointBuilderFactory.java
|
{
"start": 18534,
"end": 21883
}
|
interface ____ {
/**
* QuickFix (camel-quickfix)
* Open a Financial Interchange (FIX) session using an embedded
* QuickFix/J engine.
*
* Category: messaging
* Since: 2.1
* Maven coordinates: org.apache.camel:camel-quickfix
*
* @return the dsl builder for the headers' name.
*/
default QuickfixjHeaderNameBuilder quickfix() {
return QuickfixjHeaderNameBuilder.INSTANCE;
}
/**
* QuickFix (camel-quickfix)
* Open a Financial Interchange (FIX) session using an embedded
* QuickFix/J engine.
*
* Category: messaging
* Since: 2.1
* Maven coordinates: org.apache.camel:camel-quickfix
*
* Syntax: <code>quickfix:configurationName</code>
*
* Path parameter: configurationName (required)
* Path to the quickfix configuration file. You can prefix with:
* classpath, file, http, ref, or bean. classpath, file and http loads
* the configuration file using these protocols (classpath is default).
* ref will lookup the configuration file in the registry. bean will
* call a method on a bean to be used as the configuration. For bean you
* can specify the method name after dot, eg bean:myBean.myMethod
* This option can also be loaded from an existing file, by prefixing
* with file: or classpath: followed by the location of the file.
*
* @param path configurationName
* @return the dsl builder
*/
default QuickfixjEndpointBuilder quickfix(String path) {
return QuickfixjEndpointBuilderFactory.endpointBuilder("quickfix", path);
}
/**
* QuickFix (camel-quickfix)
* Open a Financial Interchange (FIX) session using an embedded
* QuickFix/J engine.
*
* Category: messaging
* Since: 2.1
* Maven coordinates: org.apache.camel:camel-quickfix
*
* Syntax: <code>quickfix:configurationName</code>
*
* Path parameter: configurationName (required)
* Path to the quickfix configuration file. You can prefix with:
* classpath, file, http, ref, or bean. classpath, file and http loads
* the configuration file using these protocols (classpath is default).
* ref will lookup the configuration file in the registry. bean will
* call a method on a bean to be used as the configuration. For bean you
* can specify the method name after dot, eg bean:myBean.myMethod
* This option can also be loaded from an existing file, by prefixing
* with file: or classpath: followed by the location of the file.
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path configurationName
* @return the dsl builder
*/
default QuickfixjEndpointBuilder quickfix(String componentName, String path) {
return QuickfixjEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the QuickFix component.
*/
public static
|
QuickfixjBuilders
|
java
|
apache__maven
|
its/core-it-support/core-it-plugins/maven-it-plugin-class-loader/maven-it-plugin-class-loader/src/main/java/org/apache/maven/plugin/coreit/AbstractLoadMojo.java
|
{
"start": 4679,
"end": 5045
}
|
class ____ " + type.getClassLoader());
try {
if (!type.equals(childClassLoader.loadClass(name))) {
throw new ClassNotFoundException(name);
}
} catch (ClassNotFoundException cnfe) {
getLog().error("[MAVEN-CORE-IT-LOG] Detected
|
from
|
java
|
google__guava
|
guava/src/com/google/common/collect/RangeMap.java
|
{
"start": 1479,
"end": 7795
}
|
interface ____<K extends Comparable, V> {
/*
* TODO(cpovirk): These docs sometimes say "map" and sometimes say "range map." Pick one, or at
* least decide on a policy for when to use which.
*/
/**
* Returns the value associated with the specified key, or {@code null} if there is no such value.
*
* <p>Specifically, if any range in this range map contains the specified key, the value
* associated with that range is returned.
*/
@Nullable V get(K key);
/**
* Returns the range containing this key and its associated value, if such a range is present in
* the range map, or {@code null} otherwise.
*/
@Nullable Entry<Range<K>, V> getEntry(K key);
/**
* Returns the minimal range {@linkplain Range#encloses(Range) enclosing} the ranges in this
* {@code RangeMap}.
*
* @throws NoSuchElementException if this range map is empty
*/
Range<K> span();
/**
* Maps a range to a specified value (optional operation).
*
* <p>Specifically, after a call to {@code put(range, value)}, if {@link
* Range#contains(Comparable) range.contains(k)}, then {@link #get(Comparable) get(k)} will return
* {@code value}.
*
* <p>If {@code range} {@linkplain Range#isEmpty() is empty}, then this is a no-op.
*/
void put(Range<K> range, V value);
/**
* Maps a range to a specified value, coalescing this range with any existing ranges with the same
* value that are {@linkplain Range#isConnected connected} to this range.
*
* <p>The behavior of {@link #get(Comparable) get(k)} after calling this method is identical to
* the behavior described in {@link #put(Range, Object) put(range, value)}, however the ranges
* returned from {@link #asMapOfRanges} will be different if there were existing entries which
* connect to the given range and value.
*
* <p>Even if the input range is empty, if it is connected on both sides by ranges mapped to the
* same value those two ranges will be coalesced.
*
* <p><b>Note:</b> coalescing requires calling {@code .equals()} on any connected values, which
* may be expensive depending on the value type. Using this method on range maps with large values
* such as {@link Collection} types is discouraged.
*
* @since 22.0
*/
void putCoalescing(Range<K> range, V value);
/** Puts all the associations from {@code rangeMap} into this range map (optional operation). */
void putAll(RangeMap<K, ? extends V> rangeMap);
/** Removes all associations from this range map (optional operation). */
void clear();
/**
* Removes all associations from this range map in the specified range (optional operation).
*
* <p>If {@code !range.contains(k)}, {@link #get(Comparable) get(k)} will return the same result
* before and after a call to {@code remove(range)}. If {@code range.contains(k)}, then after a
* call to {@code remove(range)}, {@code get(k)} will return {@code null}.
*/
void remove(Range<K> range);
/**
* Merges a value into a part of the map by applying a remapping function.
*
* <p>If any parts of the range are already present in this map, those parts are mapped to new
* values by applying the remapping function. The remapping function accepts the map's existing
* value for that part of the range and the given value. It returns the value to be associated
* with that part of the map, or it returns {@code null} to clear that part of the map.
*
* <p>Any parts of the range not already present in this map are mapped to the specified value,
* unless the value is {@code null}.
*
* <p>Any existing entry spanning either range boundary may be split at the boundary, even if the
* merge does not affect its value. For example, if {@code rangeMap} had one entry {@code [1, 5]
* => 3} then {@code rangeMap.merge(Range.closed(0,2), 3, Math::max)} could yield a map with the
* entries {@code [0, 1) => 3, [1, 2] => 3, (2, 5] => 3}.
*
* @since 28.1
*/
void merge(
Range<K> range,
@Nullable V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction);
/**
* Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. Modifications to
* this range map are guaranteed to read through to the returned {@code Map}.
*
* <p>The returned {@code Map} iterates over entries in ascending order of the bounds of the
* {@code Range} entries.
*
* <p>It is guaranteed that no empty ranges will be in the returned {@code Map}.
*/
Map<Range<K>, V> asMapOfRanges();
/**
* Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. Modifications to
* this range map are guaranteed to read through to the returned {@code Map}.
*
* <p>The returned {@code Map} iterates over entries in descending order of the bounds of the
* {@code Range} entries.
*
* <p>It is guaranteed that no empty ranges will be in the returned {@code Map}.
*
* @since 19.0
*/
Map<Range<K>, V> asDescendingMapOfRanges();
/**
* Returns a view of the part of this range map that intersects with {@code range}.
*
* <p>For example, if {@code rangeMap} had the entries {@code [1, 5] => "foo", (6, 8) => "bar",
* (10, ∞) => "baz"} then {@code rangeMap.subRangeMap(Range.open(3, 12))} would return a range map
* with the entries {@code (3, 5] => "foo", (6, 8) => "bar", (10, 12) => "baz"}.
*
* <p>The returned range map supports all optional operations that this range map supports, except
* for {@code asMapOfRanges().iterator().remove()}.
*
* <p>The returned range map will throw an {@link IllegalArgumentException} on an attempt to
* insert a range not {@linkplain Range#encloses(Range) enclosed} by {@code range}.
*/
// TODO(cpovirk): Consider documenting that IAE on the various methods that can throw it.
RangeMap<K, V> subRangeMap(Range<K> range);
/**
* Returns {@code true} if {@code obj} is another {@code RangeMap} that has an equivalent {@link
* #asMapOfRanges()}.
*/
@Override
boolean equals(@Nullable Object o);
/** Returns {@code asMapOfRanges().hashCode()}. */
@Override
int hashCode();
/** Returns a readable string representation of this range map. */
@Override
String toString();
}
|
RangeMap
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/codec/vectors/diskbbq/DocIdsWriter.java
|
{
"start": 1333,
"end": 13774
}
|
class ____ {
private static final byte CONTINUOUS_IDS = (byte) -2;
private static final byte DELTA_BPV_16 = (byte) 16;
private static final byte BPV_21 = (byte) 21;
private static final byte BPV_24 = (byte) 24;
private static final byte BPV_32 = (byte) 32;
private int[] scratch = new int[0];
public DocIdsWriter() {}
/**
* Calculate the best encoding that will be used to write blocks of doc ids of blockSize.
* The encoding choice is universal for all the blocks, which means that the encoding is only as
* efficient as the worst block.
* @param docIds function to access the doc ids
* @param count number of doc ids
* @param blockSize the block size
* @return the byte encoding to use for the blocks
*/
public byte calculateBlockEncoding(IntToIntFunction docIds, int count, int blockSize) {
if (count == 0) {
return CONTINUOUS_IDS;
}
int iterationLimit = count - blockSize + 1;
int i = 0;
int maxValue = 0;
int maxMin2Max = 0;
boolean continuousIds = true;
for (; i < iterationLimit; i += blockSize) {
int offset = i;
var r = sortedAndMaxAndMin2Max(d -> docIds.apply(offset + d), blockSize);
continuousIds &= r[0] == 1;
maxValue = Math.max(maxValue, r[1]);
maxMin2Max = Math.max(maxMin2Max, r[2]);
}
// check the tail
if (i < count) {
int offset = i;
var r = sortedAndMaxAndMin2Max(d -> docIds.apply(offset + d), count - i);
continuousIds &= r[0] == 1;
maxValue = Math.max(maxValue, r[1]);
maxMin2Max = Math.max(maxMin2Max, r[2]);
}
if (continuousIds) {
return CONTINUOUS_IDS;
} else if (maxMin2Max <= 0xFFFF) {
return DELTA_BPV_16;
} else {
if (maxValue <= 0x1FFFFF) {
return BPV_21;
} else if (maxValue <= 0xFFFFFF) {
return BPV_24;
} else {
return BPV_32;
}
}
}
public void writeDocIds(IntToIntFunction docIds, int count, byte encoding, DataOutput out) throws IOException {
if (count == 0) {
return;
}
if (count > scratch.length) {
scratch = new int[count];
}
int min = docIds.apply(0);
for (int i = 1; i < count; ++i) {
int current = docIds.apply(i);
min = Math.min(min, current);
}
switch (encoding) {
case CONTINUOUS_IDS -> writeContinuousIds(docIds, count, out);
case DELTA_BPV_16 -> writeDelta16(docIds, count, min, out);
case BPV_21 -> write21(docIds, count, min, out);
case BPV_24 -> write24(docIds, count, min, out);
case BPV_32 -> write32(docIds, count, min, out);
default -> throw new IOException("Unsupported number of bits per value: " + encoding);
}
}
private static void writeContinuousIds(IntToIntFunction docIds, int count, DataOutput out) throws IOException {
out.writeVInt(docIds.apply(0));
}
private void writeDelta16(IntToIntFunction docIds, int count, int min, DataOutput out) throws IOException {
for (int i = 0; i < count; i++) {
scratch[i] = docIds.apply(i) - min;
}
out.writeVInt(min);
final int halfLen = count >> 1;
for (int i = 0; i < halfLen; ++i) {
scratch[i] = scratch[halfLen + i] | (scratch[i] << 16);
}
for (int i = 0; i < halfLen; i++) {
out.writeInt(scratch[i]);
}
if ((count & 1) == 1) {
out.writeShort((short) scratch[count - 1]);
}
}
private void write21(IntToIntFunction docIds, int count, int min, DataOutput out) throws IOException {
final int oneThird = floorToMultipleOf16(count / 3);
final int numInts = oneThird * 2;
for (int i = 0; i < numInts; i++) {
scratch[i] = docIds.apply(i) << 11;
}
for (int i = 0; i < oneThird; i++) {
final int longIdx = i + numInts;
scratch[i] |= docIds.apply(longIdx) & 0x7FF;
scratch[i + oneThird] |= (docIds.apply(longIdx) >>> 11) & 0x7FF;
}
for (int i = 0; i < numInts; i++) {
out.writeInt(scratch[i]);
}
int i = oneThird * 3;
for (; i < count - 2; i += 3) {
out.writeLong(((long) docIds.apply(i)) | (((long) docIds.apply(i + 1)) << 21) | (((long) docIds.apply(i + 2)) << 42));
}
for (; i < count; ++i) {
out.writeShort((short) docIds.apply(i));
out.writeByte((byte) (docIds.apply(i) >>> 16));
}
}
private void write24(IntToIntFunction docIds, int count, int min, DataOutput out) throws IOException {
// encode the docs in the format that can be vectorized decoded.
final int quarter = count >> 2;
final int numInts = quarter * 3;
for (int i = 0; i < numInts; i++) {
scratch[i] = docIds.apply(i) << 8;
}
for (int i = 0; i < quarter; i++) {
final int longIdx = i + numInts;
scratch[i] |= docIds.apply(longIdx) & 0xFF;
scratch[i + quarter] |= (docIds.apply(longIdx) >>> 8) & 0xFF;
scratch[i + quarter * 2] |= docIds.apply(longIdx) >>> 16;
}
for (int i = 0; i < numInts; i++) {
out.writeInt(scratch[i]);
}
for (int i = quarter << 2; i < count; ++i) {
out.writeShort((short) docIds.apply(i));
out.writeByte((byte) (docIds.apply(i) >>> 16));
}
}
private void write32(IntToIntFunction docIds, int count, int min, DataOutput out) throws IOException {
for (int i = 0; i < count; i++) {
out.writeInt(docIds.apply(i));
}
}
private static int[] sortedAndMaxAndMin2Max(IntToIntFunction docIds, int count) {
// docs can be sorted either when all docs in a block have the same value
// or when a segment is sorted
boolean strictlySorted = true;
int min = docIds.apply(0);
int max = min;
for (int i = 1; i < count; ++i) {
int last = docIds.apply(i - 1);
int current = docIds.apply(i);
if (last >= current) {
strictlySorted = false;
}
min = Math.min(min, current);
max = Math.max(max, current);
}
int min2max = max - min + 1;
return new int[] { (strictlySorted && min2max == count) ? 1 : 0, max, min2max };
}
public void writeDocIds(IntToIntFunction docIds, int count, DataOutput out) throws IOException {
if (count == 0) {
return;
}
if (count > scratch.length) {
scratch = new int[count];
}
// docs can be sorted either when all docs in a block have the same value
// or when a segment is sorted
boolean strictlySorted = true;
int min = docIds.apply(0);
int max = min;
for (int i = 1; i < count; ++i) {
int last = docIds.apply(i - 1);
int current = docIds.apply(i);
if (last >= current) {
strictlySorted = false;
}
min = Math.min(min, current);
max = Math.max(max, current);
}
int min2max = max - min + 1;
if (strictlySorted && min2max == count) {
// continuous ids, typically happens when segment is sorted
out.writeByte(CONTINUOUS_IDS);
writeContinuousIds(docIds, count, out);
return;
}
if (min2max <= 0xFFFF) {
out.writeByte(DELTA_BPV_16);
writeDelta16(docIds, count, min, out);
} else {
if (max <= 0x1FFFFF) {
out.writeByte(BPV_21);
write21(docIds, count, min, out);
} else if (max <= 0xFFFFFF) {
out.writeByte(BPV_24);
write24(docIds, count, min, out);
} else {
out.writeByte(BPV_32);
write32(docIds, count, min, out);
}
}
}
public void readInts(IndexInput in, int count, byte encoding, int[] docIDs) throws IOException {
if (count == 0) {
return;
}
if (count > scratch.length) {
scratch = new int[count];
}
switch (encoding) {
case CONTINUOUS_IDS -> readContinuousIds(in, count, docIDs);
case DELTA_BPV_16 -> readDelta16(in, count, docIDs);
case BPV_21 -> readInts21(in, count, docIDs);
case BPV_24 -> readInts24(in, count, docIDs);
case BPV_32 -> readInts32(in, count, docIDs);
default -> throw new IOException("Unsupported number of bits per value: " + encoding);
}
}
/** Read {@code count} integers into {@code docIDs}. */
public void readInts(IndexInput in, int count, int[] docIDs) throws IOException {
if (count == 0) {
return;
}
if (count > scratch.length) {
scratch = new int[count];
}
final int bpv = in.readByte();
readInts(in, count, (byte) bpv, docIDs);
}
private static void readContinuousIds(IndexInput in, int count, int[] docIDs) throws IOException {
int start = in.readVInt();
for (int i = 0; i < count; i++) {
docIDs[i] = start + i;
}
}
private static void readDelta16(IndexInput in, int count, int[] docIds) throws IOException {
final int min = in.readVInt();
final int half = count >> 1;
in.readInts(docIds, 0, half);
decode16(docIds, half, min);
// read the remaining doc if count is odd.
for (int i = half << 1; i < count; i++) {
docIds[i] = Short.toUnsignedInt(in.readShort()) + min;
}
}
private static void decode16(int[] docIDs, int half, int min) {
for (int i = 0; i < half; ++i) {
final int l = docIDs[i];
docIDs[i] = (l >>> 16) + min;
docIDs[i + half] = (l & 0xFFFF) + min;
}
}
private static int floorToMultipleOf16(int n) {
assert n >= 0;
return n & 0xFFFFFFF0;
}
private void readInts21(IndexInput in, int count, int[] docIDs) throws IOException {
int oneThird = floorToMultipleOf16(count / 3);
int numInts = oneThird << 1;
in.readInts(scratch, 0, numInts);
decode21(docIDs, scratch, oneThird, numInts);
int i = oneThird * 3;
for (; i < count - 2; i += 3) {
long l = in.readLong();
docIDs[i] = (int) (l & 0x1FFFFFL);
docIDs[i + 1] = (int) ((l >>> 21) & 0x1FFFFFL);
docIDs[i + 2] = (int) (l >>> 42);
}
for (; i < count; ++i) {
docIDs[i] = (in.readShort() & 0xFFFF) | (in.readByte() & 0xFF) << 16;
}
}
private static void decode21(int[] docIds, int[] scratch, int oneThird, int numInts) {
for (int i = 0; i < numInts; ++i) {
docIds[i] = scratch[i] >>> 11;
}
for (int i = 0; i < oneThird; i++) {
docIds[i + numInts] = (scratch[i] & 0x7FF) | ((scratch[i + oneThird] & 0x7FF) << 11);
}
}
private void readInts24(IndexInput in, int count, int[] docIDs) throws IOException {
int quarter = count >> 2;
int numInts = quarter * 3;
in.readInts(scratch, 0, numInts);
decode24(docIDs, scratch, quarter, numInts);
// Now read the remaining 0, 1, 2 or 3 values
for (int i = quarter << 2; i < count; ++i) {
docIDs[i] = (in.readShort() & 0xFFFF) | (in.readByte() & 0xFF) << 16;
}
}
private static void decode24(int[] docIDs, int[] scratch, int quarter, int numInts) {
for (int i = 0; i < numInts; ++i) {
docIDs[i] = scratch[i] >>> 8;
}
for (int i = 0; i < quarter; i++) {
docIDs[i + numInts] = (scratch[i] & 0xFF) | ((scratch[i + quarter] & 0xFF) << 8) | ((scratch[i + quarter * 2] & 0xFF) << 16);
}
}
private static void readInts32(IndexInput in, int count, int[] docIDs) throws IOException {
in.readInts(docIDs, 0, count);
}
}
|
DocIdsWriter
|
java
|
junit-team__junit5
|
junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/NodeTreeWalker.java
|
{
"start": 988,
"end": 5255
}
|
class ____ {
private final LockManager lockManager;
private final ResourceLock globalReadLock;
private final ResourceLock globalReadWriteLock;
NodeTreeWalker() {
this(new LockManager());
}
NodeTreeWalker(LockManager lockManager) {
this.lockManager = lockManager;
this.globalReadLock = lockManager.getLockForResource(GLOBAL_READ);
this.globalReadWriteLock = lockManager.getLockForResource(GLOBAL_READ_WRITE);
}
NodeExecutionAdvisor walk(TestDescriptor rootDescriptor) {
Preconditions.condition(getExclusiveResources(rootDescriptor).isEmpty(),
"Engine descriptor must not declare exclusive resources");
NodeExecutionAdvisor advisor = new NodeExecutionAdvisor();
rootDescriptor.getChildren().forEach(child -> walk(nullUnlessRequiresGlobalReadLock(child), child, advisor));
return advisor;
}
private void walk(@Nullable TestDescriptor globalLockDescriptor, TestDescriptor testDescriptor,
NodeExecutionAdvisor advisor) {
if (globalLockDescriptor != null && advisor.getResourceLock(globalLockDescriptor) == globalReadWriteLock) {
// Global read-write lock is already being enforced, so no additional locks are needed
return;
}
Set<ExclusiveResource> exclusiveResources = getExclusiveResources(testDescriptor);
if (exclusiveResources.isEmpty()) {
if (globalLockDescriptor != null && globalLockDescriptor.equals(testDescriptor)) {
advisor.useResourceLock(globalLockDescriptor, globalReadLock);
}
testDescriptor.getChildren().forEach(child -> {
var newGlobalLockDescriptor = globalLockDescriptor == null //
? nullUnlessRequiresGlobalReadLock(child) //
: globalLockDescriptor;
walk(newGlobalLockDescriptor, child, advisor);
});
}
else {
Preconditions.notNull(globalLockDescriptor,
() -> "Node requiring exclusive resources must also require global read lock: " + testDescriptor);
Set<ExclusiveResource> allResources = new HashSet<>(exclusiveResources);
if (isReadOnly(allResources)) {
doForChildrenRecursively(testDescriptor, child -> allResources.addAll(getExclusiveResources(child)));
if (!isReadOnly(allResources)) {
forceDescendantExecutionModeRecursively(advisor, testDescriptor);
}
}
else {
advisor.forceDescendantExecutionMode(testDescriptor, SAME_THREAD);
doForChildrenRecursively(testDescriptor, child -> {
allResources.addAll(getExclusiveResources(child));
advisor.forceDescendantExecutionMode(child, SAME_THREAD);
});
}
if (allResources.contains(GLOBAL_READ_WRITE)) {
advisor.forceDescendantExecutionMode(globalLockDescriptor, SAME_THREAD);
doForChildrenRecursively(globalLockDescriptor, child -> {
advisor.forceDescendantExecutionMode(child, SAME_THREAD);
// Remove any locks that may have been set for siblings or their descendants
advisor.removeResourceLock(child);
});
advisor.useResourceLock(globalLockDescriptor, globalReadWriteLock);
}
else {
if (globalLockDescriptor.equals(testDescriptor)) {
allResources.add(GLOBAL_READ);
}
else {
allResources.remove(GLOBAL_READ);
}
advisor.useResourceLock(testDescriptor, lockManager.getLockForResources(allResources));
}
}
}
private void forceDescendantExecutionModeRecursively(NodeExecutionAdvisor advisor, TestDescriptor testDescriptor) {
advisor.forceDescendantExecutionMode(testDescriptor, SAME_THREAD);
doForChildrenRecursively(testDescriptor, child -> advisor.forceDescendantExecutionMode(child, SAME_THREAD));
}
private boolean isReadOnly(Set<ExclusiveResource> exclusiveResources) {
return exclusiveResources.stream().allMatch(it -> it.getLockMode() == ExclusiveResource.LockMode.READ);
}
private Set<ExclusiveResource> getExclusiveResources(TestDescriptor testDescriptor) {
return asNode(testDescriptor).getExclusiveResources();
}
private static @Nullable TestDescriptor nullUnlessRequiresGlobalReadLock(TestDescriptor testDescriptor) {
return asNode(testDescriptor).isGlobalReadLockRequired() ? testDescriptor : null;
}
private void doForChildrenRecursively(TestDescriptor parent, Consumer<TestDescriptor> consumer) {
parent.getChildren().forEach(child -> {
consumer.accept(child);
doForChildrenRecursively(child, consumer);
});
}
}
|
NodeTreeWalker
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/support/LettuceCdiExtension.java
|
{
"start": 1983,
"end": 6088
}
|
class ____ implements Extension {
private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(LettuceCdiExtension.class);
private final Map<Set<Annotation>, Bean<RedisURI>> redisUris = new ConcurrentHashMap<>();
private final Map<Set<Annotation>, Bean<ClientResources>> clientResources = new ConcurrentHashMap<>();
public LettuceCdiExtension() {
LOGGER.info("Activating CDI extension for lettuce.");
}
/**
* Implementation of a an observer which checks for RedisURI beans and stores them in {@link #redisUris} for later
* association with corresponding repository beans.
*
* @param <T> The type.
* @param processBean The annotated type as defined by CDI.
*/
@SuppressWarnings("unchecked")
<T> void processBean(@Observes ProcessBean<T> processBean) {
Bean<T> bean = processBean.getBean();
for (Type type : bean.getTypes()) {
if (!(type instanceof Class<?>)) {
continue;
}
// Check if the bean is an RedisURI.
if (RedisURI.class.isAssignableFrom((Class<?>) type)) {
Set<Annotation> qualifiers = LettuceSets.newHashSet(bean.getQualifiers());
if (bean.isAlternative() || !redisUris.containsKey(qualifiers)) {
LOGGER.debug(String.format("Discovered '%s' with qualifiers %s.", RedisURI.class.getName(), qualifiers));
redisUris.put(qualifiers, (Bean<RedisURI>) bean);
}
}
if (ClientResources.class.isAssignableFrom((Class<?>) type)) {
Set<Annotation> qualifiers = LettuceSets.newHashSet(bean.getQualifiers());
if (bean.isAlternative() || !clientResources.containsKey(qualifiers)) {
LOGGER.debug(
String.format("Discovered '%s' with qualifiers %s.", ClientResources.class.getName(), qualifiers));
clientResources.put(qualifiers, (Bean<ClientResources>) bean);
}
}
}
}
/**
* Implementation of a an observer which registers beans to the CDI container for the detected RedisURIs.
* <p>
* The repository beans are associated to the EntityManagers using their qualifiers.
*
* @param beanManager The BeanManager instance.
*/
void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
int counter = 0;
for (Entry<Set<Annotation>, Bean<RedisURI>> entry : redisUris.entrySet()) {
Bean<RedisURI> redisUri = entry.getValue();
Set<Annotation> qualifiers = entry.getKey();
String clientBeanName = RedisClient.class.getSimpleName();
String clusterClientBeanName = RedisClusterClient.class.getSimpleName();
if (!containsDefault(qualifiers)) {
clientBeanName += counter;
clusterClientBeanName += counter;
counter++;
}
Bean<ClientResources> clientResources = this.clientResources.get(qualifiers);
RedisClientCdiBean clientBean = new RedisClientCdiBean(redisUri, clientResources, beanManager, qualifiers,
clientBeanName);
register(afterBeanDiscovery, qualifiers, clientBean);
RedisClusterClientCdiBean clusterClientBean = new RedisClusterClientCdiBean(redisUri, clientResources, beanManager,
qualifiers, clusterClientBeanName);
register(afterBeanDiscovery, qualifiers, clusterClientBean);
}
}
private boolean containsDefault(Set<Annotation> qualifiers) {
return qualifiers.stream().filter(input -> input instanceof Default).findFirst().isPresent();
}
private void register(AfterBeanDiscovery afterBeanDiscovery, Set<Annotation> qualifiers, Bean<?> bean) {
LOGGER.info(String.format("Registering bean '%s' with qualifiers %s.", bean.getBeanClass().getName(), qualifiers));
afterBeanDiscovery.addBean(bean);
}
}
|
LettuceCdiExtension
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/grouping/GroupingFunction.java
|
{
"start": 1049,
"end": 2425
}
|
class ____ extends Function {
private final Expression field;
private final List<Expression> parameters;
protected GroupingFunction(Source source, Expression field) {
this(source, field, emptyList());
}
protected GroupingFunction(Source source, Expression field, List<Expression> parameters) {
super(source, CollectionUtils.combine(singletonList(field), parameters));
this.field = field;
this.parameters = parameters;
}
public Expression field() {
return field;
}
public List<Expression> parameters() {
return parameters;
}
@Override
protected Pipe makePipe() {
// unresolved AggNameInput (should always get replaced by the folder)
return new AggNameInput(source(), this, sourceText());
}
@Override
public ScriptTemplate asScript() {
throw new QlIllegalArgumentException("Grouping functions cannot be scripted");
}
@Override
public boolean equals(Object obj) {
if (false == super.equals(obj)) {
return false;
}
GroupingFunction other = (GroupingFunction) obj;
return Objects.equals(other.field(), field()) && Objects.equals(other.parameters(), parameters());
}
@Override
public int hashCode() {
return Objects.hash(field(), parameters());
}
}
|
GroupingFunction
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytomany/IndexColumnListTest.java
|
{
"start": 5704,
"end": 7433
}
|
class ____ {
@Id
private Integer id;
private String name;
@ManyToMany(mappedBy = "children")
private List<Parent> parents;
Child() {
}
Child(Integer id, String name) {
this( id, name, null );
}
Child(Integer id, String name, Parent... parents) {
this.id = id;
this.name = name;
if ( parents != null && parents.length > 0 ) {
this.parents = new ArrayList<>( Arrays.asList( parents ) );
}
else {
this.parents = new ArrayList<>();
}
}
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 List<Parent> getParents() {
return parents;
}
public void setParent(List<Parent> parents) {
this.parents = parents;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Child child = (Child) o;
if ( id != null ? !id.equals( child.id ) : child.id != null ) {
return false;
}
if ( name != null ? !name.equals( child.name ) : child.name != null ) {
return false;
}
return parents != null ? parents.equals( child.parents ) : child.parents == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + ( name != null ? name.hashCode() : 0 );
result = 31 * result + ( parents != null ? parents.hashCode() : 0 );
return result;
}
@Override
public String toString() {
return "Child{" +
"id=" + id +
", name='" + name + '\'' +
", parents=" + parents +
'}';
}
}
}
|
Child
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/MergeCallback.java
|
{
"start": 1306,
"end": 1772
}
|
interface ____<W, R> {
/**
* Specifies that states of the given windows or slices should be merged into the result window
* or slice.
*
* @param mergeResult The resulting merged window or slice, {@code null} if it represents a
* non-state namespace.
* @param toBeMerged Windows or slices that should be merged into one window or slice.
*/
void merge(@Nullable W mergeResult, R toBeMerged) throws Exception;
}
|
MergeCallback
|
java
|
junit-team__junit5
|
junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/extension/ExtensionRegistrar.java
|
{
"start": 3248,
"end": 3781
}
|
class ____ which the extension is registered;
* never {@code null}
* @param source the source of the extension; never {@code null}
* @param initializer the initializer function to be used to create the
* extension; never {@code null}
*/
void registerUninitializedExtension(Class<?> testClass, Field source,
Function<Object, ? extends Extension> initializer);
/**
* Initialize all registered extensions for the supplied {@code testClass}
* using the supplied {@code testInstance}.
*
* @param testClass the test
|
for
|
java
|
elastic__elasticsearch
|
libs/logstash-bridge/src/main/java/org/elasticsearch/logstashbridge/geoip/AbstractExternalIpDatabaseBridge.java
|
{
"start": 753,
"end": 1034
}
|
class ____ implementing
* the {@link IpDatabaseBridge} externally to the Elasticsearch code-base. It takes care of
* the details of maintaining a singular internal-form implementation of {@link IpDatabase}
* that proxies calls to the external implementation.
*/
public abstract
|
for
|
java
|
spring-projects__spring-framework
|
spring-core-test/src/main/java/org/springframework/core/test/tools/DynamicClassFileObject.java
|
{
"start": 2141,
"end": 2286
}
|
class ____ extends ByteArrayOutputStream {
@Override
public void close() {
closeOutputStream(toByteArray());
}
}
}
|
JavaClassOutputStream
|
java
|
google__guice
|
core/test/com/google/inject/internal/OptionalBinderTest.java
|
{
"start": 6874,
"end": 11443
}
|
enum ____ {
PRESENT,
EMPTY
}
private static <T> Key<T> keyFor(TypeLiteral<T> typeLiteral, Annotation maybeAnnotation) {
if (maybeAnnotation != null) {
return Key.get(typeLiteral, maybeAnnotation);
} else {
return Key.get(typeLiteral);
}
}
private void assertOptionalState(
Injector injector,
ExpectedValueState valueState,
ExpectedProviderState providerState,
String expectedValueIfPresent) {
assertOptionalState(
injector, /* annotation= */ null, valueState, providerState, expectedValueIfPresent);
}
private void assertOptionalState(
Injector injector,
Annotation annotation,
ExpectedValueState valueState,
ExpectedProviderState providerState,
String expectedValueIfPresent) {
boolean expectedPresent = valueState == ExpectedValueState.PRESENT;
Optional<String> optional = injector.getInstance(keyFor(optionalOfString, annotation));
assertThat(optional.isPresent()).isEqualTo(expectedPresent);
optional =
Optional.fromJavaUtil(injector.getInstance(keyFor(javaOptionalOfString, annotation)));
assertThat(optional.isPresent()).isEqualTo(expectedPresent);
if (expectedPresent) {
assertThat(optional.get()).isEqualTo(expectedValueIfPresent);
}
expectedPresent = providerState == ExpectedProviderState.PRESENT;
Optional<Provider<String>> optionalP =
injector.getInstance(keyFor(optionalOfProviderString, annotation));
assertThat(optionalP.isPresent()).isEqualTo(expectedPresent);
if (expectedPresent) {
assertThat(optionalP.get().get()).isEqualTo(expectedValueIfPresent);
}
optionalP =
Optional.fromJavaUtil(
injector.getInstance(keyFor(javaOptionalOfProviderString, annotation)));
assertThat(optionalP.isPresent()).isEqualTo(expectedPresent);
if (expectedPresent) {
assertThat(optionalP.get().get()).isEqualTo(expectedValueIfPresent);
}
Optional<jakarta.inject.Provider<String>> optionalJkP =
injector.getInstance(keyFor(optionalOfJakartaProviderString, annotation));
assertThat(optionalJkP.isPresent()).isEqualTo(expectedPresent);
if (expectedPresent) {
assertThat(optionalJkP.get().get()).isEqualTo(expectedValueIfPresent);
}
optionalJkP =
Optional.fromJavaUtil(
injector.getInstance(keyFor(javaOptionalOfJakartaProviderString, annotation)));
assertThat(optionalJkP.isPresent()).isEqualTo(expectedPresent);
if (expectedPresent) {
assertThat(optionalJkP.get().get()).isEqualTo(expectedValueIfPresent);
}
}
public void testOptionalIsAbsentByDefault() throws Exception {
Module module =
new AbstractModule() {
@Override
protected void configure() {
OptionalBinder.newOptionalBinder(binder(), String.class);
}
};
Injector injector = Guice.createInjector(module);
assertOptionalState(injector, ExpectedValueState.EMPTY, ExpectedProviderState.EMPTY, null);
assertOptionalVisitor(stringKey, setOf(module), VisitType.BOTH, 0, null, null, null);
}
public void testUsesUserBoundValue() throws Exception {
Module module =
new AbstractModule() {
@Override
protected void configure() {
OptionalBinder.newOptionalBinder(binder(), String.class);
}
@Provides
String provideString() {
return "foo";
}
};
Injector injector = Guice.createInjector(module);
assertEquals("foo", injector.getInstance(String.class));
assertOptionalState(injector, ExpectedValueState.PRESENT, ExpectedProviderState.PRESENT, "foo");
assertOptionalVisitor(
stringKey, setOf(module), VisitType.BOTH, 0, null, null, providerInstance("foo"));
}
public void testUsesUserBoundValueNullProvidersMakeAbsent() throws Exception {
Module module =
new AbstractModule() {
@Override
protected void configure() {
OptionalBinder.newOptionalBinder(binder(), String.class);
}
@Provides
String provideString() {
return null;
}
};
Injector injector = Guice.createInjector(module);
assertEquals(null, injector.getInstance(String.class));
assertOptionalState(injector, ExpectedValueState.EMPTY, ExpectedProviderState.PRESENT, null);
assertOptionalVisitor(
stringKey, setOf(module), VisitType.BOTH, 0, null, null, providerInstance(null));
}
private static
|
ExpectedProviderState
|
java
|
apache__rocketmq
|
auth/src/main/java/org/apache/rocketmq/auth/authentication/context/AuthenticationContext.java
|
{
"start": 970,
"end": 2350
}
|
class ____ {
private String channelId;
private String rpcCode;
private Map<String, Object> extInfo;
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getRpcCode() {
return rpcCode;
}
public void setRpcCode(String rpcCode) {
this.rpcCode = rpcCode;
}
@SuppressWarnings("unchecked")
public <T> T getExtInfo(String key) {
if (StringUtils.isBlank(key)) {
return null;
}
if (this.extInfo == null) {
return null;
}
Object value = this.extInfo.get(key);
if (value == null) {
return null;
}
return (T) value;
}
public void setExtInfo(String key, Object value) {
if (StringUtils.isBlank(key) || value == null) {
return;
}
if (this.extInfo == null) {
this.extInfo = new HashMap<>();
}
this.extInfo.put(key, value);
}
public boolean hasExtInfo(String key) {
Object value = getExtInfo(key);
return value != null;
}
public Map<String, Object> getExtInfo() {
return extInfo;
}
public void setExtInfo(Map<String, Object> extInfo) {
this.extInfo = extInfo;
}
}
|
AuthenticationContext
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-jackson/runtime/src/main/java/io/quarkus/resteasy/reactive/jackson/runtime/serialisers/FullyFeaturedServerJacksonMessageBodyWriter.java
|
{
"start": 8912,
"end": 10027
}
|
class ____ implements Function<String, ObjectWriter> {
private final Class<? extends BiFunction<ObjectMapper, Type, ObjectWriter>> clazz;
private final Type genericType;
private final ObjectMapper originalMapper;
public MethodObjectWriterFunction(Class<? extends BiFunction<ObjectMapper, Type, ObjectWriter>> clazz, Type genericType,
ObjectMapper originalMapper) {
this.clazz = clazz;
this.genericType = genericType;
this.originalMapper = originalMapper;
}
@Override
public ObjectWriter apply(String methodId) {
try {
BiFunction<ObjectMapper, Type, ObjectWriter> biFunctionInstance = clazz.getDeclaredConstructor().newInstance();
ObjectWriter objectWriter = biFunctionInstance.apply(originalMapper, genericType);
setNecessaryJsonFactoryConfig(objectWriter.getFactory());
return objectWriter;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
|
MethodObjectWriterFunction
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/issue_3200/Issue3227.java
|
{
"start": 619,
"end": 1011
}
|
class ____<T> {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected T code;
public T getCode() {
return code;
}
public void setCode(T code) {
this.code = code;
}
}
static
|
Parent
|
java
|
reactor__reactor-core
|
reactor-core/src/main/java/reactor/core/publisher/QueueDrainSubscriber.java
|
{
"start": 1352,
"end": 6774
}
|
class ____<T, U, V> extends QueueDrainSubscriberPad4
implements InnerOperator<T, V> {
final CoreSubscriber<? super V> actual;
final Queue<U> queue;
volatile boolean cancelled;
volatile boolean done;
@Nullable Throwable error;
QueueDrainSubscriber(CoreSubscriber<? super V> actual, Queue<U> queue) {
this.actual = actual;
this.queue = queue;
}
@Override
public CoreSubscriber<? super V> actual() {
return actual;
}
public final boolean cancelled() {
return cancelled;
}
public final boolean done() {
return done;
}
public final boolean enter() {
return wip.getAndIncrement() == 0;
}
public final boolean fastEnter() {
return wip.get() == 0 && wip.compareAndSet(0, 1);
}
protected final void fastPathEmitMax(U value, boolean delayError, Disposable dispose) {
final Subscriber<? super V> s = actual;
final Queue<U> q = queue;
if (wip.get() == 0 && wip.compareAndSet(0, 1)) {
long r = requested;
if (r != 0L) {
if (accept(s, value)) {
if (r != Long.MAX_VALUE) {
produced(1);
}
}
if (leave(-1) == 0) {
return;
}
} else {
dispose.dispose();
s.onError(Exceptions.failWithOverflow("Could not emit buffer due to lack of requests"));
return;
}
} else {
q.offer(value);
if (!enter()) {
return;
}
}
drainMaxLoop(q, s, delayError, dispose, this);
}
protected final void fastPathOrderedEmitMax(U value, boolean delayError, Disposable dispose) {
final Subscriber<? super V> s = actual;
final Queue<U> q = queue;
if (wip.get() == 0 && wip.compareAndSet(0, 1)) {
long r = requested;
if (r != 0L) {
if (q.isEmpty()) {
if (accept(s, value)) {
if (r != Long.MAX_VALUE) {
produced(1);
}
}
if (leave(-1) == 0) {
return;
}
} else {
q.offer(value);
}
} else {
cancelled = true;
dispose.dispose();
s.onError(Exceptions.failWithOverflow("Could not emit buffer due to lack of requests"));
return;
}
} else {
q.offer(value);
if (!enter()) {
return;
}
}
drainMaxLoop(q, s, delayError, dispose, this);
}
/**
* Accept the value and return true if forwarded.
* @param a the subscriber
* @param v the value
* @return true if the value was delivered
*/
public boolean accept(Subscriber<? super V> a, U v) {
return false;
}
public final @Nullable Throwable error() {
return error;
}
/**
* Adds m to the wip counter.
* @param m the value to add
* @return the current value after adding m
*/
public final int leave(int m) {
return wip.addAndGet(m);
}
public final long requested() {
return requested;
}
public final long produced(long n) {
return REQUESTED.addAndGet(this, -n);
}
public final void requested(long n) {
if (Operators.validate(n)) {
Operators.addCap(REQUESTED, this, n);
}
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.TERMINATED) return done;
if (key == Attr.CANCELLED) return cancelled;
if (key == Attr.REQUESTED_FROM_DOWNSTREAM) return requested;
if (key == Attr.ERROR) return error;
return InnerOperator.super.scanUnsafe(key);
}
/**
* Drain the queue but give up with an error if there aren't enough requests.
* @param <Q> the queue value type
* @param <S> the emission value type
* @param q the queue
* @param a the subscriber
* @param delayError true if errors should be delayed after all normal items
* @param dispose the disposable to call when termination happens and cleanup is necessary
* @param qd the QueueDrain instance that gives status information to the drain logic
*/
static <Q, S> void drainMaxLoop(Queue<Q> q, Subscriber<? super S> a, boolean delayError,
Disposable dispose, QueueDrainSubscriber<?, Q, S> qd) {
int missed = 1;
for (;;) {
for (;;) {
boolean d = qd.done();
Q v = q.poll();
boolean empty = v == null;
if (checkTerminated(d, empty, a, delayError, q, qd)) {
if (dispose != null) {
dispose.dispose();
}
return;
}
if (empty) {
break;
}
long r = qd.requested();
if (r != 0L) {
if (qd.accept(a, v)) {
if (r != Long.MAX_VALUE) {
qd.produced(1);
}
}
} else {
q.clear();
if (dispose != null) {
dispose.dispose();
}
a.onError(Exceptions.failWithOverflow("Could not emit value due to lack of requests."));
return;
}
}
missed = qd.leave(-missed);
if (missed == 0) {
break;
}
}
}
static <Q, S> boolean checkTerminated(boolean d, boolean empty,
Subscriber<?> s, boolean delayError, Queue<?> q, QueueDrainSubscriber<?, Q, S> qd) {
if (qd.cancelled()) {
q.clear();
return true;
}
if (d) {
if (delayError) {
if (empty) {
Throwable err = qd.error();
if (err != null) {
s.onError(err);
} else {
s.onComplete();
}
return true;
}
} else {
Throwable err = qd.error();
if (err != null) {
q.clear();
s.onError(err);
return true;
} else
if (empty) {
s.onComplete();
return true;
}
}
}
return false;
}
}
// -------------------------------------------------------------------
// Padding superclasses
//-------------------------------------------------------------------
/** Pads the header away from other fields. */
@SuppressWarnings("unused")
|
QueueDrainSubscriber
|
java
|
apache__flink
|
flink-python/src/test/java/org/apache/flink/table/runtime/operators/python/aggregate/arrow/stream/StreamArrowPythonRowTimeBoundedRowsOperatorTest.java
|
{
"start": 2681,
"end": 10023
}
|
class ____
extends AbstractStreamArrowPythonAggregateFunctionOperatorTest {
@Test
void testOverWindowAggregateFunction() throws Exception {
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
getTestHarness(new Configuration());
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c2", 0L, 1L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c4", 1L, 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c6", 2L, 10L), initialTime + 3));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c2", "c8", 3L, 2L), initialTime + 3));
testHarness.processWatermark(Long.MAX_VALUE);
testHarness.close();
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c2", 0L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c4", 1L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", "c8", 3L, 2L, 3L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c6", 2L, 10L, 1L)));
expectedOutput.add(new Watermark(Long.MAX_VALUE));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
}
@Test
void testFinishBundleTriggeredOnWatermark() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 10);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c2", 0L, 1L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c4", 1L, 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c6", 2L, 10L), initialTime + 3));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c2", "c8", 3L, 2L), initialTime + 3));
testHarness.processWatermark(new Watermark(10000L));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c2", 0L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c4", 1L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", "c8", 3L, 2L, 3L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c6", 2L, 10L, 1L)));
expectedOutput.add(new Watermark(10000L));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
@Test
void testFinishBundleTriggeredByCount() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 6);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c2", 0L, 1L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c4", 1L, 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c1", "c6", 2L, 10L), initialTime + 3));
testHarness.processElement(
new StreamRecord<>(newBinaryRow(true, "c2", "c8", 3L, 2L), initialTime + 3));
assertOutputEquals(
"FinishBundle should not be triggered.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(1000L));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c2", 0L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c4", 1L, 1L, 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", "c8", 3L, 2L, 3L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", "c6", 2L, 10L, 1L)));
expectedOutput.add(new Watermark(1000L));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
@Override
public LogicalType[] getOutputLogicalType() {
return new LogicalType[] {
DataTypes.STRING().getLogicalType(),
DataTypes.STRING().getLogicalType(),
DataTypes.BIGINT().getLogicalType(),
DataTypes.BIGINT().getLogicalType(),
DataTypes.BIGINT().getLogicalType()
};
}
@Override
public RowType getInputType() {
return new RowType(
Arrays.asList(
new RowType.RowField("f1", new VarCharType()),
new RowType.RowField("f2", new VarCharType()),
new RowType.RowField("f3", new BigIntType()),
new RowType.RowField("rowTime", new BigIntType())));
}
@Override
public RowType getOutputType() {
return new RowType(
Arrays.asList(
new RowType.RowField("f1", new VarCharType()),
new RowType.RowField("f2", new VarCharType()),
new RowType.RowField("f3", new BigIntType()),
new RowType.RowField("rowTime", new BigIntType()),
new RowType.RowField("agg", new BigIntType())));
}
@Override
public AbstractArrowPythonAggregateFunctionOperator getTestOperator(
Configuration config,
PythonFunctionInfo[] pandasAggregateFunctions,
RowType inputType,
RowType outputType,
int[] groupingSet,
int[] udafInputOffsets) {
RowType udfInputType = (RowType) Projection.of(udafInputOffsets).project(inputType);
RowType udfOutputType =
(RowType)
Projection.range(inputType.getFieldCount(), outputType.getFieldCount())
.project(outputType);
return new PassThroughStreamArrowPythonRowTimeBoundedRowsOperator(
config,
pandasAggregateFunctions,
inputType,
udfInputType,
udfOutputType,
3,
1,
ProjectionCodeGenerator.generateProjection(
new CodeGeneratorContext(
new Configuration(),
Thread.currentThread().getContextClassLoader()),
"UdafInputProjection",
inputType,
udfInputType,
udafInputOffsets));
}
private static
|
StreamArrowPythonRowTimeBoundedRowsOperatorTest
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/jdk8/ParallelMapTryOptional.java
|
{
"start": 6045,
"end": 9331
}
|
class ____<T, R> implements ConditionalSubscriber<T>, Subscription {
final ConditionalSubscriber<? super R> downstream;
final Function<? super T, Optional<? extends R>> mapper;
final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler;
Subscription upstream;
boolean done;
ParallelMapTryConditionalSubscriber(ConditionalSubscriber<? super R> actual,
Function<? super T, Optional<? extends R>> mapper,
BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) {
this.downstream = actual;
this.mapper = mapper;
this.errorHandler = errorHandler;
}
@Override
public void request(long n) {
upstream.request(n);
}
@Override
public void cancel() {
upstream.cancel();
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.upstream, s)) {
this.upstream = s;
downstream.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
if (!tryOnNext(t) && !done) {
upstream.request(1);
}
}
@Override
public boolean tryOnNext(T t) {
if (done) {
return false;
}
long retries = 0;
for (;;) {
Optional<? extends R> v;
try {
v = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null Optional");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
ParallelFailureHandling h;
try {
h = Objects.requireNonNull(errorHandler.apply(++retries, ex), "The errorHandler returned a null ParallelFailureHandling");
} catch (Throwable exc) {
Exceptions.throwIfFatal(exc);
cancel();
onError(new CompositeException(ex, exc));
return false;
}
switch (h) {
case RETRY:
continue;
case SKIP:
return false;
case STOP:
cancel();
onComplete();
return false;
default:
cancel();
onError(ex);
return false;
}
}
return v.isPresent() && downstream.tryOnNext(v.get());
}
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
done = true;
downstream.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
downstream.onComplete();
}
}
}
|
ParallelMapTryConditionalSubscriber
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/util/ReflectionUtils.java
|
{
"start": 1872,
"end": 2465
}
|
class ____ for class {}", c);
}
// remove packaging from the name - strategy used for naming rules by default
public static String ruleLikeNaming(Class<?> c) {
String className = c.getName();
int parentPackage = className.lastIndexOf('.');
if (parentPackage > 0) {
int grandParentPackage = className.substring(0, parentPackage).lastIndexOf('.');
return (grandParentPackage > 0 ? className.substring(grandParentPackage + 1) : className.substring(parentPackage));
} else {
return className;
}
}
}
|
structure
|
java
|
apache__camel
|
components/camel-wasm/src/main/java/org/apache/camel/component/wasm/WasmProducer.java
|
{
"start": 1296,
"end": 2807
}
|
class ____ extends DefaultProducer {
private final String functionModule;
private final String functionName;
private WasmModule module;
private WasmFunction function;
public WasmProducer(Endpoint endpoint, String functionModule, String functionName) throws Exception {
super(endpoint);
this.functionModule = functionModule;
this.functionName = functionName;
}
@Override
public void doInit() throws Exception {
final ResourceLoader rl = PluginHelper.getResourceLoader(getEndpoint().getCamelContext());
final Resource res = rl.resolveResource(this.functionModule);
try (InputStream is = res.getInputStream()) {
this.module = Parser.parse(is);
}
}
@Override
public void doStart() throws Exception {
super.doStart();
if (this.module != null && this.function == null) {
this.function = new WasmFunction(this.module, this.functionName);
}
}
@Override
public void doStop() throws Exception {
super.doStop();
this.function = null;
}
@Override
public void doShutdown() throws Exception {
super.doShutdown();
this.function = null;
this.module = null;
}
@Override
public void process(Exchange exchange) throws Exception {
byte[] in = WasmSupport.serialize(exchange);
byte[] result = function.run(in);
WasmSupport.deserialize(result, exchange);
}
}
|
WasmProducer
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/issues/SpringSplitterDetermineErrorHandlerIssueTest.java
|
{
"start": 1097,
"end": 1655
}
|
class ____ extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"org/apache/camel/spring/issues/SpringSplitterDetermineErrorHandlerIssueTest.xml");
}
@Test
public void testSplitter() throws Exception {
getMockEndpoint("mock:handled").expectedMessageCount(1);
template.sendBody("direct:start", "Hello,World");
assertMockEndpointsSatisfied();
}
}
|
SpringSplitterDetermineErrorHandlerIssueTest
|
java
|
quarkusio__quarkus
|
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/AbstractRedisCommands.java
|
{
"start": 197,
"end": 1006
}
|
class ____ {
protected final RedisCommandExecutor redis;
protected final Marshaller marshaller;
public AbstractRedisCommands(RedisCommandExecutor redis, Marshaller marshaller) {
this.redis = redis;
this.marshaller = marshaller;
}
public Uni<Response> execute(RedisCommand cmd) {
return redis.execute(cmd.toRequest());
}
static boolean isMap(Response response) {
try {
return response != null && response.type() == ResponseType.MULTI && notEmptyOrNull(response.getKeys());
} catch (Exception ignored) {
// Not a map, but a plain multi
return false;
}
}
private static boolean notEmptyOrNull(Set<String> keys) {
return keys != null && !keys.isEmpty();
}
}
|
AbstractRedisCommands
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/AsyncRetryDuringSnapshotActionStep.java
|
{
"start": 3204,
"end": 8167
}
|
class ____ implements ActionListener<Void> {
private final ProjectId projectId;
private final Index index;
private final ActionListener<Void> originalListener;
private final ClusterStateObserver observer;
private final DiscoveryNode localNode;
SnapshotExceptionListener(
ProjectId projectId,
Index index,
ActionListener<Void> originalListener,
ClusterStateObserver observer,
DiscoveryNode localNode
) {
this.projectId = projectId;
this.index = index;
this.originalListener = originalListener;
this.observer = observer;
this.localNode = localNode;
}
@Override
public void onResponse(Void unused) {
originalListener.onResponse(null);
}
@Override
public void onFailure(Exception e) {
if (e instanceof SnapshotInProgressException) {
try {
logger.debug(
"[{}] attempted to run ILM step but a snapshot is in progress, step will retry at a later time",
index.getName()
);
final String indexName = index.getName();
observer.waitForNextChange(new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {
if (state.nodes().isLocalNodeElectedMaster() == false) {
originalListener.onFailure(new NotMasterException("no longer master"));
return;
}
try {
logger.debug("[{}] retrying ILM step after snapshot has completed", indexName);
final var projectState = state.projectState(projectId);
IndexMetadata idxMeta = projectState.metadata().index(index);
if (idxMeta == null) {
// The index has since been deleted, mission accomplished!
originalListener.onResponse(null);
} else {
// Re-invoke the performAction method with the new state
performAction(idxMeta, projectState, observer, originalListener);
}
} catch (Exception e) {
originalListener.onFailure(e);
}
}
@Override
public void onClusterServiceClose() {
originalListener.onFailure(new NodeClosedException(localNode));
}
@Override
public void onTimeout(TimeValue timeout) {
originalListener.onFailure(new IllegalStateException("step timed out while waiting for snapshots to complete"));
}
}, state -> {
if (state.nodes().isLocalNodeElectedMaster() == false) {
// ILM actions should only run on master, lets bail on failover
return true;
}
if (state.metadata().getProject(projectId).index(index) == null) {
// The index has since been deleted, mission accomplished!
return true;
}
for (List<SnapshotsInProgress.Entry> snapshots : SnapshotsInProgress.get(state).entriesByRepo(projectId)) {
for (SnapshotsInProgress.Entry snapshot : snapshots) {
if (snapshot.indices().containsKey(indexName)) {
// There is a snapshot running with this index name
return false;
}
}
}
// There are no snapshots for this index, so it's okay to proceed with this state
return true;
}, TimeValue.MAX_VALUE);
} catch (Exception secondError) {
// There was a second error trying to set up an observer,
// fail the original listener
secondError.addSuppressed(e);
assert false : new AssertionError("This should never fail", secondError);
originalListener.onFailure(secondError);
}
} else {
originalListener.onFailure(e);
}
}
}
}
|
SnapshotExceptionListener
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/state/metrics/StateMetricBase.java
|
{
"start": 1185,
"end": 3196
}
|
class ____ implements AutoCloseable {
protected static final String STATE_NAME_KEY = "state_name";
protected static final String STATE_CLEAR_LATENCY = "stateClearLatency";
private final MetricGroup metricGroup;
private final int sampleInterval;
private final Map<String, Histogram> histogramMetrics;
private final Supplier<Histogram> histogramSupplier;
private int clearCount = 0;
StateMetricBase(
String stateName,
MetricGroup metricGroup,
int sampleInterval,
int historySize,
boolean stateNameAsVariable) {
this.metricGroup =
stateNameAsVariable
? metricGroup.addGroup(STATE_NAME_KEY, stateName)
: metricGroup.addGroup(stateName);
this.sampleInterval = sampleInterval;
this.histogramMetrics = new HashMap<>();
this.histogramSupplier = () -> new DescriptiveStatisticsHistogram(historySize);
}
int getClearCount() {
return clearCount;
}
protected boolean trackMetricsOnClear() {
clearCount = loopUpdateCounter(clearCount);
return clearCount == 1;
}
protected int loopUpdateCounter(int counter) {
return (counter + 1 < sampleInterval) ? counter + 1 : 0;
}
protected void updateMetrics(String latencyLabel, long value) {
updateHistogram(latencyLabel, value);
}
private void updateHistogram(final String metricName, final long value) {
this.histogramMetrics
.computeIfAbsent(
metricName,
(k) -> {
Histogram histogram = histogramSupplier.get();
metricGroup.histogram(metricName, histogram);
return histogram;
})
.update(value);
}
@Override
public void close() throws Exception {
histogramMetrics.clear();
}
}
|
StateMetricBase
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/webapp/AppController.java
|
{
"start": 3849,
"end": 4671
}
|
class ____ will render the /jobcounters page
*/
protected Class<? extends View> countersPage() {
return CountersPage.class;
}
/**
* Render the /jobcounters page
*/
public void jobCounters() {
try {
requireJob();
}
catch (Exception e) {
renderText(e.getMessage());
return;
}
if (app.getJob() != null) {
setTitle(join("Counters for ", $(JOB_ID)));
}
render(countersPage());
}
/**
* Display a page showing a task's counters
*/
public void taskCounters() {
try {
requireTask();
}
catch (Exception e) {
renderText(e.getMessage());
return;
}
if (app.getTask() != null) {
setTitle(StringHelper.join("Counters for ", $(TASK_ID)));
}
render(countersPage());
}
/**
* @return the
|
that
|
java
|
junit-team__junit5
|
junit-platform-commons/src/main/java/org/junit/platform/commons/support/ModifierSupport.java
|
{
"start": 2068,
"end": 2119
}
|
class ____ {@code private}.
*
* @param clazz the
|
is
|
java
|
spring-projects__spring-boot
|
loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java
|
{
"start": 1802,
"end": 10501
}
|
class ____ extends AbstractPackagerTests<Repackager> {
private @Nullable File destination;
@Test
@SuppressWarnings("NullAway") // Test null check
void nullSource() {
assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(null));
}
@Test
void missingSource() {
assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(new File("missing")));
}
@Test
void directorySource() {
assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(this.tempDir));
}
@Test
void jarIsOnlyRepackagedOnce() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), false);
repackager.repackage(NO_LIBRARIES);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getPackagedManifest();
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
.isEqualTo("org.springframework.boot.loader.launch.JarLauncher");
assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
assertThat(hasPackagedLauncherClasses()).isTrue();
}
@Test
void sameSourceAndDestinationWithoutBackup() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = createRepackager(file, false);
repackager.setBackupSource(false);
repackager.repackage(NO_LIBRARIES);
assertThat(new File(file.getParent(), file.getName() + ".original")).doesNotExist();
assertThat(hasPackagedLauncherClasses()).isTrue();
}
@Test
void sameSourceAndDestinationWithBackup() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = createRepackager(file, false);
repackager.repackage(NO_LIBRARIES);
assertThat(new File(file.getParent(), file.getName() + ".original")).exists();
assertThat(hasPackagedLauncherClasses()).isTrue();
}
@Test
void differentDestination() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
Repackager repackager = createRepackager(source, true);
execute(repackager, NO_LIBRARIES);
assertThat(new File(source.getParent(), source.getName() + ".original")).doesNotExist();
assertThat(hasLauncherClasses(source)).isFalse();
assertThat(hasPackagedLauncherClasses()).isTrue();
}
@Test
@SuppressWarnings("NullAway") // Test null check
void nullDestination() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), true);
assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES))
.withMessageContaining("Invalid destination");
}
@Test
void destinationIsDirectory() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), true);
assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(this.tempDir, NO_LIBRARIES))
.withMessageContaining("Invalid destination");
}
@Test
void overwriteDestination() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), true);
assertThat(this.destination).isNotNull();
this.destination.createNewFile();
repackager.repackage(this.destination, NO_LIBRARIES);
assertThat(hasLauncherClasses(this.destination)).isTrue();
}
@Test
void layoutFactoryGetsOriginalFile() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), false);
repackager.setLayoutFactory(new TestLayoutFactory());
assertThat(this.destination).isNotNull();
repackager.repackage(this.destination, NO_LIBRARIES);
assertThat(hasLauncherClasses(this.destination)).isTrue();
}
@Test
void allLoaderDirectoriesAndFilesUseSameTimestamp() throws IOException {
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), true);
Long timestamp = null;
assertThat(this.destination).isNotNull();
repackager.repackage(this.destination, NO_LIBRARIES);
for (ZipArchiveEntry entry : getAllPackagedEntries()) {
if (entry.getName().startsWith("org/springframework/boot/loader")) {
if (timestamp == null) {
timestamp = entry.getTime();
}
else {
assertThat(entry.getTime())
.withFailMessage("Expected time %d to be equal to %d for entry %s", entry.getTime(), timestamp,
entry.getName())
.isEqualTo(timestamp);
}
}
}
}
@Test
void allEntriesUseProvidedTimestamp() throws IOException {
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), true);
long timestamp = OffsetDateTime.of(2000, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant().toEpochMilli();
assertThat(this.destination).isNotNull();
repackager.repackage(this.destination, NO_LIBRARIES, FileTime.fromMillis(timestamp));
long offsetTimestamp = DefaultTimeZoneOffset.INSTANCE.removeFrom(timestamp);
for (ZipArchiveEntry entry : getAllPackagedEntries()) {
assertThat(entry.getTime()).isEqualTo(offsetTimestamp);
}
}
@Test
void repackagingDeeplyNestedPackageIsNotProhibitivelySlow() throws IOException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
this.testJarFile.addClass("a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/Some.class",
ClassWithMainMethod.class);
Repackager repackager = createRepackager(this.testJarFile.getFile(), true);
assertThat(this.destination).isNotNull();
repackager.repackage(this.destination, NO_LIBRARIES, null);
stopWatch.stop();
assertThat(stopWatch.getTotalTimeMillis()).isLessThan(5000);
}
@Test
void signedJar() throws Exception {
Repackager packager = createPackager();
packager.setMainClass("a.b.C");
Manifest manifest = new Manifest();
Attributes attributes = new Attributes();
attributes.putValue("SHA1-Digest", "0000");
manifest.getEntries().put("a/b/C.class", attributes);
TestJarFile libJar = new TestJarFile(this.tempDir);
libJar.addManifest(manifest);
execute(packager, (callback) -> callback.library(newLibrary(libJar.getFile(), LibraryScope.COMPILE, false)));
assertThat(hasPackagedEntry("META-INF/BOOT.SF")).isTrue();
}
private boolean hasLauncherClasses(File file) throws IOException {
return hasEntry(file, "org/springframework/boot/")
&& hasEntry(file, "org/springframework/boot/loader/launch/JarLauncher.class");
}
private boolean hasEntry(File file, String name) throws IOException {
return getEntry(file, name) != null;
}
private JarEntry getEntry(File file, String name) throws IOException {
try (JarFile jarFile = new JarFile(file)) {
return jarFile.getJarEntry(name);
}
}
@Override
protected Repackager createPackager(File source) {
return createRepackager(source, true);
}
private Repackager createRepackager(File source, boolean differentDest) {
String ext = StringUtils.getFilenameExtension(source.getName());
this.destination = differentDest ? new File(this.tempDir, "dest." + ext) : source;
return new Repackager(source);
}
@Override
protected void execute(Repackager packager, Libraries libraries) throws IOException {
assertThat(this.destination).isNotNull();
packager.repackage(this.destination, libraries);
}
@Override
protected Collection<ZipArchiveEntry> getAllPackagedEntries() throws IOException {
List<ZipArchiveEntry> result = new ArrayList<>();
try (ZipFile zip = ZipFile.builder().setFile(this.destination).get()) {
Enumeration<ZipArchiveEntry> entries = zip.getEntries();
while (entries.hasMoreElements()) {
result.add(entries.nextElement());
}
}
return result;
}
@Override
protected Manifest getPackagedManifest() throws IOException {
assertThat(this.destination).isNotNull();
try (JarFile jarFile = new JarFile(this.destination)) {
return jarFile.getManifest();
}
}
@Override
protected @Nullable String getPackagedEntryContent(String name) throws IOException {
try (ZipFile zip = ZipFile.builder().setFile(this.destination).get()) {
ZipArchiveEntry entry = zip.getEntry(name);
if (entry == null) {
return null;
}
byte[] bytes = FileCopyUtils.copyToByteArray(zip.getInputStream(entry));
return new String(bytes, StandardCharsets.UTF_8);
}
}
static
|
RepackagerTests
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/issue_2200/Issue2289.java
|
{
"start": 229,
"end": 574
}
|
class ____ extends TestCase {
public void test_for_issue() throws Exception {
B b = new B();
b.id = 123;
JSONSerializer jsonSerializer = new JSONSerializer();
jsonSerializer.writeAs(b, A.class);
String str = jsonSerializer.toString();
assertEquals("{}", str);
}
public static
|
Issue2289
|
java
|
apache__logging-log4j2
|
log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/AbstractConfigurationTest.java
|
{
"start": 1787,
"end": 4090
}
|
class ____ {
@Test
void propertiesCanComeLast() {
final Configuration config = new TestConfiguration(null, Collections.singletonMap("console.name", "CONSOLE"));
config.initialize();
final StrSubstitutor substitutor = config.getStrSubstitutor();
assertThat(substitutor.replace("${console.name}"))
.as("No interpolation for '${console.name}'")
.isEqualTo("CONSOLE");
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
@Issue("https://github.com/apache/logging-log4j2/issues/2309")
void substitutorHasConfigurationAndLoggerContext(final boolean hasProperties) {
final LoggerContext context = mock(LoggerContext.class);
final Configuration config = new TestConfiguration(context, hasProperties ? Collections.emptyMap() : null);
config.initialize();
final Interpolator runtime = (Interpolator) config.getStrSubstitutor().getVariableResolver();
final Interpolator configTime =
(Interpolator) config.getConfigurationStrSubstitutor().getVariableResolver();
for (final Interpolator interpolator : Arrays.asList(runtime, configTime)) {
assertThat(InterpolatorTest.getConfiguration(interpolator)).isEqualTo(config);
assertThat(InterpolatorTest.getLoggerContext(interpolator)).isEqualTo(context);
}
}
@Test
@LoggerContextSource("log4j2-script-order-test.xml")
void scriptRefShouldBeResolvedWhenScriptsElementIsLast(final Configuration config) {
assertThat(config.getFilter())
.as("Top-level filter should be a CompositeFilter")
.isInstanceOf(CompositeFilter.class);
final CompositeFilter compositeFilter = (CompositeFilter) config.getFilter();
assertThat(compositeFilter.getFilters())
.as("CompositeFilter should contain one filter")
.hasSize(1);
final ScriptFilter scriptFilter =
(ScriptFilter) compositeFilter.getFilters().get(0);
assertThat(scriptFilter).isNotNull();
assertThat(scriptFilter.toString())
.as("Script name should match the one in the config")
.isEqualTo("GLOBAL_FILTER");
}
private static
|
AbstractConfigurationTest
|
java
|
quarkusio__quarkus
|
integration-tests/oidc-token-propagation-reactive/src/test/java/io/quarkus/it/keycloak/OidcTokenReactivePropagationTest.java
|
{
"start": 403,
"end": 1996
}
|
class ____ {
@Test
public void testGetUserNameWithAccessTokenPropagation() throws Exception {
try (final WebClient webClient = createWebClient()) {
HtmlPage page = webClient.getPage("http://localhost:8081/frontend/access-token-propagation");
assertEquals("Sign in to quarkus", page.getTitleText());
HtmlForm loginForm = page.getForms().get(0);
loginForm.getInputByName("username").setValueAttribute("alice");
loginForm.getInputByName("password").setValueAttribute("alice");
TextPage textPage = loginForm.getButtonByName("login").click();
assertEquals("Bearer:alice", textPage.getContent());
textPage = webClient.getPage("http://localhost:8081/frontend/id-token-propagation");
assertEquals("ID:alice", textPage.getContent());
webClient.getCookieManager().clearCookies();
}
}
@Test
public void testNoToken() {
RestAssured.given().when().redirects().follow(false)
.get("/frontend/access-token-propagation")
.then()
.statusCode(302);
}
private WebClient createWebClient() throws Exception {
WebClient webClient = new WebClient();
webClient.setCssErrorHandler(new SilentCssErrorHandler());
return webClient;
}
@Test
public void testGetUserNameWithServiceWithoutToken() {
RestAssured.when().get("/frontend/service-without-token")
.then()
.statusCode(500);
}
}
|
OidcTokenReactivePropagationTest
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/event/UpdateNodeToLabelsMappingsEvent.java
|
{
"start": 961,
"end": 1348
}
|
class ____ extends NodeLabelsStoreEvent {
private Map<NodeId, Set<String>> nodeToLabels;
public UpdateNodeToLabelsMappingsEvent(Map<NodeId, Set<String>> nodeToLabels) {
super(NodeLabelsStoreEventType.STORE_NODE_TO_LABELS);
this.nodeToLabels = nodeToLabels;
}
public Map<NodeId, Set<String>> getNodeToLabels() {
return nodeToLabels;
}
}
|
UpdateNodeToLabelsMappingsEvent
|
java
|
processing__processing4
|
core/src/processing/core/PShapeSVG.java
|
{
"start": 1489,
"end": 3550
}
|
class ____ will cause your code to break
* when combined with future versions of Processing.
* <p>
* SVG stands for Scalable Vector Graphics, a portable graphics format.
* It is a vector format so it allows for "infinite" resolution and relatively
* small file sizes. Most modern media software can view SVG files, including
* Adobe products, Firefox, etc. Illustrator and Inkscape can edit SVG files.
* View the SVG specification <A HREF="http://www.w3.org/TR/SVG">here</A>.
* <p>
* We have no intention of turning this into a full-featured SVG library.
* The goal of this project is a basic shape importer that originally was small
* enough to be included with applets, meaning that its download size should be
* in the neighborhood of 25-30 Kb. Though we're far less limited nowadays on
* size constraints, we remain extremely limited in terms of time, and do not
* have volunteers who are available to maintain a larger SVG library.
* <p>
* For more sophisticated import/export, consider the
* <A HREF="http://xmlgraphics.apache.org/batik/">Batik</A>
* library from the Apache Software Foundation.
* <p>
* Batik is used in the SVG Export library in Processing 3, however using it
* for full SVG import is still a considerable amount of work. Wiring it to
* Java2D wouldn't be too bad, but using it with OpenGL, JavaFX, and features
* like begin/endRecord() and begin/endRaw() would be considerable effort.
* <p>
* Future improvements to this library may focus on this properly supporting
* a specific subset of SVG, for instance the simpler SVG profiles known as
* <A HREF="http://www.w3.org/TR/SVGMobile/">SVG Tiny or Basic</A>,
* although we still would not support the interactivity options.
*
* <p> <hr noshade> <p>
*
* A minimal example program using SVG:
* (assuming a working moo.svg is in your data folder)
*
* <PRE>
* PShape moo;
*
* void setup() {
* size(400, 400);
* moo = loadShape("moo.svg");
* }
* void draw() {
* background(255);
* shape(moo, mouseX, mouseY);
* }
* </PRE>
*/
public
|
directly
|
java
|
grpc__grpc-java
|
api/src/main/java/io/grpc/Metadata.java
|
{
"start": 13603,
"end": 13774
}
|
class ____
* of {@link Key}. If the name ends with {@code "-bin"}, the value can be raw binary. Otherwise,
* the value must contain only characters listed in the
|
comment
|
java
|
apache__flink
|
flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/fs/cache/DoubleListLru.java
|
{
"start": 11469,
"end": 11975
}
|
class ____ implements Iterator<Tuple2<K, V>> {
private Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Tuple2<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Tuple2<K, V> entry = Tuple2.of(current.key, current.value);
current = current.next;
return entry;
}
}
private
|
LruIterator
|
java
|
elastic__elasticsearch
|
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/support/CartesianPointValuesSource.java
|
{
"start": 1148,
"end": 2345
}
|
class ____ extends ValuesSource {
public static final CartesianPointValuesSource EMPTY = new CartesianPointValuesSource() {
@Override
public SortedNumericLongValues sortedNumericLongValues(LeafReaderContext context) {
return SortedNumericLongValues.EMPTY;
}
@Override
public SortedBinaryDocValues bytesValues(LeafReaderContext context) {
return org.elasticsearch.index.fielddata.FieldData.emptySortedBinary();
}
};
@Override
public DocValueBits docsWithValue(LeafReaderContext context) {
final MultiCartesianPointValues pointValues = pointValues(context);
return org.elasticsearch.index.fielddata.FieldData.docsWithValue(pointValues);
}
@Override
public final Function<Rounding, Rounding.Prepared> roundingPreparer(AggregationContext context) {
throw AggregationErrors.unsupportedRounding("POINT");
}
/**
* Return point values.
*/
public final MultiCartesianPointValues pointValues(LeafReaderContext context) {
return new MultiCartesianPointValues(sortedNumericLongValues(context));
}
public static final
|
CartesianPointValuesSource
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/cluster/coordination/ElasticsearchNodeCommandTests.java
|
{
"start": 10334,
"end": 11112
}
|
class ____ extends TestProjectCustomMetadata {
static final String TYPE = "missing_project_custom_metadata";
TestMissingProjectCustomMetadata(String data) {
super(data);
}
@Override
public String getWriteableName() {
return TYPE;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.current();
}
@Override
public EnumSet<Metadata.XContentContext> context() {
return EnumSet.of(Metadata.XContentContext.GATEWAY);
}
}
// Similar "Missing" custom but in the cluster scope. See also the comment above for TestMissingProjectCustomMetadata.
private static
|
TestMissingProjectCustomMetadata
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumeDynamicDoneFileNameWithTwoDotsTest.java
|
{
"start": 1236,
"end": 1356
}
|
class ____ an issue where an input file is not picked up due to a dynamic doneFileName containing two dots.
*/
public
|
tests
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/api/parallel/ResourceLockAnnotationTests.java
|
{
"start": 14285,
"end": 14665
}
|
class ____ {
@Test
@ResourceLock(value = "b1", mode = ResourceAccessMode.READ)
@ResourceLock(value = "b2", target = ResourceLockTarget.SELF)
void test() {
}
@Nested
@ResourceLock(value = "c1", mode = ResourceAccessMode.READ)
@ResourceLock(value = "c2", mode = ResourceAccessMode.READ, target = ResourceLockTarget.CHILDREN)
|
SharedResourcesViaAnnotationValueTestCase
|
java
|
spring-projects__spring-security
|
access/src/main/java/org/springframework/security/access/intercept/AfterInvocationProviderManager.java
|
{
"start": 4494,
"end": 4930
}
|
class ____ queries
* @return if the <code>AfterInvocationProviderManager</code> can support the secure
* object class, which requires every one of its <code>AfterInvocationProvider</code>s
* to support the secure object class
*/
@Override
public boolean supports(Class<?> clazz) {
for (AfterInvocationProvider provider : this.providers) {
if (!provider.supports(clazz)) {
return false;
}
}
return true;
}
}
|
being
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mappingexception/User.java
|
{
"start": 198,
"end": 477
}
|
class ____ {
private Long id;
private String username;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
|
User
|
java
|
elastic__elasticsearch
|
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/HindiNormalizationFilterFactory.java
|
{
"start": 964,
"end": 1371
}
|
class ____ extends AbstractTokenFilterFactory implements NormalizingTokenFilterFactory {
HindiNormalizationFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) {
super(name);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new HindiNormalizationFilter(tokenStream);
}
}
|
HindiNormalizationFilterFactory
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/TestBusinessBeanImpl.java
|
{
"start": 838,
"end": 1345
}
|
class ____ implements TestBusinessBean, ApplicationListener<SessionCreationEvent> {
@Override
public void setInteger(int i) {
}
@Override
public int getInteger() {
return 1314;
}
@Override
public void setString(String s) {
}
public String getString() {
return "A string.";
}
@Override
public void doSomething() {
}
@Override
public void unprotected() {
}
@Override
public void onApplicationEvent(SessionCreationEvent event) {
System.out.println(event);
}
}
|
TestBusinessBeanImpl
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/action/UpdateConnectorLastSyncStatsAction.java
|
{
"start": 1414,
"end": 1743
}
|
class ____ {
public static final String NAME = "cluster:admin/xpack/connector/update_last_sync_stats";
public static final ActionType<ConnectorUpdateActionResponse> INSTANCE = new ActionType<>(NAME);
private UpdateConnectorLastSyncStatsAction() {/* no instances */}
public static
|
UpdateConnectorLastSyncStatsAction
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/DNS.java
|
{
"start": 15626,
"end": 17097
}
|
interface ____ invalid
*
*/
public static List<InetAddress> getIPsAsInetAddressList(String strInterface,
boolean returnSubinterfaces) throws UnknownHostException {
if ("default".equals(strInterface)) {
return Arrays.asList(InetAddress.getByName(cachedHostAddress));
}
NetworkInterface netIf;
try {
netIf = NetworkInterface.getByName(strInterface);
if (netIf == null) {
netIf = getSubinterface(strInterface);
}
} catch (SocketException e) {
LOG.warn("I/O error finding interface {}: {}",
strInterface, e.getMessage());
return Arrays.asList(InetAddress.getByName(cachedHostAddress));
}
if (netIf == null) {
throw new UnknownHostException("No such interface " + strInterface);
}
// NB: Using a LinkedHashSet to preserve the order for callers
// that depend on a particular element being 1st in the array.
// For example, getDefaultIP always returns the first element.
LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>();
allAddrs.addAll(Collections.list(netIf.getInetAddresses()));
if (!returnSubinterfaces) {
allAddrs.removeAll(getSubinterfaceInetAddrs(netIf));
}
return new Vector<InetAddress>(allAddrs);
}
@VisibleForTesting
static String getCachedHostname() {
return cachedHostname;
}
@VisibleForTesting
static void setCachedHostname(String hostname) {
cachedHostname = hostname;
}
}
|
is
|
java
|
spring-projects__spring-security
|
core/src/main/java/org/springframework/security/authentication/InsufficientAuthenticationException.java
|
{
"start": 1378,
"end": 2041
}
|
class ____ extends AuthenticationException {
@Serial
private static final long serialVersionUID = -5514084346181236128L;
/**
* Constructs an <code>InsufficientAuthenticationException</code> with the specified
* message.
* @param msg the detail message
*/
public InsufficientAuthenticationException(String msg) {
super(msg);
}
/**
* Constructs an <code>InsufficientAuthenticationException</code> with the specified
* message and root cause.
* @param msg the detail message
* @param cause root cause
*/
public InsufficientAuthenticationException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
InsufficientAuthenticationException
|
java
|
quarkusio__quarkus
|
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/staticinit/StaticInitConfigInjectionMissingValueFailureTest.java
|
{
"start": 607,
"end": 1621
}
|
class ____ {
static final String PROPERTY_NAME = "static.init.missing.apfelstrudel";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot(root -> root
.addClasses(StaticInitBean.class))
.assertException(t -> {
assertThat(t).isInstanceOf(IllegalStateException.class)
.hasMessageContainingAll(
"A runtime config property value differs from the value that was injected during the static intialization phase",
"the runtime value of '" + PROPERTY_NAME
+ "' is [gizmo] but the value [null] was injected into io.quarkus.arc.test.config.staticinit.StaticInitConfigInjectionMissingValueFailureTest$StaticInitBean#value");
});
@Test
public void test() {
fail();
}
@Singleton
public static
|
StaticInitConfigInjectionMissingValueFailureTest
|
java
|
apache__camel
|
components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java
|
{
"start": 884,
"end": 2194
}
|
class ____ {
private String text;
private String channel;
private String username;
private String user;
private String iconUrl;
private String iconEmoji;
private List<Attachment> attachments;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getIconEmoji() {
return iconEmoji;
}
public void setIconEmoji(String iconEmoji) {
this.iconEmoji = iconEmoji;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public static
|
SlackMessage
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/map/MapAssert_containsEntry_Test.java
|
{
"start": 1200,
"end": 1923
}
|
class ____ extends MapAssertBaseTest {
final MapEntry<String, String>[] entries = array(entry("key1", "value1"));
@Override
protected MapAssert<Object, Object> invoke_api_method() {
return assertions.containsEntry("key1", "value1");
}
@Override
protected void verify_internal_effects() {
verify(maps).assertContains(getInfo(assertions), getActual(assertions), entries, null);
}
@Test
void should_honor_custom_value_equals_when_comparing_entry_values() {
// GIVEN
var map = Map.of("key", new AtomicInteger(1));
// WHEN/THEN
then(map).usingEqualsForValues((v1, v2) -> v1.get() == v2.get())
.containsEntry("key", new AtomicInteger(1));
}
}
|
MapAssert_containsEntry_Test
|
java
|
elastic__elasticsearch
|
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java
|
{
"start": 129506,
"end": 137028
}
|
class ____ extends AbstractRunnable {
private final BytesKey decodedSalt;
private final KeyAndCache keyAndCache;
private final ActionListener<SecretKey> listener;
KeyComputingRunnable(BytesKey decodedSalt, KeyAndCache keyAndCache, ActionListener<SecretKey> listener) {
this.decodedSalt = decodedSalt;
this.keyAndCache = keyAndCache;
this.listener = listener;
}
@Override
protected void doRun() {
try {
final SecretKey computedKey = keyAndCache.getOrComputeKey(decodedSalt);
listener.onResponse(computedKey);
} catch (ExecutionException e) {
if (e.getCause() != null
&& (e.getCause() instanceof GeneralSecurityException
|| e.getCause() instanceof IOException
|| e.getCause() instanceof IllegalArgumentException)) {
// this could happen if another realm supports the Bearer token so we should
// see if another realm can use this token!
logger.debug("unable to decode bearer token", e);
listener.onResponse(null);
} else {
listener.onFailure(e);
}
}
}
@Override
public void onFailure(Exception e) {
listener.onFailure(e);
}
}
/**
* Returns the current in-use metdata of this {@link TokenService}
*/
public synchronized TokenMetadata getTokenMetadata() {
return newTokenMetadata(keyCache.currentTokenKeyHash, keyCache.cache.values());
}
private static TokenMetadata newTokenMetadata(BytesKey activeTokenKey, Iterable<KeyAndCache> iterable) {
List<KeyAndTimestamp> list = new ArrayList<>();
for (KeyAndCache v : iterable) {
list.add(v.keyAndTimestamp);
}
return new TokenMetadata(list, activeTokenKey.bytes);
}
/**
* Refreshes the current in-use metadata.
*/
synchronized void refreshMetadata(TokenMetadata metadata) {
BytesKey currentUsedKeyHash = new BytesKey(metadata.getCurrentKeyHash());
byte[] saltArr = new byte[SALT_BYTES];
Map<BytesKey, KeyAndCache> map = Maps.newMapWithExpectedSize(metadata.getKeys().size());
long maxTimestamp = createdTimeStamps.get();
for (KeyAndTimestamp key : metadata.getKeys()) {
secureRandom.nextBytes(saltArr);
KeyAndCache keyAndCache = new KeyAndCache(key, new BytesKey(saltArr));
maxTimestamp = Math.max(keyAndCache.keyAndTimestamp.getTimestamp(), maxTimestamp);
if (keyCache.cache.containsKey(keyAndCache.getKeyHash()) == false) {
map.put(keyAndCache.getKeyHash(), keyAndCache);
} else {
map.put(keyAndCache.getKeyHash(), keyCache.get(keyAndCache.getKeyHash())); // maintain the cache we already have
}
}
if (map.containsKey(currentUsedKeyHash) == false) {
// this won't leak any secrets it's only exposing the current set of hashes
throw new IllegalStateException("Current key is not in the map: " + map.keySet() + " key: " + currentUsedKeyHash);
}
createdTimeStamps.set(maxTimestamp);
keyCache = new TokenKeys(Collections.unmodifiableMap(map), currentUsedKeyHash);
logger.debug(() -> format("refreshed keys current: %s, keys: %s", currentUsedKeyHash, keyCache.cache.keySet()));
}
private SecureString generateTokenKey() {
byte[] keyBytes = new byte[KEY_BYTES];
byte[] encode = new byte[0];
char[] ref = new char[0];
try {
secureRandom.nextBytes(keyBytes);
encode = Strings.BASE_64_NO_PADDING_URL_ENCODER.encode(keyBytes);
ref = new char[encode.length];
int len = UnicodeUtil.UTF8toUTF16(encode, 0, encode.length, ref);
return new SecureString(Arrays.copyOfRange(ref, 0, len));
} finally {
Arrays.fill(keyBytes, (byte) 0x00);
Arrays.fill(encode, (byte) 0x00);
Arrays.fill(ref, (char) 0x00);
}
}
@SuppressForbidden(reason = "legacy usage of unbatched task") // TODO add support for batching here
private void submitUnbatchedTask(@SuppressWarnings("SameParameterValue") String source, ClusterStateUpdateTask task) {
clusterService.submitUnbatchedStateUpdateTask(source, task);
}
private void initialize(ClusterService clusterService) {
clusterService.addListener(event -> {
ClusterState state = event.state();
if (state.getBlocks().hasGlobalBlock(STATE_NOT_RECOVERED_BLOCK)) {
return;
}
if (state.nodes().isLocalNodeElectedMaster()) {
if (XPackPlugin.isReadyForXPackCustomMetadata(state)) {
installTokenMetadata(state);
} else {
logger.debug(
"cannot add token metadata to cluster as the following nodes might not understand the metadata: {}",
() -> XPackPlugin.nodesNotReadyForXPackCustomMetadata(state)
);
}
}
TokenMetadata custom = event.state().custom(TokenMetadata.TYPE);
if (custom != null && custom.equals(getTokenMetadata()) == false) {
logger.info("refresh keys");
try {
refreshMetadata(custom);
} catch (Exception e) {
logger.warn("refreshing metadata failed", e);
}
logger.info("refreshed keys");
}
});
}
// to prevent too many cluster state update tasks to be queued for doing the same update
private final AtomicBoolean installTokenMetadataInProgress = new AtomicBoolean(false);
private void installTokenMetadata(ClusterState state) {
if (state.custom(TokenMetadata.TYPE) == null) {
if (installTokenMetadataInProgress.compareAndSet(false, true)) {
submitUnbatchedTask("install-token-metadata", new ClusterStateUpdateTask(Priority.URGENT) {
@Override
public ClusterState execute(ClusterState currentState) {
XPackPlugin.checkReadyForXPackCustomMetadata(currentState);
if (currentState.custom(TokenMetadata.TYPE) == null) {
return ClusterState.builder(currentState).putCustom(TokenMetadata.TYPE, getTokenMetadata()).build();
} else {
return currentState;
}
}
@Override
public void onFailure(Exception e) {
installTokenMetadataInProgress.set(false);
logger.error("unable to install token metadata", e);
}
@Override
public void clusterStateProcessed(ClusterState oldState, ClusterState newState) {
installTokenMetadataInProgress.set(false);
}
});
}
}
}
/**
* Package private for testing
*/
void clearActiveKeyCache() {
this.keyCache.activeKeyCache.keyCache.invalidateAll();
}
static final
|
KeyComputingRunnable
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/inject/ast/GenericPlaceholderElement.java
|
{
"start": 2295,
"end": 2701
}
|
class ____ can be a resolved placeholder.
* We want to keep the placeholder to reference the type annotations etc.
*
* @return The resolved value of the placeholder.
* @since 4.0.0
*/
@NextMajorVersion("Remove this method. There is an equivalent in the super class.")
@Override
default Optional<ClassElement> getResolved() {
return Optional.empty();
}
}
|
element
|
java
|
resilience4j__resilience4j
|
resilience4j-spring/src/test/java/io/github/resilience4j/circuitbreaker/configure/RxJava2CircuitBreakerAspectExtTest.java
|
{
"start": 1150,
"end": 2154
}
|
class ____ {
@Mock
ProceedingJoinPoint proceedingJoinPoint;
@InjectMocks
RxJava2CircuitBreakerAspectExt rxJava2CircuitBreakerAspectExt;
@Test
public void testCheckTypes() {
assertThat(rxJava2CircuitBreakerAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava2CircuitBreakerAspectExt.canHandleReturnType(Single.class)).isTrue();
}
@Test
public void testReactorTypes() throws Throwable {
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava2CircuitBreakerAspectExt
.handle(proceedingJoinPoint, circuitBreaker, "testMethod")).isNotNull();
when(proceedingJoinPoint.proceed()).thenReturn(Flowable.just("Test"));
assertThat(rxJava2CircuitBreakerAspectExt
.handle(proceedingJoinPoint, circuitBreaker, "testMethod")).isNotNull();
}
}
|
RxJava2CircuitBreakerAspectExtTest
|
java
|
resilience4j__resilience4j
|
resilience4j-spring6/src/test/java/io/github/resilience4j/spring6/timelimiter/configure/TimeLimiterConfigurationSpringTest.java
|
{
"start": 1196,
"end": 1981
}
|
class ____ {
@Autowired
private ConfigWithOverrides configWithOverrides;
@Test
public void testAllCircuitBreakerConfigurationBeansOverridden() {
assertNotNull(configWithOverrides.timeLimiterRegistry);
assertNotNull(configWithOverrides.timeLimiterAspect);
assertNotNull(configWithOverrides.timeLimiterEventEventConsumerRegistry);
assertNotNull(configWithOverrides.timeLimiterConfigurationProperties);
assertEquals(1, configWithOverrides.timeLimiterConfigurationProperties.getConfigs().size());
}
@Configuration
@ComponentScan({"io.github.resilience4j.spring6.timelimiter","io.github.resilience4j.spring6.fallback", "io.github.resilience4j.spring6.spelresolver"})
public static
|
TimeLimiterConfigurationSpringTest
|
java
|
elastic__elasticsearch
|
modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/Walker.java
|
{
"start": 8940,
"end": 11951
}
|
class ____ extends PainlessParserBaseVisitor<ANode> {
public static SClass buildPainlessTree(String sourceName, String sourceText, CompilerSettings settings) {
return new Walker(sourceName, sourceText, settings).source;
}
private final CompilerSettings settings;
private final String sourceName;
private int identifier;
private final SClass source;
private Walker(String sourceName, String sourceText, CompilerSettings settings) {
this.settings = settings;
this.sourceName = sourceName;
this.identifier = 0;
this.source = (SClass) visit(buildAntlrTree(sourceText));
}
private int nextIdentifier() {
return identifier++;
}
private SourceContext buildAntlrTree(String sourceString) {
ANTLRInputStream stream = new ANTLRInputStream(sourceString);
PainlessLexer lexer = new EnhancedPainlessLexer(stream, sourceName);
PainlessParser parser = new PainlessParser(new CommonTokenStream(lexer));
ParserErrorStrategy strategy = new ParserErrorStrategy(sourceName);
lexer.removeErrorListeners();
parser.removeErrorListeners();
if (settings.isPicky()) {
setupPicky(parser);
}
parser.setErrorHandler(strategy);
return parser.source();
}
private static void setupPicky(PainlessParser parser) {
// Diagnostic listener invokes syntaxError on other listeners for ambiguity issues,
parser.addErrorListener(new DiagnosticErrorListener(true));
// a second listener to fail the test when the above happens.
parser.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(
final Recognizer<?, ?> recognizer,
final Object offendingSymbol,
final int line,
final int charPositionInLine,
final String msg,
final RecognitionException e
) {
throw new AssertionError("line: " + line + ", offset: " + charPositionInLine + ", symbol:" + offendingSymbol + " " + msg);
}
});
// Enable exact ambiguity detection (costly). we enable exact since its the default for
// DiagnosticErrorListener, life is too short to think about what 'inexact ambiguity' might mean.
parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
}
private Location location(ParserRuleContext ctx) {
return new Location(sourceName, ctx.getStart().getStartIndex());
}
@Override
public ANode visitSource(SourceContext ctx) {
List<SFunction> functions = new ArrayList<>();
for (FunctionContext function : ctx.function()) {
functions.add((SFunction) visit(function));
}
// handle the code to generate the execute method here
// because the statements come loose from the grammar as
// part of the overall
|
Walker
|
java
|
dropwizard__dropwizard
|
dropwizard-logging/src/test/java/io/dropwizard/logging/common/DefaultLoggingFactoryTest.java
|
{
"start": 1288,
"end": 9175
}
|
class ____ {
private final ObjectMapper objectMapper = Jackson.newObjectMapper();
private final ConfigurationSourceProvider configurationSourceProvider = new ResourceConfigurationSourceProvider();
private final YamlConfigurationFactory<DefaultLoggingFactory> factory = new YamlConfigurationFactory<>(
DefaultLoggingFactory.class,
BaseValidator.newValidator(),
objectMapper, "dw");
private DefaultLoggingFactory config;
@BeforeEach
void setUp() throws Exception {
objectMapper.getSubtypeResolver().registerSubtypes(ConsoleAppenderFactory.class,
FileAppenderFactory.class,
SyslogAppenderFactory.class);
config = factory.build(configurationSourceProvider, "yaml/logging.yml");
}
@Test
void hasADefaultLevel() {
assertThat(config.getLevel()).isEqualTo("INFO");
}
@Test
void loggerLevelsCanBeOff() throws Exception {
DefaultLoggingFactory config = null;
try {
config = factory.build(configurationSourceProvider, "yaml/logging_level_off.yml");
config.configure(new MetricRegistry(), "test-logger");
final ILoggerFactory loggerContext = LoggerFactory.getILoggerFactory();
final Logger rootLogger = ((LoggerContext) loggerContext).getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
final Logger appLogger = ((LoggerContext) loggerContext).getLogger("com.example.app");
final Logger newAppLogger = ((LoggerContext) loggerContext).getLogger("com.example.newApp");
final Logger legacyAppLogger = ((LoggerContext) loggerContext).getLogger("com.example.legacyApp");
assertThat(rootLogger.getLevel()).isEqualTo(Level.OFF);
assertThat(appLogger.getLevel()).isEqualTo(Level.OFF);
assertThat(newAppLogger.getLevel()).isEqualTo(Level.OFF);
assertThat(legacyAppLogger.getLevel()).isEqualTo(Level.OFF);
} finally {
if (config != null) {
config.reset();
}
}
}
@Test
void canParseNewLoggerFormat() throws Exception {
final DefaultLoggingFactory config = factory.build(configurationSourceProvider, "yaml/logging_advanced.yml");
assertThat(config.getLoggers()).contains(MapEntry.entry("com.example.app", new TextNode("INFO")));
final JsonNode newApp = config.getLoggers().get("com.example.newApp");
assertThat(newApp).isNotNull();
final LoggerConfiguration newAppConfiguration = objectMapper.treeToValue(newApp, LoggerConfiguration.class);
assertThat(newAppConfiguration.getLevel()).isEqualTo("DEBUG");
assertThat(newAppConfiguration.getAppenders())
.singleElement()
.isInstanceOfSatisfying(FileAppenderFactory.class, fileAppenderFactory ->
assertThat(fileAppenderFactory)
.satisfies(f -> assertThat(f.getCurrentLogFilename()).isEqualTo("${new_app}.log"))
.satisfies(f -> assertThat(f.getArchivedLogFilenamePattern()).isEqualTo("${new_app}-%d.log.gz"))
.satisfies(f -> assertThat(f.getArchivedFileCount()).isEqualTo(5))
.satisfies(f -> assertThat(f.getBufferSize().toKibibytes()).isEqualTo(256))
.extracting(FileAppenderFactory::getFilterFactories)
.asInstanceOf(InstanceOfAssertFactories.LIST)
.hasSize(2)
.satisfies(factories -> assertThat(factories).element(0).isExactlyInstanceOf(TestFilterFactory.class))
.satisfies(factories -> assertThat(factories).element(1).isExactlyInstanceOf(SecondTestFilterFactory.class)));
final JsonNode legacyApp = config.getLoggers().get("com.example.legacyApp");
assertThat(legacyApp).isNotNull();
final LoggerConfiguration legacyAppConfiguration = objectMapper.treeToValue(legacyApp, LoggerConfiguration.class);
assertThat(legacyAppConfiguration.getLevel()).isEqualTo("DEBUG");
// We should not create additional appenders, if they are not specified
assertThat(legacyAppConfiguration.getAppenders()).isEmpty();
}
@Test
void testConfigure(@TempDir Path tempDir) throws Exception {
final StringSubstitutor substitutor = new StringSubstitutor(Map.of(
"new_app", tempDir.resolve("example-new-app").toFile().getAbsolutePath(),
"new_app_not_additive", tempDir.resolve("example-new-app-not-additive").toFile().getAbsolutePath(),
"default", tempDir.resolve("example").toFile().getAbsolutePath()
));
DefaultLoggingFactory config = null;
try {
config = factory.build(new SubstitutingSourceProvider(configurationSourceProvider, substitutor), "yaml/logging_advanced.yml");
config.configure(new MetricRegistry(), "test-logger");
LoggerFactory.getLogger("com.example.app").debug("Application debug log");
LoggerFactory.getLogger("com.example.app").info("Application log");
LoggerFactory.getLogger("com.example.newApp").debug("New application debug log");
LoggerFactory.getLogger("com.example.newApp").info("New application info log");
LoggerFactory.getLogger("com.example.legacyApp").debug("Legacy application debug log");
LoggerFactory.getLogger("com.example.legacyApp").info("Legacy application info log");
LoggerFactory.getLogger("com.example.notAdditive").debug("Not additive application debug log");
LoggerFactory.getLogger("com.example.notAdditive").info("Not additive application info log");
config.stop();
config.reset();
assertThat(Files.readAllLines(tempDir.resolve("example.log"))).containsOnly(
"INFO com.example.app: Application log",
"DEBUG com.example.newApp: New application debug log",
"INFO com.example.newApp: New application info log",
"DEBUG com.example.legacyApp: Legacy application debug log",
"INFO com.example.legacyApp: Legacy application info log");
assertThat(Files.readAllLines(tempDir.resolve("example-new-app.log"))).containsOnly(
"DEBUG com.example.newApp: New application debug log",
"INFO com.example.newApp: New application info log");
assertThat(Files.readAllLines(tempDir.resolve("example-new-app-not-additive.log"))).containsOnly(
"DEBUG com.example.notAdditive: Not additive application debug log",
"INFO com.example.notAdditive: Not additive application info log");
} finally {
if (config != null) {
config.reset();
}
}
}
@Test
void testResetAppenders() throws Exception {
final DefaultLoggingFactory config = factory.build(configurationSourceProvider, "yaml/logging.yml");
config.configure(new MetricRegistry(), "test-logger");
config.reset();
// There should be exactly one appender configured, a ConsoleAppender
assertThat(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.isInstanceOfSatisfying(Logger.class, logger ->
assertThat(logger.iteratorForAppenders())
.toIterable()
.singleElement()
.isInstanceOf(ConsoleAppender.class)
.as("context").matches((Appender<?> a) -> a.getContext() != null)
.as("started").matches(LifeCycle::isStarted));
}
@Test
void testToStringIsImplemented() {
assertThat(config.toString()).startsWith(
"DefaultLoggingFactory{level=INFO, loggers={com.example.app=\"DEBUG\"}, appenders=");
}
}
|
DefaultLoggingFactoryTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.