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 | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLongTest.java | {
"start": 6595,
"end": 7043
} | class ____ {
private static final DateTime PLUS = DateTime.now().plus(42L);
private static final DateTime MINUS = DateTime.now().minus(42L);
}
""")
.doTest();
}
// DateMidnight
@Test
public void dateMidnightPlusMinusDuration() {
helper
.addSourceLines(
"TestClass.java",
"""
import org.joda.time.DateMidnight;
import org.joda.time.Duration;
public | TestClass |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/sort/RankOperator.java | {
"start": 1553,
"end": 4452
} | class ____ extends TableStreamOperator<RowData>
implements OneInputStreamOperator<RowData, RowData> {
private GeneratedRecordComparator partitionByGenComp;
private GeneratedRecordComparator orderByGenComp;
private final long rankStart;
private final long rankEnd;
private final boolean outputRankFunColumn;
private transient RecordComparator partitionByComp;
private transient RecordComparator orderByComp;
private transient long rowNum;
private transient long rank;
private transient GenericRowData rankValueRow;
private transient JoinedRowData joinedRow;
private transient RowData lastInput;
private transient StreamRecordCollector<RowData> collector;
private transient AbstractRowDataSerializer<RowData> inputSer;
public RankOperator(
GeneratedRecordComparator partitionByGenComp,
GeneratedRecordComparator orderByGenComp,
long rankStart,
long rankEnd,
boolean outputRankFunColumn) {
this.partitionByGenComp = partitionByGenComp;
this.orderByGenComp = orderByGenComp;
this.rankStart = rankStart;
this.rankEnd = rankEnd;
this.outputRankFunColumn = outputRankFunColumn;
}
@Override
public void open() throws Exception {
super.open();
ClassLoader cl = getUserCodeClassloader();
inputSer = (AbstractRowDataSerializer) getOperatorConfig().getTypeSerializerIn1(cl);
partitionByComp = partitionByGenComp.newInstance(cl);
partitionByGenComp = null;
orderByComp = orderByGenComp.newInstance(cl);
orderByGenComp = null;
if (outputRankFunColumn) {
joinedRow = new JoinedRowData();
rankValueRow = new GenericRowData(1);
}
collector = new StreamRecordCollector<>(output);
}
@Override
public void processElement(StreamRecord<RowData> element) throws Exception {
RowData input = element.getValue();
// add 1 when meets a new row
rowNum += 1L;
if (lastInput == null || partitionByComp.compare(lastInput, input) != 0) {
// reset rank value and row number value for new group
rank = 1L;
rowNum = 1L;
} else if (orderByComp.compare(lastInput, input) != 0) {
// set rank value as row number value if order-by value is change in a group
rank = rowNum;
}
emitInternal(input);
lastInput = inputSer.copy(input);
}
private void emitInternal(RowData element) {
if (rank >= rankStart && rank <= rankEnd) {
if (outputRankFunColumn) {
rankValueRow.setField(0, rank);
collector.collect(joinedRow.replace(element, rankValueRow));
} else {
collector.collect(element);
}
}
}
}
| RankOperator |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/spark/visitor/SparkOutputASTVisitor.java | {
"start": 1050,
"end": 5123
} | class ____ extends HiveOutputVisitor implements SparkASTVisitor {
public SparkOutputASTVisitor(StringBuilder appender, DbType dbType, SQLDialect dialect) {
super(appender, dbType, dialect);
}
public SparkOutputASTVisitor(StringBuilder appender) {
super(appender, DbType.spark, Spark.DIALECT);
}
//add using statment
@Override
public boolean visit(SQLCreateTableStatement x) {
if (x instanceof SparkCreateTableStatement) {
return visit((SparkCreateTableStatement) x);
}
return super.visit(x);
}
@Override
public boolean visit(SparkCreateTableStatement x) {
print0(ucase ? "CREATE " : "create ");
printCreateTableFeatures(x);
if (x.isIfNotExists()) {
print0(ucase ? "TABLE IF NOT EXISTS " : "table if not exists ");
} else {
print0(ucase ? "TABLE " : "table ");
}
x.getName().accept(this);
printCreateTableLike(x);
printTableElementsWithComment(x);
printUsing(x);
printComment(x.getComment());
printPartitionedBy(x);
printClusteredBy(x);
printSortedBy(x.getSortedBy());
printIntoBuckets(x.getBuckets());
printStoredAs(x);
printSelectAs(x, true);
printTableOptions(x);
printLocation(x);
return false;
}
protected void printUsing(SparkCreateTableStatement x) {
if (x.getDatasource() != null) {
println();
print0(ucase ? "USING " : "using ");
print0(x.getDatasource().toString());
}
}
protected void printTableOptions(SparkCreateTableStatement x) {
Map<String, SQLObject> serdeProperties = x.getSerdeProperties();
if (serdeProperties.size() > 0) {
println();
print0(ucase ? "TBLPROPERTIES (" : "tblproperties (");
String seperator = "";
for (Entry<String, SQLObject> entry : serdeProperties.entrySet()) {
print0("'" + entry.getKey() + "'='");
entry.getValue().accept(this);
print0("'" + seperator);
seperator = ",";
}
print(')');
}
}
@Override
public boolean visit(SQLHexExpr x) {
if (this.parameterized) {
print('?');
incrementReplaceCunt();
if (this.parameters != null) {
ExportParameterVisitorUtils.exportParameter(this.parameters, x);
}
return false;
}
print0("x'");
print0(x.getHex());
print('\'');
return false;
}
public boolean visit(SparkCreateScanStatement x) {
print0(ucase ? "CREATE " : "create ");
print0(ucase ? "SCAN " : "scan ");
x.getName().accept(this);
if (x.getOn() != null) {
print0(ucase ? " ON " : " on ");
x.getOn().accept(this);
}
SQLExpr using = x.getUsing();
if (using != null) {
println();
print0(ucase ? "USING " : "using ");
printExpr(using);
}
if (x.getOptions().size() > 0) {
print0(ucase ? " OPTIONS (" : " options (");
printAndAccept(x.getOptions(), ", ");
print(')');
}
return false;
}
public boolean visit(SparkCacheTableStatement x) {
print0(ucase ? "CACHE " : "cache ");
if (x.isLazy()) {
print0(ucase ? " LAZY " : " lazy ");
}
print0(ucase ? "TABLE " : "table ");
x.getName().accept(this);
if (x.getOptions().size() > 0) {
print0(ucase ? " OPTIONS (" : " options (");
printAndAccept(x.getOptions(), ", ");
print(')');
}
if (x.isAs()) {
print0(ucase ? " AS " : " as ");
}
SQLSelect query = x.getQuery();
if (query != null) {
print(' ');
query.accept(this);
}
return false;
}
}
| SparkOutputASTVisitor |
java | apache__spark | core/src/test/java/test/org/apache/spark/JavaAPISuite.java | {
"start": 26313,
"end": 27738
} | class ____ implements Comparator<Double>, Serializable {
@Override
public int compare(Double o1, Double o2) {
return o1.compareTo(o2);
}
}
@Test
public void max() {
JavaDoubleRDD rdd = sc.parallelizeDoubles(Arrays.asList(1.0, 2.0, 3.0, 4.0));
double max = rdd.max(new DoubleComparator());
assertEquals(4.0, max, 0.001);
}
@Test
public void min() {
JavaDoubleRDD rdd = sc.parallelizeDoubles(Arrays.asList(1.0, 2.0, 3.0, 4.0));
double max = rdd.min(new DoubleComparator());
assertEquals(1.0, max, 0.001);
}
@Test
public void naturalMax() {
JavaDoubleRDD rdd = sc.parallelizeDoubles(Arrays.asList(1.0, 2.0, 3.0, 4.0));
double max = rdd.max();
assertEquals(4.0, max, 0.0);
}
@Test
public void naturalMin() {
JavaDoubleRDD rdd = sc.parallelizeDoubles(Arrays.asList(1.0, 2.0, 3.0, 4.0));
double max = rdd.min();
assertEquals(1.0, max, 0.0);
}
@Test
public void takeOrdered() {
JavaDoubleRDD rdd = sc.parallelizeDoubles(Arrays.asList(1.0, 2.0, 3.0, 4.0));
assertEquals(Arrays.asList(1.0, 2.0), rdd.takeOrdered(2, new DoubleComparator()));
assertEquals(Arrays.asList(1.0, 2.0), rdd.takeOrdered(2));
}
@Test
public void top() {
JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4));
List<Integer> top2 = rdd.top(2);
assertEquals(Arrays.asList(4, 3), top2);
}
private static | DoubleComparator |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/sort/StringRecordComparator.java | {
"start": 1029,
"end": 1577
} | class ____ implements RecordComparator {
@Override
public int compare(RowData o1, RowData o2) {
boolean null0At1 = o1.isNullAt(0);
boolean null0At2 = o2.isNullAt(0);
int cmp0 =
null0At1 && null0At2
? 0
: (null0At1
? -1
: (null0At2 ? 1 : o1.getString(0).compareTo(o2.getString(0))));
if (cmp0 != 0) {
return cmp0;
}
return 0;
}
}
| StringRecordComparator |
java | apache__spark | common/network-common/src/main/java/org/apache/spark/network/server/OneForOneStreamManager.java | {
"start": 1613,
"end": 1931
} | class ____ extends StreamManager {
private static final SparkLogger logger =
SparkLoggerFactory.getLogger(OneForOneStreamManager.class);
private final AtomicLong nextStreamId;
private final ConcurrentHashMap<Long, StreamState> streams;
/** State of a single stream. */
private static | OneForOneStreamManager |
java | google__error-prone | core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTest.java | {
"start": 62860,
"end": 63247
} | class ____ {
Coinductive f;
}
}
""")
.doTest();
}
@Test
public void fieldReceivers() {
compilationHelper
.addSourceLines(
"FieldReceiversTest.java",
"""
package com.google.errorprone.dataflow.nullnesspropagation;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
public | Coinductive |
java | mapstruct__mapstruct | integrationtest/src/test/resources/lombokModuleTest/src/test/java/org/mapstruct/itest/lombok/LombokMapperTest.java | {
"start": 414,
"end": 1327
} | class ____ {
@Test
public void testSimpleImmutableBuilderHappyPath() {
PersonDto personDto = PersonMapper.INSTANCE.toDto( new Person( "Bob", 33, new Address( "Wild Drive" ) ) );
assertThat( personDto.getAge() ).isEqualTo( 33 );
assertThat( personDto.getName() ).isEqualTo( "Bob" );
assertThat( personDto.getAddress() ).isNotNull();
assertThat( personDto.getAddress().getAddressLine() ).isEqualTo( "Wild Drive" );
}
@Test
public void testLombokToImmutable() {
Person person = PersonMapper.INSTANCE.fromDto( new PersonDto( "Bob", 33, new AddressDto( "Wild Drive" ) ) );
assertThat( person.getAge() ).isEqualTo( 33 );
assertThat( person.getName() ).isEqualTo( "Bob" );
assertThat( person.getAddress() ).isNotNull();
assertThat( person.getAddress().getAddressLine() ).isEqualTo( "Wild Drive" );
}
}
| LombokMapperTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/pool/TestConnectTimeout.java | {
"start": 985,
"end": 3205
} | class ____ extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUsername("xxx1");
dataSource.setPassword("ppp");
dataSource.setUrl("jdbc:mock:xx");
dataSource.setFilters("stat");
dataSource.setMaxOpenPreparedStatements(30);
dataSource.setMaxActive(4);
dataSource.setMaxWait(50000); //时间灵敏度不够,容易导致单测失败,因此调大一点
dataSource.setMinIdle(0);
dataSource.setInitialSize(1);
dataSource.init();
}
public void testConnectTimeout() throws Exception {
{
Connection conn = dataSource.getConnection();
conn.close();
dataSource.shrink();
assertEquals(0, dataSource.getPoolingCount());
}
final List<Connection> connections = new ArrayList<Connection>();
for (int i = 0; i < 3; ++i) {
Connection conn = dataSource.getConnection();
connections.add(conn);
}
final AtomicLong errorCount = new AtomicLong();
final int THREAD_COUNT = 10;
final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
for (int i = 0; i < THREAD_COUNT; ++i) {
Thread thread = new Thread() {
public void run() {
try {
for (int i = 0; i < 100; ++i) {
Connection conn = dataSource.getConnection();
System.out.println(LocalDateTime.now() + " : " + Thread.currentThread() + " " + conn);
Thread.sleep(1);
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
errorCount.incrementAndGet();
} finally {
latch.countDown();
}
}
};
thread.start();
}
latch.await();
assertEquals(0, errorCount.get());
}
protected void tearDown() throws Exception {
JdbcUtils.close(dataSource);
}
}
| TestConnectTimeout |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/introspect/POJOPropertiesCollectorTest.java | {
"start": 1434,
"end": 1643
} | class ____ {
@JsonProperty
public int value;
@JsonIgnore
public void setValue(int v) { value = v; }
public int getValue() { return value; }
}
static | IgnoredSetter |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/impl/ProducerCacheNonSingletonTest.java | {
"start": 1419,
"end": 2449
} | class ____ extends ContextTestSupport {
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testNonSingleton() {
context.addComponent("dummy", new MyDummyComponent());
DefaultProducerCache cache = new DefaultProducerCache(this, context, 100);
cache.start();
Endpoint endpoint = context.getEndpoint("dummy:foo");
DefaultAsyncProducer producer = (DefaultAsyncProducer) cache.acquireProducer(endpoint);
assertNotNull(producer);
assertTrue(producer.getStatus().isStarted(), "Should be started");
Object found = context.hasService(MyDummyProducer.class);
assertNull(found, "Should not store producer on CamelContext");
cache.releaseProducer(endpoint, producer);
assertTrue(producer.getStatus().isStarted(), "Should still be started");
cache.stop();
assertTrue(producer.getStatus().isStopped(), "Should be stopped");
}
public static | ProducerCacheNonSingletonTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/tck/GroupByTckTest.java | {
"start": 878,
"end": 1417
} | class ____ extends BaseTck<Integer> {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Publisher<Integer> createPublisher(long elements) {
return
Flowable.range(0, (int)elements).groupBy(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer v) throws Exception {
return v & 1;
}
})
.flatMap((Function)Functions.identity())
;
}
}
| GroupByTckTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/CBRPredicateBeanThrowExceptionTest.java | {
"start": 1249,
"end": 3334
} | class ____ extends ContextTestSupport {
private static final AtomicBoolean check = new AtomicBoolean();
private static final AtomicBoolean check2 = new AtomicBoolean();
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("cbrBean", new MyCBRBean());
return jndi;
}
@Test
public void testCBR() throws Exception {
check.set(false);
check2.set(false);
getMockEndpoint("mock:dead").expectedMessageCount(0);
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello Foo");
getMockEndpoint("mock:bar").expectedBodiesReceived("Hello Bar");
template.sendBodyAndHeader("direct:start", "Hello Foo", "foo", "bar");
template.sendBodyAndHeader("direct:start", "Hello Bar", "foo", "other");
assertMockEndpointsSatisfied();
assertTrue(check.get());
assertTrue(check2.get());
}
@Test
public void testCBRKaboom() throws Exception {
check.set(false);
check2.set(false);
getMockEndpoint("mock:foo").expectedMessageCount(0);
getMockEndpoint("mock:foo2").expectedMessageCount(0);
getMockEndpoint("mock:bar").expectedMessageCount(0);
getMockEndpoint("mock:dead").expectedMessageCount(1);
template.sendBodyAndHeader("direct:start", "Hello Foo", "foo", "Kaboom");
assertMockEndpointsSatisfied();
assertTrue(check.get());
assertFalse(check2.get());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
errorHandler(deadLetterChannel("mock:dead"));
from("direct:start").choice().when().method("cbrBean", "checkHeader").to("mock:foo").when()
.method("cbrBean", "checkHeader2").to("mock:foo2").otherwise()
.to("mock:bar").end();
}
};
}
public static | CBRPredicateBeanThrowExceptionTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/javadoc/NotJavadocTest.java | {
"start": 2247,
"end": 2640
} | class ____ {",
// It would be nice if this were caught.
" /** Not Javadoc. */",
" /** Javadoc. */",
" void test() {",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void notJavadocOnLocalClass() {
helper
.addInputLines(
"Test.java",
"""
| Test |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Kinesis2EndpointBuilderFactory.java | {
"start": 1452,
"end": 1592
} | interface ____ {
/**
* Builder for endpoint consumers for the AWS Kinesis component.
*/
public | Kinesis2EndpointBuilderFactory |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/resourceplugin/fpga/AbstractFpgaVendorPlugin.java | {
"start": 1162,
"end": 1465
} | interface ____ vendor to implement. Used by {@link FpgaDiscoverer} and
* {@link org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.fpga.FpgaResourceHandlerImpl}
* to discover devices/download IP/configure IP
* */
@InterfaceAudience.Private
@InterfaceStability.Unstable
public | for |
java | quarkusio__quarkus | extensions/redis-client/deployment/src/test/java/io/quarkus/redis/deployment/client/patterns/CacheTest.java | {
"start": 1846,
"end": 2075
} | class ____ {
public String result;
public BusinessObject() {
}
public BusinessObject(String v) {
this.result = v;
}
}
@ApplicationScoped
public static | BusinessObject |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RequiredModifiersCheckerTest.java | {
"start": 3860,
"end": 4368
} | class ____ {
// BUG: Diagnostic contains: The annotation '@PublicAndFinalRequired' has specified that it must
// be used together with the following modifiers: [public]
@PublicAndFinalRequired final int n = 0;
}
""")
.doTest();
}
@Test
public void annotationWithRequiredModifiersMissingOnMethodFails1() {
compilationHelper
.addSourceLines(
"test/RequiredModifiersTestCase.java",
"""
package test;
import test.PublicAndFinalRequired;
public | RequiredModifiersTestCase |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/expressions/context/ExpressionCompilationContextFactory.java | {
"start": 1003,
"end": 1083
} | interface ____ producing expression evaluation context.
*/
@Experimental
public | for |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/orphan/NoDirtyCheckEnhancementContext.java | {
"start": 346,
"end": 711
} | class ____ extends DefaultEnhancementContext {
@Override
public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) {
return true;
}
@Override
public boolean isLazyLoadable(UnloadedField field) {
return true;
}
@Override
public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) {
return false;
}
}
| NoDirtyCheckEnhancementContext |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/producer/ProducerWithoutZeroParamCtorAndInterceptionTest.java | {
"start": 2052,
"end": 2222
} | class ____ {
@Produces
MyNonbean produce(InterceptionProxy<MyNonbean> proxy) {
return proxy.create(new MyNonbean(0));
}
}
}
| MyProducer |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/PreparedStatementDetailsStandard.java | {
"start": 859,
"end": 3202
} | class ____ implements PreparedStatementDetails {
private final TableMapping mutatingTableDetails;
private final String sql;
private final Supplier<PreparedStatement> jdbcStatementCreator;
private final Expectation expectation;
private final JdbcServices jdbcServices;
private PreparedStatement statement;
private boolean toRelease;
public PreparedStatementDetailsStandard(
PreparableMutationOperation tableMutation,
Supplier<PreparedStatement> jdbcStatementCreator,
JdbcServices jdbcServices) {
this(
tableMutation,
tableMutation.getSqlString(),
jdbcStatementCreator,
tableMutation.getExpectation(),
jdbcServices
);
}
public PreparedStatementDetailsStandard(
PreparableMutationOperation tableMutation,
String sql,
Supplier<PreparedStatement> jdbcStatementCreator,
Expectation expectation,
JdbcServices jdbcServices) {
this.mutatingTableDetails = tableMutation.getTableDetails();
this.sql = sql;
this.jdbcStatementCreator = jdbcStatementCreator;
this.expectation = expectation;
this.jdbcServices = jdbcServices;
}
@Override
public TableMapping getMutatingTableDetails() {
return mutatingTableDetails;
}
@Override
public void releaseStatement(SharedSessionContractImplementor session) {
if ( statement != null ) {
final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( statement );
statement = null;
toRelease = false;
jdbcCoordinator.afterStatementExecution();
}
}
@Override
public String getSqlString() {
return sql;
}
@Override
public PreparedStatement getStatement() {
return statement;
}
@Override
public PreparedStatement resolveStatement() {
if ( statement == null ) {
toRelease = true;
statement = jdbcStatementCreator.get();
try {
expectation.prepare( statement );
}
catch (SQLException e) {
throw jdbcServices.getSqlExceptionHelper().convert(
e,
"Unable to prepare for expectation",
sql
);
}
}
return statement;
}
@Override
public Expectation getExpectation() {
return expectation;
}
@Override
public boolean toRelease() {
return toRelease;
}
@Override
public String toString() {
return "PreparedStatementDetails(" + sql + ")";
}
}
| PreparedStatementDetailsStandard |
java | google__guava | android/guava-tests/test/com/google/common/collect/ReflectionFreeAssertThrows.java | {
"start": 3965,
"end": 7116
} | enum ____ {
PLATFORM {
@GwtIncompatible
@J2ktIncompatible
@Override
// returns the types available in "normal" environments
ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() {
return ImmutableMap.of(
InvocationTargetException.class,
e -> e instanceof InvocationTargetException,
StackOverflowError.class,
e -> e instanceof StackOverflowError);
}
};
// used under GWT, etc., since the override of this method does not exist there
ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() {
return ImmutableMap.of();
}
}
private static final ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> INSTANCE_OF =
ImmutableMap.<Class<? extends Throwable>, Predicate<Throwable>>builder()
.put(ArithmeticException.class, e -> e instanceof ArithmeticException)
.put(
ArrayIndexOutOfBoundsException.class,
e -> e instanceof ArrayIndexOutOfBoundsException)
.put(ArrayStoreException.class, e -> e instanceof ArrayStoreException)
.put(AssertionFailedError.class, e -> e instanceof AssertionFailedError)
.put(CancellationException.class, e -> e instanceof CancellationException)
.put(ClassCastException.class, e -> e instanceof ClassCastException)
.put(
ConcurrentModificationException.class,
e -> e instanceof ConcurrentModificationException)
.put(ExecutionException.class, e -> e instanceof ExecutionException)
.put(IllegalArgumentException.class, e -> e instanceof IllegalArgumentException)
.put(IllegalStateException.class, e -> e instanceof IllegalStateException)
.put(IncomparableValueException.class, e -> e instanceof IncomparableValueException)
.put(IndexOutOfBoundsException.class, e -> e instanceof IndexOutOfBoundsException)
.put(NoSuchElementException.class, e -> e instanceof NoSuchElementException)
.put(NullPointerException.class, e -> e instanceof NullPointerException)
.put(NumberFormatException.class, e -> e instanceof NumberFormatException)
.put(RuntimeException.class, e -> e instanceof RuntimeException)
.put(SomeCheckedException.class, e -> e instanceof SomeCheckedException)
.put(SomeError.class, e -> e instanceof SomeError)
.put(SomeOtherCheckedException.class, e -> e instanceof SomeOtherCheckedException)
.put(SomeUncheckedException.class, e -> e instanceof SomeUncheckedException)
.put(TimeoutException.class, e -> e instanceof TimeoutException)
.put(UnsupportedCharsetException.class, e -> e instanceof UnsupportedCharsetException)
.put(UnsupportedOperationException.class, e -> e instanceof UnsupportedOperationException)
.put(VerifyException.class, e -> e instanceof VerifyException)
.putAll(PlatformSpecificExceptionBatch.PLATFORM.exceptions())
.buildOrThrow();
private ReflectionFreeAssertThrows() {}
}
| PlatformSpecificExceptionBatch |
java | apache__camel | core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedStepMBean.java | {
"start": 858,
"end": 932
} | interface ____ extends ManagedProcessorMBean {
// noop
}
| ManagedStepMBean |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/error/ShouldEndWith_create_Test.java | {
"start": 1391,
"end": 2853
} | class ____ {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = shouldEndWith(list("Yoda", "Luke"), list("Han", "Leia"));
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" [\"Yoda\", \"Luke\"]%n" +
"to end with:%n" +
" [\"Han\", \"Leia\"]%n"));
}
@Test
void should_create_error_message_with_custom_comparison_strategy() {
// GIVEN
ErrorMessageFactory factory = shouldEndWith(list("Yoda", "Luke"), list("Han", "Leia"),
new ComparatorBasedComparisonStrategy(CaseInsensitiveStringComparator.INSTANCE));
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(String.format("[Test] %n" +
"Expecting actual:%n" +
" [\"Yoda\", \"Luke\"]%n" +
"to end with:%n" +
" [\"Han\", \"Leia\"]%n"
+ "when comparing values using CaseInsensitiveStringComparator"));
}
}
| ShouldEndWith_create_Test |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/aot/hint/SimpleTypeReference.java | {
"start": 929,
"end": 1522
} | class ____ extends AbstractTypeReference {
private static final List<String> PRIMITIVE_NAMES = List.of("boolean", "byte",
"short", "int", "long", "char", "float", "double", "void");
private @Nullable String canonicalName;
SimpleTypeReference(String packageName, String simpleName, @Nullable TypeReference enclosingType) {
super(packageName, simpleName, enclosingType);
}
static SimpleTypeReference of(String className) {
Assert.notNull(className, "'className' must not be null");
if (!isValidClassName(className)) {
throw new IllegalStateException("Invalid | SimpleTypeReference |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MissingSetterWithEnhancementTest.java | {
"start": 2268,
"end": 2537
} | class ____ {
private Long id;
@Column
@Access(AccessType.FIELD)
private int someInt;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return null;
}
}
}
| EntityWithMissingSetter |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/dev/testing/TestResult.java | {
"start": 291,
"end": 2872
} | class ____ implements TestResultInterface {
final String displayName;
final String testClass;
final List<String> tags;
final UniqueId uniqueId;
final TestExecutionResult testExecutionResult;
final List<String> logOutput;
final boolean test;
final long runId;
final long time;
final List<Throwable> problems;
final boolean reportable;
public TestResult(String displayName, String testClass, List<String> tags, UniqueId uniqueId,
TestExecutionResult testExecutionResult,
List<String> logOutput, boolean test, long runId, long time, boolean reportable) {
this.displayName = displayName;
this.testClass = testClass;
this.tags = tags;
this.uniqueId = uniqueId;
this.testExecutionResult = testExecutionResult;
this.logOutput = logOutput;
this.test = test;
this.runId = runId;
this.time = time;
this.reportable = reportable;
List<Throwable> problems = new ArrayList<>();
if (testExecutionResult.getThrowable().isPresent()) {
Throwable t = testExecutionResult.getThrowable().get();
while (t != null) {
problems.add(t);
t = t.getCause();
}
}
this.problems = Collections.unmodifiableList(problems);
}
public TestExecutionResult getTestExecutionResult() {
return testExecutionResult;
}
@Override
public List<String> getLogOutput() {
return logOutput;
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public String getTestClass() {
return testClass;
}
@Override
public List<String> getTags() {
return tags;
}
public UniqueId getUniqueId() {
return uniqueId;
}
@Override
public boolean isTest() {
return test;
}
@Override
public String getId() {
return uniqueId.toString();
}
@Override
public long getRunId() {
return runId;
}
@Override
public long getTime() {
return time;
}
@Override
public List<Throwable> getProblems() {
return problems;
}
@Override
public boolean isReportable() {
return reportable;
}
@Override
public State getState() {
return switch (testExecutionResult.getStatus()) {
case FAILED -> State.FAILED;
case ABORTED -> State.SKIPPED;
case SUCCESSFUL -> State.PASSED;
};
}
}
| TestResult |
java | netty__netty | codec-xml/src/test/java/io/netty/handler/codec/xml/NativeImageHandlerMetadataTest.java | {
"start": 772,
"end": 960
} | class ____ {
@Test
public void collectAndCompareMetadata() {
ChannelHandlerMetadataUtil.generateMetadata("io.netty.handler.codec.xml");
}
}
| NativeImageHandlerMetadataTest |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java | {
"start": 1903,
"end": 4777
} | class ____ {
@Mock
private SecurityContext securityContext;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private AsyncWebRequest asyncWebRequest;
private WebAsyncManager asyncManager;
private JoinableThreadFactory threadFactory;
private MockFilterChain filterChain;
private WebAsyncManagerIntegrationFilter filter;
@BeforeEach
public void setUp() {
this.filterChain = new MockFilterChain();
this.threadFactory = new JoinableThreadFactory();
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
executor.setThreadFactory(this.threadFactory);
this.asyncManager = WebAsyncUtils.getAsyncManager(this.request);
this.asyncManager.setAsyncWebRequest(this.asyncWebRequest);
this.asyncManager.setTaskExecutor(executor);
given(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).willReturn(this.asyncManager);
this.filter = new WebAsyncManagerIntegrationFilter();
}
@AfterEach
public void clearSecurityContext() {
SecurityContextHolder.clearContext();
}
@Test
public void doFilterInternalRegistersSecurityContextCallableProcessor() throws Exception {
SecurityContextHolder.setContext(this.securityContext);
this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptor() {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext())
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
}
});
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
VerifyingCallable verifyingCallable = new VerifyingCallable();
this.asyncManager.startCallableProcessing(verifyingCallable);
this.threadFactory.join();
assertThat(this.asyncManager.getConcurrentResult()).isSameAs(this.securityContext);
}
@Test
public void doFilterInternalRegistersSecurityContextCallableProcessorContextUpdated() throws Exception {
SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptor() {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext())
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
}
});
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
SecurityContextHolder.setContext(this.securityContext);
VerifyingCallable verifyingCallable = new VerifyingCallable();
this.asyncManager.startCallableProcessing(verifyingCallable);
this.threadFactory.join();
assertThat(this.asyncManager.getConcurrentResult()).isSameAs(this.securityContext);
}
private static final | WebAsyncManagerIntegrationFilterTests |
java | google__dagger | hilt-compiler/main/java/dagger/hilt/processor/internal/disableinstallincheck/KspDisableInstallInCheckProcessor.java | {
"start": 1603,
"end": 1852
} | class ____ implements SymbolProcessorProvider {
@Override
public SymbolProcessor create(SymbolProcessorEnvironment symbolProcessorEnvironment) {
return new KspDisableInstallInCheckProcessor(symbolProcessorEnvironment);
}
}
}
| Provider |
java | google__guava | android/guava-tests/test/com/google/common/io/SourceSinkFactories.java | {
"start": 10289,
"end": 10864
} | class ____ extends FileFactory implements CharSourceFactory {
@Override
public CharSource createSource(String string) throws IOException {
checkNotNull(string);
File file = createFile();
Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8);
try {
writer.write(string);
} finally {
writer.close();
}
return Files.asCharSource(file, UTF_8);
}
@Override
public String getExpected(String string) {
return checkNotNull(string);
}
}
private static | FileCharSourceFactory |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/alibabacloudsearch/request/AlibabaCloudSearchEmbeddingsRequest.java | {
"start": 1467,
"end": 4468
} | class ____ extends AlibabaCloudSearchRequest {
private final AlibabaCloudSearchAccount account;
private final List<String> input;
private final InputType inputType;
private final URI uri;
private final AlibabaCloudSearchEmbeddingsTaskSettings taskSettings;
private final String model;
private final String host;
private final String workspaceName;
private final String httpSchema;
private final String inferenceEntityId;
public AlibabaCloudSearchEmbeddingsRequest(
AlibabaCloudSearchAccount account,
List<String> input,
InputType inputType,
AlibabaCloudSearchEmbeddingsModel embeddingsModel
) {
Objects.requireNonNull(embeddingsModel);
this.account = Objects.requireNonNull(account);
this.input = Objects.requireNonNull(input);
this.inputType = inputType;
taskSettings = embeddingsModel.getTaskSettings();
model = embeddingsModel.getServiceSettings().getCommonSettings().modelId();
host = embeddingsModel.getServiceSettings().getCommonSettings().getHost();
workspaceName = embeddingsModel.getServiceSettings().getCommonSettings().getWorkspaceName();
httpSchema = embeddingsModel.getServiceSettings().getCommonSettings().getHttpSchema() != null
? embeddingsModel.getServiceSettings().getCommonSettings().getHttpSchema()
: "https";
uri = buildUri(null, AlibabaCloudSearchUtils.SERVICE_NAME, this::buildDefaultUri);
inferenceEntityId = embeddingsModel.getInferenceEntityId();
}
@Override
public HttpRequest createHttpRequest() {
HttpPost httpPost = new HttpPost(uri);
ByteArrayEntity byteEntity = new ByteArrayEntity(
Strings.toString(new AlibabaCloudSearchEmbeddingsRequestEntity(input, inputType, taskSettings)).getBytes(StandardCharsets.UTF_8)
);
httpPost.setEntity(byteEntity);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, XContentType.JSON.mediaType());
httpPost.setHeader(createAuthBearerHeader(account.apiKey()));
return new HttpRequest(httpPost, getInferenceEntityId());
}
@Override
public String getInferenceEntityId() {
return inferenceEntityId;
}
@Override
public URI getURI() {
return uri;
}
@Override
public Request truncate() {
return this;
}
@Override
public boolean[] getTruncationInfo() {
return null;
}
URI buildDefaultUri() throws URISyntaxException {
return new URIBuilder().setScheme(httpSchema)
.setHost(host)
.setPathSegments(
AlibabaCloudSearchUtils.VERSION_3,
AlibabaCloudSearchUtils.OPENAPI_PATH,
AlibabaCloudSearchUtils.WORKSPACE_PATH,
workspaceName,
AlibabaCloudSearchUtils.TEXT_EMBEDDING_PATH,
model
)
.build();
}
}
| AlibabaCloudSearchEmbeddingsRequest |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/processing/DeclaredBeanElementCreator.java | {
"start": 18479,
"end": 26222
} | class
____ false;
}
// This method requires pre-processing. See Executable#processOnStartup()
boolean preprocess = methodElement.isTrue(Executable.class, Executable.MEMBER_PROCESS_ON_STARTUP);
if (preprocess) {
visitor.setRequiresMethodProcessing(true);
}
if (methodElement.hasStereotype(Adapter.class)) {
staticMethodCheck(methodElement);
visitAdaptedMethod(methodElement);
// Adapter is always an executable method but can also be intercepted so continue with visitors below
}
if (visitAopMethod(visitor, methodElement)) {
return true;
}
return visitExecutableMethod(visitor, methodElement);
}
/**
* Visit an AOP method.
*
* @param visitor The visitor
* @param methodElement The method
* @return true if processed
*/
protected boolean visitAopMethod(BeanDefinitionVisitor visitor, MethodElement methodElement) {
boolean aopDefinedOnClassAndPublicMethod = isAopProxy && (methodElement.isPublic() || methodElement.isPackagePrivate());
AnnotationMetadata methodAnnotationMetadata = methodElement.getMethodAnnotationMetadata();
if (aopDefinedOnClassAndPublicMethod ||
!isAopProxy && InterceptedMethodUtil.hasAroundStereotype(methodAnnotationMetadata) ||
InterceptedMethodUtil.hasDeclaredAroundAdvice(methodAnnotationMetadata) && !classElement.isAbstract()) {
if (methodElement.isFinal()) {
if (InterceptedMethodUtil.hasDeclaredAroundAdvice(methodAnnotationMetadata)) {
throw new ProcessingException(methodElement, "Method defines AOP advice but is declared final. Change the method to be non-final in order for AOP advice to be applied.");
} else if (!methodElement.isSynthetic() && aopDefinedOnClassAndPublicMethod && isDeclaredInThisClass(methodElement)) {
throw new ProcessingException(methodElement, "Public method inherits AOP advice but is declared final. Either make the method non-public or apply AOP advice only to public methods declared on the class.");
}
return false;
} else if (methodElement.isPrivate()) {
throw new ProcessingException(methodElement, "Method annotated as executable but is declared private. Change the method to be non-private in order for AOP advice to be applied.");
} else if (methodElement.isStatic()) {
throw new ProcessingException(methodElement, "Method defines AOP advice but is declared static");
}
ProxyingBeanDefinitionVisitor aopProxyVisitor = getAroundAopProxyVisitor(visitor, methodElement);
visitAroundMethod(aopProxyVisitor, classElement, methodElement);
return true;
}
return false;
}
protected void visitAroundMethod(ProxyingBeanDefinitionVisitor aopProxyWriter, TypedElement beanType, MethodElement methodElement) {
aopProxyWriter.visitInterceptorBinding(
InterceptedMethodUtil.resolveInterceptorBinding(methodElement.getAnnotationMetadata(), InterceptorKind.AROUND)
);
aopProxyWriter.visitAroundMethod(beanType, methodElement);
}
/**
* Apply configuration injection for the constructor.
*
* @param visitor The visitor
* @param constructor The constructor
*/
protected void applyConfigurationInjectionIfNecessary(BeanDefinitionVisitor visitor,
MethodElement constructor) {
// default to do nothing
}
/**
* Is inject point method?
*
* @param memberElement The method
* @return true if it is
*/
protected boolean isInjectPointMethod(MemberElement memberElement) {
return memberElement.hasDeclaredStereotype(AnnotationUtil.INJECT);
}
private void staticMethodCheck(MethodElement methodElement) {
if (methodElement.isStatic()) {
if (!isExplicitlyAnnotatedAsExecutable(methodElement)) {
throw new ProcessingException(methodElement, "Static methods only allowed when annotated with @Executable");
}
failIfMethodNotAccessible(methodElement);
}
}
private void failIfMethodNotAccessible(MethodElement methodElement) {
if (!methodElement.isAccessible(classElement)) {
throw new ProcessingException(methodElement, "Method is not accessible for the invocation. To invoke the method using reflection annotate it with @ReflectiveAccess");
}
}
private static boolean isExplicitlyAnnotatedAsExecutable(MethodElement methodElement) {
return !methodElement.getMethodAnnotationMetadata().hasDeclaredAnnotation(Executable.class);
}
/**
* Visit a field.
*
* @param visitor The visitor
* @param fieldElement The field
* @return true if processed
*/
protected boolean visitField(BeanDefinitionVisitor visitor, FieldElement fieldElement) {
if (fieldElement.isStatic() || fieldElement.isFinal()) {
return false;
}
AnnotationMetadata fieldAnnotationMetadata = fieldElement.getAnnotationMetadata();
boolean isRequired = InjectionPoint.isInjectionRequired(fieldElement);
if (fieldAnnotationMetadata.hasStereotype(Value.class) || fieldAnnotationMetadata.hasStereotype(Property.class)) {
visitor.visitFieldValue(
fieldElement.getDeclaringType(),
fieldElement,
fieldElement.isReflectionRequired(classElement),
!isRequired
);
return true;
}
if (fieldAnnotationMetadata.hasStereotype(AnnotationUtil.INJECT)
|| fieldAnnotationMetadata.hasDeclaredStereotype(AnnotationUtil.QUALIFIER)) {
visitor.visitFieldInjectionPoint(
fieldElement.getDeclaringType(),
fieldElement,
fieldElement.isReflectionRequired(classElement),
visitorContext
);
return true;
}
return false;
}
private void addOriginatingElementIfNecessary(BeanDefinitionVisitor writer, MemberElement memberElement) {
if (!memberElement.isSynthetic() && !isDeclaredInThisClass(memberElement)) {
writer.addOriginatingElement(memberElement.getDeclaringType());
}
}
/**
* Visit an executable method.
*
* @param visitor The visitor
* @param methodElement The method
* @return true if processed
*/
protected boolean visitExecutableMethod(BeanDefinitionVisitor visitor, MethodElement methodElement) {
if (!methodElement.hasStereotype(Executable.class)) {
return false;
}
if (methodElement.isSynthetic()) {
// Synthetic methods cannot be executable as @Executable cannot be put on a field
return false;
}
if (methodElement.getMethodAnnotationMetadata().hasStereotype(Executable.class)) {
// @Executable annotated on the method
// Throw error if it cannot be accessed without the reflection
if (!methodElement.isAccessible()) {
throw new ProcessingException(methodElement, "Method annotated as executable but is declared private. To invoke the method using reflection annotate it with @ReflectiveAccess");
}
} else if (!isDeclaredInThisClass(methodElement) && !methodElement.getDeclaringType().hasStereotype(Executable.class)) {
// @Executable not annotated on the declared | return |
java | apache__logging-log4j2 | log4j-mongodb4/src/main/java/org/apache/logging/log4j/mongodb4/MongoDb4DocumentObjectCodec.java | {
"start": 1082,
"end": 1966
} | class ____ implements Codec<MongoDb4DocumentObject> {
private final Codec<Document> documentCodec = new DocumentCodec();
@Override
public void encode(
final BsonWriter writer, final MongoDb4DocumentObject value, final EncoderContext encoderContext) {
documentCodec.encode(writer, value.unwrap(), encoderContext);
}
@Override
public Class<MongoDb4DocumentObject> getEncoderClass() {
return MongoDb4DocumentObject.class;
}
@Override
public MongoDb4DocumentObject decode(final BsonReader reader, final DecoderContext decoderContext) {
final MongoDb4DocumentObject object = new MongoDb4DocumentObject();
documentCodec.decode(reader, decoderContext).entrySet().stream()
.forEach(entry -> object.set(entry.getKey(), entry.getValue()));
return object;
}
}
| MongoDb4DocumentObjectCodec |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/Unbox.java | {
"start": 3143,
"end": 3234
} | class ____ a singleton.
*/
@SuppressWarnings("ThreadLocalUsage")
private static | is |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/introspect/TestNamingStrategyCustom.java | {
"start": 4577,
"end": 8576
} | class ____
{
protected int a = 3;
public int getA() { return a; }
public void setA(int value) { a = value; }
}
/*
/**********************************************************************
/* Test methods
/**********************************************************************
*/
@Test
public void testSimpleGetters() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.propertyNamingStrategy(new PrefixStrategy())
.build();
assertEquals("{\"Get-key\":123}", mapper.writeValueAsString(new GetterBean()));
}
@Test
public void testSimpleSetters() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.propertyNamingStrategy(new PrefixStrategy())
.build();
SetterBean bean = mapper.readValue("{\"Set-key\":13}", SetterBean.class);
assertEquals(13, bean.value);
}
@Test
public void testSimpleFields() throws Exception
{
// First serialize
ObjectMapper mapper = jsonMapperBuilder()
.propertyNamingStrategy(new PrefixStrategy())
.build();
String json = mapper.writeValueAsString(new FieldBean(999));
assertEquals("{\"Field-key\":999}", json);
// then deserialize
FieldBean result = mapper.readValue(json, FieldBean.class);
assertEquals(999, result.key);
}
@Test
public void testCStyleNaming() throws Exception
{
// First serialize
ObjectMapper mapper = jsonMapperBuilder()
.propertyNamingStrategy(new CStyleStrategy())
.build();
String json = mapper.writeValueAsString(new PersonBean("Joe", "Sixpack", 42));
assertEquals("{\"first_name\":\"Joe\",\"last_name\":\"Sixpack\",\"age\":42}", json);
// then deserialize
PersonBean result = mapper.readValue(json, PersonBean.class);
assertEquals("Joe", result.firstName);
assertEquals("Sixpack", result.lastName);
assertEquals(42, result.age);
}
@Test
public void testWithGetterAsSetter() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.enable(MapperFeature.USE_GETTERS_AS_SETTERS)
.propertyNamingStrategy(new CStyleStrategy())
.build();
SetterlessWithValue input = new SetterlessWithValue().add(3);
String json = mapper.writeValueAsString(input);
assertEquals("{\"value_list\":[{\"int_value\":3}]}", json);
SetterlessWithValue result = mapper.readValue(json, SetterlessWithValue.class);
assertNotNull(result.values);
assertEquals(1, result.values.size());
assertEquals(3, result.values.get(0).intValue);
}
@Test
public void testLowerCase() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.propertyNamingStrategy(new LcStrategy())
.build();
// mapper.disable(DeserializationConfig.DeserializationFeature.USE_GETTERS_AS_SETTERS);
RenamedCollectionBean result = mapper.readValue("{\"thevalues\":[\"a\"]}",
RenamedCollectionBean.class);
assertNotNull(result.getTheValues());
assertEquals(1, result.getTheValues().size());
assertEquals("a", result.getTheValues().get(0));
}
// @JsonNaming / [databind#45]
@Test
public void testPerClassAnnotation() throws Exception
{
final ObjectMapper mapper = jsonMapperBuilder()
.propertyNamingStrategy(new LcStrategy())
.build();
BeanWithPrefixNames input = new BeanWithPrefixNames();
String json = mapper.writeValueAsString(input);
assertEquals("{\"Get-a\":3}", json);
BeanWithPrefixNames output = mapper.readValue("{\"Set-a\":7}",
BeanWithPrefixNames.class);
assertEquals(7, output.a);
}
}
| BeanWithPrefixNames |
java | apache__flink | flink-state-backends/flink-statebackend-forst/src/test/java/org/apache/flink/state/forst/fs/ForStFileSystemTrackingCreatedDirDecoratorTest.java | {
"start": 1301,
"end": 3966
} | class ____ extends LocalFileSystem {
private final boolean dummyMkdirEnabled;
public MockLocalFileSystem(boolean dummyMkdirEnabled) {
super();
this.dummyMkdirEnabled = dummyMkdirEnabled;
}
@Override
public synchronized boolean mkdirs(org.apache.flink.core.fs.Path path) throws IOException {
if (dummyMkdirEnabled) {
return true;
} else {
return super.mkdirs(path);
}
}
}
@Test
public void testMkdirAndCheck() throws IOException {
mkdirAndCheck(false);
}
@Test
public void testDummyMkdirAndCheck() throws IOException {
mkdirAndCheck(true);
}
void mkdirAndCheck(boolean enableDummyMkdir) throws IOException {
org.apache.flink.core.fs.Path remotePath =
new org.apache.flink.core.fs.Path(tempDir.toString() + "/remote");
org.apache.flink.core.fs.Path localPath =
new org.apache.flink.core.fs.Path(tempDir.toString() + "/local");
MockLocalFileSystem mockLocalFileSystem = new MockLocalFileSystem(enableDummyMkdir);
ForStFlinkFileSystem fileSystem =
ForStFileSystemUtils.tryDecorate(
new ForStFlinkFileSystem(
mockLocalFileSystem,
remotePath.toString(),
localPath.toString(),
null));
if (enableDummyMkdir) {
assertThat(fileSystem).isInstanceOf(ForStFileSystemTrackingCreatedDirDecorator.class);
}
// create a directory
String dirPathStr = genRandomFilePathStr();
org.apache.flink.core.fs.Path testMkdirPath = new org.apache.flink.core.fs.Path(dirPathStr);
fileSystem.mkdirs(testMkdirPath);
assertThat(mockLocalFileSystem.exists(testMkdirPath)).isEqualTo(!enableDummyMkdir);
assertThat(fileSystem.exists(testMkdirPath)).isTrue();
// create sub directories
for (int i = 0; i < 10; i++) {
String subDirName = UUID.randomUUID().toString();
org.apache.flink.core.fs.Path testSubMkdirPath =
new org.apache.flink.core.fs.Path(dirPathStr, subDirName);
fileSystem.mkdirs(testSubMkdirPath);
assertThat(mockLocalFileSystem.exists(testSubMkdirPath)).isEqualTo(!enableDummyMkdir);
assertThat(fileSystem.exists(testSubMkdirPath)).isTrue();
}
}
private String genRandomFilePathStr() {
return tempDir.toString() + "/" + UUID.randomUUID();
}
}
| MockLocalFileSystem |
java | quarkusio__quarkus | devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/examples/google-cloud-functions-example/java/src/test/java/org/acme/googlecloudfunctions/HelloWorldCloudEventsFunctionTest.java | {
"start": 341,
"end": 1735
} | class ____ {
@Test
void testAccept() {
given()
.body("{\n" +
" \"bucket\": \"MY_BUCKET\",\n" +
" \"contentType\": \"text/plain\",\n" +
" \"kind\": \"storage#object\",\n" +
" \"md5Hash\": \"...\",\n" +
" \"metageneration\": \"1\",\n" +
" \"name\": \"MY_FILE.txt\",\n" +
" \"size\": \"352\",\n" +
" \"storageClass\": \"MULTI_REGIONAL\",\n" +
" \"timeCreated\": \"2020-04-23T07:38:57.230Z\",\n" +
" \"timeStorageClassUpdated\": \"2020-04-23T07:38:57.230Z\",\n" +
" \"updated\": \"2020-04-23T07:38:57.230Z\"\n" +
" }")
.header("ce-specversion", "1.0")
.header("ce-id", "1234567890")
.header("ce-type", "google.cloud.storage.object.v1.finalized")
.header("ce-source", "//storage.googleapis.com/projects/_/buckets/MY-BUCKET-NAME")
.header("ce-subject", "objects/MY_FILE.txt")
.when()
.post()
.then()
.statusCode(200);
}
} | HelloWorldCloudEventsFunctionTest |
java | apache__rocketmq | tools/src/test/java/org/apache/rocketmq/tools/command/consumer/UpdateSubGroupListSubCommandTest.java | {
"start": 1107,
"end": 1883
} | class ____ {
@Test
public void testArguments() {
UpdateSubGroupListSubCommand cmd = new UpdateSubGroupListSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String brokerAddress = "127.0.0.1:10911";
String inputFileName = "groups.json";
String[] args = new String[] {"-b " + brokerAddress, "-f " + inputFileName};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), args,
cmd.buildCommandlineOptions(options), new DefaultParser());
assertEquals(brokerAddress, commandLine.getOptionValue('b').trim());
assertEquals(inputFileName, commandLine.getOptionValue('f').trim());
}
} | UpdateSubGroupListSubCommandTest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/security/token/DelegationTokenProvider.java | {
"start": 1170,
"end": 1375
} | interface ____
* responsible to produce the serialized form of tokens which will be handled by {@link
* DelegationTokenReceiver} instances both on JobManager and TaskManager side.
*/
@Experimental
public | is |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/test/TestWebAppTests.java | {
"start": 2256,
"end": 3173
} | class ____ extends Bar {
}
@Test
void testCreateInjector() throws Exception {
Bar bar = new Bar();
Injector injector = WebAppTests.createMockInjector(Foo.class, bar);
logInstances(injector.getInstance(HttpServletRequest.class),
injector.getInstance(HttpServletResponse.class),
injector.getInstance(HttpServletResponse.class).getWriter());
assertSame(bar, injector.getInstance(Foo.class));
}
@Test
void testCreateInjector2() {
final FooBar foobar = new FooBar();
Bar bar = new Bar();
Injector injector = WebAppTests.createMockInjector(Foo.class, bar,
new AbstractModule() {
@Override
protected void configure() {
bind(Bar.class).toInstance(foobar);
}
});
assertNotSame(bar, injector.getInstance(Bar.class));
assertSame(foobar, injector.getInstance(Bar.class));
}
@RequestScoped
static | FooBar |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/jpa/internal/util/PersistenceUtilHelper.java | {
"start": 8172,
"end": 8435
} | class ____ extends HibernateException {
public AttributeExtractionException(String message) {
super( message );
}
public AttributeExtractionException(String message, Throwable cause) {
super( message, cause );
}
}
public | AttributeExtractionException |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/UserBoolQueryBuilder.java | {
"start": 921,
"end": 2405
} | class ____ extends BoolQueryBuilder {
private static final Set<String> FIELDS_ALLOWED_TO_QUERY = Set.of("_id", User.Fields.TYPE.getPreferredName());
private UserBoolQueryBuilder() {}
public static UserBoolQueryBuilder build(QueryBuilder queryBuilder) {
final UserBoolQueryBuilder finalQuery = new UserBoolQueryBuilder();
if (queryBuilder != null) {
QueryBuilder processedQuery = USER_FIELD_NAME_TRANSLATORS.translateQueryBuilderFields(queryBuilder, null);
finalQuery.must(processedQuery);
}
finalQuery.filter(QueryBuilders.termQuery(User.Fields.TYPE.getPreferredName(), NativeUsersStore.USER_DOC_TYPE));
return finalQuery;
}
@Override
protected Query doToQuery(SearchExecutionContext context) throws IOException {
context.setAllowedFields(this::isIndexFieldNameAllowed);
return super.doToQuery(context);
}
@Override
protected QueryBuilder doRewrite(QueryRewriteContext queryRewriteContext) throws IOException {
if (queryRewriteContext instanceof SearchExecutionContext) {
((SearchExecutionContext) queryRewriteContext).setAllowedFields(this::isIndexFieldNameAllowed);
}
return super.doRewrite(queryRewriteContext);
}
boolean isIndexFieldNameAllowed(String fieldName) {
return FIELDS_ALLOWED_TO_QUERY.contains(fieldName) || USER_FIELD_NAME_TRANSLATORS.isIndexFieldSupported(fieldName);
}
}
| UserBoolQueryBuilder |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/SerializableReads.java | {
"start": 1317,
"end": 1592
} | class ____. I don't think anyone will bother calling this
// directly, but I don't see any reason not to block it.
"readClassDescriptor",
// These are basically the same as above.
"resolveClass",
"resolveObject");
}
| descriptors |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestMaxRunningAppsEnforcer.java | {
"start": 1619,
"end": 8493
} | class ____ {
private QueueManager queueManager;
private Map<String, Integer> userMaxApps;
private MaxRunningAppsEnforcer maxAppsEnforcer;
private int appNum;
private ControlledClock clock;
private RMContext rmContext;
private FairScheduler scheduler;
@BeforeEach
public void setup() {
FairSchedulerConfiguration conf = new FairSchedulerConfiguration();
PlacementManager placementManager = new PlacementManager();
rmContext = mock(RMContext.class);
when(rmContext.getQueuePlacementManager()).thenReturn(placementManager);
when(rmContext.getEpoch()).thenReturn(0L);
when(rmContext.getYarnConfiguration()).thenReturn(conf);
clock = new ControlledClock();
scheduler = mock(FairScheduler.class);
when(scheduler.getConf()).thenReturn(conf);
when(scheduler.getConfig()).thenReturn(conf);
when(scheduler.getClock()).thenReturn(clock);
when(scheduler.getResourceCalculator()).thenReturn(
new DefaultResourceCalculator());
when(scheduler.getRMContext()).thenReturn(rmContext);
AllocationConfiguration allocConf = new AllocationConfiguration(scheduler);
when(scheduler.getAllocationConfiguration()).thenReturn(allocConf);
queueManager = new QueueManager(scheduler);
queueManager.initialize();
userMaxApps = allocConf.userMaxApps;
maxAppsEnforcer = new MaxRunningAppsEnforcer(scheduler);
appNum = 0;
}
private FSAppAttempt addApp(FSLeafQueue queue, String user) {
ApplicationId appId = ApplicationId.newInstance(0l, appNum++);
ApplicationAttemptId attId = ApplicationAttemptId.newInstance(appId, 0);
FSAppAttempt app = new FSAppAttempt(scheduler, attId, user, queue, null,
rmContext);
boolean runnable = maxAppsEnforcer.canAppBeRunnable(queue, app);
queue.addApp(app, runnable);
if (runnable) {
maxAppsEnforcer.trackRunnableApp(app);
} else {
maxAppsEnforcer.trackNonRunnableApp(app);
}
return app;
}
private void removeApp(FSAppAttempt app) {
app.getQueue().removeApp(app);
maxAppsEnforcer.untrackRunnableApp(app);
maxAppsEnforcer.updateRunnabilityOnAppRemoval(app, app.getQueue());
}
@Test
public void testRemoveDoesNotEnableAnyApp() {
FSParentQueue root = queueManager.getRootQueue();
FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1", true);
FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue2", true);
root.setMaxRunningApps(2);
leaf1.setMaxRunningApps(1);
leaf2.setMaxRunningApps(1);
FSAppAttempt app1 = addApp(leaf1, "user");
addApp(leaf2, "user");
addApp(leaf2, "user");
assertEquals(1, leaf1.getNumRunnableApps());
assertEquals(1, leaf2.getNumRunnableApps());
assertEquals(1, leaf2.getNumNonRunnableApps());
removeApp(app1);
assertEquals(0, leaf1.getNumRunnableApps());
assertEquals(1, leaf2.getNumRunnableApps());
assertEquals(1, leaf2.getNumNonRunnableApps());
}
@Test
public void testRemoveEnablesAppOnCousinQueue() {
FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.subqueue1.leaf1", true);
FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.subqueue2.leaf2", true);
FSParentQueue queue1 = queueManager.getParentQueue("root.queue1", true);
queue1.setMaxRunningApps(2);
FSAppAttempt app1 = addApp(leaf1, "user");
addApp(leaf2, "user");
addApp(leaf2, "user");
assertEquals(1, leaf1.getNumRunnableApps());
assertEquals(1, leaf2.getNumRunnableApps());
assertEquals(1, leaf2.getNumNonRunnableApps());
removeApp(app1);
assertEquals(0, leaf1.getNumRunnableApps());
assertEquals(2, leaf2.getNumRunnableApps());
assertEquals(0, leaf2.getNumNonRunnableApps());
}
@Test
public void testRemoveEnablesOneByQueueOneByUser() {
FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.leaf1", true);
FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.leaf2", true);
leaf1.setMaxRunningApps(2);
userMaxApps.put("user1", 1);
FSAppAttempt app1 = addApp(leaf1, "user1");
addApp(leaf1, "user2");
addApp(leaf1, "user3");
addApp(leaf2, "user1");
assertEquals(2, leaf1.getNumRunnableApps());
assertEquals(1, leaf1.getNumNonRunnableApps());
assertEquals(1, leaf2.getNumNonRunnableApps());
removeApp(app1);
assertEquals(2, leaf1.getNumRunnableApps());
assertEquals(1, leaf2.getNumRunnableApps());
assertEquals(0, leaf1.getNumNonRunnableApps());
assertEquals(0, leaf2.getNumNonRunnableApps());
}
@Test
public void testRemoveEnablingOrderedByStartTime() {
FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.subqueue1.leaf1", true);
FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.subqueue2.leaf2", true);
FSParentQueue queue1 = queueManager.getParentQueue("root.queue1", true);
queue1.setMaxRunningApps(2);
FSAppAttempt app1 = addApp(leaf1, "user");
addApp(leaf2, "user");
addApp(leaf2, "user");
clock.tickSec(20);
addApp(leaf1, "user");
assertEquals(1, leaf1.getNumRunnableApps());
assertEquals(1, leaf2.getNumRunnableApps());
assertEquals(1, leaf1.getNumNonRunnableApps());
assertEquals(1, leaf2.getNumNonRunnableApps());
removeApp(app1);
assertEquals(0, leaf1.getNumRunnableApps());
assertEquals(2, leaf2.getNumRunnableApps());
assertEquals(0, leaf2.getNumNonRunnableApps());
}
@Test
public void testMultipleAppsWaitingOnCousinQueue() {
FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.subqueue1.leaf1", true);
FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.subqueue2.leaf2", true);
FSParentQueue queue1 = queueManager.getParentQueue("root.queue1", true);
queue1.setMaxRunningApps(2);
FSAppAttempt app1 = addApp(leaf1, "user");
addApp(leaf2, "user");
addApp(leaf2, "user");
addApp(leaf2, "user");
assertEquals(1, leaf1.getNumRunnableApps());
assertEquals(1, leaf2.getNumRunnableApps());
assertEquals(2, leaf2.getNumNonRunnableApps());
removeApp(app1);
assertEquals(0, leaf1.getNumRunnableApps());
assertEquals(2, leaf2.getNumRunnableApps());
assertEquals(1, leaf2.getNumNonRunnableApps());
}
@Test
public void testMultiListStartTimeIteratorEmptyAppLists() {
List<List<FSAppAttempt>> lists = new ArrayList<List<FSAppAttempt>>();
lists.add(Arrays.asList(mockAppAttempt(1)));
lists.add(Arrays.asList(mockAppAttempt(2)));
Iterator<FSAppAttempt> iter =
new MaxRunningAppsEnforcer.MultiListStartTimeIterator(lists);
assertEquals(1, iter.next().getStartTime());
assertEquals(2, iter.next().getStartTime());
}
private FSAppAttempt mockAppAttempt(long startTime) {
FSAppAttempt schedApp = mock(FSAppAttempt.class);
when(schedApp.getStartTime()).thenReturn(startTime);
return schedApp;
}
}
| TestMaxRunningAppsEnforcer |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/method/configuration/PrePostMethodSecurityConfigurationTests.java | {
"start": 67196,
"end": 68004
} | class ____ {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
Advisor customAfterAdvice(SecurityContextHolderStrategy strategy) {
JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut();
pointcut.setPattern(".*MethodSecurityServiceImpl.*securedUser");
MethodInterceptor interceptor = (mi) -> {
Authentication auth = strategy.getContext().getAuthentication();
if ("bob".equals(auth.getName())) {
return "granted";
}
throw new AccessDeniedException("Access Denied for User '" + auth.getName() + "'");
};
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, interceptor);
advisor.setOrder(AuthorizationInterceptorsOrder.POST_FILTER.getOrder() + 1);
return advisor;
}
}
@Configuration
static | CustomAuthorizationManagerAfterAdviceConfig |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/service/connection/ConnectionDetailsFactoriesTests.java | {
"start": 1460,
"end": 5544
} | class ____ {
private final MockSpringFactoriesLoader loader = new MockSpringFactoriesLoader();
@Test
void getRequiredConnectionDetailsWhenNoFactoryForSourceThrowsException() {
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
assertThatExceptionOfType(ConnectionDetailsFactoryNotFoundException.class)
.isThrownBy(() -> factories.getConnectionDetails("source", true));
}
@Test
void getOptionalConnectionDetailsWhenNoFactoryForSourceThrowsException() {
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
assertThat(factories.getConnectionDetails("source", false)).isEmpty();
}
@Test
void getConnectionDetailsWhenSourceHasOneMatchReturnsSingleResult() {
this.loader.addInstance(ConnectionDetailsFactory.class, new TestConnectionDetailsFactory());
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
Map<Class<?>, ConnectionDetails> connectionDetails = factories.getConnectionDetails("source", false);
assertThat(connectionDetails).hasSize(1);
assertThat(connectionDetails.get(TestConnectionDetails.class)).isInstanceOf(TestConnectionDetailsImpl.class);
}
@Test
void getRequiredConnectionDetailsWhenSourceHasNoMatchTheowsException() {
this.loader.addInstance(ConnectionDetailsFactory.class, new NullResultTestConnectionDetailsFactory());
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
assertThatExceptionOfType(ConnectionDetailsNotFoundException.class)
.isThrownBy(() -> factories.getConnectionDetails("source", true));
}
@Test
void getOptionalConnectionDetailsWhenSourceHasNoMatchReturnsEmptyMap() {
this.loader.addInstance(ConnectionDetailsFactory.class, new NullResultTestConnectionDetailsFactory());
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
Map<Class<?>, ConnectionDetails> connectionDetails = factories.getConnectionDetails("source", false);
assertThat(connectionDetails).isEmpty();
}
@Test
void getConnectionDetailsWhenSourceHasMultipleMatchesReturnsMultipleResults() {
this.loader.addInstance(ConnectionDetailsFactory.class, new TestConnectionDetailsFactory(),
new OtherConnectionDetailsFactory());
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
Map<Class<?>, ConnectionDetails> connectionDetails = factories.getConnectionDetails("source", false);
assertThat(connectionDetails).hasSize(2);
}
@Test
void getConnectionDetailsWhenDuplicatesThrowsException() {
this.loader.addInstance(ConnectionDetailsFactory.class, new TestConnectionDetailsFactory(),
new TestConnectionDetailsFactory());
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
assertThatIllegalStateException().isThrownBy(() -> factories.getConnectionDetails("source", false))
.withMessage("Duplicate connection details supplied for " + TestConnectionDetails.class.getName());
}
@Test
void getRegistrationsReturnsOrderedDelegates() {
TestConnectionDetailsFactory orderOne = new TestConnectionDetailsFactory(1);
TestConnectionDetailsFactory orderTwo = new TestConnectionDetailsFactory(2);
TestConnectionDetailsFactory orderThree = new TestConnectionDetailsFactory(3);
this.loader.addInstance(ConnectionDetailsFactory.class, orderOne, orderThree, orderTwo);
ConnectionDetailsFactories factories = new ConnectionDetailsFactories(this.loader);
List<Registration<String, ?>> registrations = factories.getRegistrations("source", false);
assertThat(registrations.get(0).factory()).isEqualTo(orderOne);
assertThat(registrations.get(1).factory()).isEqualTo(orderTwo);
assertThat(registrations.get(2).factory()).isEqualTo(orderThree);
}
@Test
void factoryLoadFailureDoesNotPreventOtherFactoriesFromLoading() {
this.loader.add(ConnectionDetailsFactory.class.getName(), "com.example.NonExistentConnectionDetailsFactory");
assertThatNoException().isThrownBy(() -> new ConnectionDetailsFactories(this.loader));
}
private static final | ConnectionDetailsFactoriesTests |
java | apache__camel | test-infra/camel-test-infra-kafka/src/test/java/org/apache/camel/test/infra/kafka/services/KafkaServiceFactory.java | {
"start": 4044,
"end": 4702
} | class ____ extends ContainerLocalKafkaInfraService implements KafkaService {
public ContainerLocalKafkaService(KafkaContainer kafka) {
super.kafka = kafka;
}
public static ContainerLocalKafkaService kafka3Container() {
KafkaContainer container
= new KafkaContainer(
DockerImageName.parse(System.getProperty(KafkaProperties.KAFKA_CONTAINER, KAFKA3_IMAGE_NAME))
.asCompatibleSubstituteFor("apache/kafka"));
return new ContainerLocalKafkaService(container);
}
}
public static | ContainerLocalKafkaService |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/aggregate/SybaseASEAggregateSupport.java | {
"start": 21837,
"end": 22661
} | class ____ implements XmlWriteExpression {
private final SelectableMapping selectableMapping;
PassThroughXmlWriteExpression(SelectableMapping selectableMapping) {
this.selectableMapping = selectableMapping;
}
@Override
public boolean isAggregate() {
return selectableMapping.getJdbcMapping().getJdbcType().isXml();
}
@Override
public void append(
SqlAppender sb,
String path,
SqlAstTranslator<?> translator,
AggregateColumnWriteExpression expression) {
sb.append( "xmlextract(" );
sb.append( xmlExtractArguments( path, selectableMapping.getSelectableName() ) );
// This expression is always going to be concatenated
// Since concatenation doesn't support LOBs, ensure a varchar is returned
sb.append( " returns varchar(16384))" );
}
}
}
| PassThroughXmlWriteExpression |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/MulticastNoStopOnExceptionTest.java | {
"start": 1206,
"end": 3033
} | class ____ extends ContextTestSupport {
@Test
public void testMulticastNoStopOnExceptionOk() throws Exception {
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello");
getMockEndpoint("mock:bar").expectedBodiesReceived("Hello");
getMockEndpoint("mock:baz").expectedBodiesReceived("Hello");
getMockEndpoint("mock:result").expectedBodiesReceived("Hello");
template.sendBody("direct:start", "Hello");
assertMockEndpointsSatisfied();
}
@Test
public void testMulticastNoStopOnExceptionStop() throws Exception {
getMockEndpoint("mock:foo").expectedBodiesReceived("Kaboom");
getMockEndpoint("mock:bar").expectedMessageCount(0);
// we do not stop so we should continue and thus baz receives 1 message
getMockEndpoint("mock:baz").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
try {
template.sendBody("direct:start", "Kaboom");
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
assertEquals("Forced", e.getCause().getMessage());
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").multicast().to("direct:foo", "direct:bar", "direct:baz").end().to("mock:result");
from("direct:foo").to("mock:foo");
from("direct:bar").process(new MyProcessor()).to("mock:bar");
from("direct:baz").to("mock:baz");
}
};
}
public static | MulticastNoStopOnExceptionTest |
java | apache__camel | components/camel-kafka/src/main/java/org/apache/camel/component/kafka/serde/DefaultKafkaHeaderSerializer.java | {
"start": 1027,
"end": 2869
} | class ____ implements KafkaHeaderSerializer, CamelContextAware {
private static final Logger LOG = LoggerFactory.getLogger(DefaultKafkaHeaderSerializer.class);
private CamelContext camelContext;
@Override
public byte[] serialize(final String key, final Object value) {
if (value instanceof String string) {
return string.getBytes();
} else if (value instanceof Long aLong) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(aLong);
return buffer.array();
} else if (value instanceof Integer integer) {
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.putInt(integer);
return buffer.array();
} else if (value instanceof Double aDouble) {
ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
buffer.putDouble(aDouble);
return buffer.array();
} else if (value instanceof Boolean b) {
return b.toString().getBytes();
} else if (value instanceof byte[] bytes) {
return bytes;
}
if (camelContext != null) {
byte[] converted = camelContext.getTypeConverter().tryConvertTo(byte[].class, value);
if (converted != null) {
return converted;
}
}
LOG.debug("Cannot propagate header value of type[{}], skipping... "
+ "Supported types: String, Integer, Long, Double, byte[].",
value != null ? value.getClass() : "null");
return null;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
}
| DefaultKafkaHeaderSerializer |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_2663/RequestDto.java | {
"start": 753,
"end": 1038
} | class ____ {
private JsonNullable<String> name = JsonNullable.undefined();
public JsonNullable<String> getName() {
return name;
}
public void setName(JsonNullable<String> name) {
this.name = name;
}
}
}
| ChildRequestDto |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/shard/EngineResetLock.java | {
"start": 987,
"end": 3320
} | class ____ implements ReadWriteLock {
private final ReentrantReadWriteLock lock;
public EngineResetLock() {
this.lock = Assertions.ENABLED ? new QueuedWriterThreadsReentrantReadWriteLock() : new ReentrantReadWriteLock();
}
@Override
public Lock writeLock() {
return lock.writeLock();
}
@Override
public Lock readLock() {
return lock.readLock();
}
/**
* See {@link ReentrantReadWriteLock#isWriteLocked()}
*/
public boolean isWriteLocked() {
return lock.isWriteLocked();
}
/**
* See {@link ReentrantReadWriteLock#isWriteLockedByCurrentThread()}
*/
public boolean isWriteLockedByCurrentThread() {
return lock.isWriteLockedByCurrentThread();
}
/**
* Returns {@code true} if the number of read locks held by any thread is greater than zero.
* This method is designed for use in monitoring system state, not for synchronization control.
*
* @return {@code true} if any thread holds a read lock and {@code false} otherwise
*/
public boolean isReadLocked() {
return lock.getReadLockCount() > 0;
}
/**
* Returns {@code true} if the number of holds on the read lock by the current thread is greater than zero.
* This method is designed for use in monitoring system state, not for synchronization control.
*
* @return {@code true} if the number of holds on the read lock by the current thread is greater than zero, {@code false} otherwise
*/
public boolean isReadLockedByCurrentThread() {
return lock.getReadHoldCount() > 0;
}
/**
* See {@link ReentrantReadWriteLock#getReadLockCount()}
*/
public int getReadLockCount() {
return lock.getReadLockCount();
}
/**
* See {@link ReentrantReadWriteLock#getQueuedWriterThreads()}
*/
// package-private for tests
Collection<Thread> getQueuedWriterThreads() {
if (lock instanceof QueuedWriterThreadsReentrantReadWriteLock queuedLock) {
return queuedLock.queuedWriterThreads();
} else {
return List.of();
}
}
/**
* Extends ReentrantReadWriteLock to expose the protected {@link ReentrantReadWriteLock#getQueuedWriterThreads()} method
*/
private static | EngineResetLock |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/selectcase/SelectCaseTest.java | {
"start": 3822,
"end": 3865
} | enum ____ {
VALUE_1,
VALUE_2
}
}
| EnumValue |
java | resilience4j__resilience4j | resilience4j-spring/src/main/java/io/github/resilience4j/circuitbreaker/configure/IgnoreClassBindingExceptionConverter.java | {
"start": 738,
"end": 1370
} | class ____ implements Converter<String, Class<? extends Throwable>> {
private static final Logger LOG = LoggerFactory.getLogger(IgnoreClassBindingExceptionConverter.class);
private final boolean ignoreUnknownExceptions;
public IgnoreClassBindingExceptionConverter(boolean ignoreUnknownExceptions) {
this.ignoreUnknownExceptions = ignoreUnknownExceptions;
if (ignoreUnknownExceptions) {
LOG.debug("Configured to ignore unknown exceptions. Unknown exceptions will be replaced with a placeholder.");
}
}
/**
* Converts the given exception | IgnoreClassBindingExceptionConverter |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/erroneous/interceptorBean/InterceptorBeanInjectionBeanClassTest.java | {
"start": 908,
"end": 990
} | class ____ {
@Inject
Interceptor<MyBean> interceptor;
}
}
| MyBean |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/TemporalAccessorGetChronoFieldTest.java | {
"start": 2028,
"end": 2600
} | class ____ {
private static final long value1 = MONDAY.getLong(DAY_OF_WEEK);
// BUG: Diagnostic contains: TemporalAccessorGetChronoField
private static final long value2 = MONDAY.getLong(NANO_OF_DAY);
}
""")
.doTest();
}
@Test
public void temporalAccessor_get_noStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"""
import static java.time.DayOfWeek.MONDAY;
import java.time.temporal.ChronoField;
public | TestClass |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ActiveMQ6EndpointBuilderFactory.java | {
"start": 25087,
"end": 26039
} | class ____ is
* good enough as subscription name). Only makes sense when listening to
* a topic (pub-sub domain), therefore this method switches the
* pubSubDomain flag as well.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param subscriptionDurable the value to set
* @return the dsl builder
*/
default ActiveMQ6EndpointConsumerBuilder subscriptionDurable(String subscriptionDurable) {
doSetProperty("subscriptionDurable", subscriptionDurable);
return this;
}
/**
* Set the name of a subscription to create. To be applied in case of a
* topic (pub-sub domain) with a shared or durable subscription. The
* subscription name needs to be unique within this client's JMS client
* id. Default is the | name |
java | apache__camel | components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/KubernetesCategory.java | {
"start": 864,
"end": 1756
} | class ____ {
public static final String NAMESPACES = "namespaces";
public static final String SERVICES = "services";
public static final String REPLICATION_CONTROLLERS = "replicationControllers";
public static final String PODS = "pods";
public static final String PERSISTENT_VOLUMES = "persistentVolumes";
public static final String PERSISTENT_VOLUMES_CLAIMS = "persistentVolumesClaims";
public static final String SECRETS = "secrets";
public static final String RESOURCES_QUOTA = "resourcesQuota";
public static final String SERVICE_ACCOUNTS = "serviceAccounts";
public static final String NODES = "nodes";
public static final String CONFIGMAPS = "configMaps";
public static final String BUILDS = "builds";
public static final String BUILD_CONFIGS = "buildConfigs";
private KubernetesCategory() {
}
}
| KubernetesCategory |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/cache/spi/entry/UnstructuredCacheEntry.java | {
"start": 336,
"end": 762
} | class ____ implements CacheEntryStructure {
/**
* Access to the singleton instance.
*/
public static final UnstructuredCacheEntry INSTANCE = new UnstructuredCacheEntry();
@Override
public Object structure(Object item) {
return item;
}
@Override
public Object destructure(Object structured, SessionFactoryImplementor factory) {
return structured;
}
private UnstructuredCacheEntry() {
}
}
| UnstructuredCacheEntry |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/tofix/AnyGetterNameConflictSerialization5342Test.java | {
"start": 768,
"end": 2682
} | class ____ {
@JsonIgnore
private Map<String, Object> additionalProperties;
@JsonProperty(value = "additionalProperties")
private Map<String, Object> hidden;
@JsonAnySetter
private void additionalProperties(String key, Object value) {
if (additionalProperties == null) {
additionalProperties = new HashMap<>();
}
additionalProperties.put(key.replace("\\.", "."), value);
}
@JsonAnyGetter
public Map<String, Object> additionalProperties() {
return additionalProperties;
}
public Map<String, Object> hidden() {
return hidden;
}
public void hidden(Map<String, Object> additionalPropertiesProperty) {
this.hidden = additionalPropertiesProperty;
}
}
private final ObjectMapper MAPPER = newJsonMapper();
@JacksonTestFailureExpected
@Test
public void anyGetter5342()
throws Exception
{
Pojo5342 pojo = new Pojo5342();
pojo.additionalProperties("foo", "bar");
Map<String, Object> hidden = new HashMap<>();
hidden.put("fizz", "buzz");
pojo.hidden(hidden);
String JSON = MAPPER.writeValueAsString(pojo);
// was in 2.18 : {"foo":"bar","additionalProperties": {"fizz":"buzz"}}
// now in 2.19 : {"foo":"bar"}... need FIX!
// any-getter
assertThat(JSON).contains("\"foo\":\"bar\"");
// hidden field
assertThat(JSON).contains("\"additionalProperties\":{\"fizz\":\"buzz\"}");
// Try deserializing back
Pojo5342 actual = MAPPER.readValue(JSON, Pojo5342.class);
assertNotNull(actual.additionalProperties());
assertEquals(1, actual.additionalProperties.size());
assertNotNull(actual.hidden());
assertEquals(1, actual.hidden().size());
}
}
| Pojo5342 |
java | apache__hadoop | hadoop-tools/hadoop-streaming/src/test/java/org/apache/hadoop/streaming/TestStreamXmlMultipleRecords.java | {
"start": 1443,
"end": 5448
} | class ____ extends TestStreaming
{
private static final Logger LOG = LoggerFactory.getLogger(
TestStreamXmlMultipleRecords.class);
private boolean hasPerl = false;
private long blockSize;
private String isSlowMatch;
// Our own configuration used for creating FileSystem object where
// fs.local.block.size is set to 60 OR 80.
// See 60th char in input. It is before the end of end-tag of a record.
// See 80th char in input. It is in between the end-tag of a record and
// the begin-tag of next record.
private Configuration conf = null;
private String myPerlMapper =
"perl -n -a -e 'print join(qq(\\n), map { qq($_\\t1) } @F), qq(\\n);'";
private String myPerlReducer =
"perl -n -a -e '$freq{$F[0]}++; END { print qq(is\\t$freq{is}\\n); }'";
public TestStreamXmlMultipleRecords() throws IOException {
super();
input = "<line>This is a single line,\nand it is containing multiple" +
" words.</line> <line>Only is appears more than" +
" once.</line>\n";
outputExpect = "is\t3\n";
map = myPerlMapper;
reduce = myPerlReducer;
hasPerl = UtilTest.hasPerlSupport();
}
@Override
@BeforeEach
public void setUp() throws IOException {
super.setUp();
// Without this closeAll() call, setting of FileSystem block size is
// not effective and will be old block size set in earlier test.
FileSystem.closeAll();
}
// Set file system block size such that split falls
// (a) before the end of end-tag of a record (testStreamXmlMultiInner...) OR
// (b) between records(testStreamXmlMultiOuter...)
@Override
protected Configuration getConf() {
conf = new Configuration();
conf.setLong("fs.local.block.size", blockSize);
return conf;
}
@Override
protected String[] genArgs() {
args.add("-inputreader");
args.add("StreamXmlRecordReader,begin=<line>,end=</line>,slowmatch=" +
isSlowMatch);
return super.genArgs();
}
/**
* Tests if StreamXmlRecordReader will read the next record, _after_ the
* end of a split if the split falls before the end of end-tag of a record.
* Tests with slowmatch=false.
* @throws Exception
*/
@Test
public void testStreamXmlMultiInnerFast() throws Exception {
if (hasPerl) {
blockSize = 60;
isSlowMatch = "false";
super.testCommandLine();
}
else {
LOG.warn("No perl; skipping test.");
}
}
/**
* Tests if StreamXmlRecordReader will read a record twice if end of a
* split is after few characters after the end-tag of a record but before the
* begin-tag of next record.
* Tests with slowmatch=false.
* @throws Exception
*/
@Test
public void testStreamXmlMultiOuterFast() throws Exception {
if (hasPerl) {
blockSize = 80;
isSlowMatch = "false";
super.testCommandLine();
}
else {
LOG.warn("No perl; skipping test.");
}
}
/**
* Tests if StreamXmlRecordReader will read the next record, _after_ the
* end of a split if the split falls before the end of end-tag of a record.
* Tests with slowmatch=true.
* @throws Exception
*/
@Test
public void testStreamXmlMultiInnerSlow() throws Exception {
if (hasPerl) {
blockSize = 60;
isSlowMatch = "true";
super.testCommandLine();
}
else {
LOG.warn("No perl; skipping test.");
}
}
/**
* Tests if StreamXmlRecordReader will read a record twice if end of a
* split is after few characters after the end-tag of a record but before the
* begin-tag of next record.
* Tests with slowmatch=true.
* @throws Exception
*/
@Test
public void testStreamXmlMultiOuterSlow() throws Exception {
if (hasPerl) {
blockSize = 80;
isSlowMatch = "true";
super.testCommandLine();
}
else {
LOG.warn("No perl; skipping test.");
}
}
@Override
@Test
public void testCommandLine() {
// Do nothing
}
}
| TestStreamXmlMultipleRecords |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ext/javatime/key/PeriodAsKeyTest.java | {
"start": 388,
"end": 1856
} | class ____ extends DateTimeTestBase
{
private static final TypeReference<Map<Period, String>> TYPE_REF = new TypeReference<Map<Period, String>>() {
};
private static final Period PERIOD_0 = Period.of(0, 0, 0);
private static final String PERIOD_0_STRING = "P0D";
private static final Period PERIOD = Period.of(3, 1, 4);
private static final String PERIOD_STRING = "P3Y1M4D";
private final ObjectMapper MAPPER = newMapper();
private final ObjectReader READER = MAPPER.readerFor(TYPE_REF);
@Test
public void testSerialization0() throws Exception {
assertEquals(mapAsString(PERIOD_0_STRING, "test"),
MAPPER.writeValueAsString(asMap(PERIOD_0, "test")),
"Value is incorrect");
}
@Test
public void testSerialization1() throws Exception {
assertEquals(mapAsString(PERIOD_STRING, "test"),
MAPPER.writeValueAsString(asMap(PERIOD, "test")),
"Value is incorrect");
}
@Test
public void testDeserialization0() throws Exception {
assertEquals(asMap(PERIOD_0, "test"),
READER.readValue(mapAsString(PERIOD_0_STRING, "test")),
"Value is incorrect");
}
@Test
public void testDeserialization1() throws Exception {
assertEquals(asMap(PERIOD, "test"),
READER.readValue(mapAsString(PERIOD_STRING, "test")),
"Value is incorrect");
}
}
| PeriodAsKeyTest |
java | apache__flink | flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/catalog/GenericInMemoryCatalogStoreFactoryOptions.java | {
"start": 1033,
"end": 1210
} | class ____ {
public static final String IDENTIFIER = "generic_in_memory";
private GenericInMemoryCatalogStoreFactoryOptions() {}
}
| GenericInMemoryCatalogStoreFactoryOptions |
java | apache__dubbo | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java | {
"start": 4935,
"end": 5760
} | class ____ of Dubbo service interface
* @param group the Dubbo Service Group (optional)
* @param version the Dubbo Service Version (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface, String group, String version) {
return getExportedURLs(serviceInterface, group, version, null);
}
/**
* Get the sorted set of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code>, <code>group</code>, <code>version</code> and <code>protocol</code>
*
* @param serviceInterface The | name |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/selection/qualifier/MovieFactoryMapper.java | {
"start": 675,
"end": 904
} | interface ____ {
MovieFactoryMapper INSTANCE = Mappers.getMapper( MovieFactoryMapper.class );
@BeanMapping(qualifiedBy = CreateGermanRelease.class)
AbstractEntry toGerman( OriginalRelease movies );
}
| MovieFactoryMapper |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/RestCancellableNodeClient.java | {
"start": 4396,
"end": 7245
} | class ____ implements ActionListener<Void> {
private final AtomicReference<HttpChannel> channel = new AtomicReference<>();
@Nullable // if already drained
private Set<TaskId> tasks = new HashSet<>();
CloseListener() {}
synchronized int getNumTasks() {
return tasks == null ? 0 : tasks.size();
}
void maybeRegisterChannel(HttpChannel httpChannel) {
if (channel.compareAndSet(null, httpChannel)) {
// In case the channel is already closed when we register the listener, the listener will be immediately executed which will
// remove the channel from the map straight-away. That is why we first create the CloseListener and later we associate it
// with the channel. This guarantees that the close listener is already in the map when it gets registered to its
// corresponding channel, hence it is always found in the map when it gets invoked if the channel gets closed.
httpChannel.addCloseListener(this);
}
}
void registerTask(TaskHolder taskHolder, TaskId taskId) {
synchronized (this) {
taskHolder.taskId = taskId;
if (tasks != null) {
if (taskHolder.completed == false) {
tasks.add(taskId);
}
return;
}
}
// else tasks == null so the channel is already closed
cancelTask(taskId);
}
synchronized void unregisterTask(TaskHolder taskHolder) {
if (taskHolder.taskId != null && tasks != null) {
tasks.remove(taskHolder.taskId);
}
taskHolder.completed = true;
}
@Override
public void onResponse(Void aVoid) {
final HttpChannel httpChannel = channel.get();
assert httpChannel != null : "channel not registered";
// when the channel gets closed it won't be reused: we can remove it from the map and forget about it.
final CloseListener closeListener = httpChannels.remove(httpChannel);
assert closeListener != null : "channel not found in the map of tracked channels: " + httpChannel;
assert closeListener == CloseListener.this : "channel had a different CloseListener registered: " + httpChannel;
for (final var taskId : drainTasks()) {
cancelTask(taskId);
}
}
private synchronized Collection<TaskId> drainTasks() {
final var drained = tasks;
tasks = null;
return drained;
}
@Override
public void onFailure(Exception e) {
onResponse(null);
}
}
private static | CloseListener |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/events/ListenerTest.java | {
"start": 4194,
"end": 4443
} | class ____ {
@PreUpdate
@PrePersist
public void setLastUpdate(Person p) {
p.setLastUpdate( new Date() );
}
}
//end::events-jpa-callbacks-example[]
//tag::events-interceptors-load-listener-example-part2[]
public static | LastUpdateListener |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/conversion/CurrencyToStringConversion.java | {
"start": 533,
"end": 1139
} | class ____ extends SimpleConversion {
@Override
protected String getToExpression(final ConversionContext conversionContext) {
return "<SOURCE>.getCurrencyCode()";
}
@Override
protected String getFromExpression(final ConversionContext conversionContext) {
return currency( conversionContext ) + ".getInstance( <SOURCE> )";
}
@Override
protected Set<Type> getFromConversionImportTypes(final ConversionContext conversionContext) {
return Collections.asSet( conversionContext.getTypeFactory().getType( Currency.class ) );
}
}
| CurrencyToStringConversion |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/model/simple/oneclassandskipfirstline/Order.java | {
"start": 1122,
"end": 4088
} | class ____ {
@DataField(pos = 1)
private int orderNr;
@DataField(pos = 2)
private String clientNr;
@DataField(pos = 3)
private String firstName;
@DataField(pos = 4)
private String lastName;
@DataField(pos = 5)
private String instrumentCode;
@DataField(pos = 6)
private String instrumentNumber;
@DataField(pos = 7)
private String orderType;
@DataField(name = "Name", pos = 8)
private String instrumentType;
@DataField(pos = 9, precision = 2)
private BigDecimal amount;
@DataField(pos = 10)
private String currency;
@DataField(pos = 11, pattern = "dd-MM-yyyy")
private Date orderDate;
public int getOrderNr() {
return orderNr;
}
public void setOrderNr(int orderNr) {
this.orderNr = orderNr;
}
public String getClientNr() {
return clientNr;
}
public void setClientNr(String clientNr) {
this.clientNr = clientNr;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getInstrumentCode() {
return instrumentCode;
}
public void setInstrumentCode(String instrumentCode) {
this.instrumentCode = instrumentCode;
}
public String getInstrumentNumber() {
return instrumentNumber;
}
public void setInstrumentNumber(String instrumentNumber) {
this.instrumentNumber = instrumentNumber;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public String getInstrumentType() {
return instrumentType;
}
public void setInstrumentType(String instrumentType) {
this.instrumentType = instrumentType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
@Override
public String toString() {
return "Model : " + Order.class.getName() + " : " + this.orderNr + ", " + this.orderType + ", "
+ String.valueOf(this.amount) + ", " + this.instrumentCode + ", "
+ this.instrumentNumber + ", " + this.instrumentType + ", " + this.currency + ", " + this.clientNr + ", "
+ this.firstName + ", " + this.lastName + ", "
+ String.valueOf(this.orderDate);
}
}
| Order |
java | micronaut-projects__micronaut-core | http-client-core/src/main/java/io/micronaut/http/client/exceptions/EmptyResponseException.java | {
"start": 784,
"end": 1010
} | class ____ extends HttpClientException {
/**
* Default constructor.
*/
public EmptyResponseException() {
super("HTTP Server returned an empty (and invalid) response body");
}
}
| EmptyResponseException |
java | micronaut-projects__micronaut-core | inject-groovy/src/main/groovy/io/micronaut/ast/groovy/scan/Context.java | {
"start": 715,
"end": 822
} | class ____ parsed in a {@link groovyjarjarasm.asm.ClassReader}.
*
* @author Eric Bruneton
*/
@Internal
| being |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/web/webhdfs/TestDataNodeUGIProvider.java | {
"start": 2683,
"end": 10564
} | class ____ {
private final URI uri = URI.create(WebHdfsConstants.WEBHDFS_SCHEME + "://"
+ "127.0.0.1:0");
private final String PATH = "/foo";
private final int OFFSET = 42;
private final int LENGTH = 512;
private final static int EXPIRE_AFTER_ACCESS = 5*1000;
private Configuration conf;
@BeforeEach
public void setUp(){
conf = WebHdfsTestUtil.createConf();
conf.setInt(DFSConfigKeys.DFS_WEBHDFS_UGI_EXPIRE_AFTER_ACCESS_KEY,
EXPIRE_AFTER_ACCESS);
DataNodeUGIProvider.init(conf);
}
@Test
public void testUGICacheSecure() throws Exception {
// fake turning on security so api thinks it should use tokens
SecurityUtil.setAuthenticationMethod(KERBEROS, conf);
UserGroupInformation.setConfiguration(conf);
UserGroupInformation ugi = UserGroupInformation
.createRemoteUser("test-user");
ugi.setAuthenticationMethod(KERBEROS);
ugi = UserGroupInformation.createProxyUser("test-proxy-user", ugi);
UserGroupInformation.setLoginUser(ugi);
List<Token<DelegationTokenIdentifier>> tokens = Lists.newArrayList();
getWebHdfsFileSystem(ugi, conf, tokens);
String uri1 = WebHdfsFileSystem.PATH_PREFIX
+ PATH
+ "?op=OPEN"
+ Param.toSortedString("&", new NamenodeAddressParam("127.0.0.1:1010"),
new OffsetParam((long) OFFSET), new LengthParam((long) LENGTH),
new DelegationParam(tokens.get(0).encodeToUrlString()));
String uri2 = WebHdfsFileSystem.PATH_PREFIX
+ PATH
+ "?op=OPEN"
+ Param.toSortedString("&", new NamenodeAddressParam("127.0.0.1:1010"),
new OffsetParam((long) OFFSET), new LengthParam((long) LENGTH),
new DelegationParam(tokens.get(1).encodeToUrlString()));
DataNodeUGIProvider ugiProvider1 = new DataNodeUGIProvider(
new ParameterParser(new QueryStringDecoder(URI.create(uri1)), conf));
UserGroupInformation ugi11 = ugiProvider1.ugi();
UserGroupInformation ugi12 = ugiProvider1.ugi();
assertEquals(ugi11, ugi12,
"With UGI cache, two UGIs returned by the same token should be same");
DataNodeUGIProvider ugiProvider2 = new DataNodeUGIProvider(
new ParameterParser(new QueryStringDecoder(URI.create(uri2)), conf));
UserGroupInformation url21 = ugiProvider2.ugi();
UserGroupInformation url22 = ugiProvider2.ugi();
assertEquals(url21, url22,
"With UGI cache, two UGIs returned by the same token should be same");
assertNotEquals(ugi11, url22,
"With UGI cache, two UGIs for the different token should not be same");
ugiProvider2.clearCache();
awaitCacheEmptyDueToExpiration();
ugi12 = ugiProvider1.ugi();
url22 = ugiProvider2.ugi();
String msg = "With cache eviction, two UGIs returned" +
" by the same token should not be same";
assertNotEquals(ugi11, ugi12, msg);
assertNotEquals(url21, url22, msg);
assertNotEquals(ugi11, url22,
"With UGI cache, two UGIs for the different token should not be same");
}
@Test
public void testUGICacheInSecure() throws Exception {
String uri1 = WebHdfsFileSystem.PATH_PREFIX
+ PATH
+ "?op=OPEN"
+ Param.toSortedString("&", new OffsetParam((long) OFFSET),
new LengthParam((long) LENGTH), new UserParam("root"));
String uri2 = WebHdfsFileSystem.PATH_PREFIX
+ PATH
+ "?op=OPEN"
+ Param.toSortedString("&", new OffsetParam((long) OFFSET),
new LengthParam((long) LENGTH), new UserParam("hdfs"));
DataNodeUGIProvider ugiProvider1 = new DataNodeUGIProvider(
new ParameterParser(new QueryStringDecoder(URI.create(uri1)), conf));
UserGroupInformation ugi11 = ugiProvider1.ugi();
UserGroupInformation ugi12 = ugiProvider1.ugi();
assertEquals(ugi11, ugi12,
"With UGI cache, two UGIs for the same user should be same");
DataNodeUGIProvider ugiProvider2 = new DataNodeUGIProvider(
new ParameterParser(new QueryStringDecoder(URI.create(uri2)), conf));
UserGroupInformation url21 = ugiProvider2.ugi();
UserGroupInformation url22 = ugiProvider2.ugi();
assertEquals(url21, url22,
"With UGI cache, two UGIs for the same user should be same");
assertNotEquals(ugi11, url22,
"With UGI cache, two UGIs for the different user should not be same");
awaitCacheEmptyDueToExpiration();
ugi12 = ugiProvider1.ugi();
url22 = ugiProvider2.ugi();
String msg = "With cache eviction, two UGIs returned by" +
" the same user should not be same";
assertNotEquals(ugi11, ugi12, msg);
assertNotEquals(url21, url22, msg);
assertNotEquals(ugi11, url22,
"With UGI cache, two UGIs for the different user should not be same");
}
@Test
public void testUGINullTokenSecure() throws IOException {
SecurityUtil.setAuthenticationMethod(KERBEROS, conf);
UserGroupInformation.setConfiguration(conf);
String uri1 = WebHdfsFileSystem.PATH_PREFIX
+ PATH
+ "?op=OPEN"
+ Param.toSortedString("&", new OffsetParam((long) OFFSET),
new LengthParam((long) LENGTH), new UserParam("root"));
ParameterParser params = new ParameterParser(
new QueryStringDecoder(URI.create(uri1)), conf);
DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params);
String usernameFromQuery = params.userName();
String doAsUserFromQuery = params.doAsUser();
String remoteUser = usernameFromQuery == null ? JspHelper
.getDefaultWebUserName(params.conf())
: usernameFromQuery;
DataNodeUGIProvider spiedUGIProvider = spy(ugiProvider);
spiedUGIProvider.ugi();
verify(spiedUGIProvider).nonTokenUGI(usernameFromQuery, doAsUserFromQuery,
remoteUser);
}
/**
* Wait for expiration of entries from the UGI cache. We need to be careful
* not to touch the entries in the cache while we're waiting for expiration.
* If we did, then that would reset the clock on expiration for those entries.
* Instead, we trigger internal clean-up of the cache and check for size 0.
*
* @throws Exception if there is any error
*/
private void awaitCacheEmptyDueToExpiration() throws Exception {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
DataNodeUGIProvider.ugiCache.cleanUp();
return DataNodeUGIProvider.ugiCache.size() == 0;
}
}, EXPIRE_AFTER_ACCESS, 10 * EXPIRE_AFTER_ACCESS);
}
private WebHdfsFileSystem getWebHdfsFileSystem(UserGroupInformation ugi,
Configuration conf, List<Token<DelegationTokenIdentifier>> tokens)
throws IOException {
if (UserGroupInformation.isSecurityEnabled()) {
DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(new Text(
ugi.getUserName()), null, null);
FSNamesystem namesystem = mock(FSNamesystem.class);
DelegationTokenSecretManager dtSecretManager = new DelegationTokenSecretManager(
86400000, 86400000, 86400000, 86400000, namesystem);
dtSecretManager.startThreads();
Token<DelegationTokenIdentifier> token1 = new Token<DelegationTokenIdentifier>(
dtId, dtSecretManager);
Token<DelegationTokenIdentifier> token2 = new Token<DelegationTokenIdentifier>(
dtId, dtSecretManager);
SecurityUtil.setTokenService(token1,
NetUtils.createSocketAddr(uri.getAuthority()));
SecurityUtil.setTokenService(token2,
NetUtils.createSocketAddr(uri.getAuthority()));
token1.setKind(WebHdfsConstants.WEBHDFS_TOKEN_KIND);
token2.setKind(WebHdfsConstants.WEBHDFS_TOKEN_KIND);
tokens.add(token1);
tokens.add(token2);
ugi.addToken(token1);
ugi.addToken(token2);
}
return (WebHdfsFileSystem) FileSystem.get(uri, conf);
}
}
| TestDataNodeUGIProvider |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17613/a/ChildA.java | {
"start": 418,
"end": 541
} | class ____<A extends Parent, B extends ChildB<A>> extends Parent {
@OneToMany
private Set<B> bs = new HashSet<>();
}
| ChildA |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/IgnoredPureGetterTest.java | {
"start": 6688,
"end": 7236
} | interface ____ {",
" LocalTimeBuilder setHour(int hour);",
" LocalTimeBuilder setMinute(int minute);",
" LocalTimeBuilder setSecond(int second);",
" LocalTimeBuilder setNanoOfSecond(int nanoOfSecond);",
" int getHour();",
" int getMinute();",
" int getSecond();",
" int getNanoOfSecond();",
" LocalTime build();", // calls: LocalTime.of(...)
"}")
.addSourceLines(
"B.java",
" | LocalTimeBuilder |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java | {
"start": 10626,
"end": 11155
} | class ____ extends DelegatingTransactionAttribute {
private final String name;
public TestContextTransactionAttribute(
TransactionAttribute targetAttribute, TestContext testContext, boolean includeMethodName) {
super(targetAttribute);
String name = testContext.getTestClass().getName();
if (includeMethodName) {
name += "." + testContext.getTestMethod().getName();
}
this.name = name;
}
@Override
public @Nullable String getName() {
return this.name;
}
}
}
| TestContextTransactionAttribute |
java | quarkusio__quarkus | extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/customized/QuarkusStrategySelectorBuilder.java | {
"start": 3467,
"end": 5245
} | class ____ service used to (attempt to) resolve any un-registered
* strategy implementations.
*
* @return The selector.
*/
public static StrategySelector buildSelector(ClassLoaderService classLoaderService) {
final StrategySelectorImpl strategySelector = new StrategySelectorImpl(classLoaderService);
// build the baseline...
strategySelector.registerStrategyLazily(
Dialect.class,
new AggregatedDialectSelector(classLoaderService.loadJavaServices(DialectSelector.class)));
strategySelector.registerStrategyLazily(JtaPlatform.class, new DefaultJtaPlatformSelector());
addTransactionCoordinatorBuilders(strategySelector);
addSqmMultiTableInsertStrategies(strategySelector);
addSqmMultiTableMutationStrategies(strategySelector);
addImplicitNamingStrategies(strategySelector);
addColumnOrderingStrategies(strategySelector);
addCacheKeysFactories(strategySelector);
addJsonFormatMappers(strategySelector);
addXmlFormatMappers(strategySelector);
// Required to support well known extensions e.g. Envers
// TODO: should we introduce a new integrator SPI to limit these to extensions supported by Quarkus?
for (StrategyRegistrationProvider provider : classLoaderService.loadJavaServices(StrategyRegistrationProvider.class)) {
for (StrategyRegistration<?> discoveredStrategyRegistration : provider.getStrategyRegistrations()) {
applyFromStrategyRegistration(strategySelector, discoveredStrategyRegistration);
}
}
return strategySelector;
}
/**
* Builds the selector for runtime use.
*
* @param classLoaderService The | loading |
java | apache__camel | components/camel-bonita/src/main/java/org/apache/camel/component/bonita/api/BonitaAPIBuilder.java | {
"start": 1181,
"end": 1844
} | class ____ {
protected BonitaAPIBuilder() {
}
public static BonitaAPI build(BonitaAPIConfig bonitaAPIConfig) {
if (bonitaAPIConfig == null) {
throw new IllegalArgumentException("bonitaApiConfig is null");
}
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
clientBuilder.register(JacksonJsonProvider.class);
Client client = clientBuilder.build();
client.register(new BonitaAuthFilter(bonitaAPIConfig));
WebTarget webTarget = client.target(bonitaAPIConfig.getBaseBonitaURI()).path("/API/bpm");
return new BonitaAPI(bonitaAPIConfig, webTarget);
}
}
| BonitaAPIBuilder |
java | apache__camel | archetypes/camel-archetype-main/src/main/resources/archetype-resources/src/main/java/MyApplication.java | {
"start": 1067,
"end": 1216
} | class ____ {
private MyApplication() {
}
public static void main(String[] args) throws Exception {
// use Camels Main | MyApplication |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/ITestBlobTypeSpeedDifference.java | {
"start": 1350,
"end": 2342
} | class ____ extends AbstractWasbTestBase {
@Override
protected AzureBlobStorageTestAccount createTestAccount() throws Exception {
return AzureBlobStorageTestAccount.create();
}
/**
* Writes data to the given stream of the given size, flushing every
* x bytes.
*/
private static void writeTestFile(OutputStream writeStream,
long size, long flushInterval) throws IOException {
int bufferSize = (int) Math.min(1000, flushInterval);
byte[] buffer = new byte[bufferSize];
Arrays.fill(buffer, (byte) 7);
int bytesWritten = 0;
int bytesUnflushed = 0;
while (bytesWritten < size) {
int numberToWrite = (int) Math.min(bufferSize, size - bytesWritten);
writeStream.write(buffer, 0, numberToWrite);
bytesWritten += numberToWrite;
bytesUnflushed += numberToWrite;
if (bytesUnflushed >= flushInterval) {
writeStream.flush();
bytesUnflushed = 0;
}
}
}
private static | ITestBlobTypeSpeedDifference |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/SortedMapType.java | {
"start": 489,
"end": 1420
} | class ____ extends MapType {
private final Comparator<?> comparator;
public SortedMapType(String role, String propertyRef, Comparator<?> comparator) {
super( role, propertyRef );
this.comparator = comparator;
}
@Override
public CollectionClassification getCollectionClassification() {
return CollectionClassification.SORTED_MAP;
}
public Class<?> getReturnedClass() {
return java.util.SortedMap.class;
}
@Override
public PersistentCollection<?> instantiate(SharedSessionContractImplementor session, CollectionPersister persister, Object key) {
return new PersistentSortedMap<>( session, comparator );
}
public Object instantiate(int anticipatedSize) {
return new TreeMap<>(comparator);
}
@Override
public PersistentCollection<?> wrap(SharedSessionContractImplementor session, Object collection) {
return new PersistentSortedMap<>( session, (java.util.SortedMap<?,?>) collection );
}
}
| SortedMapType |
java | dropwizard__dropwizard | dropwizard-core/src/main/java/io/dropwizard/core/Configuration.java | {
"start": 1834,
"end": 4856
} | class ____ {
@Valid
@NotNull
private ServerFactory server = new DefaultServerFactory();
@Valid
@Nullable
private LoggingFactory logging;
@Valid
@NotNull
private MetricsFactory metrics = new MetricsFactory();
@Valid
@NotNull
private AdminFactory admin = new AdminFactory();
@Valid
@Nullable
private HealthFactory health;
/**
* Returns the server-specific section of the configuration file.
*
* @return server-specific configuration parameters
*/
@JsonProperty("server")
public ServerFactory getServerFactory() {
return server;
}
/**
* Sets the HTTP-specific section of the configuration file.
*/
@JsonProperty("server")
public void setServerFactory(ServerFactory factory) {
this.server = factory;
}
/**
* Returns the logging-specific section of the configuration file.
*
* @return logging-specific configuration parameters
*/
@JsonProperty("logging")
public synchronized LoggingFactory getLoggingFactory() {
if (logging == null) {
// Lazy init to avoid a hard dependency to logback
logging = new DefaultLoggingFactory();
}
return logging;
}
/**
* Sets the logging-specific section of the configuration file.
*/
@JsonProperty("logging")
public synchronized void setLoggingFactory(LoggingFactory factory) {
this.logging = factory;
}
@JsonProperty("metrics")
public MetricsFactory getMetricsFactory() {
return metrics;
}
@JsonProperty("metrics")
public void setMetricsFactory(MetricsFactory metrics) {
this.metrics = metrics;
}
/**
* Returns the admin interface-specific section of the configuration file.
*
* @return admin interface-specific configuration parameters
* @since 2.0
*/
@JsonProperty("admin")
public AdminFactory getAdminFactory() {
return admin;
}
/**
* Sets the admin interface-specific section of the configuration file.
*
* @since 2.0
*/
@JsonProperty("admin")
public void setAdminFactory(AdminFactory admin) {
this.admin = admin;
}
/**
* Returns the health interface-specific section of the configuration file.
*
* @return health interface-specific configuration parameters
* @since 2.1
*/
@JsonProperty("health")
public Optional<HealthFactory> getHealthFactory() {
return Optional.ofNullable(health);
}
/**
* Sets the health interface-specific section of the configuration file.
*
* @since 2.1
*/
@JsonProperty("health")
public void setHealthFactory(HealthFactory health) {
this.health = health;
}
@Override
public String toString() {
return "Configuration{server=" + server + ", logging=" + logging + ", metrics=" + metrics + ", admin=" + admin + ", health=" + health + "}";
}
}
| Configuration |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/crypto/TestHdfsCryptoStreams.java | {
"start": 1589,
"end": 3021
} | class ____ extends CryptoStreamsTestBase {
private static MiniDFSCluster dfsCluster;
private static FileSystem fs;
private static int pathCount = 0;
private static Path path;
private static Path file;
@BeforeAll
public static void init() throws Exception {
Configuration conf = new HdfsConfiguration();
dfsCluster = new MiniDFSCluster.Builder(conf).build();
dfsCluster.waitClusterUp();
fs = dfsCluster.getFileSystem();
codec = CryptoCodec.getInstance(conf);
}
@AfterAll
public static void shutdown() throws Exception {
if (dfsCluster != null) {
dfsCluster.shutdown();
}
}
@BeforeEach
@Override
public void setUp() throws IOException {
++pathCount;
path = new Path("/p" + pathCount);
file = new Path(path, "file");
FileSystem.mkdirs(fs, path, FsPermission.createImmutable((short) 0700));
super.setUp();
}
@AfterEach
public void cleanUp() throws IOException {
fs.delete(path, true);
}
@Override
protected OutputStream getOutputStream(int bufferSize, byte[] key, byte[] iv)
throws IOException {
return new CryptoFSDataOutputStream(fs.create(file), codec, bufferSize,
key, iv);
}
@Override
protected InputStream getInputStream(int bufferSize, byte[] key, byte[] iv)
throws IOException {
return new CryptoFSDataInputStream(fs.open(file), codec, bufferSize, key,
iv);
}
}
| TestHdfsCryptoStreams |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/collection_injection/immutable/ImmutableDefect.java | {
"start": 726,
"end": 1130
} | class ____ {
private final int id;
private final String defect;
public ImmutableDefect(int id, String defect) {
this.id = id;
this.defect = defect;
}
public int getId() {
return id;
}
public String getDefect() {
return defect;
}
@Override
public String toString() {
return "ImmutableDefect{" + "id=" + id + ", defect='" + defect + '\'' + '}';
}
}
| ImmutableDefect |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServer.java | {
"start": 2977,
"end": 3237
} | class ____ extends HttpServerFunctionalTest {
static final Logger LOG = LoggerFactory.getLogger(TestHttpServer.class);
private static HttpServer2 server;
private static final int MAX_THREADS = 10;
@SuppressWarnings("serial")
public static | TestHttpServer |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/mllib/JavaElementwiseProductExample.java | {
"start": 1221,
"end": 2239
} | class ____ {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaElementwiseProductExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
// $example on$
// Create some vector data; also works for sparse vectors
JavaRDD<Vector> data = jsc.parallelize(Arrays.asList(
Vectors.dense(1.0, 2.0, 3.0), Vectors.dense(4.0, 5.0, 6.0)));
Vector transformingVector = Vectors.dense(0.0, 1.0, 2.0);
ElementwiseProduct transformer = new ElementwiseProduct(transformingVector);
// Batch transform and per-row transform give the same results:
JavaRDD<Vector> transformedData = transformer.transform(data);
JavaRDD<Vector> transformedData2 = data.map(transformer::transform);
// $example off$
System.out.println("transformedData: ");
transformedData.foreach(System.out::println);
System.out.println("transformedData2: ");
transformedData2.foreach(System.out::println);
jsc.stop();
}
}
| JavaElementwiseProductExample |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/converters/ConverterTest.java | {
"start": 2115,
"end": 2535
} | class ____ implements MessageConverter {
@Override
public boolean canConvert(Message<?> in, Type target) {
return target.equals(Person.class) && in.getPayload().getClass().equals(String.class);
}
@Override
public Message<?> convert(Message<?> in, Type target) {
return in.withPayload(new Person((String) in.getPayload()));
}
}
}
| MyPersonConverter |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerBuilder.java | {
"start": 1311,
"end": 5495
} | class ____ {
// Id format for FileMergingSnapshotManager, consist with jobId and tmId
private static final String ID_FORMAT = "job_%s_tm_%s";
private final JobID jobId;
private final ResourceID tmResourceId;
/** The file merging type. */
private final FileMergingType fileMergingType;
/** Max size for a file. */
private long maxFileSize = 32 * 1024 * 1024;
/** Type of physical file pool. */
private PhysicalFilePool.Type filePoolType = PhysicalFilePool.Type.NON_BLOCKING;
/** The max space amplification that the manager should control. */
private float maxSpaceAmplification = Float.MAX_VALUE;
@Nullable private Executor ioExecutor = null;
@Nullable private TaskManagerJobMetricGroup metricGroup;
/**
* Initialize the builder.
*
* @param id the id of the manager.
*/
public FileMergingSnapshotManagerBuilder(
JobID jobId, ResourceID tmResourceId, FileMergingType type) {
this.jobId = jobId;
this.tmResourceId = tmResourceId;
this.fileMergingType = type;
}
/** Set the max file size. */
public FileMergingSnapshotManagerBuilder setMaxFileSize(long maxFileSize) {
Preconditions.checkArgument(maxFileSize > 0);
this.maxFileSize = maxFileSize;
return this;
}
/** Set the type of physical file pool. */
public FileMergingSnapshotManagerBuilder setFilePoolType(PhysicalFilePool.Type filePoolType) {
this.filePoolType = filePoolType;
return this;
}
public FileMergingSnapshotManagerBuilder setMaxSpaceAmplification(float amplification) {
if (amplification < 1) {
// only valid number counts. If not valid, disable space control by setting this to
// Float.MAX_VALUE.
this.maxSpaceAmplification = Float.MAX_VALUE;
} else {
this.maxSpaceAmplification = amplification;
}
return this;
}
/**
* Set the executor for io operation in manager. If null(default), all io operation will be
* executed synchronously.
*/
public FileMergingSnapshotManagerBuilder setIOExecutor(@Nullable Executor ioExecutor) {
this.ioExecutor = ioExecutor;
return this;
}
public FileMergingSnapshotManagerBuilder setMetricGroup(TaskManagerJobMetricGroup metricGroup) {
this.metricGroup = metricGroup;
return this;
}
/**
* Create file-merging snapshot manager based on configuration.
*
* @return the created manager.
*/
public FileMergingSnapshotManager build() {
switch (fileMergingType) {
case MERGE_WITHIN_CHECKPOINT:
return new WithinCheckpointFileMergingSnapshotManager(
String.format(ID_FORMAT, jobId, tmResourceId),
maxFileSize,
filePoolType,
maxSpaceAmplification,
ioExecutor == null ? Runnable::run : ioExecutor,
metricGroup == null
? new UnregisteredMetricGroups
.UnregisteredTaskManagerJobMetricGroup()
: metricGroup);
case MERGE_ACROSS_CHECKPOINT:
return new AcrossCheckpointFileMergingSnapshotManager(
String.format(ID_FORMAT, jobId, tmResourceId),
maxFileSize,
filePoolType,
maxSpaceAmplification,
ioExecutor == null ? Runnable::run : ioExecutor,
metricGroup == null
? new UnregisteredMetricGroups
.UnregisteredTaskManagerJobMetricGroup()
: metricGroup);
default:
throw new UnsupportedOperationException(
String.format(
"Unsupported type %s when creating file merging manager",
fileMergingType));
}
}
}
| FileMergingSnapshotManagerBuilder |
java | netty__netty | transport/src/main/java/io/netty/channel/embedded/EmbeddedSocketAddress.java | {
"start": 710,
"end": 914
} | class ____ extends SocketAddress {
private static final long serialVersionUID = 1400788804624980619L;
@Override
public String toString() {
return "embedded";
}
}
| EmbeddedSocketAddress |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/read/ParserScopeMatchingTest.java | {
"start": 419,
"end": 6994
} | class ____ extends JacksonCoreTestBase
{
@Test
void unclosedArray() throws Exception
{
for (int mode : ALL_MODES) {
_testUnclosedArray(mode);
}
}
public void _testUnclosedArray(int mode)
{
try (JsonParser p = createParser(mode, "[ 1, 2 ")) {
assertToken(JsonToken.START_ARRAY, p.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(2, p.getIntValue());
try {
p.nextToken();
fail("Expected an exception for unclosed ARRAY (mode: " + mode + ")");
} catch (StreamReadException pe) {
verifyException(pe, "expected close marker for ARRAY");
}
}
}
@Test
void unclosedObject() throws Exception
{
for (int mode : ALL_MODES) {
_testUnclosedObject(mode);
}
}
private void _testUnclosedObject(int mode)
{
try (JsonParser p = createParser(mode, "{ \"key\" : 3 ")) {
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
try {
p.nextToken();
fail("Expected an exception for unclosed OBJECT (mode: " + mode + ")");
} catch (StreamReadException e) {
verifyException(e, "expected close marker for OBJECT");
}
}
}
@Test
void eofInName() throws Exception
{
for (int mode : ALL_MODES) {
_testEOFInName(mode);
}
}
public void _testEOFInName(int mode)
{
final String JSON = "{ \"abcd";
try (JsonParser p = createParser(mode, JSON)) {
assertToken(JsonToken.START_OBJECT, p.nextToken());
try {
p.nextToken();
fail("Expected an exception for EOF");
} catch (StreamReadException pe) {
verifyException(pe, "Unexpected end-of-input");
} catch (JacksonException ie) {
// DataInput behaves bit differently
if (mode == MODE_DATA_INPUT) {
verifyException(ie, "end-of-input");
return;
}
fail("Should not end up in here");
}
}
}
@Test
void weirdToken() throws Exception
{
for (int mode : ALL_MODES) {
_testWeirdToken(mode);
}
}
private void _testWeirdToken(int mode)
{
final String JSON = "[ nil ]";
JsonParser p = createParser(mode, JSON);
assertToken(JsonToken.START_ARRAY, p.nextToken());
try {
p.nextToken();
fail("Expected an exception for weird token");
} catch (StreamReadException pe) {
verifyException(pe, "Unrecognized token");
}
p.close();
}
@Test
void mismatchArrayToObject() throws Exception
{
for (int mode : ALL_MODES) {
_testMismatchArrayToObject(mode);
}
}
private void _testMismatchArrayToObject(int mode)
{
final String JSON = "[ 1, 2 }";
JsonParser p = createParser(mode, JSON);
assertToken(JsonToken.START_ARRAY, p.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
try {
p.nextToken();
fail("Expected an exception for incorrectly closed ARRAY");
} catch (StreamReadException pe) {
verifyException(pe, "Unexpected close marker '}': expected ']'");
}
p.close();
}
@Test
void mismatchObjectToArray() throws Exception
{
for (int mode : ALL_MODES) {
_testMismatchObjectToArray(mode);
}
}
private void _testMismatchObjectToArray(int mode)
{
final String JSON = "{ ]";
JsonParser p = createParser(mode, JSON);
assertToken(JsonToken.START_OBJECT, p.nextToken());
try {
p.nextToken();
fail("Expected an exception for incorrectly closed OBJECT");
} catch (StreamReadException pe) {
verifyException(pe, "Unexpected close marker ']': expected '}'");
}
p.close();
}
@Test
void misssingColon() throws Exception
{
for (int mode : ALL_MODES) {
_testMisssingColon(mode);
}
}
private void _testMisssingColon(int mode)
{
final String JSON = "{ \"a\" \"b\" }";
JsonParser p = createParser(mode, JSON);
assertToken(JsonToken.START_OBJECT, p.nextToken());
try {
// can be either here, or with next one...
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
p.nextToken();
fail("Expected an exception for missing semicolon");
} catch (StreamReadException pe) {
verifyException(pe, "was expecting a colon");
}
p.close();
}
// [core#1394]
@Test
void extraEndArray() throws Exception
{
for (int mode : ALL_MODES) {
_extraEndArray(mode);
}
}
public void _extraEndArray(int mode) throws Exception
{
try (JsonParser p = createParser(mode, "{ }]")) {
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.END_OBJECT, p.nextToken());
try {
p.nextToken();
fail("Should have thrown an exception");
} catch (StreamReadException e) {
verifyException(e, "Unexpected close marker ']': no open Array");
}
}
}
// [core#1394]
@Test
void extraEndObject() throws Exception
{
for (int mode : ALL_MODES) {
_extraEndObject(mode);
}
}
public void _extraEndObject(int mode) throws Exception
{
try (JsonParser p = createParser(mode, "[ ]}")) {
assertToken(JsonToken.START_ARRAY, p.nextToken());
assertToken(JsonToken.END_ARRAY, p.nextToken());
try {
p.nextToken();
fail("Should have thrown an exception");
} catch (StreamReadException e) {
verifyException(e, "Unexpected close marker '}': no open Object");
}
}
}
}
| ParserScopeMatchingTest |
java | junit-team__junit5 | junit-vintage-engine/src/main/java/org/junit/vintage/engine/descriptor/RunnerRequest.java | {
"start": 450,
"end": 642
} | class ____ extends Request {
private final Runner runner;
RunnerRequest(Runner runner) {
this.runner = runner;
}
@Override
public Runner getRunner() {
return runner;
}
}
| RunnerRequest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/impl/StateStoreZooKeeperImpl.java | {
"start": 2932,
"end": 7127
} | class ____ extends StateStoreSerializableImpl {
private static final Logger LOG =
LoggerFactory.getLogger(StateStoreZooKeeperImpl.class);
/** Service to get/update zk state. */
private ThreadPoolExecutor executorService;
private boolean enableConcurrent;
/** Directory to store the state store data. */
private String baseZNode;
/** Interface to ZooKeeper. */
private ZKCuratorManager zkManager;
/** ACLs for ZooKeeper. */
private List<ACL> zkAcl;
@Override
public boolean initDriver() {
LOG.info("Initializing ZooKeeper connection");
Configuration conf = getConf();
baseZNode = conf.get(
RBFConfigKeys.FEDERATION_STORE_ZK_PARENT_PATH,
RBFConfigKeys.FEDERATION_STORE_ZK_PARENT_PATH_DEFAULT);
int numThreads = conf.getInt(
RBFConfigKeys.FEDERATION_STORE_ZK_ASYNC_MAX_THREADS,
RBFConfigKeys.FEDERATION_STORE_ZK_ASYNC_MAX_THREADS_DEFAULT);
enableConcurrent = numThreads > 0;
if (enableConcurrent) {
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("StateStore ZK Client-%d")
.build();
this.executorService = new ThreadPoolExecutor(numThreads, numThreads,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), threadFactory);
LOG.info("Init StateStoreZookeeperImpl by async mode with {} threads.", numThreads);
} else {
LOG.info("Init StateStoreZookeeperImpl by sync mode.");
}
String zkHostPort = conf.get(RBFConfigKeys.FEDERATION_STORE_ZK_ADDRESS);
try {
this.zkManager = new ZKCuratorManager(conf);
this.zkManager.start(zkHostPort);
this.zkAcl = ZKCuratorManager.getZKAcls(conf);
} catch (IOException e) {
LOG.error("Cannot initialize the ZK connection", e);
return false;
}
return true;
}
@Override
public <T extends BaseRecord> boolean initRecordStorage(
String className, Class<T> clazz) {
try {
String checkPath = getNodePath(baseZNode, className);
zkManager.createRootDirRecursively(checkPath, zkAcl);
return true;
} catch (Exception e) {
LOG.error("Cannot initialize ZK node for {}: {}",
className, e.getMessage());
return false;
}
}
@VisibleForTesting
public void setEnableConcurrent(boolean enableConcurrent) {
this.enableConcurrent = enableConcurrent;
}
@Override
public void close() throws Exception {
super.close();
if (executorService != null) {
executorService.shutdown();
}
if (zkManager != null) {
zkManager.close();
}
}
@Override
public boolean isDriverReady() {
if (zkManager == null) {
return false;
}
CuratorFramework curator = zkManager.getCurator();
if (curator == null) {
return false;
}
return curator.getState() == CuratorFrameworkState.STARTED;
}
@Override
public <T extends BaseRecord> QueryResult<T> get(Class<T> clazz)
throws IOException {
verifyDriverReady();
long start = monotonicNow();
List<T> ret = new ArrayList<>();
String znode = getZNodeForClass(clazz);
try {
List<Callable<T>> callables = new ArrayList<>();
zkManager.getChildren(znode).forEach(c -> callables.add(() -> getRecord(clazz, znode, c)));
if (enableConcurrent) {
List<Future<T>> futures = executorService.invokeAll(callables);
for (Future<T> future : futures) {
if (future.get() != null) {
ret.add(future.get());
}
}
} else {
for (Callable<T> callable : callables) {
T record = callable.call();
if (record != null) {
ret.add(record);
}
}
}
} catch (Exception e) {
getMetrics().addFailure(monotonicNow() - start);
String msg = "Cannot get children for \"" + znode + "\": " +
e.getMessage();
LOG.error(msg);
throw new IOException(msg);
}
long end = monotonicNow();
getMetrics().addRead(end - start);
return new QueryResult<T>(ret, getTime());
}
/**
* Get one data record in the StateStore or delete it if it's corrupted.
*
* @param clazz Record | StateStoreZooKeeperImpl |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/function/support/HandlerFunctionAdapter.java | {
"start": 1884,
"end": 6268
} | class ____ implements HandlerAdapter, Ordered {
private static final Log logger = LogFactory.getLog(HandlerFunctionAdapter.class);
private int order = Ordered.LOWEST_PRECEDENCE;
private @Nullable Long asyncRequestTimeout;
/**
* Specify the order value for this HandlerAdapter bean.
* <p>The default value is {@code Ordered.LOWEST_PRECEDENCE}, meaning non-ordered.
* @see org.springframework.core.Ordered#getOrder()
*/
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
/**
* Specify the amount of time, in milliseconds, before concurrent handling
* should time out. In Servlet 3, the timeout begins after the main request
* processing thread has exited and ends when the request is dispatched again
* for further processing of the concurrently produced result.
* <p>If this value is not set, the default timeout of the underlying
* implementation is used.
* <p>A value of 0 or less indicates that the asynchronous operation will never
* time out.
* @param timeout the timeout value in milliseconds
*/
public void setAsyncRequestTimeout(long timeout) {
this.asyncRequestTimeout = timeout;
}
@Override
public boolean supports(Object handler) {
return handler instanceof HandlerFunction;
}
@Override
public @Nullable ModelAndView handle(HttpServletRequest servletRequest,
HttpServletResponse servletResponse,
Object handler) throws Exception {
WebAsyncManager asyncManager = getWebAsyncManager(servletRequest, servletResponse);
servletResponse = getWrappedResponse(asyncManager);
ServerRequest serverRequest = getServerRequest(servletRequest);
ServerResponse serverResponse;
if (asyncManager.hasConcurrentResult()) {
serverResponse = handleAsync(asyncManager);
}
else {
HandlerFunction<?> handlerFunction = (HandlerFunction<?>) handler;
serverResponse = handlerFunction.handle(serverRequest);
}
if (serverResponse != null) {
return serverResponse.writeTo(servletRequest, servletResponse, new ServerRequestContext(serverRequest));
}
else {
return null;
}
}
private WebAsyncManager getWebAsyncManager(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(servletRequest, servletResponse);
asyncWebRequest.setTimeout(this.asyncRequestTimeout);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(servletRequest);
asyncManager.setAsyncWebRequest(asyncWebRequest);
return asyncManager;
}
/**
* Obtain response wrapped by
* {@link org.springframework.web.context.request.async.StandardServletAsyncWebRequest}
* to enforce lifecycle rules from Servlet spec (section 2.3.3.4)
* in case of async handling.
*/
private static HttpServletResponse getWrappedResponse(WebAsyncManager asyncManager) {
AsyncWebRequest asyncRequest = asyncManager.getAsyncWebRequest();
Assert.notNull(asyncRequest, "No AsyncWebRequest");
HttpServletResponse servletResponse = asyncRequest.getNativeResponse(HttpServletResponse.class);
Assert.notNull(servletResponse, "No HttpServletResponse");
return servletResponse;
}
private ServerRequest getServerRequest(HttpServletRequest servletRequest) {
ServerRequest serverRequest =
(ServerRequest) servletRequest.getAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
Assert.state(serverRequest != null, () -> "Required attribute '" +
RouterFunctions.REQUEST_ATTRIBUTE + "' is missing");
return serverRequest;
}
private @Nullable ServerResponse handleAsync(WebAsyncManager asyncManager) throws Exception {
Object result = asyncManager.getConcurrentResult();
asyncManager.clearConcurrentResult();
LogFormatUtils.traceDebug(logger, traceOn -> {
String formatted = LogFormatUtils.formatValue(result, !traceOn);
return "Resume with async result [" + formatted + "]";
});
if (result instanceof ServerResponse response) {
return response;
}
else if (result instanceof Exception exception) {
throw exception;
}
else if (result instanceof Throwable throwable) {
throw new ServletException("Async processing failed", throwable);
}
else if (result == null) {
return null;
}
else {
throw new IllegalArgumentException("Unknown result from WebAsyncManager: [" + result + "]");
}
}
private static | HandlerFunctionAdapter |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/columnar/vector/heap/HeapByteVector.java | {
"start": 1023,
"end": 1091
} | class ____ a nullable byte column vector. */
@Internal
public | represents |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/convert/ConvertingSerializerTest.java | {
"start": 788,
"end": 939
} | class ____
{
public int x, y;
public Point(int v1, int v2) {
x = v1;
y = v2;
}
}
static | Point |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/descriptors/DescriptorProperties.java | {
"start": 17003,
"end": 18698
} | class ____ under the given key if it exists. */
@SuppressWarnings("unchecked")
public <T> Optional<Class<T>> getOptionalClass(String key, Class<T> superClass) {
return optionalGet(key)
.map(
(name) -> {
final Class<?> clazz;
try {
clazz =
Class.forName(
name,
true,
Thread.currentThread().getContextClassLoader());
if (!superClass.isAssignableFrom(clazz)) {
throw new ValidationException(
"Class '"
+ name
+ "' does not extend from the required class '"
+ superClass.getName()
+ "' for key '"
+ key
+ "'.");
}
return (Class<T>) clazz;
} catch (Exception e) {
throw new ValidationException(
"Could not get class '" + name + "' for key '" + key + "'.",
e);
}
});
}
/** Returns a | value |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTestBeanTests.java | {
"start": 1958,
"end": 2177
} | class ____ {
private final ImmutableProperties properties;
SomeConfiguration(ImmutableProperties properties) {
this.properties = properties;
}
}
@ConfigurationProperties("immutable")
static | SomeConfiguration |
java | micronaut-projects__micronaut-core | http-netty/src/main/java/io/micronaut/http/netty/SslContextAutoLoader.java | {
"start": 1683,
"end": 8924
} | class ____ {
private final Logger log;
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
@Nullable
private SslContextHolder current;
private Disposable refreshSslDisposable;
private long generation;
/**
* Create a new auto-loader.
*
* @param log logger used to report initialization failures
*/
protected SslContextAutoLoader(Logger log) {
this.log = log;
}
private void replace(@Nullable SslContextHolder holder, long gen) {
rwLock.writeLock().lock();
try {
if (gen < this.generation) {
if (holder != null) {
holder.release();
}
return;
}
assert gen == this.generation;
if (current != null) {
current.release();
}
current = holder;
} finally {
rwLock.writeLock().unlock();
}
}
/**
* Obtain the current SSL context holder and retain the underlying Netty contexts.
*
* @return the retained holder, or {@code null} if no context is currently available
*/
@Nullable
public final SslContextHolder takeRetained() {
rwLock.readLock().lock();
try {
if (current != null) {
current.retain();
}
return current;
} finally {
rwLock.readLock().unlock();
}
}
/**
* Stop watching for updates and release the current SSL context holder.
* Safe to call multiple times.
*/
public final void clear() {
Disposable d;
rwLock.writeLock().lock();
try {
d = refreshSslDisposable;
refreshSslDisposable = null;
if (current != null) {
current.release();
current = null;
}
generation++;
} finally {
rwLock.writeLock().unlock();
}
if (d != null) {
d.dispose();
}
}
/**
* Access to named {@link CertificateProvider} beans used to resolve key/trust material.
*
* @return a provider of {@link CertificateProvider} beans
*/
protected abstract @NonNull BeanProvider<CertificateProvider> certificateProviders();
/**
* The SSL configuration used to derive defaults like protocols, ciphers and client auth.
*
* @return the SSL configuration
*/
protected abstract @NonNull SslConfiguration sslConfiguration();
/**
* Whether the target transport is QUIC/HTTP3 (true) or TCP (false).
*
* @return {@code true} for QUIC, {@code false} for TCP
*/
protected abstract boolean quic();
/**
* Create the legacy SSL context holder when no certificate providers are configured.
* Implementations should read from legacy configuration and build fixed contexts.
*
* @return a holder for legacy contexts
*/
protected abstract @NonNull SslContextHolder createLegacy();
/**
* Start auto-loading using names from {@link SslConfiguration}
* ({@link SslConfiguration#getKeyName()} and {@link SslConfiguration#getTrustName()}).
*/
public final void autoLoad() {
autoLoad(sslConfiguration().getKeyName(), sslConfiguration().getTrustName());
}
/**
* Start auto-loading using the given provider names.
*
* @param keyName optional name of the {@link CertificateProvider} for the key store
* @param trustName optional name of the {@link CertificateProvider} for the trust store
*/
public final void autoLoad(@Nullable String keyName, @Nullable String trustName) {
long gen;
Disposable d;
rwLock.writeLock().lock();
try {
gen = ++generation;
d = refreshSslDisposable;
refreshSslDisposable = null;
} finally {
rwLock.writeLock().unlock();
}
if (d != null) {
d.dispose();
}
Disposable nextDisposable;
if (keyName == null && trustName == null) {
// legacy code path
replace(createLegacy(), gen);
nextDisposable = null;
} else if (keyName != null && trustName != null) {
CertificateProvider keyProvider = certificateProviders().get(Qualifiers.byName(keyName));
CertificateProvider trustProvider = certificateProviders().get(Qualifiers.byName(trustName));
nextDisposable = Flux.combineLatest(keyProvider.getKeyStore(), trustProvider.getTrustStore(), Tuples::of)
.subscribe(tuple -> refreshSsl(tuple.getT1(), tuple.getT2(), gen));
} else if (keyName != null) {
CertificateProvider keyProvider = certificateProviders().get(Qualifiers.byName(keyName));
nextDisposable = Flux.from(keyProvider.getKeyStore())
.subscribe(ks -> refreshSsl(ks, null, gen));
} else {
CertificateProvider trustProvider = certificateProviders().get(Qualifiers.byName(trustName));
nextDisposable = Flux.from(trustProvider.getTrustStore())
.subscribe(ts -> refreshSsl(null, ts, gen));
}
if (nextDisposable != null) {
rwLock.writeLock().lock();
try {
if (generation == gen) {
refreshSslDisposable = nextDisposable;
} else {
nextDisposable.dispose();
}
} finally {
rwLock.writeLock().unlock();
}
}
}
/**
* Create a new {@link NettySslContextBuilder} in server or client mode depending on the subclass.
*
* @return the builder to construct Netty SSL contexts
*/
protected abstract @NonNull NettySslContextBuilder builder();
/**
* Build fresh SSL contexts from the supplied key/trust stores and swap the active holder.
*
* @param ks the key store, or {@code null}
* @param ts the trust store, or {@code null}
* @param gen generation stamp ensuring only the latest update wins
*/
private void refreshSsl(@Nullable KeyStore ks, @Nullable KeyStore ts, long gen) {
try {
NettySslContextBuilder builder = builder()
.openssl(NettyTlsUtils.useOpenssl(sslConfiguration()))
.keyStore(ks)
.keyPassword(sslConfiguration().getKey().getPassword()
.or(() -> sslConfiguration().getKeyStore().getPassword())
.orElse(null))
.trustStore(ts)
.clientAuthentication(sslConfiguration().getClientAuthentication().orElse(null))
.ciphers(sslConfiguration().getCiphers().map(List::of).orElse(null), false)
.protocols(sslConfiguration().getProtocols().map(List::of).orElse(null));
replace(quic() ?
new SslContextHolder(null, builder.buildHttp3()) :
new SslContextHolder(builder.buildTcp(), null),
gen);
} catch (Exception e) {
log.warn("Failed to initialize SSL context", e);
}
}
}
| SslContextAutoLoader |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_1552/Target.java | {
"start": 232,
"end": 591
} | class ____ {
private Inner first;
private Inner second;
public Inner getFirst() {
return first;
}
public void setFirst(Inner first) {
this.first = first;
}
public Inner getSecond() {
return second;
}
public void setSecond(Inner second) {
this.second = second;
}
public static | Target |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.