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
|
spring-projects__spring-security
|
web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java
|
{
"start": 1739,
"end": 7330
}
|
class ____ {
@AfterEach
@BeforeEach
public void clearContext() {
SecurityContextHolder.clearContext();
}
@Test
public void rejectsMissingHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class)
.isThrownBy(() -> filter.doFilter(request, response, chain));
}
@Test
public void defaultsToUsingSiteminderHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("SM_USER", "cat");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("N/A");
}
@Test
public void alternativeHeaderNameIsSupported() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("myUsernameHeader", "wolfman");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.setPrincipalRequestHeader("myUsernameHeader");
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman");
}
@Test
public void credentialsAreRetrievedIfHeaderNameIsSet() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.setCredentialsRequestHeader("myCredentialsHeader");
request.addHeader("SM_USER", "cat");
request.addHeader("myCredentialsHeader", "catspassword");
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword");
}
@Test
public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.setCheckForPrincipalChanges(true);
request.addHeader("SM_USER", "cat");
filter.doFilter(request, response, new MockFilterChain());
request = new MockHttpServletRequest();
request.addHeader("SM_USER", "dog");
filter.doFilter(request, response, new MockFilterChain());
Authentication dog = SecurityContextHolder.getContext().getAuthentication();
assertThat(dog).isNotNull();
assertThat(dog.getName()).isEqualTo("dog");
// Make sure authentication doesn't occur every time (i.e. if the header *doesn't
// change)
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.doFilter(request, response, new MockFilterChain());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(dog);
}
@Test
public void missingHeaderCausesException() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class)
.isThrownBy(() -> filter.doFilter(request, response, chain));
}
@Test
public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setExceptionIfHeaderMissing(false);
filter.setAuthenticationManager(createAuthenticationManager());
filter.doFilter(request, response, chain);
}
/**
* Create an authentication manager which returns the passed in object.
*/
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
return am;
}
}
|
RequestHeaderAuthenticationFilterTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java
|
{
"start": 35282,
"end": 35766
}
|
class ____ extends ParserRuleContext {
@SuppressWarnings("this-escape")
public DataTypeContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_dataType; }
@SuppressWarnings("this-escape")
public DataTypeContext() { }
public void copyFrom(DataTypeContext ctx) {
super.copyFrom(ctx);
}
}
@SuppressWarnings("CheckReturnValue")
public static
|
DataTypeContext
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactoryProducer.java
|
{
"start": 787,
"end": 901
}
|
interface ____ {
SessionFactoryImplementor produceSessionFactory(MetadataImplementor model);
}
|
SessionFactoryProducer
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jackson2/src/main/java/org/springframework/boot/jackson2/autoconfigure/Jackson2TesterTestAutoConfiguration.java
|
{
"start": 1960,
"end": 2317
}
|
class ____ {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@ConditionalOnBean(ObjectMapper.class)
@ImportRuntimeHints(Jackson2TesterRuntimeHints.class)
FactoryBean<Jackson2Tester<?>> jackson2TesterFactoryBean(ObjectMapper mapper) {
return new JsonTesterFactoryBean<>(Jackson2Tester.class, mapper);
}
static
|
Jackson2TesterTestAutoConfiguration
|
java
|
quarkusio__quarkus
|
extensions/panache/hibernate-orm-rest-data-panache/deployment/src/main/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/ResourceImplementor.java
|
{
"start": 1623,
"end": 10200
}
|
class ____ registered as beans and are later used in the generated JAX-RS controllers.
*/
String implement(ClassOutput classOutput, DataAccessImplementor dataAccessImplementor, ClassInfo resourceInterface,
String entityType, List<ClassInfo> resourceMethodListeners) {
String resourceType = resourceInterface.name().toString();
String className = resourceType + "Impl_" + HashUtil.sha1(resourceType);
LOGGER.tracef("Starting generation of '%s'", className);
ClassCreator classCreator = ClassCreator.builder()
.classOutput(classOutput)
.className(className)
.interfaces(resourceType)
.build();
classCreator.addAnnotation(ApplicationScoped.class);
// The same resource is generated as part of the JaxRsResourceImplementor, so we need to avoid ambiguous resolution
// when injecting the resource in user beans:
classCreator.addAnnotation(Alternative.class);
classCreator.addAnnotation(Priority.class).add("value", Integer.MAX_VALUE);
HibernateORMResourceMethodListenerImplementor listenerImplementor = new HibernateORMResourceMethodListenerImplementor(
classCreator,
resourceMethodListeners);
implementList(classCreator, dataAccessImplementor);
implementListWithQuery(classCreator, dataAccessImplementor);
implementListPageCount(classCreator, dataAccessImplementor);
implementCount(classCreator, dataAccessImplementor);
implementGet(classCreator, dataAccessImplementor);
implementAdd(classCreator, dataAccessImplementor, listenerImplementor);
implementUpdate(classCreator, dataAccessImplementor, entityType, listenerImplementor);
implementDelete(classCreator, dataAccessImplementor, listenerImplementor);
classCreator.close();
LOGGER.tracef("Completed generation of '%s'", className);
return className;
}
private void implementList(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator("list", List.class, Page.class, Sort.class);
ResultHandle page = methodCreator.getMethodParam(0);
ResultHandle sort = methodCreator.getMethodParam(1);
ResultHandle columns = methodCreator.invokeVirtualMethod(ofMethod(Sort.class, "getColumns", List.class), sort);
ResultHandle isEmptySort = methodCreator.invokeInterfaceMethod(ofMethod(List.class, "isEmpty", boolean.class), columns);
BranchResult isEmptySortBranch = methodCreator.ifTrue(isEmptySort);
isEmptySortBranch.trueBranch().returnValue(dataAccessImplementor.findAll(isEmptySortBranch.trueBranch(), page));
isEmptySortBranch.falseBranch().returnValue(dataAccessImplementor.findAll(isEmptySortBranch.falseBranch(), page, sort));
methodCreator.close();
}
private void implementListWithQuery(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator("list", List.class, Page.class, Sort.class,
String.class, Map.class);
ResultHandle page = methodCreator.getMethodParam(0);
ResultHandle sort = methodCreator.getMethodParam(1);
ResultHandle query = methodCreator.getMethodParam(2);
ResultHandle queryParams = methodCreator.getMethodParam(3);
ResultHandle columns = methodCreator.invokeVirtualMethod(ofMethod(Sort.class, "getColumns", List.class), sort);
ResultHandle isEmptySort = methodCreator.invokeInterfaceMethod(ofMethod(List.class, "isEmpty", boolean.class), columns);
BranchResult isEmptySortBranch = methodCreator.ifTrue(isEmptySort);
isEmptySortBranch.trueBranch().returnValue(dataAccessImplementor.findAll(isEmptySortBranch.trueBranch(), page, query,
queryParams));
isEmptySortBranch.falseBranch().returnValue(dataAccessImplementor.findAll(isEmptySortBranch.falseBranch(), page, sort,
query, queryParams));
methodCreator.close();
}
/**
* Generate list page count method.
* This method is used when building page URLs for list operation response and is not exposed to a user.
*/
private void implementListPageCount(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator(Constants.PAGE_COUNT_METHOD_PREFIX + "list", int.class,
Page.class, String.class, Map.class);
ResultHandle page = methodCreator.getMethodParam(0);
ResultHandle query = methodCreator.getMethodParam(1);
ResultHandle queryParams = methodCreator.getMethodParam(2);
methodCreator.returnValue(dataAccessImplementor.pageCount(methodCreator, page, query, queryParams));
methodCreator.close();
}
/**
* Generate count method.
*/
private void implementCount(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator("count", long.class);
methodCreator.returnValue(dataAccessImplementor.count(methodCreator));
methodCreator.close();
}
private void implementGet(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator("get", Object.class, Object.class);
ResultHandle id = methodCreator.getMethodParam(0);
methodCreator.returnValue(dataAccessImplementor.findById(methodCreator, id));
methodCreator.close();
}
private void implementAdd(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor,
HibernateORMResourceMethodListenerImplementor resourceMethodListenerImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator("add", Object.class, Object.class);
methodCreator.addAnnotation(Transactional.class);
ResultHandle entity = methodCreator.getMethodParam(0);
resourceMethodListenerImplementor.onBeforeAdd(methodCreator, entity);
ResultHandle createdEntity = dataAccessImplementor.persist(methodCreator, entity);
resourceMethodListenerImplementor.onAfterAdd(methodCreator, createdEntity);
methodCreator.returnValue(createdEntity);
methodCreator.close();
}
private void implementUpdate(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor, String entityType,
HibernateORMResourceMethodListenerImplementor resourceMethodListenerImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator("update", Object.class, Object.class, Object.class);
methodCreator.addAnnotation(Transactional.class);
ResultHandle id = methodCreator.getMethodParam(0);
ResultHandle entity = methodCreator.getMethodParam(1);
// Set entity ID before executing an update to make sure that a requested object ID matches a given entity ID.
setId(methodCreator, entityType, entity, id);
resourceMethodListenerImplementor.onBeforeUpdate(methodCreator, entity);
ResultHandle updatedEntity = dataAccessImplementor.update(methodCreator, entity);
resourceMethodListenerImplementor.onAfterUpdate(methodCreator, updatedEntity);
methodCreator.returnValue(updatedEntity);
methodCreator.close();
}
private void implementDelete(ClassCreator classCreator, DataAccessImplementor dataAccessImplementor,
HibernateORMResourceMethodListenerImplementor resourceMethodListenerImplementor) {
MethodCreator methodCreator = classCreator.getMethodCreator("delete", boolean.class, Object.class);
methodCreator.addAnnotation(Transactional.class);
ResultHandle id = methodCreator.getMethodParam(0);
resourceMethodListenerImplementor.onBeforeDelete(methodCreator, id);
ResultHandle deleted = dataAccessImplementor.deleteById(methodCreator, id);
resourceMethodListenerImplementor.onAfterDelete(methodCreator, id);
methodCreator.returnValue(deleted);
methodCreator.close();
}
private void setId(BytecodeCreator creator, String entityType, ResultHandle entity, ResultHandle id) {
FieldInfo idField = entityClassHelper.getIdField(entityType);
MethodDescriptor idSetter = entityClassHelper.getSetter(entityType, idField);
creator.invokeVirtualMethod(idSetter, entity, id);
}
}
|
are
|
java
|
spring-projects__spring-security
|
web/src/main/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluator.java
|
{
"start": 3336,
"end": 3838
}
|
interface ____ {
HttpServletRequestTransformer IDENTITY = (request) -> request;
/**
* Return the {@link HttpServletRequest} that is passed into the
* {@link AuthorizationManager}
* @param request the {@link HttpServletRequest} created by the
* {@link WebInvocationPrivilegeEvaluator}
* @return the {@link HttpServletRequest} that is passed into the
* {@link AuthorizationManager}
*/
HttpServletRequest transform(HttpServletRequest request);
}
}
|
HttpServletRequestTransformer
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/remove/RemoveAndOrderUpdateTest.java
|
{
"start": 3071,
"end": 3738
}
|
class ____ {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "formVersion")
private List<FormInput> inputs;
@EmbeddedId
protected FormVersionId id;
public FormVersionId getId() {
return id;
}
public void setId(FormVersionId id) {
this.id = id;
}
public FormVersion() {
id = new FormVersionId();
}
public FormVersion(Form form, int version) {
this();
this.id.setForm( form );
this.id.setVersionNumber( version );
}
public List<FormInput> getInputs() {
return inputs;
}
public void setInputs(List<FormInput> inputs) {
this.inputs = inputs;
}
}
@Embeddable
public static
|
FormVersion
|
java
|
apache__flink
|
flink-metrics/flink-metrics-core/src/main/java/org/apache/flink/metrics/LogicalScopeProvider.java
|
{
"start": 1222,
"end": 2904
}
|
interface ____ {
/**
* Returns the logical scope for the metric group, for example {@code "taskmanager.job.task"},
* with the given filter being applied to all scope components.
*
* @param filter filter to apply to all scope components
* @return logical scope
*/
String getLogicalScope(CharacterFilter filter);
/**
* Returns the logical scope for the metric group, for example {@code "taskmanager.job.task"},
* with the given filter being applied to all scope components and the given delimiter being
* used to concatenate scope components.
*
* @param filter filter to apply to all scope components
* @param delimiter delimiter to use for concatenating scope components
* @return logical scope
*/
String getLogicalScope(CharacterFilter filter, char delimiter);
/** Returns the underlying metric group. */
MetricGroup getWrappedMetricGroup();
/**
* Casts the given metric group to a {@link LogicalScopeProvider}, if it implements the
* interface.
*
* @param metricGroup metric group to cast
* @return cast metric group
* @throws IllegalStateException if the metric group did not implement the LogicalScopeProvider
* interface
*/
static LogicalScopeProvider castFrom(MetricGroup metricGroup) throws IllegalStateException {
if (metricGroup instanceof LogicalScopeProvider) {
return (LogicalScopeProvider) metricGroup;
} else {
throw new IllegalStateException(
"The given metric group does not implement the LogicalScopeProvider interface.");
}
}
}
|
LogicalScopeProvider
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/join/OuterJoinRecordReader.java
|
{
"start": 1222,
"end": 1666
}
|
class ____<K extends WritableComparable>
extends JoinRecordReader<K> {
OuterJoinRecordReader(int id, JobConf conf, int capacity,
Class<? extends WritableComparator> cmpcl) throws IOException {
super(id, conf, capacity, cmpcl);
}
/**
* Emit everything from the collector.
*/
protected boolean combine(Object[] srcs, TupleWritable dst) {
assert srcs.length == dst.size();
return true;
}
}
|
OuterJoinRecordReader
|
java
|
mockito__mockito
|
mockito-core/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java
|
{
"start": 7012,
"end": 8213
}
|
class ____ extends ReturnsDeepStubs
implements Serializable {
@SuppressWarnings("serial") // not gonna be serialized
private final GenericMetadataSupport returnTypeGenericMetadata;
public ReturnsDeepStubsSerializationFallback(
GenericMetadataSupport returnTypeGenericMetadata) {
this.returnTypeGenericMetadata = returnTypeGenericMetadata;
}
@Override
protected GenericMetadataSupport actualParameterizedType(Object mock) {
return returnTypeGenericMetadata;
}
/**
* Generics support and serialization with deep stubs don't work together.
* <p>
* The issue is that GenericMetadataSupport is not serializable because
* the type elements inferred via reflection are not serializable. Supporting
* serialization would require to replace all types coming from the Java reflection
* with our own and still managing type equality with the JDK ones.
*/
private Object writeReplace() throws IOException {
return Mockito.RETURNS_DEEP_STUBS;
}
}
private static
|
ReturnsDeepStubsSerializationFallback
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/azureopenai/embeddings/AzureOpenAiEmbeddingsServiceSettings.java
|
{
"start": 2586,
"end": 12704
}
|
class ____ extends FilteredXContentObject
implements
ServiceSettings,
AzureOpenAiRateLimitServiceSettings {
public static final String NAME = "azure_openai_embeddings_service_settings";
static final String DIMENSIONS_SET_BY_USER = "dimensions_set_by_user";
/**
* Rate limit documentation can be found here:
* Limits per region per model id
* https://learn.microsoft.com/en-us/azure/ai-services/openai/quotas-limits
*
* How to change the limits
* https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/quota?tabs=rest
*
* Blog giving some examples
* https://techcommunity.microsoft.com/t5/fasttrack-for-azure/optimizing-azure-openai-a-guide-to-limits-quotas-and-best/ba-p/4076268
*
* According to the docs 1000 tokens per minute (TPM) = 6 requests per minute (RPM). The limits change depending on the region
* and model. The lowest text embedding limit is 240K TPM, so we'll default to that.
* Calculation: 240K TPM = 240 * 6 = 1440 requests per minute (used `eastus` and `Text-Embedding-Ada-002` as basis for the calculation).
*/
private static final RateLimitSettings DEFAULT_RATE_LIMIT_SETTINGS = new RateLimitSettings(1_440);
public static AzureOpenAiEmbeddingsServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) {
ValidationException validationException = new ValidationException();
var settings = fromMap(map, validationException, context);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return new AzureOpenAiEmbeddingsServiceSettings(settings);
}
private static CommonFields fromMap(
Map<String, Object> map,
ValidationException validationException,
ConfigurationParseContext context
) {
String resourceName = extractRequiredString(map, RESOURCE_NAME, ModelConfigurations.SERVICE_SETTINGS, validationException);
String deploymentId = extractRequiredString(map, DEPLOYMENT_ID, ModelConfigurations.SERVICE_SETTINGS, validationException);
String apiVersion = extractRequiredString(map, API_VERSION, ModelConfigurations.SERVICE_SETTINGS, validationException);
Integer dims = extractOptionalPositiveInteger(map, DIMENSIONS, ModelConfigurations.SERVICE_SETTINGS, validationException);
Integer maxTokens = extractOptionalPositiveInteger(
map,
MAX_INPUT_TOKENS,
ModelConfigurations.SERVICE_SETTINGS,
validationException
);
SimilarityMeasure similarity = extractSimilarity(map, ModelConfigurations.SERVICE_SETTINGS, validationException);
RateLimitSettings rateLimitSettings = RateLimitSettings.of(
map,
DEFAULT_RATE_LIMIT_SETTINGS,
validationException,
AzureOpenAiService.NAME,
context
);
Boolean dimensionsSetByUser = extractOptionalBoolean(map, DIMENSIONS_SET_BY_USER, validationException);
switch (context) {
case REQUEST -> {
if (dimensionsSetByUser != null) {
validationException.addValidationError(
ServiceUtils.invalidSettingError(DIMENSIONS_SET_BY_USER, ModelConfigurations.SERVICE_SETTINGS)
);
}
dimensionsSetByUser = dims != null;
}
case PERSISTENT -> {
if (dimensionsSetByUser == null) {
validationException.addValidationError(
InferenceUtils.missingSettingErrorMsg(DIMENSIONS_SET_BY_USER, ModelConfigurations.SERVICE_SETTINGS)
);
}
}
}
return new CommonFields(
resourceName,
deploymentId,
apiVersion,
dims,
Boolean.TRUE.equals(dimensionsSetByUser),
maxTokens,
similarity,
rateLimitSettings
);
}
private record CommonFields(
String resourceName,
String deploymentId,
String apiVersion,
@Nullable Integer dimensions,
Boolean dimensionsSetByUser,
@Nullable Integer maxInputTokens,
@Nullable SimilarityMeasure similarity,
RateLimitSettings rateLimitSettings
) {}
private final String resourceName;
private final String deploymentId;
private final String apiVersion;
private final Integer dimensions;
private final Boolean dimensionsSetByUser;
private final Integer maxInputTokens;
private final SimilarityMeasure similarity;
private final RateLimitSettings rateLimitSettings;
public AzureOpenAiEmbeddingsServiceSettings(
String resourceName,
String deploymentId,
String apiVersion,
@Nullable Integer dimensions,
Boolean dimensionsSetByUser,
@Nullable Integer maxInputTokens,
@Nullable SimilarityMeasure similarity,
@Nullable RateLimitSettings rateLimitSettings
) {
this.resourceName = resourceName;
this.deploymentId = deploymentId;
this.apiVersion = apiVersion;
this.dimensions = dimensions;
this.dimensionsSetByUser = Objects.requireNonNull(dimensionsSetByUser);
this.maxInputTokens = maxInputTokens;
this.similarity = similarity;
this.rateLimitSettings = Objects.requireNonNullElse(rateLimitSettings, DEFAULT_RATE_LIMIT_SETTINGS);
}
public AzureOpenAiEmbeddingsServiceSettings(StreamInput in) throws IOException {
resourceName = in.readString();
deploymentId = in.readString();
apiVersion = in.readString();
dimensions = in.readOptionalVInt();
dimensionsSetByUser = in.readBoolean();
maxInputTokens = in.readOptionalVInt();
similarity = in.readOptionalEnum(SimilarityMeasure.class);
rateLimitSettings = new RateLimitSettings(in);
}
private AzureOpenAiEmbeddingsServiceSettings(CommonFields fields) {
this(
fields.resourceName,
fields.deploymentId,
fields.apiVersion,
fields.dimensions,
fields.dimensionsSetByUser,
fields.maxInputTokens,
fields.similarity,
fields.rateLimitSettings
);
}
@Override
public RateLimitSettings rateLimitSettings() {
return rateLimitSettings;
}
@Override
public String resourceName() {
return resourceName;
}
@Override
public String deploymentId() {
return deploymentId;
}
public String apiVersion() {
return apiVersion;
}
@Override
public Integer dimensions() {
return dimensions;
}
public Boolean dimensionsSetByUser() {
return dimensionsSetByUser;
}
public Integer maxInputTokens() {
return maxInputTokens;
}
@Override
public SimilarityMeasure similarity() {
return similarity;
}
@Override
public DenseVectorFieldMapper.ElementType elementType() {
return DenseVectorFieldMapper.ElementType.FLOAT;
}
@Override
public String modelId() {
return null;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
toXContentFragmentOfExposedFields(builder, params);
builder.field(DIMENSIONS_SET_BY_USER, dimensionsSetByUser);
builder.endObject();
return builder;
}
@Override
protected XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException {
builder.field(RESOURCE_NAME, resourceName);
builder.field(DEPLOYMENT_ID, deploymentId);
builder.field(API_VERSION, apiVersion);
if (dimensions != null) {
builder.field(DIMENSIONS, dimensions);
}
if (maxInputTokens != null) {
builder.field(MAX_INPUT_TOKENS, maxInputTokens);
}
if (similarity != null) {
builder.field(SIMILARITY, similarity);
}
rateLimitSettings.toXContent(builder, params);
return builder;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_14_0;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(resourceName);
out.writeString(deploymentId);
out.writeString(apiVersion);
out.writeOptionalVInt(dimensions);
out.writeBoolean(dimensionsSetByUser);
out.writeOptionalVInt(maxInputTokens);
out.writeOptionalEnum(SimilarityMeasure.translateSimilarity(similarity, out.getTransportVersion()));
rateLimitSettings.writeTo(out);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AzureOpenAiEmbeddingsServiceSettings that = (AzureOpenAiEmbeddingsServiceSettings) o;
return Objects.equals(resourceName, that.resourceName)
&& Objects.equals(deploymentId, that.deploymentId)
&& Objects.equals(apiVersion, that.apiVersion)
&& Objects.equals(dimensions, that.dimensions)
&& Objects.equals(dimensionsSetByUser, that.dimensionsSetByUser)
&& Objects.equals(maxInputTokens, that.maxInputTokens)
&& Objects.equals(similarity, that.similarity)
&& Objects.equals(rateLimitSettings, that.rateLimitSettings);
}
@Override
public int hashCode() {
return Objects.hash(
resourceName,
deploymentId,
apiVersion,
dimensions,
dimensionsSetByUser,
maxInputTokens,
similarity,
rateLimitSettings
);
}
}
|
AzureOpenAiEmbeddingsServiceSettings
|
java
|
processing__processing4
|
app/src/processing/app/contrib/LocalContribution.java
|
{
"start": 1439,
"end": 4284
}
|
class ____ extends Contribution {
static public final String DELETION_FLAG = "marked_for_deletion";
static public final String UPDATE_FLAGGED = "marked_for_update";
// static public final String RESTART_FLAG = "requires_restart";
protected String id; // 1 (unique id for this library)
protected File folder;
protected StringDict properties;
protected ClassLoader loader;
public LocalContribution(File folder) {
this.folder = folder;
// required for contributed modes, but not for built-in core modes
File propertiesFile = new File(folder, getTypeName() + ".properties");
if (propertiesFile.exists()) {
properties = Util.readSettings(propertiesFile, false);
if (properties != null) {
name = properties.get("name");
id = properties.get("id");
categories = parseCategories(properties);
// Only used by Libraries and Modes
imports = parseImports(properties, IMPORTS_PROPERTY);
exports = parseImports(properties, EXPORTS_PROPERTY);
if (name == null) {
name = folder.getName();
}
// changed 'authorList' to 'authors' in 3.0a11
authors = properties.get(AUTHORS_PROPERTY);
url = properties.get("url");
sentence = properties.get("sentence");
paragraph = properties.get("paragraph");
try {
version = Integer.parseInt(properties.get("version"));
} catch (NumberFormatException e) {
System.err.println("The version number for the “" + name + "” library is not a number.");
System.err.println("Please contact the library author to fix it according to the guidelines.");
}
setPrettyVersion(properties.get("prettyVersion"));
try {
lastUpdated = Long.parseLong(properties.get("lastUpdated"));
} catch (NumberFormatException e) {
lastUpdated = 0;
}
String minRev = properties.get("minRevision");
if (minRev != null) {
minRevision = PApplet.parseInt(minRev, 0);
}
String maxRev = properties.get("maxRevision");
if (maxRev != null) {
maxRevision = PApplet.parseInt(maxRev, 0);
}
} else {
Messages.log("Could not read " + propertiesFile.getAbsolutePath());
}
} else {
Messages.log("No properties file at " + propertiesFile.getAbsolutePath());
}
if (name == null) { // fall-through case
// We'll need this to be set at a minimum.
name = folder.getName();
categories = new StringList(UNKNOWN_CATEGORY);
}
}
public String initLoader(String className) throws Exception {
File modeDirectory = new File(folder, getTypeName());
if (modeDirectory.exists()) {
Messages.log("checking mode folder regarding " + className);
// If no
|
LocalContribution
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/objectid/TestObjectIdDeserialization.java
|
{
"start": 2541,
"end": 2851
}
|
class ____
{
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,
property="customId")
public ValueNodeExt node;
public IdWrapperExt() { }
public IdWrapperExt(int v) {
node = new ValueNodeExt(v);
}
}
static
|
IdWrapperExt
|
java
|
junit-team__junit5
|
junit-platform-launcher/src/main/java/org/junit/platform/launcher/core/LauncherFactory.java
|
{
"start": 2165,
"end": 2895
}
|
interface ____ declared.
*
* <p>By default, test execution listeners are discovered at runtime via the
* {@link java.util.ServiceLoader ServiceLoader} mechanism and are
* automatically registered with the {@link Launcher} created by this factory.
* Users may register additional listeners using the
* {@link Launcher#registerTestExecutionListeners(TestExecutionListener...)}
* method on the created launcher instance.
*
* <p>For full control over automatic registration and programmatic registration
* of test engines and listeners, supply an instance of {@link LauncherConfig}
* to {@link #create(LauncherConfig)}.
*
* @since 1.0
* @see Launcher
* @see LauncherConfig
*/
@API(status = STABLE, since = "1.0")
public
|
is
|
java
|
micronaut-projects__micronaut-core
|
json-core/src/main/java/io/micronaut/json/bind/JsonBeanPropertyBinderExceptionHandler.java
|
{
"start": 1050,
"end": 1549
}
|
interface ____ {
/**
* Attempt to convert the given exception to a {@link ConversionErrorException}.
*
* @param object The object that was supposed to be updated, or {@code null}.
* @param e The exception that occurred during mapping.
* @return The conversion error, or an empty value if default handling should be used.
*/
Optional<ConversionErrorException> toConversionError(@Nullable Object object, @NonNull Exception e);
}
|
JsonBeanPropertyBinderExceptionHandler
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java
|
{
"start": 1268,
"end": 4380
}
|
class ____ {
private HandlerMethodReturnValueHandlerComposite handlers = new HandlerMethodReturnValueHandlerComposite();
private HandlerMethodReturnValueHandler integerHandler = mock();
private ModelAndViewContainer mavContainer = new ModelAndViewContainer();
private MethodParameter integerType;
private MethodParameter stringType;
@BeforeEach
void setup() throws Exception {
this.integerType = new MethodParameter(getClass().getDeclaredMethod("handleInteger"), -1);
this.stringType = new MethodParameter(getClass().getDeclaredMethod("handleString"), -1);
given(this.integerHandler.supportsReturnType(this.integerType)).willReturn(true);
this.handlers.addHandler(this.integerHandler);
}
@Test
void supportsReturnType() {
assertThat(this.handlers.supportsReturnType(this.integerType)).isTrue();
assertThat(this.handlers.supportsReturnType(this.stringType)).isFalse();
}
@Test
void handleReturnValue() throws Exception {
this.handlers.handleReturnValue(55, this.integerType, this.mavContainer, null);
verify(this.integerHandler).handleReturnValue(55, this.integerType, this.mavContainer, null);
}
@Test
void handleReturnValueWithMultipleHandlers() throws Exception {
HandlerMethodReturnValueHandler anotherIntegerHandler = mock();
given(anotherIntegerHandler.supportsReturnType(this.integerType)).willReturn(true);
this.handlers.handleReturnValue(55, this.integerType, this.mavContainer, null);
verify(this.integerHandler).handleReturnValue(55, this.integerType, this.mavContainer, null);
verifyNoMoreInteractions(anotherIntegerHandler);
}
@Test // SPR-13083
void handleReturnValueWithAsyncHandler() throws Exception {
Promise<Integer> promise = new Promise<>();
MethodParameter promiseType = new MethodParameter(getClass().getDeclaredMethod("handlePromise"), -1);
HandlerMethodReturnValueHandler responseBodyHandler = mock();
given(responseBodyHandler.supportsReturnType(promiseType)).willReturn(true);
this.handlers.addHandler(responseBodyHandler);
AsyncHandlerMethodReturnValueHandler promiseHandler = mock();
given(promiseHandler.supportsReturnType(promiseType)).willReturn(true);
given(promiseHandler.isAsyncReturnValue(promise, promiseType)).willReturn(true);
this.handlers.addHandler(promiseHandler);
this.handlers.handleReturnValue(promise, promiseType, this.mavContainer, null);
verify(promiseHandler).isAsyncReturnValue(promise, promiseType);
verify(promiseHandler).supportsReturnType(promiseType);
verify(promiseHandler).handleReturnValue(promise, promiseType, this.mavContainer, null);
verifyNoMoreInteractions(promiseHandler);
verifyNoMoreInteractions(responseBodyHandler);
}
@Test
void noSuitableReturnValueHandler() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() ->
this.handlers.handleReturnValue("value", this.stringType, null, null));
}
private Integer handleInteger() {
return null;
}
private String handleString() {
return null;
}
private Promise<Integer> handlePromise() {
return null;
}
private static
|
HandlerMethodReturnValueHandlerCompositeTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/OverriddenFieldTest.java
|
{
"start": 1142,
"end": 1556
}
|
class ____ {
@Test
public void test(SessionFactoryScope scope) {
scope.inTransaction( s -> {
Fruit testEntity = new Fruit();
testEntity.setId( 1 );
testEntity.setName( "John" );
s.persist( testEntity );
} );
scope.inTransaction( s -> {
Fruit testEntity = s.get( Fruit.class, 1 );
assertEquals( "John", testEntity.getName() );
} );
}
@MappedSuperclass
public static
|
OverriddenFieldTest
|
java
|
grpc__grpc-java
|
xds/src/generated/thirdparty/grpc/io/envoyproxy/envoy/service/status/v3/ClientStatusDiscoveryServiceGrpc.java
|
{
"start": 15940,
"end": 18448
}
|
class ____<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_FETCH_CLIENT_STATUS:
serviceImpl.fetchClientStatus((io.envoyproxy.envoy.service.status.v3.ClientStatusRequest) request,
(io.grpc.stub.StreamObserver<io.envoyproxy.envoy.service.status.v3.ClientStatusResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_STREAM_CLIENT_STATUS:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.streamClientStatus(
(io.grpc.stub.StreamObserver<io.envoyproxy.envoy.service.status.v3.ClientStatusResponse>) responseObserver);
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getStreamClientStatusMethod(),
io.grpc.stub.ServerCalls.asyncBidiStreamingCall(
new MethodHandlers<
io.envoyproxy.envoy.service.status.v3.ClientStatusRequest,
io.envoyproxy.envoy.service.status.v3.ClientStatusResponse>(
service, METHODID_STREAM_CLIENT_STATUS)))
.addMethod(
getFetchClientStatusMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
io.envoyproxy.envoy.service.status.v3.ClientStatusRequest,
io.envoyproxy.envoy.service.status.v3.ClientStatusResponse>(
service, METHODID_FETCH_CLIENT_STATUS)))
.build();
}
private static abstract
|
MethodHandlers
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/deser/filter/UnknownPropertyDeserTest.java
|
{
"start": 967,
"end": 1100
}
|
class ____
* just marks unknown property/ies when encountered, along with
* Json value of the property.
*/
static
|
that
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy-qute/deployment/src/test/java/io/quarkus/qute/resteasy/deployment/HelloResource.java
|
{
"start": 393,
"end": 455
}
|
class ____ {
@CheckedTemplate
public static
|
HelloResource
|
java
|
quarkusio__quarkus
|
integration-tests/oidc-tenancy/src/test/java/io/quarkus/it/keycloak/AnnotationBasedTenantTest.java
|
{
"start": 254,
"end": 3892
}
|
class ____ {
@Test
public void testJaxRsHttpSecurityPolicyNoRbac() {
String token = getTokenWithRole("role1");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo/jax-rs-perm-check")
.then().statusCode(200)
.body(Matchers.equalTo(("tenant-id=tenant-public-key, static.tenant.id=tenant-public-key, name=alice")));
token = getTokenWithRole("wrong-role");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo/jax-rs-perm-check")
.then().statusCode(403);
}
@Test
public void testJaxRsHttpSecurityPolicyWithRbac() {
String token = getTokenWithRole("role1");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo2/jax-rs-perm-check")
.then().statusCode(200)
.body(Matchers.equalTo(("tenant-id=tenant-public-key, static.tenant.id=tenant-public-key, name=alice")));
token = getTokenWithRole("wrong-role");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo2/jax-rs-perm-check")
.then().statusCode(403);
}
@Test
public void testClassicHttpSecurityPolicyWithRbac() {
// authentication fails as tenant id is not selected when non-JAX-RS permission check is performed
String token = getTokenWithRole("role1");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo2/classic-perm-check")
.then().statusCode(401);
}
@Test
public void testJaxRsAndClassicHttpSecurityPolicyNoRbac() {
// authentication fails as tenant id is not selected when non-JAX-RS permission check is performed
RestAssured.given().auth().oauth2(getTokenWithRole("role3", "role2", "role1"))
.when().get("/api/tenant-echo/classic-and-jaxrs-perm-check")
.then().statusCode(401);
}
@Test
public void testJaxRsAndClassicHttpSecurityPolicyWithRbac() {
// authentication fails as tenant id is not selected when non-JAX-RS permission check is performed
RestAssured.given().auth().oauth2(getTokenWithRole("role2", "role1"))
.when().get("/api/tenant-echo2/classic-and-jaxrs-perm-check")
.then().statusCode(401);
}
@Test
public void testJaxRsIdentityAugmentation() {
// pass JAX-RS permission check but missing permission
String token = getTokenWithRole("role2");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo/hr-identity-augmentation")
.then().statusCode(403);
token = getTokenWithRole("role3");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo/hr-identity-augmentation")
.then().statusCode(200)
.body(Matchers.equalTo(("tenant-id=tenant-public-key, static.tenant.id=tenant-public-key, name=alice")));
// test mapped role can be used by a roles policy
token = getTokenWithRole("role4");
RestAssured.given().auth().oauth2(token)
.when().get("/api/tenant-echo/hr-identity-augmentation")
.then().statusCode(200)
.body(Matchers.equalTo(("tenant-id=tenant-public-key, static.tenant.id=tenant-public-key, name=alice")));
}
static String getTokenWithRole(String... roles) {
return Jwt.claim("scope", "read:data").preferredUserName("alice").groups(Set.of(roles)).sign();
}
}
|
AnnotationBasedTenantTest
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/EntityTools.java
|
{
"start": 2841,
"end": 3184
}
|
class ____ to specified entity name.
*/
public static Class getEntityClass(SharedSessionContractImplementor sessionImplementor, String entityName) {
final EntityPersister entityPersister = sessionImplementor.getFactory()
.getMappingMetamodel()
.getEntityDescriptor( entityName );
return entityPersister.getMappedClass();
}
}
|
mapped
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/script/VectorScoreScriptUtils.java
|
{
"start": 9496,
"end": 10138
}
|
class ____ extends ByteDenseVectorFunction implements HammingDistanceInterface {
public ByteHammingDistance(ScoreScript scoreScript, DenseVectorDocValuesField field, List<Number> queryVector) {
super(scoreScript, field, queryVector, false, ElementType.BYTE);
}
public ByteHammingDistance(ScoreScript scoreScript, DenseVectorDocValuesField field, byte[] queryVector) {
super(scoreScript, field, queryVector);
}
public int hamming() {
setNextVector();
return field.get().hamming(byteQueryVector);
}
}
public static final
|
ByteHammingDistance
|
java
|
grpc__grpc-java
|
api/src/main/java/io/grpc/InternalMethodDescriptor.java
|
{
"start": 773,
"end": 1399
}
|
class ____ {
private final InternalKnownTransport transport;
public InternalMethodDescriptor(InternalKnownTransport transport) {
// TODO(carl-mastrangelo): maybe restrict access to this.
this.transport = checkNotNull(transport, "transport");
}
@SuppressWarnings("EnumOrdinal")
public Object geRawMethodName(MethodDescriptor<?, ?> descriptor) {
return descriptor.getRawMethodName(transport.ordinal());
}
@SuppressWarnings("EnumOrdinal")
public void setRawMethodName(MethodDescriptor<?, ?> descriptor, Object o) {
descriptor.setRawMethodName(transport.ordinal(), o);
}
}
|
InternalMethodDescriptor
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/test/ssl/SSLHandshakeTimeoutTests.java
|
{
"start": 1430,
"end": 1857
}
|
class ____ extends SingleCertSSLTests {
@Test
@Override // here we validate that it the handshake times out
public void testSslTrust() {
ResponseSpec responseSpec = testClient.get().uri("/ssltrust").exchange();
responseSpec.expectStatus().is5xxServerError();
JsonPathAssertions jsonPath = responseSpec.expectBody().jsonPath("message");
jsonPath.isEqualTo("handshake timed out after 1ms");
}
}
|
SSLHandshakeTimeoutTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/amazonbedrock/request/embeddings/AmazonBedrockEmbeddingsRequest.java
|
{
"start": 1667,
"end": 4216
}
|
class ____ extends AmazonBedrockRequest {
private final AmazonBedrockEmbeddingsModel embeddingsModel;
private final ToXContent requestEntity;
private final Truncator truncator;
private final Truncator.TruncationResult truncationResult;
private final AmazonBedrockProvider provider;
private ActionListener<InvokeModelResponse> listener = null;
public AmazonBedrockEmbeddingsRequest(
Truncator truncator,
Truncator.TruncationResult input,
AmazonBedrockEmbeddingsModel model,
ToXContent requestEntity,
@Nullable TimeValue timeout
) {
super(model, timeout);
this.truncator = Objects.requireNonNull(truncator);
this.truncationResult = Objects.requireNonNull(input);
this.requestEntity = Objects.requireNonNull(requestEntity);
this.embeddingsModel = model;
this.provider = model.provider();
}
public AmazonBedrockProvider provider() {
return provider;
}
@Override
protected void executeRequest(AmazonBedrockBaseClient client) {
try {
var jsonBuilder = new AmazonBedrockJsonBuilder(requestEntity);
var bodyAsString = jsonBuilder.getStringContent();
var invokeModelRequest = InvokeModelRequest.builder()
.modelId(embeddingsModel.model())
.body(SdkBytes.fromString(bodyAsString, StandardCharsets.UTF_8))
.build();
SocketAccess.doPrivileged(() -> client.invokeModel(invokeModelRequest, listener));
} catch (IOException e) {
listener.onFailure(new RuntimeException(e));
}
}
@Override
public Request truncate() {
if (provider == AmazonBedrockProvider.COHERE) {
return this; // Cohere has its own truncation logic
}
var truncatedInput = truncator.truncate(truncationResult.input());
return new AmazonBedrockEmbeddingsRequest(truncator, truncatedInput, embeddingsModel, requestEntity, timeout);
}
@Override
public boolean[] getTruncationInfo() {
return truncationResult.truncated().clone();
}
@Override
public TaskType taskType() {
return TaskType.TEXT_EMBEDDING;
}
public void executeEmbeddingsRequest(
AmazonBedrockBaseClient awsBedrockClient,
AmazonBedrockEmbeddingsResponseListener embeddingsResponseListener
) {
this.listener = embeddingsResponseListener;
this.executeRequest(awsBedrockClient);
}
}
|
AmazonBedrockEmbeddingsRequest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/query/Order.java
|
{
"start": 1928,
"end": 2358
}
|
class ____ similar to {@code jakarta.data.Sort}, and is
* used by Hibernate Data Repositories to implement Jakarta Data
* query methods.
*
* @see org.hibernate.query.specification.SelectionSpecification#sort(Order)
* @see org.hibernate.query.specification.SelectionSpecification#resort(List)
* @see org.hibernate.query.restriction.Restriction
*
* @author Gavin King
*
* @since 6.3
*/
@Incubating
public
|
is
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/statistics/impl/DynamicIOStatisticsBuilder.java
|
{
"start": 1398,
"end": 7528
}
|
class ____ {
/**
* the instance being built up. Will be null after the (single)
* call to {@link #build()}.
*/
private DynamicIOStatistics instance = new DynamicIOStatistics();
/**
* Build the IOStatistics instance.
* @return an instance.
* @throws IllegalStateException if the builder has already been built.
*/
public IOStatistics build() {
final DynamicIOStatistics stats = activeInstance();
// stop the builder from working any more.
instance = null;
return stats;
}
/**
* Get the statistics instance.
* @return the instance to build/return
* @throws IllegalStateException if the builder has already been built.
*/
private DynamicIOStatistics activeInstance() {
checkState(instance != null, "Already built");
return instance;
}
/**
* Add a new evaluator to the counter statistics.
* @param key key of this statistic
* @param eval evaluator for the statistic
* @return the builder.
*/
public DynamicIOStatisticsBuilder withLongFunctionCounter(String key,
ToLongFunction<String> eval) {
activeInstance().addCounterFunction(key, eval::applyAsLong);
return this;
}
/**
* Add a counter statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic long counter
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicLongCounter(String key,
AtomicLong source) {
withLongFunctionCounter(key, s -> source.get());
return this;
}
/**
* Add a counter statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic int counter
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicIntegerCounter(String key,
AtomicInteger source) {
withLongFunctionCounter(key, s -> source.get());
return this;
}
/**
* Build a dynamic counter statistic from a
* {@link MutableCounterLong}.
* @param key key of this statistic
* @param source mutable long counter
* @return the builder.
*/
public DynamicIOStatisticsBuilder withMutableCounter(String key,
MutableCounterLong source) {
withLongFunctionCounter(key, s -> source.value());
return this;
}
/**
* Add a new evaluator to the gauge statistics.
* @param key key of this statistic
* @param eval evaluator for the statistic
* @return the builder.
*/
public DynamicIOStatisticsBuilder withLongFunctionGauge(String key,
ToLongFunction<String> eval) {
activeInstance().addGaugeFunction(key, eval::applyAsLong);
return this;
}
/**
* Add a gauge statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic long gauge
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicLongGauge(String key,
AtomicLong source) {
withLongFunctionGauge(key, s -> source.get());
return this;
}
/**
* Add a gauge statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic int gauge
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicIntegerGauge(String key,
AtomicInteger source) {
withLongFunctionGauge(key, s -> source.get());
return this;
}
/**
* Add a new evaluator to the minimum statistics.
* @param key key of this statistic
* @param eval evaluator for the statistic
* @return the builder.
*/
public DynamicIOStatisticsBuilder withLongFunctionMinimum(String key,
ToLongFunction<String> eval) {
activeInstance().addMinimumFunction(key, eval::applyAsLong);
return this;
}
/**
* Add a minimum statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic long minimum
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicLongMinimum(String key,
AtomicLong source) {
withLongFunctionMinimum(key, s -> source.get());
return this;
}
/**
* Add a minimum statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic int minimum
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicIntegerMinimum(String key,
AtomicInteger source) {
withLongFunctionMinimum(key, s -> source.get());
return this;
}
/**
* Add a new evaluator to the maximum statistics.
* @param key key of this statistic
* @param eval evaluator for the statistic
* @return the builder.
*/
public DynamicIOStatisticsBuilder withLongFunctionMaximum(String key,
ToLongFunction<String> eval) {
activeInstance().addMaximumFunction(key, eval::applyAsLong);
return this;
}
/**
* Add a maximum statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic long maximum
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicLongMaximum(String key,
AtomicLong source) {
withLongFunctionMaximum(key, s -> source.get());
return this;
}
/**
* Add a maximum statistic to dynamically return the
* latest value of the source.
* @param key key of this statistic
* @param source atomic int maximum
* @return the builder.
*/
public DynamicIOStatisticsBuilder withAtomicIntegerMaximum(String key,
AtomicInteger source) {
withLongFunctionMaximum(key, s -> source.get());
return this;
}
/**
* Add a new evaluator to the mean statistics.
*
* This is a function which must return the mean and the sample count.
* @param key key of this statistic
* @param eval evaluator for the statistic
* @return the builder.
*/
public DynamicIOStatisticsBuilder withMeanStatisticFunction(String key,
Function<String, MeanStatistic> eval) {
activeInstance().addMeanStatisticFunction(key, eval);
return this;
}
}
|
DynamicIOStatisticsBuilder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/assignment/planning/AssignmentPlan.java
|
{
"start": 16492,
"end": 22762
}
|
class ____ {
private final Map<Deployment, Map<Node, Integer>> assignments;
private final Map<Node, Long> remainingNodeMemory;
private final Map<Node, Integer> remainingNodeCores;
private final Map<Deployment, Integer> remainingModelAllocations;
private Builder(Collection<Node> nodes, Collection<Deployment> deployments) {
if (new HashSet<>(nodes).size() != nodes.size()) {
throw new IllegalArgumentException("there should be no duplicate nodes");
}
if (new HashSet<>(deployments).size() != deployments.size()) {
throw new IllegalArgumentException("there should be no duplicate models");
}
assignments = Maps.newHashMapWithExpectedSize(nodes.size() * deployments.size());
remainingNodeMemory = Maps.newHashMapWithExpectedSize(nodes.size());
remainingNodeCores = Maps.newHashMapWithExpectedSize(nodes.size());
remainingModelAllocations = Maps.newHashMapWithExpectedSize(deployments.size());
nodes.forEach(n -> {
remainingNodeMemory.put(n, n.availableMemoryBytes());
remainingNodeCores.put(n, n.cores());
});
for (Deployment m : deployments) {
Map<Node, Integer> nodeAssignments = new HashMap<>();
for (Node n : nodes) {
nodeAssignments.put(n, 0);
}
assignments.put(m, nodeAssignments);
remainingModelAllocations.put(m, m.allocations());
}
}
int getRemainingCores(Node n) {
return remainingNodeCores.get(n);
}
long getRemainingMemory(Node n) {
return remainingNodeMemory.get(n);
}
int getRemainingThreads(Deployment m) {
return remainingModelAllocations.get(m) * m.threadsPerAllocation();
}
int getRemainingAllocations(Deployment m) {
return remainingModelAllocations.get(m);
}
boolean canAssign(Deployment deployment, Node node, int allocations) {
long requiredMemory = getDeploymentMemoryRequirement(deployment, node, allocations);
return canAssign(deployment, node, allocations, requiredMemory);
}
boolean canAssign(Deployment deployment, Node node, int allocations, long requiredMemory) {
return (requiredMemory <= remainingNodeMemory.get(node))
&& (deployment.priority == Priority.LOW || allocations * deployment.threadsPerAllocation() <= remainingNodeCores.get(node));
}
public long getDeploymentMemoryRequirement(Deployment deployment, Node node, int newAllocations) {
int assignedAllocations = getAssignedAllocations(deployment, node);
if (assignedAllocations > 0) {
return deployment.estimateAdditionalMemoryUsageBytes(assignedAllocations, assignedAllocations + newAllocations);
}
return deployment.estimateMemoryUsageBytes(newAllocations);
}
public Builder assignModelToNode(Deployment deployment, Node node, int allocations) {
return assignModelToNode(deployment, node, allocations, getDeploymentMemoryRequirement(deployment, node, allocations));
}
public Builder assignModelToNode(Deployment deployment, Node node, int allocations, long requiredMemory) {
if (allocations <= 0 || canAssign(deployment, node, allocations, requiredMemory) == false) {
return this;
}
assignments.get(deployment).compute(node, (n, assignedAllocations) -> assignedAllocations + allocations);
accountMemory(deployment, node, requiredMemory);
if (deployment.priority == Priority.NORMAL) {
remainingNodeCores.compute(node, (n, remCores) -> remCores - allocations * deployment.threadsPerAllocation());
}
remainingModelAllocations.compute(deployment, (m, remModelThreads) -> remModelThreads - allocations);
return this;
}
private int getAssignedAllocations(Deployment deployment, Node node) {
return assignments.get(deployment).get(node);
}
public void accountMemory(Deployment m, Node n, long requiredMemory) {
remainingNodeMemory.computeIfPresent(n, (k, v) -> v - requiredMemory);
if (remainingNodeMemory.containsKey(n) && remainingNodeMemory.get(n) < 0) {
throw new IllegalArgumentException("not enough memory on node [" + n.id() + "] to assign model [" + m.deploymentId() + "]");
}
}
public AssignmentPlan build() {
Map<Deployment, Map<Node, Integer>> finalAssignments = new HashMap<>();
for (Deployment m : assignments.keySet()) {
Map<Node, Integer> allocationsPerNode = new HashMap<>();
for (Map.Entry<Node, Integer> entry : assignments.get(m).entrySet()) {
if (entry.getValue() > 0) {
allocationsPerNode.put(entry.getKey(), entry.getValue());
}
}
finalAssignments.put(m, allocationsPerNode);
}
return new AssignmentPlan(
finalAssignments,
remainingNodeMemory.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().id(), Map.Entry::getValue)),
remainingNodeCores.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().id(), Map.Entry::getValue)),
remainingModelAllocations
);
}
}
private record Quality(boolean satisfiesPreviousAssignments, double allocationsScore, double memoryScore)
implements
Comparable<Quality> {
private int previousAssignmentScore() {
return satisfiesPreviousAssignments ? 1 : 0;
}
@Override
public int compareTo(Quality o) {
return Comparator.comparingInt(Quality::previousAssignmentScore)
.thenComparingDouble(Quality::allocationsScore)
.thenComparingDouble(Quality::memoryScore)
.compare(this, o);
}
}
}
|
Builder
|
java
|
quarkusio__quarkus
|
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/InjectableContext.java
|
{
"start": 2329,
"end": 2995
}
|
interface ____ encouraged to provide an optimized implementation of this method.
*
* @param state
*/
default void destroy(ContextState state) {
for (InjectableBean<?> bean : state.getContextualInstances().keySet()) {
try {
destroy(bean);
} catch (Exception e) {
throw new IllegalStateException("Unable to destroy contextual instance of " + bean, e);
}
}
}
/**
*
* @return {@code true} if this context represents a normal scope
*/
default boolean isNormal() {
return getScope().isAnnotationPresent(NormalScope.class);
}
|
are
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ConcurrentReferenceHashMap.java
|
{
"start": 11020,
"end": 11375
}
|
class ____<K> extends SoftReference<K> implements KeyReference {
final int hash;
SoftKeyReference(K key, int hash, ReferenceQueue<Object> refQueue) {
super( key, refQueue );
this.hash = hash;
}
@Override
public int keyHash() {
return hash;
}
@Override
public Object keyRef() {
return this;
}
}
static final
|
SoftKeyReference
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/StateStoreUtils.java
|
{
"start": 1342,
"end": 1539
}
|
class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(StateStoreUtils.class);
private StateStoreUtils() {
// Utility class
}
/**
* Get the base
|
StateStoreUtils
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfig.java
|
{
"start": 1352,
"end": 1619
}
|
class ____ users to configure the factory used to create
* an instance of the LMAX disruptor WaitStrategy
* used by Async Loggers in the log4j configuration.
*/
@Plugin(name = "AsyncWaitStrategyFactory", category = Core.CATEGORY_NAME, printObject = true)
public
|
allows
|
java
|
apache__kafka
|
connect/api/src/test/java/org/apache/kafka/connect/source/SourceConnectorTest.java
|
{
"start": 1710,
"end": 2437
}
|
class ____ implements SourceConnectorContext {
@Override
public void requestTaskReconfiguration() {
// Unexpected in these tests
throw new UnsupportedOperationException();
}
@Override
public void raiseError(Exception e) {
// Unexpected in these tests
throw new UnsupportedOperationException();
}
@Override
public PluginMetrics pluginMetrics() {
// Unexpected in these tests
throw new UnsupportedOperationException();
}
@Override
public OffsetStorageReader offsetStorageReader() {
return null;
}
}
private static
|
TestSourceConnectorContext
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/CustomEclipseLinkJpaVendorAdapter.java
|
{
"start": 1284,
"end": 1927
}
|
class ____ extends EclipseLinkJpaVendorAdapter {
@Override
protected String determineTargetDatabaseName(Database database) {
if (Database.HSQL.equals(database)) {
return EclipseLinkHsqlPlatform.class.getName();
}
return super.determineTargetDatabaseName(database);
}
/**
* Workaround {@link HSQLPlatform} to make sure EclipseLink uses the right syntax to call stored procedures on HSQL.
*
* @author Oliver Gierke
* @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=467072">https://bugs.eclipse.org/bugs/show_bug.cgi?id=467072</a>
*/
@SuppressWarnings("serial")
public static
|
CustomEclipseLinkJpaVendorAdapter
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/util/datetime/FastDatePrinter.java
|
{
"start": 36069,
"end": 36945
}
|
class ____ implements NumberRule {
static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
/**
* Constructs an instance of {@code TwoDigitMonthField}.
*/
TwoDigitMonthField() {}
/**
* {@inheritDoc}
*/
@Override
public int estimateLength() {
return 2;
}
/**
* {@inheritDoc}
*/
@Override
public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException {
appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
}
/**
* {@inheritDoc}
*/
@Override
public final void appendTo(final Appendable buffer, final int value) throws IOException {
appendDigits(buffer, value);
}
}
/**
* <p>Inner
|
TwoDigitMonthField
|
java
|
quarkusio__quarkus
|
integration-tests/micrometer-prometheus/src/main/java/io/quarkus/it/micrometer/prometheus/RootResource.java
|
{
"start": 128,
"end": 301
}
|
class ____ {
@Path("{rootParam}/sub")
public SubResource subResource(@PathParam("rootParam") String value) {
return new SubResource(value);
}
}
|
RootResource
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoder.java
|
{
"start": 15619,
"end": 18331
}
|
class ____ {
private static final ThrowingFunction<SecretKey, OctetSequenceKey.Builder> defaultJwk = JWKS::signing;
private final OctetSequenceKey.Builder builder;
private final Set<JWSAlgorithm> allowedAlgorithms;
private SecretKeyJwtEncoderBuilder(SecretKey secretKey) {
Assert.notNull(secretKey, "secretKey cannot be null");
Set<JWSAlgorithm> allowedAlgorithms = computeAllowedAlgorithms(secretKey);
Assert.notEmpty(allowedAlgorithms,
"This key is too small for any standard JWK symmetric signing algorithm");
this.allowedAlgorithms = allowedAlgorithms;
this.builder = defaultJwk.apply(secretKey, IllegalArgumentException::new)
.algorithm(this.allowedAlgorithms.iterator().next());
}
private Set<JWSAlgorithm> computeAllowedAlgorithms(SecretKey secretKey) {
try {
return new MACSigner(secretKey).supportedJWSAlgorithms();
}
catch (JOSEException ex) {
throw new IllegalArgumentException(ex);
}
}
/**
* Sets the JWS algorithm to use for signing. Defaults to
* {@link JWSAlgorithm#HS256}. Must be an HMAC-based algorithm (HS256, HS384, or
* HS512).
* @param macAlgorithm the {@link MacAlgorithm} to use
* @return this builder instance for method chaining
*/
public SecretKeyJwtEncoderBuilder algorithm(MacAlgorithm macAlgorithm) {
Assert.notNull(macAlgorithm, "macAlgorithm cannot be null");
JWSAlgorithm jws = JWSAlgorithm.parse(macAlgorithm.getName());
Assert.isTrue(this.allowedAlgorithms.contains(jws), String
.format("This key can only support " + "the following algorithms: [%s]", this.allowedAlgorithms));
this.builder.algorithm(JWSAlgorithm.parse(macAlgorithm.getName()));
return this;
}
/**
* Post-process the {@link JWK} using the given {@link Consumer}. For example, you
* may use this to override the default {@code kid}
* @param jwkPostProcessor the post-processor to use
* @return this builder instance for method chaining
*/
public SecretKeyJwtEncoderBuilder jwkPostProcessor(Consumer<OctetSequenceKey.Builder> jwkPostProcessor) {
Assert.notNull(jwkPostProcessor, "jwkPostProcessor cannot be null");
jwkPostProcessor.accept(this.builder);
return this;
}
/**
* Builds the {@link NimbusJwtEncoder} instance.
* @return the configured {@link NimbusJwtEncoder}
* @throws IllegalStateException if the configured JWS algorithm is not compatible
* with a {@link SecretKey}.
*/
public NimbusJwtEncoder build() {
return new NimbusJwtEncoder(this.builder.build());
}
}
/**
* A builder for creating {@link NimbusJwtEncoder} instances configured with a
* {@link KeyPair}.
*
* @since 7.0
*/
public static final
|
SecretKeyJwtEncoderBuilder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/DoubleState.java
|
{
"start": 526,
"end": 1394
}
|
class ____ implements AggregatorState {
private double value;
private boolean seen;
DoubleState(double init) {
this.value = init;
}
double doubleValue() {
return value;
}
void doubleValue(double value) {
this.value = value;
}
boolean seen() {
return seen;
}
void seen(boolean seen) {
this.seen = seen;
}
/** Extracts an intermediate view of the contents of this state. */
@Override
public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) {
assert blocks.length >= offset + 2;
blocks[offset + 0] = driverContext.blockFactory().newConstantDoubleBlockWith(value, 1);
blocks[offset + 1] = driverContext.blockFactory().newConstantBooleanBlockWith(seen, 1);
}
@Override
public void close() {}
}
|
DoubleState
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/collection/list/ListElementNullBasicTest.java
|
{
"start": 4521,
"end": 4781
}
|
class ____ {
@Id
@GeneratedValue
private int id;
@ElementCollection
@CollectionTable(name = "AnEntity_aCollection", joinColumns = { @JoinColumn(name = "AnEntity_id") })
@OrderColumn
private List<String> aCollection = new ArrayList<>();
}
}
|
AnEntity
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/archive/internal/FileInputStreamAccess.java
|
{
"start": 589,
"end": 1357
}
|
class ____ implements InputStreamAccess, Serializable {
private final String name;
private final File file;
public FileInputStreamAccess(String name, File file) {
this.name = name;
this.file = file;
if ( ! file.exists() ) {
throw new HibernateException( "File must exist : " + file.getAbsolutePath() );
}
}
@Override
public String getStreamName() {
return name;
}
@Override
public InputStream accessInputStream() {
try {
return new BufferedInputStream( new FileInputStream( file ) );
}
catch (FileNotFoundException e) {
// should never ever ever happen, but...
throw new ArchiveException(
"File believed to exist based on File.exists threw error when passed to FileInputStream ctor",
e
);
}
}
}
|
FileInputStreamAccess
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/vector/VectorMetadata.java
|
{
"start": 1101,
"end": 9974
}
|
class ____ {
private Integer dimensionality;
private QuantizationType type;
private Integer size;
private Integer maxNodeUid;
private Integer vSetUid;
private Integer maxNodes;
private Integer projectionInputDim;
private Integer attributesCount;
private Integer maxLevel;
/**
* Creates a new empty {@link VectorMetadata} instance.
* <p>
* This constructor creates an empty metadata object. The fields will be populated when the object is used to parse the
* response from a Redis VINFO command.
*/
public VectorMetadata() {
// Default constructor
}
/**
* Gets the dimensionality of the vectors in the vector set.
* <p>
* This represents the number of dimensions (features) in each vector. All vectors in a vector set must have the same
* dimensionality. Higher dimensionality vectors can represent more complex data but require more memory and processing
* power.
*
* @return the number of dimensions for each vector in the vector set, or {@code null} if not available
* @see <a href="https://redis.io/docs/latest/develop/data-types/vector-sets/memory/">Memory Optimization</a>
*/
public Integer getDimensionality() {
return dimensionality;
}
/**
* Gets the quantization type used for storing vectors in the vector set.
* <p>
* Quantization affects how vectors are stored and impacts memory usage, performance, and recall quality.
* <p>
* Common types include:
* <ul>
* <li>{@code Q8} - Uses signed 8-bit quantization, balancing memory usage and recall quality</li>
* <li>{@code NOQUANT} - Stores vectors without quantization, using more memory but preserving full precision</li>
* <li>{@code BIN} - Uses binary quantization, which is faster and uses less memory, but impacts recall quality</li>
* </ul>
*
* @return the quantization type used for the vector set, or {@code null} if not available
* @see <a href="https://redis.io/docs/latest/develop/data-types/vector-sets/performance/#quantization-effects">Quantization
* Effects</a>
*/
public QuantizationType getType() {
return type;
}
/**
* Gets the number of elements (vectors) in the vector set.
* <p>
* This represents the total count of vectors currently stored in the vector set. This is equivalent to the result of the
* {@code VCARD} command.
*
* @return the total count of vectors in the vector set, or {@code null} if not available
* @see <a href="https://redis.io/docs/latest/commands/vcard/">VCARD Command</a>
*/
public Integer getSize() {
return size;
}
/**
* Gets the maximum node UID in the HNSW graph.
* <p>
* This is an internal identifier used by Redis to track nodes in the HNSW graph. It can be useful for debugging and
* monitoring purposes.
*
* @return the maximum node UID in the HNSW graph, or {@code null} if not available
*/
public Integer getMaxNodeUid() {
return maxNodeUid;
}
/**
* Gets the unique identifier of the vector set.
* <p>
* This is an internal identifier used by Redis to track the vector set. It can be useful for debugging and monitoring
* purposes.
*
* @return the unique identifier used by Redis to track the vector set, or {@code null} if not available
*/
public Integer getvSetUid() {
return vSetUid;
}
/**
* Gets the maximum number of connections per node in the HNSW graph.
* <p>
* This parameter (also known as M) specifies the maximum number of connections that each node of the graph will have with
* other nodes. More connections means more memory, but provides for more efficient graph exploration.
* <p>
* Higher values improve recall at the cost of memory usage and indexing speed.
*
* @return the maximum number of connections per node, or {@code null} if not available
* @see <a href="https://redis.io/docs/latest/develop/data-types/vector-sets/performance/#hnsw-parameters">HNSW
* Parameters</a>
*/
public Integer getMaxNodes() {
return maxNodes;
}
/**
* Gets the original dimensionality of vectors before dimensionality reduction.
* <p>
* When using the REDUCE option with VADD, this field indicates the original dimensionality of the vectors before they were
* projected to a lower-dimensional space.
*
* @return the original dimensionality before reduction, or {@code null} if dimensionality reduction is not used
* @see <a href=
* "https://redis.io/docs/latest/develop/data-types/vector-sets/memory/#dimensionality-reduction">Dimensionality
* Reduction</a>
*/
public Integer getProjectionInputDim() {
return projectionInputDim;
}
/**
* Gets the number of elements in the vector set that have attributes.
* <p>
* Attributes are JSON metadata associated with vector elements that can be used for filtering in similarity searches.
*
* @return the number of elements with attributes, or {@code null} if not available
* @see <a href="https://redis.io/docs/latest/develop/data-types/vector-sets/filtered-search/">Filtered Search</a>
*/
public Integer getAttributesCount() {
return attributesCount;
}
/**
* Gets the maximum level in the HNSW graph.
* <p>
* The HNSW algorithm organizes vectors in a hierarchical graph with multiple levels. This parameter indicates the highest
* level in the graph structure.
* <p>
* Higher levels enable faster navigation through the graph during similarity searches.
*
* @return the maximum level in the HNSW graph, or {@code null} if not available
* @see <a href="https://redis.io/docs/latest/develop/data-types/vector-sets/performance/#hnsw-parameters">HNSW
* Parameters</a>
*/
public Integer getMaxLevel() {
return maxLevel;
}
/**
* Sets the dimensionality of the vectors in the vector set.
*
* @param value the number of dimensions for each vector in the vector set
*/
public void setDimensionality(Integer value) {
this.dimensionality = value;
}
/**
* Sets the quantization type used for storing vectors in the vector set.
*
* @param value the quantization type (Q8, NOQUANT, or BIN)
*/
public void setType(QuantizationType value) {
this.type = value;
}
/**
* Sets the number of elements (vectors) in the vector set.
*
* @param value the total count of vectors in the vector set
*/
public void setSize(Integer value) {
this.size = value;
}
/**
* Sets the maximum node UID in the HNSW graph.
* <p>
* This is an internal identifier used by Redis to track nodes in the HNSW graph.
*
* @param value the maximum node UID in the HNSW graph
*/
public void setMaxNodeUid(Integer value) {
this.maxNodeUid = value;
}
/**
* Sets the unique identifier of the vector set.
*
* @param value the unique identifier used by Redis to track the vector set
*/
public void setvSetUid(Integer value) {
this.vSetUid = value;
}
/**
* Sets the maximum number of connections per node in the HNSW graph.
* <p>
* This parameter (also known as M) affects the memory usage and search performance of the vector set.
*
* @param value the maximum number of connections per node
*/
public void setMaxNodes(Integer value) {
this.maxNodes = value;
}
/**
* Sets the original dimensionality of vectors before dimensionality reduction.
* <p>
* This is used when the REDUCE option is specified with VADD.
*
* @param value the original dimensionality before reduction
*/
public void setProjectionInputDim(Integer value) {
this.projectionInputDim = value;
}
/**
* Sets the number of elements in the vector set that have attributes.
*
* @param value the number of elements with attributes
*/
public void setAttributesCount(Integer value) {
this.attributesCount = value;
}
/**
* Sets the maximum level in the HNSW graph.
* <p>
* The HNSW algorithm organizes vectors in a hierarchical graph with multiple levels. Higher levels enable faster navigation
* through the graph during similarity searches.
* <p>
* Corresponds to the {@code max-level} field in the VINFO command response.
*
* @param value the maximum level in the HNSW graph
*/
public void setMaxLevel(Integer value) {
this.maxLevel = value;
}
}
|
VectorMetadata
|
java
|
spring-projects__spring-boot
|
module/spring-boot-cache/src/main/java/org/springframework/boot/cache/autoconfigure/CacheProperties.java
|
{
"start": 1230,
"end": 3013
}
|
class ____ {
/**
* Cache type. By default, auto-detected according to the environment.
*/
private @Nullable CacheType type;
/**
* List of cache names to create if supported by the underlying cache manager.
* Usually, this disables the ability to create additional caches on-the-fly.
*/
private List<String> cacheNames = new ArrayList<>();
private final Caffeine caffeine = new Caffeine();
private final Couchbase couchbase = new Couchbase();
private final Infinispan infinispan = new Infinispan();
private final JCache jcache = new JCache();
private final Redis redis = new Redis();
public @Nullable CacheType getType() {
return this.type;
}
public void setType(@Nullable CacheType mode) {
this.type = mode;
}
public List<String> getCacheNames() {
return this.cacheNames;
}
public void setCacheNames(List<String> cacheNames) {
this.cacheNames = cacheNames;
}
public Caffeine getCaffeine() {
return this.caffeine;
}
public Couchbase getCouchbase() {
return this.couchbase;
}
public Infinispan getInfinispan() {
return this.infinispan;
}
public JCache getJcache() {
return this.jcache;
}
public Redis getRedis() {
return this.redis;
}
/**
* Resolve the config location if set.
* @param config the config resource
* @return the location or {@code null} if it is not set
* @throws IllegalArgumentException if the config attribute is set to an unknown
* location
*/
public @Nullable Resource resolveConfigLocation(@Nullable Resource config) {
if (config != null) {
Assert.isTrue(config.exists(),
() -> "'config' resource [%s] must exist".formatted(config.getDescription()));
return config;
}
return null;
}
/**
* Caffeine specific cache properties.
*/
public static
|
CacheProperties
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/proxy/DetachedProxyAsQueryParameterTest.java
|
{
"start": 3008,
"end": 3240
}
|
class ____ {
@Id
private Integer id;
public Department() {
}
public Department(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
@Entity(name = "BasicDepartment")
public static
|
Department
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/package-info.java
|
{
"start": 2734,
"end": 5668
}
|
class ____ make it constant foldable,
* and return the right types. Take a stab at these, but don’t worry too much about getting
* it right. Your function might extend from one of several abstract base classes, all of
* those are fine for this guide, but might have special instructions called out later.
* Known good base classes:
* <ul>
* <li>{@link org.elasticsearch.xpack.esql.expression.function.scalar.convert.AbstractConvertFunction}</li>
* <li>{@link org.elasticsearch.xpack.esql.expression.function.scalar.multivalue.AbstractMultivalueFunction}</li>
* <li>{@link org.elasticsearch.xpack.esql.expression.function.scalar.UnaryScalarFunction}
* or any subclass like {@code AbstractTrigonometricFunction}</li>
* <li>{@link org.elasticsearch.xpack.esql.expression.function.scalar.EsqlScalarFunction}</li>
* <li>{@link org.elasticsearch.xpack.esql.expression.function.scalar.math.DoubleConstantFunction}</li>
* </ul>
* </li>
* <li>
* There are also methods annotated with {@link org.elasticsearch.compute.ann.Evaluator}
* that contain the actual inner implementation of the function. They are usually named
* "process" or "processInts" or "processBar". Modify those to look right and run the {@code CsvTests}
* again. This should generate an {@link org.elasticsearch.compute.operator.EvalOperator.ExpressionEvaluator}
* implementation calling the method annotated with {@link org.elasticsearch.compute.ann.Evaluator}.
*. To make it work with IntelliJ, also click {@code Build->Recompile 'FunctionName.java'}.
* Please commit the generated evaluator before submitting your PR.
* <p>
* NOTE 1: The function you copied may have a method annotated with
* {@link org.elasticsearch.compute.ann.ConvertEvaluator} or
* {@link org.elasticsearch.compute.ann.MvEvaluator} instead of
* {@link org.elasticsearch.compute.ann.Evaluator}. Those do similar things and the
* instructions should still work for you regardless. If your function contains an implementation
* of {@link org.elasticsearch.compute.operator.EvalOperator.ExpressionEvaluator} written by
* hand then please stop and ask for help. This is not a good first function.
* </p>
* <p>
* NOTE 2: Regardless of which annotation is on your "process" method you can learn more
* about the options for generating code from the javadocs on those annotations.
* </p>
* <li>
* Once your evaluator is generated you can have your function return it,
* generally by implementing {@link org.elasticsearch.xpack.esql.evaluator.mapper.EvaluatorMapper#toEvaluator}.
* It’s possible that your abstract base
|
to
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFilter.java
|
{
"start": 4567,
"end": 6088
}
|
class ____<T> extends BaseFilterSubscriber<T> {
final ConditionalSubscriber<? super T> downstream;
ParallelFilterConditionalSubscriber(ConditionalSubscriber<? super T> actual, Predicate<? super T> predicate) {
super(predicate);
this.downstream = actual;
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.upstream, s)) {
this.upstream = s;
downstream.onSubscribe(this);
}
}
@Override
public boolean tryOnNext(T t) {
if (!done) {
boolean b;
try {
b = predicate.test(t);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
cancel();
onError(ex);
return false;
}
if (b) {
return downstream.tryOnNext(t);
}
}
return false;
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
done = true;
downstream.onError(t);
}
@Override
public void onComplete() {
if (!done) {
done = true;
downstream.onComplete();
}
}
}}
|
ParallelFilterConditionalSubscriber
|
java
|
quarkusio__quarkus
|
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/OpenTelemetrySuppressNonAppUriTest.java
|
{
"start": 680,
"end": 2696
}
|
class ____ {
@RegisterExtension
final static QuarkusDevModeTest TEST = new QuarkusDevModeTest()
.withApplicationRoot((jar) -> jar
.addClasses(HelloResource.class, TestSpanExporter.class, TestSpanExporterProvider.class)
.addAsResource(new StringAsset(TestSpanExporterProvider.class.getCanonicalName()),
"META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider")
.add(new StringAsset(
"""
quarkus.otel.traces.exporter=test-span-exporter
quarkus.otel.metrics.exporter=none
quarkus.otel.bsp.export.timeout=1s
quarkus.otel.bsp.schedule.delay=50
"""),
"application.properties"));
@Test
void test() {
// Must not be traced
RestAssured.given()
.get("/q/health/")
.then()
.statusCode(200);
RestAssured.given()
.get("/q/dev-ui/")
.then()
.statusCode(200);
RestAssured.given()
.get("/q/dev-ui/icon/font-awesome.js")
.then()
.statusCode(200);
// Valid trace
RestAssured.given()
.get("/hello")
.then()
.statusCode(200);
// Get span names
List<String> spans = Arrays.asList(
RestAssured.given()
.get("/hello/spans")
.then()
.statusCode(200)
.extract().body()
.asString()
.split(";"));
assertThat(spans).containsExactly("GET /hello");
}
@Path("/hello")
public static
|
OpenTelemetrySuppressNonAppUriTest
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/api/AbstractYearMonthAssert.java
|
{
"start": 1895,
"end": 28478
}
|
class ____<SELF extends AbstractYearMonthAssert<SELF>>
extends AbstractTemporalAssert<SELF, YearMonth> {
/**
* Creates a new <code>{@link AbstractYearMonthAssert}</code>.
*
* @param selfType the "self-type".
* @param actual the actual value to verify.
*/
protected AbstractYearMonthAssert(YearMonth actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that the actual {@code YearMonth} is strictly before the given one.
* <p>
* Example:
* <pre><code class='java'> assertThat(YearMonth.of(2000, 1)).isBefore(YearMonth.of(2000, 2));</code></pre>
*
* @param other the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if other {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not strictly before the given one.
*/
public SELF isBefore(YearMonth other) {
Objects.instance().assertNotNull(info, actual);
assertYearMonthParameterIsNotNull(other);
if (!actual.isBefore(other)) throwAssertionError(shouldBeBefore(actual, other));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is strictly before the given one.
* <p>
* Same assertion as {@link #isBefore(YearMonth)} but the {@code YearMonth} is built from the given string,
* which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isBefore("2000-02");</code></pre>
*
* @param otherYearMonthAsString string representation of the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if the given string is {@code null}.
* @throws DateTimeParseException if the given string cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is not strictly before the {@code YearMonth} built
* from given string.
*/
public SELF isBefore(String otherYearMonthAsString) {
assertYearMonthAsStringParameterIsNotNull(otherYearMonthAsString);
return isBefore(parse(otherYearMonthAsString));
}
/**
* Verifies that the actual {@code YearMonth} is before or equal to the given one.
* <p>
* Example:
* <pre><code class='java'> assertThat(YearMonth.of(2000, 1)).isBeforeOrEqualTo(YearMonth.of(2000, 1))
* .isBeforeOrEqualTo(YearMonth.of(2000, 2));</code></pre>
*
* @param other the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if other {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not before or equal to the given one.
*/
public SELF isBeforeOrEqualTo(YearMonth other) {
Objects.instance().assertNotNull(info, actual);
assertYearMonthParameterIsNotNull(other);
if (actual.isAfter(other)) {
throwAssertionError(shouldBeBeforeOrEqualTo(actual, other));
}
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is before or equal to the given one.
* <p>
* Same assertion as {@link #isBeforeOrEqualTo(YearMonth)} but the {@code YearMonth} is built from given
* string, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isBeforeOrEqualTo("2000-01")
* .isBeforeOrEqualTo("2000-02");</code></pre>
*
* @param otherYearMonthAsString string representation of the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if the given string is {@code null}.
* @throws DateTimeParseException if the given string cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is not before or equal to the {@code YearMonth} built from
* given string.
*/
public SELF isBeforeOrEqualTo(String otherYearMonthAsString) {
assertYearMonthAsStringParameterIsNotNull(otherYearMonthAsString);
return isBeforeOrEqualTo(parse(otherYearMonthAsString));
}
/**
* Verifies that the actual {@code YearMonth} is after or equal to the given one.
* <p>
* Example:
* <pre><code class='java'> assertThat(YearMonth.of(2000, 1)).isAfterOrEqualTo(YearMonth.of(2000, 1))
* .isAfterOrEqualTo(parse("1999-12"));</code></pre>
*
* @param other the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if other {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not after or equal to the given one.
*/
public SELF isAfterOrEqualTo(YearMonth other) {
Objects.instance().assertNotNull(info, actual);
assertYearMonthParameterIsNotNull(other);
if (actual.isBefore(other)) throwAssertionError(shouldBeAfterOrEqualTo(actual, other));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is after or equal to the given one.
* <p>
* Same assertion as {@link #isAfterOrEqualTo(YearMonth)} but the {@code YearMonth} is built from given
* string, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isAfterOrEqualTo("2000-01")
* .isAfterOrEqualTo("1999-12");</code></pre>
*
* @param otherYearMonthAsString string representation of the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if the given string is {@code null}.
* @throws DateTimeParseException if the given string cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is not after or equal to the {@code YearMonth} built from
* given string.
*/
public SELF isAfterOrEqualTo(String otherYearMonthAsString) {
assertYearMonthAsStringParameterIsNotNull(otherYearMonthAsString);
return isAfterOrEqualTo(parse(otherYearMonthAsString));
}
/**
* Verifies that the actual {@code YearMonth} is strictly after the given one.
* <p>
* Example:
* <pre><code class='java'> assertThat(YearMonth.of(2000, 1)).isAfter(parse("1999-12"));</code></pre>
*
* @param other the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if other {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not strictly after the given one.
*/
public SELF isAfter(YearMonth other) {
Objects.instance().assertNotNull(info, actual);
assertYearMonthParameterIsNotNull(other);
if (!actual.isAfter(other)) throwAssertionError(shouldBeAfter(actual, other));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is strictly after the given one.
* <p>
* Same assertion as {@link #isAfter(YearMonth)} but the {@code YearMonth} is built from given
* string, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isAfter("1999-12");</code></pre>
*
* @param otherYearMonthAsString string representation of the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if the given string is {@code null}.
* @throws DateTimeParseException if the given string cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is not strictly after the {@code YearMonth} built
* from given string.
*/
public SELF isAfter(String otherYearMonthAsString) {
assertYearMonthAsStringParameterIsNotNull(otherYearMonthAsString);
return isAfter(parse(otherYearMonthAsString));
}
/**
* Verifies that the actual {@code YearMonth} is equal to the given one.
* <p>
* Same assertion as {@link #isEqualTo(Object)} but the {@code YearMonth} is built from given
* string, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isEqualTo("2000-01");</code></pre>
*
* @param otherYearMonthAsString string representation of the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if the given string is {@code null}.
* @throws DateTimeParseException if the given string cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is not equal to the {@code YearMonth} built from
* given string.
*/
public SELF isEqualTo(String otherYearMonthAsString) {
assertYearMonthAsStringParameterIsNotNull(otherYearMonthAsString);
return isEqualTo(parse(otherYearMonthAsString));
}
/**
* Verifies that the actual {@code YearMonth} is not equal to the given one.
* <p>
* Same assertion as {@link #isNotEqualTo(Object)} but the {@code YearMonth} is built from given
* string, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isNotEqualTo("2000-02");</code></pre>
*
* @param otherYearMonthAsString string representation of the other {@code YearMonth} to compare to, not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if the given string is {@code null}.
* @throws DateTimeParseException if the given string cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is equal to the {@code YearMonth} built from given string.
*/
public SELF isNotEqualTo(String otherYearMonthAsString) {
assertYearMonthAsStringParameterIsNotNull(otherYearMonthAsString);
return isNotEqualTo(parse(otherYearMonthAsString));
}
/**
* Verifies that the actual {@code YearMonth} is present in the given array of values.
* <p>
* Same assertion as {@link #isIn(Object...)} but the {@code YearMonth}s are built from given
* strings, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isIn("1999-12", "2000-01");</code></pre>
*
* @param otherYearMonthsAsString string array representing {@code YearMonth}s.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if any of the given strings is {@code null}.
* @throws DateTimeParseException if any of the given strings cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is not in the {@code YearMonth}s built from given strings.
*/
public SELF isIn(String... otherYearMonthsAsString) {
checkIsNotNullAndNotEmpty(otherYearMonthsAsString);
return isIn(convertToYearMonthArray(otherYearMonthsAsString));
}
/**
* Verifies that the actual {@code YearMonth} is not present in the given array of values.
* <p>
* Same assertion as {@link #isNotIn(Object...)} but the {@code YearMonth}s are built from given
* strings, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> // use string representation of YearMonth
* assertThat(YearMonth.of(2000, 1)).isNotIn("1999-12", "2000-02");</code></pre>
*
* @param otherYearMonthsAsString Array of string representing a {@code YearMonth}.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws IllegalArgumentException if any of the given strings is {@code null}.
* @throws DateTimeParseException if any of the given strings cannot be parsed to a {@code YearMonth}.
* @throws AssertionError if the actual {@code YearMonth} is in the {@code YearMonth}s built from given strings.
*/
public SELF isNotIn(String... otherYearMonthsAsString) {
checkIsNotNullAndNotEmpty(otherYearMonthsAsString);
return isNotIn(convertToYearMonthArray(otherYearMonthsAsString));
}
/**
* Verifies that the actual {@code YearMonth} is strictly in the past.
* <p>
* Example:
* <pre><code class='java'> // assertion succeeds:
* assertThat(YearMonth.now().minusMonths(1)).isInThePast();</code></pre>
*
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not in the past.
*/
public SELF isInThePast() {
Objects.instance().assertNotNull(info, actual);
if (!actual.isBefore(YearMonth.now())) throwAssertionError(shouldBeInThePast(actual));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is the current {@code YearMonth}.
* <p>
* Example:
* <pre><code class='java'> // assertion succeeds:
* assertThat(YearMonth.now()).isCurrentYearMonth();
*
* // assertion fails:
* assertThat(theFellowshipOfTheRing.getReleaseDate()).isCurrentYearMonth();</code></pre>
*
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not the current {@code YearMonth}.
*/
public SELF isCurrentYearMonth() {
Objects.instance().assertNotNull(info, actual);
if (!actual.equals(YearMonth.now())) throwAssertionError(shouldBeCurrentYearMonth(actual));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is strictly in the future.
* <p>
* Example:
* <pre><code class='java'> // assertion succeeds:
* assertThat(YearMonth.now().plusMonths(1)).isInTheFuture();</code></pre>
*
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not in the future.
*/
public SELF isInTheFuture() {
Objects.instance().assertNotNull(info, actual);
if (!actual.isAfter(YearMonth.now())) throwAssertionError(shouldBeInTheFuture(actual));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is in the [start, end] period (start and end included).
* <p>
* Example:
* <pre><code class='java'> YearMonth yearMonth = YearMonth.now();
*
* // assertions succeed:
* assertThat(yearMonth).isBetween(yearMonth.minusMonths(1), yearMonth.plusMonths(1))
* .isBetween(yearMonth, yearMonth.plusMonths(1))
* .isBetween(yearMonth.minusMonths(1), yearMonth)
* .isBetween(yearMonth, yearMonth);
*
* // assertions fail:
* assertThat(yearMonth).isBetween(yearMonth.minusMonths(10), yearMonth.minusMonths(1));
* assertThat(yearMonth).isBetween(yearMonth.plusMonths(1), yearMonth.plusMonths(10));</code></pre>
*
* @param startInclusive the start value (inclusive), not null.
* @param endInclusive the end value (inclusive), not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws NullPointerException if start value is {@code null}.
* @throws NullPointerException if end value is {@code null}.
* @throws AssertionError if the actual value is not in [start, end] period.
*/
public SELF isBetween(YearMonth startInclusive, YearMonth endInclusive) {
comparables.assertIsBetween(info, actual, startInclusive, endInclusive, true, true);
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is in the [start, end] period (start and end included).
* <p>
* Same assertion as {@link #isBetween(YearMonth, YearMonth)} but the {@code YearMonth}s are built from given
* strings, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> YearMonth january2000 = YearMonth.parse("2000-01");
*
* // assertions succeed:
* assertThat(january2000).isBetween("1999-01", "2001-01")
* .isBetween("2000-01", "2001-01")
* .isBetween("1999-01", "2000-01")
* .isBetween("2000-01", "2000-01");
*
* // assertion fails:
* assertThat(january2000).isBetween("1999-01", "1999-12");</code></pre>
*
* @param startInclusive the start value (inclusive), not null.
* @param endInclusive the end value (inclusive), not null.
* @return {@code this} assertion object.
*
* @throws AssertionError if the actual value is {@code null}.
* @throws NullPointerException if start value is {@code null}.
* @throws NullPointerException if end value is {@code null}.
* @throws DateTimeParseException if any of the given string can't be converted to a {@code YearMonth}.
* @throws AssertionError if the actual value is not in [start, end] period.
*/
public SELF isBetween(String startInclusive, String endInclusive) {
return isBetween(parse(startInclusive), parse(endInclusive));
}
/**
* Verifies that the actual {@code YearMonth} is in the ]start, end[ period (start and end excluded).
* <p>
* Example:
* <pre><code class='java'> YearMonth yearMonth = YearMonth.now();
*
* // assertion succeeds:
* assertThat(yearMonth).isStrictlyBetween(yearMonth.minusMonths(1), yearMonth.plusMonths(1));
*
* // assertions fail:
* assertThat(yearMonth).isStrictlyBetween(yearMonth.minusMonths(10), yearMonth.minusMonths(1));
* assertThat(yearMonth).isStrictlyBetween(yearMonth.plusMonths(1), yearMonth.plusMonths(10));
* assertThat(yearMonth).isStrictlyBetween(yearMonth, yearMonth.plusMonths(1));
* assertThat(yearMonth).isStrictlyBetween(yearMonth.minusMonths(1), yearMonth);</code></pre>
*
* @param startExclusive the start value (exclusive), not null.
* @param endExclusive the end value (exclusive), not null.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws NullPointerException if start value is {@code null}.
* @throws NullPointerException if end value is {@code null}.
* @throws AssertionError if the actual value is not in ]start, end[ period.
*/
public SELF isStrictlyBetween(YearMonth startExclusive, YearMonth endExclusive) {
comparables.assertIsBetween(info, actual, startExclusive, endExclusive, false, false);
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is in the ]start, end[ period (start and end excluded).
* <p>
* Same assertion as {@link #isStrictlyBetween(YearMonth, YearMonth)} but the {@code YearMonth}s are built from given
* strings, which must follow the {@link DateTimeFormatter} pattern <code>uuuu-MM</code>
* to allow calling {@link YearMonth#parse(CharSequence)} method.
* <p>
* Example:
* <pre><code class='java'> YearMonth january2000 = YearMonth.parse("2000-01");
*
* // assertion succeeds:
* assertThat(january2000).isStrictlyBetween("1999-01", "2001-01");
*
* // assertions fail:
* assertThat(january2000).isStrictlyBetween("1999-01", "1999-12");
* assertThat(january2000).isStrictlyBetween("2000-01", "2001-01");
* assertThat(january2000).isStrictlyBetween("1999-01", "2000-01");</code></pre>
*
* @param startExclusive the start value (exclusive), not null.
* @param endExclusive the end value (exclusive), not null.
* @return {@code this} assertion object.
*
* @throws AssertionError if the actual value is {@code null}.
* @throws NullPointerException if start value is {@code null}.
* @throws NullPointerException if end value is {@code null}.
* @throws DateTimeParseException if any of the given string can't be converted to a {@code YearMonth}.
* @throws AssertionError if the actual value is not in ]start, end[ period.
*/
public SELF isStrictlyBetween(String startExclusive, String endExclusive) {
return isStrictlyBetween(parse(startExclusive), parse(endExclusive));
}
/**
* Verifies that the actual {@code YearMonth} is in the given year.
* <p>
* Example:
* <pre><code class='java'> // assertion succeeds:
* assertThat(YearMonth.of(2000, 12)).hasYear(2000);
*
* // assertion fails:
* assertThat(YearMonth.of(2000, 12)).hasYear(2001);</code></pre>
*
* @param year the given year.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not in the given year.
*/
public SELF hasYear(int year) {
Objects.instance().assertNotNull(info, actual);
if (actual.getYear() != year) throwAssertionError(shouldHaveDateField(actual, "year", year));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is in the given month.
* <p>
* Example:
* <pre><code class='java'> // assertion succeeds:
* assertThat(YearMonth.of(2000, 12)).hasMonth(Month.DECEMBER);
*
* // assertion fails:
* assertThat(YearMonth.of(2000, 12)).hasMonth(Month.JANUARY);</code></pre>
*
* @param month the given {@link Month}.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not in the given month.
*/
public SELF hasMonth(Month month) {
Objects.instance().assertNotNull(info, actual);
if (!actual.getMonth().equals(month)) throwAssertionError(shouldHaveMonth(actual, month));
return myself;
}
/**
* Verifies that the actual {@code YearMonth} is in the given month.
* <p>
* Example:
* <pre><code class='java'> // assertion succeeds:
* assertThat(YearMonth.of(2000, 12)).hasMonthValue(12);
*
* // assertion fails:
* assertThat(YearMonth.of(2000, 12)).hasMonthValue(11);</code></pre>
*
* @param month the given month's value between 1 and 12 inclusive.
* @return {@code this} assertion object.
* @throws AssertionError if the actual {@code YearMonth} is {@code null}.
* @throws AssertionError if the actual {@code YearMonth} is not in the given month.
*/
public SELF hasMonthValue(int month) {
Objects.instance().assertNotNull(info, actual);
if (actual.getMonthValue() != month) throwAssertionError(shouldHaveDateField(actual, "month", month));
return myself;
}
/**
* Obtains an instance of {@link YearMonth} from a text string such as 2007-12.
*
* @see YearMonth#parse(CharSequence)
*/
@Override
protected YearMonth parse(String yearMonthAsString) {
return YearMonth.parse(yearMonthAsString);
}
/**
* Check that the {@code YearMonth} to compare actual {@code YearMonth} to is not null, in that case throws a
* {@link IllegalArgumentException} with an explicit message.
*
* @param other the {@code YearMonth} to check.
* @throws IllegalArgumentException with an explicit message if the given {@code YearMonth} is null.
*/
private static void assertYearMonthParameterIsNotNull(YearMonth other) {
checkArgument(other != null, "The YearMonth to compare actual with should not be null");
}
/**
* Check that the {@code YearMonth} string representation to compare actual {@code YearMonth} to is not null,
* otherwise throws a {@link IllegalArgumentException} with an explicit message.
*
* @param otherYearMonthAsString string representing the {@code YearMonth} to compare actual with.
* @throws IllegalArgumentException with an explicit message if the given {@code String} is null.
*/
private static void assertYearMonthAsStringParameterIsNotNull(String otherYearMonthAsString) {
checkArgument(otherYearMonthAsString != null,
"The String representing the YearMonth to compare actual with should not be null");
}
private static void checkIsNotNullAndNotEmpty(Object[] values) {
checkArgument(values != null, "The given YearMonth array should not be null");
checkArgument(values.length > 0, "The given YearMonth array should not be empty");
}
private static Object[] convertToYearMonthArray(String... yearMonthsAsString) {
return Arrays.stream(yearMonthsAsString).map(YearMonth::parse).toArray();
}
}
|
AbstractYearMonthAssert
|
java
|
apache__camel
|
components/camel-openstack/src/main/java/org/apache/camel/component/openstack/common/AbstractOpenstackEndpoint.java
|
{
"start": 1254,
"end": 3192
}
|
class ____ extends DefaultEndpoint {
public static final String V2 = "V2";
public static final String V3 = "V3";
protected AbstractOpenstackEndpoint(String endpointUri, Component component) {
super(endpointUri, component);
}
protected abstract String getHost();
protected abstract String getUsername();
protected abstract String getDomain();
protected abstract String getPassword();
protected abstract String getProject();
protected abstract String getOperation();
protected abstract Config getConfig();
protected abstract String getApiVersion();
protected OSClient createClient() {
//client should reAuthenticate itself when token expires
if (V2.equals(getApiVersion())) {
return createV2Client();
}
return createV3Client();
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new IllegalStateException("There is no consumer available for OpenStack");
}
private OSClient.OSClientV3 createV3Client() {
IOSClientBuilder.V3 builder = OSFactory.builderV3()
.endpoint(getHost());
builder.credentials(getUsername(), getPassword(), Identifier.byName(getDomain()));
if (getProject() != null) {
builder.scopeToProject(Identifier.byId(getProject()));
}
if (getConfig() != null) {
builder.withConfig(getConfig());
}
return builder.authenticate();
}
private OSClient.OSClientV2 createV2Client() {
IOSClientBuilder.V2 builder = OSFactory.builderV2()
.endpoint(getHost());
builder.credentials(getUsername(), getPassword());
builder.tenantId(getProject());
if (getConfig() != null) {
builder.withConfig(getConfig());
}
return builder.authenticate();
}
}
|
AbstractOpenstackEndpoint
|
java
|
quarkusio__quarkus
|
extensions/tls-registry/deployment-spi/src/main/java/io/quarkus/tls/deployment/spi/TlsCertificateBuildItem.java
|
{
"start": 339,
"end": 1060
}
|
class ____ extends MultiBuildItem {
public final String name;
public final Supplier<TlsConfiguration> supplier;
/**
* Create an instance of {@link TlsCertificateBuildItem} to register a TLS certificate.
* The certificate will be registered just after the regular TLS certificate configuration is registered.
*
* @param name the name of the certificate, cannot be {@code null}, cannot be {@code <default>}
* @param supplier the supplier providing the TLS configuration, must not return {@code null}
*/
public TlsCertificateBuildItem(String name, Supplier<TlsConfiguration> supplier) {
this.name = name;
this.supplier = supplier;
}
}
|
TlsCertificateBuildItem
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/NettyMessage.java
|
{
"start": 35349,
"end": 36870
}
|
class ____ extends NettyMessage {
private static final byte ID = 10;
final int bufferSize;
final InputChannelID receiverId;
NewBufferSize(int bufferSize, InputChannelID receiverId) {
checkArgument(bufferSize > 0, "The new buffer size should be greater than 0");
this.bufferSize = bufferSize;
this.receiverId = receiverId;
}
@Override
void write(ChannelOutboundInvoker out, ChannelPromise promise, ByteBufAllocator allocator)
throws IOException {
ByteBuf result = null;
try {
result =
allocateBuffer(
allocator, ID, Integer.BYTES + InputChannelID.getByteBufLength());
result.writeInt(bufferSize);
receiverId.writeTo(result);
out.write(result, promise);
} catch (Throwable t) {
handleException(result, null, t);
}
}
static NewBufferSize readFrom(ByteBuf buffer) {
int bufferSize = buffer.readInt();
InputChannelID receiverId = InputChannelID.fromByteBuf(buffer);
return new NewBufferSize(bufferSize, receiverId);
}
@Override
public String toString() {
return String.format("NewBufferSize(%s : %d)", receiverId, bufferSize);
}
}
/** Message to notify producer about the id of required segment. */
static
|
NewBufferSize
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/pool/ha/MockDataSource.java
|
{
"start": 335,
"end": 1308
}
|
class ____ extends WrapperAdapter implements DataSource {
private String name;
public MockDataSource(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public Connection getConnection() throws SQLException {
return new MockConnection(null, name, null);
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
}
|
MockDataSource
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/TestConstructorAnnotationIntegrationTests.java
|
{
"start": 1395,
"end": 1796
}
|
class ____ in conjunction with the
* {@link TestConstructor @TestConstructor} annotation
*
* @author Sam Brannen
* @since 5.2
* @see SpringExtension
* @see SpringJUnitJupiterAutowiredConstructorInjectionTests
* @see SpringJUnitJupiterConstructorInjectionTests
*/
@SpringJUnitConfig(TestConfig.class)
@TestPropertySource(properties = "enigma = 42")
@TestConstructor(autowireMode = ALL)
|
constructors
|
java
|
apache__maven
|
api/maven-api-di/src/main/java/org/apache/maven/api/di/Provides.java
|
{
"start": 1501,
"end": 1779
}
|
class ____ {
* {@literal @}Provides
* {@literal @}Singleton
* public static Configuration provideConfiguration() {
* return Configuration.load();
* }
* }
* </pre>
*
* @since 4.0.0
*/
@Target(METHOD)
@Retention(RUNTIME)
@Documented
public @
|
Providers
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/MisleadingEscapedSpaceTest.java
|
{
"start": 2617,
"end": 2980
}
|
class ____ {
private static final String FOO =
\"""
foo \\s
bar \\s
\""";
}
""")
.doTest();
}
@Test
public void multipleAtEndOfLine_notMisleading() {
testHelper
.addSourceLines(
"Test.class",
"""
|
Test
|
java
|
google__guava
|
android/guava/src/com/google/common/collect/AbstractMultimap.java
|
{
"start": 1289,
"end": 3740
}
|
class ____<K extends @Nullable Object, V extends @Nullable Object>
implements Multimap<K, V> {
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsValue(@Nullable Object value) {
for (Collection<V> collection : asMap().values()) {
if (collection.contains(value)) {
return true;
}
}
return false;
}
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
Collection<V> collection = asMap().get(key);
return collection != null && collection.contains(value);
}
@CanIgnoreReturnValue
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
Collection<V> collection = asMap().get(key);
return collection != null && collection.remove(value);
}
@CanIgnoreReturnValue
@Override
public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
return get(key).add(value);
}
@CanIgnoreReturnValue
@Override
public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) {
checkNotNull(values);
// make sure we only call values.iterator() once
// and we only call get(key) if values is nonempty
if (values instanceof Collection) {
Collection<? extends V> valueCollection = (Collection<? extends V>) values;
return !valueCollection.isEmpty() && get(key).addAll(valueCollection);
} else {
Iterator<? extends V> valueItr = values.iterator();
return valueItr.hasNext() && Iterators.addAll(get(key), valueItr);
}
}
@CanIgnoreReturnValue
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
boolean changed = false;
for (Entry<? extends K, ? extends V> entry : multimap.entries()) {
changed |= put(entry.getKey(), entry.getValue());
}
return changed;
}
@CanIgnoreReturnValue
@Override
public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
checkNotNull(values);
Collection<V> result = removeAll(key);
putAll(key, values);
return result;
}
@LazyInit private transient @Nullable Collection<Entry<K, V>> entries;
@Override
public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
return (result == null) ? entries = createEntries() : result;
}
abstract Collection<Entry<K, V>> createEntries();
@WeakOuter
|
AbstractMultimap
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/SingleTableInheritancePersistTest.java
|
{
"start": 6457,
"end": 7189
}
|
class ____ extends Person {
private String hobby;
@OneToOne
private Woman wife;
@OneToMany(mappedBy = "father")
private List<Child> children = new ArrayList<>();
public Man() {
}
public Man(String name, String hobby) {
super( name );
this.hobby = hobby;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public Woman getWife() {
return wife;
}
public void setWife(Woman wife) {
this.wife = wife;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
@Entity(name = "Woman")
@DiscriminatorValue("WOMAN")
public static
|
Man
|
java
|
apache__camel
|
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/unmarshall/simple/trimfield/BindySimpleFixedLengthUnmarshallTrimFieldTest.java
|
{
"start": 3199,
"end": 7019
}
|
class ____ {
@DataField(pos = 1, length = 2)
private int orderNr;
@DataField(pos = 3, length = 2)
private String clientNr;
@DataField(pos = 5, length = 9, trim = true)
private String firstName;
@DataField(pos = 14, length = 5, align = "L")
private String lastName;
@DataField(pos = 19, length = 4)
private String instrumentCode;
@DataField(pos = 23, length = 10)
private String instrumentNumber;
@DataField(pos = 33, length = 3)
private String orderType;
@DataField(pos = 36, length = 5)
private String instrumentType;
@DataField(pos = 41, precision = 2, length = 12, paddingChar = '0')
private BigDecimal amount;
@DataField(pos = 53, length = 3)
private String currency;
@DataField(pos = 56, length = 10, pattern = "dd-MM-yyyy")
private Date orderDate;
@DataField(pos = 66, length = 10, trim = true, align = "L", paddingChar = '#')
private String comment;
public int getOrderNr() {
return orderNr;
}
public void setOrderNr(int orderNr) {
this.orderNr = orderNr;
}
public String getClientNr() {
return clientNr;
}
public void setClientNr(String clientNr) {
this.clientNr = clientNr;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getInstrumentCode() {
return instrumentCode;
}
public void setInstrumentCode(String instrumentCode) {
this.instrumentCode = instrumentCode;
}
public String getInstrumentNumber() {
return instrumentNumber;
}
public void setInstrumentNumber(String instrumentNumber) {
this.instrumentNumber = instrumentNumber;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public String getInstrumentType() {
return instrumentType;
}
public void setInstrumentType(String instrumentType) {
this.instrumentType = instrumentType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public String toString() {
return "Model : " + Order.class.getName() + " : " + this.orderNr + ", " + this.orderType + ", "
+ String.valueOf(this.amount) + ", " + this.instrumentCode + ", "
+ this.instrumentNumber + ", " + this.instrumentType + ", " + this.currency + ", " + this.clientNr + ", "
+ this.firstName + ", " + this.lastName + ", "
+ String.valueOf(this.orderDate);
}
}
}
|
Order
|
java
|
alibaba__nacos
|
api/src/test/java/com/alibaba/nacos/api/ai/remote/request/McpServerEndpointRequestTest.java
|
{
"start": 1084,
"end": 3365
}
|
class ____ extends BasicRequestTest {
@Test
void testSerialize() throws Exception {
McpServerEndpointRequest request = new McpServerEndpointRequest();
String id = UUID.randomUUID().toString();
request.setRequestId("1");
request.setNamespaceId(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE);
request.setMcpName("testMcpName");
request.setMcpId(id);
request.setType(AiRemoteConstants.REGISTER_ENDPOINT);
request.setAddress("1.1.1.1");
request.setPort(3306);
request.setVersion("1.0.0");
String json = mapper.writeValueAsString(request);
assertNotNull(json);
assertTrue(json.contains("\"requestId\":\"1\""));
assertTrue(json.contains("\"namespaceId\":\"public\""));
assertTrue(json.contains("\"mcpName\":\"testMcpName\""));
assertTrue(json.contains(String.format("\"mcpId\":\"%s\"", id)));
assertTrue(json.contains(String.format("\"type\":\"%s\"", AiRemoteConstants.REGISTER_ENDPOINT)));
assertTrue(json.contains("\"address\":\"1.1.1.1\""));
assertTrue(json.contains("\"version\":\"1.0.0\""));
assertTrue(json.contains("\"port\":3306"));
}
@Test
void testDeserialize() throws Exception {
String json =
"{\"headers\":{},\"requestId\":\"1\",\"namespaceId\":\"public\",\"mcpId\":\"2aaebf2d-4b7b-4ab9-9ad2-1e60355ae041\","
+ "\"mcpName\":\"testMcpName\",\"address\":\"1.1.1.1\",\"port\":3306,\"version\":\"1.0.0\","
+ "\"type\":\"registerEndpoint\",\"module\":\"ai\"}";
McpServerEndpointRequest result = mapper.readValue(json, McpServerEndpointRequest.class);
assertNotNull(result);
assertEquals("1", result.getRequestId());
assertEquals(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE, result.getNamespaceId());
assertEquals("testMcpName", result.getMcpName());
assertEquals("2aaebf2d-4b7b-4ab9-9ad2-1e60355ae041", result.getMcpId());
assertEquals("1.1.1.1", result.getAddress());
assertEquals(3306, result.getPort());
assertEquals("1.0.0", result.getVersion());
assertEquals(AiRemoteConstants.REGISTER_ENDPOINT, result.getType());
}
}
|
McpServerEndpointRequestTest
|
java
|
google__guava
|
android/guava/src/com/google/common/escape/Escaper.java
|
{
"start": 3221,
"end": 4767
}
|
class ____ {
// TODO(dbeaumont): evaluate custom implementations, considering package private constructor.
/** Constructor for use by subclasses. */
protected Escaper() {}
/**
* Returns the escaped form of a given literal string.
*
* <p>Note that this method may treat input characters differently depending on the specific
* escaper implementation.
*
* <ul>
* <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
* correctly, including surrogate character pairs. If the input is badly formed the escaper
* should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not verify the input
* for well formed characters. A {@code CharEscaper} should not be used in situations where
* input is not guaranteed to be restricted to the Basic Multilingual Plane (BMP).
* </ul>
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be
* escaped for any other reason
*/
public abstract String escape(String string);
private final Function<String, String> asFunction = this::escape;
/** Returns a {@link Function} that invokes {@link #escape(String)} on this escaper. */
public final Function<String, String> asFunction() {
return asFunction;
}
}
|
Escaper
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderElectionDriver.java
|
{
"start": 1927,
"end": 2853
}
|
interface ____ {
/** Callback that is called once the driver obtains the leadership. */
void onGrantLeadership(UUID leaderSessionID);
/** Callback that is called once the driver loses the leadership. */
void onRevokeLeadership();
/**
* Notifies the listener about a changed leader information for the given component.
*
* @param componentId identifying the component whose leader information has changed
* @param leaderInformation new leader information
*/
void onLeaderInformationChange(String componentId, LeaderInformation leaderInformation);
/** Notifies the listener about all currently known leader information. */
void onLeaderInformationChange(LeaderInformationRegister leaderInformationRegister);
/** Notifies the listener if an error occurred. */
void onError(Throwable t);
}
}
|
Listener
|
java
|
quarkusio__quarkus
|
integration-tests/redis-devservices/src/main/java/io/quarkus/test/devservices/redis/TestResource.java
|
{
"start": 231,
"end": 758
}
|
class ____ {
@Inject
RedisDataSource redis;
@GET
@Path("/ping")
public String ping() {
return redis.execute("ping").toString();
}
@GET
@Path("/set/{key}/{value}")
public String set(@PathParam("key") String key, @PathParam("value") String value) {
redis.value(String.class).set(key, value);
return "OK";
}
@GET
@Path("/get/{key}")
public String get(@PathParam("key") String key) {
return redis.value(String.class).get(key);
}
}
|
TestResource
|
java
|
google__auto
|
value/src/test/java/com/google/auto/value/extension/toprettystring/ToPrettyStringValidatorTest.java
|
{
"start": 5948,
"end": 6310
}
|
class ____");
}
@Test
public void onlyOneToPrettyStringMethod_superinterface() {
JavaFileObject superinterface =
JavaFileObjects.forSourceLines(
"test.Superinterface",
"package test;",
"",
"import com.google.auto.value.extension.toprettystring.ToPrettyString;",
"",
"
|
Subclass
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/window/groupwindow/internal/MergingWindowSetTest.java
|
{
"start": 21363,
"end": 23585
}
|
class ____ extends MergingWindowAssigner<TimeWindow> {
private static final long serialVersionUID = 1L;
protected long sessionTimeout;
public NonEagerlyMergingWindowAssigner(long sessionTimeout) {
this.sessionTimeout = sessionTimeout;
}
@Override
public Collection<TimeWindow> assignWindows(RowData element, long timestamp) {
return Collections.singletonList(new TimeWindow(timestamp, timestamp + sessionTimeout));
}
@Override
public TypeSerializer<TimeWindow> getWindowSerializer(ExecutionConfig executionConfig) {
return null;
}
@Override
public boolean isEventTime() {
return true;
}
/** Merge overlapping {@link TimeWindow}s. */
@Override
public void mergeWindows(
TimeWindow newWindow,
NavigableSet<TimeWindow> sortedWindows,
MergeCallback<TimeWindow, Collection<TimeWindow>> callback) {
TreeSet<TimeWindow> treeWindows = new TreeSet<>();
treeWindows.add(newWindow);
treeWindows.addAll(sortedWindows);
TimeWindow earliestStart = treeWindows.first();
List<TimeWindow> associatedWindows = new ArrayList<>();
for (TimeWindow win : treeWindows) {
if (win.getStart() < earliestStart.getEnd()
&& win.getStart() >= earliestStart.getStart()) {
associatedWindows.add(win);
}
}
TimeWindow target =
new TimeWindow(earliestStart.getStart(), earliestStart.getEnd() + 1);
if (associatedWindows.size() > 1) {
try {
callback.merge(target, associatedWindows);
} catch (Exception e) {
throw new IllegalStateException(
"Failed to merge windows in " + this.getClass().getCanonicalName(), e);
}
}
}
@Override
public String toString() {
return "NonEagerlyMergingWindows";
}
}
private static
|
NonEagerlyMergingWindowAssigner
|
java
|
apache__commons-lang
|
src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java
|
{
"start": 4303,
"end": 22078
}
|
class ____ implements FormatFactory {
private static final Format UPPER_INSTANCE = new UpperCaseFormat();
@Override
public Format getFormat(final String name, final String arguments, final Locale locale) {
return UPPER_INSTANCE;
}
}
private final Map<String, FormatFactory> registry = new HashMap<>();
// /**
// * Test extended formats with choice format.
// *
// * NOTE: FAILING - currently sub-formats not supported
// */
// void testExtendedWithChoiceFormat() {
// String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}";
// ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
// assertPatterns(null, pattern, emf.toPattern());
// try {
// assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"}));
// assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"}));
// } catch (IllegalArgumentException e) {
// // currently sub-formats not supported
// }
// }
// /**
// * Test mixed extended and built-in formats with choice format.
// *
// * NOTE: FAILING - currently sub-formats not supported
// */
// void testExtendedAndBuiltInWithChoiceFormat() {
// String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}";
// Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")};
// Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")};
// Locale[] availableLocales = ChoiceFormat.getAvailableLocales();
// Locale[] testLocales = new Locale[availableLocales.length + 1];
// testLocales[0] = null;
// System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length);
// for (int i = 0; i < testLocales.length; i++) {
// NumberFormat nf = null;
// NumberFormat cf = null;
// ExtendedMessageFormat emf = null;
// if (testLocales[i] == null) {
// nf = NumberFormat.getNumberInstance();
// cf = NumberFormat.getCurrencyInstance();
// emf = new ExtendedMessageFormat(pattern, registry);
// } else {
// nf = NumberFormat.getNumberInstance(testLocales[i]);
// cf = NumberFormat.getCurrencyInstance(testLocales[i]);
// emf = new ExtendedMessageFormat(pattern, testLocales[i], registry);
// }
// assertPatterns(null, pattern, emf.toPattern());
// try {
// String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]);
// String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]);
// assertEquals(lowExpected, emf.format(lowArgs));
// assertEquals(highExpected, emf.format(highArgs));
// } catch (IllegalArgumentException e) {
// // currently sub-formats not supported
// }
// }
// }
/**
* Create an ExtendedMessageFormat for the specified pattern and locale and check the
* formatted output matches the expected result for the parameters.
* @param pattern string
* @param registryUnused map (currently unused)
* @param args Object[]
* @param locale Locale
*/
private void checkBuiltInFormat(final String pattern, final Map<String, ?> registryUnused, final Object[] args, final Locale locale) {
final StringBuilder buffer = new StringBuilder();
buffer.append("Pattern=[");
buffer.append(pattern);
buffer.append("], locale=[");
buffer.append(locale);
buffer.append("]");
final MessageFormat mf = createMessageFormat(pattern, locale);
final ExtendedMessageFormat emf;
if (locale == null) {
emf = new ExtendedMessageFormat(pattern);
} else {
emf = new ExtendedMessageFormat(pattern, locale);
}
assertEquals(mf.format(args), emf.format(args), "format " + buffer);
assertEquals(mf.toPattern(), emf.toPattern(), "toPattern " + buffer);
}
/**
* Test a built-in format for the specified Locales, plus {@code null} Locale.
* @param pattern MessageFormat pattern
* @param fmtRegistry FormatFactory registry to use
* @param args MessageFormat arguments
* @param locales to test
*/
private void checkBuiltInFormat(final String pattern, final Map<String, ?> fmtRegistry, final Object[] args, final Locale[] locales) {
checkBuiltInFormat(pattern, fmtRegistry, args, (Locale) null);
for (final Locale locale : locales) {
checkBuiltInFormat(pattern, fmtRegistry, args, locale);
}
}
/**
* Test a built-in format for the specified Locales, plus {@code null} Locale.
* @param pattern MessageFormat pattern
* @param args MessageFormat arguments
* @param locales to test
*/
private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales) {
checkBuiltInFormat(pattern, null, args, locales);
}
/**
* Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4).
* @param pattern string
* @param locale Locale
* @return MessageFormat
*/
private MessageFormat createMessageFormat(final String pattern, final Locale locale) {
final MessageFormat result = new MessageFormat(pattern);
if (locale != null) {
result.setLocale(locale);
result.applyPattern(pattern);
}
return result;
}
@BeforeEach
public void setUp() {
registry.put("lower", new LowerCaseFormatFactory());
registry.put("upper", new UpperCaseFormatFactory());
}
/**
* Test the built-in choice format.
*/
@Test
void testBuiltInChoiceFormat() {
final Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")};
String choicePattern;
final Locale[] availableLocales = NumberFormat.getAvailableLocales();
choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
for (final Object value : values) {
checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales);
}
choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}";
for (final Object value : values) {
checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales);
}
}
/**
* Test the built-in date/time formats
*/
@Test
void testBuiltInDateTimeFormat() {
final Calendar cal = Calendar.getInstance();
cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
final Object[] args = {cal.getTime()};
final Locale[] availableLocales = DateFormat.getAvailableLocales();
checkBuiltInFormat("1: {0,date,short}", args, availableLocales);
checkBuiltInFormat("2: {0,date,medium}", args, availableLocales);
checkBuiltInFormat("3: {0,date,long}", args, availableLocales);
checkBuiltInFormat("4: {0,date,full}", args, availableLocales);
checkBuiltInFormat("5: {0,date,d MMM yy}", args, availableLocales);
checkBuiltInFormat("6: {0,time,short}", args, availableLocales);
checkBuiltInFormat("7: {0,time,medium}", args, availableLocales);
checkBuiltInFormat("8: {0,time,long}", args, availableLocales);
checkBuiltInFormat("9: {0,time,full}", args, availableLocales);
checkBuiltInFormat("10: {0,time,HH:mm}", args, availableLocales);
checkBuiltInFormat("11: {0,date}", args, availableLocales);
checkBuiltInFormat("12: {0,time}", args, availableLocales);
}
/**
* Test the built-in number formats.
*/
@Test
void testBuiltInNumberFormat() {
final Object[] args = {Double.valueOf("6543.21")};
final Locale[] availableLocales = NumberFormat.getAvailableLocales();
checkBuiltInFormat("1: {0,number}", args, availableLocales);
checkBuiltInFormat("2: {0,number,integer}", args, availableLocales);
checkBuiltInFormat("3: {0,number,currency}", args, availableLocales);
checkBuiltInFormat("4: {0,number,percent}", args, availableLocales);
checkBuiltInFormat("5: {0,number,00000.000}", args, availableLocales);
}
/**
* Test Bug LANG-917 - IndexOutOfBoundsException and/or infinite loop when using a choice pattern
*/
@Test
void testEmbeddedPatternInChoice() {
final String pattern = "Hi {0,lower}, got {1,choice,0#none|1#one|1<{1,number}}, {2,upper}!";
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
assertEquals(emf.format(new Object[] {"there", 3, "great"}), "Hi there, got 3, GREAT!");
}
/**
* Test equals() and hashCode().
*/
@Test
void testEqualsHashcode() {
final Map<String, ? extends FormatFactory> fmtRegistry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory());
final Map<String, ? extends FormatFactory> otherRegistry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory());
final String pattern = "Pattern: {0,testfmt}";
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
ExtendedMessageFormat other;
// Same object
assertEquals(emf, emf, "same, equals()");
assertEquals(emf.hashCode(), emf.hashCode(), "same, hashCode()");
// Equal Object
other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
assertEquals(emf, other, "equal, equals()");
assertEquals(emf.hashCode(), other.hashCode(), "equal, hashCode()");
// Different Class
other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
assertNotEquals(emf, other, "class, equals()");
assertEquals(emf.hashCode(), other.hashCode(), "class, hashCode()"); // same hash code
// Different pattern
other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry);
assertNotEquals(emf, other, "pattern, equals()");
assertNotEquals(emf.hashCode(), other.hashCode(), "pattern, hashCode()");
// Different registry
other = new ExtendedMessageFormat(pattern, Locale.US, otherRegistry);
assertNotEquals(emf, other, "registry, equals()");
assertNotEquals(emf.hashCode(), other.hashCode(), "registry, hashCode()");
// Different Locale
other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry);
assertNotEquals(emf, other, "locale, equals()");
assertEquals(emf.hashCode(), other.hashCode(), "locale, hashCode()"); // same hash code
}
/**
* Test Bug LANG-948 - Exception while using ExtendedMessageFormat and escaping braces
*/
@Test
void testEscapedBraces_LANG_948() {
// message without placeholder because braces are escaped by quotes
final String pattern = "Message without placeholders '{}'";
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
assertEquals("Message without placeholders {}", emf.format(new Object[] {"DUMMY"}));
// message with placeholder because quotes are escaped by quotes
final String pattern2 = "Message with placeholder ''{0}''";
final ExtendedMessageFormat emf2 = new ExtendedMessageFormat(pattern2, registry);
assertEquals("Message with placeholder 'DUMMY'", emf2.format(new Object[] {"DUMMY"}));
}
/**
* Test Bug LANG-477 - out of memory error with escaped quote
*/
@Test
void testEscapedQuote_LANG_477() {
final String pattern = "it''s a {0,lower} 'test'!";
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"}));
}
/**
* Test extended and built-in formats with available locales.
*/
@Test
void testExtendedAndBuiltInFormatsWithAvailableLocales() {
final String extendedPattern = "Name: {0,upper} ";
final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
final String pattern = extendedPattern + builtinsPattern;
final Calendar cal = Calendar.getInstance();
cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
final Object[] args = {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
final HashSet<Locale> testLocales = new HashSet<>(Arrays.asList(DateFormat.getAvailableLocales()));
testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales()));
for (final Locale locale : testLocales) {
final MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
final String expectedPattern = extendedPattern + builtins.toPattern();
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, locale, registry);
assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for locale " + locale);
final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
final NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
final StringBuilder expected = new StringBuilder();
expected.append("Name: ");
expected.append(args[0].toString().toUpperCase(locale));
expected.append(" DOB: ");
expected.append(df.format(args[1]));
expected.append(" Salary: ");
expected.append(nf.format(args[2]));
assertEquals(expected.toString(), emf.format(args), String.valueOf(locale));
}
}
/**
* Test extended and built-in formats with the default locale.
*/
@Test
void testExtendedAndBuiltInFormatsWithDefaultLocale() {
final String extendedPattern = "Name: {0,upper} ";
final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
final String pattern = extendedPattern + builtinsPattern;
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
final MessageFormat builtins = createMessageFormat(builtinsPattern, null);
final String expectedPattern = extendedPattern + builtins.toPattern();
assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for default locale");
final Calendar cal = Calendar.getInstance();
cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
final Object[] args = {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
final NumberFormat nf = NumberFormat.getCurrencyInstance();
final StringBuilder expected = new StringBuilder();
expected.append("Name: ");
expected.append(args[0].toString().toUpperCase());
expected.append(" DOB: ");
expected.append(df.format(args[1]));
expected.append(" Salary: ");
expected.append(nf.format(args[2]));
assertEquals(expected.toString(), emf.format(args));
}
/**
* Test extended formats.
*/
@Test
void testExtendedFormats() {
final String pattern = "Lower: {0,lower} Upper: {1,upper}";
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
assertEquals(pattern, emf.toPattern(), "TOPATTERN");
assertEquals(emf.format(new Object[] {"foo", "bar"}), "Lower: foo Upper: BAR");
assertEquals(emf.format(new Object[] {"Foo", "Bar"}), "Lower: foo Upper: BAR");
assertEquals(emf.format(new Object[] {"FOO", "BAR"}), "Lower: foo Upper: BAR");
assertEquals(emf.format(new Object[] {"FOO", "bar"}), "Lower: foo Upper: BAR");
assertEquals(emf.format(new Object[] {"foo", "BAR"}), "Lower: foo Upper: BAR");
}
@Test
void testOverriddenBuiltinFormat() {
final Calendar cal = Calendar.getInstance();
cal.set(2007, Calendar.JANUARY, 23);
final Object[] args = {cal.getTime()};
final Locale[] availableLocales = DateFormat.getAvailableLocales();
final Map<String, ? extends FormatFactory> dateRegistry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());
//check the non-overridden builtins:
checkBuiltInFormat("1: {0,date}", dateRegistry, args, availableLocales);
checkBuiltInFormat("2: {0,date,medium}", dateRegistry, args, availableLocales);
checkBuiltInFormat("3: {0,date,long}", dateRegistry, args, availableLocales);
checkBuiltInFormat("4: {0,date,full}", dateRegistry, args, availableLocales);
checkBuiltInFormat("5: {0,date,d MMM yy}", dateRegistry, args, availableLocales);
//check the overridden format:
for (int i = -1; i < availableLocales.length; i++) {
final Locale locale = i < 0 ? null : availableLocales[i];
final MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
final String pattern = "{0,date,short}";
final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, dateRegistry);
assertEquals(dateDefault.format(args), dateShort.format(args), "overridden date,short format");
assertEquals(pattern, dateShort.toPattern(), "overridden date,short pattern");
}
}
}
|
UpperCaseFormatFactory
|
java
|
apache__camel
|
components/camel-telemetry/src/main/java/org/apache/camel/telemetry/decorators/FtpSpanDecorator.java
|
{
"start": 858,
"end": 1125
}
|
class ____ extends FileSpanDecorator {
@Override
public String getComponent() {
return "ftp";
}
@Override
public String getComponentClassName() {
return "org.apache.camel.component.file.remote.FtpComponent";
}
}
|
FtpSpanDecorator
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/IndicesPermission.java
|
{
"start": 50858,
"end": 55052
}
|
class ____ {
public static final Group[] EMPTY_ARRAY = new Group[0];
private final IndexPrivilege privilege;
private final IndexComponentSelectorPredicate selectorPredicate;
private final Predicate<String> actionMatcher;
private final String[] indices;
private final StringMatcher indexNameMatcher;
private final Supplier<Automaton> indexNameAutomaton;
// TODO: Use FieldPermissionsDefinition instead of FieldPermissions. The former is a better counterpart to query
private final FieldPermissions fieldPermissions;
private final Set<BytesReference> query;
// by default certain restricted indices are exempted when granting privileges, as they should generally be hidden for ordinary
// users. Setting this flag true eliminates the special status for the purpose of this permission - restricted indices still have
// to be covered by the "indices"
private final boolean allowRestrictedIndices;
public Group(
IndexPrivilege privilege,
FieldPermissions fieldPermissions,
@Nullable Set<BytesReference> query,
boolean allowRestrictedIndices,
RestrictedIndices restrictedIndices,
String... indices
) {
assert indices.length != 0;
this.privilege = privilege;
this.actionMatcher = privilege.predicate();
this.selectorPredicate = privilege.getSelectorPredicate();
this.indices = indices;
this.allowRestrictedIndices = allowRestrictedIndices;
if (allowRestrictedIndices) {
this.indexNameMatcher = StringMatcher.of(indices);
this.indexNameAutomaton = CachedSupplier.wrap(() -> Automatons.patterns(indices));
} else {
this.indexNameMatcher = StringMatcher.of(indices).and(name -> restrictedIndices.isRestricted(name) == false);
this.indexNameAutomaton = CachedSupplier.wrap(
() -> Automatons.minusAndMinimize(Automatons.patterns(indices), restrictedIndices.getAutomaton())
);
}
this.fieldPermissions = Objects.requireNonNull(fieldPermissions);
this.query = query;
}
public IndexPrivilege privilege() {
return privilege;
}
public String[] indices() {
return indices;
}
@Nullable
public Set<BytesReference> getQuery() {
return query;
}
public FieldPermissions getFieldPermissions() {
return fieldPermissions;
}
private boolean checkAction(String action) {
return actionMatcher.test(action);
}
private boolean checkIndex(String index) {
assert index != null;
return indexNameMatcher.test(index);
}
boolean hasQuery() {
return query != null;
}
public boolean checkSelector(@Nullable IndexComponentSelector selector) {
return selectorPredicate.test(selector == null ? IndexComponentSelector.DATA : selector);
}
public boolean allowRestrictedIndices() {
return allowRestrictedIndices;
}
public Automaton getIndexMatcherAutomaton() {
return indexNameAutomaton.get();
}
boolean isTotal() {
return allowRestrictedIndices
&& indexNameMatcher.isTotal()
&& privilege == IndexPrivilege.ALL
&& query == null
&& false == fieldPermissions.hasFieldLevelSecurity();
}
@Override
public String toString() {
return "Group{"
+ "privilege="
+ privilege
+ ", indices="
+ Strings.arrayToCommaDelimitedString(indices)
+ ", fieldPermissions="
+ fieldPermissions
+ ", query="
+ query
+ ", allowRestrictedIndices="
+ allowRestrictedIndices
+ '}';
}
}
private static
|
Group
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/model/internal/TimeZoneStorageHelper.java
|
{
"start": 875,
"end": 3387
}
|
class ____ {
private static final String OFFSET_TIME_CLASS = OffsetTime.class.getName();
private static final String OFFSET_DATETIME_CLASS = OffsetDateTime.class.getName();
private static final String ZONED_DATETIME_CLASS = ZonedDateTime.class.getName();
static Class<? extends CompositeUserType<?>> resolveTimeZoneStorageCompositeUserType(
MemberDetails attributeMember,
ClassDetails returnedClass,
MetadataBuildingContext context) {
if ( useColumnForTimeZoneStorage( attributeMember, context ) ) {
final String returnedClassName = returnedClass.getName();
if ( OFFSET_DATETIME_CLASS.equals( returnedClassName ) ) {
return OffsetDateTimeCompositeUserType.class;
}
else if ( ZONED_DATETIME_CLASS.equals( returnedClassName ) ) {
return ZonedDateTimeCompositeUserType.class;
}
else if ( OFFSET_TIME_CLASS.equals( returnedClassName ) ) {
return OffsetTimeCompositeUserType.class;
}
}
return null;
}
private static boolean isTemporalWithTimeZoneClass(String returnedClassName) {
return OFFSET_DATETIME_CLASS.equals( returnedClassName )
|| ZONED_DATETIME_CLASS.equals( returnedClassName )
|| isOffsetTimeClass( returnedClassName );
}
public static boolean isOffsetTimeClass(AnnotationTarget element) {
return element instanceof MemberDetails memberDetails
&& isOffsetTimeClass( memberDetails );
}
public static boolean isOffsetTimeClass(MemberDetails element) {
final var type = element.getType();
return type != null
&& isOffsetTimeClass( type.determineRawClass().getClassName() );
}
private static boolean isOffsetTimeClass(String returnedClassName) {
return OFFSET_TIME_CLASS.equals( returnedClassName );
}
static boolean useColumnForTimeZoneStorage(AnnotationTarget element, MetadataBuildingContext context) {
final var timeZoneStorage = element.getDirectAnnotationUsage( TimeZoneStorage.class );
if ( timeZoneStorage == null ) {
return element instanceof MemberDetails attributeMember
&& isTemporalWithTimeZoneClass( attributeMember.getType().getName() )
//no @TimeZoneStorage annotation, so we need to use the default storage strategy
&& context.getBuildingOptions().getDefaultTimeZoneStorage() == COLUMN;
}
else {
return switch ( timeZoneStorage.value() ) {
case COLUMN -> true;
// if the db has native support for timezones, we use that, not a column
case AUTO -> context.getBuildingOptions().getTimeZoneSupport() != NATIVE;
default -> false;
};
}
}
}
|
TimeZoneStorageHelper
|
java
|
apache__spark
|
sql/core/src/main/java/org/apache/spark/sql/execution/datasources/parquet/ParquetVectorUpdaterFactory.java
|
{
"start": 11800,
"end": 12720
}
|
class ____ implements ParquetVectorUpdater {
@Override
public void readValues(
int total,
int offset,
WritableColumnVector values,
VectorizedValuesReader valuesReader) {
throw SparkUnsupportedOperationException.apply();
}
@Override
public void skipValues(int total, VectorizedValuesReader valuesReader) {
throw SparkUnsupportedOperationException.apply();
}
@Override
public void readValue(
int offset,
WritableColumnVector values,
VectorizedValuesReader valuesReader) {
throw SparkUnsupportedOperationException.apply();
}
@Override
public void decodeSingleDictionaryId(
int offset,
WritableColumnVector values,
WritableColumnVector dictionaryIds,
Dictionary dictionary) {
throw SparkUnsupportedOperationException.apply();
}
}
private static
|
NullTypeUpdater
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/admin/DescribeClusterOptions.java
|
{
"start": 904,
"end": 2379
}
|
class ____ extends AbstractOptions<DescribeClusterOptions> {
private boolean includeAuthorizedOperations;
private boolean includeFencedBrokers;
/**
* Set the timeout in milliseconds for this operation or {@code null} if the default api timeout for the
* AdminClient should be used.
*
*/
// This method is retained to keep binary compatibility with 0.11
public DescribeClusterOptions timeoutMs(Integer timeoutMs) {
this.timeoutMs = timeoutMs;
return this;
}
public DescribeClusterOptions includeAuthorizedOperations(boolean includeAuthorizedOperations) {
this.includeAuthorizedOperations = includeAuthorizedOperations;
return this;
}
public DescribeClusterOptions includeFencedBrokers(boolean includeFencedBrokers) {
this.includeFencedBrokers = includeFencedBrokers;
return this;
}
/**
* Specify if authorized operations should be included in the response. Note that some
* older brokers cannot not supply this information even if it is requested.
*/
public boolean includeAuthorizedOperations() {
return includeAuthorizedOperations;
}
/**
* Specify if fenced brokers should be included in the response. Note that some
* older brokers cannot not supply this information even if it is requested.
*/
public boolean includeFencedBrokers() {
return includeFencedBrokers;
}
}
|
DescribeClusterOptions
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/http/HttpReadTimeoutException.java
|
{
"start": 508,
"end": 731
}
|
class ____ extends RuntimeException {
public HttpReadTimeoutException(long readTimeoutMillis, Exception cause) {
super("http read timeout after " + readTimeoutMillis + "ms", cause);
}
}
|
HttpReadTimeoutException
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SecretsManagerEndpointBuilderFactory.java
|
{
"start": 23190,
"end": 28213
}
|
class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final SecretsManagerHeaderNameBuilder INSTANCE = new SecretsManagerHeaderNameBuilder();
/**
* The operation we want to perform.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsSecretsManagerOperation}.
*/
public String awsSecretsManagerOperation() {
return "CamelAwsSecretsManagerOperation";
}
/**
* The number of results to include in the response.
*
* The option is a: {@code Integer} type.
*
* Group: producer
*
* @return the name of the header {@code AwsSecretsManagerMaxResults}.
*/
public String awsSecretsManagerMaxResults() {
return "CamelAwsSecretsManagerMaxResults";
}
/**
* The name of the secret.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsSecretsManagerSecretName}.
*/
public String awsSecretsManagerSecretName() {
return "CamelAwsSecretsManagerSecretName";
}
/**
* The description of the secret.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code
* AwsSecretsManagerSecretDescription}.
*/
public String awsSecretsManagerSecretDescription() {
return "CamelAwsSecretsManagerSecretDescription";
}
/**
* The ARN or name of the secret.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsSecretsManagerSecretId}.
*/
public String awsSecretsManagerSecretId() {
return "CamelAwsSecretsManagerSecretId";
}
/**
* A comma separated list of the ARN or name of the secrets.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsSecretsManagerSecretIds}.
*/
public String awsSecretsManagerSecretIds() {
return "CamelAwsSecretsManagerSecretIds";
}
/**
* The ARN of the Lambda rotation function that can rotate the secret.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code
* AwsSecretsManagerLambdaRotationFunctionArn}.
*/
public String awsSecretsManagerLambdaRotationFunctionArn() {
return "CamelAwsSecretsManagerLambdaRotationFunctionArn";
}
/**
* The unique identifier of the version of the secret.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code
* AwsSecretsManagerSecretVersionId}.
*/
public String awsSecretsManagerSecretVersionId() {
return "CamelAwsSecretsManagerSecretVersionId";
}
/**
* The unique identifier of the version of the secrets in batch
* operation.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code
* AwsSecretsManagerSecretVersionIds}.
*/
public String awsSecretsManagerSecretVersionIds() {
return "CamelAwsSecretsManagerSecretVersionIds";
}
/**
* A comma separated list of Regions in which to replicate the secret.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code
* AwsSecretsManagerSecretReplicationRegions}.
*/
public String awsSecretsManagerSecretReplicationRegions() {
return "CamelAwsSecretsManagerSecretReplicationRegions";
}
/**
* If this header is set to true, the deleted secret won't have any
* retention period.
*
* The option is a: {@code Boolean} type.
*
* Group: producer
*
* @return the name of the header {@code
* AwsSecretsManagerSecretForceDeletion}.
*/
public String awsSecretsManagerSecretForceDeletion() {
return "CamelAwsSecretsManagerSecretForceDeletion";
}
}
static SecretsManagerEndpointBuilder endpointBuilder(String componentName, String path) {
|
SecretsManagerHeaderNameBuilder
|
java
|
apache__camel
|
components/camel-schematron/src/main/java/org/apache/camel/component/schematron/SchematronEndpoint.java
|
{
"start": 4722,
"end": 5128
}
|
class ____ {}", path);
InputStream schRules = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), path);
rules = TemplatesFactory.newInstance().getTemplates(schRules, transformerFactory);
} catch (Exception classPathException) {
// Attempts from the file system.
LOG.debug("Error loading schematron rules from
|
path
|
java
|
hibernate__hibernate-orm
|
local-build-plugins/src/main/java/org/hibernate/orm/properties/jdk11/SettingsCollector.java
|
{
"start": 3958,
"end": 8170
}
|
class ____
//
// <a id="DIALECT">
// <!-- -->
// </a>
// <ul class="blockList">
// <li class="blockList">
// <h4>DIALECT</h4>
// ..
// <div class="block">{COMMENT}</div>
// <dl>
// <!-- "notes" -->
// </dl>
// </li>
// </ul>
final Element fieldJavadocBlockList = constantsClassDocument.selectFirst( "#" + simpleFieldName + " + ul li.blockList" );
if ( fieldJavadocBlockList == null || isUselessJavadoc( fieldJavadocBlockList ) ) {
System.out.println( className + "#" + simpleFieldName + " defined no Javadoc - ignoring." );
continue;
}
final SettingWorkingDetails settingWorkingDetails = new SettingWorkingDetails(
settingName,
className,
simpleFieldName,
Utils.fieldJavadocLink(
publishedJavadocsUrl,
className,
simpleFieldName
)
);
applyMetadata( className, publishedJavadocsUrl, settingWorkingDetails, fieldJavadocBlockList );
final Elements javadocsToConvert = cleanupFieldJavadocElement( fieldJavadocBlockList, className, publishedJavadocsUrl );
final SettingDescriptor settingDescriptor = settingWorkingDetails.buildDescriptor(
DomToAsciidocConverter.convert( javadocsToConvert )
);
final SortedSet<SettingDescriptor> docSectionSettings = result.get( docSection );
docSectionSettings.add( settingDescriptor );
}
}
}
return result;
}
public static Document loadConstants(File javadocDirectory) {
try {
final File constantValuesFile = new File( javadocDirectory, "constant-values.html" );
return Jsoup.parse( constantValuesFile );
}
catch (IOException e) {
throw new IllegalStateException( "Unable to access javadocs `constant-values.html`", e );
}
}
private static Document loadClassJavadoc(String enclosingClass, File javadocDirectory) {
final String classJavadocFileName = enclosingClass.replace( ".", File.separator ) + ".html";
final File classJavadocFile = new File( javadocDirectory, classJavadocFileName );
try {
return Jsoup.parse( classJavadocFile );
}
catch (IOException e) {
throw new RuntimeException( "Unable to access javadocs for " + enclosingClass, e );
}
}
/**
* @param fieldJavadocElement The element to inspect if it has some valuable documentation.
* @return {@code true} if no Javadoc was written for this field; {@code false} otherwise.
*/
private static boolean isUselessJavadoc(Element fieldJavadocElement) {
return fieldJavadocElement.selectFirst( "div.block" ) == null;
}
private static void applyMetadata(
String className,
String publishedJavadocsUrl,
SettingWorkingDetails settingDetails,
Element fieldJavadocElement) {
processNotes(
fieldJavadocElement,
(name, content) -> {
switch ( name ) {
case "Default Value:": {
fixUrls( className, publishedJavadocsUrl, content );
final String defaultValueText = DomToAsciidocConverter.convert( content );
settingDetails.setDefaultValue( defaultValueText );
break;
}
case "API Note:": {
settingDetails.setApiNote( content.text() );
break;
}
case "Since:": {
settingDetails.setSince( content.text() );
break;
}
}
}
);
settingDetails.setIncubating( interpretIncubation( fieldJavadocElement ) );
settingDetails.setDeprecated( interpretDeprecation( fieldJavadocElement ) );
settingDetails.setUnsafe( interpretUnsafe( fieldJavadocElement ) );
settingDetails.setCompatibility( interpretCompatibility( fieldJavadocElement ) );
}
private static SettingsDocSection findMatchingDocSection(
String className,
Map<String, SettingsDocSection> sections) {
for ( Map.Entry<String, SettingsDocSection> entry : sections.entrySet() ) {
if ( entry.getValue().getSettingsClassNames().contains( className ) ) {
return entry.getValue();
}
}
return null;
}
private static String stripQuotes(String value) {
if ( value.startsWith( "\"" ) && value.endsWith( "\"" ) ) {
return value.substring( 1, value.length() - 1 );
}
return value;
}
@FunctionalInterface
private
|
Javadoc
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/Plugin.java
|
{
"start": 1001,
"end": 1728
}
|
interface ____ {
/**
* Customize given command line adding sub-commands in particular.
*
* @param commandLine the command line to adjust.
* @param main the current JBang main.
*/
void customize(CommandLine commandLine, CamelJBangMain main);
/**
* The plugin may provide an optional project exporter implementation that is able to participate in an export
* performed by Camel JBang. Project exporter implementations may add properties and dependencies to the generated
* export.
*
* @return the plugin specific exporter implementation, otherwise empty
*/
default Optional<PluginExporter> getExporter() {
return Optional.empty();
}
}
|
Plugin
|
java
|
quarkusio__quarkus
|
extensions/grpc-common/runtime/src/main/java/io/quarkus/grpc/common/runtime/graal/GrpcNettySubstitutions.java
|
{
"start": 1150,
"end": 2115
}
|
class ____ {
@Substitute
public static SslContextBuilder configure(SslContextBuilder builder, SslProvider provider) {
switch (provider) {
case JDK: {
Provider jdkProvider = findJdkProvider();
if (jdkProvider == null) {
throw new IllegalArgumentException(
"Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers");
}
return configure(builder, jdkProvider);
}
default:
throw new IllegalArgumentException("Unsupported provider: " + provider);
}
}
@Alias
private static Provider findJdkProvider() {
return null;
}
@Alias
public static SslContextBuilder configure(SslContextBuilder builder, Provider jdkProvider) {
return null;
}
}
@TargetClass(className = "io.grpc.netty.Utils")
final
|
Target_io_grpc_netty_GrpcSslContexts
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
|
{
"start": 44035,
"end": 44163
}
|
interface ____ {",
" String duplicated();",
"",
" @Subcomponent.Builder",
"
|
Child
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest35.java
|
{
"start": 1016,
"end": 2391
}
|
class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "CREATE TABLE lookup" +
" (id INT, INDEX USING BTREE (id))" +
" AUTO_INCREMENT = 1;";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(1, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("lookup")));
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE TABLE lookup (" +
"\n\tid INT," +
"\n\tINDEX USING BTREE(id)" +
"\n) AUTO_INCREMENT = 1;", output);
}
}
|
MySqlCreateTableTest35
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/script/ScriptException.java
|
{
"start": 1573,
"end": 5762
}
|
class ____ extends ElasticsearchException {
private final List<String> scriptStack;
private final String script;
private final String lang;
private final Position pos;
/**
* Create a new ScriptException.
* @param message A short and simple summary of what happened, such as "compile error".
* Must not be {@code null}.
* @param cause The underlying cause of the exception. Must not be {@code null}.
* @param scriptStack An implementation-specific "stacktrace" for the error in the script.
* Must not be {@code null}, but can be empty (though this should be avoided if possible).
* @param script Identifier for which script failed. Must not be {@code null}.
* @param lang Scripting engine language, such as "painless". Must not be {@code null}.
* @param pos Position of error within script, may be {@code null}.
* @throws NullPointerException if any parameters are {@code null} except pos.
*/
public ScriptException(String message, Throwable cause, List<String> scriptStack, String script, String lang, Position pos) {
super(Objects.requireNonNull(message), Objects.requireNonNull(cause));
this.scriptStack = Collections.unmodifiableList(Objects.requireNonNull(scriptStack));
this.script = Objects.requireNonNull(script);
this.lang = Objects.requireNonNull(lang);
this.pos = pos;
}
/**
* Create a new ScriptException with null Position.
*/
public ScriptException(String message, Throwable cause, List<String> scriptStack, String script, String lang) {
this(message, cause, scriptStack, script, lang, null);
}
/**
* Deserializes a ScriptException from a {@code StreamInput}
*/
public ScriptException(StreamInput in) throws IOException {
super(in);
scriptStack = Arrays.asList(in.readStringArray());
script = in.readString();
lang = in.readString();
if (in.readBoolean()) {
pos = new Position(in);
} else {
pos = null;
}
}
@Override
protected void writeTo(StreamOutput out, Writer<Throwable> nestedExceptionsWriter) throws IOException {
super.writeTo(out, nestedExceptionsWriter);
out.writeStringCollection(scriptStack);
out.writeString(script);
out.writeString(lang);
if (pos == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
pos.writeTo(out);
}
}
@Override
protected void metadataToXContent(XContentBuilder builder, Params params) throws IOException {
builder.field("script_stack", scriptStack);
builder.field("script", script);
builder.field("lang", lang);
if (pos != null) {
pos.toXContent(builder, params);
}
}
/**
* Returns the stacktrace for the error in the script.
* @return a read-only list of frames, which may be empty.
*/
public List<String> getScriptStack() {
return scriptStack;
}
/**
* Returns the identifier for which script.
* @return script's name or source text that identifies the script.
*/
public String getScript() {
return script;
}
/**
* Returns the language of the script.
* @return the {@code lang} parameter of the scripting engine.
*/
public String getLang() {
return lang;
}
/**
* Returns the position of the error.
*/
public Position getPos() {
return pos;
}
/**
* Returns a JSON version of this exception for debugging.
*/
public String toJsonString() {
try {
XContentBuilder json = XContentFactory.jsonBuilder().prettyPrint();
json.startObject();
toXContent(json, ToXContent.EMPTY_PARAMS);
json.endObject();
return Strings.toString(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public RestStatus status() {
return RestStatus.BAD_REQUEST;
}
public static
|
ScriptException
|
java
|
elastic__elasticsearch
|
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LimitTokenCountFilterFactory.java
|
{
"start": 846,
"end": 1618
}
|
class ____ extends AbstractTokenFilterFactory {
static final int DEFAULT_MAX_TOKEN_COUNT = 1;
static final boolean DEFAULT_CONSUME_ALL_TOKENS = false;
private final int maxTokenCount;
private final boolean consumeAllTokens;
LimitTokenCountFilterFactory(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(name);
this.maxTokenCount = settings.getAsInt("max_token_count", DEFAULT_MAX_TOKEN_COUNT);
this.consumeAllTokens = settings.getAsBoolean("consume_all_tokens", DEFAULT_CONSUME_ALL_TOKENS);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new LimitTokenCountFilter(tokenStream, maxTokenCount, consumeAllTokens);
}
}
|
LimitTokenCountFilterFactory
|
java
|
apache__camel
|
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedDynamicRouterMBean.java
|
{
"start": 1021,
"end": 2007
}
|
interface ____ extends ManagedProcessorMBean, ManagedExtendedInformation, ManagedDestinationAware {
@ManagedAttribute(description = "The language for the expression")
String getExpressionLanguage();
@ManagedAttribute(description = "Expression to call that returns the endpoint(s) to route to in the dynamic routing",
mask = true)
String getExpression();
@ManagedAttribute(description = "The uri delimiter to use")
String getUriDelimiter();
@ManagedAttribute(description = "Sets the maximum size used by the ProducerCache which is used to cache and reuse producers")
Integer getCacheSize();
@ManagedAttribute(description = "Ignore the invalidate endpoint exception when try to create a producer with that endpoint")
Boolean isIgnoreInvalidEndpoints();
@Override
@ManagedOperation(description = "Statistics of the endpoints which has been sent to")
TabularData extendedInformation();
}
|
ManagedDynamicRouterMBean
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
|
{
"start": 61783,
"end": 62311
}
|
interface ____ {
// intentionally omitted: attribute = "value"
@AliasFor(annotation = ContextConfig.class)
String value() default "";
// intentionally omitted: attribute = "locations"
@AliasFor(annotation = ContextConfig.class)
String location() default "";
@AliasFor(annotation = ContextConfig.class, attribute = "location")
String xmlFile() default "";
}
@ImplicitAliasesWithImpliedAliasNamesOmittedContextConfig
@Retention(RetentionPolicy.RUNTIME)
@
|
ImplicitAliasesWithImpliedAliasNamesOmittedContextConfig
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Translate2EndpointBuilderFactory.java
|
{
"start": 23881,
"end": 25759
}
|
class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final Translate2HeaderNameBuilder INSTANCE = new Translate2HeaderNameBuilder();
/**
* The text source language.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsTranslateSourceLanguage}.
*/
public String awsTranslateSourceLanguage() {
return "CamelAwsTranslateSourceLanguage";
}
/**
* The text target language.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsTranslateTargetLanguage}.
*/
public String awsTranslateTargetLanguage() {
return "CamelAwsTranslateTargetLanguage";
}
/**
* The terminologies to use.
*
* The option is a: {@code Collection<String>} type.
*
* Group: producer
*
* @return the name of the header {@code AwsTranslateTerminologyNames}.
*/
public String awsTranslateTerminologyNames() {
return "CamelAwsTranslateTerminologyNames";
}
/**
* The operation we want to perform.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code AwsTranslateOperation}.
*/
public String awsTranslateOperation() {
return "CamelAwsTranslateOperation";
}
}
static Translate2EndpointBuilder endpointBuilder(String componentName, String path) {
|
Translate2HeaderNameBuilder
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/engine/jdbc/proxy/NClobProxy.java
|
{
"start": 824,
"end": 1689
}
|
class ____ extends ClobProxy implements NClob, NClobImplementer {
protected NClobProxy(String string) {
super( string );
}
protected NClobProxy(Reader reader, long length) {
super( reader, length );
}
/**
* Generates a {@link java.sql.Clob} proxy using the string data.
*
* @param string The data to be wrapped as a {@link java.sql.Clob}.
*
* @return The generated proxy.
*/
public static NClob generateProxy(String string) {
return new NClobProxy( string );
}
/**
* Generates a {@link NClob} proxy using a character reader of given length.
*
* @param reader The character reader
* @param length The length of the character reader
*
* @return The generated proxy.
*/
public static NClob generateProxy(Reader reader, long length) {
return new NClobProxy( reader, length );
}
/**
* Determines the appropriate
|
NClobProxy
|
java
|
spring-projects__spring-boot
|
module/spring-boot-health/src/main/java/org/springframework/boot/health/autoconfigure/actuate/endpoint/AvailabilityProbesAutoConfiguration.java
|
{
"start": 2127,
"end": 2914
}
|
class ____ {
@Bean
@ConditionalOnMissingBean(name = "livenessStateHealthIndicator")
LivenessStateHealthIndicator livenessStateHealthIndicator(ApplicationAvailability applicationAvailability) {
return new LivenessStateHealthIndicator(applicationAvailability);
}
@Bean
@ConditionalOnMissingBean(name = "readinessStateHealthIndicator")
ReadinessStateHealthIndicator readinessStateHealthIndicator(ApplicationAvailability applicationAvailability) {
return new ReadinessStateHealthIndicator(applicationAvailability);
}
@Bean
AvailabilityProbesHealthEndpointGroupsPostProcessor availabilityProbesHealthEndpointGroupsPostProcessor(
Environment environment) {
return new AvailabilityProbesHealthEndpointGroupsPostProcessor(environment);
}
}
|
AvailabilityProbesAutoConfiguration
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/fetching/FetchModeSubselectTest.java
|
{
"start": 1101,
"end": 2481
}
|
class ____ {
private final Logger log = Logger.getLogger( FetchModeSubselectTest.class );
@AfterEach
void tearDown(SessionFactoryScope factoryScope) {
factoryScope.dropData();
}
@Test
public void test(SessionFactoryScope factoryScope) {
factoryScope.inTransaction( entityManager -> {
for (long i = 0; i < 2; i++) {
Department department = new Department();
department.id = i + 1;
department.name = String.format("Department %d", department.id);
entityManager.persist(department);
for (long j = 0; j < 3; j++) {
Employee employee1 = new Employee();
employee1.username = String.format("user %d_%d", i, j);
employee1.department = department;
entityManager.persist(employee1);
}
}
});
factoryScope.inTransaction( entityManager -> {
//tag::fetching-strategies-fetch-mode-subselect-example[]
List<Department> departments = entityManager.createQuery(
"select d " +
"from Department d " +
"where d.name like :token", Department.class)
.setParameter("token", "Department%")
.getResultList();
log.infof("Fetched %d Departments", departments.size());
for (Department department : departments) {
assertEquals( 3, department.getEmployees().size() );
}
//end::fetching-strategies-fetch-mode-subselect-example[]
});
}
@Entity(name = "Department")
public static
|
FetchModeSubselectTest
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/utils/HistogramTest.java
|
{
"start": 120,
"end": 980
}
|
class ____ extends TestCase {
public void test_histo() throws Exception {
Histogram histo = Histogram.makeHistogram(4);
assertEquals(4, histo.getRanges().length);
histo.record(0);
histo.record(1);
histo.record(2);
histo.record(11);
histo.record(12);
histo.record(13);
histo.record(101);
histo.record(102);
histo.record(103);
histo.record(104);
histo.record(1001);
histo.record(1002);
histo.record(1003);
histo.record(1004);
histo.record(1005);
histo.record(10001);
assertEquals(1, histo.get(0));
assertEquals(2, histo.get(1));
assertEquals(3, histo.get(2));
assertEquals(4, histo.get(3));
assertEquals(6, histo.get(4));
histo.toString();
}
}
|
HistogramTest
|
java
|
apache__logging-log4j2
|
log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/BlockingAppender.java
|
{
"start": 1935,
"end": 2931
}
|
class ____ extends AbstractAppender {
private static final long serialVersionUID = 1L;
// logEvents may be nulled to disable event tracking, this is useful in scenarios testing garbage collection.
public List<LogEvent> logEvents = new CopyOnWriteArrayList<>();
public CountDownLatch countDownLatch = null;
public BlockingAppender(final String name) {
super(name, null, null, true, Property.EMPTY_ARRAY);
}
@Override
public void append(final LogEvent event) {
// for scenarios where domain objects log from their toString method in the background thread
event.getMessage().getFormattedMessage();
// may be a reusable event, make a copy, don't keep a reference to the original event
final List<LogEvent> events = logEvents;
if (events != null) {
events.add(event.toImmutable());
}
if (countDownLatch == null) {
return;
}
// block until the test
|
BlockingAppender
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/AnyKeySource.java
|
{
"start": 277,
"end": 439
}
|
interface ____ extends ImplicitAnyKeyColumnNameSource {
HibernateTypeSource getTypeSource();
List<RelationalValueSource> getRelationalValueSources();
}
|
AnyKeySource
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/CamelRouteStatus.java
|
{
"start": 1875,
"end": 20996
}
|
class ____ extends ProcessWatchCommand {
@CommandLine.Parameters(description = "Name or pid of running Camel integration", arity = "0..1")
String name = "*";
@CommandLine.Option(names = { "--sort" }, completionCandidates = PidNameAgeCompletionCandidates.class,
description = "Sort by pid, name or age", defaultValue = "pid")
String sort;
@CommandLine.Option(names = { "--source" },
description = "Prefer to display source filename/code instead of IDs")
boolean source;
@CommandLine.Option(names = { "--short-uri" },
description = "List endpoint URI without query parameters (short)")
boolean shortUri;
@CommandLine.Option(names = { "--wide-uri" },
description = "List endpoint URI in full details")
boolean wideUri;
@CommandLine.Option(names = { "--limit" },
description = "Filter routes by limiting to the given number of rows")
int limit;
@CommandLine.Option(names = { "--filter-mean" },
description = "Filter routes that must be slower than the given time (ms)")
long mean;
@CommandLine.Option(names = { "--running" },
description = "Only include running routes")
boolean running;
@CommandLine.Option(names = { "--filter" },
description = "Filter routes by id, or url")
String[] filter;
@CommandLine.Option(names = { "--group" },
description = "Filter routes by group")
String[] group;
@CommandLine.Option(names = { "--error" },
description = "Shows detailed information for routes that has error status")
boolean error;
@CommandLine.Option(names = { "--description" },
description = "Include description in the ID column (if available)")
boolean description;
@CommandLine.Option(names = { "--note" },
description = "Include note in the ID column (if available)")
boolean note;
@CommandLine.Option(names = { "--show-group" },
description = "Include group column")
boolean showGroup;
public CamelRouteStatus(CamelJBangMain main) {
super(main);
}
@Override
public Integer doProcessWatchCall() throws Exception {
List<Row> rows = new ArrayList<>();
AtomicBoolean remoteVisible = new AtomicBoolean();
List<Long> pids = findPids(name);
ProcessHandle.allProcesses()
.filter(ph -> pids.contains(ph.pid()))
.forEach(ph -> {
JsonObject root = loadStatus(ph.pid());
if (root != null) {
JsonObject context = (JsonObject) root.get("context");
if (context == null) {
return;
}
JsonArray array = (JsonArray) root.get("routes");
for (int i = 0; i < array.size(); i++) {
JsonObject o = (JsonObject) array.get(i);
Row row = new Row();
row.name = context.getString("name");
if ("CamelJBang".equals(row.name)) {
row.name = ProcessHelper.extractName(root, ph);
}
row.pid = Long.toString(ph.pid());
row.routeId = o.getString("routeId");
row.group = o.getString("group");
row.description = o.getString("description");
row.note = o.getString("note");
row.from = o.getString("from");
Boolean bool = o.getBoolean("remote");
if (bool != null) {
// older camel versions does not include this information
remoteVisible.set(true);
row.remote = bool;
}
row.source = o.getString("source");
row.state = o.getString("state");
row.age = o.getString("uptime");
row.uptime = row.age != null ? TimeUtils.toMilliSeconds(row.age) : 0;
JsonObject eo = (JsonObject) o.get("lastError");
if (eo != null) {
row.lastErrorPhase = eo.getString("phase");
row.lastErrorTimestamp = eo.getLongOrDefault("timestamp", 0);
row.lastErrorMessage = eo.getString("message");
row.stackTrace = eo.getCollection("stackTrace");
}
Map<String, ?> stats = o.getMap("statistics");
if (stats != null) {
Object load = stats.get("load01");
if (load != null) {
row.load01 = load.toString();
}
load = stats.get("load05");
if (load != null) {
row.load05 = load.toString();
}
load = stats.get("load15");
if (load != null) {
row.load15 = load.toString();
}
Object thp = stats.get("exchangesThroughput");
if (thp != null) {
row.throughput = thp.toString();
}
Object coverage = stats.get("coverage");
if (coverage != null) {
row.coverage = coverage.toString();
}
row.total = stats.get("exchangesTotal").toString();
row.inflight = stats.get("exchangesInflight").toString();
row.failed = stats.get("exchangesFailed").toString();
row.mean = stats.get("meanProcessingTime").toString();
if ("-1".equals(row.mean)) {
row.mean = null;
}
row.max = stats.get("maxProcessingTime").toString();
row.min = stats.get("minProcessingTime").toString();
Object last = stats.get("lastProcessingTime");
if (last != null) {
row.last = last.toString();
}
last = stats.get("deltaProcessingTime");
if (last != null) {
row.delta = last.toString();
}
last = stats.get("lastCreatedExchangeTimestamp");
if (last != null) {
long time = Long.parseLong(last.toString());
row.sinceLastStarted = TimeUtils.printSince(time);
}
last = stats.get("lastCompletedExchangeTimestamp");
if (last != null) {
long time = Long.parseLong(last.toString());
row.sinceLastCompleted = TimeUtils.printSince(time);
}
last = stats.get("lastFailedExchangeTimestamp");
if (last != null) {
long time = Long.parseLong(last.toString());
row.sinceLastFailed = TimeUtils.printSince(time);
}
}
boolean add = true;
if (mean > 0 && (row.mean == null || Long.parseLong(row.mean) < mean)) {
add = false;
}
if (limit > 0 && rows.size() >= limit) {
add = false;
}
if (add && filter != null) {
boolean match = false;
for (String f : filter) {
if (!match) {
String from = StringHelper.before(row.from, "?", row.from);
String w = f.endsWith("*") ? f : f + "*"; // use wildcard in matching url
match = PatternHelper.matchPattern(row.routeId, f)
|| PatternHelper.matchPattern(from, w);
}
}
if (!match) {
add = false;
}
}
if (add && group != null) {
add = PatternHelper.matchPatterns(row.group, group);
}
if (add && running) {
add = "Started".equals(row.state);
}
if (add) {
rows.add(row);
}
}
}
});
// sort rows
rows.sort(this::sortRow);
if (!rows.isEmpty()) {
if (error) {
for (Row r : rows) {
boolean error = r.lastErrorPhase != null;
if (error) {
printErrorTable(r, remoteVisible.get());
}
}
} else {
printTable(rows, remoteVisible.get());
}
}
return 0;
}
protected void printTable(List<Row> rows, boolean remoteVisible) {
printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, rows, Arrays.asList(
new Column().header("PID").headerAlign(HorizontalAlign.CENTER).with(r -> r.pid),
new Column().header("NAME").dataAlign(HorizontalAlign.LEFT).maxWidth(30, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(r -> r.name),
new Column().header("GROUP").visible(showGroup).dataAlign(HorizontalAlign.LEFT)
.maxWidth(20, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getGroup),
new Column().header("ID").visible(!description && !note).dataAlign(HorizontalAlign.LEFT)
.maxWidth(20, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getId),
new Column().header("ID").visible(description || note).dataAlign(HorizontalAlign.LEFT)
.maxWidth(45, OverflowBehaviour.NEWLINE)
.with(this::getIdAndNoteDescription),
new Column().header("FROM").visible(!wideUri).dataAlign(HorizontalAlign.LEFT)
.maxWidth(45, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getFrom),
new Column().header("FROM").visible(wideUri).dataAlign(HorizontalAlign.LEFT)
.maxWidth(140, OverflowBehaviour.NEWLINE)
.with(r -> r.from),
new Column().header("REMOTE").visible(remoteVisible).headerAlign(HorizontalAlign.CENTER)
.dataAlign(HorizontalAlign.CENTER)
.with(this::getRemote),
new Column().header("STATUS").dataAlign(HorizontalAlign.LEFT).headerAlign(HorizontalAlign.CENTER)
.with(this::getStatus),
new Column().header("AGE").headerAlign(HorizontalAlign.CENTER).with(r -> r.age),
new Column().header("COVER").with(this::getCoverage),
new Column().header("MSG/S").with(this::getThroughput),
new Column().header("TOTAL").with(this::getTotal),
new Column().header("FAIL").with(this::getFailed),
new Column().header("INFLIGHT").with(this::getInflight),
new Column().header("MEAN").with(r -> r.mean),
new Column().header("MIN").with(r -> r.min),
new Column().header("MAX").with(r -> r.max),
new Column().header("LAST").with(r -> r.last),
new Column().header("DELTA").with(this::getDelta),
new Column().header("SINCE-LAST").with(this::getSinceLast))));
}
protected void printErrorTable(Row er, boolean remoteVisible) {
printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, List.of(er), Arrays.asList(
new Column().header("PID").headerAlign(HorizontalAlign.CENTER).with(r -> r.pid),
new Column().header("NAME").dataAlign(HorizontalAlign.LEFT).maxWidth(30, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(r -> r.name),
new Column().header("ID").visible(!description).dataAlign(HorizontalAlign.LEFT)
.maxWidth(20, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getId),
new Column().header("ID").visible(description).dataAlign(HorizontalAlign.LEFT)
.maxWidth(45, OverflowBehaviour.NEWLINE)
.with(this::getIdAndNoteDescription),
new Column().header("FROM").visible(!wideUri).dataAlign(HorizontalAlign.LEFT)
.maxWidth(45, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getFrom),
new Column().header("FROM").visible(wideUri).dataAlign(HorizontalAlign.LEFT)
.with(r -> r.from),
new Column().header("REMOTE").visible(remoteVisible).headerAlign(HorizontalAlign.CENTER)
.dataAlign(HorizontalAlign.CENTER)
.with(this::getRemote),
new Column().header("STATUS").dataAlign(HorizontalAlign.LEFT).headerAlign(HorizontalAlign.CENTER)
.with(this::getStatus),
new Column().header("PHASE").dataAlign(HorizontalAlign.LEFT).headerAlign(HorizontalAlign.CENTER)
.with(r -> r.lastErrorPhase),
new Column().header("AGO").headerAlign(HorizontalAlign.CENTER)
.with(this::getErrorAgo),
new Column().header("MESSAGE").dataAlign(HorizontalAlign.LEFT)
.maxWidth(80, OverflowBehaviour.NEWLINE)
.with(r -> r.lastErrorMessage))));
if (!er.stackTrace.isEmpty()) {
printer().println();
printer().println(StringHelper.fillChars('-', 120));
printer().println(StringHelper.padString(1, 55) + "STACK-TRACE");
printer().println(StringHelper.fillChars('-', 120));
for (String line : er.stackTrace) {
printer().println(String.format("\t%s", line));
}
printer().println();
}
}
protected int sortRow(Row o1, Row o2) {
String s = sort;
int negate = 1;
if (s.startsWith("-")) {
s = s.substring(1);
negate = -1;
}
switch (s) {
case "pid":
return Long.compare(Long.parseLong(o1.pid), Long.parseLong(o2.pid)) * negate;
case "name":
return o1.name.compareToIgnoreCase(o2.name) * negate;
case "age":
return Long.compare(o1.uptime, o2.uptime) * negate;
default:
return 0;
}
}
protected String getErrorAgo(Row r) {
if (r.lastErrorTimestamp > 0) {
return TimeUtils.printSince(r.lastErrorTimestamp);
}
return "";
}
protected String getFrom(Row r) {
String u = r.from;
if (shortUri) {
int pos = u.indexOf('?');
if (pos > 0) {
u = u.substring(0, pos);
}
}
return u;
}
protected String getSinceLast(Row r) {
String s1 = r.sinceLastStarted != null ? r.sinceLastStarted : "-";
String s2 = r.sinceLastCompleted != null ? r.sinceLastCompleted : "-";
String s3 = r.sinceLastFailed != null ? r.sinceLastFailed : "-";
return s1 + "/" + s2 + "/" + s3;
}
protected String getThroughput(Row r) {
String s = r.throughput;
if (s == null || s.isEmpty()) {
s = "";
}
return s;
}
protected String getCoverage(Row r) {
String s = r.coverage;
if (s == null || s.isEmpty()) {
s = "";
}
return s;
}
protected String getRemote(Row r) {
return r.remote ? "x" : "";
}
protected String getStatus(Row r) {
if (r.lastErrorPhase != null) {
return "Error";
}
return r.state;
}
protected String getGroup(Row r) {
return r.group;
}
protected String getId(Row r) {
if (source && r.source != null) {
return sourceLocLine(r.source);
} else {
return r.routeId;
}
}
protected String getIdAndNoteDescription(Row r) {
String id = getId(r);
if (description && r.description != null) {
if (id != null) {
id = id + "\n " + Strings.wrapWords(r.description, " ", "\n ", 40, true);
} else {
id = r.description;
}
}
if (note && r.note != null) {
if (id != null) {
id = id + "\n " + Strings.wrapWords(r.note, " ", "\n ", 40, true);
} else {
id = r.note;
}
}
return id;
}
protected String getDelta(Row r) {
if (r.delta != null) {
if (r.delta.startsWith("-")) {
return r.delta;
} else if (!"0".equals(r.delta)) {
// use plus sign to denote slower when positive
return "+" + r.delta;
}
}
return r.delta;
}
protected String getTotal(Row r) {
return r.total;
}
protected String getFailed(Row r) {
return r.failed;
}
protected String getInflight(Row r) {
return r.inflight;
}
static
|
CamelRouteStatus
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/utils/StatisticsReportTestBase.java
|
{
"start": 12483,
"end": 13717
}
|
class ____ extends RelVisitor {
private FlinkStatistic result = null;
@Override
public void visit(RelNode node, int ordinal, RelNode parent) {
if (node instanceof TableScan) {
Preconditions.checkArgument(result == null);
TableSourceTable table = (TableSourceTable) node.getTable();
result = table.getStatistic();
}
super.visit(node, ordinal, parent);
}
}
protected static String[] ddlTypesMapToStringList(Map<String, String> ddlTypesMap) {
String[] types = new String[ddlTypesMap.size()];
int i = 0;
for (Map.Entry<String, String> entry : ddlTypesMap.entrySet()) {
String str = entry.getValue() + " " + entry.getKey();
types[i++] = str;
}
return types;
}
private static PlannerBase getPlanner(TableEnvironment tEnv) {
TableEnvironmentImpl tEnvImpl = (TableEnvironmentImpl) tEnv;
return (PlannerBase) tEnvImpl.getPlanner();
}
protected LocalDateTime localDateTime(String dateTime, int precision) {
return DateTimeUtils.parseTimestampData(dateTime, precision).toLocalDateTime();
}
}
|
FlinkStatisticVisitor
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ClientDatanodeProtocol.java
|
{
"start": 2611,
"end": 6924
}
|
class ____ used for protocols
* serialization. DO not update this version any further.
*/
long versionID = 9L;
/** Return the visible length of a replica. */
long getReplicaVisibleLength(ExtendedBlock b) throws IOException;
/**
* Refresh the list of federated namenodes from updated configuration
* Adds new namenodes and stops the deleted namenodes.
*
* @throws IOException on error
**/
void refreshNamenodes() throws IOException;
/**
* Delete the block pool directory. If force is false it is deleted only if
* it is empty, otherwise it is deleted along with its contents.
*
* @param bpid Blockpool id to be deleted.
* @param force If false blockpool directory is deleted only if it is empty
* i.e. if it doesn't contain any block files, otherwise it is
* deleted along with its contents.
* @throws IOException
*/
void deleteBlockPool(String bpid, boolean force) throws IOException;
/**
* Retrieves the path names of the block file and metadata file stored on the
* local file system.
*
* In order for this method to work, one of the following should be satisfied:
* <ul>
* <li>
* The client user must be configured at the datanode to be able to use this
* method.</li>
* <li>
* When security is enabled, kerberos authentication must be used to connect
* to the datanode.</li>
* </ul>
*
* @param block
* the specified block on the local datanode
* @param token
* the block access token.
* @return the BlockLocalPathInfo of a block
* @throws IOException
* on error
*/
BlockLocalPathInfo getBlockLocalPathInfo(ExtendedBlock block,
Token<BlockTokenIdentifier> token) throws IOException;
/**
* Shuts down a datanode.
*
* @param forUpgrade If true, data node does extra prep work before shutting
* down. The work includes advising clients to wait and saving
* certain states for quick restart. This should only be used when
* the stored data will remain the same during upgrade/restart.
* @throws IOException
*/
void shutdownDatanode(boolean forUpgrade) throws IOException;
/**
* Evict clients that are writing to a datanode.
*
* @throws IOException
*/
void evictWriters() throws IOException;
/**
* Obtains datanode info
*
* @return software/config version and uptime of the datanode
*/
DatanodeLocalInfo getDatanodeInfo() throws IOException;
/**
* Asynchronously reload configuration on disk and apply changes.
*/
void startReconfiguration() throws IOException;
/**
* Get the status of the previously issued reconfig task.
* @see org.apache.hadoop.conf.ReconfigurationTaskStatus
*/
ReconfigurationTaskStatus getReconfigurationStatus() throws IOException;
/**
* Get a list of allowed properties for reconfiguration.
*/
List<String> listReconfigurableProperties() throws IOException;
/**
* Trigger a new block report.
*/
void triggerBlockReport(BlockReportOptions options)
throws IOException;
/**
* Get current value of the balancer bandwidth in bytes per second.
*
* @return balancer bandwidth
*/
long getBalancerBandwidth() throws IOException;
/**
* Get volume report of datanode.
*/
List<DatanodeVolumeInfo> getVolumeReport() throws IOException;
/**
* Submit a disk balancer plan for execution.
*/
void submitDiskBalancerPlan(String planID, long planVersion, String planFile,
String planData, boolean skipDateCheck)
throws IOException;
/**
* Cancel an executing plan.
*
* @param planID - A SHA-1 hash of the plan string.
*/
void cancelDiskBalancePlan(String planID) throws IOException;
/**
* Gets the status of an executing diskbalancer Plan.
*/
DiskBalancerWorkStatus queryDiskBalancerPlan() throws IOException;
/**
* Gets a run-time configuration value from running diskbalancer instance.
* For example : Disk Balancer bandwidth of a running instance.
*
* @param key runtime configuration key
* @return value of the key as a string.
* @throws IOException - Throws if there is no such key
*/
String getDiskBalancerSetting(String key) throws IOException;
}
|
was
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/ast/SQLPartitionByList.java
|
{
"start": 712,
"end": 1696
}
|
class ____ extends SQLPartitionBy {
protected PartitionByListType type;
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, columns);
acceptChild(visitor, partitionsCount);
acceptChild(visitor, getPartitions());
acceptChild(visitor, subPartitionBy);
}
visitor.endVisit(this);
}
public PartitionByListType getType() {
return type;
}
public void setType(PartitionByListType type) {
this.type = type;
}
public SQLPartitionByList clone() {
SQLPartitionByList x = new SQLPartitionByList();
this.cloneTo(x);
for (SQLExpr column : columns) {
SQLExpr c2 = column.clone();
c2.setParent(x);
x.columns.add(c2);
}
return x;
}
public void cloneTo(SQLPartitionByList x) {
super.cloneTo(x);
}
public
|
SQLPartitionByList
|
java
|
google__dagger
|
dagger-producers/main/java/dagger/producers/internal/AbstractMapProducer.java
|
{
"start": 1335,
"end": 1833
}
|
class ____<K, V, V2> extends AbstractProducer<Map<K, V2>> {
private final ImmutableMap<K, Producer<V>> contributingMap;
AbstractMapProducer(ImmutableMap<K, Producer<V>> contributingMap) {
this.contributingMap = contributingMap;
}
/** The map of {@link Producer}s that contribute to this map binding. */
final ImmutableMap<K, Producer<V>> contributingMap() {
return contributingMap;
}
/** A builder for {@link AbstractMapProducer} */
public abstract static
|
AbstractMapProducer
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/index/fieldvisitor/IgnoredSourceFieldLoaderTests.java
|
{
"start": 1256,
"end": 6170
}
|
class ____ extends ESTestCase {
public void testSupports() {
assertTrue(
IgnoredSourceFieldLoader.supports(
StoredFieldsSpec.withSourcePaths(
IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE,
Set.of("foo")
)
)
);
assertFalse(
IgnoredSourceFieldLoader.supports(
StoredFieldsSpec.withSourcePaths(IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE, Set.of())
)
);
assertFalse(
IgnoredSourceFieldLoader.supports(
StoredFieldsSpec.withSourcePaths(IgnoredSourceFieldMapper.IgnoredSourceFormat.NO_IGNORED_SOURCE, Set.of("foo"))
)
);
assertFalse(IgnoredSourceFieldLoader.supports(StoredFieldsSpec.NO_REQUIREMENTS));
}
private IgnoredSourceFieldMapper.NameValue[] nameValue(String name, String... values) {
var nameValues = new IgnoredSourceFieldMapper.NameValue[values.length];
for (int i = 0; i < values.length; i++) {
nameValues[i] = new IgnoredSourceFieldMapper.NameValue(name, 0, new BytesRef(values[i]), null);
}
return nameValues;
}
public void testLoadSingle() throws IOException {
var fooValue = nameValue("foo", "lorem ipsum");
Document doc = new Document();
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(fooValue))));
testLoader(doc, Set.of("foo"), ignoredSourceEntries -> {
assertThat(ignoredSourceEntries, containsInAnyOrder(containsInAnyOrder(fooValue)));
});
}
public void testLoadMultiple() throws IOException {
var fooValue = nameValue("foo", "lorem ipsum");
var barValue = nameValue("bar", "dolor sit amet");
Document doc = new Document();
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(fooValue))));
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(barValue))));
testLoader(doc, Set.of("foo", "bar"), ignoredSourceEntries -> {
assertThat(ignoredSourceEntries, containsInAnyOrder(containsInAnyOrder(fooValue), containsInAnyOrder(barValue)));
});
}
public void testLoadSubset() throws IOException {
var fooValue = nameValue("foo", "lorem ipsum");
var barValue = nameValue("bar", "dolor sit amet");
Document doc = new Document();
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(fooValue))));
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(barValue))));
testLoader(doc, Set.of("foo"), ignoredSourceEntries -> {
assertThat(ignoredSourceEntries, containsInAnyOrder(containsInAnyOrder(fooValue)));
});
}
public void testLoadFromParent() throws IOException {
var fooValue = new IgnoredSourceFieldMapper.NameValue("parent", 7, new BytesRef("lorem ipsum"), null);
Document doc = new Document();
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(fooValue))));
testLoader(doc, Set.of("parent.foo"), ignoredSourceEntries -> {
assertThat(ignoredSourceEntries, containsInAnyOrder(containsInAnyOrder(fooValue)));
});
}
private void testLoader(
Document doc,
Set<String> fieldsToLoad,
Consumer<List<List<IgnoredSourceFieldMapper.NameValue>>> ignoredSourceTest
) throws IOException {
try (Directory dir = newDirectory(); IndexWriter iw = new IndexWriter(dir, newIndexWriterConfig(Lucene.STANDARD_ANALYZER))) {
StoredFieldsSpec spec = StoredFieldsSpec.withSourcePaths(
IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE,
fieldsToLoad
);
assertTrue(IgnoredSourceFieldLoader.supports(spec));
iw.addDocument(doc);
try (DirectoryReader reader = DirectoryReader.open(iw)) {
IgnoredSourceFieldLoader loader = new IgnoredSourceFieldLoader(spec, false);
var leafLoader = loader.getLoader(reader.leaves().getFirst(), new int[] { 0 });
leafLoader.advanceTo(0);
@SuppressWarnings("unchecked")
var ignoredSourceEntries = (List<List<IgnoredSourceFieldMapper.NameValue>>) (Object) leafLoader.storedFields()
.get("_ignored_source");
ignoredSourceTest.accept(ignoredSourceEntries);
}
}
}
}
|
IgnoredSourceFieldLoaderTests
|
java
|
apache__camel
|
components/camel-github/src/test/java/org/apache/camel/component/github/services/MockCommitService.java
|
{
"start": 1376,
"end": 3464
}
|
class ____ extends CommitService {
protected static final Logger LOG = LoggerFactory.getLogger(MockCommitService.class);
private List<RepositoryCommit> commitsList = new ArrayList<>();
private AtomicLong fakeSha = new AtomicLong(System.currentTimeMillis());
private Map<String, CommitStatus> commitStatus = new HashMap<>();
public synchronized RepositoryCommit addRepositoryCommit(String message) {
User author = new User();
author.setEmail("someguy@gmail.com"); // TODO change
author.setHtmlUrl("http://github/someguy");
author.setLogin("someguy");
RepositoryCommit rc = new RepositoryCommit();
rc.setAuthor(author);
rc.setSha(fakeSha.incrementAndGet() + "");
rc.setCommitter(author);
Commit commit = new Commit();
if (message == null) {
commit.setMessage("Test");
} else {
commit.setMessage(message);
}
rc.setCommit(commit);
LOG.debug("In MockCommitService added commit with sha {}", rc.getSha());
commitsList.add(0, rc);
return rc;
}
@Override
public synchronized List<RepositoryCommit> getCommits(IRepositoryIdProvider repository, String sha, String path) {
LOG.debug("Returning list of size {}", commitsList.size());
if (sha != null) {
for (int i = 0; i < commitsList.size(); i++) {
RepositoryCommit commit = commitsList.get(i);
if (commit.getSha().equals(sha)) {
return commitsList.subList(i, commitsList.size());
}
}
}
return commitsList;
}
@Override
public CommitStatus createStatus(
IRepositoryIdProvider repository,
String sha, CommitStatus status) {
commitStatus.put(sha, status);
return status;
}
public String getNextSha() {
return fakeSha.incrementAndGet() + "";
}
public CommitStatus getCommitStatus(String sha) {
return commitStatus.get(sha);
}
}
|
MockCommitService
|
java
|
spring-projects__spring-boot
|
smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyFilterManagementPortTests.java
|
{
"start": 974,
"end": 1059
}
|
class ____ extends AbstractJerseyManagementPortTests {
}
|
JerseyFilterManagementPortTests
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/QueryFederationQueuePoliciesResponse.java
|
{
"start": 1443,
"end": 4312
}
|
class ____ {
@Private
@Unstable
public static QueryFederationQueuePoliciesResponse newInstance(
int totalSize, int totalPage, int currentPage, int pageSize,
List<FederationQueueWeight> federationQueueWeights) {
QueryFederationQueuePoliciesResponse response =
Records.newRecord(QueryFederationQueuePoliciesResponse.class);
response.setTotalSize(totalSize);
response.setTotalPage(totalPage);
response.setCurrentPage(currentPage);
response.setPageSize(pageSize);
response.setFederationQueueWeights(federationQueueWeights);
return response;
}
@Private
@Unstable
public static QueryFederationQueuePoliciesResponse newInstance() {
QueryFederationQueuePoliciesResponse response =
Records.newRecord(QueryFederationQueuePoliciesResponse.class);
return response;
}
/**
* Returns the total size of the query result.
* It is mainly related to the filter conditions set by the user.
*
* @return The total size of the query result.
*/
public abstract int getTotalSize();
/**
* Sets the total size of the federationQueueWeights.
*
* @param totalSize The total size of the query result to be set.
*/
public abstract void setTotalSize(int totalSize);
/**
* Returns the page.
*
* @return page.
*/
@Public
@Unstable
public abstract int getTotalPage();
/**
* Sets the page.
*
* @param page page.
*/
@Private
@Unstable
public abstract void setTotalPage(int page);
/**
* Returns the current page number in the FederationQueuePolicies pagination.
*
* @return The current page number.
*/
@Public
@Unstable
public abstract int getCurrentPage();
/**
* Sets the current page in the FederationQueuePolicies pagination.
*
* @param currentPage The current page number.
*/
@Private
@Unstable
public abstract void setCurrentPage(int currentPage);
/**
* Retrieves the page size.
*
* @return The number of policies to display per page.
*/
@Public
@Unstable
public abstract int getPageSize();
/**
* Sets the page size for FederationQueuePolicies pagination.
*
* @param pageSize The number of policies to display per page.
*/
@Private
@Unstable
public abstract void setPageSize(int pageSize);
/**
* Get a list of FederationQueueWeight objects of different queues.
*
* @return list of FederationQueueWeight.
*/
@Public
@Unstable
public abstract List<FederationQueueWeight> getFederationQueueWeights();
/**
* Sets the FederationQueueWeights, which represent the weights of different queues.
*
* @param federationQueueWeights list of FederationQueueWeight.
*/
@Private
@Unstable
public abstract void setFederationQueueWeights(
List<FederationQueueWeight> federationQueueWeights);
}
|
QueryFederationQueuePoliciesResponse
|
java
|
apache__camel
|
components/camel-servicenow/camel-servicenow-component/src/test/java/org/apache/camel/component/servicenow/ServiceNowImportSetIT.java
|
{
"start": 1759,
"end": 5929
}
|
class ____ extends ServiceNowITSupport {
@Test
public void testIncidentImport() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:servicenow");
mock.reset();
mock.expectedMessageCount(1);
mock.expectedHeaderReceived(ServiceNowConstants.RESPONSE_TYPE, ArrayList.class);
IncidentImportRequest incident = new IncidentImportRequest();
incident.description = UUID.randomUUID().toString();
incident.correlationId = UUID.randomUUID().toString();
template().sendBodyAndHeaders(
"direct:servicenow",
incident,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, ServiceNowConstants.RESOURCE_IMPORT)
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_CREATE)
.put(ServiceNowConstants.REQUEST_MODEL, IncidentImportRequest.class)
.put(ServiceNowConstants.RESPONSE_MODEL, ImportSetResult.class)
.put(ServiceNowParams.PARAM_TABLE_NAME, "u_test_imp_incident")
.build());
mock.assertIsSatisfied();
Message in = mock.getExchanges().get(0).getIn();
// Meta data
Map<String, String> meta = in.getHeader(ServiceNowConstants.RESPONSE_META, Map.class);
assertNotNull(meta);
assertEquals("u_test_imp_incident", meta.get("staging_table"));
// Incidents
List<ImportSetResult> responses = in.getBody(List.class);
assertNotNull(responses);
assertEquals(1, responses.size());
assertEquals("inserted", responses.get(0).getStatus());
assertEquals("test_imp_incident", responses.get(0).getTransformMap());
assertEquals("incident", responses.get(0).getTable());
}
@Test
public void testIncidentImportWithRetrieve() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:servicenow");
mock.reset();
mock.expectedMessageCount(1);
mock.expectedHeaderReceived(ServiceNowConstants.RESPONSE_TYPE, Incident.class);
IncidentImportRequest incident = new IncidentImportRequest();
incident.description = UUID.randomUUID().toString();
template().sendBodyAndHeaders(
"direct:servicenow",
incident,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, ServiceNowConstants.RESOURCE_IMPORT)
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_CREATE)
.put(ServiceNowConstants.REQUEST_MODEL, IncidentImportRequest.class)
.put(ServiceNowConstants.RESPONSE_MODEL, Incident.class)
.put(ServiceNowConstants.RETRIEVE_TARGET_RECORD, true)
.put(ServiceNowParams.PARAM_TABLE_NAME, "u_test_imp_incident")
.build());
mock.assertIsSatisfied();
Incident response = mock.getExchanges().get(0).getIn().getBody(Incident.class);
assertNotNull(response);
assertEquals(incident.description, response.getDescription());
assertNotNull(response.getNumber());
assertNotNull(response.getId());
}
// *************************************************************************
//
// *************************************************************************
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:servicenow")
.to("servicenow:{{env:SERVICENOW_INSTANCE}}")
.to("log:org.apache.camel.component.servicenow?level=INFO&showAll=true")
.to("mock:servicenow");
}
};
}
// *************************************************************************
//
// *************************************************************************
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
private static final
|
ServiceNowImportSetIT
|
java
|
grpc__grpc-java
|
alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java
|
{
"start": 7549,
"end": 9019
}
|
class ____
extends io.grpc.stub.AbstractBlockingStub<HandshakerServiceBlockingV2Stub> {
private HandshakerServiceBlockingV2Stub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected HandshakerServiceBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new HandshakerServiceBlockingV2Stub(channel, callOptions);
}
/**
* <pre>
* Handshaker service accepts a stream of handshaker request, returning a
* stream of handshaker response. Client is expected to send exactly one
* message with either client_start or server_start followed by one or more
* messages with next. Each time client sends a request, the handshaker
* service expects to respond. Client does not have to wait for service's
* response before sending next request.
* </pre>
*/
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/10918")
public io.grpc.stub.BlockingClientCall<io.grpc.alts.internal.HandshakerReq, io.grpc.alts.internal.HandshakerResp>
doHandshake() {
return io.grpc.stub.ClientCalls.blockingBidiStreamingCall(
getChannel(), getDoHandshakeMethod(), getCallOptions());
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service HandshakerService.
*/
public static final
|
HandshakerServiceBlockingV2Stub
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.