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 | quarkusio__quarkus | extensions/jaxb/deployment/src/main/java/io/quarkus/jaxb/deployment/FilteredJaxbClassesToBeBoundBuildItem.java | {
"start": 1003,
"end": 1772
} | class ____ {
private final Set<String> classNames = new LinkedHashSet<>();
private final Set<Predicate<String>> classNamePredicateExcludes = new LinkedHashSet<>();
public Builder classNameExcludes(Collection<String> classNameExcludes) {
final String packMatch = ".*";
for (String classNameExclude : classNameExcludes) {
if (classNameExclude.endsWith(packMatch)) {
// Package ends with ".*"
final String packageName = classNameExclude.substring(0, classNameExclude.length() - packMatch.length());
this.classNamePredicateExcludes.add((className) -> className.startsWith(packageName));
} else {
// Standard | Builder |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/MapKeyJoinColumnsJpaAnnotation.java | {
"start": 721,
"end": 2394
} | class ____ implements MapKeyJoinColumns, RepeatableContainer<MapKeyJoinColumn> {
private jakarta.persistence.MapKeyJoinColumn[] value;
private jakarta.persistence.ForeignKey foreignKey;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public MapKeyJoinColumnsJpaAnnotation(ModelsContext modelContext) {
this.foreignKey = JpaAnnotations.FOREIGN_KEY.createUsage( modelContext );
}
/**
* Used in creating annotation instances from JDK variant
*/
public MapKeyJoinColumnsJpaAnnotation(MapKeyJoinColumns annotation, ModelsContext modelContext) {
this.value = extractJdkValue( annotation, JpaAnnotations.MAP_KEY_JOIN_COLUMNS, "value", modelContext );
this.foreignKey = extractJdkValue(
annotation,
JpaAnnotations.MAP_KEY_JOIN_COLUMNS,
"foreignKey",
modelContext
);
}
/**
* Used in creating annotation instances from Jandex variant
*/
public MapKeyJoinColumnsJpaAnnotation(
Map<String, Object> attributeValues,
ModelsContext modelContext) {
this.value = (MapKeyJoinColumn[]) attributeValues.get( "value" );
this.foreignKey = (jakarta.persistence.ForeignKey) attributeValues.get( "foreignKey" );
}
@Override
public Class<? extends Annotation> annotationType() {
return MapKeyJoinColumns.class;
}
@Override
public jakarta.persistence.MapKeyJoinColumn[] value() {
return value;
}
public void value(jakarta.persistence.MapKeyJoinColumn[] value) {
this.value = value;
}
@Override
public jakarta.persistence.ForeignKey foreignKey() {
return foreignKey;
}
public void foreignKey(jakarta.persistence.ForeignKey value) {
this.foreignKey = value;
}
}
| MapKeyJoinColumnsJpaAnnotation |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/rest/RestDefinition.java | {
"start": 2543,
"end": 32206
} | class ____ extends OptionalIdentifiedDefinition<RestDefinition> implements ResourceAware {
public static final String MISSING_VERB = "Must add verb first, such as get/post/delete";
@XmlAttribute
private String path;
@XmlAttribute
private String consumes;
@XmlAttribute
private String produces;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String disabled;
@XmlAttribute
@Metadata(defaultValue = "off", enums = "off,auto,json,xml,json_xml")
private String bindingMode;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String skipBindingOnErrorCode;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String clientRequestValidation;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String clientResponseValidation;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String enableCORS;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String enableNoContentResponse;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "true")
private String apiDocs;
@XmlAttribute
@Metadata(label = "advanced")
private String tag;
@XmlElement
private OpenApiDefinition openApi;
@XmlElement(name = "securityDefinitions") // use the name Swagger/OpenAPI uses
@Metadata(label = "security")
private RestSecuritiesDefinition securityDefinitions;
@XmlElement
@Metadata(label = "security")
private List<SecurityDefinition> securityRequirements = new ArrayList<>();
@XmlElementRef
private List<VerbDefinition> verbs = new ArrayList<>();
@XmlTransient
private Resource resource;
@Override
public String getShortName() {
return "rest";
}
@Override
public String getLabel() {
return "rest";
}
public String getPath() {
return path;
}
/**
* Path of the rest service, such as "/foo"
*/
public void setPath(String path) {
this.path = path;
}
public String getTag() {
return tag;
}
/**
* To configure a special tag for the operations within this rest definition.
*/
public void setTag(String tag) {
this.tag = tag;
}
public String getConsumes() {
return consumes;
}
/**
* To define the content type what the REST service consumes (accept as input), such as application/xml or
* application/json. This option will override what may be configured on a parent level
*/
public void setConsumes(String consumes) {
this.consumes = consumes;
}
public String getProduces() {
return produces;
}
/**
* To define the content type what the REST service produces (uses for output), such as application/xml or
* application/json This option will override what may be configured on a parent level
*/
public void setProduces(String produces) {
this.produces = produces;
}
public String getDisabled() {
return disabled;
}
/**
* Whether to disable this REST service from the route during build time. Once an REST service has been disabled
* then it cannot be enabled later at runtime.
*/
public void setDisabled(String disabled) {
this.disabled = disabled;
}
public String getBindingMode() {
return bindingMode;
}
/**
* Sets the binding mode to use. This option will override what may be configured on a parent level
* <p/>
* The default value is auto
*/
public void setBindingMode(String bindingMode) {
this.bindingMode = bindingMode;
}
public List<VerbDefinition> getVerbs() {
return verbs;
}
public RestSecuritiesDefinition getSecurityDefinitions() {
return securityDefinitions;
}
/**
* Sets the security definitions such as Basic, OAuth2 etc.
*/
public void setSecurityDefinitions(RestSecuritiesDefinition securityDefinitions) {
this.securityDefinitions = securityDefinitions;
}
public List<SecurityDefinition> getSecurityRequirements() {
return securityRequirements;
}
/**
* Sets the security requirement(s) for all endpoints.
*/
public void setSecurityRequirements(List<SecurityDefinition> securityRequirements) {
this.securityRequirements = securityRequirements;
}
/**
* The HTTP verbs this REST service accepts and uses
*/
public void setVerbs(List<VerbDefinition> verbs) {
this.verbs = verbs;
}
public String getSkipBindingOnErrorCode() {
return skipBindingOnErrorCode;
}
/**
* Whether to skip binding on output if there is a custom HTTP error code header. This allows to build custom error
* messages that do not bind to json / xml etc, as success messages otherwise will do. This option will override
* what may be configured on a parent level
*/
public void setSkipBindingOnErrorCode(String skipBindingOnErrorCode) {
this.skipBindingOnErrorCode = skipBindingOnErrorCode;
}
public String getClientRequestValidation() {
return clientRequestValidation;
}
/**
* Whether to enable validation of the client request to check:
* <p>
* 1) Content-Type header matches what the Rest DSL consumes; returns HTTP Status 415 if validation error. 2) Accept
* header matches what the Rest DSL produces; returns HTTP Status 406 if validation error. 3) Missing required data
* (query parameters, HTTP headers, body); returns HTTP Status 400 if validation error. 4) Parsing error of the
* message body (JSon, XML or Auto binding mode must be enabled); returns HTTP Status 400 if validation error.
*/
public void setClientRequestValidation(String clientRequestValidation) {
this.clientRequestValidation = clientRequestValidation;
}
public String getClientResponseValidation() {
return clientResponseValidation;
}
/**
* Whether to check what Camel is returning as response to the client:
*
* 1) Status-code and Content-Type matches Rest DSL response messages. 2) Check whether expected headers is included
* according to the Rest DSL repose message headers. 3) If the response body is JSon then check whether its valid
* JSon. Returns 500 if validation error detected.
*/
public void setClientResponseValidation(String clientResponseValidation) {
this.clientResponseValidation = clientResponseValidation;
}
public String getEnableCORS() {
return enableCORS;
}
/**
* Whether to enable CORS headers in the HTTP response. This option will override what may be configured on a parent
* level
* <p/>
* The default value is false.
*/
public void setEnableCORS(String enableCORS) {
this.enableCORS = enableCORS;
}
public String getEnableNoContentResponse() {
return enableNoContentResponse;
}
/**
* Whether to return HTTP 204 with an empty body when a response contains an empty JSON object or XML root object.
* <p/>
* The default value is false.
*/
public void setEnableNoContentResponse(String enableNoContentResponse) {
this.enableNoContentResponse = enableNoContentResponse;
}
public String getApiDocs() {
return apiDocs;
}
/**
* Whether to include or exclude this rest operation in API documentation. This option will override what may be
* configured on a parent level.
* <p/>
* The default value is true.
*/
public void setApiDocs(String apiDocs) {
this.apiDocs = apiDocs;
}
public OpenApiDefinition getOpenApi() {
return openApi;
}
/**
* To use an existing OpenAPI specification as contract-first for Camel Rest DSL.
*/
public void setOpenApi(OpenApiDefinition openApi) {
this.openApi = openApi;
}
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
// Fluent API
// -------------------------------------------------------------------------
/**
* To use an existing OpenAPI specification as contract-first for Camel Rest DSL.
*/
public OpenApiDefinition openApi() {
openApi = new OpenApiDefinition();
openApi.setRest(this);
return openApi;
}
/**
* To use an existing OpenAPI specification as contract-first for Camel Rest DSL.
*/
public RestDefinition openApi(String specification) {
openApi = new OpenApiDefinition();
openApi.setRest(this);
openApi.specification(specification);
return this;
}
/**
* To set the base path of this REST service
*/
public RestDefinition path(String path) {
setPath(path);
return this;
}
/**
* Disables this REST service from the route during build time. Once an REST service has been disabled then it
* cannot be enabled later at runtime.
*/
public RestDefinition disabled() {
disabled("true");
return this;
}
/**
* Whether to disable this REST service from the route during build time. Once an REST service has been disabled
* then it cannot be enabled later at runtime.
*/
public RestDefinition disabled(boolean disabled) {
disabled(disabled ? "true" : "false");
return this;
}
/**
* Whether to disable this REST service from the route during build time. Once an REST service has been disabled
* then it cannot be enabled later at runtime.
*/
public RestDefinition disabled(String disabled) {
if (getVerbs().isEmpty()) {
this.disabled = disabled;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setDisabled(disabled);
}
return this;
}
/**
* To set the tag to use of this REST service
*/
public RestDefinition tag(String tag) {
setTag(tag);
return this;
}
public RestDefinition get() {
return addVerb("get", null);
}
public RestDefinition get(String uri) {
return addVerb("get", uri);
}
public RestDefinition post() {
return addVerb("post", null);
}
public RestDefinition post(String uri) {
return addVerb("post", uri);
}
public RestDefinition put() {
return addVerb("put", null);
}
public RestDefinition put(String uri) {
return addVerb("put", uri);
}
public RestDefinition patch() {
return addVerb("patch", null);
}
public RestDefinition patch(String uri) {
return addVerb("patch", uri);
}
public RestDefinition delete() {
return addVerb("delete", null);
}
public RestDefinition delete(String uri) {
return addVerb("delete", uri);
}
public RestDefinition head() {
return addVerb("head", null);
}
public RestDefinition head(String uri) {
return addVerb("head", uri);
}
public RestDefinition verb(String verb) {
return addVerb(verb, null);
}
public RestDefinition verb(String verb, String uri) {
return addVerb(verb, uri);
}
@Override
public RestDefinition id(String id) {
if (getVerbs().isEmpty()) {
super.id(id);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.id(id);
}
return this;
}
public RestDefinition routeId(String routeId) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setRouteId(routeId);
return this;
}
public RestDefinition deprecated() {
if (!getVerbs().isEmpty()) {
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setDeprecated("true");
}
return this;
}
@Override
public RestDefinition description(String description) {
if (getVerbs().isEmpty()) {
super.description(description);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.description(description);
}
return this;
}
public RestDefinition consumes(String mediaType) {
if (getVerbs().isEmpty()) {
this.consumes = mediaType;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setConsumes(mediaType);
}
return this;
}
public ParamDefinition param() {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
return param(verb);
}
public RestDefinition param(ParamDefinition param) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getParams().add(param);
return this;
}
public RestDefinition params(List<ParamDefinition> params) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getParams().addAll(params);
return this;
}
public ParamDefinition param(VerbDefinition verb) {
return new ParamDefinition(verb);
}
public RestDefinition responseMessage(ResponseMessageDefinition msg) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getResponseMsgs().add(msg);
return this;
}
public ResponseMessageDefinition responseMessage() {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
return responseMessage(verb);
}
public ResponseMessageDefinition responseMessage(VerbDefinition verb) {
return new ResponseMessageDefinition(verb);
}
public RestDefinition responseMessages(List<ResponseMessageDefinition> msgs) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getResponseMsgs().addAll(msgs);
return this;
}
public RestDefinition responseMessage(int code, String message) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
ResponseMessageDefinition msg = responseMessage(verb);
msg.setCode(String.valueOf(code));
msg.setMessage(message);
return this;
}
public RestDefinition responseMessage(String code, String message) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
ResponseMessageDefinition response = responseMessage(verb);
response.setCode(code);
response.setMessage(message);
verb.getResponseMsgs().add(response);
return this;
}
/**
* To configure security definitions.
*/
public RestSecuritiesDefinition securityDefinitions() {
if (securityDefinitions == null) {
securityDefinitions = new RestSecuritiesDefinition(this);
}
return securityDefinitions;
}
public RestDefinition produces(String mediaType) {
if (getVerbs().isEmpty()) {
this.produces = mediaType;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setProduces(mediaType);
}
return this;
}
public RestDefinition type(String classType) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setType(classType);
return this;
}
public RestDefinition type(Class<?> classType) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setTypeClass(classType);
verb.setType(asTypeName(classType));
return this;
}
public RestDefinition outType(String classType) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setOutType(classType);
return this;
}
public RestDefinition outType(Class<?> classType) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setOutTypeClass(classType);
verb.setOutType(asTypeName(classType));
return this;
}
public RestDefinition bindingMode(RestBindingMode mode) {
return bindingMode(mode.name());
}
public RestDefinition bindingMode(String mode) {
if (getVerbs().isEmpty()) {
this.bindingMode = mode.toLowerCase();
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setBindingMode(mode.toLowerCase());
}
return this;
}
public RestDefinition skipBindingOnErrorCode(boolean skipBindingOnErrorCode) {
if (getVerbs().isEmpty()) {
this.skipBindingOnErrorCode = Boolean.toString(skipBindingOnErrorCode);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setSkipBindingOnErrorCode(Boolean.toString(skipBindingOnErrorCode));
}
return this;
}
public RestDefinition clientRequestValidation(boolean clientRequestValidation) {
if (getVerbs().isEmpty()) {
this.clientRequestValidation = Boolean.toString(clientRequestValidation);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setClientRequestValidation(Boolean.toString(clientRequestValidation));
}
return this;
}
public RestDefinition clientResponseValidation(boolean clientResponseValidation) {
if (getVerbs().isEmpty()) {
this.clientResponseValidation = Boolean.toString(clientResponseValidation);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setClientResponseValidation(Boolean.toString(clientResponseValidation));
}
return this;
}
public RestDefinition enableCORS(boolean enableCORS) {
if (getVerbs().isEmpty()) {
this.enableCORS = Boolean.toString(enableCORS);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setEnableCORS(Boolean.toString(enableCORS));
}
return this;
}
public RestDefinition enableNoContentResponse(boolean enableNoContentResponse) {
if (getVerbs().isEmpty()) {
this.enableNoContentResponse = Boolean.toString(enableNoContentResponse);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setEnableNoContentResponse(Boolean.toString(enableNoContentResponse));
}
return this;
}
/**
* Include or exclude the current Rest Definition in API documentation.
* <p/>
* The default value is true.
*/
public RestDefinition apiDocs(Boolean apiDocs) {
if (getVerbs().isEmpty()) {
this.apiDocs = apiDocs != null ? apiDocs.toString() : null;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setApiDocs(apiDocs != null ? apiDocs.toString() : null);
}
return this;
}
/**
* Sets the security setting for this verb.
*/
public RestDefinition security(String key) {
return security(key, null);
}
/**
* Sets the security setting for this verb.
*/
public RestDefinition security(String key, String scopes) {
// add to last verb
if (getVerbs().isEmpty()) {
SecurityDefinition requirement = securityRequirements
.stream().filter(r -> key.equals(r.getKey())).findFirst().orElse(null);
if (requirement == null) {
requirement = new SecurityDefinition();
securityRequirements.add(requirement);
requirement.setKey(key);
}
requirement.setScopes(scopes);
} else {
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
SecurityDefinition sd = new SecurityDefinition();
sd.setKey(key);
sd.setScopes(scopes);
verb.getSecurity().add(sd);
}
return this;
}
/**
* The Camel endpoint this REST service will call, such as a direct endpoint to link to an existing route that
* handles this REST call.
*
* @param uri the uri of the endpoint
* @return this builder
*/
public RestDefinition to(String uri) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
ToDefinition to = new ToDefinition(uri);
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setTo(to);
return this;
}
/**
* Sends the exchange to the given endpoint
*
* @param endpoint the endpoint to send to
* @return the builder
*/
public RestDefinition to(Endpoint endpoint) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
ToDefinition to = new ToDefinition(endpoint);
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setTo(to);
return this;
}
/**
* Sends the exchange to the given endpoint
*
* @param endpoint the endpoint to send to
* @return the builder
*/
public RestDefinition to(@AsEndpointUri EndpointProducerBuilder endpoint) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
ToDefinition to = new ToDefinition(endpoint);
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setTo(to);
return this;
}
/**
* Build the from endpoint uri for the verb
*/
public String buildFromUri(CamelContext camelContext, VerbDefinition verb) {
return "rest:" + verb.asVerb() + ":" + buildUri(camelContext, verb);
}
/**
* Build the from endpoint uri for the open-api
*/
public String buildFromUri(CamelContext camelContext, OpenApiDefinition openApi) {
return "rest-openapi:" + parseText(camelContext, openApi.getSpecification());
}
// Implementation
// -------------------------------------------------------------------------
private RestDefinition addVerb(String verb, String uri) {
VerbDefinition answer;
if ("get".equals(verb)) {
answer = new GetDefinition();
} else if ("post".equals(verb)) {
answer = new PostDefinition();
} else if ("delete".equals(verb)) {
answer = new DeleteDefinition();
} else if ("head".equals(verb)) {
answer = new HeadDefinition();
} else if ("put".equals(verb)) {
answer = new PutDefinition();
} else if ("patch".equals(verb)) {
answer = new PatchDefinition();
} else {
throw new IllegalArgumentException("Verb " + verb + " not supported");
}
getVerbs().add(answer);
answer.setRest(this);
answer.setPath(uri);
return this;
}
/**
* Transforms this REST definition into a list of {@link org.apache.camel.model.RouteDefinition} which Camel routing
* engine can add and run. This allows us to define REST services using this REST DSL and turn those into regular
* Camel routes.
*
* @param camelContext The Camel context
*/
public List<RouteDefinition> asRouteDefinition(CamelContext camelContext) {
ObjectHelper.notNull(camelContext, "CamelContext");
List<RouteDefinition> answer = new ArrayList<>();
Boolean disabled = CamelContextHelper.parseBoolean(camelContext, this.disabled);
if (disabled != null && disabled) {
return answer; // all rest services are disabled
}
// only include enabled verbs
List<VerbDefinition> filter = new ArrayList<>();
for (VerbDefinition verb : verbs) {
disabled = CamelContextHelper.parseBoolean(camelContext, verb.getDisabled());
if (disabled == null || !disabled) {
filter.add(verb);
}
}
// any open-api contracts
if (openApi != null) {
disabled = CamelContextHelper.parseBoolean(camelContext, openApi.getDisabled());
if (disabled != null && disabled) {
openApi = null;
}
}
if (!filter.isEmpty() && openApi != null) {
// we cannot have both code-first and contract-first in rest-dsl
throw new IllegalArgumentException("Cannot have both code-first and contract-first in Rest DSL");
}
// sanity check this rest definition do not have duplicates
validateUniquePaths(filter);
RestConfiguration config = camelContext.getRestConfiguration();
if (config.isInlineRoutes()) {
// sanity check this rest definition do not have duplicates linked routes via direct endpoints
validateUniqueDirects(filter);
}
if (!filter.isEmpty()) {
addRouteDefinition(camelContext, filter, answer, config.getComponent(), config.getProducerComponent());
}
if (openApi != null) {
addRouteDefinition(camelContext, openApi, answer, config.getComponent(), config.getProducerComponent(),
config.getApiContextPath(), config.isClientRequestValidation(), config.isClientResponseValidation());
}
return answer;
}
protected void validateUniquePaths(List<VerbDefinition> verbs) {
Set<String> paths = new HashSet<>();
for (VerbDefinition verb : verbs) {
String path = verb.asVerb();
if (verb.getPath() != null) {
path += ":" + verb.getPath();
}
if (!paths.add(path)) {
throw new IllegalArgumentException("Duplicate verb detected in rest-dsl: " + path);
}
}
}
protected void validateUniqueDirects(List<VerbDefinition> verbs) {
Set<String> directs = new HashSet<>();
for (VerbDefinition verb : verbs) {
ToDefinition to = verb.getTo();
if (to != null) {
String uri = to.getEndpointUri();
if (uri.startsWith("direct:")) {
if (!directs.add(uri)) {
throw new IllegalArgumentException("Duplicate to in rest-dsl: " + uri);
}
}
}
}
}
protected String asTypeName(Class<?> classType) {
// Workaround for https://issues.apache.org/jira/browse/CAMEL-15199
//
// The VerbDefinition::setType and VerbDefinition::setOutType require
// the | RestDefinition |
java | apache__rocketmq | auth/src/main/java/org/apache/rocketmq/auth/authentication/manager/AuthenticationMetadataManager.java | {
"start": 1048,
"end": 1496
} | interface ____ {
void shutdown();
void initUser(AuthConfig authConfig);
CompletableFuture<Void> createUser(User user);
CompletableFuture<Void> updateUser(User user);
CompletableFuture<Void> deleteUser(String username);
CompletableFuture<User> getUser(String username);
CompletableFuture<List<User>> listUser(String filter);
CompletableFuture<Boolean> isSuperUser(String username);
}
| AuthenticationMetadataManager |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/ProtobufDataFormat.java | {
"start": 7872,
"end": 10574
} | class ____ use when unmarshalling
*/
public void setInstanceClass(String instanceClass) {
this.instanceClass = instanceClass;
}
/**
* Defines a content type format in which protobuf message will be serialized/deserialized from(to) the Java been.
* The format can either be native or json for either native protobuf or json fields representation. The default
* value is native.
*/
public void setContentTypeFormat(String contentTypeFormat) {
this.contentTypeFormat = contentTypeFormat;
}
public String getContentTypeFormat() {
return contentTypeFormat;
}
public String getContentTypeHeader() {
return contentTypeHeader;
}
public void setContentTypeHeader(String contentTypeHeader) {
this.contentTypeHeader = contentTypeHeader;
}
public Object getDefaultInstance() {
return defaultInstance;
}
public void setDefaultInstance(Object defaultInstance) {
this.defaultInstance = defaultInstance;
}
public ProtobufLibrary getLibrary() {
return library;
}
/**
* Which Protobuf library to use.
*/
public void setLibrary(ProtobufLibrary library) {
this.library = library;
}
public String getObjectMapper() {
return objectMapper;
}
/**
* Lookup and use the existing ObjectMapper with the given id when using Jackson.
*/
public void setObjectMapper(String objectMapper) {
this.objectMapper = objectMapper;
}
public String getUseDefaultObjectMapper() {
return useDefaultObjectMapper;
}
/**
* Whether to lookup and use default Jackson ObjectMapper from the registry.
*/
public void setUseDefaultObjectMapper(String useDefaultObjectMapper) {
this.useDefaultObjectMapper = useDefaultObjectMapper;
}
public String getUnmarshalTypeName() {
return unmarshalTypeName;
}
/**
* Class name of the java type to use when unmarshalling
*/
public void setUnmarshalTypeName(String unmarshalTypeName) {
this.unmarshalTypeName = unmarshalTypeName;
}
public Class<?> getUnmarshalType() {
return unmarshalType;
}
/**
* Class of the java type to use when unmarshalling
*/
public void setUnmarshalType(Class<?> unmarshalType) {
this.unmarshalType = unmarshalType;
}
public String getJsonViewTypeName() {
return jsonViewTypeName;
}
/**
* When marshalling a POJO to JSON you might want to exclude certain fields from the JSON output. With Jackson you
* can use JSON views to accomplish this. This option is to refer to the | to |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/DataStreamTest.java | {
"start": 81534,
"end": 81919
} | class ____ {
private String s;
private int i;
public CustomPOJO() {}
public void setS(String s) {
this.s = s;
}
public void setI(int i) {
this.i = i;
}
public String getS() {
return s;
}
public int getI() {
return i;
}
}
private | CustomPOJO |
java | apache__flink | flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/RowDataToAvroConverters.java | {
"start": 1852,
"end": 2279
} | class ____ {
// --------------------------------------------------------------------------------
// Runtime Converters
// --------------------------------------------------------------------------------
/**
* Runtime converter that converts objects of Flink Table & SQL internal data structures to
* corresponding Avro data structures.
*/
@FunctionalInterface
public | RowDataToAvroConverters |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/EvalOperatorTests.java | {
"start": 1102,
"end": 4848
} | class ____ extends OperatorTestCase {
@Override
protected SourceOperator simpleInput(BlockFactory blockFactory, int end) {
return new TupleLongLongBlockSourceOperator(blockFactory, LongStream.range(0, end).mapToObj(l -> Tuple.tuple(l, end - l)));
}
record Addition(DriverContext driverContext, int lhs, int rhs) implements EvalOperator.ExpressionEvaluator {
@Override
public Block eval(Page page) {
LongVector lhsVector = page.<LongBlock>getBlock(0).asVector();
LongVector rhsVector = page.<LongBlock>getBlock(1).asVector();
try (LongVector.FixedBuilder result = driverContext.blockFactory().newLongVectorFixedBuilder(page.getPositionCount())) {
for (int p = 0; p < page.getPositionCount(); p++) {
result.appendLong(lhsVector.getLong(p) + rhsVector.getLong(p));
}
return result.build().asBlock();
}
}
@Override
public long baseRamBytesUsed() {
return 1;
}
@Override
public String toString() {
return "Addition[lhs=" + lhs + ", rhs=" + rhs + ']';
}
@Override
public void close() {}
}
record LoadFromPage(int channel) implements EvalOperator.ExpressionEvaluator {
@Override
public Block eval(Page page) {
Block block = page.getBlock(channel);
block.incRef();
return block;
}
@Override
public long baseRamBytesUsed() {
return 2;
}
@Override
public void close() {}
}
@Override
protected Operator.OperatorFactory simple(SimpleOptions options) {
return new EvalOperator.EvalOperatorFactory(new EvalOperator.ExpressionEvaluator.Factory() {
@Override
public EvalOperator.ExpressionEvaluator get(DriverContext context) {
return new Addition(context, 0, 1);
}
@Override
public String toString() {
return "Addition[lhs=0, rhs=1]";
}
});
}
@Override
protected Matcher<String> expectedDescriptionOfSimple() {
return equalTo("EvalOperator[evaluator=Addition[lhs=0, rhs=1]]");
}
@Override
protected Matcher<String> expectedToStringOfSimple() {
return expectedDescriptionOfSimple();
}
@Override
protected void assertSimpleOutput(List<Page> input, List<Page> results) {
final int positions = input.stream().map(page -> page.<Block>getBlock(0)).mapToInt(Block::getPositionCount).sum();
final int expectedValue = positions;
final int resultChannel = 2;
for (var page : results) {
LongBlock lb = page.getBlock(resultChannel);
IntStream.range(0, lb.getPositionCount()).forEach(pos -> assertEquals(expectedValue, lb.getLong(pos)));
}
}
public void testReadFromBlock() {
DriverContext context = driverContext();
List<Page> input = CannedSourceOperator.collectPages(simpleInput(context.blockFactory(), 10));
List<Page> results = drive(new EvalOperatorFactory(dvrCtx -> new LoadFromPage(0)).get(context), input.iterator(), context);
Set<Long> found = new TreeSet<>();
for (var page : results) {
LongBlock lb = page.getBlock(2);
IntStream.range(0, lb.getPositionCount()).forEach(pos -> found.add(lb.getLong(pos)));
}
assertThat(found, equalTo(LongStream.range(0, 10).mapToObj(Long::valueOf).collect(Collectors.toSet())));
results.forEach(Page::releaseBlocks);
assertThat(context.breaker().getUsed(), equalTo(0L));
}
}
| EvalOperatorTests |
java | micronaut-projects__micronaut-core | websocket/src/main/java/io/micronaut/websocket/annotation/WebSocketComponent.java | {
"start": 1190,
"end": 1686
} | interface ____ {
/**
* The default WebSocket URI.
*/
String DEFAULT_URI = "/ws";
/**
* @return The URI of the action
*/
@AliasFor(member = "uri")
String value() default DEFAULT_URI;
/**
* @return The URI of the action
*/
@AliasFor(member = "value")
String uri() default DEFAULT_URI;
/**
* @return The WebSocket version to use to connect
*/
WebSocketVersion version() default WebSocketVersion.V13;
}
| WebSocketComponent |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/model/ObjectFactoryMethodResolver.java | {
"start": 1167,
"end": 7269
} | class ____ {
private ObjectFactoryMethodResolver() {
}
/**
* returns a no arg factory method
*
* @param method target mapping method
* @param selectionParameters parameters used in the selection process
* @param ctx the mapping builder context
*
* @return a method reference to the factory method, or null if no suitable, or ambiguous method found
*/
public static MethodReference getFactoryMethod( Method method,
SelectionParameters selectionParameters,
MappingBuilderContext ctx) {
return getFactoryMethod( method, method.getResultType(), selectionParameters, ctx );
}
/**
* returns a no arg factory method
*
* @param method target mapping method
* @param alternativeTarget alternative to {@link Method#getResultType()} e.g. when target is abstract
* @param selectionParameters parameters used in the selection process
* @param ctx the mapping builder context
*
* @return a method reference to the factory method, or null if no suitable, or ambiguous method found
*
*/
public static MethodReference getFactoryMethod( Method method,
Type alternativeTarget,
SelectionParameters selectionParameters,
MappingBuilderContext ctx) {
List<SelectedMethod<SourceMethod>> matchingFactoryMethods = getMatchingFactoryMethods(
method,
alternativeTarget,
selectionParameters,
ctx
);
if (matchingFactoryMethods.isEmpty()) {
return null;
}
if ( matchingFactoryMethods.size() > 1 ) {
ctx.getMessager().printMessage(
method.getExecutable(),
Message.GENERAL_AMBIGUOUS_FACTORY_METHOD,
alternativeTarget.describe(),
matchingFactoryMethods.stream()
.map( SelectedMethod::getMethod )
.map( Method::describe )
.collect( Collectors.joining( ", " ) )
);
return null;
}
SelectedMethod<SourceMethod> matchingFactoryMethod = first( matchingFactoryMethods );
return getFactoryMethodReference( method, matchingFactoryMethod, ctx );
}
public static MethodReference getFactoryMethodReference(Method method,
SelectedMethod<SourceMethod> matchingFactoryMethod, MappingBuilderContext ctx) {
Parameter providingParameter =
method.getContextProvidedMethods().getParameterForProvidedMethod( matchingFactoryMethod.getMethod() );
if ( providingParameter != null ) {
return MethodReference.forParameterProvidedMethod(
matchingFactoryMethod.getMethod(),
providingParameter,
matchingFactoryMethod.getParameterBindings() );
}
else {
MapperReference ref = MapperReference.findMapperReference(
ctx.getMapperReferences(),
matchingFactoryMethod.getMethod() );
return MethodReference.forMapperReference(
matchingFactoryMethod.getMethod(),
ref,
matchingFactoryMethod.getParameterBindings() );
}
}
public static List<SelectedMethod<SourceMethod>> getMatchingFactoryMethods( Method method,
Type alternativeTarget,
SelectionParameters selectionParameters,
MappingBuilderContext ctx) {
MethodSelectors selectors =
new MethodSelectors( ctx.getTypeUtils(), ctx.getElementUtils(), ctx.getMessager(), null );
return selectors.getMatchingMethods(
getAllAvailableMethods( method, ctx.getSourceModel() ),
SelectionContext.forFactoryMethods( method, alternativeTarget, selectionParameters, ctx.getTypeFactory() )
);
}
public static MethodReference getBuilderFactoryMethod(Method method, BuilderType builder ) {
return getBuilderFactoryMethod( method.getReturnType(), builder );
}
public static MethodReference getBuilderFactoryMethod(Type typeToBuild, BuilderType builder ) {
if ( builder == null ) {
return null;
}
ExecutableElement builderCreationMethod = builder.getBuilderCreationMethod();
if ( builderCreationMethod.getKind() == ElementKind.CONSTRUCTOR ) {
// If the builder creation method is a constructor it would be handled properly down the line
return null;
}
if ( !builder.getBuildingType().isAssignableTo( typeToBuild ) ) {
//TODO print error message
return null;
}
return MethodReference.forStaticBuilder(
builderCreationMethod.getSimpleName().toString(),
builder.getOwningType()
);
}
private static List<SourceMethod> getAllAvailableMethods(Method method, List<SourceMethod> sourceModelMethods) {
ParameterProvidedMethods contextProvidedMethods = method.getContextProvidedMethods();
if ( contextProvidedMethods.isEmpty() ) {
return sourceModelMethods;
}
List<SourceMethod> methodsProvidedByParams = contextProvidedMethods
.getAllProvidedMethodsInParameterOrder( method.getContextParameters() );
List<SourceMethod> availableMethods =
new ArrayList<>( methodsProvidedByParams.size() + sourceModelMethods.size() );
for ( SourceMethod methodProvidedByParams : methodsProvidedByParams ) {
// add only methods from context that do have the @ObjectFactory annotation
if ( methodProvidedByParams.hasObjectFactoryAnnotation() ) {
availableMethods.add( methodProvidedByParams );
}
}
availableMethods.addAll( sourceModelMethods );
return availableMethods;
}
}
| ObjectFactoryMethodResolver |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/snapshots/CloneSnapshotIT.java | {
"start": 2388,
"end": 42794
} | class ____ extends AbstractSnapshotIntegTestCase {
public void testShardClone() throws Exception {
internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final String repoName = "repo-name";
final Path repoPath = randomRepoPath();
createRepository(repoName, "fs", repoPath);
final boolean useBwCFormat = randomBoolean();
if (useBwCFormat) {
initWithSnapshotVersion(repoName, repoPath, SnapshotsService.OLD_SNAPSHOT_FORMAT);
}
final String indexName = "test-index";
createIndexWithRandomDocs(indexName, randomIntBetween(5, 10));
final String sourceSnapshot = "source-snapshot";
final SnapshotInfo sourceSnapshotInfo = createFullSnapshot(repoName, sourceSnapshot);
final BlobStoreRepository repository = getRepositoryOnMaster(repoName);
final RepositoryData repositoryData = getRepositoryData(repoName);
final IndexId indexId = repositoryData.resolveIndexId(indexName);
final int shardId = 0;
final RepositoryShardId repositoryShardId = new RepositoryShardId(indexId, shardId);
final SnapshotId targetSnapshotId = new SnapshotId("target-snapshot", UUIDs.randomBase64UUID(random()));
final ShardGeneration currentShardGen;
if (useBwCFormat) {
currentShardGen = null;
} else {
currentShardGen = repositoryData.shardGenerations().getShardGen(indexId, shardId);
}
final ShardSnapshotResult shardSnapshotResult = safeAwait(
listener -> repository.cloneShardSnapshot(
sourceSnapshotInfo.snapshotId(),
targetSnapshotId,
repositoryShardId,
currentShardGen,
listener
)
);
final ShardGeneration newShardGeneration = shardSnapshotResult.getGeneration();
if (useBwCFormat) {
assertEquals(newShardGeneration, new ShardGeneration(1L)); // Initial snapshot brought it to 0, clone increments it to 1
}
final BlobStoreIndexShardSnapshot targetShardSnapshot = readShardSnapshot(repository, repositoryShardId, targetSnapshotId);
final BlobStoreIndexShardSnapshot sourceShardSnapshot = readShardSnapshot(
repository,
repositoryShardId,
sourceSnapshotInfo.snapshotId()
);
assertThat(targetShardSnapshot.incrementalFileCount(), is(0));
final List<BlobStoreIndexShardSnapshot.FileInfo> sourceFiles = sourceShardSnapshot.indexFiles();
final List<BlobStoreIndexShardSnapshot.FileInfo> targetFiles = targetShardSnapshot.indexFiles();
final int fileCount = sourceFiles.size();
assertEquals(fileCount, targetFiles.size());
for (int i = 0; i < fileCount; i++) {
assertTrue(sourceFiles.get(i).isSame(targetFiles.get(i)));
}
final BlobStoreIndexShardSnapshots shardMetadata = readShardGeneration(repository, repositoryShardId, newShardGeneration);
final List<SnapshotFiles> snapshotFiles = shardMetadata.snapshots();
assertThat(snapshotFiles, hasSize(2));
assertTrue(snapshotFiles.get(0).isSame(snapshotFiles.get(1)));
// verify that repeated cloning is idempotent
final ShardSnapshotResult shardSnapshotResult2 = safeAwait(
listener -> repository.cloneShardSnapshot(
sourceSnapshotInfo.snapshotId(),
targetSnapshotId,
repositoryShardId,
newShardGeneration,
listener
)
);
assertEquals(newShardGeneration, shardSnapshotResult2.getGeneration());
assertEquals(shardSnapshotResult.getSegmentCount(), shardSnapshotResult2.getSegmentCount());
assertEquals(shardSnapshotResult.getSize(), shardSnapshotResult2.getSize());
}
public void testCloneSnapshotIndex() throws Exception {
internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final String repoName = "repo-name";
createRepository(repoName, "fs");
final String indexName = "index-1";
createIndexWithRandomDocs(indexName, randomIntBetween(5, 10));
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
indexRandomDocs(indexName, randomIntBetween(20, 100));
if (randomBoolean()) {
assertAcked(indicesAdmin().prepareDelete(indexName));
}
final String targetSnapshot = "target-snapshot";
assertAcked(startClone(repoName, sourceSnapshot, targetSnapshot, indexName).get());
final List<SnapshotStatus> status = clusterAdmin().prepareSnapshotStatus(TEST_REQUEST_TIMEOUT, repoName)
.setSnapshots(sourceSnapshot, targetSnapshot)
.get()
.getSnapshots();
assertThat(status, hasSize(2));
final SnapshotIndexStatus status1 = status.get(0).getIndices().get(indexName);
final SnapshotIndexStatus status2 = status.get(1).getIndices().get(indexName);
assertEquals(status1.getStats().getTotalFileCount(), status2.getStats().getTotalFileCount());
assertEquals(status1.getStats().getTotalSize(), status2.getStats().getTotalSize());
}
public void testClonePreventsSnapshotDelete() throws Exception {
final String masterName = internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final String repoName = "repo-name";
createRepository(repoName, "mock");
final String indexName = "index-1";
createIndexWithRandomDocs(indexName, randomIntBetween(5, 10));
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
indexRandomDocs(indexName, randomIntBetween(20, 100));
final String targetSnapshot = "target-snapshot";
blockNodeOnAnyFiles(repoName, masterName);
final ActionFuture<AcknowledgedResponse> cloneFuture = startClone(repoName, sourceSnapshot, targetSnapshot, indexName);
waitForBlock(masterName, repoName);
assertFalse(cloneFuture.isDone());
ConcurrentSnapshotExecutionException ex = expectThrows(
ConcurrentSnapshotExecutionException.class,
startDeleteSnapshot(repoName, sourceSnapshot)
);
assertThat(ex.getMessage(), containsString("cannot delete snapshot while it is being cloned"));
unblockNode(repoName, masterName);
assertAcked(cloneFuture.get());
final List<SnapshotStatus> status = clusterAdmin().prepareSnapshotStatus(TEST_REQUEST_TIMEOUT, repoName)
.setSnapshots(sourceSnapshot, targetSnapshot)
.get()
.getSnapshots();
assertThat(status, hasSize(2));
final SnapshotIndexStatus status1 = status.get(0).getIndices().get(indexName);
final SnapshotIndexStatus status2 = status.get(1).getIndices().get(indexName);
assertEquals(status1.getStats().getTotalFileCount(), status2.getStats().getTotalFileCount());
assertEquals(status1.getStats().getTotalSize(), status2.getStats().getTotalSize());
}
public void testConcurrentCloneAndSnapshot() throws Exception {
internalCluster().startMasterOnlyNode();
final String dataNode = internalCluster().startDataOnlyNode();
final String repoName = "repo-name";
createRepository(repoName, "mock");
final String indexName = "index-1";
createIndexWithRandomDocs(indexName, randomIntBetween(5, 10));
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
indexRandomDocs(indexName, randomIntBetween(20, 100));
final String targetSnapshot = "target-snapshot";
final ActionFuture<CreateSnapshotResponse> snapshot2Future = startFullSnapshotBlockedOnDataNode("snapshot-2", repoName, dataNode);
waitForBlock(dataNode, repoName);
final ActionFuture<AcknowledgedResponse> cloneFuture = startClone(repoName, sourceSnapshot, targetSnapshot, indexName);
awaitNumberOfSnapshotsInProgress(2);
unblockNode(repoName, dataNode);
assertAcked(cloneFuture.get());
assertSuccessful(snapshot2Future);
}
public void testLongRunningCloneAllowsConcurrentSnapshot() throws Exception {
// large snapshot pool so blocked snapshot threads from cloning don't prevent concurrent snapshot finalizations
final String masterNode = internalCluster().startMasterOnlyNode(LARGE_SNAPSHOT_POOL_SETTINGS);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String indexSlow = "index-slow";
createIndexWithContent(indexSlow);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
final String targetSnapshot = "target-snapshot";
blockMasterOnShardClone(repoName);
final ActionFuture<AcknowledgedResponse> cloneFuture = startClone(repoName, sourceSnapshot, targetSnapshot, indexSlow);
waitForBlock(masterNode, repoName);
final String indexFast = "index-fast";
createIndexWithRandomDocs(indexFast, randomIntBetween(20, 100));
assertSuccessful(
clusterAdmin().prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, repoName, "fast-snapshot")
.setIndices(indexFast)
.setWaitForCompletion(true)
.execute()
);
assertThat(cloneFuture.isDone(), is(false));
unblockNode(repoName, masterNode);
assertAcked(cloneFuture.get());
}
public void testLongRunningSnapshotAllowsConcurrentClone() throws Exception {
internalCluster().startMasterOnlyNode();
final String dataNode = internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String indexSlow = "index-slow";
createIndexWithContent(indexSlow);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
final String indexFast = "index-fast";
createIndexWithRandomDocs(indexFast, randomIntBetween(20, 100));
blockDataNode(repoName, dataNode);
final ActionFuture<CreateSnapshotResponse> snapshotFuture = clusterAdmin().prepareCreateSnapshot(
TEST_REQUEST_TIMEOUT,
repoName,
"fast-snapshot"
).setIndices(indexFast).setWaitForCompletion(true).execute();
waitForBlock(dataNode, repoName);
final String targetSnapshot = "target-snapshot";
assertAcked(startClone(repoName, sourceSnapshot, targetSnapshot, indexSlow).get());
assertThat(snapshotFuture.isDone(), is(false));
unblockNode(repoName, dataNode);
assertSuccessful(snapshotFuture);
}
public void testDeletePreventsClone() throws Exception {
final String masterName = internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final String repoName = "repo-name";
createRepository(repoName, "mock");
final String indexName = "index-1";
createIndexWithRandomDocs(indexName, randomIntBetween(5, 10));
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
indexRandomDocs(indexName, randomIntBetween(20, 100));
final String targetSnapshot = "target-snapshot";
blockNodeOnAnyFiles(repoName, masterName);
final ActionFuture<AcknowledgedResponse> deleteFuture = startDeleteSnapshot(repoName, sourceSnapshot);
waitForBlock(masterName, repoName);
assertFalse(deleteFuture.isDone());
ConcurrentSnapshotExecutionException ex = expectThrows(
ConcurrentSnapshotExecutionException.class,
startClone(repoName, sourceSnapshot, targetSnapshot, indexName)
);
assertThat(ex.getMessage(), containsString("cannot clone from snapshot that is being deleted"));
unblockNode(repoName, masterName);
assertAcked(deleteFuture.get());
}
public void testBackToBackClonesForIndexNotInCluster() throws Exception {
// large snapshot pool so blocked snapshot threads from cloning don't prevent concurrent snapshot finalizations
final String masterNode = internalCluster().startMasterOnlyNode(LARGE_SNAPSHOT_POOL_SETTINGS);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String indexBlocked = "index-blocked";
createIndexWithContent(indexBlocked);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
assertAcked(indicesAdmin().prepareDelete(indexBlocked).get());
final String targetSnapshot1 = "target-snapshot";
blockMasterOnShardClone(repoName);
final ActionFuture<AcknowledgedResponse> cloneFuture1 = startClone(repoName, sourceSnapshot, targetSnapshot1, indexBlocked);
waitForBlock(masterNode, repoName);
assertThat(cloneFuture1.isDone(), is(false));
final int extraClones = randomIntBetween(1, 5);
final List<ActionFuture<AcknowledgedResponse>> extraCloneFutures = new ArrayList<>(extraClones);
final boolean slowInitClones = extraClones > 1 && randomBoolean();
if (slowInitClones) {
blockMasterOnReadIndexMeta(repoName);
}
for (int i = 0; i < extraClones; i++) {
extraCloneFutures.add(startClone(repoName, sourceSnapshot, "target-snapshot-" + i, indexBlocked));
}
awaitNumberOfSnapshotsInProgress(1 + extraClones);
for (ActionFuture<AcknowledgedResponse> extraCloneFuture : extraCloneFutures) {
assertFalse(extraCloneFuture.isDone());
}
final int extraSnapshots = randomIntBetween(0, 5);
if (extraSnapshots > 0) {
createIndexWithContent(indexBlocked);
}
final List<ActionFuture<CreateSnapshotResponse>> extraSnapshotFutures = new ArrayList<>(extraSnapshots);
for (int i = 0; i < extraSnapshots; i++) {
extraSnapshotFutures.add(startFullSnapshot(repoName, "extra-snap-" + i));
}
awaitNumberOfSnapshotsInProgress(1 + extraClones + extraSnapshots);
for (ActionFuture<CreateSnapshotResponse> extraSnapshotFuture : extraSnapshotFutures) {
assertFalse(extraSnapshotFuture.isDone());
}
unblockNode(repoName, masterNode);
assertAcked(cloneFuture1.get());
for (ActionFuture<AcknowledgedResponse> extraCloneFuture : extraCloneFutures) {
assertAcked(extraCloneFuture.get());
}
for (ActionFuture<CreateSnapshotResponse> extraSnapshotFuture : extraSnapshotFutures) {
assertSuccessful(extraSnapshotFuture);
}
}
public void testMasterFailoverDuringCloneStep1() throws Exception {
internalCluster().startMasterOnlyNodes(3);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
createIndexWithContent(testIndex);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
blockMasterOnReadIndexMeta(repoName);
final String cloneName = "target-snapshot";
final ActionFuture<AcknowledgedResponse> cloneFuture = startCloneFromDataNode(repoName, sourceSnapshot, cloneName, testIndex);
awaitNumberOfSnapshotsInProgress(1);
final String masterNode = internalCluster().getMasterName();
waitForBlock(masterNode, repoName);
internalCluster().restartNode(masterNode);
boolean cloneSucceeded = false;
try {
cloneFuture.actionGet(TimeValue.timeValueSeconds(30L));
cloneSucceeded = true;
} catch (SnapshotException sne) {
// ignored, most of the time we will throw here but we could randomly run into a situation where the data node retries the
// snapshot on disconnect slowly enough for it to work out
}
awaitNoMoreRunningOperations();
// Check if the clone operation worked out by chance as a result of the clone request being retried because of the master failover
cloneSucceeded = cloneSucceeded
|| getRepositoryData(repoName).getSnapshotIds().stream().anyMatch(snapshotId -> snapshotId.getName().equals(cloneName));
assertAllSnapshotsSuccessful(getRepositoryData(repoName), cloneSucceeded ? 2 : 1);
}
public void testFailsOnCloneMissingIndices() {
internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final String repoName = "repo-name";
final Path repoPath = randomRepoPath();
if (randomBoolean()) {
createIndexWithContent("test-idx");
}
createRepository(repoName, "fs", repoPath);
final String snapshotName = "snapshot";
createFullSnapshot(repoName, snapshotName);
expectThrows(IndexNotFoundException.class, startClone(repoName, snapshotName, "target-snapshot", "does-not-exist"));
}
public void testMasterFailoverDuringCloneStep2() throws Exception {
// large snapshot pool so blocked snapshot threads from cloning don't prevent concurrent snapshot finalizations
internalCluster().startMasterOnlyNodes(3, LARGE_SNAPSHOT_POOL_SETTINGS);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
createIndexWithContent(testIndex);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
final String targetSnapshot = "target-snapshot";
blockMasterOnShardClone(repoName);
final ActionFuture<AcknowledgedResponse> cloneFuture = startCloneFromDataNode(repoName, sourceSnapshot, targetSnapshot, testIndex);
awaitNumberOfSnapshotsInProgress(1);
final String masterNode = internalCluster().getMasterName();
waitForBlock(masterNode, repoName);
internalCluster().restartNode(masterNode);
expectThrows(SnapshotException.class, cloneFuture);
awaitNoMoreRunningOperations();
assertAllSnapshotsSuccessful(getRepositoryData(repoName), 2);
}
public void testExceptionDuringShardClone() throws Exception {
// large snapshot pool so blocked snapshot threads from cloning don't prevent concurrent snapshot finalizations
internalCluster().startMasterOnlyNodes(3, LARGE_SNAPSHOT_POOL_SETTINGS);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
createIndexWithContent(testIndex);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
final String targetSnapshot = "target-snapshot";
blockMasterFromFinalizingSnapshotOnSnapFile(repoName);
final ActionFuture<AcknowledgedResponse> cloneFuture = startCloneFromDataNode(repoName, sourceSnapshot, targetSnapshot, testIndex);
awaitNumberOfSnapshotsInProgress(1);
final String masterNode = internalCluster().getMasterName();
waitForBlock(masterNode, repoName);
unblockNode(repoName, masterNode);
expectThrows(SnapshotException.class, cloneFuture);
awaitNoMoreRunningOperations();
assertAllSnapshotsSuccessful(getRepositoryData(repoName), 1);
assertAcked(startDeleteSnapshot(repoName, sourceSnapshot).get());
}
public void testDoesNotStartOnBrokenSourceSnapshot() throws Exception {
internalCluster().startMasterOnlyNode();
final String dataNode = internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
createIndexWithContent(testIndex);
final String sourceSnapshot = "source-snapshot";
blockDataNode(repoName, dataNode);
final Client masterClient = internalCluster().masterClient();
final ActionFuture<CreateSnapshotResponse> sourceSnapshotFuture = masterClient.admin()
.cluster()
.prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, repoName, sourceSnapshot)
.setWaitForCompletion(true)
.execute();
awaitNumberOfSnapshotsInProgress(1);
waitForBlock(dataNode, repoName);
internalCluster().restartNode(dataNode);
assertThat(sourceSnapshotFuture.get().getSnapshotInfo().state(), is(SnapshotState.PARTIAL));
final SnapshotException sne = expectThrows(
SnapshotException.class,
startClone(masterClient, repoName, sourceSnapshot, "target-snapshot", testIndex)
);
assertThat(
sne.getMessage(),
containsString(
"Can't clone index [" + getRepositoryData(repoName).resolveIndexId(testIndex) + "] because its snapshot was not successful."
)
);
}
public void testSnapshotQueuedAfterCloneFromBrokenSourceSnapshot() throws Exception {
internalCluster().startMasterOnlyNode();
final String dataNode = internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
createIndexWithContent(testIndex);
final String sourceSnapshot = "source-snapshot";
blockDataNode(repoName, dataNode);
final Client masterClient = internalCluster().masterClient();
final ActionFuture<CreateSnapshotResponse> sourceSnapshotFuture = masterClient.admin()
.cluster()
.prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, repoName, sourceSnapshot)
.setWaitForCompletion(true)
.execute();
awaitNumberOfSnapshotsInProgress(1);
waitForBlock(dataNode, repoName);
internalCluster().restartNode(dataNode);
ensureGreen();
assertThat(sourceSnapshotFuture.get().getSnapshotInfo().state(), is(SnapshotState.PARTIAL));
final String sourceSnapshotHealthy = "source-snapshot-healthy";
createFullSnapshot(repoName, "source-snapshot-healthy");
final ActionFuture<CreateSnapshotResponse> sn1 = startFullSnapshot(repoName, "concurrent-snapshot-1");
final ActionFuture<AcknowledgedResponse> clone1 = startClone(
masterClient,
repoName,
sourceSnapshotHealthy,
"target-snapshot-1",
testIndex
);
final ActionFuture<CreateSnapshotResponse> sn2 = startFullSnapshot(repoName, "concurrent-snapshot-2");
final ActionFuture<AcknowledgedResponse> clone2 = startClone(
masterClient,
repoName,
sourceSnapshotHealthy,
"target-snapshot-2",
testIndex
);
final ActionFuture<CreateSnapshotResponse> sn3 = startFullSnapshot(repoName, "concurrent-snapshot-3");
final ActionFuture<AcknowledgedResponse> clone3 = startClone(
masterClient,
repoName,
sourceSnapshotHealthy,
"target-snapshot-3",
testIndex
);
final SnapshotException sne = expectThrows(
SnapshotException.class,
startClone(masterClient, repoName, sourceSnapshot, "target-snapshot", testIndex)
);
assertThat(
sne.getMessage(),
containsString(
"Can't clone index [" + getRepositoryData(repoName).resolveIndexId(testIndex) + "] because its snapshot was not successful."
)
);
assertSuccessful(sn1);
assertSuccessful(sn2);
assertSuccessful(sn3);
assertAcked(clone1, clone2, clone3);
}
public void testStartSnapshotWithSuccessfulShardClonePendingFinalization() throws Exception {
final String masterName = internalCluster().startMasterOnlyNode(LARGE_SNAPSHOT_POOL_SETTINGS);
final String dataNode = internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String indexName = "test-idx";
createIndexWithContent(indexName);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
blockMasterOnWriteIndexFile(repoName);
final String cloneName = "clone-blocked";
final ActionFuture<AcknowledgedResponse> blockedClone = startClone(repoName, sourceSnapshot, cloneName, indexName);
waitForBlock(masterName, repoName);
awaitNumberOfSnapshotsInProgress(1);
blockNodeOnAnyFiles(repoName, dataNode);
final ActionFuture<CreateSnapshotResponse> otherSnapshot = startFullSnapshot(repoName, "other-snapshot");
awaitNumberOfSnapshotsInProgress(2);
assertFalse(blockedClone.isDone());
unblockNode(repoName, masterName);
awaitNumberOfSnapshotsInProgress(1);
awaitMasterFinishRepoOperations();
unblockNode(repoName, dataNode);
assertAcked(blockedClone.get());
assertEquals(getSnapshot(repoName, cloneName).state(), SnapshotState.SUCCESS);
assertSuccessful(otherSnapshot);
}
public void testStartCloneWithSuccessfulShardClonePendingFinalization() throws Exception {
final String masterName = internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String indexName = "test-idx";
createIndexWithContent(indexName);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
blockMasterOnWriteIndexFile(repoName);
final String cloneName = "clone-blocked";
final ActionFuture<AcknowledgedResponse> blockedClone = startClone(repoName, sourceSnapshot, cloneName, indexName);
waitForBlock(masterName, repoName);
awaitNumberOfSnapshotsInProgress(1);
final String otherCloneName = "other-clone";
final ActionFuture<AcknowledgedResponse> otherClone = startClone(repoName, sourceSnapshot, otherCloneName, indexName);
awaitNumberOfSnapshotsInProgress(2);
assertFalse(blockedClone.isDone());
unblockNode(repoName, masterName);
awaitNoMoreRunningOperations(masterName);
awaitMasterFinishRepoOperations();
assertAcked(blockedClone, otherClone);
assertEquals(getSnapshot(repoName, cloneName).state(), SnapshotState.SUCCESS);
assertEquals(getSnapshot(repoName, otherCloneName).state(), SnapshotState.SUCCESS);
}
public void testStartCloneWithSuccessfulShardSnapshotPendingFinalization() throws Exception {
final String masterName = internalCluster().startMasterOnlyNode(LARGE_SNAPSHOT_POOL_SETTINGS);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String indexName = "test-idx";
createIndexWithContent(indexName);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
blockMasterOnWriteIndexFile(repoName);
final ActionFuture<CreateSnapshotResponse> blockedSnapshot = startFullSnapshot(repoName, "snap-blocked");
waitForBlock(masterName, repoName);
awaitNumberOfSnapshotsInProgress(1);
final String cloneName = "clone";
final ActionFuture<AcknowledgedResponse> clone = startClone(repoName, sourceSnapshot, cloneName, indexName);
logger.info("--> wait for clone to start fully with shards assigned in the cluster state");
try {
awaitClusterState(clusterState -> {
final List<SnapshotsInProgress.Entry> entries = SnapshotsInProgress.get(clusterState).forRepo(repoName);
return entries.size() == 2 && entries.get(1).shardSnapshotStatusByRepoShardId().isEmpty() == false;
});
assertFalse(blockedSnapshot.isDone());
} finally {
unblockNode(repoName, masterName);
}
awaitNoMoreRunningOperations();
awaitMasterFinishRepoOperations();
assertSuccessful(blockedSnapshot);
assertAcked(clone.get());
assertEquals(getSnapshot(repoName, cloneName).state(), SnapshotState.SUCCESS);
}
public void testStartCloneDuringRunningDelete() throws Exception {
final String masterName = internalCluster().startMasterOnlyNode(LARGE_SNAPSHOT_POOL_SETTINGS);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String indexName = "test-idx";
createIndexWithContent(indexName);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
final List<String> snapshotNames = createNSnapshots(repoName, randomIntBetween(1, 5));
blockMasterOnWriteIndexFile(repoName);
final ActionFuture<AcknowledgedResponse> deleteFuture = startDeleteSnapshot(repoName, randomFrom(snapshotNames));
waitForBlock(masterName, repoName);
awaitNDeletionsInProgress(1);
final ActionFuture<AcknowledgedResponse> cloneFuture = startClone(repoName, sourceSnapshot, "target-snapshot", indexName);
logger.info("--> waiting for snapshot clone to be fully initialized");
awaitClusterState(state -> {
for (SnapshotsInProgress.Entry entry : SnapshotsInProgress.get(state).forRepo(repoName)) {
if (entry.shardSnapshotStatusByRepoShardId().isEmpty() == false) {
assertEquals(sourceSnapshot, entry.source().getName());
for (SnapshotsInProgress.ShardSnapshotStatus value : entry.shardSnapshotStatusByRepoShardId().values()) {
assertSame(value, SnapshotsInProgress.ShardSnapshotStatus.UNASSIGNED_QUEUED);
}
return true;
}
}
return false;
});
unblockNode(repoName, masterName);
assertAcked(deleteFuture.get());
assertAcked(cloneFuture.get());
}
public void testManyConcurrentClonesStartOutOfOrder() throws Exception {
// large snapshot pool to allow for concurrently finishing clone while another clone is blocked on trying to load SnapshotInfo
final String masterName = internalCluster().startMasterOnlyNode(LARGE_SNAPSHOT_POOL_SETTINGS);
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "test-idx";
createIndexWithContent(testIndex);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
assertAcked(indicesAdmin().prepareDelete(testIndex).get());
final MockRepository repo = getRepositoryOnMaster(repoName);
repo.setBlockOnceOnReadSnapshotInfoIfAlreadyBlocked();
repo.setBlockOnWriteIndexFile();
final ActionFuture<AcknowledgedResponse> clone1 = startClone(repoName, sourceSnapshot, "target-snapshot-1", testIndex);
// wait for this snapshot to show up in the cluster state
awaitNumberOfSnapshotsInProgress(1);
waitForBlock(masterName, repoName);
final ActionFuture<AcknowledgedResponse> clone2 = startClone(repoName, sourceSnapshot, "target-snapshot-2", testIndex);
awaitNumberOfSnapshotsInProgress(2);
awaitClusterState(state -> SnapshotsInProgress.get(state).forRepo(repoName).stream().anyMatch(entry -> entry.state().completed()));
repo.unblock();
assertAcked(clone1, clone2);
}
public void testRemoveFailedCloneFromCSWithoutIO() throws Exception {
final String masterNode = internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
createIndexWithContent(testIndex);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
final String targetSnapshot = "target-snapshot";
blockAndFailMasterOnShardClone(repoName);
final ActionFuture<AcknowledgedResponse> cloneFuture = startClone(repoName, sourceSnapshot, targetSnapshot, testIndex);
awaitNumberOfSnapshotsInProgress(1);
waitForBlock(masterNode, repoName);
unblockNode(repoName, masterNode);
expectThrows(SnapshotException.class, cloneFuture);
awaitNoMoreRunningOperations();
assertAllSnapshotsSuccessful(getRepositoryData(repoName), 1);
assertAcked(startDeleteSnapshot(repoName, sourceSnapshot).get());
}
public void testRemoveFailedCloneFromCSWithQueuedSnapshotInProgress() throws Exception {
// single threaded master snapshot pool so we can selectively fail part of a clone by letting it run shard by shard
final String masterNode = internalCluster().startMasterOnlyNode(
Settings.builder().put("thread_pool.snapshot.core", 1).put("thread_pool.snapshot.max", 1).build()
);
final String dataNode = internalCluster().startDataOnlyNode(LARGE_SNAPSHOT_POOL_SETTINGS);
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
final String testIndex2 = "index-test-2";
createIndexWithContent(testIndex);
createIndexWithContent(testIndex2);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
final String targetSnapshot = "target-snapshot";
blockAndFailMasterOnShardClone(repoName);
createIndexWithContent("test-index-3");
blockDataNode(repoName, dataNode);
final ActionFuture<CreateSnapshotResponse> fullSnapshotFuture1 = startFullSnapshot(repoName, "full-snapshot-1");
waitForBlock(dataNode, repoName);
// make sure we don't have so many files in the shard that will get blocked to fully clog up the snapshot pool on the data node
final var files = indicesAdmin().prepareStats("test-index-3")
.setSegments(true)
.setIncludeSegmentFileSizes(true)
.get()
.getPrimaries()
.getSegments()
.getFiles();
assertThat(files.size(), lessThan(LARGE_POOL_SIZE));
final ActionFuture<AcknowledgedResponse> cloneFuture = startClone(repoName, sourceSnapshot, targetSnapshot, testIndex, testIndex2);
awaitNumberOfSnapshotsInProgress(2);
waitForBlock(masterNode, repoName);
unblockNode(repoName, masterNode);
final ActionFuture<CreateSnapshotResponse> fullSnapshotFuture2 = startFullSnapshot(repoName, "full-snapshot-2");
expectThrows(SnapshotException.class, cloneFuture);
unblockNode(repoName, dataNode);
awaitNoMoreRunningOperations();
assertSuccessful(fullSnapshotFuture1);
assertSuccessful(fullSnapshotFuture2);
assertAllSnapshotsSuccessful(getRepositoryData(repoName), 3);
assertAcked(startDeleteSnapshot(repoName, sourceSnapshot).get());
}
public void testCloneAfterFailedShardSnapshot() throws Exception {
final String masterNode = internalCluster().startMasterOnlyNode();
final String dataNode = internalCluster().startDataOnlyNode();
final String repoName = "test-repo";
createRepository(repoName, "mock");
final String testIndex = "index-test";
createIndex(testIndex);
final String sourceSnapshot = "source-snapshot";
createFullSnapshot(repoName, sourceSnapshot);
indexRandomDocs(testIndex, randomIntBetween(1, 100));
blockDataNode(repoName, dataNode);
final ActionFuture<CreateSnapshotResponse> snapshotFuture = client(masterNode).admin()
.cluster()
.prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, repoName, "full-snapshot")
.execute();
awaitNumberOfSnapshotsInProgress(1);
waitForBlock(dataNode, repoName);
final ActionFuture<AcknowledgedResponse> cloneFuture = client(masterNode).admin()
.cluster()
.prepareCloneSnapshot(TEST_REQUEST_TIMEOUT, repoName, sourceSnapshot, "target-snapshot")
.setIndices(testIndex)
.execute();
awaitNumberOfSnapshotsInProgress(2);
internalCluster().stopNode(dataNode);
assertAcked(cloneFuture.get());
assertTrue(snapshotFuture.isDone());
}
private ActionFuture<AcknowledgedResponse> startCloneFromDataNode(
String repoName,
String sourceSnapshot,
String targetSnapshot,
String... indices
) {
return startClone(dataNodeClient(), repoName, sourceSnapshot, targetSnapshot, indices);
}
private ActionFuture<AcknowledgedResponse> startClone(
String repoName,
String sourceSnapshot,
String targetSnapshot,
String... indices
) {
return startClone(client(), repoName, sourceSnapshot, targetSnapshot, indices);
}
private static ActionFuture<AcknowledgedResponse> startClone(
Client client,
String repoName,
String sourceSnapshot,
String targetSnapshot,
String... indices
) {
return client.admin()
.cluster()
.prepareCloneSnapshot(TEST_REQUEST_TIMEOUT, repoName, sourceSnapshot, targetSnapshot)
.setIndices(indices)
.execute();
}
private void blockMasterOnReadIndexMeta(String repoName) {
AbstractSnapshotIntegTestCase.<MockRepository>getRepositoryOnMaster(repoName).setBlockOnReadIndexMeta();
}
private void blockMasterOnShardClone(String repoName) {
AbstractSnapshotIntegTestCase.<MockRepository>getRepositoryOnMaster(repoName).setBlockOnWriteShardLevelMeta();
}
private void blockAndFailMasterOnShardClone(String repoName) {
AbstractSnapshotIntegTestCase.<MockRepository>getRepositoryOnMaster(repoName).setBlockAndFailOnWriteShardLevelMeta();
}
/**
* Assert that given {@link RepositoryData} contains exactly the given number of snapshots and all of them are successful.
*/
private static void assertAllSnapshotsSuccessful(RepositoryData repositoryData, int successfulSnapshotCount) {
final Collection<SnapshotId> snapshotIds = repositoryData.getSnapshotIds();
assertThat(snapshotIds, hasSize(successfulSnapshotCount));
for (SnapshotId snapshotId : snapshotIds) {
assertThat(repositoryData.getSnapshotState(snapshotId), is(SnapshotState.SUCCESS));
}
}
private static BlobStoreIndexShardSnapshots readShardGeneration(
BlobStoreRepository repository,
RepositoryShardId repositoryShardId,
ShardGeneration generation
) throws IOException {
return BlobStoreRepository.INDEX_SHARD_SNAPSHOTS_FORMAT.read(
repository.getProjectRepo(),
repository.shardContainer(repositoryShardId.index(), repositoryShardId.shardId()),
generation.getGenerationUUID(),
NamedXContentRegistry.EMPTY
);
}
private static BlobStoreIndexShardSnapshot readShardSnapshot(
BlobStoreRepository repository,
RepositoryShardId repositoryShardId,
SnapshotId snapshotId
) {
return repository.loadShardSnapshot(repository.shardContainer(repositoryShardId.index(), repositoryShardId.shardId()), snapshotId);
}
}
| CloneSnapshotIT |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/JobTable.java | {
"start": 2381,
"end": 4895
} | interface ____ extends AutoCloseable {
/**
* Gets a registered {@link Job} or creates one if not present.
*
* @param jobId jobId identifies the job to get
* @param jobServicesSupplier jobServicesSupplier create new {@link JobTable.JobServices} if a
* new job needs to be created
* @return the current job (existing or created) registered under jobId
* @throws E if the job services could not be created
*/
<E extends Exception> Job getOrCreateJob(
JobID jobId,
SupplierWithException<? extends JobTable.JobServices, E> jobServicesSupplier)
throws E;
/**
* Gets the job registered under jobId.
*
* @param jobId jobId identifying the job to get
* @return an {@code Optional} containing the {@link Job} registered under jobId, or an empty
* {@code Optional} if no job has been registered
*/
Optional<Job> getJob(JobID jobId);
/**
* Gets the connection registered under jobId.
*
* @param jobId jobId identifying the connection to get
* @return an {@code Optional} containing the {@link Connection} registered under jobId, or an
* empty {@code Optional} if no connection has been registered (this could also mean that a
* job which has not been connected exists)
*/
Optional<Connection> getConnection(JobID jobId);
/**
* Gets the connection registered under resourceId.
*
* @param resourceId resourceId identifying the connection to get
* @return an {@code Optional} containing the {@link Connection} registered under resourceId, or
* an empty {@code Optional} if no connection has been registered
*/
Optional<Connection> getConnection(ResourceID resourceId);
/**
* Gets all registered jobs.
*
* @return collection of registered jobs
*/
Collection<Job> getJobs();
/**
* Returns {@code true} if the job table does not contain any jobs.
*
* @return {@code true} if the job table does not contain any jobs, otherwise {@code false}
*/
boolean isEmpty();
/**
* A job contains services which are bound to the lifetime of a Flink job. Moreover, it can be
* connected to a leading JobManager and then store further services which are bound to the
* lifetime of the JobManager connection.
*
* <p>Accessing any methods after a job has been closed will throw an {@link
* IllegalStateException}.
*/
| JobTable |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/core/ConverterTest.java | {
"start": 7366,
"end": 8628
} | class ____
implements ObservableConverter<Integer, Flowable<Integer>>,
ParallelFlowableConverter<Integer, Flowable<Integer>>,
FlowableConverter<Integer, Observable<Integer>>,
MaybeConverter<Integer, Flowable<Integer>>,
SingleConverter<Integer, Flowable<Integer>>,
CompletableConverter<Flowable<Integer>> {
@Override
public Flowable<Integer> apply(ParallelFlowable<Integer> upstream) {
return upstream.sequential();
}
@Override
public Flowable<Integer> apply(Completable upstream) {
return upstream.toFlowable();
}
@Override
public Observable<Integer> apply(Flowable<Integer> upstream) {
return upstream.toObservable();
}
@Override
public Flowable<Integer> apply(Maybe<Integer> upstream) {
return upstream.toFlowable();
}
@Override
public Flowable<Integer> apply(Observable<Integer> upstream) {
return upstream.toFlowable(BackpressureStrategy.MISSING);
}
@Override
public Flowable<Integer> apply(Single<Integer> upstream) {
return upstream.toFlowable();
}
}
}
| CompositeConverter |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/AbstractActionTest.java | {
"start": 1494,
"end": 2174
} | class ____ {
// Test for LOG4J2-2658
@Test
void testExceptionsAreLoggedToStatusLogger() {
final StatusLogger statusLogger = StatusLogger.getLogger();
statusLogger.clear();
new TestAction().run();
final List<StatusData> statusDataList = statusLogger.getStatusData();
assertThat(statusDataList, hasSize(1));
final StatusData statusData = statusDataList.get(0);
assertEquals(Level.WARN, statusData.getLevel());
final String formattedMessage = statusData.getFormattedStatus();
assertThat(
formattedMessage,
containsString("Exception reported by action ' | AbstractActionTest |
java | apache__hadoop | hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/audit/AuditReplayMapper.java | {
"start": 6550,
"end": 7107
} | enum ____ {
APPEND(WRITE),
CREATE(WRITE),
GETFILEINFO(READ),
CONTENTSUMMARY(READ),
MKDIRS(WRITE),
RENAME(WRITE),
LISTSTATUS(READ),
DELETE(WRITE),
OPEN(READ),
SETPERMISSION(WRITE),
SETOWNER(WRITE),
SETTIMES(WRITE),
SETREPLICATION(WRITE),
CONCAT(WRITE);
private final CommandType type;
ReplayCommand(CommandType type) {
this.type = type;
}
public CommandType getType() {
return type;
}
}
/** Define the type of command, either read or write. */
public | ReplayCommand |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java | {
"start": 4023,
"end": 7999
} | class ____ {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private ConfigManager configManager;
@Autowired
private ModuleModel moduleModel;
@Test
void testConfigProps() {
ApplicationConfig applicationConfig = configManager.getApplicationOrElseThrow();
Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName());
MonitorConfig monitorConfig = configManager.getMonitor().get();
Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress());
MetricsConfig metricsConfig = configManager.getMetrics().get();
Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol());
Assertions.assertTrue(metricsConfig.getPrometheus().getPushgateway().getEnabled());
Assertions.assertEquals(
"localhost:9091", metricsConfig.getPrometheus().getPushgateway().getBaseUrl());
Assertions.assertEquals(
"username", metricsConfig.getPrometheus().getPushgateway().getUsername());
Assertions.assertEquals(
"password", metricsConfig.getPrometheus().getPushgateway().getPassword());
Assertions.assertEquals(
"job", metricsConfig.getPrometheus().getPushgateway().getJob());
Assertions.assertEquals(
30, metricsConfig.getPrometheus().getPushgateway().getPushInterval());
Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum());
Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds());
Assertions.assertTrue(metricsConfig.getAggregation().getEnabled());
Assertions.assertTrue(metricsConfig.getHistogram().getEnabled());
List<ProtocolConfig> defaultProtocols = configManager.getDefaultProtocols();
Assertions.assertEquals(1, defaultProtocols.size());
ProtocolConfig protocolConfig = defaultProtocols.get(0);
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(20880, protocolConfig.getPort());
List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries();
Assertions.assertEquals(1, defaultRegistries.size());
RegistryConfig registryConfig = defaultRegistries.get(0);
Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
ConfigCenterConfig centerConfig = configCenters.iterator().next();
Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress1(), centerConfig.getAddress());
Assertions.assertEquals("group1", centerConfig.getGroup());
Collection<MetadataReportConfig> metadataConfigs = configManager.getMetadataConfigs();
Assertions.assertEquals(1, metadataConfigs.size());
MetadataReportConfig reportConfig = metadataConfigs.iterator().next();
Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress2(), reportConfig.getAddress());
Assertions.assertEquals("User", reportConfig.getUsername());
// module configs
ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager();
ModuleConfig moduleConfig = moduleConfigManager.getModule().get();
Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName());
ProviderConfig providerConfig = moduleConfigManager.getDefaultProvider().get();
Assertions.assertEquals("127.0.0.1", providerConfig.getHost());
ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get();
Assertions.assertEquals("netty", consumerConfig.getClient());
}
}
| SpringBootMultipleConfigPropsTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/pl/Oracle_pl_open_for_0.java | {
"start": 922,
"end": 8153
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = "DECLARE\n" +
" sal employees.salary%TYPE;\n" +
" sal_multiple employees.salary%TYPE;\n" +
" factor INTEGER := 2;\n" +
" \n" +
" cv SYS_REFCURSOR;\n" +
" \n" +
"BEGIN\n" +
" DBMS_OUTPUT.PUT_LINE('factor = ' || factor);\n" +
" \n" +
" OPEN cv FOR\n" +
" SELECT salary, salary*factor\n" +
" FROM employees\n" +
" WHERE job_id LIKE 'AD_%'; -- PL/SQL evaluates factor\n" +
" \n" +
" LOOP\n" +
" FETCH cv INTO sal, sal_multiple;\n" +
" EXIT WHEN cv%NOTFOUND;\n" +
" DBMS_OUTPUT.PUT_LINE('sal = ' || sal);\n" +
" DBMS_OUTPUT.PUT_LINE('sal_multiple = ' || sal_multiple);\n" +
" END LOOP;\n" +
" \n" +
" factor := factor + 1;\n" +
" \n" +
" DBMS_OUTPUT.PUT_LINE('factor = ' || factor);\n" +
" \n" +
" OPEN cv FOR\n" +
" SELECT salary, salary*factor\n" +
" FROM employees\n" +
" WHERE job_id LIKE 'AD_%'; -- PL/SQL evaluates factor\n" +
" \n" +
" LOOP\n" +
" FETCH cv INTO sal, sal_multiple;\n" +
" EXIT WHEN cv%NOTFOUND;\n" +
" DBMS_OUTPUT.PUT_LINE('sal = ' || sal);\n" +
" DBMS_OUTPUT.PUT_LINE('sal_multiple = ' || sal_multiple);\n" +
" END LOOP;\n" +
" \n" +
" CLOSE cv;\n" +
"END;";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE);
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE);
for (SQLStatement statement : statementList) {
statement.accept(visitor);
}
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("relationships : " + visitor.getRelationships());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(0, visitor.getTables().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("employees")));
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("emp_name")));
// assertEquals(7, visitor.getColumns().size());
// assertEquals(3, visitor.getConditions().size());
// assertEquals(1, visitor.getRelationships().size());
// assertTrue(visitor.getColumns().contains(new TableStat.Column("employees", "salary")));
{
String output = SQLUtils.toOracleString(stmt);
assertEquals("DECLARE\n" +
"\tsal employees.salary%TYPE;\n" +
"\tsal_multiple employees.salary%TYPE;\n" +
"\tfactor INTEGER := 2;\n" +
"\tcv SYS_REFCURSOR;\n" +
"BEGIN\n" +
"\tDBMS_OUTPUT.PUT_LINE('factor = ' || factor);\n" +
"\tOPEN cv FOR \n" +
"\t\tSELECT salary, salary * factor\n" +
"\t\tFROM employees\n" +
"\t\tWHERE job_id LIKE 'AD_%';\n" +
"\tLOOP\n" +
"\t\tFETCH cv INTO sal, sal_multiple;\n" +
"\t\tEXIT WHEN cv%NOTFOUND;\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal = ' || sal);\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal_multiple = ' || sal_multiple);\n" +
"\tEND LOOP;\n" +
"\tfactor := factor + 1;\n" +
"\tDBMS_OUTPUT.PUT_LINE('factor = ' || factor);\n" +
"\tOPEN cv FOR \n" +
"\t\tSELECT salary, salary * factor\n" +
"\t\tFROM employees\n" +
"\t\tWHERE job_id LIKE 'AD_%';\n" +
"\tLOOP\n" +
"\t\tFETCH cv INTO sal, sal_multiple;\n" +
"\t\tEXIT WHEN cv%NOTFOUND;\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal = ' || sal);\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal_multiple = ' || sal_multiple);\n" +
"\tEND LOOP;\n" +
"\tCLOSE cv;\n" +
"END;", //
output);
}
{
String output = SQLUtils.toOracleString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("declare\n" +
"\tsal employees.salary%TYPE;\n" +
"\tsal_multiple employees.salary%TYPE;\n" +
"\tfactor INTEGER := 2;\n" +
"\tcv SYS_REFCURSOR;\n" +
"begin\n" +
"\tDBMS_OUTPUT.PUT_LINE('factor = ' || factor);\n" +
"\topen cv for \n" +
"\t\tselect salary, salary * factor\n" +
"\t\tfrom employees\n" +
"\t\twhere job_id like 'AD_%';\n" +
"\tloop\n" +
"\t\tfetch cv into sal, sal_multiple;\n" +
"\t\texit when cv%NOTFOUND;\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal = ' || sal);\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal_multiple = ' || sal_multiple);\n" +
"\tend loop;\n" +
"\tfactor := factor + 1;\n" +
"\tDBMS_OUTPUT.PUT_LINE('factor = ' || factor);\n" +
"\topen cv for \n" +
"\t\tselect salary, salary * factor\n" +
"\t\tfrom employees\n" +
"\t\twhere job_id like 'AD_%';\n" +
"\tloop\n" +
"\t\tfetch cv into sal, sal_multiple;\n" +
"\t\texit when cv%NOTFOUND;\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal = ' || sal);\n" +
"\t\tDBMS_OUTPUT.PUT_LINE('sal_multiple = ' || sal_multiple);\n" +
"\tend loop;\n" +
"\tclose cv;\n" +
"end;", //
output);
}
}
}
| Oracle_pl_open_for_0 |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/StackTracePruningTests.java | {
"start": 8163,
"end": 8245
} | class ____ {
@Test
void test() {
}
}
}
}
}
| NestedNestedTestCase |
java | apache__camel | components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agentruntime/BedrockAgentRuntimeProducer.java | {
"start": 1584,
"end": 6804
} | class ____ extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(BedrockAgentRuntimeProducer.class);
private transient String bedrockAgentRuntimeProducerToString;
public BedrockAgentRuntimeProducer(Endpoint endpoint) {
super(endpoint);
}
@Override
public void process(Exchange exchange) throws Exception {
switch (determineOperation(exchange)) {
case retrieveAndGenerate:
retrieveAndGenerate(getEndpoint().getBedrockAgentRuntimeClient(), exchange);
break;
default:
throw new IllegalArgumentException("Unsupported operation");
}
}
private BedrockAgentRuntimeOperations determineOperation(Exchange exchange) {
BedrockAgentRuntimeOperations operation
= exchange.getIn().getHeader(BedrockAgentRuntimeConstants.OPERATION, BedrockAgentRuntimeOperations.class);
if (operation == null) {
operation = getConfiguration().getOperation();
}
return operation;
}
protected BedrockAgentRuntimeConfiguration getConfiguration() {
return getEndpoint().getConfiguration();
}
@Override
public String toString() {
if (bedrockAgentRuntimeProducerToString == null) {
bedrockAgentRuntimeProducerToString
= "BedrockAgentRuntimeProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]";
}
return bedrockAgentRuntimeProducerToString;
}
@Override
public BedrockAgentRuntimeEndpoint getEndpoint() {
return (BedrockAgentRuntimeEndpoint) super.getEndpoint();
}
private void retrieveAndGenerate(BedrockAgentRuntimeClient bedrockAgentRuntimeClient, Exchange exchange)
throws InvalidPayloadException {
if (getConfiguration().isPojoRequest()) {
Object payload = exchange.getMessage().getMandatoryBody();
if (payload instanceof RetrieveAndGenerateRequest) {
RetrieveAndGenerateResponse result;
try {
result = bedrockAgentRuntimeClient.retrieveAndGenerate((RetrieveAndGenerateRequest) payload);
} catch (AwsServiceException ase) {
LOG.trace("Retrieve and Generate command returned the error code {}", ase.awsErrorDetails().errorCode());
throw ase;
}
Message message = getMessageForResponse(exchange);
prepareResponse(result, message);
}
} else {
String inputText = exchange.getMessage().getMandatoryBody(String.class);
KnowledgeBaseVectorSearchConfiguration knowledgeBaseVectorSearchConfiguration
= KnowledgeBaseVectorSearchConfiguration.builder()
.build();
KnowledgeBaseRetrievalConfiguration knowledgeBaseRetrievalConfiguration
= KnowledgeBaseRetrievalConfiguration.builder()
.vectorSearchConfiguration(knowledgeBaseVectorSearchConfiguration)
.build();
KnowledgeBaseRetrieveAndGenerateConfiguration configuration = KnowledgeBaseRetrieveAndGenerateConfiguration
.builder().knowledgeBaseId(getConfiguration().getKnowledgeBaseId())
.modelArn(getConfiguration().getModelId())
.retrievalConfiguration(knowledgeBaseRetrievalConfiguration).build();
RetrieveAndGenerateType type = RetrieveAndGenerateType.KNOWLEDGE_BASE;
RetrieveAndGenerateConfiguration build
= RetrieveAndGenerateConfiguration.builder().knowledgeBaseConfiguration(configuration).type(type).build();
RetrieveAndGenerateInput input = RetrieveAndGenerateInput.builder()
.text(inputText).build();
RetrieveAndGenerateRequest.Builder request = RetrieveAndGenerateRequest.builder();
request.retrieveAndGenerateConfiguration(build).input(input);
if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentRuntimeConstants.SESSION_ID))) {
request.sessionId(exchange.getMessage().getHeader(BedrockAgentRuntimeConstants.SESSION_ID, String.class));
}
RetrieveAndGenerateResponse retrieveAndGenerateResponse
= bedrockAgentRuntimeClient.retrieveAndGenerate(request.build());
Message message = getMessageForResponse(exchange);
prepareResponse(retrieveAndGenerateResponse, message);
}
}
private void prepareResponse(RetrieveAndGenerateResponse result, Message message) {
if (result.hasCitations()) {
message.setHeader(BedrockAgentRuntimeConstants.CITATIONS, result.citations());
}
if (ObjectHelper.isNotEmpty(result.sessionId())) {
message.setHeader(BedrockAgentRuntimeConstants.SESSION_ID, result.sessionId());
}
message.setBody(result.output().text());
}
public static Message getMessageForResponse(final Exchange exchange) {
return exchange.getMessage();
}
}
| BedrockAgentRuntimeProducer |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSNamesystemLock.java | {
"start": 13904,
"end": 17750
} | class ____ in the stack trace
Pattern t1Pattern = Pattern.compile(
String.format(stackTracePatternString, t1.getClass().getName()));
assertTrue(t1Pattern.matcher(logs.getOutput()).find());
Pattern t2Pattern = Pattern.compile(
String.format(stackTracePatternString, t2.getClass().getName()));
assertFalse(t2Pattern.matcher(logs.getOutput()).find());
// match the held interval time in the log
Pattern pattern = Pattern.compile(".*[\n].*\\d+ms(.*[\n].*){1,}");
assertTrue(pattern.matcher(logs.getOutput()).find());
}
@Test
public void testDetailedHoldMetrics() throws Exception {
Configuration conf = new Configuration();
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_LOCK_DETAILED_METRICS_KEY, true);
FakeTimer timer = new FakeTimer();
MetricsRegistry registry = new MetricsRegistry("Test");
MutableRatesWithAggregation rates =
registry.newRatesWithAggregation("Test");
FSNamesystemLock fsLock = new FSNamesystemLock(conf, "FSN", rates, timer);
fsLock.readLock();
timer.advanceNanos(1300000);
fsLock.readUnlock("foo");
fsLock.readLock();
timer.advanceNanos(2400000);
fsLock.readUnlock("foo");
fsLock.readLock();
timer.advance(1);
fsLock.readLock();
timer.advance(1);
fsLock.readUnlock("bar");
fsLock.readUnlock("bar");
fsLock.writeLock();
timer.advance(1);
fsLock.writeUnlock("baz", false);
MetricsRecordBuilder rb = MetricsAsserts.mockMetricsRecordBuilder();
rates.snapshot(rb, true);
assertGauge("FSNReadLockFooNanosAvgTime", 1850000.0, rb);
assertCounter("FSNReadLockFooNanosNumOps", 2L, rb);
assertGauge("FSNReadLockBarNanosAvgTime", 2000000.0, rb);
assertCounter("FSNReadLockBarNanosNumOps", 1L, rb);
assertGauge("FSNWriteLockBazNanosAvgTime", 1000000.0, rb);
assertCounter("FSNWriteLockBazNanosNumOps", 1L, rb);
// Overall
assertGauge("FSNReadLockOverallNanosAvgTime", 1900000.0, rb);
assertCounter("FSNReadLockOverallNanosNumOps", 3L, rb);
assertGauge("FSNWriteLockOverallNanosAvgTime", 1000000.0, rb);
assertCounter("FSNWriteLockOverallNanosNumOps", 1L, rb);
}
/**
* Test to suppress FSNameSystem write lock report when it is held for long
* time.
*/
@Test
@Timeout(value = 45)
public void testFSWriteLockReportSuppressed() throws Exception {
final long writeLockReportingThreshold = 1L;
final long writeLockSuppressWarningInterval = 10L;
Configuration conf = new Configuration();
conf.setLong(
DFSConfigKeys.DFS_NAMENODE_WRITE_LOCK_REPORTING_THRESHOLD_MS_KEY,
writeLockReportingThreshold);
conf.setTimeDuration(DFSConfigKeys.DFS_LOCK_SUPPRESS_WARNING_INTERVAL_KEY,
writeLockSuppressWarningInterval, TimeUnit.MILLISECONDS);
final FakeTimer timer = new FakeTimer();
final FSNamesystemLock fsnLock = new FSNamesystemLock(conf, "FSN", null, timer);
timer.advance(writeLockSuppressWarningInterval);
LogCapturer logs = LogCapturer.captureLogs(FSNamesystem.LOG);
GenericTestUtils
.setLogLevel(LoggerFactory.getLogger(FSNamesystem.class.getName()),
org.slf4j.event.Level.INFO);
// Should trigger the write lock report
fsnLock.writeLock();
timer.advance(writeLockReportingThreshold + 100);
fsnLock.writeUnlock();
assertTrue(logs.getOutput().contains(
"Number of suppressed write-lock reports"));
logs.clearOutput();
// Suppress report if the write lock is held for a long time
fsnLock.writeLock();
timer.advance(writeLockReportingThreshold + 100);
fsnLock.writeUnlock("testFSWriteLockReportSuppressed", true);
assertFalse(logs.getOutput().contains(GenericTestUtils.getMethodName()));
assertFalse(logs.getOutput().contains(
"Number of suppressed write-lock reports:"));
}
} | names |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java | {
"start": 75443,
"end": 75584
} | class ____ {
public void setBean1(PreparingBean1 bean1) {
}
public void setBean2(PreparingBean2 bean2) {
}
}
static | InTheMiddleBean |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorTests.java | {
"start": 11394,
"end": 11494
} | class ____ extends MyParameterizedController<SimpleBean> {
}
private | MySimpleParameterizedController |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/indices/memory/breaker/CircuitBreakerNoopIT.java | {
"start": 1392,
"end": 3903
} | class ____ extends ESIntegTestCase {
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
return Settings.builder()
.put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_TYPE_SETTING.getKey(), "noop")
// This is set low, because if the "noop" is not a noop, it will break
.put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "10b")
.put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_TYPE_SETTING.getKey(), "noop")
// This is set low, because if the "noop" is not a noop, it will break
.put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "10b")
.build();
}
public void testNoopRequestBreaker() throws Exception {
assertAcked(prepareCreate("cb-test", 1, Settings.builder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1))));
Client client = client();
// index some different terms so we have some field data for loading
int docCount = scaledRandomIntBetween(300, 1000);
List<IndexRequestBuilder> reqs = new ArrayList<>();
for (long id = 0; id < docCount; id++) {
reqs.add(client.prepareIndex("cb-test").setId(Long.toString(id)).setSource("test", id));
}
indexRandom(true, reqs);
// A cardinality aggregation uses BigArrays and thus the REQUEST breaker
client.prepareSearch("cb-test").setQuery(matchAllQuery()).addAggregation(cardinality("card").field("test")).get().decRef();
// no exception because the breaker is a noop
}
public void testNoopFielddataBreaker() throws Exception {
assertAcked(prepareCreate("cb-test", 1, Settings.builder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1))));
Client client = client();
// index some different terms so we have some field data for loading
int docCount = scaledRandomIntBetween(300, 1000);
List<IndexRequestBuilder> reqs = new ArrayList<>();
for (long id = 0; id < docCount; id++) {
reqs.add(client.prepareIndex("cb-test").setId(Long.toString(id)).setSource("test", id));
}
indexRandom(true, reqs);
// Sorting using fielddata and thus the FIELDDATA breaker
client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC).get().decRef();
// no exception because the breaker is a noop
}
}
| CircuitBreakerNoopIT |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/matchers/method/MethodInvocationMatcher.java | {
"start": 7329,
"end": 7818
} | class ____ which it is defined, for static methods).
*/
public record ReceiverType(String receiverType) implements Token {
public static ReceiverType create(String receiverType) {
return new ReceiverType(receiverType);
}
@Override
public Object comparisonKey() {
return receiverType();
}
@Override
public TokenType type() {
return TokenType.RECEIVER_TYPE;
}
}
/**
* A token specifying that the | in |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/ExportParameterShardingTest.java | {
"start": 403,
"end": 1979
} | class ____ extends TestCase {
DbType dbType = JdbcConstants.MYSQL;
public void test_exportParameter() throws Exception {
String sql = "select * from t_user_0000 where oid = 1001";
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
assertEquals(1, stmtList.size());
SQLStatement stmt = stmtList.get(0);
StringBuilder out = new StringBuilder();
SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, dbType);
visitor.setParameterized(true);
visitor.setParameterizedMergeInList(true);
List<Object> parameters = visitor.getParameters();
//visitor.setParameters(parameters);
stmt.accept(visitor);
System.out.println(out);
System.out.println(JSON.toJSONString(parameters));
String restoredSql = restore(out.toString(), parameters);
assertEquals("SELECT *\n" +
"FROM t_user_0000\n" +
"WHERE oid = 1001", restoredSql);
}
public String restore(String sql, List<Object> parameters) {
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
assertEquals(1, stmtList.size());
SQLStatement stmt = stmtList.get(0);
StringBuilder out = new StringBuilder();
SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, dbType);
visitor.setInputParameters(parameters);
visitor.addTableMapping("t_user", "t_user_0000");
stmt.accept(visitor);
return out.toString();
}
}
| ExportParameterShardingTest |
java | spring-projects__spring-boot | module/spring-boot-http-converter/src/main/java/org/springframework/boot/http/converter/autoconfigure/ClientHttpMessageConvertersCustomizer.java | {
"start": 1017,
"end": 1265
} | interface ____ {
/**
* Callback to customize a {@link ClientBuilder HttpMessageConverters.ClientBuilder}
* instance.
* @param builder the builder to customize
*/
void customize(ClientBuilder builder);
}
| ClientHttpMessageConvertersCustomizer |
java | quarkusio__quarkus | extensions/liquibase/liquibase/deployment/src/main/java/io/quarkus/liquibase/deployment/LiquibaseProcessor.java | {
"start": 3945,
"end": 11479
} | class ____ {
private static final Logger LOGGER = Logger.getLogger(LiquibaseProcessor.class);
private static final String LIQUIBASE_BEAN_NAME_PREFIX = "liquibase_";
private static final ArtifactCoords LIQUIBASE_ARTIFACT = Dependency.of("org.liquibase", "liquibase-core", "*");
private static final PathFilter LIQUIBASE_RESOURCE_FILTER = PathFilter.forIncludes(List.of(
"*.properties",
"www.liquibase.org/xml/ns/dbchangelog/*.xsd"));
private static final DotName DATABASE_CHANGE_PROPERTY = DotName.createSimple(DatabaseChangeProperty.class.getName());
private static final DotName DATA_TYPE_INFO_ANNOTATION = DotName.createSimple(DataTypeInfo.class.getName());
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.LIQUIBASE);
}
@BuildStep(onlyIf = NativeOrNativeSourcesBuild.class)
IndexDependencyBuildItem indexLiquibase() {
return new IndexDependencyBuildItem(LIQUIBASE_ARTIFACT.getGroupId(), LIQUIBASE_ARTIFACT.getArtifactId());
}
@BuildStep(onlyIf = NativeOrNativeSourcesBuild.class)
void nativeImageConfiguration(
LiquibaseBuildTimeConfig liquibaseBuildConfig,
List<JdbcDataSourceBuildItem> jdbcDataSourceBuildItems,
CombinedIndexBuildItem combinedIndex,
CurateOutcomeBuildItem curateOutcome,
BuildProducer<ReflectiveClassBuildItem> reflective,
BuildProducer<NativeImageResourceBuildItem> resource,
BuildProducer<ServiceProviderBuildItem> services,
BuildProducer<RuntimeInitializedClassBuildItem> runtimeInitialized,
BuildProducer<NativeImageResourceBundleBuildItem> resourceBundle) {
runtimeInitialized.produce(new RuntimeInitializedClassBuildItem(liquibase.diff.compare.CompareControl.class.getName()));
runtimeInitialized.produce(new RuntimeInitializedClassBuildItem(
liquibase.sqlgenerator.core.LockDatabaseChangeLogGenerator.class.getName()));
reflective.produce(ReflectiveClassBuildItem
.builder(liquibase.datatype.core.UnknownType.class.getName())
.reason(getClass().getName())
.constructors().methods()
.build());
reflective.produce(ReflectiveClassBuildItem.builder(
liquibase.AbstractExtensibleObject.class.getName(),
liquibase.change.core.DeleteDataChange.class.getName(),
liquibase.change.core.EmptyChange.class.getName(),
liquibase.database.jvm.JdbcConnection.class.getName(),
liquibase.plugin.AbstractPlugin.class.getName())
.reason(getClass().getName())
.methods()
.build());
reflective.produce(ReflectiveClassBuildItem
.builder(combinedIndex.getIndex().getAllKnownSubclasses(AbstractPluginFactory.class).stream()
.map(classInfo -> classInfo.name().toString())
.toArray(String[]::new))
.reason(getClass().getName())
.constructors().build());
reflective.produce(ReflectiveClassBuildItem.builder(
liquibase.command.CommandFactory.class.getName(),
liquibase.database.LiquibaseTableNamesFactory.class.getName(),
liquibase.configuration.ConfiguredValueModifierFactory.class.getName(),
liquibase.changelog.FastCheckService.class.getName())
.reason(getClass().getName())
.constructors().build());
reflective.produce(ReflectiveClassBuildItem.builder(
liquibase.changelog.RanChangeSet.class.getName(),
liquibase.configuration.LiquibaseConfiguration.class.getName(),
liquibase.parser.ChangeLogParserConfiguration.class.getName(),
liquibase.GlobalConfiguration.class.getName(),
liquibase.executor.ExecutorService.class.getName(),
liquibase.change.ColumnConfig.class.getName(),
liquibase.change.AddColumnConfig.class.getName(),
liquibase.change.core.LoadDataColumnConfig.class.getName())
.reason(getClass().getName())
.constructors().methods().fields().build());
reflective.produce(ReflectiveClassBuildItem.builder(
liquibase.change.ConstraintsConfig.class.getName())
.reason(getClass().getName())
.fields().build());
// liquibase seems to instantiate these types reflectively...
reflective.produce(ReflectiveClassBuildItem.builder(ConcurrentHashMap.class, ArrayList.class)
.reason(getClass().getName())
.build());
// register classes marked with @DatabaseChangeProperty for reflection
Set<String> classesMarkedWithDatabaseChangeProperty = new HashSet<>();
for (AnnotationInstance databaseChangePropertyInstance : combinedIndex.getIndex()
.getAnnotations(DATABASE_CHANGE_PROPERTY)) {
// the annotation is only supported on methods but let's be safe
AnnotationTarget annotationTarget = databaseChangePropertyInstance.target();
if (annotationTarget.kind() == AnnotationTarget.Kind.METHOD) {
classesMarkedWithDatabaseChangeProperty.add(annotationTarget.asMethod().declaringClass().name().toString());
}
}
reflective.produce(
ReflectiveClassBuildItem.builder(classesMarkedWithDatabaseChangeProperty.toArray(new String[0]))
.reason(getClass().getName())
.constructors().methods().fields().build());
// the subclasses of AbstractSqlVisitor are also accessed reflectively
reflective.produce(ReflectiveClassBuildItem.builder(
liquibase.sql.visitor.AbstractSqlVisitor.class.getName(),
liquibase.sql.visitor.AppendSqlIfNotPresentVisitor.class.getName(),
liquibase.sql.visitor.AppendSqlVisitor.class.getName(),
liquibase.sql.visitor.PrependSqlVisitor.class.getName(),
liquibase.sql.visitor.RegExpReplaceSqlVisitor.class.getName(),
liquibase.sql.visitor.ReplaceSqlVisitor.class.getName())
.reason(getClass().getName())
.constructors().methods().fields().build());
// register all liquibase.datatype.core.* data types
Set<String> classesAnnotatedWithDataTypeInfo = combinedIndex.getIndex().getAnnotations(DATA_TYPE_INFO_ANNOTATION)
.stream()
.map(AnnotationInstance::target)
.filter(at -> at.kind() == AnnotationTarget.Kind.CLASS)
.map(at -> at.asClass().name().toString())
.collect(Collectors.toSet());
reflective.produce(ReflectiveClassBuildItem.builder(classesAnnotatedWithDataTypeInfo.toArray(String[]::new))
.reason(getClass().getName())
.constructors().methods()
.build());
Collection<String> dataSourceNames = jdbcDataSourceBuildItems.stream()
.map(JdbcDataSourceBuildItem::getName)
.collect(Collectors.toSet());
resource.produce(
new NativeImageResourceBuildItem(getChangeLogs(dataSourceNames, liquibaseBuildConfig).toArray(new String[0])));
// Register Precondition services, and the implementation | LiquibaseProcessor |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/ingest/TestProcessor.java | {
"start": 919,
"end": 3219
} | class ____ implements Processor {
private final String type;
private final String tag;
private final String description;
private final Function<IngestDocument, IngestDocument> ingestDocumentMapper;
private final AtomicInteger invokedCounter = new AtomicInteger();
public TestProcessor(Consumer<IngestDocument> ingestDocumentConsumer) {
this(null, "test-processor", null, ingestDocumentConsumer);
}
public TestProcessor(RuntimeException e) {
this(null, "test-processor", null, e);
}
public TestProcessor(String tag, String type, String description, RuntimeException e) {
this(tag, type, description, (Consumer<IngestDocument>) i -> { throw e; });
}
public TestProcessor(String tag, String type, String description, Consumer<IngestDocument> ingestDocumentConsumer) {
this(tag, type, description, id -> {
ingestDocumentConsumer.accept(id);
return id;
});
}
public TestProcessor(String tag, String type, String description, Function<IngestDocument, IngestDocument> ingestDocumentMapper) {
this.ingestDocumentMapper = ingestDocumentMapper;
this.type = type;
this.tag = tag;
this.description = description;
}
@Override
public void execute(IngestDocument ingestDocument, BiConsumer<IngestDocument, Exception> handler) {
invokedCounter.incrementAndGet();
try {
ingestDocumentMapper.apply(ingestDocument);
} catch (Exception e) {
if (this.isAsync()) {
handler.accept(null, e);
return;
} else {
throw e;
}
}
handler.accept(ingestDocument, null);
}
@Override
public IngestDocument execute(IngestDocument ingestDocument) throws Exception {
invokedCounter.incrementAndGet();
return ingestDocumentMapper.apply(ingestDocument);
}
@Override
public String getType() {
return type;
}
@Override
public String getTag() {
return tag;
}
@Override
public String getDescription() {
return description;
}
public int getInvokedCounter() {
return invokedCounter.get();
}
public static final | TestProcessor |
java | netty__netty | codec-haproxy/src/main/java/io/netty/handler/codec/haproxy/HAProxyProxiedProtocol.java | {
"start": 4208,
"end": 6303
} | enum ____ {
/**
* The UNSPECIFIED address family represents a connection which was forwarded for an unknown protocol.
*/
AF_UNSPEC(AF_UNSPEC_BYTE),
/**
* The IPV4 address family represents a connection which was forwarded for an IPV4 client.
*/
AF_IPv4(AF_IPV4_BYTE),
/**
* The IPV6 address family represents a connection which was forwarded for an IPV6 client.
*/
AF_IPv6(AF_IPV6_BYTE),
/**
* The UNIX address family represents a connection which was forwarded for a unix socket.
*/
AF_UNIX(AF_UNIX_BYTE);
/**
* The highest 4 bits of the transport protocol and address family byte contain the address family
*/
private static final byte FAMILY_MASK = (byte) 0xf0;
private final byte byteValue;
/**
* Creates a new instance
*/
AddressFamily(byte byteValue) {
this.byteValue = byteValue;
}
/**
* Returns the {@link AddressFamily} represented by the highest 4 bits of the specified byte.
*
* @param tpafByte transport protocol and address family byte
*/
public static AddressFamily valueOf(byte tpafByte) {
int addressFamily = tpafByte & FAMILY_MASK;
switch((byte) addressFamily) {
case AF_IPV4_BYTE:
return AF_IPv4;
case AF_IPV6_BYTE:
return AF_IPv6;
case AF_UNSPEC_BYTE:
return AF_UNSPEC;
case AF_UNIX_BYTE:
return AF_UNIX;
default:
throw new IllegalArgumentException("unknown address family: " + addressFamily);
}
}
/**
* Returns the byte value of this address family.
*/
public byte byteValue() {
return byteValue;
}
}
/**
* The transport protocol of an HAProxy proxy protocol header
*/
public | AddressFamily |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNullTest.java | {
"start": 2848,
"end": 3265
} | class ____ {
@Override
// BUG: Diagnostic contains: if (obj == null) { return false; }
public boolean equals(Object obj) {
if (!ObjectGetClassArgToEquals2.class.equals(obj.getClass())) {
return false;
}
return true;
}
}
private | ObjectGetClassArgToEquals2 |
java | apache__camel | components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/integration/PahoMqtt5ToDIT.java | {
"start": 1070,
"end": 2166
} | class ____ extends PahoMqtt5ITSupport {
@Test
public void testToD() throws Exception {
getMockEndpoint("mock:bar").expectedBodiesReceived("Hello bar");
getMockEndpoint("mock:beer").expectedBodiesReceived("Hello beer");
template.sendBodyAndHeader("direct:start", "Hello bar", "where", "bar");
template.sendBodyAndHeader("direct:start", "Hello beer", "where", "beer");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
PahoMqtt5Component paho = context.getComponent("paho-mqtt5", PahoMqtt5Component.class);
paho.getConfiguration().setBrokerUrl("tcp://localhost:" + mqttPort);
// route message dynamic using toD
from("direct:start").toD("paho-mqtt5:${header.where}");
from("paho-mqtt5:bar").to("mock:bar");
from("paho-mqtt5:beer").to("mock:beer");
}
};
}
}
| PahoMqtt5ToDIT |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/cache/StrategyRegistrationProviderImpl.java | {
"start": 671,
"end": 1037
} | class ____ implements StrategyRegistrationProvider {
@Override
public Iterable<StrategyRegistration<?>> getStrategyRegistrations() {
return singletonList(
new SimpleStrategyRegistrationImpl<>(
RegionFactory.class,
CachingRegionFactory.class,
"testing",
CachingRegionFactory.class.getName()
)
);
}
}
| StrategyRegistrationProviderImpl |
java | spring-projects__spring-boot | module/spring-boot-health/src/test/java/org/springframework/boot/health/contributor/ReactiveHealthContributorTests.java | {
"start": 916,
"end": 2207
} | class ____ {
@Test
void adaptWhenHealthIndicatorReturnsHealthIndicatorReactiveAdapter() {
HealthIndicator indicator = () -> Health.outOfService().build();
ReactiveHealthContributor adapted = ReactiveHealthContributor.adapt(indicator);
assertThat(adapted).isInstanceOf(HealthIndicatorAdapter.class);
Health health = ((ReactiveHealthIndicator) adapted).health().block();
assertThat(health).isNotNull();
assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE);
}
@Test
void adaptWhenCompositeHealthContributorReturnsCompositeHealthContributorReactiveAdapter() {
HealthIndicator indicator = () -> Health.outOfService().build();
CompositeHealthContributor contributor = CompositeHealthContributor
.fromMap(Collections.singletonMap("a", indicator));
ReactiveHealthContributor adapted = ReactiveHealthContributor.adapt(contributor);
assertThat(adapted).isInstanceOf(CompositeHealthContributorAdapter.class);
ReactiveHealthContributor contained = ((CompositeReactiveHealthContributor) adapted).getContributor("a");
assertThat(contained).isNotNull();
Health health = ((ReactiveHealthIndicator) contained).health().block();
assertThat(health).isNotNull();
assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE);
}
}
| ReactiveHealthContributorTests |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsLease.java | {
"start": 2814,
"end": 3730
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(AbfsLease.class);
// Number of retries for acquiring lease
static final int DEFAULT_LEASE_ACQUIRE_MAX_RETRIES = 7;
// Retry interval for acquiring lease in secs
static final int DEFAULT_LEASE_ACQUIRE_RETRY_INTERVAL = 10;
private final AbfsClient client;
private final String path;
private final TracingContext tracingContext;
// Lease status variables
private volatile boolean leaseFreed;
private volatile String leaseID = null;
private volatile Throwable exception = null;
private volatile int acquireRetryCount = 0;
private volatile ListenableScheduledFuture<AbfsRestOperation> future = null;
private final long leaseRefreshDuration;
private final int leaseRefreshDurationInSeconds;
private final Timer timer;
private LeaseTimerTask leaseTimerTask;
private final boolean isAsync;
public static | AbfsLease |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googlevertexai/request/GoogleVertexAiRerankRequestEntityTests.java | {
"start": 778,
"end": 4207
} | class ____ extends ESTestCase {
public void testXContent_SingleRequest_WritesAllFieldsIfDefined() throws IOException {
var entity = new GoogleVertexAiRerankRequestEntity("query", List.of("abc"), Boolean.TRUE, 10, "model");
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
entity.toXContent(builder, null);
String xContentResult = Strings.toString(builder);
assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString("""
{
"model": "model",
"query": "query",
"records": [
{
"id": "0",
"content": "abc"
}
],
"topN": 10,
"ignoreRecordDetailsInResponse": false
}
"""));
}
public void testXContent_SingleRequest_WritesMinimalFields() throws IOException {
var entity = new GoogleVertexAiRerankRequestEntity("query", List.of("abc"), null, null, null);
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
entity.toXContent(builder, null);
String xContentResult = Strings.toString(builder);
assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString("""
{
"query": "query",
"records": [
{
"id": "0",
"content": "abc"
}
]
}
"""));
}
public void testXContent_MultipleRequests_WritesAllFieldsIfDefined() throws IOException {
var entity = new GoogleVertexAiRerankRequestEntity("query", List.of("abc", "def"), Boolean.FALSE, 12, "model");
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
entity.toXContent(builder, null);
String xContentResult = Strings.toString(builder);
assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString("""
{
"model": "model",
"query": "query",
"records": [
{
"id": "0",
"content": "abc"
},
{
"id": "1",
"content": "def"
}
],
"topN": 12,
"ignoreRecordDetailsInResponse": true
}
"""));
}
public void testXContent_MultipleRequests_WritesMinimalFields() throws IOException {
var entity = new GoogleVertexAiRerankRequestEntity("query", List.of("abc", "def"), null, null, null);
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
entity.toXContent(builder, null);
String xContentResult = Strings.toString(builder);
assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString("""
{
"query": "query",
"records": [
{
"id": "0",
"content": "abc"
},
{
"id": "1",
"content": "def"
}
]
}
"""));
}
}
| GoogleVertexAiRerankRequestEntityTests |
java | apache__flink | flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/workflow/EmbeddedRefreshHandler.java | {
"start": 1116,
"end": 2644
} | class ____ implements RefreshHandler, Serializable {
private static final long serialVersionUID = 1L;
private final String workflowName;
private final String workflowGroup;
public EmbeddedRefreshHandler(String workflowName, String workflowGroup) {
this.workflowName = workflowName;
this.workflowGroup = workflowGroup;
}
@Override
public String asSummaryString() {
return String.format(
"{\n workflowName: %s,\n workflowGroup: %s\n}", workflowName, workflowGroup);
}
public String getWorkflowName() {
return workflowName;
}
public String getWorkflowGroup() {
return workflowGroup;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EmbeddedRefreshHandler that = (EmbeddedRefreshHandler) o;
return Objects.equals(workflowName, that.workflowName)
&& Objects.equals(workflowGroup, that.workflowGroup);
}
@Override
public int hashCode() {
return Objects.hash(workflowName, workflowGroup);
}
@Override
public String toString() {
return "EmbeddedRefreshHandler{"
+ "workflowName='"
+ workflowName
+ '\''
+ ", workflowGroup='"
+ workflowGroup
+ '\''
+ '}';
}
}
| EmbeddedRefreshHandler |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/oncrpc/SimpleUdpClient.java | {
"start": 1079,
"end": 3232
} | class ____ {
protected final String host;
protected final int port;
protected final XDR request;
protected final boolean oneShot;
protected final DatagramSocket clientSocket;
private int udpTimeoutMillis;
public SimpleUdpClient(String host, int port, XDR request,
DatagramSocket clientSocket) {
this(host, port, request, true, clientSocket, 500);
}
public SimpleUdpClient(String host, int port, XDR request, Boolean oneShot,
DatagramSocket clientSocket) {
this(host, port, request, oneShot, clientSocket, 500);
}
public SimpleUdpClient(String host, int port, XDR request, Boolean oneShot,
DatagramSocket clientSocket, int udpTimeoutMillis) {
this.host = host;
this.port = port;
this.request = request;
this.oneShot = oneShot;
this.clientSocket = clientSocket;
this.udpTimeoutMillis = udpTimeoutMillis;
}
public void run() throws IOException {
InetAddress IPAddress = InetAddress.getByName(host);
byte[] sendData = request.getBytes();
byte[] receiveData = new byte[65535];
// Use the provided socket if there is one, else just make a new one.
DatagramSocket socket = this.clientSocket == null ?
new DatagramSocket() : this.clientSocket;
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);
socket.send(sendPacket);
socket.setSoTimeout(udpTimeoutMillis);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
socket.receive(receivePacket);
// Check reply status
XDR xdr = new XDR(Arrays.copyOfRange(receiveData, 0,
receivePacket.getLength()));
RpcReply reply = RpcReply.read(xdr);
if (reply.getState() != RpcReply.ReplyState.MSG_ACCEPTED) {
throw new IOException("Request failed: " + reply.getState());
}
} finally {
// If the client socket was passed in to this UDP client, it's on the
// caller of this UDP client to close that socket.
if (this.clientSocket == null) {
socket.close();
}
}
}
}
| SimpleUdpClient |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/session/SqlSessionTest.java | {
"start": 2506,
"end": 26604
} | class ____ extends BaseDataTest {
private static SqlSessionFactory sqlMapper;
@BeforeAll
static void setup() throws Exception {
createBlogDataSource();
final String resource = "org/apache/ibatis/builder/MapperConfig.xml";
final Reader reader = Resources.getResourceAsReader(resource);
sqlMapper = new SqlSessionFactoryBuilder().build(reader);
}
@Test
void shouldResolveBothSimpleNameAndFullyQualifiedName() {
Configuration c = new Configuration();
final String fullName = "com.mycache.MyCache";
final String shortName = "MyCache";
final PerpetualCache cache = new PerpetualCache(fullName);
c.addCache(cache);
assertEquals(cache, c.getCache(fullName));
assertEquals(cache, c.getCache(shortName));
}
@Test
void shouldFailOverToMostApplicableSimpleName() {
Configuration c = new Configuration();
final String fullName = "com.mycache.MyCache";
final String invalidName = "unknown.namespace.MyCache";
final PerpetualCache cache = new PerpetualCache(fullName);
c.addCache(cache);
assertEquals(cache, c.getCache(fullName));
Assertions.assertThrows(IllegalArgumentException.class, () -> c.getCache(invalidName));
}
@Test
void shouldSucceedWhenFullyQualifiedButFailDueToAmbiguity() {
Configuration c = new Configuration();
final String name1 = "com.mycache.MyCache";
final PerpetualCache cache1 = new PerpetualCache(name1);
c.addCache(cache1);
final String name2 = "com.other.MyCache";
final PerpetualCache cache2 = new PerpetualCache(name2);
c.addCache(cache2);
final String shortName = "MyCache";
assertEquals(cache1, c.getCache(name1));
assertEquals(cache2, c.getCache(name2));
try {
c.getCache(shortName);
fail("Exception expected.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("ambiguous"));
}
}
@Test
void shouldFailToAddDueToNameConflict() {
Configuration c = new Configuration();
final String fullName = "com.mycache.MyCache";
final PerpetualCache cache = new PerpetualCache(fullName);
try {
c.addCache(cache);
c.addCache(cache);
fail("Exception expected.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("already contains key"));
}
}
@Test
void shouldOpenAndClose() {
SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE);
session.close();
}
@Test
void shouldCommitAnUnUsedSqlSession() {
try (SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE)) {
session.commit(true);
}
}
@Test
void shouldRollbackAnUnUsedSqlSession() {
try (SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE)) {
session.rollback(true);
}
}
@Test
void shouldSelectAllAuthors() {
try (SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE)) {
List<Author> authors = session.selectList("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAllAuthors");
assertEquals(2, authors.size());
}
}
@Test
void shouldFailWithTooManyResultsException() {
try (SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE)) {
Assertions.assertThrows(TooManyResultsException.class,
() -> session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAllAuthors"));
}
}
@Test
void shouldSelectAllAuthorsAsMap() {
try (SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE)) {
final Map<Integer, Author> authors = session
.selectMap("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAllAuthors", "id");
assertEquals(2, authors.size());
for (Map.Entry<Integer, Author> authorEntry : authors.entrySet()) {
assertEquals(authorEntry.getKey(), (Integer) authorEntry.getValue().getId());
}
}
}
@Test
void shouldSelectCountOfPosts() {
try (SqlSession session = sqlMapper.openSession()) {
Integer count = session.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectCountOfPosts");
assertEquals(5, count.intValue());
}
}
@Test
void shouldEnsureThatBothEarlyAndLateResolutionOfNesteDiscriminatorsResolesToUseNestedResultSetHandler() {
Configuration configuration = sqlMapper.getConfiguration();
assertTrue(
configuration.getResultMap("org.apache.ibatis.domain.blog.mappers.BlogMapper.earlyNestedDiscriminatorPost")
.hasNestedResultMaps());
assertTrue(
configuration.getResultMap("org.apache.ibatis.domain.blog.mappers.BlogMapper.lateNestedDiscriminatorPost")
.hasNestedResultMaps());
}
@Test
void shouldSelectOneAuthor() {
try (SqlSession session = sqlMapper.openSession()) {
Author author = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor",
new Author(101));
assertEquals(101, author.getId());
assertEquals(Section.NEWS, author.getFavouriteSection());
}
}
@Test
void shouldSelectOneAuthorAsList() {
try (SqlSession session = sqlMapper.openSession()) {
List<Author> authors = session.selectList("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor",
new Author(101));
assertEquals(101, authors.get(0).getId());
assertEquals(Section.NEWS, authors.get(0).getFavouriteSection());
}
}
@Test
void shouldSelectOneImmutableAuthor() {
try (SqlSession session = sqlMapper.openSession()) {
ImmutableAuthor author = session
.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectImmutableAuthor", new Author(101));
assertEquals(101, author.getId());
assertEquals(Section.NEWS, author.getFavouriteSection());
}
}
@Test
void shouldSelectOneAuthorWithInlineParams() {
try (SqlSession session = sqlMapper.openSession()) {
Author author = session.selectOne(
"org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthorWithInlineParams", new Author(101));
assertEquals(101, author.getId());
}
}
@Test
void shouldInsertAuthor() {
try (SqlSession session = sqlMapper.openSession()) {
Author expected = new Author(500, "cbegin", "******", "cbegin@somewhere.com", "Something...", null);
int updates = session.insert("org.apache.ibatis.domain.blog.mappers.AuthorMapper.insertAuthor", expected);
assertEquals(1, updates);
Author actual = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor",
new Author(500));
assertNotNull(actual);
assertEquals(expected.getId(), actual.getId());
assertEquals(expected.getUsername(), actual.getUsername());
assertEquals(expected.getPassword(), actual.getPassword());
assertEquals(expected.getEmail(), actual.getEmail());
assertEquals(expected.getBio(), actual.getBio());
}
}
@Test
void shouldUpdateAuthorImplicitRollback() {
try (SqlSession session = sqlMapper.openSession()) {
Author original = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
original.setEmail("new@email.com");
int updates = session.update("org.apache.ibatis.domain.blog.mappers.AuthorMapper.updateAuthor", original);
assertEquals(1, updates);
Author updated = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
assertEquals(original.getEmail(), updated.getEmail());
}
try (SqlSession session = sqlMapper.openSession()) {
Author updated = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
assertEquals("jim@ibatis.apache.org", updated.getEmail());
}
}
@Test
void shouldUpdateAuthorCommit() {
Author original;
try (SqlSession session = sqlMapper.openSession()) {
original = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
original.setEmail("new@email.com");
int updates = session.update("org.apache.ibatis.domain.blog.mappers.AuthorMapper.updateAuthor", original);
assertEquals(1, updates);
Author updated = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
assertEquals(original.getEmail(), updated.getEmail());
session.commit();
}
try (SqlSession session = sqlMapper.openSession()) {
Author updated = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
assertEquals(original.getEmail(), updated.getEmail());
}
}
@Test
void shouldUpdateAuthorIfNecessary() {
Author original;
try (SqlSession session = sqlMapper.openSession()) {
original = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
original.setEmail("new@email.com");
original.setBio(null);
int updates = session.update("org.apache.ibatis.domain.blog.mappers.AuthorMapper.updateAuthorIfNecessary",
original);
assertEquals(1, updates);
Author updated = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
assertEquals(original.getEmail(), updated.getEmail());
session.commit();
}
try (SqlSession session = sqlMapper.openSession()) {
Author updated = session.selectOne("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", 101);
assertEquals(original.getEmail(), updated.getEmail());
}
}
@Test
void shouldDeleteAuthor() {
try (SqlSession session = sqlMapper.openSession()) {
final int id = 102;
List<Author> authors = session.selectList("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", id);
assertEquals(1, authors.size());
int updates = session.delete("org.apache.ibatis.domain.blog.mappers.AuthorMapper.deleteAuthor", id);
assertEquals(1, updates);
authors = session.selectList("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", id);
assertEquals(0, authors.size());
session.rollback();
authors = session.selectList("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", id);
assertEquals(1, authors.size());
}
}
@Test
void shouldSelectBlogWithPostsAndAuthorUsingSubSelects() {
try (SqlSession session = sqlMapper.openSession()) {
Blog blog = session
.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect", 1);
assertEquals("Jim Business", blog.getTitle());
assertEquals(2, blog.getPosts().size());
assertEquals("Corn nuts", blog.getPosts().get(0).getSubject());
assertEquals(101, blog.getAuthor().getId());
assertEquals("jim", blog.getAuthor().getUsername());
}
}
@Test
void shouldSelectBlogWithPostsAndAuthorUsingSubSelectsLazily() {
try (SqlSession session = sqlMapper.openSession()) {
Blog blog = session
.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelectLazily", 1);
Assertions.assertTrue(blog instanceof Proxy);
assertEquals("Jim Business", blog.getTitle());
assertEquals(2, blog.getPosts().size());
assertEquals("Corn nuts", blog.getPosts().get(0).getSubject());
assertEquals(101, blog.getAuthor().getId());
assertEquals("jim", blog.getAuthor().getUsername());
}
}
@Test
void shouldSelectBlogWithPostsAndAuthorUsingJoin() {
try (SqlSession session = sqlMapper.openSession()) {
Blog blog = session
.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogJoinedWithPostsAndAuthor", 1);
assertEquals("Jim Business", blog.getTitle());
final Author author = blog.getAuthor();
assertEquals(101, author.getId());
assertEquals("jim", author.getUsername());
final List<Post> posts = blog.getPosts();
assertEquals(2, posts.size());
final Post post = blog.getPosts().get(0);
assertEquals(1, post.getId());
assertEquals("Corn nuts", post.getSubject());
final List<Comment> comments = post.getComments();
assertEquals(2, comments.size());
final List<Tag> tags = post.getTags();
assertEquals(3, tags.size());
final Comment comment = comments.get(0);
assertEquals(1, comment.getId());
assertEquals(DraftPost.class, blog.getPosts().get(0).getClass());
assertEquals(Post.class, blog.getPosts().get(1).getClass());
}
}
@Test
void shouldSelectNestedBlogWithPostsAndAuthorUsingJoin() {
try (SqlSession session = sqlMapper.openSession()) {
Blog blog = session
.selectOne("org.apache.ibatis.domain.blog.mappers.NestedBlogMapper.selectBlogJoinedWithPostsAndAuthor", 1);
assertEquals("Jim Business", blog.getTitle());
final Author author = blog.getAuthor();
assertEquals(101, author.getId());
assertEquals("jim", author.getUsername());
final List<Post> posts = blog.getPosts();
assertEquals(2, posts.size());
final Post post = blog.getPosts().get(0);
assertEquals(1, post.getId());
assertEquals("Corn nuts", post.getSubject());
final List<Comment> comments = post.getComments();
assertEquals(2, comments.size());
final List<Tag> tags = post.getTags();
assertEquals(3, tags.size());
final Comment comment = comments.get(0);
assertEquals(1, comment.getId());
assertEquals(DraftPost.class, blog.getPosts().get(0).getClass());
assertEquals(Post.class, blog.getPosts().get(1).getClass());
}
}
@Test
void shouldThrowExceptionIfMappedStatementDoesNotExist() {
try (SqlSession session = sqlMapper.openSession()) {
session.selectList("ThisStatementDoesNotExist");
fail("Expected exception to be thrown due to statement that does not exist.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("does not contain value for ThisStatementDoesNotExist"));
}
}
@Test
void shouldThrowExceptionIfTryingToAddStatementWithSameNameInXml() {
Configuration config = sqlMapper.getConfiguration();
try {
MappedStatement ms = new MappedStatement.Builder(config,
"org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect",
Mockito.mock(SqlSource.class), SqlCommandType.SELECT).resource("org/mybatis/TestMapper.xml").build();
config.addMappedStatement(ms);
fail("Expected exception to be thrown due to statement that already exists.");
} catch (Exception e) {
assertTrue(e.getMessage().contains(
"already contains key org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect. please check org/apache/ibatis/builder/BlogMapper.xml and org/mybatis/TestMapper.xml"));
}
}
@Test
void shouldThrowExceptionIfTryingToAddStatementWithSameNameInAnnotation() {
Configuration config = sqlMapper.getConfiguration();
try {
MappedStatement ms = new MappedStatement.Builder(config,
"org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor2", Mockito.mock(SqlSource.class),
SqlCommandType.SELECT).resource("org/mybatis/TestMapper.xml").build();
config.addMappedStatement(ms);
fail("Expected exception to be thrown due to statement that already exists.");
} catch (Exception e) {
assertTrue(e.getMessage().contains(
"already contains key org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor2. please check org/apache/ibatis/domain/blog/mappers/AuthorMapper.java (best guess) and org/mybatis/TestMapper.xml"));
}
}
@Test
void shouldCacheAllAuthors() {
int first;
try (SqlSession session = sqlMapper.openSession()) {
List<Author> authors = session.selectList("org.apache.ibatis.builder.CachedAuthorMapper.selectAllAuthors");
first = System.identityHashCode(authors);
session.commit(); // commit should not be required for read/only activity.
}
int second;
try (SqlSession session = sqlMapper.openSession()) {
List<Author> authors = session.selectList("org.apache.ibatis.builder.CachedAuthorMapper.selectAllAuthors");
second = System.identityHashCode(authors);
}
assertEquals(first, second);
}
@Test
void shouldNotCacheAllAuthors() {
int first;
try (SqlSession session = sqlMapper.openSession()) {
List<Author> authors = session.selectList("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAllAuthors");
first = System.identityHashCode(authors);
}
int second;
try (SqlSession session = sqlMapper.openSession()) {
List<Author> authors = session.selectList("org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAllAuthors");
second = System.identityHashCode(authors);
}
assertTrue(first != second);
}
@Test
void shouldSelectAuthorsUsingMapperClass() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
List<Author> authors = mapper.selectAllAuthors();
assertEquals(2, authors.size());
}
}
@Test
void shouldExecuteSelectOneAuthorUsingMapperClass() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Author author = mapper.selectAuthor(101);
assertEquals(101, author.getId());
}
}
@Test
void shouldExecuteSelectOneAuthorUsingMapperClassThatReturnsALinedHashMap() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
LinkedHashMap<String, Object> author = mapper.selectAuthorLinkedHashMap(101);
assertEquals(101, author.get("ID"));
}
}
@Test
void shouldExecuteSelectAllAuthorsUsingMapperClassThatReturnsSet() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Collection<Author> authors = mapper.selectAllAuthorsSet();
assertEquals(2, authors.size());
}
}
@Test
void shouldExecuteSelectAllAuthorsUsingMapperClassThatReturnsVector() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Collection<Author> authors = mapper.selectAllAuthorsVector();
assertEquals(2, authors.size());
}
}
@Test
void shouldExecuteSelectAllAuthorsUsingMapperClassThatReturnsLinkedList() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Collection<Author> authors = mapper.selectAllAuthorsLinkedList();
assertEquals(2, authors.size());
}
}
@Test
void shouldExecuteSelectAllAuthorsUsingMapperClassThatReturnsAnArray() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Author[] authors = mapper.selectAllAuthorsArray();
assertEquals(2, authors.length);
}
}
@Test
void shouldExecuteSelectOneAuthorUsingMapperClassWithResultHandler() {
try (SqlSession session = sqlMapper.openSession()) {
DefaultResultHandler handler = new DefaultResultHandler();
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
mapper.selectAuthor(101, handler);
Author author = (Author) handler.getResultList().get(0);
assertEquals(101, author.getId());
}
}
@Test
void shouldFailExecutingAnAnnotatedMapperClassWithResultHandler() {
try (SqlSession session = sqlMapper.openSession()) {
DefaultResultHandler handler = new DefaultResultHandler();
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Assertions.assertThrows(BindingException.class, () -> mapper.selectAuthor2(101, handler));
}
}
@Test
void shouldSelectAuthorsUsingMapperClassWithResultHandler() {
try (SqlSession session = sqlMapper.openSession()) {
DefaultResultHandler handler = new DefaultResultHandler();
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
mapper.selectAllAuthors(handler);
assertEquals(2, handler.getResultList().size());
}
}
@Test
void shouldFailSelectOneAuthorUsingMapperClassWithTwoResultHandlers() {
Configuration configuration = new Configuration(sqlMapper.getConfiguration().getEnvironment());
configuration.addMapper(AuthorMapperWithMultipleHandlers.class);
SqlSessionFactory sqlMapperWithMultipleHandlers = new DefaultSqlSessionFactory(configuration);
try (SqlSession sqlSession = sqlMapperWithMultipleHandlers.openSession();) {
DefaultResultHandler handler1 = new DefaultResultHandler();
DefaultResultHandler handler2 = new DefaultResultHandler();
AuthorMapperWithMultipleHandlers mapper = sqlSession.getMapper(AuthorMapperWithMultipleHandlers.class);
Assertions.assertThrows(BindingException.class, () -> mapper.selectAuthor(101, handler1, handler2));
}
}
@Test
void shouldFailSelectOneAuthorUsingMapperClassWithTwoRowBounds() {
Configuration configuration = new Configuration(sqlMapper.getConfiguration().getEnvironment());
configuration.addMapper(AuthorMapperWithRowBounds.class);
SqlSessionFactory sqlMapperWithMultipleHandlers = new DefaultSqlSessionFactory(configuration);
try (SqlSession sqlSession = sqlMapperWithMultipleHandlers.openSession();) {
RowBounds bounds1 = new RowBounds(0, 1);
RowBounds bounds2 = new RowBounds(0, 1);
AuthorMapperWithRowBounds mapper = sqlSession.getMapper(AuthorMapperWithRowBounds.class);
Assertions.assertThrows(BindingException.class, () -> mapper.selectAuthor(101, bounds1, bounds2));
}
}
@Test
void shouldInsertAuthorUsingMapperClass() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Author expected = new Author(500, "cbegin", "******", "cbegin@somewhere.com", "Something...", null);
mapper.insertAuthor(expected);
Author actual = mapper.selectAuthor(500);
assertNotNull(actual);
assertEquals(expected.getId(), actual.getId());
assertEquals(expected.getUsername(), actual.getUsername());
assertEquals(expected.getPassword(), actual.getPassword());
assertEquals(expected.getEmail(), actual.getEmail());
assertEquals(expected.getBio(), actual.getBio());
}
}
@Test
void shouldDeleteAuthorUsingMapperClass() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
int count = mapper.deleteAuthor(101);
assertEquals(1, count);
assertNull(mapper.selectAuthor(101));
}
}
@Test
void shouldUpdateAuthorUsingMapperClass() {
try (SqlSession session = sqlMapper.openSession()) {
AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Author expected = mapper.selectAuthor(101);
expected.setUsername("NewUsername");
int count = mapper.updateAuthor(expected);
assertEquals(1, count);
Author actual = mapper.selectAuthor(101);
assertEquals(expected.getUsername(), actual.getUsername());
}
}
@Test
void shouldSelectAllPostsUsingMapperClass() {
try (SqlSession session = sqlMapper.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
List<Map> posts = mapper.selectAllPosts();
assertEquals(5, posts.size());
}
}
@Test
void shouldLimitResultsUsingMapperClass() {
try (SqlSession session = sqlMapper.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
List<Map> posts = mapper.selectAllPosts(new RowBounds(0, 2), null);
assertEquals(2, posts.size());
assertEquals(1, posts.get(0).get("ID"));
assertEquals(2, posts.get(1).get("ID"));
}
}
private static | SqlSessionTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/Thing.java | {
"start": 210,
"end": 252
} | interface ____ {
String getContent();
}
| Thing |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/placement/csmappingrule/MappingRuleMatcher.java | {
"start": 976,
"end": 1275
} | interface ____ {
/**
* Returns true if the matcher matches the current context.
* @param variables The variable context, which contains all the variables
* @return true if this matcher matches to the provided variable set
*/
boolean match(VariableContext variables);
}
| MappingRuleMatcher |
java | apache__rocketmq | common/src/main/java/org/apache/rocketmq/common/statistics/StatisticsItemFormatter.java | {
"start": 905,
"end": 1408
} | class ____ {
public String format(StatisticsItem statItem) {
final String separator = "|";
StringBuilder sb = new StringBuilder();
sb.append(statItem.getStatKind()).append(separator);
sb.append(statItem.getStatObject()).append(separator);
for (AtomicLong acc : statItem.getItemAccumulates()) {
sb.append(acc.get()).append(separator);
}
sb.append(statItem.getInvokeTimes());
return sb.toString();
}
}
| StatisticsItemFormatter |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/support/AbstractRegexpMethodPointcut.java | {
"start": 1828,
"end": 4055
} | class ____ extends StaticMethodMatcherPointcut
implements Serializable {
/**
* Regular expressions to match.
*/
private String[] patterns = new String[0];
/**
* Regular expressions <strong>not</strong> to match.
*/
private String[] excludedPatterns = new String[0];
/**
* Convenience method when we have only a single pattern.
* Use either this method or {@link #setPatterns}, not both.
* @see #setPatterns
*/
public void setPattern(String pattern) {
setPatterns(pattern);
}
/**
* Set the regular expressions defining methods to match.
* Matching will be the union of all these; if any match, the pointcut matches.
* @see #setPattern
*/
public void setPatterns(String... patterns) {
Assert.notEmpty(patterns, "'patterns' must not be empty");
this.patterns = new String[patterns.length];
for (int i = 0; i < patterns.length; i++) {
this.patterns[i] = patterns[i].strip();
}
initPatternRepresentation(this.patterns);
}
/**
* Return the regular expressions for method matching.
*/
public String[] getPatterns() {
return this.patterns;
}
/**
* Convenience method when we have only a single exclusion pattern.
* Use either this method or {@link #setExcludedPatterns}, not both.
* @see #setExcludedPatterns
*/
public void setExcludedPattern(String excludedPattern) {
setExcludedPatterns(excludedPattern);
}
/**
* Set the regular expressions defining methods to match for exclusion.
* Matching will be the union of all these; if any match, the pointcut matches.
* @see #setExcludedPattern
*/
public void setExcludedPatterns(String... excludedPatterns) {
Assert.notEmpty(excludedPatterns, "'excludedPatterns' must not be empty");
this.excludedPatterns = new String[excludedPatterns.length];
for (int i = 0; i < excludedPatterns.length; i++) {
this.excludedPatterns[i] = excludedPatterns[i].strip();
}
initExcludedPatternRepresentation(this.excludedPatterns);
}
/**
* Returns the regular expressions for exclusion matching.
*/
public String[] getExcludedPatterns() {
return this.excludedPatterns;
}
/**
* Try to match the regular expression against the fully qualified name
* of the target | AbstractRegexpMethodPointcut |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/ConsumerTemplateMaximumCacheSizeTest.java | {
"start": 1295,
"end": 1876
} | class ____ extends SpringRunWithTestSupport {
@Autowired
private ConsumerTemplate template;
@Autowired
private CamelContext context;
@Test
public void testTemplateMaximumCache() throws Exception {
assertNotNull(template, "Should have injected a consumer template");
ConsumerTemplate lookup = context.getRegistry().lookupByNameAndType("template", ConsumerTemplate.class);
assertNotNull(lookup, "Should lookup consumer template");
assertEquals(50, template.getMaximumCacheSize());
}
}
| ConsumerTemplateMaximumCacheSizeTest |
java | apache__camel | components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java | {
"start": 1360,
"end": 3335
} | class ____ implements InterceptStrategy {
private MDCService mdcService;
public MDCProcessorsInterceptStrategy(MDCService mdcService) {
this.mdcService = mdcService;
}
@Override
public Processor wrapProcessorInInterceptors(
final CamelContext context,
final NamedNode definition,
final Processor target,
final Processor nextTarget)
throws Exception {
final AsyncProcessor asyncProcessor = AsyncProcessorConverterHelper.convert(target);
return new AsyncProcessor() {
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
mdcService.setMDC(exchange);
boolean answer = asyncProcessor.process(exchange, doneSync -> {
callback.done(doneSync);
});
mdcService.unsetMDC(exchange);
return answer;
}
@Override
public void process(Exchange exchange) throws Exception {
mdcService.setMDC(exchange);
try {
asyncProcessor.process(exchange);
} finally {
mdcService.unsetMDC(exchange);
}
}
@Override
public CompletableFuture<Exchange> processAsync(Exchange exchange) {
CompletableFuture<Exchange> future = new CompletableFuture<>();
mdcService.setMDC(exchange);
asyncProcessor.process(exchange, doneSync -> {
if (exchange.getException() != null) {
future.completeExceptionally(exchange.getException());
} else {
future.complete(exchange);
}
});
mdcService.unsetMDC(exchange);
return future;
}
};
}
}
| MDCProcessorsInterceptStrategy |
java | apache__hadoop | hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/audit/AuditReplayCommand.java | {
"start": 1729,
"end": 4149
} | class ____ implements Delayed {
private static final Logger LOG = LoggerFactory
.getLogger(AuditReplayCommand.class);
private static final Pattern SIMPLE_UGI_PATTERN = Pattern
.compile("([^/@ ]*).*?");
private Long sequence;
private long absoluteTimestamp;
private String ugi;
private String command;
private String src;
private String dest;
private String sourceIP;
AuditReplayCommand(Long sequence, long absoluteTimestamp, String ugi, String command,
String src, String dest, String sourceIP) {
this.sequence = sequence;
this.absoluteTimestamp = absoluteTimestamp;
this.ugi = ugi;
this.command = command;
this.src = src;
this.dest = dest;
this.sourceIP = sourceIP;
}
Long getSequence() {
return sequence;
}
long getAbsoluteTimestamp() {
return absoluteTimestamp;
}
String getSimpleUgi() {
Matcher m = SIMPLE_UGI_PATTERN.matcher(ugi);
if (m.matches()) {
return m.group(1);
} else {
LOG.error("Error parsing simple UGI <{}>; falling back to current user",
ugi);
try {
return UserGroupInformation.getCurrentUser().getShortUserName();
} catch (IOException ioe) {
return "";
}
}
}
String getCommand() {
return command;
}
String getSrc() {
return src;
}
String getDest() {
return dest;
}
String getSourceIP() {
return sourceIP;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(absoluteTimestamp - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
int result = Long.compare(absoluteTimestamp,
((AuditReplayCommand) o).absoluteTimestamp);
if (result != 0) {
return result;
}
return Long.compare(sequence, ((AuditReplayCommand) o).sequence);
}
/**
* If true, the thread which consumes this item should not process any further
* items and instead simply terminate itself.
*/
boolean isPoison() {
return false;
}
/**
* A command representing a Poison Pill, indicating that the processing thread
* should not process any further items and instead should terminate itself.
* Always returns true for {@link #isPoison()}. It does not contain any other
* information besides a timestamp; other getter methods wil return null.
*/
private static final | AuditReplayCommand |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/BaseInsertOrderingTest.java | {
"start": 1008,
"end": 4357
} | class ____ {
Collection<String> sql;
int size;
Batch(String sql, int size) {
this(List.of(sql), size);
}
Batch(String sql) {
this( sql, 1 );
}
Batch(Collection<String> sql, int size) {
if (sql.isEmpty()) {
throw new IllegalArgumentException( "At least one expected statement is required" );
}
this.sql = sql;
this.size = size;
}
Batch(Collection<String> sql) {
this( sql, 1 );
}
}
private final PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider(
);
@Override
protected void applySettings(StandardServiceRegistryBuilder builer) {
builer.applySetting( Environment.ORDER_INSERTS, "true" );
builer.applySetting( Environment.STATEMENT_BATCH_SIZE, "10" );
ConnectionProvider connectionProvider = (ConnectionProvider) builer.getSettings()
.get( AvailableSettings.CONNECTION_PROVIDER );
this.connectionProvider.setConnectionProvider( connectionProvider );
builer.applySetting( AvailableSettings.CONNECTION_PROVIDER, this.connectionProvider );
builer.applySetting( AvailableSettings.DIALECT_NATIVE_PARAM_MARKERS, false );
builer.applySetting( AvailableSettings.DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG );
}
@AfterAll
public void releaseResources() {
connectionProvider.stop();
}
protected String literal(String value) {
final JdbcType jdbcType = sessionFactory().getTypeConfiguration().getJdbcTypeRegistry().getDescriptor(
Types.VARCHAR
);
return jdbcType.getJdbcLiteralFormatter( StringJavaType.INSTANCE )
.toJdbcLiteral(
value,
sessionFactory().getJdbcServices().getDialect(),
sessionFactory().getWrapperOptions()
);
}
void verifyContainsBatches(Batch... expectedBatches) {
for ( Batch expectedBatch : expectedBatches ) {
PreparedStatement preparedStatement = findPreparedStatement( expectedBatch );
try {
List<Object[]> addBatchCalls = connectionProvider.spyContext.getCalls(
PreparedStatement.class.getMethod( "addBatch" ),
preparedStatement
);
List<Object[]> executeBatchCalls = connectionProvider.spyContext.getCalls(
PreparedStatement.class.getMethod( "executeBatch" ),
preparedStatement
);
assertThat( addBatchCalls.size() ).isEqualTo( expectedBatch.size );
assertThat( executeBatchCalls.size() ).isEqualTo( 1 );
}
catch (Exception e) {
throw new RuntimeException( e );
}
}
}
private PreparedStatement findPreparedStatement(Batch expectedBatch) {
IllegalArgumentException firstException = null;
for (String sql : expectedBatch.sql) {
try {
return connectionProvider.getPreparedStatement( sql );
}
catch ( IllegalArgumentException e ) {
if ( firstException == null ) {
firstException = e;
} else {
firstException.addSuppressed( e );
}
}
}
throw firstException != null
? firstException
: new IllegalArgumentException( "No prepared statement found as none were expected" );
}
void verifyPreparedStatementCount(int expectedBatchCount) {
final int realBatchCount = connectionProvider.getPreparedSQLStatements().size();
assertThat( realBatchCount )
.as( "Expected %d batches, but found %d", expectedBatchCount, realBatchCount )
.isEqualTo( expectedBatchCount );
}
void clearBatches() {
connectionProvider.clear();
}
}
| Batch |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/AutoValueBoxedValuesTest.java | {
"start": 13575,
"end": 14238
} | class ____ {",
" abstract Builder setStringId(String value);",
" abstract Builder setNullableStringId(@Nullable String value);",
" abstract Test build();",
" }"),
lines("}")))
.doTest();
}
@Test
public void mixedTypes_refactoring() {
refactoringHelper
.addInputLines(
"in/Test.java",
mergeLines(
lines(
"import com.google.auto.value.AutoValue;",
"import javax.annotation.Nullable;",
"@AutoValue",
"abstract | Builder |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AccessTests.java | {
"start": 837,
"end": 1219
} | class ____ {
@Test
void capWhenAboveMaximum() {
assertThat(Access.UNRESTRICTED.cap(Access.READ_ONLY)).isEqualTo(Access.READ_ONLY);
}
@Test
void capWhenAtMaximum() {
assertThat(Access.READ_ONLY.cap(Access.READ_ONLY)).isEqualTo(Access.READ_ONLY);
}
@Test
void capWhenBelowMaximum() {
assertThat(Access.NONE.cap(Access.READ_ONLY)).isEqualTo(Access.NONE);
}
}
| AccessTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/transformations/OneInputTransformation.java | {
"start": 2003,
"end": 7740
} | class ____<IN, OUT> extends PhysicalTransformation<OUT> {
private final Transformation<IN> input;
private final StreamOperatorFactory<OUT> operatorFactory;
private KeySelector<IN, ?> stateKeySelector;
private TypeInformation<?> stateKeyType;
/**
* Creates a new {@code OneInputTransformation} from the given input and operator.
*
* @param input The input {@code Transformation}
* @param name The name of the {@code Transformation}, this will be shown in Visualizations and
* the Log
* @param operator The {@code TwoInputStreamOperator}
* @param outputType The type of the elements produced by this {@code OneInputTransformation}
* @param parallelism The parallelism of this {@code OneInputTransformation}
*/
public OneInputTransformation(
Transformation<IN> input,
String name,
OneInputStreamOperator<IN, OUT> operator,
TypeInformation<OUT> outputType,
int parallelism) {
this(input, name, SimpleOperatorFactory.of(operator), outputType, parallelism);
}
public OneInputTransformation(
Transformation<IN> input,
String name,
OneInputStreamOperator<IN, OUT> operator,
TypeInformation<OUT> outputType,
int parallelism,
boolean parallelismConfigured) {
this(
input,
name,
SimpleOperatorFactory.of(operator),
outputType,
parallelism,
parallelismConfigured);
}
public OneInputTransformation(
Transformation<IN> input,
String name,
StreamOperatorFactory<OUT> operatorFactory,
TypeInformation<OUT> outputType,
int parallelism) {
super(name, outputType, parallelism);
this.input = input;
this.operatorFactory = operatorFactory;
}
/**
* Creates a new {@code LegacySinkTransformation} from the given input {@code Transformation}.
*
* @param input The input {@code Transformation}
* @param name The name of the {@code Transformation}, this will be shown in Visualizations and
* the Log
* @param operatorFactory The {@code TwoInputStreamOperator} factory
* @param outputType The type of the elements produced by this {@code OneInputTransformation}
* @param parallelism The parallelism of this {@code OneInputTransformation}
* @param parallelismConfigured If true, the parallelism of the transformation is explicitly set
* and should be respected. Otherwise the parallelism can be changed at runtime.
*/
public OneInputTransformation(
Transformation<IN> input,
String name,
StreamOperatorFactory<OUT> operatorFactory,
TypeInformation<OUT> outputType,
int parallelism,
boolean parallelismConfigured) {
super(name, outputType, parallelism, parallelismConfigured);
this.input = input;
this.operatorFactory = operatorFactory;
}
/** Returns the {@code TypeInformation} for the elements of the input. */
public TypeInformation<IN> getInputType() {
return input.getOutputType();
}
@VisibleForTesting
public OneInputStreamOperator<IN, OUT> getOperator() {
return (OneInputStreamOperator<IN, OUT>)
((SimpleOperatorFactory) operatorFactory).getOperator();
}
/** Returns the {@code StreamOperatorFactory} of this Transformation. */
public StreamOperatorFactory<OUT> getOperatorFactory() {
return operatorFactory;
}
/**
* Sets the {@link KeySelector} that must be used for partitioning keyed state of this
* operation.
*
* @param stateKeySelector The {@code KeySelector} to set
*/
public void setStateKeySelector(KeySelector<IN, ?> stateKeySelector) {
this.stateKeySelector = stateKeySelector;
updateManagedMemoryStateBackendUseCase(stateKeySelector != null);
}
/**
* Returns the {@code KeySelector} that must be used for partitioning keyed state in this
* Operation.
*
* @see #setStateKeySelector
*/
public KeySelector<IN, ?> getStateKeySelector() {
return stateKeySelector;
}
public void setStateKeyType(TypeInformation<?> stateKeyType) {
this.stateKeyType = stateKeyType;
}
public TypeInformation<?> getStateKeyType() {
return stateKeyType;
}
@Override
protected List<Transformation<?>> getTransitivePredecessorsInternal() {
List<Transformation<?>> result = Lists.newArrayList();
result.add(this);
result.addAll(input.getTransitivePredecessors());
return result;
}
@Override
public List<Transformation<?>> getInputs() {
return Collections.singletonList(input);
}
@Override
public final void setChainingStrategy(ChainingStrategy strategy) {
operatorFactory.setChainingStrategy(strategy);
}
public boolean isOutputOnlyAfterEndOfStream() {
return operatorFactory.getOperatorAttributes().isOutputOnlyAfterEndOfStream();
}
public boolean isInternalSorterSupported() {
return operatorFactory.getOperatorAttributes().isInternalSorterSupported();
}
@Override
public void enableAsyncState() {
OneInputStreamOperator<IN, OUT> operator =
(OneInputStreamOperator<IN, OUT>)
((SimpleOperatorFactory<OUT>) operatorFactory).getOperator();
if (!(operator instanceof AsyncKeyOrderedProcessingOperator)) {
super.enableAsyncState();
}
}
}
| OneInputTransformation |
java | apache__camel | components/camel-flink/src/main/java/org/apache/camel/component/flink/FlinkEndpoint.java | {
"start": 1587,
"end": 8309
} | class ____ extends DefaultEndpoint {
@UriPath
@Metadata(required = true)
private EndpointType endpointType;
@UriParam
private DataSet dataSet;
@UriParam
private DataSetCallback dataSetCallback;
@UriParam
private DataStream dataStream;
@UriParam
private DataStreamCallback dataStreamCallback;
@UriParam(defaultValue = "true")
private boolean collect = true;
@UriParam(label = "producer,advanced", enums = "STREAMING,BATCH,AUTOMATIC")
private String executionMode;
@UriParam(label = "producer,advanced")
private Long checkpointInterval;
@UriParam(label = "producer,advanced", enums = "EXACTLY_ONCE,AT_LEAST_ONCE")
private String checkpointingMode;
@UriParam(label = "producer,advanced")
private Integer parallelism;
@UriParam(label = "producer,advanced")
private Integer maxParallelism;
@UriParam(label = "producer,advanced")
private String jobName;
@UriParam(label = "producer,advanced")
private Long checkpointTimeout;
@UriParam(label = "producer,advanced")
private Long minPauseBetweenCheckpoints;
public FlinkEndpoint(String endpointUri, FlinkComponent component, EndpointType endpointType) {
super(endpointUri, component);
this.endpointType = endpointType;
}
@Override
protected void doInit() throws Exception {
super.doInit();
if (dataSet == null) {
dataSet = getComponent().getDataSet();
}
if (dataSetCallback == null) {
dataSetCallback = getComponent().getDataSetCallback();
}
}
@Override
public Producer createProducer() throws Exception {
if (endpointType == EndpointType.dataset) {
return new DataSetFlinkProducer(this);
} else if (endpointType == EndpointType.datastream) {
return new DataStreamFlinkProducer(this);
} else {
return null;
}
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Flink Component supports producer endpoints only.");
}
@Override
public FlinkComponent getComponent() {
return (FlinkComponent) super.getComponent();
}
/**
* Type of the endpoint (dataset, datastream).
*/
public void setEndpointType(EndpointType endpointType) {
this.endpointType = endpointType;
}
public DataSet getDataSet() {
return dataSet;
}
public DataStream getDataStream() {
return dataStream;
}
/**
* DataSet to compute against.
*
* @deprecated The DataSet API is deprecated since Flink 1.12. Use the DataStream API with bounded streams instead.
*/
@Deprecated(since = "4.16.0")
public void setDataSet(DataSet ds) {
this.dataSet = ds;
}
/**
* DataStream to compute against.
*/
public void setDataStream(DataStream ds) {
this.dataStream = ds;
}
public DataSetCallback getDataSetCallback() {
return dataSetCallback;
}
public DataStreamCallback getDataStreamCallback() {
return dataStreamCallback;
}
/**
* Function performing action against a DataSet.
*
* @deprecated The DataSet API is deprecated since Flink 1.12. Use the DataStream API with bounded streams instead.
*/
@Deprecated(since = "4.16.0")
public void setDataSetCallback(DataSetCallback dataSetCallback) {
this.dataSetCallback = dataSetCallback;
}
/**
* Function performing action against a DataStream.
*/
public void setDataStreamCallback(DataStreamCallback dataStreamCallback) {
this.dataStreamCallback = dataStreamCallback;
}
public boolean isCollect() {
return collect;
}
/**
* Indicates if results should be collected or counted.
*/
public void setCollect(boolean collect) {
this.collect = collect;
}
public String getExecutionMode() {
return executionMode;
}
/**
* Execution mode for the Flink job. Options: STREAMING (default), BATCH, AUTOMATIC. BATCH mode is recommended for
* bounded streams (batch processing).
*/
public void setExecutionMode(String executionMode) {
this.executionMode = executionMode;
}
public Long getCheckpointInterval() {
return checkpointInterval;
}
/**
* Interval in milliseconds between checkpoints. Enables checkpointing when set. Recommended for streaming jobs to
* ensure fault tolerance.
*/
public void setCheckpointInterval(Long checkpointInterval) {
this.checkpointInterval = checkpointInterval;
}
public String getCheckpointingMode() {
return checkpointingMode;
}
/**
* Checkpointing mode: EXACTLY_ONCE (default) or AT_LEAST_ONCE. EXACTLY_ONCE provides stronger guarantees but may
* have higher overhead.
*/
public void setCheckpointingMode(String checkpointingMode) {
this.checkpointingMode = checkpointingMode;
}
public Integer getParallelism() {
return parallelism;
}
/**
* Parallelism for the Flink job. If not set, uses the default parallelism of the execution environment.
*/
public void setParallelism(Integer parallelism) {
this.parallelism = parallelism;
}
public Integer getMaxParallelism() {
return maxParallelism;
}
/**
* Maximum parallelism for the Flink job. Defines the upper bound for dynamic scaling and the number of key groups
* for stateful operators.
*/
public void setMaxParallelism(Integer maxParallelism) {
this.maxParallelism = maxParallelism;
}
public String getJobName() {
return jobName;
}
/**
* Name for the Flink job. Useful for identification in the Flink UI and logs.
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
public Long getCheckpointTimeout() {
return checkpointTimeout;
}
/**
* Timeout in milliseconds for checkpoints. Checkpoints that take longer will be aborted.
*/
public void setCheckpointTimeout(Long checkpointTimeout) {
this.checkpointTimeout = checkpointTimeout;
}
public Long getMinPauseBetweenCheckpoints() {
return minPauseBetweenCheckpoints;
}
/**
* Minimum pause in milliseconds between consecutive checkpoints. Helps prevent checkpoint storms under heavy load.
*/
public void setMinPauseBetweenCheckpoints(Long minPauseBetweenCheckpoints) {
this.minPauseBetweenCheckpoints = minPauseBetweenCheckpoints;
}
}
| FlinkEndpoint |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/util/concurrent/SizeBlockingQueueTests.java | {
"start": 853,
"end": 3466
} | class ____ extends ESTestCase {
/*
* Tests that the size of a queue remains at most the capacity while offers are made to a queue when at capacity. This test would have
* previously failed when the size of the queue was incremented and exposed externally even though the item offered to the queue was
* never actually added to the queue.
*/
public void testQueueSize() throws InterruptedException {
final int capacity = randomIntBetween(1, 32);
final BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(capacity);
final SizeBlockingQueue<Integer> sizeBlockingQueue = new SizeBlockingQueue<>(blockingQueue, capacity);
// fill the queue to capacity
for (int i = 0; i < capacity; i++) {
sizeBlockingQueue.offer(i);
}
final int iterations = 1 << 16;
final CyclicBarrier barrier = new CyclicBarrier(2);
// this thread will try to offer items to the queue while the queue size thread is polling the size
final Thread queueOfferThread = new Thread(() -> {
for (int i = 0; i < iterations; i++) {
try {
// synchronize each iteration of checking the size with each iteration of offering, each iteration is a race
barrier.await();
} catch (final BrokenBarrierException | InterruptedException e) {
throw new RuntimeException(e);
}
sizeBlockingQueue.offer(capacity + i);
}
});
queueOfferThread.start();
// this thread will repeatedly poll the size of the queue keeping track of the maximum size that it sees
final AtomicInteger maxSize = new AtomicInteger();
final Thread queueSizeThread = new Thread(() -> {
for (int i = 0; i < iterations; i++) {
try {
// synchronize each iteration of checking the size with each iteration of offering, each iteration is a race
barrier.await();
} catch (final BrokenBarrierException | InterruptedException e) {
throw new RuntimeException(e);
}
maxSize.set(Math.max(maxSize.get(), sizeBlockingQueue.size()));
}
});
queueSizeThread.start();
// wait for the threads to finish
queueOfferThread.join();
queueSizeThread.join();
// the maximum size of the queue should be equal to the capacity
assertThat(maxSize.get(), equalTo(capacity));
}
}
| SizeBlockingQueueTests |
java | apache__flink | flink-state-backends/flink-statebackend-heap-spillable/src/main/java/org/apache/flink/runtime/state/heap/SkipListKeyComparator.java | {
"start": 947,
"end": 3653
} | class ____ {
/**
* Compares for order. Returns a negative integer, zero, or a positive integer as the first node
* is less than, equal to, or greater than the second.
*
* @param left left skip list key's ByteBuffer
* @param leftOffset left skip list key's ByteBuffer's offset
* @param right right skip list key's ByteBuffer
* @param rightOffset right skip list key's ByteBuffer's offset
* @return An integer result of the comparison.
*/
static int compareTo(MemorySegment left, int leftOffset, MemorySegment right, int rightOffset) {
// compare namespace
int leftNamespaceLen = left.getInt(leftOffset);
int rightNamespaceLen = right.getInt(rightOffset);
int c =
left.compare(
right,
leftOffset + Integer.BYTES,
rightOffset + Integer.BYTES,
leftNamespaceLen,
rightNamespaceLen);
if (c != 0) {
return c;
}
// compare key
int leftKeyOffset = leftOffset + Integer.BYTES + leftNamespaceLen;
int rightKeyOffset = rightOffset + Integer.BYTES + rightNamespaceLen;
int leftKeyLen = left.getInt(leftKeyOffset);
int rightKeyLen = right.getInt(rightKeyOffset);
return left.compare(
right,
leftKeyOffset + Integer.BYTES,
rightKeyOffset + Integer.BYTES,
leftKeyLen,
rightKeyLen);
}
/**
* Compares the namespace in the memory segment with the namespace in the node . Returns a
* negative integer, zero, or a positive integer as the first node is less than, equal to, or
* greater than the second.
*
* @param namespaceSegment memory segment to store the namespace.
* @param namespaceOffset offset of namespace in the memory segment.
* @param namespaceLen length of namespace.
* @param nodeSegment memory segment to store the node key.
* @param nodeKeyOffset offset of node key in the memory segment.
* @return An integer result of the comparison.
*/
static int compareNamespaceAndNode(
MemorySegment namespaceSegment,
int namespaceOffset,
int namespaceLen,
MemorySegment nodeSegment,
int nodeKeyOffset) {
int nodeNamespaceLen = nodeSegment.getInt(nodeKeyOffset);
return namespaceSegment.compare(
nodeSegment,
namespaceOffset,
nodeKeyOffset + Integer.BYTES,
namespaceLen,
nodeNamespaceLen);
}
}
| SkipListKeyComparator |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/ShutdownRoute.java | {
"start": 1647,
"end": 1695
} | enum ____ {
Default,
Defer
}
| ShutdownRoute |
java | apache__logging-log4j2 | log4j-core-java9/src/main/java/org/apache/logging/log4j/core/pattern/PlainTextRenderer.java | {
"start": 1057,
"end": 1189
} | class ____ implements TextRenderer {
public static PlainTextRenderer getInstance() {
return null;
}
}
| PlainTextRenderer |
java | quarkusio__quarkus | test-framework/junit5-component/src/main/java/io/quarkus/test/component/MockBeanConfigurator.java | {
"start": 1371,
"end": 1545
} | class ____ used as a bean instance.
*
* @return the test extension
*/
QuarkusComponentTestExtensionBuilder createMockitoMock(Consumer<T> mockInitializer);
} | is |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/boot/BootFailureTest.java | {
"start": 1934,
"end": 2358
} | class ____ extends ClassLoader {
static final List<URL> urls = Arrays.asList( ClassLoaderServiceTestingImpl.INSTANCE.locateResource(
"org/hibernate/orm/test/jpa/boot/META-INF/persistence.xml" ) );
@Override
protected Enumeration<URL> findResources(String name) {
return name.equals( "META-INF/persistence.xml" ) ?
Collections.enumeration( urls ) :
Collections.emptyEnumeration();
}
}
}
| TestClassLoader |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClass.java | {
"start": 8176,
"end": 8582
} | class ____ not be final (CGLIB limitation) unless it does not have to proxy bean methods
if (attributes != null && (Boolean) attributes.get("proxyBeanMethods") && hasNonStaticBeanMethods() &&
this.metadata.isFinal()) {
problemReporter.error(new FinalConfigurationProblem());
}
for (BeanMethod beanMethod : this.beanMethods) {
beanMethod.validate(problemReporter);
}
// A configuration | may |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/aggregations/AggregatorFactoriesBuilderTests.java | {
"start": 1420,
"end": 7931
} | class ____ extends AbstractXContentSerializingTestCase<Builder> {
private NamedWriteableRegistry namedWriteableRegistry;
private NamedXContentRegistry namedXContentRegistry;
@Before
public void setUp() throws Exception {
super.setUp();
// register aggregations as NamedWriteable
SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList());
namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables());
namedXContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
}
@Override
protected NamedWriteableRegistry getNamedWriteableRegistry() {
return namedWriteableRegistry;
}
@Override
protected NamedXContentRegistry xContentRegistry() {
return namedXContentRegistry;
}
@Override
protected Builder doParseInstance(XContentParser parser) throws IOException {
// parseAggregators expects to be already inside the xcontent object
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
AggregatorFactories.Builder builder = AggregatorFactories.parseAggregators(parser);
return builder;
}
@Override
protected Builder createTestInstance() {
AggregatorFactories.Builder builder = new AggregatorFactories.Builder();
// ensure that the unlikely does not happen: 2 aggs share the same name
Set<String> names = new HashSet<>();
for (int i = 0; i < randomIntBetween(1, 20); ++i) {
AggregationBuilder aggBuilder = getRandomAggregation();
if (names.add(aggBuilder.getName())) {
builder.addAggregator(aggBuilder);
}
}
for (int i = 0; i < randomIntBetween(0, 20); ++i) {
PipelineAggregationBuilder aggBuilder = getRandomPipelineAggregation();
if (names.add(aggBuilder.getName())) {
builder.addPipelineAggregator(aggBuilder);
}
}
return builder;
}
@Override
protected Builder mutateInstance(Builder instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Reader<Builder> instanceReader() {
return AggregatorFactories.Builder::new;
}
public void testUnorderedEqualsSubSet() {
Set<String> names = new HashSet<>();
List<AggregationBuilder> aggBuilders = new ArrayList<>();
while (names.size() < 2) {
AggregationBuilder aggBuilder = getRandomAggregation();
if (names.add(aggBuilder.getName())) {
aggBuilders.add(aggBuilder);
}
}
AggregatorFactories.Builder builder1 = new AggregatorFactories.Builder();
AggregatorFactories.Builder builder2 = new AggregatorFactories.Builder();
builder1.addAggregator(aggBuilders.get(0));
builder1.addAggregator(aggBuilders.get(1));
builder2.addAggregator(aggBuilders.get(1));
assertFalse(builder1.equals(builder2));
assertFalse(builder2.equals(builder1));
assertNotEquals(builder1.hashCode(), builder2.hashCode());
builder2.addAggregator(aggBuilders.get(0));
assertTrue(builder1.equals(builder2));
assertTrue(builder2.equals(builder1));
assertEquals(builder1.hashCode(), builder2.hashCode());
builder1.addPipelineAggregator(getRandomPipelineAggregation());
assertFalse(builder1.equals(builder2));
assertFalse(builder2.equals(builder1));
assertNotEquals(builder1.hashCode(), builder2.hashCode());
}
public void testForceExcludedDocs() {
// simple
AggregatorFactories.Builder builder = new AggregatorFactories.Builder();
TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("myterms");
builder.addAggregator(termsAggregationBuilder);
assertFalse(termsAggregationBuilder.excludeDeletedDocs());
assertFalse(builder.hasZeroMinDocTermsAggregation());
termsAggregationBuilder.minDocCount(0);
assertTrue(builder.hasZeroMinDocTermsAggregation());
builder.forceTermsAggsToExcludeDeletedDocs();
assertTrue(termsAggregationBuilder.excludeDeletedDocs());
// nested
AggregatorFactories.Builder nested = new AggregatorFactories.Builder();
boolean hasZeroMinDocTermsAggregation = false;
for (int i = 0; i <= randomIntBetween(1, 10); i++) {
AggregationBuilder agg = getRandomAggregation();
nested.addAggregator(agg);
if (randomBoolean()) {
hasZeroMinDocTermsAggregation = true;
agg.subAggregation(termsAggregationBuilder);
}
}
if (hasZeroMinDocTermsAggregation) {
assertTrue(nested.hasZeroMinDocTermsAggregation());
nested.forceTermsAggsToExcludeDeletedDocs();
for (AggregationBuilder agg : nested.getAggregatorFactories()) {
if (agg instanceof TermsAggregationBuilder) {
assertTrue(((TermsAggregationBuilder) agg).excludeDeletedDocs());
}
}
} else {
assertFalse(nested.hasZeroMinDocTermsAggregation());
}
}
private static AggregationBuilder getRandomAggregation() {
// just a couple of aggregations, sufficient for the purpose of this test
final int randomAggregatorPoolSize = 4;
return switch (randomIntBetween(1, randomAggregatorPoolSize)) {
case 1 -> AggregationBuilders.avg(randomAlphaOfLengthBetween(3, 10)).field("foo");
case 2 -> AggregationBuilders.min(randomAlphaOfLengthBetween(3, 10)).field("foo");
case 3 -> AggregationBuilders.max(randomAlphaOfLengthBetween(3, 10)).field("foo");
case 4 -> AggregationBuilders.sum(randomAlphaOfLengthBetween(3, 10)).field("foo");
default ->
// never reached
null;
};
}
private static PipelineAggregationBuilder getRandomPipelineAggregation() {
// just 1 type of pipeline agg, sufficient for the purpose of this test
String name = randomAlphaOfLengthBetween(3, 20);
String bucketsPath = randomAlphaOfLengthBetween(3, 20);
PipelineAggregationBuilder builder = new CumulativeSumPipelineAggregationBuilder(name, bucketsPath);
return builder;
}
}
| AggregatorFactoriesBuilderTests |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Iif.java | {
"start": 1135,
"end": 2817
} | class ____ extends Case implements OptionalArgument {
public Iif(Source source, Expression condition, Expression thenResult, Expression elseResult) {
super(source, Arrays.asList(new IfConditional(source, condition, thenResult), elseResult != null ? elseResult : Literal.NULL));
}
Iif(Source source, List<Expression> expressions) {
super(source, expressions);
}
@Override
protected NodeInfo<? extends Iif> info() {
return NodeInfo.create(this, Iif::new, combine(conditions(), elseResult()));
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new Iif(source(), newChildren);
}
@Override
protected TypeResolution resolveType() {
if (conditions().isEmpty()) {
return TypeResolution.TYPE_RESOLVED;
}
TypeResolution conditionTypeResolution = isBoolean(conditions().get(0).condition(), sourceText(), FIRST);
if (conditionTypeResolution.unresolved()) {
return conditionTypeResolution;
}
DataType resultDataType = conditions().get(0).dataType();
if (SqlDataTypes.areCompatible(resultDataType, elseResult().dataType()) == false) {
return new TypeResolution(
format(
null,
"third argument of [{}] must be [{}], found value [{}] type [{}]",
sourceText(),
resultDataType.typeName(),
Expressions.name(elseResult()),
elseResult().dataType().typeName()
)
);
}
return TypeResolution.TYPE_RESOLVED;
}
}
| Iif |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/enricher/EnricherSendEventTest.java | {
"start": 3557,
"end": 4079
} | class ____ extends EventNotifierSupport {
final AtomicInteger exchangeSendingEvent = new AtomicInteger();
final AtomicInteger exchangeSentEvent = new AtomicInteger();
@Override
public void notify(CamelEvent event) {
if (event instanceof ExchangeSendingEvent) {
exchangeSendingEvent.incrementAndGet();
} else if (event instanceof ExchangeSentEvent) {
exchangeSentEvent.incrementAndGet();
}
}
}
}
| MyEventNotifier |
java | google__dagger | javatests/dagger/internal/codegen/SwitchingProviderTest.java | {
"start": 8490,
"end": 8649
} | class ____ {}");
Source absent =
CompilerTests.javaSource(
"test.Absent",
"package test;",
"",
" | Present |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/cache/config/ExpressionCachingIntegrationTests.java | {
"start": 2659,
"end": 2876
} | class ____ {
private final String id;
public Order(String id) {
this.id = id;
}
@SuppressWarnings("unused")
public String getId() {
return this.id;
}
}
@Configuration
@EnableCaching
static | Order |
java | apache__camel | components/camel-ical/src/test/java/org/apache/camel/component/ical/ICalDataFormatTest.java | {
"start": 2090,
"end": 5339
} | class ____ extends CamelTestSupport {
private java.util.TimeZone defaultTimeZone;
@Override
public void doPostSetup() {
defaultTimeZone = java.util.TimeZone.getDefault();
java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("America/New_York"));
}
@Override
public void doPostTearDown() {
java.util.TimeZone.setDefault(defaultTimeZone);
}
@Test
public void testUnmarshal() throws Exception {
InputStream stream = IOConverter.toInputStream(new File("src/test/resources/data.ics"));
MockEndpoint endpoint = getMockEndpoint("mock:result");
endpoint.expectedBodiesReceived(createTestCalendar());
template.sendBody("direct:unmarshal", stream);
endpoint.assertIsSatisfied();
}
@Test
public void testMarshal() throws Exception {
Calendar testCalendar = createTestCalendar();
MockEndpoint endpoint = getMockEndpoint("mock:result");
endpoint.expectedBodiesReceived(testCalendar.toString());
template.sendBody("direct:marshal", testCalendar);
endpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:unmarshal")
.unmarshal().ical(true)
.to("mock:result");
from("direct:marshal")
.marshal("ical")
.to("mock:result");
}
};
}
/**
* Creates test calendar instance.
*
* @return ICal calendar object.
*/
protected Calendar createTestCalendar() {
// Create a TimeZone
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timezone = registry.getTimeZone("America/New_York");
VTimeZone tz = timezone.getVTimeZone();
// Create the event
VEvent meeting = new VEvent();
meeting.replace(new DtStamp("20130324T180000Z"));
meeting.add(new DtStart("20130401T170000"));
meeting.add(new DtEnd("20130401T210000"));
meeting.add(new Summary("Progress Meeting"));
// add timezone info..
meeting.add(tz.getTimeZoneId());
// generate unique identifier..
meeting.add(new Uid("00000000"));
// add attendees..
Attendee dev1 = new Attendee(URI.create("mailto:dev1@mycompany.com"));
dev1.add(Role.REQ_PARTICIPANT);
dev1.add(new Cn("Developer 1"));
meeting.add(dev1);
Attendee dev2 = new Attendee(URI.create("mailto:dev2@mycompany.com"));
dev2.add(Role.OPT_PARTICIPANT);
dev2.add(new Cn("Developer 2"));
meeting.add(dev2);
// Create a calendar
net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
icsCalendar.add(ImmutableVersion.VERSION_2_0);
icsCalendar.add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.add(ImmutableCalScale.GREGORIAN);
// Add the event and print
icsCalendar.add(meeting);
return icsCalendar;
}
}
| ICalDataFormatTest |
java | apache__camel | components/camel-rest-openapi/src/main/java/org/apache/camel/component/rest/openapi/validator/RestOpenApiOperation.java | {
"start": 1123,
"end": 2617
} | class ____ {
private final Operation operation;
private final String method;
private final String uriTemplate;
private final Set<Parameter> queryParams;
private final Set<Parameter> formParams;
private final Set<Parameter> headers;
public RestOpenApiOperation(Operation operation, String method, String uriTemplate) {
this.operation = operation;
this.method = method;
this.uriTemplate = uriTemplate;
this.queryParams = resolveParametersForType("query");
this.formParams = resolveParametersForType("form");
this.headers = resolveParametersForType("header");
}
public Operation getOperation() {
return operation;
}
public String getMethod() {
return method;
}
public String getUriTemplate() {
return uriTemplate;
}
public Set<Parameter> getQueryParams() {
return queryParams;
}
public Set<Parameter> getFormParams() {
return formParams;
}
public Set<Parameter> getHeaders() {
return headers;
}
private Set<Parameter> resolveParametersForType(String type) {
List<Parameter> parameters = operation.getParameters();
if (ObjectHelper.isEmpty(parameters)) {
return Collections.emptySet();
}
return parameters.stream()
.filter(parameter -> type.equals(parameter.getIn()))
.collect(Collectors.toUnmodifiableSet());
}
}
| RestOpenApiOperation |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/EqualsHashCodeTestUtils.java | {
"start": 1228,
"end": 1458
} | interface ____<T> {
T copy(T t) throws IOException;
}
/**
* A function that creates a copy of its input argument that is different from its
* input in exactly one aspect (e.g. one parameter of a | CopyFunction |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java | {
"start": 6228,
"end": 10893
} | class ____
String interfaceName = "dubbo.service.io.grpc.examples.helloworld.DubboGreeterGrpc$IGreeter";
s = ConfigUtils.replaceProperty(interfaceName, compositeConfiguration);
Assertions.assertEquals(interfaceName, s);
}
@Test
void testGetProperties1() throws Exception {
try {
SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY);
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY, "properties.load");
Properties p = ConfigUtils.getProperties(Collections.emptySet());
assertThat((String) p.get("a"), equalTo("12"));
assertThat((String) p.get("b"), equalTo("34"));
assertThat((String) p.get("c"), equalTo("56"));
} finally {
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY);
}
}
@Test
void testGetProperties2() throws Exception {
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY);
Properties p = ConfigUtils.getProperties(Collections.emptySet());
assertThat((String) p.get("dubbo"), equalTo("properties"));
}
@Test
void testLoadPropertiesNoFile() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "notExisted", true);
Properties expected = new Properties();
assertEquals(expected, p);
p = ConfigUtils.loadProperties(Collections.emptySet(), "notExisted", false);
assertEquals(expected, p);
}
@Test
void testGetProperty() throws Exception {
assertThat(properties.getProperty("dubbo"), equalTo("properties"));
}
@Test
void testGetPropertyDefaultValue() throws Exception {
assertThat(properties.getProperty("not-exist", "default"), equalTo("default"));
}
@Test
void testGetSystemProperty() throws Exception {
try {
System.setProperty("dubbo", "system-only");
assertThat(ConfigUtils.getSystemProperty("dubbo"), equalTo("system-only"));
} finally {
System.clearProperty("dubbo");
}
}
@Test
void testLoadProperties() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "dubbo.properties");
assertThat((String) p.get("dubbo"), equalTo("properties"));
}
@Test
void testLoadPropertiesOneFile() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "properties.load", false);
Properties expected = new Properties();
expected.put("a", "12");
expected.put("b", "34");
expected.put("c", "56");
assertEquals(expected, p);
}
@Test
void testLoadPropertiesOneFileAllowMulti() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "properties.load", true);
Properties expected = new Properties();
expected.put("a", "12");
expected.put("b", "34");
expected.put("c", "56");
assertEquals(expected, p);
}
@Test
void testLoadPropertiesOneFileNotRootPath() throws Exception {
Properties p = ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool", false);
Properties expected = new Properties();
expected.put("fixed", "org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool");
expected.put("cached", "org.apache.dubbo.common.threadpool.support.cached.CachedThreadPool");
expected.put("limited", "org.apache.dubbo.common.threadpool.support.limited.LimitedThreadPool");
expected.put("eager", "org.apache.dubbo.common.threadpool.support.eager.EagerThreadPool");
assertEquals(expected, p);
}
@Disabled("Not know why disabled, the original link explaining this was reachable.")
@Test
void testLoadPropertiesMultiFileNotRootPathException() throws Exception {
try {
ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/services/org.apache.dubbo.common.status.StatusChecker", false);
Assertions.fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"only 1 META-INF/services/org.apache.dubbo.common.status.StatusChecker file is expected, but 2 dubbo.properties files found on | name |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java | {
"start": 26884,
"end": 27159
} | class ____ {
private int foo = 123;
private int bar = 456;
int getFoo() {
return this.foo;
}
void setFoo(int foo) {
this.foo = foo;
}
int getBar() {
return this.bar;
}
void setBar(int bar) {
this.bar = bar;
}
}
static | ExampleDefaultsBean |
java | quarkusio__quarkus | extensions/google-cloud-functions/runtime/src/main/java/io/quarkus/gcp/functions/QuarkusBackgroundFunction.java | {
"start": 472,
"end": 5390
} | class ____ implements RawBackgroundFunction {
protected static final String deploymentStatus;
protected static boolean started = false;
private static volatile BackgroundFunction delegate;
private static volatile Class<?> parameterType;
private static volatile RawBackgroundFunction rawDelegate;
static {
StringWriter error = new StringWriter();
PrintWriter errorWriter = new PrintWriter(error, true);
if (Application.currentApplication() == null) { // were we already bootstrapped? Needed for mock unit testing.
ClassLoader currentCl = Thread.currentThread().getContextClassLoader();
try {
// For GCP functions, we need to set the TCCL to the QuarkusHttpFunction classloader then restore it.
// Without this, we have a lot of classloading issues (ClassNotFoundException on existing classes)
// during static init.
Thread.currentThread().setContextClassLoader(QuarkusBackgroundFunction.class.getClassLoader());
Class<?> appClass = Class.forName("io.quarkus.runner.ApplicationImpl");
String[] args = {};
Application app = (Application) appClass.getConstructor().newInstance();
app.start(args);
errorWriter.println("Quarkus bootstrapped successfully.");
started = true;
} catch (Exception ex) {
errorWriter.println("Quarkus bootstrap failed.");
ex.printStackTrace(errorWriter);
} finally {
Thread.currentThread().setContextClassLoader(currentCl);
}
} else {
errorWriter.println("Quarkus bootstrapped successfully.");
started = true;
}
deploymentStatus = error.toString();
}
static void setDelegates(String selectedDelegate, String selectedRawDelegate) {
if (selectedDelegate != null) {
try {
Class<?> clazz = Class.forName(selectedDelegate, false, Thread.currentThread().getContextClassLoader());
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals("accept")) {
// the first parameter of the accept method is the event, we need to register it's type to
// be able to deserialize to it to mimic what a BackgroundFunction does
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes[0] != Object.class) {// FIXME we have two accept methods !!!
parameterType = parameterTypes[0];
}
}
}
delegate = (BackgroundFunction) Arc.container().instance(clazz).get();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
if (selectedRawDelegate != null) {
try {
Class<?> clazz = Class.forName(selectedRawDelegate, false, Thread.currentThread().getContextClassLoader());
rawDelegate = (RawBackgroundFunction) Arc.container().instance(clazz).get();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void accept(String event, Context context) throws Exception {
if (!started) {
throw new IOException(deploymentStatus);
}
// TODO maybe we can check this at static init
if ((delegate == null && rawDelegate == null) || (delegate != null && rawDelegate != null)) {
throw new IOException("We didn't found any BackgroundFunction or RawBackgroundFunction to run " +
"(or there is multiple one and none selected inside your application.properties)");
}
if (rawDelegate != null) {
rawDelegate.accept(event, context);
} else {
// here we emulate a BackgroundFunction from a RawBackgroundFunction
// so we need to un-marshall the JSON into the delegate parameter type
// this is done via Gson as it's the library that GCF uses internally for the same purpose
// see NewBackgroundFunctionExecutor.TypedFunctionExecutor<T>
// from the functions-framework-java https://github.com/GoogleCloudPlatform/functions-framework-java
Gson gson = new Gson();
try {
Object eventObj = gson.fromJson(event, parameterType);
delegate.accept(eventObj, context);
} catch (JsonParseException e) {
throw new RuntimeException("Could not parse received event payload into type "
+ parameterType.getCanonicalName(), e);
}
}
}
}
| QuarkusBackgroundFunction |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/bulk/BulkRequestBuilder.java | {
"start": 1753,
"end": 9913
} | class ____ extends ActionRequestLazyBuilder<BulkRequest, BulkResponse>
implements
WriteRequestBuilder<BulkRequestBuilder> {
private final String globalIndex;
/*
* The following 3 variables hold the list of requests that make up this bulk. Only one can be non-empty. That is, users can't add
* some IndexRequests and some IndexRequestBuilders. They need to pick one (preferably builders) and stick with it.
*/
private final List<DocWriteRequest<?>> requests = new ArrayList<>();
private final List<FramedData> framedData = new ArrayList<>();
private final Deque<ActionRequestLazyBuilder<? extends DocWriteRequest<?>, ? extends DocWriteResponse>> requestBuilders =
new ArrayDeque<>();
private ActiveShardCount waitForActiveShards;
private TimeValue timeout;
private String globalPipeline;
private String globalRouting;
private WriteRequest.RefreshPolicy refreshPolicy;
private boolean requestPreviouslyCalled = false;
public BulkRequestBuilder(ElasticsearchClient client, @Nullable String globalIndex) {
super(client, TransportBulkAction.TYPE);
this.globalIndex = globalIndex;
}
public BulkRequestBuilder(ElasticsearchClient client) {
this(client, null);
}
/**
* Adds an {@link IndexRequest} to the list of actions to execute. Follows the same behavior of {@link IndexRequest}
* (for example, if no id is provided, one will be generated, or usage of the create flag).
* @deprecated use {@link #add(IndexRequestBuilder)} instead
*/
@Deprecated
public BulkRequestBuilder add(IndexRequest request) {
requests.add(request);
return this;
}
/**
* Adds an {@link IndexRequest} to the list of actions to execute. Follows the same behavior of {@link IndexRequest}
* (for example, if no id is provided, one will be generated, or usage of the create flag).
*/
public BulkRequestBuilder add(IndexRequestBuilder request) {
requestBuilders.add(request);
return this;
}
/**
* Adds an {@link DeleteRequest} to the list of actions to execute.
* @deprecated use {@link #add(DeleteRequestBuilder)} instead
*/
@Deprecated
public BulkRequestBuilder add(DeleteRequest request) {
requests.add(request);
return this;
}
/**
* Adds an {@link DeleteRequest} to the list of actions to execute.
*/
public BulkRequestBuilder add(DeleteRequestBuilder request) {
requestBuilders.add(request);
return this;
}
/**
* Adds an {@link UpdateRequest} to the list of actions to execute.
* @deprecated use {@link #add(UpdateRequestBuilder)} instead
*/
@Deprecated
public BulkRequestBuilder add(UpdateRequest request) {
requests.add(request);
return this;
}
/**
* Adds an {@link UpdateRequest} to the list of actions to execute.
*/
public BulkRequestBuilder add(UpdateRequestBuilder request) {
requestBuilders.add(request);
return this;
}
/**
* Adds a framed data in binary format
*/
public BulkRequestBuilder add(byte[] data, int from, int length, XContentType xContentType) throws Exception {
framedData.add(new FramedData(data, from, length, null, xContentType));
return this;
}
/**
* Adds a framed data in binary format
*/
public BulkRequestBuilder add(byte[] data, int from, int length, @Nullable String defaultIndex, XContentType xContentType)
throws Exception {
framedData.add(new FramedData(data, from, length, defaultIndex, xContentType));
return this;
}
/**
* Sets the number of shard copies that must be active before proceeding with the write.
* See {@link ReplicationRequest#waitForActiveShards(ActiveShardCount)} for details.
*/
public BulkRequestBuilder setWaitForActiveShards(ActiveShardCount waitForActiveShards) {
this.waitForActiveShards = waitForActiveShards;
return this;
}
/**
* A shortcut for {@link #setWaitForActiveShards(ActiveShardCount)} where the numerical
* shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)}
* to get the ActiveShardCount.
*/
public BulkRequestBuilder setWaitForActiveShards(final int waitForActiveShards) {
return setWaitForActiveShards(ActiveShardCount.from(waitForActiveShards));
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to {@code 1m}.
*/
public final BulkRequestBuilder setTimeout(TimeValue timeout) {
this.timeout = timeout;
return this;
}
/**
* The number of actions currently in the bulk.
*/
public int numberOfActions() {
return requests.size() + requestBuilders.size() + framedData.size();
}
public BulkRequestBuilder pipeline(String globalPipeline) {
this.globalPipeline = globalPipeline;
return this;
}
public BulkRequestBuilder routing(String globalRouting) {
this.globalRouting = globalRouting;
return this;
}
@Override
public BulkRequestBuilder setRefreshPolicy(WriteRequest.RefreshPolicy refreshPolicy) {
this.refreshPolicy = refreshPolicy;
return this;
}
@Override
public BulkRequestBuilder setRefreshPolicy(String refreshPolicy) {
this.refreshPolicy = WriteRequest.RefreshPolicy.parse(refreshPolicy);
return this;
}
@Override
public BulkRequest request() {
assert requestPreviouslyCalled == false : "Cannot call request() multiple times on the same BulkRequestBuilder object";
if (requestPreviouslyCalled) {
throw new IllegalStateException("Cannot call request() multiple times on the same BulkRequestBuilder object");
}
requestPreviouslyCalled = true;
validate();
BulkRequest request = new BulkRequest(globalIndex);
/*
* In the following loop we intentionally remove the builders from requestBuilders so that they can be garbage collected. This is
* so that we don't require double the memory of all of the inner requests, which could be really bad for a lage bulk request.
*/
for (var builder = requestBuilders.pollFirst(); builder != null; builder = requestBuilders.pollFirst()) {
request.add(builder.request());
}
for (DocWriteRequest<?> childRequest : requests) {
request.add(childRequest);
}
for (FramedData framedData : framedData) {
try {
request.add(framedData.data, framedData.from, framedData.length, framedData.defaultIndex, framedData.xContentType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (waitForActiveShards != null) {
request.waitForActiveShards(waitForActiveShards);
}
if (timeout != null) {
request.timeout(timeout);
}
if (globalPipeline != null) {
request.pipeline(globalPipeline);
}
if (globalRouting != null) {
request.routing(globalRouting);
}
if (refreshPolicy != null) {
request.setRefreshPolicy(refreshPolicy);
}
return request;
}
private void validate() {
if (countNonEmptyCollections(requestBuilders, requests, framedData) > 1) {
throw new IllegalStateException(
"Must use only request builders, requests, or byte arrays within a single bulk request. Cannot mix and match"
);
}
}
private int countNonEmptyCollections(Collection<?>... collections) {
int sum = 0;
for (Collection<?> collection : collections) {
if (collection.isEmpty() == false) {
sum++;
}
}
return sum;
}
private record FramedData(byte[] data, int from, int length, @Nullable String defaultIndex, XContentType xContentType) {}
}
| BulkRequestBuilder |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/objectid/TestObjectIdWithPolymorphic.java | {
"start": 2176,
"end": 2477
} | class ____ extends Activity {
public final List<FaultHandler> faultHandlers = new ArrayList<FaultHandler>();
public Scope(Process owner, Activity parent) {
super(owner, parent);
}
protected Scope() {
super();
}
}
public static | Scope |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestDeleteRace.java | {
"start": 6913,
"end": 15327
} | class ____ extends SubjectInheritingThread {
private FileSystem fs;
private Path from;
private Path to;
RenameThread(FileSystem fs, Path from, Path to) {
this.fs = fs;
this.from = from;
this.to = to;
}
@Override
public void work() {
try {
Thread.sleep(1000);
LOG.info("Renaming " + from + " to " + to);
fs.rename(from, to);
LOG.info("Renamed " + from + " to " + to);
} catch (Exception e) {
LOG.info(e.toString());
}
}
}
@Test
public void testRenameRace() throws Exception {
try {
conf.setClass(DFSConfigKeys.DFS_BLOCK_REPLICATOR_CLASSNAME_KEY,
SlowBlockPlacementPolicy.class, BlockPlacementPolicy.class);
cluster = new MiniDFSCluster.Builder(conf).build();
FileSystem fs = cluster.getFileSystem();
Path dirPath1 = new Path("/testRenameRace1");
Path dirPath2 = new Path("/testRenameRace2");
Path filePath = new Path("/testRenameRace1/file1");
fs.mkdirs(dirPath1);
FSDataOutputStream out = fs.create(filePath);
Thread renameThread = new RenameThread(fs, dirPath1, dirPath2);
renameThread.start();
// write data and close to make sure a block is allocated.
out.write(new byte[32], 0, 32);
out.close();
// Restart name node so that it replays edit. If old path was
// logged in edit, it will fail to come up.
cluster.restartNameNode(0);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Test race between delete operation and commitBlockSynchronization method.
* See HDFS-6825.
* @param hasSnapshot
* @throws Exception
*/
private void testDeleteAndCommitBlockSynchronizationRace(boolean hasSnapshot)
throws Exception {
LOG.info("Start testing, hasSnapshot: " + hasSnapshot);
ArrayList<AbstractMap.SimpleImmutableEntry<String, Boolean>> testList =
new ArrayList<AbstractMap.SimpleImmutableEntry<String, Boolean>> ();
testList.add(
new AbstractMap.SimpleImmutableEntry<String, Boolean>("/test-file", false));
testList.add(
new AbstractMap.SimpleImmutableEntry<String, Boolean>("/test-file1", true));
testList.add(
new AbstractMap.SimpleImmutableEntry<String, Boolean>(
"/testdir/testdir1/test-file", false));
testList.add(
new AbstractMap.SimpleImmutableEntry<String, Boolean>(
"/testdir/testdir1/test-file1", true));
final Path rootPath = new Path("/");
final Configuration conf = new Configuration();
// Disable permissions so that another user can recover the lease.
conf.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
FSDataOutputStream stm = null;
Map<DataNode, DatanodeProtocolClientSideTranslatorPB> dnMap =
new HashMap<DataNode, DatanodeProtocolClientSideTranslatorPB>();
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(3)
.build();
cluster.waitActive();
DistributedFileSystem fs = cluster.getFileSystem();
int stId = 0;
for(AbstractMap.SimpleImmutableEntry<String, Boolean> stest : testList) {
String testPath = stest.getKey();
Boolean mkSameDir = stest.getValue();
LOG.info("test on " + testPath + " mkSameDir: " + mkSameDir
+ " snapshot: " + hasSnapshot);
Path fPath = new Path(testPath);
//find grandest non-root parent
Path grandestNonRootParent = fPath;
while (!grandestNonRootParent.getParent().equals(rootPath)) {
grandestNonRootParent = grandestNonRootParent.getParent();
}
stm = fs.create(fPath);
LOG.info("test on " + testPath + " created " + fPath);
// write a half block
AppendTestUtil.write(stm, 0, BLOCK_SIZE / 2);
stm.hflush();
if (hasSnapshot) {
SnapshotTestHelper.createSnapshot(fs, rootPath,
"st" + String.valueOf(stId));
++stId;
}
// Look into the block manager on the active node for the block
// under construction.
NameNode nn = cluster.getNameNode();
ExtendedBlock blk = DFSTestUtil.getFirstBlock(fs, fPath);
DatanodeDescriptor expectedPrimary =
DFSTestUtil.getExpectedPrimaryNode(nn, blk);
LOG.info("Expecting block recovery to be triggered on DN " +
expectedPrimary);
// Find the corresponding DN daemon, and spy on its connection to the
// active.
DataNode primaryDN = cluster.getDataNode(expectedPrimary.getIpcPort());
DatanodeProtocolClientSideTranslatorPB nnSpy = dnMap.get(primaryDN);
if (nnSpy == null) {
nnSpy = InternalDataNodeTestUtils.spyOnBposToNN(primaryDN, nn);
dnMap.put(primaryDN, nnSpy);
}
// Delay the commitBlockSynchronization call
DelayAnswer delayer = new DelayAnswer(LOG);
Mockito.doAnswer(delayer).when(nnSpy).commitBlockSynchronization(
Mockito.eq(blk),
Mockito.anyLong(), // new genstamp
Mockito.anyLong(), // new length
Mockito.eq(true), // close file
Mockito.eq(false), // delete block
Mockito.any(), // new targets
Mockito.any()); // new target storages
fs.recoverLease(fPath);
LOG.info("Waiting for commitBlockSynchronization call from primary");
delayer.waitForCall();
LOG.info("Deleting recursively " + grandestNonRootParent);
fs.delete(grandestNonRootParent, true);
if (mkSameDir && !grandestNonRootParent.toString().equals(testPath)) {
LOG.info("Recreate dir " + grandestNonRootParent + " testpath: "
+ testPath);
fs.mkdirs(grandestNonRootParent);
}
delayer.proceed();
LOG.info("Now wait for result");
delayer.waitForResult();
Throwable t = delayer.getThrown();
if (t != null) {
LOG.info("Result exception (snapshot: " + hasSnapshot + "): " + t);
}
} // end of loop each fPath
LOG.info("Now check we can restart");
cluster.restartNameNodes();
LOG.info("Restart finished");
} finally {
if (stm != null) {
IOUtils.closeStream(stm);
}
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test
@Timeout(value = 600)
public void testDeleteAndCommitBlockSynchonizationRaceNoSnapshot()
throws Exception {
testDeleteAndCommitBlockSynchronizationRace(false);
}
@Test
@Timeout(value = 600)
public void testDeleteAndCommitBlockSynchronizationRaceHasSnapshot()
throws Exception {
testDeleteAndCommitBlockSynchronizationRace(true);
}
/**
* Test the sequence of deleting a file that has snapshot,
* and lease manager's hard limit recovery.
*/
@Test
public void testDeleteAndLeaseRecoveryHardLimitSnapshot() throws Exception {
final Path rootPath = new Path("/");
final Configuration config = new Configuration();
// Disable permissions so that another user can recover the lease.
config.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
config.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
long leaseRecheck = 1000;
conf.setLong(DFS_NAMENODE_LEASE_RECHECK_INTERVAL_MS_KEY, leaseRecheck);
conf.setLong(DFS_LEASE_HARDLIMIT_KEY, leaseRecheck/1000);
FSDataOutputStream stm = null;
try {
cluster = new MiniDFSCluster.Builder(config).numDataNodes(3).build();
cluster.waitActive();
final DistributedFileSystem fs = cluster.getFileSystem();
final Path testPath = new Path("/testfile");
stm = fs.create(testPath);
LOG.info("test on " + testPath);
// write a half block
AppendTestUtil.write(stm, 0, BLOCK_SIZE / 2);
stm.hflush();
// create a snapshot, so delete does not release the file's inode.
SnapshotTestHelper.createSnapshot(fs, rootPath, "snap");
// delete the file without closing it.
fs.delete(testPath, false);
// write enough bytes to trigger an addBlock, which would fail in
// the streamer.
AppendTestUtil.write(stm, 0, BLOCK_SIZE);
// wait for lease manager's background 'Monitor' | RenameThread |
java | apache__flink | flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/aftermatch/SkipRelativeToWholeMatchStrategy.java | {
"start": 917,
"end": 1332
} | class ____ extends AfterMatchSkipStrategy {
private static final long serialVersionUID = -3214720554878479037L;
@Override
public final boolean isSkipStrategy() {
return true;
}
@Override
protected final boolean shouldPrune(EventId startEventID, EventId pruningId) {
return startEventID != null && startEventID.compareTo(pruningId) <= 0;
}
}
| SkipRelativeToWholeMatchStrategy |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/FlowableComponentBuilderFactory.java | {
"start": 5379,
"end": 6289
} | class ____
extends AbstractComponentBuilder<FlowableComponent>
implements FlowableComponentBuilder {
@Override
protected FlowableComponent buildConcreteComponent() {
return new FlowableComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "bridgeErrorHandler": ((FlowableComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "lazyStartProducer": ((FlowableComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((FlowableComponent) component).setAutowiredEnabled((boolean) value); return true;
default: return false;
}
}
}
} | FlowableComponentBuilderImpl |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/dev/HibernateOrmDevUIProcessor.java | {
"start": 1126,
"end": 4364
} | class ____ {
@BuildStep
public CardPageBuildItem create(HibernateOrmConfig config) {
CardPageBuildItem card = new CardPageBuildItem();
card.setLogo("hibernate_icon_dark.svg", "hibernate_icon_light.svg");
card.addLibraryVersion("org.hibernate.orm", "hibernate-core", "Hibernate", "https://hibernate.org/orm/");
card.addLibraryVersion("jakarta.persistence", "jakarta.persistence-api", "Jakarta Persistence",
"https://jakarta.ee/specifications/persistence/");
card.addPage(Page.webComponentPageBuilder()
.title("Persistence Units")
.componentLink("hibernate-orm-persistence-units.js")
.icon("font-awesome-solid:boxes-stacked")
.dynamicLabelJsonRPCMethodName("getNumberOfPersistenceUnits"));
card.addPage(Page.webComponentPageBuilder()
.title("Entity Types")
.componentLink("hibernate-orm-entity-types.js")
.icon("font-awesome-solid:table")
.dynamicLabelJsonRPCMethodName("getNumberOfEntityTypes"));
card.addPage(Page.webComponentPageBuilder()
.title("Named Queries")
.componentLink("hibernate-orm-named-queries.js")
.icon("font-awesome-solid:circle-question")
.dynamicLabelJsonRPCMethodName("getNumberOfNamedQueries"));
card.addPage(Page.webComponentPageBuilder()
.title("HQL Console")
.componentLink("hibernate-orm-hql-console.js")
.icon("font-awesome-solid:play"));
return card;
}
@BuildStep
JsonRPCProvidersBuildItem createJsonRPCService() {
return new JsonRPCProvidersBuildItem(HibernateOrmDevJsonRpcService.class);
}
@BuildStep
void handleInitialSql(List<PersistenceUnitDescriptorBuildItem> persistenceUnitDescriptorBuildItems,
BuildProducer<JdbcInitialSQLGeneratorBuildItem> initialSQLGeneratorBuildItemBuildProducer) {
for (PersistenceUnitDescriptorBuildItem puDescriptor : persistenceUnitDescriptorBuildItems) {
String puName = puDescriptor.getPersistenceUnitName();
String dsName = puDescriptor.getConfig().getDataSource().orElse(PersistenceUnitUtil.DEFAULT_PERSISTENCE_UNIT_NAME);
initialSQLGeneratorBuildItemBuildProducer
.produce(new JdbcInitialSQLGeneratorBuildItem(dsName, new HibernateOrmDevInfoCreateDDLSupplier(puName)));
}
}
@BuildStep
void handleUpdateSql(List<PersistenceUnitDescriptorBuildItem> persistenceUnitDescriptorBuildItems,
BuildProducer<JdbcUpdateSQLGeneratorBuildItem> updateSQLGeneratorBuildItemBuildProducer) {
for (PersistenceUnitDescriptorBuildItem puDescriptor : persistenceUnitDescriptorBuildItems) {
String puName = puDescriptor.getPersistenceUnitName();
String dsName = puDescriptor.getConfig().getDataSource().orElse(PersistenceUnitUtil.DEFAULT_PERSISTENCE_UNIT_NAME);
updateSQLGeneratorBuildItemBuildProducer
.produce(new JdbcUpdateSQLGeneratorBuildItem(dsName, new HibernateOrmDevInfoUpdateDDLSupplier(puName)));
}
}
}
| HibernateOrmDevUIProcessor |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ComparableTypeTest.java | {
"start": 1571,
"end": 1785
} | class ____ implements Serializable, Comparable<Long> {
@Override
public int compareTo(Long o) {
return 0;
}
}
// BUG: Diagnostic contains: [ComparableType]
public static | SerializableComparable |
java | quarkusio__quarkus | extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/MyRunTimeFilter.java | {
"start": 409,
"end": 673
} | class ____ implements OASFilter {
@Override
public void filterOpenAPI(OpenAPI openAPI) {
Info info = OASFactory.createInfo();
info.setDescription("Created from Annotated Runtime filter");
openAPI.setInfo(info);
}
}
| MyRunTimeFilter |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java | {
"start": 4105,
"end": 4840
} | class ____ {
@Id
@GeneratedValue
private Long id;
private String name;
@ElementCollection
@SQLInsert(sql = "INSERT INTO person_phones (person_id, phones, valid) VALUES (?, ?, true) ")
@SQLDeleteAll(sql = "UPDATE person_phones SET valid = false WHERE person_id = ?")
@SQLSelect(sql = "SELECT phones FROM Person_phones WHERE person_id = ? and valid = true")
private List<String> phones = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhones() {
return phones;
}
}
//end::sql-custom-crud-example[]
}
| Person |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/MonoPublishMulticast.java | {
"start": 1489,
"end": 2616
} | class ____<T, R> extends InternalMonoOperator<T, R> implements Fuseable {
final Function<? super Mono<T>, ? extends Mono<? extends R>> transform;
MonoPublishMulticast(Mono<? extends T> source,
Function<? super Mono<T>, ? extends Mono<? extends R>> transform) {
super(source);
this.transform = Objects.requireNonNull(transform, "transform");
}
@Override
public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super R> actual) {
MonoPublishMulticaster<T> multicast = new MonoPublishMulticaster<>(actual.currentContext());
Mono<? extends R> out = fromDirect(
Objects.requireNonNull(transform.apply(fromDirect(multicast)), "The transform returned a null Mono"));
if (out instanceof Fuseable) {
out.subscribe(new FluxPublishMulticast.CancelFuseableMulticaster<>(actual, multicast));
}
else {
out.subscribe(new FluxPublishMulticast.CancelMulticaster<>(actual, multicast));
}
return multicast;
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return super.scanUnsafe(key);
}
static final | MonoPublishMulticast |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/config/UnsupportedConfigDataLocationExceptionTests.java | {
"start": 892,
"end": 1475
} | class ____ {
@Test
void createSetsMessage() {
UnsupportedConfigDataLocationException exception = new UnsupportedConfigDataLocationException(
ConfigDataLocation.of("test"));
assertThat(exception).hasMessage("Unsupported config data location 'test'");
}
@Test
void getLocationReturnsLocation() {
ConfigDataLocation location = ConfigDataLocation.of("test");
UnsupportedConfigDataLocationException exception = new UnsupportedConfigDataLocationException(location);
assertThat(exception.getLocation()).isEqualTo(location);
}
}
| UnsupportedConfigDataLocationExceptionTests |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabelUtil.java | {
"start": 1268,
"end": 7540
} | class ____ {
private NodeLabelUtil() {
}
private static final int MAX_LABEL_LENGTH = 255;
private static final Pattern LABEL_OR_VALUE_PATTERN =
Pattern.compile("^[0-9a-zA-Z][0-9a-zA-Z-_]*");
private static final Pattern PREFIX_PATTERN =
Pattern.compile("^[0-9a-zA-Z][0-9a-zA-Z-_\\.]*");
private static final Pattern ATTRIBUTE_VALUE_PATTERN =
Pattern.compile("^[0-9a-zA-Z][0-9a-zA-Z-_.]*");
private static final Pattern ATTRIBUTE_NAME_PATTERN =
Pattern.compile("^[0-9a-zA-Z][0-9a-zA-Z-_]*");
public static void checkAndThrowLabelName(String label) throws IOException {
if (label == null || label.isEmpty() || label.length() > MAX_LABEL_LENGTH) {
throw new IOException("label added is empty or exceeds "
+ MAX_LABEL_LENGTH + " character(s)");
}
label = label.trim();
boolean match = LABEL_OR_VALUE_PATTERN.matcher(label).matches();
if (!match) {
throw new IOException("label name should only contains "
+ "{0-9, a-z, A-Z, -, _} and should not started with {-,_}"
+ ", now it is= " + label);
}
}
public static void checkAndThrowAttributeName(String attributeName)
throws IOException {
if (attributeName == null || attributeName.isEmpty()
|| attributeName.length() > MAX_LABEL_LENGTH) {
throw new IOException(
"attribute name added is empty or exceeds " + MAX_LABEL_LENGTH
+ " character(s)");
}
attributeName = attributeName.trim();
boolean match = ATTRIBUTE_NAME_PATTERN.matcher(attributeName).matches();
if (!match) {
throw new IOException("attribute name should only contains "
+ "{0-9, a-z, A-Z, -, _} and should not started with {-,_}"
+ ", now it is= " + attributeName);
}
}
public static void checkAndThrowAttributeValue(String value)
throws IOException {
if (value == null) {
return;
} else if (value.trim().length() > MAX_LABEL_LENGTH) {
throw new IOException("Attribute value added exceeds " + MAX_LABEL_LENGTH
+ " character(s)");
}
value = value.trim();
if(value.isEmpty()) {
return;
}
boolean match = ATTRIBUTE_VALUE_PATTERN.matcher(value).matches();
if (!match) {
throw new IOException("attribute value should only contains "
+ "{0-9, a-z, A-Z, -, _} and should not started with {-,_}"
+ ", now it is= " + value);
}
}
public static void checkAndThrowAttributePrefix(String prefix)
throws IOException {
if (prefix == null) {
throw new IOException("Attribute prefix cannot be null.");
}
if (prefix.trim().length() > MAX_LABEL_LENGTH) {
throw new IOException("Attribute value added exceeds " + MAX_LABEL_LENGTH
+ " character(s)");
}
prefix = prefix.trim();
if(prefix.isEmpty()) {
return;
}
boolean match = PREFIX_PATTERN.matcher(prefix).matches();
if (!match) {
throw new IOException("attribute value should only contains "
+ "{0-9, a-z, A-Z, -, _,.} and should not started with {-,_}"
+ ", now it is= " + prefix);
}
}
/**
* Validate if a given set of attributes are valid. Attributes could be
* invalid if any of following conditions is met:
*
* <ul>
* <li>Missing prefix: the attribute doesn't have prefix defined</li>
* <li>Malformed attribute prefix: the prefix is not in valid format</li>
* </ul>
* @param attributeSet node attribute set.
* @throws IOException io error occur.
*/
public static void validateNodeAttributes(Set<NodeAttribute> attributeSet)
throws IOException {
if (attributeSet != null && !attributeSet.isEmpty()) {
for (NodeAttribute nodeAttribute : attributeSet) {
NodeAttributeKey attributeKey = nodeAttribute.getAttributeKey();
if (attributeKey == null) {
throw new IOException("AttributeKey must be set");
}
String prefix = attributeKey.getAttributePrefix();
if (Strings.isNullOrEmpty(prefix)) {
throw new IOException("Attribute prefix must be set");
}
// Verify attribute prefix format.
checkAndThrowAttributePrefix(prefix);
// Verify attribute name format.
checkAndThrowAttributeName(attributeKey.getAttributeName());
// Verify attribute value format.
checkAndThrowAttributeValue(nodeAttribute.getAttributeValue());
}
}
}
/**
* Filter a set of node attributes by a given prefix. Returns a filtered
* set of node attributes whose prefix equals the given prefix.
* If the prefix is null or empty, then the original set is returned.
* @param attributeSet node attribute set
* @param prefix node attribute prefix
* @return a filtered set of node attributes
*/
public static Set<NodeAttribute> filterAttributesByPrefix(
Set<NodeAttribute> attributeSet, String prefix) {
if (Strings.isNullOrEmpty(prefix)) {
return attributeSet;
}
return attributeSet.stream()
.filter(nodeAttribute -> prefix
.equals(nodeAttribute.getAttributeKey().getAttributePrefix()))
.collect(Collectors.toSet());
}
/**
* Are these two input node attributes the same.
*
* @param leftNodeAttributes left node attribute.
* @param rightNodeAttributes right node attribute.
* @return true if they are the same
*/
public static boolean isNodeAttributesEquals(
Set<NodeAttribute> leftNodeAttributes,
Set<NodeAttribute> rightNodeAttributes) {
if (leftNodeAttributes == null && rightNodeAttributes == null) {
return true;
} else if (leftNodeAttributes == null || rightNodeAttributes == null
|| leftNodeAttributes.size() != rightNodeAttributes.size()) {
return false;
}
return leftNodeAttributes.stream()
.allMatch(e -> isNodeAttributeIncludes(rightNodeAttributes, e));
}
private static boolean isNodeAttributeIncludes(
Set<NodeAttribute> nodeAttributes, NodeAttribute checkNodeAttribute) {
return nodeAttributes.stream().anyMatch(
e -> e.equals(checkNodeAttribute) && Objects
.equals(e.getAttributeValue(),
checkNodeAttribute.getAttributeValue()));
}
}
| NodeLabelUtil |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java | {
"start": 1413,
"end": 1669
} | interface ____ be implemented by most bean factories. Provides
* facilities to configure a bean factory, in addition to the bean factory
* client methods in the {@link org.springframework.beans.factory.BeanFactory}
* interface.
*
* <p>This bean factory | to |
java | elastic__elasticsearch | plugins/examples/custom-processor/src/yamlRestTest/java/org/elasticsearch/example/customprocessor/ExampleProcessorClientYamlTestSuiteIT.java | {
"start": 1507,
"end": 2012
} | class ____ extends ESClientYamlSuiteTestCase {
public ExampleProcessorClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) {
super(testCandidate);
}
@ParametersFactory
public static Iterable<Object[]> parameters() throws Exception {
// The test executes all the test candidates by default
// see ESClientYamlSuiteTestCase.REST_TESTS_SUITE
return ESClientYamlSuiteTestCase.createParameters();
}
}
| ExampleProcessorClientYamlTestSuiteIT |
java | google__truth | core/src/main/java/com/google/common/truth/IterableSubject.java | {
"start": 37473,
"end": 42755
} | interface ____ {
boolean check(@Nullable Object prev, @Nullable Object next);
}
private void pairwiseCheck(Iterable<?> actual, String expectedFact, PairwiseChecker checker) {
Iterator<?> iterator = actual.iterator();
if (iterator.hasNext()) {
Object prev = iterator.next();
while (iterator.hasNext()) {
Object next = iterator.next();
if (!checker.check(prev, next)) {
failWithoutActual(
simpleFact(expectedFact),
fact("but contained", prev),
fact("followed by", next),
fullContents());
return;
}
prev = next;
}
}
}
/**
* @deprecated You probably meant to call {@link #containsNoneOf} instead.
*/
@Override
@Deprecated
public void isNoneOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
super.isNoneOf(first, second, rest);
}
/**
* @deprecated You probably meant to call {@link #containsNoneIn} instead.
*/
@Override
@Deprecated
public void isNotIn(@Nullable Iterable<?> iterable) {
if (iterable == null) {
super.isNotIn(null); // fails
return;
}
if (Iterables.contains(iterable, actual)) {
failWithActual("expected not to be any of", iterable);
}
List<@Nullable Object> nonIterables = new ArrayList<>();
for (Object element : iterable) {
if (!(element instanceof Iterable<?>)) {
nonIterables.add(element);
}
}
if (!nonIterables.isEmpty()) {
failWithoutActual(
simpleFact(
"The actual value is an Iterable, and you've written a test that compares it to "
+ "some objects that are not Iterables. Did you instead mean to check "
+ "whether its *contents* match any of the *contents* of the given values? "
+ "If so, call containsNoneOf(...)/containsNoneIn(...) instead."),
fact("non-iterables", nonIterables));
}
}
/**
* Starts a method chain for a check in which the actual elements (i.e. the elements of the {@link
* Iterable} under test) are compared to expected elements using the given {@link Correspondence}.
* The actual elements must be of type {@code A}, the expected elements must be of type {@code E}.
* The check is actually executed by continuing the method chain. For example:
*
* <pre>{@code
* assertThat(actualIterable).comparingElementsUsing(correspondence).contains(expected);
* }</pre>
*
* where {@code actualIterable} is an {@code Iterable<A>} (or, more generally, an {@code
* Iterable<? extends A>}), {@code correspondence} is a {@code Correspondence<A, E>}, and {@code
* expected} is an {@code E}.
*
* <p>Any of the methods on the returned object may throw {@link ClassCastException} if they
* encounter an actual element that is not of type {@code A}.
*/
public <A extends @Nullable Object, E extends @Nullable Object>
UsingCorrespondence<A, E> comparingElementsUsing(
Correspondence<? super A, ? super E> correspondence) {
return new UsingCorrespondence<>(this, correspondence);
}
/**
* Starts a method chain for a check in which failure messages may use the given {@link
* DiffFormatter} to describe the difference between an actual element (i.e. an element of the
* {@link Iterable} under test) and the element it is expected to be equal to, but isn't. The
* actual and expected elements must be of type {@code T}. The check is actually executed by
* continuing the method chain. You may well want to use {@link
* UsingCorrespondence#displayingDiffsPairedBy} to specify how the elements should be paired up
* for diffing. For example:
*
* <pre>{@code
* assertThat(actualFoos)
* .formattingDiffsUsing(FooTestHelper::formatDiff)
* .displayingDiffsPairedBy(Foo::getId)
* .containsExactly(foo1, foo2, foo3);
* }</pre>
*
* where {@code actualFoos} is an {@code Iterable<Foo>}, {@code FooTestHelper.formatDiff} is a
* static method taking two {@code Foo} arguments and returning a {@link String}, {@code
* Foo.getId} is a no-arg instance method returning some kind of ID, and {@code foo1}, {code
* foo2}, and {@code foo3} are {@code Foo} instances.
*
* <p>Unlike when using {@link #comparingElementsUsing}, the elements are still compared using
* object equality, so this method does not affect whether a test passes or fails.
*
* <p>Any of the methods on the returned object may throw {@link ClassCastException} if they
* encounter an actual element that is not of type {@code T}.
*
* @since 1.1
*/
public <T extends @Nullable Object> UsingCorrespondence<T, T> formattingDiffsUsing(
DiffFormatter<? super T, ? super T> formatter) {
return comparingElementsUsing(Correspondence.<T>equality().formattingDiffsUsing(formatter));
}
/**
* A partially specified check in which the actual elements (normally the elements of the {@link
* Iterable} under test) are compared to expected elements using a {@link Correspondence}. The
* expected elements are of type {@code E}. Call methods on this object to actually execute the
* check.
*/
public static | PairwiseChecker |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java | {
"start": 7914,
"end": 9100
} | class ____ no interfaces specified.
* @see #setProxyTargetClass
*/
public void setAutodetectInterfaces(boolean autodetectInterfaces) {
this.autodetectInterfaces = autodetectInterfaces;
}
/**
* Set the value of the singleton property. Governs whether this factory
* should always return the same proxy instance (which implies the same target)
* or whether it should return a new prototype instance, which implies that
* the target and interceptors may be new instances also, if they are obtained
* from prototype bean definitions. This allows for fine control of
* independence/uniqueness in the object graph.
*/
public void setSingleton(boolean singleton) {
this.singleton = singleton;
}
/**
* Specify the AdvisorAdapterRegistry to use.
* Default is the global AdvisorAdapterRegistry.
* @see org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry
*/
public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) {
this.advisorAdapterRegistry = advisorAdapterRegistry;
}
@Override
public void setFrozen(boolean frozen) {
this.freezeProxy = frozen;
}
/**
* Set the ClassLoader to generate the proxy | if |
java | quarkusio__quarkus | extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/MeterRegistryCustomizer.java | {
"start": 406,
"end": 1177
} | interface ____ extends Comparable<MeterRegistryCustomizer> {
int MINIMUM_PRIORITY = Integer.MIN_VALUE;
// we use this priority to give a chance to other customizers to override serializers / deserializers
// that might have been added by the modules that Quarkus registers automatically
// (Jackson will keep the last registered serializer / deserializer for a given type
// if multiple are registered)
int QUARKUS_CUSTOMIZER_PRIORITY = MINIMUM_PRIORITY + 100;
int DEFAULT_PRIORITY = 0;
void customize(MeterRegistry registry);
default int priority() {
return DEFAULT_PRIORITY;
}
default int compareTo(MeterRegistryCustomizer o) {
return Integer.compare(o.priority(), priority());
}
}
| MeterRegistryCustomizer |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/executor/loader/ResultLoaderMap.java | {
"start": 4406,
"end": 10641
} | class ____ which we get database connection.
*/
private Class<?> configurationFactory;
/**
* Name of the unread property.
*/
private final String property;
/**
* ID of SQL statement which loads the property.
*/
private String mappedStatement;
/**
* Parameter of the sql statement.
*/
private Serializable mappedParameter;
private LoadPair(final String property, MetaObject metaResultObject, ResultLoader resultLoader) {
this.property = property;
this.metaResultObject = metaResultObject;
this.resultLoader = resultLoader;
/* Save required information only if original object can be serialized. */
if (metaResultObject != null && metaResultObject.getOriginalObject() instanceof Serializable) {
final Object mappedStatementParameter = resultLoader.parameterObject;
/* @todo May the parameter be null? */
if (mappedStatementParameter instanceof Serializable) {
this.mappedStatement = resultLoader.mappedStatement.getId();
this.mappedParameter = (Serializable) mappedStatementParameter;
this.configurationFactory = resultLoader.configuration.getConfigurationFactory();
} else {
Log log = this.getLogger();
if (log.isDebugEnabled()) {
log.debug("Property [" + this.property + "] of [" + metaResultObject.getOriginalObject().getClass()
+ "] cannot be loaded " + "after deserialization. Make sure it's loaded before serializing "
+ "forenamed object.");
}
}
}
}
public void load() throws SQLException {
/*
* These field should not be null unless the loadpair was serialized. Yet in that case this method should not be
* called.
*/
if (this.metaResultObject == null) {
throw new IllegalArgumentException("metaResultObject is null");
}
if (this.resultLoader == null) {
throw new IllegalArgumentException("resultLoader is null");
}
this.load(null);
}
public void load(final Object userObject) throws SQLException {
if (this.metaResultObject == null || this.resultLoader == null) {
if (this.mappedParameter == null) {
throw new ExecutorException("Property [" + this.property + "] cannot be loaded because "
+ "required parameter of mapped statement [" + this.mappedStatement + "] is not serializable.");
}
final Configuration config = this.getConfiguration();
final MappedStatement ms = config.getMappedStatement(this.mappedStatement);
if (ms == null) {
throw new ExecutorException(
"Cannot lazy load property [" + this.property + "] of deserialized object [" + userObject.getClass()
+ "] because configuration does not contain statement [" + this.mappedStatement + "]");
}
this.metaResultObject = config.newMetaObject(userObject);
this.resultLoader = new ResultLoader(config, new ClosedExecutor(), ms, this.mappedParameter,
metaResultObject.getSetterType(this.property), null, null);
}
/*
* We are using a new executor because we may be (and likely are) on a new thread and executors aren't thread
* safe. (Is this sufficient?) A better approach would be making executors thread safe.
*/
if (this.serializationCheck == null) {
final ResultLoader old = this.resultLoader;
this.resultLoader = new ResultLoader(old.configuration, new ClosedExecutor(), old.mappedStatement,
old.parameterObject, old.targetType, old.cacheKey, old.boundSql);
}
this.metaResultObject.setValue(property, this.resultLoader.loadResult());
}
private Configuration getConfiguration() {
if (this.configurationFactory == null) {
throw new ExecutorException("Cannot get Configuration as configuration factory was not set.");
}
Object configurationObject;
try {
final Method factoryMethod = this.configurationFactory.getDeclaredMethod(FACTORY_METHOD);
if (!Modifier.isStatic(factoryMethod.getModifiers())) {
throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#["
+ FACTORY_METHOD + "] is not static.");
}
if (!factoryMethod.canAccess(null)) {
configurationObject = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
try {
factoryMethod.setAccessible(true);
return factoryMethod.invoke(null);
} finally {
factoryMethod.setAccessible(false);
}
});
} else {
configurationObject = factoryMethod.invoke(null);
}
} catch (final ExecutorException ex) {
throw ex;
} catch (final NoSuchMethodException ex) {
throw new ExecutorException("Cannot get Configuration as factory class [" + this.configurationFactory
+ "] is missing factory method of name [" + FACTORY_METHOD + "].", ex);
} catch (final PrivilegedActionException ex) {
throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#["
+ FACTORY_METHOD + "] threw an exception.", ex.getCause());
} catch (final Exception ex) {
throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#["
+ FACTORY_METHOD + "] threw an exception.", ex);
}
if (!(configurationObject instanceof Configuration)) {
throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#["
+ FACTORY_METHOD + "] didn't return [" + Configuration.class + "] but ["
+ (configurationObject == null ? "null" : configurationObject.getClass()) + "].");
}
return Configuration.class.cast(configurationObject);
}
private Log getLogger() {
if (this.log == null) {
this.log = LogFactory.getLog(this.getClass());
}
return this.log;
}
}
private static final | through |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/postgresql/issues/Issue5822.java | {
"start": 774,
"end": 5547
} | class ____ {
@Test
public void test_parse_postgresql_collate() {
for (String sql : new String[]{
"SELECT a < 'foo' FROM test1;",
"SELECT a < b FROM test1;",
"SELECT a < b COLLATE \"de_DE\" FROM test1;",
"SELECT a COLLATE \"de_DE\" < b FROM test1;",
"SELECT a || b FROM test1;",
"SELECT * FROM test1 ORDER BY a || 'foo';",
"SELECT * FROM test1 ORDER BY a || b;",
"SELECT * FROM test1 ORDER BY a || b COLLATE \"fr_FR\";",
"SELECT a COLLATE \"C\" < b COLLATE \"POSIX\" FROM test1;",
"SELECT a < ('foo' COLLATE \"zh_CN\") FROM test1;",
"SELECT a < ('foo' COLLATE 'zh_CN') FROM test1;",
"SELECT a < ('foo') FROM test1;",
"SELECT a < (bbb COLLATE \"zh_CN\") FROM test1;",
"SELECT a < (ccc COLLATE 'zh_CN') FROM test1;",
"SELECT id FROM a_product WHERE product_name COLLATE \"C\" ILIKE '%70%'"
+ " AND 1=1 ORDER BY product_name,created_at DESC,id DESC LIMIT 20",
"SELECT id FROM a_product WHERE a_product.tenant_id=123 AND (tenant_id=123 AND del_flg=0 AND (product_name COLLATE \"C\" ILIKE '%70%' AND (INDEPENDENT_PRODUCT=1 AND ((1711942157815>=START_DATE AND 1711942157815< END_DATE) OR (START_DATE IS NULL AND END_DATE IS NULL) OR (START_DATE IS NULL AND 1711942157815< END_DATE) OR (1711942157815>=START_DATE AND END_DATE IS NULL))) AND id IN (SELECT dbc_relation_2 FROM p_custom_data_408 WHERE p_custom_data_408.tenant_id=123 AND (TENANT_ID=123 AND dbc_relation_1=1706133096090917 AND DELETE_FLG=0 AND dbc_select_2=1)) AND (((EXISTS (SELECT id FROM b_entity_checkbox pickvalue WHERE pickvalue.tenant_id=123 AND (a_product.id=pickvalue.object_id AND item_id=1776944933031192 AND option_code IN (1))) AND 1=1) OR (EXISTS (SELECT id FROM b_entity_checkbox pickvalue WHERE pickvalue.tenant_id=123 AND (a_product.id=pickvalue.object_id AND item_id=1776944933031192 AND option_code IN (2))) AND id=-999999999)) AND dbc_varchar_16='FERT') AND 1=1)) ORDER BY product_name,created_at DESC,id DESC LIMIT 20",
}) {
System.out.println("原始的sql===" + sql);
SQLStatementParser parser1 = SQLParserUtils.createSQLStatementParser(sql, DbType.postgresql);
List<SQLStatement> statementList1 = parser1.parseStatementList();
String sqleNew = statementList1.get(0).toString();
System.out.println("生成的sql===" + sqleNew);
SQLStatementParser parser2 = SQLParserUtils.createSQLStatementParser(sqleNew, DbType.greenplum);
List<SQLStatement> statementList2 = parser2.parseStatementList();
String sqleNew2 = statementList2.get(0).toString();
System.out.println("再次解析生成的sql===" + sqleNew2);
assertEquals(sqleNew, sqleNew2);
}
}
/**
* @see <a href="https://dev.mysql.com/doc/refman/8.4/en/charset-collate.html">Using COLLATE in SQL Statements</a>
*/
@Test
public void test_parse_mysql_collate() {
for (String sql : new String[]{
"SELECT k\n"
+ "FROM t1\n"
+ "ORDER BY k COLLATE latin1_german2_ci;",
"SELECT k COLLATE latin1_german2_ci AS k1\n"
+ "FROM t1\n"
+ "ORDER BY k1;",
"SELECT k\n"
+ "FROM t1\n"
+ "GROUP BY k COLLATE latin1_german2_ci;",
"SELECT MAX(k COLLATE latin1_german2_ci)\n"
+ "FROM t1;",
"SELECT DISTINCT k COLLATE latin1_german2_ci\n"
+ "FROM t1;",
"SELECT *\n"
+ "FROM t1\n"
+ "WHERE _latin1 'Müller' COLLATE latin1_german2_ci = k;",
"SELECT *\n"
+ "FROM t1\n"
+ "WHERE k LIKE _latin1 'Müller' COLLATE latin1_german2_ci;",
"SELECT k\n"
+ "FROM t1\n"
+ "GROUP BY k\n"
+ "HAVING k = _latin1 'Müller' COLLATE latin1_german2_ci;",
}) {
System.out.println("原始的sql===" + sql);
SQLStatementParser parser1 = SQLParserUtils.createSQLStatementParser(sql, DbType.mysql);
List<SQLStatement> statementList1 = parser1.parseStatementList();
String sqleNew = statementList1.get(0).toString();
System.out.println("生成的sql===" + sqleNew);
SQLStatementParser parser2 = SQLParserUtils.createSQLStatementParser(sqleNew, DbType.mariadb);
List<SQLStatement> statementList2 = parser2.parseStatementList();
String sqleNew2 = statementList2.get(0).toString();
System.out.println("再次解析生成的sql===" + sqleNew2);
assertEquals(sqleNew, sqleNew2);
}
}
}
| Issue5822 |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/spi-deployment/src/main/java/io/quarkus/resteasy/reactive/server/spi/GlobalHandlerCustomizerBuildItem.java | {
"start": 335,
"end": 667
} | class ____ extends MultiBuildItem {
private final HandlerChainCustomizer customizer;
public GlobalHandlerCustomizerBuildItem(HandlerChainCustomizer customizer) {
this.customizer = customizer;
}
public HandlerChainCustomizer getCustomizer() {
return customizer;
}
}
| GlobalHandlerCustomizerBuildItem |
java | quarkusio__quarkus | integration-tests/gradle/src/main/resources/custom-config-java-module/src/main/java/org/acme/WorkingDirResource.java | {
"start": 170,
"end": 352
} | class ____ {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return java.nio.file.Paths.get(".").toAbsolutePath().toString();
}
}
| WorkingDirResource |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/context/XmlServletWebServerApplicationContext.java | {
"start": 1600,
"end": 2930
} | class ____ extends ServletWebServerApplicationContext {
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
/**
* Create a new {@link XmlServletWebServerApplicationContext} that needs to be
* {@linkplain #load loaded} and then manually {@link #refresh refreshed}.
*/
public XmlServletWebServerApplicationContext() {
this.reader.setEnvironment(getEnvironment());
}
/**
* Create a new {@link XmlServletWebServerApplicationContext}, loading bean
* definitions from the given resources and automatically refreshing the context.
* @param resources the resources to load from
*/
public XmlServletWebServerApplicationContext(Resource... resources) {
load(resources);
refresh();
}
/**
* Create a new {@link XmlServletWebServerApplicationContext}, loading bean
* definitions from the given resource locations and automatically refreshing the
* context.
* @param resourceLocations the resources to load from
*/
public XmlServletWebServerApplicationContext(String... resourceLocations) {
load(resourceLocations);
refresh();
}
/**
* Create a new {@link XmlServletWebServerApplicationContext}, loading bean
* definitions from the given resource locations and automatically refreshing the
* context.
* @param relativeClass | XmlServletWebServerApplicationContext |
java | netty__netty | codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeadersSubframe.java | {
"start": 837,
"end": 1960
} | class ____ implements StompHeadersSubframe {
protected final StompCommand command;
protected DecoderResult decoderResult = DecoderResult.SUCCESS;
protected final DefaultStompHeaders headers;
public DefaultStompHeadersSubframe(StompCommand command) {
this(command, null);
}
DefaultStompHeadersSubframe(StompCommand command, DefaultStompHeaders headers) {
this.command = ObjectUtil.checkNotNull(command, "command");
this.headers = headers == null ? new DefaultStompHeaders() : headers;
}
@Override
public StompCommand command() {
return command;
}
@Override
public StompHeaders headers() {
return headers;
}
@Override
public DecoderResult decoderResult() {
return decoderResult;
}
@Override
public void setDecoderResult(DecoderResult decoderResult) {
this.decoderResult = decoderResult;
}
@Override
public String toString() {
return "StompFrame{" +
"command=" + command +
", headers=" + headers +
'}';
}
}
| DefaultStompHeadersSubframe |
java | apache__camel | components/camel-hazelcast/src/generated/java/org/apache/camel/processor/aggregate/hazelcast/HazelcastAggregationRepositoryConfigurer.java | {
"start": 758,
"end": 4068
} | class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.processor.aggregate.hazelcast.HazelcastAggregationRepository target = (org.apache.camel.processor.aggregate.hazelcast.HazelcastAggregationRepository) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowserializedheaders":
case "allowSerializedHeaders": target.setAllowSerializedHeaders(property(camelContext, boolean.class, value)); return true;
case "deadletteruri":
case "deadLetterUri": target.setDeadLetterUri(property(camelContext, java.lang.String.class, value)); return true;
case "hazelcastinstance":
case "hazelcastInstance": target.setHazelcastInstance(property(camelContext, com.hazelcast.core.HazelcastInstance.class, value)); return true;
case "maximumredeliveries":
case "maximumRedeliveries": target.setMaximumRedeliveries(property(camelContext, int.class, value)); return true;
case "recoveryinterval":
case "recoveryInterval": target.setRecoveryInterval(property(camelContext, long.class, value)); return true;
case "userecovery":
case "useRecovery": target.setUseRecovery(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowserializedheaders":
case "allowSerializedHeaders": return boolean.class;
case "deadletteruri":
case "deadLetterUri": return java.lang.String.class;
case "hazelcastinstance":
case "hazelcastInstance": return com.hazelcast.core.HazelcastInstance.class;
case "maximumredeliveries":
case "maximumRedeliveries": return int.class;
case "recoveryinterval":
case "recoveryInterval": return long.class;
case "userecovery":
case "useRecovery": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.processor.aggregate.hazelcast.HazelcastAggregationRepository target = (org.apache.camel.processor.aggregate.hazelcast.HazelcastAggregationRepository) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowserializedheaders":
case "allowSerializedHeaders": return target.isAllowSerializedHeaders();
case "deadletteruri":
case "deadLetterUri": return target.getDeadLetterUri();
case "hazelcastinstance":
case "hazelcastInstance": return target.getHazelcastInstance();
case "maximumredeliveries":
case "maximumRedeliveries": return target.getMaximumRedeliveries();
case "recoveryinterval":
case "recoveryInterval": return target.getRecoveryInterval();
case "userecovery":
case "useRecovery": return target.isUseRecovery();
default: return null;
}
}
}
| HazelcastAggregationRepositoryConfigurer |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/UnmarshalReifier.java | {
"start": 1178,
"end": 1959
} | class ____ extends ProcessorReifier<UnmarshalDefinition> {
public UnmarshalReifier(Route route, ProcessorDefinition<?> definition) {
super(route, (UnmarshalDefinition) definition);
}
@Override
public Processor createProcessor() {
DataFormat dataFormat = DataFormatReifier.getDataFormat(camelContext, definition.getDataFormatType());
UnmarshalProcessor answer
= new UnmarshalProcessor(dataFormat, Boolean.TRUE == parseBoolean(definition.getAllowNullBody()));
answer.setDisabled(isDisabled(camelContext, definition));
answer.setVariableSend(parseString(definition.getVariableSend()));
answer.setVariableReceive(parseString(definition.getVariableReceive()));
return answer;
}
}
| UnmarshalReifier |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest.java | {
"start": 790,
"end": 3088
} | class ____ extends TestCase {
public void testWall() throws Exception {
assertFalse(WallUtils.isValidateMySql("SELECT * FROM X where id=1 and 1!=1 union select 14,13,12,11,10,@@version_compile_os,8,7,6,5,4,3,2,1 FROM X"));
assertTrue(WallUtils.isValidateMySql("select '@@version_compile_os' FROM X"));
assertFalse(WallUtils.isValidateMySql("SELECT * FROM X where id=1 and 1!=1 union select hex(load_file(0x633A2F77696E646F77732F7265706169722F73616D))"));
assertTrue(WallUtils.isValidateMySql("select hex(load_file(0x633A2F77696E646F77732F7265706169722F73616D))"));
assertTrue(WallUtils.isValidateMySql("select 'hex(load_file(0x633A2F77696E646F77732F7265706169722F73616D))'"));
assertFalse(WallUtils.isValidateMySql("select * from t where fid = 1 union select 15,version() FROM X"));
assertTrue(WallUtils.isValidateMySql("select 15,version() FROM X"));
assertTrue(WallUtils.isValidateMySql("select 15,'version'"));
assertFalse(WallUtils.isValidateMySql("SELECT *FROM T UNION select 1 from information_schema.columns"));
assertTrue(WallUtils.isValidateMySql("select 'information_schema.columns'"));
assertFalse(WallUtils.isValidateMySql("SELECT *FROM T UNION select 1 from mysql.user"));
assertTrue(WallUtils.isValidateMySql("select 'mysql.user'"));
assertFalse(WallUtils.isValidateMySql("select * FROM T WHERE id = 1 AND select 0x3C3F706870206576616C28245F504F53545B2763275D293F3E into outfile '\\www\\edu\\1.php'"));
assertTrue(WallUtils.isValidateMySql("select 'outfile'"));
//assertFalse(WallUtils.isValidateMySql("select f1, f2 from t where c1=1 union select 1, 2"));
assertFalse(WallUtils.isValidateMySql("select c1 from t where 1=1 or id =1"));
assertFalse(WallUtils.isValidateMySql("select c1 from t where id =1 or 1=1"));
assertFalse(WallUtils.isValidateMySql("select c1 from t where id =1 || 1=1"));
WallConfig config = new WallConfig();
config.setHintAllow(false);
assertFalse(WallUtils.isValidateMySql(
"select * from person where id = '3'/**/union select v,b,a from (select 1,2,4/*! ,database() as b,user() as a,version() as v*/) a where '1'<>''",
config));
}
}
| MySqlWallTest |
java | spring-projects__spring-framework | spring-tx/src/test/java/org/springframework/transaction/event/ReactiveTransactionalEventListenerTests.java | {
"start": 16598,
"end": 16826
} | class ____ extends BaseTransactionalTestListener {
@AfterCommitEventListener
public void handleAfterCommit(String data) {
handleEvent(EventCollector.AFTER_COMMIT, data);
}
}
static | AfterCommitMetaAnnotationTestListener |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/InternalAlwaysCondition.java | {
"start": 675,
"end": 1944
} | class ____ extends AlwaysCondition implements ExecutableCondition {
public static final Result RESULT_INSTANCE = new Result(null, TYPE, true);
public static final InternalAlwaysCondition INSTANCE = new InternalAlwaysCondition();
private InternalAlwaysCondition() {}
public static InternalAlwaysCondition parse(String watchId, XContentParser parser) throws IOException {
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException(
"unable to parse [{}] condition for watch [{}]. expected an empty object but found [{}]",
TYPE,
watchId,
parser.currentName()
);
}
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new ElasticsearchParseException(
"unable to parse [{}] condition for watch [{}]. expected an empty object but found [{}]",
TYPE,
watchId,
parser.currentName()
);
}
return INSTANCE;
}
@Override
public Result execute(WatchExecutionContext ctx) {
return RESULT_INSTANCE;
}
}
| InternalAlwaysCondition |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select_into.java | {
"start": 431,
"end": 2114
} | class ____ extends TestCase {
private String sql = "select * into x from t where id = ?";
protected void setUp() throws Exception {
WallContext.clearContext();
}
protected void tearDown() throws Exception {
WallContext.clearContext();
}
public void testMySql() throws Exception {
WallProvider provider = new MySqlWallProvider();
assertTrue(provider.checkValid(sql));
{
WallTableStat tableStat = provider.getTableStat("t");
assertEquals(1, tableStat.getSelectCount());
assertEquals(0, tableStat.getSelectIntoCount());
}
{
WallTableStat tableStat = provider.getTableStat("x");
assertEquals(0, tableStat.getSelectCount());
assertEquals(1, tableStat.getSelectIntoCount());
}
}
public void testOracle() throws Exception {
WallProvider provider = new OracleWallProvider();
assertTrue(provider.checkValid(sql));
WallTableStat tableStat = provider.getTableStat("t");
assertEquals(1, tableStat.getSelectCount());
}
public void testPG() throws Exception {
WallProvider provider = new PGWallProvider();
assertTrue(provider.checkValid(sql));
WallTableStat tableStat = provider.getTableStat("t");
assertEquals(1, tableStat.getSelectCount());
}
public void testSQLServer() throws Exception {
WallProvider provider = new SQLServerWallProvider();
assertTrue(provider.checkValid(sql));
WallTableStat tableStat = provider.getTableStat("t");
assertEquals(1, tableStat.getSelectCount());
}
}
| WallStatTest_select_into |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/service/registry/AbstractHttpServiceRegistrar.java | {
"start": 2318,
"end": 3600
} | interface ____ proxies organized by
* {@link HttpServiceGroup}.
* <li>Bean definition for an {@link HttpServiceProxyRegistryFactoryBean} that
* initializes the infrastructure for each group, {@code RestClient} or
* {@code WebClient} and a proxy factory, necessary to create the proxies.
* </ul>
*
* <p>Subclasses determine the HTTP Service types (interfaces with
* {@link HttpExchange @HttpExchange} methods) to register by implementing
* {@link #registerHttpServices}.
*
* <p>There is built-in support for declaring HTTP Services through
* {@link ImportHttpServices} annotations. It is also possible to perform
* registrations directly, sourced in another way, by extending this class.
*
* <p>It is possible to import multiple instances of this registrar type.
* Subsequent imports update the existing registry {@code FactoryBean}
* definition, and likewise merge HTTP Service group definitions.
*
* <p>An application can autowire HTTP Service proxy beans, or autowire the
* {@link HttpServiceProxyRegistry} from which to obtain proxies.
*
* @author Rossen Stoyanchev
* @author Phillip Webb
* @author Olga Maciaszek-Sharma
* @author Stephane Nicoll
* @since 7.0
* @see ImportHttpServices
* @see HttpServiceProxyRegistryFactoryBean
*/
public abstract | client |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/InternalRbacFilter.java | {
"start": 757,
"end": 849
} | class ____ some functionality in RbacFilter to other packages. */
@Internal
public final | exposes |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/PainlessParser.java | {
"start": 66184,
"end": 68106
} | class ____ extends ParserRuleContext {
public TerminalNode ID() {
return getToken(PainlessParser.ID, 0);
}
public TerminalNode ASSIGN() {
return getToken(PainlessParser.ASSIGN, 0);
}
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class, 0);
}
public DeclvarContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override
public int getRuleIndex() {
return RULE_declvar;
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if (visitor instanceof PainlessParserVisitor) return ((PainlessParserVisitor<? extends T>) visitor).visitDeclvar(this);
else return visitor.visitChildren(this);
}
}
public final DeclvarContext declvar() throws RecognitionException {
DeclvarContext _localctx = new DeclvarContext(_ctx, getState());
enterRule(_localctx, 28, RULE_declvar);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(253);
match(ID);
setState(256);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la == ASSIGN) {
{
setState(254);
match(ASSIGN);
setState(255);
expression();
}
}
}
} catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
} finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static | DeclvarContext |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.