language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/engine/ThreadPoolMergeExecutorService.java | {
"start": 45457,
"end": 46516
} | interface ____ {
void accept(long prev, long next);
}
}
public boolean usingMaxTargetIORateBytesPerSec() {
return MAX_IO_RATE.getBytes() == targetIORateBytesPerSec.get();
}
public void registerMergeEventListener(MergeEventListener consumer) {
mergeEventListeners.add(consumer);
}
// exposed for tests
Set<MergeTask> getRunningMergeTasks() {
return runningMergeTasks;
}
// exposed for tests
int getMergeTasksQueueLength() {
return queuedMergeTasks.queueSize();
}
// exposed for tests
long getDiskSpaceAvailableForNewMergeTasks() {
return queuedMergeTasks.getAvailableBudget();
}
// exposed for tests and stats
long getTargetIORateBytesPerSec() {
return targetIORateBytesPerSec.get();
}
// exposed for tests
int getMaxConcurrentMerges() {
return maxConcurrentMerges;
}
@Override
public void close() throws IOException {
availableDiskSpacePeriodicMonitor.close();
}
}
| UpdateConsumer |
java | elastic__elasticsearch | x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/AsyncHttpResourceHelper.java | {
"start": 861,
"end": 1386
} | class ____ {
@SuppressWarnings("unchecked")
static ActionListener<Boolean> mockBooleanActionListener() {
return mock(ActionListener.class);
}
@SuppressWarnings("unchecked")
static ActionListener<HttpResource.ResourcePublishResult> mockPublishResultActionListener() {
return mock(ActionListener.class);
}
static <T> ActionListener<T> wrapMockListener(ActionListener<T> mock) {
// wraps the mock listener so that default functions on the ActionListener | AsyncHttpResourceHelper |
java | google__guava | android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java | {
"start": 10744,
"end": 10855
} | class ____ be created in the
* test to facilitate equality testing. For example:
*
* <pre>
* public | can |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlPrepareStatement.java | {
"start": 932,
"end": 1985
} | class ____ extends MySqlStatementImpl {
private SQLName name;
private SQLExpr from;
public MySqlPrepareStatement() {
}
public MySqlPrepareStatement(SQLName name, SQLExpr from) {
this.name = name;
this.from = from;
}
public SQLName getName() {
return name;
}
public void setName(SQLName name) {
this.name = name;
}
public SQLExpr getFrom() {
return from;
}
public void setFrom(SQLExpr from) {
this.from = from;
}
public void accept0(MySqlASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, name);
acceptChild(visitor, from);
}
visitor.endVisit(this);
}
@Override
public List<SQLObject> getChildren() {
List<SQLObject> children = new ArrayList<SQLObject>();
if (name != null) {
children.add(name);
}
if (this.from != null) {
children.add(from);
}
return children;
}
}
| MySqlPrepareStatement |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MinaEndpointBuilderFactory.java | {
"start": 82297,
"end": 84885
} | interface ____ {
/**
* Mina (camel-mina)
* Socket level networking using TCP or UDP with Apache Mina 2.x.
*
* Category: networking
* Since: 2.10
* Maven coordinates: org.apache.camel:camel-mina
*
* @return the dsl builder for the headers' name.
*/
default MinaHeaderNameBuilder mina() {
return MinaHeaderNameBuilder.INSTANCE;
}
/**
* Mina (camel-mina)
* Socket level networking using TCP or UDP with Apache Mina 2.x.
*
* Category: networking
* Since: 2.10
* Maven coordinates: org.apache.camel:camel-mina
*
* Syntax: <code>mina:protocol:host:port</code>
*
* Path parameter: protocol (required)
* Protocol to use
*
* Path parameter: host (required)
* Hostname to use. Use localhost or 0.0.0.0 for local server as
* consumer. For producer use the hostname or ip address of the remote
* server.
*
* Path parameter: port (required)
* Port number
*
* @param path protocol:host:port
* @return the dsl builder
*/
default MinaEndpointBuilder mina(String path) {
return MinaEndpointBuilderFactory.endpointBuilder("mina", path);
}
/**
* Mina (camel-mina)
* Socket level networking using TCP or UDP with Apache Mina 2.x.
*
* Category: networking
* Since: 2.10
* Maven coordinates: org.apache.camel:camel-mina
*
* Syntax: <code>mina:protocol:host:port</code>
*
* Path parameter: protocol (required)
* Protocol to use
*
* Path parameter: host (required)
* Hostname to use. Use localhost or 0.0.0.0 for local server as
* consumer. For producer use the hostname or ip address of the remote
* server.
*
* Path parameter: port (required)
* Port number
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path protocol:host:port
* @return the dsl builder
*/
default MinaEndpointBuilder mina(String componentName, String path) {
return MinaEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the Mina component.
*/
public static | MinaBuilders |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/FloatLeg.java | {
"start": 413,
"end": 1133
} | enum ____ {
LIBOR, EURIBOR, TIBOR}
;
private RateIndex rateIndex;
/**
* Spread over the selected rate index (in basis points).
*/
private double rateSpread;
public RateIndex getRateIndex() {
return rateIndex;
}
public void setRateIndex(RateIndex rateIndex) {
this.rateIndex = rateIndex;
}
public double getRateSpread() {
return rateSpread;
}
public void setRateSpread(double rateSpread) {
this.rateSpread = rateSpread;
}
public String toString() {
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits( 1 );
format.setMaximumFractionDigits( 1 );
return "[" + getRateIndex().toString() + "+" + format.format( getRateSpread() ) + "]";
}
}
| RateIndex |
java | apache__logging-log4j2 | log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4CappedIntIT.java | {
"start": 1240,
"end": 1442
} | class ____ extends AbstractMongoDb4CappedIT {
@Test
@Override
protected void test(LoggerContext ctx, MongoClient mongoClient) {
super.test(ctx, mongoClient);
}
}
| MongoDb4CappedIntIT |
java | apache__dubbo | dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/zipkin/ZipkinConfigurations.java | {
"start": 5723,
"end": 6451
} | class ____ {
@Bean
@ConditionalOnMissingBean(Sender.class)
ZipkinWebClientSender webClientSender(
DubboConfigurationProperties properties, ObjectProvider<ZipkinWebClientBuilderCustomizer> customizers) {
ExporterConfig.ZipkinConfig zipkinConfig =
properties.getTracing().getTracingExporter().getZipkinConfig();
WebClient.Builder builder = WebClient.builder();
customizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return new ZipkinWebClientSender(zipkinConfig.getEndpoint(), builder.build());
}
}
@Configuration(proxyBeanMethods = false)
static | WebClientSenderConfiguration |
java | spring-projects__spring-security | messaging/src/main/java/org/springframework/security/messaging/access/intercept/MessageAuthorizationContext.java | {
"start": 949,
"end": 2100
} | class ____<T> {
private final Message<T> message;
private final Map<String, String> variables;
/**
* Creates an instance.
* @param message the {@link HttpServletRequest} to use
*/
public MessageAuthorizationContext(Message<T> message) {
this(message, Collections.emptyMap());
}
/**
* Creates an instance.
* @param message the {@link HttpServletRequest} to use
* @param variables a map containing key-value pairs representing extracted variable
* names and variable values
*/
public MessageAuthorizationContext(Message<T> message, Map<String, String> variables) {
this.message = message;
this.variables = variables;
}
/**
* Returns the {@link HttpServletRequest}.
* @return the {@link HttpServletRequest} to use
*/
public Message<T> getMessage() {
return this.message;
}
/**
* Returns the extracted variable values where the key is the variable name and the
* value is the variable value.
* @return a map containing key-value pairs representing extracted variable names and
* variable values
*/
public Map<String, String> getVariables() {
return this.variables;
}
}
| MessageAuthorizationContext |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/web/context/reactive/GenericReactiveWebApplicationContext.java | {
"start": 1111,
"end": 2095
} | class ____ extends GenericApplicationContext
implements ConfigurableReactiveWebApplicationContext {
/**
* Create a new {@link GenericReactiveWebApplicationContext}.
* @see #registerBeanDefinition
* @see #refresh
*/
public GenericReactiveWebApplicationContext() {
}
/**
* Create a new {@link GenericReactiveWebApplicationContext} with the given
* DefaultListableBeanFactory.
* @param beanFactory the DefaultListableBeanFactory instance to use for this context
* @see #registerBeanDefinition
* @see #refresh
*/
public GenericReactiveWebApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
}
@Override
protected ConfigurableEnvironment createEnvironment() {
return new StandardReactiveWebEnvironment();
}
@Override
protected Resource getResourceByPath(String path) {
// We must be careful not to expose classpath resources
return new FilteredReactiveWebContextResource(path);
}
}
| GenericReactiveWebApplicationContext |
java | google__dagger | javatests/dagger/internal/codegen/MissingBindingValidationTest.java | {
"start": 42524,
"end": 44311
} | interface ____ {",
" String string1();",
" String string2();",
" String string3();",
" String string4();",
" String string5();",
" String string6();",
" String string7();",
" String string8();",
" String string9();",
" String string10();",
" String string11();",
" String string12();",
"}");
CompilerTests.daggerCompiler(component)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
String.join(
"\n",
"String cannot be provided without an @Inject constructor or an "
+ "@Provides-annotated method.",
"",
" String is requested at",
" [TestComponent] TestComponent.string1()",
"The following other entry points also depend on it:",
" TestComponent.string2()",
" TestComponent.string3()",
" TestComponent.string4()",
" TestComponent.string5()",
" TestComponent.string6()",
" TestComponent.string7()",
" TestComponent.string8()",
" TestComponent.string9()",
" TestComponent.string10()",
" TestComponent.string11()",
" and 1 other"))
.onSource(component)
.onLineContaining(" | TestComponent |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSDirRenameOp.java | {
"start": 24503,
"end": 36062
} | class ____ {
private final FSDirectory fsd;
private INodesInPath srcIIP;
private final INodesInPath srcParentIIP;
private INodesInPath dstIIP;
private final INodesInPath dstParentIIP;
private final INodeReference.WithCount withCount;
private final int srcRefDstSnapshot;
private final INodeDirectory srcParent;
private final byte[] srcChildName;
private final boolean isSrcInSnapshot;
private final boolean srcChildIsReference;
private final QuotaCounts oldSrcCountsInSnapshot;
private final boolean sameStoragePolicy;
private final Optional<QuotaCounts> srcSubTreeCount;
private final Optional<QuotaCounts> dstSubTreeCount;
private INode srcChild;
private INode oldDstChild;
RenameOperation(FSDirectory fsd, INodesInPath srcIIP, INodesInPath dstIIP,
Pair<Optional<QuotaCounts>, Optional<QuotaCounts>> quotaPair) {
this.fsd = fsd;
this.srcIIP = srcIIP;
this.dstIIP = dstIIP;
this.srcParentIIP = srcIIP.getParentINodesInPath();
this.dstParentIIP = dstIIP.getParentINodesInPath();
this.sameStoragePolicy = isSameStoragePolicy();
BlockStoragePolicySuite bsps = fsd.getBlockStoragePolicySuite();
srcChild = this.srcIIP.getLastINode();
srcChildName = srcChild.getLocalNameBytes();
final int srcLatestSnapshotId = srcIIP.getLatestSnapshotId();
isSrcInSnapshot = srcChild.isInLatestSnapshot(srcLatestSnapshotId);
srcChildIsReference = srcChild.isReference();
srcParent = this.srcIIP.getINode(-2).asDirectory();
// Record the snapshot on srcChild. After the rename, before any new
// snapshot is taken on the dst tree, changes will be recorded in the
// latest snapshot of the src tree.
if (isSrcInSnapshot) {
if (srcChild.isFile()) {
INodeFile file = srcChild.asFile();
file.recordModification(srcLatestSnapshotId, true);
} else {
srcChild.recordModification(srcLatestSnapshotId);
}
}
// check srcChild for reference
srcRefDstSnapshot = srcChildIsReference ?
srcChild.asReference().getDstSnapshotId() : Snapshot.CURRENT_STATE_ID;
oldSrcCountsInSnapshot = new QuotaCounts.Builder().build();
if (isSrcInSnapshot) {
final INodeReference.WithName withName = srcParent
.replaceChild4ReferenceWithName(srcChild, srcLatestSnapshotId);
withCount = (INodeReference.WithCount) withName.getReferredINode();
srcChild = withName;
this.srcIIP = INodesInPath.replace(srcIIP, srcIIP.length() - 1,
srcChild);
// get the counts before rename
oldSrcCountsInSnapshot.add(withCount.getReferredINode().computeQuotaUsage(bsps));
} else if (srcChildIsReference) {
// srcChild is reference but srcChild is not in latest snapshot
withCount = (INodeReference.WithCount) srcChild.asReference()
.getReferredINode();
} else {
withCount = null;
}
// Set quota for src and dst, ignore src is in Snapshot or is Reference
this.srcSubTreeCount = withCount == null ?
quotaPair.getLeft() : Optional.empty();
this.dstSubTreeCount = quotaPair.getRight();
}
boolean isSameStoragePolicy() {
final INode src = srcIIP.getLastINode();
final INode dst = dstIIP.getLastINode();
// If the source INode has a storagePolicyID, we should use
// its storagePolicyId to update dst`s quota usage.
if (src.isSetStoragePolicy()) {
return true;
}
final byte srcSp;
final byte dstSp;
if (dst == null) {
dstSp = dstIIP.getINode(-2).getStoragePolicyID();
} else if (dst.isSymlink()) {
dstSp = HdfsConstants.BLOCK_STORAGE_POLICY_ID_UNSPECIFIED;
} else {
dstSp = dst.getStoragePolicyID();
}
if (src.isSymlink()) {
srcSp = HdfsConstants.BLOCK_STORAGE_POLICY_ID_UNSPECIFIED;
} else {
// Update src should use src·s storage policyID
srcSp = src.getStoragePolicyID();
}
return srcSp == dstSp;
}
long removeSrc() throws IOException {
long removedNum = fsd.removeLastINode(srcIIP);
if (removedNum == -1) {
String error = "Failed to rename " + srcIIP.getPath() + " to " +
dstIIP.getPath() + " because the source can not be removed";
NameNode.stateChangeLog.warn("DIR* FSDirRenameOp.unprotectedRenameTo:" +
error);
throw new IOException(error);
} else {
// update the quota count if necessary
Optional<QuotaCounts> countOp = sameStoragePolicy ?
srcSubTreeCount : Optional.empty();
fsd.updateCountForDelete(srcChild, srcIIP, countOp);
srcIIP = INodesInPath.replace(srcIIP, srcIIP.length() - 1, null);
return removedNum;
}
}
boolean removeSrc4OldRename() {
final long removedSrc = fsd.removeLastINode(srcIIP);
if (removedSrc == -1) {
NameNode.stateChangeLog.warn("DIR* FSDirRenameOp.unprotectedRenameTo: "
+ "failed to rename " + srcIIP.getPath() + " to "
+ dstIIP.getPath() + " because the source can not be removed");
return false;
} else {
// update the quota count if necessary
Optional<QuotaCounts> countOp = sameStoragePolicy ?
srcSubTreeCount : Optional.empty();
fsd.updateCountForDelete(srcChild, srcIIP, countOp);
srcIIP = INodesInPath.replace(srcIIP, srcIIP.length() - 1, null);
return true;
}
}
long removeDst() {
long removedNum = fsd.removeLastINode(dstIIP);
if (removedNum != -1) {
oldDstChild = dstIIP.getLastINode();
// update the quota count if necessary
fsd.updateCountForDelete(oldDstChild, dstIIP, dstSubTreeCount);
dstIIP = INodesInPath.replace(dstIIP, dstIIP.length() - 1, null);
}
return removedNum;
}
INodesInPath addSourceToDestination() {
final INode dstParent = dstParentIIP.getLastINode();
final byte[] dstChildName = dstIIP.getLastLocalName();
final INode toDst;
if (withCount == null) {
srcChild.setLocalName(dstChildName);
toDst = srcChild;
} else {
withCount.getReferredINode().setLocalName(dstChildName);
toDst = new INodeReference.DstReference(dstParent.asDirectory(),
withCount, dstIIP.getLatestSnapshotId());
}
return fsd.addLastINodeNoQuotaCheck(dstParentIIP, toDst, srcSubTreeCount);
}
void updateMtimeAndLease(long timestamp) {
srcParent.updateModificationTime(timestamp, srcIIP.getLatestSnapshotId());
final INode dstParent = dstParentIIP.getLastINode();
dstParent.updateModificationTime(timestamp, dstIIP.getLatestSnapshotId());
}
void restoreSource() {
// Rename failed - restore src
final INode oldSrcChild = srcChild;
// put it back
if (withCount == null) {
srcChild.setLocalName(srcChildName);
} else if (!srcChildIsReference) { // src must be in snapshot
// the withCount node will no longer be used thus no need to update
// its reference number here
srcChild = withCount.getReferredINode();
srcChild.setLocalName(srcChildName);
} else {
withCount.removeReference(oldSrcChild.asReference());
srcChild = new INodeReference.DstReference(srcParent, withCount,
srcRefDstSnapshot);
withCount.getReferredINode().setLocalName(srcChildName);
}
if (isSrcInSnapshot) {
srcParent.undoRename4ScrParent(oldSrcChild.asReference(), srcChild);
} else {
// srcParent is not an INodeDirectoryWithSnapshot, we only need to add
// the srcChild back
Optional<QuotaCounts> countOp = sameStoragePolicy ?
srcSubTreeCount : Optional.empty();
fsd.addLastINodeNoQuotaCheck(srcParentIIP, srcChild, countOp);
}
}
void restoreDst(BlockStoragePolicySuite bsps) {
Preconditions.checkState(oldDstChild != null);
final INodeDirectory dstParent = dstParentIIP.getLastINode().asDirectory();
if (dstParent.isWithSnapshot()) {
dstParent.undoRename4DstParent(bsps, oldDstChild, dstIIP.getLatestSnapshotId());
} else {
fsd.addLastINodeNoQuotaCheck(dstParentIIP, oldDstChild, dstSubTreeCount);
}
if (oldDstChild != null && oldDstChild.isReference()) {
final INodeReference removedDstRef = oldDstChild.asReference();
final INodeReference.WithCount wc = (INodeReference.WithCount)
removedDstRef.getReferredINode().asReference();
wc.addReference(removedDstRef);
}
}
boolean cleanDst(
BlockStoragePolicySuite bsps, BlocksMapUpdateInfo collectedBlocks) {
Preconditions.checkState(oldDstChild != null);
List<INode> removedINodes = new ChunkedArrayList<>();
List<Long> removedUCFiles = new ChunkedArrayList<>();
INode.ReclaimContext context = new INode.ReclaimContext(
bsps, collectedBlocks, removedINodes, removedUCFiles);
final boolean filesDeleted;
if (!oldDstChild.isInLatestSnapshot(dstIIP.getLatestSnapshotId())) {
oldDstChild.destroyAndCollectBlocks(context);
filesDeleted = true;
} else {
oldDstChild.cleanSubtree(context, Snapshot.CURRENT_STATE_ID,
dstIIP.getLatestSnapshotId());
filesDeleted = context.quotaDelta().getNsDelta() >= 0;
}
fsd.updateReplicationFactor(context.collectedBlocks()
.toUpdateReplicationInfo());
fsd.getFSNamesystem().removeLeasesAndINodes(
removedUCFiles, removedINodes, false);
return filesDeleted;
}
void updateQuotasInSourceTree(BlockStoragePolicySuite bsps) {
// update the quota usage in src tree
if (isSrcInSnapshot) {
// get the counts after rename
QuotaCounts newSrcCounts = srcChild.computeQuotaUsage(bsps, false);
newSrcCounts.subtract(oldSrcCountsInSnapshot);
srcParent.addSpaceConsumed(newSrcCounts);
}
}
}
private static void checkUnderSameSnapshottableRoot(
FSDirectory fsd, INodesInPath srcIIP, INodesInPath dstIIP)
throws IOException {
// Ensure rename out of a snapshottable root is not permitted if ordered
// snapshot deletion feature is enabled
SnapshotManager snapshotManager = fsd.getFSNamesystem().
getSnapshotManager();
if (snapshotManager.isSnapshotDeletionOrdered() && fsd.getFSNamesystem()
.isSnapshotTrashRootEnabled()) {
INodeDirectory srcRoot = snapshotManager.
getSnapshottableAncestorDir(srcIIP);
INodeDirectory dstRoot = snapshotManager.
getSnapshottableAncestorDir(dstIIP);
// Ensure snapshoottable root for both src and dest are same.
if (srcRoot != dstRoot) {
String errMsg = "Source " + srcIIP.getPath() +
" and dest " + dstIIP.getPath() + " are not under " +
"the same snapshot root.";
throw new SnapshotException(errMsg);
}
}
}
private static RenameResult createRenameResult(FSDirectory fsd,
INodesInPath dst, boolean filesDeleted,
BlocksMapUpdateInfo collectedBlocks) throws IOException {
boolean success = (dst != null);
FileStatus auditStat = success ? fsd.getAuditFileInfo(dst) : null;
return new RenameResult(
success, auditStat, filesDeleted, collectedBlocks);
}
static | RenameOperation |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/hql/MetamodelBoundedCacheTest.java | {
"start": 2061,
"end": 2406
} | class ____ {
@Id
private long id;
private String name;
public Employee() {
}
public Employee(long id, String strName) {
this();
this.name = strName;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String strName) {
this.name = strName;
}
}
}
| Employee |
java | grpc__grpc-java | s2a/src/main/java/io/grpc/s2a/internal/channel/S2AHandshakerServiceChannel.java | {
"start": 1903,
"end": 2903
} | class ____ {
/**
* Returns a {@link SharedResourceHolder.Resource} instance for managing channels to an S2A server
* running at {@code s2aAddress}.
*
* @param s2aAddress the address of the S2A, typically in the format {@code host:port}.
* @param s2aChannelCredentials the credentials to use when establishing a connection to the S2A.
* @return a {@link ChannelResource} instance that manages a {@link Channel} to the S2A server
* running at {@code s2aAddress}.
*/
public static Resource<Channel> getChannelResource(
String s2aAddress, ChannelCredentials s2aChannelCredentials) {
checkNotNull(s2aAddress);
return new ChannelResource(s2aAddress, s2aChannelCredentials);
}
/**
* Defines how to create and destroy a {@link Channel} instance that uses shared resources. A
* channel created by {@code ChannelResource} is a plaintext, local channel to the service running
* at {@code targetAddress}.
*/
private static | S2AHandshakerServiceChannel |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/InfrastructureProxy.java | {
"start": 1509,
"end": 1640
} | interface ____ {
/**
* Return the underlying resource (never {@code null}).
*/
Object getWrappedObject();
}
| InfrastructureProxy |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/IgniteSetComponentBuilderFactory.java | {
"start": 1376,
"end": 1853
} | interface ____ {
/**
* Ignite Sets (camel-ignite)
* Interact with Ignite Set data structures.
*
* Category: cache,clustering
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-ignite
*
* @return the dsl builder
*/
static IgniteSetComponentBuilder igniteSet() {
return new IgniteSetComponentBuilderImpl();
}
/**
* Builder for the Ignite Sets component.
*/
| IgniteSetComponentBuilderFactory |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/short_/ShortAssert_isCloseToPercentage_Short_Test.java | {
"start": 893,
"end": 1370
} | class ____ extends ShortAssertBaseTest {
private final Percentage percentage = withPercentage((short) 5);
private final Short value = (short) 10;
@Override
protected ShortAssert invoke_api_method() {
return assertions.isCloseTo(value, percentage);
}
@Override
protected void verify_internal_effects() {
verify(shorts).assertIsCloseToPercentage(getInfo(assertions), getActual(assertions), value, percentage);
}
}
| ShortAssert_isCloseToPercentage_Short_Test |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/AggregatorState.java | {
"start": 454,
"end": 659
} | interface ____ extends Releasable {
/** Extracts an intermediate view of the contents of this state. */
void toIntermediate(Block[] blocks, int offset, DriverContext driverContext);
}
| AggregatorState |
java | quarkusio__quarkus | extensions/oidc/runtime/src/test/java/io/quarkus/oidc/runtime/TokenIntrospectionCacheTest.java | {
"start": 491,
"end": 2696
} | class ____ {
TokenIntrospectionCache cache = new DefaultTokenIntrospectionUserInfoCache(createOidcConfig(), null);
@Test
public void testExpiredIntrospection() {
TokenIntrospection introspectionValidFor10secs = new TokenIntrospection(
"{\"active\": true,"
+ "\"exp\":" + (System.currentTimeMillis() / 1000 + 10) + "}");
TokenIntrospection introspectionValidFor3secs = new TokenIntrospection(
"{\"active\": true,"
+ "\"exp\":" + (System.currentTimeMillis() / 1000 + 3) + "}");
cache.addIntrospection("tokenValidFor10secs", introspectionValidFor10secs, null, null);
cache.addIntrospection("tokenValidFor3secs", introspectionValidFor3secs, null, null);
assertNotNull(cache.getIntrospection("tokenValidFor10secs", null, null).await().indefinitely());
assertNotNull(cache.getIntrospection("tokenValidFor3secs", null, null).await().indefinitely());
await().atMost(Duration.ofSeconds(5)).pollInterval(1, TimeUnit.SECONDS)
.until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return cache.getIntrospection("tokenValidFor3secs", null, null).await().indefinitely() == null;
}
});
assertNotNull(cache.getIntrospection("tokenValidFor10secs", null, null).await().indefinitely());
assertNull(cache.getIntrospection("tokenValidFor3secs", null, null).await().indefinitely());
}
private static OidcConfig createOidcConfig() {
record OidcConfigImpl(OidcTenantConfig defaultTenant, Map<String, OidcTenantConfig> namedTenants, TokenCache tokenCache,
boolean resolveTenantsWithIssuer) implements OidcConfig {
}
record TokenCacheImpl(int maxSize, Duration timeToLive,
Optional<Duration> cleanUpTimerInterval) implements OidcConfig.TokenCache {
}
var tokenCache = new TokenCacheImpl(2, Duration.ofMinutes(3), Optional.empty());
return new OidcConfigImpl(null, Map.of(), tokenCache, false);
}
}
| TokenIntrospectionCacheTest |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/beans/SyntheticInjectionPointInstanceTest.java | {
"start": 2510,
"end": 2869
} | class ____ implements BeanCreator<List<String>> {
@SuppressWarnings("serial")
@Override
public List<String> create(SyntheticCreationalContext<List<String>> context) {
return List.of(context.getInjectedReference(new TypeLiteral<Instance<SomethingRemovable>>() {
}).get().toString());
}
}
}
| ListCreator |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/SQLRowDataType.java | {
"start": 331,
"end": 2628
} | class ____ extends SQLObjectImpl implements SQLDataType {
private DbType dbType;
private List<Field> fields = new ArrayList<Field>();
public SQLRowDataType() {
}
public SQLRowDataType(DbType dbType) {
this.dbType = dbType;
}
@Override
public String getName() {
return "ROW";
}
@Override
public long nameHashCode64() {
return FnvHash.Constants.ROW;
}
@Override
public void setName(String name) {
throw new UnsupportedOperationException();
}
@Override
public List<SQLExpr> getArguments() {
return Collections.emptyList();
}
@Override
public Boolean getWithTimeZone() {
return null;
}
@Override
public void setWithTimeZone(Boolean value) {
throw new UnsupportedOperationException();
}
@Override
public boolean isWithLocalTimeZone() {
return false;
}
@Override
public void setWithLocalTimeZone(boolean value) {
throw new UnsupportedOperationException();
}
@Override
public void setDbType(DbType dbType) {
this.dbType = dbType;
}
@Override
public DbType getDbType() {
return dbType;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, fields);
}
visitor.endVisit(this);
}
public SQLRowDataType clone() {
SQLRowDataType x = new SQLRowDataType(dbType);
for (Field field : fields) {
x.addField(field.getName(), field.getDataType().clone());
}
return x;
}
public List<Field> getFields() {
return fields;
}
public Field addField(SQLName name, SQLDataType dataType) {
Field field = new Field(name, dataType);
field.setParent(this);
fields.add(field);
return field;
}
public int jdbcType() {
return Types.STRUCT;
}
@Override
public boolean isInt() {
return false;
}
@Override
public boolean isNumberic() {
return false;
}
@Override
public boolean isString() {
return false;
}
@Override
public boolean hasKeyLength() {
return false;
}
}
| SQLRowDataType |
java | apache__logging-log4j2 | log4j-api-test/src/test/java/org/apache/logging/log4j/spi/LoggerAdapterTest.java | {
"start": 2844,
"end": 3174
} | class ____ extends AbstractLoggerAdapter<Logger> {
@Override
protected LoggerContext getContext() {
return null;
}
@Override
protected Logger newLogger(final String name, final LoggerContext context) {
return null;
}
}
private static | TestLoggerAdapter |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/ResponseEntity.java | {
"start": 16406,
"end": 17298
} | interface ____ extends HeadersBuilder<BodyBuilder> {
/**
* Set the length of the body in bytes, as specified by the
* {@code Content-Length} header.
* @param contentLength the content length
* @return this builder
* @see HttpHeaders#setContentLength(long)
*/
BodyBuilder contentLength(long contentLength);
/**
* Set the {@linkplain MediaType media type} of the body, as specified by the
* {@code Content-Type} header.
* @param contentType the content type
* @return this builder
* @see HttpHeaders#setContentType(MediaType)
*/
BodyBuilder contentType(MediaType contentType);
/**
* Set the body of the response entity and returns it.
* @param <T> the type of the body
* @param body the body of the response entity
* @return the built response entity
*/
<T> ResponseEntity<T> body(@Nullable T body);
}
private static | BodyBuilder |
java | quarkusio__quarkus | test-framework/junit5-internal/src/test/java/io/quarkus/test/QuarkusProdModeTestExpectExitTest.java | {
"start": 2469,
"end": 2627
} | class ____ {
public static void main(String[] args) {
System.out.printf("current nano time: %s%n", System.nanoTime());
}
}
}
| Main |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/defaultvalue/CountryMapper.java | {
"start": 382,
"end": 1939
} | class ____ {
public static final CountryMapper INSTANCE = Mappers.getMapper( CountryMapper.class );
@Mappings( {
@Mapping( target = "code", defaultValue = "DE" ),
@Mapping( target = "id", defaultValue = "42" ),
@Mapping( target = "zipcode", defaultValue = "1337" ),
@Mapping( target = "region", defaultValue = "someRegion" ),
@Mapping( target = "continent", defaultValue = "EUROPE" )
} )
public abstract CountryDts mapToCountryDts(CountryEntity country);
@Mappings( {
@Mapping( target = "code", defaultValue = "DE" ),
@Mapping( target = "id", defaultValue = "42" ),
@Mapping( target = "zipcode", defaultValue = "1337" ),
@Mapping( target = "region", ignore = true ),
@Mapping( target = "continent", defaultValue = "EUROPE" )
} )
public abstract void mapToCountryEntity(CountryDts countryDts, @MappingTarget CountryEntity country);
@Mappings( {
@Mapping( target = "code", defaultValue = "DE" ),
@Mapping( target = "id", defaultValue = "42" ),
@Mapping( target = "zipcode", defaultValue = "1337" ),
@Mapping( target = "region", ignore = true ),
@Mapping( target = "continent", defaultValue = "EUROPE" )
} )
public abstract void mapToCountryEntity(CountryEntity source, @MappingTarget CountryEntity target);
protected String mapToString(Region region) {
return ( region != null ) ? region.getCode() : null;
}
}
| CountryMapper |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/ClassUtils.java | {
"start": 73200,
"end": 73527
} | class ____ be used as
* {@code ClassUtils.getShortClassName(cls)}.
*
* <p>
* This constructor is public to permit tools that require a JavaBean instance to operate.
* </p>
*
* @deprecated TODO Make private in 4.0.
*/
@Deprecated
public ClassUtils() {
// empty
}
}
| should |
java | apache__kafka | trogdor/src/main/java/org/apache/kafka/trogdor/workload/SustainedConnectionWorker.java | {
"start": 19404,
"end": 23372
} | class ____ {
private final long totalProducerConnections;
private final long totalProducerFailedConnections;
private final long totalConsumerConnections;
private final long totalConsumerFailedConnections;
private final long totalMetadataConnections;
private final long totalMetadataFailedConnections;
private final long totalAbortedThreads;
private final long updatedMs;
@JsonCreator
StatusData(@JsonProperty("totalProducerConnections") long totalProducerConnections,
@JsonProperty("totalProducerFailedConnections") long totalProducerFailedConnections,
@JsonProperty("totalConsumerConnections") long totalConsumerConnections,
@JsonProperty("totalConsumerFailedConnections") long totalConsumerFailedConnections,
@JsonProperty("totalMetadataConnections") long totalMetadataConnections,
@JsonProperty("totalMetadataFailedConnections") long totalMetadataFailedConnections,
@JsonProperty("totalAbortedThreads") long totalAbortedThreads,
@JsonProperty("updatedMs") long updatedMs) {
this.totalProducerConnections = totalProducerConnections;
this.totalProducerFailedConnections = totalProducerFailedConnections;
this.totalConsumerConnections = totalConsumerConnections;
this.totalConsumerFailedConnections = totalConsumerFailedConnections;
this.totalMetadataConnections = totalMetadataConnections;
this.totalMetadataFailedConnections = totalMetadataFailedConnections;
this.totalAbortedThreads = totalAbortedThreads;
this.updatedMs = updatedMs;
}
@JsonProperty
public long totalProducerConnections() {
return totalProducerConnections;
}
@JsonProperty
public long totalProducerFailedConnections() {
return totalProducerFailedConnections;
}
@JsonProperty
public long totalConsumerConnections() {
return totalConsumerConnections;
}
@JsonProperty
public long totalConsumerFailedConnections() {
return totalConsumerFailedConnections;
}
@JsonProperty
public long totalMetadataConnections() {
return totalMetadataConnections;
}
@JsonProperty
public long totalMetadataFailedConnections() {
return totalMetadataFailedConnections;
}
@JsonProperty
public long totalAbortedThreads() {
return totalAbortedThreads;
}
@JsonProperty
public long updatedMs() {
return updatedMs;
}
}
@Override
public void stop(Platform platform) throws Exception {
if (!running.compareAndSet(true, false)) {
throw new IllegalStateException("SustainedConnectionWorker is not running.");
}
log.info("{}: Deactivating SustainedConnectionWorker.", this.id);
// Shut down the periodic status updater and perform a final update on the
// statistics. We want to do this first, before deactivating any threads.
// Otherwise, if some threads take a while to terminate, this could lead
// to a misleading rate getting reported.
this.statusUpdaterFuture.cancel(false);
this.statusUpdaterExecutor.shutdown();
this.statusUpdaterExecutor.awaitTermination(1, TimeUnit.HOURS);
this.statusUpdaterExecutor = null;
new StatusUpdater().run();
doneFuture.complete("");
for (SustainedConnection connection : this.connections) {
connection.close();
}
workerExecutor.shutdownNow();
workerExecutor.awaitTermination(1, TimeUnit.HOURS);
this.workerExecutor = null;
this.status = null;
this.connections = null;
}
}
| StatusData |
java | apache__camel | components/camel-zookeeper-master/src/main/java/org/apache/camel/component/zookeepermaster/group/internal/GetDataOperation.java | {
"start": 939,
"end": 1910
} | class ____<T extends NodeState> implements Operation {
private final ZooKeeperGroup<T> cache;
private final String fullPath;
GetDataOperation(ZooKeeperGroup<T> cache, String fullPath) {
this.cache = cache;
this.fullPath = fullPath;
}
@Override
public void invoke() throws Exception {
cache.getDataAndStat(fullPath);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetDataOperation<T> that = (GetDataOperation<T>) o;
if (!fullPath.equals(that.fullPath)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return fullPath.hashCode();
}
@Override
public String toString() {
return "GetDataOperation{fullPath='" + fullPath + '\'' + '}';
}
}
| GetDataOperation |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Ddb2EndpointBuilderFactory.java | {
"start": 26295,
"end": 41255
} | class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final Ddb2HeaderNameBuilder INSTANCE = new Ddb2HeaderNameBuilder();
/**
* The list of attributes returned by the operation.
*
* The option is a: {@code Map<String, AttributeValue>} type.
*
* Group: DeleteItem GetItem PutItem UpdateItem
*
* @return the name of the header {@code AwsDdbAttributes}.
*/
public String awsDdbAttributes() {
return "CamelAwsDdbAttributes";
}
/**
* If attribute names are not specified then all attributes will be
* returned.
*
* The option is a: {@code Collection<String>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbAttributeNames}.
*/
public String awsDdbAttributeNames() {
return "CamelAwsDdbAttributeNames";
}
/**
* A map of the table name and corresponding items to get by primary
* key.
*
* The option is a: {@code Map<String, KeysAndAttributes>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbBatchItems}.
*/
public String awsDdbBatchItems() {
return "CamelAwsDdbBatchItems";
}
/**
* Table names and the respective item attributes from the tables.
*
* The option is a: {@code Map<String, BatchResponse>} type.
*
* Group: BatchGetItems
*
* @return the name of the header {@code AwsDdbBatchResponse}.
*/
public String awsDdbBatchResponse() {
return "CamelAwsDdbBatchResponse";
}
/**
* If set to true, then a consistent read is issued, otherwise
* eventually consistent is used.
*
* The option is a: {@code Boolean} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbConsistentRead}.
*/
public String awsDdbConsistentRead() {
return "CamelAwsDdbConsistentRead";
}
/**
* The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation.
*
* The option is a: {@code Double} type.
*
* Group: Query Scan
*
* @return the name of the header {@code AwsDdbConsumedCapacity}.
*/
public String awsDdbConsumedCapacity() {
return "CamelAwsDdbConsumedCapacity";
}
/**
* Number of items in the response.
*
* The option is a: {@code Integer} type.
*
* Group: Query Scan
*
* @return the name of the header {@code AwsDdbCount}.
*/
public String awsDdbCount() {
return "CamelAwsDdbCount";
}
/**
* Creation DateTime of this table.
*
* The option is a: {@code Date} type.
*
* Group: DeleteTable DescribeTable
*
* @return the name of the header {@code AwsDdbCreationDate}.
*/
public String awsDdbCreationDate() {
return "CamelAwsDdbCreationDate";
}
/**
* If set will be used as Secondary Index for Query operation.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbIndexName}.
*/
public String awsDdbIndexName() {
return "CamelAwsDdbIndexName";
}
/**
* A map of the attributes for the item, and must include the primary
* key values that define the item.
*
* The option is a: {@code Map<String, AttributeValue>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbItem}.
*/
public String awsDdbItem() {
return "CamelAwsDdbItem";
}
/**
* The list of attributes returned by the operation.
*
* The option is a: {@code List<Map<String,AttributeValue>>} type.
*
* Group: Query Scan
*
* @return the name of the header {@code AwsDdbItems}.
*/
public String awsDdbItems() {
return "CamelAwsDdbItems";
}
/**
* Item count for this table.
*
* The option is a: {@code Long} type.
*
* Group: DeleteTable DescribeTable
*
* @return the name of the header {@code AwsDdbTableItemCount}.
*/
public String awsDdbTableItemCount() {
return "CamelAwsDdbTableItemCount";
}
/**
* The primary key that uniquely identifies each item in a table.
*
* The option is a: {@code Map<String, AttributeValue>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbKey}.
*/
public String awsDdbKey() {
return "CamelAwsDdbKey";
}
/**
* This header specify the selection criteria for the query, and merge
* together the two old headers CamelAwsDdbHashKeyValue and
* CamelAwsDdbScanRangeKeyCondition.
*
* The option is a: {@code Map<String, Condition>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbKeyConditions}.
*/
public String awsDdbKeyConditions() {
return "CamelAwsDdbKeyConditions";
}
/**
* The KeySchema that identifies the primary key for this table. From
* Camel 2.16.0 the type of this header is List and not KeySchema.
*
* The option is a: {@code List<KeySchemaElement>} type.
*
* Group: DeleteTable DescribeTable
*
* @return the name of the header {@code AwsDdbKeySchema}.
*/
public String awsDdbKeySchema() {
return "CamelAwsDdbKeySchema";
}
/**
* Primary key of the item where the query operation stopped, inclusive
* of the previous result set.
*
* The option is a: {@code Key} type.
*
* Group: Query Scan
*
* @return the name of the header {@code AwsDdbLastEvaluatedKey}.
*/
public String awsDdbLastEvaluatedKey() {
return "CamelAwsDdbLastEvaluatedKey";
}
/**
* The maximum number of items to return.
*
* The option is a: {@code Integer} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbLimit}.
*/
public String awsDdbLimit() {
return "CamelAwsDdbLimit";
}
/**
* The operation to perform.
*
* The option is a: {@code
* org.apache.camel.component.aws2.ddb.Ddb2Operations} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbOperation}.
*/
public String awsDdbOperation() {
return "CamelAwsDdbOperation";
}
/**
* The value of the ProvisionedThroughput property for this table.
*
* The option is a: {@code
* software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription} type.
*
* Group: DeleteTable DescribeTable
*
* @return the name of the header {@code AwsDdbProvisionedThroughput}.
*/
public String awsDdbProvisionedThroughput() {
return "CamelAwsDdbProvisionedThroughput";
}
/**
* ReadCapacityUnits property of this table.
*
* The option is a: {@code Long} type.
*
* Group: UpdateTable DescribeTable
*
* @return the name of the header {@code AwsDdbReadCapacity}.
*/
public String awsDdbReadCapacity() {
return "CamelAwsDdbReadCapacity";
}
/**
* Use this parameter if you want to get the attribute name-value pairs
* before or after they are modified(NONE, ALL_OLD, UPDATED_OLD,
* ALL_NEW, UPDATED_NEW).
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbReturnValues}.
*/
public String awsDdbReturnValues() {
return "CamelAwsDdbReturnValues";
}
/**
* Number of items in the complete scan before any filters are applied.
*
* The option is a: {@code Integer} type.
*
* Group: Scan
*
* @return the name of the header {@code AwsDdbScannedCount}.
*/
public String awsDdbScannedCount() {
return "CamelAwsDdbScannedCount";
}
/**
* Specifies forward or backward traversal of the index.
*
* The option is a: {@code Boolean} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbScanIndexForward}.
*/
public String awsDdbScanIndexForward() {
return "CamelAwsDdbScanIndexForward";
}
/**
* Evaluates the scan results and returns only the desired values.
*
* The option is a: {@code Map<String, Condition>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbScanFilter}.
*/
public String awsDdbScanFilter() {
return "CamelAwsDdbScanFilter";
}
/**
* Primary key of the item from which to continue an earlier query.
*
* The option is a: {@code Map<String, AttributeValue>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbStartKey}.
*/
public String awsDdbStartKey() {
return "CamelAwsDdbStartKey";
}
/**
* Table Name for this operation.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbTableName}.
*/
public String awsDdbTableName() {
return "CamelAwsDdbTableName";
}
/**
* The table size in bytes.
*
* The option is a: {@code Long} type.
*
* Group: DeleteTable DescribeTable
*
* @return the name of the header {@code AwsDdbTableSize}.
*/
public String awsDdbTableSize() {
return "CamelAwsDdbTableSize";
}
/**
* The status of the table: CREATING, UPDATING, DELETING, ACTIVE.
*
* The option is a: {@code String} type.
*
* Group: DeleteTable DescribeTable
*
* @return the name of the header {@code AwsDdbTableStatus}.
*/
public String awsDdbTableStatus() {
return "CamelAwsDdbTableStatus";
}
/**
* Designates an attribute for a conditional modification.
*
* The option is a: {@code Map<String, ExpectedAttributeValue>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbUpdateCondition}.
*/
public String awsDdbUpdateCondition() {
return "CamelAwsDdbUpdateCondition";
}
/**
* Map of attribute name to the new value and action for the update.
*
* The option is a: {@code Map<String, AttributeValueUpdate>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsDdbUpdateValues}.
*/
public String awsDdbUpdateValues() {
return "CamelAwsDdbUpdateValues";
}
/**
* Contains a map of tables and their respective keys that were not
* processed with the current response.
*
* The option is a: {@code Map<String,KeysAndAttributes>} type.
*
* Group: BatchGetItems
*
* @return the name of the header {@code AwsDdbUnprocessedKeys}.
*/
public String awsDdbUnprocessedKeys() {
return "CamelAwsDdbUnprocessedKeys";
}
/**
* WriteCapacityUnits property of this table.
*
* The option is a: {@code Long} type.
*
* Group: UpdateTable DescribeTable
*
* @return the name of the header {@code AwsDdbWriteCapacity}.
*/
public String awsDdbWriteCapacity() {
return "CamelAwsDdbWriteCapacity";
}
/**
* The Filter Expression.
*
* The option is a: {@code String} type.
*
* Group: Query Scan
*
* @return the name of the header {@code AwsDdbFilterExpression}.
*/
public String awsDdbFilterExpression() {
return "CamelAwsDdbFilterExpression";
}
/**
* The Filter Expression Attribute Names.
*
* The option is a: {@code Map<String, String>} type.
*
* Group: Query Scan
*
* @return the name of the header {@code
* AwsDdbFilterExpressionAttributeNames}.
*/
public String awsDdbFilterExpressionAttributeNames() {
return "CamelAwsDdbFilterExpressionAttributeNames";
}
/**
* The Filter Expression Attribute Values.
*
* The option is a: {@code Map<String, String>} type.
*
* Group: Query Scan
*
* @return the name of the header {@code
* AwsDdbFilterExpressionAttributeValues}.
*/
public String awsDdbFilterExpressionAttributeValues() {
return "CamelAwsDdbFilterExpressionAttributeValues";
}
/**
* The Project Expression.
*
* The option is a: {@code String} type.
*
* Group: Query Scan
*
* @return the name of the header {@code AwsDdbProjectExpression}.
*/
public String awsDdbProjectExpression() {
return "CamelAwsDdbProjectExpression";
}
}
static Ddb2EndpointBuilder endpointBuilder(String componentName, String path) {
| Ddb2HeaderNameBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/registry/classloading/spi/ClassLoadingException.java | {
"start": 283,
"end": 851
} | class ____ extends HibernateException {
/**
* Constructs a ClassLoadingException using the specified message and cause.
*
* @param message A message explaining the exception condition.
* @param cause The underlying cause
*/
public ClassLoadingException(String message, Throwable cause) {
super( message, cause );
}
/**
* Constructs a ClassLoadingException using the specified message.
*
* @param message A message explaining the exception condition.
*/
public ClassLoadingException(String message) {
super( message );
}
}
| ClassLoadingException |
java | apache__dubbo | dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java | {
"start": 1062,
"end": 1875
} | class ____ implements RestService {
@Override
public String param(String param) {
return null;
}
@Override
public String params(int a, String b) {
return null;
}
@Override
public String headers(String header, String header2, Integer param) {
return null;
}
@Override
public String pathVariables(String path1, String path2, String param) {
return null;
}
@Override
public String form(String form) {
return null;
}
@Override
public User requestBodyMap(Map<String, Object> data, String param) {
return null;
}
@Override
public Map<String, Object> requestBodyUser(User user) {
return null;
}
public User user(User user) {
return user;
}
}
| DefaultRestService |
java | apache__camel | components/camel-splunk/src/main/java/org/apache/camel/component/splunk/SplunkComponent.java | {
"start": 1149,
"end": 2177
} | class ____ extends HealthCheckComponent {
@Metadata(label = "advanced")
private SplunkConfigurationFactory splunkConfigurationFactory = new DefaultSplunkConfigurationFactory();
public SplunkComponent() {
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
SplunkConfiguration configuration = splunkConfigurationFactory.parseMap(parameters);
SplunkEndpoint answer = new SplunkEndpoint(uri, this, configuration);
setProperties(answer, parameters);
configuration.setName(remaining);
return answer;
}
public SplunkConfigurationFactory getSplunkConfigurationFactory() {
return splunkConfigurationFactory;
}
/**
* To use the {@link SplunkConfigurationFactory}
*/
public void setSplunkConfigurationFactory(SplunkConfigurationFactory splunkConfigurationFactory) {
this.splunkConfigurationFactory = splunkConfigurationFactory;
}
}
| SplunkComponent |
java | apache__camel | components/camel-jackson/src/main/java/org/apache/camel/component/jackson/AbstractJacksonDataFormat.java | {
"start": 27207,
"end": 28624
} | enum ____ types [SerializationFeature,DeserializationFeature,MapperFeature]");
}
}
private PropertyNamingStrategy determineNamingStrategy(String namingStrategy) {
PropertyNamingStrategy strategy = null;
switch (namingStrategy) {
case "LOWER_CAMEL_CASE":
strategy = PropertyNamingStrategies.LOWER_CAMEL_CASE;
break;
case "LOWER_DOT_CASE":
strategy = PropertyNamingStrategies.LOWER_DOT_CASE;
break;
case "LOWER_CASE":
strategy = PropertyNamingStrategies.LOWER_CASE;
break;
case "KEBAB_CASE":
strategy = PropertyNamingStrategies.KEBAB_CASE;
break;
case "SNAKE_CASE":
strategy = PropertyNamingStrategies.SNAKE_CASE;
break;
case "UPPER_CAMEL_CASE":
strategy = PropertyNamingStrategies.UPPER_CAMEL_CASE;
break;
default:
break;
}
return strategy;
}
@Override
protected void doStop() throws Exception {
// noop
}
public abstract String getDataFormatName();
protected abstract ObjectMapper createNewObjectMapper();
protected abstract Class<? extends ObjectMapper> getObjectMapperClass();
protected abstract String getDefaultContentType();
}
| of |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileAlreadyExistsException.java | {
"start": 1162,
"end": 1352
} | class ____
extends IOException {
public FileAlreadyExistsException() {
super();
}
public FileAlreadyExistsException(String msg) {
super(msg);
}
}
| FileAlreadyExistsException |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvMarshallTrimClipTest.java | {
"start": 1415,
"end": 2348
} | class ____ {
private static final String URI_MOCK_RESULT = "mock:result";
private static final String URI_DIRECT_START = "direct:start";
private String expected;
@Produce(URI_DIRECT_START)
private ProducerTemplate template;
@EndpointInject(URI_MOCK_RESULT)
private MockEndpoint result;
@Test
@DirtiesContext
public void testMarshallMessage() throws Exception {
expected = "Mr,John,Doeeeeeeee,Cityyyyyyy\r\n";
result.expectedBodiesReceived(expected);
template.sendBody(generateModel());
result.assertIsSatisfied();
}
public Object generateModel() {
Customer customer = new Customer();
customer.setSalutation("Mr");
customer.setFirstName(" John ");
customer.setLastName("Doeeeeeeeeeeeee");
customer.setCity("Cityyyyyyy ");
return customer;
}
public static | BindySimpleCsvMarshallTrimClipTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java | {
"start": 10149,
"end": 10367
} | class ____ extends Super {}
""")
.doTest();
}
@Test
public void extendsMutable() {
compilationHelper
.addSourceLines(
"Super.java",
"""
public | Test |
java | apache__camel | components/camel-scheduler/src/main/java/org/apache/camel/component/scheduler/SchedulerConstants.java | {
"start": 936,
"end": 1167
} | class ____ {
@Metadata(description = "The timestamp of the message", javaType = "long")
public static final String MESSAGE_TIMESTAMP = Exchange.MESSAGE_TIMESTAMP;
private SchedulerConstants() {
}
}
| SchedulerConstants |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/aot/hint/predicate/ProxyHintsPredicatesTests.java | {
"start": 2023,
"end": 2340
} | interface ____ {
}
private void assertPredicateMatches(Predicate<RuntimeHints> predicate) {
assertThat(predicate.test(this.runtimeHints)).isTrue();
}
private void assertPredicateDoesNotMatch(Predicate<RuntimeHints> predicate) {
assertThat(predicate.test(this.runtimeHints)).isFalse();
}
}
| SecondTestInterface |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2SelectTest_31.java | {
"start": 1100,
"end": 3313
} | class ____ extends DB2Test {
public void test_0() throws Exception {
String sql = "select rtrim(current_server), rtrim(current schema), rtrim(current_user) from sysibm.sysdummy1";
DB2StatementParser parser = new DB2StatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
assertEquals("SELECT rtrim(current_server), rtrim(CURRENT SCHEMA)\n" +
"\t, rtrim(current_user)\n" +
"FROM sysibm.sysdummy1", stmt.getSelect().toString());
assertEquals("sysibm.sysdummy1", stmt.getSelect().getQueryBlock().getFrom().toString());
assertEquals(1, statementList.size());
DB2SchemaStatVisitor visitor = new DB2SchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(2, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("sysibm.sysdummy1")));
// assertTrue(visitor.getColumns().contains(new Column("DSN8B10.EMP", "WORKDEPT")));
// assertTrue(visitor.getColumns().contains(new Column("mytable", "first_name")));
// assertTrue(visitor.getColumns().contains(new Column("mytable", "full_name")));
assertEquals("SELECT rtrim(current_server), rtrim(CURRENT SCHEMA)\n" +
"\t, rtrim(current_user)\n" +
"FROM sysibm.sysdummy1", //
SQLUtils.toSQLString(stmt, JdbcConstants.DB2));
assertEquals("select rtrim(current_server), rtrim(CURRENT SCHEMA)\n" +
"\t, rtrim(current_user)\n" +
"from sysibm.sysdummy1", //
SQLUtils.toSQLString(stmt, JdbcConstants.DB2, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION));
}
}
| DB2SelectTest_31 |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/accessibility/referenced/ReferencedTarget.java | {
"start": 245,
"end": 420
} | class ____ {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
| ReferencedTarget |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/expressions/converter/converters/JsonArrayConverter.java | {
"start": 1447,
"end": 2212
} | class ____ extends CustomizedConverter {
@Override
public RexNode convert(CallExpression call, CallExpressionConvertRule.ConvertContext context) {
checkArgument(call, call.getChildren().size() >= 1);
final List<RexNode> operands = new LinkedList<>();
final SqlJsonConstructorNullClause onNull = JsonConverterUtil.getOnNullArgument(call, 0);
operands.add(context.getRelBuilder().getRexBuilder().makeFlag(onNull));
for (int i = 1; i < call.getChildren().size(); i++) {
operands.add(context.toRexNode(call.getChildren().get(i)));
}
return context.getRelBuilder()
.getRexBuilder()
.makeCall(FlinkSqlOperatorTable.JSON_ARRAY, operands);
}
}
| JsonArrayConverter |
java | apache__kafka | storage/src/main/java/org/apache/kafka/storage/internals/log/ProducerAppendInfo.java | {
"start": 1701,
"end": 1986
} | class ____ used to validate the records appended by a given producer before they are written to the log.
* It is initialized with the producer's state after the last successful append, and transitively validates the
* sequence numbers and epochs of each new record. Additionally, this | is |
java | apache__flink | flink-core-api/src/main/java/org/apache/flink/api/common/state/StateDeclarations.java | {
"start": 5600,
"end": 6982
} | class ____<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final String name;
private final TypeDescriptor<T> typeInformation;
private final ReduceFunction<T> reduceFunction;
public ReducingStateDeclarationBuilder(
String name, TypeDescriptor<T> typeInformation, ReduceFunction<T> reduceFunction) {
this.name = name;
this.typeInformation = typeInformation;
this.reduceFunction = reduceFunction;
}
ReducingStateDeclaration<T> build() {
return new ReducingStateDeclaration<T>() {
@Override
public TypeDescriptor<T> getTypeDescriptor() {
return typeInformation;
}
@Override
public String getName() {
return name;
}
@Override
public ReduceFunction<T> getReduceFunction() {
return reduceFunction;
}
@Override
public RedistributionMode getRedistributionMode() {
return RedistributionMode.NONE;
}
};
}
}
/** Builder for {@link AggregatingStateDeclaration}. */
@Experimental
public static | ReducingStateDeclarationBuilder |
java | apache__camel | components/camel-bonita/src/test/java/org/apache/camel/component/bonita/api/BonitaAPITest.java | {
"start": 1179,
"end": 2314
} | class ____ {
@Test
public void testGetProcessDefinitionEmptyInput() {
BonitaAPI bonitaApi = BonitaAPIBuilder
.build(new BonitaAPIConfig("hostname", "port", "username", "password"));
assertThrows(IllegalArgumentException.class,
() -> bonitaApi.getProcessDefinition(""));
}
@Test
public void testStartCaseEmptyProcessDefinitionId() {
BonitaAPI bonitaApi = BonitaAPIBuilder
.build(new BonitaAPIConfig("hostname", "port", "username", "password"));
Map<String, Serializable> map = new HashMap<>();
assertThrows(IllegalArgumentException.class,
() -> bonitaApi.startCase(null, map));
}
@Test
public void testStartCaseNUllContractInput() {
BonitaAPI bonitaApi = BonitaAPIBuilder
.build(new BonitaAPIConfig("hostname", "port", "username", "password"));
ProcessDefinitionResponse processDefinition = new ProcessDefinitionResponse();
assertThrows(IllegalArgumentException.class,
() -> bonitaApi.startCase(processDefinition, null));
}
}
| BonitaAPITest |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/ml/JavaNormalizerExample.java | {
"start": 1401,
"end": 2630
} | class ____ {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("JavaNormalizerExample")
.getOrCreate();
// $example on$
List<Row> data = Arrays.asList(
RowFactory.create(0, Vectors.dense(1.0, 0.1, -8.0)),
RowFactory.create(1, Vectors.dense(2.0, 1.0, -4.0)),
RowFactory.create(2, Vectors.dense(4.0, 10.0, 8.0))
);
StructType schema = new StructType(new StructField[]{
new StructField("id", DataTypes.IntegerType, false, Metadata.empty()),
new StructField("features", new VectorUDT(), false, Metadata.empty())
});
Dataset<Row> dataFrame = spark.createDataFrame(data, schema);
// Normalize each Vector using $L^1$ norm.
Normalizer normalizer = new Normalizer()
.setInputCol("features")
.setOutputCol("normFeatures")
.setP(1.0);
Dataset<Row> l1NormData = normalizer.transform(dataFrame);
l1NormData.show();
// Normalize each Vector using $L^\infty$ norm.
Dataset<Row> lInfNormData =
normalizer.transform(dataFrame, normalizer.p().w(Double.POSITIVE_INFINITY));
lInfNormData.show();
// $example off$
spark.stop();
}
}
| JavaNormalizerExample |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/TestFileSystem.java | {
"start": 8586,
"end": 11291
} | class ____ extends Configured
implements Mapper<Text, LongWritable, Text, LongWritable> {
private Random random = new Random();
private byte[] buffer = new byte[BUFFER_SIZE];
private byte[] check = new byte[BUFFER_SIZE];
private FileSystem fs;
private boolean fastCheck;
{
try {
fs = FileSystem.get(conf);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public ReadMapper() { super(null); }
public ReadMapper(Configuration conf) { super(conf); }
public void configure(JobConf job) {
setConf(job);
fastCheck = job.getBoolean("fs.test.fastCheck", false);
}
public void map(Text key, LongWritable value,
OutputCollector<Text, LongWritable> collector,
Reporter reporter)
throws IOException {
String name = key.toString();
long size = value.get();
long seed = Long.parseLong(name);
random.setSeed(seed);
reporter.setStatus("opening " + name);
DataInputStream in =
new DataInputStream(fs.open(new Path(DATA_DIR, name)));
long read = 0;
try {
while (read < size) {
long remains = size - read;
int n = (remains<=buffer.length) ? (int)remains : buffer.length;
in.readFully(buffer, 0, n);
read += n;
if (fastCheck) {
Arrays.fill(check, (byte)random.nextInt(Byte.MAX_VALUE));
} else {
random.nextBytes(check);
}
if (n != buffer.length) {
Arrays.fill(buffer, n, buffer.length, (byte)0);
Arrays.fill(check, n, check.length, (byte)0);
}
assertTrue(Arrays.equals(buffer, check));
reporter.setStatus("reading "+name+"@"+read+"/"+size);
}
} finally {
in.close();
}
collector.collect(new Text("bytes"), new LongWritable(read));
reporter.setStatus("read " + name);
}
public void close() {
}
}
public static void readTest(FileSystem fs, boolean fastCheck)
throws Exception {
fs.delete(READ_DIR, true);
JobConf job = new JobConf(conf, TestFileSystem.class);
job.setBoolean("fs.test.fastCheck", fastCheck);
FileInputFormat.setInputPaths(job, CONTROL_DIR);
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(ReadMapper.class);
job.setReducerClass(LongSumReducer.class);
FileOutputFormat.setOutputPath(job, READ_DIR);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
job.setNumReduceTasks(1);
JobClient.runJob(job);
}
public static | ReadMapper |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractSingleCheckedElementTag.java | {
"start": 1123,
"end": 3021
} | class ____ extends AbstractCheckedElementTag {
/**
* The value of the '{@code value}' attribute.
*/
private @Nullable Object value;
/**
* The value of the '{@code label}' attribute.
*/
private @Nullable Object label;
/**
* Set the value of the '{@code value}' attribute.
* May be a runtime expression.
*/
public void setValue(Object value) {
this.value = value;
}
/**
* Get the value of the '{@code value}' attribute.
*/
protected @Nullable Object getValue() {
return this.value;
}
/**
* Set the value of the '{@code label}' attribute.
* May be a runtime expression.
*/
public void setLabel(Object label) {
this.label = label;
}
/**
* Get the value of the '{@code label}' attribute.
*/
protected @Nullable Object getLabel() {
return this.label;
}
/**
* Renders the '{@code input(radio)}' element with the configured
* {@link #setValue(Object) value}. Marks the element as checked if the
* value matches the {@link #getValue bound value}.
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
tagWriter.startTag("input");
String id = resolveId();
writeOptionalAttribute(tagWriter, "id", id);
writeOptionalAttribute(tagWriter, "name", getName());
writeOptionalAttributes(tagWriter);
writeTagDetails(tagWriter);
tagWriter.endTag();
Object resolvedLabel = evaluate("label", getLabel());
if (resolvedLabel != null) {
Assert.state(id != null, "Label id is required");
tagWriter.startTag("label");
tagWriter.writeAttribute("for", id);
tagWriter.appendValue(convertToDisplayString(resolvedLabel));
tagWriter.endTag();
}
return SKIP_BODY;
}
/**
* Write the details for the given primary tag:
* i.e. special attributes and the tag's value.
*/
protected abstract void writeTagDetails(TagWriter tagWriter) throws JspException;
}
| AbstractSingleCheckedElementTag |
java | apache__flink | flink-yarn/src/main/java/org/apache/flink/yarn/YarnWorkerNode.java | {
"start": 1154,
"end": 1700
} | class ____ implements ResourceIDRetrievable {
private final ResourceID resourceID;
private final Container container;
public YarnWorkerNode(Container container, ResourceID resourceID) {
Preconditions.checkNotNull(container);
Preconditions.checkNotNull(resourceID);
this.resourceID = resourceID;
this.container = container;
}
@Override
public ResourceID getResourceID() {
return resourceID;
}
public Container getContainer() {
return container;
}
}
| YarnWorkerNode |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java | {
"start": 1568,
"end": 3860
} | class ____ {
private static final String BASE_PACKAGE = FactoryMethodComponent.class.getPackage().getName();
@Test
void testSingletonScopedFactoryMethod() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
context.getBeanFactory().registerScope("request", new SimpleMapScope());
scanner.scan(BASE_PACKAGE);
context.registerBeanDefinition("clientBean", new RootBeanDefinition(QualifiedClientBean.class));
context.refresh();
FactoryMethodComponent fmc = context.getBean("factoryMethodComponent", FactoryMethodComponent.class);
assertThat(fmc.getClass().getName()).doesNotContain(ClassUtils.CGLIB_CLASS_SEPARATOR);
TestBean tb = (TestBean) context.getBean("publicInstance"); //2
assertThat(tb.getName()).isEqualTo("publicInstance");
TestBean tb2 = (TestBean) context.getBean("publicInstance"); //2
assertThat(tb2.getName()).isEqualTo("publicInstance");
assertThat(tb).isSameAs(tb2);
tb = (TestBean) context.getBean("protectedInstance"); //3
assertThat(tb.getName()).isEqualTo("protectedInstance");
assertThat(context.getBean("protectedInstance")).isSameAs(tb);
assertThat(tb.getCountry()).isEqualTo("0");
tb2 = context.getBean("protectedInstance", TestBean.class); //3
assertThat(tb2.getName()).isEqualTo("protectedInstance");
assertThat(tb).isSameAs(tb2);
tb = context.getBean("privateInstance", TestBean.class); //4
assertThat(tb.getName()).isEqualTo("privateInstance");
assertThat(tb.getAge()).isEqualTo(1);
tb2 = context.getBean("privateInstance", TestBean.class); //4
assertThat(tb2.getAge()).isEqualTo(2);
assertThat(tb).isNotSameAs(tb2);
Object bean = context.getBean("requestScopedInstance"); //5
assertThat(AopUtils.isCglibProxy(bean)).isTrue();
boolean condition = bean instanceof ScopedObject;
assertThat(condition).isTrue();
QualifiedClientBean clientBean = context.getBean("clientBean", QualifiedClientBean.class);
assertThat(clientBean.testBean).isSameAs(context.getBean("publicInstance"));
assertThat(clientBean.dependencyBean).isSameAs(context.getBean("dependencyBean"));
assertThat(clientBean.applicationContext).isSameAs(context);
}
public static | ClassPathFactoryBeanDefinitionScannerTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java | {
"start": 20327,
"end": 20538
} | interface ____ {}
}
}
""")
.addOutputLines(
"out/AddAnnotation.java",
"""
import some.pkg.SomeAnnotation;
| SomeAnnotation |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/condition/AllOf_toString_Test.java | {
"start": 3695,
"end": 3955
} | class ____<T> extends TestCondition<T> {
public DynamicCondition(String description) {
super(description);
}
@Override
public boolean matches(T value) {
describedAs("ChangedDescription");
return true;
}
}
}
| DynamicCondition |
java | quarkusio__quarkus | extensions/liquibase/liquibase-mongodb/deployment/src/main/java/io/quarkus/liquibase/mongodb/deployment/LiquibaseMongodbProcessor.java | {
"start": 10622,
"end": 20349
} | class ____ reflection while also registering fields for reflection
addService(services, reflective, liquibase.precondition.Precondition.class.getName(), true);
// CommandStep implementations are needed (just like in non-mongodb variant)
addService(services, reflective, liquibase.command.CommandStep.class.getName(), false,
"liquibase.command.core.StartH2CommandStep");
var dependencies = curateOutcome.getApplicationModel().getRuntimeDependencies();
resource.produce(NativeImageResourceBuildItem.ofDependencyResources(
dependencies, LIQUIBASE_ARTIFACT, LIQUIBASE_RESOURCE_FILTER));
resource.produce(NativeImageResourceBuildItem.ofDependencyResources(
dependencies, LIQUIBASE_MONGODB_ARTIFACT, LIQUIBASE_MONGODB_RESOURCE_FILTER));
services.produce(ServiceProviderBuildItem.allProvidersOfDependencies(
dependencies, List.of(LIQUIBASE_ARTIFACT, LIQUIBASE_MONGODB_ARTIFACT)));
// liquibase resource bundles
resourceBundle.produce(new NativeImageResourceBundleBuildItem("liquibase/i18n/liquibase-core"));
resourceBundle.produce(new NativeImageResourceBundleBuildItem("liquibase/i18n/liquibase-mongo"));
}
private void addService(BuildProducer<ServiceProviderBuildItem> services,
BuildProducer<ReflectiveClassBuildItem> reflective, String serviceClassName,
boolean shouldRegisterFieldForReflection, String... excludedImpls) {
try {
String service = ServiceProviderBuildItem.SPI_ROOT + serviceClassName;
Set<String> implementations = ServiceUtil.classNamesNamedIn(Thread.currentThread().getContextClassLoader(),
service);
if (excludedImpls.length > 0) {
implementations = new HashSet<>(implementations);
Arrays.asList(excludedImpls).forEach(implementations::remove);
}
services.produce(new ServiceProviderBuildItem(serviceClassName, implementations.toArray(new String[0])));
reflective.produce(
ReflectiveClassBuildItem.builder(implementations.toArray(new String[0])).reason(getClass().getName())
.constructors().methods().fields(shouldRegisterFieldForReflection).build());
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void createBeans(LiquibaseMongodbRecorder recorder,
LiquibaseMongodbBuildTimeConfig config,
BuildProducer<AdditionalBeanBuildItem> additionalBeans,
BuildProducer<SyntheticBeanBuildItem> syntheticBeanBuildItemBuildProducer) {
additionalBeans.produce(AdditionalBeanBuildItem.builder()
.addBeanClass(LiquibaseMongodbClient.class).build());
for (String clientName : config.clientConfigs().keySet()) {
SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem
.configure(LiquibaseMongodbFactory.class)
.scope(ApplicationScoped.class) // this is what the existing code does, but it doesn't seem reasonable
.setRuntimeInit()
.unremovable()
.supplier(recorder.liquibaseSupplier(clientName));
if (MongoConfig.isDefaultClient(clientName)) {
configurator.addQualifier(Default.class);
} else {
configurator.name(LIQUIBASE_MONGODB_BEAN_NAME_PREFIX + clientName);
configurator.addQualifier().annotation(LiquibaseMongodbClient.class)
.addValue("value", clientName).done();
}
syntheticBeanBuildItemBuildProducer.produce(configurator.done());
}
}
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
@Consume(BeanContainerBuildItem.class)
ServiceStartBuildItem startLiquibase(LiquibaseMongodbRecorder recorder,
LiquibaseMongodbBuildTimeConfig config,
BuildProducer<InitTaskCompletedBuildItem> initializationCompleteBuildItem) {
// will actually run the actions at runtime
for (String clientName : config.clientConfigs().keySet()) {
recorder.doStartActions(clientName);
}
initializationCompleteBuildItem.produce(new InitTaskCompletedBuildItem("liquibase-mongodb"));
return new ServiceStartBuildItem("liquibase-mongodb");
}
@BuildStep
public InitTaskBuildItem configureInitTask(ApplicationInfoBuildItem app) {
return InitTaskBuildItem.create()
.withName(app.getName() + "-liquibase-mongodb-init")
.withTaskEnvVars(
Map.of("QUARKUS_INIT_AND_EXIT", "true", "QUARKUS_LIQUIBASE_MONGODB_ENABLED", "true"))
.withAppEnvVars(Map.of("QUARKUS_LIQUIBASE_MONGODB_ENABLED", "false"))
.withSharedEnvironment(true)
.withSharedFilesystem(true);
}
/**
* Collect the configured changeLog file for the default and all named clients.
* <p>
* A {@link LinkedHashSet} is used to avoid duplications.
*/
private List<String> getChangeLogs(LiquibaseMongodbBuildTimeConfig liquibaseBuildConfig) {
ChangeLogParameters changeLogParameters = new ChangeLogParameters();
ChangeLogParserFactory changeLogParserFactory = ChangeLogParserFactory.getInstance();
try (var classLoaderResourceAccessor = new ClassLoaderResourceAccessor(
Thread.currentThread().getContextClassLoader())) {
Set<String> resources = new LinkedHashSet<>();
for (LiquibaseMongodbBuildTimeClientConfig buildConfig : liquibaseBuildConfig.clientConfigs().values()) {
resources.addAll(findAllChangeLogFiles(
buildConfig.changeLog(),
changeLogParserFactory,
classLoaderResourceAccessor,
changeLogParameters));
}
LOGGER.debugf("Liquibase changeLogs: %s", resources);
return new ArrayList<>(resources);
} catch (Exception ex) {
// close() really shouldn't declare that exception, see also https://github.com/liquibase/liquibase/pull/2576
throw new IllegalStateException(
"Error while loading the liquibase changelogs: %s".formatted(ex.getMessage()), ex);
}
}
/**
* Finds all resource files for the given change log file
*/
private Set<String> findAllChangeLogFiles(String file, ChangeLogParserFactory changeLogParserFactory,
ClassLoaderResourceAccessor classLoaderResourceAccessor,
ChangeLogParameters changeLogParameters) {
try {
ChangeLogParser parser = changeLogParserFactory.getParser(file, classLoaderResourceAccessor);
DatabaseChangeLog changelog = parser.parse(file, changeLogParameters, classLoaderResourceAccessor);
if (changelog != null) {
Set<String> result = new LinkedHashSet<>();
// get all changeSet files
for (ChangeSet changeSet : changelog.getChangeSets()) {
result.add(changeSet.getFilePath());
changeSet.getChanges().stream()
.map(change -> extractChangeFile(change, changeSet.getFilePath()))
.forEach(changeFile -> changeFile.ifPresent(result::add));
// get all parents of the changeSet
DatabaseChangeLog parent = changeSet.getChangeLog();
while (parent != null) {
result.add(parent.getFilePath());
parent = parent.getParentChangeLog();
}
}
result.add(changelog.getFilePath());
return result;
}
} catch (LiquibaseException ex) {
throw new IllegalStateException(ex);
}
return Collections.emptySet();
}
private Optional<String> extractChangeFile(Change change, String changeSetFilePath) {
String path = null;
Boolean relative = null;
if (change instanceof LoadDataChange loadDataChange) {
path = loadDataChange.getFile();
relative = loadDataChange.isRelativeToChangelogFile();
} else if (change instanceof SQLFileChange sqlFileChange) {
path = sqlFileChange.getPath();
relative = sqlFileChange.isRelativeToChangelogFile();
} else if (change instanceof CreateProcedureChange createProcedureChange) {
path = createProcedureChange.getPath();
relative = createProcedureChange.isRelativeToChangelogFile();
} else if (change instanceof CreateViewChange createViewChange) {
path = createViewChange.getPath();
relative = createViewChange.getRelativeToChangelogFile();
}
// unrelated change or change does not reference a file (e.g. inline view)
if (path == null) {
return Optional.empty();
}
// absolute file path or changeSet has no file path
if (relative == null || !relative || changeSetFilePath == null) {
return Optional.of(path);
}
// relative file path needs to be resolved against changeSetFilePath
// notes: ClassLoaderResourceAccessor does not provide a suitable method and CLRA.getFinalPath() is not visible
return Optional.of(Paths.get(changeSetFilePath).resolveSibling(path).toString().replace('\\', '/'));
}
}
| for |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/AbstractArrayState.java | {
"start": 703,
"end": 1782
} | class ____ implements Releasable, GroupingAggregatorState {
protected final BigArrays bigArrays;
private BitArray seen;
public AbstractArrayState(BigArrays bigArrays) {
this.bigArrays = bigArrays;
}
public boolean hasValue(int groupId) {
return seen == null || seen.get(groupId);
}
/**
* Switches this array state into tracking which group ids are set. This is
* idempotent and fast if already tracking so it's safe to, say, call it once
* for every block of values that arrives containing {@code null}.
*/
@Override
public final void enableGroupIdTracking(SeenGroupIds seenGroupIds) {
if (seen == null) {
seen = seenGroupIds.seenGroupIds(bigArrays);
}
}
protected final void trackGroupId(int groupId) {
if (trackingGroupIds()) {
seen.set(groupId);
}
}
protected final boolean trackingGroupIds() {
return seen != null;
}
@Override
public void close() {
Releasables.close(seen);
}
}
| AbstractArrayState |
java | google__dagger | dagger-android/main/java/dagger/android/DaggerBroadcastReceiver.java | {
"start": 1768,
"end": 1959
} | class ____ extends BroadcastReceiver {
@CallSuper
@Override
public void onReceive(Context context, Intent intent) {
AndroidInjection.inject(this, context);
}
}
| DaggerBroadcastReceiver |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/LogEipListenerTest.java | {
"start": 1278,
"end": 2588
} | class ____ {
private static boolean listenerFired;
@Test
public void testLogListener() throws Exception {
listenerFired = false;
CamelContext context = createCamelContext();
MockEndpoint mock = context.getEndpoint("mock:foo", MockEndpoint.class);
mock.expectedMessageCount(1);
context.getCamelContextExtension().addLogListener((exchange, camelLogger, message) -> {
assertEquals("Got hello", message);
listenerFired = true;
return message + " - modified by listener";
});
context.start();
context.createProducerTemplate().sendBody("direct:foo", "hello");
mock.assertIsSatisfied();
assertTrue(listenerFired);
context.stop();
}
protected CamelContext createCamelContext() throws Exception {
Registry registry = new DefaultRegistry();
CamelContext context = new DefaultCamelContext(registry);
context.addRoutes(createRouteBuilder());
return context;
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:foo").routeId("foo").log("Got ${body}").to("mock:foo");
}
};
}
}
| LogEipListenerTest |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/beanmanager/BeanManagerTest.java | {
"start": 15060,
"end": 15258
} | class ____ {
@AroundInvoke
Object intercept(InvocationContext ctx) throws Exception {
return ctx.proceed();
}
}
@Dependent
static | LowPriorityInterceptor |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ExtendedThrowablePatternConverterTest.java | {
"start": 1600,
"end": 4285
} | class ____ extends AbstractPropertyTest {
PropertyTest() {
super("%xEx", THROWING_METHOD);
}
}
private static final List<String> EXPECTED_FULL_STACK_TRACE_LINES = asList(
"foo.TestFriendlyException: r [localized]",
" at " + TestFriendlyException.NAMED_MODULE_STACK_TRACE_ELEMENT + " ~[?:?]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" at foo.TestFriendlyException.<clinit>(TestFriendlyException.java:0) ~[test-classes/:?]",
" at " + TestFriendlyException.ORG_APACHE_REPLACEMENT_STACK_TRACE_ELEMENT + " ~[?:0]",
" Suppressed: foo.TestFriendlyException: r_s [localized]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" ... 2 more",
" Suppressed: foo.TestFriendlyException: r_s_s [localized]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" ... 3 more",
" Caused by: foo.TestFriendlyException: r_s_c [localized]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" ... 3 more",
"Caused by: foo.TestFriendlyException: r_c [localized]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" ... 2 more",
" Suppressed: foo.TestFriendlyException: r_c_s [localized]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" ... 3 more",
" Caused by: [CIRCULAR REFERENCE: foo.TestFriendlyException: r_c [localized]]",
"Caused by: foo.TestFriendlyException: r_c_c [localized]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" at foo.TestFriendlyException.create(TestFriendlyException.java:0) ~[test-classes/:?]",
" ... 3 more",
"Caused by: [CIRCULAR REFERENCE: foo.TestFriendlyException: r_c [localized]]");
@Nested
| PropertyTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableTest12.java | {
"start": 986,
"end": 1983
} | class ____ extends TestCase {
public void test_alter_first() throws Exception {
String sql = "ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;";
MySqlStatementParser parser = new MySqlStatementParser(sql);
SQLStatement stmt = parser.parseStatementList().get(0);
parser.match(Token.EOF);
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
String output = SQLUtils.toMySqlString(stmt);
assertEquals("ALTER TABLE tbl_name" +
"\n\tDROP FOREIGN KEY fk_symbol;", output);
assertEquals(1, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
}
}
| MySqlAlterTableTest12 |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/fulltext/AbstractMatchFullTextFunctionTests.java | {
"start": 943,
"end": 14761
} | class ____ extends AbstractFunctionTestCase {
protected static List<TestCaseSupplier> testCaseSuppliers() {
List<TestCaseSupplier> suppliers = new ArrayList<>();
AbstractMatchFullTextFunctionTests.addUnsignedLongCases(suppliers);
AbstractMatchFullTextFunctionTests.addNumericCases(suppliers);
AbstractMatchFullTextFunctionTests.addNonNumericCases(suppliers);
AbstractMatchFullTextFunctionTests.addQueryAsStringTestCases(suppliers);
AbstractMatchFullTextFunctionTests.addStringTestCases(suppliers);
return addNullFieldTestCases(suppliers);
}
private static void addNonNumericCases(List<TestCaseSupplier> suppliers) {
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.booleanCases(),
TestCaseSupplier.booleanCases(),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.ipCases(),
TestCaseSupplier.ipCases(),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.versionCases(""),
TestCaseSupplier.versionCases(""),
List.of(),
false
)
);
// Datetime
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.dateCases(),
TestCaseSupplier.dateCases(),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.dateNanosCases(),
TestCaseSupplier.dateNanosCases(),
List.of(),
false
)
);
}
private static void addNumericCases(List<TestCaseSupplier> suppliers) {
suppliers.addAll(
TestCaseSupplier.forBinaryComparisonWithWidening(
new TestCaseSupplier.NumericTypeTestConfigs<>(
new TestCaseSupplier.NumericTypeTestConfig<>(
(Integer.MIN_VALUE >> 1) - 1,
(Integer.MAX_VALUE >> 1) - 1,
(l, r) -> true,
"EqualsIntsEvaluator"
),
new TestCaseSupplier.NumericTypeTestConfig<>(
(Long.MIN_VALUE >> 1) - 1,
(Long.MAX_VALUE >> 1) - 1,
(l, r) -> true,
"EqualsLongsEvaluator"
),
new TestCaseSupplier.NumericTypeTestConfig<>(
Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY,
// NB: this has different behavior than Double::equals
(l, r) -> true,
"EqualsDoublesEvaluator"
)
),
"field",
"query",
(lhs, rhs) -> List.of(),
false
)
);
}
private static void addUnsignedLongCases(List<TestCaseSupplier> suppliers) {
// TODO: These should be integrated into the type cross product above, but are currently broken
// see https://github.com/elastic/elasticsearch/issues/102935
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.ulongCases(BigInteger.ZERO, NumericUtils.UNSIGNED_LONG_MAX, true),
TestCaseSupplier.ulongCases(BigInteger.ZERO, NumericUtils.UNSIGNED_LONG_MAX, true),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.ulongCases(BigInteger.ZERO, NumericUtils.UNSIGNED_LONG_MAX, true),
TestCaseSupplier.intCases(Integer.MIN_VALUE, Integer.MAX_VALUE, true),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.ulongCases(BigInteger.ZERO, NumericUtils.UNSIGNED_LONG_MAX, true),
TestCaseSupplier.longCases(Long.MIN_VALUE, Long.MAX_VALUE, true),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.ulongCases(BigInteger.ZERO, NumericUtils.UNSIGNED_LONG_MAX, true),
TestCaseSupplier.doubleCases(Double.MIN_VALUE, Double.MAX_VALUE, true),
List.of(),
false
)
);
}
private static void addQueryAsStringTestCases(List<TestCaseSupplier> suppliers) {
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.intCases(Integer.MIN_VALUE, Integer.MAX_VALUE, true),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.intCases(Integer.MIN_VALUE, Integer.MAX_VALUE, true),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.longCases(Integer.MIN_VALUE, Integer.MAX_VALUE, true),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.doubleCases(Double.MIN_VALUE, Double.MAX_VALUE, true),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
// Unsigned Long cases
// TODO: These should be integrated into the type cross product above, but are currently broken
// see https://github.com/elastic/elasticsearch/issues/102935
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.ulongCases(BigInteger.ZERO, NumericUtils.UNSIGNED_LONG_MAX, true),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.booleanCases(),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.ipCases(),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.versionCases(""),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
// Datetime
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.dateCases(),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
suppliers.addAll(
TestCaseSupplier.forBinaryNotCasting(
null,
"field",
"query",
Object::equals,
DataType.BOOLEAN,
TestCaseSupplier.dateNanosCases(),
TestCaseSupplier.stringCases(DataType.KEYWORD),
List.of(),
false
)
);
}
private static void addStringTestCases(List<TestCaseSupplier> suppliers) {
for (DataType fieldType : DataType.stringTypes()) {
if (DataType.UNDER_CONSTRUCTION.contains(fieldType)) {
continue;
}
for (TestCaseSupplier.TypedDataSupplier queryDataSupplier : stringCases(fieldType)) {
suppliers.add(
TestCaseSupplier.testCaseSupplier(
queryDataSupplier,
new TestCaseSupplier.TypedDataSupplier(fieldType.typeName(), () -> randomAlphaOfLength(10), DataType.KEYWORD),
(d1, d2) -> equalTo("string"),
DataType.BOOLEAN,
(o1, o2) -> true
)
);
}
}
}
/**
* Adds test cases with null field (first argument) to the provided list of suppliers.
* This creates copies of existing test cases but with the field parameter set to null,
* which tests how full-text functions handle missing/null fields.
*
* @param suppliers the list of test case suppliers to augment
* @return the same list with additional null-field test cases added
*/
public static List<TestCaseSupplier> addNullFieldTestCases(List<TestCaseSupplier> suppliers) {
List<TestCaseSupplier> nullFieldCases = new ArrayList<>();
Set<List<DataType>> uniqueSignatures = new HashSet<>();
for (TestCaseSupplier supplier : suppliers) {
boolean firstTimeSeenSignature = uniqueSignatures.add(supplier.types());
// Add a single null field case per unique signature, similar to AbstractFunctionTestCase.anyNullIsNull
if (firstTimeSeenSignature == false) {
continue;
}
// Create a new test case supplier with null as the first argument (field)
List<DataType> types = new ArrayList<>(supplier.types());
types.set(0, DataType.NULL);
TestCaseSupplier nullFieldCase = new TestCaseSupplier(supplier.name() + " with null field", types, () -> {
TestCaseSupplier.TestCase original = supplier.supplier().get();
List<TestCaseSupplier.TypedData> modifiedData = new ArrayList<>(original.getData());
// Replace the first argument (field) with null
TestCaseSupplier.TypedData originalField = modifiedData.get(0);
modifiedData.set(0, new TestCaseSupplier.TypedData(null, DataType.NULL, originalField.name()));
// Return a test case that expects null result since field is null
return new TestCaseSupplier.TestCase(modifiedData, original.evaluatorToString(), DataType.BOOLEAN, equalTo(null));
});
nullFieldCases.add(nullFieldCase);
}
suppliers.addAll(nullFieldCases);
return suppliers;
}
public final void testLiteralExpressions() {
Expression expression = buildLiteralExpression(testCase);
assertFalse("expected resolved", expression.typeResolved().unresolved());
}
}
| AbstractMatchFullTextFunctionTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/mapping/EmbeddableDiscriminatorMapping.java | {
"start": 397,
"end": 577
} | interface ____ extends DiscriminatorMapping, FetchOptions {
/**
* Retrieve the relational discriminator value corresponding to the provided embeddable | EmbeddableDiscriminatorMapping |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/MessageSourceResolvable.java | {
"start": 1120,
"end": 2312
} | interface ____ {
/**
* Return the codes to be used to resolve this message, in the order that
* they should get tried. The last code will therefore be the default one.
* @return a String array of codes which are associated with this message
*/
String @Nullable [] getCodes();
/**
* Return the array of arguments to be used to resolve this message.
* <p>The default implementation simply returns {@code null}.
* @return an array of objects to be used as parameters to replace
* placeholders within the message text
* @see java.text.MessageFormat
*/
default Object @Nullable [] getArguments() {
return null;
}
/**
* Return the default message to be used to resolve this message.
* <p>The default implementation simply returns {@code null}.
* Note that the default message may be identical to the primary
* message code ({@link #getCodes()}), which effectively enforces
* {@link org.springframework.context.support.AbstractMessageSource#setUseCodeAsDefaultMessage}
* for this particular message.
* @return the default message, or {@code null} if no default
*/
default @Nullable String getDefaultMessage() {
return null;
}
}
| MessageSourceResolvable |
java | quarkusio__quarkus | integration-tests/infinispan-cache-jpa/src/main/java/io/quarkus/it/infinispan/cache/jpa/Person.java | {
"start": 1071,
"end": 1276
} | class ____ implements java.util.Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o1.getName().compareTo(o2.getName());
}
}
}
| Comparator |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/main/java/io/quarkus/rest/client/reactive/deployment/RestClientReactiveProcessor.java | {
"start": 43593,
"end": 45334
} | class ____ '" + classResult.interfaceName + "'");
}
result.put(classResult.interfaceName, classResult);
reflectiveClasses.produce(ReflectiveClassBuildItem.builder(classResult.generatedClassName)
.reason(getClass().getName())
.build());
}
return result;
}
private void addGeneratedProviders(IndexView index, ClassCreator classCreator, MethodCreator constructor,
Map<String, List<AnnotationInstance>> annotationsByClassName,
Map<String, List<GeneratedClassResult>> generatedProviders) {
int i = 1;
for (Map.Entry<String, List<AnnotationInstance>> annotationsForClass : annotationsByClassName.entrySet()) {
MethodCreator mc = classCreator.getMethodCreator("addGeneratedProviders" + i, void.class);
ResultHandle map = mc.newInstance(MethodDescriptor.ofConstructor(HashMap.class));
for (AnnotationInstance value : annotationsForClass.getValue()) {
String className = value.value().asString();
AnnotationValue priorityAnnotationValue = value.value("priority");
int priority;
if (priorityAnnotationValue == null) {
priority = getAnnotatedPriority(index, className, Priorities.USER);
} else {
priority = priorityAnnotationValue.asInt();
}
mc.invokeInterfaceMethod(MAP_PUT, map, mc.loadClassFromTCCL(className),
mc.load(priority));
}
String ifaceName = annotationsForClass.getKey();
if (generatedProviders.containsKey(ifaceName)) {
// remove the | is |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/OpenshiftDeploymentconfigsComponentBuilderFactory.java | {
"start": 2118,
"end": 6286
} | interface ____ extends ComponentBuilder<OpenshiftDeploymentConfigsComponent> {
/**
* To use an existing kubernetes client.
*
* The option is a:
* <code>io.fabric8.kubernetes.client.KubernetesClient</code> type.
*
* Group: common
*
* @param kubernetesClient the value to set
* @return the dsl builder
*/
default OpenshiftDeploymentconfigsComponentBuilder kubernetesClient(io.fabric8.kubernetes.client.KubernetesClient kubernetesClient) {
doSetProperty("kubernetesClient", kubernetesClient);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default OpenshiftDeploymentconfigsComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default OpenshiftDeploymentconfigsComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default OpenshiftDeploymentconfigsComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
| OpenshiftDeploymentconfigsComponentBuilder |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/javadoc/UnescapedEntityTest.java | {
"start": 7333,
"end": 7825
} | interface ____ {
/**
* @see <a href="https://google.com">google</a>
*/
void foo(List<Integer> foos);
}
""")
.doTest();
}
@Test
public void extraClosingTag() {
refactoring
.addInputLines(
"Test.java",
"""
/**
*
*
* <pre>Foo List<Foo> bar</pre>
*
* </pre>
*/
| Test |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/ContentPathTests.java | {
"start": 560,
"end": 3567
} | class ____ extends ESTestCase {
public void testAddPath() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
contentPath.add("bar");
String pathAsText = contentPath.pathAsText("baz");
assertEquals("foo.bar.baz", pathAsText);
}
public void testRemovePath() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
String[] path = contentPath.getPath();
assertEquals("foo", path[0]);
contentPath.remove();
assertNull(path[0]);
assertEquals(0, contentPath.length());
String pathAsText = contentPath.pathAsText("bar");
assertEquals("bar", pathAsText);
}
public void testRemovePathException() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
contentPath.remove();
expectThrows(IndexOutOfBoundsException.class, contentPath::remove);
}
public void testBehaviourWithLongerPath() {
ContentPath contentPath = new ContentPath();
contentPath.add("1");
contentPath.add("2");
contentPath.add("3");
contentPath.add("4");
contentPath.add("5");
contentPath.add("6");
contentPath.add("7");
contentPath.add("8");
contentPath.add("9");
contentPath.add("10");
assertEquals(10, contentPath.length());
String pathAsText = contentPath.pathAsText("11");
assertEquals("1.2.3.4.5.6.7.8.9.10.11", pathAsText);
}
public void testLengthOfPath() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
contentPath.add("bar");
contentPath.add("baz");
assertEquals(3, contentPath.length());
}
public void testLengthOfPathAfterRemove() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
contentPath.add("bar");
contentPath.add("baz");
assertEquals(3, contentPath.length());
contentPath.remove();
contentPath.remove();
assertEquals(1, contentPath.length());
}
public void testPathAsText() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
contentPath.add("bar");
assertEquals("foo.bar.baz", contentPath.pathAsText("baz"));
}
public void testPathAsTextAfterRemove() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
contentPath.add("bar");
contentPath.add("baz");
contentPath.remove();
contentPath.remove();
assertEquals("foo.qux", contentPath.pathAsText("qux"));
}
public void testPathAsTextAfterRemoveAndMoreAdd() {
ContentPath contentPath = new ContentPath();
contentPath.add("foo");
contentPath.add("bar");
contentPath.remove();
contentPath.add("baz");
assertEquals("foo.baz.qux", contentPath.pathAsText("qux"));
}
}
| ContentPathTests |
java | apache__flink | flink-python/src/main/java/org/apache/flink/streaming/api/utils/ByteArrayWrapper.java | {
"start": 996,
"end": 1090
} | class ____ used to calculate a deterministic hash code of a byte
* array.
*/
@Internal
public | is |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/test/GatewayIntegrationTests.java | {
"start": 8147,
"end": 8784
} | class ____ {
private static final Log log = LogFactory.getLog(TestConfig.class);
private static Mono<Void> postFilterWork(ServerWebExchange exchange) {
log.info("postFilterWork");
exchange.getResponse().getHeaders().add("X-Post-Header", "AddedAfterRoute");
return Mono.empty();
}
@GetMapping("/httpbin/nocontenttype")
ResponseEntity<Void> nocontenttype() {
return ResponseEntity.status(204).build();
}
@Bean
@Order(-1)
GlobalFilter postFilter() {
return (exchange, chain) -> {
log.info("postFilter start");
return chain.filter(exchange).then(postFilterWork(exchange));
};
}
}
}
| TestConfig |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/SplitTwoSubUnitOfWorkTest.java | {
"start": 4100,
"end": 4444
} | class ____ {
private final String foo;
private final String bar;
private MyBody(String foo, String bar) {
this.foo = foo;
this.bar = bar;
}
public String getFoo() {
return foo;
}
public String getBar() {
return bar;
}
}
}
| MyBody |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/LoginTokenTest.java | {
"start": 1274,
"end": 3046
} | class ____ {
@Test
public void testLoginTokenWithUnknownFields() throws Exception {
String salesforceOAuthResponse = "{\n"
+ " \"access_token\": \"00XXXXXXXXXXXX!ARMAQKg_lg_hGaRElvizVFBQHoCpvX8tzwGnROQ0_MDPXSceMeZHtm3JHkPmMhlgK0Km3rpJkwxwHInd_8o022KsDy.p4O.X\",\n"
+ " \"is_readonly\": \"false\",\n"
+ " \"signature\": \"XXXXXXXXXX+MYU+JrOXPSbpHa2ihMpSvUqow1iTPh7Q=\",\n"
+ " \"instance_url\": \"https://xxxxxxxx--xxxxxxx.cs5.my.salesforce.com\",\n"
+ " \"id\": \"https://test.salesforce.com/id/00DO00000054tO8MAI/005O0000001cmmdIAA\",\n"
+ " \"token_type\": \"Bearer\",\n"
+ " \"issued_at\": \"1442798068621\",\n"
+ " \"an_unrecognised_field\": \"foo\"\n" + "}";
ObjectMapper mapper = JsonUtils.createObjectMapper();
Exception e = null;
LoginToken token = null;
try {
token = mapper.readValue(salesforceOAuthResponse, LoginToken.class);
} catch (Exception ex) {
e = ex;
}
// assert ObjectMapper deserialized the SF OAuth response and returned a
// valid token back
assertNotNull(token, "An invalid token was returned");
// assert No exception was thrown during the JSON deserialization
// process
assertNull(e, "Exception was thrown during JSON deserialisation");
// assert one of the token fields
assertEquals("false", token.getIsReadOnly());
}
}
| LoginTokenTest |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/indices/state/SimpleIndexStateIT.java | {
"start": 1343,
"end": 6479
} | class ____ extends ESIntegTestCase {
public void testSimpleOpenClose() {
logger.info("--> creating test index");
createIndex("test");
logger.info("--> waiting for green status");
ensureGreen();
NumShards numShards = getNumShards("test");
ClusterStateResponse stateResponse = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get();
assertThat(stateResponse.getState().metadata().getProject().index("test").getState(), equalTo(IndexMetadata.State.OPEN));
assertThat(stateResponse.getState().routingTable().index("test").size(), equalTo(numShards.numPrimaries));
assertEquals(
stateResponse.getState().routingTable().index("test").shardsWithState(ShardRoutingState.STARTED).size(),
numShards.totalNumShards
);
logger.info("--> indexing a simple document");
prepareIndex("test").setId("1").setSource("field1", "value1").get();
logger.info("--> closing test index...");
assertAcked(indicesAdmin().prepareClose("test"));
stateResponse = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get();
assertThat(stateResponse.getState().metadata().getProject().index("test").getState(), equalTo(IndexMetadata.State.CLOSE));
assertThat(stateResponse.getState().routingTable().index("test"), notNullValue());
logger.info("--> trying to index into a closed index ...");
try {
prepareIndex("test").setId("1").setSource("field1", "value1").get();
fail();
} catch (IndexClosedException e) {
// all is well
}
logger.info("--> opening index...");
assertAcked(indicesAdmin().prepareOpen("test"));
logger.info("--> waiting for green status");
ensureGreen();
stateResponse = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get();
assertThat(stateResponse.getState().metadata().getProject().index("test").getState(), equalTo(IndexMetadata.State.OPEN));
assertThat(stateResponse.getState().routingTable().index("test").size(), equalTo(numShards.numPrimaries));
assertEquals(
stateResponse.getState().routingTable().index("test").shardsWithState(ShardRoutingState.STARTED).size(),
numShards.totalNumShards
);
logger.info("--> indexing a simple document");
prepareIndex("test").setId("1").setSource("field1", "value1").get();
}
public void testFastCloseAfterCreateContinuesCreateAfterOpen() {
logger.info("--> creating test index that cannot be allocated");
indicesAdmin().prepareCreate("test")
.setWaitForActiveShards(ActiveShardCount.NONE)
.setSettings(Settings.builder().put("index.routing.allocation.include.tag", "no_such_node").build())
.get();
ClusterHealthResponse health = clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT, "test").setWaitForNodes(">=2").get();
assertThat(health.isTimedOut(), equalTo(false));
assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
assertAcked(indicesAdmin().prepareClose("test").setWaitForActiveShards(ActiveShardCount.NONE));
logger.info("--> updating test index settings to allow allocation");
updateIndexSettings(Settings.builder().put("index.routing.allocation.include.tag", ""), "test");
indicesAdmin().prepareOpen("test").get();
logger.info("--> waiting for green status");
ensureGreen();
NumShards numShards = getNumShards("test");
ClusterStateResponse stateResponse = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get();
assertThat(stateResponse.getState().metadata().getProject().index("test").getState(), equalTo(IndexMetadata.State.OPEN));
assertThat(stateResponse.getState().routingTable().index("test").size(), equalTo(numShards.numPrimaries));
assertEquals(
stateResponse.getState().routingTable().index("test").shardsWithState(ShardRoutingState.STARTED).size(),
numShards.totalNumShards
);
logger.info("--> indexing a simple document");
prepareIndex("test").setId("1").setSource("field1", "value1").get();
}
public void testConsistencyAfterIndexCreationFailure() {
logger.info("--> deleting test index....");
try {
indicesAdmin().prepareDelete("test").get();
} catch (IndexNotFoundException ex) {
// Ignore
}
logger.info("--> creating test index with invalid settings ");
try {
indicesAdmin().prepareCreate("test").setSettings(Settings.builder().put("number_of_shards", "bad")).get();
fail();
} catch (IllegalArgumentException ex) {
assertEquals("Failed to parse value [bad] for setting [index.number_of_shards]", ex.getMessage());
// Expected
}
logger.info("--> creating test index with valid settings ");
assertAcked(indicesAdmin().prepareCreate("test").setSettings(Settings.builder().put("number_of_shards", 1)));
}
}
| SimpleIndexStateIT |
java | quarkusio__quarkus | extensions/mailer/runtime/src/main/java/io/quarkus/mailer/Mail.java | {
"start": 458,
"end": 14275
} | class ____ {
private List<String> bcc = new ArrayList<>();
private List<String> cc = new ArrayList<>();
private String from;
private final List<String> replyTo = new ArrayList<>();
private String bounceAddress;
private String subject;
private String text;
private String html;
private List<String> to = new ArrayList<>();
private Map<String, List<String>> headers = new HashMap<>();
private List<Attachment> attachments = new ArrayList<>();
/**
* Creates a new instance of {@link Mail}.
*/
public Mail() {
// empty
}
/**
* Creates a new instance of {@link Mail} that contains a "text" body.
* The returned instance can be modified.
*
* @param to the address of the recipient
* @param subject the subject
* @param text the body
* @return the new {@link Mail} instance.
*/
public static Mail withText(String to, String subject, String text) {
return new Mail().addTo(to).setSubject(subject).setText(text);
}
/**
* Creates a new instance of {@link Mail} that contains a "html" body.
* The returned instance can be modified.
*
* @param to the address of the recipient
* @param subject the subject
* @param html the body
* @return the new {@link Mail} instance.
*/
public static Mail withHtml(String to, String subject, String html) {
return new Mail().addTo(to).setSubject(subject).setHtml(html);
}
/**
* Adds BCC recipients.
*
* @param bcc the recipients, each item must be a valid email address.
* @return the current {@link Mail}
*/
public Mail addBcc(String... bcc) {
if (bcc != null) {
Collections.addAll(this.bcc, bcc);
}
return this;
}
/**
* Adds CC recipients.
*
* @param cc the recipients, each item must be a valid email address.
* @return the current {@link Mail}
*/
public Mail addCc(String... cc) {
if (cc != null) {
Collections.addAll(this.cc, cc);
}
return this;
}
/**
* Adds TO recipients.
*
* @param to the recipients, each item must be a valid email address.
* @return the current {@link Mail}
*/
public Mail addTo(String... to) {
if (to != null) {
Collections.addAll(this.to, to);
}
return this;
}
/**
* @return the BCC recipients.
*/
public List<String> getBcc() {
return bcc;
}
/**
* Sets the BCC recipients.
*
* @param bcc the list of recipients
* @return the current {@link Mail}
*/
public Mail setBcc(List<String> bcc) {
this.bcc = Objects.requireNonNullElseGet(bcc, ArrayList::new);
return this;
}
/**
* @return the CC recipients.
*/
public List<String> getCc() {
return cc;
}
/**
* Sets the CC recipients.
*
* @param cc the list of recipients
* @return the current {@link Mail}
*/
public Mail setCc(List<String> cc) {
this.cc = Objects.requireNonNullElseGet(cc, ArrayList::new);
return this;
}
/**
* @return the sender address.
*/
public String getFrom() {
return from;
}
/**
* Sets the sender address. Notes that it's not accepted to send an email without a sender address.
* A default sender address can be configured in the application properties ( {@code quarkus.mailer.from} )
*
* @param from the sender address
* @return the current {@link Mail}
*/
public Mail setFrom(String from) {
this.from = from;
return this;
}
/**
* @return the reply-to address. In the case of multiple addresses, the comma-separated list is returned, following
* the https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.2 recommendation. If no reply-to address has been
* set, it returns {@code null}.
*/
public String getReplyTo() {
if (replyTo == null || replyTo.isEmpty()) {
return null;
}
return String.join(",", replyTo);
}
/**
* Adds a reply-to address.
*
* @param replyTo the address to use as reply-to. Must be a valid email address.
* @return the current {@link Mail}
* @see #setReplyTo(String)
*/
public Mail addReplyTo(String replyTo) {
this.replyTo.add(replyTo);
return this;
}
/**
* Sets the reply-to address.
*
* @param replyTo the address to use as reply-to. Must be a valid email address.
* @return the current {@link Mail}
* @see #setReplyTo(String[])
*/
public Mail setReplyTo(String replyTo) {
this.replyTo.clear();
this.replyTo.add(replyTo);
return this;
}
/**
* Sets the reply-to addresses.
*
* @param replyTo the addresses to use as reply-to. Must contain valid email addresses, must contain at least
* one address.
* @return the current {@link Mail}
*/
public Mail setReplyTo(String... replyTo) {
this.replyTo.clear();
Collections.addAll(this.replyTo, replyTo);
return this;
}
/**
* @return the bounce address.
*/
public String getBounceAddress() {
return bounceAddress;
}
/**
* Sets the bounce address.
* A default sender address can be configured in the application properties ( {@code quarkus.mailer.bounceAddress} )
*
* @param bounceAddress the bounce address, must be a valid email address.
* @return the current {@link Mail}
*/
public Mail setBounceAddress(String bounceAddress) {
this.bounceAddress = bounceAddress;
return this;
}
/**
* @return the subject
*/
public String getSubject() {
return subject;
}
/**
* Sets the email subject.
*
* @param subject the subject
* @return the current {@link Mail}
*/
public Mail setSubject(String subject) {
this.subject = subject;
return this;
}
/**
* @return the text content of the email
*/
public String getText() {
return text;
}
/**
* Sets the body of the email as plain text.
*
* @param text the content
* @return the current {@link Mail}
*/
public Mail setText(String text) {
this.text = text;
return this;
}
/**
* @return the HTML content of the email
*/
public String getHtml() {
return html;
}
/**
* Sets the body of the email as HTML.
*
* @param html the content
* @return the current {@link Mail}
*/
public Mail setHtml(String html) {
this.html = html;
return this;
}
/**
* @return the TO recipients.
*/
public List<String> getTo() {
return to;
}
/**
* Sets the TO recipients.
*
* @param to the list of recipients
* @return the current {@link Mail}
*/
public Mail setTo(List<String> to) {
this.to = Objects.requireNonNullElseGet(to, ArrayList::new);
return this;
}
/**
* @return the current set of headers.
*/
public Map<String, List<String>> getHeaders() {
return headers;
}
/**
* Adds a header value. If this header already has a value, the value is appended.
*
* @param key the header name, must not be {@code null}
* @param values the header values, must not be {@code null}
* @return the current {@link Mail}
*/
public Mail addHeader(String key, String... values) {
if (key == null || values == null) {
throw new IllegalArgumentException("Cannot add header, key and value must not be null");
}
List<String> content = this.headers.computeIfAbsent(key, k -> new ArrayList<>());
Collections.addAll(content, values);
return this;
}
/**
* Removes a header.
*
* @param key the header name, must not be {@code null}.
* @return the current {@link Mail}
*/
public Mail removeHeader(String key) {
if (key == null) {
throw new IllegalArgumentException("Cannot remove header, key must not be null");
}
headers.remove(key);
return this;
}
/**
* Sets the list of headers.
*
* @param headers the headers
* @return the current {@link Mail}
*/
public Mail setHeaders(Map<String, List<String>> headers) {
this.headers = Objects.requireNonNullElseGet(headers, HashMap::new);
return this;
}
/**
* Adds an inline attachment.
*
* @param name the name of the attachment, generally a file name.
* @param file the file to be attached. Note that the file will be read asynchronously.
* @param contentType the content type
* @param contentId the content id. It must follow the {@code <some-id@some-domain>} syntax. Then the HTML
* content can reference this attachment using {@code src="cid:some-id@some-domain"}.
* @return the current {@link Mail}
*/
public Mail addInlineAttachment(String name, File file, String contentType, String contentId) {
this.attachments.add(new Attachment(name, file, contentType, contentId));
return this;
}
/**
* Adds an attachment.
*
* @param name the name of the attachment, generally a file name.
* @param file the file to be attached. Note that the file will be read asynchronously.
* @param contentType the content type.
* @return the current {@link Mail}
*/
public Mail addAttachment(String name, File file, String contentType) {
this.attachments.add(new Attachment(name, file, contentType));
return this;
}
/**
* Adds an attachment.
*
* @param name the name of the attachment, generally a file name.
* @param data the binary data to be attached
* @param contentType the content type.
* @return the current {@link Mail}
*/
public Mail addAttachment(String name, byte[] data, String contentType) {
this.attachments.add(new Attachment(name, data, contentType));
return this;
}
/**
* Adds an attachment.
*
* @param name the name of the attachment, generally a file name.
* @param data the binary data to be attached
* @param contentType the content type.
* @return the current {@link Mail}
*/
public Mail addAttachment(String name, Publisher<Byte> data, String contentType) {
this.attachments.add(new Attachment(name, data, contentType));
return this;
}
/**
* Adds an inline attachment.
*
* @param name the name of the attachment, generally a file name.
* @param data the binary data to be attached
* @param contentType the content type
* @param contentId the content id. It must follow the {@code <some-id@some-domain>} syntax. Then the HTML
* content can reference this attachment using {@code src="cid:some-id@some-domain"}.
* @return the current {@link Mail}
*/
public Mail addInlineAttachment(String name, byte[] data, String contentType, String contentId) {
this.attachments.add(new Attachment(name, data, contentType, contentId));
return this;
}
/**
* Adds an inline attachment.
*
* @param name the name of the attachment, generally a file name.
* @param data the binary data to be attached
* @param contentType the content type
* @param contentId the content id. It must follow the {@code <some-id@some-domain>} syntax. Then the HTML
* content can reference this attachment using {@code src="cid:some-id@some-domain"}.
* @return the current {@link Mail}
*/
public Mail addInlineAttachment(String name, Publisher<Byte> data, String contentType, String contentId) {
this.attachments.add(new Attachment(name, data, contentType, contentId));
return this;
}
/**
* Adds an attachment.
*
* @param name the name of the attachment, generally a file name.
* @param data the binary data to be attached
* @param contentType the content type
* @param description the description of the attachment
* @param disposition the disposition of the attachment
* @return the current {@link Mail}
*/
public Mail addAttachment(String name, byte[] data, String contentType, String description, String disposition) {
this.attachments.add(new Attachment(name, data, contentType, description, disposition));
return this;
}
/**
* Adds an attachment.
*
* @param name the name of the attachment, generally a file name.
* @param data the binary data to be attached
* @param contentType the content type
* @param description the description of the attachment
* @param disposition the disposition of the attachment
* @return the current {@link Mail}
*/
public Mail addAttachment(String name, Publisher<Byte> data, String contentType, String description,
String disposition) {
this.attachments.add(new Attachment(name, data, contentType, description, disposition));
return this;
}
/**
* @return the list of attachments
*/
public List<Attachment> getAttachments() {
return attachments;
}
/**
* Sets the attachment list.
*
* @param attachments the attachments.
* @return the current {@link Mail}
*/
public Mail setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
return this;
}
}
| Mail |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java | {
"start": 1206,
"end": 2149
} | class ____ {@link Environment} implementations. Supports the notion of
* reserved default profile names and enables specifying active and default profiles
* through the {@link #ACTIVE_PROFILES_PROPERTY_NAME} and
* {@link #DEFAULT_PROFILES_PROPERTY_NAME} properties.
*
* <p>Concrete subclasses differ primarily on which {@link PropertySource} objects they
* add by default. {@code AbstractEnvironment} adds none. Subclasses should contribute
* property sources through the protected {@link #customizePropertySources(MutablePropertySources)}
* hook, while clients should customize using {@link ConfigurableEnvironment#getPropertySources()}
* and work against the {@link MutablePropertySources} API.
* See {@link ConfigurableEnvironment} javadoc for usage examples.
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Phillip Webb
* @since 3.1
* @see ConfigurableEnvironment
* @see StandardEnvironment
*/
public abstract | for |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java | {
"start": 2991,
"end": 16430
} | interface ____ {
/**
* Service factory key.
*/
String FACTORY = "thread-factory-listener";
/**
* Listener when Camel has created a new {@link ThreadFactory} to be used by this
* {@link ExecutorServiceManager}.
*
* @param source optional source where the thread is being used (such as a {@link org.apache.camel.Consumer}.
* @param factory the created factory
* @return the factory to use by this {@link ExecutorServiceManager}.
*/
ThreadFactory onNewThreadFactory(Object source, ThreadFactory factory);
}
/**
* Adds a custom {@link ThreadFactoryListener} to use
*
* @param threadFactoryListener the thread factory listener
*/
void addThreadFactoryListener(ThreadFactoryListener threadFactoryListener);
/**
* Gets the {@link ThreadPoolFactory} to use for creating the thread pools.
*
* @return the thread pool factory
*/
ThreadPoolFactory getThreadPoolFactory();
/**
* Sets a custom {@link ThreadPoolFactory} to use
*
* @param threadPoolFactory the thread pool factory
*/
void setThreadPoolFactory(ThreadPoolFactory threadPoolFactory);
/**
* Creates a full thread name
*
* @param name name which is appended to the full thread name
* @return the full thread name
*/
String resolveThreadName(String name);
/**
* Gets the thread pool profile by the given id
*
* @param id id of the thread pool profile to get
* @return the found profile, or <tt>null</tt> if not found
*/
ThreadPoolProfile getThreadPoolProfile(String id);
/**
* Registers the given thread pool profile
*
* @param profile the profile
*/
void registerThreadPoolProfile(ThreadPoolProfile profile);
/**
* Sets the default thread pool profile
*
* @param defaultThreadPoolProfile the new default thread pool profile
*/
void setDefaultThreadPoolProfile(ThreadPoolProfile defaultThreadPoolProfile);
/**
* Gets the default thread pool profile
*
* @return the default profile which are newer <tt>null</tt>
*/
ThreadPoolProfile getDefaultThreadPoolProfile();
/**
* Sets the thread name pattern used for creating the full thread name.
* <p/>
* The default pattern is: <tt>Camel (#camelId#) thread ##counter# - #name#</tt>
* <p/>
* Where <tt>#camelId#</tt> is the name of the {@link org.apache.camel.CamelContext} <br/>
* and <tt>#counter#</tt> is a unique incrementing counter. <br/>
* and <tt>#name#</tt> is the regular thread name. <br/>
* You can also use <tt>#longName#</tt> is the long thread name which can include endpoint parameters etc.
*
* @param pattern the pattern
* @throws IllegalArgumentException if the pattern is invalid.
*/
void setThreadNamePattern(String pattern) throws IllegalArgumentException;
/**
* Gets the thread name pattern to use
*
* @return the pattern
*/
String getThreadNamePattern();
/**
* Sets the time to wait for thread pools to shutdown orderly, when invoking the {@link #shutdown()} method.
* <p/>
* The default value is <tt>10000</tt> millis.
*
* @param timeInMillis time in millis.
*/
void setShutdownAwaitTermination(long timeInMillis);
/**
* Gets the time to wait for thread pools to shutdown orderly, when invoking the {@link #shutdown()} method.
* <p/>
* The default value is <tt>10000</tt> millis.
*
* @return the timeout value
*/
long getShutdownAwaitTermination();
/**
* Creates a new daemon thread with the given name.
*
* @param name name which is appended to the thread name
* @param runnable a runnable to be executed by new thread instance
* @return the created thread
*/
Thread newThread(String name, Runnable runnable);
/**
* Creates a new thread pool using the default thread pool profile.
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @return the created thread pool
*/
ExecutorService newDefaultThreadPool(Object source, String name);
/**
* Creates a new scheduled thread pool using the default thread pool profile.
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @return the created thread pool
*/
ScheduledExecutorService newDefaultScheduledThreadPool(Object source, String name);
/**
* Creates a new thread pool using the given profile
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @param profile the profile with the thread pool settings to use
* @return the created thread pool
*/
ExecutorService newThreadPool(Object source, String name, ThreadPoolProfile profile);
/**
* Creates a new thread pool using using the given profile id
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @param profileId the id of the profile with the thread pool settings to use
* @return the created thread pool, or <tt>null</tt> if the thread pool profile could not be found
*/
ExecutorService newThreadPool(Object source, String name, String profileId);
/**
* Creates a new thread pool.
* <p/>
* Will fallback and use values from the default thread pool profile for keep alive time, rejection policy and other
* parameters which cannot be specified.
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @param poolSize the core pool size
* @param maxPoolSize the maximum pool size
* @return the created thread pool
*/
ExecutorService newThreadPool(Object source, String name, int poolSize, int maxPoolSize);
/**
* Creates a new single-threaded thread pool. This is often used for background threads.
* <p/>
* Notice that there will always be a single thread in the pool. If you want the pool to be able to shrink to no
* threads, then use the <tt>newThreadPool</tt> method, and use 0 in core pool size, and 1 in max pool size.
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @return the created thread pool
*/
ExecutorService newSingleThreadExecutor(Object source, String name);
/**
* Creates a new cached thread pool.
* <p/>
* <b>Important:</b> Using cached thread pool should be used by care as they have no upper bound on created threads,
* and have no task backlog, and can therefore overload the JVM.
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @return the created thread pool
*/
ExecutorService newCachedThreadPool(Object source, String name);
/**
* Creates a new fixed thread pool (the pool will not grow or shrink but has a fixed number of threads constantly).
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @param poolSize the core pool size
* @return the created thread pool
*/
ExecutorService newFixedThreadPool(Object source, String name, int poolSize);
/**
* Creates a new scheduled thread pool.
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @param poolSize the core pool size
* @return the created thread pool
*/
ScheduledExecutorService newScheduledThreadPool(Object source, String name, int poolSize);
/**
* Creates a new single-threaded thread pool. This is often used for background threads.
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @return the created thread pool
*/
ScheduledExecutorService newSingleThreadScheduledExecutor(Object source, String name);
/**
* Creates a new scheduled thread pool using a profile
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @param profile the profile with the thread pool settings to use
* @return created thread pool
*/
ScheduledExecutorService newScheduledThreadPool(Object source, String name, ThreadPoolProfile profile);
/**
* Creates a new scheduled thread pool using a profile id
*
* @param source the source object, usually it should be <tt>this</tt> passed in as parameter
* @param name name which is appended to the thread name
* @param profileId the id of the profile with the thread pool settings to use
* @return created thread pool
*/
ScheduledExecutorService newScheduledThreadPool(Object source, String name, String profileId);
/**
* Shutdown the given executor service (<b>not</b> graceful).
* <p/>
* This implementation will issue a regular shutdown of the executor service, ie calling
* {@link java.util.concurrent.ExecutorService#shutdown()} and return.
*
* @param executorService the executor service to shutdown
* @see java.util.concurrent.ExecutorService#shutdown()
*/
void shutdown(ExecutorService executorService);
/**
* Shutdown the given executor service graceful at first, and then aggressively if the await termination timeout was
* hit.
* <p/>
* Will try to perform an orderly shutdown by giving the running threads time to complete tasks, before going more
* aggressively by doing a {@link #shutdownNow(java.util.concurrent.ExecutorService)} which forces a shutdown. The
* {@link #getShutdownAwaitTermination()} is used as timeout value waiting for orderly shutdown to complete
* normally, before going aggressively.
*
* @param executorService the executor service to shutdown
* @see java.util.concurrent.ExecutorService#shutdown()
* @see #getShutdownAwaitTermination()
*/
void shutdownGraceful(ExecutorService executorService);
/**
* Shutdown the given executor service graceful at first, and then aggressively if the await termination timeout was
* hit.
* <p/>
* Will try to perform an orderly shutdown by giving the running threads time to complete tasks, before going more
* aggressively by doing a {@link #shutdownNow(java.util.concurrent.ExecutorService)} which forces a shutdown. The
* parameter <tt>shutdownAwaitTermination</tt> is used as timeout value waiting for orderly shutdown to complete
* normally, before going aggressively.
*
* @param executorService the executor service to shutdown
* @param shutdownAwaitTermination timeout in millis to wait for orderly shutdown
* @see java.util.concurrent.ExecutorService#shutdown()
*/
void shutdownGraceful(ExecutorService executorService, long shutdownAwaitTermination);
/**
* Shutdown now the given executor service aggressively.
* <p/>
* This implementation will issues a regular shutdownNow of the executor service, ie calling
* {@link java.util.concurrent.ExecutorService#shutdownNow()} and return.
*
* @param executorService the executor service to shutdown now
* @return list of tasks that never commenced execution
* @see java.util.concurrent.ExecutorService#shutdownNow()
*/
List<Runnable> shutdownNow(ExecutorService executorService);
/**
* Awaits the termination of the thread pool.
* <p/>
* This implementation will log every 2nd second at INFO level that we are waiting, so the end user can see we are
* not hanging in case it takes longer time to terminate the pool.
*
* @param executorService the thread pool
* @param shutdownAwaitTermination time in millis to use as timeout
* @return <tt>true</tt> if the pool is terminated, or <tt>false</tt> if we timed out
* @throws InterruptedException is thrown if we are interrupted during waiting
*/
boolean awaitTermination(ExecutorService executorService, long shutdownAwaitTermination) throws InterruptedException;
}
| ThreadFactoryListener |
java | processing__processing4 | java/test/processing/mode/java/JavaFxRuntimePathFactoryTest.java | {
"start": 1024,
"end": 2122
} | class ____ {
private RuntimePathBuilder.RuntimePathFactoryStrategy factory;
private JavaMode testMode;
private List<ImportStatement> testImports;
private Sketch testSketch;
private List<String> classpath;
@Before
public void setUp() throws Exception {
RuntimePathBuilder builder = new RuntimePathBuilder();
factory = builder::buildJavaFxRuntimePath;
testMode = RuntimePathFactoryTestUtil.createTestJavaMode();
testImports = RuntimePathFactoryTestUtil.createTestImports();
testSketch = RuntimePathFactoryTestUtil.createTestSketch();
classpath = factory.buildClasspath(testMode, testImports, testSketch);
}
@Test
public void testBuildClasspathSize() {
assertEquals(RuntimePathBuilder.JAVA_FX_JARS.length, classpath.size());
}
@Test
public void testBuildClasspathValues() {
boolean foundTarget = false;
for (String entry : classpath) {
boolean justFound = entry.contains("javafx.base.jar") && entry.contains("lib");
foundTarget = foundTarget || justFound;
}
assertTrue(foundTarget);
}
} | JavaFxRuntimePathFactoryTest |
java | grpc__grpc-java | examples/example-dualstack/src/main/java/io/grpc/examples/dualstack/ExampleDualStackNameResolver.java | {
"start": 1140,
"end": 3159
} | class ____ extends NameResolver {
static public final int[] SERVER_PORTS = {50051, 50052, 50053};
// This is a fake name resolver, so we just hard code the address here.
private static final ImmutableMap<String, List<List<SocketAddress>>> addrStore =
ImmutableMap.<String, List<List<SocketAddress>>>builder()
.put("lb.example.grpc.io",
Arrays.stream(SERVER_PORTS)
.mapToObj(port -> getLocalAddrs(port))
.collect(Collectors.toList())
)
.build();
private Listener2 listener;
private final URI uri;
public ExampleDualStackNameResolver(URI targetUri) {
this.uri = targetUri;
}
private static List<SocketAddress> getLocalAddrs(int port) {
return Arrays.asList(
new InetSocketAddress("127.0.0.1", port),
new InetSocketAddress("::1", port));
}
@Override
public String getServiceAuthority() {
return uri.getPath().substring(1);
}
@Override
public void shutdown() {
}
@Override
public void start(Listener2 listener) {
this.listener = listener;
this.resolve();
}
@Override
public void refresh() {
this.resolve();
}
private void resolve() {
List<List<SocketAddress>> addresses = addrStore.get(uri.getPath().substring(1));
try {
List<EquivalentAddressGroup> eagList = new ArrayList<>();
for (List<SocketAddress> endpoint : addresses) {
// every server is an EquivalentAddressGroup, so they can be accessed randomly
eagList.add(new EquivalentAddressGroup(endpoint));
}
this.listener.onResult(ResolutionResult.newBuilder().setAddresses(eagList).build());
} catch (Exception e){
// when error occurs, notify listener
this.listener.onError(Status.UNAVAILABLE.withDescription("Unable to resolve host ").withCause(e));
}
}
}
| ExampleDualStackNameResolver |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java | {
"start": 54985,
"end": 55576
} | class ____ {
private final Object actual = Period.ofYears(1);
@Test
void createAssert() {
// WHEN
AbstractPeriodAssert<?> result = PERIOD.createAssert(actual);
// THEN
result.hasYears(1);
}
@Test
void createAssert_with_ValueProvider() {
// GIVEN
ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual);
// WHEN
AbstractPeriodAssert<?> result = PERIOD.createAssert(valueProvider);
// THEN
result.hasYears(1);
verify(valueProvider).apply(Period.class);
}
}
@Nested
| Period_Factory |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/runtime/ConnectorConfigTest.java | {
"start": 2604,
"end": 2669
} | class ____ extends Connector {
}
public static | TestConnector |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WhatsAppEndpointBuilderFactory.java | {
"start": 1545,
"end": 2422
} | interface ____
extends
EndpointProducerBuilder {
default AdvancedWhatsAppEndpointBuilder advanced() {
return (AdvancedWhatsAppEndpointBuilder) this;
}
/**
* The authorization access token taken from whatsapp-business
* dashboard.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: security
*
* @param authorizationToken the value to set
* @return the dsl builder
*/
default WhatsAppEndpointBuilder authorizationToken(String authorizationToken) {
doSetProperty("authorizationToken", authorizationToken);
return this;
}
}
/**
* Advanced builder for endpoint for the WhatsApp component.
*/
public | WhatsAppEndpointBuilder |
java | grpc__grpc-java | opentelemetry/src/main/java/io/grpc/opentelemetry/GrpcOpenTelemetry.java | {
"start": 13918,
"end": 16181
} | class ____ {
private OpenTelemetry openTelemetrySdk = OpenTelemetry.noop();
private final List<OpenTelemetryPlugin> plugins = new ArrayList<>();
private final Collection<String> optionalLabels = new ArrayList<>();
private final Map<String, Boolean> enableMetrics = new HashMap<>();
private boolean disableAll;
private Builder() {}
/**
* Sets the {@link io.opentelemetry.api.OpenTelemetry} entrypoint to use. This can be used to
* configure OpenTelemetry by returning the instance created by a
* {@code io.opentelemetry.sdk.OpenTelemetrySdkBuilder}.
*/
public Builder sdk(OpenTelemetry sdk) {
this.openTelemetrySdk = sdk;
return this;
}
Builder plugin(OpenTelemetryPlugin plugin) {
plugins.add(checkNotNull(plugin, "plugin"));
return this;
}
/**
* Adds optionalLabelKey to all the metrics that can provide value for the
* optionalLabelKey.
*/
public Builder addOptionalLabel(String optionalLabelKey) {
this.optionalLabels.add(optionalLabelKey);
return this;
}
/**
* Enables the specified metrics for collection and export. By default, only a subset of
* metrics are enabled.
*/
public Builder enableMetrics(Collection<String> enableMetrics) {
for (String metric : enableMetrics) {
this.enableMetrics.put(metric, true);
}
return this;
}
/**
* Disables the specified metrics from being collected and exported.
*/
public Builder disableMetrics(Collection<String> disableMetrics) {
for (String metric : disableMetrics) {
this.enableMetrics.put(metric, false);
}
return this;
}
/**
* Disable all metrics. If set to true all metrics must be explicitly enabled.
*/
public Builder disableAllMetrics() {
this.enableMetrics.clear();
this.disableAll = true;
return this;
}
Builder enableTracing(boolean enable) {
ENABLE_OTEL_TRACING = enable;
return this;
}
/**
* Returns a new {@link GrpcOpenTelemetry} built with the configuration of this {@link
* Builder}.
*/
public GrpcOpenTelemetry build() {
return new GrpcOpenTelemetry(this);
}
}
}
| Builder |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java | {
"start": 1050,
"end": 3380
} | class ____ {
private ByteArrayHttpMessageConverter converter;
@BeforeEach
void setUp() {
converter = new ByteArrayHttpMessageConverter();
}
@Test
void canRead() {
assertThat(converter.canRead(byte[].class, new MediaType("application", "octet-stream"))).isTrue();
}
@Test
void canWrite() {
assertThat(converter.canWrite(byte[].class, new MediaType("application", "octet-stream"))).isTrue();
assertThat(converter.canWrite(byte[].class, MediaType.ALL)).isTrue();
}
@Test
void read() throws IOException {
byte[] body = new byte[]{0x1, 0x2};
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
inputMessage.getHeaders().setContentType(new MediaType("application", "octet-stream"));
byte[] result = converter.read(byte[].class, inputMessage);
assertThat(result).as("Invalid result").isEqualTo(body);
}
@Test
void readWithContentLengthHeaderSet() throws IOException {
byte[] body = new byte[]{0x1, 0x2, 0x3, 0x4, 0x5};
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
inputMessage.getHeaders().setContentType(new MediaType("application", "octet-stream"));
inputMessage.getHeaders().setContentLength(body.length);
byte[] result = converter.read(byte[].class, inputMessage);
assertThat(result).as("Invalid result").isEqualTo(body);
}
@Test
void write() throws IOException {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
byte[] body = new byte[]{0x1, 0x2};
converter.write(body, null, outputMessage);
assertThat(outputMessage.getBodyAsBytes()).as("Invalid result").isEqualTo(body);
assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_OCTET_STREAM);
assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(2);
}
@Test
void repeatableWrites() throws IOException {
MockHttpOutputMessage outputMessage1 = new MockHttpOutputMessage();
byte[] body = new byte[]{0x1, 0x2};
assertThat(converter.supportsRepeatableWrites(body)).isTrue();
converter.write(body, null, outputMessage1);
assertThat(outputMessage1.getBodyAsBytes()).isEqualTo(body);
MockHttpOutputMessage outputMessage2 = new MockHttpOutputMessage();
converter.write(body, null, outputMessage2);
assertThat(outputMessage2.getBodyAsBytes()).isEqualTo(body);
}
}
| ByteArrayHttpMessageConverterTests |
java | elastic__elasticsearch | x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/action/TransportStopILMActionTests.java | {
"start": 1297,
"end": 2904
} | class ____ extends ESTestCase {
public void testStopILMClusterStatePriorityIsImmediate() {
ClusterService clusterService = mock(ClusterService.class);
ThreadPool threadPool = mock(ThreadPool.class);
TransportService transportService = MockUtils.setupTransportServiceWithThreadpoolExecutor(threadPool);
TransportStopILMAction transportStopILMAction = new TransportStopILMAction(
transportService,
clusterService,
threadPool,
mock(ActionFilters.class),
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
Task task = new Task(
randomLong(),
"transport",
ILMActions.STOP.name(),
"description",
new TaskId(randomLong() + ":" + randomLong()),
Map.of()
);
StopILMRequest request = new StopILMRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT);
transportStopILMAction.masterOperation(task, request, ClusterState.EMPTY_STATE, ActionListener.noop());
verify(clusterService).submitUnbatchedStateUpdateTask(
eq("ilm_operation_mode_update[stopping]"),
argThat(new ArgumentMatcher<AckedClusterStateUpdateTask>() {
Priority actualPriority = null;
@Override
public boolean matches(AckedClusterStateUpdateTask other) {
actualPriority = other.priority();
return actualPriority == Priority.IMMEDIATE;
}
})
);
}
}
| TransportStopILMActionTests |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/calcite/sql/SqlUtil.java | {
"start": 51165,
"end": 52019
} | class ____ extends BarfingInvocationHandler {
private final String databaseProductName;
private final String identifierQuoteString;
public DatabaseMetaDataInvocationHandler(
String databaseProductName, String identifierQuoteString) {
this.databaseProductName = databaseProductName;
this.identifierQuoteString = identifierQuoteString;
}
public String getDatabaseProductName() throws SQLException {
return databaseProductName;
}
public String getIdentifierQuoteString() throws SQLException {
return identifierQuoteString;
}
}
/**
* Walks over a {@link org.apache.calcite.sql.SqlNode} tree and returns the ancestry stack when
* it finds a given node.
*/
private static | DatabaseMetaDataInvocationHandler |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/dataframe/process/AnalysisFieldInfo.java | {
"start": 591,
"end": 1293
} | class ____ implements DataFrameAnalysis.FieldInfo {
private final ExtractedFields extractedFields;
AnalysisFieldInfo(ExtractedFields extractedFields) {
this.extractedFields = Objects.requireNonNull(extractedFields);
}
@Override
public Set<String> getTypes(String field) {
Optional<ExtractedField> extractedField = extractedFields.getAllFields().stream().filter(f -> f.getName().equals(field)).findAny();
return extractedField.isPresent() ? extractedField.get().getTypes() : null;
}
@Override
public Long getCardinality(String field) {
return extractedFields.getCardinalitiesForFieldsWithConstraints().get(field);
}
}
| AnalysisFieldInfo |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/criteria/JpaCoalesce.java | {
"start": 336,
"end": 666
} | interface ____<T> extends JpaExpression<T>, CriteriaBuilder.Coalesce<T> {
@Override
JpaCoalesce<T> value(@Nullable T value);
@Override
JpaCoalesce<T> value(Expression<? extends T> value);
JpaCoalesce<T> value(JpaExpression<? extends T> value);
@SuppressWarnings("unchecked")
JpaCoalesce<T> values(T... values);
}
| JpaCoalesce |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTest.java | {
"start": 26691,
"end": 34721
} | class ____ implements SourceEvent, DynamicFilteringInfo {}
CoordinatorStore store = new CoordinatorStoreImpl();
store.putIfAbsent(listeningID, new SourceEventWrapper(new TestDynamicFilteringEvent()));
final SourceCoordinator<?, ?> coordinator =
new SourceCoordinator<>(
new JobID(),
OPERATOR_NAME,
createMockSource(),
context,
store,
WatermarkAlignmentParams.WATERMARK_ALIGNMENT_DISABLED,
listeningID);
assertThat(coordinator.inferSourceParallelismAsync(2, 1).get()).isEqualTo(2);
}
@Test
void testDuplicateRedistribution() throws Exception {
final List<MockSourceSplit> splits =
Arrays.asList(
new MockSourceSplit(0), new MockSourceSplit(1), new MockSourceSplit(2));
testRedistribution(
(coordinator) -> {
registerReader(coordinator, 0, 0, splits);
registerReader(coordinator, 1, 0, Collections.emptyList());
registerReader(coordinator, 2, 0, Collections.emptyList());
waitForCoordinatorToProcessActions();
checkAddSplitEvents(new int[][] {new int[] {1}, new int[] {1}, new int[] {1}});
// duplicate registration
registerReader(coordinator, 0, 0, splits);
waitForCoordinatorToProcessActions();
// split 1,2,3 won't be sent again.
checkAddSplitEvents(new int[][] {new int[] {1}, new int[] {1}, new int[] {1}});
});
}
@Test
void testRedistributionInPartialRestartBeforeAnyCheckpoint() throws Exception {
final List<MockSourceSplit> splits =
Arrays.asList(
new MockSourceSplit(0), new MockSourceSplit(1), new MockSourceSplit(2));
testRedistribution(
(coordinator) -> {
registerReader(coordinator, 0, 0, splits);
registerReader(coordinator, 1, 0, Collections.emptyList());
registerReader(coordinator, 2, 0, Collections.emptyList());
waitForCoordinatorToProcessActions();
checkAddSplitEvents(new int[][] {new int[] {1}, new int[] {1}, new int[] {1}});
coordinator.subtaskReset(0, 0);
setReaderTaskReady(coordinator, 0, 1);
registerReader(coordinator, 0, 1, splits);
waitForCoordinatorToProcessActions();
checkAddSplitEvents(
new int[][] {new int[] {1, 1}, new int[] {1}, new int[] {1}});
});
}
@Test
void testRedistributionInPartialRestartAfterCheckpoint() throws Exception {
final List<MockSourceSplit> splits =
Arrays.asList(
new MockSourceSplit(0), new MockSourceSplit(1), new MockSourceSplit(2));
testRedistribution(
(coordinator) -> {
registerReader(coordinator, 0, 0, splits);
registerReader(coordinator, 1, 0, Collections.emptyList());
registerReader(coordinator, 2, 0, Collections.emptyList());
waitForCoordinatorToProcessActions();
checkAddSplitEvents(new int[][] {new int[] {1}, new int[] {1}, new int[] {1}});
CompletableFuture<byte[]> fulture = new CompletableFuture<>();
coordinator.checkpointCoordinator(1, fulture);
fulture.get();
coordinator.subtaskReset(0, 0);
setReaderTaskReady(coordinator, 0, 1);
registerReader(
coordinator, 0, 1, Collections.singletonList(new MockSourceSplit(0)));
waitForCoordinatorToProcessActions();
checkAddSplitEvents(
new int[][] {new int[] {1, 1}, new int[] {1}, new int[] {1}});
});
}
void testRedistribution(
FutureConsumerWithException<
SourceCoordinator<MockSourceSplit, Set<MockSourceSplit>>, Exception>
consumer)
throws Exception {
try (final SplitEnumerator<MockSourceSplit, Set<MockSourceSplit>> splitEnumerator =
new MockSplitEnumerator(0, context);
final SourceCoordinator<MockSourceSplit, Set<MockSourceSplit>> coordinator =
new SourceCoordinator<>(
new JobID(),
OPERATOR_NAME,
new EnumeratorCreatingSource<>(() -> splitEnumerator),
context,
new CoordinatorStoreImpl(),
WatermarkAlignmentParams.WATERMARK_ALIGNMENT_DISABLED,
null)) {
coordinator.start();
setAllReaderTasksReady(coordinator);
consumer.accept(coordinator);
}
}
private void checkAddSplitEvents(int[][] expectedAssignedSplitNum) {
MockSourceSplitSerializer mockSourceSplitSerializer = new MockSourceSplitSerializer();
assertThat(expectedAssignedSplitNum.length).isEqualTo(NUM_SUBTASKS);
for (int i = 0; i < NUM_SUBTASKS; i++) {
List<OperatorEvent> sentEventsForSubtask = receivingTasks.getSentEventsForSubtask(i);
assertThat(sentEventsForSubtask).hasSize(expectedAssignedSplitNum[i].length);
for (int j = 0; j < sentEventsForSubtask.size(); j++) {
assertThat(sentEventsForSubtask.get(j)).isExactlyInstanceOf(AddSplitEvent.class);
List<MockSourceSplit> splits;
try {
splits =
((AddSplitEvent<MockSourceSplit>) sentEventsForSubtask.get(j))
.splits(mockSourceSplitSerializer);
} catch (Exception e) {
throw new RuntimeException();
}
assertThat(splits).hasSize(expectedAssignedSplitNum[i][j]);
}
}
}
// ------------------------------------------------------------------------
// test helpers
// ------------------------------------------------------------------------
private byte[] createCheckpointDataWithSerdeV0(Set<MockSourceSplit> splits) throws Exception {
final MockSplitEnumeratorCheckpointSerializer enumChkptSerializer =
new MockSplitEnumeratorCheckpointSerializer();
final DataOutputSerializer serializer = new DataOutputSerializer(32);
serializer.writeInt(SourceCoordinatorSerdeUtils.VERSION_0);
serializer.writeInt(enumChkptSerializer.getVersion());
final byte[] serializedEnumChkpt = enumChkptSerializer.serialize(splits);
serializer.writeInt(serializedEnumChkpt.length);
serializer.write(serializedEnumChkpt);
// Version 0 wrote number of reader, see FLINK-21452
serializer.writeInt(0);
// Version 0 wrote split assignment tracker
serializer.writeInt(0); // SplitSerializer version used in assignment tracker
serializer.writeInt(0); // Number of checkpoint in assignment tracker
return serializer.getCopyOfBuffer();
}
private static byte[] createEmptyCheckpoint() throws Exception {
return SourceCoordinator.writeCheckpointBytes(
Collections.emptySet(), new MockSplitEnumeratorCheckpointSerializer());
}
// ------------------------------------------------------------------------
// test mocks
// ------------------------------------------------------------------------
private static final | TestDynamicFilteringEvent |
java | quarkusio__quarkus | extensions/oidc-client-filter/deployment/src/test/java/io/quarkus/oidc/client/filter/OidcClientFilterRevokedAccessTokenDevModeTest.java | {
"start": 4569,
"end": 4916
} | interface ____ {
@OidcClientFilter(NAMED_CLIENT)
@POST
String revokeAccessTokenAndRespond_NamedClient(String named);
@OidcClientFilter
@POST
String revokeAccessTokenAndRespond_DefaultClient(String named);
@POST
String noAccessToken();
}
public static | MyClient_MultipleMethods |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/topology/DefaultLogicalPipelinedRegion.java | {
"start": 1202,
"end": 2310
} | class ____ implements LogicalPipelinedRegion {
private final Map<JobVertexID, LogicalVertex> vertexById;
public DefaultLogicalPipelinedRegion(final Set<? extends LogicalVertex> logicalVertices) {
checkNotNull(logicalVertices);
this.vertexById =
logicalVertices.stream()
.collect(Collectors.toMap(LogicalVertex::getId, Function.identity()));
}
@Override
public Iterable<? extends LogicalVertex> getVertices() {
return vertexById.values();
}
@Override
public LogicalVertex getVertex(JobVertexID vertexId) {
return vertexById.get(vertexId);
}
@Override
public boolean contains(JobVertexID vertexId) {
return vertexById.containsKey(vertexId);
}
@Override
public String toString() {
return "DefaultLogicalPipelinedRegion{"
+ "vertexIDs="
+ vertexById.values().stream()
.map(LogicalVertex::getId)
.collect(Collectors.toList())
+ '}';
}
}
| DefaultLogicalPipelinedRegion |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/result/view/UrlBasedViewResolver.java | {
"start": 3568,
"end": 4129
} | class ____ is assignable to the required view class
* (by default: AbstractUrlBasedView)
* @see #requiredViewClass()
* @see #instantiateView()
* @see AbstractUrlBasedView
*/
public void setViewClass(@Nullable Class<?> viewClass) {
if (viewClass != null && !requiredViewClass().isAssignableFrom(viewClass)) {
String name = viewClass.getName();
throw new IllegalArgumentException("Given view class [" + name + "] " +
"is not of type [" + requiredViewClass().getName() + "]");
}
this.viewClass = viewClass;
}
/**
* Return the view | that |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/serialization/SerializerConfigImplTest.java | {
"start": 11514,
"end": 11941
} | class ____ extends Serializer<SerializerConfigImplTest>
implements Serializable {
@Override
public void write(Kryo kryo, Output output, SerializerConfigImplTest object) {}
@Override
public SerializerConfigImplTest read(
Kryo kryo, Input input, Class<? extends SerializerConfigImplTest> type) {
return null;
}
}
private static | TestSerializer1 |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei.java | {
"start": 177,
"end": 672
} | class ____ extends TestCase {
public void test_for_sepcial_chars() throws Exception {
String text = "{\"answerAllow\":true,\"atUsers\":[],\"desc\":\"Halios 1000M \\\"Puck\\\"很微众的品牌,几乎全靠玩家口口相传\"} ";
JSONObject obj = JSON.parseObject(text);
Assert.assertEquals(true, obj.get("answerAllow"));;
Assert.assertEquals(0, obj.getJSONArray("atUsers").size());;
Assert.assertEquals("Halios 1000M \"Puck\"很微众的品牌,几乎全靠玩家口口相传", obj.get("desc"));;
}
}
| Bug_for_yanpei |
java | elastic__elasticsearch | modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/MustachePlugin.java | {
"start": 1596,
"end": 3321
} | class ____ extends Plugin implements ScriptPlugin, ActionPlugin, SearchPlugin {
public static final ActionType<SearchTemplateResponse> SEARCH_TEMPLATE_ACTION = new ActionType<>("indices:data/read/search/template");
public static final ActionType<MultiSearchTemplateResponse> MULTI_SEARCH_TEMPLATE_ACTION = new ActionType<>(
"indices:data/read/msearch/template"
);
@Override
public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) {
return new MustacheScriptEngine(settings);
}
@Override
public List<ActionHandler> getActions() {
return Arrays.asList(
new ActionHandler(SEARCH_TEMPLATE_ACTION, TransportSearchTemplateAction.class),
new ActionHandler(MULTI_SEARCH_TEMPLATE_ACTION, TransportMultiSearchTemplateAction.class)
);
}
@Override
public List<RestHandler> getRestHandlers(
Settings settings,
NamedWriteableRegistry namedWriteableRegistry,
RestController restController,
ClusterSettings clusterSettings,
IndexScopedSettings indexScopedSettings,
SettingsFilter settingsFilter,
IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<DiscoveryNodes> nodesInCluster,
Predicate<NodeFeature> clusterSupportsFeature
) {
return Arrays.asList(
new RestSearchTemplateAction(clusterSupportsFeature, settings),
new RestMultiSearchTemplateAction(settings),
new RestRenderSearchTemplateAction()
);
}
@Override
public List<Setting<?>> getSettings() {
return List.of(MustacheScriptEngine.MUSTACHE_RESULT_SIZE_LIMIT);
}
}
| MustachePlugin |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ExtensionContextExecutionTests.java | {
"start": 2346,
"end": 2383
} | class ____ extends Parent {
}
static | A |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/hash/ReOpenableHashPartition.java | {
"start": 1405,
"end": 6983
} | class ____<BT, PT> extends HashPartition<BT, PT> {
protected int initialPartitionBuffersCount =
-1; // stores the number of buffers used for an in-memory partition after the build
// phase has finished.
private FileIOChannel.ID initialBuildSideChannel =
null; // path to initial build side contents (only for in-memory partitions)
private BlockChannelWriter<MemorySegment> initialBuildSideWriter = null;
private boolean isRestored = false; // marks a restored partition
int getInitialPartitionBuffersCount() {
if (initialPartitionBuffersCount == -1) {
throw new RuntimeException(
"Hash Join: Bug: This partition is most likely a spilled partition that is not restorable");
}
return initialPartitionBuffersCount;
}
ReOpenableHashPartition(
TypeSerializer<BT> buildSideAccessors,
TypeSerializer<PT> probeSideAccessors,
int partitionNumber,
int recursionLevel,
MemorySegment initialBuffer,
MemorySegmentSource memSource,
int segmentSize) {
super(
buildSideAccessors,
probeSideAccessors,
partitionNumber,
recursionLevel,
initialBuffer,
memSource,
segmentSize);
}
@Override
public int finalizeProbePhase(
List<MemorySegment> freeMemory,
List<HashPartition<BT, PT>> spilledPartitions,
boolean keepUnprobedSpilledPartitions)
throws IOException {
if (furtherPartitioning || recursionLevel != 0 || isRestored) {
if (isInMemory() && initialBuildSideChannel != null && !isRestored) {
// return the overflow segments
for (int k = 0; k < this.numOverflowSegments; k++) {
freeMemory.add(this.overflowSegments[k]);
}
this.overflowSegments = null;
this.numOverflowSegments = 0;
this.nextOverflowBucket = 0;
// we already returned the partitionBuffers via the returnQueue.
return 0;
}
return super.finalizeProbePhase(
freeMemory, spilledPartitions, keepUnprobedSpilledPartitions);
}
if (isInMemory()) {
return 0;
} else if (this.probeSideRecordCounter == 0 && !keepUnprobedSpilledPartitions) {
freeMemory.add(this.probeSideBuffer.getCurrentSegment());
// delete the spill files
this.probeSideChannel.close();
this.probeSideChannel.deleteChannel();
return 0;
} else {
this.probeSideBuffer.close();
this.probeSideChannel.close(); // finish pending write requests.
spilledPartitions.add(this);
return 1;
}
}
/**
* Spills this partition to disk. This method is invoked once after the initial open() method
*
* @return Number of memorySegments in the writeBehindBuffers!
*/
int spillInMemoryPartition(
FileIOChannel.ID targetChannel,
IOManager ioManager,
LinkedBlockingQueue<MemorySegment> writeBehindBuffers)
throws IOException {
this.initialPartitionBuffersCount = partitionBuffers.length; // for ReOpenableHashMap
this.initialBuildSideChannel = targetChannel;
initialBuildSideWriter =
ioManager.createBlockChannelWriter(targetChannel, writeBehindBuffers);
final int numSegments = this.partitionBuffers.length;
for (int i = 0; i < numSegments; i++) {
initialBuildSideWriter.writeBlock(partitionBuffers[i]);
}
this.partitionBuffers = null;
initialBuildSideWriter.close();
// num partitions are now in the writeBehindBuffers. We propagate this information back
return numSegments;
}
/**
* This method is called every time a multi-match hash map is opened again for a new probe
* input.
*
* @param ioManager
* @param availableMemory
* @throws IOException
*/
void restorePartitionBuffers(IOManager ioManager, List<MemorySegment> availableMemory)
throws IOException {
final BulkBlockChannelReader reader =
ioManager.createBulkBlockChannelReader(
this.initialBuildSideChannel,
availableMemory,
this.initialPartitionBuffersCount);
reader.close();
final List<MemorySegment> partitionBuffersFromDisk = reader.getFullSegments();
this.partitionBuffers =
(MemorySegment[])
partitionBuffersFromDisk.toArray(
new MemorySegment[partitionBuffersFromDisk.size()]);
this.overflowSegments = new MemorySegment[2];
this.numOverflowSegments = 0;
this.nextOverflowBucket = 0;
this.isRestored = true;
}
@Override
public void clearAllMemory(List<MemorySegment> target) {
if (initialBuildSideChannel != null) {
try {
this.initialBuildSideWriter.closeAndDelete();
} catch (IOException ioex) {
throw new RuntimeException(
"Error deleting the partition files. Some temporary files might not be removed.");
}
}
super.clearAllMemory(target);
}
}
| ReOpenableHashPartition |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/conversion/YearMonthIntervalPeriodConverter.java | {
"start": 1905,
"end": 3128
} | interface ____ extends Serializable {
java.time.Period construct(Integer internal);
}
// --------------------------------------------------------------------------------------------
// Factory method
// --------------------------------------------------------------------------------------------
public static YearMonthIntervalPeriodConverter create(DataType dataType) {
return create((YearMonthIntervalType) dataType.getLogicalType());
}
public static YearMonthIntervalPeriodConverter create(YearMonthIntervalType intervalType) {
return new YearMonthIntervalPeriodConverter(
createPeriodConstructor(intervalType.getResolution()));
}
private static PeriodConstructor createPeriodConstructor(YearMonthResolution resolution) {
switch (resolution) {
case YEAR:
return internal -> java.time.Period.ofYears(internal / 12);
case YEAR_TO_MONTH:
return internal -> java.time.Period.of(internal / 12, internal % 12, 0);
case MONTH:
return Period::ofMonths;
default:
throw new IllegalStateException();
}
}
}
| PeriodConstructor |
java | elastic__elasticsearch | client/rest/src/main/java/org/elasticsearch/client/RestClient.java | {
"start": 33189,
"end": 33695
} | class ____ implements Iterator<Node> {
private final Iterator<DeadNode> itr;
private DeadNodeIteratorAdapter(Iterator<DeadNode> itr) {
this.itr = itr;
}
@Override
public boolean hasNext() {
return itr.hasNext();
}
@Override
public Node next() {
return itr.next().node;
}
@Override
public void remove() {
itr.remove();
}
}
private | DeadNodeIteratorAdapter |
java | apache__flink | flink-core/src/main/java/org/apache/flink/util/ThrowableCatchingRunnable.java | {
"start": 1066,
"end": 1571
} | class ____ implements Runnable {
private final Consumer<Throwable> exceptionHandler;
private final Runnable runnable;
public ThrowableCatchingRunnable(Consumer<Throwable> exceptionHandler, Runnable runnable) {
this.exceptionHandler = exceptionHandler;
this.runnable = runnable;
}
@Override
public void run() {
try {
runnable.run();
} catch (Throwable t) {
exceptionHandler.accept(t);
}
}
}
| ThrowableCatchingRunnable |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/UnauthorizedExceptionMapper.java | {
"start": 734,
"end": 2637
} | class ____ implements ExceptionMapper<UnauthorizedException> {
private static final Logger log = Logger.getLogger(UnauthorizedExceptionMapper.class.getName());
private volatile CurrentVertxRequest currentVertxRequest;
CurrentVertxRequest currentVertxRequest() {
if (currentVertxRequest == null) {
currentVertxRequest = CDI.current().select(CurrentVertxRequest.class).get();
}
return currentVertxRequest;
}
@Override
public Response toResponse(UnauthorizedException exception) {
RoutingContext context = currentVertxRequest().getCurrent();
if (context != null) {
HttpAuthenticator authenticator = context.get(HttpAuthenticator.class.getName());
if (authenticator != null) {
ChallengeData challengeData = authenticator.getChallenge(context)
.await().indefinitely();
if (challengeData != null) {
Response.ResponseBuilder status = Response.status(challengeData.status);
if (challengeData.headerName != null) {
status.header(challengeData.headerName.toString(), challengeData.headerContent);
}
log.debugf("Returning an authentication challenge, status code: %d", challengeData.status);
return status.build();
} else {
log.debug("ChallengeData is null, returning HTTP status 401");
return Response.status(401).build();
}
} else {
log.error("HttpAuthenticator is not found, returning HTTP status 401");
}
} else {
log.error("RoutingContext is not found, returning HTTP status 401");
}
return Response.status(401).entity("Not authorized").build();
}
}
| UnauthorizedExceptionMapper |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ToStringReturnsNullTest.java | {
"start": 1297,
"end": 1662
} | class ____ {
// BUG: Diagnostic contains: ToStringReturnsNull
public String toString() {
return null;
}
}
""")
.doTest();
}
@Test
public void conditionalExpression() {
compilationHelper
.addSourceLines(
"Test.java",
"""
| Test |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/impl/producer/TopicPublishInfo.java | {
"start": 1202,
"end": 1519
} | class ____ {
private boolean orderTopic = false;
private boolean haveTopicRouterInfo = false;
private List<MessageQueue> messageQueueList = new ArrayList<>();
private volatile ThreadLocalIndex sendWhichQueue = new ThreadLocalIndex();
private TopicRouteData topicRouteData;
public | TopicPublishInfo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.