language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/concurrent/Computable.java | {
"start": 1096,
"end": 1414
} | class ____ that it maybe passed around an application.</p>
*
* <p>See also {@code FailableFunction<I, O, InterruptedException>}.</p>
*
* @param <I> the type of the input to the calculation
* @param <O> the type of the output of the calculation
* @see FailableFunction
* @since 3.6
*/
@FunctionalInterface
public | so |
java | apache__kafka | coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRuntime.java | {
"start": 50214,
"end": 51805
} | class ____ implements DeferredEvent {
/**
* The logger.
*/
private final Logger log;
/**
* The list of events.
*/
private final List<DeferredEvent> events = new ArrayList<>();
public DeferredEventCollection(Logger log) {
this.log = log;
}
@Override
public void complete(Throwable t) {
for (DeferredEvent event : events) {
try {
event.complete(t);
} catch (Throwable e) {
log.error("Completion of event {} failed due to {}.", event, e.getMessage(), e);
}
}
}
public boolean add(DeferredEvent event) {
return events.add(event);
}
public int size() {
return events.size();
}
@Override
public String toString() {
return "DeferredEventCollection(events=" + events + ")";
}
public static DeferredEventCollection of(Logger log, DeferredEvent... deferredEvents) {
DeferredEventCollection collection = new DeferredEventCollection(log);
for (DeferredEvent deferredEvent : deferredEvents) {
collection.add(deferredEvent);
}
return collection;
}
}
/**
* A coordinator write operation.
*
* @param <S> The type of the coordinator state machine.
* @param <T> The type of the response.
* @param <U> The type of the records.
*/
public | DeferredEventCollection |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/ParentPk.java | {
"start": 272,
"end": 908
} | class ____ implements Serializable {
String firstName;
String lastName;
/**
* is a male or a female
*/
//show hetereogenous PK types
boolean isMale;
public int hashCode() {
//this implem sucks
return firstName.hashCode() + lastName.hashCode() + ( isMale ? 0 : 1 );
}
public boolean equals(Object obj) {
//firstName and lastName are expected to be set in this implem
if ( obj != null && obj instanceof ParentPk ) {
ParentPk other = (ParentPk) obj;
return firstName.equals( other.firstName )
&& lastName.equals( other.lastName )
&& isMale == other.isMale;
}
else {
return false;
}
}
}
| ParentPk |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java | {
"start": 66517,
"end": 66684
} | interface ____ {
Filter[] excludeFilters() default {};
}
@ComponentScan(excludeFilters = {@Filter(pattern = "*Foo"), @Filter(pattern = "*Bar")})
static | ComponentScan |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java | {
"start": 43869,
"end": 47375
} | class ____ {
*
* @Bean
* public SecurityFilterChain securityFilterChain(HttpSecurity http) {
* http
* .authorizeHttpRequests((authorizeHttpRequests) ->
* authorizeHttpRequests
* .anyRequest().authenticated()
* )
* .saml2Login(withDefaults());
* return http.build();
* }
*
* @Bean
* public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
* return new InMemoryRelyingPartyRegistrationRepository(this.getSaml2RelyingPartyRegistration());
* }
*
* private RelyingPartyRegistration getSaml2RelyingPartyRegistration() {
* //remote IDP entity ID
* String idpEntityId = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/metadata.php";
* //remote WebSSO Endpoint - Where to Send AuthNRequests to
* String webSsoEndpoint = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/SSOService.php";
* //local registration ID
* String registrationId = "simplesamlphp";
* //local entity ID - autogenerated based on URL
* String localEntityIdTemplate = "{baseUrl}/saml2/service-provider-metadata/{registrationId}";
* //local signing (and decryption key)
* Saml2X509Credential signingCredential = getSigningCredential();
* //IDP certificate for verification of incoming messages
* Saml2X509Credential idpVerificationCertificate = getVerificationCertificate();
* return RelyingPartyRegistration.withRegistrationId(registrationId)
* .remoteIdpEntityId(idpEntityId)
* .idpWebSsoUrl(webSsoEndpoint)
* .credential(signingCredential)
* .credential(idpVerificationCertificate)
* .localEntityIdTemplate(localEntityIdTemplate)
* .build();
* }
* }
* </pre>
*
* <p>
* @param saml2LoginCustomizer the {@link Customizer} to provide more options for the
* {@link Saml2LoginConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @ @since 5.2
*/
public HttpSecurity saml2Login(Customizer<Saml2LoginConfigurer<HttpSecurity>> saml2LoginCustomizer) {
saml2LoginCustomizer.customize(getOrApply(new Saml2LoginConfigurer<>()));
return HttpSecurity.this;
}
/**
* Configures logout support for an SAML 2.0 Relying Party. <br>
* <br>
*
* Implements the <b>Single Logout Profile, using POST and REDIRECT bindings</b>, as
* documented in the
* <a target="_blank" href="https://docs.oasis-open.org/security/saml/">SAML V2.0
* Core, Profiles and Bindings</a> specifications. <br>
* <br>
*
* As a prerequisite to using this feature, is that you have a SAML v2.0 Asserting
* Party to sent a logout request to. The representation of the relying party and the
* asserting party is contained within {@link RelyingPartyRegistration}. <br>
* <br>
*
* {@link RelyingPartyRegistration}(s) are composed within a
* {@link RelyingPartyRegistrationRepository}, which is <b>required</b> and must be
* registered with the {@link ApplicationContext} or configured via
* {@link #saml2Login(Customizer)}.<br>
* <br>
*
* The default configuration provides an auto-generated logout endpoint at
* <code>"/logout"</code> and redirects to <code>/login?logout</code> when
* logout completes. <br>
* <br>
*
* <p>
* <h2>Example Configuration</h2>
*
* The following example shows the minimal configuration required, using a
* hypothetical asserting party.
*
* <pre>
* @EnableWebSecurity
* @Configuration
* public | Saml2LoginSecurityConfig |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimplePartitionKeyTest.java | {
"start": 1246,
"end": 2134
} | class ____ {
@Id
private Long id;
private String firstname;
private String lastname;
@PartitionKey
private String tenantKey;
//Getters and setters are omitted for brevity
//end::partition-key-simple-basic-attribute-mapping-example[]
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String title) {
this.firstname = title;
}
public String getLastname() {
return lastname;
}
public void setLastname(String author) {
this.lastname = author;
}
public String getTenantKey() {
return tenantKey;
}
public void setTenantKey(String tenantKey) {
this.tenantKey = tenantKey;
}
//tag::partition-key-simple-basic-attribute-mapping-example[]
}
//end::partition-key-simple-basic-attribute-mapping-example[]
}
| User |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/hint/ClearQueryHintsWithInvalidPropagationShuttle.java | {
"start": 1966,
"end": 4346
} | class ____ extends QueryHintsRelShuttle {
@Override
protected RelNode doVisit(RelNode node) {
List<RelHint> hints = ((Hintable) node).getHints();
Set<String> allHintNames =
hints.stream().map(hint -> hint.hintName).collect(Collectors.toSet());
// there are no query hints on this Join/Correlate node
if (allHintNames.stream().noneMatch(FlinkHints::isQueryHint)) {
return super.visit(node);
}
Optional<RelHint> firstAliasHint =
hints.stream()
.filter(hint -> FlinkHints.HINT_ALIAS.equals(hint.hintName))
.findFirst();
// there are no alias hints on this Join/Correlate/Aggregate node
if (!firstAliasHint.isPresent()) {
return super.visit(node);
}
List<RelHint> queryHintsFromOuterQueryBlock =
hints.stream()
.filter(
hint ->
FlinkHints.isQueryHint(hint.hintName)
// if the size of inheritPath is bigger than 0, it
// means that this query hint is propagated from its
// parent
&& hint.inheritPath.size()
> firstAliasHint.get().inheritPath.size())
.collect(Collectors.toList());
if (queryHintsFromOuterQueryBlock.isEmpty()) {
return super.visit(node);
}
RelNode newRelNode = node;
ClearOuterQueryHintShuttle clearOuterQueryHintShuttle;
for (RelHint outerQueryHint : queryHintsFromOuterQueryBlock) {
clearOuterQueryHintShuttle = new ClearOuterQueryHintShuttle(outerQueryHint);
newRelNode = newRelNode.accept(clearOuterQueryHintShuttle);
}
return super.visit(newRelNode);
}
/**
* A shuttle to clean the query hints which are in outer query block and should not affect the
* query-block inside.
*
* <p>Only the nodes that query hints could attach may be cleared. See more at {@link
* FlinkHintStrategies}.
*/
private static | ClearQueryHintsWithInvalidPropagationShuttle |
java | apache__kafka | connect/runtime/src/test/resources/test-plugins/non-migrated/test/plugins/NonMigratedPredicate.java | {
"start": 1234,
"end": 1571
} | class ____ implements Predicate {
@Override
public void configure(Map<String, ?> configs) {
}
@Override
public ConfigDef config() {
return null;
}
@Override
public boolean test(ConnectRecord record) {
return false;
}
@Override
public void close() {
}
}
| NonMigratedPredicate |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/jsontype/impl/TypeDeserializerBase.java | {
"start": 6571,
"end": 11420
} | class ____ the same which is
* important for some reason?
* Disabling the check will break 2 Enum-related tests.
*/
// 19-Jun-2016, tatu: As per [databind#1270] we may actually get full
// generic type with custom type resolvers. If so, should try to retain them.
// Whether this is sufficient to avoid problems remains to be seen, but for
// now it should improve things.
if (!type.hasGenericTypes()) {
try { // [databind#2668]: Should not expose generic RTEs
type = ctxt.constructSpecializedType(_baseType, type.getRawClass());
} catch (IllegalArgumentException e) {
// 29-Mar-2020, tatu: I hope this is not misleading for other cases, but
// for [databind#2668] seems reasonable
throw ctxt.invalidTypeIdException(_baseType, typeId, e.getMessage());
}
}
}
deser = ctxt.findContextualValueDeserializer(type, _property);
}
_deserializers.put(typeId, deser);
}
return deser;
}
protected final ValueDeserializer<Object> _findDefaultImplDeserializer(DeserializationContext ctxt)
{
// 06-Feb-2013, tatu: As per [databind#148], consider default implementation value of
// {@link java.lang.Void} to mean "serialize as null"; as well as DeserializationFeature
// to do swift mapping to null
if (_defaultImpl == null) {
if (!ctxt.isEnabled(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)) {
return NullifyingDeserializer.instance;
}
return null;
}
Class<?> raw = _defaultImpl.getRawClass();
if (ClassUtil.isBogusClass(raw)) {
return NullifyingDeserializer.instance;
}
if (_defaultImplDeserializer == null) {
synchronized (_defaultImpl) {
if (_defaultImplDeserializer == null) {
_defaultImplDeserializer = ctxt.findContextualValueDeserializer(
_defaultImpl, _property);
}
}
}
return _defaultImplDeserializer;
}
/**
* Helper method called when {@link JsonParser} indicates that it can use
* so-called native type ids, and such type id has been found.
*/
protected Object _deserializeWithNativeTypeId(JsonParser p, DeserializationContext ctxt, Object typeId)
throws JacksonException
{
ValueDeserializer<Object> deser;
if (typeId == null) {
// 04-May-2014, tatu: Should error be obligatory, or should there be another method
// for "try to deserialize with native type id"?
deser = _findDefaultImplDeserializer(ctxt);
if (deser == null) {
return ctxt.reportInputMismatch(baseType(),
"No (native) type id found when one was expected for polymorphic type handling");
}
} else {
String typeIdStr = (typeId instanceof String string) ? string : String.valueOf(typeId);
deser = _findDeserializer(ctxt, typeIdStr);
}
return deser.deserialize(p, ctxt);
}
/**
* Helper method called when given type id cannot be resolved into
* concrete deserializer either directly (using given {@link TypeIdResolver}),
* or using default type.
* Default implementation simply throws a {@link tools.jackson.databind.DatabindException} to
* indicate the problem; sub-classes may choose
*
* @return If it is possible to resolve type id into a {@link ValueDeserializer}
* should return that deserializer; otherwise throw an exception to indicate
* the problem.
*/
protected JavaType _handleUnknownTypeId(DeserializationContext ctxt, String typeId)
throws JacksonException
{
String extraDesc = _idResolver.getDescForKnownTypeIds();
if (extraDesc == null) {
extraDesc = "type ids are not statically known";
} else {
extraDesc = "known type ids = " + extraDesc;
}
if (_property != null) {
extraDesc = String.format("%s (for POJO property '%s')", extraDesc,
_property.getName());
}
return ctxt.handleUnknownTypeId(_baseType, typeId, _idResolver, extraDesc);
}
protected JavaType _handleMissingTypeId(DeserializationContext ctxt, String extraDesc)
throws JacksonException
{
return ctxt.handleMissingTypeId(_baseType, _idResolver, extraDesc);
}
}
| is |
java | spring-projects__spring-boot | cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java | {
"start": 920,
"end": 2932
} | class ____ extends WhitespaceArgumentDelimiter {
@Override
public boolean isEscaped(CharSequence buffer, int pos) {
return (isEscapeChar(buffer, pos - 1));
}
private boolean isEscapeChar(CharSequence buffer, int pos) {
if (pos >= 0) {
for (char c : getEscapeChars()) {
if (buffer.charAt(pos) == c) {
return !isEscapeChar(buffer, pos - 1);
}
}
}
return false;
}
@Override
public boolean isQuoted(CharSequence buffer, int pos) {
int closingQuote = searchBackwards(buffer, pos - 1, getQuoteChars());
if (closingQuote == -1) {
return false;
}
int openingQuote = searchBackwards(buffer, closingQuote - 1, buffer.charAt(closingQuote));
if (openingQuote == -1) {
return true;
}
return isQuoted(buffer, openingQuote - 1);
}
private int searchBackwards(CharSequence buffer, int pos, char... chars) {
while (pos >= 0) {
for (char c : chars) {
if (buffer.charAt(pos) == c && !isEscaped(buffer, pos)) {
return pos;
}
}
pos--;
}
return -1;
}
String[] parseArguments(String line) {
ArgumentList delimit = delimit(line, 0);
return cleanArguments(delimit.getArguments());
}
private String[] cleanArguments(String[] arguments) {
String[] cleanArguments = new String[arguments.length];
for (int i = 0; i < arguments.length; i++) {
cleanArguments[i] = cleanArgument(arguments[i]);
}
return cleanArguments;
}
private String cleanArgument(String argument) {
for (char c : getQuoteChars()) {
String quote = String.valueOf(c);
if (argument.startsWith(quote) && argument.endsWith(quote)) {
return replaceEscapes(argument.substring(1, argument.length() - 1));
}
}
return replaceEscapes(argument);
}
private String replaceEscapes(String string) {
string = string.replace("\\ ", " ");
string = string.replace("\\\\", "\\");
string = string.replace("\\t", "\t");
string = string.replace("\\\"", "\"");
string = string.replace("\\'", "'");
return string;
}
}
| EscapeAwareWhiteSpaceArgumentDelimiter |
java | google__auto | value/src/main/java/com/google/auto/value/processor/AutoValueishTemplateVars.java | {
"start": 1513,
"end": 1586
} | class ____ not available. */
String generated;
/** The package of the | is |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NettyHttpEndpointBuilderFactory.java | {
"start": 180792,
"end": 206980
} | interface ____
extends
AdvancedNettyHttpEndpointConsumerBuilder,
AdvancedNettyHttpEndpointProducerBuilder {
default NettyHttpEndpointBuilder basic() {
return (NettyHttpEndpointBuilder) this;
}
/**
* Only used for TCP when transferExchange is true. When set to true,
* serializable objects in headers and properties will be added to the
* exchange. Otherwise Camel will exclude any non-serializable objects
* and log it at WARN level.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param allowSerializedHeaders the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder allowSerializedHeaders(boolean allowSerializedHeaders) {
doSetProperty("allowSerializedHeaders", allowSerializedHeaders);
return this;
}
/**
* Only used for TCP when transferExchange is true. When set to true,
* serializable objects in headers and properties will be added to the
* exchange. Otherwise Camel will exclude any non-serializable objects
* and log it at WARN level.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param allowSerializedHeaders the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder allowSerializedHeaders(String allowSerializedHeaders) {
doSetProperty("allowSerializedHeaders", allowSerializedHeaders);
return this;
}
/**
* To use an explicit ChannelGroup.
*
* The option is a: <code>io.netty.channel.group.ChannelGroup</code>
* type.
*
* Group: advanced
*
* @param channelGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder channelGroup(io.netty.channel.group.ChannelGroup channelGroup) {
doSetProperty("channelGroup", channelGroup);
return this;
}
/**
* To use an explicit ChannelGroup.
*
* The option will be converted to a
* <code>io.netty.channel.group.ChannelGroup</code> type.
*
* Group: advanced
*
* @param channelGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder channelGroup(String channelGroup) {
doSetProperty("channelGroup", channelGroup);
return this;
}
/**
* To use a custom configured NettyHttpConfiguration for configuring
* this endpoint.
*
* The option is a:
* <code>org.apache.camel.component.netty.http.NettyHttpConfiguration</code> type.
*
* Group: advanced
*
* @param configuration the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder configuration(org.apache.camel.component.netty.http.NettyHttpConfiguration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* To use a custom configured NettyHttpConfiguration for configuring
* this endpoint.
*
* The option will be converted to a
* <code>org.apache.camel.component.netty.http.NettyHttpConfiguration</code> type.
*
* Group: advanced
*
* @param configuration the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder configuration(String configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* Determines whether or not the raw input stream from Netty
* HttpRequest#getContent() or HttpResponset#getContent() is cached or
* not (Camel will read the stream into a in light-weight memory based
* Stream caching) cache. By default Camel will cache the Netty input
* stream to support reading it multiple times to ensure it Camel can
* retrieve all data from the stream. However you can set this option to
* true when you for example need to access the raw stream, such as
* streaming it directly to a file or other persistent store. Mind that
* if you enable this option, then you cannot read the Netty stream
* multiple times out of the box, and you would need manually to reset
* the reader index on the Netty raw stream. Also Netty will auto-close
* the Netty stream when the Netty HTTP server/HTTP client is done
* processing, which means that if the asynchronous routing engine is in
* use then any asynchronous thread that may continue routing the
* org.apache.camel.Exchange may not be able to read the Netty stream,
* because Netty has closed it.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param disableStreamCache the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder disableStreamCache(boolean disableStreamCache) {
doSetProperty("disableStreamCache", disableStreamCache);
return this;
}
/**
* Determines whether or not the raw input stream from Netty
* HttpRequest#getContent() or HttpResponset#getContent() is cached or
* not (Camel will read the stream into a in light-weight memory based
* Stream caching) cache. By default Camel will cache the Netty input
* stream to support reading it multiple times to ensure it Camel can
* retrieve all data from the stream. However you can set this option to
* true when you for example need to access the raw stream, such as
* streaming it directly to a file or other persistent store. Mind that
* if you enable this option, then you cannot read the Netty stream
* multiple times out of the box, and you would need manually to reset
* the reader index on the Netty raw stream. Also Netty will auto-close
* the Netty stream when the Netty HTTP server/HTTP client is done
* processing, which means that if the asynchronous routing engine is in
* use then any asynchronous thread that may continue routing the
* org.apache.camel.Exchange may not be able to read the Netty stream,
* because Netty has closed it.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param disableStreamCache the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder disableStreamCache(String disableStreamCache) {
doSetProperty("disableStreamCache", disableStreamCache);
return this;
}
/**
* To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter
* headers.
*
* The option is a:
* <code>org.apache.camel.spi.HeaderFilterStrategy</code> type.
*
* Group: advanced
*
* @param headerFilterStrategy the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) {
doSetProperty("headerFilterStrategy", headerFilterStrategy);
return this;
}
/**
* To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter
* headers.
*
* The option will be converted to a
* <code>org.apache.camel.spi.HeaderFilterStrategy</code> type.
*
* Group: advanced
*
* @param headerFilterStrategy the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder headerFilterStrategy(String headerFilterStrategy) {
doSetProperty("headerFilterStrategy", headerFilterStrategy);
return this;
}
/**
* Whether to use native transport instead of NIO. Native transport
* takes advantage of the host operating system and is only supported on
* some platforms. You need to add the netty JAR for the host operating
* system you are using. See more details at:
* http://netty.io/wiki/native-transports.html.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param nativeTransport the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder nativeTransport(boolean nativeTransport) {
doSetProperty("nativeTransport", nativeTransport);
return this;
}
/**
* Whether to use native transport instead of NIO. Native transport
* takes advantage of the host operating system and is only supported on
* some platforms. You need to add the netty JAR for the host operating
* system you are using. See more details at:
* http://netty.io/wiki/native-transports.html.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param nativeTransport the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder nativeTransport(String nativeTransport) {
doSetProperty("nativeTransport", nativeTransport);
return this;
}
/**
* To use a custom
* org.apache.camel.component.netty.http.NettyHttpBinding for binding
* to/from Netty and Camel Message API.
*
* The option is a:
* <code>org.apache.camel.component.netty.http.NettyHttpBinding</code>
* type.
*
* Group: advanced
*
* @param nettyHttpBinding the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder nettyHttpBinding(org.apache.camel.component.netty.http.NettyHttpBinding nettyHttpBinding) {
doSetProperty("nettyHttpBinding", nettyHttpBinding);
return this;
}
/**
* To use a custom
* org.apache.camel.component.netty.http.NettyHttpBinding for binding
* to/from Netty and Camel Message API.
*
* The option will be converted to a
* <code>org.apache.camel.component.netty.http.NettyHttpBinding</code>
* type.
*
* Group: advanced
*
* @param nettyHttpBinding the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder nettyHttpBinding(String nettyHttpBinding) {
doSetProperty("nettyHttpBinding", nettyHttpBinding);
return this;
}
/**
* Allows to configure additional netty options using option. as prefix.
* For example option.child.keepAlive=false. See the Netty documentation
* for possible options that can be used. This is a multi-value option
* with prefix: option.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.Object></code> type.
* The option is multivalued, and you can use the options(String,
* Object) method to add a value (call the method multiple times to set
* more values).
*
* Group: advanced
*
* @param key the option key
* @param value the option value
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder options(String key, Object value) {
doSetMultiValueProperty("options", "option." + key, value);
return this;
}
/**
* Allows to configure additional netty options using option. as prefix.
* For example option.child.keepAlive=false. See the Netty documentation
* for possible options that can be used. This is a multi-value option
* with prefix: option.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.Object></code> type.
* The option is multivalued, and you can use the options(String,
* Object) method to add a value (call the method multiple times to set
* more values).
*
* Group: advanced
*
* @param values the values
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder options(Map values) {
doSetMultiValueProperties("options", "option.", values);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during inbound communication.
* Size is bytes.
*
* The option is a: <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param receiveBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder receiveBufferSize(int receiveBufferSize) {
doSetProperty("receiveBufferSize", receiveBufferSize);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during inbound communication.
* Size is bytes.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param receiveBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder receiveBufferSize(String receiveBufferSize) {
doSetProperty("receiveBufferSize", receiveBufferSize);
return this;
}
/**
* Configures the buffer size predictor. See details at Jetty
* documentation and this mail thread.
*
* The option is a: <code>int</code> type.
*
* Group: advanced
*
* @param receiveBufferSizePredictor the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder receiveBufferSizePredictor(int receiveBufferSizePredictor) {
doSetProperty("receiveBufferSizePredictor", receiveBufferSizePredictor);
return this;
}
/**
* Configures the buffer size predictor. See details at Jetty
* documentation and this mail thread.
*
* The option will be converted to a <code>int</code> type.
*
* Group: advanced
*
* @param receiveBufferSizePredictor the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder receiveBufferSizePredictor(String receiveBufferSizePredictor) {
doSetProperty("receiveBufferSizePredictor", receiveBufferSizePredictor);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during outbound communication.
* Size is bytes.
*
* The option is a: <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param sendBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder sendBufferSize(int sendBufferSize) {
doSetProperty("sendBufferSize", sendBufferSize);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during outbound communication.
* Size is bytes.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param sendBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder sendBufferSize(String sendBufferSize) {
doSetProperty("sendBufferSize", sendBufferSize);
return this;
}
/**
* Shutdown await timeout in milliseconds.
*
* The option is a: <code>int</code> type.
*
* Default: 100
* Group: advanced
*
* @param shutdownTimeout the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder shutdownTimeout(int shutdownTimeout) {
doSetProperty("shutdownTimeout", shutdownTimeout);
return this;
}
/**
* Shutdown await timeout in milliseconds.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 100
* Group: advanced
*
* @param shutdownTimeout the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder shutdownTimeout(String shutdownTimeout) {
doSetProperty("shutdownTimeout", shutdownTimeout);
return this;
}
/**
* Sets whether synchronous processing should be strictly used.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param synchronous the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder synchronous(boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param synchronous the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* If enabled and an Exchange failed processing on the consumer side,
* and if the caused Exception was send back serialized in the response
* as a application/x-java-serialized-object content type. On the
* producer side the exception will be deserialized and thrown as is,
* instead of the HttpOperationFailedException. The caused exception is
* required to be serialized. This is by default turned off. If you
* enable this then be aware that Java will deserialize the incoming
* data from the request to Java and that can be a potential security
* risk.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferException the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder transferException(boolean transferException) {
doSetProperty("transferException", transferException);
return this;
}
/**
* If enabled and an Exchange failed processing on the consumer side,
* and if the caused Exception was send back serialized in the response
* as a application/x-java-serialized-object content type. On the
* producer side the exception will be deserialized and thrown as is,
* instead of the HttpOperationFailedException. The caused exception is
* required to be serialized. This is by default turned off. If you
* enable this then be aware that Java will deserialize the incoming
* data from the request to Java and that can be a potential security
* risk.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferException the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder transferException(String transferException) {
doSetProperty("transferException", transferException);
return this;
}
/**
* Only used for TCP. You can transfer the exchange over the wire
* instead of just the body. The following fields are transferred: In
* body, Out body, fault body, In headers, Out headers, fault headers,
* exchange properties, exchange exception. This requires that the
* objects are serializable. Camel will exclude any non-serializable
* objects and log it at WARN level.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferExchange the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder transferExchange(boolean transferExchange) {
doSetProperty("transferExchange", transferExchange);
return this;
}
/**
* Only used for TCP. You can transfer the exchange over the wire
* instead of just the body. The following fields are transferred: In
* body, Out body, fault body, In headers, Out headers, fault headers,
* exchange properties, exchange exception. This requires that the
* objects are serializable. Camel will exclude any non-serializable
* objects and log it at WARN level.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferExchange the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder transferExchange(String transferExchange) {
doSetProperty("transferExchange", transferExchange);
return this;
}
/**
* Path to unix domain socket to use instead of inet socket. Host and
* port parameters will not be used, however required. It is ok to set
* dummy values for them. Must be used with nativeTransport=true and
* clientMode=false.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param unixDomainSocketPath the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder unixDomainSocketPath(String unixDomainSocketPath) {
doSetProperty("unixDomainSocketPath", unixDomainSocketPath);
return this;
}
/**
* When netty works on nio mode, it uses default workerCount parameter
* from Netty (which is cpu_core_threads x 2). User can use this option
* to override the default workerCount from Netty.
*
* The option is a: <code>int</code> type.
*
* Group: advanced
*
* @param workerCount the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder workerCount(int workerCount) {
doSetProperty("workerCount", workerCount);
return this;
}
/**
* When netty works on nio mode, it uses default workerCount parameter
* from Netty (which is cpu_core_threads x 2). User can use this option
* to override the default workerCount from Netty.
*
* The option will be converted to a <code>int</code> type.
*
* Group: advanced
*
* @param workerCount the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder workerCount(String workerCount) {
doSetProperty("workerCount", workerCount);
return this;
}
/**
* To use a explicit EventLoopGroup as the boss thread pool. For example
* to share a thread pool with multiple consumers or producers. By
* default each consumer or producer has their own worker pool with 2 x
* cpu count core threads.
*
* The option is a: <code>io.netty.channel.EventLoopGroup</code> type.
*
* Group: advanced
*
* @param workerGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder workerGroup(io.netty.channel.EventLoopGroup workerGroup) {
doSetProperty("workerGroup", workerGroup);
return this;
}
/**
* To use a explicit EventLoopGroup as the boss thread pool. For example
* to share a thread pool with multiple consumers or producers. By
* default each consumer or producer has their own worker pool with 2 x
* cpu count core threads.
*
* The option will be converted to a
* <code>io.netty.channel.EventLoopGroup</code> type.
*
* Group: advanced
*
* @param workerGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyHttpEndpointBuilder workerGroup(String workerGroup) {
doSetProperty("workerGroup", workerGroup);
return this;
}
}
public | AdvancedNettyHttpEndpointBuilder |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/internal/net/SocketInternal.java | {
"start": 866,
"end": 3514
} | interface ____ extends Socket {
/**
* Returns the {@link ChannelHandlerContext} of the last handler (named {@code handler}) of the pipeline that
* delivers message to the application with the {@link #handler(Handler)} and {@link #messageHandler(Handler)}.
* <p/>
* Handlers should be inserted in the pipeline using {@link io.netty.channel.ChannelPipeline#addBefore(String, String, ChannelHandler)}:
* <p/>
* <code><pre>
* ChannelPipeline pipeline = so.channelHandlerContext().pipeline();
* pipeline.addBefore("handler", "myhandler", new MyHandler());
* </pre></code>
* @return the channel handler context
*/
ChannelHandlerContext channelHandlerContext();
/**
* Write a message in the channel pipeline.
* <p/>
* When a read operation is in progress, the flush operation is delayed until the read operation completes.
*
* Note: this handler does not take in account the eventually pending buffers
*
* @param message the message to write, it should be handled by one of the channel pipeline handlers
* @return a future completed with the result
*/
Future<Void> writeMessage(Object message);
/**
* Set a {@code handler} on this socket to process the messages produced by this socket. The message can be
* {@link io.netty.buffer.ByteBuf} or other messages produced by channel pipeline handlers.
* <p/>
* The {@code} handler should take care of releasing pooled / direct messages.
* <p/>
* The handler replaces any {@link #handler(Handler)} previously set.
*
* @param handler the handler to set
* @return a reference to this, so the API can be used fluently
*/
SocketInternal messageHandler(Handler<Object> handler);
/**
* Set a {@code handler} on this socket to process the read complete event produced by this socket. This handler
* is called when the socket has finished delivering message to the message handler. It should not be used
* when it comes to buffers, since buffer delivery might be further buffered.
* <p/>
* The handler replaces any {@link #handler(Handler)} previously set.
*
* @param handler the handler to set
* @return a reference to this, so the API can be used fluently
*/
SocketInternal readCompletionHandler(Handler<Void> handler);
/**
* Set a handler to process pipeline user events.
*
* The handler should take care of releasing event, e.g calling {@code ReferenceCountUtil.release(evt)}.
*
* @param handler the handler to set
* @return a reference to this, so the API can be used fluently
*/
SocketInternal eventHandler(Handler<Object> handler);
}
| SocketInternal |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_anyMatch_with_description_Test.java | {
"start": 1046,
"end": 1589
} | class ____ extends AtomicReferenceArrayAssertBaseTest {
private Predicate<Object> predicate;
@BeforeEach
void beforeOnce() {
predicate = Objects::nonNull;
}
@Override
protected AtomicReferenceArrayAssert<Object> invoke_api_method() {
return assertions.anyMatch(predicate, "custom");
}
@Override
protected void verify_internal_effects() {
verify(iterables).assertAnyMatch(info(), list(internalArray()), predicate, new PredicateDescription("custom"));
}
}
| AtomicReferenceArrayAssert_anyMatch_with_description_Test |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/storage/SortBufferAccumulatorTest.java | {
"start": 2019,
"end": 11584
} | class ____ {
private static final int NUM_TOTAL_BUFFERS = 1000;
private static final int BUFFER_SIZE_BYTES = 1024;
private static final float NUM_BUFFERS_TRIGGER_FLUSH_RATIO = 0.6f;
private NetworkBufferPool globalPool;
@BeforeEach
void before() {
globalPool = new NetworkBufferPool(NUM_TOTAL_BUFFERS, BUFFER_SIZE_BYTES);
}
@AfterEach
void after() {
globalPool.destroy();
}
@Test
void testAccumulateRecordsAndGenerateBuffers() throws IOException {
testAccumulateRecordsAndGenerateBuffers(
true,
Arrays.asList(
Buffer.DataType.DATA_BUFFER, Buffer.DataType.DATA_BUFFER_WITH_CLEAR_END));
}
@Test
void testAccumulateRecordsAndGenerateBuffersWithPartialRecordUnallowed() throws IOException {
testAccumulateRecordsAndGenerateBuffers(
false, Collections.singletonList(Buffer.DataType.DATA_BUFFER_WITH_CLEAR_END));
}
private void testAccumulateRecordsAndGenerateBuffers(
boolean isPartialRecordAllowed, Collection<Buffer.DataType> expectedDataTypes)
throws IOException {
int numBuffers = 10;
int numRecords = 1000;
int indexEntrySize = 16;
TieredStorageSubpartitionId subpartitionId = new TieredStorageSubpartitionId(0);
Random random = new Random(1234);
TieredStorageMemoryManager memoryManager = createStorageMemoryManager(numBuffers);
int numExpectBuffers = 0;
int currentBufferWrittenBytes = 0;
AtomicInteger numReceivedFinishedBuffer = new AtomicInteger(0);
// The test use only one buffer for sort, and when it is full, the sort buffer will be
// flushed.
try (SortBufferAccumulator bufferAccumulator =
new SortBufferAccumulator(
1, 2, BUFFER_SIZE_BYTES, memoryManager, isPartialRecordAllowed)) {
bufferAccumulator.setup(
((subpartition, buffer, numRemainingBuffers) -> {
assertThat(buffer.getDataType()).isIn(expectedDataTypes);
numReceivedFinishedBuffer.incrementAndGet();
buffer.recycleBuffer();
}));
boolean isBroadcastForPreviousRecord = false;
for (int i = 0; i < numRecords; i++) {
int numBytes = random.nextInt(BUFFER_SIZE_BYTES) + 1;
ByteBuffer record = generateRandomData(numBytes, random);
boolean isBroadcast = random.nextBoolean();
bufferAccumulator.receive(
record, subpartitionId, Buffer.DataType.DATA_BUFFER, isBroadcast);
if (currentBufferWrittenBytes + numBytes + indexEntrySize > BUFFER_SIZE_BYTES
|| i > 0 && isBroadcastForPreviousRecord != isBroadcast) {
numExpectBuffers++;
currentBufferWrittenBytes = 0;
}
isBroadcastForPreviousRecord = isBroadcast;
currentBufferWrittenBytes += numBytes + indexEntrySize;
}
}
assertThat(currentBufferWrittenBytes).isLessThan(BUFFER_SIZE_BYTES);
numExpectBuffers += currentBufferWrittenBytes == 0 ? 0 : 1;
assertThat(numReceivedFinishedBuffer).hasValue(numExpectBuffers);
}
@Test
void testWriteLargeRecord() throws IOException {
testWriteLargeRecord(true);
}
@Test
void testWriteLargeRecordWithPartialRecordUnallowed() throws IOException {
testWriteLargeRecord(false);
}
private void testWriteLargeRecord(boolean isPartialRecordAllowed) throws IOException {
int numBuffers = 15;
Random random = new Random();
TieredStorageMemoryManager memoryManager = createStorageMemoryManager(numBuffers);
// The test use only one buffer for sort, and when it is full, the sort buffer will be
// flushed.
try (SortBufferAccumulator bufferAccumulator =
new SortBufferAccumulator(
1, 2, BUFFER_SIZE_BYTES, memoryManager, isPartialRecordAllowed)) {
AtomicInteger numReceivedBuffers = new AtomicInteger(0);
bufferAccumulator.setup(
(subpartitionIndex, buffer, numRemainingBuffers) -> {
numReceivedBuffers.getAndAdd(1);
buffer.recycleBuffer();
});
ByteBuffer largeRecord = generateRandomData(BUFFER_SIZE_BYTES * numBuffers, random);
bufferAccumulator.receive(
largeRecord,
new TieredStorageSubpartitionId(0),
Buffer.DataType.DATA_BUFFER,
false);
assertThat(numReceivedBuffers).hasValue(numBuffers);
}
}
@Test
void testNoBuffersForSort() throws IOException {
int numBuffers = 10;
int bufferSize = 1024;
Random random = new Random(1111);
TieredStorageSubpartitionId subpartitionId = new TieredStorageSubpartitionId(0);
TieredStorageMemoryManager memoryManager = createStorageMemoryManager(numBuffers);
try (SortBufferAccumulator bufferAccumulator =
new SortBufferAccumulator(1, 1, bufferSize, memoryManager, true)) {
bufferAccumulator.setup((subpartitionIndex, buffer, numRemainingBuffers) -> {});
assertThatThrownBy(
() ->
bufferAccumulator.receive(
generateRandomData(1, random),
subpartitionId,
Buffer.DataType.DATA_BUFFER,
false))
.isInstanceOf(IllegalArgumentException.class);
}
}
@Test
void testCloseWithUnFinishedBuffers() throws IOException {
int numBuffers = 10;
TieredStorageMemoryManager tieredStorageMemoryManager =
createStorageMemoryManager(numBuffers);
SortBufferAccumulator bufferAccumulator =
new SortBufferAccumulator(
1, 2, BUFFER_SIZE_BYTES, tieredStorageMemoryManager, true);
bufferAccumulator.setup(
((subpartition, buffer, numRemainingBuffers) -> buffer.recycleBuffer()));
bufferAccumulator.receive(
generateRandomData(1, new Random()),
new TieredStorageSubpartitionId(0),
Buffer.DataType.DATA_BUFFER,
false);
assertThat(tieredStorageMemoryManager.numOwnerRequestedBuffer(bufferAccumulator))
.isEqualTo(2);
bufferAccumulator.close();
assertThat(tieredStorageMemoryManager.numOwnerRequestedBuffer(bufferAccumulator)).isZero();
}
@Test
void testReuseRecycledBuffersWhenFlushDataBuffer() throws IOException {
int numBuffers = 10;
int numSubpartitions = 10;
AtomicInteger numRequestedBuffers = new AtomicInteger(0);
TestingTieredStorageMemoryManager memoryManager =
new TestingTieredStorageMemoryManager.Builder()
.setRequestBufferBlockingFunction(
owner -> {
numRequestedBuffers.incrementAndGet();
MemorySegment memorySegment =
globalPool.requestPooledMemorySegment();
// When flushing data from the data buffer, the buffers should
// not be requested from here anymore because the freeSegments
// can be reused before released.
assertThat(numRequestedBuffers.get() <= numBuffers).isTrue();
return new BufferBuilder(
memorySegment,
segment -> globalPool.requestPooledMemorySegment());
})
.build();
SortBufferAccumulator bufferAccumulator =
new SortBufferAccumulator(
numSubpartitions, numBuffers, BUFFER_SIZE_BYTES, memoryManager, true);
bufferAccumulator.setup(
((subpartition, buffer, numRemainingBuffers) -> buffer.recycleBuffer()));
for (int i = 0; i < numSubpartitions; i++) {
bufferAccumulator.receive(
generateRandomData(10, new Random()),
new TieredStorageSubpartitionId(i % numSubpartitions),
Buffer.DataType.DATA_BUFFER,
false);
}
// Trigger flushing buffers from data buffer.
bufferAccumulator.close();
}
private TieredStorageMemoryManagerImpl createStorageMemoryManager(int numBuffersInBufferPool)
throws IOException {
BufferPool bufferPool =
globalPool.createBufferPool(numBuffersInBufferPool, numBuffersInBufferPool);
TieredStorageMemoryManagerImpl storageMemoryManager =
new TieredStorageMemoryManagerImpl(NUM_BUFFERS_TRIGGER_FLUSH_RATIO, true);
storageMemoryManager.setup(
bufferPool, Collections.singletonList(new TieredStorageMemorySpec(this, 1)));
return storageMemoryManager;
}
}
| SortBufferAccumulatorTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/visitor/OracleSchemaStatVisitorTest_Subquery.java | {
"start": 978,
"end": 2044
} | class ____ extends TestCase {
public void test_0() throws Exception {
String sql = "SELECT id, name FROM (select id, name from users where ROWNUM < 10) a";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement statemen = statementList.get(0);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
statemen.accept(visitor);
System.out.println(sql);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(true, visitor.containsTable("users"));
assertEquals(2, visitor.getColumns().size());
assertEquals(true, visitor.getColumns().contains(new Column("users", "id")));
assertEquals(true, visitor.getColumns().contains(new Column("users", "name")));
}
}
| OracleSchemaStatVisitorTest_Subquery |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4721OptionalPluginDependencyTest.java | {
"start": 1131,
"end": 2231
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify the handling of direct/transitive optional plugin dependencies.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4721");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteArtifacts("org.apache.maven.its.mng4721");
verifier.addCliArgument("-s");
verifier.addCliArgument("settings.xml");
verifier.filterFile("settings-template.xml", "settings.xml");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/pcl.properties");
assertEquals("1", props.get("org/apache/maven/plugin/coreit/c.properties.count"));
assertEquals("1", props.get("mng4721a.properties.count"));
assertEquals("0", props.get("mng4721b.properties.count"));
}
}
| MavenITmng4721OptionalPluginDependencyTest |
java | micronaut-projects__micronaut-core | router/src/main/java/io/micronaut/web/router/DefaultRouteBuilder.java | {
"start": 40137,
"end": 45382
} | class ____ implements ResourceRoute {
private final Map<HttpMethod, Route> resourceRoutes;
private final DefaultUriRoute getRoute;
/**
* @param resourceRoutes The resource routes
* @param getRoute The default Uri route
*/
DefaultResourceRoute(Map<HttpMethod, Route> resourceRoutes, DefaultUriRoute getRoute) {
this.resourceRoutes = resourceRoutes;
this.getRoute = getRoute;
}
/**
* @param type The class
*/
DefaultResourceRoute(Class<?> type) {
this.resourceRoutes = new LinkedHashMap<>();
// GET /foo/1
Map<HttpMethod, Route> routeMap = this.resourceRoutes;
this.getRoute = buildGetRoute(type, routeMap);
buildRemainingRoutes(type, routeMap);
}
@Override
public RouteInfo<Object> toRouteInfo() {
throw new IllegalStateException("Not implemented!");
}
@Override
public ResourceRoute consumes(MediaType... mediaTypes) {
if (mediaTypes != null) {
for (Route route : resourceRoutes.values()) {
route.consumes(mediaTypes);
}
}
return this;
}
@Override
public Route consumesAll() {
return consumes(MediaType.EMPTY_ARRAY);
}
@Override
public ResourceRoute nest(Runnable nested) {
DefaultUriRoute previous = DefaultRouteBuilder.this.currentParentRoute;
DefaultRouteBuilder.this.currentParentRoute = getRoute;
try {
nested.run();
} finally {
DefaultRouteBuilder.this.currentParentRoute = previous;
}
return this;
}
@Override
public ResourceRoute where(Predicate<HttpRequest<?>> condition) {
for (Route route : resourceRoutes.values()) {
route.where(condition);
}
return this;
}
@Override
public ResourceRoute produces(MediaType... mediaType) {
if (mediaType != null) {
for (Route route : resourceRoutes.values()) {
route.produces(mediaType);
}
}
return this;
}
@Override
public ResourceRoute body(String argument) {
return this;
}
@Override
public Route body(Argument<?> argument) {
return this;
}
@Override
public ResourceRoute readOnly(boolean readOnly) {
List<HttpMethod> excluded = Arrays.asList(HttpMethod.DELETE, HttpMethod.PATCH, HttpMethod.POST, HttpMethod.PUT);
return handleExclude(excluded);
}
@Override
public ResourceRoute exclude(HttpMethod... methods) {
return handleExclude(Arrays.asList(methods));
}
/**
* @param newMap New map info
* @param getRoute The default route
*
* @return The {@link ResourceRoute}
*/
protected ResourceRoute newResourceRoute(Map<HttpMethod, Route> newMap, DefaultUriRoute getRoute) {
return new DefaultResourceRoute(newMap, getRoute);
}
/**
* @param type The class
* @param routeMap The route info
*
* @return The {@link DefaultUriRoute}
*/
protected DefaultUriRoute buildGetRoute(Class<?> type, Map<HttpMethod, Route> routeMap) {
DefaultUriRoute getRoute = (DefaultUriRoute) DefaultRouteBuilder.this.GET(type, ID);
routeMap.put(
HttpMethod.GET, getRoute
);
return getRoute;
}
/**
* Build the remaining routes.
*
* @param type The class
* @param routeMap The route info
*/
protected void buildRemainingRoutes(Class<?> type, Map<HttpMethod, Route> routeMap) {
// GET /foo
routeMap.put(
HttpMethod.GET, DefaultRouteBuilder.this.GET(type)
);
// POST /foo
routeMap.put(
HttpMethod.POST, DefaultRouteBuilder.this.POST(type)
);
// DELETE /foo/1
routeMap.put(
HttpMethod.DELETE, DefaultRouteBuilder.this.DELETE(type, ID)
);
// PATCH /foo/1
routeMap.put(
HttpMethod.PATCH, DefaultRouteBuilder.this.PATCH(type, ID)
);
// PUT /foo/1
routeMap.put(
HttpMethod.PUT, DefaultRouteBuilder.this.PUT(type, ID)
);
}
private ResourceRoute handleExclude(List<HttpMethod> excluded) {
var newMap = new LinkedHashMap<HttpMethod, Route>();
this.resourceRoutes.forEach((key, value) -> {
if (excluded.contains(key)) {
DefaultRouteBuilder.this.uriRoutes.remove(value);
} else {
newMap.put(key, value);
}
});
return newResourceRoute(newMap, getRoute);
}
}
}
| DefaultResourceRoute |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java | {
"start": 128879,
"end": 128977
} | interface ____ {
}
/**
* Mimics jakarta.persistence.GeneratedValue
*/
@Retention(RUNTIME)
@ | Id |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/sql/NativeQueryResultBuilderTests.java | {
"start": 1961,
"end": 7377
} | class ____ {
public static final String STRING_VALUE = "a string value";
public static final String URL_STRING = "http://hibernate.org";
@Test
public void fullyImplicitTest(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final String sql = "select the_string, the_integer, id from EntityOfBasics";
final NativeQuery<?> query = session.createNativeQuery( sql );
final List<?> results = query.list();
assertThat( results.size(), is( 1 ) );
final Object result = results.get( 0 );
assertThat( result, instanceOf( Object[].class ) );
final Object[] values = (Object[]) result;
assertThat( values.length, is(3 ) );
assertThat( values[ 0 ], is( STRING_VALUE ) );
assertThat( values[ 1 ], is( 2 ) );
assertThat( values[ 2 ], is( 1 ) );
}
);
}
@Test
// DB2, Derby, SQL Server and Sybase return an Integer for count by default
// Oracle returns a NUMERIC(39,0) i.e. a BigDecimal for count by default
@SkipForDialect(dialectClass = DB2Dialect.class)
@SkipForDialect(dialectClass = DerbyDialect.class)
@SkipForDialect(dialectClass = SQLServerDialect.class)
@SkipForDialect(dialectClass = SybaseDialect.class, matchSubTypes = true)
@SkipForDialect(dialectClass = OracleDialect.class)
@SkipForDialect(dialectClass = InformixDialect.class)
public void fullyImplicitTest2(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final String sql = "select count(the_string) from EntityOfBasics";
final NativeQuery<?> query = session.createNativeQuery( sql );
final List<?> results = query.list();
assertThat( results.size(), is( 1 ) );
final Object result = results.get( 0 );
assertThat( result, instanceOf( Long.class ) );
assertThat( result, is( 1L ) );
}
);
}
@Test
public void explicitOrderTest(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final String sql = "select the_string, the_integer, id from EntityOfBasics";
final NativeQuery<?> query = session.createNativeQuery( sql );
// notice the reverse order from the select clause
query.addScalar( "id" );
query.addScalar( "the_integer" );
query.addScalar( "the_string" );
final List<?> results = query.list();
assertThat( results.size(), is( 1 ) );
final Object result = results.get( 0 );
assertThat( result, instanceOf( Object[].class ) );
final Object[] values = (Object[]) result;
assertThat( values.length, is(3 ) );
assertThat( values[ 0 ], is( 1 ) );
assertThat( values[ 1 ], is( 2 ) );
assertThat( values[ 2 ], is( STRING_VALUE ) );
}
);
}
@Test
public void explicitEnumTypeTest(SessionFactoryScope scope) {
final String sql = "select id, gender, ordinal_gender from EntityOfBasics";
// first, without explicit typing
scope.inTransaction(
session -> {
final NativeQuery<?> query = session.createNativeQuery( sql );
query.addScalar( "id" );
query.addScalar( "gender" );
query.addScalar( "ordinal_gender" );
final List<?> results = query.list();
assertThat( results.size(), is( 1 ) );
final Object result = results.get( 0 );
assertThat( result, instanceOf( Object[].class ) );
final Object[] values = (Object[]) result;
assertThat( values.length, is(3 ) );
assertThat( values[ 0 ], is( 1 ) );
assertThat( values[ 1 ], is( "MALE" ) );
assertThat( values[ 2 ], matchesOrdinal( EntityOfBasics.Gender.FEMALE ) );
}
);
// then using explicit typing
scope.inTransaction(
session -> {
final NativeQuery<?> query = session.createNativeQuery( sql );
query.addScalar( "id" );
query.addScalar( "gender", EntityOfBasics.Gender.class );
query.addScalar( "ordinal_gender", EntityOfBasics.Gender.class );
final List<?> results = query.list();
assertThat( results.size(), is( 1 ) );
final Object result = results.get( 0 );
assertThat( result, instanceOf( Object[].class ) );
final Object[] values = (Object[]) result;
assertThat( values.length, is(3 ) );
assertThat( values[ 0 ], is( 1 ) );
assertThat( values[ 1 ], is( EntityOfBasics.Gender.MALE ) );
assertThat( values[ 2 ], is( EntityOfBasics.Gender.FEMALE ) );
}
);
}
@Test
public void explicitConversionTest(SessionFactoryScope scope) {
final String sql = "select converted_gender from EntityOfBasics";
// Control
scope.inTransaction(
session -> {
final NativeQuery<?> query = session.createNativeQuery( sql );
final List<?> results = query.list();
assertThat( results.size(), is( 1 ) );
final Object result = results.get( 0 );
assertThat( result, instanceOf( Character.class ) );
assertThat( result, is( 'O' ) );
}
);
// Converter instance
scope.inTransaction(
session -> {
final NativeQuery<?> query = session.createNativeQuery( sql );
query.addScalar(
"converted_gender",
EntityOfBasics.Gender.class,
Character.class,
new EntityOfBasics.GenderConverter()
);
final List<?> results = query.list();
assertThat( results.size(), is( 1 ) );
final Object result = results.get( 0 );
assertThat( result, instanceOf( EntityOfBasics.Gender.class ) );
assertThat( result, is( EntityOfBasics.Gender.OTHER ) );
}
);
// Converter | NativeQueryResultBuilderTests |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/core/userdetails/ReactiveUserDetailsPasswordService.java | {
"start": 869,
"end": 1397
} | interface ____ {
ReactiveUserDetailsPasswordService NOOP = (user, newPassword) -> Mono.just(user);
/**
* Modify the specified user's password. This should change the user's password in the
* persistent user repository (database, LDAP etc).
* @param user the user to modify the password for
* @param newPassword the password to change to
* @return the updated UserDetails with the new password
*/
Mono<UserDetails> updatePassword(UserDetails user, @Nullable String newPassword);
}
| ReactiveUserDetailsPasswordService |
java | quarkusio__quarkus | extensions/agroal/deployment/src/test/java/io/quarkus/agroal/test/DevServicesH2DatasourceTestCase.java | {
"start": 749,
"end": 2291
} | class ____ {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.withEmptyApplication()
// Expect no warnings (in particular from Agroal)
.setLogRecordPredicate(record -> record.getLevel().intValue() >= Level.WARNING.intValue()
// There are other warnings: JDK8, TestContainers, drivers, ...
// Ignore them: we're only interested in Agroal here.
&& record.getMessage().contains("Agroal"))
.assertLogRecords(records -> assertThat(records)
// This is just to get meaningful error messages, as LogRecord doesn't have a toString()
.extracting(LogRecord::getMessage)
.isEmpty());
@Inject
AgroalDataSource dataSource;
@Test
public void testDatasource() throws Exception {
AgroalConnectionPoolConfiguration configuration = dataSource.getConfiguration().connectionPoolConfiguration();
assertTrue(configuration.connectionFactoryConfiguration().jdbcUrl().contains("jdbc:h2:"));
assertEquals(DatabaseDefaultSetupConfig.DEFAULT_DATABASE_USERNAME,
configuration.connectionFactoryConfiguration().principal().getName());
assertEquals(50, configuration.maxSize());
assertThat(configuration.exceptionSorter()).isInstanceOf(ExceptionSorter.emptyExceptionSorter().getClass());
try (Connection connection = dataSource.getConnection()) {
}
}
}
| DevServicesH2DatasourceTestCase |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/jsontype/impl/TypeDeserializerBase.java | {
"start": 469,
"end": 547
} | class ____ all standard Jackson {@link TypeDeserializer}s.
*/
public abstract | for |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/FileInputFormat.java | {
"start": 2297,
"end": 2864
} | class ____ all file-based
* <code>InputFormat</code>s. This provides a generic implementation of
* {@link #getSplits(JobContext)}.
*
* Implementations of <code>FileInputFormat</code> can also override the
* {@link #isSplitable(JobContext, Path)} method to prevent input files
* from being split-up in certain situations. Implementations that may
* deal with non-splittable files <i>must</i> override this method, since
* the default implementation assumes splitting is always possible.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public abstract | for |
java | spring-projects__spring-framework | spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/CacheResultInterceptor.java | {
"start": 1361,
"end": 4070
} | class ____ extends AbstractKeyCacheInterceptor<CacheResultOperation, CacheResult> {
public CacheResultInterceptor(CacheErrorHandler errorHandler) {
super(errorHandler);
}
@Override
protected @Nullable Object invoke(
CacheOperationInvocationContext<CacheResultOperation> context, CacheOperationInvoker invoker) {
CacheResultOperation operation = context.getOperation();
Object cacheKey = generateKey(context);
Cache cache = resolveCache(context);
Cache exceptionCache = resolveExceptionCache(context);
if (!operation.isAlwaysInvoked()) {
Cache.ValueWrapper cachedValue = doGet(cache, cacheKey);
if (cachedValue != null) {
return cachedValue.get();
}
checkForCachedException(exceptionCache, cacheKey);
}
try {
Object invocationResult = invoker.invoke();
doPut(cache, cacheKey, invocationResult);
return invocationResult;
}
catch (CacheOperationInvoker.ThrowableWrapper ex) {
Throwable original = ex.getOriginal();
cacheException(exceptionCache, operation.getExceptionTypeFilter(), cacheKey, original);
throw ex;
}
}
/**
* Check for a cached exception. If the exception is found, throw it directly.
*/
protected void checkForCachedException(@Nullable Cache exceptionCache, Object cacheKey) {
if (exceptionCache == null) {
return;
}
Cache.ValueWrapper result = doGet(exceptionCache, cacheKey);
if (result != null) {
Throwable ex = (Throwable) result.get();
Assert.state(ex != null, "No exception in cache");
throw rewriteCallStack(ex, getClass().getName(), "invoke");
}
}
protected void cacheException(@Nullable Cache exceptionCache, ExceptionTypeFilter filter, Object cacheKey, Throwable ex) {
if (exceptionCache == null) {
return;
}
if (filter.match(ex)) {
doPut(exceptionCache, cacheKey, ex);
}
}
private @Nullable Cache resolveExceptionCache(CacheOperationInvocationContext<CacheResultOperation> context) {
CacheResolver exceptionCacheResolver = context.getOperation().getExceptionCacheResolver();
if (exceptionCacheResolver != null) {
return extractFrom(exceptionCacheResolver.resolveCaches(context));
}
return null;
}
/**
* Rewrite the call stack of the specified {@code exception} so that it matches
* the current call stack up to (included) the specified method invocation.
* <p>Clone the specified exception. If the exception is not {@code serializable},
* the original exception is returned. If no common ancestor can be found, returns
* the original exception.
* <p>Used to make sure that a cached exception has a valid invocation context.
* @param exception the exception to merge with the current call stack
* @param className the | CacheResultInterceptor |
java | google__auto | value/src/main/java/com/google/auto/value/processor/AutoValueishProcessor.java | {
"start": 50413,
"end": 51444
} | class ____ does not exist, then javac will represent it as a String in the
// AnnotationValue, rather than an ErrorType as you might expect. So we filter out anything that
// is not a DeclaredType. (ErrorType *is* a DeclaredType.) Presumably you'll get a compilation
// error because of the missing class. If another compiler uses ErrorType instead of String,
// then we'll just add that ErrorType to the returned TypeMirrorSet here, where it will
// presumably be ignored, or perhaps match the ErrorType for `@Missing` somewhere else in the
// code.
// This is a pretty obscure case so our main concern here is to avoid a ClassCastException.
return excludedClasses.stream()
.map(AnnotationValue::getValue)
.filter(DeclaredType.class::isInstance)
.map(DeclaredType.class::cast)
.collect(toCollection(TypeMirrorSet::new));
}
/**
* Returns the contents of the {@code AutoValue.CopyAnnotations.exclude} element, as a set of
* strings that are fully-qualified | that |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/validator/ValidatorResourceResolverFactoryTest.java | {
"start": 1883,
"end": 6324
} | class ____ extends ContextTestSupport {
private Context jndiContext;
@Test
public void testConfigurationOnEndpoint() throws Exception {
// ensure that validator from test method "testConfigurationOnComponent"
// is unbind
jndiContext.unbind("validator");
String directStart = "direct:start";
String endpointUri
= "validator:org/apache/camel/component/validator/xsds/person.xsd?resourceResolverFactory=#resourceResolverFactory";
execute(directStart, endpointUri);
}
@Test
public void testConfigurationOnComponent() throws Exception {
// set resource resolver factory on component
ValidatorComponent validatorComponent = new ValidatorComponent();
validatorComponent.setResourceResolverFactory(new ResourceResolverFactoryImpl());
jndiContext.bind("validator", validatorComponent);
String directStart = "direct:startComponent";
String endpointUri = "validator:org/apache/camel/component/validator/xsds/person.xsd";
execute(directStart, endpointUri);
}
void execute(String directStart, String endpointUri) throws InterruptedException {
MockEndpoint endEndpoint = resolveMandatoryEndpoint("mock:end", MockEndpoint.class);
endEndpoint.expectedMessageCount(1);
final String body
= "<p:person user=\"james\" xmlns:p=\"org.person\" xmlns:h=\"org.health.check.person\" xmlns:c=\"org.health.check.common\">\n" //
+ " <p:firstName>James</p:firstName>\n" //
+ " <p:lastName>Strachan</p:lastName>\n" //
+ " <p:city>London</p:city>\n" //
+ " <h:health>\n"//
+ " <h:lastCheck>2011-12-23</h:lastCheck>\n" //
+ " <h:status>OK</h:status>\n" //
+ " <c:commonElement>" //
+ " <c:element1/>" //
+ " <c:element2/>" //
+ " </c:commonElement>" //
+ " </h:health>\n" //
+ "</p:person>";
template.sendBody(directStart, body);
// wait until endpoint is resolved
await().atMost(1, TimeUnit.SECONDS).until(() -> resolveMandatoryEndpoint(endpointUri, ValidatorEndpoint.class) != null);
MockEndpoint.assertIsSatisfied(endEndpoint);
ValidatorEndpoint validatorEndpoint = resolveMandatoryEndpoint(endpointUri, ValidatorEndpoint.class);
assertNotNull(validatorEndpoint);
CustomResourceResolver resolver = (CustomResourceResolver) validatorEndpoint.getResourceResolver();
Set<String> uris = resolver.getResolvedResourceUris();
checkResourceUri(uris, "../type2.xsd");
checkResourceUri(uris, "health/health.xsd");
checkResourceUri(uris, "type1.xsd");
checkResourceUri(uris, "common/common.xsd");
}
void checkResourceUri(Set<String> uris, String resourceUri) {
assertTrue(uris.contains(resourceUri), "Missing resource uri " + resourceUri + " in resolved resource URI set");
}
@Override
protected Registry createCamelRegistry() throws Exception {
jndiContext = createJndiContext();
jndiContext.bind("resourceResolverFactory", new ResourceResolverFactoryImpl());
return new DefaultRegistry(new JndiBeanRepository(jndiContext));
}
@Override
protected RouteBuilder[] createRouteBuilders() {
return new RouteBuilder[] { new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.setHeader("xsd_file", new ConstantExpression("org/apache/camel/component/validator/xsds/person.xsd"))
.recipientList(new SimpleExpression(
"validator:${header.xsd_file}?resourceResolverFactory=#resourceResolverFactory"))
.to("mock:end");
}
}, new RouteBuilder() {
@Override
public void configure() {
from("direct:startComponent")
.setHeader("xsd_file", new ConstantExpression("org/apache/camel/component/validator/xsds/person.xsd"))
.recipientList(new SimpleExpression("validator:${header.xsd_file}")).to("mock:end");
}
} };
}
static | ValidatorResourceResolverFactoryTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/JsonAsStringJdbcType.java | {
"start": 857,
"end": 6390
} | class ____ extends JsonJdbcType implements AdjustableJdbcType {
/**
* Singleton access
*/
public static final JsonAsStringJdbcType VARCHAR_INSTANCE = new JsonAsStringJdbcType( SqlTypes.LONG32VARCHAR, null );
public static final JsonAsStringJdbcType NVARCHAR_INSTANCE = new JsonAsStringJdbcType( SqlTypes.LONG32NVARCHAR, null );
public static final JsonAsStringJdbcType CLOB_INSTANCE = new JsonAsStringJdbcType( SqlTypes.CLOB, null );
public static final JsonAsStringJdbcType NCLOB_INSTANCE = new JsonAsStringJdbcType( SqlTypes.NCLOB, null );
private final boolean nationalized;
private final int ddlTypeCode;
protected JsonAsStringJdbcType(int ddlTypeCode, EmbeddableMappingType embeddableMappingType) {
super( embeddableMappingType );
this.ddlTypeCode = ddlTypeCode;
this.nationalized = ddlTypeCode == SqlTypes.LONG32NVARCHAR
|| ddlTypeCode == SqlTypes.NCLOB;
}
@Override
public int getJdbcTypeCode() {
return nationalized ? SqlTypes.NVARCHAR : SqlTypes.VARCHAR;
}
@Override
public int getDdlTypeCode() {
return ddlTypeCode;
}
@Override
public String toString() {
return "JsonAsStringJdbcType";
}
@Override
public JdbcType resolveIndicatedType(JdbcTypeIndicators indicators, JavaType<?> domainJtd) {
// Depending on the size of the column, we might have to adjust the jdbc type code for DDL.
// In some DBMS we can compare LOBs with special functions which is handled in the SqlAstTranslators,
// but that requires the correct jdbc type code to be available, which we ensure this way
if ( getEmbeddableMappingType() == null ) {
if ( needsLob( indicators ) ) {
return indicators.isNationalized() ? NCLOB_INSTANCE : CLOB_INSTANCE;
}
else {
return indicators.isNationalized() ? NVARCHAR_INSTANCE : VARCHAR_INSTANCE;
}
}
else {
if ( needsLob( indicators ) ) {
return new JsonAsStringJdbcType(
indicators.isNationalized() ? SqlTypes.NCLOB : SqlTypes.CLOB,
getEmbeddableMappingType()
);
}
else {
return new JsonAsStringJdbcType(
indicators.isNationalized() ? SqlTypes.LONG32NVARCHAR : SqlTypes.LONG32VARCHAR,
getEmbeddableMappingType()
);
}
}
}
protected boolean needsLob(JdbcTypeIndicators indicators) {
final Dialect dialect = indicators.getDialect();
final long length = indicators.getColumnLength();
final long maxLength = indicators.isNationalized()
? dialect.getMaxNVarcharLength()
: dialect.getMaxVarcharLength();
if ( length > maxLength ) {
return true;
}
final DdlTypeRegistry ddlTypeRegistry = indicators.getTypeConfiguration().getDdlTypeRegistry();
final String typeName = ddlTypeRegistry.getTypeName( getDdlTypeCode(), dialect );
return typeName.equals( ddlTypeRegistry.getTypeName( SqlTypes.CLOB, dialect ) )
|| typeName.equals( ddlTypeRegistry.getTypeName( SqlTypes.NCLOB, dialect ) );
}
@Override
public AggregateJdbcType resolveAggregateJdbcType(
EmbeddableMappingType mappingType,
String sqlType,
RuntimeModelCreationContext creationContext) {
return new JsonAsStringJdbcType( ddlTypeCode, mappingType );
}
@Override
public <X> ValueBinder<X> getBinder(JavaType<X> javaType) {
if ( nationalized ) {
return new BasicBinder<>( javaType, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options)
throws SQLException {
final String json = ( (JsonAsStringJdbcType) getJdbcType() ).toString( value, getJavaType(), options );
if ( options.getDialect().supportsNationalizedMethods() ) {
st.setNString( index, json );
}
else {
st.setString( index, json );
}
}
@Override
protected void doBind(CallableStatement st, X value, String name, WrapperOptions options)
throws SQLException {
final String json = ( (JsonAsStringJdbcType) getJdbcType() ).toString( value, getJavaType(), options );
if ( options.getDialect().supportsNationalizedMethods() ) {
st.setNString( name, json );
}
else {
st.setString( name, json );
}
}
};
}
else {
return super.getBinder( javaType );
}
}
@Override
public <X> ValueExtractor<X> getExtractor(JavaType<X> javaType) {
if ( nationalized ) {
return new BasicExtractor<>( javaType, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
if ( options.getDialect().supportsNationalizedMethods() ) {
return fromString( rs.getNString( paramIndex ), getJavaType(), options );
}
else {
return fromString( rs.getString( paramIndex ), getJavaType(), options );
}
}
@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options)
throws SQLException {
if ( options.getDialect().supportsNationalizedMethods() ) {
return fromString( statement.getNString( index ), getJavaType(), options );
}
else {
return fromString( statement.getString( index ), getJavaType(), options );
}
}
@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options)
throws SQLException {
if ( options.getDialect().supportsNationalizedMethods() ) {
return fromString( statement.getNString( name ), getJavaType(), options );
}
else {
return fromString( statement.getString( name ), getJavaType(), options );
}
}
};
}
else {
return super.getExtractor( javaType );
}
}
}
| JsonAsStringJdbcType |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/streaming/runtime/CoGroupJoinITCase.java | {
"start": 16071,
"end": 16345
} | class ____
implements KeySelector<Tuple3<String, String, Integer>, String> {
@Override
public String getKey(Tuple3<String, String, Integer> value) throws Exception {
return value.f0;
}
}
private static | Tuple3KeyExtractor |
java | quarkusio__quarkus | integration-tests/gradle/src/test/java/io/quarkus/gradle/MultiCompositeBuildExtensionsQuarkusBuildTest.java | {
"start": 276,
"end": 3622
} | class ____ extends QuarkusGradleWrapperTestBase {
@Test
public void testBasicMultiModuleBuild() throws Exception {
final File projectDir = getProjectDir("multi-composite-build-extensions-project");
final File appProperties = new File(projectDir, "application/gradle.properties");
final File libsProperties = new File(projectDir, "libraries/gradle.properties");
final File extensionProperties = new File(projectDir, "extensions/example-extension/gradle.properties");
final File anotherExtensionProperties = new File(projectDir, "extensions/another-example-extension/gradle.properties");
final Path projectProperties = projectDir.toPath().resolve("gradle.properties");
try {
Files.copy(projectProperties, appProperties.toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.copy(projectProperties, libsProperties.toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.copy(projectProperties, extensionProperties.toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.copy(projectProperties, anotherExtensionProperties.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Unable to copy gradle.properties file", e);
}
runGradleWrapper(projectDir, ":application:quarkusBuild");
final Path extension = projectDir.toPath().resolve("extensions").resolve("example-extension").resolve("runtime")
.resolve("build")
.resolve("libs");
assertThat(extension).exists();
assertThat(extension.resolve("example-extension-1.0-SNAPSHOT.jar")).exists();
final Path anotherExtension = projectDir.toPath().resolve("extensions").resolve("another-example-extension")
.resolve("runtime")
.resolve("build");
assertThat(anotherExtension).exists();
assertThat(anotherExtension.resolve("resources/main/META-INF/quarkus-extension.yaml")).exists();
final Path libA = projectDir.toPath().resolve("libraries").resolve("libraryA").resolve("build").resolve("libs");
assertThat(libA).exists();
assertThat(libA.resolve("libraryA-1.0-SNAPSHOT.jar")).exists();
final Path libB = projectDir.toPath().resolve("libraries").resolve("libraryB").resolve("build").resolve("libs");
assertThat(libB).exists();
assertThat(libB.resolve("libraryB-1.0-SNAPSHOT.jar")).exists();
final Path applicationLib = projectDir.toPath().resolve("application").resolve("build").resolve("quarkus-app");
assertThat(applicationLib.resolve("lib").resolve("main").resolve("org.acme.libs.libraryA-1.0-SNAPSHOT.jar")).exists();
assertThat(applicationLib.resolve("lib").resolve("main").resolve("org.acme.libs.libraryB-1.0-SNAPSHOT.jar")).exists();
assertThat(applicationLib.resolve("lib").resolve("main")
.resolve("org.acme.extensions.example-extension-1.0-SNAPSHOT.jar")).exists();
assertThat(applicationLib.resolve("lib").resolve("main")
.resolve("org.acme.extensions.another-example-extension-1.0-SNAPSHOT.jar")).exists();
assertThat(applicationLib.resolve("app").resolve("application-1.0-SNAPSHOT.jar")).exists();
}
}
| MultiCompositeBuildExtensionsQuarkusBuildTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13151/SideEntity.java | {
"start": 285,
"end": 665
} | class ____ {
public SideEntity() {
this( "" );
}
public SideEntity(String name) {
this.name = name;
}
@Id
@GeneratedValue
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;
}
private Long id;
private String name;
}
| SideEntity |
java | google__guava | android/guava-tests/test/com/google/common/collect/ListsTest.java | {
"start": 31283,
"end": 36242
} | class ____<E> extends ForwardingList<E> {
private final List<E> realDelegate;
private ListIterationOnlyList(List<E> realDelegate) {
this.realDelegate = realDelegate;
}
@Override
public int size() {
return realDelegate.size();
}
@Override
public ListIterator<E> listIterator(int index) {
return realDelegate.listIterator(index);
}
@Override
protected List<E> delegate() {
throw new UnsupportedOperationException("This list only supports ListIterator");
}
}
private static void assertTransformIterator(List<String> list) {
Iterator<String> iterator = list.iterator();
assertTrue(iterator.hasNext());
assertEquals("1", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("2", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("3", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("4", iterator.next());
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("did not detect end of list");
} catch (NoSuchElementException expected) {
}
iterator.remove();
assertEquals(asList("1", "2", "3"), list);
assertFalse(iterator.hasNext());
}
public void testPartition_badSize() {
List<Integer> source = singletonList(1);
assertThrows(IllegalArgumentException.class, () -> partition(source, 0));
}
public void testPartition_empty() {
List<Integer> source = emptyList();
List<List<Integer>> partitions = partition(source, 1);
assertTrue(partitions.isEmpty());
assertEquals(0, partitions.size());
}
public void testPartition_1_1() {
List<Integer> source = singletonList(1);
List<List<Integer>> partitions = partition(source, 1);
assertEquals(1, partitions.size());
assertEquals(singletonList(1), partitions.get(0));
}
public void testPartition_1_2() {
List<Integer> source = singletonList(1);
List<List<Integer>> partitions = partition(source, 2);
assertEquals(1, partitions.size());
assertEquals(singletonList(1), partitions.get(0));
}
public void testPartition_2_1() {
List<Integer> source = asList(1, 2);
List<List<Integer>> partitions = partition(source, 1);
assertEquals(2, partitions.size());
assertEquals(singletonList(1), partitions.get(0));
assertEquals(singletonList(2), partitions.get(1));
}
public void testPartition_3_2() {
List<Integer> source = asList(1, 2, 3);
List<List<Integer>> partitions = partition(source, 2);
assertEquals(2, partitions.size());
assertEquals(asList(1, 2), partitions.get(0));
assertEquals(asList(3), partitions.get(1));
}
@J2ktIncompatible // Arrays.asList(...).subList() doesn't implement RandomAccess in J2KT.
@GwtIncompatible // ArrayList.subList doesn't implement RandomAccess in GWT.
public void testPartitionRandomAccessTrue() {
List<Integer> source = asList(1, 2, 3);
List<List<Integer>> partitions = partition(source, 2);
assertTrue(
"partition should be RandomAccess, but not: " + partitions.getClass(),
partitions instanceof RandomAccess);
assertTrue(
"partition[0] should be RandomAccess, but not: " + partitions.get(0).getClass(),
partitions.get(0) instanceof RandomAccess);
assertTrue(
"partition[1] should be RandomAccess, but not: " + partitions.get(1).getClass(),
partitions.get(1) instanceof RandomAccess);
}
public void testPartitionRandomAccessFalse() {
List<Integer> source = new LinkedList<>(asList(1, 2, 3));
List<List<Integer>> partitions = partition(source, 2);
assertFalse(partitions instanceof RandomAccess);
assertFalse(partitions.get(0) instanceof RandomAccess);
assertFalse(partitions.get(1) instanceof RandomAccess);
}
// TODO: use the ListTestSuiteBuilder
public void testPartition_view() {
List<Integer> list = asList(1, 2, 3);
List<List<Integer>> partitions = partition(list, 3);
// Changes before the partition is retrieved are reflected
list.set(0, 3);
Iterator<List<Integer>> iterator = partitions.iterator();
// Changes before the partition is retrieved are reflected
list.set(1, 4);
List<Integer> first = iterator.next();
// Changes after are too (unlike Iterables.partition)
list.set(2, 5);
assertEquals(asList(3, 4, 5), first);
// Changes to a sublist also write through to the original list
first.set(1, 6);
assertEquals(asList(3, 6, 5), list);
}
public void testPartitionSize_1() {
List<Integer> list = asList(1, 2, 3);
assertEquals(1, partition(list, Integer.MAX_VALUE).size());
assertEquals(1, partition(list, Integer.MAX_VALUE - 1).size());
}
@GwtIncompatible // cannot do such a big explicit copy
@J2ktIncompatible // too slow
public void testPartitionSize_2() {
assertEquals(2, partition(nCopies(0x40000001, 1), 0x40000000).size());
}
}
| ListIterationOnlyList |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/security/ssl/mock/TestProvider.java | {
"start": 896,
"end": 1569
} | class ____ extends Provider {
private static final String KEY_MANAGER_FACTORY = String.format("KeyManagerFactory.%s", TestKeyManagerFactory.ALGORITHM);
private static final String TRUST_MANAGER_FACTORY = String.format("TrustManagerFactory.%s", TestTrustManagerFactory.ALGORITHM);
public TestProvider() {
this("TestProvider", "0.1", "provider for test cases");
}
private TestProvider(String name, String version, String info) {
super(name, version, info);
super.put(KEY_MANAGER_FACTORY, TestKeyManagerFactory.class.getName());
super.put(TRUST_MANAGER_FACTORY, TestTrustManagerFactory.class.getName());
}
}
| TestProvider |
java | spring-projects__spring-boot | buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitectureCheck.java | {
"start": 2599,
"end": 8401
} | class ____ extends DefaultTask {
static final String CONDITIONAL_ON_CLASS = "ConditionalOnClass";
static final String DEPRECATED_CONFIGURATION_PROPERTY = "DeprecatedConfigurationProperty";
private static final String CONDITIONAL_ON_CLASS_ANNOTATION = "org.springframework.boot.autoconfigure.condition.ConditionalOnClass";
private static final String DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION = "org.springframework.boot.context.properties.DeprecatedConfigurationProperty";
private FileCollection classes;
public ArchitectureCheck() {
getOutputDirectory().convention(getProject().getLayout().getBuildDirectory().dir(getName()));
getAnnotationClasses().convention(Map.of(CONDITIONAL_ON_CLASS, CONDITIONAL_ON_CLASS_ANNOTATION,
DEPRECATED_CONFIGURATION_PROPERTY, DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION));
getRules().addAll(getProhibitObjectsRequireNonNull().convention(true)
.map(whenTrue(ArchitectureRules::noClassesShouldCallObjectsRequireNonNull)));
getRules().addAll(ArchitectureRules.standard());
getRules().addAll(whenMainSources(() -> ArchitectureRules
.beanMethods(annotationClassFor(CONDITIONAL_ON_CLASS, CONDITIONAL_ON_CLASS_ANNOTATION))));
getRules().addAll(whenMainSources(() -> ArchitectureRules.configurationProperties(
annotationClassFor(DEPRECATED_CONFIGURATION_PROPERTY, DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION))));
getRules().addAll(and(getNullMarkedEnabled(), isMainSourceSet()).map(whenTrue(() -> Collections.singletonList(
ArchitectureRules.packagesShouldBeAnnotatedWithNullMarked(getNullMarkedIgnoredPackages().get())))));
getRuleDescriptions().set(getRules().map(this::asDescriptions));
}
private Provider<Boolean> and(Provider<Boolean> provider1, Provider<Boolean> provider2) {
return provider1.zip(provider2, (result1, result2) -> result1 && result2);
}
private Provider<List<ArchRule>> whenMainSources(Supplier<List<ArchRule>> rules) {
return isMainSourceSet().map(whenTrue(rules));
}
private Provider<Boolean> isMainSourceSet() {
return getSourceSet().convention(SourceSet.MAIN_SOURCE_SET_NAME).map(SourceSet.MAIN_SOURCE_SET_NAME::equals);
}
private Transformer<List<ArchRule>, Boolean> whenTrue(Supplier<List<ArchRule>> rules) {
return (in) -> (!in) ? Collections.emptyList() : rules.get();
}
private List<String> asDescriptions(List<ArchRule> rules) {
return rules.stream().map(ArchRule::getDescription).toList();
}
private String annotationClassFor(String name, String defaultValue) {
return getAnnotationClasses().get().getOrDefault(name, defaultValue);
}
@TaskAction
void checkArchitecture() throws Exception {
withCompileClasspath(() -> {
JavaClasses javaClasses = new ClassFileImporter().importPaths(classFilesPaths());
List<EvaluationResult> results = new ArrayList<>();
evaluate(javaClasses).forEach(results::add);
results.add(new AutoConfigurationChecker().check(javaClasses));
File outputFile = getOutputDirectory().file("failure-report.txt").get().getAsFile();
List<EvaluationResult> violations = results.stream().filter(EvaluationResult::hasViolation).toList();
writeViolationReport(violations, outputFile);
if (!violations.isEmpty()) {
throw new VerificationException("Architecture check failed. See '" + outputFile + "' for details.");
}
return null;
});
}
private List<Path> classFilesPaths() {
return this.classes.getFiles().stream().map(File::toPath).toList();
}
private Stream<EvaluationResult> evaluate(JavaClasses javaClasses) {
return getRules().get().stream().map((rule) -> rule.evaluate(javaClasses));
}
private void withCompileClasspath(Callable<?> callable) throws Exception {
ClassLoader previous = Thread.currentThread().getContextClassLoader();
try {
List<URL> urls = new ArrayList<>();
for (File file : getCompileClasspath().getFiles()) {
urls.add(file.toURI().toURL());
}
ClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
Thread.currentThread().setContextClassLoader(classLoader);
callable.call();
}
finally {
Thread.currentThread().setContextClassLoader(previous);
}
}
private void writeViolationReport(List<EvaluationResult> violations, File outputFile) throws IOException {
outputFile.getParentFile().mkdirs();
StringBuilder report = new StringBuilder();
for (EvaluationResult violation : violations) {
report.append(violation.getFailureReport());
report.append(String.format("%n"));
}
Files.writeString(outputFile.toPath(), report.toString(), StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
}
public void setClasses(FileCollection classes) {
this.classes = classes;
}
@Internal
public FileCollection getClasses() {
return this.classes;
}
@InputFiles
@SkipWhenEmpty
@IgnoreEmptyDirectories
@PathSensitive(PathSensitivity.RELATIVE)
final FileTree getInputClasses() {
return this.classes.getAsFileTree();
}
@InputFiles
@Classpath
public abstract ConfigurableFileCollection getCompileClasspath();
@Optional
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
public abstract DirectoryProperty getResourcesDirectory();
@OutputDirectory
public abstract DirectoryProperty getOutputDirectory();
@Internal
public abstract ListProperty<ArchRule> getRules();
@Internal
public abstract Property<Boolean> getProhibitObjectsRequireNonNull();
@Internal
abstract Property<String> getSourceSet();
@Input // Use descriptions as input since rules aren't serializable
abstract ListProperty<String> getRuleDescriptions();
@Internal
abstract Property<Boolean> getNullMarkedEnabled();
@Internal
abstract SetProperty<String> getNullMarkedIgnoredPackages();
@Input
abstract MapProperty<String, String> getAnnotationClasses();
}
| ArchitectureCheck |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/type/classreading/SimpleMetadataReader.java | {
"start": 1163,
"end": 2074
} | class ____ implements MetadataReader {
private static final int PARSING_OPTIONS =
(ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
private final Resource resource;
private final AnnotationMetadata annotationMetadata;
SimpleMetadataReader(Resource resource, @Nullable ClassLoader classLoader) throws IOException {
SimpleAnnotationMetadataReadingVisitor visitor = new SimpleAnnotationMetadataReadingVisitor(classLoader);
getClassReader(resource).accept(visitor, PARSING_OPTIONS);
this.resource = resource;
this.annotationMetadata = visitor.getMetadata();
}
private static ClassReader getClassReader(Resource resource) throws IOException {
try (InputStream is = resource.getInputStream()) {
try {
return new ClassReader(is);
}
catch (IllegalArgumentException ex) {
throw new ClassFormatException("ASM ClassReader failed to parse | SimpleMetadataReader |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/Lock.java | {
"start": 644,
"end": 1161
} | class ____ {
private Integer id;
private Integer version;
private String name;
public Lock() {
}
public Lock(String name) {
this.name = name;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Version
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
| Lock |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/jackson2/SwitchUserGrantedAuthorityMixIn.java | {
"start": 1131,
"end": 1843
} | class ____ serialize/deserialize {@link SwitchUserGrantedAuthority}.
*
* @author Markus Heiden
* @since 6.3
* @see WebJackson2Module
* @see WebServletJackson2Module
* @see org.springframework.security.jackson2.SecurityJackson2Modules
* @deprecated as of 7.0 in favor of
* {@code org.springframework.security.web.jackson.SwitchUserGrantedAuthorityMixIn} based
* on Jackson 3
*/
@SuppressWarnings("removal")
@Deprecated(forRemoval = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract | to |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsZero_Test.java | {
"start": 1287,
"end": 3445
} | class ____ extends BytesBaseTest {
@BeforeEach
@Override
public void setUp() {
super.setUp();
resetFailures();
}
@Test
void should_succeed_since_actual_is_zero() {
bytes.assertIsZero(someInfo(), (byte) 0x00);
}
@Test
void should_fail_since_actual_is_not_zero() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsZero(someInfo(), (byte) 2))
.withMessage(shouldBeEqualMessage("2", "0"));
}
@Test
void should_fail_since_actual_is_not_zero_in_hex_representation() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsZero(someHexInfo(), (byte) 0x02))
.withMessage(shouldBeEqualMessage("0x02", "0x00"));
}
@Test
void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is() {
bytesWithAbsValueComparisonStrategy.assertIsZero(someInfo(), (byte) 0);
}
@Test
void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is_in_hex_representation() {
bytesWithAbsValueComparisonStrategy.assertIsZero(someHexInfo(), (byte) 0x00);
}
@Test
void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytesWithAbsValueComparisonStrategy.assertIsZero(someInfo(),
(byte) 1))
.withMessage(shouldBeEqualMessage("1", "0"));
}
@Test
void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is_in_hex_representation() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytesWithAbsValueComparisonStrategy.assertIsZero(someHexInfo(),
(byte) 0x01))
.withMessage(shouldBeEqualMessage("0x01", "0x00"));
}
}
| Bytes_assertIsZero_Test |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/Token.java | {
"start": 5216,
"end": 5334
} | class ____ for it
* @throws IOException failure to unmarshall the data
* @throws RuntimeException if the token | found |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java | {
"start": 32600,
"end": 33794
} | class ____ extends AuxiliaryService {
static final FsPermission RECOVERY_PATH_PERMS =
new FsPermission((short)0700);
String auxName;
RecoverableAuxService(String name, String auxName) {
super(name);
this.auxName = auxName;
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
super.serviceInit(conf);
Path storagePath = getRecoveryPath();
assertNotNull(storagePath,
"Recovery path not present when aux service inits");
assertTrue(storagePath.toString().contains(auxName));
FileSystem fs = FileSystem.getLocal(conf);
assertTrue(fs.exists(storagePath), "Recovery path does not exist");
assertEquals(new FsPermission((short)0700),
fs.getFileStatus(storagePath).getPermission(),
"Recovery path has wrong permissions");
}
@Override
public void initializeApplication(
ApplicationInitializationContext initAppContext) {
}
@Override
public void stopApplication(ApplicationTerminationContext stopAppContext) {
}
@Override
public ByteBuffer getMetaData() {
return null;
}
}
static | RecoverableAuxService |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestPendingReconstruction.java | {
"start": 3328,
"end": 3469
} | class ____ the internals of PendingReconstructionBlocks.java, as well
* as how PendingReconstructionBlocks acts in BlockManager
*/
public | tests |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/insert/OracleInsertTest.java | {
"start": 978,
"end": 2084
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = "INSERT INTO films VALUES ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement statemen = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
statemen.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());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("films")));
assertEquals(0, visitor.getColumns().size());
// assertTrue(visitor.getFields().contains(new TableStat.Column("films", "producer_id")));
}
}
| OracleInsertTest |
java | junit-team__junit5 | junit-platform-commons/src/main/java/org/junit/platform/commons/support/ModifierSupport.java | {
"start": 7425,
"end": 8445
} | class ____ not {@code final}
* @since 1.5
* @see java.lang.reflect.Modifier#isFinal(int)
*/
@API(status = MAINTAINED, since = "1.5")
public static boolean isNotFinal(Class<?> clazz) {
return ReflectionUtils.isNotFinal(clazz);
}
/**
* Determine if the supplied member is {@code final}.
*
* @param member the member to check; never {@code null}
* @return {@code true} if the member is {@code final}
* @since 1.5
* @see java.lang.reflect.Modifier#isFinal(int)
*/
@API(status = MAINTAINED, since = "1.5")
public static boolean isFinal(Member member) {
return ReflectionUtils.isFinal(member);
}
/**
* Determine if the supplied member is not {@code final}.
*
* @param member the member to check; never {@code null}
* @return {@code true} if the member is not {@code final}
* @since 1.5
* @see java.lang.reflect.Modifier#isFinal(int)
*/
@API(status = MAINTAINED, since = "1.5")
public static boolean isNotFinal(Member member) {
return ReflectionUtils.isNotFinal(member);
}
}
| is |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CheckReturnValueWellKnownLibrariesTest.java | {
"start": 2372,
"end": 2836
} | class ____ {
void m() {
lib.Test t = new lib.Test();
Mockito.verify(t).f();
verify(t).f();
doReturn(1).when(t).f();
Mockito.doReturn(1).when(t).f();
}
}
""")
.doTest();
}
@Test
public void mockitoVerifyMistake() {
refactoringHelper
.addInputLines(
"Test.java",
"""
| TestCase |
java | spring-projects__spring-security | oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/TestOAuth2AuthorizationResponses.java | {
"start": 742,
"end": 1386
} | class ____ {
private TestOAuth2AuthorizationResponses() {
}
public static OAuth2AuthorizationResponse.Builder success() {
// @formatter:off
return OAuth2AuthorizationResponse.success("authorization-code")
.state("state")
.redirectUri("https://example.com/authorize/oauth2/code/registration-id");
// @formatter:on
}
public static OAuth2AuthorizationResponse.Builder error() {
// @formatter:off
return OAuth2AuthorizationResponse.error("error")
.redirectUri("https://example.com/authorize/oauth2/code/registration-id")
.errorUri("https://example.com/error");
// @formatter:on
}
}
| TestOAuth2AuthorizationResponses |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/output/FlushAcknowledgementTests.java | {
"start": 623,
"end": 1760
} | class ____ extends AbstractXContentSerializingTestCase<FlushAcknowledgement> {
@Override
protected FlushAcknowledgement doParseInstance(XContentParser parser) {
return FlushAcknowledgement.PARSER.apply(parser, null);
}
@Override
protected FlushAcknowledgement createTestInstance() {
if (randomBoolean()) {
return new FlushAcknowledgement(
randomAlphaOfLengthBetween(1, 20),
randomFrom(randomNonNegativeLong(), 0L, null),
randomBoolean()
);
} else {
return new FlushAcknowledgement(
randomAlphaOfLengthBetween(1, 20),
randomFrom(randomInstant(), Instant.EPOCH, null),
randomBoolean()
);
}
}
@Override
protected FlushAcknowledgement mutateInstance(FlushAcknowledgement instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Reader<FlushAcknowledgement> instanceReader() {
return FlushAcknowledgement::new;
}
}
| FlushAcknowledgementTests |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/service/GetServiceAccountCredentialsResponse.java | {
"start": 718,
"end": 3354
} | class ____ extends ActionResponse implements ToXContentObject {
private final String principal;
private final List<TokenInfo> indexTokenInfos;
private final GetServiceAccountCredentialsNodesResponse nodesResponse;
public GetServiceAccountCredentialsResponse(
String principal,
Collection<TokenInfo> indexTokenInfos,
GetServiceAccountCredentialsNodesResponse nodesResponse
) {
this.principal = principal;
this.indexTokenInfos = indexTokenInfos == null ? List.of() : indexTokenInfos.stream().sorted().toList();
this.nodesResponse = nodesResponse;
}
public GetServiceAccountCredentialsResponse(StreamInput in) throws IOException {
this.principal = in.readString();
this.indexTokenInfos = in.readCollectionAsList(TokenInfo::new);
this.nodesResponse = new GetServiceAccountCredentialsNodesResponse(in);
}
public String getPrincipal() {
return principal;
}
public List<TokenInfo> getIndexTokenInfos() {
return indexTokenInfos;
}
public GetServiceAccountCredentialsNodesResponse getNodesResponse() {
return nodesResponse;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(principal);
out.writeCollection(indexTokenInfos);
nodesResponse.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
final List<TokenInfo> fileTokenInfos = nodesResponse.getFileTokenInfos();
builder.startObject()
.field("service_account", principal)
.field("count", indexTokenInfos.size() + fileTokenInfos.size())
.field("tokens")
.startObject();
for (TokenInfo info : indexTokenInfos) {
info.toXContent(builder, params);
}
builder.endObject().field("nodes_credentials").startObject();
RestActions.buildNodesHeader(builder, params, nodesResponse);
builder.startObject("file_tokens");
for (TokenInfo info : fileTokenInfos) {
info.toXContent(builder, params);
}
builder.endObject();
builder.endObject().endObject();
return builder;
}
@Override
public String toString() {
return "GetServiceAccountCredentialsResponse{"
+ "principal='"
+ principal
+ '\''
+ ", indexTokenInfos="
+ indexTokenInfos
+ ", nodesResponse="
+ nodesResponse
+ '}';
}
}
| GetServiceAccountCredentialsResponse |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/commons/util/CollectionUtilsTests.java | {
"start": 3653,
"end": 9992
} | class ____ {
@ParameterizedTest
@ValueSource(classes = { //
Stream.class, //
DoubleStream.class, //
IntStream.class, //
LongStream.class, //
Collection.class, //
Iterable.class, //
Iterator.class, //
IteratorProvider.class, //
Object[].class, //
String[].class, //
int[].class, //
double[].class, //
char[].class //
})
void isConvertibleToStreamForSupportedTypes(Class<?> type) {
assertThat(CollectionUtils.isConvertibleToStream(type)).isTrue();
}
@ParameterizedTest
@MethodSource("objectsConvertibleToStreams")
void isConvertibleToStreamForSupportedTypesFromObjects(Object object) {
assertThat(CollectionUtils.isConvertibleToStream(object.getClass())).isTrue();
}
static Stream<Object> objectsConvertibleToStreams() {
return Stream.of(//
Stream.of("cat", "dog"), //
DoubleStream.of(42.3), //
IntStream.of(99), //
LongStream.of(100_000_000), //
Set.of(1, 2, 3), //
Arguments.of((Object) new Object[] { 9, 8, 7 }), //
new int[] { 5, 10, 15 }, //
new IteratorProvider(1, 2, 3, 4, 5)//
);
}
@ParameterizedTest
@ValueSource(classes = { //
void.class, //
Void.class, //
Object.class, //
Integer.class, //
String.class, //
UnusableIteratorProvider.class, //
Spliterator.class, //
int.class, //
boolean.class //
})
void isConvertibleToStreamForUnsupportedTypes(Class<?> type) {
assertThat(CollectionUtils.isConvertibleToStream(type)).isFalse();
}
@Test
void isConvertibleToStreamForNull() {
assertThat(CollectionUtils.isConvertibleToStream(null)).isFalse();
}
@SuppressWarnings("DataFlowIssue")
@Test
void toStreamWithNull() {
assertPreconditionViolationNotNullFor("Object", () -> CollectionUtils.toStream(null));
}
@Test
void toStreamWithUnsupportedObjectType() {
assertPreconditionViolationFor(() -> CollectionUtils.toStream("unknown"))//
.withMessage("Cannot convert instance of java.lang.String into a Stream: unknown");
}
@Test
void toStreamWithExistingStream() {
var input = Stream.of("foo");
var result = CollectionUtils.toStream(input);
assertThat(result).isSameAs(input);
}
@Test
@SuppressWarnings("unchecked")
void toStreamWithDoubleStream() {
var input = DoubleStream.of(42.23);
var result = (Stream<Double>) CollectionUtils.toStream(input);
assertThat(result).containsExactly(42.23);
}
@Test
@SuppressWarnings("unchecked")
void toStreamWithIntStream() {
var input = IntStream.of(23, 42);
var result = (Stream<Integer>) CollectionUtils.toStream(input);
assertThat(result).containsExactly(23, 42);
}
@Test
@SuppressWarnings("unchecked")
void toStreamWithLongStream() {
var input = LongStream.of(23L, 42L);
var result = (Stream<Long>) CollectionUtils.toStream(input);
assertThat(result).containsExactly(23L, 42L);
}
@Test
@SuppressWarnings({ "unchecked", "serial" })
void toStreamWithCollection() {
var collectionStreamClosed = new AtomicBoolean(false);
var input = new ArrayList<>(List.of("foo", "bar")) {
@Override
public Stream<String> stream() {
return super.stream().onClose(() -> collectionStreamClosed.set(true));
}
};
try (var stream = (Stream<String>) CollectionUtils.toStream(input)) {
var result = stream.toList();
assertThat(result).containsExactly("foo", "bar");
}
assertThat(collectionStreamClosed.get()).describedAs("collectionStreamClosed").isTrue();
}
@Test
@SuppressWarnings("unchecked")
void toStreamWithIterable() {
Iterable<String> input = () -> List.of("foo", "bar").iterator();
var result = (Stream<String>) CollectionUtils.toStream(input);
assertThat(result).containsExactly("foo", "bar");
}
@Test
@SuppressWarnings("unchecked")
void toStreamWithIterator() {
var input = List.of("foo", "bar").iterator();
var result = (Stream<String>) CollectionUtils.toStream(input);
assertThat(result).containsExactly("foo", "bar");
}
@Test
@SuppressWarnings("unchecked")
void toStreamWithIteratorProvider() {
var input = new IteratorProvider("foo", "bar");
var result = (Stream<String>) CollectionUtils.toStream(input);
assertThat(result).containsExactly("foo", "bar");
}
@Test
void throwWhenIteratorNamedMethodDoesNotReturnAnIterator() {
var o = new UnusableIteratorProvider("Test");
assertPreconditionViolationFor(() -> CollectionUtils.toStream(o))//
.withMessage("Cannot convert instance of %s into a Stream: %s".formatted(
UnusableIteratorProvider.class.getName(), o));
}
@Test
@SuppressWarnings("unchecked")
void toStreamWithArray() {
var result = (Stream<String>) CollectionUtils.toStream(new String[] { "foo", "bar" });
assertThat(result).containsExactly("foo", "bar");
}
@TestFactory
Stream<DynamicTest> toStreamWithPrimitiveArrays() {
//@formatter:off
return Stream.of(
dynamicTest("boolean[]",
() -> toStreamWithPrimitiveArray(new boolean[] { true, false })),
dynamicTest("byte[]",
() -> toStreamWithPrimitiveArray(new byte[] { 0, Byte.MIN_VALUE, Byte.MAX_VALUE })),
dynamicTest("char[]",
() -> toStreamWithPrimitiveArray(new char[] { 0, Character.MIN_VALUE, Character.MAX_VALUE })),
dynamicTest("double[]",
() -> toStreamWithPrimitiveArray(new double[] { 0, Double.MIN_VALUE, Double.MAX_VALUE })),
dynamicTest("float[]",
() -> toStreamWithPrimitiveArray(new float[] { 0, Float.MIN_VALUE, Float.MAX_VALUE })),
dynamicTest("int[]",
() -> toStreamWithPrimitiveArray(new int[] { 0, Integer.MIN_VALUE, Integer.MAX_VALUE })),
dynamicTest("long[]",
() -> toStreamWithPrimitiveArray(new long[] { 0, Long.MIN_VALUE, Long.MAX_VALUE })),
dynamicTest("short[]",
() -> toStreamWithPrimitiveArray(new short[] { 0, Short.MIN_VALUE, Short.MAX_VALUE }))
);
//@formatter:on
}
private void toStreamWithPrimitiveArray(Object primitiveArray) {
assertTrue(primitiveArray.getClass().isArray());
assertTrue(primitiveArray.getClass().getComponentType().isPrimitive());
var result = CollectionUtils.toStream(primitiveArray).toArray();
for (var i = 0; i < result.length; i++) {
assertEquals(Array.get(primitiveArray, i), result[i]);
}
}
}
@Nested
| StreamConversion |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilderTest.java | {
"start": 1465,
"end": 8612
} | class ____ {
private static FrameworkModel frameworkModel;
@BeforeAll
public static void setup() {
frameworkModel = new FrameworkModel();
TypeDefinitionBuilder.initBuilders(frameworkModel);
}
@AfterAll
public static void clear() {
frameworkModel.destroy();
}
@Test
void testBuilderComplexObject() {
TypeDefinitionBuilder.initBuilders(FrameworkModel.defaultModel());
FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(DemoService.class);
checkComplexObjectAsParam(fullServiceDefinition);
}
void checkComplexObjectAsParam(FullServiceDefinition fullServiceDefinition) {
Assertions.assertTrue(fullServiceDefinition
.getAnnotations()
.contains(
"@org.apache.dubbo.metadata.definition.service.annotation.MockTypeAnnotation(value=666)")
// JDK 17 style
|| fullServiceDefinition
.getAnnotations()
.contains("@org.apache.dubbo.metadata.definition.service.annotation.MockTypeAnnotation(666)"));
List<MethodDefinition> methodDefinitions = fullServiceDefinition.getMethods();
MethodDefinition complexCompute = null;
MethodDefinition findComplexObject = null;
MethodDefinition testAnnotation = null;
for (MethodDefinition methodDefinition : methodDefinitions) {
if ("complexCompute".equals(methodDefinition.getName())) {
complexCompute = methodDefinition;
} else if ("findComplexObject".equals(methodDefinition.getName())) {
findComplexObject = methodDefinition;
} else if ("testAnnotation".equals(methodDefinition.getName())) {
testAnnotation = methodDefinition;
}
}
Assertions.assertTrue(Arrays.equals(
complexCompute.getParameterTypes(),
new String[] {String.class.getName(), ComplexObject.class.getName()}));
Assertions.assertEquals(complexCompute.getReturnType(), String.class.getName());
Assertions.assertTrue(Arrays.equals(findComplexObject.getParameterTypes(), new String[] {
String.class.getName(),
"int",
"long",
String[].class.getCanonicalName(),
"java.util.List<java.lang.Integer>",
ComplexObject.TestEnum.class.getCanonicalName()
}));
Assertions.assertEquals(findComplexObject.getReturnType(), ComplexObject.class.getCanonicalName());
Assertions.assertTrue(
(testAnnotation
.getAnnotations()
.contains(
"@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation(value=777)")
&& testAnnotation
.getAnnotations()
.contains(
"@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation2(value=888)"))
// JDK 17 style
|| (testAnnotation
.getAnnotations()
.contains(
"@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation(777)")
&& testAnnotation
.getAnnotations()
.contains(
"@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation2(888)")));
Assertions.assertEquals(testAnnotation.getReturnType(), "void");
List<TypeDefinition> typeDefinitions = fullServiceDefinition.getTypes();
TypeDefinition topTypeDefinition = null;
TypeDefinition innerTypeDefinition = null;
TypeDefinition inner2TypeDefinition = null;
TypeDefinition inner3TypeDefinition = null;
TypeDefinition listTypeDefinition = null;
for (TypeDefinition typeDefinition : typeDefinitions) {
if (typeDefinition.getType().equals(ComplexObject.class.getCanonicalName())) {
topTypeDefinition = typeDefinition;
} else if (typeDefinition.getType().equals(ComplexObject.InnerObject.class.getCanonicalName())) {
innerTypeDefinition = typeDefinition;
} else if (typeDefinition.getType().equals(ComplexObject.InnerObject2.class.getCanonicalName())) {
inner2TypeDefinition = typeDefinition;
} else if (typeDefinition.getType().equals(ComplexObject.InnerObject3.class.getCanonicalName())) {
inner3TypeDefinition = typeDefinition;
} else if (typeDefinition.getType().equals("java.util.List<java.lang.Integer>")) {
listTypeDefinition = typeDefinition;
}
}
Assertions.assertEquals("long", topTypeDefinition.getProperties().get("v"));
Assertions.assertEquals(
"java.util.Map<java.lang.String,java.lang.String>",
topTypeDefinition.getProperties().get("maps"));
Assertions.assertEquals(
ComplexObject.InnerObject.class.getCanonicalName(),
topTypeDefinition.getProperties().get("innerObject"));
Assertions.assertEquals(
"java.util.List<java.lang.Integer>",
topTypeDefinition.getProperties().get("intList"));
Assertions.assertEquals(
"java.lang.String[]", topTypeDefinition.getProperties().get("strArrays"));
Assertions.assertEquals(
"org.apache.dubbo.metadata.definition.service.ComplexObject.InnerObject3[]",
topTypeDefinition.getProperties().get("innerObject3"));
Assertions.assertEquals(
"org.apache.dubbo.metadata.definition.service.ComplexObject.TestEnum",
topTypeDefinition.getProperties().get("testEnum"));
Assertions.assertEquals(
"java.util.Set<org.apache.dubbo.metadata.definition.service.ComplexObject.InnerObject2>",
topTypeDefinition.getProperties().get("innerObject2"));
Assertions.assertSame(
"java.lang.String", innerTypeDefinition.getProperties().get("innerA"));
Assertions.assertSame("int", innerTypeDefinition.getProperties().get("innerB"));
Assertions.assertSame(
"java.lang.String", inner2TypeDefinition.getProperties().get("innerA2"));
Assertions.assertSame("int", inner2TypeDefinition.getProperties().get("innerB2"));
Assertions.assertSame(
"java.lang.String", inner3TypeDefinition.getProperties().get("innerA3"));
Assertions.assertEquals(
Integer.class.getCanonicalName(), listTypeDefinition.getItems().get(0));
}
}
| ServiceDefinitionBuilderTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/serializer/date/DateTest.java | {
"start": 393,
"end": 4927
} | class ____ extends TestCase {
protected void setUp() throws Exception {
JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
JSON.defaultLocale = Locale.CHINA;
}
public void test_0() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294552193254L));
Assert.assertEquals("1294552193254", out.toString());
}
public void test_1() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.UseISO8601DateFormat, true);
Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294552193254L));
Assert.assertEquals("\"2011-01-09T13:49:53.254+08:00\"", out.toString());
}
public void test_2() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.UseISO8601DateFormat, true);
Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294552193000L));
Assert.assertEquals("\"2011-01-09T13:49:53+08:00\"", out.toString());
}
public void test_3() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.UseISO8601DateFormat, true);
Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294502400000L));
Assert.assertEquals("\"2011-01-09+08:00\"", out.toString());
}
public void test_4() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.UseISO8601DateFormat, true);
serializer.config(SerializerFeature.UseSingleQuotes, true);
Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294502400000L));
Assert.assertEquals("'2011-01-09+08:00'", out.toString());
}
public void test_5() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.UseISO8601DateFormat, true);
Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294502401000L));
Assert.assertEquals("\"2011-01-09T00:00:01+08:00\"", out.toString());
}
public void test_6() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.UseISO8601DateFormat, true);
Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294502460000L));
Assert.assertEquals("\"2011-01-09T00:01:00+08:00\"", out.toString());
}
public void test_7() throws Exception {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
serializer.config(SerializerFeature.UseISO8601DateFormat, true);
Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseISO8601DateFormat));
serializer.write(new Date(1294506000000L));
Assert.assertEquals("\"2011-01-09T01:00:00+08:00\"", out.toString());
}
public void test_8() throws Exception {
String text = JSON.toJSONString(new Date(1294506000000L), SerializerFeature.UseISO8601DateFormat);
Assert.assertEquals("\"2011-01-09T01:00:00+08:00\"", text);
}
public void test_9() throws Exception {
String text = JSON.toJSONString(new Entity(new Date(1294506000000L)), SerializerFeature.UseISO8601DateFormat);
Assert.assertEquals("{\"date\":\"2011-01-09T01:00:00+08:00\"}", text);
Entity entity = JSON.parseObject(text, Entity.class);
Assert.assertEquals(new Date(1294506000000L), entity.getDate());
}
public static | DateTest |
java | dropwizard__dropwizard | dropwizard-core/src/test/java/io/dropwizard/core/setup/AdminEnvironmentTest.java | {
"start": 541,
"end": 1766
} | class ____ {
static {
BootstrapLogging.bootstrap();
}
private final MutableServletContextHandler handler = new MutableServletContextHandler();
private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
private final MetricRegistry metricRegistry = new MetricRegistry();
private final AdminFactory adminFactory = new AdminFactory();
private final AdminEnvironment env = new AdminEnvironment(handler, healthCheckRegistry, metricRegistry, adminFactory);
@Test
void addsATaskServlet() throws Exception {
final Task task = new Task("thing") {
@Override
public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception {
}
};
env.addTask(task);
handler.setServer(new Server());
handler.start();
final ServletRegistration registration = handler.getServletHandler()
.getServletContext()
.getServletRegistration("tasks");
assertThat(registration.getMappings())
.containsOnly("/tasks/*");
}
}
| AdminEnvironmentTest |
java | google__guava | guava/src/com/google/common/util/concurrent/FuturesGetChecked.java | {
"start": 3517,
"end": 4391
} | interface ____ {
void validateClass(Class<? extends Exception> exceptionClass);
}
private static GetCheckedTypeValidator bestGetCheckedTypeValidator() {
return GetCheckedTypeValidatorHolder.BEST_VALIDATOR;
}
@VisibleForTesting
static GetCheckedTypeValidator weakSetValidator() {
return GetCheckedTypeValidatorHolder.WeakSetValidator.INSTANCE;
}
@J2ObjCIncompatible // ClassValue
@VisibleForTesting
static GetCheckedTypeValidator classValueValidator() {
return GetCheckedTypeValidatorHolder.ClassValueValidator.INSTANCE;
}
/**
* Provides a check of whether an exception type is valid for use with {@link
* FuturesGetChecked#getChecked(Future, Class)}, possibly using caching.
*
* <p>Uses reflection to gracefully fall back to when certain implementations aren't available.
*/
private static final | GetCheckedTypeValidator |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/eventbus/MessageProducer.java | {
"start": 729,
"end": 1869
} | interface ____<T> {
/**
* Update the delivery options of this producer.
*
* @param options the new options
* @return this producer object
*/
@Fluent
MessageProducer<T> deliveryOptions(DeliveryOptions options);
/**
* @return The address to which the producer produces messages.
*/
String address();
/**
* Write a message to the event-bus, either sending or publishing.
*
* The returned {@link Future} completion depends on the producer type:
*
* <ul>
* <li>send or request: the future is completed successfully if the message has been written; otherwise, the future is failed</li>
* <li>publish: the future is failed if there is no recipient; otherwise, the future is completed successfully</li>
* </ul>
*
* In any case, a successfully completed {@link Future} is not a delivery guarantee.
*
* @param body the message body
*/
Future<Void> write(T body);
/**
* Closes the producer, this method should be called when the message producer is not used anymore.
*
* @return a future completed with the result
*/
Future<Void> close();
}
| MessageProducer |
java | apache__flink | flink-table/flink-table-api-java-bridge/src/test/java/org/apache/flink/table/factories/DataGenTableSourceFactoryTest.java | {
"start": 34670,
"end": 35218
} | class ____ implements ScanTableSource.ScanContext {
@Override
public <T> TypeInformation<T> createTypeInformation(DataType producedDataType) {
return null;
}
@Override
public <T> TypeInformation<T> createTypeInformation(LogicalType producedLogicalType) {
return null;
}
@Override
public DynamicTableSource.DataStructureConverter createDataStructureConverter(
DataType producedDataType) {
return null;
}
}
}
| TestScanContext |
java | grpc__grpc-java | api/src/test/java/io/grpc/DecompressorRegistryTest.java | {
"start": 2742,
"end": 2979
} | class ____ implements Decompressor {
@Override
public String getMessageEncoding() {
return "dummy";
}
@Override
public InputStream decompress(InputStream is) throws IOException {
return is;
}
}
}
| Dummy |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageFileTests.java | {
"start": 2262,
"end": 22068
} | class ____ extends ESTestCase {
private Environment env;
private Map<String, Path> paths;
@Before
public void setup() throws Exception {
env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
paths = new HashMap<>();
requirePath("ca1.p12");
requirePath("ca1.jks");
requirePath("ca1.crt");
requirePath("cert1a.p12");
requirePath("cert1a.jks");
requirePath("cert1a.crt");
requirePath("cert1a.key");
}
public void testMessageForMissingKeystore() {
checkMissingKeyManagerResource("[jks] keystore", "keystore.path", null);
}
public void testMessageForMissingPemCertificate() {
checkMissingKeyManagerResource("PEM certificate", "certificate", withKey("cert1a.key"));
}
public void testMessageForMissingPemKey() {
checkMissingKeyManagerResource("PEM private key", "key", withCertificate("cert1a.crt"));
}
public void testMessageForMissingTruststore() {
checkMissingTrustManagerResource("[jks] keystore (as a truststore)", "truststore.path");
}
public void testMessageForMissingCertificateAuthorities() {
checkMissingTrustManagerResource("PEM certificate_authorities", "certificate_authorities");
}
public void testMessageForKeystoreWithoutReadAccess() throws Exception {
checkUnreadableKeyManagerResource("cert1a.p12", "[PKCS12] keystore", "keystore.path", null);
}
public void testMessageForPemCertificateWithoutReadAccess() throws Exception {
checkUnreadableKeyManagerResource("cert1a.crt", "PEM certificate", "certificate", withKey("cert1a.key"));
}
public void testMessageForPemKeyWithoutReadAccess() throws Exception {
checkUnreadableKeyManagerResource("cert1a.key", "PEM private key", "key", withCertificate("cert1a.crt"));
}
public void testMessageForTruststoreWithoutReadAccess() throws Exception {
checkUnreadableTrustManagerResource("cert1a.p12", "[PKCS12] keystore (as a truststore)", "truststore.path");
}
public void testMessageForCertificateAuthoritiesWithoutReadAccess() throws Exception {
checkUnreadableTrustManagerResource("ca1.crt", "PEM certificate_authorities", "certificate_authorities");
}
public void testMessageForKeyStoreOutsideConfigDir() throws Exception {
checkBlockedKeyManagerResource("[jks] keystore", "keystore.path", null);
}
public void testMessageForPemCertificateOutsideConfigDir() throws Exception {
checkBlockedKeyManagerResource("PEM certificate", "certificate", withKey("cert1a.key"));
}
public void testMessageForPemKeyOutsideConfigDir() throws Exception {
checkBlockedKeyManagerResource("PEM private key", "key", withCertificate("cert1a.crt"));
}
public void testMessageForTrustStoreOutsideConfigDir() throws Exception {
checkBlockedTrustManagerResource("[jks] keystore (as a truststore)", "truststore.path");
}
public void testMessageForCertificateAuthoritiesOutsideConfigDir() throws Exception {
checkBlockedTrustManagerResource("PEM certificate_authorities", "certificate_authorities");
}
public void testMessageForTransportSslEnabledWithoutKeys() throws Exception {
final String prefix = "xpack.security.transport.ssl";
final Settings.Builder settings = Settings.builder();
settings.put(prefix + ".enabled", true);
if (inFipsJvm()) {
configureWorkingTrustedAuthorities(prefix, settings);
} else {
configureWorkingTruststore(prefix, settings);
}
Throwable exception = expectFailure(settings);
assertThat(
exception,
throwableWithMessage(
"invalid SSL configuration for "
+ prefix
+ " - server ssl configuration requires a key and certificate, but these have not been configured;"
+ " you must set either ["
+ prefix
+ ".keystore.path], or both ["
+ prefix
+ ".key] and ["
+ prefix
+ ".certificate]"
)
);
assertThat(exception, instanceOf(ElasticsearchException.class));
}
public void testNoErrorIfTransportSslDisabledWithoutKeys() throws Exception {
final String prefix = "xpack.security.transport.ssl";
final Settings.Builder settings = Settings.builder();
settings.put(prefix + ".enabled", false);
if (inFipsJvm()) {
configureWorkingTrustedAuthorities(prefix, settings);
} else {
configureWorkingTruststore(prefix, settings);
}
expectSuccess(settings);
}
public void testMessageForTransportNotEnabledButKeystoreConfigured() throws Exception {
assumeFalse("Cannot run in a FIPS JVM since it uses a PKCS12 keystore", inFipsJvm());
final String prefix = "xpack.security.transport.ssl";
checkUnusedConfiguration(prefix, prefix + ".keystore.path," + prefix + ".keystore.secure_password", this::configureWorkingKeystore);
}
public void testMessageForTransportNotEnabledButTruststoreConfigured() throws Exception {
assumeFalse("Cannot run in a FIPS JVM since it uses a PKCS12 keystore", inFipsJvm());
final String prefix = "xpack.security.transport.ssl";
checkUnusedConfiguration(
prefix,
prefix + ".truststore.path," + prefix + ".truststore.secure_password",
this::configureWorkingTruststore
);
}
public void testMessageForHttpsNotEnabledButKeystoreConfigured() throws Exception {
assumeFalse("Cannot run in a FIPS JVM since it uses a PKCS12 keystore", inFipsJvm());
final String prefix = "xpack.security.http.ssl";
checkUnusedConfiguration(prefix, prefix + ".keystore.path," + prefix + ".keystore.secure_password", this::configureWorkingKeystore);
}
public void testMessageForHttpsNotEnabledButTruststoreConfigured() throws Exception {
assumeFalse("Cannot run in a FIPS JVM since it uses a PKCS12 keystore", inFipsJvm());
final String prefix = "xpack.security.http.ssl";
checkUnusedConfiguration(
prefix,
prefix + ".truststore.path," + prefix + ".truststore.secure_password",
this::configureWorkingTruststore
);
}
public void testMessageForRemoteClusterSslEnabledWithoutKeys() {
final String prefix = "xpack.security.remote_cluster_server.ssl";
final Settings.Builder builder = Settings.builder().put("remote_cluster_server.enabled", true);
// remote cluster ssl is enabled by default
if (randomBoolean()) {
builder.put(prefix + ".enabled", true);
}
if (inFipsJvm()) {
configureWorkingTrustedAuthorities(prefix, builder);
} else {
configureWorkingTruststore(prefix, builder);
}
final Throwable exception = expectFailure(builder);
assertThat(
exception,
throwableWithMessage(
"invalid SSL configuration for "
+ prefix
+ " - server ssl configuration requires a key and certificate, but these have not been configured;"
+ " you must set either ["
+ prefix
+ ".keystore.path], or both ["
+ prefix
+ ".key] and ["
+ prefix
+ ".certificate]"
)
);
assertThat(exception, instanceOf(ElasticsearchException.class));
}
public void testNoErrorIfRemoteClusterOrSslDisabledWithoutKeys() {
final String prefix = "xpack.security.remote_cluster_server.ssl";
final Settings.Builder builder = Settings.builder().put(prefix + ".enabled", false);
if (randomBoolean()) {
builder.put("remote_cluster_server.enabled", true);
} else {
builder.put("remote_cluster_server.enabled", false);
}
if (inFipsJvm()) {
configureWorkingTrustedAuthorities(prefix, builder);
} else {
configureWorkingTruststore(prefix, builder);
}
expectSuccess(builder);
}
private void checkMissingKeyManagerResource(String fileType, String configKey, @Nullable Settings.Builder additionalSettings) {
checkMissingResource(fileType, configKey, (prefix, builder) -> buildKeyConfigSettings(additionalSettings, prefix, builder));
}
private void buildKeyConfigSettings(@Nullable Settings.Builder additionalSettings, String prefix, Settings.Builder builder) {
if (inFipsJvm()) {
configureWorkingTrustedAuthorities(prefix, builder);
} else {
configureWorkingTruststore(prefix, builder);
}
if (additionalSettings != null) {
builder.put(additionalSettings.normalizePrefix(prefix + ".").build());
}
}
private void checkMissingTrustManagerResource(String fileType, String configKey) {
checkMissingResource(fileType, configKey, this::configureWorkingKeystore);
}
private void checkUnreadableKeyManagerResource(
String fromResource,
String fileType,
String configKey,
@Nullable Settings.Builder additionalSettings
) throws Exception {
checkUnreadableResource(
fromResource,
fileType,
configKey,
(prefix, builder) -> buildKeyConfigSettings(additionalSettings, prefix, builder)
);
}
private void checkUnreadableTrustManagerResource(String fromResource, String fileType, String configKey) throws Exception {
checkUnreadableResource(fromResource, fileType, configKey, this::configureWorkingKeystore);
}
private void checkBlockedKeyManagerResource(String fileType, String configKey, Settings.Builder additionalSettings) throws Exception {
checkBlockedResource(
"KeyManager",
fileType,
configKey,
(prefix, builder) -> buildKeyConfigSettings(additionalSettings, prefix, builder)
);
}
private void checkBlockedTrustManagerResource(String fileType, String configKey) throws Exception {
checkBlockedResource("TrustManager", fileType, configKey, this::configureWorkingKeystore);
}
private void checkMissingResource(String fileType, String configKey, BiConsumer<String, Settings.Builder> configure) {
final String prefix = randomSslPrefix();
final Settings.Builder settings = Settings.builder();
configure.accept(prefix, settings);
final String fileName = missingFile();
final String key = prefix + "." + configKey;
settings.put(key, fileName);
final String fileErrorMessage = "cannot read configured " + fileType + " [" + fileName + "] because the file does not exist";
Throwable exception = expectFailure(settings);
assertThat(exception, throwableWithMessage("failed to load SSL configuration [" + prefix + "] - " + fileErrorMessage));
assertThat(exception, instanceOf(ElasticsearchSecurityException.class));
exception = exception.getCause();
assertThat(exception, throwableWithMessage(fileErrorMessage));
assertThat(exception, instanceOf(SslConfigException.class));
exception = exception.getCause();
assertThat(exception, instanceOf(NoSuchFileException.class));
assertThat(exception, throwableWithMessage(fileName));
}
private void checkUnreadableResource(
String fromResource,
String fileType,
String configKey,
BiConsumer<String, Settings.Builder> configure
) throws Exception {
final String prefix = randomSslPrefix();
final Settings.Builder settings = Settings.builder();
configure.accept(prefix, settings);
final String fileName = unreadableFile(fromResource);
final String key = prefix + "." + configKey;
settings.put(key, fileName);
final String fileErrorMessage = "not permitted to read the " + fileType + " file [" + fileName + "]";
Throwable exception = expectFailure(settings);
assertThat(exception, throwableWithMessage("failed to load SSL configuration [" + prefix + "] - " + fileErrorMessage));
assertThat(exception, instanceOf(ElasticsearchSecurityException.class));
exception = exception.getCause();
assertThat(exception, throwableWithMessage(fileErrorMessage));
assertThat(exception, instanceOf(SslConfigException.class));
exception = exception.getCause();
assertThat(exception, instanceOf(AccessDeniedException.class));
assertThat(exception, throwableWithMessage(fileName));
}
private void checkBlockedResource(
String sslManagerType,
String fileType,
String configKey,
BiConsumer<String, Settings.Builder> configure
) throws Exception {
final String prefix = randomSslPrefix();
final Settings.Builder settings = Settings.builder();
configure.accept(prefix, settings);
final String fileName = blockedFile();
final String key = prefix + "." + configKey;
settings.put(key, fileName);
final String fileErrorMessage = "cannot read configured "
+ fileType
+ " ["
+ fileName
+ "] because access to read the file is blocked; SSL resources should be placed in the ["
+ env.configDir().toAbsolutePath().toString()
+ "] directory";
Throwable exception = expectFailure(settings);
assertThat(exception, throwableWithMessage("failed to load SSL configuration [" + prefix + "] - " + fileErrorMessage));
assertThat(exception, instanceOf(ElasticsearchSecurityException.class));
exception = exception.getCause();
assertThat(exception, throwableWithMessage(fileErrorMessage));
assertThat(exception, instanceOf(SslConfigException.class));
exception = exception.getCause();
assertThat(exception, instanceOf(AccessControlException.class));
assertThat(exception, throwableWithMessage(containsString(fileName)));
}
private void checkUnusedConfiguration(String prefix, String settingsConfigured, BiConsumer<String, Settings.Builder> configure) {
final Settings.Builder settings = Settings.builder();
configure.accept(prefix, settings);
Throwable exception = expectFailure(settings);
assertThat(
exception,
throwableWithMessage(
"invalid configuration for "
+ prefix
+ " - ["
+ prefix
+ ".enabled] is not set,"
+ " but the following settings have been configured in elasticsearch.yml : ["
+ settingsConfigured
+ "]"
)
);
assertThat(exception, instanceOf(ElasticsearchException.class));
}
private String missingFile() {
return resource("cert1a.p12").replace("cert1a.p12", "file.dne");
}
private String unreadableFile(String fromResource) throws IOException {
assumeFalse("This behaviour uses POSIX file permissions", Constants.WINDOWS);
final Path fromPath = this.paths.get(fromResource);
if (fromPath == null) {
throw new IllegalArgumentException("Test SSL resource " + fromResource + " has not been loaded");
}
final String extension = FilenameUtils.getExtension(fromResource);
return copy(fromPath, createTempFile(fromResource, "-no-read." + extension), PosixFilePermissions.fromString("---------"));
}
private String blockedFile() throws IOException {
return PathUtils.get("/this", "path", "is", "outside", "the", "config", "directory", "file.error").toAbsolutePath().toString();
}
/**
* This more-or-less replicates the functionality of {@link Files#copy(Path, Path, CopyOption...)} but doing it this way allows us to
* set the file permissions when creating the file (which helps with security manager issues)
*/
private String copy(Path fromPath, Path toPath, Set<PosixFilePermission> permissions) throws IOException {
Files.deleteIfExists(toPath);
final FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
final EnumSet<StandardOpenOption> options = EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
try (
SeekableByteChannel channel = Files.newByteChannel(toPath, options, fileAttributes);
OutputStream out = Channels.newOutputStream(channel)
) {
Files.copy(fromPath, out);
}
return toPath.toString();
}
private Settings.Builder withKey(String fileName) {
assertThat(fileName, endsWith(".key"));
return Settings.builder().put("key", resource(fileName));
}
private Settings.Builder withCertificate(String fileName) {
assertThat(fileName, endsWith(".crt"));
return Settings.builder().put("certificate", resource(fileName));
}
private Settings.Builder configureWorkingTruststore(String prefix, Settings.Builder settings) {
settings.put(prefix + ".truststore.path", resource("cert1a.p12"));
addSecureSettings(settings, secure -> secure.setString(prefix + ".truststore.secure_password", "cert1a-p12-password"));
return settings;
}
private Settings.Builder configureWorkingTrustedAuthorities(String prefix, Settings.Builder settings) {
settings.putList(prefix + ".certificate_authorities", resource("ca1.crt"));
return settings;
}
private Settings.Builder configureWorkingKeystore(String prefix, Settings.Builder settings) {
settings.put(prefix + ".keystore.path", resource("cert1a.p12"));
addSecureSettings(settings, secure -> secure.setString(prefix + ".keystore.secure_password", "cert1a-p12-password"));
return settings;
}
private ElasticsearchException expectFailure(Settings.Builder settings) {
return expectThrows(
ElasticsearchException.class,
() -> new SSLService(new Environment(buildEnvSettings(settings.build()), env.configDir()))
);
}
private SSLService expectSuccess(Settings.Builder settings) {
return new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings.build())));
}
private String resource(String fileName) {
final Path path = this.paths.get(fileName);
if (path == null) {
throw new IllegalArgumentException("Test SSL resource " + fileName + " has not been loaded");
}
return path.toString();
}
private void requirePath(String fileName) throws FileNotFoundException {
final Path path = getDataPath("/org/elasticsearch/xpack/ssl/SSLErrorMessageTests/" + fileName);
if (Files.exists(path)) {
paths.put(fileName, path);
} else {
throw new FileNotFoundException("File " + path + " does not exist");
}
}
private String randomSslPrefix() {
return randomFrom(
"xpack.security.transport.ssl",
"xpack.security.http.ssl",
"xpack.http.ssl",
"xpack.security.authc.realms.ldap.ldap1.ssl",
"xpack.security.authc.realms.saml.saml1.ssl",
"xpack.monitoring.exporters.http.ssl"
);
}
}
| SSLErrorMessageFileTests |
java | quarkusio__quarkus | extensions/oidc-client-filter/deployment/src/test/java/io/quarkus/oidc/client/filter/AbstractRevokedAccessTokenDevModeTest.java | {
"start": 563,
"end": 6961
} | class ____ {
protected static final String NAMED_CLIENT = "named";
protected static final String RESPONSE = "Ho hey!";
protected static final String MY_CLIENT_RESOURCE_PATH = "/my-client-resource";
protected static final String MY_SERVER_RESOURCE_PATH = "/my-server-resource";
private static final Class<?>[] BASE_TEST_CLASSES = {
MyServerResource.class, MyClientResource.class, MyClient.class, MyClientCategory.class,
AbstractRevokedAccessTokenDevModeTest.class
};
protected static QuarkusDevModeTest createQuarkusDevModeTest(String additionalProperties,
Class<? extends MyClient> defaultClientClass,
Class<? extends MyClient> namedClientClass, Class<? extends MyClient> namedClientWithoutRefresh,
Class<? extends MyClient> defaultClientWithoutRefresh, Class<? extends MyClientResource> myClientResourceImpl,
Class<?>... additionalClasses) {
return new QuarkusDevModeTest().withApplicationRoot((jar) -> jar
.addAsResource(
new StringAsset("""
%s/mp-rest/url=http://localhost:${quarkus.http.port}
%s/mp-rest/url=http://localhost:${quarkus.http.port}
%s/mp-rest/url=http://localhost:${quarkus.http.port}
%s/mp-rest/url=http://localhost:${quarkus.http.port}
quarkus.oidc.auth-server-url=${keycloak.url}/realms/quarkus/
quarkus.oidc.client-id=quarkus-service-app
quarkus.oidc.credentials.secret=secret
quarkus.oidc.token.verify-access-token-with-user-info=true
quarkus.oidc-client.auth-server-url=${quarkus.oidc.auth-server-url}
quarkus.oidc-client.client-id=${quarkus.oidc.client-id}
quarkus.oidc-client.credentials.client-secret.value=${quarkus.oidc.credentials.secret}
quarkus.oidc-client.credentials.client-secret.method=POST
quarkus.oidc-client.grant.type=password
quarkus.oidc-client.grant-options.password.username=alice
quarkus.oidc-client.grant-options.password.password=alice
quarkus.oidc-client.scopes=openid
quarkus.oidc-client.named.scopes=openid
quarkus.oidc-client.named.auth-server-url=${quarkus.oidc.auth-server-url}
quarkus.oidc-client.named.client-id=${quarkus.oidc.client-id}
quarkus.oidc-client.named.credentials.client-secret.value=${quarkus.oidc.credentials.secret}
quarkus.oidc-client.named.credentials.client-secret.method=POST
quarkus.oidc-client.named.grant.type=password
quarkus.oidc-client.named.grant-options.password.username=alice
quarkus.oidc-client.named.grant-options.password.password=alice
%s
""".formatted(defaultClientClass.getName(), namedClientClass.getName(),
namedClientWithoutRefresh.getName(), defaultClientWithoutRefresh.getName(),
additionalProperties)),
"application.properties")
.addClasses(defaultClientClass, namedClientClass, namedClientWithoutRefresh, defaultClientWithoutRefresh,
myClientResourceImpl)
.addClasses(additionalClasses)
.addClasses(BASE_TEST_CLASSES));
}
void verifyTokenRefreshedOn401(MyClientCategory myClientCategory) {
RestAssured.given()
.body(myClientCategory)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(200)
.body(Matchers.is(RESPONSE));
// access token is revoked now
RestAssured.given()
.body(myClientCategory)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(401);
// response filter recognized 401 and told the request token to refresh the token on next request
RestAssured.given()
.body(myClientCategory)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(200)
.body(Matchers.is(RESPONSE));
}
@Test
void verifyDefaultClientHasNotRefreshedTokenOnUnauthorized() {
RestAssured.given()
.body(MyClientCategory.DEFAULT_CLIENT_WITHOUT_REFRESH)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(200)
.body(Matchers.is(RESPONSE));
// access token is revoked now
RestAssured.given()
.body(MyClientCategory.DEFAULT_CLIENT_WITHOUT_REFRESH)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(401);
// there is no response filter, so our request filter still doesn't know that the token is revoked
RestAssured.given()
.body(MyClientCategory.DEFAULT_CLIENT_WITHOUT_REFRESH)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(401);
}
@Test
void verifyNamedClientHasNotRefreshedTokenOnUnauthorized() {
RestAssured.given()
.body(MyClientCategory.NAMED_CLIENT_WITHOUT_REFRESH)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(200)
.body(Matchers.is(RESPONSE));
// access token is revoked now
RestAssured.given()
.body(MyClientCategory.NAMED_CLIENT_WITHOUT_REFRESH)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(401);
// there is no response filter, so our request filter still doesn't know that the token is revoked
RestAssured.given()
.body(MyClientCategory.NAMED_CLIENT_WITHOUT_REFRESH)
.post(MY_CLIENT_RESOURCE_PATH)
.then().statusCode(401);
}
@Path(MY_SERVER_RESOURCE_PATH)
public static | AbstractRevokedAccessTokenDevModeTest |
java | google__guava | android/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java | {
"start": 1067,
"end": 1664
} | class ____ {
// Represents the max nanoseconds representable on a linux timespec with a 32 bit tv_sec
static final long MAX_NANOSECONDS_THRESHOLD = (1L + Integer.MAX_VALUE) * 1_000_000_000L - 1L;
private OverflowAvoidingLockSupport() {}
static void parkNanos(@Nullable Object blocker, long nanos) {
// Even in the extremely unlikely event that a thread unblocks itself early after only 68 years,
// this is indistinguishable from a spurious wakeup, which LockSupport allows.
LockSupport.parkNanos(blocker, min(nanos, MAX_NANOSECONDS_THRESHOLD));
}
}
| OverflowAvoidingLockSupport |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/aot/samples/basic/DisabledInAotRuntimeClassLevelTests.java | {
"start": 1676,
"end": 1796
} | class ____ be properly processed
* for AOT optimizations, but we want to ensure that we can also disable such a
* test | can |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java | {
"start": 22965,
"end": 23392
} | class ____ {
void f(ParameterizedType t) {
// BUG: Diagnostic contains: getRawType
t.getClass();
}
}
""")
.doTest();
}
@Test
public void positive_classInfoGetClass() {
testHelper
.addSourceLines(
"Test.java",
"""
import com.google.common.reflect.ClassPath.ClassInfo;
| Test |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TestTaskAttempt.java | {
"start": 6198,
"end": 6401
} | class ____ extends RawLocalFileSystem {
@Override
public FileStatus getFileStatus(Path f) throws IOException {
return new FileStatus(1, false, 1, 1, 1, f);
}
}
private static | StubbedFS |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/OrderByTwoEntityOneAuditedTest.java | {
"start": 1907,
"end": 2563
} | class ____ {
@Id
@GeneratedValue
private Integer id;
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
@ManyToMany(mappedBy = "parents", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@OrderBy("index1, index2 desc")
@Fetch(FetchMode.SELECT)
@BatchSize(size = 100)
private List<Child> children = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
@Entity(name = "Child")
@Audited
public static | Parent |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/test/java/org/apache/hadoop/yarn/server/federation/policies/router/TestLoadBasedRouterPolicy.java | {
"start": 2356,
"end": 2473
} | class ____ the {@link LoadBasedRouterPolicy}. Test that the load
* is properly considered for allocation.
*/
public | for |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassTest.java | {
"start": 649,
"end": 1410
} | class ____ {
@BeforeEach
public void init(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
SystemUser systemUser = new SystemUser();
systemUser.setId(
new PK(
"Hibernate Forum",
"vlad"
)
);
systemUser.setName("Vlad Mihalcea");
entityManager.persist(systemUser);
});
}
@Test
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
SystemUser systemUser = entityManager.find(
SystemUser.class,
new PK(
"Hibernate Forum",
"vlad"
)
);
assertEquals("Vlad Mihalcea", systemUser.getName());
});
}
//tag::identifiers-basic-idclass-mapping-example[]
@Entity(name = "SystemUser")
@IdClass(PK.class)
public static | IdClassTest |
java | spring-projects__spring-boot | module/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java | {
"start": 1250,
"end": 2555
} | class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class));
@Test
@SuppressWarnings("unchecked")
void runShouldHaveEndpointBeanThatIsNotDisposable() {
this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true")
.withPropertyValues("management.endpoints.web.exposure.include=shutdown")
.run((context) -> {
assertThat(context).hasSingleBean(ShutdownEndpoint.class);
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
Map<String, Object> disposableBeans = (Map<String, Object>) ReflectionTestUtils.getField(beanFactory,
"disposableBeans");
assertThat(disposableBeans).isEmpty();
});
}
@Test
void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true")
.run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class));
}
@Test
void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class));
}
}
| ShutdownEndpointAutoConfigurationTests |
java | google__guava | android/guava/src/com/google/common/cache/LocalCache.java | {
"start": 136411,
"end": 137379
} | class ____ extends AbstractCacheSet<Entry<K, V>> {
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
if (key == null) {
return false;
}
V v = LocalCache.this.get(key);
return v != null && valueEquivalence.equivalent(e.getValue(), v);
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
return key != null && LocalCache.this.remove(key, e.getValue());
}
}
// Serialization Support
/**
* Serializes the configuration of a LocalCache, reconstituting it as a Cache using CacheBuilder
* upon deserialization. An instance of this | EntrySet |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/StateTransitionManager.java | {
"start": 1588,
"end": 1715
} | interface ____ can be used by the {@code StateTransitionManager} to communicate with the
* underlying system.
*/
| that |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SubscriptionMethodReturnValueHandlerTests.java | {
"start": 9025,
"end": 9740
} | class ____ {
@JsonView(MyJacksonView1.class)
private String withView1;
@JsonView(MyJacksonView2.class)
private String withView2;
private String withoutView;
@SuppressWarnings("unused")
public String getWithView1() {
return withView1;
}
public void setWithView1(String withView1) {
this.withView1 = withView1;
}
@SuppressWarnings("unused")
public String getWithView2() {
return withView2;
}
public void setWithView2(String withView2) {
this.withView2 = withView2;
}
@SuppressWarnings("unused")
public String getWithoutView() {
return withoutView;
}
public void setWithoutView(String withoutView) {
this.withoutView = withoutView;
}
}
}
| JacksonViewBean |
java | google__auto | value/src/it/gwtserializer/src/test/java/com/google/auto/value/client/GwtSerializerTest.java | {
"start": 1101,
"end": 1194
} | class ____ extends GWTTestCase {
@RemoteServiceRelativePath("test")
public | GwtSerializerTest |
java | elastic__elasticsearch | modules/analysis-common/src/test/java/org/elasticsearch/analysis/common/PatternCaptureTokenFilterTests.java | {
"start": 1128,
"end": 2982
} | class ____ extends ESTokenStreamTestCase {
public void testPatternCaptureTokenFilter() throws Exception {
String json = "/org/elasticsearch/analysis/common/pattern_capture.json";
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.loadFromStream(json, getClass().getResourceAsStream(json), false)
.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current())
.build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings);
IndexAnalyzers indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisPlugin()).indexAnalyzers;
NamedAnalyzer analyzer1 = indexAnalyzers.get("single");
assertTokenStreamContents(analyzer1.tokenStream("test", "foobarbaz"), new String[] { "foobarbaz", "foobar", "foo" });
NamedAnalyzer analyzer2 = indexAnalyzers.get("multi");
assertTokenStreamContents(analyzer2.tokenStream("test", "abc123def"), new String[] { "abc123def", "abc", "123", "def" });
NamedAnalyzer analyzer3 = indexAnalyzers.get("preserve");
assertTokenStreamContents(analyzer3.tokenStream("test", "foobarbaz"), new String[] { "foobar", "foo" });
}
public void testNoPatterns() {
try {
new PatternCaptureGroupTokenFilterFactory(
IndexSettingsModule.newIndexSettings("test", Settings.EMPTY),
null,
"pattern_capture",
Settings.builder().put("pattern", "foobar").build()
);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("required setting 'patterns' is missing"));
}
}
}
| PatternCaptureTokenFilterTests |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/FormatFactory.java | {
"start": 1250,
"end": 2336
} | interface ____ extends Factory {
/**
* Returns a set of {@link ConfigOption} that are directly forwarded to the runtime
* implementation but don't affect the final execution topology.
*
* <p>Options declared here can override options of the persisted plan during an enrichment
* phase. Since a restored topology is static, an implementer has to ensure that the declared
* options don't affect fundamental abilities such as {@link ChangelogMode}.
*
* <p>For example, given a JSON format, if an option defines how to parse timestamps, changing
* the parsing behavior does not affect the pipeline topology and can be allowed. However, an
* option that defines whether the format results in a {@link ProjectableDecodingFormat} or not
* is not allowed. The wrapping connector and planner might not react to the changed abilities
* anymore.
*
* @see DynamicTableFactory.Context#getEnrichmentOptions()
*/
default Set<ConfigOption<?>> forwardOptions() {
return Collections.emptySet();
}
}
| FormatFactory |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/archive/ArchiveFeatureSetUsage.java | {
"start": 762,
"end": 2361
} | class ____ extends XPackFeatureUsage {
private final int numberOfArchiveIndices;
public ArchiveFeatureSetUsage(StreamInput input) throws IOException {
super(input);
numberOfArchiveIndices = input.readVInt();
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_3_0;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(numberOfArchiveIndices);
}
public ArchiveFeatureSetUsage(boolean available, int numberOfArchiveIndices) {
super(XPackField.ARCHIVE, available, true);
this.numberOfArchiveIndices = numberOfArchiveIndices;
}
public int getNumberOfArchiveIndices() {
return numberOfArchiveIndices;
}
@Override
protected void innerXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
super.innerXContent(builder, params);
builder.field("indices_count", numberOfArchiveIndices);
}
@Override
public int hashCode() {
return Objects.hash(available, enabled, numberOfArchiveIndices);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ArchiveFeatureSetUsage other = (ArchiveFeatureSetUsage) obj;
return available == other.available && enabled == other.enabled && numberOfArchiveIndices == other.numberOfArchiveIndices;
}
}
| ArchiveFeatureSetUsage |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests.java | {
"start": 2375,
"end": 7303
} | class ____ {
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
private ObjectPostProcessor<Object> objectObjectPostProcessor;
@Test
public void postProcessWhenApplicationContextAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ApplicationContextAware toPostProcess = mock(ApplicationContextAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setApplicationContext(isNotNull());
}
@Test
public void postProcessWhenApplicationEventPublisherAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ApplicationEventPublisherAware toPostProcess = mock(ApplicationEventPublisherAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setApplicationEventPublisher(isNotNull());
}
@Test
public void postProcessWhenBeanClassLoaderAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
BeanClassLoaderAware toPostProcess = mock(BeanClassLoaderAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setBeanClassLoader(isNotNull());
}
@Test
public void postProcessWhenBeanFactoryAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
BeanFactoryAware toPostProcess = mock(BeanFactoryAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setBeanFactory(isNotNull());
}
@Test
public void postProcessWhenEnvironmentAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
EnvironmentAware toPostProcess = mock(EnvironmentAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setEnvironment(isNotNull());
}
@Test
public void postProcessWhenMessageSourceAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
MessageSourceAware toPostProcess = mock(MessageSourceAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setMessageSource(isNotNull());
}
@Test
public void postProcessWhenServletContextAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ServletContextAware toPostProcess = mock(ServletContextAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setServletContext(isNotNull());
}
@Test
public void postProcessWhenDisposableBeanThenAwareInvoked() throws Exception {
this.spring.register(Config.class).autowire();
DisposableBean toPostProcess = mock(DisposableBean.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
this.spring.getContext().close();
verify(toPostProcess).destroy();
}
@Test
public void postProcessWhenSmartInitializingSingletonThenAwareInvoked() {
this.spring.register(Config.class, SmartConfig.class).autowire();
SmartConfig config = this.spring.getContext().getBean(SmartConfig.class);
verify(config.toTest).afterSingletonsInstantiated();
}
@Test
// SEC-2382
public void autowireBeanFactoryWhenBeanNameAutoProxyCreatorThenWorks() {
this.spring.testConfigLocations("AutowireBeanFactoryObjectPostProcessorTests-aopconfig.xml").autowire();
MyAdvisedBean bean = this.spring.getContext().getBean(MyAdvisedBean.class);
assertThat(bean.doStuff()).isEqualTo("null");
}
@Test
void postProcessWhenObjectIsCgLibProxyAndInNativeImageThenUseExistingBean() {
try (MockedStatic<NativeDetector> detector = Mockito.mockStatic(NativeDetector.class)) {
given(NativeDetector.inNativeImage()).willReturn(true);
ProxyFactory proxyFactory = new ProxyFactory(new MyClass());
proxyFactory.setProxyTargetClass(!Modifier.isFinal(MyClass.class.getModifiers()));
MyClass myClass = (MyClass) proxyFactory.getProxy();
this.spring.register(Config.class, myClass.getClass()).autowire();
this.spring.getContext().getBean(myClass.getClass()).setIdentifier("0000");
MyClass postProcessed = this.objectObjectPostProcessor.postProcess(myClass);
assertThat(postProcessed.getIdentifier()).isEqualTo("0000");
}
}
@Test
void postProcessWhenObjectIsCgLibProxyAndInNativeImageAndBeanDoesNotExistsThenIllegalStateException() {
try (MockedStatic<NativeDetector> detector = Mockito.mockStatic(NativeDetector.class)) {
given(NativeDetector.inNativeImage()).willReturn(true);
ProxyFactory proxyFactory = new ProxyFactory(new MyClass());
proxyFactory.setProxyTargetClass(!Modifier.isFinal(MyClass.class.getModifiers()));
MyClass myClass = (MyClass) proxyFactory.getProxy();
this.spring.register(Config.class).autowire();
assertThatException().isThrownBy(() -> this.objectObjectPostProcessor.postProcess(myClass))
.havingRootCause()
.isInstanceOf(IllegalStateException.class)
.withMessage(
"""
Failed to resolve an unique bean (single or primary) of type [ | AutowireBeanFactoryObjectPostProcessorTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/OneToManyAbstractTablePerClassTest.java | {
"start": 1490,
"end": 3460
} | class ____ {
@Test
public void testAddAndRemove(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final TablePerClassSub1 o1 = session.find( TablePerClassSub1.class, 1 );
assertNotNull( o1 );
assertEquals( 1, o1.childrenSet.size() );
assertEquals( 1, o1.childrenList.size() );
assertEquals( 1, o1.childrenMap.size() );
TablePerClassBase o2 = o1.childrenSet.iterator().next();
assertEquals( 2, o2.id );
assertEquals( 2, o1.childrenList.get( 0 ).id );
assertEquals( 2, o1.childrenMap.get( 2 ).id );
o1.childrenSet.remove( o2 );
o1.childrenList.remove( 0 );
o1.childrenMap.remove( 2 );
o2.parent = null;
TablePerClassSub1 o3 = new TablePerClassSub1( 3 );
o3.parent = o1;
session.persist( o3 );
o1.childrenSet.add( o3 );
o1.childrenList.add( o3 );
o1.childrenMap.put( 3, o3 );
session.flush();
} );
scope.inTransaction( session -> {
final TablePerClassSub1 o1 = session.find( TablePerClassSub1.class, 1 );
assertNotNull( o1 );
assertEquals( 1, o1.childrenSet.size() );
assertEquals( 1, o1.childrenList.size() );
assertEquals( 1, o1.childrenMap.size() );
TablePerClassBase o2 = o1.childrenSet.iterator().next();
assertEquals( 3, o2.id );
assertEquals( 3, o1.childrenList.get( 0 ).id );
assertEquals( 3, o1.childrenMap.get( 3 ).id );
});
}
@BeforeEach
public void setupData(SessionFactoryScope scope) {
scope.inTransaction( session -> {
TablePerClassSub1 o1 = new TablePerClassSub1( 1 );
TablePerClassSub2 o2 = new TablePerClassSub2( 2 );
o1.childrenSet.add( o2 );
o1.childrenList.add( o2 );
session.persist( o2 );
session.persist( o1 );
o1.childrenMap.put( 2, o2 );
o2.parent = o1;
} );
}
@AfterEach
public void cleanupData(SessionFactoryScope scope) {
scope.dropData();
}
@Entity(name = "TablePerClassBase")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public static abstract | OneToManyAbstractTablePerClassTest |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/TimeSeriesIdFieldMapperTests.java | {
"start": 1790,
"end": 38532
} | class ____ extends MetadataMapperTestCase {
@Override
protected String fieldName() {
return TimeSeriesIdFieldMapper.NAME;
}
@Override
protected boolean isConfigurable() {
return false;
}
@Override
protected void registerParameters(ParameterChecker checker) throws IOException {
// There aren't any parameters
}
@Override
protected IndexVersion getVersion() {
return IndexVersionUtils.randomVersionBetween(
random(),
IndexVersions.V_8_8_0,
IndexVersionUtils.getPreviousVersion(IndexVersions.TIME_SERIES_ID_HASHING)
);
}
private DocumentMapper createDocumentMapper(String routingPath, XContentBuilder mappings) throws IOException {
return createDocumentMapper(getVersion(), routingPath, mappings);
}
private DocumentMapper createDocumentMapper(IndexVersion version, String routingPath, XContentBuilder mappings) throws IOException {
return createMapperService(
version,
getIndexSettingsBuilder().put(IndexSettings.MODE.getKey(), IndexMode.TIME_SERIES.name())
.put(MapperService.INDEX_MAPPING_DIMENSION_FIELDS_LIMIT_SETTING.getKey(), 200) // Allow tests that use many dimensions
.put(IndexMetadata.INDEX_ROUTING_PATH.getKey(), routingPath)
.put(IndexSettings.TIME_SERIES_START_TIME.getKey(), "2021-04-28T00:00:00Z")
.put(IndexSettings.TIME_SERIES_END_TIME.getKey(), "2021-10-29T00:00:00Z")
.build(),
() -> true,
mappings
).documentMapper();
}
private static ParsedDocument parseDocument(DocumentMapper docMapper, CheckedConsumer<XContentBuilder, IOException> f)
throws IOException {
// Add the @timestamp field required by DataStreamTimestampFieldMapper for all time series indices
return docMapper.parse(source(null, b -> {
f.accept(b);
b.field("@timestamp", "2021-10-01");
}, null));
}
private static BytesRef parseAndGetTsid(DocumentMapper docMapper, CheckedConsumer<XContentBuilder, IOException> f) throws IOException {
return parseDocument(docMapper, f).rootDoc().getBinaryValue(TimeSeriesIdFieldMapper.NAME);
}
@SuppressWarnings("unchecked")
public void testEnabledInTimeSeriesMode() throws Exception {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "long").field("time_series_dimension", true).endObject();
}));
ParsedDocument doc = parseDocument(docMapper, b -> b.field("a", "value").field("b", 100).field("c", 500));
assertThat(
doc.rootDoc().getBinaryValue("_tsid"),
equalTo(new BytesRef("\u0002\u0001as\u0005value\u0001bl\u0000\u0000\u0000\u0000\u0000\u0000\u0000d"))
);
assertThat(doc.rootDoc().getField("a").binaryValue(), equalTo(new BytesRef("value")));
assertThat(doc.rootDoc().getField("b").numericValue(), equalTo(100L));
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new ByteArrayStreamInput(doc.rootDoc().getBinaryValue("_tsid").bytes)), "AWE");
}
public void testDisabledInStandardMode() throws Exception {
DocumentMapper docMapper = createMapperService(
getIndexSettingsBuilder().put(IndexSettings.MODE.getKey(), IndexMode.STANDARD.name()).build(),
mapping(b -> {})
).documentMapper();
assertThat(docMapper.metadataMapper(TimeSeriesIdFieldMapper.class), is(nullValue()));
ParsedDocument doc = docMapper.parse(source("id", b -> b.field("field", "value"), null));
assertThat(doc.rootDoc().getBinaryValue("_tsid"), is(nullValue()));
assertThat(doc.rootDoc().get("field"), equalTo("value"));
}
public void testIncludeInDocumentNotAllowed() throws Exception {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("_tsid", "foo")));
assertThat(e.getCause().getMessage(), containsString("Field [_tsid] is a metadata field and cannot be added inside a document"));
}
/**
* Test with non-randomized string for sanity checking.
*/
@SuppressWarnings("unchecked")
public void testStrings() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("o")
.startObject("properties")
.startObject("e")
.field("type", "keyword")
.field("time_series_dimension", true)
.endObject()
.endObject()
.endObject();
}));
BytesRef tsid = parseAndGetTsid(
docMapper,
b -> b.field("a", "foo").field("b", "bar").field("c", "baz").startObject("o").field("e", "bort").endObject()
);
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new BytesArray(tsid).streamInput()), "AWE");
}
@SuppressWarnings("unchecked")
public void testUnicodeKeys() throws IOException {
String fire = new String(new int[] { 0x1F525 }, 0, 1);
String coffee = "\u2615";
DocumentMapper docMapper = createDocumentMapper(fire + "," + coffee, mapping(b -> {
b.startObject(fire).field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject(coffee).field("type", "keyword").field("time_series_dimension", true).endObject();
}));
ParsedDocument doc = parseDocument(docMapper, b -> b.field(fire, "hot").field(coffee, "good"));
Object tsid = TimeSeriesIdFieldMapper.encodeTsid(new ByteArrayStreamInput(doc.rootDoc().getBinaryValue("_tsid").bytes));
assertEquals(tsid, "A-I");
}
@SuppressWarnings("unchecked")
public void testKeywordTooLong() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
ParsedDocument doc = parseDocument(docMapper, b -> b.field("a", "more_than_1024_bytes".repeat(52)));
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new ByteArrayStreamInput(doc.rootDoc().getBinaryValue("_tsid").bytes)), "AQ");
}
@SuppressWarnings("unchecked")
public void testKeywordTooLongUtf8() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
String theWordLong = "長い";
ParsedDocument doc = parseDocument(docMapper, b -> b.field("a", theWordLong.repeat(200)));
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new ByteArrayStreamInput(doc.rootDoc().getBinaryValue("_tsid").bytes)), "AQ");
}
public void testKeywordNull() throws IOException {
DocumentMapper docMapper = createDocumentMapper("r", mapping(b -> {
b.startObject("r").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
BytesRef withNull = parseAndGetTsid(docMapper, b -> b.field("r", "foo").field("a", (String) null));
BytesRef withoutField = parseAndGetTsid(docMapper, b -> b.field("r", "foo"));
assertThat(withNull, equalTo(withoutField));
}
/**
* Test with non-randomized longs for sanity checking.
*/
@SuppressWarnings("unchecked")
public void testLong() throws IOException {
DocumentMapper docMapper = createDocumentMapper("kw", mapping(b -> {
b.startObject("kw").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("a").field("type", "long").field("time_series_dimension", true).endObject();
b.startObject("o")
.startObject("properties")
.startObject("e")
.field("type", "long")
.field("time_series_dimension", true)
.endObject()
.endObject()
.endObject();
}));
BytesRef tsid = parseAndGetTsid(docMapper, b -> {
b.field("kw", "kw");
b.field("a", 1L);
b.field("b", -1);
b.field("c", "baz");
b.startObject("o").field("e", 1234).endObject();
});
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new BytesArray(tsid).streamInput()), "AWFs");
}
public void testLongInvalidString() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "long").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", "not_a_long")));
assertThat(
e.getMessage(),
// TODO describe the document instead of "null"
equalTo("[1:6] failed to parse field [a] of type [long] in a time series document. Preview of field's value: 'not_a_long'")
);
}
public void testLongNull() throws IOException {
DocumentMapper docMapper = createDocumentMapper("r", mapping(b -> {
b.startObject("r").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("a").field("type", "long").field("time_series_dimension", true).endObject();
}));
BytesRef withNull = parseAndGetTsid(docMapper, b -> b.field("r", "foo").field("a", (Long) null));
BytesRef withoutField = parseAndGetTsid(docMapper, b -> b.field("r", "foo"));
assertThat(withNull, equalTo(withoutField));
}
/**
* Test with non-randomized integers for sanity checking.
*/
@SuppressWarnings("unchecked")
public void testInteger() throws IOException {
DocumentMapper docMapper = createDocumentMapper("kw", mapping(b -> {
b.startObject("kw").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("a").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("o")
.startObject("properties")
.startObject("e")
.field("type", "integer")
.field("time_series_dimension", true)
.endObject()
.endObject()
.endObject();
}));
BytesRef tsid = parseAndGetTsid(docMapper, b -> {
b.field("kw", "kw");
b.field("a", 1L);
b.field("b", -1);
b.field("c", "baz");
b.startObject("o").field("e", Integer.MIN_VALUE).endObject();
});
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new BytesArray(tsid).streamInput()), "AWFs");
}
public void testIntegerInvalidString() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", "not_an_int")));
assertThat(
e.getMessage(),
equalTo("[1:6] failed to parse field [a] of type [integer] in a time series document. Preview of field's value: 'not_an_int'")
);
}
public void testIntegerOutOfRange() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", Long.MAX_VALUE)));
assertThat(
e.getMessage(),
equalTo(
"[1:6] failed to parse field [a] of type [integer] in a time series document. Preview of field's value: '"
+ Long.MAX_VALUE
+ "'"
)
);
}
/**
* Test with non-randomized shorts for sanity checking.
*/
@SuppressWarnings("unchecked")
public void testShort() throws IOException {
DocumentMapper docMapper = createDocumentMapper("kw", mapping(b -> {
b.startObject("kw").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("a").field("type", "short").field("time_series_dimension", true).endObject();
b.startObject("o")
.startObject("properties")
.startObject("e")
.field("type", "short")
.field("time_series_dimension", true)
.endObject()
.endObject()
.endObject();
}));
BytesRef tsid = parseAndGetTsid(docMapper, b -> {
b.field("kw", "kw");
b.field("a", 1L);
b.field("b", -1);
b.field("c", "baz");
b.startObject("o").field("e", Short.MIN_VALUE).endObject();
});
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new BytesArray(tsid).streamInput()), "AWFs");
}
public void testShortInvalidString() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "short").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", "not_a_short")));
assertThat(
e.getMessage(),
equalTo("[1:6] failed to parse field [a] of type [short] in a time series document. Preview of field's value: 'not_a_short'")
);
}
public void testShortOutOfRange() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "short").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", Long.MAX_VALUE)));
assertThat(
e.getMessage(),
equalTo(
"[1:6] failed to parse field [a] of type [short] in a time series document. Preview of field's value: '"
+ Long.MAX_VALUE
+ "'"
)
);
}
/**
* Test with non-randomized shorts for sanity checking.
*/
@SuppressWarnings("unchecked")
public void testByte() throws IOException {
DocumentMapper docMapper = createDocumentMapper("kw", mapping(b -> {
b.startObject("kw").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("a").field("type", "byte").field("time_series_dimension", true).endObject();
b.startObject("o")
.startObject("properties")
.startObject("e")
.field("type", "byte")
.field("time_series_dimension", true)
.endObject()
.endObject()
.endObject();
}));
BytesRef tsid = parseAndGetTsid(docMapper, b -> {
b.field("kw", "kw");
b.field("a", 1L);
b.field("b", -1);
b.field("c", "baz");
b.startObject("o").field("e", (int) Byte.MIN_VALUE).endObject();
});
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new BytesArray(tsid).streamInput()), "AWFs");
}
public void testByteInvalidString() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "byte").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", "not_a_byte")));
assertThat(
e.getMessage(),
equalTo("[1:6] failed to parse field [a] of type [byte] in a time series document. Preview of field's value: 'not_a_byte'")
);
}
public void testByteOutOfRange() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "byte").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", Long.MAX_VALUE)));
assertThat(
e.getMessage(),
equalTo(
"[1:6] failed to parse field [a] of type [byte] in a time series document. Preview of field's value: '"
+ Long.MAX_VALUE
+ "'"
)
);
}
/**
* Test with non-randomized ips for sanity checking.
*/
@SuppressWarnings("unchecked")
public void testIp() throws IOException {
DocumentMapper docMapper = createDocumentMapper("kw", mapping(b -> {
b.startObject("kw").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("a").field("type", "ip").field("time_series_dimension", true).endObject();
b.startObject("o")
.startObject("properties")
.startObject("e")
.field("type", "ip")
.field("time_series_dimension", true)
.endObject()
.endObject()
.endObject();
}));
ParsedDocument doc = parseDocument(docMapper, b -> {
b.field("kw", "kw");
b.field("a", "192.168.0.1");
b.field("b", -1);
b.field("c", "baz");
b.startObject("o").field("e", "255.255.255.1").endObject();
});
assertEquals(TimeSeriesIdFieldMapper.encodeTsid(new ByteArrayStreamInput(doc.rootDoc().getBinaryValue("_tsid").bytes)), "AWFz");
}
public void testIpInvalidString() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("a").field("type", "ip").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
}));
Exception e = expectThrows(DocumentParsingException.class, () -> parseDocument(docMapper, b -> b.field("a", "not_an_ip")));
assertThat(
e.getMessage(),
equalTo("[1:6] failed to parse field [a] of type [ip] in a time series document. Preview of field's value: 'not_an_ip'")
);
}
/**
* Tests when the total of the tsid is more than 32k.
*/
@SuppressWarnings("unchecked")
public void testVeryLarge() throws IOException {
DocumentMapper docMapper = createDocumentMapper("b", mapping(b -> {
b.startObject("b").field("type", "keyword").field("time_series_dimension", true).endObject();
for (int i = 0; i < 100; i++) {
b.startObject("d" + i).field("type", "keyword").field("time_series_dimension", true).endObject();
}
}));
String large = "many words ".repeat(80);
ParsedDocument doc = parseDocument(docMapper, b -> {
b.field("b", "foo");
for (int i = 0; i < 100; i++) {
b.field("d" + i, large);
}
});
Object tsid = TimeSeriesIdFieldMapper.encodeTsid(new ByteArrayStreamInput(doc.rootDoc().getBinaryValue("_tsid").bytes));
assertEquals(
tsid,
"AWJzA2ZvbwJkMHPwBm1hbnkgd29yZHMgbWFueSB3b3JkcyBtYW55IHdvcmRzIG1hbnkgd29yZHMgbWFueSB3b3JkcyBtYW55IHdvcmRzIG1hbnkgd"
+ "29yZHMgbWFueSB3b3JkcyA"
);
}
/**
* Sending the same document twice produces the same value.
*/
public void testSameGenConsistentForSameDoc() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("c").field("type", "long").field("time_series_dimension", true).endObject();
}));
String a = randomAlphaOfLength(10);
int b = between(1, 100);
int c = between(0, 2);
CheckedConsumer<XContentBuilder, IOException> fields = d -> d.field("a", a).field("b", b).field("c", (long) c);
ParsedDocument doc1 = parseDocument(docMapper, fields);
ParsedDocument doc2 = parseDocument(docMapper, fields);
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, equalTo(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
/**
* Non-dimension fields don't influence the value of _tsid.
*/
public void testExtraFieldsDoNotMatter() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("c").field("type", "long").field("time_series_dimension", true).endObject();
}));
String a = randomAlphaOfLength(10);
int b = between(1, 100);
int c = between(0, 2);
ParsedDocument doc1 = parseDocument(
docMapper,
d -> d.field("a", a).field("b", b).field("c", (long) c).field("e", between(10, 100))
);
ParsedDocument doc2 = parseDocument(
docMapper,
d -> d.field("a", a).field("b", b).field("c", (long) c).field("e", between(50, 200))
);
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, equalTo(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
/**
* The order that the dimensions appear in the document do not influence the value of _tsid.
*/
public void testOrderDoesNotMatter() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("c").field("type", "long").field("time_series_dimension", true).endObject();
}));
String a = randomAlphaOfLength(10);
int b = between(1, 100);
int c = between(0, 2);
ParsedDocument doc1 = parseDocument(docMapper, d -> d.field("a", a).field("b", b).field("c", (long) c));
ParsedDocument doc2 = parseDocument(docMapper, d -> d.field("b", b).field("a", a).field("c", (long) c));
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, equalTo(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
/**
* Dimensions that appear in the mapping but not in the document don't influence the value of _tsid.
*/
public void testUnusedExtraDimensions() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("c").field("type", "long").field("time_series_dimension", true).endObject();
}));
String a = randomAlphaOfLength(10);
int b = between(1, 100);
CheckedConsumer<XContentBuilder, IOException> fields = d -> d.field("a", a).field("b", b);
ParsedDocument doc1 = parseDocument(docMapper, fields);
ParsedDocument doc2 = parseDocument(docMapper, fields);
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, equalTo(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
/**
* Different values for dimensions change the result.
*/
public void testDifferentValues() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
}));
String a = randomAlphaOfLength(10);
ParsedDocument doc1 = parseDocument(docMapper, d -> d.field("a", a).field("b", between(1, 100)));
ParsedDocument doc2 = parseDocument(docMapper, d -> d.field("a", a + 1).field("b", between(200, 300)));
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, not(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
public void testSameMetricNamesDifferentValues() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("m1").field("type", "double").field("time_series_metric", "gauge").endObject();
b.startObject("m2").field("type", "integer").field("time_series_metric", "counter").endObject();
}));
ParsedDocument doc1 = parseDocument(
docMapper,
d -> d.field("a", "value")
.field("b", 10)
.field("m1", randomDoubleBetween(100, 200, true))
.field("m2", randomIntBetween(100, 200))
);
ParsedDocument doc2 = parseDocument(
docMapper,
d -> d.field("a", "value").field("b", 10).field("m1", randomDoubleBetween(10, 20, true)).field("m2", randomIntBetween(10, 20))
);
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, equalTo(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
public void testDifferentMetricNamesSameValues() throws IOException {
DocumentMapper docMapper1 = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("m1").field("type", "double").field("time_series_metric", "gauge").endObject();
}));
DocumentMapper docMapper2 = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("m2").field("type", "double").field("time_series_metric", "gauge").endObject();
}));
double metricValue = randomDoubleBetween(10, 20, true);
ParsedDocument doc1 = parseDocument(docMapper1, d -> d.field("a", "value").field("b", 10).field("m1", metricValue));
ParsedDocument doc2 = parseDocument(docMapper2, d -> d.field("a", "value").field("b", 10).field("m2", metricValue));
// NOTE: plain tsid (not hashed) does not take metric names/values into account
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, equalTo(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
/**
* Two documents with the same *values* but different dimension keys will generate
* different {@code _tsid}s.
*/
public void testDifferentDimensions() throws IOException {
// First doc mapper has dimension fields a and b
DocumentMapper docMapper1 = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
}));
// Second doc mapper has dimension fields a and c
DocumentMapper docMapper2 = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("c").field("type", "integer").field("time_series_dimension", true).endObject();
}));
String a = randomAlphaOfLength(10);
int b = between(1, 100);
int c = between(5, 500);
CheckedConsumer<XContentBuilder, IOException> fields = d -> d.field("a", a).field("b", b).field("c", c);
ParsedDocument doc1 = parseDocument(docMapper1, fields);
ParsedDocument doc2 = parseDocument(docMapper2, fields);
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, not(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
public void testMultiValueDimensionsNotSupportedBeforeTsidHashing() throws IOException {
IndexVersion priorToTsidHashing = IndexVersionUtils.getPreviousVersion(IndexVersions.TIME_SERIES_ID_HASHING);
DocumentMapper docMapper = createDocumentMapper(
priorToTsidHashing,
"a",
mapping(b -> b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject())
);
String a1 = randomAlphaOfLength(10);
String a2 = randomAlphaOfLength(10);
CheckedConsumer<XContentBuilder, IOException> fields = d -> d.field("a", new String[] { a1, a2 });
DocumentParsingException exception = assertThrows(DocumentParsingException.class, () -> parseDocument(docMapper, fields));
assertThat(exception.getMessage(), containsString("Dimension field [a] cannot be a multi-valued field"));
}
public void testMultiValueDimensions() throws IOException {
DocumentMapper docMapper = createDocumentMapper(
IndexVersions.TIME_SERIES_ID_HASHING,
"a",
mapping(b -> b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject())
);
String a1 = randomAlphaOfLength(10);
String a2 = randomAlphaOfLength(10);
List<ParsedDocument> docs = List.of(
parseDocument(docMapper, d -> d.field("a", new String[] { a1 })),
parseDocument(docMapper, d -> d.field("a", new String[] { a1, a2 })),
parseDocument(docMapper, d -> d.field("a", new String[] { a2, a1 })),
parseDocument(docMapper, d -> d.field("a", new String[] { a1, a2, a1 })),
parseDocument(docMapper, d -> d.field("a", new String[] { a2, a1, a2 }))
);
List<String> tsids = docs.stream()
.map(doc -> doc.rootDoc().getBinaryValue("_tsid").toString())
.distinct()
.collect(Collectors.toList());
assertThat(tsids, hasSize(docs.size()));
}
/**
* Documents with fewer dimensions have a different value.
*/
public void testFewerDimensions() throws IOException {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "integer").field("time_series_dimension", true).endObject();
b.startObject("c").field("type", "integer").field("time_series_dimension", true).endObject();
}));
String a = randomAlphaOfLength(10);
int b = between(1, 100);
int c = between(5, 500);
ParsedDocument doc1 = parseDocument(docMapper, d -> d.field("a", a).field("b", b));
ParsedDocument doc2 = parseDocument(docMapper, d -> d.field("a", a).field("b", b).field("c", c));
assertThat(doc1.rootDoc().getBinaryValue("_tsid").bytes, not(doc2.rootDoc().getBinaryValue("_tsid").bytes));
}
public void testParseWithDynamicMapping() {
Settings indexSettings = Settings.builder()
.put(IndexSettings.MODE.getKey(), "time_series")
.put(IndexMetadata.INDEX_ROUTING_PATH.getKey(), "dim")
.build();
MapperService mapper = createMapperService(IndexVersion.current(), indexSettings, () -> false);
SourceToParse source = new SourceToParse(null, new BytesArray("""
{
"@timestamp": 1609459200000,
"dim": "6a841a21",
"value": 100
}"""), XContentType.JSON, TimeSeriesRoutingHashFieldMapper.DUMMY_ENCODED_VALUE);
Engine.Index index = IndexShard.prepareIndex(
mapper,
source,
UNASSIGNED_SEQ_NO,
randomNonNegativeLong(),
Versions.MATCH_ANY,
VersionType.INTERNAL,
Engine.Operation.Origin.PRIMARY,
-1,
false,
UNASSIGNED_SEQ_NO,
0,
System.nanoTime()
);
assertNotNull(index.parsedDoc().dynamicMappingsUpdate());
}
public void testParseWithDynamicMappingInvalidRoutingHash() {
Settings indexSettings = Settings.builder()
.put(IndexSettings.MODE.getKey(), "time_series")
.put(IndexMetadata.INDEX_ROUTING_PATH.getKey(), "dim")
.build();
MapperService mapper = createMapperService(IndexVersion.current(), indexSettings, () -> false);
SourceToParse source = new SourceToParse(null, new BytesArray("""
{
"@timestamp": 1609459200000,
"dim": "6a841a21",
"value": 100
}"""), XContentType.JSON, "no such routing hash");
var failure = expectThrows(DocumentParsingException.class, () -> {
IndexShard.prepareIndex(
mapper,
source,
UNASSIGNED_SEQ_NO,
randomNonNegativeLong(),
Versions.MATCH_ANY,
VersionType.INTERNAL,
Engine.Operation.Origin.PRIMARY,
-1,
false,
UNASSIGNED_SEQ_NO,
0,
System.nanoTime()
);
});
assertThat(failure.getMessage(), equalTo("[5:1] failed to parse: Illegal base64 character 20"));
}
public void testValueForDisplay() throws Exception {
DocumentMapper docMapper = createDocumentMapper("a", mapping(b -> {
b.startObject("a").field("type", "keyword").field("time_series_dimension", true).endObject();
b.startObject("b").field("type", "long").field("time_series_dimension", true).endObject();
}));
ParsedDocument doc = parseDocument(docMapper, b -> b.field("a", "value").field("b", 100));
BytesRef tsidBytes = doc.rootDoc().getBinaryValue("_tsid");
assertThat(tsidBytes, not(nullValue()));
TimeSeriesIdFieldMapper.TimeSeriesIdFieldType fieldType = TimeSeriesIdFieldMapper.FIELD_TYPE;
Object displayValue = fieldType.valueForDisplay(tsidBytes);
Object encodedValue = TimeSeriesIdFieldMapper.encodeTsid(tsidBytes);
assertThat(displayValue, equalTo(encodedValue));
assertThat(displayValue.getClass(), is(String.class));
assertThat(fieldType.valueForDisplay(null), nullValue());
}
}
| TimeSeriesIdFieldMapperTests |
java | spring-projects__spring-boot | module/spring-boot-jackson2/src/main/java/org/springframework/boot/jackson2/JsonMixinModuleEntriesBeanRegistrationAotProcessor.java | {
"start": 2465,
"end": 4915
} | class ____ extends BeanRegistrationCodeFragmentsDecorator {
private static final Class<?> BEAN_TYPE = JsonMixinModuleEntries.class;
private final RegisteredBean registeredBean;
private final @Nullable ClassLoader classLoader;
AotContribution(BeanRegistrationCodeFragments delegate, RegisteredBean registeredBean) {
super(delegate);
this.registeredBean = registeredBean;
this.classLoader = registeredBean.getBeanFactory().getBeanClassLoader();
}
@Override
public ClassName getTarget(RegisteredBean registeredBean) {
return ClassName.get(BEAN_TYPE);
}
@Override
public CodeBlock generateInstanceSupplierCode(GenerationContext generationContext,
BeanRegistrationCode beanRegistrationCode, boolean allowDirectSupplierShortcut) {
JsonMixinModuleEntries entries = this.registeredBean.getBeanFactory()
.getBean(this.registeredBean.getBeanName(), JsonMixinModuleEntries.class);
contributeHints(generationContext.getRuntimeHints(), entries);
GeneratedMethod generatedMethod = beanRegistrationCode.getMethods().add("getInstance", (method) -> {
method.addJavadoc("Get the bean instance for '$L'.", this.registeredBean.getBeanName());
method.addModifiers(Modifier.PRIVATE, Modifier.STATIC);
method.returns(BEAN_TYPE);
CodeBlock.Builder code = CodeBlock.builder();
code.add("return $T.create(", JsonMixinModuleEntries.class).beginControlFlow("(mixins) ->");
entries.doWithEntry(this.classLoader, (type, mixin) -> addEntryCode(code, type, mixin));
code.endControlFlow(")");
method.addCode(code.build());
});
return generatedMethod.toMethodReference().toCodeBlock();
}
private void addEntryCode(CodeBlock.Builder code, Class<?> type, Class<?> mixin) {
AccessControl accessForTypes = AccessControl.lowest(AccessControl.forClass(type),
AccessControl.forClass(mixin));
if (accessForTypes.isPublic()) {
code.addStatement("$L.and($T.class, $T.class)", "mixins", type, mixin);
}
else {
code.addStatement("$L.and($S, $S)", "mixins", type.getName(), mixin.getName());
}
}
private void contributeHints(RuntimeHints runtimeHints, JsonMixinModuleEntries entries) {
Set<Class<?>> mixins = new LinkedHashSet<>();
entries.doWithEntry(this.classLoader, (type, mixin) -> mixins.add(mixin));
new BindingReflectionHintsRegistrar().registerReflectionHints(runtimeHints.reflection(),
mixins.toArray(Class<?>[]::new));
}
}
}
| AotContribution |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/IgnoreNullMetricsPhysicalPlannerTests.java | {
"start": 1120,
"end": 3620
} | class ____ extends AbstractLocalPhysicalPlanOptimizerTests {
public IgnoreNullMetricsPhysicalPlannerTests(String name, Configuration config) {
super(name, config);
}
/**
* This tests that we get the same end result plan with an explicit isNotNull and the implicit one added by the rule
*/
public void testSamePhysicalPlans() {
assumeTrue("requires metrics command", EsqlCapabilities.Cap.TS_COMMAND_V0.isEnabled());
String testQuery = """
TS k8s
| STATS max(rate(network.total_bytes_in)) BY Bucket(@timestamp, 1 hour)
| LIMIT 10
""";
PhysicalPlan actualPlan = plannerOptimizerTimeSeries.plan(testQuery);
String controlQuery = """
TS k8s
| WHERE network.total_bytes_in IS NOT NULL
| STATS max(rate(network.total_bytes_in)) BY Bucket(@timestamp, 1 hour)
| LIMIT 10
""";
PhysicalPlan expectedPlan = plannerOptimizerTimeSeries.plan(controlQuery);
assertEqualsIgnoringIds(NodeUtils.diffString(expectedPlan, actualPlan), expectedPlan, actualPlan);
}
public void testPushdownOfSimpleCounterQuery() {
assumeTrue("requires metrics command", EsqlCapabilities.Cap.TS_COMMAND_V0.isEnabled());
String query = """
TS k8s
| STATS max(rate(network.total_bytes_in)) BY Bucket(@timestamp, 1 hour)
| LIMIT 10
""";
PhysicalPlan actualPlan = plannerOptimizerTimeSeries.plan(query);
EsQueryExec queryExec = (EsQueryExec) actualPlan.collect(node -> node instanceof EsQueryExec).get(0);
QueryBuilder expected = unscore(existsQuery("network.total_bytes_in"));
assertThat(queryExec.query().toString(), is(expected.toString()));
}
public void testPushdownOfSimpleGagueQuery() {
assumeTrue("requires metrics command", EsqlCapabilities.Cap.TS_COMMAND_V0.isEnabled());
String query = """
TS k8s
| STATS max(max_over_time(network.eth0.tx)) BY Bucket(@timestamp, 1 hour)
| LIMIT 10
""";
PhysicalPlan actualPlan = plannerOptimizerTimeSeries.plan(query);
EsQueryExec queryExec = (EsQueryExec) actualPlan.collect(node -> node instanceof EsQueryExec).get(0);
QueryBuilder expected = unscore(existsQuery("network.eth0.tx"));
assertThat(queryExec.query().toString(), is(expected.toString()));
}
}
| IgnoreNullMetricsPhysicalPlannerTests |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/resource/InheritanceParentResource.java | {
"start": 140,
"end": 242
} | interface ____ {
@GET
@Produces("text/plain")
String firstest();
}
| InheritanceParentResource |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/objects/Objects_assertEqual_Test.java | {
"start": 4071,
"end": 4223
} | class ____ extends RuntimeException {
private static final long serialVersionUID = 6906581676690444515L;
}
private static | NullEqualsException |
java | elastic__elasticsearch | modules/data-streams/src/internalClusterTest/java/org/elasticsearch/datastreams/DataStreamAutoshardingIT.java | {
"start": 32581,
"end": 36665
} | class ____ extends Plugin {
@Override
public List<Setting<?>> getSettings() {
return List.of(
Setting.boolSetting(DATA_STREAMS_AUTO_SHARDING_ENABLED, false, Setting.Property.Dynamic, Setting.Property.NodeScope)
);
}
@Override
public Settings additionalSettings() {
return Settings.builder().put(DATA_STREAMS_AUTO_SHARDING_ENABLED, true).build();
}
}
private static void mockStatsForIndex(
ClusterState clusterState,
String assignedShardNodeId,
IndexMetadata indexMetadata,
List<ShardStats> shards
) {
for (DiscoveryNode node : clusterState.nodes().getAllNodes()) {
// one node returns the stats for all our shards, the other nodes don't return any stats
if (node.getId().equals(assignedShardNodeId)) {
MockTransportService.getInstance(node.getName())
.addRequestHandlingBehavior(IndicesStatsAction.NAME + "[n]", (handler, request, channel, task) -> {
TransportIndicesStatsAction instance = internalCluster().getInstance(
TransportIndicesStatsAction.class,
node.getName()
);
channel.sendResponse(instance.new NodeResponse(node.getId(), indexMetadata.getNumberOfShards(), shards, List.of()));
});
} else {
MockTransportService.getInstance(node.getName())
.addRequestHandlingBehavior(IndicesStatsAction.NAME + "[n]", (handler, request, channel, task) -> {
TransportIndicesStatsAction instance = internalCluster().getInstance(
TransportIndicesStatsAction.class,
node.getName()
);
channel.sendResponse(instance.new NodeResponse(node.getId(), 0, List.of(), List.of()));
});
}
}
}
private static void resetTelemetry() {
for (PluginsService pluginsService : internalCluster().getInstances(PluginsService.class)) {
final TestTelemetryPlugin telemetryPlugin = pluginsService.filterPlugins(TestTelemetryPlugin.class).findFirst().orElseThrow();
telemetryPlugin.resetMeter();
}
}
private static void assertTelemetry(String expectedEmittedMetric) {
Map<String, List<Measurement>> measurements = new HashMap<>();
for (PluginsService pluginsService : internalCluster().getInstances(PluginsService.class)) {
final TestTelemetryPlugin telemetryPlugin = pluginsService.filterPlugins(TestTelemetryPlugin.class).findFirst().orElseThrow();
telemetryPlugin.collect();
List<String> autoShardingMetrics = telemetryPlugin.getRegisteredMetrics(InstrumentType.LONG_COUNTER)
.stream()
.filter(metric -> metric.startsWith("es.auto_sharding."))
.sorted()
.toList();
assertEquals(autoShardingMetrics, MetadataRolloverService.AUTO_SHARDING_METRIC_NAMES.values().stream().sorted().toList());
for (String metricName : MetadataRolloverService.AUTO_SHARDING_METRIC_NAMES.values()) {
measurements.computeIfAbsent(metricName, n -> new ArrayList<>())
.addAll(telemetryPlugin.getLongCounterMeasurement(metricName));
}
}
// assert other metrics not emitted
MetadataRolloverService.AUTO_SHARDING_METRIC_NAMES.values()
.stream()
.filter(metric -> metric.equals(expectedEmittedMetric) == false)
.forEach(metric -> assertThat(measurements.get(metric), empty()));
assertThat(measurements.get(expectedEmittedMetric), hasSize(1));
Measurement measurement = measurements.get(expectedEmittedMetric).get(0);
assertThat(measurement.getLong(), is(1L));
assertFalse(measurement.isDouble());
}
}
| TestAutoshardingPlugin |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceRequestFilterTest.java | {
"start": 1997,
"end": 2242
} | class ____ {
@Inject
RestSubResource restSubResource;
@Path("{last}")
public RestSubResource hello() {
return restSubResource;
}
}
@ApplicationScoped
public static | MiddleRestResource |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 63663,
"end": 63960
} | class ____ {
@Bean
static PropertySourcesPlaceholderConfigurer configurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(SimplePrefixedProperties.class)
static | WithPropertyPlaceholderValueConfiguration |
java | spring-projects__spring-framework | spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineReactiveCachingTests.java | {
"start": 5285,
"end": 5539
} | class ____ {
@Bean
CacheManager cacheManager() {
CaffeineCacheManager cm = new CaffeineCacheManager("first");
cm.setAsyncCacheMode(true);
return cm;
}
}
@Configuration(proxyBeanMethods = false)
@EnableCaching
static | AsyncCacheModeConfig |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/delegation/web/DelegationTokenAuthenticationFilter.java | {
"start": 7019,
"end": 12843
} | class ____ the configuration from the filter configs, we are
// creating an empty configuration and injecting the proxyuser settings in
// it. In the initialization of the filter, the returned configuration is
// passed to the ProxyUsers which only looks for 'proxyusers.' properties.
Configuration conf = new Configuration(false);
Enumeration<?> names = filterConfig.getInitParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (name.startsWith(PROXYUSER_PREFIX + ".")) {
String value = filterConfig.getInitParameter(name);
conf.set(name, value);
}
}
return conf;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
AuthenticationHandler handler = getAuthenticationHandler();
AbstractDelegationTokenSecretManager dtSecretManager =
(AbstractDelegationTokenSecretManager) filterConfig.getServletContext().
getAttribute(DELEGATION_TOKEN_SECRET_MANAGER_ATTR);
if (dtSecretManager != null && handler
instanceof DelegationTokenAuthenticationHandler) {
DelegationTokenAuthenticationHandler dtHandler =
(DelegationTokenAuthenticationHandler) getAuthenticationHandler();
dtHandler.setExternalDelegationTokenSecretManager(dtSecretManager);
}
if (handler instanceof PseudoAuthenticationHandler ||
handler instanceof PseudoDelegationTokenAuthenticationHandler) {
setHandlerAuthMethod(SaslRpcServer.AuthMethod.SIMPLE);
}
if (handler instanceof KerberosAuthenticationHandler ||
handler instanceof KerberosDelegationTokenAuthenticationHandler) {
setHandlerAuthMethod(SaslRpcServer.AuthMethod.KERBEROS);
}
// proxyuser configuration
Configuration conf = getProxyuserConfiguration(filterConfig);
ProxyUsers.refreshSuperUserGroupsConfiguration(conf, PROXYUSER_PREFIX);
}
@Override
protected void initializeAuthHandler(String authHandlerClassName,
FilterConfig filterConfig) throws ServletException {
// A single CuratorFramework should be used for a ZK cluster.
// If the ZKSignerSecretProvider has already created it, it has to
// be set here... to be used by the ZKDelegationTokenSecretManager
ZKDelegationTokenSecretManager.setCurator((CuratorFramework)
filterConfig.getServletContext().getAttribute(ZKSignerSecretProvider.
ZOOKEEPER_SIGNER_SECRET_PROVIDER_CURATOR_CLIENT_ATTRIBUTE));
super.initializeAuthHandler(authHandlerClassName, filterConfig);
ZKDelegationTokenSecretManager.setCurator(null);
}
protected void setHandlerAuthMethod(SaslRpcServer.AuthMethod authMethod) {
this.handlerAuthMethod = authMethod;
}
@VisibleForTesting
static String getDoAs(HttpServletRequest request) {
String queryString = request.getQueryString();
if (queryString == null) {
return null;
}
List<NameValuePair> list = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
if (list != null) {
for (NameValuePair nv : list) {
if (DelegationTokenAuthenticatedURL.DO_AS.
equalsIgnoreCase(nv.getName())) {
return nv.getValue();
}
}
}
return null;
}
static UserGroupInformation getHttpUserGroupInformationInContext() {
return UGI_TL.get();
}
@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
boolean requestCompleted = false;
UserGroupInformation ugi = null;
AuthenticationToken authToken = (AuthenticationToken)
request.getUserPrincipal();
if (authToken != null && authToken != AuthenticationToken.ANONYMOUS) {
// if the request was authenticated because of a delegation token,
// then we ignore proxyuser (this is the same as the RPC behavior).
ugi = (UserGroupInformation) request.getAttribute(
DelegationTokenAuthenticationHandler.DELEGATION_TOKEN_UGI_ATTRIBUTE);
if (ugi == null) {
String realUser = request.getUserPrincipal().getName();
ugi = UserGroupInformation.createRemoteUser(realUser,
handlerAuthMethod);
String doAsUser = getDoAs(request);
if (doAsUser != null) {
ugi = UserGroupInformation.createProxyUser(doAsUser, ugi);
try {
ProxyUsers.authorize(ugi, request.getRemoteAddr());
} catch (AuthorizationException ex) {
HttpExceptionUtils.createServletExceptionResponse(response,
HttpServletResponse.SC_FORBIDDEN, ex);
requestCompleted = true;
if (LOG.isDebugEnabled()) {
LOG.debug("Authentication exception: " + ex.getMessage(), ex);
} else {
LOG.warn("Authentication exception: " + ex.getMessage());
}
}
}
}
UGI_TL.set(ugi);
}
if (!requestCompleted) {
final UserGroupInformation ugiF = ugi;
try {
request = new HttpServletRequestWrapper(request) {
@Override
public String getAuthType() {
return (ugiF != null) ? handlerAuthMethod.toString() : null;
}
@Override
public String getRemoteUser() {
return (ugiF != null) ? ugiF.getShortUserName() : null;
}
@Override
public Principal getUserPrincipal() {
return (ugiF != null) ? new Principal() {
@Override
public String getName() {
return ugiF.getUserName();
}
} : null;
}
};
super.doFilter(filterChain, request, response);
} finally {
UGI_TL.remove();
}
}
}
}
| gets |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/activities/ActivityLevel.java | {
"start": 944,
"end": 1001
} | enum ____ {
QUEUE,
APP,
REQUEST,
NODE
}
| ActivityLevel |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/join/JoinTest.java | {
"start": 4185,
"end": 9440
} | class ____ null" ).list().size() );
assertEquals( 1, s.createQuery( "from Person p where p.class = User" ).list().size() );
assertTrue( s.createQuery( "from User u" ).list().size() == 1 );
s.clear();
// Remove the optional row from the join table and requery the User obj
doWork( s );
s.clear();
jesus = (User) s.get( Person.class, new Long( jesus.getId() ) );
s.clear();
// Cleanup the test data
s.remove( jesus );
assertTrue( s.createQuery( "from Person" ).list().isEmpty() );
}
);
}
private void doWork(final Session s) {
s.doWork(
new AbstractWork() {
@Override
public void execute(Connection connection) throws SQLException {
try (PreparedStatement ps = connection.prepareStatement( "delete from t_user" )) {
ps.execute();
}
}
}
);
}
@Test
public void testCustomColumnReadAndWrite(SessionFactoryScope scope) {
scope.inTransaction(
s -> {
final double HEIGHT_INCHES = 73;
final double HEIGHT_CENTIMETERS = HEIGHT_INCHES * 2.54d;
Person p = new Person();
p.setName( "Emmanuel" );
p.setSex( 'M' );
p.setHeightInches( HEIGHT_INCHES );
s.persist( p );
final double PASSWORD_EXPIRY_WEEKS = 4;
final double PASSWORD_EXPIRY_DAYS = PASSWORD_EXPIRY_WEEKS * 7d;
User u = new User();
u.setName( "Steve" );
u.setSex( 'M' );
u.setPasswordExpiryDays( PASSWORD_EXPIRY_DAYS );
s.persist( u );
s.flush();
// Test value conversion during insert
// Oracle returns BigDecimaal while other dialects return Double;
// casting to Number so it works on all dialects
Number heightViaSql = (Number) s.createNativeQuery(
"select height_centimeters from person where name='Emmanuel'" ).uniqueResult();
assertEquals( HEIGHT_CENTIMETERS, heightViaSql.doubleValue(), 0.01d );
Number expiryViaSql = (Number) s.createNativeQuery(
"select pwd_expiry_weeks from t_user where person_id=?" )
.setParameter( 1, u.getId() )
.uniqueResult();
assertEquals( PASSWORD_EXPIRY_WEEKS, expiryViaSql.doubleValue(), 0.01d );
// Test projection
Double heightViaHql = (Double) s.createQuery(
"select p.heightInches from Person p where p.name = 'Emmanuel'" ).uniqueResult();
assertEquals( HEIGHT_INCHES, heightViaHql, 0.01d );
Double expiryViaHql = (Double) s.createQuery(
"select u.passwordExpiryDays from User u where u.name = 'Steve'" ).uniqueResult();
assertEquals( PASSWORD_EXPIRY_DAYS, expiryViaHql, 0.01d );
// Test restriction and entity load via criteria
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
CriteriaQuery<Person> personCriteria = criteriaBuilder.createQuery( Person.class );
Root<Person> rootPerson = personCriteria.from( Person.class );
personCriteria.where( criteriaBuilder.between(
rootPerson.get( "heightInches" ),
HEIGHT_INCHES - 0.01d,
HEIGHT_INCHES + 0.01d
) );
p = s.createQuery( personCriteria ).uniqueResult();
// p = (Person)s.createCriteria(Person.class)
// .add(Restrictions.between("heightInches", HEIGHT_INCHES - 0.01d, HEIGHT_INCHES + 0.01d))
// .uniqueResult();
assertEquals( HEIGHT_INCHES, p.getHeightInches(), 0.01d );
CriteriaQuery<User> userCriteria = criteriaBuilder.createQuery( User.class );
Root<User> userRoot = userCriteria.from( User.class );
userCriteria.where( criteriaBuilder.between(
userRoot.get( "passwordExpiryDays" ),
PASSWORD_EXPIRY_DAYS - 0.01d,
PASSWORD_EXPIRY_DAYS + 0.01d
) );
u = s.createQuery( userCriteria ).uniqueResult();
// u = (User)s.createCriteria(User.class)
// .add(Restrictions.between("passwordExpiryDays", PASSWORD_EXPIRY_DAYS - 0.01d, PASSWORD_EXPIRY_DAYS + 0.01d))
// .uniqueResult();
assertEquals( PASSWORD_EXPIRY_DAYS, u.getPasswordExpiryDays(), 0.01d );
// Test predicate and entity load via HQL
p = (Person) s.createQuery( "from Person p where p.heightInches between ?1 and ?2" )
.setParameter( 1, HEIGHT_INCHES - 0.01d )
.setParameter( 2, HEIGHT_INCHES + 0.01d )
.uniqueResult();
assertNotNull( p );
assertEquals( 0.01d, HEIGHT_INCHES, p.getHeightInches() );
u = (User) s.createQuery( "from User u where u.passwordExpiryDays between ?1 and ?2" )
.setParameter( 1, PASSWORD_EXPIRY_DAYS - 0.01d )
.setParameter( 2, PASSWORD_EXPIRY_DAYS + 0.01d )
.uniqueResult();
assertEquals( PASSWORD_EXPIRY_DAYS, u.getPasswordExpiryDays(), 0.01d );
// Test update
p.setHeightInches( 1 );
u.setPasswordExpiryDays( 7d );
s.flush();
heightViaSql = (Number) s.createNativeQuery(
"select height_centimeters from person where name='Emmanuel'" ).uniqueResult();
assertEquals( 2.54d, heightViaSql.doubleValue(), 0.01d );
expiryViaSql = (Number) s.createNativeQuery( "select pwd_expiry_weeks from t_user where person_id=?" )
.setParameter( 1, u.getId() )
.uniqueResult();
assertEquals( 1d, expiryViaSql.doubleValue(), 0.01d );
s.remove( p );
s.remove( u );
assertTrue( s.createQuery( "from Person" ).list().isEmpty() );
}
);
}
}
| is |
java | spring-projects__spring-security | oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtValidators.java | {
"start": 5832,
"end": 8789
} | class ____ {
Map<String, OAuth2TokenValidator<Jwt>> validators = new LinkedHashMap<>();
private AtJwtBuilder() {
JwtTimestampValidator timestamps = new JwtTimestampValidator();
this.validators.put(JoseHeaderNames.TYP, new JwtTypeValidator(List.of("at+jwt", "application/at+jwt")));
this.validators.put(JwtClaimNames.EXP, require(JwtClaimNames.EXP).and(timestamps));
this.validators.put(JwtClaimNames.SUB, require(JwtClaimNames.SUB));
this.validators.put(JwtClaimNames.IAT, require(JwtClaimNames.IAT).and(timestamps));
this.validators.put(JwtClaimNames.JTI, require(JwtClaimNames.JTI));
}
/**
* Validate that each token has this <a href=
* "https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1">issuer</a>.
* @param issuer the required issuer
* @return the {@link AtJwtBuilder} for further configuration
*/
public AtJwtBuilder issuer(String issuer) {
return validators((v) -> v.put(JwtClaimNames.ISS, new JwtIssuerValidator(issuer)));
}
/**
* Validate that each token has this <a href=
* "https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3">audience</a>.
* @param audience the required audience
* @return the {@link AtJwtBuilder} for further configuration
*/
public AtJwtBuilder audience(String audience) {
return validators((v) -> v.put(JwtClaimNames.AUD, new JwtAudienceValidator(audience)));
}
/**
* Validate that each token has this <a href=
* "https://datatracker.ietf.org/doc/html/rfc8693#name-client_id-client-identifier">client_id</a>.
* @param clientId the client identifier to use
* @return the {@link AtJwtBuilder} for further configuration
*/
public AtJwtBuilder clientId(String clientId) {
return validators((v) -> v.put("client_id", require("client_id").isEqualTo(clientId)));
}
/**
* Mutate the list of validators by claim name.
*
* <p>
* For example, to add a validator for
* <a href="https://datatracker.ietf.org/doc/html/rfc9068#section-2.2.1">azp</a>
* do: <code>
* builder.validators((v) -> v.put("acr", myValidator()));
* </code>
*
* <p>
* A validator is required for all required RFC 9068 claims.
* @param validators the mutator for the map of validators
* @return the {@link AtJwtBuilder} for further configuration
*/
public AtJwtBuilder validators(Consumer<Map<String, OAuth2TokenValidator<Jwt>>> validators) {
validators.accept(this.validators);
return this;
}
/**
* Build the validator
* @return the RFC 9068 validator
*/
public OAuth2TokenValidator<Jwt> build() {
List.of(JoseHeaderNames.TYP, JwtClaimNames.EXP, JwtClaimNames.SUB, JwtClaimNames.IAT, JwtClaimNames.JTI,
JwtClaimNames.ISS, JwtClaimNames.AUD, "client_id")
.forEach((name) -> Assert.isTrue(this.validators.containsKey(name), name + " must be validated"));
return new DelegatingOAuth2TokenValidator<>(this.validators.values());
}
}
private static final | AtJwtBuilder |
java | apache__camel | components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpPojoTypeTest.java | {
"start": 1589,
"end": 12710
} | class ____ extends BaseUndertowTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void testUndertowPojoTypeValidateModel() {
// Wasn't clear if there's a way to put this test into camel-core just to test the model
// perhaps without starting the Camel Context?
List<RestDefinition> restDefinitions
= context().getCamelContextExtension().getContextPlugin(Model.class).getRestDefinitions();
assertNotNull(restDefinitions);
assertTrue(!restDefinitions.isEmpty());
RestDefinition restDefinition = restDefinitions.get(0);
List<VerbDefinition> verbs = restDefinition.getVerbs();
assertNotNull(verbs);
Map<String, VerbDefinition> mapVerb = new TreeMap<>();
verbs.forEach(verb -> mapVerb.put(verb.getId(), verb));
assertEquals(UserPojo[].class.getCanonicalName(), mapVerb.get("getUsers").getOutType());
assertEquals(UserPojo[].class.getCanonicalName(), mapVerb.get("getUsersList").getOutType());
assertEquals(UserPojo.class.getCanonicalName(), mapVerb.get("getUser").getOutType());
assertEquals(UserPojo.class.getCanonicalName(), mapVerb.get("putUser").getType());
assertEquals(UserPojo[].class.getCanonicalName(), mapVerb.get("putUsers").getType());
assertEquals(UserPojo[].class.getCanonicalName(), mapVerb.get("putUsersList").getType());
}
@Test
public void testUndertowPojoTypeGetUsers() throws Exception {
Exchange outExchange = template.request("undertow:http://localhost:{{port}}/users", exchange -> {
exchange.getIn().setHeader(Exchange.HTTP_METHOD, "GET");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
});
assertNotNull(outExchange);
assertEquals("application/json", outExchange.getMessage().getHeader(Exchange.CONTENT_TYPE));
String out = outExchange.getMessage().getBody(String.class);
assertNotNull(out);
UserPojo[] users = mapper.readValue(out, UserPojo[].class);
assertEquals(2, users.length);
assertEquals("Scott", users[0].getName());
assertEquals("Claus", users[1].getName());
}
@Test
public void testUndertowPojoTypePutUser() {
Exchange outExchange = template.request("undertow:http://localhost:{{port}}/users/1", exchange -> {
exchange.getIn().setHeader(Exchange.HTTP_METHOD, "PUT");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
UserPojo user = new UserPojo();
user.setId(1);
user.setName("Scott");
String body = mapper.writeValueAsString(user);
exchange.getIn().setBody(body);
});
assertNotNull(outExchange);
assertEquals(200, outExchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
}
@Test
public void testUndertowPojoTypePutUserFail() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:putUser");
mock.expectedMessageCount(0);
Exchange outExchange = template.request("undertow:http://localhost:{{port}}/users/1", exchange -> {
exchange.getIn().setHeader(Exchange.HTTP_METHOD, "PUT");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
CountryPojo country = new CountryPojo();
country.setIso("US");
country.setCountry("United States");
String body = mapper.writeValueAsString(country);
exchange.getIn().setBody(body);
});
assertNotNull(outExchange);
assertEquals(400, outExchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testUndertowPojoTypePutUsers() throws Exception {
UserPojo user1 = new UserPojo();
user1.setId(1);
user1.setName("Scott");
UserPojo user2 = new UserPojo();
user2.setId(2);
user2.setName("Claus");
final UserPojo[] users = new UserPojo[] { user1, user2 };
MockEndpoint mock = getMockEndpoint("mock:putUsers");
mock.expectedMessageCount(1);
mock.message(0).body(UserPojo[].class);
Exchange outExchange = template.request("undertow:http://localhost:{{port}}/users", exchange -> {
exchange.getIn().setHeader(Exchange.HTTP_METHOD, "PUT");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
String body = mapper.writeValueAsString(users);
exchange.getIn().setBody(body);
});
assertNotNull(outExchange);
assertEquals(200, outExchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
MockEndpoint.assertIsSatisfied(context);
Exchange exchange = mock.assertExchangeReceived(0);
UserPojo[] receivedUsers = exchange.getIn().getBody(UserPojo[].class);
assertEquals(2, receivedUsers.length);
assertEquals(user1.getName(), receivedUsers[0].getName());
assertEquals(user2.getName(), receivedUsers[1].getName());
}
@Test
public void testUndertowPojoTypePutUsersFail() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:putUsers");
mock.expectedMessageCount(0);
Exchange outExchange = template.request("undertow:http://localhost:{{port}}/users", exchange -> {
exchange.getIn().setHeader(Exchange.HTTP_METHOD, "PUT");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
UserPojo user = new UserPojo();
user.setId(1);
user.setName("Scott");
String body = mapper.writeValueAsString(user);
exchange.getIn().setBody(body);
});
assertNotNull(outExchange);
assertEquals(400, outExchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testUndertowPojoTypePutUsersList() throws Exception {
UserPojo user1 = new UserPojo();
user1.setId(1);
user1.setName("Scott");
UserPojo user2 = new UserPojo();
user2.setId(2);
user2.setName("Claus");
final UserPojo[] users = new UserPojo[] { user1, user2 };
MockEndpoint mock = getMockEndpoint("mock:putUsersList");
mock.expectedMessageCount(1);
mock.message(0).body(UserPojo[].class);
Exchange outExchange = template.request("undertow:http://localhost:{{port}}/users/list", exchange -> {
exchange.getIn().setHeader(Exchange.HTTP_METHOD, "PUT");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
String body = mapper.writeValueAsString(users);
exchange.getIn().setBody(body);
});
assertNotNull(outExchange);
assertEquals(200, outExchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
MockEndpoint.assertIsSatisfied(context);
Exchange exchange = mock.assertExchangeReceived(0);
UserPojo[] receivedUsers = exchange.getIn().getBody(UserPojo[].class);
assertEquals(2, receivedUsers.length);
assertEquals(user1.getName(), receivedUsers[0].getName());
assertEquals(user2.getName(), receivedUsers[1].getName());
}
@Test
public void testUndertowPojoTypePutUsersListFail() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:putUsersList");
mock.expectedMessageCount(0);
Exchange outExchange = template.request("undertow:http://localhost:{{port}}/users/list", exchange -> {
exchange.getIn().setHeader(Exchange.HTTP_METHOD, "PUT");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
UserPojo user = new UserPojo();
user.setId(1);
user.setName("Scott");
String body = mapper.writeValueAsString(user);
exchange.getIn().setBody(body);
});
assertNotNull(outExchange);
assertEquals(400, outExchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
onException(Exception.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
.setBody().simple("${exchange.message}");
// configure to use undertow on localhost with the given port
restConfiguration().component("undertow").host("localhost").port(getPort())
.bindingMode(RestBindingMode.json);
// use the rest DSL to define the rest services
rest()
.get("/users").id("getUsers").outType(UserPojo[].class).to("direct:users")
.get("/users/list").id("getUsersList").outType(UserPojo[].class).to("direct:list")
.get("/users/{id}").id("getUser").outType(UserPojo.class).to("direct:id")
.put("/users/{id}").id("putUser").type(UserPojo.class).to("mock:putUser")
.put("/users").id("putUsers").type(UserPojo[].class).to("mock:putUsers")
.put("/users/list").id("putUsersList").type(UserPojo[].class).to("mock:putUsersList");
from("direct:users")
.process(exchange -> {
UserPojo user1 = new UserPojo();
user1.setId(1);
user1.setName("Scott");
UserPojo user2 = new UserPojo();
user2.setId(2);
user2.setName("Claus");
exchange.getMessage().setBody(new UserPojo[] { user1, user2 });
});
from("direct:list")
.process(exchange -> {
UserPojo user1 = new UserPojo();
user1.setId(1);
user1.setName("Scott");
UserPojo user2 = new UserPojo();
user2.setId(2);
user2.setName("Claus");
exchange.getMessage().setBody(new UserPojo[] { user1, user2 });
});
from("direct:id")
.process(exchange -> {
UserPojo user1 = new UserPojo();
user1.setId(exchange.getIn().getHeader("id", int.class));
user1.setName("Scott");
exchange.getMessage().setBody(user1);
});
}
};
}
}
| RestUndertowHttpPojoTypeTest |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/model/ResourceUriLoader.java | {
"start": 1066,
"end": 1535
} | class ____ only handles resource Uris that are from the application's
* package, resource uris from other packages are handled by {@link UriLoader}. {@link UriLoader} is
* even less preferred because it can only handle certain resources from raw resources and it will
* not apply appropriate theming, RTL or night mode attributes.
*
* @param <DataT> The type of data produced, e.g. {@link InputStream} or {@link
* AssetFileDescriptor}.
*/
public final | explicitly |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/state/CheckpointStorageLoaderTest.java | {
"start": 2130,
"end": 7126
} | class ____ {
private final Logger LOG = LoggerFactory.getLogger(CheckpointStorageLoaderTest.class);
@TempDir private java.nio.file.Path tmp;
private final ClassLoader cl = getClass().getClassLoader();
@Test
void testNoCheckpointStorageDefined() throws Exception {
assertThat(CheckpointStorageLoader.fromConfig(new Configuration(), cl, null))
.isNotPresent();
}
@Test
void testLegacyStateBackendTakesPrecedence() throws Exception {
StateBackend legacy = new LegacyStateBackend();
CheckpointStorage storage = new MockStorage();
CheckpointStorage configured =
CheckpointStorageLoader.load(
storage, legacy, new Configuration(), new Configuration(), cl, LOG);
assertThat(configured)
.withFailMessage("Legacy state backends should always take precedence")
.isEqualTo(legacy);
}
@Test
void testModernStateBackendDoesNotTakePrecedence() throws Exception {
StateBackend modern = new ModernStateBackend();
CheckpointStorage storage = new MockStorage();
CheckpointStorage configured =
CheckpointStorageLoader.load(
storage, modern, new Configuration(), new Configuration(), cl, LOG);
assertThat(configured)
.withFailMessage("Modern state backends should never take precedence")
.isEqualTo(storage);
}
@Test
void testLoadingFromFactory() throws Exception {
final Configuration jobConfig = new Configuration();
final Configuration clusterConfig = new Configuration();
jobConfig.set(CheckpointingOptions.CHECKPOINT_STORAGE, WorkingFactory.class.getName());
clusterConfig.set(CheckpointingOptions.CHECKPOINT_STORAGE, "jobmanager");
CheckpointStorage storage1 =
CheckpointStorageLoader.load(
null, new ModernStateBackend(), jobConfig, clusterConfig, cl, LOG);
assertThat(storage1).isInstanceOf(MockStorage.class);
CheckpointStorage storage2 =
CheckpointStorageLoader.load(
null,
new ModernStateBackend(),
new Configuration(),
clusterConfig,
cl,
LOG);
assertThat(storage2).isInstanceOf(JobManagerCheckpointStorage.class);
}
@Test
void testDefaultCheckpointStorage() throws Exception {
CheckpointStorage storage1 =
CheckpointStorageLoader.load(
null,
new ModernStateBackend(),
new Configuration(),
new Configuration(),
cl,
LOG);
assertThat(storage1).isInstanceOf(JobManagerCheckpointStorage.class);
final String checkpointDir1 = new Path(TempDirUtils.newFolder(tmp).toURI()).toString();
final String checkpointDir2 = new Path(TempDirUtils.newFolder(tmp).toURI()).toString();
Configuration jobConfig = new Configuration();
Configuration clusterConfig = new Configuration();
jobConfig.set(CheckpointingOptions.CHECKPOINTS_DIRECTORY, checkpointDir1);
clusterConfig.set(CheckpointingOptions.CHECKPOINTS_DIRECTORY, checkpointDir2);
CheckpointStorage storage2 =
CheckpointStorageLoader.load(
null, new ModernStateBackend(), jobConfig, clusterConfig, cl, LOG);
assertThat(((FileSystemCheckpointStorage) storage2).getCheckpointPath())
.isEqualTo(new Path(jobConfig.get(CheckpointingOptions.CHECKPOINTS_DIRECTORY)));
CheckpointStorage storage3 =
CheckpointStorageLoader.load(
null,
new ModernStateBackend(),
new Configuration(),
clusterConfig,
cl,
LOG);
assertThat(((FileSystemCheckpointStorage) storage3).getCheckpointPath())
.isEqualTo(new Path(clusterConfig.get(CheckpointingOptions.CHECKPOINTS_DIRECTORY)));
}
@Test
void testLoadingFails() throws Exception {
final Configuration config = new Configuration();
config.set(CheckpointingOptions.CHECKPOINT_STORAGE, "does.not.exist");
assertThatThrownBy(
() ->
CheckpointStorageLoader.load(
null,
new ModernStateBackend(),
new Configuration(),
config,
cl,
LOG))
.isInstanceOf(DynamicCodeLoadingException.class);
// try a | CheckpointStorageLoaderTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAsyncTest.java | {
"start": 6965,
"end": 7339
} | class ____ implements Processor {
public MyProcessor() {
}
@Override
public void process(Exchange exchange) {
if (exchange.getIn().getBody(String.class).contains("Kaboom")) {
throw new IllegalArgumentException("Kaboom");
}
exchange.getIn().setBody("Bye World");
}
}
}
| MyProcessor |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/TextSimilarityConfig.java | {
"start": 1326,
"end": 9037
} | class ____ implements NlpConfig {
public static final String NAME = "text_similarity";
public static final ParseField TEXT = new ParseField("text");
public static final ParseField SPAN_SCORE_COMBINATION_FUNCTION = new ParseField("span_score_combination_function");
public static TextSimilarityConfig fromXContentStrict(XContentParser parser) {
return STRICT_PARSER.apply(parser, null);
}
public static TextSimilarityConfig fromXContentLenient(XContentParser parser) {
return LENIENT_PARSER.apply(parser, null);
}
private static final ConstructingObjectParser<TextSimilarityConfig, Void> STRICT_PARSER = createParser(false);
private static final ConstructingObjectParser<TextSimilarityConfig, Void> LENIENT_PARSER = createParser(true);
private static ConstructingObjectParser<TextSimilarityConfig, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<TextSimilarityConfig, Void> parser = new ConstructingObjectParser<>(
NAME,
ignoreUnknownFields,
a -> new TextSimilarityConfig((VocabularyConfig) a[0], (Tokenization) a[1], (String) a[2], (String) a[3])
);
parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> {
if (ignoreUnknownFields == false) {
throw ExceptionsHelper.badRequestException(
"illegal setting [{}] on inference model creation",
VOCABULARY.getPreferredName()
);
}
return VocabularyConfig.fromXContentLenient(p);
}, VOCABULARY);
parser.declareNamedObject(
ConstructingObjectParser.optionalConstructorArg(),
(p, c, n) -> p.namedObject(Tokenization.class, n, ignoreUnknownFields),
TOKENIZATION
);
parser.declareString(ConstructingObjectParser.optionalConstructorArg(), RESULTS_FIELD);
parser.declareString(ConstructingObjectParser.optionalConstructorArg(), SPAN_SCORE_COMBINATION_FUNCTION);
return parser;
}
private final VocabularyConfig vocabularyConfig;
private final Tokenization tokenization;
private final String resultsField;
private final String text;
private final SpanScoreFunction spanScoreFunction;
TextSimilarityConfig(
@Nullable VocabularyConfig vocabularyConfig,
@Nullable Tokenization tokenization,
@Nullable String resultsField,
@Nullable String spanScoreFunction
) {
this.vocabularyConfig = Optional.ofNullable(vocabularyConfig)
.orElse(new VocabularyConfig(InferenceIndexConstants.nativeDefinitionStore()));
this.tokenization = tokenization == null ? Tokenization.createDefault() : tokenization;
this.resultsField = resultsField;
this.text = null;
this.spanScoreFunction = Optional.ofNullable(spanScoreFunction).map(SpanScoreFunction::fromString).orElse(SpanScoreFunction.MAX);
}
public TextSimilarityConfig(
String text,
VocabularyConfig vocabularyConfig,
Tokenization tokenization,
String resultsField,
SpanScoreFunction spanScoreFunction
) {
this.text = ExceptionsHelper.requireNonNull(text, TEXT);
this.vocabularyConfig = ExceptionsHelper.requireNonNull(vocabularyConfig, VOCABULARY);
this.tokenization = ExceptionsHelper.requireNonNull(tokenization, TOKENIZATION);
this.resultsField = resultsField;
this.spanScoreFunction = spanScoreFunction;
}
public TextSimilarityConfig(StreamInput in) throws IOException {
vocabularyConfig = new VocabularyConfig(in);
tokenization = in.readNamedWriteable(Tokenization.class);
resultsField = in.readOptionalString();
text = in.readOptionalString();
spanScoreFunction = in.readEnum(SpanScoreFunction.class);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
vocabularyConfig.writeTo(out);
out.writeNamedWriteable(tokenization);
out.writeOptionalString(resultsField);
out.writeOptionalString(text);
out.writeEnum(spanScoreFunction);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(VOCABULARY.getPreferredName(), vocabularyConfig, params);
NamedXContentObjectHelper.writeNamedObject(builder, params, TOKENIZATION.getPreferredName(), tokenization);
if (resultsField != null) {
builder.field(RESULTS_FIELD.getPreferredName(), resultsField);
}
if (text != null) {
builder.field(TEXT.getPreferredName(), text);
}
builder.field(SPAN_SCORE_COMBINATION_FUNCTION.getPreferredName(), spanScoreFunction.toString());
builder.endObject();
return builder;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public boolean isTargetTypeSupported(TargetType targetType) {
return false;
}
@Override
public InferenceConfig apply(InferenceConfigUpdate update) {
if (update instanceof TextSimilarityConfigUpdate configUpdate) {
return new TextSimilarityConfig(
configUpdate.getText(),
vocabularyConfig,
configUpdate.tokenizationUpdate == null ? tokenization : configUpdate.tokenizationUpdate.apply(tokenization),
Optional.ofNullable(configUpdate.getResultsField()).orElse(resultsField),
Optional.ofNullable(configUpdate.getSpanScoreFunction()).orElse(spanScoreFunction)
);
} else if (update instanceof TokenizationConfigUpdate tokenizationUpdate) {
var updatedTokenization = getTokenization().updateWindowSettings(tokenizationUpdate.getSpanSettings());
return new TextSimilarityConfig(text, vocabularyConfig, updatedTokenization, resultsField, spanScoreFunction);
} else {
throw incompatibleUpdateException(update.getName());
}
}
@Override
public MlConfigVersion getMinimalSupportedMlConfigVersion() {
return MlConfigVersion.V_8_5_0;
}
@Override
public TransportVersion getMinimalSupportedTransportVersion() {
return TransportVersions.V_8_5_0;
}
@Override
public String getName() {
return NAME;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
TextSimilarityConfig that = (TextSimilarityConfig) o;
return Objects.equals(vocabularyConfig, that.vocabularyConfig)
&& Objects.equals(tokenization, that.tokenization)
&& Objects.equals(text, that.text)
&& Objects.equals(spanScoreFunction, that.spanScoreFunction)
&& Objects.equals(resultsField, that.resultsField);
}
@Override
public int hashCode() {
return Objects.hash(vocabularyConfig, tokenization, resultsField, text, spanScoreFunction);
}
@Override
public VocabularyConfig getVocabularyConfig() {
return vocabularyConfig;
}
@Override
public Tokenization getTokenization() {
return tokenization;
}
public String getText() {
return text;
}
public SpanScoreFunction getSpanScoreFunction() {
return spanScoreFunction;
}
@Override
public String getResultsField() {
return resultsField;
}
@Override
public boolean isAllocateOnly() {
return true;
}
public | TextSimilarityConfig |
java | quarkusio__quarkus | extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/SelectedKubernetesDeploymentTargetBuildItem.java | {
"start": 105,
"end": 427
} | class ____ extends SimpleBuildItem {
private final DeploymentTargetEntry entry;
public SelectedKubernetesDeploymentTargetBuildItem(DeploymentTargetEntry entry) {
this.entry = entry;
}
public DeploymentTargetEntry getEntry() {
return entry;
}
}
| SelectedKubernetesDeploymentTargetBuildItem |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java | {
"start": 25991,
"end": 26554
} | class ____ {
public void foo(Suit suit) {
// BUG: Diagnostic contains:
switch (suit) {
case HEART:
System.out.println("heart");
break;
}
}
}
""")
.setArgs("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion")
.doTest();
}
@Test
public void emptyExpressionSwitchCases_noMatch() {
helper
.addSourceLines(
"Test.java",
"""
| Test |
java | google__guice | core/src/com/google/inject/internal/UntargettedBindingProcessor.java | {
"start": 808,
"end": 2630
} | class ____ extends AbstractBindingProcessor {
UntargettedBindingProcessor(Errors errors, ProcessedBindingData processedBindingData) {
super(errors, processedBindingData);
}
@Override
public <T> Boolean visit(Binding<T> binding) {
return binding.acceptTargetVisitor(
new Processor<T, Boolean>((BindingImpl<T>) binding) {
@Override
public Boolean visit(UntargettedBinding<? extends T> untargetted) {
prepareBinding();
// Error: Missing implementation.
// Example: bind(Date.class).annotatedWith(Red.class);
// We can't assume abstract types aren't injectable. They may have an
// @ImplementedBy annotation or something.
if (key.getAnnotationType() != null) {
errors.missingImplementationWithHint(key, injector);
putBinding(invalidBinding(injector, key, source));
return true;
}
// Queue up the creationListener for notify until after bindings are processed.
try {
BindingImpl<T> binding =
injector.createUninitializedBinding(
key,
scoping,
source,
errors,
false,
processedBindingData::addCreationListener);
scheduleInitialization(binding);
putBinding(binding);
} catch (ErrorsException e) {
errors.merge(e.getErrors());
putBinding(invalidBinding(injector, key, source));
}
return true;
}
@Override
protected Boolean visitOther(Binding<? extends T> binding) {
return false;
}
});
}
}
| UntargettedBindingProcessor |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/FactoryUtil.java | {
"start": 44253,
"end": 44754
} | class ____ extends FactoryHelper<CatalogFactory> {
public CatalogFactoryHelper(CatalogFactory catalogFactory, CatalogFactory.Context context) {
super(catalogFactory, context.getOptions(), PROPERTY_VERSION);
}
}
/**
* Helper utility for validating all options for a {@link CatalogStoreFactory}.
*
* @see #createCatalogStoreFactoryHelper(CatalogStoreFactory, CatalogStoreFactory.Context)
*/
@PublicEvolving
public static | CatalogFactoryHelper |
java | alibaba__fastjson | src/test/java/com/alibaba/json/SerializerFeatureDistinctTest.java | {
"start": 220,
"end": 725
} | class ____ extends TestCase {
public void test_allfeatures() throws Exception {
Set<Object> masks = new HashSet<Object>();
for (SerializerFeature feature : SerializerFeature.values()) {
Object mask = feature.getMask();
assertFalse(masks.contains(mask));
masks.add(mask);
}
assertEquals(masks.size(), SerializerFeature.values().length);
System.out.println(SerializerFeature.values().length);
}
}
| SerializerFeatureDistinctTest |
java | apache__kafka | server-common/src/main/java/org/apache/kafka/server/share/persister/PersisterStateManager.java | {
"start": 12174,
"end": 22332
} | class ____ return the appropriate completable future encapsulating
* the response for the RPC.
*
* @return A completable future of RPC response
*/
protected abstract CompletableFuture<? extends AbstractResponse> result();
/**
* Returns builder for share coordinator
*
* @return builder for find coordinator
*/
protected AbstractRequest.Builder<FindCoordinatorRequest> findShareCoordinatorBuilder() {
return new FindCoordinatorRequest.Builder(new FindCoordinatorRequestData()
.setKeyType(FindCoordinatorRequest.CoordinatorType.SHARE.id())
.setKey(partitionKey().asCoordinatorKey()));
}
public void addRequestToNodeMap(Node node, PersisterStateManagerHandler handler) {
if (!handler.isBatchable()) {
return;
}
synchronized (nodeMapLock) {
nodeRPCMap.computeIfAbsent(node, k -> new HashMap<>())
.computeIfAbsent(handler.rpcType(), k -> new HashMap<>())
.computeIfAbsent(partitionKey().groupId(), k -> new LinkedList<>())
.add(handler);
}
sender.wakeup();
}
/**
* Returns true is coordinator node is not yet set
*
* @return boolean
*/
protected boolean lookupNeeded() {
if (coordinatorNode != null) {
return false;
}
if (cacheHelper.containsTopic(Topic.SHARE_GROUP_STATE_TOPIC_NAME)) {
log.debug("{} internal topic already exists.", Topic.SHARE_GROUP_STATE_TOPIC_NAME);
Node node = cacheHelper.getShareCoordinator(partitionKey(), Topic.SHARE_GROUP_STATE_TOPIC_NAME);
if (node != Node.noNode()) {
log.debug("Found coordinator node in cache: {}", node);
coordinatorNode = node;
addRequestToNodeMap(node, this);
return false;
}
}
return true;
}
/**
* Returns the String key to be used as share coordinator key
*
* @return String
*/
protected SharePartitionKey partitionKey() {
return partitionKey;
}
/**
* Returns true if the RPC response if for Find Coordinator RPC.
*
* @param response - Client response object
* @return boolean
*/
protected boolean isFindCoordinatorResponse(ClientResponse response) {
return response != null && response.requestHeader().apiKey() == ApiKeys.FIND_COORDINATOR;
}
@Override
public void onComplete(ClientResponse response) {
if (onCompleteCallback != null) {
onCompleteCallback.accept(response);
}
// We don't know if FIND_COORD or actual REQUEST. Let's err on side of request.
if (response == null) {
requestErrorResponse(Errors.UNKNOWN_SERVER_ERROR, new NetworkException("Did not receive any response (response = null)"));
sender.wakeup();
return;
}
if (isFindCoordinatorResponse(response)) {
handleFindCoordinatorResponse(response);
} else if (isResponseForRequest(response)) {
handleRequestResponse(response);
}
sender.wakeup();
}
// Visibility for testing
Optional<Errors> checkResponseError(ClientResponse response) {
if (response.hasResponse()) {
return Optional.empty();
}
log.debug("Response for RPC {} with key {} is invalid - {}", name(), this.partitionKey, response);
if (response.authenticationException() != null) {
log.error("Authentication exception", response.authenticationException());
Errors error = Errors.forException(response.authenticationException());
return Optional.of(error);
} else if (response.versionMismatch() != null) {
log.error("Version mismatch exception", response.versionMismatch());
Errors error = Errors.forException(response.versionMismatch());
return Optional.of(error);
} else if (response.wasDisconnected()) { // Retriable
return Optional.of(Errors.NETWORK_EXCEPTION);
} else if (response.wasTimedOut()) { // Retriable
log.debug("Response for RPC {} with key {} timed out - {}.", name(), this.partitionKey, response);
return Optional.of(Errors.REQUEST_TIMED_OUT);
} else {
return Optional.of(Errors.UNKNOWN_SERVER_ERROR);
}
}
protected void resetCoordinatorNode() {
coordinatorNode = null;
}
/**
* Handles the response for find coordinator RPC and sets appropriate state.
*
* @param response - Client response for find coordinator RPC
*/
protected void handleFindCoordinatorResponse(ClientResponse response) {
log.debug("Find coordinator response received - {}", response);
// Incrementing the number of find coordinator attempts
findCoordBackoff.incrementAttempt();
Errors clientResponseError = checkResponseError(response).orElse(Errors.NONE);
String clientResponseErrorMessage = clientResponseError.message();
switch (clientResponseError) {
case NONE:
List<FindCoordinatorResponseData.Coordinator> coordinators = ((FindCoordinatorResponse) response.responseBody()).coordinators();
if (coordinators.size() != 1) {
log.error("Find coordinator response for {} is invalid. Number of coordinators = {}", partitionKey(), coordinators.size());
findCoordinatorErrorResponse(Errors.UNKNOWN_SERVER_ERROR, new IllegalStateException("Invalid response with multiple coordinators."));
return;
}
FindCoordinatorResponseData.Coordinator coordinatorData = coordinators.get(0);
Errors error = Errors.forCode(coordinatorData.errorCode());
String errorMessage = coordinatorData.errorMessage();
if (errorMessage == null || errorMessage.isEmpty()) {
errorMessage = error.message();
}
switch (error) {
case NONE:
log.trace("Find coordinator response valid. Enqueuing actual request.");
findCoordBackoff.resetAttempts();
coordinatorNode = new Node(coordinatorData.nodeId(), coordinatorData.host(), coordinatorData.port());
// now we want the actual share state RPC call to happen
if (this.isBatchable()) {
addRequestToNodeMap(coordinatorNode, this);
} else {
enqueue(this);
}
break;
case COORDINATOR_NOT_AVAILABLE: // retriable error codes
case COORDINATOR_LOAD_IN_PROGRESS:
case NOT_COORDINATOR:
case UNKNOWN_TOPIC_OR_PARTITION:
log.debug("Received retriable error in find coordinator for {} using key {}: {}", name(), partitionKey(), errorMessage);
if (!findCoordBackoff.canAttempt()) {
log.error("Exhausted max retries to find coordinator for {} using key {} without success.", name(), partitionKey());
findCoordinatorErrorResponse(error, new Exception("Exhausted max retries to find coordinator without success."));
break;
}
resetCoordinatorNode();
timer.add(new PersisterTimerTask(findCoordBackoff.backOff(), this));
break;
default:
log.error("Unable to find coordinator for {} using key {}: {}.", name(), partitionKey(), errorMessage);
findCoordinatorErrorResponse(error, new Exception(errorMessage));
}
return;
case NETWORK_EXCEPTION: // Retriable client response error codes.
case REQUEST_TIMED_OUT:
log.debug("Received retriable error in find coordinator client response for {} using key {} due to {}.", name(), partitionKey(), clientResponseErrorMessage);
if (!findCoordBackoff.canAttempt()) {
log.error("Exhausted max retries to find coordinator due to error in client response for {} using key {}.", name(), partitionKey());
findCoordinatorErrorResponse(clientResponseError, new Exception("Exhausted max retries to find coordinator without success."));
break;
}
resetCoordinatorNode();
timer.add(new PersisterTimerTask(findCoordBackoff.backOff(), this));
break;
default:
log.error("Unable to find coordinator due to error in client response for {} using key {}: {}", name(), partitionKey(), clientResponseError.code());
findCoordinatorErrorResponse(clientResponseError, new Exception(clientResponseErrorMessage));
}
}
// Visible for testing
public Node getCoordinatorNode() {
return coordinatorNode;
}
protected abstract boolean isBatchable();
/**
* This method can be called by child | should |
java | elastic__elasticsearch | modules/lang-painless/src/test/java/org/elasticsearch/painless/LookupTests.java | {
"start": 1757,
"end": 2094
} | class ____ extends B { // in whitelist
public String getString0() {
return "D/0";
} // in whitelist
public String getString1(int param0) {
return "D/1 (" + param0 + ")";
} // in whitelist
}
public | D |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/tree/domain/SqmSingularValuedJoin.java | {
"start": 232,
"end": 354
} | interface ____<L,R> extends SqmJoin<L, R> {
SqmCorrelatedSingularValuedJoin<L,R> createCorrelation();
}
| SqmSingularValuedJoin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.