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 | apache__camel | core/camel-main/src/generated/java/org/apache/camel/main/RestConfigurationPropertiesConfigurer.java | {
"start": 705,
"end": 15057
} | class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("ApiComponent", java.lang.String.class);
map.put("ApiContextPath", java.lang.String.class);
map.put("ApiContextRouteId", java.lang.String.class);
map.put("ApiHost", java.lang.String.class);
map.put("ApiProperties", java.util.Map.class);
map.put("ApiVendorExtension", boolean.class);
map.put("BindingMode", java.lang.String.class);
map.put("BindingPackageScan", java.lang.String.class);
map.put("ClientRequestValidation", boolean.class);
map.put("ClientResponseValidation", boolean.class);
map.put("Component", java.lang.String.class);
map.put("ComponentProperties", java.util.Map.class);
map.put("ConsumerProperties", java.util.Map.class);
map.put("ContextPath", java.lang.String.class);
map.put("CorsHeaders", java.util.Map.class);
map.put("DataFormatProperties", java.util.Map.class);
map.put("EnableCORS", boolean.class);
map.put("EnableNoContentResponse", boolean.class);
map.put("EndpointProperties", java.util.Map.class);
map.put("Host", java.lang.String.class);
map.put("HostNameResolver", java.lang.String.class);
map.put("InlineRoutes", boolean.class);
map.put("JsonDataFormat", java.lang.String.class);
map.put("Port", int.class);
map.put("ProducerApiDoc", java.lang.String.class);
map.put("ProducerComponent", java.lang.String.class);
map.put("Scheme", java.lang.String.class);
map.put("SkipBindingOnErrorCode", boolean.class);
map.put("UseXForwardHeaders", boolean.class);
map.put("ValidationLevels", java.util.Map.class);
map.put("XmlDataFormat", java.lang.String.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.main.RestConfigurationProperties target = (org.apache.camel.main.RestConfigurationProperties) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apicomponent":
case "apiComponent": target.setApiComponent(property(camelContext, java.lang.String.class, value)); return true;
case "apicontextpath":
case "apiContextPath": target.setApiContextPath(property(camelContext, java.lang.String.class, value)); return true;
case "apicontextrouteid":
case "apiContextRouteId": target.setApiContextRouteId(property(camelContext, java.lang.String.class, value)); return true;
case "apihost":
case "apiHost": target.setApiHost(property(camelContext, java.lang.String.class, value)); return true;
case "apiproperties":
case "apiProperties": target.setApiProperties(property(camelContext, java.util.Map.class, value)); return true;
case "apivendorextension":
case "apiVendorExtension": target.setApiVendorExtension(property(camelContext, boolean.class, value)); return true;
case "bindingmode":
case "bindingMode": target.setBindingMode(property(camelContext, java.lang.String.class, value)); return true;
case "bindingpackagescan":
case "bindingPackageScan": target.setBindingPackageScan(property(camelContext, java.lang.String.class, value)); return true;
case "clientrequestvalidation":
case "clientRequestValidation": target.setClientRequestValidation(property(camelContext, boolean.class, value)); return true;
case "clientresponsevalidation":
case "clientResponseValidation": target.setClientResponseValidation(property(camelContext, boolean.class, value)); return true;
case "component": target.setComponent(property(camelContext, java.lang.String.class, value)); return true;
case "componentproperties":
case "componentProperties": target.setComponentProperties(property(camelContext, java.util.Map.class, value)); return true;
case "consumerproperties":
case "consumerProperties": target.setConsumerProperties(property(camelContext, java.util.Map.class, value)); return true;
case "contextpath":
case "contextPath": target.setContextPath(property(camelContext, java.lang.String.class, value)); return true;
case "corsheaders":
case "corsHeaders": target.setCorsHeaders(property(camelContext, java.util.Map.class, value)); return true;
case "dataformatproperties":
case "dataFormatProperties": target.setDataFormatProperties(property(camelContext, java.util.Map.class, value)); return true;
case "enablecors":
case "enableCORS": target.setEnableCORS(property(camelContext, boolean.class, value)); return true;
case "enablenocontentresponse":
case "enableNoContentResponse": target.setEnableNoContentResponse(property(camelContext, boolean.class, value)); return true;
case "endpointproperties":
case "endpointProperties": target.setEndpointProperties(property(camelContext, java.util.Map.class, value)); return true;
case "host": target.setHost(property(camelContext, java.lang.String.class, value)); return true;
case "hostnameresolver":
case "hostNameResolver": target.setHostNameResolver(property(camelContext, java.lang.String.class, value)); return true;
case "inlineroutes":
case "inlineRoutes": target.setInlineRoutes(property(camelContext, boolean.class, value)); return true;
case "jsondataformat":
case "jsonDataFormat": target.setJsonDataFormat(property(camelContext, java.lang.String.class, value)); return true;
case "port": target.setPort(property(camelContext, int.class, value)); return true;
case "producerapidoc":
case "producerApiDoc": target.setProducerApiDoc(property(camelContext, java.lang.String.class, value)); return true;
case "producercomponent":
case "producerComponent": target.setProducerComponent(property(camelContext, java.lang.String.class, value)); return true;
case "scheme": target.setScheme(property(camelContext, java.lang.String.class, value)); return true;
case "skipbindingonerrorcode":
case "skipBindingOnErrorCode": target.setSkipBindingOnErrorCode(property(camelContext, boolean.class, value)); return true;
case "usexforwardheaders":
case "useXForwardHeaders": target.setUseXForwardHeaders(property(camelContext, boolean.class, value)); return true;
case "validationlevels":
case "validationLevels": target.setValidationLevels(property(camelContext, java.util.Map.class, value)); return true;
case "xmldataformat":
case "xmlDataFormat": target.setXmlDataFormat(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "apicomponent":
case "apiComponent": return java.lang.String.class;
case "apicontextpath":
case "apiContextPath": return java.lang.String.class;
case "apicontextrouteid":
case "apiContextRouteId": return java.lang.String.class;
case "apihost":
case "apiHost": return java.lang.String.class;
case "apiproperties":
case "apiProperties": return java.util.Map.class;
case "apivendorextension":
case "apiVendorExtension": return boolean.class;
case "bindingmode":
case "bindingMode": return java.lang.String.class;
case "bindingpackagescan":
case "bindingPackageScan": return java.lang.String.class;
case "clientrequestvalidation":
case "clientRequestValidation": return boolean.class;
case "clientresponsevalidation":
case "clientResponseValidation": return boolean.class;
case "component": return java.lang.String.class;
case "componentproperties":
case "componentProperties": return java.util.Map.class;
case "consumerproperties":
case "consumerProperties": return java.util.Map.class;
case "contextpath":
case "contextPath": return java.lang.String.class;
case "corsheaders":
case "corsHeaders": return java.util.Map.class;
case "dataformatproperties":
case "dataFormatProperties": return java.util.Map.class;
case "enablecors":
case "enableCORS": return boolean.class;
case "enablenocontentresponse":
case "enableNoContentResponse": return boolean.class;
case "endpointproperties":
case "endpointProperties": return java.util.Map.class;
case "host": return java.lang.String.class;
case "hostnameresolver":
case "hostNameResolver": return java.lang.String.class;
case "inlineroutes":
case "inlineRoutes": return boolean.class;
case "jsondataformat":
case "jsonDataFormat": return java.lang.String.class;
case "port": return int.class;
case "producerapidoc":
case "producerApiDoc": return java.lang.String.class;
case "producercomponent":
case "producerComponent": return java.lang.String.class;
case "scheme": return java.lang.String.class;
case "skipbindingonerrorcode":
case "skipBindingOnErrorCode": return boolean.class;
case "usexforwardheaders":
case "useXForwardHeaders": return boolean.class;
case "validationlevels":
case "validationLevels": return java.util.Map.class;
case "xmldataformat":
case "xmlDataFormat": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.main.RestConfigurationProperties target = (org.apache.camel.main.RestConfigurationProperties) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apicomponent":
case "apiComponent": return target.getApiComponent();
case "apicontextpath":
case "apiContextPath": return target.getApiContextPath();
case "apicontextrouteid":
case "apiContextRouteId": return target.getApiContextRouteId();
case "apihost":
case "apiHost": return target.getApiHost();
case "apiproperties":
case "apiProperties": return target.getApiProperties();
case "apivendorextension":
case "apiVendorExtension": return target.isApiVendorExtension();
case "bindingmode":
case "bindingMode": return target.getBindingMode();
case "bindingpackagescan":
case "bindingPackageScan": return target.getBindingPackageScan();
case "clientrequestvalidation":
case "clientRequestValidation": return target.isClientRequestValidation();
case "clientresponsevalidation":
case "clientResponseValidation": return target.isClientResponseValidation();
case "component": return target.getComponent();
case "componentproperties":
case "componentProperties": return target.getComponentProperties();
case "consumerproperties":
case "consumerProperties": return target.getConsumerProperties();
case "contextpath":
case "contextPath": return target.getContextPath();
case "corsheaders":
case "corsHeaders": return target.getCorsHeaders();
case "dataformatproperties":
case "dataFormatProperties": return target.getDataFormatProperties();
case "enablecors":
case "enableCORS": return target.isEnableCORS();
case "enablenocontentresponse":
case "enableNoContentResponse": return target.isEnableNoContentResponse();
case "endpointproperties":
case "endpointProperties": return target.getEndpointProperties();
case "host": return target.getHost();
case "hostnameresolver":
case "hostNameResolver": return target.getHostNameResolver();
case "inlineroutes":
case "inlineRoutes": return target.isInlineRoutes();
case "jsondataformat":
case "jsonDataFormat": return target.getJsonDataFormat();
case "port": return target.getPort();
case "producerapidoc":
case "producerApiDoc": return target.getProducerApiDoc();
case "producercomponent":
case "producerComponent": return target.getProducerComponent();
case "scheme": return target.getScheme();
case "skipbindingonerrorcode":
case "skipBindingOnErrorCode": return target.isSkipBindingOnErrorCode();
case "usexforwardheaders":
case "useXForwardHeaders": return target.isUseXForwardHeaders();
case "validationlevels":
case "validationLevels": return target.getValidationLevels();
case "xmldataformat":
case "xmlDataFormat": return target.getXmlDataFormat();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiproperties":
case "apiProperties": return java.lang.Object.class;
case "componentproperties":
case "componentProperties": return java.lang.Object.class;
case "consumerproperties":
case "consumerProperties": return java.lang.Object.class;
case "corsheaders":
case "corsHeaders": return java.lang.String.class;
case "dataformatproperties":
case "dataFormatProperties": return java.lang.Object.class;
case "endpointproperties":
case "endpointProperties": return java.lang.Object.class;
case "validationlevels":
case "validationLevels": return java.lang.String.class;
default: return null;
}
}
}
| RestConfigurationPropertiesConfigurer |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/ClassUtils.java | {
"start": 13915,
"end": 14025
} | class ____
* one of its dependencies is not present or cannot be loaded.
* @param className the name of the | or |
java | elastic__elasticsearch | x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/config/ConfigTests.java | {
"start": 1548,
"end": 6688
} | class ____ extends ESTestCase {
public void testEmptyField() {
Exception e = expectThrows(IllegalArgumentException.class, () -> new MetricConfig(null, singletonList("max")));
assertThat(e.getMessage(), equalTo("Field must be a non-null, non-empty string"));
e = expectThrows(IllegalArgumentException.class, () -> new MetricConfig("", singletonList("max")));
assertThat(e.getMessage(), equalTo("Field must be a non-null, non-empty string"));
}
public void testEmptyMetrics() {
Exception e = expectThrows(IllegalArgumentException.class, () -> new MetricConfig("foo", emptyList()));
assertThat(e.getMessage(), equalTo("Metrics must be a non-null, non-empty array of strings"));
e = expectThrows(IllegalArgumentException.class, () -> new MetricConfig("foo", null));
assertThat(e.getMessage(), equalTo("Metrics must be a non-null, non-empty array of strings"));
}
public void testEmptyGroup() {
Exception e = expectThrows(IllegalArgumentException.class, () -> new GroupConfig(null, null, null));
assertThat(e.getMessage(), equalTo("Date histogram must not be null"));
}
public void testNoDateHisto() {
Exception e = expectThrows(
IllegalArgumentException.class,
() -> new GroupConfig(null, randomHistogramGroupConfig(random()), randomTermsGroupConfig(random()))
);
assertThat(e.getMessage(), equalTo("Date histogram must not be null"));
}
public void testEmptyDateHistoField() {
Exception e = expectThrows(IllegalArgumentException.class, () -> new CalendarInterval(null, DateHistogramInterval.HOUR));
assertThat(e.getMessage(), equalTo("Field must be a non-null, non-empty string"));
e = expectThrows(IllegalArgumentException.class, () -> new CalendarInterval("", DateHistogramInterval.HOUR));
assertThat(e.getMessage(), equalTo("Field must be a non-null, non-empty string"));
}
public void testEmptyDateHistoInterval() {
Exception e = expectThrows(IllegalArgumentException.class, () -> new CalendarInterval("foo", null));
assertThat(e.getMessage(), equalTo("Interval must be non-null"));
}
public void testNullTimeZone() {
DateHistogramGroupConfig config = new CalendarInterval("foo", DateHistogramInterval.HOUR, null, null);
assertThat(config.getTimeZone(), equalTo(ZoneId.of("UTC").getId()));
}
public void testEmptyTimeZone() {
DateHistogramGroupConfig config = new CalendarInterval("foo", DateHistogramInterval.HOUR, null, "");
assertThat(config.getTimeZone(), equalTo(ZoneId.of("UTC").getId()));
}
public void testDefaultTimeZone() {
DateHistogramGroupConfig config = new CalendarInterval("foo", DateHistogramInterval.HOUR);
assertThat(config.getTimeZone(), equalTo(ZoneId.of("UTC").getId()));
}
public void testUnkownTimeZone() {
Exception e = expectThrows(ZoneRulesException.class, () -> new CalendarInterval("foo", DateHistogramInterval.HOUR, null, "FOO"));
assertThat(e.getMessage(), equalTo("Unknown time-zone ID: FOO"));
}
public void testObsoleteTimeZone() {
DateHistogramGroupConfig config = new DateHistogramGroupConfig.FixedInterval(
"foo",
DateHistogramInterval.HOUR,
null,
"Canada/Mountain"
);
assertThat(config.getTimeZone(), equalTo("Canada/Mountain"));
}
public void testEmptyHistoField() {
Exception e = expectThrows(IllegalArgumentException.class, () -> new HistogramGroupConfig(1L, (String[]) null));
assertThat(e.getMessage(), equalTo("Fields must have at least one value"));
e = expectThrows(IllegalArgumentException.class, () -> new HistogramGroupConfig(1L, new String[0]));
assertThat(e.getMessage(), equalTo("Fields must have at least one value"));
}
public void testBadHistoIntervals() {
Exception e = expectThrows(IllegalArgumentException.class, () -> new HistogramGroupConfig(0L, "foo", "bar"));
assertThat(e.getMessage(), equalTo("Interval must be a positive long"));
e = expectThrows(IllegalArgumentException.class, () -> new HistogramGroupConfig(-1L, "foo", "bar"));
assertThat(e.getMessage(), equalTo("Interval must be a positive long"));
}
public void testEmptyTermsField() {
final String[] fields = randomBoolean() ? new String[0] : null;
Exception e = expectThrows(IllegalArgumentException.class, () -> new TermsGroupConfig(fields));
assertThat(e.getMessage(), equalTo("Fields must have at least one value"));
}
public void testNoHeadersInJSON() {
Map<String, String> headers = Maps.newMapWithExpectedSize(2);
headers.put("es-security-runas-user", "foo");
headers.put("_xpack_security_authentication", "bar");
RollupJob job = new RollupJob(randomRollupJobConfig(random()), headers);
String json = job.toString();
assertFalse(json.contains("authentication"));
assertFalse(json.contains("security"));
}
}
| ConfigTests |
java | apache__camel | components/camel-ibm/camel-ibm-cos/src/test/java/org/apache/camel/component/ibm/cos/IBMCOSComponentTest.java | {
"start": 1052,
"end": 1960
} | class ____ extends CamelTestSupport {
@Test
public void testComponentConfiguration() {
IBMCOSComponent component = context.getComponent("ibm-cos", IBMCOSComponent.class);
assertNotNull(component);
assertNotNull(component.getConfiguration());
}
@Test
public void testEndpointCreationRequiresCredentials() {
// Test that endpoint creation without credentials fails
ResolveEndpointFailedException exception = assertThrows(ResolveEndpointFailedException.class, () -> {
context.getEndpoint("ibm-cos:mybucket");
});
// The exception message should indicate credentials are required
String message = exception.getMessage();
assertTrue(message.contains("cosClient") || message.contains("apiKey"),
"Exception should mention credentials requirement, but was: " + message);
}
}
| IBMCOSComponentTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmLiteralNull.java | {
"start": 444,
"end": 1639
} | class ____<T> extends SqmLiteral<T> {
public SqmLiteralNull(NodeBuilder nodeBuilder) {
//noinspection unchecked
this( null, nodeBuilder );
}
public SqmLiteralNull(@Nullable SqmBindableType<T> expressibleType, NodeBuilder nodeBuilder) {
super( expressibleType, nodeBuilder );
}
@Override
public SqmLiteralNull<T> copy(SqmCopyContext context) {
final SqmLiteralNull<T> existing = context.getCopy( this );
if ( existing != null ) {
return existing;
}
final SqmLiteralNull<T> expression = context.registerCopy(
this,
new SqmLiteralNull<>(
getNodeType(),
nodeBuilder()
)
);
copyTo( expression, context );
return expression;
}
@Override
public String asLoggableText() {
return "<literal-null>";
}
@Override
public void appendHqlString(StringBuilder hql, SqmRenderContext context) {
hql.append( "null" );
}
@Override
public boolean equals(@Nullable Object object) {
return object instanceof SqmLiteralNull;
}
@Override
public int hashCode() {
return 1;
}
@Override
public boolean isCompatible(Object object) {
return equals( object );
}
@Override
public int cacheHashCode() {
return hashCode();
}
}
| SqmLiteralNull |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/TypeInferenceUtil.java | {
"start": 14928,
"end": 15881
} | class ____ {
private final List<DataType> expectedArgumentTypes;
private final LinkedHashMap<String, StateInfo> stateInfos;
private final DataType outputDataType;
public Result(
List<DataType> expectedArgumentTypes,
LinkedHashMap<String, StateInfo> stateInfos,
DataType outputDataType) {
this.expectedArgumentTypes = expectedArgumentTypes;
this.stateInfos = stateInfos;
this.outputDataType = outputDataType;
}
public List<DataType> getExpectedArgumentTypes() {
return expectedArgumentTypes;
}
public LinkedHashMap<String, StateInfo> getStateInfos() {
return stateInfos;
}
public DataType getOutputDataType() {
return outputDataType;
}
}
/** Result of running {@link StateTypeStrategy}. */
@Internal
public static final | Result |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelDoOnNextTry.java | {
"start": 1242,
"end": 2682
} | class ____<T> extends ParallelFlowable<T> {
final ParallelFlowable<T> source;
final Consumer<? super T> onNext;
final BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler;
public ParallelDoOnNextTry(ParallelFlowable<T> source, Consumer<? super T> onNext,
BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) {
this.source = source;
this.onNext = onNext;
this.errorHandler = errorHandler;
}
@Override
public void subscribe(Subscriber<? super T>[] subscribers) {
subscribers = RxJavaPlugins.onSubscribe(this, subscribers);
if (!validate(subscribers)) {
return;
}
int n = subscribers.length;
@SuppressWarnings("unchecked")
Subscriber<? super T>[] parents = new Subscriber[n];
for (int i = 0; i < n; i++) {
Subscriber<? super T> a = subscribers[i];
if (a instanceof ConditionalSubscriber) {
parents[i] = new ParallelDoOnNextConditionalSubscriber<>((ConditionalSubscriber<? super T>)a, onNext, errorHandler);
} else {
parents[i] = new ParallelDoOnNextSubscriber<>(a, onNext, errorHandler);
}
}
source.subscribe(parents);
}
@Override
public int parallelism() {
return source.parallelism();
}
static final | ParallelDoOnNextTry |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/PutPrivilegesRequest.java | {
"start": 1195,
"end": 5418
} | class ____ extends LegacyActionRequest
implements
ApplicationPrivilegesRequest,
WriteRequest<PutPrivilegesRequest> {
private List<ApplicationPrivilegeDescriptor> privileges;
private RefreshPolicy refreshPolicy = RefreshPolicy.IMMEDIATE;
public PutPrivilegesRequest(StreamInput in) throws IOException {
super(in);
privileges = in.readCollectionAsImmutableList(ApplicationPrivilegeDescriptor::new);
refreshPolicy = RefreshPolicy.readFrom(in);
}
public PutPrivilegesRequest() {
privileges = Collections.emptyList();
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (privileges.isEmpty()) {
validationException = addValidationError("At least one application privilege must be provided", validationException);
} else {
for (ApplicationPrivilegeDescriptor privilege : privileges) {
try {
ApplicationPrivilege.validateApplicationName(privilege.getApplication());
} catch (IllegalArgumentException e) {
validationException = addValidationError(e.getMessage(), validationException);
}
try {
ApplicationPrivilege.validatePrivilegeName(privilege.getName());
} catch (IllegalArgumentException e) {
validationException = addValidationError(e.getMessage(), validationException);
}
if (privilege.getActions().isEmpty()) {
validationException = addValidationError("Application privileges must have at least one action", validationException);
}
for (String action : privilege.getActions()) {
try {
ApplicationPrivilege.validateActionName(action);
} catch (IllegalArgumentException e) {
validationException = addValidationError(e.getMessage(), validationException);
}
}
if (MetadataUtils.containsReservedMetadata(privilege.getMetadata())) {
validationException = addValidationError(
"metadata keys may not start with ["
+ MetadataUtils.RESERVED_PREFIX
+ "] (in privilege "
+ privilege.getApplication()
+ ' '
+ privilege.getName()
+ ")",
validationException
);
}
}
}
return validationException;
}
/**
* Should this request trigger a refresh ({@linkplain RefreshPolicy#IMMEDIATE}, the default), wait for a refresh (
* {@linkplain RefreshPolicy#WAIT_UNTIL}), or proceed ignore refreshes entirely ({@linkplain RefreshPolicy#NONE}).
*/
@Override
public RefreshPolicy getRefreshPolicy() {
return refreshPolicy;
}
@Override
public PutPrivilegesRequest setRefreshPolicy(RefreshPolicy refreshPolicy) {
this.refreshPolicy = refreshPolicy;
return this;
}
public List<ApplicationPrivilegeDescriptor> getPrivileges() {
return privileges;
}
public void setPrivileges(Collection<ApplicationPrivilegeDescriptor> privileges) {
this.privileges = List.copyOf(privileges);
}
@Override
public Collection<String> getApplicationNames() {
return privileges.stream().map(ApplicationPrivilegeDescriptor::getApplication).collect(Collectors.toUnmodifiableSet());
}
@Override
public String toString() {
return getClass().getSimpleName()
+ "{["
+ privileges.stream().map(Strings::toString).collect(Collectors.joining(","))
+ "];"
+ refreshPolicy
+ "}";
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeCollection(privileges);
refreshPolicy.writeTo(out);
}
}
| PutPrivilegesRequest |
java | apache__maven | api/maven-api-cli/src/main/java/org/apache/maven/api/cli/ParserRequest.java | {
"start": 1761,
"end": 9273
} | interface ____ {
/**
* Returns the Maven command to be executed. This command is used in some invokers (ie forked) but also to
* present help to user.
*
* @return the command string
*/
@Nonnull
String command();
/**
* Returns the Maven command name (ie "Maven"). This string is used in some invokers to complete error messages.
*
* @return the command (human) name
*/
@Nonnull
String commandName();
/**
* Returns the logger to be used during the parsing process.
*
* @return the logger instance
*/
@Nonnull
Logger logger();
/**
* Returns the factory for creating message builders.
*
* @return the message builder factory
*/
@Nonnull
MessageBuilderFactory messageBuilderFactory();
/**
* Returns the command-line arguments to be parsed.
*
* @return a list of argument strings
*/
@Nonnull
List<String> args();
/**
* Per-request {@link Lookup} for customization.
*
* @return a lookup possibly with custom components
*/
@Nonnull
Lookup lookup();
/**
* Returns the current working directory for the Maven execution.
* If not explicitly set, this value will be detected during parsing.
*
* @return the current working directory path, or null if not set
*/
@Nullable
Path cwd();
/**
* Returns the Maven home directory.
* If not explicitly set, this value will be detected during parsing.
*
* @return the Maven home directory path, or null if not set
*/
@Nullable
Path mavenHome();
/**
* Returns the user's home directory.
* If not explicitly set, this value will be detected during parsing.
*
* @return the user's home directory path, or null if not set
*/
@Nullable
Path userHome();
/**
* Returns the input stream to be used for the Maven execution.
* If not set, {@link System#in} will be used by default.
*
* @return the input stream, or null if not set
*/
@Nullable
InputStream stdIn();
/**
* Returns the output stream to be used for the Maven execution.
* If not set, {@link System#out} will be used by default.
*
* @return the output stream, or null if not set
*/
@Nullable
OutputStream stdOut();
/**
* Returns the error stream to be used for the Maven execution.
* If not set, {@link System#err} will be used by default.
*
* @return the error stream, or null if not set
*/
@Nullable
OutputStream stdErr();
/**
* Returns {@code true} if this call happens in "embedded" mode, for example by another application that
* embeds Maven. When running in "embedded" mode, Maven will not try to grab system terminal and will use
* provided {@link #stdIn()} or {@link InputStream#nullInputStream()} as standard in stream.
*/
boolean embedded();
/**
* Creates a new Builder instance for constructing a Maven ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvn(@Nonnull String[] args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return mvn(Arrays.asList(args), messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a Maven ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvn(@Nonnull List<String> args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return builder(Tools.MVN_CMD, Tools.MVN_NAME, args, messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a Maven Encrypting Tool ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvnenc(@Nonnull String[] args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return mvnenc(Arrays.asList(args), messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a Maven Encrypting Tool ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvnenc(@Nonnull List<String> args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return builder(Tools.MVNENC_CMD, Tools.MVNENC_NAME, args, messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a Maven Shell Tool ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvnsh(@Nonnull String[] args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return mvnsh(Arrays.asList(args), messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a Maven Shell Tool ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvnsh(@Nonnull List<String> args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return builder(Tools.MVNSHELL_CMD, Tools.MVNSHELL_NAME, args, messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a Maven Upgrade Tool ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvnup(@Nonnull String[] args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return mvnup(Arrays.asList(args), messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a Maven Upgrade Tool ParserRequest.
*
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder mvnup(@Nonnull List<String> args, @Nonnull MessageBuilderFactory messageBuilderFactory) {
return builder(Tools.MVNUP_CMD, Tools.MVNUP_NAME, args, messageBuilderFactory);
}
/**
* Creates a new Builder instance for constructing a ParserRequest.
*
* @param command the Maven command to be executed
* @param commandName the Maven command Name to be executed
* @param args the command-line arguments
* @param messageBuilderFactory the factory for creating message builders
* @return a new Builder instance
*/
@Nonnull
static Builder builder(
@Nonnull String command,
@Nonnull String commandName,
@Nonnull List<String> args,
@Nonnull MessageBuilderFactory messageBuilderFactory) {
return new Builder(command, commandName, args, messageBuilderFactory);
}
| ParserRequest |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/NamespaceChange.java | {
"start": 2249,
"end": 2754
} | class ____ implements NamespaceChange {
private final String property;
private final String value;
private SetProperty(String property, String value) {
this.property = property;
this.value = value;
}
public String property() {
return property;
}
public String value() {
return value;
}
}
/**
* A NamespaceChange to remove a namespace property.
* <p>
* If the property does not exist, the change should succeed.
*/
final | SetProperty |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/records/TaskAttemptCompletionEventStatus.java | {
"start": 868,
"end": 967
} | enum ____ {
FAILED,
KILLED,
SUCCEEDED,
OBSOLETE,
TIPFAILED
}
| TaskAttemptCompletionEventStatus |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/generated/GeneratedJoinCondition.java | {
"start": 1079,
"end": 1466
} | class ____ extends GeneratedClass<JoinCondition> {
private static final long serialVersionUID = 2L;
@VisibleForTesting
public GeneratedJoinCondition(String className, String code, Object[] references) {
super(className, code, references, new Configuration());
}
/**
* Creates a GeneratedJoinCondition.
*
* @param className | GeneratedJoinCondition |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/merge/PropertyMergeTest.java | {
"start": 1659,
"end": 1810
} | class ____ extends AtomicReference<String> {
public StringReference(String str) {
set(str);
}
}
static | StringReference |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableScalarXMap.java | {
"start": 6147,
"end": 8140
} | class ____<T>
extends AtomicInteger
implements QueueDisposable<T>, Runnable {
private static final long serialVersionUID = 3880992722410194083L;
final Observer<? super T> observer;
final T value;
static final int START = 0;
static final int FUSED = 1;
static final int ON_NEXT = 2;
static final int ON_COMPLETE = 3;
public ScalarDisposable(Observer<? super T> observer, T value) {
this.observer = observer;
this.value = value;
}
@Override
public boolean offer(T value) {
throw new UnsupportedOperationException("Should not be called!");
}
@Override
public boolean offer(T v1, T v2) {
throw new UnsupportedOperationException("Should not be called!");
}
@Nullable
@Override
public T poll() {
if (get() == FUSED) {
lazySet(ON_COMPLETE);
return value;
}
return null;
}
@Override
public boolean isEmpty() {
return get() != FUSED;
}
@Override
public void clear() {
lazySet(ON_COMPLETE);
}
@Override
public void dispose() {
set(ON_COMPLETE);
}
@Override
public boolean isDisposed() {
return get() == ON_COMPLETE;
}
@Override
public int requestFusion(int mode) {
if ((mode & SYNC) != 0) {
lazySet(FUSED);
return SYNC;
}
return NONE;
}
@Override
public void run() {
if (get() == START && compareAndSet(START, ON_NEXT)) {
observer.onNext(value);
if (get() == ON_NEXT) {
lazySet(ON_COMPLETE);
observer.onComplete();
}
}
}
}
}
| ScalarDisposable |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/IdGeneratorTypeWithBeanContainerTest.java | {
"start": 1581,
"end": 1650
} | class ____ {
@Id @SimpleId
long id;
String data;
}
}
| SimpleEntity |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/WeatherComponentBuilderFactory.java | {
"start": 1381,
"end": 1841
} | interface ____ {
/**
* Weather (camel-weather)
* Poll the weather information from Open Weather Map.
*
* Category: api
* Since: 2.12
* Maven coordinates: org.apache.camel:camel-weather
*
* @return the dsl builder
*/
static WeatherComponentBuilder weather() {
return new WeatherComponentBuilderImpl();
}
/**
* Builder for the Weather component.
*/
| WeatherComponentBuilderFactory |
java | grpc__grpc-java | services/src/main/java/io/grpc/services/MetricRecorderHelper.java | {
"start": 779,
"end": 1770
} | class ____ {
/**
* Return true if the utilization value is in the range [0, 1] and false otherwise.
*/
static boolean isUtilizationValid(double utilization) {
return utilization >= 0.0 && utilization <= 1.0;
}
/**
* Return true if the cpu utilization or application specific utilization value is in the range
* [0, inf) and false otherwise. Occasionally users have over 100% cpu utilization and get a
* runaway effect where the backend with highest qps gets more and more qps sent to it. So we
* allow cpu utilization > 1.0, similarly for application specific utilization.
*/
static boolean isCpuOrApplicationUtilizationValid(double utilization) {
return utilization >= 0.0;
}
/**
* Return true if a rate value (such as qps or eps) is in the range [0, inf) and false otherwise.
*/
static boolean isRateValid(double rate) {
return rate >= 0.0;
}
// Prevent instantiation.
private MetricRecorderHelper() {
}
}
| MetricRecorderHelper |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/BeanParamSuperClass.java | {
"start": 336,
"end": 2760
} | class ____ {
@QueryParam("query")
String query;
@QueryParam("query")
private String privateQuery;
@QueryParam("query")
protected String protectedQuery;
@QueryParam("query")
public String publicQuery;
@HeaderParam("header")
String header;
@Context
UriInfo uriInfo;
@BeanParam
OtherBeanParam otherBeanParam;
@QueryParam("queryList")
List<String> queryList;
@QueryParam("query")
ParameterWithFromString parameterWithFromString;
@QueryParam("missing")
String missing;
@DefaultValue("there")
@QueryParam("missing")
String missingWithDefaultValue;
@QueryParam("missing")
ParameterWithFromString missingParameterWithFromString;
@DefaultValue("there")
@QueryParam("missing")
ParameterWithFromString missingParameterWithFromStringAndDefaultValue;
@QueryParam("int")
int primitiveParam;
@QueryParam("missing")
int missingPrimitiveParam;
@DefaultValue("42")
@QueryParam("missing")
int missingPrimitiveParamWithDefaultValue;
public void check(String path) {
Assertions.assertEquals("one-query", query);
Assertions.assertEquals("one-query", privateQuery);
Assertions.assertEquals("one-query", protectedQuery);
Assertions.assertEquals("one-query", publicQuery);
Assertions.assertEquals("one-header", header);
Assertions.assertNotNull(uriInfo);
Assertions.assertEquals(path, uriInfo.getPath());
Assertions.assertNotNull(otherBeanParam);
otherBeanParam.check(path);
Assertions.assertNotNull(queryList);
Assertions.assertEquals("one", queryList.get(0));
Assertions.assertEquals("two", queryList.get(1));
Assertions.assertNotNull(parameterWithFromString);
Assertions.assertEquals("ParameterWithFromString[val=one-query]", parameterWithFromString.toString());
Assertions.assertNull(missing);
Assertions.assertEquals("there", missingWithDefaultValue);
Assertions.assertNull(missingParameterWithFromString);
Assertions.assertEquals("ParameterWithFromString[val=there]", missingParameterWithFromStringAndDefaultValue.toString());
Assertions.assertEquals(666, primitiveParam);
Assertions.assertEquals(0, missingPrimitiveParam);
Assertions.assertEquals(42, missingPrimitiveParamWithDefaultValue);
}
}
| BeanParamSuperClass |
java | apache__camel | catalog/camel-report-maven-plugin/src/main/java/org/apache/camel/maven/htmlxlsx/model/CamelContextRouteCoverage.java | {
"start": 858,
"end": 1994
} | class ____ {
private String id;
private int exchangesTotal;
private int totalProcessingTime;
private Routes routes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getExchangesTotal() {
return exchangesTotal;
}
public void setExchangesTotal(int exchangesTotal) {
this.exchangesTotal = exchangesTotal;
}
public int getTotalProcessingTime() {
return totalProcessingTime;
}
public void setTotalProcessingTime(int totalProcessingTime) {
this.totalProcessingTime = totalProcessingTime;
}
public Routes getRoutes() {
return routes;
}
public void setRoutes(Routes routes) {
this.routes = routes;
}
@Override
public String toString() {
return "CamelContextRouteCoverage{" +
"id='" + id + '\'' +
", exchangesTotal=" + exchangesTotal +
", totalProcessingTime=" + totalProcessingTime +
", routes=" + routes +
'}';
}
}
| CamelContextRouteCoverage |
java | netty__netty | handler/src/test/java/io/netty/handler/ssl/OpenSslCertificateExceptionTest.java | {
"start": 1011,
"end": 2033
} | class ____ {
@BeforeAll
public static void ensureOpenSsl() {
OpenSsl.ensureAvailability();
}
@Test
public void testValidErrorCode() throws Exception {
Field[] fields = CertificateVerifier.class.getFields();
for (Field field : fields) {
if (field.isAccessible()) {
int errorCode = field.getInt(null);
OpenSslCertificateException exception = new OpenSslCertificateException(errorCode);
assertEquals(errorCode, exception.errorCode());
}
}
}
@Test
public void testNonValidErrorCode() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
new OpenSslCertificateException(Integer.MIN_VALUE);
}
});
}
@Test
public void testCanBeInstancedWhenOpenSslIsNotAvailable() {
new OpenSslCertificateException(0);
}
}
| OpenSslCertificateExceptionTest |
java | spring-projects__spring-boot | buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/GitHubRepository.java | {
"start": 830,
"end": 1849
} | interface ____ {
/**
* Opens a new issue with the given title. The given {@code labels} will be applied to
* the issue and it will be assigned to the given {@code milestone}.
* @param title the title of the issue
* @param body the body of the issue
* @param labels the labels to apply to the issue
* @param milestone the milestone to assign the issue to
* @return the number of the new issue
*/
int openIssue(String title, String body, List<String> labels, Milestone milestone);
/**
* Returns the labels in the repository.
* @return the labels
*/
Set<String> getLabels();
/**
* Returns the milestones in the repository.
* @return the milestones
*/
List<Milestone> getMilestones();
/**
* Finds issues that have the given {@code labels} and are assigned to the given
* {@code milestone}.
* @param labels issue labels
* @param milestone assigned milestone
* @return the matching issues
*/
List<Issue> findIssues(List<String> labels, Milestone milestone);
}
| GitHubRepository |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/features/ResetFeatureStateResponse.java | {
"start": 4036,
"end": 8369
} | enum ____ {
SUCCESS,
FAILURE
}
/**
* Create a feature status for a successful reset operation
* @param featureName Name of the feature whose state was successfully reset
* @return Success status for a feature
*/
public static ResetFeatureStateStatus success(String featureName) {
return new ResetFeatureStateStatus(featureName, Status.SUCCESS, null);
}
/**
* Create a feature status for a failed reset operation
* @param featureName Name of the feature that failed
* @param exception The exception that caused or described the failure
* @return Failure status for a feature
*/
public static ResetFeatureStateStatus failure(String featureName, Exception exception) {
return new ResetFeatureStateStatus(featureName, Status.FAILURE, exception);
}
private ResetFeatureStateStatus(String featureName, Status status, @Nullable Exception exception) {
this.featureName = featureName;
this.status = status;
assert Status.FAILURE.equals(status) ? Objects.nonNull(exception) : Objects.isNull(exception);
this.exception = exception;
}
ResetFeatureStateStatus(StreamInput in) throws IOException {
this.featureName = in.readString();
this.status = Status.valueOf(in.readString());
this.exception = in.readBoolean() ? in.readException() : null;
}
/**
* @return Name of the feature we tried to reset
*/
public String getFeatureName() {
return this.featureName;
}
/**
* @return Success or failure for the reset operation
*/
public Status getStatus() {
return this.status;
}
/**
* @return For a failed reset operation, the exception that caused or describes the failure.
*/
@Nullable
public Exception getException() {
return this.exception;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("feature_name", this.featureName);
builder.field("status", this.status);
if (Objects.nonNull(this.exception)) {
builder.field("exception");
builder.startObject();
new ElasticsearchException(exception).toXContent(builder, params);
builder.endObject();
}
builder.endObject();
return builder;
}
/**
* Without a convenient way to compare Exception equality, we consider
* only feature name and success or failure for equality.
* @param o An object to compare for equality
* @return True if the feature name and status are equal, false otherwise
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResetFeatureStateStatus that = (ResetFeatureStateStatus) o;
return Objects.equals(featureName, that.featureName) && status == that.status;
}
/**
* @return Hash code based only on feature name and status.
*/
@Override
public int hashCode() {
return Objects.hash(featureName, status);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(this.featureName);
out.writeString(this.status.toString());
if (exception != null) {
out.writeBoolean(true);
out.writeException(exception);
} else {
out.writeBoolean(false);
}
}
@Override
public String toString() {
return "ResetFeatureStateStatus{"
+ "featureName='"
+ featureName
+ '\''
+ ", status="
+ status
+ ", exception='"
+ exception
+ '\''
+ '}';
}
}
}
| Status |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/enums/EnumAltIdTest.java | {
"start": 3258,
"end": 3434
} | class ____ {
@JsonFormat(without = JsonFormat.Feature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
public Types type;
}
static | SpeedWithoutDefaultOverride |
java | apache__camel | components/camel-coap/src/main/java/org/apache/camel/coap/CoAPConstants.java | {
"start": 951,
"end": 2347
} | interface ____ {
/**
* Supported request methods
*/
String METHOD_DELETE = "DELETE";
String METHOD_GET = "GET";
String METHOD_PING = "PING";
String METHOD_POST = "POST";
String METHOD_PUT = "PUT";
/**
* Supported CoAP server methods
*/
String METHOD_RESTRICT_ALL = String.format("%s,%s,%s,%s", METHOD_DELETE, METHOD_GET, METHOD_POST, METHOD_PUT);
/**
* CoAP exchange header names
*/
@Metadata(description = "The CoAP ETag for the response.", javaType = "byte[]")
String COAP_ETAG = "CamelCoapETag";
@Metadata(description = "The CoAP Max-Age for the response body.", javaType = "java.lang.Long")
String COAP_MAX_AGE = "CamelCoapMaxAge";
@Metadata(description = "The request method that the CoAP producer should use when calling the target CoAP\n" +
"server URI. Valid options are DELETE, GET, PING, POST & PUT.",
javaType = "String")
String COAP_METHOD = "CamelCoapMethod";
@Metadata(description = "The CoAP response code sent by the external server. See RFC 7252 for details\n" +
"of what each code means.",
javaType = "String")
String COAP_RESPONSE_CODE = "CamelCoapResponseCode";
@Metadata(description = "The content type", javaType = "String")
String CONTENT_TYPE = Exchange.CONTENT_TYPE;
}
| CoAPConstants |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java | {
"start": 3024,
"end": 3593
} | interface ____ extends Lifecycle, ApplicationContext {
String[] getConfigLocations();
}
// TODO improve GenericWebApplicationContext test scenario
@Test
void testGenericWebApplicationContext() {
GenericWebApplicationContext context = mock(GenericWebApplicationContext.class);
given(context.isRunning()).willReturn(true);
SpringStatusChecker checker = new SpringStatusChecker(context);
Status status = checker.check();
Assertions.assertEquals(Status.Level.OK, status.getLevel());
}
}
| ApplicationLifeCycle |
java | apache__kafka | metadata/src/test/java/org/apache/kafka/image/MetadataImageTest.java | {
"start": 1349,
"end": 6511
} | class ____ {
public static final MetadataImage IMAGE1;
public static final MetadataDelta DELTA1;
public static final MetadataImage IMAGE2;
static {
IMAGE1 = new MetadataImage(
new MetadataProvenance(100, 4, 2000, true),
FeaturesImageTest.IMAGE1,
ClusterImageTest.IMAGE1,
TopicsImageTest.IMAGE1,
ConfigurationsImageTest.IMAGE1,
ClientQuotasImageTest.IMAGE1,
ProducerIdsImageTest.IMAGE1,
AclsImageTest.IMAGE1,
ScramImageTest.IMAGE1,
DelegationTokenImageTest.IMAGE1);
DELTA1 = new MetadataDelta.Builder().
setImage(IMAGE1).
build();
RecordTestUtils.replayAll(DELTA1, FeaturesImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, ClusterImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, TopicsImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, ConfigurationsImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, ClientQuotasImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, ProducerIdsImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, AclsImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, ScramImageTest.DELTA1_RECORDS);
RecordTestUtils.replayAll(DELTA1, DelegationTokenImageTest.DELTA1_RECORDS);
IMAGE2 = new MetadataImage(
new MetadataProvenance(200, 5, 4000, true),
FeaturesImageTest.IMAGE2,
ClusterImageTest.IMAGE2,
TopicsImageTest.IMAGE2,
ConfigurationsImageTest.IMAGE2,
ClientQuotasImageTest.IMAGE2,
ProducerIdsImageTest.IMAGE2,
AclsImageTest.IMAGE2,
ScramImageTest.IMAGE2,
DelegationTokenImageTest.IMAGE2);
}
@Test
public void testEmptyImageRoundTrip() {
var image = MetadataImage.EMPTY;
var metadataVersion = MetadataVersion.MINIMUM_VERSION;
ImageWriterOptions options = new ImageWriterOptions.Builder(metadataVersion).build();
// A metadata version is required for writing, so the expected image is not actually empty
var expectedImage = new MetadataImage(
MetadataProvenance.EMPTY,
new FeaturesImage(Map.of(), metadataVersion),
ClusterImage.EMPTY,
TopicsImage.EMPTY,
ConfigurationsImage.EMPTY,
ClientQuotasImage.EMPTY,
ProducerIdsImage.EMPTY,
AclsImage.EMPTY,
ScramImage.EMPTY,
DelegationTokenImage.EMPTY);
testToImage(expectedImage, getImageRecords(image, options));
}
@Test
public void testImage1RoundTrip() {
testToImage(IMAGE1);
}
@Test
public void testApplyDelta1() {
assertEquals(IMAGE2, DELTA1.apply(IMAGE2.provenance()));
// check image1 + delta1 = image2, since records for image1 + delta1 might differ from records from image2
ImageWriterOptions options = new ImageWriterOptions.Builder(IMAGE1.features().metadataVersionOrThrow()).build();
List<ApiMessageAndVersion> records = getImageRecords(IMAGE1, options);
records.addAll(FeaturesImageTest.DELTA1_RECORDS);
records.addAll(ClusterImageTest.DELTA1_RECORDS);
records.addAll(TopicsImageTest.DELTA1_RECORDS);
records.addAll(ConfigurationsImageTest.DELTA1_RECORDS);
records.addAll(ClientQuotasImageTest.DELTA1_RECORDS);
records.addAll(ProducerIdsImageTest.DELTA1_RECORDS);
records.addAll(AclsImageTest.DELTA1_RECORDS);
records.addAll(ScramImageTest.DELTA1_RECORDS);
records.addAll(DelegationTokenImageTest.DELTA1_RECORDS);
testToImage(IMAGE2, records);
}
@Test
public void testImage2RoundTrip() {
testToImage(IMAGE2);
}
private static void testToImage(MetadataImage image) {
testToImage(image, new ImageWriterOptions.Builder(image.features().metadataVersionOrThrow()).build(), Optional.empty());
}
static void testToImage(MetadataImage image, ImageWriterOptions options, Optional<List<ApiMessageAndVersion>> fromRecords) {
testToImage(image, fromRecords.orElseGet(() -> getImageRecords(image, options)));
}
private static void testToImage(MetadataImage image, List<ApiMessageAndVersion> fromRecords) {
// test from empty image stopping each of the various intermediate images along the way
new RecordTestUtils.TestThroughAllIntermediateImagesLeadingToFinalImageHelper<>(
() -> MetadataImage.EMPTY,
MetadataDelta::new
) {
@Override
public MetadataImage createImageByApplyingDelta(MetadataDelta delta) {
return delta.apply(image.provenance());
}
}.test(image, fromRecords);
}
private static List<ApiMessageAndVersion> getImageRecords(MetadataImage image, ImageWriterOptions options) {
RecordListWriter writer = new RecordListWriter();
image.write(writer, options);
return writer.records();
}
}
| MetadataImageTest |
java | apache__camel | components/camel-spring-parent/camel-spring-main/src/test/java/org/apache/camel/spring/MyHelloBean.java | {
"start": 905,
"end": 1013
} | class ____ {
@Override
public String toString() {
return "I am hello bean";
}
}
| MyHelloBean |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/convert/support/StringToCharacterConverter.java | {
"start": 874,
"end": 1301
} | class ____ implements Converter<String, Character> {
@Override
public @Nullable Character convert(String source) {
if (source.isEmpty()) {
return null;
}
if (source.length() > 1) {
throw new IllegalArgumentException(
"Can only convert a [String] with length of 1 to a [Character]; string value '" + source + "' has length of " + source.length());
}
return source.charAt(0);
}
}
| StringToCharacterConverter |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/naming/TestEmbeddable.java | {
"start": 260,
"end": 553
} | class ____ {
String value1;
String value2;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
}
| TestEmbeddable |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/core/Observable.java | {
"start": 578403,
"end": 580416
} | class ____ to send a Disposable to the downstream.
* // Note that relaying the upstream's Disposable directly is not allowed in RxJava
* @Override
* public void onSubscribe(Disposable d) {
* if (upstream != null) {
* d.dispose();
* } else {
* upstream = d;
* downstream.onSubscribe(this);
* }
* }
*
* // The upstream calls this with the next item and the implementation's
* // responsibility is to emit an item to the downstream based on the intended
* // business logic, or if it can't do so for the particular item,
* // request more from the upstream
* @Override
* public void onNext(T item) {
* String str = item.toString();
* if (str.length() < 2) {
* downstream.onNext(str);
* }
* // Observable doesn't support backpressure, therefore, there is no
* // need or opportunity to call upstream.request(1) if an item
* // is not produced to the downstream
* }
*
* // Some operators may handle the upstream's error while others
* // could just forward it to the downstream.
* @Override
* public void onError(Throwable throwable) {
* downstream.onError(throwable);
* }
*
* // When the upstream completes, usually the downstream should complete as well.
* @Override
* public void onComplete() {
* downstream.onComplete();
* }
*
* // Some operators may use their own resources which should be cleaned up if
* // the downstream disposes the flow before it completed. Operators without
* // resources can simply forward the dispose to the upstream.
* // In some cases, a disposed flag may be set by this method so that other parts
* // of this | has |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java | {
"start": 54882,
"end": 57094
} | enum ____ implements FetchState {
INITIALIZING() {
@Override
public Collection<FetchState> validTransitions() {
return Arrays.asList(FetchStates.FETCHING, FetchStates.AWAIT_RESET, FetchStates.AWAIT_VALIDATION);
}
@Override
public boolean requiresPosition() {
return false;
}
@Override
public boolean hasValidPosition() {
return false;
}
},
FETCHING() {
@Override
public Collection<FetchState> validTransitions() {
return Arrays.asList(FetchStates.FETCHING, FetchStates.AWAIT_RESET, FetchStates.AWAIT_VALIDATION);
}
@Override
public boolean requiresPosition() {
return true;
}
@Override
public boolean hasValidPosition() {
return true;
}
},
AWAIT_RESET() {
@Override
public Collection<FetchState> validTransitions() {
return Arrays.asList(FetchStates.FETCHING, FetchStates.AWAIT_RESET);
}
@Override
public boolean requiresPosition() {
return false;
}
@Override
public boolean hasValidPosition() {
return false;
}
},
AWAIT_VALIDATION() {
@Override
public Collection<FetchState> validTransitions() {
return Arrays.asList(FetchStates.FETCHING, FetchStates.AWAIT_RESET, FetchStates.AWAIT_VALIDATION);
}
@Override
public boolean requiresPosition() {
return true;
}
@Override
public boolean hasValidPosition() {
return false;
}
}
}
/**
* Represents the position of a partition subscription.
*
* This includes the offset and epoch from the last record in
* the batch from a FetchResponse. It also includes the leader epoch at the time the batch was consumed.
*/
public static | FetchStates |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java | {
"start": 15431,
"end": 15607
} | interface ____ extends Suppressible {
Description matchDeconstructionPattern(DeconstructionPatternTree tree, VisitorState state);
}
public | DeconstructionPatternTreeMatcher |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java | {
"start": 14373,
"end": 14501
} | interface ____ extends Suppressible {
Description matchCatch(CatchTree tree, VisitorState state);
}
public | CatchTreeMatcher |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java | {
"start": 1124,
"end": 1725
} | class ____ implements Stream {
protected Executor executor;
protected final FrameworkModel frameworkModel;
private static final boolean HAS_PROTOBUF = ClassUtils.hasProtobuf();
public AbstractStream(Executor executor, FrameworkModel frameworkModel) {
this.executor = new SerializingExecutor(executor);
this.frameworkModel = frameworkModel;
}
public void setExecutor(Executor executor) {
this.executor = new SerializingExecutor(executor);
}
public static boolean getGrpcStatusDetailEnabled() {
return HAS_PROTOBUF;
}
}
| AbstractStream |
java | quarkusio__quarkus | extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigMappingTest.java | {
"start": 4065,
"end": 4134
} | interface ____ {
String host();
}
| ServerHost |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/listener/ListSetListener.java | {
"start": 905,
"end": 1103
} | interface ____ extends ObjectListener {
/**
* Invoked on event of setting element to list
*
* @param name - name of object
*/
void onListSet(String name);
}
| ListSetListener |
java | google__gson | gson/src/main/java/com/google/gson/annotations/JsonAdapter.java | {
"start": 2482,
"end": 2913
} | class ____ {
* @JsonAdapter(UserJsonAdapter.class)
* final User user;
*
* Gadget(User user) {
* this.user = user;
* }
* }
* </pre>
*
* It's possible to specify different type adapters on a field, that field's type, and in the {@link
* GsonBuilder}. Field annotations take precedence over {@code GsonBuilder}-registered type
* adapters, which in turn take precedence over annotated types.
*
* <p>The | Gadget |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fix/BindySimpleKeyValuePairUnicodeNextLineTest.java | {
"start": 1537,
"end": 2424
} | class ____ {
private static final String URI_MOCK_RESULT = "mock:result";
private static final String URI_DIRECT_START = "direct:start";
@Produce(URI_DIRECT_START)
private ProducerTemplate template;
@EndpointInject(URI_MOCK_RESULT)
private MockEndpoint result;
@Test
public void testUnmarshallMessage() throws Exception {
String sent = "8=FIX.4.1 37=1 38=1 40=\u0085butter";
result.expectedMessageCount(1);
template.sendBody(sent);
result.assertIsSatisfied();
UnicodeFixOrder unicodeFixOrder = result.getReceivedExchanges().get(0).getIn().getBody(UnicodeFixOrder.class);
assertEquals("1", unicodeFixOrder.getId());
assertEquals("butter", unicodeFixOrder.getProduct());
assertEquals("1", unicodeFixOrder.getQuantity());
}
public static | BindySimpleKeyValuePairUnicodeNextLineTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/profile/aggregation/AggregationProfileBreakdown.java | {
"start": 788,
"end": 1442
} | class ____ extends AbstractProfileBreakdown<AggregationTimingType> {
private final Map<String, Object> extra = new HashMap<>();
public AggregationProfileBreakdown() {
super(AggregationTimingType.class);
}
/**
* Add extra debugging information about the aggregation.
*/
public void addDebugInfo(String key, Object value) {
Object old = extra.put(key, value);
assert old == null : "debug info duplicate key [" + key + "] was [" + old + "] is [" + value + "]";
}
@Override
protected Map<String, Object> toDebugMap() {
return unmodifiableMap(extra);
}
}
| AggregationProfileBreakdown |
java | apache__kafka | generator/src/main/java/org/apache/kafka/message/EntityType.java | {
"start": 897,
"end": 2140
} | enum ____ {
@JsonProperty("unknown")
UNKNOWN(null),
@JsonProperty("transactionalId")
TRANSACTIONAL_ID(FieldType.StringFieldType.INSTANCE),
@JsonProperty("producerId")
PRODUCER_ID(FieldType.Int64FieldType.INSTANCE),
@JsonProperty("groupId")
GROUP_ID(FieldType.StringFieldType.INSTANCE),
@JsonProperty("topicName")
TOPIC_NAME(FieldType.StringFieldType.INSTANCE),
@JsonProperty("brokerId")
BROKER_ID(FieldType.Int32FieldType.INSTANCE);
private final FieldType baseType;
EntityType(FieldType baseType) {
this.baseType = baseType;
}
public void verifyTypeMatches(String fieldName, FieldType type) {
if (this == UNKNOWN) {
return;
}
if (type instanceof FieldType.ArrayType) {
FieldType.ArrayType arrayType = (FieldType.ArrayType) type;
verifyTypeMatches(fieldName, arrayType.elementType());
} else {
if (!type.toString().equals(baseType.toString())) {
throw new RuntimeException("Field " + fieldName + " has entity type " +
name() + ", but field type " + type + ", which does " +
"not match.");
}
}
}
}
| EntityType |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/spi/NotInstrumentedException.java | {
"start": 341,
"end": 595
} | class ____ extends HibernateException {
/**
* Constructs a NotInstrumentedException
*
* @param message Message explaining the exception condition
*/
public NotInstrumentedException(String message) {
super( message );
}
}
| NotInstrumentedException |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/plain/LeafGeoPointFieldData.java | {
"start": 901,
"end": 1689
} | class ____ extends LeafPointFieldData<MultiGeoPointValues> {
protected final ToScriptFieldFactory<MultiGeoPointValues> toScriptFieldFactory;
public LeafGeoPointFieldData(ToScriptFieldFactory<MultiGeoPointValues> toScriptFieldFactory) {
this.toScriptFieldFactory = toScriptFieldFactory;
}
@Override
public final MultiGeoPointValues getPointValues() {
return new MultiGeoPointValues(getSortedNumericLongValues());
}
@Override
public final SortedBinaryDocValues getBytesValues() {
return FieldData.toString(getPointValues());
}
@Override
public DocValuesScriptFieldFactory getScriptFieldFactory(String name) {
return toScriptFieldFactory.getScriptFieldFactory(getPointValues(), name);
}
}
| LeafGeoPointFieldData |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean.java | {
"start": 7666,
"end": 8173
} | class ____ {
private int id;
protected String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
protected String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
public ClassLoader getClassLoader() {
return Entity.class.getClassLoader();
}
}
private static | Entity |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableMergeWithCompletableTest.java | {
"start": 1056,
"end": 5404
} | class ____ extends RxJavaTest {
@Test
public void normal() {
final TestObserver<Integer> to = new TestObserver<>();
Observable.range(1, 5).mergeWith(
Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
to.onNext(100);
}
})
)
.subscribe(to);
to.assertResult(1, 2, 3, 4, 5, 100);
}
@Test
public void take() {
final TestObserver<Integer> to = new TestObserver<>();
Observable.range(1, 5).mergeWith(
Completable.complete()
)
.take(3)
.subscribe(to);
to.assertResult(1, 2, 3);
}
@Test
public void cancel() {
final PublishSubject<Integer> ps = PublishSubject.create();
final CompletableSubject cs = CompletableSubject.create();
TestObserver<Integer> to = ps.mergeWith(cs).test();
assertTrue(ps.hasObservers());
assertTrue(cs.hasObservers());
to.dispose();
assertFalse(ps.hasObservers());
assertFalse(cs.hasObservers());
}
@Test
public void mainError() {
Observable.error(new TestException())
.mergeWith(Completable.complete())
.test()
.assertFailure(TestException.class);
}
@Test
public void otherError() {
Observable.never()
.mergeWith(Completable.error(new TestException()))
.test()
.assertFailure(TestException.class);
}
@Test
public void completeRace() {
for (int i = 0; i < 1000; i++) {
final PublishSubject<Integer> ps = PublishSubject.create();
final CompletableSubject cs = CompletableSubject.create();
TestObserver<Integer> to = ps.mergeWith(cs).test();
Runnable r1 = new Runnable() {
@Override
public void run() {
ps.onNext(1);
ps.onComplete();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
cs.onComplete();
}
};
TestHelper.race(r1, r2);
to.assertResult(1);
}
}
@Test
public void isDisposed() {
new Observable<Integer>() {
@Override
protected void subscribeActual(Observer<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
assertFalse(((Disposable)observer).isDisposed());
observer.onNext(1);
assertTrue(((Disposable)observer).isDisposed());
}
}.mergeWith(Completable.complete())
.take(1)
.test()
.assertResult(1);
}
@Test
public void cancelOtherOnMainError() {
PublishSubject<Integer> ps = PublishSubject.create();
CompletableSubject cs = CompletableSubject.create();
TestObserver<Integer> to = ps.mergeWith(cs).test();
assertTrue(ps.hasObservers());
assertTrue(cs.hasObservers());
ps.onError(new TestException());
to.assertFailure(TestException.class);
assertFalse("main has observers!", ps.hasObservers());
assertFalse("other has observers", cs.hasObservers());
}
@Test
public void cancelMainOnOtherError() {
PublishSubject<Integer> ps = PublishSubject.create();
CompletableSubject cs = CompletableSubject.create();
TestObserver<Integer> to = ps.mergeWith(cs).test();
assertTrue(ps.hasObservers());
assertTrue(cs.hasObservers());
cs.onError(new TestException());
to.assertFailure(TestException.class);
assertFalse("main has observers!", ps.hasObservers());
assertFalse("other has observers", cs.hasObservers());
}
@Test
public void undeliverableUponCancel() {
TestHelper.checkUndeliverableUponCancel(new ObservableConverter<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Observable<Integer> upstream) {
return upstream.mergeWith(Completable.complete().hide());
}
});
}
}
| ObservableMergeWithCompletableTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/XmlSignerEndpointBuilderFactory.java | {
"start": 13509,
"end": 14429
} | class ____ which reads the private key
* from a Java keystore.
*
* The option is a:
* <code>org.apache.camel.component.xmlsecurity.api.KeyAccessor</code>
* type.
*
* Group: producer
*
* @param keyAccessor the value to set
* @return the dsl builder
*/
default XmlSignerEndpointBuilder keyAccessor(org.apache.camel.component.xmlsecurity.api.KeyAccessor keyAccessor) {
doSetProperty("keyAccessor", keyAccessor);
return this;
}
/**
* For the signing process, a private key is necessary. You specify a
* key accessor bean which provides this private key. The key accessor
* bean must implement the KeyAccessor interface. The package
* org.apache.camel.component.xmlsecurity.api contains the default
* implementation | DefaultKeyAccessor |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/indices/IndicesExpressionGrouper.java | {
"start": 1075,
"end": 1353
} | interface ____ {
/**
* See {@link org.elasticsearch.transport.RemoteClusterService#groupIndices} for details
*/
Map<String, OriginalIndices> groupIndices(IndicesOptions indicesOptions, String[] indexExpressions, boolean returnLocalAll);
}
| IndicesExpressionGrouper |
java | elastic__elasticsearch | libs/entitlement/qa/src/javaRestTest/java/org/elasticsearch/entitlement/qa/EntitlementsAllowedViaOverrideIT.java | {
"start": 1070,
"end": 2398
} | class ____ extends AbstractEntitlementsIT {
private static Map<String, String> createPolicyOverrideSystemProperty(Path tempDir) {
String policyOverride = Strings.format("""
policy:
%s:
- load_native_libraries
- files:
- path: %s
mode: read
""", ENTITLEMENT_QA_TEST_MODULE_NAME, tempDir.resolve("read_dir"));
var encodedPolicyOverride = new String(Base64.getEncoder().encode(policyOverride.getBytes(StandardCharsets.UTF_8)));
return Map.of("es.entitlements.policy." + ENTITLEMENT_TEST_PLUGIN_NAME, encodedPolicyOverride);
}
@ClassRule
public static EntitlementsTestRule testRule = new EntitlementsTestRule(
true,
null,
EntitlementsAllowedViaOverrideIT::createPolicyOverrideSystemProperty
);
public EntitlementsAllowedViaOverrideIT(@Name("actionName") String actionName) {
super(actionName, true);
}
@ParametersFactory
public static Iterable<Object[]> data() {
return Stream.of("runtimeLoadLibrary", "fileList").map(action -> new Object[] { action }).toList();
}
@Override
protected String getTestRestCluster() {
return testRule.cluster.getHttpAddresses();
}
}
| EntitlementsAllowedViaOverrideIT |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java | {
"start": 2812,
"end": 33054
} | class ____ parameters or itself.
*
* @param method {@link Method}
* @param annotationClass {@link Annotation} type
* @param <A> {@link Annotation} type
* @return If present , return <code>true</code> , or <code>false</code>
*/
public static <A extends Annotation> boolean isPresent(Method method, Class<A> annotationClass) {
Map<ElementType, List<A>> annotationsMap = findAnnotations(method, annotationClass);
return !annotationsMap.isEmpty();
}
/**
* Find specified {@link Annotation} type maps from {@link Method}
*
* @param method {@link Method}
* @param annotationClass {@link Annotation} type
* @param <A> {@link Annotation} type
* @return {@link Annotation} type maps , the {@link ElementType} as key ,
* the list of {@link Annotation} as value.
* If {@link Annotation} was annotated on {@link Method}'s parameters{@link ElementType#PARAMETER} ,
* the associated {@link Annotation} list may contain multiple elements.
*/
public static <A extends Annotation> Map<ElementType, List<A>> findAnnotations(
Method method, Class<A> annotationClass) {
Retention retention = annotationClass.getAnnotation(Retention.class);
RetentionPolicy retentionPolicy = retention.value();
if (!RetentionPolicy.RUNTIME.equals(retentionPolicy)) {
return Collections.emptyMap();
}
Map<ElementType, List<A>> annotationsMap = new LinkedHashMap<ElementType, List<A>>();
Target target = annotationClass.getAnnotation(Target.class);
ElementType[] elementTypes = target.value();
for (ElementType elementType : elementTypes) {
List<A> annotationsList = new LinkedList<A>();
switch (elementType) {
case PARAMETER:
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotationClass.equals(annotation.annotationType())) {
annotationsList.add((A) annotation);
}
}
}
break;
case METHOD:
A annotation = findAnnotation(method, annotationClass);
if (annotation != null) {
annotationsList.add(annotation);
}
break;
case TYPE:
Class<?> beanType = method.getDeclaringClass();
A annotation2 = findAnnotation(beanType, annotationClass);
if (annotation2 != null) {
annotationsList.add(annotation2);
}
break;
}
if (!annotationsList.isEmpty()) {
annotationsMap.put(elementType, annotationsList);
}
}
return Collections.unmodifiableMap(annotationsMap);
}
/**
* Get the {@link Annotation} attributes
*
* @param annotation specified {@link Annotation}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
* @since 1.0.2
*/
public static Map<String, Object> getAttributes(
Annotation annotation, boolean ignoreDefaultValue, String... ignoreAttributeNames) {
return getAttributes(annotation, null, ignoreDefaultValue, ignoreAttributeNames);
}
/**
* Get the {@link Annotation} attributes
*
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
* @since 1.0.2
*/
public static Map<String, Object> getAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return getAttributes(annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames);
}
/**
* Get the {@link Annotation} attributes
*
* @param annotationAttributes the attributes of specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
* @since 1.0.4
*/
public static Map<String, Object> getAttributes(
Map<String, Object> annotationAttributes,
PropertyResolver propertyResolver,
String... ignoreAttributeNames) {
Set<String> ignoreAttributeNamesSet =
new HashSet<String>((Collection<? extends String>) arrayToList(ignoreAttributeNames));
Map<String, Object> actualAttributes = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) {
String attributeName = annotationAttribute.getKey();
Object attributeValue = annotationAttribute.getValue();
// ignore attribute name
if (ignoreAttributeNamesSet.contains(attributeName)) {
continue;
}
if (attributeValue instanceof String) {
attributeValue = resolvePlaceholders(valueOf(attributeValue), propertyResolver);
} else if (attributeValue instanceof String[]) {
String[] values = (String[]) attributeValue;
for (int i = 0; i < values.length; i++) {
values[i] = resolvePlaceholders(values[i], propertyResolver);
}
attributeValue = values;
}
actualAttributes.put(attributeName, attributeValue);
}
return actualAttributes;
}
/**
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return
* @since 1.0.11
*/
public static Map<String, Object> getAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
Map<String, Object> annotationAttributes =
org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(
annotation, classValuesAsString, nestedAnnotationsAsMap);
String[] actualIgnoreAttributeNames = ignoreAttributeNames;
if (ignoreDefaultValue && !isEmpty(annotationAttributes)) {
List<String> attributeNamesToIgnore = new LinkedList<String>(asList(ignoreAttributeNames));
for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) {
String attributeName = annotationAttribute.getKey();
Object attributeValue = annotationAttribute.getValue();
if (nullSafeEquals(attributeValue, getDefaultValue(annotation, attributeName))) {
attributeNamesToIgnore.add(attributeName);
}
}
// extends the ignored list
actualIgnoreAttributeNames = attributeNamesToIgnore.toArray(new String[attributeNamesToIgnore.size()]);
}
return getAttributes(annotationAttributes, propertyResolver, actualIgnoreAttributeNames);
}
private static String resolvePlaceholders(String attributeValue, PropertyResolver propertyResolver) {
String resolvedValue = attributeValue;
if (propertyResolver != null) {
resolvedValue = propertyResolver.resolvePlaceholders(resolvedValue);
resolvedValue = trimWhitespace(resolvedValue);
}
return resolvedValue;
}
/**
* Get the attribute value
*
* @param annotation {@link Annotation annotation}
* @param attributeName the name of attribute
* @param <T> the type of attribute value
* @return the attribute value if found
* @since 1.0.3
*/
public static <T> T getAttribute(Annotation annotation, String attributeName) {
return getAttribute(
org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(annotation), attributeName);
}
/**
* Get the attribute value
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param <T> the type of attribute value
* @return the attribute value if found
* @since 1.0.3
*/
public static <T> T getAttribute(Map<String, Object> attributes, String attributeName) {
return getAttribute(attributes, attributeName, false);
}
/**
* Get the attribute value the will
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param required the required attribute or not
* @param <T> the type of attribute value
* @return the attribute value if found
* @throws IllegalStateException if attribute value can't be found
* @since 1.0.6
*/
public static <T> T getAttribute(Map<String, Object> attributes, String attributeName, boolean required) {
T value = getAttribute(attributes, attributeName, null);
if (required && value == null) {
throw new IllegalStateException("The attribute['" + attributeName + "] is required!");
}
return value;
}
/**
* Get the attribute value with default value
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param defaultValue the default value of attribute
* @param <T> the type of attribute value
* @return the attribute value if found
* @since 1.0.6
*/
public static <T> T getAttribute(Map<String, Object> attributes, String attributeName, T defaultValue) {
T value = (T) attributes.get(attributeName);
return value == null ? defaultValue : value;
}
/**
* Get the required attribute value
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param <T> the type of attribute value
* @return the attribute value if found
* @throws IllegalStateException if attribute value can't be found
* @since 1.0.6
*/
public static <T> T getRequiredAttribute(Map<String, Object> attributes, String attributeName) {
return getAttribute(attributes, attributeName, true);
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotation specified {@link Annotation}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
* @see #getAnnotationAttributes(Annotation, PropertyResolver, boolean, String...)
* @since 1.0.3
*/
public static AnnotationAttributes getAnnotationAttributes(
Annotation annotation, boolean ignoreDefaultValue, String... ignoreAttributeNames) {
return getAnnotationAttributes(annotation, null, ignoreDefaultValue, ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @param ignoreDefaultValue whether ignore default value or not
* @return non-null
* @see #getAttributes(Annotation, PropertyResolver, boolean, String...)
* @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...)
* @since 1.0.11
*/
public static AnnotationAttributes getAnnotationAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return fromMap(getAttributes(
annotation,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames));
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
* @see #getAttributes(Annotation, PropertyResolver, boolean, String...)
* @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...)
* @since 1.0.3
*/
public static AnnotationAttributes getAnnotationAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return getAnnotationAttributes(
annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code>
* @since 1.0.3
*/
public static AnnotationAttributes getAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return getAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
false,
false,
ignoreDefaultValue,
ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code>
* @since 1.0.11
*/
public static AnnotationAttributes getAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
Annotation annotation = annotatedElement.getAnnotation(annotationType);
return annotation == null
? null
: getAnnotationAttributes(
annotation,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}, if the argument <code>tryMergedAnnotation</code> is <code>true</code>,
* the {@link AnnotationAttributes} will be got from
* {@link #tryGetMergedAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) merged annotation} first,
* if failed, and then to get from
* {@link #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, boolean, String...) normal one}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param tryMergedAnnotation whether try merged annotation or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code>
* @since 1.0.3
*/
public static AnnotationAttributes getAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
boolean tryMergedAnnotation,
String... ignoreAttributeNames) {
return getAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
false,
false,
ignoreDefaultValue,
tryMergedAnnotation,
ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}, if the argument <code>tryMergedAnnotation</code> is <code>true</code>,
* the {@link AnnotationAttributes} will be got from
* {@link #tryGetMergedAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) merged annotation} first,
* if failed, and then to get from
* {@link #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, boolean, String...) normal one}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreDefaultValue whether ignore default value or not
* @param tryMergedAnnotation whether try merged annotation or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code>
* @since 1.0.11
*/
public static AnnotationAttributes getAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
boolean tryMergedAnnotation,
String... ignoreAttributeNames) {
AnnotationAttributes attributes = null;
if (tryMergedAnnotation) {
attributes = tryGetMergedAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
if (attributes == null) {
attributes = getAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
return attributes;
}
/**
* Try to get the merged {@link Annotation annotation}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @return If current version of Spring Framework is below 4.2, return <code>null</code>
* @since 1.0.3
*/
public static Annotation tryGetMergedAnnotation(
AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType) {
return tryGetMergedAnnotation(annotatedElement, annotationType, false, false);
}
/**
* Try to get the merged {@link Annotation annotation}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @return If current version of Spring Framework is below 4.2, return <code>null</code>
* @since 1.0.11
*/
public static Annotation tryGetMergedAnnotation(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap) {
Annotation mergedAnnotation = null;
ClassLoader classLoader = annotationType.getClassLoader();
if (ClassUtils.isPresent(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader)) {
Class<?> annotatedElementUtilsClass = resolveClassName(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader);
// getMergedAnnotation method appears in the Spring Framework 5.x
Method getMergedAnnotationMethod =
findMethod(annotatedElementUtilsClass, "getMergedAnnotation", AnnotatedElement.class, Class.class);
if (getMergedAnnotationMethod != null) {
mergedAnnotation =
(Annotation) invokeMethod(getMergedAnnotationMethod, null, annotatedElement, annotationType);
} else {
// getMergedAnnotation method appears in the Spring Framework 4.2
getMergedAnnotationMethod = findMethod(
annotatedElementUtilsClass,
"getMergedAnnotation",
AnnotatedElement.class,
Class.class,
boolean.class,
boolean.class);
if (getMergedAnnotationMethod != null) {
mergedAnnotation = (Annotation) invokeMethod(
getMergedAnnotationMethod,
null,
annotatedElement,
annotationType,
classValuesAsString,
nestedAnnotationsAsMap);
}
}
}
return mergedAnnotation;
}
/**
* Try to get {@link AnnotationAttributes the annotation attributes} after merging and resolving the placeholders
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return If the specified annotation type is not found, return <code>null</code>
* @since 1.0.3
*/
public static AnnotationAttributes tryGetMergedAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return tryGetMergedAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
false,
false,
ignoreDefaultValue,
ignoreAttributeNames);
}
/**
* Try to get {@link AnnotationAttributes the annotation attributes} after merging and resolving the placeholders
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return If the specified annotation type is not found, return <code>null</code>
* @since 1.0.11
*/
public static AnnotationAttributes tryGetMergedAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
Annotation annotation =
tryGetMergedAnnotation(annotatedElement, annotationType, classValuesAsString, nestedAnnotationsAsMap);
return annotation == null
? null
: getAnnotationAttributes(
annotation,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
}
| or |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0249ResolveDepsFromReactorTest.java | {
"start": 1119,
"end": 2680
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that the reactor can establish the artifact location of known projects for dependencies.
*
* @throws Exception in case of failure
*/
@Test
public void testitMNG0249() throws Exception {
File testDir = extractResources("/mng-0249");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> ccp = verifier.loadLines("test-component-c/target/compile.txt");
assertTrue(ccp.contains("test-component-c/classes"), ccp.toString());
assertTrue(ccp.contains("test-component-b/classes"), ccp.toString());
assertTrue(ccp.contains("test-component-a/classes"), ccp.toString());
List<String> rcp = verifier.loadLines("test-component-c/target/runtime.txt");
assertTrue(rcp.contains("test-component-c/classes"), rcp.toString());
assertTrue(rcp.contains("test-component-b/classes"), rcp.toString());
assertTrue(rcp.contains("test-component-a/classes"), rcp.toString());
List<String> tcp = verifier.loadLines("test-component-c/target/test.txt");
assertTrue(tcp.contains("test-component-c/classes"), tcp.toString());
assertTrue(tcp.contains("test-component-b/classes"), tcp.toString());
assertTrue(tcp.contains("test-component-a/classes"), tcp.toString());
}
}
| MavenITmng0249ResolveDepsFromReactorTest |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/ContextReloadStrategy.java | {
"start": 1111,
"end": 1171
} | interface ____ extends ReloadStrategy {
}
| ContextReloadStrategy |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/mistral/completion/MistralChatCompletionModelTests.java | {
"start": 684,
"end": 5243
} | class ____ extends ESTestCase {
public static MistralChatCompletionModel createCompletionModel(String apiKey, String modelId) {
return new MistralChatCompletionModel(
"id",
TaskType.COMPLETION,
"service",
new MistralChatCompletionServiceSettings(modelId, null),
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static MistralChatCompletionModel createCompletionModel(String url, String apiKey, String modelId) {
MistralChatCompletionModel mistralChatCompletionModel = new MistralChatCompletionModel(
"id",
TaskType.COMPLETION,
"service",
new MistralChatCompletionServiceSettings(modelId, null),
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
mistralChatCompletionModel.setURI(url);
return mistralChatCompletionModel;
}
public static MistralChatCompletionModel createChatCompletionModel(String apiKey, String modelId) {
return new MistralChatCompletionModel(
"id",
TaskType.CHAT_COMPLETION,
"service",
new MistralChatCompletionServiceSettings(modelId, null),
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static MistralChatCompletionModel createChatCompletionModel(String url, String apiKey, String modelId) {
MistralChatCompletionModel mistralChatCompletionModel = new MistralChatCompletionModel(
"id",
TaskType.CHAT_COMPLETION,
"service",
new MistralChatCompletionServiceSettings(modelId, null),
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
mistralChatCompletionModel.setURI(url);
return mistralChatCompletionModel;
}
public void testOverrideWith_UnifiedCompletionRequest_OverridesExistingModelId() {
var model = createCompletionModel("api_key", "model_name");
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
"different_model",
null,
null,
null,
null,
null,
null
);
var overriddenModel = MistralChatCompletionModel.of(model, request);
assertThat(overriddenModel.getServiceSettings().modelId(), is("different_model"));
}
public void testOverrideWith_UnifiedCompletionRequest_OverridesNullModelId() {
var model = createCompletionModel("api_key", null);
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
"different_model",
null,
null,
null,
null,
null,
null
);
var overriddenModel = MistralChatCompletionModel.of(model, request);
assertThat(overriddenModel.getServiceSettings().modelId(), is("different_model"));
}
public void testOverrideWith_UnifiedCompletionRequest_KeepsNullIfNoModelIdProvided() {
var model = createCompletionModel("api_key", null);
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
null,
null,
null,
null,
null,
null,
null
);
var overriddenModel = MistralChatCompletionModel.of(model, request);
assertNull(overriddenModel.getServiceSettings().modelId());
}
public void testOverrideWith_UnifiedCompletionRequest_UsesModelFields_WhenRequestDoesNotOverride() {
var model = createCompletionModel("api_key", "model_name");
var request = new UnifiedCompletionRequest(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "role", null, null)),
null, // not overriding model
null,
null,
null,
null,
null,
null
);
var overriddenModel = MistralChatCompletionModel.of(model, request);
assertThat(overriddenModel.getServiceSettings().modelId(), is("model_name"));
}
}
| MistralChatCompletionModelTests |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/jdbc/JdbcSpies.java | {
"start": 950,
"end": 2880
} | class ____ {
private final Map<Method, Map<Object, List<Object[]>>> calls = new HashMap<>();
private final List<Callback> callbacks = new ArrayList<>();
private Object call(Object spy, Object realObject, Method method, Object[] args) throws Throwable {
return onCall( spy, method, args, callOnly( realObject, method, args ) );
}
private Object callOnly(Object realObject, Method method, Object[] args) throws Throwable {
try {
return method.invoke( realObject, args );
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
private <T> T onCall(Object spy, Method method, Object[] args, T result) {
calls.computeIfAbsent( method, m -> new IdentityHashMap<>() )
.computeIfAbsent( spy, s -> new ArrayList<>() )
.add( args );
for ( Callback callback : callbacks ) {
callback.onCall( spy, method, args, result );
}
return result;
}
public SpyContext registerCallback(Callback callback) {
callbacks.add( callback );
return this;
}
public List<Object[]> getCalls(Method method, Object spy) {
return calls.getOrDefault( method, Collections.emptyMap() ).getOrDefault( spy, Collections.emptyList() );
}
public void clear() {
calls.clear();
}
public <T> T getSpiedInstance(T spy) {
if ( Proxy.isProxyClass( spy.getClass() ) ) {
final InvocationHandler invocationHandler = Proxy.getInvocationHandler( spy );
if ( invocationHandler instanceof Spy ) {
//noinspection unchecked
return (T) ( (Spy) invocationHandler ).getSpiedInstance();
}
}
throw new IllegalArgumentException( "Passed object is not a spy: " + spy );
}
}
public static Connection spy(Connection connection, SpyContext context) {
return (Connection) Proxy.newProxyInstance(
ClassLoader.getSystemClassLoader(),
new Class[]{ Connection.class },
new ConnectionHandler( connection, context )
);
}
private | SpyContext |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/state/TestLocalRecoveryConfig.java | {
"start": 1291,
"end": 2380
} | class ____ implements LocalSnapshotDirectoryProvider {
private TestDummyLocalDirectoryProvider() {}
@Override
public File allocationBaseDirectory(long checkpointId) {
throw new UnsupportedOperationException("Test dummy");
}
@Override
public File subtaskBaseDirectory(long checkpointId) {
throw new UnsupportedOperationException("Test dummy");
}
@Override
public File subtaskSpecificCheckpointDirectory(long checkpointId) {
throw new UnsupportedOperationException("Test dummy");
}
@Override
public File selectAllocationBaseDirectory(int idx) {
throw new UnsupportedOperationException("Test dummy");
}
@Override
public File selectSubtaskBaseDirectory(int idx) {
throw new UnsupportedOperationException("Test dummy");
}
@Override
public int allocationBaseDirsCount() {
throw new UnsupportedOperationException("Test dummy");
}
}
}
| TestDummyLocalDirectoryProvider |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/profile/TransportProfileHasPrivilegesAction.java | {
"start": 2128,
"end": 6833
} | class ____ extends HandledTransportAction<ProfileHasPrivilegesRequest, ProfileHasPrivilegesResponse> {
private static final Logger logger = LogManager.getLogger(TransportProfileHasPrivilegesAction.class);
private final AuthorizationService authorizationService;
private final NativePrivilegeStore privilegeStore;
private final ProfileService profileService;
private final ThreadPool threadPool;
@Inject
public TransportProfileHasPrivilegesAction(
TransportService transportService,
ActionFilters actionFilters,
AuthorizationService authorizationService,
NativePrivilegeStore privilegeStore,
ProfileService profileService,
ThreadPool threadPool
) {
super(
ProfileHasPrivilegesAction.NAME,
transportService,
actionFilters,
ProfileHasPrivilegesRequest::new,
EsExecutors.DIRECT_EXECUTOR_SERVICE
);
this.authorizationService = authorizationService;
this.privilegeStore = privilegeStore;
this.profileService = profileService;
this.threadPool = threadPool;
}
@Override
protected void doExecute(Task task, ProfileHasPrivilegesRequest request, ActionListener<ProfileHasPrivilegesResponse> listener) {
assert task instanceof CancellableTask : "task must be cancellable";
profileService.getProfileSubjects(request.profileUids(), ActionListener.wrap(profileSubjectsAndFailures -> {
if (profileSubjectsAndFailures.results().isEmpty()) {
listener.onResponse(new ProfileHasPrivilegesResponse(Set.of(), profileSubjectsAndFailures.errors()));
return;
}
final Set<String> hasPrivilegeProfiles = Collections.synchronizedSet(new HashSet<>());
final Map<String, Exception> errorProfiles = new ConcurrentHashMap<>(profileSubjectsAndFailures.errors());
final AtomicInteger counter = new AtomicInteger(profileSubjectsAndFailures.results().size());
assert counter.get() > 0;
resolveApplicationPrivileges(
request,
ActionListener.wrap(applicationPrivilegeDescriptors -> threadPool.generic().execute(() -> {
for (Map.Entry<String, Subject> profileUidToSubject : profileSubjectsAndFailures.results()) {
// return the partial response if the "has privilege" task got cancelled in the meantime
if (((CancellableTask) task).isCancelled()) {
listener.onFailure(new TaskCancelledException("has privilege task cancelled"));
return;
}
final String profileUid = profileUidToSubject.getKey();
final Subject subject = profileUidToSubject.getValue();
authorizationService.checkPrivileges(
subject,
request.privilegesToCheck(),
applicationPrivilegeDescriptors,
ActionListener.runAfter(ActionListener.wrap(privilegesCheckResult -> {
assert privilegesCheckResult.getDetails() == null;
if (privilegesCheckResult.allChecksSuccess()) {
hasPrivilegeProfiles.add(profileUid);
}
}, checkPrivilegesException -> {
logger.debug(() -> "Failed to check privileges for profile [" + profileUid + "]", checkPrivilegesException);
errorProfiles.put(profileUid, checkPrivilegesException);
}), () -> {
if (counter.decrementAndGet() == 0) {
listener.onResponse(new ProfileHasPrivilegesResponse(hasPrivilegeProfiles, errorProfiles));
}
})
);
}
}), listener::onFailure)
);
}, listener::onFailure));
}
private void resolveApplicationPrivileges(
ProfileHasPrivilegesRequest request,
ActionListener<Collection<ApplicationPrivilegeDescriptor>> listener
) {
final Set<String> applications = Arrays.stream(request.privilegesToCheck().application())
.map(RoleDescriptor.ApplicationResourcePrivileges::getApplication)
.collect(Collectors.toSet());
privilegeStore.getPrivileges(applications, null, listener);
}
}
| TransportProfileHasPrivilegesAction |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/boolean2darray/Boolean2DArrayAssert_isNotEmpty_Test.java | {
"start": 1011,
"end": 1344
} | class ____ extends Boolean2DArrayAssertBaseTest {
@Override
protected Boolean2DArrayAssert invoke_api_method() {
return assertions.isNotEmpty();
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertNotEmpty(getInfo(assertions), getActual(assertions));
}
}
| Boolean2DArrayAssert_isNotEmpty_Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/stream/KeyToOneCollectionFetchScrollTest.java | {
"start": 3996,
"end": 4117
} | class ____ extends BasicEntity {
public EntityC() {
}
public EntityC(String name) {
super( name );
}
}
}
| EntityC |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/matchers/GreaterOrEqual.java | {
"start": 197,
"end": 531
} | class ____<T extends Comparable<T>> extends CompareTo<T> implements Serializable {
public GreaterOrEqual(T value) {
super(value);
}
@Override
protected String getName() {
return "geq";
}
@Override
protected boolean matchResult(int result) {
return result >= 0;
}
}
| GreaterOrEqual |
java | apache__dubbo | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionResolver.java | {
"start": 3543,
"end": 18287
} | class ____ {
private static final FluentLogger LOG = FluentLogger.of(DefinitionResolver.class);
private final ExtensionFactory extensionFactory;
private final ConfigFactory configFactory;
private final SchemaResolver schemaResolver;
private final OpenAPIDefinitionResolver[] resolvers;
DefinitionResolver(FrameworkModel frameworkModel) {
extensionFactory = frameworkModel.getOrRegisterBean(ExtensionFactory.class);
configFactory = frameworkModel.getOrRegisterBean(ConfigFactory.class);
schemaResolver = frameworkModel.getOrRegisterBean(SchemaResolver.class);
resolvers = extensionFactory.getExtensions(OpenAPIDefinitionResolver.class);
}
public OpenAPI resolve(ServiceMeta serviceMeta, Collection<List<Registration>> registrationsByMethod) {
OpenAPI definition = new OpenAPIChainImpl(resolvers, openAPI -> {
if (StringUtils.isEmpty(openAPI.getGroup())) {
openAPI.setGroup(Constants.DEFAULT_GROUP);
}
openAPI.setConfig(configFactory.getConfig(openAPI.getGroup()));
String service = serviceMeta.getServiceInterface();
int index = service.lastIndexOf('.');
String tagName = index == -1 ? service : service.substring(index + 1);
openAPI.addTag(new Tag().setName(tagName).setDescription(service));
return openAPI;
})
.resolve(
new OpenAPI().setMeta(serviceMeta).setGlobalConfig(configFactory.getGlobalConfig()),
serviceMeta);
if (definition == null) {
return null;
}
if (definition.getConfig() == null) {
definition.setConfig(configFactory.getConfig(definition.getGroup()));
}
if (CollectionUtils.isEmpty(definition.getServers())) {
URL url = serviceMeta.getUrl();
definition.addServer(new Server()
.setUrl("http://" + url.getHost() + ':' + url.getPort())
.setDescription(Constants.DUBBO_DEFAULT_SERVER));
}
OperationContext context = new OperationContextImpl(definition, schemaResolver, extensionFactory);
for (List<Registration> registrations : registrationsByMethod) {
String mainPath = null;
for (Registration registration : registrations) {
RequestMapping mapping = registration.getMapping();
PathCondition pathCondition = mapping.getPathCondition();
if (pathCondition == null) {
continue;
}
for (PathExpression expression : pathCondition.getExpressions()) {
String path = expression.toString();
PathItem pathItem = definition.getOrAddPath(path);
String ref = pathItem.getRef();
if (ref != null) {
path = ref;
pathItem = definition.getOrAddPath(path);
}
if (mainPath != null && expression.isDirect()) {
pathItem.setRef(mainPath);
continue;
}
MethodMeta methodMeta = registration.getMeta().getMethod();
if (resolvePath(path, pathItem, definition, methodMeta, mapping, context)) {
mainPath = path;
}
}
}
}
return definition;
}
private boolean resolvePath(
String path,
PathItem pathItem,
OpenAPI openAPI,
MethodMeta methodMeta,
RequestMapping mapping,
OperationContext context) {
Collection<HttpMethods> httpMethods = null;
for (OpenAPIDefinitionResolver resolver : resolvers) {
httpMethods = resolver.resolve(pathItem, methodMeta, context);
if (httpMethods != null) {
break;
}
}
if (httpMethods == null) {
httpMethods = new LinkedList<>();
for (String method : determineHttpMethods(openAPI, methodMeta, mapping)) {
httpMethods.add(HttpMethods.of(method.toUpperCase()));
}
}
boolean added = false;
for (HttpMethods httpMethod : httpMethods) {
Operation operation = new Operation().setMeta(methodMeta);
Operation existingOperation = pathItem.getOperation(httpMethod);
if (existingOperation != null && existingOperation.getMeta() != null) {
LOG.internalWarn(
"Operation already exists, path='{}', httpMethod='{}', method={}",
path,
httpMethod,
methodMeta);
continue;
}
operation = new OperationChainImpl(
resolvers, op -> resolveOperation(path, httpMethod, op, openAPI, methodMeta, mapping))
.resolve(operation, methodMeta, context);
if (operation != null) {
pathItem.addOperation(httpMethod, operation);
added = true;
}
}
return added;
}
private Collection<String> determineHttpMethods(OpenAPI openAPI, MethodMeta meta, RequestMapping mapping) {
Collection<String> httpMethods = null;
MethodsCondition condition = mapping.getMethodsCondition();
if (condition != null) {
httpMethods = condition.getMethods();
}
if (httpMethods == null) {
String[] defaultHttpMethods = openAPI.getConfigValue(OpenAPIConfig::getDefaultHttpMethods);
if (defaultHttpMethods == null) {
httpMethods = Helper.guessHttpMethod(meta);
} else {
httpMethods = Arrays.asList(defaultHttpMethods);
}
}
return httpMethods;
}
private Operation resolveOperation(
String path,
HttpMethods httpMethod,
Operation operation,
OpenAPI openAPI,
MethodMeta meta,
RequestMapping mapping) {
if (operation.getGroup() == null) {
operation.setGroup(openAPI.getGroup());
}
for (Tag tag : openAPI.getTags()) {
operation.addTag(tag.getName());
}
if (operation.getDeprecated() == null && meta.isHierarchyAnnotated(Deprecated.class)) {
operation.setDeprecated(true);
}
ServiceMeta serviceMeta = meta.getServiceMeta();
if (serviceMeta.getServiceVersion() != null) {
operation.addParameter(new Parameter(TripleHeaderEnum.SERVICE_GROUP.getName(), In.HEADER)
.setSchema(PrimitiveSchema.STRING.newSchema()));
}
if (serviceMeta.getServiceGroup() != null) {
operation.addParameter(new Parameter(TripleHeaderEnum.SERVICE_VERSION.getName(), In.HEADER)
.setSchema(PrimitiveSchema.STRING.newSchema()));
}
List<String> variables = Helper.extractVariables(path);
if (variables != null) {
for (String variable : variables) {
Parameter parameter = operation.getParameter(variable, In.PATH);
if (parameter == null) {
parameter = new Parameter(variable, In.PATH);
operation.addParameter(parameter);
}
parameter.setRequired(true);
if (parameter.getSchema() == null) {
parameter.setSchema(PrimitiveSchema.STRING.newSchema());
}
}
}
for (ParameterMeta paramMeta : meta.getParameters()) {
resolveParameter(httpMethod, operation, paramMeta, true);
}
if (httpMethod.supportBody()) {
RequestBody body = operation.getRequestBody();
if (body == null) {
body = new RequestBody();
operation.setRequestBody(body);
}
if (CollectionUtils.isEmptyMap(body.getContents())) {
resolveRequestBody(body, openAPI, meta, mapping);
}
}
if (CollectionUtils.isEmptyMap(operation.getResponses())) {
String[] httpStatusCodes = openAPI.getConfigValue(OpenAPIConfig::getDefaultHttpStatusCodes);
if (httpStatusCodes == null) {
httpStatusCodes = new String[] {"200", "400", "500"};
}
for (String httpStatusCode : httpStatusCodes) {
ApiResponse response = operation.getOrAddResponse(httpStatusCode);
resolveResponse(httpStatusCode, response, openAPI, meta, mapping);
}
}
return operation;
}
private void resolveParameter(HttpMethods httpMethod, Operation operation, ParameterMeta meta, boolean traverse) {
String name = meta.getName();
if (name == null) {
return;
}
NamedValueMeta valueMeta = meta.getNamedValueMeta();
ParamType paramType = valueMeta.paramType();
if (paramType == null) {
if (httpMethod.supportBody()) {
return;
}
paramType = ParamType.Param;
}
In in = Helper.toIn(paramType);
if (in == null) {
return;
}
boolean simple = meta.isSimple();
if (in != In.QUERY && !simple) {
return;
}
if (simple) {
Parameter parameter = operation.getParameter(name, in);
if (parameter == null) {
parameter = new Parameter(name, in);
operation.addParameter(parameter);
}
if (parameter.getRequired() == null) {
parameter.setRequired(valueMeta.required());
}
Schema schema = parameter.getSchema();
if (schema == null) {
parameter.setSchema(schema = schemaResolver.resolve(meta));
}
if (schema.getDefaultValue() == null) {
schema.setDefaultValue(valueMeta.defaultValue());
}
parameter.setMeta(meta);
return;
}
if (!traverse) {
return;
}
BeanMeta beanMeta = meta.getBeanMeta();
try {
for (ParameterMeta ctorParam : beanMeta.getConstructor().getParameters()) {
resolveParameter(httpMethod, operation, ctorParam, false);
}
} catch (Throwable ignored) {
}
for (PropertyMeta property : beanMeta.getProperties()) {
if ((property.getVisibility() & 0b001) == 0) {
continue;
}
resolveParameter(httpMethod, operation, property, false);
}
}
private void resolveRequestBody(RequestBody body, OpenAPI openAPI, MethodMeta meta, RequestMapping mapping) {
Collection<MediaType> mediaTypes = null;
if (mapping.getConsumesCondition() != null) {
mediaTypes = mapping.getConsumesCondition().getMediaTypes();
}
if (mediaTypes == null) {
String[] defaultMediaTypes = openAPI.getConfigValue(OpenAPIConfig::getDefaultConsumesMediaTypes);
if (defaultMediaTypes == null) {
mediaTypes = Collections.singletonList(MediaType.APPLICATION_JSON);
} else {
mediaTypes = Arrays.stream(defaultMediaTypes).map(MediaType::of).collect(Collectors.toList());
}
}
out:
for (MediaType mediaType : mediaTypes) {
org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.MediaType content =
body.getOrAddContent(mediaType.getName());
if (content.getSchema() == null) {
for (ParameterMeta paramMeta : meta.getParameters()) {
ParamType paramType = paramMeta.getNamedValueMeta().paramType();
if (paramType == ParamType.Body) {
content.setSchema(schemaResolver.resolve(paramMeta));
continue out;
}
}
List<ParameterMeta> paramMetas = new ArrayList<>();
for (ParameterMeta paramMeta : meta.getParameters()) {
if (paramMeta.getNamedValueMeta().paramType() == null) {
paramMetas.add(paramMeta);
}
}
int size = paramMetas.size();
if (size == 0) {
continue;
}
if (size == 1) {
content.setSchema(schemaResolver.resolve(paramMetas.get(0)));
} else {
content.setSchema(schemaResolver.resolve(paramMetas));
}
}
}
}
private void resolveResponse(
String httpStatusCode, ApiResponse response, OpenAPI openAPI, MethodMeta meta, RequestMapping mapping) {
int httpStatus = Integer.parseInt(httpStatusCode);
if (response.getDescription() == null) {
response.setDescription(HttpUtils.getStatusMessage(httpStatus));
}
if (httpStatus > 201 && httpStatus < 400) {
return;
}
if (meta.getActualReturnType() == void.class) {
return;
}
Collection<MediaType> mediaTypes = null;
if (mapping.getProducesCondition() != null) {
mediaTypes = mapping.getProducesCondition().getMediaTypes();
}
if (mediaTypes == null) {
String[] defaultMediaTypes = openAPI.getConfigValue(OpenAPIConfig::getDefaultProducesMediaTypes);
if (defaultMediaTypes == null) {
mediaTypes = Collections.singletonList(MediaType.APPLICATION_JSON);
} else {
mediaTypes = Arrays.stream(defaultMediaTypes).map(MediaType::of).collect(Collectors.toList());
}
}
for (MediaType mediaType : mediaTypes) {
org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.MediaType content =
response.getOrAddContent(mediaType.getName());
if (content.getSchema() == null) {
if (httpStatus >= 400) {
content.setSchema(schemaResolver.resolve(ErrorResponse.class));
} else {
content.setSchema(schemaResolver.resolve(meta.getReturnParameter()));
}
}
}
}
private static final | DefinitionResolver |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/logger/ErrorTypeAwareLogger.java | {
"start": 1533,
"end": 2879
} | interface ____ extends Logger {
/**
* Logs a message with warn log level.
*
* @param code error code
* @param cause error cause
* @param extendedInformation extended information
* @param msg log this message
*/
void warn(String code, String cause, String extendedInformation, String msg);
/**
* Logs a message with warn log level.
*
* @param code error code
* @param cause error cause
* @param extendedInformation extended information
* @param msg log this message
* @param e log this cause
*/
void warn(String code, String cause, String extendedInformation, String msg, Throwable e);
/**
* Logs a message with error log level.
*
* @param code error code
* @param cause error cause
* @param extendedInformation extended information
* @param msg log this message
*/
void error(String code, String cause, String extendedInformation, String msg);
/**
* Logs a message with error log level.
*
* @param code error code
* @param cause error cause
* @param extendedInformation extended information
* @param msg log this message
* @param e log this cause
*/
void error(String code, String cause, String extendedInformation, String msg, Throwable e);
}
| ErrorTypeAwareLogger |
java | spring-projects__spring-boot | core/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java | {
"start": 5888,
"end": 6032
} | class ____ {
@Bean
String bean() {
return "bean";
}
}
@SelfAnnotating
@Import(ImportedBean.class)
static | TestWithImportAndBeanMethod |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/filter/factory/RemoveResponseHeaderGatewayFilterFactoryTests.java | {
"start": 1473,
"end": 2157
} | class ____ extends BaseWebClientTests {
@Test
public void removeResponseHeaderFilterWorks() {
testClient.get()
.uri("/headers")
.header("Host", "www.removereresponseheader.org")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.doesNotExist("X-Request-Foo");
}
@Test
public void toStringFormat() {
NameConfig config = new NameConfig();
config.setName("myname");
GatewayFilter filter = new RemoveResponseHeaderGatewayFilterFactory().apply(config);
assertThat(filter.toString()).contains("myname");
}
@EnableAutoConfiguration
@SpringBootConfiguration
@Import(DefaultTestConfig.class)
public static | RemoveResponseHeaderGatewayFilterFactoryTests |
java | elastic__elasticsearch | x-pack/plugin/analytics/src/main/java/org/elasticsearch/xpack/analytics/topmetrics/TopMetricsAggregator.java | {
"start": 8314,
"end": 8473
} | interface ____ {
MetricValues build(int size, BigArrays bigArrays, String name, ValuesSourceConfig config);
}
abstract static | MetricValuesSupplier |
java | apache__camel | components/camel-ai/camel-pinecone/src/main/java/org/apache/camel/component/pinecone/PineconeVectorDbHeaders.java | {
"start": 895,
"end": 3922
} | class ____ {
@Metadata(description = "The action to be performed.", javaType = "String",
enums = "CREATE_COLLECTION,CREATE_SERVERLESS_INDEX,CREATE_POD_INDEX,FETCH,UPSERT,DELETE_INDEX,DELETE_COLLECTION,QUERY,QUERY_BY_ID,UPDATE,DELETE_BY_ID")
public static final String ACTION = "CamelPineconeAction";
@Metadata(description = "Text Field Name for Insert/Upsert operation", javaType = "String")
public static final String TEXT_FIELD_NAME = "CamelPineconeTextFieldName";
@Metadata(description = "Vector Field Name for Insert/Upsert operation", javaType = "String")
public static final String VECTOR_FIELD_NAME = "CamelPineconeVectorFieldName";
@Metadata(description = "Index Name", javaType = "String")
public static final String INDEX_NAME = "CamelPineconeIndexName";
@Metadata(description = "Index Pod Type", javaType = "String")
public static final String INDEX_POD_TYPE = "CamelPineconeIndexPodType";
@Metadata(description = "Index Pod Environment", javaType = "String")
public static final String INDEX_POD_ENVIRONMENT = "CamelPineconeIndexPodEnvironment";
@Metadata(description = "Collection Name for Insert/Upsert operation", javaType = "String")
public static final String COLLECTION_NAME = "CamelPineconeCollectionName";
@Metadata(description = "Collection Similarity Metric", javaType = "String", enums = "cosine,euclidean,dotproduct")
public static final String COLLECTION_SIMILARITY_METRIC = "CamelPineconeCollectionSimilarityMetric";
@Metadata(description = "Collection Dimension", javaType = "int")
public static final String COLLECTION_DIMENSION = "CamelPineconeCollectionDimension";
@Metadata(description = "Collection Cloud Vendor", javaType = "String", enums = "aws,gcp,azure")
public static final String COLLECTION_CLOUD = "CamelPineconeCollectionCloud";
@Metadata(description = "Collection Cloud Vendor Region", javaType = "String", enums = "aws,gcp,azure")
public static final String COLLECTION_CLOUD_REGION = "CamelPineconeCollectionCloudRegion";
@Metadata(description = "Index Upsert Id", javaType = "String")
public static final String INDEX_ID = "CamelPineconeIndexId";
@Metadata(description = "Query Top K", javaType = "Integer")
public static final String QUERY_TOP_K = "CamelPineconeQueryTopK";
@Metadata(description = "Namespace for actions (query/upsert/etc)", javaType = "String")
public static final String NAMESPACE = "CamelPineconeNamespace";
@Metadata(description = "Query Filter", javaType = "String")
public static final String QUERY_FILTER = "CamelPineconeQueryFilter";
@Metadata(description = "Query Include Values", javaType = "boolean")
public static final String QUERY_INCLUDE_VALUES = "CamelPineconeQueryIncludeValues";
@Metadata(description = "Query Include Metadata", javaType = "com.google.protobuf.Struct")
public static final String QUERY_INCLUDE_METADATA = "CamelPineconeQueryIncludeMetadata";
}
| PineconeVectorDbHeaders |
java | grpc__grpc-java | netty/src/main/java/io/grpc/netty/NettyServerTransport.java | {
"start": 1798,
"end": 5953
} | class ____ implements ServerTransport {
// connectionLog is for connection related messages only
private static final Logger connectionLog = Logger.getLogger(
String.format("%s.connections", NettyServerTransport.class.getName()));
// Some exceptions are not very useful and add too much noise to the log
private static final ImmutableList<String> QUIET_EXCEPTIONS = ImmutableList.of(
"NativeIoException" /* Netty exceptions */);
private final InternalLogId logId;
private final Channel channel;
private final ChannelPromise channelUnused;
private final ProtocolNegotiator protocolNegotiator;
private final int maxStreams;
// only accessed from channel event loop
private NettyServerHandler grpcHandler;
private ServerTransportListener listener;
private boolean terminated;
private final boolean autoFlowControl;
private final int flowControlWindow;
private final int maxMessageSize;
private final int maxHeaderListSize;
private final int softLimitHeaderListSize;
private final long keepAliveTimeInNanos;
private final long keepAliveTimeoutInNanos;
private final long maxConnectionIdleInNanos;
private final long maxConnectionAgeInNanos;
private final long maxConnectionAgeGraceInNanos;
private final boolean permitKeepAliveWithoutCalls;
private final long permitKeepAliveTimeInNanos;
private final int maxRstCount;
private final long maxRstPeriodNanos;
private final Attributes eagAttributes;
private final List<? extends ServerStreamTracer.Factory> streamTracerFactories;
private final TransportTracer transportTracer;
NettyServerTransport(
Channel channel,
ChannelPromise channelUnused,
ProtocolNegotiator protocolNegotiator,
List<? extends ServerStreamTracer.Factory> streamTracerFactories,
TransportTracer transportTracer,
int maxStreams,
boolean autoFlowControl,
int flowControlWindow,
int maxMessageSize,
int maxHeaderListSize,
int softLimitHeaderListSize,
long keepAliveTimeInNanos,
long keepAliveTimeoutInNanos,
long maxConnectionIdleInNanos,
long maxConnectionAgeInNanos,
long maxConnectionAgeGraceInNanos,
boolean permitKeepAliveWithoutCalls,
long permitKeepAliveTimeInNanos,
int maxRstCount,
long maxRstPeriodNanos,
Attributes eagAttributes) {
this.channel = Preconditions.checkNotNull(channel, "channel");
this.channelUnused = channelUnused;
this.protocolNegotiator = Preconditions.checkNotNull(protocolNegotiator, "protocolNegotiator");
this.streamTracerFactories =
Preconditions.checkNotNull(streamTracerFactories, "streamTracerFactories");
this.transportTracer = Preconditions.checkNotNull(transportTracer, "transportTracer");
this.maxStreams = maxStreams;
this.autoFlowControl = autoFlowControl;
this.flowControlWindow = flowControlWindow;
this.maxMessageSize = maxMessageSize;
this.maxHeaderListSize = maxHeaderListSize;
this.softLimitHeaderListSize = softLimitHeaderListSize;
this.keepAliveTimeInNanos = keepAliveTimeInNanos;
this.keepAliveTimeoutInNanos = keepAliveTimeoutInNanos;
this.maxConnectionIdleInNanos = maxConnectionIdleInNanos;
this.maxConnectionAgeInNanos = maxConnectionAgeInNanos;
this.maxConnectionAgeGraceInNanos = maxConnectionAgeGraceInNanos;
this.permitKeepAliveWithoutCalls = permitKeepAliveWithoutCalls;
this.permitKeepAliveTimeInNanos = permitKeepAliveTimeInNanos;
this.maxRstCount = maxRstCount;
this.maxRstPeriodNanos = maxRstPeriodNanos;
this.eagAttributes = Preconditions.checkNotNull(eagAttributes, "eagAttributes");
SocketAddress remote = channel.remoteAddress();
this.logId = InternalLogId.allocate(getClass(), remote != null ? remote.toString() : null);
}
public void start(ServerTransportListener listener) {
Preconditions.checkState(this.listener == null, "Handler already registered");
this.listener = listener;
// Create the Netty handler for the pipeline.
grpcHandler = createHandler(listener, channelUnused);
// Notify when the channel closes.
final | NettyServerTransport |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/runtime/operators/windowing/CountTriggerTest.java | {
"start": 1360,
"end": 8845
} | class ____ {
/** Verify that state of separate windows does not leak into other windows. */
@Test
void testWindowSeparationAndFiring() throws Exception {
TriggerTestHarness<Object, TimeWindow> testHarness =
new TriggerTestHarness<>(CountTrigger.of(3), new TimeWindow.Serializer());
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(0, 2)))
.isEqualTo(TriggerResult.CONTINUE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(2, 4)))
.isEqualTo(TriggerResult.CONTINUE);
// shouldn't have any timers
assertThat(testHarness.numProcessingTimeTimers()).isZero();
assertThat(testHarness.numEventTimeTimers()).isZero();
assertThat(testHarness.numStateEntries()).isEqualTo(2);
assertThat(testHarness.numStateEntries(new TimeWindow(0, 2))).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isOne();
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(0, 2)))
.isEqualTo(TriggerResult.CONTINUE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(0, 2)))
.isEqualTo(TriggerResult.FIRE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(2, 4)))
.isEqualTo(TriggerResult.CONTINUE);
// right now, CountTrigger will clear it's state in onElement when firing
// ideally, this should be moved to onFire()
assertThat(testHarness.numStateEntries()).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(0, 2))).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isOne();
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(2, 4)))
.isEqualTo(TriggerResult.FIRE);
// now all state should be gone
assertThat(testHarness.numStateEntries()).isZero();
}
/** Verify that clear() does not leak across windows. */
@Test
void testClear() throws Exception {
TriggerTestHarness<Object, TimeWindow> testHarness =
new TriggerTestHarness<>(CountTrigger.of(3), new TimeWindow.Serializer());
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(0, 2)))
.isEqualTo(TriggerResult.CONTINUE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(2, 4)))
.isEqualTo(TriggerResult.CONTINUE);
// shouldn't have any timers
assertThat(testHarness.numProcessingTimeTimers()).isZero();
assertThat(testHarness.numEventTimeTimers()).isZero();
assertThat(testHarness.numStateEntries()).isEqualTo(2);
assertThat(testHarness.numStateEntries(new TimeWindow(0, 2))).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isOne();
testHarness.clearTriggerState(new TimeWindow(2, 4));
assertThat(testHarness.numStateEntries()).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(0, 2))).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isZero();
testHarness.clearTriggerState(new TimeWindow(0, 2));
assertThat(testHarness.numStateEntries()).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(0, 2))).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isZero();
}
@Test
void testMergingWindows() throws Exception {
TriggerTestHarness<Object, TimeWindow> testHarness =
new TriggerTestHarness<>(CountTrigger.of(3), new TimeWindow.Serializer());
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(0, 2)))
.isEqualTo(TriggerResult.CONTINUE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(2, 4)))
.isEqualTo(TriggerResult.CONTINUE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(4, 6)))
.isEqualTo(TriggerResult.CONTINUE);
// shouldn't have any timers
assertThat(testHarness.numProcessingTimeTimers()).isZero();
assertThat(testHarness.numEventTimeTimers()).isZero();
assertThat(testHarness.numStateEntries()).isEqualTo(3);
assertThat(testHarness.numStateEntries(new TimeWindow(0, 2))).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(4, 6))).isOne();
testHarness.mergeWindows(
new TimeWindow(0, 4),
Lists.newArrayList(new TimeWindow(0, 2), new TimeWindow(2, 4)));
assertThat(testHarness.numStateEntries()).isEqualTo(2);
assertThat(testHarness.numStateEntries(new TimeWindow(0, 2))).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(0, 4))).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(4, 6))).isOne();
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(0, 4)))
.isEqualTo(TriggerResult.FIRE);
assertThat(testHarness.numStateEntries()).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(0, 4))).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(4, 6))).isOne();
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(4, 6)))
.isEqualTo(TriggerResult.CONTINUE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(4, 6)))
.isEqualTo(TriggerResult.FIRE);
assertThat(testHarness.numStateEntries()).isZero();
}
@Test
void testMergeSubsumingWindow() throws Exception {
TriggerTestHarness<Object, TimeWindow> testHarness =
new TriggerTestHarness<>(CountTrigger.of(3), new TimeWindow.Serializer());
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(2, 4)))
.isEqualTo(TriggerResult.CONTINUE);
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(4, 6)))
.isEqualTo(TriggerResult.CONTINUE);
// shouldn't have any timers
assertThat(testHarness.numProcessingTimeTimers()).isZero();
assertThat(testHarness.numEventTimeTimers()).isZero();
assertThat(testHarness.numStateEntries()).isEqualTo(2);
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(4, 6))).isOne();
testHarness.mergeWindows(
new TimeWindow(0, 8),
Lists.newArrayList(new TimeWindow(2, 4), new TimeWindow(4, 6)));
assertThat(testHarness.numStateEntries()).isOne();
assertThat(testHarness.numStateEntries(new TimeWindow(2, 4))).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(4, 6))).isZero();
assertThat(testHarness.numStateEntries(new TimeWindow(0, 8))).isOne();
assertThat(testHarness.processElement(new StreamRecord<>(1), new TimeWindow(0, 8)))
.isEqualTo(TriggerResult.FIRE);
assertThat(testHarness.numStateEntries()).isZero();
}
}
| CountTriggerTest |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoAnnotationTest.java | {
"start": 16056,
"end": 16147
} | interface ____ {
int[] ints();
}
@IntArray(ints = {1, 2, 3})
private static | IntArray |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/huggingface/response/HuggingFaceElserResponseEntity.java | {
"start": 1255,
"end": 4253
} | class ____ {
/**
* The response from hugging face will be formatted as [{"token": 0.0...123}]. Each object within the array will correspond to the
* item within the inputs array within the request sent to hugging face. For example for a request like:
*
* <pre>
* <code>
* {
* "inputs": ["hello this is my name", "I wish I was there!"]
* }
* </code>
* </pre>
*
* The response would look like:
*
* <pre>
* <code>
* [
* {
* "the": 0.7226026,
* "to": 0.29198948,
* "is": 0.059944477,
* ...
* },
* {
* "wish": 0.123456,
* ...
* }
* ]
* </code>
* </pre>
*/
public static SparseEmbeddingResults fromResponse(Request request, HttpResult response) throws IOException {
var parserConfig = XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE);
try (XContentParser jsonParser = XContentFactory.xContent(XContentType.JSON).createParser(parserConfig, response.body())) {
moveToFirstToken(jsonParser);
var truncationResults = request.getTruncationInfo();
List<SparseEmbeddingResults.Embedding> parsedEmbeddings = parseList(
jsonParser,
(parser, index) -> HuggingFaceElserResponseEntity.parseExpansionResult(truncationResults, parser, index)
);
if (parsedEmbeddings.isEmpty()) {
return new SparseEmbeddingResults(Collections.emptyList());
}
return new SparseEmbeddingResults(parsedEmbeddings);
}
}
private static SparseEmbeddingResults.Embedding parseExpansionResult(boolean[] truncationResults, XContentParser parser, int index)
throws IOException {
XContentParser.Token token = parser.currentToken();
ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser);
List<WeightedToken> weightedTokens = new ArrayList<>();
token = parser.nextToken();
while (token != null && token != XContentParser.Token.END_OBJECT) {
ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser);
var floatToken = parser.nextToken();
ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, floatToken, parser);
weightedTokens.add(new WeightedToken(parser.currentName(), parser.floatValue()));
token = parser.nextToken();
}
// prevent an out of bounds if for some reason the truncation list is smaller than the results
var isTruncated = truncationResults != null && index < truncationResults.length && truncationResults[index];
return new SparseEmbeddingResults.Embedding(weightedTokens, isTruncated);
}
private HuggingFaceElserResponseEntity() {}
}
| HuggingFaceElserResponseEntity |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/runtime/AbstractScriptFieldQuery.java | {
"start": 1393,
"end": 5328
} | class ____<S extends AbstractFieldScript> extends Query {
/**
* We don't have the infrastructure to estimate the match cost of a script
* so we just use a big number.
*/
protected static final float MATCH_COST = 9000f;
private final Script script;
private final String fieldName;
private final Function<LeafReaderContext, S> scriptContextFunction;
protected AbstractScriptFieldQuery(Script script, String fieldName, Function<LeafReaderContext, S> scriptContextFunction) {
this.script = Objects.requireNonNull(script);
this.fieldName = Objects.requireNonNull(fieldName);
this.scriptContextFunction = scriptContextFunction;
}
final Function<LeafReaderContext, S> scriptContextFunction() {
return scriptContextFunction;
}
public final Script script() {
return script;
}
public final String fieldName() {
return fieldName;
}
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
return new ConstantScoreWeight(this, boost) {
@Override
public boolean isCacheable(LeafReaderContext ctx) {
return false; // scripts aren't really cacheable at this point
}
@Override
public ScorerSupplier scorerSupplier(LeafReaderContext ctx) throws IOException {
S scriptContext = scriptContextFunction.apply(ctx);
DocIdSetIterator approximation = DocIdSetIterator.all(ctx.reader().maxDoc());
Scorer scorer = new ConstantScoreScorer(score(), scoreMode, createTwoPhaseIterator(scriptContext, approximation));
return new DefaultScorerSupplier(scorer);
}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
Explanation constantExplanation = super.explain(context, doc);
if (constantExplanation.isMatch()) {
return explainMatch(boost, constantExplanation.getDescription());
}
return constantExplanation;
}
};
}
/**
* Creates the {@link TwoPhaseIterator} for the current leaf reader. Override to inject custom behaviour or provide
* additional context to the matches method when needed.
*/
protected TwoPhaseIterator createTwoPhaseIterator(S scriptContext, DocIdSetIterator approximation) {
return new TwoPhaseIterator(approximation) {
@Override
public boolean matches() {
return AbstractScriptFieldQuery.this.matches(scriptContext, approximation.docID());
}
@Override
public float matchCost() {
return MATCH_COST;
}
};
}
protected abstract boolean matches(S scriptContext, int docId);
@Override
public int hashCode() {
return Objects.hash(classHash(), script, fieldName);
}
@Override
public boolean equals(Object obj) {
if (sameClassAs(obj) == false) {
return false;
}
AbstractScriptFieldQuery<?> other = (AbstractScriptFieldQuery<?>) obj;
return script.equals(other.script) && fieldName.equals(other.fieldName);
}
@Override
public void visit(QueryVisitor visitor) {
if (visitor.acceptField(fieldName)) {
visitor.visitLeaf(this);
}
}
static Explanation explainMatch(float boost, String description) {
return Explanation.match(
boost,
description,
Explanation.match(
boost,
"boost * runtime_field_score",
Explanation.match(boost, "boost"),
Explanation.match(1.0, "runtime_field_score is always 1")
)
);
}
}
| AbstractScriptFieldQuery |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/ai/remote/response/ReleaseAgentCardResponse.java | {
"start": 850,
"end": 902
} | class ____ extends Response {
}
| ReleaseAgentCardResponse |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/DataInputViewStreamTest.java | {
"start": 2385,
"end": 2674
} | class ____ extends InputStream {
long skipped = 0;
@Override
public int read() throws IOException {
return 0;
}
@Override
public long skip(long n) {
skipped += n;
return n;
}
}
}
| TestInputStream |
java | junit-team__junit5 | junit-platform-commons/src/main/java/org/junit/platform/commons/support/AnnotationSupport.java | {
"start": 11987,
"end": 12655
} | class ____ the repeatable annotation
* is {@link java.lang.annotation.Inherited @Inherited}, this method will
* search on superclasses first in order to support top-down semantics.
* The result is that this algorithm finds repeatable annotations that
* would be <em>shadowed</em> and therefore not visible according to Java's
* standard semantics for inherited, repeatable annotations, but most
* developers will naturally assume that all repeatable annotations in JUnit
* are discovered regardless of whether they are declared stand-alone, in a
* container, or as a meta-annotation (e.g., multiple declarations of
* {@code @ExtendWith} within a test | and |
java | spring-projects__spring-boot | core/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/UriBuilderFactoryWebConnectionHtmlUnitDriver.java | {
"start": 1121,
"end": 2537
} | class ____ extends WebConnectionHtmlUnitDriver {
private final UriBuilderFactory uriBuilderFactory;
public UriBuilderFactoryWebConnectionHtmlUnitDriver(UriBuilderFactory uriBuilderFactory) {
Assert.notNull(uriBuilderFactory, "'uriBuilderFactory' must not be null");
this.uriBuilderFactory = uriBuilderFactory;
}
public UriBuilderFactoryWebConnectionHtmlUnitDriver(UriBuilderFactory uriBuilderFactory, boolean enableJavascript) {
super(enableJavascript);
Assert.notNull(uriBuilderFactory, "'uriBuilderFactory' must not be null");
this.uriBuilderFactory = uriBuilderFactory;
}
public UriBuilderFactoryWebConnectionHtmlUnitDriver(UriBuilderFactory uriBuilderFactory,
BrowserVersion browserVersion) {
super(browserVersion);
Assert.notNull(uriBuilderFactory, "'uriBuilderFactory' must not be null");
this.uriBuilderFactory = uriBuilderFactory;
}
public UriBuilderFactoryWebConnectionHtmlUnitDriver(UriBuilderFactory uriBuilderFactory,
Capabilities capabilities) {
super(capabilities);
Assert.notNull(uriBuilderFactory, "'uriBuilderFactory' must not be null");
this.uriBuilderFactory = uriBuilderFactory;
}
@Override
@SuppressWarnings("ConstantValue") // default constructor calls this method
public void get(String url) {
super.get((this.uriBuilderFactory != null) ? this.uriBuilderFactory.uriString(url).toUriString() : url);
}
}
| UriBuilderFactoryWebConnectionHtmlUnitDriver |
java | google__guice | core/test/com/google/inject/BinderTestSuite.java | {
"start": 15931,
"end": 16670
} | class ____ extends TestCase {
final String name;
final Key<?> key;
final ImmutableList<Module> modules;
final String creationException;
public CreationExceptionTest(Builder builder) {
super("test");
name = builder.name;
key = builder.key;
modules = ImmutableList.copyOf(builder.modules);
creationException = builder.creationException;
}
@Override
public String getName() {
return "creation errors:" + name;
}
public void test() {
try {
Guice.createInjector(modules);
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(), creationException);
}
}
}
public static | CreationExceptionTest |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java | {
"start": 12944,
"end": 13412
} | class ____ extends BeanSerializerFactory {
protected DelegatingSerializerFactory(SerializerFactoryConfig config) {
super(config);
}
@Override
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType type) throws JsonMappingException {
if (type.getRawClass() == TestBeanSimple.class) {
return new TestBeanSimpleSerializer();
}
else {
return super.createSerializer(prov, type);
}
}
}
}
| DelegatingSerializerFactory |
java | apache__hadoop | hadoop-tools/hadoop-compat-bench/src/test/java/org/apache/hadoop/fs/compat/common/TestHdfsCompatShellCommand.java | {
"start": 1448,
"end": 2789
} | class ____ {
private HdfsCompatMiniCluster cluster;
@BeforeEach
public void runCluster() throws IOException {
this.cluster = new HdfsCompatMiniCluster();
this.cluster.start();
}
@AfterEach
public void shutdownCluster() {
this.cluster.shutdown();
this.cluster = null;
}
@Test
public void testDfsCompatibility() throws Exception {
final String uri = cluster.getUri() + "/tmp";
final Configuration conf = cluster.getConf();
HdfsCompatCommand cmd = new TestCommand(uri, conf);
cmd.initialize();
HdfsCompatReport report = cmd.apply();
assertEquals(3, report.getPassedCase().size());
assertEquals(0, report.getFailedCase().size());
show(conf, report);
}
@Test
public void testSkipCompatibility() throws Exception {
final String uri = cluster.getUri() + "/tmp";
final Configuration conf = cluster.getConf();
HdfsCompatCommand cmd = new TestSkipCommand(uri, conf);
cmd.initialize();
HdfsCompatReport report = cmd.apply();
assertEquals(2, report.getPassedCase().size());
assertEquals(0, report.getFailedCase().size());
show(conf, report);
}
private void show(Configuration conf, HdfsCompatReport report) throws IOException {
new HdfsCompatTool(conf).printReport(report, System.out);
}
private static final | TestHdfsCompatShellCommand |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/checker/AsyncChecker.java | {
"start": 1197,
"end": 1444
} | class ____ can be used to schedule an asynchronous check on a given
* {@link Checkable}. If the check is successfully scheduled then a
* {@link ListenableFuture} is returned.
*
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public | that |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ProcessTableFunctionTestUtils.java | {
"start": 22412,
"end": 23526
} | class ____ extends AppendProcessTableFunctionBase {
public void eval(Context ctx, @ArgumentHint({ROW_SEMANTIC_TABLE, REQUIRE_ON_TIME}) Row r) {
final TimeContext<Long> asLong = ctx.timeContext(Long.class);
final TimeContext<Instant> asInstant = ctx.timeContext(Instant.class);
final TimeContext<LocalDateTime> asLocalDateTime = ctx.timeContext(LocalDateTime.class);
// read
collectObjects(
String.format(
"Time (Long: %s, Instant: %s, LocalDateTime: %s), "
+ "Watermark (Long: %s, Instant: %s, LocalDateTime: %s)",
asLong.time(),
asInstant.time(),
asLocalDateTime.time(),
asLong.currentWatermark(),
asInstant.currentWatermark(),
asLocalDateTime.currentWatermark()));
}
}
/** Testing function. */
@SuppressWarnings("SameParameterValue")
public static | TimeConversionsFunction |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/cache/spi/entry/ReferenceCacheEntryImpl.java | {
"start": 490,
"end": 1530
} | class ____ at cache retrieval time
private final EntityPersister subclassPersister;
/**
* Constructs a ReferenceCacheEntryImpl
*
* @param reference The reference entity instance
* @param subclassPersister The specific subclass persister
*/
public ReferenceCacheEntryImpl(Object reference, EntityPersister subclassPersister) {
this.reference = reference;
this.subclassPersister = subclassPersister;
}
/**
* Provides access to the stored reference.
*
* @return The stored reference
*/
public Object getReference() {
return reference;
}
@Override
public boolean isReferenceEntry() {
return true;
}
@Override
public String getSubclass() {
return subclassPersister.getEntityName();
}
public EntityPersister getSubclassPersister() {
return subclassPersister;
}
@Override
public Object getVersion() {
// reference data cannot be versioned
return null;
}
@Override
public Serializable[] getDisassembledState() {
// reference data is not disassembled into the cache
return null;
}
}
| name |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/indices/InvalidIndexNameException.java | {
"start": 732,
"end": 1320
} | class ____ extends ElasticsearchException {
public InvalidIndexNameException(String name, String desc) {
super("Invalid index name [" + name + "], " + desc);
setIndex(name);
}
public InvalidIndexNameException(Index index, String name, String desc) {
super("Invalid index name [" + name + "], " + desc);
setIndex(index);
}
public InvalidIndexNameException(StreamInput in) throws IOException {
super(in);
}
@Override
public RestStatus status() {
return RestStatus.BAD_REQUEST;
}
}
| InvalidIndexNameException |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/script/StringFieldScript.java | {
"start": 848,
"end": 2853
} | class ____ extends AbstractFieldScript {
/**
* The maximum number of chars a script should be allowed to emit.
*/
public static final long MAX_CHARS = 1024 * 1024;
public static final ScriptContext<Factory> CONTEXT = newContext("keyword_field", Factory.class);
public static final StringFieldScript.Factory PARSE_FROM_SOURCE = new Factory() {
@Override
public LeafFactory newFactory(String field, Map<String, Object> params, SearchLookup lookup, OnScriptError onScriptError) {
return ctx -> new StringFieldScript(field, params, lookup, OnScriptError.FAIL, ctx) {
@Override
public void execute() {
emitFromSource();
}
};
}
@Override
public boolean isResultDeterministic() {
return true;
}
@Override
public boolean isParsedFromSource() {
return true;
}
};
public static Factory leafAdapter(Function<SearchLookup, CompositeFieldScript.LeafFactory> parentFactory) {
return (leafFieldName, params, searchLookup, onScriptError) -> {
CompositeFieldScript.LeafFactory parentLeafFactory = parentFactory.apply(searchLookup);
return (LeafFactory) ctx -> {
CompositeFieldScript compositeFieldScript = parentLeafFactory.newInstance(ctx);
return new StringFieldScript(leafFieldName, params, searchLookup, onScriptError, ctx) {
@Override
public void setDocument(int docId) {
compositeFieldScript.setDocument(docId);
}
@Override
public void execute() {
emitFromCompositeScript(compositeFieldScript);
}
};
};
};
}
@SuppressWarnings("unused")
public static final String[] PARAMETERS = {};
public | StringFieldScript |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/testsupport/BaseTestConsumerEx.java | {
"start": 1116,
"end": 6236
} | class ____<T, U extends BaseTestConsumerEx<T, U>>
extends BaseTestConsumer<T, U> {
protected int initialFusionMode;
protected int establishedFusionMode;
/**
* The optional tag associated with this test consumer.
* @since 2.0.7
*/
protected CharSequence tag;
/**
* Indicates that one of the awaitX method has timed out.
* @since 2.0.7
*/
protected boolean timeout;
public BaseTestConsumerEx() {
super();
}
/**
* Returns the last thread which called the onXXX methods of this TestObserver/TestSubscriber.
* @return the last thread which called the onXXX methods
*/
public final Thread lastThread() {
return lastThread;
}
// assertion methods
/**
* Assert that this TestObserver/TestSubscriber did not receive an onNext value which is equal to
* the given value with respect to null-safe Object.equals.
*
* <p>History: 2.0.5 - experimental
* @param value the value to expect not being received
* @return this
* @since 2.1
*/
@SuppressWarnings("unchecked")
public final U assertNever(T value) {
int s = values.size();
for (int i = 0; i < s; i++) {
T v = this.values.get(i);
if (Objects.equals(v, value)) {
throw fail("Value at position " + i + " is equal to " + valueAndClass(value) + "; Expected them to be different");
}
}
return (U) this;
}
/**
* Asserts that this TestObserver/TestSubscriber did not receive any onNext value for which
* the provided predicate returns true.
*
* <p>History: 2.0.5 - experimental
* @param valuePredicate the predicate that receives the onNext value
* and should return true for the expected value.
* @return this
* @since 2.1
*/
@SuppressWarnings("unchecked")
public final U assertNever(Predicate<? super T> valuePredicate) {
int s = values.size();
for (int i = 0; i < s; i++) {
T v = this.values.get(i);
try {
if (valuePredicate.test(v)) {
throw fail("Value at position " + i + " matches predicate " + valuePredicate.toString() + ", which was not expected.");
}
} catch (Throwable ex) {
throw ExceptionHelper.wrapOrThrow(ex);
}
}
return (U)this;
}
/**
* Assert that the TestObserver/TestSubscriber terminated (i.e., the terminal latch reached zero).
* @return this
*/
@SuppressWarnings("unchecked")
public final U assertTerminated() {
if (done.getCount() != 0) {
throw fail("Subscriber still running!");
}
long c = completions;
if (c > 1) {
throw fail("Terminated with multiple completions: " + c);
}
int s = errors.size();
if (s > 1) {
throw fail("Terminated with multiple errors: " + s);
}
if (c != 0 && s != 0) {
throw fail("Terminated with multiple completions and errors: " + c);
}
return (U)this;
}
/**
* Assert that the TestObserver/TestSubscriber has not terminated (i.e., the terminal latch is still non-zero).
* @return this
*/
@SuppressWarnings("unchecked")
public final U assertNotTerminated() {
if (done.getCount() == 0) {
throw fail("Subscriber terminated!");
}
return (U)this;
}
/**
* Assert that there is a single error and it has the given message.
* @param message the message expected
* @return this
*/
@SuppressWarnings("unchecked")
public final U assertErrorMessage(String message) {
int s = errors.size();
if (s == 0) {
throw fail("No errors");
} else
if (s == 1) {
Throwable e = errors.get(0);
String errorMessage = e.getMessage();
if (!Objects.equals(message, errorMessage)) {
throw fail("\nexpected: " + message + "\ngot: " + errorMessage
+ "; Error message differs");
}
} else {
throw fail("Multiple errors");
}
return (U)this;
}
/**
* Assert that the upstream signalled the specified values in order and then failed
* with a Throwable for which the provided predicate returns true.
* @param errorPredicate
* the predicate that receives the error Throwable
* and should return true for expected errors.
* @param values the expected values, asserted in order
* @return this
*/
@SafeVarargs
public final U assertFailure(Predicate<Throwable> errorPredicate, T... values) {
return assertSubscribed()
.assertValues(values)
.assertError(errorPredicate)
.assertNotComplete();
}
/**
* Assert that the upstream signalled the specified values in order,
* then failed with a specific | BaseTestConsumerEx |
java | resilience4j__resilience4j | resilience4j-rxjava2/src/main/java/io/github/resilience4j/micrometer/transformer/FlowableTimer.java | {
"start": 1328,
"end": 1925
} | class ____ extends AbstractSubscriber<T> {
private final Context context;
TimerSubscriber(Subscriber<? super T> downstreamObserver, Timer timer) {
super(downstreamObserver);
context = timer.createContext();
}
@Override
protected void hookOnError(Throwable e) {
context.onFailure(e);
}
@Override
protected void hookOnComplete() {
context.onSuccess();
}
@Override
protected void hookOnCancel() {
context.onSuccess();
}
}
}
| TimerSubscriber |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedNestedClassTest.java | {
"start": 1683,
"end": 1917
} | class ____ {}
}
""")
.doTest();
}
@Test
public void nonPrivateNestedClass_noWarning() {
compilationHelper
.addSourceLines(
"Test.java",
"""
| UnusedClass |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/MiniBatchStreamingJoinOperator.java | {
"start": 14623,
"end": 15396
} | class ____
extends MiniBatchStreamingJoinOperator {
public MiniBatchInnerJoinStreamOperator(MiniBatchStreamingJoinParameter parameter) {
super(parameter);
}
@Override
protected void processBundles(BufferBundle<?> leftBuffer, BufferBundle<?> rightBuffer)
throws Exception {
// process right
this.processSingleSideBundles(
rightBuffer, rightRecordStateView, leftRecordStateView, false);
// process left
this.processSingleSideBundles(
leftBuffer, leftRecordStateView, rightRecordStateView, true);
}
}
/** MiniBatch Left outer join operator. */
private static final | MiniBatchInnerJoinStreamOperator |
java | elastic__elasticsearch | libs/cli/src/main/java/org/elasticsearch/cli/ExitCodes.java | {
"start": 537,
"end": 1833
} | class ____ {
// please be extra careful when changing these as the values might be used in scripts,
// usages of which are not tracked by the IDE
public static final int OK = 0;
public static final int USAGE = 64; // command line usage error
public static final int DATA_ERROR = 65; // data format error
public static final int NO_INPUT = 66; // cannot open input
public static final int NO_USER = 67; // addressee unknown
public static final int NO_HOST = 68; // host name unknown
public static final int UNAVAILABLE = 69; // service unavailable
public static final int CODE_ERROR = 70; // internal software error
public static final int CANT_CREATE = 73; // can't create (user) output file
public static final int IO_ERROR = 74; // input/output error
public static final int TEMP_FAILURE = 75; // temp failure; user is invited to retry
public static final int PROTOCOL = 76; // remote error in protocol
public static final int NOPERM = 77; // permission denied
public static final int CONFIG = 78; // configuration error
public static final int NOOP = 80; // nothing to do
private ExitCodes() { /* no instance, just constants */ }
}
| ExitCodes |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_assertThat_with_DoubleStream_Test.java | {
"start": 985,
"end": 4211
} | class ____ {
private final DoubleStream intStream = DoubleStream.empty();
@Test
void should_create_Assert() {
Object assertions = assertThat(DoubleStream.of(823952.8, 1947230585.9));
assertThat(assertions).isNotNull();
}
@Test
void should_assert_on_size() {
assertThat(DoubleStream.empty()).isEmpty();
assertThat(DoubleStream.of(123.3, 5674.5, 363.4)).isNotEmpty()
.hasSize(3);
}
@Test
void isEqualTo_should_honor_comparing_the_same_mocked_stream() {
DoubleStream stream = mock();
assertThat(stream).isEqualTo(stream);
}
@Test
void stream_can_be_asserted_twice() {
DoubleStream names = DoubleStream.of(823952.8, 1947230585.9);
assertThat(names).containsExactly(823952.8, 1947230585.9)
.containsExactly(823952.8, 1947230585.9);
}
@Test
void should_not_consume_stream_when_asserting_non_null() {
DoubleStream stream = mock();
assertThat(stream).isNotNull();
verifyNoInteractions(stream);
}
@Test
void isInstanceOf_should_check_the_original_stream_without_consuming_it() {
DoubleStream stream = mock();
assertThat(stream).isInstanceOf(DoubleStream.class);
verifyNoInteractions(stream);
}
@Test
void isInstanceOfAny_should_check_the_original_stream_without_consuming_it() {
DoubleStream stream = mock();
assertThat(stream).isInstanceOfAny(DoubleStream.class, String.class);
verifyNoInteractions(stream);
}
@Test
void isOfAnyClassIn_should_check_the_original_stream_without_consuming_it() {
DoubleStream stream = mock();
assertThat(stream).isOfAnyClassIn(Double.class, stream.getClass());
}
@Test
void isExactlyInstanceOf_should_check_the_original_stream() {
// factory creates use internal classes
assertThat(intStream).isExactlyInstanceOf(intStream.getClass());
}
@Test
void isNotExactlyInstanceOf_should_check_the_original_stream() {
assertThat(intStream).isNotExactlyInstanceOf(DoubleStream.class);
Throwable error = catchThrowable(() -> assertThat(intStream).isNotExactlyInstanceOf(intStream.getClass()));
assertThat(error).isInstanceOf(AssertionError.class);
}
@Test
void isNotInstanceOf_should_check_the_original_stream() {
assertThat(intStream).isNotInstanceOf(String.class);
}
@Test
void isNotInstanceOfAny_should_check_the_original_stream() {
assertThat(intStream).isNotInstanceOfAny(Long.class, String.class);
}
@Test
void isNotOfAnyClassIn_should_check_the_original_stream() {
assertThat(intStream).isNotOfAnyClassIn(Long.class, String.class);
}
@Test
void isSameAs_should_check_the_original_stream_without_consuming_it() {
DoubleStream stream = mock();
assertThat(stream).isSameAs(stream);
verifyNoInteractions(stream);
}
@Test
void isNotSameAs_should_check_the_original_stream_without_consuming_it() {
DoubleStream stream = mock();
try {
assertThat(stream).isNotSameAs(stream);
} catch (AssertionError e) {
verifyNoInteractions(stream);
return;
}
Assertions.fail("Expected assertionError, because assert notSame on same stream.");
}
}
| Assertions_assertThat_with_DoubleStream_Test |
java | processing__processing4 | java/src/processing/mode/java/tweak/SketchParser.java | {
"start": 927,
"end": 28473
} | class ____ {
public List<List<ColorControlBox>> colorBoxes;
public List<List<Handle>> allHandles;
int intVarCount;
int floatVarCount;
final String varPrefix = "tweakmode";
String[] codeTabs;
boolean requiresComment;
List<ColorMode> colorModes;
List<List<Range>> scientificNotations;
// currently is used to ignore numbers in 'setup' and 'settings' functions
List<List<Range>> ignoreFunctions;
List<List<Range>> commentBlocks;
List<int[]> curlyScopes;
public SketchParser(String[] codeTabs, boolean requiresComment) {
this.codeTabs = codeTabs;
this.requiresComment = requiresComment;
intVarCount = 0;
floatVarCount = 0;
// get all comment blocks
commentBlocks = new ArrayList<>();
for (String code : codeTabs) {
commentBlocks.add(getCommentBlocks(code));
}
// add 'settings' and 'setup' to ignore list (to ignore all numbers there)
ignoreFunctions = new ArrayList<>();
Range settingsRange = getVoidFunctionRange(codeTabs[0], "settings");
Range setupRange = getVoidFunctionRange(codeTabs[0], "setup");
ignoreFunctions.add(Arrays.asList(settingsRange, setupRange));
//Add empty lists for the other tabs so we do not get an index out of bounds error later
for (int i = 0; i < codeTabs.length-1; i++) {
ignoreFunctions.add(new ArrayList<SketchParser.Range>());
}
// build curly scope for every character in the code
curlyScopes = new ArrayList<>();
for (String code : codeTabs) {
curlyScopes.add(getCurlyScopes(code));
}
// get all scientific notation (to ignore them)
scientificNotations = getAllScientificNotations();
// find, add, and sort all tweak-able numbers in the sketch
addAllNumbers();
// handle colors
colorModes = findAllColorModes();
//colorBoxes = new ArrayList[codeTabs.length];
createColorBoxes();
createColorBoxesForLights();
// If there is more than one color mode per context, allow only hex and
// webcolors in this context. Currently there is no notion of order of
// execution so we cannot know which color mode relate to a color.
handleMultipleColorModes();
}
private void addAllNumbers() {
allHandles = new ArrayList<>();
addAllDecimalNumbers();
addAllHexNumbers();
addAllWebColorNumbers();
for (List<Handle> handle : allHandles) {
//Collections.sort(allHandles[i], new HandleComparator());
Collections.sort(handle, new HandleComparator());
}
}
/**
* Get a list of all the numbers in this sketch
* @return
* list of all numbers in the sketch (excluding hexadecimals)
*/
private void addAllDecimalNumbers() {
// for every number found:
// save its type (int/float), name, value and position in code.
Pattern p = Pattern.compile("[\\[\\{<>(),\\t\\s\\+\\-\\/\\*^%!|&=?:~]\\d+(_+\\d+)*(\\.\\d+(_+\\d+)*)?"); // Matches any "delimiting" character, and then a decimal number.
for (int i = 0; i < codeTabs.length; i++) {
List<Handle> handles = new ArrayList<>();
allHandles.add(handles);
String c = codeTabs[i];
Matcher m = p.matcher(c);
while (m.find()) {
boolean forceFloat = false;
int start = m.start()+1;
int end = m.end();
if (isInRangeList(start, commentBlocks.get(i))) {
// ignore comments
continue;
}
if (isInRangeList(start, ignoreFunctions.get(i))) {
// ignore numbers in predefined functions
continue;
}
if (requiresComment) {
// only add numbers that have the "// tweak" comment in their line
if (!lineHasTweakComment(start, c)) {
continue;
}
}
// ignore scientific notation (e.g. 1e-6)
boolean found = false;
for (Range r : scientificNotations.get(i)) {
if (r.contains(start)) {
found=true;
break;
}
}
if (found) {
continue;
}
// remove any 'f' after the number
if (c.charAt(end) == 'f') {
forceFloat = true;
end++;
}
// if its a negative, include the '-' sign
if (c.charAt(start-1) == '-') {
if (isNegativeSign(start-2, c)) {
start--;
}
}
// special case for ignoring (0x...). will be handled later
if (c.charAt(m.end()) == 'x' ||
c.charAt(m.end()) == 'X') {
continue;
}
// special case for ignoring number inside a string ("")
if (isInsideString(start, c))
continue;
// beware of the global assignment (bug from 26.07.2013)
if (isGlobal(m.start(), i))
continue;
int line = countLines(c.substring(0, start)) - 1; // zero based
String value = c.substring(start, end).replace("_", "");
if (value.contains(".") || forceFloat) {
// consider this as a float
String name = varPrefix + "_float[" + floatVarCount +"]";
int decimalDigits = getNumDigitsAfterPoint(value);
handles.add(new Handle("float", name, floatVarCount, value, i, line, start, end, decimalDigits));
floatVarCount++;
} else {
// consider this as an int
String name = varPrefix + "_int[" + intVarCount +"]";
handles.add(new Handle("int", name, intVarCount, value, i, line, start, end, 0));
intVarCount++;
}
}
}
}
/**
* Get a list of all the hexadecimal numbers in the code
* @return
* list of all hexadecimal numbers in the sketch
*/
private void addAllHexNumbers() {
// for every number found:
// save its type (int/float), name, value and position in code.
Pattern p = Pattern.compile("[\\[\\{<>(),\\t\\s\\+\\-\\/\\*^%!|&=?:~]0x[A-Fa-f0-9]+(_+[A-Fa-f0-9]+)*");
for (int i = 0; i < codeTabs.length; i++) {
String c = codeTabs[i];
Matcher m = p.matcher(c);
while (m.find()) {
int start = m.start()+1;
int end = m.end();
if (isInRangeList(start, commentBlocks.get(i))) {
// ignore comments
continue;
}
if (isInRangeList(start, ignoreFunctions.get(i))) {
// ignore numbers in predefined functions
continue;
}
if (requiresComment) {
// only add numbers that have the "// tweak" comment in their line
if (!lineHasTweakComment(start, c)) {
continue;
}
}
// special case for ignoring number inside a string ("")
if (isInsideString(start, c)) {
continue;
}
// beware of the global assignment (bug from 26.07.2013)
if (isGlobal(m.start(), i)) {
continue;
}
int line = countLines(c.substring(0, start)) - 1; // zero based
String value = c.substring(start, end).replace("_", "");
String name = varPrefix + "_int[" + intVarCount + "]";
Handle handle;
try {
handle = new Handle("hex", name, intVarCount, value, i, line, start, end, 0);
}
catch (NumberFormatException e) {
// don't add this number
continue;
}
allHandles.get(i).add(handle);
intVarCount++;
}
}
}
/**
* Get a list of all the webcolors (#) numbers in the code
* list of all hexadecimal numbers in the sketch
*/
private void addAllWebColorNumbers() {
Pattern p = Pattern.compile("#([A-Fa-f0-9]{2})?[A-Fa-f0-9]{6}");
for (int i=0; i<codeTabs.length; i++)
{
String c = codeTabs[i];
Matcher m = p.matcher(c);
while (m.find())
{
int start = m.start();
int end = m.end();
if (isInRangeList(start, commentBlocks.get(i))) {
// ignore comments
continue;
}
if (isInRangeList(start, ignoreFunctions.get(i))) {
// ignore numbers in predefined functions
continue;
}
if (requiresComment) {
// only add numbers that have the "// tweak" comment in their line
if (!lineHasTweakComment(start, c)) {
continue;
}
}
// special case for ignoring number inside a string ("")
if (isInsideString(start, c)) {
continue;
}
// beware of the global assignment (bug from 26.07.2013)
if (isGlobal(m.start(), i)) {
continue;
}
int line = countLines(c.substring(0, start)) - 1; // zero based
String value = c.substring(start, end);
String name = varPrefix + "_int[" + intVarCount + "]";
Handle handle;
try {
handle = new Handle("webcolor", name, intVarCount, value, i, line, start, end, 0);
}
catch (NumberFormatException e) {
// don't add this number
continue;
}
allHandles.get(i).add(handle);
intVarCount++;
}
}
}
private ArrayList<ColorMode> findAllColorModes() {
ArrayList<ColorMode> modes = new ArrayList<>();
for (int i=0; i<codeTabs.length; i++) {
String tab = codeTabs[i];
int index = -1;
// search for a call to colorMode function
while ((index = tab.indexOf("colorMode", index+1)) > -1) {
// found colorMode at index
if (isInRangeList(index, commentBlocks.get(i))) {
// ignore comments
continue;
}
index += 9;
int parOpen = tab.indexOf('(', index);
if (parOpen < 0) {
continue;
}
int parClose = tab.indexOf(')', parOpen+1);
if (parClose < 0) {
continue;
}
// add this mode
String modeDesc = tab.substring(parOpen+1, parClose);
String context = getObject(index-9, tab);
modes.add(ColorMode.fromString(context, modeDesc));
}
}
return modes;
}
private void createColorBoxes() {
colorBoxes = new ArrayList<>();
// search tab for the functions: 'color', 'fill', 'stroke', 'background', 'tint'
Pattern p = Pattern.compile("color\\(|color\\s\\(|fill[\\(\\s]|stroke[\\(\\s]|background[\\(\\s]|tint[\\(\\s]");
for (int i = 0; i < codeTabs.length; i++) {
List<ColorControlBox> colorBox = new ArrayList<>();
colorBoxes.add(colorBox);
String tab = codeTabs[i];
Matcher m = p.matcher(tab);
while (m.find()) {
ArrayList<Handle> colorHandles = new ArrayList<>();
// look for the '(' and ')' positions
int openPar = tab.indexOf("(", m.start());
int closePar = tab.indexOf(")", m.end());
if (openPar < 0 || closePar < 0) {
// ignore this color
continue;
}
if (isInRangeList(m.start(), commentBlocks.get(i))) {
// ignore colors in a comment
continue;
}
if (isInRangeList(m.start(), ignoreFunctions.get(i))) {
// ignore numbers in predefined functions
continue;
}
// look for handles inside the parenthesis
for (Handle handle : allHandles.get(i)) {
if (handle.startChar > openPar &&
handle.endChar <= closePar) {
// we have a match
colorHandles.add(handle);
}
}
if (colorHandles.size() > 0) {
/* make sure there is no other stuff between '()' like variables.
* subtract all handle values from string inside parenthesis and
* check there is no garbage left
*/
String insidePar = tab.substring(openPar+1, closePar);
for (Handle h : colorHandles) {
insidePar = insidePar.replaceFirst(h.strValue, "");
}
// make sure there is only ' ' and ',' left in the string.
boolean garbage = false;
for (int j=0; j<insidePar.length(); j++) {
if (insidePar.charAt(j) != ' ' && insidePar.charAt(j) != ',') {
// don't add this color box because we can not know the
// real value of this color
garbage = true;
}
}
// create a new color box
if (!garbage) {
// find the context of the color (e.g. this.fill() or <object>.fill())
String context = getObject(m.start(), tab);
ColorMode cmode = getColorModeForContext(context);
// not adding color operations for modes we couldn't understand
ColorControlBox newCCB = new ColorControlBox(context, cmode, colorHandles);
if (cmode.unrecognizedMode) {
// the color mode is unrecognizable add only if is a hex or webcolor
if (newCCB.isHex) {
colorBox.add(newCCB);
}
} else {
colorBox.add(newCCB);
}
}
}
}
}
}
private void createColorBoxesForLights() {
// search code for light color and material color functions.
Pattern p = Pattern.compile("ambientLight[\\(\\s]|directionalLight[\\(\\s]"+
"|pointLight[\\(\\s]|spotLight[\\(\\s]|lightSpecular[\\(\\s]"+
"|specular[\\(\\s]|ambient[\\(\\s]|emissive[\\(\\s]");
for (int i=0; i<codeTabs.length; i++) {
String tab = codeTabs[i];
Matcher m = p.matcher(tab);
while (m.find()) {
ArrayList<Handle> colorHandles = new ArrayList<>();
// look for the '(' and ')' positions
int openPar = tab.indexOf("(", m.start());
int closePar = tab.indexOf(")", m.end());
if (openPar < 0 || closePar < 0) {
// ignore this color
continue;
}
if (isInRangeList(m.start(), commentBlocks.get(i))) {
// ignore colors in a comment
continue;
}
if (isInRangeList(m.start(), ignoreFunctions.get(i))) {
// ignore numbers in predefined functions
continue;
}
// put 'colorParamsEnd' after three parameters inside the parenthesis or at the close
int colorParamsEnd = openPar;
int commas=3;
while (commas-- > 0) {
colorParamsEnd=tab.indexOf(",", colorParamsEnd+1);
if (colorParamsEnd < 0 ||
colorParamsEnd > closePar) {
colorParamsEnd = closePar;
break;
}
}
for (Handle handle : allHandles.get(i)) {
if (handle.startChar > openPar &&
handle.endChar <= colorParamsEnd) {
// we have a match
colorHandles.add(handle);
}
}
if (colorHandles.size() > 0) {
/* make sure there is no other stuff between '()' like variables.
* subtract all handle values from string inside parenthesis and
* check there is no garbage left
*/
String insidePar = tab.substring(openPar+1, colorParamsEnd);
for (Handle h : colorHandles) {
insidePar = insidePar.replaceFirst(h.strValue, "");
}
// make sure there is only ' ' and ',' left in the string.
boolean garbage = false;
for (int j=0; j<insidePar.length(); j++) {
if (insidePar.charAt(j) != ' ' && insidePar.charAt(j) != ',') {
// don't add this color box because we can not know the
// real value of this color
garbage = true;
}
}
// create a new color box
if (!garbage) {
// find the context of the color (e.g. this.fill() or <object>.fill())
String context = getObject(m.start(), tab);
ColorMode cmode = getColorModeForContext(context);
// not adding color operations for modes we couldn't understand
ColorControlBox newCCB = new ColorControlBox(context, cmode, colorHandles);
if (cmode.unrecognizedMode) {
// the color mode is unrecognizable add only if is a hex or webcolor
if (newCCB.isHex) {
colorBoxes.get(i).add(newCCB);
}
} else {
colorBoxes.get(i).add(newCCB);
}
}
}
}
}
}
private ColorMode getColorModeForContext(String context) {
for (ColorMode cm: colorModes) {
if (cm.drawContext.equals(context)) {
return cm;
}
}
// if none found, create the default color mode for this context and return it
ColorMode newMode = new ColorMode(context);
colorModes.add(newMode);
return newMode;
}
private void handleMultipleColorModes() {
// count how many color modes per context
Map<String, Integer> modeCount = new HashMap<>();
for (ColorMode cm : colorModes) {
Integer prev = modeCount.get(cm.drawContext);
if (prev == null) {
prev = 0;
}
modeCount.put(cm.drawContext, prev+1);
}
// find the contexts that have more than one color mode
ArrayList<String> multipleContexts = new ArrayList<>();
Set<String> allContexts = modeCount.keySet();
for (String context : allContexts) {
if (modeCount.get(context) > 1) {
multipleContexts.add(context);
}
}
// keep only hex and web color boxes in color calls
// that belong to 'multipleContexts' contexts
for (int i = 0; i < codeTabs.length; i++) {
List<ColorControlBox> toDelete = new ArrayList<>();
for (String context : multipleContexts) {
for (ColorControlBox ccb : colorBoxes.get(i)) {
if (ccb.drawContext.equals(context) && !ccb.isHex) {
toDelete.add(ccb);
}
}
}
colorBoxes.get(i).removeAll(toDelete);
}
}
private List<List<Range>> getAllScientificNotations() {
List<List<Range>> notations = new ArrayList<>();
Pattern p = Pattern.compile("[+\\-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?[eE][+\\-]?\\d+");
for (String code : codeTabs) {
List<Range> notation = new ArrayList<>();
Matcher m = p.matcher(code);
while (m.find()) {
notation.add(new Range(m.start(), m.end()));
}
notations.add(notation);
}
return notations;
}
static public boolean containsTweakComment(String[] codeTabs) {
for (String tab : codeTabs) {
if (hasTweakComment(tab)) {
return true;
}
}
return false;
}
static private boolean lineHasTweakComment(int pos, String code) {
int lineEnd = getEndOfLine(pos, code);
if (lineEnd < 0) {
return false;
}
String line = code.substring(pos, lineEnd);
return hasTweakComment(line);
}
static private boolean hasTweakComment(String code) {
// https://github.com/processing/processing/issues/3742
return code.contains("/// tweak");
/*
Pattern p = Pattern.compile("\\/\\/.*tweak", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(code);
return m.find();
*/
}
static private boolean isNegativeSign(int pos, String code) {
// go back and look for ,{[(=?+-/*%<>:&|^!~
for (int i = pos; i >= 0; i--) {
char c = code.charAt(i);
if (c != ' ' && c != '\t') {
return (c==',' || c=='{' || c=='[' || c=='(' ||
c=='=' || c=='?' || c=='+' || c=='-' ||
c=='/' || c=='*' || c=='%' || c=='<' ||
c=='>' || c==':' || c=='&' || c=='|' ||
c=='^' || c=='!' || c=='~');
}
}
return false;
}
static private int getNumDigitsAfterPoint(String number) {
Pattern p = Pattern.compile("\\.[0-9]+");
Matcher m = p.matcher(number);
if (m.find()) {
return m.end() - m.start() - 1;
}
return 0;
}
static private int countLines(String str) {
String[] lines = str.split("\r\n|\n\r|\n|\r");
return lines.length;
}
/**
* Are we inside a string? (TODO: ignore comments in the code)
* @param pos
* position in the code
* @param code
* the code
* @return
*/
static private boolean isInsideString(int pos, String code) {
int quoteNum = 0; // count '"'
for (int c = pos; c>=0 && code.charAt(c) != '\n'; c--) {
if (code.charAt(c) == '"') {
quoteNum++;
}
}
if (quoteNum%2 == 1) {
return true;
}
return false;
}
/**
* Builds an int array for every tab that represents
* the scope depth at each character.
*/
static private int[] getCurlyScopes(String code) {
List<Range> comments = getCommentBlocks(code);
int[] scopes = new int[code.length()];
int curlyScope = 0;
boolean arrayAssignmentMaybeCommingFlag = false;
int arrayAssignmentCurlyScope = 0;
for (int pos=0; pos<code.length(); pos++) {
scopes[pos] = curlyScope;
if (isInRangeList(pos, comments)) {
// we are inside a comment, ignore and move on
continue;
}
if (code.charAt(pos) == '{') {
if (arrayAssignmentMaybeCommingFlag ||
arrayAssignmentCurlyScope>0) {
// this is an array assignment
arrayAssignmentCurlyScope++;
arrayAssignmentMaybeCommingFlag = false;
}
else {
curlyScope++;
}
}
else if (code.charAt(pos) == '}') {
if (arrayAssignmentCurlyScope>0) {
arrayAssignmentCurlyScope--;
}
else {
curlyScope--;
}
}
else if (code.charAt(pos) == '=') {
arrayAssignmentMaybeCommingFlag = true;
}
else if (!isWhiteSpace(code.charAt(pos))) {
arrayAssignmentMaybeCommingFlag = false;
}
}
return scopes;
}
static private boolean isWhiteSpace(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
/**
* Is this a global position?
* @param pos position
* @param codeTabIndex index of the code in codeTabs
* @return true if the position 'pos' is in global scope
* in the code 'codeTabs[codeTabIndex]'
*
*/
private boolean isGlobal(int pos, int codeTabIndex) {
return (curlyScopes.get(codeTabIndex)[pos]==0);
};
static private List<Range> getCommentBlocks(String code) {
List<Range> commentBlocks = new ArrayList<>();
int lastBlockStart=0;
boolean lookForEnd = false;
for (int pos=0; pos<code.length()-1; pos++) {
if (lookForEnd) {
// we have a start, look for the end
if (code.charAt(pos) == '*' && code.charAt(pos+1) == '/') {
commentBlocks.add(new Range(lastBlockStart, pos+1));
lookForEnd = false;
}
}
else {
if (code.charAt(pos) == '/' && code.charAt(pos+1) == '*') {
// we found a block start
lastBlockStart = pos;
lookForEnd = true;
}
else if (code.charAt(pos) == '/' && code.charAt(pos+1) == '/') {
// we found a line comment
commentBlocks.add(new Range(pos, getEndOfLine(pos, code)));
}
}
}
return commentBlocks;
}
static private boolean isInRangeList(int pos, List<Range> rangeList) {
for (Range r : rangeList) {
if (r.contains(pos)) {
return true;
}
}
return false;
}
static private int getEndOfLine(int pos, String code) {
return code.indexOf("\n", pos);
}
/**
* returns the object name (what comes before the '.')
* of the function starting at 'pos'
*/
static private String getObject(int pos, String code) {
boolean readObject = false;
String obj = "this";
while (pos-- >= 0) {
if (code.charAt(pos) == '.') {
if (!readObject) {
obj = "";
readObject = true;
}
else {
break;
}
}
else if (code.charAt(pos) == ' ' || code.charAt(pos) == '\t') {
break;
}
else if (readObject) {
obj = code.charAt(pos) + obj;
}
}
return obj;
}
static public Range getVoidFunctionRange(String code, String functionName) {
return new Range(getVoidFunctionStart(code, functionName),
getVoidFunctionEnd(code, functionName));
}
static public int getVoidFunctionStart(String code, String functionName) {
Pattern p = Pattern.compile("void[\\s\\t\\r\\n]*"+functionName+"[\\s\\t]*\\(\\)[\\s\\t\\r\\n]*\\{");
Matcher m = p.matcher(code);
if (m.find()) {
return m.end();
}
return -1;
}
static public int getVoidFunctionEnd(String code, String functionName) {
List<Range> comments = getCommentBlocks(code);
int start = getVoidFunctionStart(code, functionName);
if (start == -1) {
return -1;
}
// count brackets to look for setup end
int bracketCount=1;
int pos = start;
while (bracketCount > 0 && pos < code.length()) {
if (isInRangeList(pos, comments)) {
// in a comment, ignore and move on
pos++;
continue;
}
if (code.charAt(pos) == '{') {
bracketCount++;
}
else if (code.charAt(pos) == '}') {
bracketCount--;
}
pos++;
}
if (bracketCount == 0) {
return pos-1;
}
return -1;
}
static public int getSetupStart(String code) {
Pattern p = Pattern.compile("void[\\s\\t\\r\\n]*setup[\\s\\t]*\\(\\)[\\s\\t\\r\\n]*\\{");
Matcher m = p.matcher(code);
if (m.find()) {
return m.end();
}
return -1;
}
static public int getSetupEnd(String code) {
List<Range> comments = getCommentBlocks(code);
int setupStart = getSetupStart(code);
if (setupStart == -1) {
return -1;
}
// count brackets to look for setup end
int bracketCount=1;
int pos = setupStart;
while (bracketCount > 0 && pos < code.length()) {
if (isInRangeList(pos, comments)) {
// in a comment, ignore and move on
pos++;
continue;
}
if (code.charAt(pos) == '{') {
bracketCount++;
}
else if (code.charAt(pos) == '}') {
bracketCount--;
}
pos++;
}
if (bracketCount == 0) {
return pos-1;
}
return -1;
}
static public int getAfterSizePos(String code) {
List<Range> comments = getCommentBlocks(code);
// find the size function
Pattern p = Pattern.compile("size[\\s\\t]*\\(");
Matcher m = p.matcher(code);
while (m.find()) {
if (isInRangeList(m.start(), comments) ||
isInRangeList(m.end(), comments)) {
// this is a comment, next
continue;
}
// count brackets to look for size call end
int bracketCount=1;
int pos = m.end();
while (bracketCount > 0 && pos < code.length()) {
if (isInRangeList(pos, comments)) {
// in a comment, ignore and move on
pos++;
continue;
}
if (code.charAt(pos) == '(') {
bracketCount++;
}
else if (code.charAt(pos) == ')') {
bracketCount--;
}
pos++;
}
if (bracketCount != 0) {
// could not find closing ')'. next
continue;
}
// find ';' sign
boolean found = false;
while (pos < code.length()) {
if (code.charAt(pos) == ';' &&
!isInRangeList(pos, comments)) {
found = true;
break;
}
pos++;
}
if (!found) {
// didn't find the ';'. next
continue;
}
// success! we found the place
return pos+1;
}
// nothing was found
return -1;
}
static | SketchParser |
java | reactor__reactor-core | reactor-test/src/main/java/reactor/test/ValueFormatters.java | {
"start": 1101,
"end": 1935
} | class ____ create {@link ToStringConverter} {@link Function} that convert objects to {@link String}.
* They can be applied to any {@link Object} but will restrict the types they actually
* convert by filtering and defaulting to {@link String#valueOf(Object)}.
* <p>
* Also defines {@link Extractor} {@link BiFunction} that extract multiple elements from
* containers and applies a {@link Function} (most probably a {@link ToStringConverter})
* to its elements, reforming a complete {@link String} representation. Again, this matches
* on at least a given {@link Class} and potentially an additional {@link Predicate}.
* <p>
* An additional static utility method {@link #convertVarArgs(ToStringConverter, Collection, Object...)} can
* be used to apply such functions and to varargs.
*
* @author Simon Baslé
*/
public final | to |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ProcessTableFunctionTestUtils.java | {
"start": 8303,
"end": 8565
} | class ____ extends ProcessTableFunction<Integer> {
public void eval(@ArgumentHint(SET_SEMANTIC_TABLE) Row r) {
collect(r.getFieldAs(1));
}
}
@DataTypeHint("ROW<`out` STRING>")
public abstract static | AtomicTypeWrappingFunction |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/TestDecompressorStream.java | {
"start": 1197,
"end": 3523
} | class ____ {
private static final String TEST_STRING =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private ByteArrayInputStream bytesIn;
private Decompressor decompressor;
private DecompressorStream decompressorStream;
@BeforeEach
public void setUp() throws IOException {
bytesIn = new ByteArrayInputStream(TEST_STRING.getBytes());
decompressor = new FakeDecompressor();
decompressorStream =
new DecompressorStream(bytesIn, decompressor, 20, 13);
}
@Test
public void testReadOneByte() throws IOException {
for (int i = 0; i < TEST_STRING.length(); ++i) {
assertThat(decompressorStream.read()).isEqualTo(TEST_STRING.charAt(i));
}
try {
int ret = decompressorStream.read();
fail("Not reachable but got ret " + ret);
} catch (EOFException e) {
// Expect EOF exception
}
}
@Test
public void testReadBuffer() throws IOException {
// 32 buf.length < 52 TEST_STRING.length()
byte[] buf = new byte[32];
int bytesToRead = TEST_STRING.length();
int i = 0;
while (bytesToRead > 0) {
int n = Math.min(bytesToRead, buf.length);
int bytesRead = decompressorStream.read(buf, 0, n);
assertTrue(bytesRead > 0 && bytesRead <= n);
assertThat(new String(buf, 0, bytesRead))
.isEqualTo(TEST_STRING.substring(i, i + bytesRead));
bytesToRead = bytesToRead - bytesRead;
i = i + bytesRead;
}
try {
int ret = decompressorStream.read(buf, 0, buf.length);
fail("Not reachable but got ret " + ret);
} catch (EOFException e) {
// Expect EOF exception
}
}
@Test
public void testSkip() throws IOException {
assertThat(decompressorStream.skip(12)).isEqualTo(12L);
assertThat(decompressorStream.read()).isEqualTo(TEST_STRING.charAt(12));
assertThat(decompressorStream.read()).isEqualTo(TEST_STRING.charAt(13));
assertThat(decompressorStream.read()).isEqualTo(TEST_STRING.charAt(14));
assertThat(decompressorStream.skip(10)).isEqualTo(10L);
assertThat(decompressorStream.read()).isEqualTo(TEST_STRING.charAt(25));
try {
long ret = decompressorStream.skip(1000);
fail("Not reachable but got ret " + ret);
} catch (EOFException e) {
// Expect EOF exception
}
}
} | TestDecompressorStream |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/repositories/blobstore/BlobStoreRepositoryOperationPurposeIT.java | {
"start": 2149,
"end": 4072
} | class ____ extends AbstractSnapshotIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return CollectionUtils.appendToCopy(super.nodePlugins(), TestPlugin.class);
}
public void testSnapshotOperationPurposes() throws Exception {
// Perform some simple operations on the repository in order to exercise the checks that the purpose is set correctly for various
// operations
final var repoName = randomIdentifier();
createRepository(repoName, TestPlugin.ASSERTING_REPO_TYPE);
final var count = between(1, 3);
for (int i = 0; i < count; i++) {
createIndexWithContent("index-" + i);
createFullSnapshot(repoName, "snap-" + i);
}
final var timeout = TimeValue.timeValueSeconds(10);
clusterAdmin().prepareCleanupRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repoName).get(timeout);
clusterAdmin().prepareCloneSnapshot(TEST_REQUEST_TIMEOUT, repoName, "snap-0", "clone-0").setIndices("index-0").get(timeout);
// restart to ensure that the reads which happen when starting a node on a nonempty repository use the expected purposes
internalCluster().fullRestart();
clusterAdmin().prepareGetSnapshots(TEST_REQUEST_TIMEOUT, repoName).get(timeout);
clusterAdmin().prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, repoName, "clone-0")
.setRenamePattern("index-0")
.setRenameReplacement("restored-0")
.setWaitForCompletion(true)
.get(timeout);
for (int i = 0; i < count; i++) {
assertTrue(startDeleteSnapshot(repoName, "snap-" + i).get(10, TimeUnit.SECONDS).isAcknowledged());
}
clusterAdmin().prepareDeleteRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repoName).get(timeout);
}
public static | BlobStoreRepositoryOperationPurposeIT |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java | {
"start": 114348,
"end": 115035
} | class ____ {
@ModelAttribute("testBeanList")
public List<TestBean> getTestBeans() {
List<TestBean> list = new ArrayList<>();
list.add(new TestBean("tb1"));
list.add(new TestBean("tb2"));
return list;
}
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
FieldError error = errors.getFieldError("age");
assertThat(error).as("Must have field error for age property").isNotNull();
assertThat(error.getRejectedValue()).isEqualTo("value2");
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
}
static | MyFormController |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AStorageClass.java | {
"start": 6605,
"end": 7373
} | class
____(dir);
Path path = new Path(dir, "file1");
ContractTestUtils.touch(fs, path);
assertObjectHasNoStorageClass(path);
Path path2 = new Path(dir, "file1");
fs.rename(path, path2);
assertObjectHasNoStorageClass(path2);
}
/*
* Verify object can be created and copied correctly
* with empty string configuration
*/
@Test
public void testCreateAndCopyObjectWithStorageClassEmpty() throws Throwable {
Configuration conf = this.createConfiguration();
conf.set(STORAGE_CLASS, "");
S3AContract contract = (S3AContract) createContract(conf);
contract.init();
FileSystem fs = contract.getTestFileSystem();
Path dir = methodPath();
fs.mkdirs(dir);
// even with storage | assertObjectHasNoStorageClass |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/MachineList.java | {
"start": 1462,
"end": 1697
} | class ____ {
public static final Logger LOG = LoggerFactory.getLogger(MachineList.class);
public static final String WILDCARD_VALUE = "*";
/**
* InetAddressFactory is used to obtain InetAddress from host.
* This | MachineList |
java | apache__camel | components/camel-aws/camel-aws-xray/src/test/java/org/apache/camel/component/aws/xray/ClientRecipientListRouteTest.java | {
"start": 1171,
"end": 3007
} | class ____ extends CamelAwsXRayTestSupport {
public ClientRecipientListRouteTest() {
super(
TestDataBuilder.createTrace().inRandomOrder()
.withSegment(TestDataBuilder.createSegment("start")
.withSubsegment(TestDataBuilder.createSubsegment("seda:a"))
.withSubsegment(TestDataBuilder.createSubsegment("seda:b"))
.withSubsegment(TestDataBuilder.createSubsegment("seda:c")))
.withSegment(TestDataBuilder.createSegment("a"))
.withSegment(TestDataBuilder.createSegment("b"))
.withSegment(TestDataBuilder.createSegment("c")));
}
@Test
public void testRoute() {
NotifyBuilder notify = new NotifyBuilder(context).whenDone(7).create();
template.requestBody("direct:start", "Hello");
assertThat("Not all exchanges were fully processed",
notify.matches(5, TimeUnit.SECONDS), is(equalTo(true)));
verify();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").routeId("start")
.recipientList(constant("seda:a,seda:b,seda:c"));
from("seda:a").routeId("a")
.log("routing at ${routeId}");
from("seda:b").routeId("b")
.log("routing at ${routeId}")
.delay(simple("${random(1000,2000)}"));
from("seda:c").routeId("c")
.log("routing at ${routeId}")
.delay(simple("${random(0,100)}"));
}
};
}
}
| ClientRecipientListRouteTest |
java | apache__flink | flink-table/flink-table-code-splitter/src/main/java/org/apache/flink/table/codesplit/BlockStatementGrouper.java | {
"start": 12627,
"end": 15328
} | class ____ implements LocalGroupElement {
private final ParserRuleContext parserRuleContext;
private ContextGroupElement(ParserRuleContext parserRuleContext) {
this.parserRuleContext = parserRuleContext;
}
@Override
public Token getStart() {
return this.parserRuleContext.start;
}
@Override
public Token getStop() {
return this.parserRuleContext.stop;
}
@Override
public String getBody(TokenStreamRewriter rewriter) {
return rewriter.getText(this.parserRuleContext.getSourceInterval());
}
@Override
public ParserRuleContext getContext() {
return this.parserRuleContext;
}
}
/**
* Extracted element that is represented by {@link ParserRuleContext} and {@link
* TokenStreamRewriter} It's used for extracted block statements that represent TRUE/FALSE
* branches of IF/ELSE statements or WHILE's statement body. The string representation is
* extracted from {@link TokenStreamRewriter} which could be further rewritten.
*
* <p>This element can be used for IF/ELSE/WHILE statements that will be rewritten in further
* processing. Then this statement in the original code cen be rewritten using Start and Stop
* tokens, whereas the getBody() method backed by TokenStreamRewriter will return the rewritten
* value of the original statement.
*
* <p>The example would parserRuleContext and rewriter representing below statement:
*
* <pre><code>
* while (counter > 0) {
* myFun_whileBody0_0(a, b);
* if (a[0] > 0) {
* myFun_whileBody0_0_ifBody0(a, b);
* } else {
* myFun_whileBody0_0_ifBody1(a, b);
* }
*
* a[2] += b[2];
* b[3] += a[3];
* if (a[0] > 0) {
* System.out.println("Hello");
* } else {
* System.out.println("World");
* }
*
* counter--;
* }
* </code></pre>
*
* <p>This statement, being a part of a different statement will be further rewritten, new
* methods will be extracted from its body. At the end in order to rewrite the original
* statement we need to know what is the current form of this expression. For that we can call
* getBody() method, which in this case will return:
*
* <pre><code>
* while (counter > 0) {
* myFun_rewriteGroup0_1_rewriteGroup3(a, b);
*
* myFun_rewriteGroup0_1_rewriteGroup5(a, b);
*
* counter--;
* }
* </code></pre>
*/
private static | ContextGroupElement |
java | elastic__elasticsearch | modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java | {
"start": 44417,
"end": 44830
} | class ____ extends DummyAsyncBulkByScrollAction {
@Override
BackoffPolicy buildBackoffPolicy() {
return buildTestBackoffPolicy();
}
}
private BackoffPolicy buildTestBackoffPolicy() {
// Force a backoff time of 0 to prevent sleeping
return constantBackoff(timeValueMillis(0), testRequest.getMaxRetries());
}
private static | DummyActionWithoutBackoff |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/SetGenerators.java | {
"start": 5245,
"end": 5566
} | class ____ extends TestStringSortedSetGenerator {
@Override
protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("zzz");
return ImmutableSortedSet.copyOf(list).headSet("zzy");
}
}
public static | ImmutableSortedSetHeadsetGenerator |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java | {
"start": 21093,
"end": 21258
} | class ____ extends ParentClass {
public Foo() {
}
public Foo(String parentProperty) {
super(parentProperty);
}
}
@JsonTypeName("bar")
public static | Foo |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/file/TestingPartitionFileReader.java | {
"start": 3151,
"end": 4192
} | class ____ {
private BiFunction<Integer, Integer, ReadBufferResult> readBufferSupplier =
(bufferIndex, segmentId) -> null;
private Function<Integer, Long> prioritySupplier = bufferIndex -> 0L;
private Runnable releaseNotifier = () -> {};
public Builder setReadBufferSupplier(
BiFunction<Integer, Integer, ReadBufferResult> readBufferSupplier) {
this.readBufferSupplier = readBufferSupplier;
return this;
}
public Builder setPrioritySupplier(Function<Integer, Long> prioritySupplier) {
this.prioritySupplier = prioritySupplier;
return this;
}
public Builder setReleaseNotifier(Runnable releaseNotifier) {
this.releaseNotifier = releaseNotifier;
return this;
}
public TestingPartitionFileReader build() {
return new TestingPartitionFileReader(
readBufferSupplier, prioritySupplier, releaseNotifier);
}
}
}
| Builder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.