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__guava | android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java | {
"start": 21600,
"end": 21884
} | class ____ {
@Keep public static final WithPublicConstants FIRST = new WithPublicConstants();
// To test that we pick the first constant alphabetically
@Keep public static final WithPublicConstants SECOND = new WithPublicConstants();
}
private static | WithPublicConstants |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/OpenSslNpnApplicationProtocolNegotiator.java | {
"start": 968,
"end": 2046
} | class ____ implements OpenSslApplicationProtocolNegotiator {
private final List<String> protocols;
public OpenSslNpnApplicationProtocolNegotiator(Iterable<String> protocols) {
this.protocols = checkNotNull(toList(protocols), "protocols");
}
public OpenSslNpnApplicationProtocolNegotiator(String... protocols) {
this.protocols = checkNotNull(toList(protocols), "protocols");
}
@Override
public ApplicationProtocolConfig.Protocol protocol() {
return ApplicationProtocolConfig.Protocol.NPN;
}
@Override
public List<String> protocols() {
return protocols;
}
@Override
public ApplicationProtocolConfig.SelectorFailureBehavior selectorFailureBehavior() {
return ApplicationProtocolConfig.SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL;
}
@Override
public ApplicationProtocolConfig.SelectedListenerFailureBehavior selectedListenerFailureBehavior() {
return ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT;
}
}
| OpenSslNpnApplicationProtocolNegotiator |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/aggregations/bucket/sampler/random/RandomSamplerAggregationBuilderTests.java | {
"start": 683,
"end": 1402
} | class ____ extends BaseAggregationTestCase<RandomSamplerAggregationBuilder> {
@Override
protected RandomSamplerAggregationBuilder createTestAggregatorBuilder() {
RandomSamplerAggregationBuilder builder = new RandomSamplerAggregationBuilder(randomAlphaOfLength(10));
if (randomBoolean()) {
builder.setSeed(randomInt());
}
if (randomBoolean()) {
builder.setShardSeed(randomInt());
}
builder.setProbability(randomFrom(1.0, randomDoubleBetween(0.0, 0.5, false)));
builder.subAggregation(AggregationBuilders.max(randomAlphaOfLength(10)).field(randomAlphaOfLength(10)));
return builder;
}
}
| RandomSamplerAggregationBuilderTests |
java | alibaba__druid | druid-wrapper/src/main/java/org/logicalcobwebs/proxool/ProxoolConstants.java | {
"start": 8586,
"end": 8886
} | interface ____
Revision 1.20 2004/03/15 02:43:47 chr32
Removed explicit JNDI properties. Going for a generic approach instead.
Added constant for JNDI properties prefix.
Revision 1.19 2003/09/30 18:39:08 billhorsman
New test-before-use, test-after-use and fatal-sql-exception-wrapper- | constants |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/resource/beans/internal/BeansMessageLogger.java | {
"start": 1046,
"end": 1642
} | interface ____ {
String LOGGER_NAME = SubSystemLogging.BASE + ".beans";
BeansMessageLogger BEANS_MSG_LOGGER = Logger.getMessageLogger( MethodHandles.lookup(), BeansMessageLogger.class, LOGGER_NAME );
@LogMessage( level = TRACE )
@Message(
id = 10005001,
value = "Creating ManagedBean [%s] using direct instantiation"
)
void creatingManagedBeanUsingDirectInstantiation(String beanName);
@LogMessage( level = INFO )
@Message(
id = 10005002,
value = "No explicit CDI BeanManager reference was passed to Hibernate, " +
"but CDI is available on the Hibernate | BeansMessageLogger |
java | quarkusio__quarkus | extensions/hibernate-search-orm-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/orm/elasticsearch/runtime/management/HibernateSearchPostRequestProcessor.java | {
"start": 745,
"end": 4945
} | class ____ {
private static final String QUERY_PARAM_WAIT_FOR = "wait_for";
private static final String QUERY_PARAM_PERSISTENCE_UNIT = "persistence_unit";
public void process(RoutingContext ctx) {
JsonObject config = ctx.body().asJsonObject();
if (config == null) {
config = new JsonObject();
}
try (InstanceHandle<SearchMapping> searchMappingInstanceHandle = searchMappingInstanceHandle(ctx.request())) {
SearchMapping searchMapping = searchMappingInstanceHandle.get();
JsonObject filter = config.getJsonObject("filter");
List<String> types = getTypesToFilter(filter);
Set<String> tenants = getTenants(filter);
MassIndexer massIndexer;
if (types == null || types.isEmpty()) {
massIndexer = createMassIndexer(searchMapping.scope(Object.class), tenants);
} else {
massIndexer = createMassIndexer(searchMapping.scope(Object.class, types), tenants);
}
HibernateSearchMassIndexerConfiguration.configure(massIndexer, config.getJsonObject("massIndexer"));
CompletionStage<?> massIndexerFuture = massIndexer.start();
if (WaitFor.STARTED.equals(getWaitForParameter(ctx.request()))) {
ctx.response().end(message(202, "Reindexing started"));
} else {
ctx.response()
.setChunked(true)
.write(message(202, "Reindexing started"),
ignored -> massIndexerFuture.whenComplete((ignored2, throwable) -> {
if (throwable == null) {
ctx.response().end(message(200, "Reindexing succeeded"));
} else {
ctx.response().end(message(
500,
"Reindexing failed:\n" + Arrays.stream(throwable.getStackTrace())
.map(Object::toString)
.collect(Collectors.joining("\n"))));
}
}));
}
}
}
private MassIndexer createMassIndexer(SearchScope<Object> scope, Set<String> tenants) {
if (tenants == null || tenants.isEmpty()) {
return scope.massIndexer();
} else {
return scope.massIndexer(tenants);
}
}
private List<String> getTypesToFilter(JsonObject filter) {
if (filter == null) {
return null;
}
JsonArray array = filter.getJsonArray("types");
if (array == null) {
return null;
}
List<String> types = array
.stream()
.map(Object::toString)
.collect(Collectors.toList());
return types.isEmpty() ? null : types;
}
private Set<String> getTenants(JsonObject filter) {
if (filter == null) {
return null;
}
JsonArray array = filter.getJsonArray("tenants");
if (array == null) {
return null;
}
Set<String> types = array
.stream()
.map(Object::toString)
.collect(Collectors.toSet());
return types.isEmpty() ? null : types;
}
private WaitFor getWaitForParameter(HttpServerRequest request) {
return WaitFor.valueOf(request.getParam(QUERY_PARAM_WAIT_FOR, WaitFor.STARTED.name()).toUpperCase(Locale.ROOT));
}
private InstanceHandle<SearchMapping> searchMappingInstanceHandle(HttpServerRequest request) {
String pu = request.getParam(QUERY_PARAM_PERSISTENCE_UNIT, PersistenceUnit.DEFAULT);
return Arc.container().instance(SearchMapping.class, new PersistenceUnit.PersistenceUnitLiteral(pu));
}
private static String message(int code, String message) {
return JsonObject.of("code", code, "message", message) + "\n";
}
private | HibernateSearchPostRequestProcessor |
java | apache__camel | components/camel-flink/src/main/java/org/apache/camel/component/flink/ConvertingDataSetCallback.java | {
"start": 1462,
"end": 2394
} | class ____<T> implements DataSetCallback<T> {
private final CamelContext camelContext;
private final Class<?>[] payloadTypes;
protected ConvertingDataSetCallback(CamelContext camelContext, Class<?>... payloadTypes) {
this.camelContext = camelContext;
this.payloadTypes = payloadTypes;
}
@Override
public T onDataSet(DataSet ds, Object... payloads) {
if (payloads.length != payloadTypes.length) {
String message = format("Received %d payloads, but expected %d.", payloads.length, payloadTypes.length);
throw new IllegalArgumentException(message);
}
for (int i = 0; i < payloads.length; i++) {
payloads[i] = camelContext.getTypeConverter().convertTo(payloadTypes[i], payloads[i]);
}
return doOnDataSet(ds, payloads);
}
public abstract T doOnDataSet(DataSet ds, Object... payloads);
}
| ConvertingDataSetCallback |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/creators/ValueInstantiatorTest.java | {
"start": 7731,
"end": 8172
} | class ____ extends InstantiatorBase
{
@Override
public String getValueTypeDesc() {
return AnnotatedBean.class.getName();
}
@Override
public boolean canCreateUsingDefault() { return true; }
@Override
public AnnotatedBean createUsingDefault(DeserializationContext ctxt) {
return new AnnotatedBean("foo", 3);
}
}
static | AnnotatedBeanInstantiator |
java | elastic__elasticsearch | libs/simdvec/src/main/java/org/elasticsearch/simdvec/QuantizedByteVectorValuesAccess.java | {
"start": 583,
"end": 666
} | interface ____ {
QuantizedByteVectorValues get();
}
| QuantizedByteVectorValuesAccess |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestRPC.java | {
"start": 5884,
"end": 6375
} | interface ____ extends VersionedProtocol {
long versionID = 1L;
void ping() throws IOException;
void sleep(long delay) throws IOException, InterruptedException;
String echo(String value) throws IOException;
String[] echo(String[] value) throws IOException;
Writable echo(Writable value) throws IOException;
int add(int v1, int v2) throws IOException;
int add(int[] values) throws IOException;
int error() throws IOException;
}
public static | TestProtocol |
java | apache__camel | components/camel-jmx/src/generated/java/org/apache/camel/component/jmx/JMXComponentConfigurer.java | {
"start": 730,
"end": 2289
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
JMXComponent target = (JMXComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
JMXComponent target = (JMXComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
default: return null;
}
}
}
| JMXComponentConfigurer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ProtoTruthMixedDescriptorsTest.java | {
"start": 3733,
"end": 4109
} | class ____ {
void test() {
assertThat(TestProtoMessage.getDefaultInstance())
.ignoringFields(
TestProtoMessage.MULTI_FIELD_FIELD_NUMBER, TestProtoMessage.MESSAGE_FIELD_NUMBER);
assertThat((Message) TestFieldProtoMessage.getDefaultInstance())
.ignoringFields(TestProtoMessage.MULTI_FIELD_FIELD_NUMBER);
}
}
""")
.doTest();
}
}
| Test |
java | apache__flink | flink-rpc/flink-rpc-akka/src/main/java/org/apache/flink/runtime/rpc/pekko/DeadLettersActor.java | {
"start": 1392,
"end": 2840
} | class ____ extends AbstractActor {
private static final Logger LOG = LoggerFactory.getLogger(DeadLettersActor.class);
@Override
public Receive createReceive() {
return new ReceiveBuilder().match(DeadLetter.class, this::handleDeadLetter).build();
}
private void handleDeadLetter(DeadLetter deadLetter) {
if (deadLetter.message() instanceof Message) {
if (deadLetter.sender().equals(getContext().getSystem().deadLetters())) {
LOG.debug(
"Could not deliver message {} with no sender to recipient {}. "
+ "This indicates that the actor terminated unexpectedly.",
deadLetter.message(),
deadLetter.recipient());
} else {
deadLetter
.sender()
.tell(
new Status.Failure(
new RecipientUnreachableException(
deadLetter.sender().toString(),
deadLetter.recipient().toString(),
deadLetter.message().toString())),
getSelf());
}
}
}
public static Props getProps() {
return Props.create(DeadLettersActor.class);
}
}
| DeadLettersActor |
java | apache__logging-log4j2 | log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/WebLookupTest.java | {
"start": 849,
"end": 5631
} | class ____ {
// TODO: re-enable when https://github.com/spring-projects/spring-framework/issues/25354 is fixed
// @Test
// public void testLookup() throws Exception {
// ContextAnchor.THREAD_CONTEXT.remove();
// final ServletContext servletContext = new MockServletContext();
// ((MockServletContext) servletContext).setContextPath("/WebApp");
// servletContext.setAttribute("TestAttr", "AttrValue");
// servletContext.setInitParameter("TestParam", "ParamValue");
// servletContext.setAttribute("Name1", "Ben");
// servletContext.setInitParameter("Name2", "Jerry");
// final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);
// try {
// initializer.start();
// initializer.setLoggerContext();
// final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
// assertNotNull(ctx, "No LoggerContext");
// assertNotNull(WebLoggerContextUtils.getServletContext(), "No ServletContext");
// final Configuration config = ctx.getConfiguration();
// assertNotNull(config, "No Configuration");
// final StrSubstitutor substitutor = config.getStrSubstitutor();
// assertNotNull(substitutor, "No Interpolator");
// String value = substitutor.replace("${web:initParam.TestParam}");
// assertNotNull(value, "No value for TestParam");
// assertEquals("ParamValue", value, "Incorrect value for TestParam: " + value);
// value = substitutor.replace("${web:attr.TestAttr}");
// assertNotNull(value, "No value for TestAttr");
// assertEquals("AttrValue", value, "Incorrect value for TestAttr: " + value);
// value = substitutor.replace("${web:Name1}");
// assertNotNull(value, "No value for Name1");
// assertEquals("Ben", value, "Incorrect value for Name1: " + value);
// value = substitutor.replace("${web:Name2}");
// assertNotNull(value, "No value for Name2");
// assertEquals("Jerry", value, "Incorrect value for Name2: " + value);
// value = substitutor.replace("${web:contextPathName}");
// assertNotNull(value, "No value for context name");
// assertEquals("WebApp", value, "Incorrect value for context name");
// } catch (final IllegalStateException e) {
// fail("Failed to initialize Log4j properly." + e.getMessage());
// }
// initializer.stop();
// ContextAnchor.THREAD_CONTEXT.remove();
// }
//
// @Test
// public void testLookup2() throws Exception {
// ContextAnchor.THREAD_CONTEXT.remove();
// final ServletContext servletContext = new MockServletContext();
// ((MockServletContext) servletContext).setContextPath("/");
// servletContext.setAttribute("TestAttr", "AttrValue");
// servletContext.setInitParameter("myapp.logdir", "target");
// servletContext.setAttribute("Name1", "Ben");
// servletContext.setInitParameter("Name2", "Jerry");
// servletContext.setInitParameter("log4jConfiguration", "WEB-INF/classes/log4j-webvar.xml");
// final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);
// initializer.start();
// initializer.setLoggerContext();
// final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
// assertNotNull(ctx, "No LoggerContext");
// assertNotNull(WebLoggerContextUtils.getServletContext(), "No ServletContext");
// final Configuration config = ctx.getConfiguration();
// assertNotNull(config, "No Configuration");
// final Map<String, Appender> appenders = config.getAppenders();
// for (final Map.Entry<String, Appender> entry : appenders.entrySet()) {
// if (entry.getKey().equals("file")) {
// final FileAppender fa = (FileAppender) entry.getValue();
// assertEquals("target/myapp.log", fa.getFileName());
// }
// }
// final StrSubstitutor substitutor = config.getStrSubstitutor();
// String value = substitutor.replace("${web:contextPathName:-default}");
// assertEquals("default", value, "Incorrect value for context name");
// assertNotNull(value, "No value for context name");
// initializer.stop();
// ContextAnchor.THREAD_CONTEXT.remove();
// }
}
| WebLookupTest |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2RefreshTokenGenerator.java | {
"start": 1611,
"end": 3244
} | class ____ implements OAuth2TokenGenerator<OAuth2RefreshToken> {
private final StringKeyGenerator refreshTokenGenerator = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
private Clock clock = Clock.systemUTC();
@Nullable
@Override
public OAuth2RefreshToken generate(OAuth2TokenContext context) {
if (!OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) {
return null;
}
if (isPublicClientForAuthorizationCodeGrant(context)) {
// Do not issue refresh token to public client
return null;
}
Instant issuedAt = this.clock.instant();
Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getRefreshTokenTimeToLive());
return new OAuth2RefreshToken(this.refreshTokenGenerator.generateKey(), issuedAt, expiresAt);
}
/**
* Sets the {@link Clock} used when obtaining the current instant via
* {@link Clock#instant()}.
* @param clock the {@link Clock} used when obtaining the current instant via
* {@link Clock#instant()}
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
private static boolean isPublicClientForAuthorizationCodeGrant(OAuth2TokenContext context) {
// @formatter:off
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType()) &&
(context.getAuthorizationGrant().getPrincipal() instanceof OAuth2ClientAuthenticationToken clientPrincipal)) {
return clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE);
}
// @formatter:on
return false;
}
}
| OAuth2RefreshTokenGenerator |
java | grpc__grpc-java | api/src/main/java/io/grpc/ServerRegistry.java | {
"start": 5721,
"end": 6148
} | class ____
implements ServiceProviders.PriorityAccessor<ServerProvider> {
@Override
public boolean isAvailable(ServerProvider provider) {
return provider.isAvailable();
}
@Override
public int getPriority(ServerProvider provider) {
return provider.priority();
}
}
/** Thrown when no suitable {@link ServerProvider} objects can be found. */
public static final | ServerPriorityAccessor |
java | quarkusio__quarkus | extensions/qute/runtime/src/main/java/io/quarkus/qute/runtime/QuteConfig.java | {
"start": 1567,
"end": 4254
} | class ____. The value {@code *} can be used to match any name.
* <p>
* Examples:
* <ul>
* <li>{@code org.acme.Foo.name} - exclude the property/method {@code name} on the {@code org.acme.Foo} class</li>
* <li>{@code org.acme.Foo.*} - exclude any property/method on the {@code org.acme.Foo} class</li>
* <li>{@code *.age} - exclude the property/method {@code age} on any class</li>
* </ul>
*/
Optional<List<String>> typeCheckExcludes();
/**
* This regular expression is used to exclude template files found in template roots. Excluded templates are
* neither parsed nor validated during build and are not available at runtime.
* <p>
* The matched input is the file path relative from the root directory and the {@code /} is used as a path separator.
* <p>
* By default, the hidden files are excluded. The name of a hidden file starts with a dot.
*/
@WithDefault("^\\..*|.*\\/\\..*$")
Pattern templatePathExclude();
/**
* The prefix is used to access the iteration metadata inside a loop section.
* <p>
* A valid prefix consists of alphanumeric characters and underscores.
* Three special constants can be used:
* <ul>
* <li>{@code <alias_>} - the alias of an iterated element suffixed with an underscore is used, e.g. {@code item_hasNext}
* and {@code it_count}</li>
* <li>{@code <alias?>} - the alias of an iterated element suffixed with a question mark is used, e.g. {@code item?hasNext}
* and {@code it?count}</li>
* <li>{@code <none>} - no prefix is used, e.g. {@code hasNext} and {@code count}</li>
* </ul>
* By default, the {@code <alias_>} constant is set.
*/
@WithDefault("<alias_>")
String iterationMetadataPrefix();
/**
* The list of content types for which the {@code '}, {@code "}, {@code <}, {@code >} and {@code &} characters are escaped
* if a template variant is set.
*/
@WithDefault("text/html,text/xml,application/xml,application/xhtml+xml")
List<String> escapeContentTypes();
/**
* The default charset of the templates files.
*/
@WithDefault("UTF-8")
Charset defaultCharset();
/**
* The strategy used when multiple templates with the same path are found in the application.
*/
@WithDefault("PRIORITIZE")
DuplicitTemplatesStrategy duplicitTemplatesStrategy();
/**
* Development mode configuration.
*/
QuteDevModeConfig devMode();
/**
* Test mode configuration.
*/
QuteTestModeConfig testMode();
/**
* Qute debugger configuration.
*/
QuteDebugConfig debug();
public | name |
java | quarkusio__quarkus | integration-tests/devtools/src/test/java/io/quarkus/devtools/codestarts/quarkus/GrpcCodestartTest.java | {
"start": 376,
"end": 1096
} | class ____ {
@RegisterExtension
public static QuarkusCodestartTest codestartTest = QuarkusCodestartTest.builder()
.codestarts("grpc")
.languages(JAVA)
.build();
@Test
void testContent() throws Throwable {
codestartTest.checkGeneratedSource("org.acme.HelloGrpcService");
codestartTest.assertThatGeneratedFileMatchSnapshot(JAVA, "src/main/proto/hello.proto");
codestartTest.checkGeneratedTestSource("org.acme.HelloGrpcServiceTest");
}
@Test
@EnabledIfSystemProperty(named = "build-projects", matches = "true")
void buildAllProjectsForLocalUse() throws Throwable {
codestartTest.buildAllProjects();
}
}
| GrpcCodestartTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/TestWebApp.java | {
"start": 3234,
"end": 3393
} | class ____ extends Controller {
@Override public void index() {
set("key", "default");
render(FooView.class);
}
}
static | DefaultController |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/File.java | {
"start": 166,
"end": 945
} | class ____ {
private long id;
private String name;
private File parent;
private boolean deleted;
private Set children;
public Set getChildren() {
return children;
}
public void setChildren(Set children) {
this.children = children;
}
public File(String name, File parent) {
this.name = name;
this.parent = parent;
}
File() {}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getParent() {
return parent;
}
public void setParent(File parent) {
this.parent = parent;
}
}
| File |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/common/ArgumentSupplierBeanPostProcessor.java | {
"start": 2785,
"end": 3625
} | class ____ implements RouterFunctions.Visitor {
private final PredicateVisitor predicateVisitor;
RouterFunctionVisitor(PredicateVisitor predicateVisitor) {
this.predicateVisitor = predicateVisitor;
}
@Override
public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) {
predicate.accept(predicateVisitor);
}
@Override
public void attributes(Map<String, Object> attributes) {
this.predicateVisitor.attributesRef.set(attributes);
}
@Override
public void startNested(RequestPredicate predicate) {
}
@Override
public void endNested(RequestPredicate predicate) {
}
@Override
public void resources(Function<ServerRequest, Optional<Resource>> lookupFunction) {
}
@Override
public void unknown(RouterFunction<?> routerFunction) {
}
}
static | RouterFunctionVisitor |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java | {
"start": 163158,
"end": 163311
} | class ____
extends RepositoryMethodInjectionBeanWithVariables<String, Integer> {
}
public static | RepositoryMethodInjectionBeanWithSubstitutedVariables |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/lucene/index/ElasticsearchDirectoryReader.java | {
"start": 4211,
"end": 6985
} | class ____ extends FilterDirectoryReader.SubReaderWrapper {
private final ShardId shardId;
SubReaderWrapper(ShardId shardId) {
this.shardId = shardId;
}
@Override
public LeafReader wrap(LeafReader reader) {
return new ElasticsearchLeafReader(reader, shardId);
}
}
/**
* Adds the given listener to the provided directory reader. The reader
* must contain an {@link ElasticsearchDirectoryReader} in it's hierarchy
* otherwise we can't safely install the listener.
*
* @throws IllegalArgumentException if the reader doesn't contain an
* {@link ElasticsearchDirectoryReader} in it's hierarchy
*/
@SuppressForbidden(reason = "This is the only sane way to add a ReaderClosedListener")
public static void addReaderCloseListener(DirectoryReader reader, IndexReader.ClosedListener listener) {
ElasticsearchDirectoryReader elasticsearchDirectoryReader = getElasticsearchDirectoryReader(reader);
if (elasticsearchDirectoryReader == null) {
throw new IllegalArgumentException(
"Can't install close listener reader is not an ElasticsearchDirectoryReader/ElasticsearchLeafReader"
);
}
IndexReader.CacheHelper cacheHelper = elasticsearchDirectoryReader.getReaderCacheHelper();
if (cacheHelper == null) {
throw new IllegalArgumentException("Reader " + elasticsearchDirectoryReader + " does not support caching");
}
assert cacheHelper.getKey() == reader.getReaderCacheHelper().getKey();
cacheHelper.addClosedListener(listener);
}
/**
* Tries to unwrap the given reader until the first
* {@link ElasticsearchDirectoryReader} instance is found or {@code null}
* if no instance is found.
*/
public static ElasticsearchDirectoryReader getElasticsearchDirectoryReader(DirectoryReader reader) {
if (reader instanceof FilterDirectoryReader) {
if (reader instanceof ElasticsearchDirectoryReader) {
return (ElasticsearchDirectoryReader) reader;
} else {
// We need to use FilterDirectoryReader#getDelegate and not FilterDirectoryReader#unwrap, because
// If there are multiple levels of filtered leaf readers then with the unwrap() method it immediately
// returns the most inner leaf reader and thus skipping of over any other filtered leaf reader that
// may be instance of ElasticsearchLeafReader. This can cause us to miss the shardId.
return getElasticsearchDirectoryReader(((FilterDirectoryReader) reader).getDelegate());
}
}
return null;
}
}
| SubReaderWrapper |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/plugins/DiscoveryPlugin.java | {
"start": 1570,
"end": 2908
} | interface ____ like _mycard_
* and implement by yourself the logic to get an actual IP address/hostname based on this
* name.
*
* For example: you could call a third party service (an API) to resolve _mycard_.
* Then you could define in elasticsearch.yml settings like:
*
* <pre>{@code
* network.host: _mycard_
* }</pre>
*/
default NetworkService.CustomNameResolver getCustomNameResolver(Settings settings) {
return null;
}
/**
* Returns providers of seed hosts for discovery.
*
* The key of the returned map is the name of the host provider
* (see {@link org.elasticsearch.discovery.DiscoveryModule#DISCOVERY_SEED_PROVIDERS_SETTING}), and
* the value is a supplier to construct the host provider when it is selected for use.
*
* @param transportService Use to form the {@link org.elasticsearch.common.transport.TransportAddress} portion
* of a {@link org.elasticsearch.cluster.node.DiscoveryNode}
* @param networkService Use to find the publish host address of the current node
*/
default Map<String, Supplier<SeedHostsProvider>> getSeedHostProviders(
TransportService transportService,
NetworkService networkService
) {
return Collections.emptyMap();
}
}
| name |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/delegate/DelegateSubtypeTest.java | {
"start": 971,
"end": 1238
} | class ____ implements A {
private final A a;
@Inject
public C(@Delegate A a) {
this.a = a;
}
@Override
public int ping() {
return a.ping() + 1;
}
}
@Decorator
public static | C |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationAdapterPropertyPathTests.java | {
"start": 8160,
"end": 8919
} | class ____ {
public void addCourse(@Valid Course course) {
}
public void addCourseList(@Valid List<Course> courses) {
}
public void addCourseArray(@Valid Course[] courses) {
}
public void addCourseMap(@Valid Map<String, Course> courses) {
}
public void addOptionalCourse(@Valid Optional<Course> course) {
}
@Valid
public Course getCourse(Course course) {
throw new UnsupportedOperationException();
}
@Valid
public List<Course> getCourseList() {
throw new UnsupportedOperationException();
}
}
private record Course(@NotBlank String title, @Valid Person professor, @Valid List<Course> requiredCourses) {
}
@SuppressWarnings("unused")
private record Person(@Size(min = 1, max = 5) String name) {
}
}
| MyService |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/health/NodeHealthScriptRunner.java | {
"start": 5129,
"end": 9850
} | class ____ extends TimerTask {
private String exceptionStackTrace = "";
NodeHealthMonitorExecutor(String[] args) {
ArrayList<String> execScript = new ArrayList<String>();
execScript.add(nodeHealthScript);
if (args != null) {
execScript.addAll(Arrays.asList(args));
}
commandExecutor = new ShellCommandExecutor(execScript
.toArray(new String[execScript.size()]), null, null, scriptTimeout);
}
@Override
public void run() {
HealthCheckerExitStatus status = HealthCheckerExitStatus.SUCCESS;
try {
commandExecutor.execute();
} catch (ExitCodeException e) {
// ignore the exit code of the script
status = HealthCheckerExitStatus.FAILED_WITH_EXIT_CODE;
// On Windows, we will not hit the Stream closed IOException
// thrown by stdout buffered reader for timeout event.
if (Shell.WINDOWS && commandExecutor.isTimedOut()) {
status = HealthCheckerExitStatus.TIMED_OUT;
}
} catch (Exception e) {
LOG.warn("Caught exception : " + e.getMessage());
if (!commandExecutor.isTimedOut()) {
status = HealthCheckerExitStatus.FAILED_WITH_EXCEPTION;
} else {
status = HealthCheckerExitStatus.TIMED_OUT;
}
exceptionStackTrace = StringUtils.stringifyException(e);
} finally {
if (status == HealthCheckerExitStatus.SUCCESS) {
if (hasErrors(commandExecutor.getOutput())) {
status = HealthCheckerExitStatus.FAILED;
}
}
reportHealthStatus(status);
}
}
/**
* Method which is used to parse output from the node health monitor and
* send to the report address.
*
* The timed out script or script which causes IOException output is
* ignored.
*
* The node is marked unhealthy if
* <ol>
* <li>The node health script times out</li>
* <li>The node health scripts output has a line which begins
* with ERROR</li>
* <li>An exception is thrown while executing the script</li>
* </ol>
* If the script throws {@link IOException} or {@link ExitCodeException} the
* output is ignored and node is left remaining healthy, as script might
* have syntax error.
*
* @param status
*/
void reportHealthStatus(HealthCheckerExitStatus status) {
switch (status) {
case SUCCESS:
case FAILED_WITH_EXIT_CODE:
// see Javadoc above - we don't report bad health intentionally
setHealthyWithoutReport();
break;
case TIMED_OUT:
setUnhealthyWithReport(NODE_HEALTH_SCRIPT_TIMED_OUT_MSG);
break;
case FAILED_WITH_EXCEPTION:
setUnhealthyWithReport(exceptionStackTrace);
break;
case FAILED:
setUnhealthyWithReport(commandExecutor.getOutput());
break;
default:
LOG.warn("Unknown HealthCheckerExitStatus - ignored.");
break;
}
}
/**
* Method to check if the output string has line which begins with ERROR.
*
* @param output the output of the node health script to process
* @return true if output string has error pattern in it.
*/
private boolean hasErrors(String output) {
String[] splits = output.split("\n");
for (String split : splits) {
if (split.startsWith(ERROR_PATTERN)) {
return true;
}
}
return false;
}
}
@Override
public void serviceStop() throws Exception {
if (commandExecutor != null) {
Process p = commandExecutor.getProcess();
if (p != null) {
p.destroy();
}
}
super.serviceStop();
}
/**
* Method used to determine whether the {@link NodeHealthScriptRunner}
* should be started or not.<p>
* Returns true if following conditions are met:
*
* <ol>
* <li>Path to Node health check script is not empty</li>
* <li>Node health check script file exists</li>
* </ol>
*
* @return true if node health monitoring service can be started.
*/
static boolean shouldRun(String script, String healthScript) {
if (healthScript == null || healthScript.trim().isEmpty()) {
LOG.info("Missing location for the node health check script \"{}\".",
script);
return false;
}
File f = new File(healthScript);
if (!f.exists()) {
LOG.warn("File {} for script \"{}\" does not exist.",
healthScript, script);
return false;
}
if (!FileUtil.canExecute(f)) {
LOG.warn("File {} for script \"{}\" can not be executed.",
healthScript, script);
return false;
}
return true;
}
}
| NodeHealthMonitorExecutor |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/collection/mapkey/ComponentMapKey.java | {
"start": 988,
"end": 3115
} | class ____ {
private Integer cmke_id;
private Integer cte1_id;
private Integer cte2_id;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
ComponentMapKeyEntity imke = new ComponentMapKeyEntity();
// Revision 1 (intialy 1 mapping)
scope.inTransaction( em -> {
ComponentTestEntity cte1 = new ComponentTestEntity(
new Component1( "x1", "y2" ), new Component2(
"a1",
"b2"
)
);
ComponentTestEntity cte2 = new ComponentTestEntity(
new Component1( "x1", "y2" ), new Component2(
"a1",
"b2"
)
);
em.persist( cte1 );
em.persist( cte2 );
imke.getIdmap().put( cte1.getComp1(), cte1 );
em.persist( imke );
cte1_id = cte1.getId();
cte2_id = cte2.getId();
} );
// Revision 2 (sse1: adding 1 mapping)
scope.inTransaction( em -> {
ComponentTestEntity cte2 = em.find( ComponentTestEntity.class, cte2_id );
ComponentMapKeyEntity imkeRef = em.find( ComponentMapKeyEntity.class, imke.getId() );
imkeRef.getIdmap().put( cte2.getComp1(), cte2 );
} );
cmke_id = imke.getId();
}
@Test
public void testRevisionsCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
assertEquals( Arrays.asList( 1, 2 ), AuditReaderFactory.get( em ).getRevisions( ComponentMapKeyEntity.class, cmke_id ) );
} );
}
@Test
public void testHistoryOfImke(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
ComponentTestEntity cte1 = em.find( ComponentTestEntity.class, cte1_id );
ComponentTestEntity cte2 = em.find( ComponentTestEntity.class, cte2_id );
// These fields are unversioned.
cte1.setComp2( null );
cte2.setComp2( null );
var auditReader = AuditReaderFactory.get( em );
ComponentMapKeyEntity rev1 = auditReader.find( ComponentMapKeyEntity.class, cmke_id, 1 );
ComponentMapKeyEntity rev2 = auditReader.find( ComponentMapKeyEntity.class, cmke_id, 2 );
assertEquals( TestTools.makeMap( cte1.getComp1(), cte1 ), rev1.getIdmap() );
assertEquals( TestTools.makeMap( cte1.getComp1(), cte1, cte2.getComp1(), cte2 ), rev2.getIdmap() );
} );
}
}
| ComponentMapKey |
java | grpc__grpc-java | census/src/main/java/io/grpc/census/CensusStatsModule.java | {
"start": 7250,
"end": 16835
} | class ____ extends ClientStreamTracer {
@Nullable private static final AtomicLongFieldUpdater<ClientTracer> outboundMessageCountUpdater;
@Nullable private static final AtomicLongFieldUpdater<ClientTracer> inboundMessageCountUpdater;
@Nullable private static final AtomicLongFieldUpdater<ClientTracer> outboundWireSizeUpdater;
@Nullable private static final AtomicLongFieldUpdater<ClientTracer> inboundWireSizeUpdater;
@Nullable
private static final AtomicLongFieldUpdater<ClientTracer> outboundUncompressedSizeUpdater;
@Nullable
private static final AtomicLongFieldUpdater<ClientTracer> inboundUncompressedSizeUpdater;
/*
* When using Atomic*FieldUpdater, some Samsung Android 5.0.x devices encounter a bug in their
* JDK reflection API that triggers a NoSuchFieldException. When this occurs, we fallback to
* (potentially racy) direct updates of the volatile variables.
*/
static {
AtomicLongFieldUpdater<ClientTracer> tmpOutboundMessageCountUpdater;
AtomicLongFieldUpdater<ClientTracer> tmpInboundMessageCountUpdater;
AtomicLongFieldUpdater<ClientTracer> tmpOutboundWireSizeUpdater;
AtomicLongFieldUpdater<ClientTracer> tmpInboundWireSizeUpdater;
AtomicLongFieldUpdater<ClientTracer> tmpOutboundUncompressedSizeUpdater;
AtomicLongFieldUpdater<ClientTracer> tmpInboundUncompressedSizeUpdater;
try {
tmpOutboundMessageCountUpdater =
AtomicLongFieldUpdater.newUpdater(ClientTracer.class, "outboundMessageCount");
tmpInboundMessageCountUpdater =
AtomicLongFieldUpdater.newUpdater(ClientTracer.class, "inboundMessageCount");
tmpOutboundWireSizeUpdater =
AtomicLongFieldUpdater.newUpdater(ClientTracer.class, "outboundWireSize");
tmpInboundWireSizeUpdater =
AtomicLongFieldUpdater.newUpdater(ClientTracer.class, "inboundWireSize");
tmpOutboundUncompressedSizeUpdater =
AtomicLongFieldUpdater.newUpdater(ClientTracer.class, "outboundUncompressedSize");
tmpInboundUncompressedSizeUpdater =
AtomicLongFieldUpdater.newUpdater(ClientTracer.class, "inboundUncompressedSize");
} catch (Throwable t) {
logger.log(Level.SEVERE, "Creating atomic field updaters failed", t);
tmpOutboundMessageCountUpdater = null;
tmpInboundMessageCountUpdater = null;
tmpOutboundWireSizeUpdater = null;
tmpInboundWireSizeUpdater = null;
tmpOutboundUncompressedSizeUpdater = null;
tmpInboundUncompressedSizeUpdater = null;
}
outboundMessageCountUpdater = tmpOutboundMessageCountUpdater;
inboundMessageCountUpdater = tmpInboundMessageCountUpdater;
outboundWireSizeUpdater = tmpOutboundWireSizeUpdater;
inboundWireSizeUpdater = tmpInboundWireSizeUpdater;
outboundUncompressedSizeUpdater = tmpOutboundUncompressedSizeUpdater;
inboundUncompressedSizeUpdater = tmpInboundUncompressedSizeUpdater;
}
final Stopwatch stopwatch;
final CallAttemptsTracerFactory attemptsState;
final AtomicBoolean inboundReceivedOrClosed = new AtomicBoolean();
final CensusStatsModule module;
final TagContext parentCtx;
final TagContext startCtx;
final StreamInfo info;
volatile long outboundMessageCount;
volatile long inboundMessageCount;
volatile long outboundWireSize;
volatile long inboundWireSize;
volatile long outboundUncompressedSize;
volatile long inboundUncompressedSize;
long roundtripNanos;
Code statusCode;
ClientTracer(
CallAttemptsTracerFactory attemptsState, CensusStatsModule module, TagContext parentCtx,
TagContext startCtx, StreamInfo info) {
this.attemptsState = attemptsState;
this.module = module;
this.parentCtx = parentCtx;
this.startCtx = startCtx;
this.info = info;
this.stopwatch = module.stopwatchSupplier.get().start();
}
@Override
public void streamCreated(Attributes transportAttrs, Metadata headers) {
if (module.propagateTags) {
headers.discardAll(module.statsHeader);
if (!module.tagger.empty().equals(parentCtx)) {
headers.put(module.statsHeader, parentCtx);
}
}
}
@Override
@SuppressWarnings({"NonAtomicVolatileUpdate", "NonAtomicOperationOnVolatileField"})
public void outboundWireSize(long bytes) {
if (outboundWireSizeUpdater != null) {
outboundWireSizeUpdater.getAndAdd(this, bytes);
} else {
outboundWireSize += bytes;
}
module.recordRealTimeMetric(
startCtx, RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, (double) bytes);
}
@Override
@SuppressWarnings("NonAtomicVolatileUpdate")
public void inboundWireSize(long bytes) {
if (inboundWireSizeUpdater != null) {
inboundWireSizeUpdater.getAndAdd(this, bytes);
} else {
inboundWireSize += bytes;
}
module.recordRealTimeMetric(
startCtx, RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_METHOD, (double) bytes);
}
@Override
@SuppressWarnings("NonAtomicVolatileUpdate")
public void outboundUncompressedSize(long bytes) {
if (outboundUncompressedSizeUpdater != null) {
outboundUncompressedSizeUpdater.getAndAdd(this, bytes);
} else {
outboundUncompressedSize += bytes;
}
}
@Override
@SuppressWarnings("NonAtomicVolatileUpdate")
public void inboundUncompressedSize(long bytes) {
if (inboundUncompressedSizeUpdater != null) {
inboundUncompressedSizeUpdater.getAndAdd(this, bytes);
} else {
inboundUncompressedSize += bytes;
}
}
@Override
@SuppressWarnings("NonAtomicVolatileUpdate")
public void inboundMessage(int seqNo) {
if (inboundReceivedOrClosed.compareAndSet(false, true)) {
// Because inboundUncompressedSize() might be called after streamClosed(),
// we will report stats in callEnded(). Note that this attempt is already committed.
attemptsState.inboundMetricTracer = this;
}
if (inboundMessageCountUpdater != null) {
inboundMessageCountUpdater.getAndIncrement(this);
} else {
inboundMessageCount++;
}
module.recordRealTimeMetric(
startCtx, RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_METHOD, 1);
}
@Override
@SuppressWarnings("NonAtomicVolatileUpdate")
public void outboundMessage(int seqNo) {
if (outboundMessageCountUpdater != null) {
outboundMessageCountUpdater.getAndIncrement(this);
} else {
outboundMessageCount++;
}
module.recordRealTimeMetric(
startCtx, RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1);
}
@Override
public void streamClosed(Status status) {
stopwatch.stop();
roundtripNanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
Deadline deadline = info.getCallOptions().getDeadline();
statusCode = status.getCode();
if (statusCode == Status.Code.CANCELLED && deadline != null) {
// When the server's deadline expires, it can only reset the stream with CANCEL and no
// description. Since our timer may be delayed in firing, we double-check the deadline and
// turn the failure into the likely more helpful DEADLINE_EXCEEDED status.
if (deadline.isExpired()) {
statusCode = Code.DEADLINE_EXCEEDED;
}
}
attemptsState.attemptEnded();
if (inboundReceivedOrClosed.compareAndSet(false, true)) {
if (module.recordFinishedRpcs) {
// Stream is closed early. So no need to record metrics for any inbound events after this
// point.
recordFinishedAttempt();
}
} // Otherwise will report stats in callEnded() to guarantee all inbound metrics are recorded.
}
void recordFinishedAttempt() {
MeasureMap measureMap =
module
.statsRecorder
.newMeasureMap()
// TODO(songya): remove the deprecated measure constants once they are completed
// removed.
.put(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT, 1)
// The latency is double value
.put(
RpcMeasureConstants.GRPC_CLIENT_ROUNDTRIP_LATENCY,
roundtripNanos / NANOS_PER_MILLI)
.put(RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_RPC, outboundMessageCount)
.put(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC, inboundMessageCount)
.put(RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_RPC, (double) outboundWireSize)
.put(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_RPC, (double) inboundWireSize)
.put(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES,
(double) outboundUncompressedSize)
.put(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES,
(double) inboundUncompressedSize);
if (statusCode != Code.OK) {
measureMap.put(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT, 1);
}
TagValue statusTag = TagValue.create(statusCode.toString());
measureMap.record(
module
.tagger
.toBuilder(startCtx)
.putLocal(RpcMeasureConstants.GRPC_CLIENT_STATUS, statusTag)
.build());
}
}
@VisibleForTesting
static final | ClientTracer |
java | apache__camel | components/camel-jsch/src/test/java/org/apache/camel/component/scp/ScpSimpleProduceTest.java | {
"start": 1210,
"end": 5983
} | class ____ extends ScpServerTestSupport {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("file:" + getScpPath() + "?recursive=true&delete=true")
.convertBodyTo(String.class)
.to("mock:result");
}
};
}
@Test
public void testScpSimpleProduce() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
String uri = getScpUri() + "?username=admin&password=admin&knownHostsFile=" + getKnownHostsFile();
template.sendBodyAndHeader(uri, "Hello World", Exchange.FILE_NAME, "hello.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testScpSimpleProduceTwoTimes() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedBodiesReceivedInAnyOrder("Hello World", "Bye World");
String uri = getScpUri() + "?username=admin&password=admin&knownHostsFile=" + getKnownHostsFile();
template.sendBodyAndHeader(uri, "Hello World", Exchange.FILE_NAME, "hello.txt");
template.sendBodyAndHeader(uri, "Bye World", Exchange.FILE_NAME, "bye.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testScpSimpleSubPathProduce() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
String uri = getScpUri() + "?username=admin&password=admin&knownHostsFile=" + getKnownHostsFile();
template.sendBodyAndHeader(uri, "Bye World", Exchange.FILE_NAME, "mysub/bye.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testScpSimpleTwoSubPathProduce() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedBodiesReceived("Farewell World");
String uri = getScpUri() + "?username=admin&password=admin&knownHostsFile=" + getKnownHostsFile();
template.sendBodyAndHeader(uri, "Farewell World", Exchange.FILE_NAME, "mysub/mysubsub/farewell.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testScpProduceChmod() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedBodiesReceived("Bonjour Monde");
String uri = getScpUri() + "?username=admin&password=admin&chmod=640&knownHostsFile=" + getKnownHostsFile();
template.sendBodyAndHeader(uri, "Bonjour Monde", Exchange.FILE_NAME, "monde.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Test
@Disabled("Fails on CI servers")
public void testScpProducePrivateKey() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedMessageCount(1);
String uri
= getScpUri()
+ "?username=admin&privateKeyFile=src/test/resources/camel-key.priv.pem&privateKeyFilePassphrase=password&knownHostsFile="
+ getKnownHostsFile();
template.sendBodyAndHeader(uri, "Hallo Welt", Exchange.FILE_NAME, "welt.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Test
@Disabled("Fails on CI servers")
public void testScpProducePrivateKeyFromClasspath() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedMessageCount(1);
String uri
= getScpUri()
+ "?username=admin&privateKeyFile=classpath:camel-key.priv.pem&privateKeyFilePassphrase=password&knownHostsFile="
+ getKnownHostsFile();
template.sendBodyAndHeader(uri, "Hallo Welt", Exchange.FILE_NAME, "welt.txt");
MockEndpoint.assertIsSatisfied(context);
}
@Test
@Disabled("Fails on CI servers")
public void testScpProducePrivateKeyByte() throws Exception {
assumeTrue(this.isSetupComplete());
getMockEndpoint("mock:result").expectedMessageCount(1);
String uri = getScpUri() + "?username=admin&privateKeyBytes=#privKey&privateKeyFilePassphrase=password&knownHostsFile="
+ getKnownHostsFile();
template.sendBodyAndHeader(uri, "Hallo Welt", Exchange.FILE_NAME, "welt.txt");
MockEndpoint.assertIsSatisfied(context);
}
@BindToRegistry("privKey")
public byte[] loadPrivateKey() throws Exception {
byte[] privKey = Files.readAllBytes(new File("src/test/resources/camel-key.priv.pem").toPath());
return privKey;
}
}
| ScpSimpleProduceTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/annotation/RId.java | {
"start": 1276,
"end": 1567
} | interface ____ {
/**
* (Optional) Live Object id generator. By default id is required to be fill during object creation.
*
* @see UUIDGenerator
* @see LongGenerator
*/
Class<? extends RIdResolver<?>> generator() default RequiredIdResolver.class;
}
| RId |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/CommonCachesTestExecutionListenerIntegrationTests.java | {
"start": 2511,
"end": 2869
} | class ____ {
@Bean
@Lazy
String dummyBean(ResourceLoader resourceLoader) {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
scanner.setResourceLoader(resourceLoader);
scanner.findCandidateComponents(SampleComponent.class.getPackageName());
return "Dummy";
}
}
}
| TestConfiguration |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/boot/models/annotation/SimpleAnnotationUsageTests.java | {
"start": 1971,
"end": 2048
} | class ____ {
@Id
private Integer id;
private String name;
}
}
| SimpleEntity |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/matchers/CompileTimeConstantExpressionMatcher.java | {
"start": 4199,
"end": 7695
} | class ____ implements Matcher<ExpressionTree> {
@Override
public boolean matches(ExpressionTree tree, VisitorState state) {
return tree.accept(
new SimpleTreeVisitor<Boolean, Void>() {
@Override
public Boolean visitConditionalExpression(ConditionalExpressionTree tree, Void unused) {
return tree.getTrueExpression().accept(this, null)
&& tree.getFalseExpression().accept(this, null);
}
@Override
public Boolean visitSwitchExpression(SwitchExpressionTree tree, Void unused) {
// This is intentionally quite restrictive: only accept bare values and throws.
return tree.getCases().stream()
.allMatch(
c ->
c.getCaseKind().equals(CaseKind.RULE)
&& (c.getBody().accept(this, null)
|| c.getBody() instanceof ThrowTree));
}
@Override
public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) {
return IMMUTABLE_FACTORY.matches(tree, state)
&& tree.getArguments().stream().allMatch(a -> a.accept(this, null));
}
@Override
public Boolean visitBinary(BinaryTree tree, Void unused) {
return defaultAction(tree, null)
|| (tree.getKind().equals(Kind.PLUS)
&& tree.getLeftOperand().accept(this, null)
&& tree.getRightOperand().accept(this, null));
}
@Override
public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) {
return tree.getExpression().accept(this, null);
}
@Override
protected Boolean defaultAction(Tree node, Void unused) {
if (constValue(node) != null) {
return true;
}
if (!(node instanceof IdentifierTree)) {
return false;
}
Symbol.VarSymbol varSymbol = (Symbol.VarSymbol) getSymbol(node);
Symbol owner = varSymbol.owner;
ElementKind ownerKind = owner.getKind();
// Check that the identifier is a formal method/constructor parameter, or a class/enum
// field.
if (ownerKind != ElementKind.METHOD
&& ownerKind != ElementKind.CONSTRUCTOR
&& ownerKind != ElementKind.CLASS
&& ownerKind != ElementKind.ENUM) {
return false;
}
// Check that the symbol is final
if (!isConsideredFinal(varSymbol)) {
return false;
}
// Check if the symbol has the @CompileTimeConstant annotation.
if (hasCompileTimeConstantAnnotation(state, varSymbol)) {
return true;
}
return false;
}
},
null);
}
}
public static boolean hasCompileTimeConstantAnnotation(VisitorState state, Symbol symbol) {
Symbol annotation = COMPILE_TIME_CONSTANT_ANNOTATION.get(state);
// If we can't look up the annotation in the current VisitorState, then presumably it couldn't
// be present on a Symbol we're inspecting.
return annotation != null && symbol.attribute(annotation) != null;
}
}
| ExpressionWithConstValueMatcher |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/MlControllerHolder.java | {
"start": 594,
"end": 881
} | class ____ {
private final MlController mlController;
public MlControllerHolder(MlController mlController) {
this.mlController = Objects.requireNonNull(mlController);
}
public MlController getMlController() {
return mlController;
}
}
| MlControllerHolder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/keymanytoone/association/CardField.java | {
"start": 342,
"end": 708
} | class ____ implements Serializable {
@EmbeddedId
private PrimaryKey primaryKey;
private String name;
CardField(Card card, Key key) {
this.primaryKey = new PrimaryKey( card, key);
}
CardField() {
}
public PrimaryKey getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(PrimaryKey primaryKey) {
this.primaryKey = primaryKey;
}
}
| CardField |
java | alibaba__nacos | istio/src/main/java/com/alibaba/nacos/istio/server/ServerInterceptor.java | {
"start": 940,
"end": 1506
} | class ____ implements io.grpc.ServerInterceptor {
@Override
public <R, T> ServerCall.Listener<R> interceptCall(ServerCall<R, T> call, Metadata headers,
ServerCallHandler<R, T> next) {
SocketAddress address = call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
String methodName = call.getMethodDescriptor().getFullMethodName();
Loggers.MAIN.info("remote address: {}, method: {}", address, methodName);
return next.startCall(call, headers);
}
}
| ServerInterceptor |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/ParallelFlatMap.java | {
"start": 1061,
"end": 2945
} | class ____<T, R> extends ParallelFlux<R> implements Scannable{
final ParallelFlux<T> source;
final Function<? super T, ? extends Publisher<? extends R>> mapper;
final boolean delayError;
final int maxConcurrency;
final Supplier<? extends Queue<R>> mainQueueSupplier;
final int prefetch;
final Supplier<? extends Queue<R>> innerQueueSupplier;
ParallelFlatMap(
ParallelFlux<T> source,
Function<? super T, ? extends Publisher<? extends R>> mapper,
boolean delayError,
int maxConcurrency, Supplier<? extends Queue<R>> mainQueueSupplier,
int prefetch, Supplier<? extends Queue<R>> innerQueueSupplier) {
this.source = ParallelFlux.from(source);
this.mapper = mapper;
this.delayError = delayError;
this.maxConcurrency = maxConcurrency;
this.mainQueueSupplier = mainQueueSupplier;
this.prefetch = prefetch;
this.innerQueueSupplier = innerQueueSupplier;
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) return source;
if (key == Attr.PREFETCH) return getPrefetch();
if (key == Attr.DELAY_ERROR) return delayError;
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
if (key == InternalProducerAttr.INSTANCE) return true;
return null;
}
@Override
public int getPrefetch() {
return prefetch;
}
@Override
public int parallelism() {
return source.parallelism();
}
@Override
public void subscribe(CoreSubscriber<? super R>[] subscribers) {
if (!validate(subscribers)) {
return;
}
int n = subscribers.length;
@SuppressWarnings("unchecked")
CoreSubscriber<T>[] parents = new CoreSubscriber[n];
for (int i = 0; i < n; i++) {
parents[i] = new FluxFlatMap.FlatMapMain<>(subscribers[i],
mapper,
delayError,
maxConcurrency,
mainQueueSupplier,
prefetch,
innerQueueSupplier);
}
source.subscribe(parents);
}
}
| ParallelFlatMap |
java | dropwizard__dropwizard | dropwizard-validation/src/main/java/io/dropwizard/validation/ConstraintViolations.java | {
"start": 227,
"end": 304
} | class ____ static methods to work with constraint violations.
*/
public | provides |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/nestedbeans/UserDtoMapperClassic.java | {
"start": 299,
"end": 720
} | interface ____ {
UserDtoMapperClassic INSTANCE = Mappers.getMapper( UserDtoMapperClassic.class );
UserDto userToUserDto(User user);
CarDto carToCarDto(Car car);
HouseDto houseToHouseDto(House house);
RoofDto roofToRoofDto(Roof roof);
List<WheelDto> mapWheels(List<Wheel> wheels);
WheelDto mapWheel(Wheel wheels);
ExternalRoofType mapRoofType(RoofType roofType);
}
| UserDtoMapperClassic |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportPutCalendarAction.java | {
"start": 1713,
"end": 4101
} | class ____ extends HandledTransportAction<PutCalendarAction.Request, PutCalendarAction.Response> {
private final Client client;
@Inject
public TransportPutCalendarAction(TransportService transportService, ActionFilters actionFilters, Client client) {
super(PutCalendarAction.NAME, transportService, actionFilters, PutCalendarAction.Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE);
this.client = client;
}
@Override
protected void doExecute(Task task, PutCalendarAction.Request request, ActionListener<PutCalendarAction.Response> listener) {
Calendar calendar = request.getCalendar();
IndexRequest indexRequest = new IndexRequest(MlMetaIndex.indexName()).id(calendar.documentId());
try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
indexRequest.source(
calendar.toXContent(
builder,
new ToXContent.MapParams(Collections.singletonMap(ToXContentParams.FOR_INTERNAL_STORAGE, "true"))
)
);
} catch (IOException e) {
throw new IllegalStateException("Failed to serialise calendar with id [" + calendar.getId() + "]", e);
}
// Make it an error to overwrite an existing calendar
indexRequest.opType(DocWriteRequest.OpType.CREATE);
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
executeAsyncWithOrigin(client, ML_ORIGIN, TransportIndexAction.TYPE, indexRequest, new ActionListener<>() {
@Override
public void onResponse(DocWriteResponse indexResponse) {
listener.onResponse(new PutCalendarAction.Response(calendar));
}
@Override
public void onFailure(Exception e) {
if (ExceptionsHelper.unwrapCause(e) instanceof VersionConflictEngineException) {
listener.onFailure(
ExceptionsHelper.badRequestException(
"Cannot create calendar with id [" + calendar.getId() + "] as it already exists"
)
);
} else {
listener.onFailure(ExceptionsHelper.serverError("Error putting calendar with id [" + calendar.getId() + "]", e));
}
}
});
}
}
| TransportPutCalendarAction |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/AsteriskComponentBuilderFactory.java | {
"start": 1834,
"end": 5328
} | interface ____ extends ComponentBuilder<AsteriskComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AsteriskComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AsteriskComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default AsteriskComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
| AsteriskComponentBuilder |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestClearVotingConfigExclusionsAction.java | {
"start": 1256,
"end": 2597
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(DELETE, "/_cluster/voting_config_exclusions"));
}
@Override
public boolean canTripCircuitBreaker() {
return false;
}
@Override
public String getName() {
return "clear_voting_config_exclusions_action";
}
@Override
public Set<String> supportedCapabilities() {
return Set.of(PLAIN_TEXT_EMPTY_RESPONSE_CAPABILITY_NAME);
}
@Override
protected RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
final var req = resolveVotingConfigExclusionsRequest(request);
return channel -> client.execute(TransportClearVotingConfigExclusionsAction.TYPE, req, new EmptyResponseListener(channel));
}
static ClearVotingConfigExclusionsRequest resolveVotingConfigExclusionsRequest(final RestRequest request) {
final var resolvedRequest = new ClearVotingConfigExclusionsRequest(getMasterNodeTimeout(request));
resolvedRequest.setTimeout(resolvedRequest.masterNodeTimeout());
resolvedRequest.setWaitForRemoval(request.paramAsBoolean("wait_for_removal", resolvedRequest.getWaitForRemoval()));
return resolvedRequest;
}
}
| RestClearVotingConfigExclusionsAction |
java | apache__flink | flink-state-backends/flink-statebackend-changelog/src/test/java/org/apache/flink/state/changelog/ChangelogDelegateHashMapTest.java | {
"start": 1932,
"end": 4710
} | class ____ extends HashMapStateBackendTest {
@TempDir private Path temp;
protected TestTaskStateManager getTestTaskStateManager() throws IOException {
return ChangelogStateBackendTestUtils.createTaskStateManager(TempDirUtils.newFolder(temp));
}
@Override
protected boolean snapshotUsesStreamFactory() {
return false;
}
@Override
protected boolean supportsMetaInfoVerification() {
return false;
}
@Override
protected <K> CheckpointableKeyedStateBackend<K> createKeyedBackend(
TypeSerializer<K> keySerializer,
int numberOfKeyGroups,
KeyGroupRange keyGroupRange,
Environment env)
throws Exception {
return ChangelogStateBackendTestUtils.createKeyedBackend(
new ChangelogStateBackend(super.getStateBackend()),
keySerializer,
numberOfKeyGroups,
keyGroupRange,
env);
}
@Override
protected ConfigurableStateBackend getStateBackend() {
return new ChangelogStateBackend(super.getStateBackend());
}
@TestTemplate
public void testMaterializedRestore() throws Exception {
CheckpointStreamFactory streamFactory = createStreamFactory();
ChangelogStateBackendTestUtils.testMaterializedRestore(
getStateBackend(), StateTtlConfig.DISABLED, env, streamFactory);
}
@TestTemplate
public void testMaterializedRestoreWithWrappedState() throws Exception {
CheckpointStreamFactory streamFactory = createStreamFactory();
Configuration configuration = new Configuration();
configuration.set(StateLatencyTrackOptions.LATENCY_TRACK_ENABLED, true);
StateBackend stateBackend =
getStateBackend()
.configure(configuration, Thread.currentThread().getContextClassLoader());
ChangelogStateBackendTestUtils.testMaterializedRestore(
stateBackend,
StateTtlConfig.newBuilder(Duration.ofMinutes(1)).build(),
env,
streamFactory);
}
@TestTemplate
public void testMaterializedRestorePriorityQueue() throws Exception {
CheckpointStreamFactory streamFactory = createStreamFactory();
ChangelogStateBackendTestUtils.testMaterializedRestoreForPriorityQueue(
getStateBackend(), env, streamFactory);
}
// Follow https://issues.apache.org/jira/browse/FLINK-38144
@Override
@TestTemplate
@Disabled("Currently, ChangelogStateBackend does not support null values for map state")
public void testMapStateWithNullValue() throws Exception {
super.testMapStateWithNullValue();
}
}
| ChangelogDelegateHashMapTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/conf/TestGetInstances.java | {
"start": 1144,
"end": 1208
} | interface ____ extends SampleInterface {}
static | ChildInterface |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/GenericEventTypeMetricsManager.java | {
"start": 1107,
"end": 1812
} | class ____ {
private GenericEventTypeMetricsManager() {
// nothing to do
}
// Construct a GenericEventTypeMetrics for dispatcher
public static <T extends Enum<T>> GenericEventTypeMetrics
create(String dispatcherName, Class<T> eventTypeClass) {
MetricsInfo metricsInfo = info("GenericEventTypeMetrics for " + eventTypeClass.getName(),
"Metrics for " + dispatcherName);
return new GenericEventTypeMetrics.EventTypeMetricsBuilder<T>()
.setMs(DefaultMetricsSystem.instance())
.setInfo(metricsInfo)
.setEnumClass(eventTypeClass)
.setEnums(eventTypeClass.getEnumConstants())
.build().registerMetrics();
}
}
| GenericEventTypeMetricsManager |
java | google__guava | android/guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java | {
"start": 34421,
"end": 34694
} | class ____ implements Runnable {
public volatile boolean done = false;
@Override
public void run() {
try {
delay(MEDIUM_DELAY_MS);
done = true;
} catch (InterruptedException ok) {
}
}
}
public static | TrackedMediumRunnable |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/serializer/TestSpecial2.java | {
"start": 118,
"end": 538
} | class ____ extends TestCase {
public void test_0() throws Exception {
StringBuilder buf = new StringBuilder();
buf.append('\r');
buf.append('\r');
for (int i = 0; i < 1000; ++i) {
buf.append((char) 160);
}
VO vo = new VO();
vo.setValue(buf.toString());
System.out.println(JSON.toJSONString(vo));
}
public static | TestSpecial2 |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/rpc/RpcTaskOperatorEventGateway.java | {
"start": 1683,
"end": 3006
} | class ____ implements TaskOperatorEventGateway {
private final JobMasterOperatorEventGateway rpcGateway;
private final ExecutionAttemptID taskExecutionId;
private final Consumer<Throwable> errorHandler;
public RpcTaskOperatorEventGateway(
JobMasterOperatorEventGateway rpcGateway,
ExecutionAttemptID taskExecutionId,
Consumer<Throwable> errorHandler) {
this.rpcGateway = rpcGateway;
this.taskExecutionId = taskExecutionId;
this.errorHandler = errorHandler;
}
@Override
public void sendOperatorEventToCoordinator(
OperatorID operator, SerializedValue<OperatorEvent> event) {
final CompletableFuture<Acknowledge> result =
rpcGateway.sendOperatorEventToCoordinator(taskExecutionId, operator, event);
result.whenComplete(
(success, exception) -> {
if (exception != null) {
errorHandler.accept(exception);
}
});
}
@Override
public CompletableFuture<CoordinationResponse> sendRequestToCoordinator(
OperatorID operator, SerializedValue<CoordinationRequest> request) {
return rpcGateway.sendRequestToCoordinator(operator, request);
}
}
| RpcTaskOperatorEventGateway |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/internal/bytebuddy/ByteBuddyState.java | {
"start": 4915,
"end": 5373
} | class ____.
* @param makeProxyFunction A function building the proxy.
* @return The loaded proxy class.
*/
public Class<?> loadProxy(Class<?> referenceClass, String proxyClassName,
BiFunction<ByteBuddy, NamingStrategy, DynamicType.Builder<?>> makeProxyFunction) {
return load( referenceClass, proxyClassName, makeProxyFunction );
}
/**
* Load a proxy as generated by the {@link BasicProxyFactory}.
*
* @param referenceClass The main | name |
java | apache__camel | components/camel-as2/camel-as2-api/src/test/java/org/apache/camel/component/as2/api/entity/ApplicationEntityTest.java | {
"start": 1399,
"end": 3323
} | class ____ {
@Test
void checkWriteToWithMultiByteCharacter() throws IOException {
byte[] messageBytes = "Test message with special char ó".getBytes(StandardCharsets.UTF_8);
ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
ApplicationEntity applicationEntity = new ApplicationEntity(messageBytes, contentType, "binary", true, null) {
@Override
public void close() throws IOException {
}
};
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
applicationEntity.writeTo(outputStream);
byte[] actualBytes = outputStream.toByteArray();
assertArrayEquals(messageBytes, actualBytes, "The output bytes should match the expected UTF-8 encoded bytes.");
assertEquals(messageBytes.length, actualBytes.length,
"The byte length should match the length of the UTF-8 encoded message.");
}
@ParameterizedTest(name = "writing content {1}")
@MethodSource("test_write_line_endings")
void test_write_carriage_return(String content, String description) throws IOException {
ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
ApplicationEntity applicationEntity = new ApplicationEntity(content.getBytes(), contentType, "binary", true, null) {
@Override
public void close() throws IOException {
}
};
OutputStream outputStream = new ByteArrayOutputStream();
applicationEntity.writeTo(outputStream);
assertArrayEquals(outputStream.toString().getBytes(), content.getBytes());
}
private static Stream<Arguments> test_write_line_endings() {
return Stream.of(
Arguments.of("\r", "CR"),
Arguments.of("\n", "LF"),
Arguments.of("\r\n", "CRLF"));
}
}
| ApplicationEntityTest |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/search/TemplateParamValidatorTests.java | {
"start": 459,
"end": 1562
} | class ____ extends ESTestCase {
public void testValidateThrowsWhenSchemaDontMatch() {
Map<String, Object> failingParams = new HashMap<>();
failingParams.put("fail", null);
TemplateParamValidator validator = new TemplateParamValidator(
"{\"properties\":{\"title_boost\":{\"type\":\"number\"},\"additionalProperties\":false},\"required\":[\"query_string\"]}"
);
assertThrows(ValidationException.class, () -> validator.validate(failingParams));
}
public void testValidateWithFloats() {
Map<String, Object> passingParams = new HashMap<>();
passingParams.put("title_boost", 1.0f);
passingParams.put("query_string", "query_string");
TemplateParamValidator validator = new TemplateParamValidator(
"{\"properties\":{\"title_boost\":{\"type\":\"number\"},\"additionalProperties\":false},\"required\":[\"query_string\"]}"
);
// This shouldn't throw
// We don't have nice assertions for this in JUnit 4
validator.validate(passingParams);
}
}
| TemplateParamValidatorTests |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/support/NativeMessageHeaderAccessorTests.java | {
"start": 1219,
"end": 10310
} | class ____ {
@Test
void createFromNativeHeaderMap() {
MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>();
inputNativeHeaders.add("foo", "bar");
inputNativeHeaders.add("bar", "baz");
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(inputNativeHeaders);
Map<String, Object> actual = headerAccessor.toMap();
assertThat(actual.size()).as(actual.toString()).isEqualTo(1);
assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotNull();
assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isEqualTo(inputNativeHeaders);
assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotSameAs(inputNativeHeaders);
}
@Test
void createFromMessage() {
MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>();
inputNativeHeaders.add("foo", "bar");
inputNativeHeaders.add("bar", "baz");
Map<String, Object> inputHeaders = new HashMap<>();
inputHeaders.put("a", "b");
inputHeaders.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, inputNativeHeaders);
GenericMessage<String> message = new GenericMessage<>("p", inputHeaders);
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message);
Map<String, Object> actual = headerAccessor.toMap();
assertThat(actual).hasSize(2);
assertThat(actual.get("a")).isEqualTo("b");
assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotNull();
assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isEqualTo(inputNativeHeaders);
assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotSameAs(inputNativeHeaders);
}
@Test
void createFromMessageNull() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor((Message<?>) null);
Map<String, Object> actual = headerAccessor.toMap();
assertThat(actual).isEmpty();
Map<String, List<String>> actualNativeHeaders = headerAccessor.toNativeHeaderMap();
assertThat(actualNativeHeaders).isEqualTo(Collections.emptyMap());
}
@Test
void createFromMessageAndModify() {
MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>();
inputNativeHeaders.add("foo", "bar");
inputNativeHeaders.add("bar", "baz");
Map<String, Object> nativeHeaders = new HashMap<>();
nativeHeaders.put("a", "b");
nativeHeaders.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, inputNativeHeaders);
GenericMessage<String> message = new GenericMessage<>("p", nativeHeaders);
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message);
headerAccessor.setHeader("a", "B");
headerAccessor.setNativeHeader("foo", "BAR");
Map<String, Object> actual = headerAccessor.toMap();
assertThat(actual).hasSize(2);
assertThat(actual.get("a")).isEqualTo("B");
@SuppressWarnings("unchecked")
Map<String, List<String>> actualNativeHeaders =
(Map<String, List<String>>) actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
assertThat(actualNativeHeaders).isNotNull();
assertThat(actualNativeHeaders.get("foo")).isEqualTo(Collections.singletonList("BAR"));
assertThat(actualNativeHeaders.get("bar")).isEqualTo(Collections.singletonList("baz"));
}
@Test
void setNativeHeader() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.setNativeHeader("foo", "baz");
assertThat(headers.getNativeHeader("foo")).isEqualTo(Collections.singletonList("baz"));
}
@Test
void setNativeHeaderNullValue() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.setNativeHeader("foo", null);
assertThat(headers.getNativeHeader("foo")).isNull();
}
@Test
void setNativeHeaderLazyInit() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.setNativeHeader("foo", "baz");
assertThat(headerAccessor.getNativeHeader("foo")).isEqualTo(Collections.singletonList("baz"));
}
@Test
void setNativeHeaderLazyInitNullValue() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.setNativeHeader("foo", null);
assertThat(headerAccessor.getNativeHeader("foo")).isNull();
assertThat(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNull();
}
@Test
void setNativeHeaderImmutable() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.setNativeHeader("foo", "bar");
headerAccessor.setImmutable();
assertThatIllegalStateException()
.isThrownBy(() -> headerAccessor.setNativeHeader("foo", "baz"))
.withMessageContaining("Already immutable");
}
@Test
void addNativeHeader() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.addNativeHeader("foo", "baz");
assertThat(headers.getNativeHeader("foo")).isEqualTo(Arrays.asList("bar", "baz"));
}
@Test
void addNativeHeaderNullValue() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.addNativeHeader("foo", null);
assertThat(headers.getNativeHeader("foo")).isEqualTo(Collections.singletonList("bar"));
}
@Test
void addNativeHeaderLazyInit() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", "bar");
assertThat(headerAccessor.getNativeHeader("foo")).isEqualTo(Collections.singletonList("bar"));
}
@Test
void addNativeHeaderLazyInitNullValue() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", null);
assertThat(headerAccessor.getNativeHeader("foo")).isNull();
assertThat(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNull();
}
@Test
void addNativeHeaderImmutable() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", "bar");
headerAccessor.setImmutable();
assertThatIllegalStateException()
.isThrownBy(() -> headerAccessor.addNativeHeader("foo", "baz"))
.withMessageContaining("Already immutable");
}
@Test
void setImmutableIdempotent() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", "bar");
headerAccessor.setImmutable();
headerAccessor.setImmutable();
}
@Test // gh-25821
void copyImmutableToMutable() {
NativeMessageHeaderAccessor sourceAccessor = new NativeMessageHeaderAccessor();
sourceAccessor.addNativeHeader("foo", "bar");
Message<String> source = MessageBuilder.createMessage("payload", sourceAccessor.getMessageHeaders());
NativeMessageHeaderAccessor targetAccessor = new NativeMessageHeaderAccessor();
targetAccessor.copyHeaders(source.getHeaders());
targetAccessor.setLeaveMutable(true);
Message<?> target = MessageBuilder.createMessage(source.getPayload(), targetAccessor.getMessageHeaders());
MessageHeaderAccessor accessor = MessageHeaderAccessor.getMutableAccessor(target);
assertThat(accessor.isMutable()).isTrue();
((NativeMessageHeaderAccessor) accessor).addNativeHeader("foo", "baz");
assertThat(((NativeMessageHeaderAccessor) accessor).getNativeHeader("foo")).containsExactly("bar", "baz");
}
@Test // gh-25821
void copyIfAbsentImmutableToMutable() {
NativeMessageHeaderAccessor sourceAccessor = new NativeMessageHeaderAccessor();
sourceAccessor.addNativeHeader("foo", "bar");
Message<String> source = MessageBuilder.createMessage("payload", sourceAccessor.getMessageHeaders());
MessageHeaderAccessor targetAccessor = new NativeMessageHeaderAccessor();
targetAccessor.copyHeadersIfAbsent(source.getHeaders());
targetAccessor.setLeaveMutable(true);
Message<?> target = MessageBuilder.createMessage(source.getPayload(), targetAccessor.getMessageHeaders());
MessageHeaderAccessor accessor = MessageHeaderAccessor.getMutableAccessor(target);
assertThat(accessor.isMutable()).isTrue();
((NativeMessageHeaderAccessor) accessor).addNativeHeader("foo", "baz");
assertThat(((NativeMessageHeaderAccessor) accessor).getNativeHeader("foo")).containsExactly("bar", "baz");
}
@Test // gh-26155
void copySelf() {
NativeMessageHeaderAccessor accessor = new NativeMessageHeaderAccessor();
accessor.addNativeHeader("foo", "bar");
accessor.setHeader("otherHeader", "otherHeaderValue");
accessor.setLeaveMutable(true);
// Does not fail with ConcurrentModificationException
accessor.copyHeaders(accessor.getMessageHeaders());
}
}
| NativeMessageHeaderAccessorTests |
java | elastic__elasticsearch | x-pack/plugin/analytics/src/main/java/org/elasticsearch/xpack/analytics/ttest/PairedTTestState.java | {
"start": 738,
"end": 3351
} | class ____ implements TTestState {
public static final String NAME = "P";
private final TTestStats stats;
private final int tails;
public PairedTTestState(TTestStats stats, int tails) {
this.stats = stats;
this.tails = tails;
}
public PairedTTestState(StreamInput in) throws IOException {
stats = new TTestStats(in);
tails = in.readVInt();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
stats.writeTo(out);
out.writeVInt(tails);
}
@Override
public double getValue() {
if (stats.count < 2) {
return Double.NaN;
}
long n = stats.count - 1;
double meanDiff = stats.sum / stats.count;
double variance = (stats.sumOfSqrs - ((stats.sum * stats.sum) / stats.count)) / stats.count;
if (variance <= 0.0) {
return meanDiff == 0.0 ? Double.NaN : 0.0;
}
double stdDiv = Math.sqrt(variance);
double stdErr = stdDiv / Math.sqrt(n);
double t = Math.abs(meanDiff / stdErr);
TDistribution dist = new TDistribution(n);
return dist.cumulativeProbability(-t) * tails;
}
@Override
public AggregatorReducer getReducer(String name, DocValueFormat format, Map<String, Object> metadata) {
return new AggregatorReducer() {
TTestStats.Reducer reducer = new TTestStats.Reducer();
@Override
public void accept(InternalAggregation aggregation) {
PairedTTestState state = (PairedTTestState) ((InternalTTest) aggregation).state;
reducer.accept(state.stats);
if (state.tails != tails) {
throw new IllegalStateException(
"Incompatible tails value in the reduce. Expected " + state.tails + " reduced with " + tails
);
}
}
@Override
public InternalAggregation get() {
return new InternalTTest(name, new PairedTTestState(reducer.result(), tails), format, metadata);
}
};
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PairedTTestState that = (PairedTTestState) o;
return tails == that.tails && stats.equals(that.stats);
}
@Override
public int hashCode() {
return Objects.hash(stats, tails);
}
}
| PairedTTestState |
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/linux/runtime/OCIContainerRuntime.java | {
"start": 3218,
"end": 14458
} | class ____ implements LinuxContainerRuntime {
private static final Logger LOG =
LoggerFactory.getLogger(OCIContainerRuntime.class);
private static final Pattern HOSTNAME_PATTERN = Pattern.compile(
"^[a-zA-Z0-9][a-zA-Z0-9_.-]+$");
static final Pattern USER_MOUNT_PATTERN = Pattern.compile(
"(?<=^|,)([^:\\x00]+):([^:\\x00]+)" +
"(:(r[ow]|(r[ow][+])?(r?shared|r?slave|r?private)))?(?:,|$)");
static final Pattern TMPFS_MOUNT_PATTERN = Pattern.compile(
"^/[^:\\x00]+$");
static final String PORTS_MAPPING_PATTERN =
"^:[0-9]+|^[0-9]+:[0-9]+|^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]" +
"|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" +
":[0-9]+:[0-9]+$";
private static final int HOST_NAME_LENGTH = 64;
@InterfaceAudience.Private
public static final String RUNTIME_PREFIX = "YARN_CONTAINER_RUNTIME_%s_%s";
@InterfaceAudience.Private
public static final String CONTAINER_PID_NAMESPACE_SUFFIX =
"CONTAINER_PID_NAMESPACE";
@InterfaceAudience.Private
public static final String RUN_PRIVILEGED_CONTAINER_SUFFIX =
"RUN_PRIVILEGED_CONTAINER";
private Map<String, CsiAdaptorProtocol> csiClients = new HashMap<>();
abstract Set<String> getAllowedNetworks();
abstract Set<String> getAllowedRuntimes();
abstract boolean getHostPidNamespaceEnabled();
abstract boolean getPrivilegedContainersEnabledOnCluster();
abstract AccessControlList getPrivilegedContainersAcl();
abstract String getEnvOciContainerPidNamespace();
abstract String getEnvOciContainerRunPrivilegedContainer();
public OCIContainerRuntime(PrivilegedOperationExecutor
privilegedOperationExecutor) {
this(privilegedOperationExecutor, ResourceHandlerModule
.getCGroupsHandler());
}
public OCIContainerRuntime(PrivilegedOperationExecutor
privilegedOperationExecutor, CGroupsHandler cGroupsHandler) {
}
public void initialize(Configuration conf, Context nmContext)
throws ContainerExecutionException {
}
public static boolean isOCICompliantContainerRequested(
Configuration daemonConf, Map<String, String> env) {
return isDockerContainerRequested(daemonConf, env) ||
isRuncContainerRequested(daemonConf, env);
}
@VisibleForTesting
protected String mountReadOnlyPath(String mount,
Map<Path, List<String>> localizedResources)
throws ContainerExecutionException {
for (Map.Entry<Path, List<String>> resource :
localizedResources.entrySet()) {
if (resource.getValue().contains(mount)) {
java.nio.file.Path path = Paths.get(resource.getKey().toString());
if (!path.isAbsolute()) {
throw new ContainerExecutionException("Mount must be absolute: " +
mount);
}
if (Files.isSymbolicLink(path)) {
throw new ContainerExecutionException("Mount cannot be a symlink: " +
mount);
}
return path.toString();
}
}
throw new ContainerExecutionException("Mount must be a localized " +
"resource: " + mount);
}
@Override
public void prepareContainer(ContainerRuntimeContext ctx)
throws ContainerExecutionException {
}
protected String getUserIdInfo(String userName)
throws ContainerExecutionException {
String id;
Shell.ShellCommandExecutor shexec = new Shell.ShellCommandExecutor(
new String[]{"id", "-u", userName});
try {
shexec.execute();
id = shexec.getOutput().replaceAll("[^0-9]", "");
} catch (Exception e) {
throw new ContainerExecutionException(e);
}
return id;
}
protected String[] getGroupIdInfo(String userName)
throws ContainerExecutionException {
String[] id;
Shell.ShellCommandExecutor shexec = new Shell.ShellCommandExecutor(
new String[]{"id", "-G", userName});
try {
shexec.execute();
id = shexec.getOutput().replace("\n", "").split(" ");
} catch (Exception e) {
throw new ContainerExecutionException(e);
}
return id;
}
protected void validateContainerNetworkType(String network)
throws ContainerExecutionException {
Set<String> allowedNetworks = getAllowedNetworks();
if (allowedNetworks.contains(network)) {
return;
}
String msg = "Disallowed network: '" + network
+ "' specified. Allowed networks: are " + allowedNetworks
.toString();
throw new ContainerExecutionException(msg);
}
protected void validateContainerRuntimeType(String runtime)
throws ContainerExecutionException {
Set<String> allowedRuntimes = getAllowedRuntimes();
if (runtime == null || runtime.isEmpty()
|| allowedRuntimes.contains(runtime)) {
return;
}
String msg = "Disallowed runtime: '" + runtime
+ "' specified. Allowed runtimes: are " + allowedRuntimes
.toString();
throw new ContainerExecutionException(msg);
}
/**
* Return whether the YARN container is allowed to run using the host's PID
* namespace for the OCI-compliant container. For this to be allowed, the
* submitting user must request the feature and the feature must be enabled
* on the cluster.
*
* @param container the target YARN container
* @return whether host pid namespace is requested and allowed
* @throws ContainerExecutionException if host pid namespace is requested
* but is not allowed
*/
protected boolean allowHostPidNamespace(Container container)
throws ContainerExecutionException {
Map<String, String> environment = container.getLaunchContext()
.getEnvironment();
String envOciContainerPidNamespace = getEnvOciContainerPidNamespace();
String pidNamespace = environment.get(envOciContainerPidNamespace);
if (pidNamespace == null) {
return false;
}
if (!pidNamespace.equalsIgnoreCase("host")) {
LOG.warn("NOT requesting PID namespace. Value of " +
envOciContainerPidNamespace
+ "is invalid: " + pidNamespace);
return false;
}
boolean hostPidNamespaceEnabled = getHostPidNamespaceEnabled();
if (!hostPidNamespaceEnabled) {
String message = "Host pid namespace being requested but this is not "
+ "enabled on this cluster";
LOG.warn(message);
throw new ContainerExecutionException(message);
}
return true;
}
protected static void validateHostname(String hostname) throws
ContainerExecutionException {
if (hostname != null && !hostname.isEmpty()) {
if (!HOSTNAME_PATTERN.matcher(hostname).matches()) {
throw new ContainerExecutionException("Hostname '" + hostname
+ "' doesn't match OCI-compliant hostname pattern");
}
if (hostname.length() > HOST_NAME_LENGTH) {
throw new ContainerExecutionException(
"Hostname can not be greater than " + HOST_NAME_LENGTH
+ " characters: " + hostname);
}
}
}
/**
* Return whether the YARN container is allowed to run in a privileged
* OCI-compliant container. For a privileged container to be allowed all of
* the following three conditions must be satisfied:
*
* <ol>
* <li>Submitting user must request for a privileged container</li>
* <li>Privileged containers must be enabled on the cluster</li>
* <li>Submitting user must be white-listed to run a privileged
* container</li>
* </ol>
*
* @param container the target YARN container
* @return whether privileged container execution is allowed
* @throws ContainerExecutionException if privileged container execution
* is requested but is not allowed
*/
protected boolean allowPrivilegedContainerExecution(Container container)
throws ContainerExecutionException {
if(!isContainerRequestedAsPrivileged(container)) {
return false;
}
LOG.info("Privileged container requested for : " + container
.getContainerId().toString());
//Ok, so we have been asked to run a privileged container. Security
// checks need to be run. Each violation is an error.
//check if privileged containers are enabled.
boolean privilegedContainersEnabledOnCluster =
getPrivilegedContainersEnabledOnCluster();
if (!privilegedContainersEnabledOnCluster) {
String message = "Privileged container being requested but privileged "
+ "containers are not enabled on this cluster";
LOG.warn(message);
throw new ContainerExecutionException(message);
}
//check if submitting user is in the whitelist.
String submittingUser = container.getUser();
UserGroupInformation submitterUgi = UserGroupInformation
.createRemoteUser(submittingUser);
if (!getPrivilegedContainersAcl().isUserAllowed(submitterUgi)) {
String message = "Cannot launch privileged container. Submitting user ("
+ submittingUser + ") fails ACL check.";
LOG.warn(message);
throw new ContainerExecutionException(message);
}
LOG.info("All checks pass. Launching privileged container for : "
+ container.getContainerId().toString());
return true;
}
/**
* This function only returns whether a privileged container was requested,
* not whether the container was or will be launched as privileged.
* @param container
* @return true if container is requested as privileged
*/
protected boolean isContainerRequestedAsPrivileged(
Container container) {
String envOciContainerRunPrivilegedContainer =
getEnvOciContainerRunPrivilegedContainer();
String runPrivilegedContainerEnvVar = container.getLaunchContext()
.getEnvironment().get(envOciContainerRunPrivilegedContainer);
return Boolean.parseBoolean(runPrivilegedContainerEnvVar);
}
public Map<String, CsiAdaptorProtocol> getCsiClients() {
return csiClients;
}
/**
* Initiate CSI clients to talk to the CSI adaptors on this node and
* cache the clients for easier fetch.
* @param config configuration
* @throws ContainerExecutionException
*/
protected void initiateCsiClients(Configuration config)
throws ContainerExecutionException {
String[] driverNames = CsiConfigUtils.getCsiDriverNames(config);
if (driverNames != null && driverNames.length > 0) {
for (String driverName : driverNames) {
try {
// find out the adaptors service address
InetSocketAddress adaptorServiceAddress =
CsiConfigUtils.getCsiAdaptorAddressForDriver(driverName, config);
LOG.info("Initializing a csi-adaptor-client for csi-adaptor {},"
+ " csi-driver {}", adaptorServiceAddress.toString(), driverName);
CsiAdaptorProtocolPBClientImpl client =
new CsiAdaptorProtocolPBClientImpl(1L, adaptorServiceAddress,
config);
csiClients.put(driverName, client);
} catch (IOException | YarnException e1) {
throw new ContainerExecutionException(e1.getMessage());
}
}
}
}
public static String formatOciEnvKey(String runtimeTypeUpper,
String envKeySuffix) {
return String.format(RUNTIME_PREFIX, runtimeTypeUpper, envKeySuffix);
}
}
| OCIContainerRuntime |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/ClosedManagerTests.java | {
"start": 601,
"end": 4095
} | class ____ extends AbstractJPATest {
@Override
protected void applySettings(StandardServiceRegistryBuilder builder) {
super.applySettings( builder );
builder.applySetting( AvailableSettings.JPA_CLOSED_COMPLIANCE, "true" );
}
@Test
public void testQuerySetMaxResults() {
final Session session = sessionFactory().openSession();
final Query qry;
try {
qry = session.createQuery( "select i from Item i" );
}
finally {
session.close();
}
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try {
qry.setMaxResults( 1 );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
}
@Test
public void testQuerySetFirstResult() {
final Session session = sessionFactory().openSession();
final Query qry;
try {
qry = session.createQuery( "select i from Item i" );
}
finally {
session.close();
}
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try {
qry.setFirstResult( 1 );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
}
@Test
public void testQuerySetPositionalParameter() {
final Session session = sessionFactory().openSession();
final Query qry;
try {
qry = session.createQuery( "select i from Item i where i.id = ?1" );
}
finally {
session.close();
}
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try {
qry.setParameter( 1, 1 );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
}
@Test
public void testQuerySetNamedParameter() {
final Session session = sessionFactory().openSession();
final Query qry;
try {
qry = session.createQuery( "select i from Item i where i.id = :id" );
}
finally {
session.close();
}
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try {
qry.setParameter( "id", 1 );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
}
@Test
public void testQueryGetPositionalParameter() {
final Session session = sessionFactory().openSession();
final Query qry;
try {
qry = session.createQuery( "select i from Item i where i.id = ?1" );
qry.setParameter( 1, 1 );
}
finally {
session.close();
}
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try {
qry.getParameter( 1 );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
try {
qry.getParameter( 1, Integer.class );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
}
@Test
public void testQueryGetNamedParameter() {
final Session session = sessionFactory().openSession();
final Query qry;
try {
qry = session.createQuery( "select i from Item i where i.id = :id" );
qry.setParameter( "id", 1 );
}
finally {
session.close();
}
assertThat( session.isOpen(), CoreMatchers.is( false ) );
try {
qry.getParameter( "id" );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
try {
qry.getParameter( "id", Long.class );
fail( "Expecting call to fail" );
}
catch (IllegalStateException expected) {
}
}
@Test
public void testClose() {
final Session session = sessionFactory().openSession();
// 1st call - should be ok
session.close();
try {
// 2nd should fail (JPA compliance enabled)
session.close();
fail();
}
catch (IllegalStateException expected) {
// expected outcome
}
}
}
| ClosedManagerTests |
java | quarkusio__quarkus | extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/stream/XTrimArgs.java | {
"start": 259,
"end": 2697
} | class ____ implements RedisCommandExtraArguments {
private long maxlen = -1;
private boolean approximateTrimming;
private String minid;
private long limit = -1;
/**
* Sets the max length of the stream.
*
* @param maxlen the max length of the stream, must be positive
* @return the current {@code XAddArgs}
*/
public XTrimArgs maxlen(long maxlen) {
this.maxlen = maxlen;
return this;
}
/**
* When set, prefix the {@link #maxlen} with {@code ~} to enable the <em>almost exact trimming</em>.
* This is recommended when using {@link #maxlen(long)}.
*
* @return the current {@code XAddArgs}
*/
public XTrimArgs nearlyExactTrimming() {
this.approximateTrimming = true;
return this;
}
/**
* Evicts entries from the stream having IDs lower to the specified one.
*
* @param minid the min id, must not be {@code null}, must be a valid stream id
* @return the current {@code XAddArgs}
*/
public XTrimArgs minid(String minid) {
this.minid = minid;
return this;
}
/**
* Sets the maximum entries that can get evicted.
*
* @param limit the limit, must be positive
* @return the current {@code XAddArgs}
*/
public XTrimArgs limit(long limit) {
this.limit = limit;
return this;
}
@Override
public List<Object> toArgs() {
List<Object> args = new ArrayList<>();
if (maxlen >= 0) {
if (minid != null) {
throw new IllegalArgumentException("Cannot use `MAXLEN` and `MINID` together");
}
args.add("MAXLEN");
if (approximateTrimming) {
args.add("~");
} else {
args.add("=");
}
args.add(Long.toString(maxlen));
}
if (minid != null) {
args.add("MINID");
if (approximateTrimming) {
args.add("~");
} else {
args.add("=");
}
args.add(minid);
}
if (limit > 0) {
if (!approximateTrimming) {
throw new IllegalArgumentException("Cannot set the eviction limit when using exact trimming");
}
args.add("LIMIT");
args.add(Long.toString(limit));
}
return args;
}
}
| XTrimArgs |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/CoordinationRequestGateway.java | {
"start": 927,
"end": 1080
} | interface ____ sends out a {@link CoordinationRequest} and expects for a {@link
* CoordinationResponse} from a {@link OperatorCoordinator}.
*/
public | which |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/TestableKeyedStateBackend.java | {
"start": 924,
"end": 993
} | interface ____ internal testing purpose. */
@VisibleForTesting
public | for |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitch.java | {
"start": 6105,
"end": 14804
} | enum ____ for 'UNRECOGNIZED'.
return fixUnrecognized(switchTree, defaultCase, state);
}
if (!unhandledCases.isEmpty()) {
// switch is non-exhaustive, default can stay.
return NO_MATCH;
}
if (isDefaultCaseForSkew(switchTree, defaultCase, state)) {
// default is explicitly commented as being present for skew, it can stay.
return NO_MATCH;
}
// switch is exhaustive, remove the default if we can.
return fixDefault(switchTree, caseBeforeDefault, defaultCase, state);
}
private Description fixDefault(
SwitchTree switchTree, CaseTree caseBeforeDefault, CaseTree defaultCase, VisitorState state) {
List<? extends StatementTree> defaultStatements = defaultCase.getStatements();
if (defaultStatements == null) {
SuggestedFix fix = SuggestedFix.delete(defaultCase);
return compilesWithFix(fix, state)
? buildDescription(defaultCase)
.setMessage(DESCRIPTION_REMOVED_DEFAULT)
.addFix(fix)
.build()
: NO_MATCH;
}
if (trivialDefault(defaultStatements)) {
// deleting `default:` or `default: break;` is a no-op
return buildDescription(defaultCase)
.setMessage(DESCRIPTION_REMOVED_DEFAULT)
.addFix(SuggestedFix.delete(defaultCase))
.build();
}
String defaultContents = getDefaultCaseContents(defaultCase, defaultStatements, state);
if (!canCompleteNormally(switchTree)) {
// if the switch statement cannot complete normally, then deleting the default
// and moving its statements to after the switch statement is a no-op
SuggestedFix fix =
SuggestedFix.builder()
.postfixWith(switchTree, defaultContents)
.delete(defaultCase)
.build();
return buildDescription(defaultCase)
.setMessage(DESCRIPTION_MOVED_DEFAULT)
.addFix(fix)
.build();
}
// The switch is already exhaustive, we want to delete the default.
// There are a few modes we need to handle:
// 1) switch (..) {
// case FOO:
// default: doWork();
// }
// In this mode, we need to lift the statements from 'default' into FOO, otherwise
// we change the code. This mode also captures any variation of statements in FOO
// where any of them would fall-through (e.g, if (!bar) { break; } ) -- if bar is
// true then we'd fall through.
//
// 2) switch (..) {
// case FOO: break;
// default: doDefault();
// }
// In this mode, we can safely delete 'default'.
//
// 3) var x;
// switch (..) {
// case FOO: x = 1; break;
// default: x = 2;
// }
// doWork(x);
// In this mode, we can't delete 'default' because javac analysis requires that 'x'
// must be set before using it.
// To solve this, we take the approach of:
// Try deleting the code entirely. If it fails to compile, we've broken (3) -> no match.
// Try lifting the code to the prior case statement. If it fails to compile, we had (2)
// and the code is unreachable -- so use (2) as the strategy. Otherwise, use (1).
if (!compilesWithFix(SuggestedFix.delete(defaultCase), state)) {
return NO_MATCH; // case (3)
}
if (!canFallThrough(caseBeforeDefault)) {
// case (2) -- If the case before the default can't fall through,
// it's OK to to delete the default.
return buildDescription(defaultCase)
.setMessage(DESCRIPTION_REMOVED_DEFAULT)
.addFix(SuggestedFix.delete(defaultCase))
.build();
}
// case (1) -- If it can complete, we need to merge the default into it.
SuggestedFix.Builder fix = SuggestedFix.builder().delete(defaultCase);
fix.postfixWith(caseBeforeDefault, defaultContents);
return buildDescription(defaultCase)
.setMessage(DESCRIPTION_REMOVED_DEFAULT)
.addFix(fix.build())
.build();
}
private Description fixUnrecognized(
SwitchTree switchTree, CaseTree defaultCase, VisitorState state) {
List<? extends StatementTree> defaultStatements = defaultCase.getStatements();
Description.Builder unrecognizedDescription =
buildDescription(defaultCase).setMessage(DESCRIPTION_UNRECOGNIZED);
if (defaultStatements == null) {
SuggestedFix fix =
SuggestedFix.replace(defaultCase.getLabels().getFirst(), "case UNRECOGNIZED");
return compilesWithFix(fix, state) ? unrecognizedDescription.addFix(fix).build() : NO_MATCH;
}
if (trivialDefault(defaultStatements)) {
// the default case is empty or contains only `break` -- replace it with `case UNRECOGNIZED:`
// with fall out.
SuggestedFix fix =
SuggestedFix.replace(defaultCase, "case UNRECOGNIZED: \n // continue below");
return unrecognizedDescription.addFix(fix).build();
}
String defaultContents = getDefaultCaseContents(defaultCase, defaultStatements, state);
if (!canCompleteNormally(switchTree)) {
// the switch statement cannot complete normally -- replace default with
// `case UNRECOGNIZED: break;` and move content of default case to after the switch tree.
SuggestedFix fix =
SuggestedFix.builder()
.replace(defaultCase, "case UNRECOGNIZED: \n break;")
.postfixWith(switchTree, defaultContents)
.build();
return unrecognizedDescription.addFix(fix).build();
}
SuggestedFix fix = SuggestedFix.replace(defaultCase, "case UNRECOGNIZED:" + defaultContents);
if (!compilesWithFix(fix, state)) {
// code in the default case can't be deleted -- no fix available.
return NO_MATCH;
}
// delete default and move its contents into `UNRECOGNIZED` case.
return unrecognizedDescription.addFix(fix).build();
}
/** Returns true if the default is empty, or contains only a break statement. */
private static boolean trivialDefault(List<? extends StatementTree> defaultStatements) {
if (defaultStatements.isEmpty()) {
return true;
}
return (defaultStatements.size() == 1
&& getOnlyElement(defaultStatements) instanceof BreakTree);
}
private static SetView<String> unhandledCases(SwitchTree tree, TypeSymbol switchType) {
return unhandledCases(tree.getCases(), switchType);
}
private static SetView<String> unhandledCases(
List<? extends CaseTree> cases, TypeSymbol switchType) {
ImmutableSet<String> handledCases =
cases.stream()
.flatMap(e -> e.getExpressions().stream())
.filter(IdentifierTree.class::isInstance)
.map(p -> ((IdentifierTree) p).getName().toString())
.collect(toImmutableSet());
return Sets.difference(ASTHelpers.enumValues(switchType), handledCases);
}
private static String getDefaultCaseContents(
CaseTree defaultCase, List<? extends StatementTree> defaultStatements, VisitorState state) {
CharSequence sourceCode = state.getSourceCode();
if (sourceCode == null) {
return "";
}
String defaultSource =
sourceCode
.subSequence(
getStartPosition(defaultStatements.getFirst()),
state.getEndPosition(getLast(defaultStatements)))
.toString();
String initialComments = comments(defaultCase, defaultStatements, sourceCode);
return initialComments + defaultSource;
}
/** Returns the comments between the "default:" case and the first statement within it, if any. */
private static String comments(
CaseTree defaultCase,
List<? extends StatementTree> defaultStatements,
CharSequence sourceCode) {
// If there are no statements, then there can be no comments that we strip,
// because comments are attached to the statements, not the "default:" case.
if (defaultStatements.isEmpty()) {
return "";
}
// To extract the comments, we have to get the source code from
// "default:" to the first statement, and then strip off "default:", because
// we have no way of identifying the end position of just the "default:" statement.
int defaultStart = getStartPosition(defaultCase);
int statementStart = getStartPosition(defaultStatements.getFirst());
String defaultAndComments = sourceCode.subSequence(defaultStart, statementStart).toString();
String comments =
defaultAndComments
.substring(defaultAndComments.indexOf("default:") + "default:".length())
.trim();
if (!comments.isEmpty()) {
comments = "\n" + comments + "\n";
}
return comments;
}
}
| except |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/transform/AnnotationVisitorTee.java | {
"start": 771,
"end": 2031
} | class ____ extends AnnotationVisitor {
private AnnotationVisitor av1, av2;
public static AnnotationVisitor getInstance(AnnotationVisitor av1, AnnotationVisitor av2) {
if (av1 == null) {
return av2;
}
if (av2 == null) {
return av1;
}
return new AnnotationVisitorTee(av1, av2);
}
public AnnotationVisitorTee(AnnotationVisitor av1, AnnotationVisitor av2) {
super(Constants.ASM_API);
this.av1 = av1;
this.av2 = av2;
}
@Override
public void visit(String name, Object value) {
av2.visit(name, value);
av2.visit(name, value);
}
@Override
public void visitEnum(String name, String desc, String value) {
av1.visitEnum(name, desc, value);
av2.visitEnum(name, desc, value);
}
@Override
public AnnotationVisitor visitAnnotation(String name, String desc) {
return getInstance(av1.visitAnnotation(name, desc),
av2.visitAnnotation(name, desc));
}
@Override
public AnnotationVisitor visitArray(String name) {
return getInstance(av1.visitArray(name), av2.visitArray(name));
}
@Override
public void visitEnd() {
av1.visitEnd();
av2.visitEnd();
}
}
| AnnotationVisitorTee |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/security/token/SQLSecretManagerRetriableHandler.java | {
"start": 1448,
"end": 1639
} | interface ____ {
void execute(SQLCommandVoid command) throws SQLException;
<T> T execute(SQLCommand<T> command) throws SQLException;
@FunctionalInterface
| SQLSecretManagerRetriableHandler |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/FlinkFilterProjectTransposeRule.java | {
"start": 1505,
"end": 2506
} | class ____ extends FilterProjectTransposeRule {
public static final RelOptRule INSTANCE = new FlinkFilterProjectTransposeRule(Config.DEFAULT);
public static FlinkFilterProjectTransposeRule build(Config config) {
return new FlinkFilterProjectTransposeRule(config);
}
protected FlinkFilterProjectTransposeRule(Config config) {
super(config);
}
@Override
public void onMatch(RelOptRuleCall call) {
Filter filter = call.rel(0);
Project project = call.rel(1);
List<RexNode> projects = project.getProjects();
InputRefVisitor inputRefVisitor = new InputRefVisitor();
filter.getCondition().accept(inputRefVisitor);
boolean existNonDeterministicRef =
Arrays.stream(inputRefVisitor.getFields())
.anyMatch(i -> !RexUtil.isDeterministic(projects.get(i)));
if (!existNonDeterministicRef) {
super.onMatch(call);
}
}
}
| FlinkFilterProjectTransposeRule |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java | {
"start": 61186,
"end": 61990
} | class ____ {
private final Object actual = AtomicLongFieldUpdater.newUpdater(Container.class, "longField");
@Test
void createAssert() {
// WHEN
AtomicLongFieldUpdaterAssert<Object> result = ATOMIC_LONG_FIELD_UPDATER.createAssert(actual);
// THEN
result.hasValue(0L, new Container());
}
@Test
void createAssert_with_ValueProvider() {
// GIVEN
ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual);
// WHEN
AtomicLongFieldUpdaterAssert<Object> result = ATOMIC_LONG_FIELD_UPDATER.createAssert(valueProvider);
// THEN
result.hasValue(0L, new Container());
verify(valueProvider).apply(parameterizedType(AtomicLongFieldUpdater.class, Object.class));
}
private static | AtomicLongFieldUpdater_Factory |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/support/hsf/HSFJSONUtils.java | {
"start": 380,
"end": 4546
} | class ____ {
final static SymbolTable typeSymbolTable = new SymbolTable(1024);
final static char[] fieldName_argsTypes = "\"argsTypes\"".toCharArray();
final static char[] fieldName_argsObjs = "\"argsObjs\"".toCharArray();
final static char[] fieldName_type = "\"@type\":".toCharArray();
public static Object[] parseInvocationArguments(String json, MethodLocator methodLocator) {
DefaultJSONParser parser = new DefaultJSONParser(json);
JSONLexerBase lexer = (JSONLexerBase) parser.getLexer();
ParseContext rootContext = parser.setContext(null, null);
Object[] values;
int token = lexer.token();
if (token == JSONToken.LBRACE) {
String[] typeNames = lexer.scanFieldStringArray(fieldName_argsTypes, -1, typeSymbolTable);
if (typeNames == null && lexer.matchStat == NOT_MATCH_NAME) {
String type = lexer.scanFieldString(fieldName_type);
if ("com.alibaba.fastjson.JSONObject".equals(type)) {
typeNames = lexer.scanFieldStringArray(fieldName_argsTypes, -1, typeSymbolTable);
}
}
Method method = methodLocator.findMethod(typeNames);
if (method == null) {
lexer.close();
JSONObject jsonObject = JSON.parseObject(json);
typeNames = jsonObject.getObject("argsTypes", String[].class);
method = methodLocator.findMethod(typeNames);
JSONArray argsObjs = jsonObject.getJSONArray("argsObjs");
if (argsObjs == null) {
values = null;
} else {
Type[] argTypes = method.getGenericParameterTypes();
values = new Object[argTypes.length];
for (int i = 0; i < argTypes.length; i++) {
Type type = argTypes[i];
values[i] = argsObjs.getObject(i, type);
}
}
} else {
Type[] argTypes = method.getGenericParameterTypes();
lexer.skipWhitespace();
if (lexer.getCurrent() == ',') {
lexer.next();
}
if (lexer.matchField2(fieldName_argsObjs)) {
lexer.nextToken();
ParseContext context = parser.setContext(rootContext, null, "argsObjs");
values = parser.parseArray(argTypes);
context.object = values;
parser.accept(JSONToken.RBRACE);
parser.handleResovleTask(null);
} else {
values = null;
}
parser.close();
}
} else if (token == JSONToken.LBRACKET) {
String[] typeNames = lexer.scanFieldStringArray(null, -1, typeSymbolTable);
lexer.skipWhitespace();
char ch = lexer.getCurrent();
if (ch == ']') {
Method method = methodLocator.findMethod(null);
Type[] argTypes = method.getGenericParameterTypes();
values = new Object[typeNames.length];
for (int i = 0; i < typeNames.length; ++i) {
Type argType = argTypes[i];
String typeName = typeNames[i];
if (argType != String.class) {
values[i] = TypeUtils.cast(typeName, argType, parser.getConfig());
} else {
values[i] = typeName;
}
}
return values;
}
if (ch == ',') {
lexer.next();
lexer.skipWhitespace();
}
lexer.nextToken(JSONToken.LBRACKET);
Method method = methodLocator.findMethod(typeNames);
Type[] argTypes = method.getGenericParameterTypes();
values = parser.parseArray(argTypes);
lexer.close();
} else {
values = null;
}
return values;
}
}
| HSFJSONUtils |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java | {
"start": 4163,
"end": 4361
} | class ____ {
private @Nullable String name;
public @Nullable String getName() {
return this.name;
}
public void setName(@Nullable String name) {
this.name = name;
}
}
}
| ExampleBean |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketRequestValues.java | {
"start": 3861,
"end": 6507
} | class ____ {
private @Nullable String route;
private @Nullable List<Object> routeVariables;
private @Nullable MetadataHelper metadataHelper;
private @Nullable Object payloadValue;
private @Nullable Publisher<?> payload;
private @Nullable ParameterizedTypeReference<?> payloadElementType;
Builder(@Nullable String route) {
this.route = (StringUtils.hasText(route) ? route : null);
}
/**
* Set the route for the request.
*/
public Builder setRoute(String route) {
this.route = route;
this.routeVariables = null;
return this;
}
/**
* Add a route variable.
*/
public Builder addRouteVariable(Object variable) {
this.routeVariables = (this.routeVariables != null ? this.routeVariables : new ArrayList<>());
this.routeVariables.add(variable);
return this;
}
/**
* Add a metadata entry.
* This must be followed by a corresponding call to {@link #addMimeType(MimeType)}.
*/
public Builder addMetadata(Object metadata) {
this.metadataHelper = (this.metadataHelper != null ? this.metadataHelper : new MetadataHelper());
this.metadataHelper.addMetadata(metadata);
return this;
}
/**
* Set the mime type for a metadata entry.
* This must be preceded by a call to {@link #addMetadata(Object)}.
*/
public Builder addMimeType(MimeType mimeType) {
this.metadataHelper = (this.metadataHelper != null ? this.metadataHelper : new MetadataHelper());
this.metadataHelper.addMimeType(mimeType);
return this;
}
/**
* Set the request payload as a concrete value to be serialized.
* <p>This is mutually exclusive with, and resets any previously set
* {@linkplain #setPayload(Publisher, ParameterizedTypeReference) payload Publisher}.
*/
public Builder setPayloadValue(Object payloadValue) {
this.payloadValue = payloadValue;
this.payload = null;
this.payloadElementType = null;
return this;
}
/**
* Set the request payload value to be serialized.
*/
public <T, P extends Publisher<T>> Builder setPayload(P payload, ParameterizedTypeReference<T> elementTye) {
this.payload = payload;
this.payloadElementType = elementTye;
this.payloadValue = null;
return this;
}
/**
* Build the {@link RSocketRequestValues} instance.
*/
public RSocketRequestValues build() {
return new RSocketRequestValues(
this.route, this.routeVariables, this.metadataHelper,
this.payloadValue, this.payload, this.payloadElementType);
}
}
/**
* Class that helps to collect a map of metadata entries as a series of calls
* to provide each metadata and mime type pair.
*/
private static | Builder |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/secrets/action/DeleteConnectorSecretAction.java | {
"start": 377,
"end": 667
} | class ____ {
public static final String NAME = "cluster:admin/xpack/connector/secret/delete";
public static final ActionType<DeleteConnectorSecretResponse> INSTANCE = new ActionType<>(NAME);
private DeleteConnectorSecretAction() {/* no instances */}
}
| DeleteConnectorSecretAction |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/topn/DefaultUnsortableTopNEncoder.java | {
"start": 644,
"end": 7228
} | class ____ implements TopNEncoder {
public static final VarHandle LONG = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder());
public static final VarHandle INT = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.nativeOrder());
public static final VarHandle FLOAT = MethodHandles.byteArrayViewVarHandle(float[].class, ByteOrder.nativeOrder());
public static final VarHandle DOUBLE = MethodHandles.byteArrayViewVarHandle(double[].class, ByteOrder.nativeOrder());
@Override
public void encodeLong(long value, BreakingBytesRefBuilder bytesRefBuilder) {
bytesRefBuilder.grow(bytesRefBuilder.length() + Long.BYTES);
LONG.set(bytesRefBuilder.bytes(), bytesRefBuilder.length(), value);
bytesRefBuilder.setLength(bytesRefBuilder.length() + Long.BYTES);
}
@Override
public long decodeLong(BytesRef bytes) {
if (bytes.length < Long.BYTES) {
throw new IllegalArgumentException("not enough bytes");
}
long v = (long) LONG.get(bytes.bytes, bytes.offset);
bytes.offset += Long.BYTES;
bytes.length -= Long.BYTES;
return v;
}
/**
* Writes an int in a variable-length format. Writes between one and
* five bytes. Smaller values take fewer bytes. Negative numbers
* will always use all 5 bytes.
*/
public void encodeVInt(int value, BreakingBytesRefBuilder bytesRefBuilder) {
while ((value & ~0x7F) != 0) {
bytesRefBuilder.append(((byte) ((value & 0x7f) | 0x80)));
value >>>= 7;
}
bytesRefBuilder.append((byte) value);
}
/**
* Reads an int stored in variable-length format. Reads between one and
* five bytes. Smaller values take fewer bytes. Negative numbers
* will always use all 5 bytes.
*/
public int decodeVInt(BytesRef bytes) {
/*
* The loop for this is unrolled because we unrolled the loop in StreamInput.
* I presume it's a decent choice here because it was a good choice there.
*/
byte b = bytes.bytes[bytes.offset];
if (b >= 0) {
bytes.offset += 1;
bytes.length -= 1;
return b;
}
int i = b & 0x7F;
b = bytes.bytes[bytes.offset + 1];
i |= (b & 0x7F) << 7;
if (b >= 0) {
bytes.offset += 2;
bytes.length -= 2;
return i;
}
b = bytes.bytes[bytes.offset + 2];
i |= (b & 0x7F) << 14;
if (b >= 0) {
bytes.offset += 3;
bytes.length -= 3;
return i;
}
b = bytes.bytes[bytes.offset + 3];
i |= (b & 0x7F) << 21;
if (b >= 0) {
bytes.offset += 4;
bytes.length -= 4;
return i;
}
b = bytes.bytes[bytes.offset + 4];
i |= (b & 0x0F) << 28;
if ((b & 0xF0) != 0) {
throw new IllegalStateException("Invalid last byte for a vint [" + Integer.toHexString(b) + "]");
}
bytes.offset += 5;
bytes.length -= 5;
return i;
}
@Override
public void encodeInt(int value, BreakingBytesRefBuilder bytesRefBuilder) {
bytesRefBuilder.grow(bytesRefBuilder.length() + Integer.BYTES);
INT.set(bytesRefBuilder.bytes(), bytesRefBuilder.length(), value);
bytesRefBuilder.setLength(bytesRefBuilder.length() + Integer.BYTES);
}
@Override
public int decodeInt(BytesRef bytes) {
if (bytes.length < Integer.BYTES) {
throw new IllegalArgumentException("not enough bytes");
}
int v = (int) INT.get(bytes.bytes, bytes.offset);
bytes.offset += Integer.BYTES;
bytes.length -= Integer.BYTES;
return v;
}
@Override
public void encodeFloat(float value, BreakingBytesRefBuilder bytesRefBuilder) {
bytesRefBuilder.grow(bytesRefBuilder.length() + Float.BYTES);
FLOAT.set(bytesRefBuilder.bytes(), bytesRefBuilder.length(), value);
bytesRefBuilder.setLength(bytesRefBuilder.length() + Float.BYTES);
}
@Override
public float decodeFloat(BytesRef bytes) {
if (bytes.length < Float.BYTES) {
throw new IllegalArgumentException("not enough bytes");
}
float v = (float) FLOAT.get(bytes.bytes, bytes.offset);
bytes.offset += Float.BYTES;
bytes.length -= Float.BYTES;
return v;
}
@Override
public void encodeDouble(double value, BreakingBytesRefBuilder bytesRefBuilder) {
bytesRefBuilder.grow(bytesRefBuilder.length() + Double.BYTES);
DOUBLE.set(bytesRefBuilder.bytes(), bytesRefBuilder.length(), value);
bytesRefBuilder.setLength(bytesRefBuilder.length() + Double.BYTES);
}
@Override
public double decodeDouble(BytesRef bytes) {
if (bytes.length < Double.BYTES) {
throw new IllegalArgumentException("not enough bytes");
}
double v = (double) DOUBLE.get(bytes.bytes, bytes.offset);
bytes.offset += Double.BYTES;
bytes.length -= Double.BYTES;
return v;
}
@Override
public void encodeBoolean(boolean value, BreakingBytesRefBuilder bytesRefBuilder) {
bytesRefBuilder.append(value ? (byte) 1 : (byte) 0);
}
@Override
public boolean decodeBoolean(BytesRef bytes) {
if (bytes.length < Byte.BYTES) {
throw new IllegalArgumentException("not enough bytes");
}
boolean v = bytes.bytes[bytes.offset] == 1;
bytes.offset += Byte.BYTES;
bytes.length -= Byte.BYTES;
return v;
}
@Override
public int encodeBytesRef(BytesRef value, BreakingBytesRefBuilder bytesRefBuilder) {
final int offset = bytesRefBuilder.length();
encodeVInt(value.length, bytesRefBuilder);
bytesRefBuilder.append(value);
return bytesRefBuilder.length() - offset;
}
@Override
public BytesRef decodeBytesRef(BytesRef bytes, BytesRef scratch) {
final int len = decodeVInt(bytes);
scratch.bytes = bytes.bytes;
scratch.offset = bytes.offset;
scratch.length = len;
bytes.offset += len;
bytes.length -= len;
return scratch;
}
@Override
public TopNEncoder toSortable() {
return TopNEncoder.DEFAULT_SORTABLE;
}
@Override
public TopNEncoder toUnsortable() {
return this;
}
@Override
public String toString() {
return "DefaultUnsortable";
}
}
| DefaultUnsortableTopNEncoder |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/LocalRecoveryConfig.java | {
"start": 1246,
"end": 3292
} | class ____ {
public static final LocalRecoveryConfig BACKUP_AND_RECOVERY_DISABLED =
new LocalRecoveryConfig(false, false, null);
/** Whether to recover from the local snapshot. */
private final boolean localRecoveryEnabled;
/** Whether to do backup checkpoint on local disk. */
private final boolean localBackupEnabled;
/** Encapsulates the root directories and the subtask-specific path. */
@Nullable private final LocalSnapshotDirectoryProvider localStateDirectories;
public LocalRecoveryConfig(
boolean localRecoveryEnabled,
boolean localBackupEnabled,
@Nullable LocalSnapshotDirectoryProvider directoryProvider) {
this.localRecoveryEnabled = localRecoveryEnabled;
this.localBackupEnabled = localBackupEnabled;
this.localStateDirectories = directoryProvider;
}
public boolean isLocalRecoveryEnabled() {
return localRecoveryEnabled;
}
public boolean isLocalBackupEnabled() {
return localBackupEnabled;
}
public boolean isLocalRecoveryOrLocalBackupEnabled() {
return localRecoveryEnabled || localBackupEnabled;
}
public Optional<LocalSnapshotDirectoryProvider> getLocalStateDirectoryProvider() {
return Optional.ofNullable(localStateDirectories);
}
@Override
public String toString() {
return "LocalRecoveryConfig{" + "localStateDirectories=" + localStateDirectories + '}';
}
public static Supplier<IllegalStateException> localRecoveryNotEnabled() {
return () ->
new IllegalStateException(
"Getting a LocalRecoveryDirectoryProvider is only supported with the local recovery enabled. This is a bug and should be reported.");
}
public static LocalRecoveryConfig backupAndRecoveryEnabled(
@Nonnull LocalSnapshotDirectoryProvider directoryProvider) {
return new LocalRecoveryConfig(true, true, Preconditions.checkNotNull(directoryProvider));
}
}
| LocalRecoveryConfig |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/boot/models/xml/complete/Name.java | {
"start": 193,
"end": 253
} | class ____ {
private String first;
private String last;
}
| Name |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/FirstValueAggFunctionWithoutOrderTest.java | {
"start": 10130,
"end": 10806
} | class ____<T>
extends FirstValueAggFunctionWithoutOrderTestBase<T> {
protected abstract T getValue(String v);
@Override
protected List<List<T>> getInputValueSets() {
return Arrays.asList(
Arrays.asList(getValue("1"), null, getValue("-99"), getValue("3"), null),
Arrays.asList(null, null, null, null),
Arrays.asList(null, getValue("10"), null, getValue("3")));
}
@Override
protected List<T> getExpectedResults() {
return Arrays.asList(getValue("1"), null, getValue("10"));
}
}
}
| NumberFirstValueAggFunctionWithoutOrderTest |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/ClassUtils.java | {
"start": 7855,
"end": 8278
} | class ____ corresponding to the Class objects, {@code null} if null input.
* @throws ClassCastException if {@code classes} contains a non-{@link Class} entry.
*/
public static List<String> convertClassesToClassNames(final List<Class<?>> classes) {
return classes == null ? null : classes.stream().map(e -> getName(e, null)).collect(Collectors.toList());
}
/**
* Given a {@link List} of | names |
java | square__retrofit | retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/AsyncTest.java | {
"start": 1995,
"end": 6608
} | interface ____ {
@GET("/")
Completable completable();
}
private Service service;
private final List<Throwable> uncaughtExceptions = new ArrayList<>();
@Before
public void setUp() {
ExecutorService executorService =
Executors.newCachedThreadPool(
r -> {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler((t, e) -> uncaughtExceptions.add(e));
return thread;
});
OkHttpClient client =
new OkHttpClient.Builder().dispatcher(new Dispatcher(executorService)).build();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.client(client)
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build();
service = retrofit.create(Service.class);
}
@After
public void tearDown() {
assertTrue("Uncaught exceptions: " + uncaughtExceptions, uncaughtExceptions.isEmpty());
}
@Test
public void success() throws InterruptedException {
TestObserver<Void> observer = new TestObserver<>();
service.completable().subscribe(observer);
assertFalse(observer.await(1, SECONDS));
server.enqueue(new MockResponse());
observer.await(1, SECONDS);
observer.assertComplete();
}
@Test
public void failure() throws InterruptedException {
TestObserver<Void> observer = new TestObserver<>();
service.completable().subscribe(observer);
assertFalse(observer.await(1, SECONDS));
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
observer.await(1, SECONDS);
observer.assertError(IOException.class);
}
@Test
public void throwingInOnCompleteDeliveredToPlugin() throws InterruptedException {
server.enqueue(new MockResponse());
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
latch.countDown();
});
TestObserver<Void> observer = new TestObserver<>();
final RuntimeException e = new RuntimeException();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onComplete() {
throw e;
}
});
latch.await(1, SECONDS);
assertThat(errorRef.get()).hasCauseThat().isSameInstanceAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() throws InterruptedException {
server.enqueue(new MockResponse().setResponseCode(404));
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!pluginRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
latch.countDown();
});
TestObserver<Void> observer = new TestObserver<>();
final RuntimeException e = new RuntimeException();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onError(Throwable throwable) {
errorRef.set(throwable);
throw e;
}
});
latch.await(1, SECONDS);
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) pluginRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void bodyThrowingFatalInOnErrorPropagates() throws InterruptedException {
server.enqueue(new MockResponse().setResponseCode(404));
final CountDownLatch latch = new CountDownLatch(1);
TestObserver<Void> observer = new TestObserver<>();
final Error e = new OutOfMemoryError("Not real");
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onError(Throwable throwable) {
throw e;
}
});
latch.await(1, SECONDS);
assertEquals(1, uncaughtExceptions.size());
assertSame(e, uncaughtExceptions.remove(0));
}
}
| Service |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/Percentile.java | {
"start": 2284,
"end": 7443
} | class ____ extends NumericAggregate implements SurrogateExpression {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(
Expression.class,
"Percentile",
Percentile::new
);
private final Expression percentile;
@FunctionInfo(
returnType = "double",
description = "Returns the value at which a certain percentage of observed values occur. "
+ "For example, the 95th percentile is the value which is greater than 95% of the "
+ "observed values and the 50th percentile is the `MEDIAN`.",
appendix = """
### `PERCENTILE` is (usually) approximate [esql-percentile-approximate]
:::{include} /reference/aggregations/_snippets/search-aggregations-metrics-percentile-aggregation-approximate.md
:::
::::{warning}
`PERCENTILE` is also {wikipedia}/Nondeterministic_algorithm[non-deterministic].
This means you can get slightly different results using the same data.
::::""",
type = FunctionType.AGGREGATE,
examples = {
@Example(file = "stats_percentile", tag = "percentile"),
@Example(
description = "The expression can use inline functions. For example, to calculate a percentile "
+ "of the maximum values of a multivalued column, first use `MV_MAX` to get the "
+ "maximum value per row, and use the result with the `PERCENTILE` function",
file = "stats_percentile",
tag = "docsStatsPercentileNestedExpression"
), }
)
public Percentile(
Source source,
@Param(name = "number", type = { "double", "integer", "long", "exponential_histogram" }) Expression field,
@Param(name = "percentile", type = { "double", "integer", "long" }) Expression percentile
) {
this(source, field, Literal.TRUE, NO_WINDOW, percentile);
}
public Percentile(Source source, Expression field, Expression filter, Expression window, Expression percentile) {
super(source, field, filter, window, singletonList(percentile));
this.percentile = percentile;
}
private Percentile(StreamInput in) throws IOException {
this(
Source.readFrom((PlanStreamInput) in),
in.readNamedWriteable(Expression.class),
in.readNamedWriteable(Expression.class),
readWindow(in),
in.readNamedWriteableCollectionAsList(Expression.class).getFirst()
);
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
protected NodeInfo<Percentile> info() {
return NodeInfo.create(this, Percentile::new, field(), filter(), window(), percentile);
}
@Override
public Percentile replaceChildren(List<Expression> newChildren) {
return new Percentile(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2), newChildren.get(3));
}
@Override
public Percentile withFilter(Expression filter) {
return new Percentile(source(), field(), filter, window(), percentile);
}
public Expression percentile() {
return percentile;
}
@Override
protected TypeResolution resolveType() {
if (childrenResolved() == false) {
return new TypeResolution("Unresolved children");
}
TypeResolution resolution = isType(
field(),
dt -> (dt.isNumeric() && dt != DataType.UNSIGNED_LONG) || dt == DataType.EXPONENTIAL_HISTOGRAM,
sourceText(),
FIRST,
"exponential_histogram or numeric except unsigned_long"
);
if (resolution.unresolved()) {
return resolution;
}
return isType(
percentile,
dt -> dt.isNumeric() && dt != DataType.UNSIGNED_LONG,
sourceText(),
SECOND,
"numeric except unsigned_long"
).and(isFoldable(percentile, sourceText(), SECOND));
}
@Override
protected AggregatorFunctionSupplier longSupplier() {
return new PercentileLongAggregatorFunctionSupplier(percentileValue());
}
@Override
protected AggregatorFunctionSupplier intSupplier() {
return new PercentileIntAggregatorFunctionSupplier(percentileValue());
}
@Override
protected AggregatorFunctionSupplier doubleSupplier() {
return new PercentileDoubleAggregatorFunctionSupplier(percentileValue());
}
private double percentileValue() {
return doubleValueOf(percentile(), source().text(), "Percentile");
}
@Override
public Expression surrogate() {
var field = field();
if (field.dataType() == DataType.EXPONENTIAL_HISTOGRAM) {
return new HistogramPercentile(source(), new HistogramMerge(source(), field, filter(), window()), percentile());
}
if (field.foldable()) {
return new MvPercentile(source(), new ToDouble(source(), field), percentile());
}
return null;
}
}
| Percentile |
java | quarkusio__quarkus | core/processor/src/main/java/io/quarkus/annotation/processor/documentation/config/formatter/JavadocToAsciidocTransformer.java | {
"start": 23089,
"end": 23170
} | class ____ {
boolean inTable;
boolean firstTableRow;
}
}
| Context |
java | apache__camel | core/camel-console/src/main/java/org/apache/camel/impl/console/ContextDevConsole.java | {
"start": 1613,
"end": 11800
} | class ____ extends AbstractDevConsole {
public ContextDevConsole() {
super("camel", "context", "CamelContext", "Overall information about the CamelContext");
}
protected String doCallText(Map<String, Object> options) {
StringBuilder sb = new StringBuilder();
String profile = "";
if (getCamelContext().getCamelContextExtension().getProfile() != null) {
profile = " (profile: " + getCamelContext().getCamelContextExtension().getProfile() + ")";
}
sb.append(String.format("Apache Camel %s %s (%s)%s uptime %s", getCamelContext().getVersion(),
getCamelContext().getStatus().name().toLowerCase(Locale.ROOT), getCamelContext().getName(),
profile, CamelContextHelper.getUptime(getCamelContext())));
if (getCamelContext().getDescription() != null) {
sb.append(String.format("\n %s", getCamelContext().getDescription()));
}
sb.append("\n");
ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class);
if (mcc != null) {
ManagedCamelContextMBean mb = mcc.getManagedCamelContext();
if (mb != null) {
int total = mb.getTotalRoutes();
int started = mb.getStartedRoutes();
sb.append(String.format("\n Routes: %s (started: %s)", total, started));
int reloaded = 0;
int reloadedFailed = 0;
Set<ReloadStrategy> rs = getCamelContext().hasServices(ReloadStrategy.class);
for (ReloadStrategy r : rs) {
reloaded += r.getReloadCounter();
reloadedFailed += r.getFailedCounter();
}
String load1 = getLoad1(mb);
String load5 = getLoad5(mb);
String load15 = getLoad15(mb);
if (!load1.isEmpty() || !load5.isEmpty() || !load15.isEmpty()) {
sb.append(String.format("\n Load Average: %s %s %s", load1, load5, load15));
}
String thp = getThroughput(mb);
if (!thp.isEmpty()) {
sb.append(String.format("\n Messages/Sec: %s", thp));
}
sb.append(String.format("\n Total: %s/%s", mb.getRemoteExchangesTotal(), mb.getExchangesTotal()));
sb.append(String.format("\n Failed: %s/%s", mb.getRemoteExchangesFailed(), mb.getExchangesFailed()));
sb.append(String.format("\n Inflight: %s/%s", mb.getRemoteExchangesInflight(), mb.getExchangesInflight()));
long idle = mb.getIdleSince();
if (idle > 0) {
sb.append(String.format("\n Idle Since: %s", TimeUtils.printDuration(idle)));
} else {
sb.append(String.format("\n Idle Since: %s", ""));
}
sb.append(String.format("\n Reloaded: %s/%s", reloaded, reloadedFailed));
sb.append(String.format("\n Mean Time: %s", TimeUtils.printDuration(mb.getMeanProcessingTime(), true)));
sb.append(String.format("\n Max Time: %s", TimeUtils.printDuration(mb.getMaxProcessingTime(), true)));
sb.append(String.format("\n Min Time: %s", TimeUtils.printDuration(mb.getMinProcessingTime(), true)));
if (mb.getExchangesTotal() > 0) {
sb.append(String.format("\n Last Time: %s", TimeUtils.printDuration(mb.getLastProcessingTime(), true)));
sb.append(
String.format("\n Delta Time: %s", TimeUtils.printDuration(mb.getDeltaProcessingTime(), true)));
}
Date last = mb.getLastExchangeCreatedTimestamp();
if (last != null) {
String ago = TimeUtils.printSince(last.getTime());
sb.append(String.format("\n Since Last Started: %s", ago));
}
last = mb.getLastExchangeCompletedTimestamp();
if (last != null) {
String ago = TimeUtils.printSince(last.getTime());
sb.append(String.format("\n Since Last Completed: %s", ago));
}
last = mb.getLastExchangeFailureTimestamp();
if (last != null) {
String ago = TimeUtils.printSince(last.getTime());
sb.append(String.format("\n Since Last Failed: %s", ago));
}
sb.append("\n");
}
}
return sb.toString();
}
protected JsonObject doCallJson(Map<String, Object> options) {
JsonObject root = new JsonObject();
root.put("name", getCamelContext().getName());
if (getCamelContext().getDescription() != null) {
root.put("description", getCamelContext().getDescription());
}
if (getCamelContext().getCamelContextExtension().getProfile() != null) {
root.put("profile", getCamelContext().getCamelContextExtension().getProfile());
}
root.put("version", getCamelContext().getVersion());
root.put("state", getCamelContext().getStatus().name());
root.put("phase", getCamelContext().getCamelContextExtension().getStatusPhase());
root.put("uptime", getCamelContext().getUptime().toMillis());
ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class);
if (mcc != null) {
ManagedCamelContextMBean mb = mcc.getManagedCamelContext();
if (mb != null) {
JsonObject stats = new JsonObject();
int total = mb.getTotalRoutes();
int started = mb.getStartedRoutes();
stats.put("routesTotal", total);
stats.put("routesStarted", started);
String load1 = getLoad1(mb);
String load5 = getLoad5(mb);
String load15 = getLoad15(mb);
if (!load1.isEmpty() || !load5.isEmpty() || !load15.isEmpty()) {
stats.put("load01", load1);
stats.put("load05", load5);
stats.put("load15", load15);
}
String thp = getThroughput(mb);
if (!thp.isEmpty()) {
stats.put("exchangesThroughput", thp);
}
stats.put("idleSince", mb.getIdleSince());
stats.put("exchangesTotal", mb.getExchangesTotal());
stats.put("exchangesFailed", mb.getExchangesFailed());
stats.put("exchangesInflight", mb.getExchangesInflight());
stats.put("remoteExchangesTotal", mb.getRemoteExchangesTotal());
stats.put("remoteExchangesFailed", mb.getRemoteExchangesFailed());
stats.put("remoteExchangesInflight", mb.getRemoteExchangesInflight());
stats.put("meanProcessingTime", mb.getMeanProcessingTime());
stats.put("maxProcessingTime", mb.getMaxProcessingTime());
stats.put("minProcessingTime", mb.getMinProcessingTime());
if (mb.getExchangesTotal() > 0) {
stats.put("lastProcessingTime", mb.getLastProcessingTime());
stats.put("deltaProcessingTime", mb.getDeltaProcessingTime());
}
Date last = mb.getLastExchangeCreatedTimestamp();
if (last != null) {
stats.put("lastCreatedExchangeTimestamp", last.getTime());
}
last = mb.getLastExchangeCompletedTimestamp();
if (last != null) {
stats.put("lastCompletedExchangeTimestamp", last.getTime());
}
last = mb.getLastExchangeFailureTimestamp();
if (last != null) {
stats.put("lastFailedExchangeTimestamp", last.getTime());
}
// reload stats
int reloaded = 0;
int reloadedFailed = 0;
Exception reloadCause = null;
Set<ReloadStrategy> rs = getCamelContext().hasServices(ReloadStrategy.class);
for (ReloadStrategy r : rs) {
reloaded += r.getReloadCounter();
reloadedFailed += r.getFailedCounter();
if (reloadCause == null) {
reloadCause = r.getLastError();
}
}
JsonObject ro = new JsonObject();
ro.put("reloaded", reloaded);
ro.put("failed", reloadedFailed);
if (reloadCause != null) {
JsonObject eo = new JsonObject();
eo.put("message", reloadCause.getMessage());
JsonArray arr2 = new JsonArray();
final String trace = ExceptionHelper.stackTraceToString(reloadCause);
eo.put("stackTrace", arr2);
Collections.addAll(arr2, trace.split("\n"));
ro.put("lastError", eo);
}
stats.put("reload", ro);
root.put("statistics", stats);
}
}
return root;
}
private String getLoad1(ManagedCamelContextMBean mb) {
String s = mb.getLoad01();
// lets use dot as separator
s = s.replace(',', '.');
return s;
}
private String getLoad5(ManagedCamelContextMBean mb) {
String s = mb.getLoad05();
// lets use dot as separator
s = s.replace(',', '.');
return s;
}
private String getLoad15(ManagedCamelContextMBean mb) {
String s = mb.getLoad15();
// lets use dot as separator
s = s.replace(',', '.');
return s;
}
private String getThroughput(ManagedCamelContextMBean mb) {
String s = mb.getThroughput();
// lets use dot as separator
s = s.replace(',', '.');
return s;
}
}
| ContextDevConsole |
java | google__dagger | javatests/dagger/android/support/functional/AllControllersAreDirectChildrenOfApplication.java | {
"start": 5179,
"end": 5319
} | interface ____ extends AndroidInjector<OuterClass.TestInnerClassActivity> {
@Subcomponent.Builder
abstract | InnerActivitySubcomponent |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin2.java | {
"start": 2219,
"end": 3451
} | enum ____ implements IntEnum<AuditStatusType> {
AUDIT_FAILURE(0, "审核失败", "FAILED"),
AUDIT_SUCCESS(1, "成功", "SUCCEED"),
AUDIT_NO_SUBMIT(2, "未实名认证", "NONAUDIT"),
AUDIT_SUBMIT(3, "审核中", "AUDITING");
private int code;
private String desc;
private String enCode;
private AuditStatusType(int code) {
this.code = code;
}
private AuditStatusType(int code, String desc, String enCode) {
this.code = code;
this.desc = desc;
this.enCode = enCode;
}
public static AuditStatusType valuesOf(String enCode) {
AuditStatusType[] arr$ = values();
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
AuditStatusType temp = arr$[i$];
if(temp.getEnCode().equals(enCode)) {
return temp;
}
}
return null;
}
public String getDesc() {
return this.desc;
}
public String getEnCode() {
return this.enCode;
}
public int getCode() {
return this.code;
}
}
public | AuditStatusType |
java | spring-projects__spring-framework | spring-r2dbc/src/main/java/org/springframework/r2dbc/core/BindParameterSource.java | {
"start": 908,
"end": 1271
} | interface ____ for the specification of the type in
* addition to parameter values. All parameter values and types are
* identified by specifying the name of the parameter.
*
* <p>Intended to wrap various implementations like a {@link java.util.Map}
* with a consistent interface.
*
* @author Mark Paluch
* @since 5.3
* @see MapBindParameterSource
*/
| allows |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/scope/custom/TestService.java | {
"start": 100,
"end": 225
} | class ____ {
public boolean destroyed;
@PreDestroy
void destroyMe() {
destroyed = true;
}
}
| TestService |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithFilenameTest.java | {
"start": 1157,
"end": 1891
} | class ____ {
private static final String CONFIG = "log4j2-rolling-1833.xml";
private static final String DIR = "target/rolling-1833";
public static LoggerContextRule loggerContextRule =
LoggerContextRule.createShutdownTimeoutLoggerContextRule(CONFIG);
@Rule
public RuleChain chain = loggerContextRule.withCleanFoldersRule(DIR);
private Logger logger;
@Before
public void setUp() {
this.logger = loggerContextRule.getLogger(RollingAppenderDirectWriteWithFilenameTest.class.getName());
}
@Test
public void testAppender() {
final File dir = new File(DIR);
assertFalse("Directory created", dir.exists());
}
}
| RollingAppenderDirectWriteWithFilenameTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/DistSum.java | {
"start": 9904,
"end": 10768
} | class ____ extends AbstractInputFormat {
/** Partitions the summation into parts and then return them as splits */
@Override
public List<InputSplit> getSplits(JobContext context) {
//read sigma from conf
final Configuration conf = context.getConfiguration();
final Summation sigma = SummationWritable.read(DistSum.class, conf);
final int nParts = conf.getInt(N_PARTS, 0);
//create splits
final List<InputSplit> splits = new ArrayList<InputSplit>(nParts);
final Summation[] parts = sigma.partition(nParts);
for(int i = 0; i < parts.length; ++i) {
splits.add(new SummationSplit(parts[i]));
//LOG.info("parts[" + i + "] = " + parts[i]);
}
return splits;
}
}
/** A mapper which computes sums */
public static | PartitionInputFormat |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/ConverterUtils.java | {
"start": 1847,
"end": 6555
} | class ____ {
public static final String APPLICATION_PREFIX = "application";
public static final String CONTAINER_PREFIX = "container";
public static final String APPLICATION_ATTEMPT_PREFIX = "appattempt";
/**
* return a hadoop path from a given url
* This method is deprecated, use {@link URL#toPath()} instead.
*
* @param url
* url to convert
* @return path from {@link URL}
* @throws URISyntaxException exception thrown to indicate that a string could not be parsed as a
* URI reference.
*/
@Public
@Deprecated
public static Path getPathFromYarnURL(URL url) throws URISyntaxException {
return url.toPath();
}
/*
* This method is deprecated, use {@link URL#fromPath(Path)} instead.
*/
@Public
@Deprecated
public static URL getYarnUrlFromPath(Path path) {
return URL.fromPath(path);
}
/*
* This method is deprecated, use {@link URL#fromURI(URI)} instead.
*/
@Public
@Deprecated
public static URL getYarnUrlFromURI(URI uri) {
return URL.fromURI(uri);
}
/*
* This method is deprecated, use {@link ApplicationId#toString()} instead.
*/
@Public
@Deprecated
public static String toString(ApplicationId appId) {
return appId.toString();
}
/*
* This method is deprecated, use {@link ApplicationId#fromString(String)}
* instead.
*/
@Public
@Deprecated
public static ApplicationId toApplicationId(RecordFactory recordFactory,
String applicationIdStr) {
return ApplicationId.fromString(applicationIdStr);
}
/*
* This method is deprecated, use {@link ContainerId#toString()} instead.
*/
@Public
@Deprecated
public static String toString(ContainerId cId) {
return cId == null ? null : cId.toString();
}
@Private
@InterfaceStability.Unstable
public static NodeId toNodeIdWithDefaultPort(String nodeIdStr) {
if (nodeIdStr.indexOf(":") < 0) {
return NodeId.fromString(nodeIdStr + ":0");
}
return NodeId.fromString(nodeIdStr);
}
/*
* This method is deprecated, use {@link NodeId#fromString(String)} instead.
*/
@Public
@Deprecated
public static NodeId toNodeId(String nodeIdStr) {
return NodeId.fromString(nodeIdStr);
}
/*
* This method is deprecated, use {@link ContainerId#fromString(String)}
* instead.
*/
@Public
@Deprecated
public static ContainerId toContainerId(String containerIdStr) {
return ContainerId.fromString(containerIdStr);
}
/*
* This method is deprecated, use {@link ApplicationAttemptId#toString()}
* instead.
*/
@Public
@Deprecated
public static ApplicationAttemptId toApplicationAttemptId(
String applicationAttemptIdStr) {
return ApplicationAttemptId.fromString(applicationAttemptIdStr);
}
/*
* This method is deprecated, use {@link ApplicationId#fromString(String)}
* instead.
*/
@Public
@Deprecated
public static ApplicationId toApplicationId(
String appIdStr) {
return ApplicationId.fromString(appIdStr);
}
/**
* Convert a protobuf token into a rpc token and set its service. Supposed
* to be used for tokens other than RMDelegationToken. For
* RMDelegationToken, use
* {@link #convertFromYarn(org.apache.hadoop.yarn.api.records.Token,
* org.apache.hadoop.io.Text)} instead.
*
* @param protoToken the yarn token
* @param serviceAddr the connect address for the service
* @param <T> Generic Type T.
* @return rpc token
*/
public static <T extends TokenIdentifier> Token<T> convertFromYarn(
org.apache.hadoop.yarn.api.records.Token protoToken,
InetSocketAddress serviceAddr) {
Token<T> token = new Token<T>(protoToken.getIdentifier().array(),
protoToken.getPassword().array(),
new Text(protoToken.getKind()),
new Text(protoToken.getService()));
if (serviceAddr != null) {
SecurityUtil.setTokenService(token, serviceAddr);
}
return token;
}
/**
* Convert a protobuf token into a rpc token and set its service.
*
* @param protoToken the yarn token
* @param service the service for the token
* @param <T> Generic Type T.
* @return rpc token
*/
public static <T extends TokenIdentifier> Token<T> convertFromYarn(
org.apache.hadoop.yarn.api.records.Token protoToken,
Text service) {
Token<T> token = new Token<T>(protoToken.getIdentifier().array(),
protoToken.getPassword().array(),
new Text(protoToken.getKind()),
new Text(protoToken.getService()));
if (service != null) {
token.setService(service);
}
return token;
}
}
| ConverterUtils |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java | {
"start": 2589,
"end": 3388
} | class ____ {
private static final String[] CLASSES_IN_CORE_IO_SUPPORT = {"EncodedResource.class",
"LocalizedResourceHelper.class", "PathMatchingResourcePatternResolver.class", "PropertiesLoaderSupport.class",
"PropertiesLoaderUtils.class", "ResourceArrayPropertyEditor.class", "ResourcePatternResolver.class",
"ResourcePatternUtils.class", "SpringFactoriesLoader.class"};
private static final String[] TEST_CLASSES_IN_CORE_IO_SUPPORT = {"PathMatchingResourcePatternResolverTests.class"};
private static final String[] CLASSES_IN_REACTOR_UTIL_ANNOTATION =
{"Incubating.class", "NonNull.class", "NonNullApi.class", "Nullable.class"};
private PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
@Nested
| PathMatchingResourcePatternResolverTests |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/indices/breaker/AllCircuitBreakerStats.java | {
"start": 899,
"end": 2136
} | class ____ implements Writeable, ToXContentFragment {
private final CircuitBreakerStats[] allStats;
public AllCircuitBreakerStats(CircuitBreakerStats[] allStats) {
this.allStats = allStats;
}
public AllCircuitBreakerStats(StreamInput in) throws IOException {
allStats = in.readArray(CircuitBreakerStats::new, CircuitBreakerStats[]::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeArray(allStats);
}
public CircuitBreakerStats[] getAllStats() {
return this.allStats;
}
public CircuitBreakerStats getStats(String name) {
for (CircuitBreakerStats stats : allStats) {
if (stats.getName().equals(name)) {
return stats;
}
}
return null;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.BREAKERS);
for (CircuitBreakerStats stats : allStats) {
if (stats != null) {
stats.toXContent(builder, params);
}
}
builder.endObject();
return builder;
}
static final | AllCircuitBreakerStats |
java | alibaba__fastjson | src/test/java/data/media/MediaContentGenDecoder.java | {
"start": 557,
"end": 6443
} | class ____ extends JavaBeanDeserializer implements ObjectDeserializer {
private char[] media_gen_prefix__ = "\"media\":".toCharArray();
private char[] images_gen_prefix__ = "\"images\":".toCharArray();
private ObjectDeserializer media_gen_deser__;
private ObjectDeserializer images_gen_list_item_deser__;
private Type images_gen_list_item_type__ = data.media.Image.class;
public MediaContentGenDecoder (ParserConfig config, Class clazz) {
super(config, clazz);
}
public Object createInstance(DefaultJSONParser parser, Type type) {
return new MediaContent();
}
public Object deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
JSONLexerBase lexer = (JSONLexerBase) parser.getLexer();
if (!lexer.isEnabled(Feature.SortFeidFastMatch)) {
return super.deserialze(parser, type, fieldName);
}
if (lexer.isEnabled(Feature.SupportArrayToBean)) {
// deserialzeArrayMapping
}
if (lexer.scanType("Department") == JSONLexerBase.NOT_MATCH) {
return super.deserialze(parser, type, fieldName);
}
ParseContext mark_context = parser.getContext();
int matchedCount = 0;
MediaContent instance = new MediaContent();
ParseContext context = parser.getContext();
ParseContext childContext = parser.setContext(context, instance, fieldName);
if (lexer.matchStat == JSONLexerBase.END) {
return instance;
}
int matchStat = 0;
int _asm_flag_0 = 0;
java.util.List images_gen = null;
data.media.Media media_gen = null;
boolean endFlag = false, restFlag = false;
if ((!endFlag) && (!restFlag)) {
if (lexer.matchField(images_gen_prefix__)) {
_asm_flag_0 |= 1;
if (lexer.token() == JSONToken.NULL) {
lexer.nextToken(JSONToken.COMMA);
} else {
if (lexer.token() == JSONToken.LBRACKET) {
if(images_gen_list_item_deser__ == null) {
images_gen_list_item_deser__ = parser.getConfig().getDeserializer(data.media.Image.class);
}
final int fastMatchToken = images_gen_list_item_deser__.getFastMatchToken();
lexer.nextToken(fastMatchToken);
images_gen = new java.util.ArrayList();
ParseContext listContext = parser.getContext();
parser.setContext(images_gen, "images");
for(int i = 0; ;++i) {
if (lexer.token() == JSONToken.RBRACKET) {
break;
}
data.media.Image itemValue = images_gen_list_item_deser__.deserialze(parser, images_gen_list_item_type__, i);
images_gen.add(itemValue);
parser.checkListResolve(images_gen);
if (lexer.token() == JSONToken.COMMA) {
lexer.nextToken(fastMatchToken);
}
}
parser.setContext(listContext);
if (lexer.token() != JSONToken.RBRACKET) {
restFlag = true;
}
lexer.nextToken(JSONToken.COMMA);
} else {
restFlag = true;
}
}
}
if(lexer.matchStat > 0) {
_asm_flag_0 |= 1;
matchedCount++;
}
if(lexer.matchStat == JSONLexerBase.NOT_MATCH) {
restFlag = true;
}
if(lexer.matchStat != JSONLexerBase.END) {
endFlag = true;
}
}
if ((!endFlag) && (!restFlag)) {
if (lexer.matchField(media_gen_prefix__)) {
_asm_flag_0 |= 2;
matchedCount++;
if (media_gen_deser__ == null) {
media_gen_deser__ = parser.getConfig().getDeserializer(data.media.Media.class);
}
media_gen_deser__.deserialze(parser, data.media.Media.class,"media");
if(parser.getResolveStatus() == DefaultJSONParser.NeedToResolve) {
ResolveTask resolveTask = parser.getLastResolveTask();
resolveTask.ownerContext = parser.getContext();
resolveTask.fieldDeserializer = this.getFieldDeserializer("media");
parser.setResolveStatus(DefaultJSONParser.NONE);
}
}
if (matchedCount <= 0 || lexer.token() != JSONToken.RBRACE) {
restFlag = true;
} else if (lexer.token() == JSONToken.COMMA) {
lexer.nextToken();
}
if(lexer.matchStat > 0) {
_asm_flag_0 |= 2;
matchedCount++;
}
if(lexer.matchStat == JSONLexerBase.NOT_MATCH) {
restFlag = true;
}
if(lexer.matchStat != JSONLexerBase.END) {
restFlag = true;
}
}
if ((_asm_flag_0 & 1) != 0) {
instance.setImages(images_gen);
}
if ((_asm_flag_0 & 2) != 0) {
instance.setMedia(media_gen);
}
if (restFlag) {
return super.parseRest(parser, type, fieldName, instance, 0, new int[0]);
}
return instance;
}
}
| MediaContentGenDecoder |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/metrics/Stats.java | {
"start": 621,
"end": 1607
} | interface ____ extends NumericMetricsAggregation.MultiValue {
/**
* @return The number of values that were aggregated.
*/
long getCount();
/**
* @return The minimum value of all aggregated values.
*/
double getMin();
/**
* @return The maximum value of all aggregated values.
*/
double getMax();
/**
* @return The avg value over all aggregated values.
*/
double getAvg();
/**
* @return The sum of aggregated values.
*/
double getSum();
/**
* @return The minimum value of all aggregated values as a String.
*/
String getMinAsString();
/**
* @return The maximum value of all aggregated values as a String.
*/
String getMaxAsString();
/**
* @return The avg value over all aggregated values as a String.
*/
String getAvgAsString();
/**
* @return The sum of aggregated values as a String.
*/
String getSumAsString();
}
| Stats |
java | apache__camel | components/camel-metrics/src/test/java/org/apache/camel/component/metrics/CounterProducerTest.java | {
"start": 1840,
"end": 8418
} | class ____ {
private static final String METRICS_NAME = "metrics.name";
private static final Long INCREMENT = 100000L;
private static final Long DECREMENT = 91929199L;
@Mock
private MetricsEndpoint endpoint;
@Mock
private Exchange exchange;
@Mock
private MetricRegistry registry;
@Mock
private Counter counter;
@Mock
private Message in;
private CounterProducer producer;
private InOrder inOrder;
@BeforeEach
public void setUp() {
producer = new CounterProducer(endpoint);
inOrder = Mockito.inOrder(endpoint, exchange, registry, counter, in);
lenient().when(registry.counter(METRICS_NAME)).thenReturn(counter);
lenient().when(exchange.getIn()).thenReturn(in);
}
@Test
public void testCounterProducer() {
assertThat(producer.getEndpoint().equals(endpoint), is(true));
}
@Test
public void testProcessWithIncrementOnly() throws Exception {
Object action = null;
when(endpoint.getIncrement()).thenReturn(INCREMENT);
when(endpoint.getDecrement()).thenReturn(null);
when(in.getHeader(HEADER_COUNTER_INCREMENT, INCREMENT, Long.class)).thenReturn(INCREMENT);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(registry, times(1)).counter(METRICS_NAME);
inOrder.verify(endpoint, times(1)).getIncrement();
inOrder.verify(endpoint, times(1)).getDecrement();
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_INCREMENT, INCREMENT, Long.class);
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_DECREMENT, action, Long.class);
inOrder.verify(counter, times(1)).inc(INCREMENT);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessWithDecrementOnly() throws Exception {
Object action = null;
when(endpoint.getIncrement()).thenReturn(null);
when(endpoint.getDecrement()).thenReturn(DECREMENT);
when(in.getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class)).thenReturn(DECREMENT);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(registry, times(1)).counter(METRICS_NAME);
inOrder.verify(endpoint, times(1)).getIncrement();
inOrder.verify(endpoint, times(1)).getDecrement();
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_INCREMENT, action, Long.class);
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class);
inOrder.verify(counter, times(1)).dec(DECREMENT);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testDoProcessWithIncrementAndDecrement() throws Exception {
when(endpoint.getIncrement()).thenReturn(INCREMENT);
when(endpoint.getDecrement()).thenReturn(DECREMENT);
when(in.getHeader(HEADER_COUNTER_INCREMENT, INCREMENT, Long.class)).thenReturn(INCREMENT);
when(in.getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class)).thenReturn(DECREMENT);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(registry, times(1)).counter(METRICS_NAME);
inOrder.verify(endpoint, times(1)).getIncrement();
inOrder.verify(endpoint, times(1)).getDecrement();
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_INCREMENT, INCREMENT, Long.class);
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class);
inOrder.verify(counter, times(1)).inc(INCREMENT);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessWithOutIncrementAndDecrement() throws Exception {
Object action = null;
when(endpoint.getIncrement()).thenReturn(null);
when(endpoint.getDecrement()).thenReturn(null);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(registry, times(1)).counter(METRICS_NAME);
inOrder.verify(endpoint, times(1)).getIncrement();
inOrder.verify(endpoint, times(1)).getDecrement();
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_INCREMENT, action, Long.class);
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_DECREMENT, action, Long.class);
inOrder.verify(counter, times(1)).inc();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessOverridingIncrement() throws Exception {
when(endpoint.getIncrement()).thenReturn(INCREMENT);
when(endpoint.getDecrement()).thenReturn(DECREMENT);
when(in.getHeader(HEADER_COUNTER_INCREMENT, INCREMENT, Long.class)).thenReturn(INCREMENT + 1);
when(in.getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class)).thenReturn(DECREMENT);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(registry, times(1)).counter(METRICS_NAME);
inOrder.verify(endpoint, times(1)).getIncrement();
inOrder.verify(endpoint, times(1)).getDecrement();
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_INCREMENT, INCREMENT, Long.class);
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class);
inOrder.verify(counter, times(1)).inc(INCREMENT + 1);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessOverridingDecrement() throws Exception {
Object action = null;
when(endpoint.getIncrement()).thenReturn(null);
when(endpoint.getDecrement()).thenReturn(DECREMENT);
when(in.getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class)).thenReturn(DECREMENT - 1);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(registry, times(1)).counter(METRICS_NAME);
inOrder.verify(endpoint, times(1)).getIncrement();
inOrder.verify(endpoint, times(1)).getDecrement();
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_INCREMENT, action, Long.class);
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class);
inOrder.verify(counter, times(1)).dec(DECREMENT - 1);
inOrder.verifyNoMoreInteractions();
}
}
| CounterProducerTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/CustomJobEndNotifier.java | {
"start": 1095,
"end": 1367
} | interface ____ setting the
* {@link MRJobConfig#MR_JOB_END_NOTIFICATION_CUSTOM_NOTIFIER_CLASS} property
* in the map-reduce Job configuration you can have your own
* notification mechanism. For now this still only works with HTTP/HTTPS URLs,
* but by implementing this | and |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java | {
"start": 31798,
"end": 36213
} | class ____ {
private static final PathPatternParser defaultPatternParser = new PathPatternParser();
private @Nullable PathPatternParser patternParser;
private @Nullable PathMatcher pathMatcher;
private @Nullable ContentNegotiationManager contentNegotiationManager;
private @Nullable ApiVersionStrategy apiVersionStrategy;
/**
* Enable use of parsed {@link PathPattern}s as described in
* {@link AbstractHandlerMapping#setPatternParser(PathPatternParser)}.
* <p><strong>Note:</strong> This property is mutually exclusive with
* {@link #setPathMatcher(PathMatcher)}.
* <p>By default, this is not set, but {@link RequestMappingInfo.Builder}
* defaults to using {@link PathPatternParser} unless
* {@link #setPathMatcher(PathMatcher)} is explicitly set.
* @since 5.3
*/
public void setPatternParser(@Nullable PathPatternParser patternParser) {
this.patternParser = patternParser;
}
/**
* Return the {@link #setPatternParser(PathPatternParser) configured}
* {@code PathPatternParser}, or {@code null}.
* @since 5.3
*/
public @Nullable PathPatternParser getPatternParser() {
return this.patternParser;
}
/**
* Set a custom UrlPathHelper to use for the PatternsRequestCondition.
* <p>By default this is not set.
* @since 4.2.8
* @deprecated the path is resolved externally and obtained with
* {@link ServletRequestPathUtils#getCachedPathValue(ServletRequest)}
*/
@Deprecated(since = "5.3")
public void setUrlPathHelper(@Nullable UrlPathHelper urlPathHelper) {
}
/**
* Return the configured UrlPathHelper.
* @deprecated the path is resolved externally and obtained with
* {@link ServletRequestPathUtils#getCachedPathValue(ServletRequest)};
* this method always returns {@link UrlPathHelper#defaultInstance}.
*/
@Deprecated(since = "5.3")
public @Nullable UrlPathHelper getUrlPathHelper() {
return UrlPathHelper.defaultInstance;
}
/**
* Set a custom PathMatcher to use for the PatternsRequestCondition.
* <p>By default, this is not set. You must set it explicitly if you want
* {@link PathMatcher} to be used, or otherwise {@link RequestMappingInfo}
* defaults to using {@link PathPatternParser}.
* @deprecated use of {@link PathMatcher} and {@link UrlPathHelper} is deprecated
* for use at runtime in web modules in favor of parsed patterns with
* {@link PathPatternParser}.
*/
@Deprecated(since = "7.0", forRemoval = true)
public void setPathMatcher(@Nullable PathMatcher pathMatcher) {
this.pathMatcher = pathMatcher;
}
/**
* Return a custom PathMatcher to use for the PatternsRequestCondition, if any.
* @deprecated use of {@link PathMatcher} and {@link UrlPathHelper} is deprecated
* for use at runtime in web modules in favor of parsed patterns with
* {@link PathPatternParser}.
*/
@Deprecated(since = "7.0", forRemoval = true)
public @Nullable PathMatcher getPathMatcher() {
return this.pathMatcher;
}
/**
* Return the {@code PathPatternParser} to use, the one set explicitly
* or falling back on a default instance if both {@code PathPatternParser}
* and {@code PathMatcher} are not set.
* @since 6.1.2
*/
public @Nullable PathPatternParser getPatternParserToUse() {
if (this.patternParser == null && this.pathMatcher == null) {
return defaultPatternParser;
}
return this.patternParser;
}
/**
* Set the ContentNegotiationManager to use for the ProducesRequestCondition.
* <p>By default, this is not set.
*/
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
this.contentNegotiationManager = contentNegotiationManager;
}
/**
* Return the ContentNegotiationManager to use for the ProducesRequestCondition,
* if any.
*/
public @Nullable ContentNegotiationManager getContentNegotiationManager() {
return this.contentNegotiationManager;
}
/**
* Set the strategy for API versioning.
* @param apiVersionStrategy the strategy to use
* @since 7.0
*/
public void setApiVersionStrategy(@Nullable ApiVersionStrategy apiVersionStrategy) {
this.apiVersionStrategy = apiVersionStrategy;
}
/**
* Return the configured strategy for API versioning.
* @since 7.0
*/
public @Nullable ApiVersionStrategy getApiVersionStrategy() {
return this.apiVersionStrategy;
}
}
}
| BuilderConfiguration |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/PredicateFactory.java | {
"start": 910,
"end": 1148
} | interface ____ {
/**
* Creates a predicate
*
* @param camelContext the camel context
* @return the created predicate.
*/
Predicate createPredicate(CamelContext camelContext);
}
| PredicateFactory |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/client/observation/DefaultClientRequestObservationConvention.java | {
"start": 1570,
"end": 6315
} | class ____ implements ClientRequestObservationConvention {
private static final String DEFAULT_NAME = "http.client.requests";
private static final Pattern PATTERN_BEFORE_PATH = Pattern.compile("^https?://[^/]+");
private static final KeyValue URI_NONE = KeyValue.of(LowCardinalityKeyNames.URI, KeyValue.NONE_VALUE);
private static final KeyValue METHOD_NONE = KeyValue.of(LowCardinalityKeyNames.METHOD, KeyValue.NONE_VALUE);
private static final KeyValue STATUS_IO_ERROR = KeyValue.of(LowCardinalityKeyNames.STATUS, "IO_ERROR");
private static final KeyValue STATUS_CLIENT_ERROR = KeyValue.of(LowCardinalityKeyNames.STATUS, "CLIENT_ERROR");
private static final KeyValue HTTP_OUTCOME_SUCCESS = KeyValue.of(LowCardinalityKeyNames.OUTCOME, "SUCCESS");
private static final KeyValue HTTP_OUTCOME_UNKNOWN = KeyValue.of(LowCardinalityKeyNames.OUTCOME, "UNKNOWN");
private static final KeyValue CLIENT_NAME_NONE = KeyValue.of(LowCardinalityKeyNames.CLIENT_NAME, KeyValue.NONE_VALUE);
private static final KeyValue EXCEPTION_NONE = KeyValue.of(LowCardinalityKeyNames.EXCEPTION, KeyValue.NONE_VALUE);
private static final KeyValue HTTP_URL_NONE = KeyValue.of(HighCardinalityKeyNames.HTTP_URL, KeyValue.NONE_VALUE);
private final String name;
/**
* Create a convention with the default name {@code "http.client.requests"}.
*/
public DefaultClientRequestObservationConvention() {
this(DEFAULT_NAME);
}
/**
* Create a convention with a custom name.
* @param name the observation name
*/
public DefaultClientRequestObservationConvention(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
public @Nullable String getContextualName(ClientRequestObservationContext context) {
ClientHttpRequest request = context.getCarrier();
return (request != null ? "http " + request.getMethod().name().toLowerCase(Locale.ROOT) : null);
}
@Override
public KeyValues getLowCardinalityKeyValues(ClientRequestObservationContext context) {
// Make sure that KeyValues entries are already sorted by name for better performance
return KeyValues.of(clientName(context), exception(context), method(context), outcome(context), status(context), uri(context));
}
protected KeyValue uri(ClientRequestObservationContext context) {
if (context.getUriTemplate() != null) {
return KeyValue.of(LowCardinalityKeyNames.URI, extractPath(context.getUriTemplate()));
}
return URI_NONE;
}
private static String extractPath(String uriTemplate) {
String path = PATTERN_BEFORE_PATH.matcher(uriTemplate).replaceFirst("");
return (path.startsWith("/") ? path : "/" + path);
}
protected KeyValue method(ClientRequestObservationContext context) {
if (context.getCarrier() != null) {
return KeyValue.of(LowCardinalityKeyNames.METHOD, context.getCarrier().getMethod().name());
}
else {
return METHOD_NONE;
}
}
protected KeyValue status(ClientRequestObservationContext context) {
ClientHttpResponse response = context.getResponse();
if (response == null) {
return STATUS_CLIENT_ERROR;
}
try {
return KeyValue.of(LowCardinalityKeyNames.STATUS, String.valueOf(response.getStatusCode().value()));
}
catch (IOException ex) {
return STATUS_IO_ERROR;
}
}
protected KeyValue clientName(ClientRequestObservationContext context) {
if (context.getCarrier() != null && context.getCarrier().getURI().getHost() != null) {
return KeyValue.of(LowCardinalityKeyNames.CLIENT_NAME, context.getCarrier().getURI().getHost());
}
return CLIENT_NAME_NONE;
}
protected KeyValue exception(ClientRequestObservationContext context) {
Throwable error = context.getError();
if (error != null) {
String simpleName = error.getClass().getSimpleName();
return KeyValue.of(LowCardinalityKeyNames.EXCEPTION,
StringUtils.hasText(simpleName) ? simpleName : error.getClass().getName());
}
return EXCEPTION_NONE;
}
protected KeyValue outcome(ClientRequestObservationContext context) {
if (context.getResponse() != null) {
try {
return HttpOutcome.forStatus(context.getResponse().getStatusCode());
}
catch (IOException ex) {
// Continue
}
}
return HTTP_OUTCOME_UNKNOWN;
}
@Override
public KeyValues getHighCardinalityKeyValues(ClientRequestObservationContext context) {
// Make sure that KeyValues entries are already sorted by name for better performance
return KeyValues.of(requestUri(context));
}
protected KeyValue requestUri(ClientRequestObservationContext context) {
if (context.getCarrier() != null) {
return KeyValue.of(HighCardinalityKeyNames.HTTP_URL, context.getCarrier().getURI().toASCIIString());
}
return HTTP_URL_NONE;
}
static | DefaultClientRequestObservationConvention |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/rest/PatchDefinition.java | {
"start": 1167,
"end": 1290
} | class ____ extends VerbDefinition {
@Override
public String asVerb() {
return "patch";
}
}
| PatchDefinition |
java | apache__flink | flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/vector/reader/AbstractColumnReader.java | {
"start": 2269,
"end": 12707
} | class ____<VECTOR extends WritableColumnVector>
implements ColumnReader<VECTOR> {
private static final Logger LOG = LoggerFactory.getLogger(AbstractColumnReader.class);
private final PageReader pageReader;
/** The dictionary, if this column has dictionary encoding. */
protected final Dictionary dictionary;
/** Maximum definition level for this column. */
protected final int maxDefLevel;
protected final ColumnDescriptor descriptor;
/** Total number of values read. */
private long valuesRead;
/**
* value that indicates the end of the current page. That is, if valuesRead ==
* endOfPageValueCount, we are at the end of the page.
*/
private long endOfPageValueCount;
/** If true, the current page is dictionary encoded. */
private boolean isCurrentPageDictionaryEncoded;
/** Total values in the current page. */
private int pageValueCount;
/*
* Input streams:
* 1.Run length encoder to encode every data, so we have run length stream to get
* run length information.
* 2.Data maybe is real data, maybe is dictionary ids which need be decode to real
* data from Dictionary.
*
* Run length stream ------> Data stream
* |
* ------> Dictionary ids stream
*/
/** Run length decoder for data and dictionary. */
protected RunLengthDecoder runLenDecoder;
/** Data input stream. */
ByteBufferInputStream dataInputStream;
/** Dictionary decoder to wrap dictionary ids input stream. */
private RunLengthDecoder dictionaryIdsDecoder;
public AbstractColumnReader(ColumnDescriptor descriptor, PageReader pageReader)
throws IOException {
this.descriptor = descriptor;
this.pageReader = pageReader;
this.maxDefLevel = descriptor.getMaxDefinitionLevel();
DictionaryPage dictionaryPage = pageReader.readDictionaryPage();
if (dictionaryPage != null) {
try {
this.dictionary =
dictionaryPage.getEncoding().initDictionary(descriptor, dictionaryPage);
this.isCurrentPageDictionaryEncoded = true;
} catch (IOException e) {
throw new IOException("could not decode the dictionary for " + descriptor, e);
}
} else {
this.dictionary = null;
this.isCurrentPageDictionaryEncoded = false;
}
/*
* Total number of values in this column (in this row group).
*/
long totalValueCount = pageReader.getTotalValueCount();
if (totalValueCount == 0) {
throw new IOException("totalValueCount == 0");
}
}
protected void checkTypeName(PrimitiveType.PrimitiveTypeName expectedName) {
PrimitiveType.PrimitiveTypeName actualName =
descriptor.getPrimitiveType().getPrimitiveTypeName();
checkArgument(
actualName == expectedName,
"Expected type name: %s, actual type name: %s",
expectedName,
actualName);
}
/** Reads `total` values from this columnReader into column. */
@Override
public final void readToVector(int readNumber, VECTOR vector) throws IOException {
int rowId = 0;
WritableIntVector dictionaryIds = null;
if (dictionary != null) {
dictionaryIds = vector.reserveDictionaryIds(readNumber);
}
while (readNumber > 0) {
// Compute the number of values we want to read in this page.
int leftInPage = (int) (endOfPageValueCount - valuesRead);
if (leftInPage == 0) {
DataPage page = pageReader.readPage();
if (page instanceof DataPageV1) {
readPageV1((DataPageV1) page);
} else if (page instanceof DataPageV2) {
readPageV2((DataPageV2) page);
} else {
throw new RuntimeException("Unsupported page type: " + page.getClass());
}
leftInPage = (int) (endOfPageValueCount - valuesRead);
}
int num = Math.min(readNumber, leftInPage);
if (isCurrentPageDictionaryEncoded) {
// Read and decode dictionary ids.
runLenDecoder.readDictionaryIds(
num, dictionaryIds, vector, rowId, maxDefLevel, this.dictionaryIdsDecoder);
if (vector.hasDictionary() || (rowId == 0 && supportLazyDecode())) {
// Column vector supports lazy decoding of dictionary values so just set the
// dictionary.
// We can't do this if rowId != 0 AND the column doesn't have a dictionary (i.e.
// some
// non-dictionary encoded values have already been added).
vector.setDictionary(new ParquetDictionary(dictionary, descriptor));
} else {
readBatchFromDictionaryIds(rowId, num, vector, dictionaryIds);
}
} else {
if (vector.hasDictionary() && rowId != 0) {
// This batch already has dictionary encoded values but this new page is not.
// The batch
// does not support a mix of dictionary and not so we will decode the
// dictionary.
readBatchFromDictionaryIds(0, rowId, vector, vector.getDictionaryIds());
}
vector.setDictionary(null);
readBatch(rowId, num, vector);
}
valuesRead += num;
rowId += num;
readNumber -= num;
}
}
private void readPageV1(DataPageV1 page) throws IOException {
this.pageValueCount = page.getValueCount();
ValuesReader rlReader = page.getRlEncoding().getValuesReader(descriptor, REPETITION_LEVEL);
// Initialize the decoders.
if (page.getDlEncoding() != Encoding.RLE && descriptor.getMaxDefinitionLevel() != 0) {
throw new UnsupportedOperationException(
"Unsupported encoding: " + page.getDlEncoding());
}
int bitWidth = BytesUtils.getWidthFromMaxInt(descriptor.getMaxDefinitionLevel());
this.runLenDecoder = new RunLengthDecoder(bitWidth);
try {
BytesInput bytes = page.getBytes();
ByteBufferInputStream in = bytes.toInputStream();
rlReader.initFromPage(pageValueCount, in);
this.runLenDecoder.initFromStream(pageValueCount, in);
prepareNewPage(page.getValueEncoding(), in);
} catch (IOException e) {
throw new IOException("could not read page " + page + " in col " + descriptor, e);
}
}
private void readPageV2(DataPageV2 page) throws IOException {
this.pageValueCount = page.getValueCount();
int bitWidth = BytesUtils.getWidthFromMaxInt(descriptor.getMaxDefinitionLevel());
// do not read the length from the stream. v2 pages handle dividing the page bytes.
this.runLenDecoder = new RunLengthDecoder(bitWidth, false);
this.runLenDecoder.initFromStream(
this.pageValueCount, page.getDefinitionLevels().toInputStream());
try {
prepareNewPage(page.getDataEncoding(), page.getData().toInputStream());
} catch (IOException e) {
throw new IOException("could not read page " + page + " in col " + descriptor, e);
}
}
private void prepareNewPage(Encoding dataEncoding, ByteBufferInputStream in)
throws IOException {
this.endOfPageValueCount = valuesRead + pageValueCount;
if (dataEncoding.usesDictionary()) {
if (dictionary == null) {
throw new IOException(
"could not read page in col "
+ descriptor
+ " as the dictionary was missing for encoding "
+ dataEncoding);
}
@SuppressWarnings("deprecation")
Encoding plainDict = Encoding.PLAIN_DICTIONARY; // var to allow warning suppression
if (dataEncoding != plainDict && dataEncoding != Encoding.RLE_DICTIONARY) {
throw new UnsupportedOperationException("Unsupported encoding: " + dataEncoding);
}
this.dataInputStream = null;
this.dictionaryIdsDecoder = new RunLengthDecoder();
try {
this.dictionaryIdsDecoder.initFromStream(pageValueCount, in);
} catch (IOException e) {
throw new IOException("could not read dictionary in col " + descriptor, e);
}
this.isCurrentPageDictionaryEncoded = true;
} else {
if (dataEncoding != Encoding.PLAIN) {
throw new UnsupportedOperationException("Unsupported encoding: " + dataEncoding);
}
this.dictionaryIdsDecoder = null;
LOG.debug("init from page at offset {} for length {}", in.position(), in.available());
this.dataInputStream = in.remainingStream();
this.isCurrentPageDictionaryEncoded = false;
}
afterReadPage();
}
final ByteBuffer readDataBuffer(int length) {
try {
return dataInputStream.slice(length).order(ByteOrder.LITTLE_ENDIAN);
} catch (IOException e) {
throw new ParquetDecodingException("Failed to read " + length + " bytes", e);
}
}
/** After read a page, we may need some initialization. */
protected void afterReadPage() {}
/**
* Support lazy dictionary ids decode. See more in {@link ParquetDictionary}. If return false,
* we will decode all the data first.
*/
protected boolean supportLazyDecode() {
return true;
}
/** Read batch from {@link #runLenDecoder} and {@link #dataInputStream}. */
protected abstract void readBatch(int rowId, int num, VECTOR column);
/**
* Decode dictionary ids to data. From {@link #runLenDecoder} and {@link #dictionaryIdsDecoder}.
*/
protected abstract void readBatchFromDictionaryIds(
int rowId, int num, VECTOR column, WritableIntVector dictionaryIds);
}
| AbstractColumnReader |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/matchers/MethodVisibility.java | {
"start": 1005,
"end": 1696
} | class ____ implements Matcher<MethodTree> {
private final Visibility visibility;
public MethodVisibility(Visibility visibility) {
this.visibility = visibility;
}
@Override
public boolean matches(MethodTree t, VisitorState state) {
Set<Modifier> modifiers = getSymbol(t).getModifiers();
if (visibility == Visibility.DEFAULT) {
return !modifiers.contains(Visibility.PUBLIC.toModifier())
&& !modifiers.contains(Visibility.PROTECTED.toModifier())
&& !modifiers.contains(Visibility.PRIVATE.toModifier());
} else {
return modifiers.contains(visibility.toModifier());
}
}
/** The visibility of a member. */
public | MethodVisibility |
java | bumptech__glide | instrumentation/src/androidTest/java/com/bumptech/glide/ErrorHandlingTest.java | {
"start": 1824,
"end": 5327
} | class ____ {
@Rule public TearDownGlide tearDownGlide = new TearDownGlide();
@Mock private RequestListener<Drawable> requestListener;
private final ConcurrencyHelper concurrency = new ConcurrencyHelper();
private Context context;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
context = ApplicationProvider.getApplicationContext();
}
private WaitForErrorStrategy initializeGlideWithWaitForErrorStrategy() {
WaitForErrorStrategy strategy = new WaitForErrorStrategy();
Glide.init(
context,
new GlideBuilder()
.setAnimationExecutor(
GlideExecutor.newAnimationExecutor(/* threadCount= */ 1, strategy))
.setSourceExecutor(GlideExecutor.newSourceExecutor(strategy))
.setDiskCacheExecutor(GlideExecutor.newDiskCacheExecutor(strategy)));
Glide.get(context)
.getRegistry()
.prepend(Bitmap.class, new FailEncoder())
.prepend(
BitmapDrawable.class,
new BitmapDrawableEncoder(Glide.get(context).getBitmapPool(), new FailEncoder()));
return strategy;
}
// ResourceEncoders are expected not to throw and to return true or false. If they do throw, it's
// a developer error, so we expect UncaughtThrowableStrategy to be called.
@Test
public void load_whenEncoderFails_callsUncaughtThrowableStrategy() {
WaitForErrorStrategy strategy = initializeGlideWithWaitForErrorStrategy();
concurrency.get(
Glide.with(context).load(ResourceIds.raw.canonical).listener(requestListener).submit());
// Writing to the disk cache and therefore the exception caused by our FailEncoder may happen
// after the request completes, so we should wait for the expected error explicitly.
ConcurrencyHelper.waitOnLatch(strategy.latch);
assertThat(strategy.error).isEqualTo(FailEncoder.TO_THROW);
verify(requestListener, never())
.onLoadFailed(
any(GlideException.class),
any(),
ArgumentMatchers.<Target<Drawable>>any(),
anyBoolean());
}
@Test
public void load_whenLoadSucceeds_butEncoderFails_doesNotCallOnLoadFailed() {
WaitForErrorStrategy strategy = initializeGlideWithWaitForErrorStrategy();
concurrency.get(
Glide.with(context).load(ResourceIds.raw.canonical).listener(requestListener).submit());
verify(requestListener)
.onResourceReady(
ArgumentMatchers.<Drawable>any(),
any(),
ArgumentMatchers.<Target<Drawable>>any(),
any(DataSource.class),
anyBoolean());
verify(requestListener, never())
.onLoadFailed(
any(GlideException.class),
any(),
ArgumentMatchers.<Target<Drawable>>any(),
anyBoolean());
}
@Test
public void clearRequest_withError_afterPrimaryFails_clearsErrorRequest() {
WaitModel<Integer> errorModel = WaitModelLoader.waitOn(ResourceIds.raw.canonical);
FutureTarget<Drawable> target =
Glide.with(context)
.load((Object) null)
.error(Glide.with(context).load(errorModel).listener(requestListener))
.submit();
Glide.with(context).clear(target);
errorModel.countDown();
// Make sure any pending requests run.
concurrency.pokeMainThread();
Glide.tearDown();
// Make sure that any callbacks posted back to the main thread run.
concurrency.pokeMainThread();
}
private static final | ErrorHandlingTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/env/repeatable/AbstractRepeatableTestPropertySourceTests.java | {
"start": 1183,
"end": 1409
} | class ____ integration tests involving
* {@link TestPropertySource @TestPropertySource} as a repeatable annotation.
*
* @author Sam Brannen
* @since 5.2
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration
abstract | for |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/annotations/ParamDef.java | {
"start": 1375,
"end": 1833
} | class ____ {@link Supplier} which provides arguments
* to this parameter. This is especially useful in the case of
* {@linkplain FilterDef#autoEnabled auto-enabled} filters.
* <p>
* When a resolver is specified for a filter parameter, it's not
* necessary to provide an argument for the parameter by calling
* {@link org.hibernate.Filter#setParameter(String, Object)}.
*/
Class<? extends Supplier> resolver() default Supplier.class;
}
| implementing |
java | spring-projects__spring-boot | module/spring-boot-data-mongodb/src/test/java/org/springframework/boot/data/mongodb/autoconfigure/DataMongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java | {
"start": 2032,
"end": 2932
} | class ____ {
private @Nullable AnnotationConfigApplicationContext context;
@AfterEach
void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
void shouldCreateInstancesForReactiveAndBlockingRepositories() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(BlockingAndReactiveConfiguration.class, BaseConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean(CityRepository.class)).isNotNull();
assertThat(this.context.getBean(ReactiveCityRepository.class)).isNotNull();
}
@Configuration(proxyBeanMethods = false)
@TestAutoConfigurationPackage(MongoAutoConfiguration.class)
@EnableMongoRepositories(basePackageClasses = ReactiveCityRepository.class)
@EnableReactiveMongoRepositories(basePackageClasses = ReactiveCityRepository.class)
static | DataMongoReactiveAndBlockingRepositoriesAutoConfigurationTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.