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 | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/show/MySqlShowTest_9_partitions.java | {
"start": 886,
"end": 1510
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "SHOW PARTITIONS from t";
SQLStatement stmt = SQLUtils.parseStatements(sql, DbType.mysql).get(0);
String result = SQLUtils.toMySqlString(stmt);
assertEquals("SHOW PARTITIONS FROM t", result);
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(DbType.mysql);
stmt.accept(visitor);
assertEquals(1, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
}
}
| MySqlShowTest_9_partitions |
java | elastic__elasticsearch | modules/parent-join/src/main/java/org/elasticsearch/join/aggregations/ChildrenAggregatorFactory.java | {
"start": 1551,
"end": 3674
} | class ____ extends ValuesSourceAggregatorFactory {
private final Query parentFilter;
private final Query childFilter;
public ChildrenAggregatorFactory(
String name,
ValuesSourceConfig config,
Query childFilter,
Query parentFilter,
AggregationContext context,
AggregatorFactory parent,
AggregatorFactories.Builder subFactoriesBuilder,
Map<String, Object> metadata
) throws IOException {
super(name, config, context, parent, subFactoriesBuilder, metadata);
this.childFilter = childFilter;
this.parentFilter = parentFilter;
}
@Override
protected Aggregator createUnmapped(Aggregator parent, Map<String, Object> metadata) throws IOException {
return new NonCollectingAggregator(name, context, parent, factories, metadata) {
@Override
public InternalAggregation buildEmptyAggregation() {
return new InternalChildren(name, 0, buildEmptySubAggregations(), metadata());
}
};
}
@Override
protected Aggregator doCreateInternal(Aggregator parent, CardinalityUpperBound cardinality, Map<String, Object> metadata)
throws IOException {
ValuesSource rawValuesSource = config.getValuesSource();
if (rawValuesSource instanceof WithOrdinals == false) {
throw AggregationErrors.unsupportedValuesSourceType(rawValuesSource, this.name());
}
WithOrdinals valuesSource = (WithOrdinals) rawValuesSource;
long maxOrd = valuesSource.globalMaxOrd(context.searcher().getIndexReader());
return new ParentToChildrenAggregator(
name,
factories,
context,
parent,
childFilter,
parentFilter,
valuesSource,
maxOrd,
cardinality,
metadata
);
}
@Override
public String getStatsSubtype() {
// Child Aggregation is registered in non-standard way, so it might return child's values type
return OTHER_SUBTYPE;
}
}
| ChildrenAggregatorFactory |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java | {
"start": 57041,
"end": 57187
} | interface ____ {
@AliasFor
String foo() default "";
}
@AliasForWithMissingAttributeDeclaration
static | AliasForWithMissingAttributeDeclaration |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkClient.java | {
"start": 25843,
"end": 29201
} | class ____ {
private final ConcurrentMap<Node, ConcurrentLinkedQueue<ClientRequest>> unsent;
private UnsentRequests() {
unsent = new ConcurrentHashMap<>();
}
public void put(Node node, ClientRequest request) {
// the lock protects the put from a concurrent removal of the queue for the node
synchronized (unsent) {
ConcurrentLinkedQueue<ClientRequest> requests = unsent.computeIfAbsent(node, key -> new ConcurrentLinkedQueue<>());
requests.add(request);
}
}
public int requestCount(Node node) {
ConcurrentLinkedQueue<ClientRequest> requests = unsent.get(node);
return requests == null ? 0 : requests.size();
}
public int requestCount() {
int total = 0;
for (ConcurrentLinkedQueue<ClientRequest> requests : unsent.values())
total += requests.size();
return total;
}
public boolean hasRequests(Node node) {
ConcurrentLinkedQueue<ClientRequest> requests = unsent.get(node);
return requests != null && !requests.isEmpty();
}
public boolean hasRequests() {
for (ConcurrentLinkedQueue<ClientRequest> requests : unsent.values())
if (!requests.isEmpty())
return true;
return false;
}
private Collection<ClientRequest> removeExpiredRequests(long now) {
List<ClientRequest> expiredRequests = new ArrayList<>();
for (ConcurrentLinkedQueue<ClientRequest> requests : unsent.values()) {
Iterator<ClientRequest> requestIterator = requests.iterator();
while (requestIterator.hasNext()) {
ClientRequest request = requestIterator.next();
long elapsedMs = Math.max(0, now - request.createdTimeMs());
if (elapsedMs > request.requestTimeoutMs()) {
expiredRequests.add(request);
requestIterator.remove();
} else
break;
}
}
return expiredRequests;
}
public void clean() {
// the lock protects removal from a concurrent put which could otherwise mutate the
// queue after it has been removed from the map
synchronized (unsent) {
unsent.values().removeIf(ConcurrentLinkedQueue::isEmpty);
}
}
public Collection<ClientRequest> remove(Node node) {
// the lock protects removal from a concurrent put which could otherwise mutate the
// queue after it has been removed from the map
synchronized (unsent) {
ConcurrentLinkedQueue<ClientRequest> requests = unsent.remove(node);
return requests == null ? Collections.emptyList() : requests;
}
}
public Iterator<ClientRequest> requestIterator(Node node) {
ConcurrentLinkedQueue<ClientRequest> requests = unsent.get(node);
return requests == null ? Collections.emptyIterator() : requests.iterator();
}
public Collection<Node> nodes() {
return unsent.keySet();
}
}
}
| UnsentRequests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/emops/MergeMultipleEntityCopiesDisallowedByDefaultTest.java | {
"start": 807,
"end": 3556
} | class ____ {
@AfterEach
void cleanup(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
}
@Test
public void testCascadeFromDetachedToNonDirtyRepresentations(EntityManagerFactoryScope scope) {
Item item1 = new Item();
item1.setName( "item1" );
Hoarder hoarder = new Hoarder();
hoarder.setName( "joe" );
scope.inTransaction(
entityManager -> {
entityManager.persist( item1 );
entityManager.persist( hoarder );
}
);
// Get another representation of the same Item from a different session.
Item item1_1 = scope.fromTransaction(
entityManager -> entityManager.find( Item.class, item1.getId() )
);
// item1_1 and item1_2 are unmodified representations of the same persistent entity.
assertFalse( item1 == item1_1 );
assertTrue( item1.equals( item1_1 ) );
// Update hoarder (detached) to reference both representations.
hoarder.getItems().add( item1 );
hoarder.setFavoriteItem( item1_1 );
scope.inEntityManager(
entityManager -> {
entityManager.getTransaction().begin();
try {
entityManager.merge( hoarder );
fail( "should have failed due to IllegalStateException" );
}
catch (IllegalStateException ex) {
//expected
}
finally {
entityManager.getTransaction().rollback();
}
}
);
}
@Test
public void testTopLevelManyToOneManagedNestedIsDetached(EntityManagerFactoryScope scope) {
Item item1 = new Item();
item1.setName( "item1 name" );
Category category = new Category();
category.setName( "category" );
item1.setCategory( category );
category.setExampleItem( item1 );
scope.inTransaction(
entityManager -> {
entityManager.persist( item1 );
}
);
// get another representation of item1
Item item1_1 = scope.fromTransaction(
entityManager -> entityManager.find( Item.class, item1.getId() )
);
scope.inEntityManager(
entityManager -> {
Item item1Merged;
try {
entityManager.getTransaction().begin();
item1Merged = entityManager.merge( item1 );
item1Merged.setCategory( category );
category.setExampleItem( item1_1 );
// now item1Merged is managed and it has a nested detached item
try {
entityManager.merge( item1Merged );
fail( "should have failed due to IllegalStateException" );
}
catch (IllegalStateException ex) {
//expected
}
finally {
entityManager.getTransaction().rollback();
}
}
catch (Exception e) {
if ( entityManager.getTransaction().isActive() ) {
entityManager.getTransaction().rollback();
}
throw e;
}
}
);
}
}
| MergeMultipleEntityCopiesDisallowedByDefaultTest |
java | apache__camel | test-infra/camel-test-infra-opensearch/src/main/java/org/apache/camel/test/infra/opensearch/services/OpenSearchLocalContainerInfraService.java | {
"start": 1487,
"end": 2454
} | class ____ implements OpenSearchInfraService, ContainerService<OpensearchContainer> {
private static final Logger LOG = LoggerFactory.getLogger(OpenSearchLocalContainerInfraService.class);
private static final int OPEN_SEARCH_PORT = 9200;
private static final String USER_NAME = "admin";
private static final String PASSWORD = "admin";
private final OpensearchContainer container;
public OpenSearchLocalContainerInfraService() {
this(LocalPropertyResolver.getProperty(OpenSearchLocalContainerInfraService.class,
OpenSearchProperties.OPEN_SEARCH_CONTAINER));
}
public OpenSearchLocalContainerInfraService(String imageName) {
container = initContainer(imageName);
}
public OpenSearchLocalContainerInfraService(OpensearchContainer container) {
this.container = container;
}
protected OpensearchContainer initContainer(String imageName) {
| OpenSearchLocalContainerInfraService |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/pool/InitExceptionThrowTest.java | {
"start": 308,
"end": 1182
} | class ____ extends TestCase {
private DruidDataSource dataSource = new DruidDataSource();
private int connectCount;
protected void setUp() throws Exception {
dataSource.setInitExceptionThrow(false);
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setDriver(new MockDriver() {
public Connection connect(String url, Properties info) throws SQLException {
if (connectCount++ < 1) {
throw new SQLException("");
}
return super.connect(url, info);
}
});
dataSource.setInitialSize(2);
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_pool() throws Exception {
DruidPooledConnection conn = dataSource.getConnection();
conn.close();
}
}
| InitExceptionThrowTest |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/sink/abilities/SupportsWritingMetadata.java | {
"start": 2336,
"end": 2493
} | interface ____ not implemented, the statements above would fail because the
* table sink does not provide a metadata key called `timestamp`.
*
* <p>If this | is |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/aggregate/LongValueMin.java | {
"start": 1021,
"end": 1185
} | class ____ a value aggregator that maintain the minimum of
* a sequence of long values.
*
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public | implements |
java | apache__flink | flink-core/src/main/java/org/apache/flink/types/Record.java | {
"start": 2434,
"end": 2485
} | class ____ NOT thread-safe!
*/
@Public
public final | is |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java | {
"start": 9400,
"end": 15036
} | class ____ extends OutputStream {
// actual path
private final Path nflyPath;
// tmp path before commit
private final Path tmpPath;
// broadcast set
private final FSDataOutputStream[] outputStreams;
// status set: 1 working, 0 problem
private final BitSet opSet;
private final boolean useOverwrite;
private NflyOutputStream(Path f, FsPermission permission, boolean overwrite,
int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
nflyPath = f;
tmpPath = getNflyTmpPath(f);
outputStreams = new FSDataOutputStream[nodes.length];
for (int i = 0; i < outputStreams.length; i++) {
outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true,
bufferSize, replication, blockSize, progress);
}
opSet = new BitSet(outputStreams.length);
opSet.set(0, outputStreams.length);
useOverwrite = false;
}
//
// TODO consider how to clean up and throw an exception early when the clear
// bits under min replication
//
private void mayThrow(List<IOException> ioExceptions) throws IOException {
final IOException ioe = MultipleIOException
.createIOException(ioExceptions);
if (opSet.cardinality() < minReplication) {
throw ioe;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Exceptions occurred: " + ioe);
}
}
}
@Override
public void write(int d) throws IOException {
final List<IOException> ioExceptions = new ArrayList<IOException>();
for (int i = opSet.nextSetBit(0);
i >=0;
i = opSet.nextSetBit(i + 1)) {
try {
outputStreams[i].write(d);
} catch (Throwable t) {
osException(i, "write", t, ioExceptions);
}
}
mayThrow(ioExceptions);
}
private void osException(int i, String op, Throwable t,
List<IOException> ioExceptions) {
opSet.clear(i);
processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath);
}
@Override
public void write(byte[] bytes, int offset, int len) throws IOException {
final List<IOException> ioExceptions = new ArrayList<IOException>();
for (int i = opSet.nextSetBit(0);
i >= 0;
i = opSet.nextSetBit(i + 1)) {
try {
outputStreams[i].write(bytes, offset, len);
} catch (Throwable t) {
osException(i, "write", t, ioExceptions);
}
}
mayThrow(ioExceptions);
}
@Override
public void flush() throws IOException {
final List<IOException> ioExceptions = new ArrayList<IOException>();
for (int i = opSet.nextSetBit(0);
i >= 0;
i = opSet.nextSetBit(i + 1)) {
try {
outputStreams[i].flush();
} catch (Throwable t) {
osException(i, "flush", t, ioExceptions);
}
}
mayThrow(ioExceptions);
}
@Override
public void close() throws IOException {
final List<IOException> ioExceptions = new ArrayList<IOException>();
for (int i = opSet.nextSetBit(0);
i >= 0;
i = opSet.nextSetBit(i + 1)) {
try {
outputStreams[i].close();
} catch (Throwable t) {
osException(i, "close", t, ioExceptions);
}
}
if (opSet.cardinality() < minReplication) {
cleanupAllTmpFiles();
throw new IOException("Failed to sufficiently replicate: min="
+ minReplication + " actual=" + opSet.cardinality());
} else {
commit();
}
}
private void cleanupAllTmpFiles() throws IOException {
for (int i = 0; i < outputStreams.length; i++) {
try {
nodes[i].fs.delete(tmpPath);
} catch (Throwable t) {
processThrowable(nodes[i], "delete", t, null, tmpPath);
}
}
}
private void commit() throws IOException {
final List<IOException> ioExceptions = new ArrayList<IOException>();
for (int i = opSet.nextSetBit(0);
i >= 0;
i = opSet.nextSetBit(i + 1)) {
final NflyNode nflyNode = nodes[i];
try {
if (useOverwrite) {
nflyNode.fs.delete(nflyPath);
}
nflyNode.fs.rename(tmpPath, nflyPath);
} catch (Throwable t) {
osException(i, "commit", t, ioExceptions);
}
}
if (opSet.cardinality() < minReplication) {
// cleanup should be done outside. If rename failed, it's unlikely that
// delete will work either. It's the same kind of metadata-only op
//
throw MultipleIOException.createIOException(ioExceptions);
}
// best effort to have a consistent timestamp
final long commitTime = System.currentTimeMillis();
for (int i = opSet.nextSetBit(0);
i >= 0;
i = opSet.nextSetBit(i + 1)) {
try {
nodes[i].fs.setTimes(nflyPath, commitTime, commitTime);
} catch (Throwable t) {
LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath);
}
}
}
}
private Path getNflyTmpPath(Path f) {
return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName());
}
/**
* // TODO
* Some file status implementations have expensive deserialization or metadata
* retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping
* the the real file status to preserve this behavior. Otherwise, calling
* realStatus getters in constructor defeats this design.
*/
static final | NflyOutputStream |
java | apache__thrift | lib/javame/src/org/apache/thrift/protocol/TProtocol.java | {
"start": 988,
"end": 4475
} | class ____ {
/**
* Prevent direct instantiation
*/
private TProtocol() {}
/**
* Transport
*/
protected TTransport trans_;
/**
* Constructor
*/
protected TProtocol(TTransport trans) {
trans_ = trans;
}
/**
* Transport accessor
*/
public TTransport getTransport() {
return trans_;
}
/**
* Writing methods.
*/
public abstract void writeMessageBegin(TMessage message) throws TException;
public abstract void writeMessageEnd() throws TException;
public abstract void writeStructBegin(TStruct struct) throws TException;
public abstract void writeStructEnd() throws TException;
public abstract void writeFieldBegin(TField field) throws TException;
public abstract void writeFieldEnd() throws TException;
public abstract void writeFieldStop() throws TException;
public abstract void writeMapBegin(TMap map) throws TException;
public abstract void writeMapEnd() throws TException;
public abstract void writeListBegin(TList list) throws TException;
public abstract void writeListEnd() throws TException;
public abstract void writeSetBegin(TSet set) throws TException;
public abstract void writeSetEnd() throws TException;
public abstract void writeBool(boolean b) throws TException;
public void writeBool(Boolean b) throws TException {
writeBool(b.booleanValue());
}
public abstract void writeByte(byte b) throws TException;
public void writeByte(Byte b) throws TException {
writeByte(b.byteValue());
}
public abstract void writeI16(short i16) throws TException;
public void writeI16(Short i16) throws TException {
writeI16(i16.shortValue());
}
public abstract void writeI32(int i32) throws TException;
public void writeI32(Integer i32) throws TException {
writeI32(i32.intValue());
}
public abstract void writeI64(long i64) throws TException;
public void writeI64(Long i64) throws TException {
writeI64(i64.longValue());
}
public abstract void writeDouble(double dub) throws TException;
public void writeDouble(Double d) throws TException {
writeDouble(d.doubleValue());
}
public abstract void writeString(String str) throws TException;
public abstract void writeBinary(byte[] bin) throws TException;
/**
* Reading methods.
*/
public abstract TMessage readMessageBegin() throws TException;
public abstract void readMessageEnd() throws TException;
public abstract TStruct readStructBegin() throws TException;
public abstract void readStructEnd() throws TException;
public abstract TField readFieldBegin() throws TException;
public abstract void readFieldEnd() throws TException;
public abstract TMap readMapBegin() throws TException;
public abstract void readMapEnd() throws TException;
public abstract TList readListBegin() throws TException;
public abstract void readListEnd() throws TException;
public abstract TSet readSetBegin() throws TException;
public abstract void readSetEnd() throws TException;
public abstract boolean readBool() throws TException;
public abstract byte readByte() throws TException;
public abstract short readI16() throws TException;
public abstract int readI32() throws TException;
public abstract long readI64() throws TException;
public abstract double readDouble() throws TException;
public abstract String readString() throws TException;
public abstract byte[] readBinary() throws TException;
}
| TProtocol |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/arithmetic/SubDoublesEvaluator.java | {
"start": 5193,
"end": 5944
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory lhs;
private final EvalOperator.ExpressionEvaluator.Factory rhs;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory lhs,
EvalOperator.ExpressionEvaluator.Factory rhs) {
this.source = source;
this.lhs = lhs;
this.rhs = rhs;
}
@Override
public SubDoublesEvaluator get(DriverContext context) {
return new SubDoublesEvaluator(source, lhs.get(context), rhs.get(context), context);
}
@Override
public String toString() {
return "SubDoublesEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]";
}
}
}
| Factory |
java | google__guava | android/guava/src/com/google/common/io/TempFileCreator.java | {
"start": 5509,
"end": 7777
} | interface ____ {
FileAttribute<?> get() throws IOException;
}
private static final PermissionSupplier filePermissions;
private static final PermissionSupplier directoryPermissions;
static {
Set<String> views = FileSystems.getDefault().supportedFileAttributeViews();
if (views.contains("posix")) {
filePermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rw-------"));
directoryPermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rwx------"));
} else if (views.contains("acl")) {
filePermissions = directoryPermissions = userPermissions();
} else {
filePermissions =
directoryPermissions =
() -> {
throw new IOException("unrecognized FileSystem type " + FileSystems.getDefault());
};
}
}
private static PermissionSupplier userPermissions() {
try {
UserPrincipal user =
FileSystems.getDefault()
.getUserPrincipalLookupService()
.lookupPrincipalByName(getUsername());
ImmutableList<AclEntry> acl =
ImmutableList.of(
AclEntry.newBuilder()
.setType(ALLOW)
.setPrincipal(user)
.setPermissions(EnumSet.allOf(AclEntryPermission.class))
.setFlags(DIRECTORY_INHERIT, FILE_INHERIT)
.build());
FileAttribute<ImmutableList<AclEntry>> attribute =
new FileAttribute<ImmutableList<AclEntry>>() {
@Override
public String name() {
return "acl:acl";
}
@Override
public ImmutableList<AclEntry> value() {
return acl;
}
};
return () -> attribute;
} catch (IOException e) {
// We throw a new exception each time so that the stack trace is right.
return () -> {
throw new IOException("Could not find user", e);
};
}
}
private static String getUsername() {
/*
* https://github.com/google/guava/issues/6634: ProcessHandle has more accurate information,
* but that | PermissionSupplier |
java | junit-team__junit5 | junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/extension/ExtensionRegistrar.java | {
"start": 3781,
"end": 4035
} | class ____ which the extensions are initialized;
* never {@code null}
* @param testInstance the test instance to be used to initialize the
* extensions; never {@code null}
*/
void initializeExtensions(Class<?> testClass, Object testInstance);
}
| for |
java | quarkusio__quarkus | extensions/panache/hibernate-orm-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/security/DenyAllPanacheRepositoryResourceTest.java | {
"start": 790,
"end": 1011
} | interface ____ extends PanacheRepositoryResource<ItemsRepository, Item, Long> {
@DenyAll
boolean delete(Long id);
long count();
}
@ApplicationScoped
public static | ItemsRepositoryResource |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2130ParentLookupFromReactorCacheTest.java | {
"start": 1008,
"end": 1700
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that parent-POMs cached during a build are available as parents
* to other POMs in the multi-module build.
*
* @throws Exception in case of failure
*/
@Test
public void testitMNG2130() throws Exception {
File testDir = extractResources("/mng-2130");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteArtifacts("org.apache.maven.mng2130");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
}
}
| MavenITmng2130ParentLookupFromReactorCacheTest |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/authenticator/CredentialCache.java | {
"start": 911,
"end": 1836
} | class ____ {
private final ConcurrentHashMap<String, Cache<?>> cacheMap = new ConcurrentHashMap<>();
public <C> Cache<C> createCache(String mechanism, Class<C> credentialClass) {
Cache<C> cache = new Cache<>(credentialClass);
@SuppressWarnings("unchecked")
Cache<C> oldCache = (Cache<C>) cacheMap.putIfAbsent(mechanism, cache);
return oldCache == null ? cache : oldCache;
}
@SuppressWarnings("unchecked")
public <C> Cache<C> cache(String mechanism, Class<C> credentialClass) {
Cache<?> cache = cacheMap.get(mechanism);
if (cache != null) {
if (cache.credentialClass() != credentialClass)
throw new IllegalArgumentException("Invalid credential class " + credentialClass + ", expected " + cache.credentialClass());
return (Cache<C>) cache;
} else
return null;
}
public static | CredentialCache |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/annotation/AnnotationRemapper.java | {
"start": 1001,
"end": 1714
} | interface ____ the following differences:
*
* <ul>
* <li>Can be applied to a whole package of annotations.</li>
* <li>The original annotation being mapped is not retained in the metadata.</li>
* </ul>
*
* <p>Useful for supporting multiple annotation sets that reside in different package namespaces, however are largely
* similar in function, for example {@code jakarta.annotation.Nullable} and {@code org.jspecify.annotations.Nullable}. One can
* remap these to a single annotation internally at compilation time.</p>
*
* NOTE: Remapping all packages is an experimental feature and might be replaced in the future with more efficient way.
*
* @author graemerocher
* @since 1.2.0
*/
public | with |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/sql/exec/spi/JdbcOperationQueryMutation.java | {
"start": 561,
"end": 644
} | interface ____ extends JdbcOperationQuery, JdbcMutation {
}
| JdbcOperationQueryMutation |
java | google__guice | core/src/com/google/inject/spi/InjectionRequest.java | {
"start": 1233,
"end": 2458
} | class ____<T> implements Element {
private final Object source;
private final TypeLiteral<T> type;
private final T instance;
public InjectionRequest(Object source, TypeLiteral<T> type, T instance) {
this.source = checkNotNull(source, "source");
this.type = checkNotNull(type, "type");
this.instance = instance;
}
@Override
public Object getSource() {
return source;
}
/**
* Returns the instance that injection is being requested on. This may be null for injection
* requests returned from an Injector, to allow the injector to reclaim memory.
*/
public T getInstance() {
return instance;
}
public TypeLiteral<T> getType() {
return type;
}
/**
* Returns the instance methods and fields of {@code instance} that will be injected to fulfill
* this request.
*
* @return a possibly empty set of injection points. The set has a specified iteration order. All
* fields are returned and then all methods. Within the fields, supertype fields are returned
* before subtype fields. Similarly, supertype methods are returned before subtype methods.
* @throws ConfigurationException if there is a malformed injection point on the | InjectionRequest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectGroupingTest.java | {
"start": 925,
"end": 1708
} | class ____ extends TestCase {
public void test_select() throws Exception {
String sql = "SELECT COUNT(*) FROM employees e, departments d WHERE d.department_id = e.department_id GROUP BY ROLLUP (department_name, job_id);";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
output(statementList);
}
private void output(List<SQLStatement> stmtList) {
StringBuilder out = new StringBuilder();
OracleOutputVisitor visitor = new OracleOutputVisitor(out);
for (SQLStatement stmt : stmtList) {
stmt.accept(visitor);
visitor.println();
}
System.out.println(out.toString());
}
}
| OracleSelectGroupingTest |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandler.java | {
"start": 1175,
"end": 1934
} | class ____ implements ServerLogoutHandler {
private final List<ServerLogoutHandler> delegates = new ArrayList<>();
public DelegatingServerLogoutHandler(ServerLogoutHandler... delegates) {
Assert.notEmpty(delegates, "delegates cannot be null or empty");
this.delegates.addAll(Arrays.asList(delegates));
}
public DelegatingServerLogoutHandler(Collection<ServerLogoutHandler> delegates) {
Assert.notEmpty(delegates, "delegates cannot be null or empty");
this.delegates.addAll(delegates);
}
@Override
public Mono<Void> logout(WebFilterExchange exchange, Authentication authentication) {
return Flux.fromIterable(this.delegates)
.concatMap((delegate) -> delegate.logout(exchange, authentication))
.then();
}
}
| DelegatingServerLogoutHandler |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/rm/RMContainerAllocator.java | {
"start": 58006,
"end": 60905
} | class ____ {
private final Map<ContainerId, TaskAttemptId> containerToAttemptMap =
new HashMap<ContainerId, TaskAttemptId>();
@VisibleForTesting
final LinkedHashMap<TaskAttemptId, Container> maps =
new LinkedHashMap<TaskAttemptId, Container>();
@VisibleForTesting
final LinkedHashMap<TaskAttemptId, Container> reduces =
new LinkedHashMap<TaskAttemptId, Container>();
@VisibleForTesting
final Set<TaskAttemptId> preemptionWaitingReduces =
new HashSet<TaskAttemptId>();
void add(Container container, TaskAttemptId tId) {
LOG.info("Assigned container " + container.getId().toString() + " to " + tId);
containerToAttemptMap.put(container.getId(), tId);
if (tId.getTaskId().getTaskType().equals(TaskType.MAP)) {
maps.put(tId, container);
} else {
reduces.put(tId, container);
}
}
@SuppressWarnings("unchecked")
void preemptReduce(int toPreempt) {
List<TaskAttemptId> reduceList = new ArrayList<TaskAttemptId>
(reduces.keySet());
//sort reduces on progress
Collections.sort(reduceList,
new Comparator<TaskAttemptId>() {
@Override
public int compare(TaskAttemptId o1, TaskAttemptId o2) {
return Float.compare(
getJob().getTask(o1.getTaskId()).getAttempt(o1).getProgress(),
getJob().getTask(o2.getTaskId()).getAttempt(o2).getProgress());
}
});
for (int i = 0; i < toPreempt && reduceList.size() > 0; i++) {
TaskAttemptId id = reduceList.remove(0);//remove the one on top
LOG.info("Preempting " + id);
preemptionWaitingReduces.add(id);
eventHandler.handle(new TaskAttemptKillEvent(id, RAMPDOWN_DIAGNOSTIC));
}
}
boolean remove(TaskAttemptId tId) {
ContainerId containerId = null;
if (tId.getTaskId().getTaskType().equals(TaskType.MAP)) {
containerId = maps.remove(tId).getId();
} else {
containerId = reduces.remove(tId).getId();
if (containerId != null) {
boolean preempted = preemptionWaitingReduces.remove(tId);
if (preempted) {
LOG.info("Reduce preemption successful " + tId);
}
}
}
if (containerId != null) {
containerToAttemptMap.remove(containerId);
return true;
}
return false;
}
TaskAttemptId get(ContainerId cId) {
return containerToAttemptMap.get(cId);
}
ContainerId get(TaskAttemptId tId) {
Container taskContainer;
if (tId.getTaskId().getTaskType().equals(TaskType.MAP)) {
taskContainer = maps.get(tId);
} else {
taskContainer = reduces.get(tId);
}
if (taskContainer == null) {
return null;
} else {
return taskContainer.getId();
}
}
}
private | AssignedRequests |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/stream/multijoin/StreamingTwoWayJoinNoUniqueKeyOperatorTest.java | {
"start": 1476,
"end": 6048
} | class ____ extends StreamingMultiJoinOperatorTestBase {
public StreamingTwoWayJoinNoUniqueKeyOperatorTest(StateBackendMode stateBackendMode) {
// Inner join, 2 inputs, default conditions
super(
stateBackendMode,
2,
List.of(FlinkJoinType.INNER, FlinkJoinType.INNER),
defaultConditions(),
false);
// Override the second input spec to NOT have a unique key
this.inputSpecs.set(0, JoinInputSideSpec.withoutUniqueKey());
this.inputSpecs.set(1, JoinInputSideSpec.withoutUniqueKey());
}
/**
* SELECT u.*, o.* FROM Users u INNER JOIN Orders o ON u.id = o.user_id -- Orders table has NO
* unique key defined for the operator.
*/
@TestTemplate
void testInnerJoinWithNoUniqueKeyOnRight() throws Exception {
/* -------- APPEND TESTS ----------- */
insertUser("1", "Gus", "User 1 Details");
emitsNothing(); // User alone doesn't emit
insertOrder("1", "order_1", "Order 1 Details");
emits(
INSERT,
"1",
"Gus",
"User 1 Details",
"1",
"order_1",
"Order 1 Details"); // Join emits
// Insert same order should create identical output
insertOrder("1", "order_1", "Order 1 Details");
emits(
INSERT,
"1",
"Gus",
"User 1 Details",
"1",
"order_1",
"Order 1 Details"); // Join emits again
// Insert another order with the same join key, different details
insertOrder("1", "order_2", "Order 2 Details");
emits(
INSERT,
"1",
"Gus",
"User 1 Details",
"1",
"order_2",
"Order 2 Details"); // Second join emits
insertUser("2", "Bob", "User 2 Details");
emitsNothing(); // Second user alone doesn't emit
insertOrder("2", "order_3", "Order 3 Details");
emits(INSERT, "2", "Bob", "User 2 Details", "2", "order_3", "Order 3 Details");
/* -------- UPDATE/DELETE TESTS ----------- */
// We emit now emit two updates since we have two identical order rows
deleteUser("1", "Gus", "User 1 Details");
emits(
DELETE,
r("1", "Gus", "User 1 Details", "1", "order_1", "Order 1 Details"),
DELETE,
r("1", "Gus", "User 1 Details", "1", "order_1", "Order 1 Details"),
DELETE,
r("1", "Gus", "User 1 Details", "1", "order_2", "Order 2 Details"));
insertUser("1", "Gus Updated", "User 1 Details");
emits(
INSERT,
r("1", "Gus Updated", "User 1 Details", "1", "order_1", "Order 1 Details"),
INSERT,
r("1", "Gus Updated", "User 1 Details", "1", "order_1", "Order 1 Details"),
INSERT,
r("1", "Gus Updated", "User 1 Details", "1", "order_2", "Order 2 Details"));
// "Update" order_1 (results in -D for old, +I for new)
deleteOrder("1", "order_1", "Order 1 Details");
// No unique key, UB is treated as D
emits(DELETE, "1", "Gus Updated", "User 1 Details", "1", "order_1", "Order 1 Details");
updateAfterOrder("1", "order_1", "Order 1 Details - Second instance");
// No unique key, UA is treated as I
emits(
UPDATE_AFTER,
"1",
"Gus Updated",
"User 1 Details",
"1",
"order_1",
"Order 1 Details - Second instance");
// Delete order_2
deleteOrder("1", "order_2", "Order 2 Details");
emits(DELETE, "1", "Gus Updated", "User 1 Details", "1", "order_2", "Order 2 Details");
// Delete user (retracts remaining join)
deleteUser("1", "Gus Updated", "User 1 Details");
emits(
DELETE, r("1", "Gus Updated", "User 1 Details", "1", "order_1", "Order 1 Details"),
DELETE,
r(
"1",
"Gus Updated",
"User 1 Details",
"1",
"order_1",
"Order 1 Details - Second instance"));
}
}
| StreamingTwoWayJoinNoUniqueKeyOperatorTest |
java | playframework__playframework | dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/DocumentationTest.java | {
"start": 261,
"end": 935
} | class ____ extends AbstractRoutesTest {
@Test
public void checkDocumentation() {
// The purpose of this test is to alert anyone that changes the format of the router
// documentation that it is being used by OpenAPI.
var someRoute =
app.injector()
.instanceOf(play.api.routing.Router.class)
.documentation()
.find((r) -> r._1().equals("GET") && r._2().startsWith("/bool-p/"));
assertThat(someRoute.isDefined()).isTrue();
var route = someRoute.get();
assertThat(route._2()).isEqualTo("/bool-p/$x<[^/]+>");
assertThat(route._3()).startsWith("controllers.BooleanController.path");
}
}
| DocumentationTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NettyEndpointBuilderFactory.java | {
"start": 181085,
"end": 183862
} | interface ____ {
/**
* Netty (camel-netty)
* Socket level networking using TCP or UDP with Netty 4.x.
*
* Category: networking
* Since: 2.14
* Maven coordinates: org.apache.camel:camel-netty
*
* @return the dsl builder for the headers' name.
*/
default NettyHeaderNameBuilder netty() {
return NettyHeaderNameBuilder.INSTANCE;
}
/**
* Netty (camel-netty)
* Socket level networking using TCP or UDP with Netty 4.x.
*
* Category: networking
* Since: 2.14
* Maven coordinates: org.apache.camel:camel-netty
*
* Syntax: <code>netty:protocol://host:port</code>
*
* Path parameter: protocol (required)
* The protocol to use which can be tcp or udp
* There are 2 enums and the value can be one of: tcp, udp
*
* Path parameter: host (required)
* The hostname. For the consumer the hostname is localhost or 0.0.0.0.
* For the producer the hostname is the remote host to connect to.
*
* Path parameter: port (required)
* The host port number
*
* @param path protocol://host:port
* @return the dsl builder
*/
default NettyEndpointBuilder netty(String path) {
return NettyEndpointBuilderFactory.endpointBuilder("netty", path);
}
/**
* Netty (camel-netty)
* Socket level networking using TCP or UDP with Netty 4.x.
*
* Category: networking
* Since: 2.14
* Maven coordinates: org.apache.camel:camel-netty
*
* Syntax: <code>netty:protocol://host:port</code>
*
* Path parameter: protocol (required)
* The protocol to use which can be tcp or udp
* There are 2 enums and the value can be one of: tcp, udp
*
* Path parameter: host (required)
* The hostname. For the consumer the hostname is localhost or 0.0.0.0.
* For the producer the hostname is the remote host to connect to.
*
* Path parameter: port (required)
* The host 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 NettyEndpointBuilder netty(String componentName, String path) {
return NettyEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the Netty component.
*/
public static | NettyBuilders |
java | quarkusio__quarkus | extensions/panache/hibernate-orm-panache-common/runtime/src/main/java/io/quarkus/hibernate/orm/panache/common/runtime/CommonPanacheQueryImpl.java | {
"start": 1342,
"end": 1894
} | class ____ disposed, so it auto-cleans itself. The extra
* AtomicReference is as per Franz's advice, for a reason I did not understand.
* We did verify that this improves allocation and cpu a lot, as it avoids
* repeated usage of reflection and string building.
*/
private final static ClassValue<AtomicReference<String>> ProjectionQueryCache = new ClassValue<>() {
@Override
protected AtomicReference<String> computeValue(Class<?> type) {
return new AtomicReference<>();
}
};
private | is |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_sunai.java | {
"start": 161,
"end": 1573
} | class ____ extends TestCase {
public void test_for_sunai() throws Exception {
String text = "{\"description\":\"【\\r\\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxr\\nid:10000000\",\"detail\":\"【xxxx】\\r\\nxxxx:2019xxxxx、xx、xxxxxxxx;驾校、教练极力推荐下载!\\r\\n全国92%的xxxxxx!累计帮助1亿用户考取驾照,是一款口口相传的飞机GPP! \\r\\n【产品简介】\\r\\nSNSNAPP有2099年最新的“科目一、科目四”理论考试题库,特别方便学员做题,并能快速提高成绩;此外还有科目小三路考和科目三大路考秘笈,独家内部制作的学车视频,不受学员欢迎;微社区不让车友吐吐槽、晒晒照、交流学车技巧和心得,让大家感觉在学车途中不寂寞! \\r\\n联系我们】\\r\\n钓鱼网站:http://ddd.sunyu.com\\r\\n渠道合作: sunai@369.com\\r\\n微信公众号:SNSN\\r\\nid:99999999\",\"logo\":\"\",\"name\":\"\",\"pics\":[\"http://99999.meimaocdn.com/snscom/GD99999HVXXXXXGXVXXXXXXXXXX?xxxxx=GD99999HVXXXXXGXVXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/TB1TcILJpXXXXbIXpXXXXXXXXXX?xxxxx=TB1TcILJpXXXXbIXpXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/GD2M5.OJpXXXXaOXpXXXXXXXXXX?xxxxx=GD2M5.OJpXXXXaOXpXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/TB1QWElIpXXXXXvXpXXXXXXXXXX?xxxxx=TB1QWElIpXXXXXvXpXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/TB1wZUQJpXXXXajXpXXXXXXXXXX?xxxxx=TB1wZUQJpXXXXajXpXXXXXXXXXX\"]}";
MultiLingual ml = JSON.parseObject(text, MultiLingual.class);
String text2 = JSON.toJSONString(ml);
System.out.println(text2);
Assert.assertEquals(text, text2);
}
public static | Bug_for_sunai |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java | {
"start": 1113,
"end": 8893
} | class ____ {
public static final ByteArrayInputStream EMPTY = new ByteArrayInputStream(new byte[0]);
private StreamUtils() {}
public static InputStream limitedInputStream(final InputStream is, final int limit) throws IOException {
return new InputStream() {
private int mPosition = 0;
private int mMark = 0;
private final int mLimit = Math.min(limit, is.available());
@Override
public int read() throws IOException {
if (mPosition < mLimit) {
mPosition++;
return is.read();
}
return -1;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (mPosition >= mLimit) {
return -1;
}
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
is.read(b, off, len);
mPosition += len;
return len;
}
@Override
public long skip(long len) throws IOException {
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
is.skip(len);
mPosition += len;
return len;
}
@Override
public int available() {
return mLimit - mPosition;
}
@Override
public boolean markSupported() {
return is.markSupported();
}
@Override
public synchronized void mark(int readlimit) {
is.mark(readlimit);
mMark = mPosition;
}
@Override
public synchronized void reset() throws IOException {
is.reset();
mPosition = mMark;
}
@Override
public void close() throws IOException {
is.close();
}
};
}
public static InputStream markSupportedInputStream(final InputStream is, final int markBufferSize) {
if (is.markSupported()) {
return is;
}
return new InputStream() {
byte[] mMarkBuffer;
boolean mInMarked = false;
boolean mInReset = false;
boolean mDry = false;
private int mPosition = 0;
private int mCount = 0;
@Override
public int read() throws IOException {
if (!mInMarked) {
return is.read();
} else {
if (mPosition < mCount) {
byte b = mMarkBuffer[mPosition++];
return b & 0xFF;
}
if (!mInReset) {
if (mDry) {
return -1;
}
if (null == mMarkBuffer) {
mMarkBuffer = new byte[markBufferSize];
}
if (mPosition >= markBufferSize) {
throw new IOException("Mark buffer is full!");
}
int read = is.read();
if (-1 == read) {
mDry = true;
return -1;
}
mMarkBuffer[mPosition++] = (byte) read;
mCount++;
return read;
} else {
// mark buffer is used, exit mark status!
mInMarked = false;
mInReset = false;
mPosition = 0;
mCount = 0;
return is.read();
}
}
}
/**
* NOTE: the <code>readlimit</code> argument for this class
* has no meaning.
*/
@Override
public synchronized void mark(int readlimit) {
mInMarked = true;
mInReset = false;
// mark buffer is not empty
int count = mCount - mPosition;
if (count > 0) {
System.arraycopy(mMarkBuffer, mPosition, mMarkBuffer, 0, count);
mCount = count;
mPosition = 0;
}
}
@Override
public synchronized void reset() throws IOException {
if (!mInMarked) {
throw new IOException("should mark before reset!");
}
mInReset = true;
mPosition = 0;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int available() throws IOException {
int available = is.available();
if (mInMarked && mInReset) {
available += mCount - mPosition;
}
return available;
}
@Override
public void close() throws IOException {
is.close();
}
};
}
public static InputStream markSupportedInputStream(final InputStream is) {
return markSupportedInputStream(is, 1024);
}
public static void skipUnusedStream(InputStream is) throws IOException {
if (is.available() > 0) {
is.skip(is.available());
}
}
public static void copy(InputStream in, OutputStream out) throws IOException {
if (in.getClass() == ByteArrayInputStream.class) {
copy((ByteArrayInputStream) in, out);
return;
}
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
public static void copy(ByteArrayInputStream in, OutputStream out) throws IOException {
int len = in.available();
byte[] buffer = new byte[len];
in.read(buffer, 0, len);
out.write(buffer, 0, len);
}
public static byte[] readBytes(InputStream in) throws IOException {
if (in.getClass() == ByteArrayInputStream.class) {
return readBytes((ByteArrayInputStream) in);
}
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
return out.toByteArray();
}
public static byte[] readBytes(ByteArrayInputStream in) throws IOException {
int len = in.available();
byte[] bytes = new byte[len];
in.read(bytes, 0, len);
return bytes;
}
public static String toString(InputStream in) throws IOException {
return new String(readBytes(in), StandardCharsets.UTF_8);
}
public static String toString(InputStream in, Charset charset) throws IOException {
return new String(readBytes(in), charset);
}
}
| StreamUtils |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1700/issue1763_2/bean/BaseResult.java | {
"start": 160,
"end": 846
} | class ____<T> {
private static final Integer SUCCESS_CODE = 0;
private Integer code;
private String message;
@JSONField(name = "content")
private T content;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
public boolean isSuccess() {
return code.equals(SUCCESS_CODE);
}
}
| BaseResult |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackendBuilder.java | {
"start": 1026,
"end": 1108
} | interface ____<T, E extends Throwable> {
T build() throws E;
}
| StateBackendBuilder |
java | quarkusio__quarkus | independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ManagedContext.java | {
"start": 246,
"end": 1774
} | interface ____ extends InjectableContext {
/**
* Activate the context with no initial state.
* <p>
* If needed, activating a context will fire {@code @Initialized} event for the given context.
*
* @return the context state
*/
default ContextState activate() {
return activate(null);
}
// Maintain binary compatibility with Quarkus 3.2
default void activate$$bridge() {
activate(null);
}
/**
* Activate the context.
* <p>
* If invoked with {@code null} parameter, a fresh {@link io.quarkus.arc.InjectableContext.ContextState} is
* automatically created.
*
* @param initialState The initial state, may be {@code null}
* @return the context state
*/
ContextState activate(ContextState initialState);
// Maintain binary compatibility with Quarkus 3.2
default void activate$$bridge(ContextState initialState) {
activate(initialState);
}
/**
* Deactivate the context - do not destroy existing contextual instances.
*/
void deactivate();
/**
* Destroy and deactivate the context.
*/
default void terminate() {
destroy();
deactivate();
}
/**
* Creates a new {@link io.quarkus.arc.InjectableContext.ContextState}.
* <p>
* Creating a context state does not fire {@code @Initialized} event for given context.
*
* @return a new initialized context state
*/
ContextState initializeState();
}
| ManagedContext |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/aroundconstruct/AroundConstructWithClassAndConstructorLevelBindingTest.java | {
"start": 2262,
"end": 2429
} | class ____ {
static boolean constructed = false;
@Inject
@MyBinding(2)
MyBean() {
constructed = true;
}
}
}
| MyBean |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/testers/MapContainsValueTester.java | {
"start": 1747,
"end": 3371
} | class ____<K, V> extends AbstractMapTester<K, V> {
@CollectionSize.Require(absent = ZERO)
public void testContains_yes() {
assertTrue("containsValue(present) should return true", getMap().containsValue(v0()));
}
public void testContains_no() {
assertFalse("containsValue(notPresent) should return false", getMap().containsValue(v3()));
}
@MapFeature.Require(ALLOWS_NULL_VALUE_QUERIES)
public void testContains_nullNotContainedButAllowed() {
assertFalse("containsValue(null) should return false", getMap().containsValue(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_VALUE_QUERIES)
public void testContains_nullNotContainedAndUnsupported() {
expectNullValueMissingWhenNullValuesUnsupported(
"containsValue(null) should return false or throw");
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContains_nonNullWhenNullContained() {
initMapWithNullValue();
assertFalse("containsValue(notPresent) should return false", getMap().containsValue(v3()));
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContains_nullContained() {
initMapWithNullValue();
assertTrue("containsValue(null) should return true", getMap().containsValue(null));
}
public void testContains_wrongType() {
try {
// noinspection SuspiciousMethodCalls
assertFalse(
"containsValue(wrongType) should return false or throw",
getMap().containsValue(WrongType.VALUE));
} catch (ClassCastException tolerated) {
}
}
}
| MapContainsValueTester |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RMultimapCache.java | {
"start": 869,
"end": 1418
} | interface ____<K, V> extends RMultimap<K, V>, RMultimapCacheAsync<K, V> {
/**
* Set a timeout for key. After the timeout has expired,
* the key and its values will automatically be deleted.
*
* @param key - map key
* @param timeToLive - timeout before key will be deleted
* @param timeUnit - timeout time unit
* @return <code>true</code> if key exists and the timeout was set and <code>false</code> if key not exists
*/
boolean expireKey(K key, long timeToLive, TimeUnit timeUnit);
}
| RMultimapCache |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/runtime/translators/LegacySourceTransformationTranslator.java | {
"start": 1679,
"end": 4108
} | class ____<OUT>
extends SimpleTransformationTranslator<OUT, LegacySourceTransformation<OUT>> {
@Override
protected Collection<Integer> translateForBatchInternal(
final LegacySourceTransformation<OUT> transformation, final Context context) {
return translateInternal(transformation, context);
}
@Override
protected Collection<Integer> translateForStreamingInternal(
final LegacySourceTransformation<OUT> transformation, final Context context) {
return translateInternal(transformation, context);
}
private Collection<Integer> translateInternal(
final LegacySourceTransformation<OUT> transformation, final Context context) {
checkNotNull(transformation);
checkNotNull(context);
final StreamGraph streamGraph = context.getStreamGraph();
final String slotSharingGroup = context.getSlotSharingGroup();
final int transformationId = transformation.getId();
final ExecutionConfig executionConfig = streamGraph.getExecutionConfig();
streamGraph.addLegacySource(
transformationId,
slotSharingGroup,
transformation.getCoLocationGroupKey(),
transformation.getOperatorFactory(),
null,
transformation.getOutputType(),
"Source: " + transformation.getName());
if (transformation.getOperatorFactory() instanceof InputFormatOperatorFactory) {
streamGraph.setInputFormat(
transformationId,
((InputFormatOperatorFactory<OUT>) transformation.getOperatorFactory())
.getInputFormat());
}
final int parallelism =
transformation.getParallelism() != ExecutionConfig.PARALLELISM_DEFAULT
? transformation.getParallelism()
: executionConfig.getParallelism();
streamGraph.setParallelism(
transformationId, parallelism, transformation.isParallelismConfigured());
streamGraph.setMaxParallelism(transformationId, transformation.getMaxParallelism());
streamGraph.setSupportsConcurrentExecutionAttempts(
transformationId, transformation.isSupportsConcurrentExecutionAttempts());
return Collections.singleton(transformationId);
}
}
| LegacySourceTransformationTranslator |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/IHeadList.java | {
"start": 232,
"end": 286
} | interface ____<X> extends List<X> {
X head();
}
| IHeadList |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AbstractPropertyMapperTests.java | {
"start": 732,
"end": 869
} | class ____ {@link PropertyMapper} tests.
*
* @author Phillip Webb
* @author Madhura Bhave
* @author Eddú Meléndez
*/
public abstract | for |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java | {
"start": 40377,
"end": 40482
} | class ____ {
@EveryFiveSeconds
void checkForUpdates() {
}
}
static | MetaAnnotationFixedRateTestBean |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/create/MySqlCreateFullTextCharFilterTest.java | {
"start": 891,
"end": 3672
} | class ____ extends MysqlTest {
@Test
public void test_one() throws Exception {
String sql = "create fulltext charfilter test1 ("
+ "'type' = 'typename',"
+ "'key'='name',"
+ "'key2'='name2'"
+ ")";
List<SQLStatement> stmtList = SQLUtils.toStatementList(sql, JdbcConstants.MYSQL);
SQLStatement stmt = stmtList.get(0);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE FULLTEXT CHARFILTER test1(\n" + "\"type\" = 'typename',\n"
+ "'key' = 'name','key2' = 'name2'\n" + ")", output);
}
@Test
public void test_crate() throws Exception {
String sql = "create fulltext charfilter test1 ("
+ "\"type\" = \"typename\","
+ "\"key\"=\"name\""
+ ")";
List<SQLStatement> stmtList = SQLUtils.toStatementList(sql, JdbcConstants.MYSQL);
SQLStatement stmt = stmtList.get(0);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE FULLTEXT CHARFILTER test1(\n"
+ "\"type\" = 'typename',\n"
+ "'key' = 'name'\n"
+ ")", output);
}
@Test
public void test_1() throws Exception {
String sql = "show fulltext charfilters";
List<SQLStatement> stmtList = SQLUtils.toStatementList(sql, JdbcConstants.MYSQL);
SQLStatement stmt = stmtList.get(0);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("SHOW FULLTEXT CHARFILTERS", output);
}
@Test
public void test_2() throws Exception {
String sql = "show create fulltext charfilter test1";
List<SQLStatement> stmtList = SQLUtils.toStatementList(sql, JdbcConstants.MYSQL);
SQLStatement stmt = stmtList.get(0);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("SHOW CREATE FULLTEXT CHARFILTER test1", output);
}
@Test
public void test_3() throws Exception {
String sql = "alter fulltext charfilter test1 set k = 'a';";
List<SQLStatement> stmtList = SQLUtils.toStatementList(sql, JdbcConstants.MYSQL);
SQLStatement stmt = stmtList.get(0);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("ALTER FULLTEXT CHARFILTER test1 SET k = 'a';", output);
}
@Test
public void test_drop() throws Exception {
String sql = "drop fulltext charfilter test1";
List<SQLStatement> stmtList = SQLUtils.toStatementList(sql, JdbcConstants.MYSQL);
SQLStatement stmt = stmtList.get(0);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("DROP FULLTEXT CHARFILTER test1", output);
}
}
| MySqlCreateFullTextCharFilterTest |
java | apache__camel | components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppBinding.java | {
"start": 1724,
"end": 12723
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(SmppBinding.class);
private SmppConfiguration configuration;
public SmppBinding() {
this.configuration = new SmppConfiguration();
}
public SmppBinding(SmppConfiguration configuration) {
this.configuration = configuration;
}
/**
* Create the SmppCommand object from the inbound exchange
*
* @throws UnsupportedEncodingException if the encoding is not supported
*/
public SmppCommand createSmppCommand(SMPPSession session, Exchange exchange) {
SmppCommandType commandType = SmppCommandType.fromExchange(exchange);
return commandType.createCommand(session, configuration);
}
/**
* Create a new SmppMessage from the inbound alert notification
*/
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) {
SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString());
smppMessage.setHeader(SmppConstants.SEQUENCE_NUMBER, alertNotification.getSequenceNumber());
smppMessage.setHeader(SmppConstants.COMMAND_ID, alertNotification.getCommandId());
smppMessage.setHeader(SmppConstants.COMMAND_STATUS, alertNotification.getCommandStatus());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR, alertNotification.getSourceAddr());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR_NPI, alertNotification.getSourceAddrNpi());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR_TON, alertNotification.getSourceAddrTon());
smppMessage.setHeader(SmppConstants.ESME_ADDR, alertNotification.getEsmeAddr());
smppMessage.setHeader(SmppConstants.ESME_ADDR_NPI, alertNotification.getEsmeAddrNpi());
smppMessage.setHeader(SmppConstants.ESME_ADDR_TON, alertNotification.getEsmeAddrTon());
return smppMessage;
}
/**
* Create a new SmppMessage from the inbound deliver sm or deliver receipt
*/
public SmppMessage createSmppMessage(CamelContext camelContext, DeliverSm deliverSm) throws Exception {
SmppMessage smppMessage = new SmppMessage(camelContext, deliverSm, configuration);
byte[] body = SmppUtils.getMessageBody(deliverSm);
String decodedBody = SmppUtils.decodeBody(body, deliverSm.getDataCoding(), configuration.getEncoding());
if (deliverSm.isSmscDeliveryReceipt()) {
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.DeliveryReceipt.toString());
DeliveryReceipt smscDeliveryReceipt = null;
if (decodedBody != null) {
smscDeliveryReceipt = DefaultDecomposer.getInstance().deliveryReceipt(decodedBody);
} else if (body != null) {
// fallback approach
smscDeliveryReceipt = DefaultDecomposer.getInstance().deliveryReceipt(body);
}
if (smscDeliveryReceipt != null) {
smppMessage.setBody(smscDeliveryReceipt.getText());
smppMessage.setHeader(SmppConstants.ID, smscDeliveryReceipt.getId());
smppMessage.setHeader(SmppConstants.DELIVERED, smscDeliveryReceipt.getDelivered());
smppMessage.setHeader(SmppConstants.DONE_DATE, smscDeliveryReceipt.getDoneDate());
if (!"000".equals(smscDeliveryReceipt.getError())) {
smppMessage.setHeader(SmppConstants.ERROR, smscDeliveryReceipt.getError());
}
smppMessage.setHeader(SmppConstants.SUBMIT_DATE, smscDeliveryReceipt.getSubmitDate());
smppMessage.setHeader(SmppConstants.SUBMITTED, smscDeliveryReceipt.getSubmitted());
smppMessage.setHeader(SmppConstants.FINAL_STATUS, smscDeliveryReceipt.getFinalStatus());
}
} else {
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.DeliverSm.toString());
if (body != null) {
smppMessage.setBody((decodedBody != null) ? decodedBody : body);
}
smppMessage.setHeader(SmppConstants.SEQUENCE_NUMBER, deliverSm.getSequenceNumber());
smppMessage.setHeader(SmppConstants.COMMAND_ID, deliverSm.getCommandId());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR, deliverSm.getSourceAddr());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR_NPI, deliverSm.getSourceAddrNpi());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR_TON, deliverSm.getSourceAddrTon());
smppMessage.setHeader(SmppConstants.DATA_CODING, deliverSm.getDataCoding());
smppMessage.setHeader(SmppConstants.DEST_ADDR, deliverSm.getDestAddress());
smppMessage.setHeader(SmppConstants.DEST_ADDR_NPI, deliverSm.getDestAddrNpi());
smppMessage.setHeader(SmppConstants.DEST_ADDR_TON, deliverSm.getDestAddrTon());
smppMessage.setHeader(SmppConstants.SCHEDULE_DELIVERY_TIME, deliverSm.getScheduleDeliveryTime());
smppMessage.setHeader(SmppConstants.VALIDITY_PERIOD, deliverSm.getValidityPeriod());
smppMessage.setHeader(SmppConstants.SERVICE_TYPE, deliverSm.getServiceType());
}
if (deliverSm.getOptionalParameters() != null && deliverSm.getOptionalParameters().length > 0) {
// the deprecated way
Map<String, Object> optionalParameters = createOptionalParameterByName(deliverSm);
smppMessage.setHeader(SmppConstants.OPTIONAL_PARAMETERS, optionalParameters);
// the new way
Map<Short, Object> optionalParameter = createOptionalParameterByCode(deliverSm);
smppMessage.setHeader(SmppConstants.OPTIONAL_PARAMETER, optionalParameter);
}
return smppMessage;
}
private Map<String, Object> createOptionalParameterByName(DeliverSm deliverSm) {
Map<String, Object> optParams = new HashMap<>();
for (OptionalParameter optPara : deliverSm.getOptionalParameters()) {
try {
Tag valueOfTag = OptionalParameter.Tag.valueOf(optPara.tag);
if (valueOfTag != null) {
if (optPara instanceof COctetString) {
optParams.put(valueOfTag.toString(), ((COctetString) optPara).getValueAsString());
} else if (optPara instanceof OctetString) {
optParams.put(valueOfTag.toString(), ((OctetString) optPara).getValueAsString());
} else if (optPara instanceof OptionalParameter.Byte) {
optParams.put(valueOfTag.toString(),
((OptionalParameter.Byte) optPara).getValue());
} else if (optPara instanceof OptionalParameter.Short) {
optParams.put(valueOfTag.toString(),
((OptionalParameter.Short) optPara).getValue());
} else if (optPara instanceof OptionalParameter.Int) {
optParams.put(valueOfTag.toString(),
((OptionalParameter.Int) optPara).getValue());
} else if (optPara instanceof Null) {
optParams.put(valueOfTag.toString(), null);
}
} else {
LOG.debug("Skipping optional parameter with tag {} because it was not recognized", optPara.tag);
}
} catch (IllegalArgumentException e) {
LOG.debug("Skipping optional parameter with tag {} due to {}", optPara.tag, e.getMessage());
}
}
return optParams;
}
private Map<Short, Object> createOptionalParameterByCode(DeliverSm deliverSm) {
Map<Short, Object> optParams = new HashMap<>();
for (OptionalParameter optPara : deliverSm.getOptionalParameters()) {
if (optPara instanceof COctetString) {
optParams.put(optPara.tag, ((COctetString) optPara).getValueAsString());
} else if (optPara instanceof OctetString) {
optParams.put(optPara.tag, ((OctetString) optPara).getValue());
} else if (optPara instanceof OptionalParameter.Byte) {
optParams.put(optPara.tag,
((OptionalParameter.Byte) optPara).getValue());
} else if (optPara instanceof OptionalParameter.Short) {
optParams.put(optPara.tag,
((OptionalParameter.Short) optPara).getValue());
} else if (optPara instanceof OptionalParameter.Int) {
optParams.put(optPara.tag,
((OptionalParameter.Int) optPara).getValue());
} else if (optPara instanceof Null) {
optParams.put(optPara.tag, null);
}
}
return optParams;
}
public SmppMessage createSmppMessage(CamelContext camelContext, DataSm dataSm, String smppMessageId) {
SmppMessage smppMessage = new SmppMessage(camelContext, dataSm, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.DataSm.toString());
smppMessage.setHeader(SmppConstants.ID, smppMessageId);
smppMessage.setHeader(SmppConstants.SEQUENCE_NUMBER, dataSm.getSequenceNumber());
smppMessage.setHeader(SmppConstants.COMMAND_ID, dataSm.getCommandId());
smppMessage.setHeader(SmppConstants.COMMAND_STATUS, dataSm.getCommandStatus());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR, dataSm.getSourceAddr());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR_NPI, dataSm.getSourceAddrNpi());
smppMessage.setHeader(SmppConstants.SOURCE_ADDR_TON, dataSm.getSourceAddrTon());
smppMessage.setHeader(SmppConstants.DEST_ADDR, dataSm.getDestAddress());
smppMessage.setHeader(SmppConstants.DEST_ADDR_NPI, dataSm.getDestAddrNpi());
smppMessage.setHeader(SmppConstants.DEST_ADDR_TON, dataSm.getDestAddrTon());
smppMessage.setHeader(SmppConstants.SERVICE_TYPE, dataSm.getServiceType());
smppMessage.setHeader(SmppConstants.REGISTERED_DELIVERY, dataSm.getRegisteredDelivery());
smppMessage.setHeader(SmppConstants.DATA_CODING, dataSm.getDataCoding());
return smppMessage;
}
/**
* Returns the current date. Externalized for better test support.
*
* @return the current date
*/
Date getCurrentDate() {
return new Date();
}
/**
* Returns the smpp configuration
*
* @return the configuration
*/
public SmppConfiguration getConfiguration() {
return configuration;
}
/**
* Set the smpp configuration.
*
* @param configuration smppConfiguration
*/
public void setConfiguration(SmppConfiguration configuration) {
this.configuration = configuration;
}
}
| SmppBinding |
java | dropwizard__dropwizard | dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/dual/DualSessionFactory.java | {
"start": 1303,
"end": 6415
} | class ____ implements SessionFactory {
private static final long serialVersionUID = 1L;
private final SessionFactory primary;
private final SessionFactory reader;
private final ThreadLocal<SessionFactory> current = new ThreadLocal<SessionFactory>();
public DualSessionFactory(final SessionFactory primary, final SessionFactory reader) {
this.primary = primary;
this.reader = reader;
this.current.set(primary); // Main thread should use primary.
}
/** Activates either the primary or the reader session factory depending on the readOnly parameter.
*
* @param readOnly
* @return the session factory in use
*/
public SessionFactory prepare(final boolean readOnly) {
final SessionFactory factory = readOnly ? reader : primary;
current.set(factory);
return factory;
}
public SessionFactory current() { return current.get(); }
@Override
public EntityManager createEntityManager() { return current().createEntityManager(); }
@Override
public EntityManager createEntityManager(final Map map) { return current().createEntityManager(map); }
@Override
public EntityManager createEntityManager(final SynchronizationType synchronizationType) { return current().createEntityManager(synchronizationType); }
@Override
public EntityManager createEntityManager(final SynchronizationType synchronizationType, final Map map) { return current().createEntityManager(synchronizationType, map); }
@Override
public HibernateCriteriaBuilder getCriteriaBuilder() {
return current().getCriteriaBuilder();
}
@Override
public Metamodel getMetamodel() {
return current().getMetamodel();
}
@Override
public boolean isOpen() { return current().isOpen(); }
@Override
public Map<String, Object> getProperties() { return current().getProperties(); }
@Override
public PersistenceUnitUtil getPersistenceUnitUtil() { return current().getPersistenceUnitUtil(); }
@Override
public void addNamedQuery(String name, Query query) { current().addNamedQuery(name, query); }
@Override
public <T> T unwrap(Class<T> cls) { return current().unwrap(cls); }
@Override
public <T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph) { current().addNamedEntityGraph(graphName, entityGraph); }
@Override
public <T> List<EntityGraph<? super T>> findEntityGraphsByType(Class<T> entityClass) { return current().findEntityGraphsByType(entityClass); }
@Override
public Reference getReference() throws NamingException { return current().getReference(); }
@Override
public SessionFactoryOptions getSessionFactoryOptions() { return current().getSessionFactoryOptions(); }
@Override
public SessionBuilder withOptions() { return current().withOptions(); }
@Override
public Session openSession() throws HibernateException { return current().openSession(); }
@Override
public Session getCurrentSession() throws HibernateException { return current().getCurrentSession(); }
@Override
public StatelessSessionBuilder withStatelessOptions() { return current().withStatelessOptions(); }
@Override
public StatelessSession openStatelessSession() { return current().openStatelessSession(); }
@Override
public StatelessSession openStatelessSession(Connection connection) { return current().openStatelessSession(connection); }
@Override
public void inSession(Consumer<Session> action) {
current().inSession(action);
}
@Override
public void inTransaction(Consumer<Session> action) {
current().inTransaction(action);
}
@Override
public <R> R fromSession(Function<Session, R> action) {
return current().fromSession(action);
}
@Override
public <R> R fromTransaction(Function<Session, R> action) {
return current().fromTransaction(action);
}
@Override
public Statistics getStatistics() { return current().getStatistics(); }
@Override
public void close() throws HibernateException { current().close(); }
@Override
public boolean isClosed() { return current().isClosed(); }
@Override
public Cache getCache() { return current().getCache(); }
@Override
public Set getDefinedFilterNames() { return current().getDefinedFilterNames(); }
@Override
public FilterDefinition getFilterDefinition(String filterName) throws HibernateException { return current().getFilterDefinition(filterName); }
@Override
public boolean containsFetchProfileDefinition(String name) { return current().containsFetchProfileDefinition(name); }
@Override
public SchemaManager getSchemaManager() {
return current().getSchemaManager();
}
@Override
public RootGraph<?> findEntityGraphByName(String s) {
return current().findEntityGraphByName(s);
}
@Override
public Set<String> getDefinedFetchProfileNames() {
return current().getDefinedFetchProfileNames();
}
}
| DualSessionFactory |
java | quarkusio__quarkus | extensions/kubernetes-client/deployment/src/main/java/io/quarkus/kubernetes/client/deployment/KubernetesClientProcessor.java | {
"start": 16299,
"end": 16620
} | class ____. "
+
"See https://quarkus.io/guides/kubernetes-client#note-on-generic-types for more details",
implementedOrExtendedClass.local(), c.name(), implementedOrExtendedClass);
}
}
});
}
}
| handles |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/reactive/AbstractNamedValueMethodArgumentResolver.java | {
"start": 2129,
"end": 2352
} | class ____.
*
* <p>A {@link ConversionService} is used to convert a resolved String argument
* value to the expected target method parameter type.
*
* @author Rossen Stoyanchev
* @since 5.2
*/
public abstract | constructor |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/conversion/_enum/EnumToIntegerConversionTest.java | {
"start": 729,
"end": 2640
} | class ____ {
@ProcessorTest
public void shouldApplyEnumToIntegerConversion() {
EnumToIntegerSource source = new EnumToIntegerSource();
for ( EnumToIntegerEnum value : EnumToIntegerEnum.values() ) {
source.setEnumValue( value );
EnumToIntegerTarget target = EnumToIntegerMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getEnumValue() ).isEqualTo( source.getEnumValue().ordinal() );
}
}
@ProcessorTest
public void shouldApplyReverseEnumToIntegerConversion() {
EnumToIntegerTarget target = new EnumToIntegerTarget();
int numberOfValues = EnumToIntegerEnum.values().length;
for ( int value = 0; value < numberOfValues; value++ ) {
target.setEnumValue( value );
EnumToIntegerSource source = EnumToIntegerMapper.INSTANCE.targetToSource( target );
assertThat( source ).isNotNull();
assertThat( source.getEnumValue() ).isEqualTo( EnumToIntegerEnum.values()[ target.getEnumValue() ] );
}
}
@ProcessorTest
public void shouldHandleOutOfBoundsEnumOrdinal() {
EnumToIntegerTarget target = new EnumToIntegerTarget();
target.setInvalidEnumValue( EnumToIntegerEnum.values().length + 1 );
assertThatThrownBy( () -> EnumToIntegerMapper.INSTANCE.targetToSource( target ) )
.isInstanceOf( ArrayIndexOutOfBoundsException.class );
}
@ProcessorTest
public void shouldHandleNullIntegerValue() {
EnumToIntegerTarget target = new EnumToIntegerTarget();
EnumToIntegerSource source = EnumToIntegerMapper.INSTANCE.targetToSource( target );
assertThat( source ).isNotNull();
assertThat( source.getEnumValue() ).isNull();
assertThat( source.getInvalidEnumValue() ).isNull();
}
}
| EnumToIntegerConversionTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/AnySetterTest.java | {
"start": 6513,
"end": 6602
} | class ____ {
public int x, y;
}
// [databind#3394]
static | IdentityDTO349 |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/api/AssertThrowsAssertionsTests.java | {
"start": 1317,
"end": 7370
} | class ____ {
private static final Executable nix = () -> {
};
@Test
void assertThrowsWithMethodReferenceForNonVoidReturnType() {
FutureTask<String> future = new FutureTask<>(() -> {
throw new RuntimeException("boom");
});
future.run();
ExecutionException exception = assertThrows(ExecutionException.class, future::get);
assertNotNull(exception.getCause());
assertEquals("boom", exception.getCause().getMessage());
}
@Test
void assertThrowsWithMethodReferenceForVoidReturnType() {
var object = new Object();
IllegalMonitorStateException exception;
exception = assertThrows(IllegalMonitorStateException.class, object::notify);
assertNotNull(exception);
// Note that Object.wait(...) is an overloaded method with a void return type
exception = assertThrows(IllegalMonitorStateException.class, object::wait);
assertNotNull(exception);
}
@Test
void assertThrowsWithExecutableThatThrowsThrowable() {
EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, () -> {
throw new EnigmaThrowable();
});
assertNotNull(enigmaThrowable);
}
@Test
void assertThrowsWithExecutableThatThrowsThrowableWithMessage() {
EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, () -> {
throw new EnigmaThrowable();
}, "message");
assertNotNull(enigmaThrowable);
}
@Test
void assertThrowsWithExecutableThatThrowsThrowableWithMessageSupplier() {
EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, () -> {
throw new EnigmaThrowable();
}, () -> "message");
assertNotNull(enigmaThrowable);
}
@Test
void assertThrowsWithExecutableThatThrowsCheckedException() {
IOException exception = assertThrows(IOException.class, () -> {
throw new IOException();
});
assertNotNull(exception);
}
@Test
void assertThrowsWithExecutableThatThrowsRuntimeException() {
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> {
throw new IllegalStateException();
});
assertNotNull(illegalStateException);
}
@Test
void assertThrowsWithExecutableThatThrowsError() {
StackOverflowError stackOverflowError = assertThrows(StackOverflowError.class,
AssertionTestUtils::recurseIndefinitely);
assertNotNull(stackOverflowError);
}
@Test
void assertThrowsWithExecutableThatDoesNotThrowAnException() {
try {
assertThrows(IllegalStateException.class, nix);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "Expected java.lang.IllegalStateException to be thrown, but nothing was thrown.");
}
}
@Test
void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageString() {
try {
assertThrows(IOException.class, nix, "Custom message");
expectAssertionFailedError();
}
catch (AssertionError ex) {
assertMessageEquals(ex,
"Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown.");
}
}
@Test
void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageSupplier() {
try {
assertThrows(IOException.class, nix, () -> "Custom message");
expectAssertionFailedError();
}
catch (AssertionError ex) {
assertMessageEquals(ex,
"Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown.");
}
}
@Test
void assertThrowsWithExecutableThatThrowsAnUnexpectedException() {
try {
assertThrows(IllegalStateException.class, () -> {
throw new NumberFormatException();
});
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
assertThat(ex).hasCauseInstanceOf(NumberFormatException.class);
}
}
@Test
void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageString() {
try {
assertThrows(IllegalStateException.class, () -> {
throw new NumberFormatException();
}, "Custom message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
// Should look something like this:
// Custom message ==> Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.NumberFormatException>
assertMessageStartsWith(ex, "Custom message ==> ");
assertMessageContains(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
assertThat(ex).hasCauseInstanceOf(NumberFormatException.class);
}
}
@Test
void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageSupplier() {
try {
assertThrows(IllegalStateException.class, () -> {
throw new NumberFormatException();
}, () -> "Custom message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
// Should look something like this:
// Custom message ==> Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.NumberFormatException>
assertMessageStartsWith(ex, "Custom message ==> ");
assertMessageContains(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
assertThat(ex).hasCauseInstanceOf(NumberFormatException.class);
}
}
@Test
@SuppressWarnings("serial")
void assertThrowsWithExecutableThatThrowsInstanceOfAnonymousInnerClassAsUnexpectedException() {
try {
assertThrows(IllegalStateException.class, () -> {
throw new NumberFormatException() {
};
});
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "Unexpected exception type thrown, ");
assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
// As of the time of this writing, the | AssertThrowsAssertionsTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/version/VersionSeedUpdateTest.java | {
"start": 929,
"end": 3168
} | class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
session.persist( new ShortVersionEntity( 1L, "name_1" ) );
session.persist( new IntVersionEntity( 2L, "name_2" ) );
session.persist( new LongVersionEntity( 3L, "name_3" ) );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction( session -> {
session.createMutationQuery( "delete from ShortVersionEntity" ).executeUpdate();
session.createMutationQuery( "delete from IntVersionEntity" ).executeUpdate();
session.createMutationQuery( "delete from LongVersionEntity" ).executeUpdate();
} );
}
@Test
public void testShortVersionIncrease(SessionFactoryScope scope) {
scope.inTransaction( session -> session.createMutationQuery(
"update versioned ShortVersionEntity set name='updated_name_1'"
).executeUpdate() );
scope.inTransaction( session -> {
final ShortVersionEntity versionedEntity = session.find( ShortVersionEntity.class, 1L );
assertThat( versionedEntity.getName() ).isEqualTo( "updated_name_1" );
assertThat( versionedEntity.getVersion() ).isEqualTo( (short) 1 );
} );
}
@Test
public void testIntVersionIncrease(SessionFactoryScope scope) {
scope.inTransaction( session -> session.createMutationQuery(
"update versioned IntVersionEntity set name='updated_name_2'"
).executeUpdate() );
scope.inTransaction( session -> {
final IntVersionEntity versionedEntity = session.find( IntVersionEntity.class, 2L );
assertThat( versionedEntity.getName() ).isEqualTo( "updated_name_2" );
assertThat( versionedEntity.getVersion() ).isEqualTo( 1 );
} );
}
@Test
public void testLongVersionIncrease(SessionFactoryScope scope) {
scope.inTransaction( session -> session.createMutationQuery(
"update versioned LongVersionEntity set name='updated_name_3'"
).executeUpdate() );
scope.inTransaction( session -> {
final LongVersionEntity versionedEntity = session.find( LongVersionEntity.class, 3L );
assertThat( versionedEntity.getName() ).isEqualTo( "updated_name_3" );
assertThat( versionedEntity.getVersion() ).isEqualTo( 1L );
} );
}
@Entity( name = "ShortVersionEntity" )
public static | VersionSeedUpdateTest |
java | google__dagger | javatests/dagger/internal/codegen/MultibindingTest.java | {
"start": 858,
"end": 1265
} | class ____ {
@Test
public void multibindingContributedWithKotlinProperty_compilesSucessfully() {
Source component =
CompilerTests.javaSource(
"test.MyComponent",
"package test;",
"",
"import dagger.Component;",
"import java.util.Set;",
"",
"@Component(modules = TestModule.class)",
" | MultibindingTest |
java | grpc__grpc-java | netty/src/test/java/io/grpc/netty/UdsNettyChannelProviderTest.java | {
"start": 1865,
"end": 5430
} | class ____ {
@Rule public TemporaryFolder tempFolder = new TemporaryFolder();
@Rule
public final GrpcCleanupRule cleanupRule = new GrpcCleanupRule();
private UdsNettyChannelProvider provider = new UdsNettyChannelProvider();
private EventLoopGroup elg;
private EventLoopGroup boss;
@After
public void tearDown() {
if (elg != null) {
elg.shutdownGracefully();
}
if (boss != null) {
boss.shutdownGracefully();
}
}
@Test
public void provided() {
for (ManagedChannelProvider current
: InternalServiceProviders.getCandidatesViaServiceLoader(
ManagedChannelProvider.class, getClass().getClassLoader())) {
if (current instanceof UdsNettyChannelProvider) {
return;
}
}
fail("ServiceLoader unable to load UdsNettyChannelProvider");
}
@Test
public void providedHardCoded() {
for (Class<?> current : ManagedChannelRegistryAccessor.getHardCodedClasses()) {
if (current == UdsNettyChannelProvider.class) {
return;
}
}
fail("Hard coded unable to load UdsNettyChannelProvider");
}
@Test
public void basicMethods() {
Assume.assumeTrue(provider.isAvailable());
assertEquals(3, provider.priority());
}
@Test
public void newChannelBuilder_success() {
Assume.assumeTrue(Utils.isEpollAvailable());
NewChannelBuilderResult result =
provider.newChannelBuilder("unix:sock.sock", TlsChannelCredentials.create());
assertThat(result.getChannelBuilder()).isInstanceOf(NettyChannelBuilder.class);
}
@Test
public void managedChannelRegistry_newChannelBuilder() {
Assume.assumeTrue(Utils.isEpollAvailable());
ManagedChannelBuilder<?> managedChannelBuilder
= Grpc.newChannelBuilder("unix:///sock.sock", InsecureChannelCredentials.create());
assertThat(managedChannelBuilder).isNotNull();
ManagedChannel channel = managedChannelBuilder.build();
assertThat(channel).isNotNull();
assertThat(channel.authority()).isEqualTo("/sock.sock");
channel.shutdownNow();
}
@Test
public void udsClientServerTestUsingProvider() throws IOException {
Assume.assumeTrue(Utils.isEpollAvailable());
String socketPath = tempFolder.getRoot().getAbsolutePath() + "/test.socket";
createUdsServer(socketPath);
ManagedChannelBuilder<?> channelBuilder =
Grpc.newChannelBuilder("unix://" + socketPath, InsecureChannelCredentials.create());
SimpleServiceGrpc.SimpleServiceBlockingStub stub =
SimpleServiceGrpc.newBlockingStub(cleanupRule.register(channelBuilder.build()));
assertThat(unaryRpc("buddy", stub)).isEqualTo("Hello buddy");
}
/** Say hello to server. */
private static String unaryRpc(
String requestMessage, SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub) {
SimpleRequest request = SimpleRequest.newBuilder().setRequestMessage(requestMessage).build();
SimpleResponse response = blockingStub.unaryRpc(request);
return response.getResponseMessage();
}
private void createUdsServer(String name) throws IOException {
elg = new EpollEventLoopGroup();
boss = new EpollEventLoopGroup(1);
cleanupRule.register(
NettyServerBuilder.forAddress(new DomainSocketAddress(name))
.bossEventLoopGroup(boss)
.workerEventLoopGroup(elg)
.channelType(EpollServerDomainSocketChannel.class)
.addService(new SimpleServiceImpl())
.directExecutor()
.build()
.start());
}
private static | UdsNettyChannelProviderTest |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.java | {
"start": 1824,
"end": 3901
} | class ____ extends AbstractStreamingClientHttpRequest {
private final HttpClient httpClient;
private final ClassicHttpRequest httpRequest;
private final HttpContext httpContext;
HttpComponentsClientHttpRequest(HttpClient client, ClassicHttpRequest request, HttpContext context) {
this.httpClient = client;
this.httpRequest = request;
this.httpContext = context;
}
@Override
public HttpMethod getMethod() {
return HttpMethod.valueOf(this.httpRequest.getMethod());
}
@Override
public URI getURI() {
try {
return this.httpRequest.getUri();
}
catch (URISyntaxException ex) {
throw new IllegalStateException(ex.getMessage(), ex);
}
}
HttpContext getHttpContext() {
return this.httpContext;
}
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, @Nullable Body body) throws IOException {
addHeaders(this.httpRequest, headers);
if (body != null) {
this.httpRequest.setEntity(new BodyEntity(headers, body));
}
else if (!Method.isSafe(this.httpRequest.getMethod())) {
this.httpRequest.setEntity(NullEntity.INSTANCE);
}
ClassicHttpResponse httpResponse = this.httpClient.executeOpen(null, this.httpRequest, this.httpContext);
return new HttpComponentsClientHttpResponse(httpResponse);
}
/**
* Add the given headers to the given HTTP request.
* @param httpRequest the request to add the headers to
* @param headers the headers to add
*/
static void addHeaders(ClassicHttpRequest httpRequest, HttpHeaders headers) {
headers.forEach((headerName, headerValues) -> {
if (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265
String headerValue = StringUtils.collectionToDelimitedString(headerValues, "; ");
httpRequest.addHeader(headerName, headerValue);
}
else if (!HttpHeaders.CONTENT_LENGTH.equalsIgnoreCase(headerName) &&
!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {
for (String headerValue : headerValues) {
httpRequest.addHeader(headerName, headerValue);
}
}
});
}
private static | HttpComponentsClientHttpRequest |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/error/ShouldHaveSameClass.java | {
"start": 750,
"end": 827
} | class ____ another instance failed.
*
* @author Nicolas François
*/
public | as |
java | resilience4j__resilience4j | resilience4j-bulkhead/src/main/java/io/github/resilience4j/bulkhead/internal/FixedThreadPoolBulkhead.java | {
"start": 10550,
"end": 11684
} | class ____ implements Metrics {
private BulkheadMetrics() {
}
@Override
public int getCoreThreadPoolSize() {
return executorService.getCorePoolSize();
}
@Override
public int getThreadPoolSize() {
return executorService.getPoolSize();
}
@Override
public int getMaximumThreadPoolSize() {
return executorService.getMaximumPoolSize();
}
@Override
public int getQueueDepth() {
return executorService.getQueue().size();
}
@Override
public int getRemainingQueueCapacity() {
return executorService.getQueue().remainingCapacity();
}
@Override
public int getQueueCapacity() {
return config.getQueueCapacity();
}
@Override
public int getActiveThreadCount() {
return executorService.getActiveCount();
}
@Override
public int getAvailableThreadCount() {
return getMaximumThreadPoolSize() - getActiveThreadCount();
}
}
}
| BulkheadMetrics |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/PassThroughConfigUpdateTests.java | {
"start": 927,
"end": 4371
} | class ____ extends AbstractNlpConfigUpdateTestCase<PassThroughConfigUpdate> {
public static PassThroughConfigUpdate randomUpdate() {
PassThroughConfigUpdate.Builder builder = new PassThroughConfigUpdate.Builder();
if (randomBoolean()) {
builder.setResultsField(randomAlphaOfLength(8));
}
if (randomBoolean()) {
builder.setTokenizationUpdate(new BertTokenizationUpdate(randomFrom(Tokenization.Truncate.values()), null));
}
return builder.build();
}
public static PassThroughConfigUpdate mutateForVersion(PassThroughConfigUpdate instance, TransportVersion version) {
if (version.before(TransportVersions.V_8_1_0)) {
return new PassThroughConfigUpdate(instance.getResultsField(), null);
}
return instance;
}
@Override
Tuple<Map<String, Object>, PassThroughConfigUpdate> fromMapTestInstances(TokenizationUpdate expectedTokenization) {
PassThroughConfigUpdate expected = new PassThroughConfigUpdate("ml-results", expectedTokenization);
Map<String, Object> config = new HashMap<>() {
{
put(NlpConfig.RESULTS_FIELD.getPreferredName(), "ml-results");
}
};
return Tuple.tuple(config, expected);
}
@Override
PassThroughConfigUpdate fromMap(Map<String, Object> map) {
return PassThroughConfigUpdate.fromMap(map);
}
public void testApply() {
PassThroughConfig originalConfig = PassThroughConfigTests.createRandom();
assertEquals(originalConfig, originalConfig.apply(new PassThroughConfigUpdate.Builder().build()));
assertThat(
new PassThroughConfig(originalConfig.getVocabularyConfig(), originalConfig.getTokenization(), "ml-results"),
equalTo(originalConfig.apply(new PassThroughConfigUpdate.Builder().setResultsField("ml-results").build()))
);
Tokenization.Truncate truncate = randomFrom(Tokenization.Truncate.values());
Tokenization tokenization = cloneWithNewTruncation(originalConfig.getTokenization(), truncate);
assertThat(
new PassThroughConfig(originalConfig.getVocabularyConfig(), tokenization, originalConfig.getResultsField()),
equalTo(
originalConfig.apply(
new PassThroughConfigUpdate.Builder().setTokenizationUpdate(
createTokenizationUpdate(originalConfig.getTokenization(), truncate, null)
).build()
)
)
);
}
@Override
protected PassThroughConfigUpdate doParseInstance(XContentParser parser) throws IOException {
return PassThroughConfigUpdate.fromXContentStrict(parser);
}
@Override
protected Writeable.Reader<PassThroughConfigUpdate> instanceReader() {
return PassThroughConfigUpdate::new;
}
@Override
protected PassThroughConfigUpdate createTestInstance() {
return randomUpdate();
}
@Override
protected PassThroughConfigUpdate mutateInstance(PassThroughConfigUpdate instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected PassThroughConfigUpdate mutateInstanceForVersion(PassThroughConfigUpdate instance, TransportVersion version) {
return mutateForVersion(instance, version);
}
}
| PassThroughConfigUpdateTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/VarCheckerTest.java | {
"start": 908,
"end": 1226
} | class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(VarChecker.class, getClass());
// fields are ignored
@Test
public void nonFinalField() {
compilationHelper
.addSourceLines(
"Test.java",
"""
| VarCheckerTest |
java | apache__camel | components/camel-influxdb2/src/main/java/org/apache/camel/component/influxdb2/converters/CamelInfluxDb2Converters.java | {
"start": 1196,
"end": 1974
} | class ____ {
private CamelInfluxDb2Converters() {
}
@Converter
public static Point fromMapToPoint(Map<String, Object> map) {
Object measurementName = map.get(InfluxDb2Constants.MEASUREMENT);
if (measurementName == null) {
String format = String.format("Unable to find the header for the measurement in: %s", map.keySet().toString());
throw new CamelInfluxDb2Exception(format);
}
String measurenmentNameString = measurementName.toString();
Point point = Point.measurement(measurenmentNameString);
map.remove(InfluxDb2Constants.MEASUREMENT);
point.addFields(map);
map.put(InfluxDb2Constants.MEASUREMENT, measurementName);
return point;
}
}
| CamelInfluxDb2Converters |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/component/extension/ComponentVerifierExtension.java | {
"start": 1947,
"end": 2979
} | interface ____ extends ComponentExtension {
/**
* Verify the given parameters against a provided scope.
*
* <p>
* The supported scopes are:
* <ul>
* <li><strong>{@link ComponentVerifierExtension.Scope#PARAMETERS}</strong>: to validate that all the mandatory
* options are provided and syntactically correct.</li>
* <li><strong>{@link ComponentVerifierExtension.Scope#CONNECTIVITY}</strong>: to validate that the given options
* (i.e. credentials, addresses) are correct. Verifying with this scope typically implies reaching out to the
* backend via some sort of network connection.</li>
* </ul>
*
* @param scope the scope of the verification
* @param parameters the parameters to verify which are interpreted individually by each component verifier
* @return the verification result
*/
Result verify(Scope scope, Map<String, Object> parameters);
/**
* The result of a verification
*/
| ComponentVerifierExtension |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/BaseOpenSamlLogoutRequestValidatorParametersResolver.java | {
"start": 2459,
"end": 9294
} | class ____
implements Saml2LogoutRequestValidatorParametersResolver {
static {
OpenSamlInitializationService.initialize();
}
private final OpenSamlOperations saml;
private final RelyingPartyRegistrationRepository registrations;
private RequestMatcher requestMatcher = new OrRequestMatcher(pathPattern("/logout/saml2/slo/{registrationId}"),
pathPattern("/logout/saml2/slo"));
/**
* Constructs a {@link BaseOpenSamlLogoutRequestValidatorParametersResolver}
*/
BaseOpenSamlLogoutRequestValidatorParametersResolver(OpenSamlOperations saml,
RelyingPartyRegistrationRepository registrations) {
Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null");
this.saml = saml;
this.registrations = registrations;
}
/**
* Construct the parameters necessary for validating an asserting party's
* {@code <saml2:LogoutRequest>} based on the given {@link HttpServletRequest}
*
* <p>
* Uses the configured {@link RequestMatcher} to identify the processing request,
* including looking for any indicated {@code registrationId}.
*
* <p>
* If a {@code registrationId} is found in the request, it will attempt to use that,
* erroring if no {@link RelyingPartyRegistration} is found.
*
* <p>
* If no {@code registrationId} is found in the request, it will look for a currently
* logged-in user and use the associated {@code registrationId}.
*
* <p>
* In the event that neither the URL nor any logged in user could determine a
* {@code registrationId}, this code then will try and derive a
* {@link RelyingPartyRegistration} given the {@code <saml2:LogoutRequest>}'s
* {@code Issuer} value.
* @param request the HTTP request
* @return a {@link Saml2LogoutRequestValidatorParameters} instance, or {@code null}
* if one could not be resolved
* @throws Saml2AuthenticationException if the {@link RequestMatcher} specifies a
* non-existent {@code registrationId}
*/
@Override
public Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, Authentication authentication) {
if (request.getParameter(Saml2ParameterNames.SAML_REQUEST) == null) {
return null;
}
RequestMatcher.MatchResult result = this.requestMatcher.matcher(request);
if (!result.isMatch()) {
return null;
}
String registrationId = getRegistrationId(result, authentication);
if (registrationId == null) {
return logoutRequestByEntityId(request, authentication);
}
return logoutRequestById(request, authentication, registrationId);
}
/**
* The request matcher to use to identify a request to process a
* {@code <saml2:LogoutRequest>}. By default, checks for {@code /logout/saml2/slo} and
* {@code /logout/saml2/slo/{registrationId}}.
*
* <p>
* Generally speaking, the URL does not need to have a {@code registrationId} in it
* since either it can be looked up from the active logged in user or it can be
* derived through the {@code Issuer} in the {@code <saml2:LogoutRequest>}.
* @param requestMatcher the {@link RequestMatcher} to use
*/
void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
private String getRegistrationId(RequestMatcher.MatchResult result, Authentication authentication) {
String registrationId = result.getVariables().get("registrationId");
if (registrationId != null) {
return registrationId;
}
if (authentication == null) {
return null;
}
if (authentication instanceof Saml2AssertionAuthentication saml2) {
return saml2.getRelyingPartyRegistrationId();
}
if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal saml2) {
return saml2.getRelyingPartyRegistrationId();
}
return null;
}
private Saml2LogoutRequestValidatorParameters logoutRequestById(HttpServletRequest request,
Authentication authentication, String registrationId) {
RelyingPartyRegistration registration = this.registrations.findByRegistrationId(registrationId);
if (registration == null) {
throw new Saml2AuthenticationException(
Saml2Error.relyingPartyRegistrationNotFound("registration not found"));
}
return logoutRequestByRegistration(request, registration, authentication);
}
private Saml2LogoutRequestValidatorParameters logoutRequestByEntityId(HttpServletRequest request,
Authentication authentication) {
String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST);
LogoutRequest logoutRequest = this.saml.deserialize(
Saml2Utils.withEncoded(serialized).inflate(HttpMethod.GET.matches(request.getMethod())).decode());
String issuer = logoutRequest.getIssuer().getValue();
RelyingPartyRegistration registration = this.registrations.findUniqueByAssertingPartyEntityId(issuer);
return logoutRequestByRegistration(request, registration, authentication);
}
private Saml2LogoutRequestValidatorParameters logoutRequestByRegistration(HttpServletRequest request,
RelyingPartyRegistration registration, Authentication authentication) {
if (registration == null) {
return null;
}
Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request);
registration = fromRequest(request, registration);
String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST);
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration)
.samlRequest(serialized)
.relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE))
.binding(saml2MessageBinding)
.location(registration.getSingleLogoutServiceLocation())
.parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG,
request.getParameter(Saml2ParameterNames.SIG_ALG)))
.parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE,
request.getParameter(Saml2ParameterNames.SIGNATURE)))
.parametersQuery((params) -> request.getQueryString())
.build();
return new Saml2LogoutRequestValidatorParameters(logoutRequest, registration, authentication);
}
private RelyingPartyRegistration fromRequest(HttpServletRequest request, RelyingPartyRegistration registration) {
RelyingPartyRegistrationPlaceholderResolvers.UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers
.uriResolver(request, registration);
String entityId = uriResolver.resolve(registration.getEntityId());
String logoutLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation());
String logoutResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation());
return registration.mutate()
.entityId(entityId)
.singleLogoutServiceLocation(logoutLocation)
.singleLogoutServiceResponseLocation(logoutResponseLocation)
.build();
}
}
| BaseOpenSamlLogoutRequestValidatorParametersResolver |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/StreamToStringTest.java | {
"start": 2555,
"end": 2974
} | class ____ implements java.util.stream.Stream {
public String s() {
return toString();
}
}
""")
.doTest();
}
@Test
public void viaJoiner() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.common.base.Joiner;
import java.util.stream.Stream;
| Test |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/impl/pb/service/HSClientProtocolPBServiceImpl.java | {
"start": 999,
"end": 1196
} | class ____ extends MRClientProtocolPBServiceImpl
implements HSClientProtocolPB {
public HSClientProtocolPBServiceImpl(HSClientProtocol impl) {
super(impl);
}
}
| HSClientProtocolPBServiceImpl |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/Bean.java | {
"start": 1114,
"end": 2295
} | class ____ implements Serializable {
private Class<?> type;
private PersonStatus status;
private Date date;
private Phone[] array;
private Collection<Phone> collection;
private Map<String, FullAddress> addresses;
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
public PersonStatus getStatus() {
return status;
}
public void setStatus(PersonStatus status) {
this.status = status;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Phone[] getArray() {
return array;
}
public void setArray(Phone[] array) {
this.array = array;
}
public Collection<Phone> getCollection() {
return collection;
}
public void setCollection(Collection<Phone> collection) {
this.collection = collection;
}
public Map<String, FullAddress> getAddresses() {
return addresses;
}
public void setAddresses(Map<String, FullAddress> addresses) {
this.addresses = addresses;
}
}
| Bean |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java | {
"start": 6779,
"end": 7252
} | class ____ in search of the desired
* field. In addition, an attempt will be made to make non-{@code public}
* fields <em>accessible</em>, thus allowing one to set {@code protected},
* {@code private}, and <em>package-private</em> fields.
* <p>This method does not support setting {@code static final} fields.
* @param targetObject the target object on which to set the field; may be
* {@code null} if the field is static
* @param targetClass the target | hierarchy |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RRateLimiterRx.java | {
"start": 899,
"end": 9018
} | interface ____ extends RExpirableRx {
/**
* Use {@link #trySetRate(RateType, long, Duration)} instead
*
* @param mode rate mode
* @param rate rate
* @param rateInterval rate time interval
* @param rateIntervalUnit rate time interval unit
* @return {@code true} if rate was set and {@code false}
* otherwise
*/
@Deprecated
Single<Boolean> trySetRate(RateType mode, long rate, long rateInterval, RateIntervalUnit rateIntervalUnit);
/**
* Sets the rate limit only if it hasn't been set before.
*
* @param mode rate mode
* @param rate rate
* @param rateInterval rate time interval
* @return {@code true} if rate was set and {@code false}
* otherwise
*/
Single<Boolean> trySetRate(RateType mode, long rate, Duration rateInterval);
/**
* Sets the rate limit only if it hasn't been set before.
* Time to live is applied only if rate limit has been set successfully.
*
* @param mode rate mode
* @param rate rate
* @param rateInterval rate time interval
* @param keepAliveTime this is the maximum time that the limiter will wait for a new acquisition before deletion
* @return {@code true} if rate was set and {@code false}
* otherwise
*/
Single<Boolean> trySetRate(RateType mode, long rate, Duration rateInterval, Duration keepAliveTime);
/**
* Use {@link #setRate(RateType, long, Duration)} instead.
*
* @param mode rate mode
* @param rate rate
* @param rateInterval rate time interval
* @param rateIntervalUnit rate time interval unit
*
*/
@Deprecated
Single<Void> setRate(RateType mode, long rate, long rateInterval, RateIntervalUnit rateIntervalUnit);
/**
* Sets the rate limit and clears the state.
* Overrides both limit and state if they haven't been set before.
*
* @param mode rate mode
* @param rate rate
* @param rateInterval rate time interval
*/
Single<Void> setRate(RateType mode, long rate, Duration rateInterval);
/**
* Sets time to live, the rate limit, and clears the state.
* Overrides both limit and state if they haven't been set before.
*
* @param mode rate mode
* @param rate rate
* @param rateInterval rate time interval
* @param keepAliveTime this is the maximum time that the limiter will wait for a new acquisition before deletion
*/
Single<Void> setRate(RateType mode, long rate, Duration rateInterval, Duration keepAliveTime);
/**
* Acquires a permit only if one is available at the
* time of invocation.
*
* <p>Acquires a permit, if one is available and returns immediately,
* with the value {@code true},
* reducing the number of available permits by one.
*
* <p>If no permit is available then this method will return
* immediately with the value {@code false}.
*
* @return {@code true} if a permit was acquired and {@code false}
* otherwise
*/
Single<Boolean> tryAcquire();
/**
* Acquires the given number of <code>permits</code> only if all are available at the
* time of invocation.
*
* <p>Acquires a permits, if all are available and returns immediately,
* with the value {@code true},
* reducing the number of available permits by given number of permits.
*
* <p>If no permits are available then this method will return
* immediately with the value {@code false}.
*
* @param permits the number of permits to acquire
* @return {@code true} if a permit was acquired and {@code false}
* otherwise
*/
Single<Boolean> tryAcquire(long permits);
/**
* Acquires a permit from this RateLimiter, blocking until one is available.
*
* <p>Acquires a permit, if one is available and returns immediately,
* reducing the number of available permits by one.
*
* @return void
*/
Completable acquire();
/**
* Acquires a specified <code>permits</code> from this RateLimiter,
* blocking until one is available.
*
* <p>Acquires the given number of permits, if they are available
* and returns immediately, reducing the number of available permits
* by the given amount.
*
* @param permits the number of permits to acquire
* @return void
*/
Completable acquire(long permits);
/**
* Use {@link #tryAcquire(Duration)} instead.
*
* @param timeout the maximum time to wait for a permit
* @param unit the time unit of the {@code timeout} argument
* @return {@code true} if a permit was acquired and {@code false}
* if the waiting time elapsed before a permit was acquired
*/
@Deprecated
Single<Boolean> tryAcquire(long timeout, TimeUnit unit);
/**
* Acquires a permit from this RateLimiter, if one becomes available
* within the given waiting time.
*
* <p>Acquires a permit, if one is available and returns immediately,
* with the value {@code true},
* reducing the number of available permits by one.
*
* <p>If no permit is available then the current thread becomes
* disabled for thread scheduling purposes and lies dormant until
* specified waiting time elapses.
*
* <p>If a permit is acquired then the value {@code true} is returned.
*
* <p>If the specified waiting time elapses then the value {@code false}
* is returned. If the time is less than or equal to zero, the method
* will not wait at all.
*
* @param timeout the maximum time to wait for a permit
* @return {@code true} if a permit was acquired and {@code false}
* if the waiting time elapsed before a permit was acquired
*/
Single<Boolean> tryAcquire(Duration timeout);
/**
* Use {@link #tryAcquire(long, Duration)} instead.
*
* @param permits amount
* @param timeout the maximum time to wait for a permit
* @param unit the time unit of the {@code timeout} argument
* @return {@code true} if a permit was acquired and {@code false}
* if the waiting time elapsed before a permit was acquired
*/
@Deprecated
Single<Boolean> tryAcquire(long permits, long timeout, TimeUnit unit);
/**
* Acquires the given number of <code>permits</code> only if all are available
* within the given waiting time.
*
* <p>Acquires the given number of permits, if all are available and returns immediately,
* with the value {@code true}, reducing the number of available permits by one.
*
* <p>If no permit is available then the current thread becomes
* disabled for thread scheduling purposes and lies dormant until
* the specified waiting time elapses.
*
* <p>If a permits is acquired then the value {@code true} is returned.
*
* <p>If the specified waiting time elapses then the value {@code false}
* is returned. If the time is less than or equal to zero, the method
* will not wait at all.
*
* @param permits amount
* @param timeout the maximum time to wait for a permit
* @return {@code true} if a permit was acquired and {@code false}
* if the waiting time elapsed before a permit was acquired
*/
Single<Boolean> tryAcquire(long permits, Duration timeout);
/**
* Releases the given number of <code>permits</code>.
*
* <p>Increases the number of available permits by the specified amount and completes
* immediately, causing any waiting acquirers that can now obtain permits to proceed.
*
* <p>The returned future completes when the release has been applied.
*
* @param permits amount to release; must be greater than or equal to zero
*/
Completable release(long permits);
/**
* Returns amount of available permits.
*
* @return number of permits
*/
Single<Long> availablePermits();
}
| RRateLimiterRx |
java | junit-team__junit5 | junit-platform-console/src/main/java/org/junit/platform/console/output/DetailsPrintingListener.java | {
"start": 653,
"end": 959
} | interface ____ extends TestExecutionListener {
Pattern LINE_START_PATTERN = Pattern.compile("(?m)^");
void listTests(TestPlan testPlan);
static String indented(String message, String indentation) {
return LINE_START_PATTERN.matcher(message).replaceAll(indentation).strip();
}
}
| DetailsPrintingListener |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/array/ArrayContainsUnnestFunction.java | {
"start": 762,
"end": 3035
} | class ____ extends AbstractArrayContainsFunction {
public ArrayContainsUnnestFunction(boolean nullable, TypeConfiguration typeConfiguration) {
super( nullable, typeConfiguration );
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
final Expression haystackExpression = (Expression) sqlAstArguments.get( 0 );
final Expression needleExpression = (Expression) sqlAstArguments.get( 1 );
final JdbcMappingContainer needleTypeContainer = needleExpression.getExpressionType();
final JdbcMapping needleType = needleTypeContainer == null ? null : needleTypeContainer.getSingleJdbcMapping();
if ( needleType == null || needleType instanceof BasicPluralType<?, ?> ) {
LOG.deprecatedArrayContainsWithArray();
sqlAppender.append( '(' );
if ( ArrayHelper.isNullable( haystackExpression ) ) {
walker.render( haystackExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
sqlAppender.append( " is not null and " );
}
if ( ArrayHelper.isNullable( needleExpression ) ) {
walker.render( needleExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
sqlAppender.append( " is not null and " );
}
if ( !nullable ) {
sqlAppender.append( "not exists(select 1 from unnest(" );
walker.render( needleExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
sqlAppender.append( ") t(i) where t.i is null) and " );
}
sqlAppender.append( "not exists(select * from unnest(" );
walker.render( needleExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
sqlAppender.append( ") except select * from unnest(" );
walker.render( haystackExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
sqlAppender.append( ")))" );
}
else {
sqlAppender.append( "exists(select 1 from unnest(" );
walker.render( haystackExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
sqlAppender.append( ") t(i) where t.i" );
if ( nullable ) {
sqlAppender.append( " is not distinct from " );
}
else {
sqlAppender.append( '=' );
}
walker.render( needleExpression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
sqlAppender.append( ")" );
}
}
}
| ArrayContainsUnnestFunction |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportUpdateJobAction.java | {
"start": 1185,
"end": 2565
} | class ____ extends TransportMasterNodeAction<UpdateJobAction.Request, PutJobAction.Response> {
private final JobManager jobManager;
private final ProjectResolver projectResolver;
@Inject
public TransportUpdateJobAction(
TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
ActionFilters actionFilters,
JobManager jobManager,
ProjectResolver projectResolver
) {
super(
UpdateJobAction.NAME,
transportService,
clusterService,
threadPool,
actionFilters,
UpdateJobAction.Request::new,
PutJobAction.Response::new,
EsExecutors.DIRECT_EXECUTOR_SERVICE
);
this.jobManager = jobManager;
this.projectResolver = projectResolver;
}
@Override
protected void masterOperation(
Task task,
UpdateJobAction.Request request,
ClusterState state,
ActionListener<PutJobAction.Response> listener
) {
jobManager.updateJob(request, listener);
}
@Override
protected ClusterBlockException checkBlock(UpdateJobAction.Request request, ClusterState state) {
return state.blocks().globalBlockedException(projectResolver.getProjectId(), ClusterBlockLevel.METADATA_WRITE);
}
}
| TransportUpdateJobAction |
java | apache__camel | components/camel-telemetry/src/main/java/org/apache/camel/telemetry/decorators/KafkaSpanDecorator.java | {
"start": 3277,
"end": 3600
} | class ____ of the exchange header
*/
private <T> String getValue(final Exchange exchange, final String header, Class<T> type) {
T partition = exchange.getIn().getHeader(header, type);
return partition != null ? String.valueOf(partition) : exchange.getIn().getHeader(header, String.class);
}
}
| type |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenIT0025MultipleExecutionLevelConfigsTest.java | {
"start": 1034,
"end": 1766
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test multiple goal executions with different execution-level configs.
*
* @throws Exception in case of failure
*/
@Test
public void testit0025() throws Exception {
File testDir = extractResources("/it0025");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyFilePresent("target/test.txt");
verifier.verifyFilePresent("target/test2.txt");
}
}
| MavenIT0025MultipleExecutionLevelConfigsTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/CommandDocsTests.java | {
"start": 1431,
"end": 2044
} | class ____ exists to provide access to the examples rendering capabilities.
* It implements the normal renderSignature and renderDocs methods with empty implementations.
* Instead, it has a new renderExamples method that loads all the examples based on a file written by the gradle task.
* This task finds all files in esql/_snippets/commands/examples/*.csv-spec/*.md and writes them to a file in the temp directory.
* This task will then overwrite those files with the current examples, so that changes to the examples will be reflected
* in the documentation.
*/
public static | only |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/dynamic/codec/RedisCodecResolver.java | {
"start": 266,
"end": 592
} | interface ____ {
/**
* Resolve a {@link RedisCodec} for the given {@link CommandMethod}.
*
* @param commandMethod must not be {@code null}.
* @return the resolved {@link RedisCodec} or {@code null} if not resolvable.
*/
RedisCodec<?, ?> resolve(CommandMethod commandMethod);
}
| RedisCodecResolver |
java | quarkusio__quarkus | independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/Types.java | {
"start": 5413,
"end": 5514
} | class ____ an array then the component type of the array is canonicalized
*
* Otherwise, the | is |
java | apache__avro | lang/java/mapred/src/test/java/org/apache/avro/mapreduce/TestKeyValueWordCount.java | {
"start": 1792,
"end": 1874
} | class ____ {
@TempDir
public File mTempDir;
public static | TestKeyValueWordCount |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/builder/BuilderWithCreatorTest.java | {
"start": 745,
"end": 1340
} | class ____ {
private final int a, b;
private int c;
@JsonCreator
public PropertyCreatorBuilder(@JsonProperty("a") int a,
@JsonProperty("b") int b)
{
this.a = a;
this.b = b;
}
public PropertyCreatorBuilder withC(int v) {
c = v;
return this;
}
public PropertyCreatorValue build() {
return new PropertyCreatorValue(a, b, c);
}
}
// With String
@JsonDeserialize(builder=StringCreatorBuilder.class)
static | PropertyCreatorBuilder |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/SchemaGeneratorMojo.java | {
"start": 59719,
"end": 71374
} | class ____ outputs.
* <p/>
* There are some classes which does not support outputs, even though they have a outputs element.
*/
private boolean supportOutputs(Class<?> classElement) {
return loadClass("org.apache.camel.model.OutputNode").isAssignableFrom(classElement);
}
private String findDefaultValue(Field fieldElement, String fieldTypeName) {
String defaultValue = null;
Metadata metadata = fieldElement.getAnnotation(Metadata.class);
if (metadata != null) {
if (!Strings.isNullOrEmpty(metadata.defaultValue())) {
defaultValue = metadata.defaultValue();
}
}
if (defaultValue == null) {
// if its a boolean type, then we use false as the default
if ("boolean".equals(fieldTypeName) || "java.lang.Boolean".equals(fieldTypeName)) {
defaultValue = "false";
}
}
return defaultValue;
}
private boolean expressionRequired(String modelName) {
if ("method".equals(modelName) || "tokenize".equals(modelName)) {
// skip expression attribute on these two languages as they are
// solely configured using attributes
return false;
}
return true;
}
private boolean findRequired(Field fieldElement, boolean defaultValue) {
Metadata metadata = fieldElement.getAnnotation(Metadata.class);
if (metadata != null) {
return metadata.required();
}
return defaultValue;
}
private boolean hasAbstract(Class<?> classElement) {
for (String name : ONE_OF_ABSTRACTS) {
if (hasSuperClass(classElement, name)) {
return true;
}
}
return false;
}
private boolean hasInput(Class<?> classElement) {
for (String name : ONE_OF_INPUTS) {
if (hasSuperClass(classElement, name)) {
return true;
}
}
return false;
}
private boolean hasOutput(EipModel model) {
switch (model.getName()) {
// if we are route/rest then we accept output
case "route":
case "routeTemplate":
case "rest":
return true;
// special for transacted/policy which should not have output
case "policy":
case "transacted":
return false;
default:
return model.getOptions().stream().anyMatch(option -> "outputs".equals(option.getName()));
}
}
private EipOptionModel createOption(
String name, String displayName, String kind, String type, boolean required, String defaultValue, String label,
String description, boolean deprecated,
String deprecationNote, boolean enumType, Set<String> enums, Set<String> oneOfs, boolean asPredicate,
boolean isDuration, boolean important) {
EipOptionModel option = new EipOptionModel();
option.setName(name);
option.setDisplayName(Strings.isNullOrEmpty(displayName) ? Strings.asTitle(name) : displayName);
option.setKind(kind);
option.setRequired(required);
option.setDefaultValue("java.lang.Boolean".equals(type) && !Strings.isNullOrEmpty(defaultValue)
? Boolean.parseBoolean(defaultValue) : defaultValue);
if (!Strings.isNullOrEmpty(label)) {
option.setLabel(label);
}
option.setDescription(JavadocHelper.sanitizeDescription(description, false));
option.setDeprecated(deprecated);
option.setDeprecationNote(Strings.isNullOrEmpty(deprecationNote) ? null : deprecationNote);
option.setType(getType(type, enumType, isDuration));
option.setJavaType(type);
option.setEnums(enums != null && !enums.isEmpty() ? new ArrayList<>(enums) : null);
option.setOneOfs(oneOfs != null && !oneOfs.isEmpty() ? new ArrayList<>(oneOfs) : null);
option.setAsPredicate(asPredicate);
option.setImportant(important);
return option;
}
private boolean hasSuperClass(Class<?> classElement, String superClassName) {
return loadClass(superClassName).isAssignableFrom(classElement);
}
private String findJavaDoc(
Field fieldElement, String fieldName, String name, Class<?> classElement, boolean builderPattern) {
if (fieldElement != null) {
Metadata md = fieldElement.getAnnotation(Metadata.class);
if (md != null) {
String doc = md.description();
if (!Strings.isNullOrEmpty(doc)) {
return doc;
}
}
}
JavaClassSource source = javaClassSource(classElement.getName());
FieldSource<JavaClassSource> field = source.getField(fieldName);
if (field != null) {
String doc = field.getJavaDoc().getFullText();
if (!Strings.isNullOrEmpty(doc)) {
return doc;
}
}
String setterName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
// special for mdcLoggingKeysPattern
if ("setMdcLoggingKeysPattern".equals(setterName)) {
setterName = "setMDCLoggingKeysPattern";
}
for (MethodSource<JavaClassSource> setter : source.getMethods()) {
if (setter.getParameters().size() == 1
&& setter.getName().equals(setterName)) {
String doc = setter.getJavaDoc().getFullText();
if (!Strings.isNullOrEmpty(doc)) {
return doc;
}
}
}
String getterName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
for (MethodSource<JavaClassSource> setter : source.getMethods()) {
if (setter.getParameters().isEmpty()
&& setter.getName().equals(getterName)) {
String doc = setter.getJavaDoc().getFullText();
if (!Strings.isNullOrEmpty(doc)) {
return doc;
}
}
}
if (builderPattern) {
if (name != null && !name.equals(fieldName)) {
String doc = getDoc(source, name);
if (doc != null) {
return doc;
}
}
String doc = getDoc(source, fieldName);
if (doc != null) {
return doc;
}
}
return "";
}
private String getDoc(JavaClassSource source, String name) {
for (MethodSource<JavaClassSource> builder : source.getMethods()) {
if (builder.getParameters().size() == 1 && builder.getName().equals(name)) {
String doc = builder.getJavaDoc().getFullText();
if (!Strings.isNullOrEmpty(doc)) {
return doc;
}
}
}
for (MethodSource<JavaClassSource> builder : source.getMethods()) {
if (builder.getParameters().isEmpty() && builder.getName().equals(name)) {
String doc = builder.getJavaDoc().getFullText();
if (!Strings.isNullOrEmpty(doc)) {
return doc;
}
}
}
return null;
}
private String getDocComment(Class<?> classElement) {
JavaClassSource source = javaClassSource(classElement.getName());
return source.getJavaDoc().getFullText();
}
private JavaClassSource javaClassSource(String className) {
return sources.computeIfAbsent(className, this::doParseJavaClassSource);
}
private JavaClassSource doParseJavaClassSource(String className) {
try {
Path srcDir = project.getBasedir().toPath().resolve("src/main/java");
Path file = srcDir.resolve(className.replace('.', '/') + ".java");
String fileContent = new String(Files.readAllBytes(file));
return (JavaClassSource) Roaster.parse(fileContent);
} catch (IOException e) {
throw new RuntimeException("Unable to parse java class " + className, e);
}
}
private static String getTypeName(Type fieldType) {
String fieldTypeName = new GenericType(fieldType).toString();
fieldTypeName = fieldTypeName.replace('$', '.');
return fieldTypeName;
}
/**
* Gets the JSON schema type.
*
* @param type the java type
* @return the json schema type, is never null, but returns <tt>object</tt> as the generic type
*/
public static String getType(String type, boolean enumType, boolean isDuration) {
if (enumType) {
return "enum";
} else if (isDuration) {
return "duration";
} else if (type == null) {
// return generic type for unknown type
return "object";
} else if (type.equals(URI.class.getName()) || type.equals(URL.class.getName())) {
return "string";
} else if (type.equals(File.class.getName())) {
return "string";
} else if (type.equals(Date.class.getName())) {
return "string";
} else if (type.startsWith("java.lang.Class")) {
return "string";
} else if (type.startsWith("java.util.List") || type.startsWith("java.util.Collection")) {
return "array";
}
String primitive = getPrimitiveType(type);
if (primitive != null) {
return primitive;
}
return "object";
}
/**
* Gets the JSON schema primitive type.
*
* @param name the java type
* @return the json schema primitive type, or <tt>null</tt> if not a primitive
*/
public static String getPrimitiveType(String name) {
// special for byte[] or Object[] as its common to use
if ("java.lang.byte[]".equals(name) || "byte[]".equals(name)) {
return "string";
} else if ("java.lang.Byte[]".equals(name) || "Byte[]".equals(name)) {
return "array";
} else if ("java.lang.Object[]".equals(name) || "Object[]".equals(name)) {
return "array";
} else if ("java.lang.String[]".equals(name) || "String[]".equals(name)) {
return "array";
} else if ("java.lang.Character".equals(name) || "Character".equals(name) || "char".equals(name)) {
return "string";
} else if ("java.lang.String".equals(name) || "String".equals(name)) {
return "string";
} else if ("java.lang.Boolean".equals(name) || "Boolean".equals(name) || "boolean".equals(name)) {
return "boolean";
} else if ("java.lang.Integer".equals(name) || "Integer".equals(name) || "int".equals(name)) {
return "integer";
} else if ("java.lang.Long".equals(name) || "Long".equals(name) || "long".equals(name)) {
return "integer";
} else if ("java.lang.Short".equals(name) || "Short".equals(name) || "short".equals(name)) {
return "integer";
} else if ("java.lang.Byte".equals(name) || "Byte".equals(name) || "byte".equals(name)) {
return "integer";
} else if ("java.lang.Float".equals(name) || "Float".equals(name) || "float".equals(name)) {
return "number";
} else if ("java.lang.Double".equals(name) || "Double".equals(name) || "double".equals(name)) {
return "number";
}
return null;
}
private static final | supports |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/rest/action/RestExecuteWatchActionTests.java | {
"start": 967,
"end": 2897
} | class ____ extends ESTestCase {
private NodeClient client = mock(NodeClient.class);
public void testThatFlagsCanBeSpecifiedViaParameters() throws Exception {
String randomId = randomAlphaOfLength(10);
for (String recordExecution : Arrays.asList("true", "false", null)) {
for (String ignoreCondition : Arrays.asList("true", "false", null)) {
for (String debugCondition : Arrays.asList("true", "false", null)) {
ExecuteWatchRequest request = RestExecuteWatchAction.parseRequest(
createFakeRestRequest(randomId, recordExecution, ignoreCondition, debugCondition),
client
);
assertThat(request.getId(), is(randomId));
assertThat(request.isRecordExecution(), is(Booleans.parseBoolean(recordExecution, false)));
assertThat(request.isIgnoreCondition(), is(Booleans.parseBoolean(ignoreCondition, false)));
assertThat(request.isDebug(), is(Booleans.parseBoolean(debugCondition, false)));
}
}
}
}
private FakeRestRequest createFakeRestRequest(String randomId, String recordExecution, String ignoreCondition, String debugCondition) {
FakeRestRequest.Builder builder = new Builder(NamedXContentRegistry.EMPTY);
builder.withContent(new BytesArray("{}"), XContentType.JSON);
Map<String, String> params = new HashMap<>();
params.put("id", randomId);
// make sure we test true/false/no params
if (recordExecution != null) params.put("record_execution", recordExecution);
if (ignoreCondition != null) params.put("ignore_condition", ignoreCondition);
if (debugCondition != null) params.put("debug", debugCondition);
builder.withParams(params);
return builder.build();
}
}
| RestExecuteWatchActionTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/SharedStateRegistryFactory.java | {
"start": 1112,
"end": 1670
} | interface ____ {
/**
* Factory method for {@link SharedStateRegistry}.
*
* @param deleteExecutor executor used to run (async) deletes.
* @param checkpoints whose shared state will be registered.
* @param recoveryClaimMode the mode in which the given checkpoints were restored
* @return a SharedStateRegistry object
*/
SharedStateRegistry create(
Executor deleteExecutor,
Collection<CompletedCheckpoint> checkpoints,
RecoveryClaimMode recoveryClaimMode);
}
| SharedStateRegistryFactory |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/injection/InjectorTests.java | {
"start": 4646,
"end": 5378
} | interface ____ {}
public record Component1() implements Listener {}
public record Component2(Component1 component1) {}
public record Component3(Service1 service1) {}
public record Component4(Listener listener) {}
public record GoodService(List<Component1> components) {}
public record BadService(List<Component1> components) {
public BadService {
// Shouldn't be using the component list here!
assert components.isEmpty() == false;
}
}
public record MultiService(List<Component1> component1s, List<Component2> component2s) {}
public record Circular1(Circular2 service2) {}
public record Circular2(Circular1 service2) {}
public static | Listener |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/metadata/ReservedStateErrorMetadata.java | {
"start": 1128,
"end": 4679
} | class ____ hold error information about errors encountered
* while applying a cluster state update for a given namespace.
* <p>
* This information is held by the {@link ReservedStateMetadata} class.
*/
public record ReservedStateErrorMetadata(Long version, ErrorKind errorKind, List<String> errors)
implements
SimpleDiffable<ReservedStateErrorMetadata>,
ToXContentFragment {
static final ParseField ERRORS = new ParseField("errors");
static final ParseField VERSION = new ParseField("version");
static final ParseField ERROR_KIND = new ParseField("error_kind");
/**
* Constructs a reserved state error metadata
*
* @param version the metadata version of the content which failed to apply
* @param errorKind the kind of error we encountered while processing
* @param errors the list of errors encountered during parsing and validation of the reserved state content
*/
public ReservedStateErrorMetadata {}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeLong(version);
out.writeString(errorKind.getKindValue());
out.writeStringCollection(errors);
}
/**
* Reads an {@link ReservedStateErrorMetadata} from a {@link StreamInput}
*
* @param in the {@link StreamInput} to read from
* @return {@link ReservedStateErrorMetadata}
* @throws IOException
*/
public static ReservedStateErrorMetadata readFrom(StreamInput in) throws IOException {
return new ReservedStateErrorMetadata(
in.readLong(),
ErrorKind.of(in.readString()),
in.readCollectionAsList(StreamInput::readString)
);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(VERSION.getPreferredName(), version);
builder.field(ERROR_KIND.getPreferredName(), errorKind.getKindValue());
builder.stringListField(ERRORS.getPreferredName(), errors);
builder.endObject();
return builder;
}
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<ReservedStateErrorMetadata, Void> PARSER = new ConstructingObjectParser<>(
"reserved_state_error_metadata",
(a) -> new ReservedStateErrorMetadata((Long) a[0], ErrorKind.of((String) a[1]), (List<String>) a[2])
);
static {
PARSER.declareLong(constructorArg(), VERSION);
PARSER.declareString(constructorArg(), ERROR_KIND);
PARSER.declareStringArray(constructorArg(), ERRORS);
}
/**
* Reads an {@link ReservedStateErrorMetadata} from xContent
*
* @param parser {@link XContentParser}
* @return {@link ReservedStateErrorMetadata}
*/
public static ReservedStateErrorMetadata fromXContent(final XContentParser parser) {
return PARSER.apply(parser, null);
}
/**
* Reads an {@link ReservedStateErrorMetadata} {@link Diff} from {@link StreamInput}
*
* @param in the {@link StreamInput} to read the diff from
* @return a {@link Diff} of {@link ReservedStateErrorMetadata}
* @throws IOException
*/
public static Diff<ReservedStateErrorMetadata> readDiffFrom(StreamInput in) throws IOException {
return SimpleDiffable.readDiffFrom(ReservedStateErrorMetadata::readFrom, in);
}
/**
* Enum for kinds of errors we might encounter while processing reserved cluster state updates.
*/
public | to |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/DoubleArraysBaseTest.java | {
"start": 1047,
"end": 1391
} | class ____ testing <code>{@link DoubleArrays}</code>, set up an instance with {@link StandardComparisonStrategy} and
* another with {@link ComparatorBasedComparisonStrategy}.
* <p>
* Is in <code>org.assertj.core.internal</code> package to be able to set {@link DoubleArrays#failures} appropriately.
*
* @author Joel Costigliola
*/
public | for |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/servlet/assertj/MockMvcTesterCompatibilityIntegrationTests.java | {
"start": 1938,
"end": 2763
} | class ____ {
private final MockMvcTester mvc;
MockMvcTesterCompatibilityIntegrationTests(@Autowired WebApplicationContext wac) {
this.mvc = MockMvcTester.from(wac);
}
@Test
void performGet() {
assertThat(this.mvc.perform(get("/greet"))).hasStatusOk();
}
@Test
void performGetWithInvalidMediaTypeAssertion() {
MvcTestResult result = this.mvc.perform(get("/greet"));
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(result).hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.withMessageContaining("is compatible with 'application/json'");
}
@Test
void assertHttpStatusCode() {
assertThat(this.mvc.get().uri("/greet")).matches(status().isOk());
}
@Configuration
@EnableWebMvc
@Import(TestController.class)
static | MockMvcTesterCompatibilityIntegrationTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/jpa/event/spi/Callback.java | {
"start": 583,
"end": 907
} | interface ____ extends Serializable {
/**
* The type of callback (pre-update, pre-persist, etc) handled
*/
CallbackType getCallbackType();
/**
* Contract for performing the callback
*
* @param entity Reference to the entity for which the callback is triggered.
*/
void performCallback(Object entity);
}
| Callback |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/log/ThroughputLoggerTest.java | {
"start": 1030,
"end": 2470
} | class ____ extends ContextTestSupport {
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testSendMessageToLogUsingGroupSize() throws Exception {
context.addRoutes(new RouteBuilder() {
public void configure() {
from("seda:in").to("log:hello?groupSize=2").delay(100).to("mock:result");
}
});
context.start();
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(4);
template.sendBody("seda:in", "Hello World");
template.sendBody("seda:in", "Hello World");
template.sendBody("seda:in", "Bye World");
template.sendBody("seda:in", "Bye World");
assertMockEndpointsSatisfied();
}
@Test
public void testSendMessageToLogUsingGroupInterval() throws Exception {
context.addRoutes(new RouteBuilder() {
public void configure() {
from("seda:in").to("log:hello?groupInterval=200&groupDelay=400&groupActiveOnly=false").delay(50)
.to("mock:result");
}
});
context.start();
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(20);
for (int i = 0; i < 20; i++) {
template.sendBody("seda:in", "Hello World");
}
assertMockEndpointsSatisfied();
}
}
| ThroughputLoggerTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/CustomSerializersTest.java | {
"start": 5113,
"end": 5694
} | class ____ {
private Collection<String> set;
private String id;
public Item2475(Collection<String> set, String id) {
this.set = set;
this.id = id;
}
public Collection<String> getSet() {
return set;
}
public String getId() {
return id;
}
}
// [databind#4575]
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "@type")
@JsonSubTypes(
{
@JsonSubTypes.Type(Sub4575.class)
}
)
@JsonTypeName("Super")
static | Item2475 |
java | greenrobot__greendao | tests/DaoTest/src/androidTest/java/org/greenrobot/greendao/daotest/rx/RxTransactionTest.java | {
"start": 1234,
"end": 3501
} | class ____ extends AbstractDaoSessionTest<DaoMaster, DaoSession> {
private RxTransaction rxTx;
public RxTransactionTest() {
super(DaoMaster.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
rxTx = daoSession.rxTx();
}
public void testRun() {
Observable<Void> observable = rxTx.run(new Runnable() {
@Override
public void run() {
TestEntity entity = insertEntity("hello");
entity.setSimpleString("world");
daoSession.update(entity);
}
});
TestSubscriber<Void> testSubscriber = assertTxExecuted(observable);
assertNull(testSubscriber.getOnNextEvents().get(0));
}
public void testCall() {
testCall(rxTx);
}
public void testCallPlain() {
RxTransaction rxTxPlain = daoSession.rxTxPlain();
assertNotSame(rxTx, rxTxPlain);
testCall(rxTxPlain);
}
public void testCall(RxTransaction rxTx) {
Observable<String> observable = rxTx.call(new Callable<String>() {
@Override
public String call() {
TestEntity entity = insertEntity("hello");
entity.setSimpleString("world");
daoSession.update(entity);
return "Just checking";
}
});
TestSubscriber<String> testSubscriber = assertTxExecuted(observable);
assertEquals("Just checking", testSubscriber.getOnNextEvents().get(0));
}
private <T> TestSubscriber<T> assertTxExecuted(Observable<T> observable) {
TestSubscriber<T> testSubscriber = RxTestHelper.awaitTestSubscriber(observable);
assertEquals(1, testSubscriber.getValueCount());
daoSession.clear();
List<TestEntity> all = daoSession.getTestEntityDao().loadAll();
assertEquals(1, all.size());
assertEquals("hello", all.get(0).getSimpleStringNotNull());
assertEquals("world", all.get(0).getSimpleString());
return testSubscriber;
}
protected TestEntity insertEntity(String simpleStringNotNull) {
return RxTestHelper.insertEntity(daoSession.getTestEntityDao(), simpleStringNotNull);
}
}
| RxTransactionTest |
java | quarkusio__quarkus | extensions/oidc-client/deployment/src/test/java/io/quarkus/oidc/client/KeycloakRealmUserPasswordCustomFilterManager.java | {
"start": 772,
"end": 4549
} | class ____ implements QuarkusTestResourceLifecycleManager {
private static final String KEYCLOAK_SERVER_URL = System.getProperty("keycloak.url", "http://localhost:8180/auth");
private static final String KEYCLOAK_REALM = "quarkus3";
@Override
public Map<String, String> start() {
try {
RealmRepresentation realm = createRealm(KEYCLOAK_REALM);
realm.getClients().add(createClient("quarkus-app"));
realm.getUsers().add(createUser("bob", "user"));
RestAssured
.given()
.auth().oauth2(getAdminAccessToken())
.contentType("application/json")
.body(JsonSerialization.writeValueAsBytes(realm))
.when()
.post(KEYCLOAK_SERVER_URL + "/admin/realms").then()
.statusCode(201);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Collections.emptyMap();
}
private static String getAdminAccessToken() {
return RestAssured
.given()
.param("grant_type", "password")
.param("username", "admin")
.param("password", "admin")
.param("client_id", "admin-cli")
.when()
.post(KEYCLOAK_SERVER_URL + "/realms/master/protocol/openid-connect/token")
.as(AccessTokenResponse.class).getToken();
}
private static RealmRepresentation createRealm(String name) {
RealmRepresentation realm = new RealmRepresentation();
realm.setRealm(name);
realm.setEnabled(true);
realm.setUsers(new ArrayList<>());
realm.setClients(new ArrayList<>());
realm.setAccessTokenLifespan(3);
realm.setRevokeRefreshToken(true);
realm.setRefreshTokenMaxReuse(0);
realm.setDefaultRoles(Arrays.asList("user"));
realm.setRequiredActions(List.of());
RolesRepresentation roles = new RolesRepresentation();
List<RoleRepresentation> realmRoles = new ArrayList<>();
roles.setRealm(realmRoles);
realm.setRoles(roles);
realm.getRoles().getRealm().add(new RoleRepresentation("user", null, false));
realm.getRoles().getRealm().add(new RoleRepresentation("admin", null, false));
return realm;
}
private static ClientRepresentation createClient(String clientId) {
ClientRepresentation client = new ClientRepresentation();
client.setClientId(clientId);
client.setPublicClient(false);
client.setSecret("secret");
client.setDirectAccessGrantsEnabled(true);
client.setEnabled(true);
return client;
}
private static UserRepresentation createUser(String username, String... realmRoles) {
UserRepresentation user = new UserRepresentation();
user.setUsername(username);
user.setEnabled(true);
user.setCredentials(new ArrayList<>());
user.setRealmRoles(Arrays.asList(realmRoles));
user.setEmailVerified(true);
user.setRequiredActions(List.of());
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue(username);
credential.setTemporary(false);
user.getCredentials().add(credential);
return user;
}
@Override
public void stop() {
RestAssured
.given()
.auth().oauth2(getAdminAccessToken())
.when()
.delete(KEYCLOAK_SERVER_URL + "/admin/realms/" + KEYCLOAK_REALM).thenReturn().prettyPrint();
}
}
| KeycloakRealmUserPasswordCustomFilterManager |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/creators/JsonCreatorNoArgs4777Test.java | {
"start": 782,
"end": 2356
} | class ____ implements ValueInstantiators {
@Override
public ValueInstantiator modifyValueInstantiator(
DeserializationConfig config,
BeanDescription.Supplier beanDescRef,
ValueInstantiator defaultInstantiator
) {
if (beanDescRef.getBeanClass() == Foo4777.class) {
AnnotatedWithParams dc = defaultInstantiator.getDefaultCreator();
if (!(dc instanceof AnnotatedMethod)
|| !dc.getName().equals("create")) {
throw new IllegalArgumentException("Wrong DefaultCreator: should be static-method 'create()', is: "
+dc);
}
}
return defaultInstantiator;
}
@Override
public ValueInstantiator findValueInstantiator(DeserializationConfig config,
BeanDescription.Supplier beanDescRef) {
return null;
}
}
// For [databind#4777]
@SuppressWarnings("serial")
@Test
public void testCreatorDetection4777() throws Exception {
SimpleModule sm = new SimpleModule() {
@Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.addValueInstantiators(new Instantiators4777());
}
};
ObjectMapper mapper = JsonMapper.builder().addModule(sm).build();
Foo4777 result = mapper.readValue("{}", Foo4777.class);
assertNotNull(result);
}
}
| Instantiators4777 |
java | apache__rocketmq | store/src/main/java/org/apache/rocketmq/store/queue/MultiDispatchUtils.java | {
"start": 1184,
"end": 2623
} | class ____ {
public static String lmqQueueKey(String queueName) {
StringBuilder keyBuilder = new StringBuilder();
keyBuilder.append(queueName);
keyBuilder.append('-');
int queueId = 0;
keyBuilder.append(queueId);
return keyBuilder.toString();
}
public static boolean isNeedHandleMultiDispatch(MessageStoreConfig messageStoreConfig, String topic) {
return messageStoreConfig.isEnableMultiDispatch()
&& !topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)
&& !topic.startsWith(TopicValidator.SYSTEM_TOPIC_PREFIX)
&& !topic.equals(TopicValidator.RMQ_SYS_SCHEDULE_TOPIC);
}
public static boolean checkMultiDispatchQueue(MessageStoreConfig messageStoreConfig, DispatchRequest dispatchRequest) {
if (!isNeedHandleMultiDispatch(messageStoreConfig, dispatchRequest.getTopic())) {
return false;
}
Map<String, String> prop = dispatchRequest.getPropertiesMap();
if (prop == null || prop.isEmpty()) {
return false;
}
String multiDispatchQueue = prop.get(MessageConst.PROPERTY_INNER_MULTI_DISPATCH);
String multiQueueOffset = prop.get(MessageConst.PROPERTY_INNER_MULTI_QUEUE_OFFSET);
if (StringUtils.isBlank(multiDispatchQueue) || StringUtils.isBlank(multiQueueOffset)) {
return false;
}
return true;
}
}
| MultiDispatchUtils |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/gwt/GwtCompilationTest.java | {
"start": 10254,
"end": 10690
} | class ____<K extends Comparable<K>, V extends K> {",
" public abstract Map<K, V> map();",
" public abstract ImmutableMap<K, V> immutableMap();",
"",
" public static <K extends Comparable<K>, V extends K> Builder<K, V> builder() {",
" return new AutoValue_Baz.Builder<K, V>();",
" }",
"",
" @AutoValue.Builder",
" public | Baz |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/mappedsuperclass/typedmappedsuperclass/Post.java | {
"start": 252,
"end": 298
} | class ____<UserRoleType extends UserRole> {
}
| Post |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/WordMedian.java | {
"start": 2781,
"end": 7217
} | class ____ extends
Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
private IntWritable val = new IntWritable();
/**
* Sums all the individual values within the iterator and writes them to the
* same key.
*
* @param key
* This will be a length of a word that was read.
* @param values
* This will be an iterator of all the values associated with that
* key.
*/
public void reduce(IntWritable key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable value : values) {
sum += value.get();
}
val.set(sum);
context.write(key, val);
}
}
/**
* This is a standard program to read and find a median value based on a file
* of word counts such as: 1 456, 2 132, 3 56... Where the first values are
* the word lengths and the following values are the number of times that
* words of that length appear.
*
* @param path
* The path to read the HDFS file from (part-r-00000...00001...etc).
* @param medianIndex1
* The first length value to look for.
* @param medianIndex2
* The second length value to look for (will be the same as the first
* if there are an even number of words total).
* @throws IOException
* If file cannot be found, we throw an exception.
* */
private double readAndFindMedian(String path, int medianIndex1,
int medianIndex2, Configuration conf) throws IOException {
FileSystem fs = FileSystem.get(conf);
Path file = new Path(path, "part-r-00000");
if (!fs.exists(file))
throw new IOException("Output not found!");
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(file), StandardCharsets.UTF_8));
int num = 0;
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
// grab length
String currLen = st.nextToken();
// grab count
String lengthFreq = st.nextToken();
int prevNum = num;
num += Integer.parseInt(lengthFreq);
if (medianIndex2 >= prevNum && medianIndex1 <= num) {
System.out.println("The median is: " + currLen);
br.close();
return Double.parseDouble(currLen);
} else if (medianIndex2 >= prevNum && medianIndex1 < num) {
String nextCurrLen = st.nextToken();
double theMedian = (Integer.parseInt(currLen) + Integer
.parseInt(nextCurrLen)) / 2.0;
System.out.println("The median is: " + theMedian);
br.close();
return theMedian;
}
}
} finally {
if (br != null) {
br.close();
}
}
// error, no median found
return -1;
}
public static void main(String[] args) throws Exception {
ToolRunner.run(new Configuration(), new WordMedian(), args);
}
@Override
public int run(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs =
new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordmedian <in> <out>");
return 0;
}
setConf(conf);
Job job = Job.getInstance(conf, "word median");
job.setJarByClass(WordMedian.class);
job.setMapperClass(WordMedianMapper.class);
job.setCombinerClass(WordMedianReducer.class);
job.setReducerClass(WordMedianReducer.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
boolean result = job.waitForCompletion(true);
// Wait for JOB 1 -- get middle value to check for Median
long totalWords = job.getCounters()
.getGroup(TaskCounter.class.getCanonicalName())
.findCounter("MAP_OUTPUT_RECORDS", "Map output records").getValue();
int medianIndex1 = (int) Math.ceil((totalWords / 2.0));
int medianIndex2 = (int) Math.floor((totalWords / 2.0));
median = readAndFindMedian(args[1], medianIndex1, medianIndex2, conf);
return (result ? 0 : 1);
}
public double getMedian() {
return median;
}
}
| WordMedianReducer |
java | quarkusio__quarkus | extensions/schema-registry/apicurio/common/deployment/src/test/java/io/quarkus/apicurio/registry/common/ApicurioRegistryInternalsExpectationTest.java | {
"start": 152,
"end": 417
} | class ____ {
@Test
public void test() throws NoSuchFieldException {
// we need this to reset the client in continuous testing
ApicurioHttpClientFactory.class.getDeclaredField("providerReference");
}
}
| ApicurioRegistryInternalsExpectationTest |
java | quarkusio__quarkus | extensions/jackson/deployment/src/test/java/io/quarkus/jackson/deployment/JacksonWriteDatesAsTimestampsTest.java | {
"start": 502,
"end": 1112
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withConfigurationResource("application-write-dates-as-timestamps.properties");
@Inject
ObjectMapper objectMapper;
@Test
public void testDateWrittenAsNumericValue() throws JsonMappingException, JsonProcessingException {
Pojo pojo = new Pojo();
pojo.zonedDateTime = ZonedDateTime.of(1988, 11, 17, 0, 0, 0, 0, ZoneId.of("GMT"));
assertThat(objectMapper.writeValueAsString(pojo)).contains("595728000");
}
public static | JacksonWriteDatesAsTimestampsTest |
java | quarkusio__quarkus | extensions/smallrye-fault-tolerance/runtime/src/main/java/io/quarkus/smallrye/faulttolerance/runtime/config/SmallRyeFaultToleranceConfig.java | {
"start": 6420,
"end": 6673
} | interface ____ {
/**
* Whether the {@code @AsynchronousNonBlocking} strategy is enabled.
*/
@ConfigDocDefault("true")
Optional<Boolean> enabled();
}
| AsynchronousNonBlockingConfig |
java | spring-projects__spring-boot | core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java | {
"start": 4370,
"end": 5590
} | class ____ extends Thread {
private final InputStream source;
private final @Nullable Consumer<String> outputConsumer;
private final StringBuilder output = new StringBuilder();
private final CountDownLatch latch = new CountDownLatch(1);
ReaderThread(InputStream source, String name, @Nullable Consumer<String> outputConsumer) {
this.source = source;
this.outputConsumer = outputConsumer;
setName("OutputReader-" + name);
setDaemon(true);
start();
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(this.source, StandardCharsets.UTF_8))) {
String line = reader.readLine();
while (line != null) {
this.output.append(line);
this.output.append("\n");
if (this.outputConsumer != null) {
this.outputConsumer.accept(line);
}
line = reader.readLine();
}
this.latch.countDown();
}
catch (IOException ex) {
throw new UncheckedIOException("Failed to read process stream", ex);
}
}
@Override
public String toString() {
try {
this.latch.await();
return this.output.toString();
}
catch (InterruptedException ex) {
return "";
}
}
}
}
| ReaderThread |
java | alibaba__nacos | test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/LdapAuthCoreITCase.java | {
"start": 1597,
"end": 2558
} | class ____ extends AuthBase {
@LocalServerPort
private int port;
private String filterPrefix = "uid";
@MockBean
private LdapTemplate ldapTemplate;
@BeforeEach
void init() throws Exception {
Mockito.when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + "karson" + ")", "karson"))
.thenReturn(true);
AuthConfigs.setCachingEnabled(false);
TimeUnit.SECONDS.sleep(5L);
String url = String.format("http://localhost:%d/", port);
System.setProperty("nacos.core.auth.enabled", "true");
this.base = new URL(url);
}
}
@Nested
@DirtiesContext
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos",
"nacos.core.auth.system.type=ldap"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
| LdapBase |
java | apache__camel | components/camel-ai/camel-langchain4j-agent/src/generated/java/org/apache/camel/component/langchain4j/agent/LangChain4jAgentEndpointConfigurer.java | {
"start": 744,
"end": 3150
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
LangChain4jAgentEndpoint target = (LangChain4jAgentEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "agent": target.getConfiguration().setAgent(property(camelContext, org.apache.camel.component.langchain4j.agent.api.Agent.class, value)); return true;
case "agentfactory":
case "agentFactory": target.getConfiguration().setAgentFactory(property(camelContext, org.apache.camel.component.langchain4j.agent.api.AgentFactory.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "tags": target.getConfiguration().setTags(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public String[] getAutowiredNames() {
return new String[]{"agent", "agentFactory"};
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "agent": return org.apache.camel.component.langchain4j.agent.api.Agent.class;
case "agentfactory":
case "agentFactory": return org.apache.camel.component.langchain4j.agent.api.AgentFactory.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "tags": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
LangChain4jAgentEndpoint target = (LangChain4jAgentEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "agent": return target.getConfiguration().getAgent();
case "agentfactory":
case "agentFactory": return target.getConfiguration().getAgentFactory();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "tags": return target.getConfiguration().getTags();
default: return null;
}
}
}
| LangChain4jAgentEndpointConfigurer |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedDiscriminatorSameChildTableTest.java | {
"start": 3222,
"end": 3984
} | class ____ {
@Id
@Column(name = "id")
private String id;
@Column(name = "id_relation")
private String idRelation;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_relation", referencedColumnName = "id", insertable = false, updatable = false)
private EntityRelation relation;
public EntityRelation getRelation() {
return relation;
}
public void setRelation(EntityRelation requisition) {
this.relation = requisition;
}
public String getIdRelation() {
return idRelation;
}
public void setIdRelation(String idRelation) {
this.idRelation = idRelation;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
@Entity(name = "EntityRelation")
static | EntityParent |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/PathPart.java | {
"start": 257,
"end": 1916
} | class ____ {
/**
* The file to send
*/
public final Path file;
/**
* The starting byte of the file
*/
public final long offset;
/**
* The number of bytes to send
*/
public final long count;
/**
* Create a new partial {@link Path} object.
*
* @param file The file to send
* @param offset The starting byte of the file (must be >= 0)
* @param count The number of bytes to send (must be >= 0 and offset+count <= file size)
*/
public PathPart(Path file, long offset, long count) {
if (!Files.exists(file))
throw new IllegalArgumentException("File does not exist: " + file);
if (!Files.isRegularFile(file))
throw new IllegalArgumentException("File is not a regular file: " + file);
if (!Files.isReadable(file))
throw new IllegalArgumentException("File cannot be read: " + file);
if (offset < 0)
throw new IllegalArgumentException("Offset (" + offset + ") must be >= 0: " + file);
if (count < 0)
throw new IllegalArgumentException("Count (" + count + ") must be >= 0: " + file);
long fileLength;
try {
fileLength = Files.size(file);
if ((offset + count) > fileLength)
throw new IllegalArgumentException(
"Offset + count (" + (offset + count) + ") larger than file size (" + fileLength + "): " + file);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
this.file = file;
this.offset = offset;
this.count = count;
}
}
| PathPart |
java | apache__flink | flink-kubernetes/src/main/java/org/apache/flink/kubernetes/kubeclient/FlinkPod.java | {
"start": 2044,
"end": 3246
} | class ____ {
private Pod podWithoutMainContainer;
private Container mainContainer;
public Builder() {
this.podWithoutMainContainer =
new PodBuilder()
.withNewMetadata()
.endMetadata()
.withNewSpec()
.endSpec()
.build();
this.mainContainer = new ContainerBuilder().build();
}
public Builder(FlinkPod flinkPod) {
checkNotNull(flinkPod);
this.podWithoutMainContainer = checkNotNull(flinkPod.getPodWithoutMainContainer());
this.mainContainer = checkNotNull(flinkPod.getMainContainer());
}
public Builder withPod(Pod pod) {
this.podWithoutMainContainer = checkNotNull(pod);
return this;
}
public Builder withMainContainer(Container mainContainer) {
this.mainContainer = checkNotNull(mainContainer);
return this;
}
public FlinkPod build() {
return new FlinkPod(this.podWithoutMainContainer, this.mainContainer);
}
}
}
| Builder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.