language
stringclasses 1
value | repo
stringclasses 60
values | path
stringlengths 22
294
| class_span
dict | source
stringlengths 13
1.16M
| target
stringlengths 1
113
|
|---|---|---|---|---|---|
java
|
spring-projects__spring-security
|
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilter.java
|
{
"start": 4560,
"end": 14639
}
|
class ____ extends OncePerRequestFilter {
static final String DEFAULT_DEVICE_VERIFICATION_ENDPOINT_URI = "/oauth2/device_verification";
private final AuthenticationManager authenticationManager;
private final RequestMatcher deviceVerificationEndpointMatcher;
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private AuthenticationConverter authenticationConverter;
private AuthenticationSuccessHandler authenticationSuccessHandler = new SimpleUrlAuthenticationSuccessHandler(
"/?success");
private AuthenticationFailureHandler authenticationFailureHandler = this::sendErrorResponse;
private String consentPage;
/**
* Constructs an {@code OAuth2DeviceVerificationEndpointFilter} using the provided
* parameters.
* @param authenticationManager the authentication manager
*/
public OAuth2DeviceVerificationEndpointFilter(AuthenticationManager authenticationManager) {
this(authenticationManager, DEFAULT_DEVICE_VERIFICATION_ENDPOINT_URI);
}
/**
* Constructs an {@code OAuth2DeviceVerificationEndpointFilter} using the provided
* parameters.
* @param authenticationManager the authentication manager
* @param deviceVerificationEndpointUri the endpoint {@code URI} for device
* verification requests
*/
public OAuth2DeviceVerificationEndpointFilter(AuthenticationManager authenticationManager,
String deviceVerificationEndpointUri) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.hasText(deviceVerificationEndpointUri, "deviceVerificationEndpointUri cannot be empty");
this.authenticationManager = authenticationManager;
this.deviceVerificationEndpointMatcher = createDefaultRequestMatcher(deviceVerificationEndpointUri);
// @formatter:off
this.authenticationConverter = new DelegatingAuthenticationConverter(
Arrays.asList(
new OAuth2DeviceVerificationAuthenticationConverter(),
new OAuth2DeviceAuthorizationConsentAuthenticationConverter()));
// @formatter:on
}
private RequestMatcher createDefaultRequestMatcher(String deviceVerificationEndpointUri) {
RequestMatcher verificationRequestGetMatcher = PathPatternRequestMatcher.withDefaults()
.matcher(HttpMethod.GET, deviceVerificationEndpointUri);
RequestMatcher verificationRequestPostMatcher = PathPatternRequestMatcher.withDefaults()
.matcher(HttpMethod.POST, deviceVerificationEndpointUri);
RequestMatcher userCodeParameterMatcher = (
request) -> request.getParameter(OAuth2ParameterNames.USER_CODE) != null;
return new AndRequestMatcher(
new OrRequestMatcher(verificationRequestGetMatcher, verificationRequestPostMatcher),
userCodeParameterMatcher);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (!this.deviceVerificationEndpointMatcher.matches(request)) {
filterChain.doFilter(request, response);
return;
}
try {
Authentication authentication = this.authenticationConverter.convert(request);
if (authentication instanceof AbstractAuthenticationToken authenticationToken) {
authenticationToken.setDetails(this.authenticationDetailsSource.buildDetails(request));
}
Authentication authenticationResult = this.authenticationManager.authenticate(authentication);
if (!authenticationResult.isAuthenticated()) {
// If the Principal (Resource Owner) is not authenticated then pass
// through the chain
// with the expectation that the authentication process will commence via
// AuthenticationEntryPoint
filterChain.doFilter(request, response);
return;
}
if (authenticationResult instanceof OAuth2DeviceAuthorizationConsentAuthenticationToken) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Device authorization consent is required");
}
sendAuthorizationConsent(request, response, authenticationResult);
return;
}
this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, authenticationResult);
}
catch (OAuth2AuthenticationException ex) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Device verification request failed: %s", ex.getError()), ex);
}
this.authenticationFailureHandler.onAuthenticationFailure(request, response, ex);
}
}
/**
* Sets the {@link AuthenticationDetailsSource} used for building an authentication
* details instance from {@link HttpServletRequest}.
* @param authenticationDetailsSource the {@link AuthenticationDetailsSource} used for
* building an authentication details instance from {@link HttpServletRequest}
*/
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "authenticationDetailsSource cannot be null");
this.authenticationDetailsSource = authenticationDetailsSource;
}
/**
* Sets the {@link AuthenticationConverter} used when attempting to extract a Device
* Verification Request (or Device Authorization Consent) from
* {@link HttpServletRequest} to an instance of
* {@link OAuth2DeviceVerificationAuthenticationToken} or
* {@link OAuth2DeviceAuthorizationConsentAuthenticationToken} used for authenticating
* the request.
* @param authenticationConverter the {@link AuthenticationConverter} used when
* attempting to extract a Device Verification Request (or Device Authorization
* Consent) from {@link HttpServletRequest}
*/
public void setAuthenticationConverter(AuthenticationConverter authenticationConverter) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter;
}
/**
* Sets the {@link AuthenticationSuccessHandler} used for handling an
* {@link OAuth2DeviceVerificationAuthenticationToken} and returning the response.
* @param authenticationSuccessHandler the {@link AuthenticationSuccessHandler} used
* for handling an {@link OAuth2DeviceVerificationAuthenticationToken}
*/
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");
this.authenticationSuccessHandler = authenticationSuccessHandler;
}
/**
* Sets the {@link AuthenticationFailureHandler} used for handling an
* {@link OAuth2AuthenticationException} and returning the {@link OAuth2Error Error
* Response}.
* @param authenticationFailureHandler the {@link AuthenticationFailureHandler} used
* for handling an {@link OAuth2AuthenticationException}
*/
public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null");
this.authenticationFailureHandler = authenticationFailureHandler;
}
/**
* Specify the URI to redirect Resource Owners to if consent is required. A default
* consent page will be generated when this attribute is not specified.
* @param consentPage the URI of the custom consent page to redirect to if consent is
* required (e.g. "/oauth2/consent")
*/
public void setConsentPage(String consentPage) {
this.consentPage = consentPage;
}
private void sendAuthorizationConsent(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
OAuth2DeviceAuthorizationConsentAuthenticationToken authorizationConsentAuthentication = (OAuth2DeviceAuthorizationConsentAuthenticationToken) authentication;
String clientId = authorizationConsentAuthentication.getClientId();
Authentication principal = (Authentication) authorizationConsentAuthentication.getPrincipal();
Set<String> requestedScopes = authorizationConsentAuthentication.getRequestedScopes();
Set<String> authorizedScopes = authorizationConsentAuthentication.getScopes();
String state = authorizationConsentAuthentication.getState();
String userCode = authorizationConsentAuthentication.getUserCode();
if (hasConsentUri()) {
String redirectUri = UriComponentsBuilder.fromUriString(resolveConsentUri(request))
.queryParam(OAuth2ParameterNames.SCOPE, String.join(" ", requestedScopes))
.queryParam(OAuth2ParameterNames.CLIENT_ID, clientId)
.queryParam(OAuth2ParameterNames.STATE, state)
.queryParam(OAuth2ParameterNames.USER_CODE, userCode)
.toUriString();
this.redirectStrategy.sendRedirect(request, response, redirectUri);
}
else {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Displaying generated consent screen");
}
Map<String, String> additionalParameters = new HashMap<>();
additionalParameters.put(OAuth2ParameterNames.USER_CODE, userCode);
DefaultConsentPage.displayConsent(request, response, clientId, principal, requestedScopes, authorizedScopes,
state, additionalParameters);
}
}
private boolean hasConsentUri() {
return StringUtils.hasText(this.consentPage);
}
private String resolveConsentUri(HttpServletRequest request) {
if (UrlUtils.isAbsoluteUrl(this.consentPage)) {
return this.consentPage;
}
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setScheme(request.getScheme());
urlBuilder.setServerName(request.getServerName());
urlBuilder.setPort(request.getServerPort());
urlBuilder.setContextPath(request.getContextPath());
urlBuilder.setPathInfo(this.consentPage);
return urlBuilder.getUrl();
}
private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authenticationException) throws IOException {
OAuth2Error error = ((OAuth2AuthenticationException) authenticationException).getError();
response.sendError(HttpStatus.BAD_REQUEST.value(), error.toString());
}
}
|
OAuth2DeviceVerificationEndpointFilter
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/component/language/LanguageScriptInHeaderRouteTest.java
|
{
"start": 1016,
"end": 1675
}
|
class ____ extends ContextTestSupport {
@Test
public void testLanguage() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBodyAndHeader("direct:start", "World", Exchange.LANGUAGE_SCRIPT, "Hello ${body}");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("language:simple?allowTemplateFromHeader=true").to("mock:result");
}
};
}
}
|
LanguageScriptInHeaderRouteTest
|
java
|
apache__kafka
|
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/modern/ModernGroupMember.java
|
{
"start": 1003,
"end": 4563
}
|
class ____ {
/**
* The member id.
*/
protected String memberId;
/**
* The current member epoch.
*/
protected int memberEpoch;
/**
* The previous member epoch.
*/
protected int previousMemberEpoch;
/**
* The member state.
*/
protected MemberState state;
/**
* The instance id provided by the member.
*/
protected String instanceId;
/**
* The rack id provided by the member.
*/
protected String rackId;
/**
* The client id reported by the member.
*/
protected String clientId;
/**
* The host reported by the member.
*/
protected String clientHost;
/**
* The list of subscriptions (topic names) configured by the member.
*/
protected Set<String> subscribedTopicNames;
/**
* The partitions assigned to this member.
*/
protected Map<Uuid, Set<Integer>> assignedPartitions;
protected ModernGroupMember(
String memberId,
int memberEpoch,
int previousMemberEpoch,
String instanceId,
String rackId,
String clientId,
String clientHost,
Set<String> subscribedTopicNames,
MemberState state,
Map<Uuid, Set<Integer>> assignedPartitions
) {
this.memberId = memberId;
this.memberEpoch = memberEpoch;
this.previousMemberEpoch = previousMemberEpoch;
this.state = state;
this.instanceId = instanceId;
this.rackId = rackId;
this.clientId = clientId;
this.clientHost = clientHost;
this.subscribedTopicNames = subscribedTopicNames;
this.assignedPartitions = assignedPartitions;
}
/**
* @return The member id.
*/
public String memberId() {
return memberId;
}
/**
* @return The current member epoch.
*/
public int memberEpoch() {
return memberEpoch;
}
/**
* @return The previous member epoch.
*/
public int previousMemberEpoch() {
return previousMemberEpoch;
}
/**
* @return The instance id.
*/
public String instanceId() {
return instanceId;
}
/**
* @return The rack id.
*/
public String rackId() {
return rackId;
}
/**
* @return The client id.
*/
public String clientId() {
return clientId;
}
/**
* @return The client host.
*/
public String clientHost() {
return clientHost;
}
/**
* @return The list of subscribed topic names.
*/
public Set<String> subscribedTopicNames() {
return subscribedTopicNames;
}
/**
* @return The current state.
*/
public MemberState state() {
return state;
}
/**
* @return True if the member is in the Stable state and at the desired epoch.
*/
public boolean isReconciledTo(int targetAssignmentEpoch) {
return state == MemberState.STABLE && memberEpoch == targetAssignmentEpoch;
}
/**
* @return The set of assigned partitions.
*/
public Map<Uuid, Set<Integer>> assignedPartitions() {
return assignedPartitions;
}
/**
* @return True of the two provided members have different assigned partitions.
*/
public static boolean hasAssignedPartitionsChanged(
ModernGroupMember member1,
ModernGroupMember member2
) {
return !member1.assignedPartitions().equals(member2.assignedPartitions());
}
}
|
ModernGroupMember
|
java
|
playframework__playframework
|
web/play-java-forms/src/main/java/play/data/validation/Constraints.java
|
{
"start": 17966,
"end": 19441
}
|
class ____ extends Validator<String>
implements ConstraintValidator<Pattern, String> {
public static final String message = "error.pattern";
java.util.regex.Pattern regex = null;
public PatternValidator() {}
public PatternValidator(String regex) {
this.regex = java.util.regex.Pattern.compile(regex);
}
@Override
public void initialize(Pattern constraintAnnotation) {
regex = java.util.regex.Pattern.compile(constraintAnnotation.value());
}
@Override
public boolean isValid(String object) {
if (object == null || object.isEmpty()) {
return true;
}
return regex.matcher(object).matches();
}
@Override
public Tuple<String, Object[]> getErrorMessageKey() {
return Tuple(message, new Object[] {regex});
}
}
/**
* Constructs a 'pattern' validator.
*
* @param regex the regular expression to match.
* @return the PatternValidator.
*/
public static Validator<String> pattern(String regex) {
return new PatternValidator(regex);
}
// --- validate fields with custom validator
/** Defines a custom validator. */
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidateWithValidator.class)
@Repeatable(play.data.validation.Constraints.ValidateWith.List.class)
@Display(
name = "constraint.validatewith",
attributes = {})
public @
|
PatternValidator
|
java
|
apache__flink
|
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/rest/handler/statement/FetchResultsHandler.java
|
{
"start": 3049,
"end": 6430
}
|
class ____
extends AbstractSqlGatewayRestHandler<
EmptyRequestBody, FetchResultsResponseBody, FetchResultsMessageParameters> {
public FetchResultsHandler(
SqlGatewayService service,
Map<String, String> responseHeaders,
MessageHeaders<
EmptyRequestBody,
FetchResultsResponseBody,
FetchResultsMessageParameters>
messageHeaders) {
super(service, responseHeaders, messageHeaders);
}
@Override
protected CompletableFuture<FetchResultsResponseBody> handleRequest(
SqlGatewayRestAPIVersion version, @Nonnull HandlerRequest<EmptyRequestBody> request)
throws RestHandlerException {
// Parse the parameters
SessionHandle sessionHandle = request.getPathParameter(SessionHandleIdPathParameter.class);
OperationHandle operationHandle =
request.getPathParameter(OperationHandleIdPathParameter.class);
Long token = request.getPathParameter(FetchResultsTokenPathParameter.class);
RowFormat rowFormat =
HandlerRequestUtils.getQueryParameter(
request, FetchResultsRowFormatQueryParameter.class, RowFormat.JSON);
// Get the statement results
ResultSet resultSet;
try {
resultSet =
service.fetchResults(sessionHandle, operationHandle, token, Integer.MAX_VALUE);
} catch (Exception e) {
throw new SqlGatewayException(e);
}
ResultSet.ResultType resultType = resultSet.getResultType();
Long nextToken = resultSet.getNextToken();
String nextResultUri =
FetchResultsHeaders.buildNextUri(
version,
sessionHandle.getIdentifier().toString(),
operationHandle.getIdentifier().toString(),
nextToken,
rowFormat);
// Build the response
if (resultType == ResultSet.ResultType.NOT_READY) {
return CompletableFuture.completedFuture(
new NotReadyFetchResultResponse(nextResultUri));
} else {
RowDataLocalTimeZoneConverter timeZoneConverter = null;
if (rowFormat == RowFormat.JSON) {
List<LogicalType> logicalTypeList =
resultSet.getResultSchema().getColumnDataTypes().stream()
.map(DataType::getLogicalType)
.collect(Collectors.toList());
timeZoneConverter =
new RowDataLocalTimeZoneConverter(
logicalTypeList,
Configuration.fromMap(service.getSessionConfig(sessionHandle)));
}
return CompletableFuture.completedFuture(
new FetchResultResponseBodyImpl(
resultType,
resultSet.isQueryResult(),
resultSet.getJobID(),
resultSet.getResultKind(),
ResultInfo.createResultInfo(resultSet, rowFormat, timeZoneConverter),
nextResultUri));
}
}
}
|
FetchResultsHandler
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java
|
{
"start": 2361,
"end": 10202
}
|
class ____ {
private OAuth2AuthorizationService authorizationService;
private OAuth2TokenRevocationAuthenticationProvider authenticationProvider;
@BeforeEach
public void setUp() {
this.authorizationService = mock(OAuth2AuthorizationService.class);
this.authenticationProvider = new OAuth2TokenRevocationAuthenticationProvider(this.authorizationService);
}
@Test
public void constructorWhenAuthorizationServiceNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> new OAuth2TokenRevocationAuthenticationProvider(null))
.withMessage("authorizationService cannot be null");
}
@Test
public void supportsWhenTypeOAuth2TokenRevocationAuthenticationTokenThenReturnTrue() {
assertThat(this.authenticationProvider.supports(OAuth2TokenRevocationAuthenticationToken.class)).isTrue();
}
@Test
public void authenticateWhenClientPrincipalNotOAuth2ClientAuthenticationTokenThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
TestingAuthenticationToken clientPrincipal = new TestingAuthenticationToken(registeredClient.getClientId(),
registeredClient.getClientSecret());
OAuth2TokenRevocationAuthenticationToken authentication = new OAuth2TokenRevocationAuthenticationToken("token",
clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue());
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
}
@Test
public void authenticateWhenClientPrincipalNotAuthenticatedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
registeredClient.getClientSecret(), null);
OAuth2TokenRevocationAuthenticationToken authentication = new OAuth2TokenRevocationAuthenticationToken("token",
clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue());
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
}
@Test
public void authenticateWhenInvalidTokenThenNotRevoked() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2TokenRevocationAuthenticationToken authentication = new OAuth2TokenRevocationAuthenticationToken("token",
clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue());
OAuth2TokenRevocationAuthenticationToken authenticationResult = (OAuth2TokenRevocationAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
assertThat(authenticationResult.isAuthenticated()).isFalse();
verify(this.authorizationService, never()).save(any());
}
@Test
public void authenticateWhenTokenIssuedToAnotherClientThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(TestRegisteredClients.registeredClient2().build())
.build();
given(this.authorizationService.findByToken(eq("token"), isNull())).willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2TokenRevocationAuthenticationToken authentication = new OAuth2TokenRevocationAuthenticationToken("token",
clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue());
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
}
@Test
public void authenticateWhenValidRefreshTokenThenRevoked() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()),
isNull()))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2TokenRevocationAuthenticationToken authentication = new OAuth2TokenRevocationAuthenticationToken(
authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal,
OAuth2TokenType.REFRESH_TOKEN.getValue());
OAuth2TokenRevocationAuthenticationToken authenticationResult = (OAuth2TokenRevocationAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
assertThat(authenticationResult.isAuthenticated()).isTrue();
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
verify(this.authorizationService).save(authorizationCaptor.capture());
OAuth2Authorization updatedAuthorization = authorizationCaptor.getValue();
OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken = updatedAuthorization.getRefreshToken();
assertThat(refreshToken.isInvalidated()).isTrue();
OAuth2Authorization.Token<OAuth2AccessToken> accessToken = updatedAuthorization.getAccessToken();
assertThat(accessToken.isInvalidated()).isTrue();
}
@Test
public void authenticateWhenValidAccessTokenThenRevoked() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
given(this.authorizationService.findByToken(eq(authorization.getAccessToken().getToken().getTokenValue()),
isNull()))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2TokenRevocationAuthenticationToken authentication = new OAuth2TokenRevocationAuthenticationToken(
authorization.getAccessToken().getToken().getTokenValue(), clientPrincipal,
OAuth2TokenType.ACCESS_TOKEN.getValue());
OAuth2TokenRevocationAuthenticationToken authenticationResult = (OAuth2TokenRevocationAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
assertThat(authenticationResult.isAuthenticated()).isTrue();
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
verify(this.authorizationService).save(authorizationCaptor.capture());
OAuth2Authorization updatedAuthorization = authorizationCaptor.getValue();
OAuth2Authorization.Token<OAuth2AccessToken> accessToken = updatedAuthorization.getAccessToken();
assertThat(accessToken.isInvalidated()).isTrue();
OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken = updatedAuthorization.getRefreshToken();
assertThat(refreshToken.isInvalidated()).isFalse();
}
}
|
OAuth2TokenRevocationAuthenticationProviderTests
|
java
|
micronaut-projects__micronaut-core
|
http-client/src/main/java/io/micronaut/http/client/netty/Http1ResponseHandler.java
|
{
"start": 5576,
"end": 8441
}
|
class ____ extends ReaderState<HttpContent> {
private final ResponseListener listener;
private final HttpResponse response;
private List<ByteBuf> buffered;
BufferedContent(ResponseListener listener, HttpResponse response) {
this.listener = listener;
this.response = response;
}
@Override
void read(ChannelHandlerContext ctx, HttpContent msg) {
if (msg.content().isReadable()) {
if (buffered == null) {
buffered = new ArrayList<>();
}
buffered.add(msg.content());
} else {
msg.release();
}
if (msg instanceof LastHttpContent) {
List<ByteBuf> buffered = this.buffered;
this.buffered = null;
transitionToState(ctx, this, AfterContent.INSTANCE);
BodySizeLimits limits = listener.sizeLimits();
if (buffered == null) {
complete(NettyByteBodyFactory.empty());
} else if (buffered.size() == 1) {
complete(new NettyByteBodyFactory(ctx.channel()).createChecked(limits, buffered.get(0)));
} else {
CompositeByteBuf composite = ctx.alloc().compositeBuffer();
composite.addComponents(true, buffered);
complete(new NettyByteBodyFactory(ctx.channel()).createChecked(limits, composite));
}
listener.finish(ctx);
}
}
@Override
void channelReadComplete(ChannelHandlerContext ctx) {
devolveToStreaming(ctx);
state.channelReadComplete(ctx); // check if there's demand
}
@Override
void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
devolveToStreaming(ctx);
state.exceptionCaught(ctx, cause);
}
private void devolveToStreaming(ChannelHandlerContext ctx) {
assert ctx.executor().inEventLoop();
UnbufferedContent unbufferedContent = new UnbufferedContent(listener, ctx, response);
if (buffered != null) {
for (ByteBuf buf : buffered) {
unbufferedContent.add(NettyReadBufferFactory.of(ctx.alloc()).adapt(buf));
}
}
transitionToState(ctx, this, unbufferedContent);
complete(new StreamingNettyByteBody(unbufferedContent.streaming));
}
private void complete(CloseableByteBody body) {
assert state != this : "should have been replaced already";
listener.complete(response, body);
}
}
/**
* Normal content handler, streaming data into a {@link StreamingNettyByteBody}.
*/
private final
|
BufferedContent
|
java
|
spring-projects__spring-framework
|
spring-jms/src/main/java/org/springframework/jms/listener/MessageListenerContainer.java
|
{
"start": 1200,
"end": 2511
}
|
interface ____ extends SmartLifecycle {
/**
* Set up the message listener to use. Throws an {@link IllegalArgumentException}
* if that message listener type is not supported.
*/
void setupMessageListener(Object messageListener);
/**
* Return the {@link MessageConverter} that can be used to
* convert {@link jakarta.jms.Message}, if any.
*/
@Nullable MessageConverter getMessageConverter();
/**
* Return the {@link DestinationResolver} to use to resolve
* destinations by names.
*/
@Nullable DestinationResolver getDestinationResolver();
/**
* Return whether the Publish/Subscribe domain ({@link jakarta.jms.Topic Topics}) is used.
* Otherwise, the Point-to-Point domain ({@link jakarta.jms.Queue Queues}) is used.
*/
boolean isPubSubDomain();
/**
* Return whether the reply destination uses Publish/Subscribe domain
* ({@link jakarta.jms.Topic Topics}). Otherwise, the Point-to-Point domain
* ({@link jakarta.jms.Queue Queues}) is used.
* <p>By default, the value is identical to {@link #isPubSubDomain()}.
*/
boolean isReplyPubSubDomain();
/**
* Return the {@link QosSettings} to use when sending a reply,
* or {@code null} if the broker's defaults should be used.
* @since 5.0
*/
@Nullable QosSettings getReplyQosSettings();
}
|
MessageListenerContainer
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/illegal/InterceptorReturningVoidTest.java
|
{
"start": 1563,
"end": 1925
}
|
class ____ have a return type of java.lang.Object"));
assertTrue(error.getMessage().contains("intercept(jakarta.interceptor.InvocationContext ctx)"));
assertTrue(error.getMessage().contains("InterceptorReturningVoidTest$MyInterceptor"));
}
@Target({ TYPE, METHOD, FIELD, PARAMETER })
@Retention(RUNTIME)
@InterceptorBinding
@
|
must
|
java
|
dropwizard__dropwizard
|
dropwizard-auth/src/main/java/io/dropwizard/auth/Authorizer.java
|
{
"start": 279,
"end": 1419
}
|
interface ____<P extends Principal> {
/**
* Decides if access is granted for the given principal in the given role.
*
* @param principal a {@link Principal} object, representing a user
* @param role a user role
* @param requestContext a request context.
* @return {@code true}, if the access is granted, {@code false otherwise}
* @since 2.0
*/
boolean authorize(P principal, String role, @Nullable ContainerRequestContext requestContext);
/**
* Returns an {@link AuthorizationContext} object, to be used in {@link CachingAuthorizer} as cache key.
* @param principal a {@link Principal} object, representing a user
* @param role a user role
* @param requestContext a request context.
* @return {@link AuthorizationContext} object, to be used in {@link CachingAuthorizer}.
* @since 2.1
*/
default AuthorizationContext<P> getAuthorizationContext(P principal, String role, @Nullable ContainerRequestContext requestContext) {
return new DefaultAuthorizationContext<>(principal, role, requestContext);
}
}
|
Authorizer
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerReadOnlyTest.java
|
{
"start": 191,
"end": 580
}
|
class ____ extends TestCase {
public void test_codec_null() throws Exception {
V0 v = new V0(123);
String text = JSON.toJSONString(v);
Assert.assertEquals("{\"value\":123}", text);
V0 v1 = JSON.parseObject(text, V0.class);
Assert.assertEquals(v1.getValue().intValue(), v.getValue().intValue());
}
public static
|
AtomicIntegerReadOnlyTest
|
java
|
spring-projects__spring-framework
|
spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/ReactorNettyCodec.java
|
{
"start": 1076,
"end": 1573
}
|
interface ____<P> {
/**
* Decode the input {@link ByteBuf} into one or more {@link Message Messages}.
* @param inputBuffer the input buffer to decode from
* @return 0 or more decoded messages
*/
Collection<Message<P>> decode(ByteBuf inputBuffer);
/**
* Encode the given {@link Message} to the output {@link ByteBuf}.
* @param message the message to encode
* @param outputBuffer the buffer to write to
*/
void encode(Message<P> message, ByteBuf outputBuffer);
}
|
ReactorNettyCodec
|
java
|
micronaut-projects__micronaut-core
|
inject-groovy/src/test/groovy/io/micronaut/inject/generics/missing/TestServiceImpl.java
|
{
"start": 761,
"end": 934
}
|
class ____ implements TestService {
@Override
public <T extends ListArguments> Flux<List<String>> findAll(T args) {
return Flux.empty();
}
}
|
TestServiceImpl
|
java
|
bumptech__glide
|
instrumentation/src/androidTest/java/com/bumptech/glide/CircleCropRegressionTest.java
|
{
"start": 871,
"end": 3599
}
|
class ____ {
@Rule public final TestName testName = new TestName();
@Rule public final TearDownGlide tearDownGlide = new TearDownGlide();
private BitmapRegressionTester bitmapRegressionTester;
private Context context;
private CanonicalBitmap canonical;
@Before
public void setUp() {
context = ApplicationProvider.getApplicationContext();
bitmapRegressionTester =
BitmapRegressionTester.newInstance(getClass(), testName).assumeShouldRun();
canonical = new CanonicalBitmap();
}
@Test
public void circleCrop_withSquareSmallerThanImage_returnsSquaredImage()
throws ExecutionException, InterruptedException {
Bitmap result =
bitmapRegressionTester.test(
GlideApp.with(context)
.asBitmap()
.load(canonical.getBitmap())
.circleCrop()
.override(50));
assertThat(result.getWidth()).isEqualTo(50);
assertThat(result.getHeight()).isEqualTo(50);
}
@Test
public void circleCrop_withSquareLargerThanImage_returnsUpscaledFitImage()
throws ExecutionException, InterruptedException {
float multiplier = 1.1f;
int multipliedWidth = (int) (canonical.getWidth() * multiplier);
Bitmap result =
bitmapRegressionTester.test(
GlideApp.with(context)
.asBitmap()
.load(canonical.getBitmap())
.circleCrop()
.override(multipliedWidth));
assertThat(result.getWidth()).isEqualTo(multipliedWidth);
assertThat(result.getHeight()).isEqualTo(multipliedWidth);
}
@Test
public void circleCrop_withNarrowRectangle_cropsWithin()
throws ExecutionException, InterruptedException {
Bitmap result =
bitmapRegressionTester.test(
GlideApp.with(context)
.asBitmap()
.load(canonical.getBitmap())
.circleCrop()
.override(canonical.getWidth() / 10, canonical.getHeight()));
assertThat(result.getWidth()).isEqualTo(canonical.getWidth() / 10);
assertThat(result.getHeight()).isEqualTo(canonical.getWidth() / 10);
}
@Test
public void circleCrop_withShortRectangle_fitsWithinMaintainingAspectRatio()
throws ExecutionException, InterruptedException {
Bitmap result =
bitmapRegressionTester.test(
GlideApp.with(context)
.asBitmap()
.load(canonical.getBitmap())
.circleCrop()
.override(canonical.getWidth(), canonical.getHeight() / 2));
assertThat(result.getWidth()).isEqualTo(canonical.getHeight() / 2);
assertThat(result.getHeight()).isEqualTo(canonical.getHeight() / 2);
}
}
|
CircleCropRegressionTest
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/example/java/WordCountSubclassPOJOITCase.java
|
{
"start": 1887,
"end": 4305
}
|
class ____ extends JavaProgramTestBaseJUnit4 implements Serializable {
private static final long serialVersionUID = 1L;
protected String textPath;
protected String resultPath;
@Override
protected void preSubmit() throws Exception {
textPath = createTempFile("text.txt", WordCountData.TEXT);
resultPath = getTempDirPath("result");
}
@Override
protected void postSubmit() throws Exception {
compareResultsByLinesInMemory(WordCountData.COUNTS, resultPath);
}
@Override
protected void testProgram() throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.BATCH);
DataStream<String> text = env.createInput(new TextInputFormat(new Path(textPath)));
DataStream<WCBase> counts =
text.flatMap(new Tokenizer())
.keyBy(x -> x.word)
.window(GlobalWindows.createWithEndOfStreamTrigger())
.reduce(
new ReduceFunction<WCBase>() {
private static final long serialVersionUID = 1L;
public WCBase reduce(WCBase value1, WCBase value2) {
WC wc1 = (WC) value1;
WC wc2 = (WC) value2;
return new WC(
value1.word, wc1.secretCount + wc2.secretCount);
}
})
.map(
new MapFunction<WCBase, WCBase>() {
@Override
public WCBase map(WCBase value) throws Exception {
WC wc = (WC) value;
wc.count = wc.secretCount;
return wc;
}
});
counts.sinkTo(
FileSink.forRowFormat(new Path(resultPath), new SimpleStringEncoder<WCBase>())
.build());
env.execute("WordCount with custom data types example");
}
private static final
|
WordCountSubclassPOJOITCase
|
java
|
google__auto
|
value/src/test/java/com/google/auto/value/processor/PropertyNamesTest.java
|
{
"start": 861,
"end": 2082
}
|
class ____ {
@Rule public Expect expect = Expect.create();
private static final ImmutableMap<String, String> NORMAL_CASES =
ImmutableMap.<String, String>builder()
.put("Foo", "foo")
.put("foo", "foo")
.put("X", "x")
.put("x", "x")
.put("", "")
.build();
@Test
public void decapitalizeLikeJavaBeans() {
NORMAL_CASES.forEach(
(input, output) ->
expect.that(PropertyNames.decapitalizeLikeJavaBeans(input)).isEqualTo(output));
expect.that(PropertyNames.decapitalizeLikeJavaBeans(null)).isNull();
expect.that(PropertyNames.decapitalizeLikeJavaBeans("HTMLPage")).isEqualTo("HTMLPage");
expect.that(PropertyNames.decapitalizeLikeJavaBeans("OAuth")).isEqualTo("OAuth");
}
@Test
public void decapitalizeNormally() {
NORMAL_CASES.forEach(
(input, output) ->
expect.that(PropertyNames.decapitalizeNormally(input)).isEqualTo(output));
expect.that(PropertyNames.decapitalizeNormally(null)).isNull();
expect.that(PropertyNames.decapitalizeNormally("HTMLPage")).isEqualTo("hTMLPage");
expect.that(PropertyNames.decapitalizeNormally("OAuth")).isEqualTo("oAuth");
}
}
|
PropertyNamesTest
|
java
|
processing__processing4
|
java/test/processing/mode/java/RuntimePathBuilderTest.java
|
{
"start": 1102,
"end": 4292
}
|
class ____ {
private RuntimePathBuilder builder;
private JavaMode testMode;
private List<ImportStatement> testImports;
private Sketch testSketch;
private PreprocSketch.Builder result;
@Before
public void setUp() throws Exception {
builder = new RuntimePathBuilder();
testMode = RuntimePathFactoryTestUtil.createTestJavaMode();
testImports = RuntimePathFactoryTestUtil.createTestImports();
testSketch = RuntimePathFactoryTestUtil.createTestSketch();
result = new PreprocSketch.Builder();
result.programImports.addAll(testImports);
result.sketch = testSketch;
builder.prepareClassPath(result, testMode);
}
@Test
public void testClassPathLoader() {
assertNotNull(result.classLoader);
}
@Test
public void testClassPathObj() {
assertNotNull(result.classPath);
}
@Test
public void testSketchClassPathStrategiesJava() {
checkPresent(result.classPathArray, "java.base.jmod");
}
@Test
public void testSketchClassPathStrategiesLibrary() {
checkPresent(result.classPathArray, "library3");
}
@Test
public void testSketchClassPathStrategiesCore() {
checkPresent(result.classPathArray, "library3");
}
@Test
public void testSketchClassPathStrategiesMode() {
checkPresent(result.classPathArray, "library6");
}
@Test
public void testSketchClassPathStrategiesCodeFolder() {
checkPresent(result.classPathArray, "file1.jar");
}
@Test
public void testSearchClassPathStrategiesCodeJava() {
checkPresent(result.searchClassPathArray, "java.base.jmod");
}
@Test
public void testSearchClassPathStrategiesCodeMode() {
checkPresent(result.classPathArray, "library6");
}
@Test
public void testSearchClassPathStrategiesCodeLibrary() {
checkPresent(result.classPathArray, "library3");
}
@Test
public void testSearchClassPathStrategiesCodeCore() {
checkPresent(result.classPathArray, "library1");
}
@Test
public void testSearchClassPathStrategiesCodeCodeFolder() {
checkPresent(result.classPathArray, "file3.zip");
}
private void checkPresent(String[] classPathArray, String target) {
long count = Arrays.stream(classPathArray)
.filter((x) -> x.contains(target))
.count();
assertTrue(count > 0);
}
@Test
public void sanitizeClassPath() {
StringJoiner testStrJoiner = new StringJoiner(File.pathSeparator);
testStrJoiner.add("test1");
testStrJoiner.add("");
testStrJoiner.add("test2");
List<String> classPath = builder.sanitizeClassPath(testStrJoiner.toString());
assertEquals(2, classPath.size());
assertEquals("test1", classPath.get(0));
assertEquals("test2", classPath.get(1));
}
@Test
public void sanitizeClassPathNoDuplicate() {
StringJoiner testStrJoiner = new StringJoiner(File.pathSeparator);
testStrJoiner.add("test1");
testStrJoiner.add("");
testStrJoiner.add("test2");
testStrJoiner.add("test2");
List<String> classPath = builder.sanitizeClassPath(testStrJoiner.toString());
assertEquals(2, classPath.size());
assertEquals("test1", classPath.get(0));
assertEquals("test2", classPath.get(1));
}
}
|
RuntimePathBuilderTest
|
java
|
apache__dubbo
|
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java
|
{
"start": 1433,
"end": 3210
}
|
class ____ {
private static final Logger logger = LoggerFactory.getLogger(TypeDefinitionBuilder.class);
public static List<TypeBuilder> BUILDERS;
public static void initBuilders(FrameworkModel model) {
Set<TypeBuilder> tbs = model.getExtensionLoader(TypeBuilder.class).getSupportedExtensionInstances();
BUILDERS = new ArrayList<>(tbs);
}
public static TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
TypeBuilder builder = getGenericTypeBuilder(clazz);
TypeDefinition td;
if (clazz.isPrimitive() || ClassUtils.isSimpleType(clazz)) { // changed since 2.7.6
td = new TypeDefinition(clazz.getCanonicalName());
typeCache.put(clazz.getCanonicalName(), td);
} else if (builder != null) {
td = builder.build(type, clazz, typeCache);
} else {
td = DefaultTypeBuilder.build(clazz, typeCache);
}
return td;
}
private static TypeBuilder getGenericTypeBuilder(Class<?> clazz) {
for (TypeBuilder builder : BUILDERS) {
try {
if (builder.accept(clazz)) {
return builder;
}
} catch (NoClassDefFoundError cnfe) {
// ignore
logger.info("Throw classNotFound (" + cnfe.getMessage() + ") in " + builder.getClass());
}
}
return null;
}
private final Map<String, TypeDefinition> typeCache = new HashMap<>();
public TypeDefinition build(Type type, Class<?> clazz) {
return build(type, clazz, typeCache);
}
public List<TypeDefinition> getTypeDefinitions() {
return new ArrayList<>(typeCache.values());
}
}
|
TypeDefinitionBuilder
|
java
|
quarkusio__quarkus
|
extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcJsonWebTokenProducer.java
|
{
"start": 869,
"end": 3488
}
|
class ____ {
private static final Logger LOG = Logger.getLogger(OidcJsonWebTokenProducer.class);
@Inject
SecurityIdentity identity;
/**
* The producer method for the current access token
*
* @return the access token
*/
@Produces
@RequestScoped
JsonWebToken currentAccessToken() {
return getTokenCredential(AccessTokenCredential.class);
}
/**
* The producer method for the current id token
*
* @return the id token
*/
@Produces
@IdToken
@RequestScoped
JsonWebToken currentIdToken() {
return getTokenCredential(IdTokenCredential.class);
}
private JsonWebToken getTokenCredential(Class<? extends TokenCredential> type) {
if (identity.isAnonymous()) {
return new NullJsonWebToken();
}
if (identity.getPrincipal() instanceof OidcJwtCallerPrincipal
&& ((OidcJwtCallerPrincipal) identity.getPrincipal()).getCredential().getClass() == type) {
return (JsonWebToken) identity.getPrincipal();
}
TokenCredential credential = OidcUtils.getTokenCredential(identity, type);
if (credential != null && credential.getToken() != null) {
if (credential instanceof AccessTokenCredential && ((AccessTokenCredential) credential).isOpaque()) {
throw new OIDCException("Opaque access token can not be converted to JsonWebToken");
}
JwtClaims jwtClaims;
try {
jwtClaims = new JwtConsumerBuilder()
.setSkipSignatureVerification()
.setSkipAllValidators()
.build().processToClaims(credential.getToken());
} catch (InvalidJwtException e) {
throw new OIDCException(e);
}
jwtClaims.setClaim(Claims.raw_token.name(), credential.getToken());
return new OidcJwtCallerPrincipal(jwtClaims, credential);
}
String tokenType = type == AccessTokenCredential.class ? "access" : "ID";
LOG.warnf(
"Identity is not associated with an %s token. Access 'JsonWebToken' with '@IdToken' qualifier if ID token is required and 'JsonWebToken' without this qualifier when JWT access token is required. Inject either 'io.quarkus.security.identity.SecurityIdentity' or 'io.quarkus.oidc.UserInfo' if you need to have the same endpoint code working for both authorization code and bearer token authentication flows.",
tokenType);
return new NullJsonWebToken();
}
}
|
OidcJsonWebTokenProducer
|
java
|
apache__camel
|
components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/batching/KafkaBatchingProcessingBreakOnFirstErrorManualCommitIT.java
|
{
"start": 1564,
"end": 6884
}
|
class ____ extends BatchingProcessingITSupport {
private static final Logger LOG = LoggerFactory.getLogger(KafkaBatchingProcessingBreakOnFirstErrorManualCommitIT.class);
public static final String TOPIC = "testBatchingProcessingBreakOnFirstErrorManualCommit";
private volatile boolean errorThrown = false;
@AfterEach
public void after() {
cleanupKafka(TOPIC);
}
@Override
protected RouteBuilder createRouteBuilder() {
String from = "kafka:" + TOPIC
+ "?groupId=KafkaBatchingProcessingBreakOnFirstErrorManualCommitIT"
+ "&pollTimeoutMs=1000"
+ "&batching=true"
+ "&maxPollRecords=10"
+ "&autoOffsetReset=earliest"
+ "&breakOnFirstError=true"
+ "&autoCommitEnable=false" // Test manual commit mode
+ "&allowManualCommit=true";
return new RouteBuilder() {
@Override
public void configure() {
onException(Exception.class)
.handled(false)
// Process the error and manually commit if needed
.process(exchange -> {
errorThrown = true;
LOG.info("Error occurred, performing manual commit");
doCommitOffset(exchange);
});
from(from).routeId("batching").process(e -> {
// The received records are stored as exchanges in a list. This gets the list of those exchanges
final List<?> exchanges = e.getMessage().getBody(List.class);
// Ensure we are actually receiving what we are asking for
if (exchanges == null || exchanges.isEmpty()) {
return;
}
// The records from the batch are stored in a list of exchanges in the original exchange.
int i = 0;
for (Object o : exchanges) {
if (o instanceof Exchange exchange) {
i++;
String body = exchange.getMessage().getBody(String.class);
LOG.info("Processing exchange with body {}", body);
// Throw exception on message-3 to test breakOnFirstError
if ("message-3".equals(body)) {
throw new RuntimeException(
"ERROR TRIGGERED BY TEST for breakOnFirstError in batching mode with manual commit");
}
}
}
}).to(KafkaTestUtil.MOCK_RESULT)
.process(exchange -> {
// Manual commit on success
doCommitOffset(exchange);
});
}
};
}
private void doCommitOffset(Exchange exchange) {
LOG.debug("Performing manual commit");
KafkaManualCommit manual = exchange.getMessage()
.getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class);
assertNotNull(manual);
manual.commit();
}
@Test
public void kafkaBreakOnFirstErrorInBatchingModeWithManualCommit() throws Exception {
to.reset();
to.expectedMinimumMessageCount(1);
// Send 6 messages where message-3 will cause an error
sendRecords(0, 6, TOPIC);
// Wait for the error to be thrown
Awaitility.await()
.atMost(10, TimeUnit.SECONDS)
.until(() -> errorThrown);
// With breakOnFirstError=true in batching mode with manual commit,
// the processing should stop when an error occurs and the error handler should commit
assertTrue(errorThrown, "Error should have been thrown on message-3");
// Reset error flag and send more messages to test reconnection
errorThrown = false;
to.reset();
to.expectedMinimumMessageCount(1);
// Send additional messages that should be processed after reconnection
// These messages don't contain "message-3" so should process successfully
sendRecords(20, 23, TOPIC); // message-20, message-21, message-22
// Wait for the new messages to be processed, indicating successful reconnection
Awaitility.await()
.atMost(15, TimeUnit.SECONDS)
.until(() -> to.getReceivedCounter() >= 1);
to.assertIsSatisfied(3000);
// Verify that no error was thrown for the second batch (reconnection successful)
assertFalse(errorThrown, "No error should be thrown for the second batch after reconnection");
// The route should have encountered the error, triggered breakOnFirstError,
// committed via the error handler, reconnected automatically, and continued processing new messages
// This verifies that the breakOnFirstError functionality works in batching mode with manual commit
// and that automatic reconnection occurs as expected
}
}
|
KafkaBatchingProcessingBreakOnFirstErrorManualCommitIT
|
java
|
apache__camel
|
core/camel-management/src/test/java/org/apache/camel/management/ManagedBrowsableEndpointAsXmlTest.java
|
{
"start": 1498,
"end": 17546
}
|
class ____ extends ManagementTestSupport {
@Test
public void testBrowseableEndpointAsXmlIncludeBody() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(7);
template.sendBody("direct:start", "<foo>Camel > Donkey</foo>");
template.sendBody("direct:start", "Camel > Donkey");
template.sendBodyAndHeader("direct:start", "<foo>Camel > Donkey</foo>", "name", "Me & You");
template.sendBodyAndHeader("direct:start", "<foo>Camel > Donkey</foo>", "title", "<title>Me & You</title>");
template.sendBodyAndHeader("direct:start", "Camel > Donkey", "name", "Me & You");
template.sendBodyAndHeader("direct:start", 123, "user", true);
Map<String, Object> headers = new HashMap<>();
headers.put("user", false);
headers.put("uid", 123);
headers.put("title", "Camel rocks");
template.sendBodyAndHeaders("direct:start", "<animal><name>Donkey</name><age>17</age></animal>", headers);
assertMockEndpointsSatisfied();
List<Exchange> exchanges = getMockEndpoint("mock:result").getReceivedExchanges();
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "mock://result");
String out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 0, true },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(0).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <body type=\"java.lang.String\"><foo>Camel &gt; Donkey</foo></body>\n</message>",
out);
out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 1, true },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(1).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <body type=\"java.lang.String\">Camel > Donkey</body>\n</message>",
out);
out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 2, true },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(2).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"name\" type=\"java.lang.String\">Me & You</header>\n </headers>\n"
+ " <body type=\"java.lang.String\"><foo>Camel &gt; Donkey</foo></body>\n</message>",
out);
out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 3, true },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals(
"<message exchangeId=\"" + exchanges.get(3).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\">\n <headers>\n"
+ " <header key=\"title\" type=\"java.lang.String\"><title>Me &amp; You</title></header>\n </headers>\n"
+ " <body type=\"java.lang.String\"><foo>Camel &gt; Donkey</foo></body>\n</message>",
out);
out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 4, true },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(4).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"name\" type=\"java.lang.String\">Me & You</header>\n </headers>\n"
+ " <body type=\"java.lang.String\">Camel > Donkey</body>\n</message>",
out);
out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 5, true },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(5).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"user\" type=\"java.lang.Boolean\">true</header>\n </headers>\n"
+ " <body type=\"java.lang.Integer\">123</body>\n</message>",
out);
out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 6, true },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(6).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"title\" type=\"java.lang.String\">Camel rocks</header>\n"
+ " <header key=\"uid\" type=\"java.lang.Integer\">123</header>\n"
+ " <header key=\"user\" type=\"java.lang.Boolean\">false</header>\n </headers>\n"
+ " <body type=\"java.lang.String\"><animal><name>Donkey</name><age>17</age></animal></body>\n</message>",
out);
}
@Test
public void testBrowseableEndpointAsXml() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(2);
template.sendBodyAndHeader("direct:start", "Hello World", "foo", 123);
template.sendBodyAndHeader("direct:start", "Bye World", "foo", 456);
assertMockEndpointsSatisfied();
List<Exchange> exchanges = getMockEndpoint("mock:result").getReceivedExchanges();
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "mock://result");
String out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 0, false },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(0).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"foo\" type=\"java.lang.Integer\">123</header>\n </headers>\n</message>",
out);
out = (String) mbeanServer.invoke(name, "browseMessageAsXml", new Object[] { 1, false },
new String[] { "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<message exchangeId=\"" + exchanges.get(1).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"foo\" type=\"java.lang.Integer\">456</header>\n </headers>\n</message>",
out);
}
@Test
public void testBrowseableEndpointAsXmlAllIncludeBody() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(2);
template.sendBody("direct:start", "Hello World");
template.sendBodyAndHeader("direct:start", "Bye World", "foo", 456);
assertMockEndpointsSatisfied();
List<Exchange> exchanges = getMockEndpoint("mock:result").getReceivedExchanges();
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "mock://result");
String out = (String) mbeanServer.invoke(name, "browseAllMessagesAsXml", new Object[] { true },
new String[] { "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<messages>\n<message exchangeId=\"" + exchanges.get(0).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <body type=\"java.lang.String\">Hello World</body>\n</message>\n"
+ "<message exchangeId=\"" + exchanges.get(1).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"foo\" type=\"java.lang.Integer\">456</header>\n </headers>\n"
+ " <body type=\"java.lang.String\">Bye World</body>\n</message>\n</messages>",
out);
}
@Test
public void testBrowseableEndpointAsXmlAll() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(2);
template.sendBodyAndHeader("direct:start", "Hello World", "foo", 123);
template.sendBodyAndHeader("direct:start", "Bye World", "foo", 456);
assertMockEndpointsSatisfied();
MBeanServer mbeanServer = getMBeanServer();
List<Exchange> exchanges = getMockEndpoint("mock:result").getReceivedExchanges();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "mock://result");
String out = (String) mbeanServer.invoke(name, "browseAllMessagesAsXml", new Object[] { false },
new String[] { "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<messages>\n<message exchangeId=\"" + exchanges.get(0).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\">\n <headers>\n"
+ " <header key=\"foo\" type=\"java.lang.Integer\">123</header>\n </headers>\n</message>\n"
+ "<message exchangeId=\"" + exchanges.get(1).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"foo\" type=\"java.lang.Integer\">456</header>\n </headers>\n"
+ "</message>\n</messages>",
out);
}
@Test
public void testBrowseableEndpointAsXmlRangeIncludeBody() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(3);
template.sendBody("direct:start", "Hello World");
template.sendBodyAndHeader("direct:start", "Bye World", "foo", 456);
template.sendBody("direct:start", "Hi Camel");
assertMockEndpointsSatisfied();
List<Exchange> exchanges = getMockEndpoint("mock:result").getReceivedExchanges();
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "mock://result");
String out = (String) mbeanServer.invoke(name, "browseRangeMessagesAsXml", new Object[] { 0, 1, true },
new String[] { "java.lang.Integer", "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<messages>\n<message exchangeId=\"" + exchanges.get(0).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <body type=\"java.lang.String\">Hello World</body>\n</message>\n"
+ "<message exchangeId=\"" + exchanges.get(1).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"foo\" type=\"java.lang.Integer\">456</header>\n </headers>\n"
+ " <body type=\"java.lang.String\">Bye World</body>\n</message>\n</messages>",
out);
}
@Test
public void testBrowseableEndpointAsXmlRange() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(3);
template.sendBodyAndHeader("direct:start", "Hello World", "foo", 123);
template.sendBodyAndHeader("direct:start", "Bye World", "foo", 456);
template.sendBody("direct:start", "Hi Camel");
assertMockEndpointsSatisfied();
List<Exchange> exchanges = getMockEndpoint("mock:result").getReceivedExchanges();
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "mock://result");
String out = (String) mbeanServer.invoke(name, "browseRangeMessagesAsXml", new Object[] { 0, 1, false },
new String[] { "java.lang.Integer", "java.lang.Integer", "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertEquals("<messages>\n<message exchangeId=\"" + exchanges.get(0).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"foo\" type=\"java.lang.Integer\">123</header>\n </headers>\n</message>\n"
+ "<message exchangeId=\"" + exchanges.get(1).getExchangeId()
+ "\" exchangePattern=\"InOnly\" exchangeType=\"org.apache.camel.support.DefaultExchange\" messageType=\"org.apache.camel.support.DefaultMessage\""
+ ">\n <headers>\n <header key=\"foo\" type=\"java.lang.Integer\">456</header>\n </headers>\n"
+ "</message>\n</messages>",
out);
}
@Test
public void testBrowseableEndpointAsXmlRangeInvalidIndex() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "mock://result");
try {
mbeanServer.invoke(name, "browseRangeMessagesAsXml", new Object[] { 3, 1, false },
new String[] { "java.lang.Integer", "java.lang.Integer", "java.lang.Boolean" });
fail("Should have thrown exception");
} catch (Exception e) {
assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
assertEquals("From index cannot be larger than to index, was: 3 > 1", e.getCause().getMessage());
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
context.setUseBreadcrumb(false);
from("direct:start").to("mock:result");
}
};
}
}
|
ManagedBrowsableEndpointAsXmlTest
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/leaderretrieval/TestingLeaderRetrievalEventHandler.java
|
{
"start": 1133,
"end": 1397
}
|
class ____ extends TestingRetrievalBase
implements LeaderRetrievalEventHandler {
@Override
public void notifyLeaderAddress(LeaderInformation leaderInformation) {
offerToLeaderQueue(leaderInformation);
}
}
|
TestingLeaderRetrievalEventHandler
|
java
|
apache__rocketmq
|
broker/src/main/java/org/apache/rocketmq/broker/metrics/ConsumerAttr.java
|
{
"start": 1021,
"end": 1870
}
|
class ____ {
String group;
LanguageCode language;
int version;
ConsumeType consumeMode;
public ConsumerAttr(String group, LanguageCode language, int version, ConsumeType consumeMode) {
this.group = group;
this.language = language;
this.version = version;
this.consumeMode = consumeMode;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ConsumerAttr attr = (ConsumerAttr) o;
return version == attr.version && Objects.equal(group, attr.group) && language == attr.language && consumeMode == attr.consumeMode;
}
@Override
public int hashCode() {
return Objects.hashCode(group, language, version, consumeMode);
}
}
|
ConsumerAttr
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-kms/src/test/java/org/apache/camel/component/aws2/kms/localstack/KmsEnableKeyIT.java
|
{
"start": 1467,
"end": 3953
}
|
class ____ extends Aws2KmsBase {
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void sendIn() throws Exception {
result.expectedMessageCount(1);
Exchange ex = template.send("direct:createKey", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(KMS2Constants.OPERATION, "createKey");
}
});
String keyId = ex.getMessage().getBody(CreateKeyResponse.class).keyMetadata().keyId();
template.send("direct:disableKey", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(KMS2Constants.OPERATION, "disableKey");
exchange.getIn().setHeader(KMS2Constants.KEY_ID, keyId);
}
});
template.send("direct:enableKey", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(KMS2Constants.OPERATION, "enableKey");
exchange.getIn().setHeader(KMS2Constants.KEY_ID, keyId);
}
});
template.send("direct:listKeys", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(KMS2Constants.OPERATION, "listKeys");
}
});
MockEndpoint.assertIsSatisfied(context);
assertEquals(1, result.getExchanges().size());
assertTrue(result.getExchanges().get(0).getIn().getBody(ListKeysResponse.class).hasKeys());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
String awsEndpoint
= "aws2-kms://default?operation=createKey";
String disableKey = "aws2-kms://default?operation=disableKey";
String enableKey = "aws2-kms://default?operation=enableKey";
String listKeys = "aws2-kms://default?operation=listKeys";
from("direct:createKey").to(awsEndpoint);
from("direct:disableKey").to(disableKey);
from("direct:enableKey").to(enableKey);
from("direct:listKeys").to(listKeys).to("mock:result");
}
};
}
}
|
KmsEnableKeyIT
|
java
|
grpc__grpc-java
|
servlet/src/jettyTest/java/io/grpc/servlet/GrpcServletSmokeTest.java
|
{
"start": 1970,
"end": 4461
}
|
class ____ {
private static final String HOST = "localhost";
private static final String MYAPP = "/grpc.testing.TestService";
@Rule
public final GrpcCleanupRule cleanupRule = new GrpcCleanupRule();
private final ScheduledExecutorService scheduledExecutorService =
Executors.newSingleThreadScheduledExecutor();
private int port;
private Server server;
@Before
public void startServer() {
BindableService service = new TestServiceImpl(scheduledExecutorService);
GrpcServlet grpcServlet = new GrpcServlet(ImmutableList.of(service));
server = new Server(0);
ServerConnector sc = (ServerConnector)server.getConnectors()[0];
HTTP2CServerConnectionFactory factory =
new HTTP2CServerConnectionFactory(new HttpConfiguration());
// Explicitly disable safeguards against malicious clients, as some unit tests trigger this
factory.setRateControlFactory(new RateControl.Factory() {});
sc.addConnectionFactory(factory);
ServletContextHandler context =
new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath(MYAPP);
context.addServlet(new ServletHolder(grpcServlet), "/*");
server.setHandler(context);
try {
server.start();
} catch (Exception e) {
throw new AssertionError(e);
}
port = sc.getLocalPort();
}
@After
public void tearDown() {
scheduledExecutorService.shutdown();
try {
server.stop();
} catch (Exception e) {
throw new AssertionError(e);
}
}
@Test
public void unaryCall() {
Channel channel = cleanupRule.register(
ManagedChannelBuilder.forAddress(HOST, port).usePlaintext().build());
SimpleResponse response = TestServiceGrpc.newBlockingStub(channel).unaryCall(
SimpleRequest.newBuilder()
.setResponseSize(1234)
.setPayload(Payload.newBuilder().setBody(ByteString.copyFromUtf8("hello foo")))
.build());
assertThat(response.getPayload().getBody().size()).isEqualTo(1234);
}
@Test
public void httpGetRequest() throws Exception {
HttpClient httpClient = new HttpClient();
try {
httpClient.start();
ContentResponse response =
httpClient.GET("http://" + HOST + ":" + port + MYAPP + "/UnaryCall");
assertThat(response.getStatus()).isEqualTo(405);
assertThat(response.getContentAsString()).contains("GET method not supported");
} finally {
httpClient.stop();
}
}
}
|
GrpcServletSmokeTest
|
java
|
quarkusio__quarkus
|
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/xml/hbm/HbmXmlQuarkusConfigTest.java
|
{
"start": 666,
"end": 1842
}
|
class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClass(SmokeTestUtils.class)
.addClass(SchemaUtil.class)
.addClass(NonAnnotatedEntity.class)
.addAsResource("application-mapping-files-my-hbm-xml.properties", "application.properties")
.addAsResource("META-INF/hbm-simple.xml", "my-hbm.xml"));
@Inject
EntityManagerFactory entityManagerFactory;
@Inject
EntityManager entityManager;
@Test
@Transactional
public void ormXmlTakenIntoAccount() {
assertThat(SchemaUtil.getColumnNames(entityManagerFactory, NonAnnotatedEntity.class))
.contains("thename")
.doesNotContain("name");
}
@Test
@Transactional
public void smokeTest() {
SmokeTestUtils.testSimplePersistRetrieveUpdateDelete(entityManager,
NonAnnotatedEntity.class, NonAnnotatedEntity::new,
NonAnnotatedEntity::getId, NonAnnotatedEntity::setName, NonAnnotatedEntity::getName);
}
}
|
HbmXmlQuarkusConfigTest
|
java
|
google__dagger
|
javatests/dagger/hilt/android/AndroidEntryPointBaseClassTest.java
|
{
"start": 3825,
"end": 4760
}
|
class ____ not actually assignable
// to the generated base classes at compile time
assertIsNotAssignableTo(
Hilt_AndroidEntryPointBaseClassTest_SSS.class,
Hilt_AndroidEntryPointBaseClassTest_S.class);
assertIsNotAssignableTo(
Hilt_AndroidEntryPointBaseClassTest_SS.class,
Hilt_AndroidEntryPointBaseClassTest_S.class);
}
@Test
public void checkGeneratedClassHierarchy_longForm() throws Exception {
// When using the long form notation, they are assignable at compile time
assertIsAssignableTo(
Hilt_AndroidEntryPointBaseClassTest_LLL.class,
Hilt_AndroidEntryPointBaseClassTest_LL.class);
assertIsAssignableTo(
Hilt_AndroidEntryPointBaseClassTest_LL.class,
Hilt_AndroidEntryPointBaseClassTest_L.class);
}
@Test
public void checkGeneratedClassHierarchy_shortFormRoot() throws Exception {
// If the root is short-form, then the child
|
is
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/monitor/fs/FsHealthServiceTests.java
|
{
"start": 15315,
"end": 16850
}
|
class ____ extends FilterFileSystemProvider {
AtomicBoolean injectIOException = new AtomicBoolean();
AtomicInteger injectedPaths = new AtomicInteger();
private String pathPrefix = null;
FileSystemFsyncIOExceptionProvider(FileSystem inner) {
super("disrupt_fs_health://", inner);
}
public void restrictPathPrefix(String pathPrefix) {
this.pathPrefix = pathPrefix;
}
public int getInjectedPathCount() {
return injectedPaths.get();
}
@Override
public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
return new FilterFileChannel(super.newFileChannel(path, options, attrs)) {
@Override
public void force(boolean metaData) throws IOException {
if (injectIOException.get()) {
assert pathPrefix != null : "must set pathPrefix before starting disruptions";
if (path.toString().startsWith(pathPrefix)
&& path.toString().endsWith(FsHealthService.FsHealthMonitor.TEMP_FILE_NAME)) {
injectedPaths.incrementAndGet();
throw new IOException("fake IOException");
}
}
super.force(metaData);
}
};
}
}
private static
|
FileSystemFsyncIOExceptionProvider
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/BeforeEachAndAfterEachComposedAnnotationTests.java
|
{
"start": 1674,
"end": 1766
}
|
interface ____ {
}
@AfterEach
@Retention(RetentionPolicy.RUNTIME)
private @
|
CustomBeforeEach
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassWithPlaceholderConfigurerBeanTests.java
|
{
"start": 5544,
"end": 5875
}
|
class ____ {
@Value("${test.name}")
private String name;
@Bean
public ITestBean testBean() {
return new TestBean(this.name);
}
@Bean
public PropertySourcesPlaceholderConfigurer ppc() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Configuration
static
|
ConfigWithValueFieldAndPlaceholderConfigurer
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-ses/src/test/java/org/apache/camel/component/aws2/ses/MockMessage.java
|
{
"start": 1151,
"end": 4374
}
|
class ____ extends Message {
@Override
public int getSize() {
return 0;
}
@Override
public int getLineCount() {
return 0;
}
@Override
public String getContentType() {
return null;
}
@Override
public boolean isMimeType(String mimeType) {
return false;
}
@Override
public String getDisposition() {
return null;
}
@Override
public void setDisposition(String disposition) {
}
@Override
public String getDescription() {
return null;
}
@Override
public void setDescription(String description) {
}
@Override
public String getFileName() {
return null;
}
@Override
public void setFileName(String filename) {
}
@Override
public InputStream getInputStream() {
return null;
}
@Override
public DataHandler getDataHandler() {
return null;
}
@Override
public Object getContent() {
return null;
}
@Override
public void setDataHandler(DataHandler dh) {
}
@Override
public void setContent(Object obj, String type) {
}
@Override
public void setText(String text) {
}
@Override
public void setContent(Multipart mp) {
}
@Override
public void writeTo(OutputStream os) {
}
@Override
public String[] getHeader(String headername) {
return null;
}
@Override
public void setHeader(String headername, String headervalue) {
}
@Override
public void addHeader(String headername, String headervalue) {
}
@Override
public void removeHeader(String headername) {
}
@Override
public Enumeration<Header> getAllHeaders() {
return null;
}
@Override
public Enumeration<Header> getMatchingHeaders(String[] headernames) {
return null;
}
@Override
public Enumeration<Header> getNonMatchingHeaders(String[] headernames) {
return null;
}
@Override
public Address[] getFrom() {
return null;
}
@Override
public void setFrom() {
}
@Override
public void setFrom(Address address) {
}
@Override
public void addFrom(Address[] addresses) {
}
@Override
public Address[] getRecipients(RecipientType type) {
return null;
}
@Override
public void setRecipients(RecipientType type, Address[] addresses) {
}
@Override
public void addRecipients(RecipientType type, Address[] addresses) {
}
@Override
public String getSubject() {
return null;
}
@Override
public void setSubject(String subject) {
}
@Override
public Date getSentDate() {
return null;
}
@Override
public void setSentDate(Date date) {
}
@Override
public Date getReceivedDate() {
return null;
}
@Override
public Flags getFlags() {
return null;
}
@Override
public void setFlags(Flags flag, boolean set) {
}
@Override
public Message reply(boolean replyToAll) {
return null;
}
@Override
public void saveChanges() {
}
}
|
MockMessage
|
java
|
apache__flink
|
flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/junit/extensions/parameterized/ParameterizedTestExtension.java
|
{
"start": 8152,
"end": 10658
}
|
class ____ implements ParameterResolver {
private final Object[] parameterValues;
public ConstructorParameterResolver(Object[] parameterValues) {
this.parameterValues = parameterValues;
}
@Override
public boolean supportsParameter(
ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return true;
}
@Override
public Object resolveParameter(
ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return parameterValues[parameterContext.getIndex()];
}
}
}
// -------------------------------- Helper functions -------------------------------------------
private Stream<TestTemplateInvocationContext> createContextForParameters(
Stream<Object[]> parameterValueStream,
String testNameTemplate,
ExtensionContext context) {
// Search fields annotated by @Parameter
final List<Field> parameterFields =
AnnotationSupport.findAnnotatedFields(
context.getRequiredTestClass(), Parameter.class);
// Use constructor parameter style
if (parameterFields.isEmpty()) {
return parameterValueStream.map(
parameterValue ->
new ConstructorParameterResolverInvocationContext(
testNameTemplate, parameterValue));
}
// Use field injection style
for (Field parameterField : parameterFields) {
final int index = parameterField.getAnnotation(Parameter.class).value();
context.getStore(NAMESPACE).put(getParameterFieldStoreKey(index), parameterField);
}
return parameterValueStream.map(
parameterValue ->
new FieldInjectingInvocationContext(testNameTemplate, parameterValue));
}
private static String getParameterFieldStoreKey(int parameterIndex) {
return PARAMETER_FIELD_STORE_KEY_PREFIX + parameterIndex;
}
private static Field getParameterField(int parameterIndex, ExtensionContext context) {
return (Field) context.getStore(NAMESPACE).get(getParameterFieldStoreKey(parameterIndex));
}
}
|
ConstructorParameterResolver
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMasterOperatorEventGateway.java
|
{
"start": 2360,
"end": 2724
}
|
interface ____ {
CompletableFuture<Acknowledge> sendOperatorEventToCoordinator(
ExecutionAttemptID task, OperatorID operatorID, SerializedValue<OperatorEvent> event);
CompletableFuture<CoordinationResponse> sendRequestToCoordinator(
OperatorID operatorID, SerializedValue<CoordinationRequest> request);
}
|
JobMasterOperatorEventGateway
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/timeline/TimelineEvent.java
|
{
"start": 1844,
"end": 4975
}
|
class ____ implements Comparable<TimelineEvent> {
private long timestamp;
private String eventType;
private HashMap<String, Object> eventInfo = new HashMap<String, Object>();
public TimelineEvent() {
}
/**
* Get the timestamp of the event
*
* @return the timestamp of the event
*/
@XmlElement(name = "timestamp")
public long getTimestamp() {
return timestamp;
}
/**
* Set the timestamp of the event
*
* @param timestamp
* the timestamp of the event
*/
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
/**
* Get the event type
*
* @return the event type
*/
@XmlElement(name = "eventtype")
public String getEventType() {
return eventType;
}
/**
* Set the event type
*
* @param eventType
* the event type
*/
public void setEventType(String eventType) {
this.eventType = eventType;
}
/**
* Set the information of the event
*
* @return the information of the event
*/
public Map<String, Object> getEventInfo() {
return eventInfo;
}
// Required by JAXB
@Private
@XmlElement(name = "eventinfo")
public HashMap<String, Object> getEventInfoJAXB() {
return eventInfo;
}
/**
* Add one piece of the information of the event to the existing information
* map
*
* @param key
* the information key
* @param value
* the information value
*/
public void addEventInfo(String key, Object value) {
this.eventInfo.put(key, value);
}
/**
* Add a map of the information of the event to the existing information map
*
* @param eventInfo
* a map of of the information of the event
*/
public void addEventInfo(Map<String, Object> eventInfo) {
this.eventInfo.putAll(eventInfo);
}
/**
* Set the information map to the given map of the information of the event
*
* @param eventInfo
* a map of of the information of the event
*/
public void setEventInfo(Map<String, Object> eventInfo) {
this.eventInfo = TimelineServiceHelper.mapCastToHashMap(
eventInfo);
}
@Override
public int compareTo(TimelineEvent other) {
if (timestamp > other.timestamp) {
return -1;
} else if (timestamp < other.timestamp) {
return 1;
} else {
return eventType.compareTo(other.eventType);
}
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
TimelineEvent event = (TimelineEvent) o;
if (timestamp != event.timestamp)
return false;
if (!eventType.equals(event.eventType))
return false;
if (eventInfo != null ? !eventInfo.equals(event.eventInfo) :
event.eventInfo != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (timestamp ^ (timestamp >>> 32));
result = 31 * result + eventType.hashCode();
result = 31 * result + (eventInfo != null ? eventInfo.hashCode() : 0);
return result;
}
}
|
TimelineEvent
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/annotation/AttributeMethodsTests.java
|
{
"start": 6472,
"end": 6578
}
|
interface ____ {
String one();
String two();
String three() default "3";
}
}
|
DefaultValueAttribute
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/cache/cfg/spi/DomainDataCachingConfig.java
|
{
"start": 361,
"end": 729
}
|
interface ____ {
/**
* The requested AccessType
*/
AccessType getAccessType();
/**
* Is the data marked as being mutable?
*/
boolean isMutable();
/**
* Is the data to be cached considered versioned?
*/
boolean isVersioned();
/**
* The {@link NavigableRole} of the thing to be cached
*/
NavigableRole getNavigableRole();
}
|
DomainDataCachingConfig
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/azureaistudio/rerank/AzureAiStudioRerankModel.java
|
{
"start": 1221,
"end": 3717
}
|
class ____ extends AzureAiStudioModel {
public static AzureAiStudioRerankModel of(AzureAiStudioRerankModel model, Map<String, Object> taskSettings) {
if (taskSettings == null || taskSettings.isEmpty()) {
return model;
}
final var requestTaskSettings = AzureAiStudioRerankRequestTaskSettings.fromMap(taskSettings);
final var taskSettingToUse = AzureAiStudioRerankTaskSettings.of(model.getTaskSettings(), requestTaskSettings);
return new AzureAiStudioRerankModel(model, taskSettingToUse);
}
public AzureAiStudioRerankModel(
String inferenceEntityId,
AzureAiStudioRerankServiceSettings serviceSettings,
AzureAiStudioRerankTaskSettings taskSettings,
DefaultSecretSettings secrets
) {
super(
new ModelConfigurations(inferenceEntityId, TaskType.RERANK, AzureAiStudioService.NAME, serviceSettings, taskSettings),
new ModelSecrets(secrets)
);
}
public AzureAiStudioRerankModel(
String inferenceEntityId,
Map<String, Object> serviceSettings,
Map<String, Object> taskSettings,
@Nullable Map<String, Object> secrets,
ConfigurationParseContext context
) {
this(
inferenceEntityId,
AzureAiStudioRerankServiceSettings.fromMap(serviceSettings, context),
AzureAiStudioRerankTaskSettings.fromMap(taskSettings),
DefaultSecretSettings.fromMap(secrets)
);
}
public AzureAiStudioRerankModel(AzureAiStudioRerankModel model, AzureAiStudioRerankTaskSettings taskSettings) {
super(model, taskSettings, model.getServiceSettings().rateLimitSettings());
}
@Override
public AzureAiStudioRerankServiceSettings getServiceSettings() {
return (AzureAiStudioRerankServiceSettings) super.getServiceSettings();
}
@Override
public AzureAiStudioRerankTaskSettings getTaskSettings() {
return (AzureAiStudioRerankTaskSettings) super.getTaskSettings();
}
@Override
public DefaultSecretSettings getSecretSettings() {
return super.getSecretSettings();
}
@Override
protected URI getEndpointUri() throws URISyntaxException {
return new URI(this.target + RERANK_URI_PATH);
}
@Override
public ExecutableAction accept(AzureAiStudioActionVisitor creator, Map<String, Object> taskSettings) {
return creator.create(this, taskSettings);
}
}
|
AzureAiStudioRerankModel
|
java
|
quarkusio__quarkus
|
extensions/flyway/deployment/src/test/java/db/migration/V1_0_1__Update.java
|
{
"start": 212,
"end": 522
}
|
class ____ extends BaseJavaMigration {
@Override
public void migrate(Context context) throws Exception {
try (Statement statement = context.getConnection().createStatement()) {
statement.executeUpdate("INSERT INTO quarked_flyway VALUES (1001, 'test')");
}
}
}
|
V1_0_1__Update
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ImpossibleNullComparisonTest.java
|
{
"start": 17958,
"end": 18366
}
|
class ____ {
public boolean o(Optional<String> o) {
return switch (o.get()) {
case null -> true;
case "" -> false;
default -> false;
};
}
}
""")
.addOutputLines(
"Test.java",
"""
import java.util.Optional;
public
|
Test
|
java
|
grpc__grpc-java
|
interop-testing/src/main/java/io/grpc/testing/integration/StressTestClient.java
|
{
"start": 22113,
"end": 22965
}
|
class ____ extends MetricsServiceGrpc.MetricsServiceImplBase {
@Override
public void getAllGauges(Metrics.EmptyMessage request,
StreamObserver<Metrics.GaugeResponse> responseObserver) {
for (Metrics.GaugeResponse gauge : gauges.values()) {
responseObserver.onNext(gauge);
}
responseObserver.onCompleted();
}
@Override
public void getGauge(Metrics.GaugeRequest request,
StreamObserver<Metrics.GaugeResponse> responseObserver) {
String gaugeName = request.getName();
Metrics.GaugeResponse gauge = gauges.get(gaugeName);
if (gauge != null) {
responseObserver.onNext(gauge);
responseObserver.onCompleted();
} else {
responseObserver.onError(new StatusException(Status.NOT_FOUND));
}
}
}
@VisibleForTesting
static
|
MetricsServiceImpl
|
java
|
quarkusio__quarkus
|
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/KotlinUtils.java
|
{
"start": 1522,
"end": 2715
}
|
class
____ isKotlinSuspendMethod(method)
&& (Modifier.isFinal(method.flags()) || Modifier.isFinal(method.declaringClass().flags()));
}
public static Type getKotlinSuspendMethodResult(MethodInfo method) {
if (!isKotlinSuspendMethod(method)) {
throw new IllegalArgumentException("Not a suspend function: " + method);
}
Type lastParameter = method.parameterType(method.parametersCount() - 1);
if (lastParameter.kind() != Type.Kind.PARAMETERIZED_TYPE) {
throw new IllegalArgumentException("Continuation parameter type not parameterized: " + lastParameter);
}
Type resultType = lastParameter.asParameterizedType().arguments().get(0);
if (resultType.kind() != Type.Kind.WILDCARD_TYPE) {
throw new IllegalArgumentException("Continuation parameter type argument not wildcard: " + resultType);
}
Type lowerBound = resultType.asWildcardType().superBound();
if (lowerBound == null) {
throw new IllegalArgumentException("Continuation parameter type argument without lower bound: " + resultType);
}
return lowerBound;
}
}
|
return
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/FileChannelOutputView.java
|
{
"start": 1503,
"end": 4935
}
|
class ____ extends AbstractPagedOutputView {
private final BlockChannelWriter<MemorySegment> writer; // the writer to the channel
private final MemoryManager memManager;
private final List<MemorySegment> memory;
private int numBlocksWritten;
private int bytesInLatestSegment;
// --------------------------------------------------------------------------------------------
public FileChannelOutputView(
BlockChannelWriter<MemorySegment> writer,
MemoryManager memManager,
List<MemorySegment> memory,
int segmentSize)
throws IOException {
super(segmentSize, 0);
checkNotNull(writer);
checkNotNull(memManager);
checkNotNull(memory);
checkArgument(!writer.isClosed());
this.writer = writer;
this.memManager = memManager;
this.memory = memory;
for (MemorySegment next : memory) {
writer.getReturnQueue().add(next);
}
// move to the first page
advance();
}
// --------------------------------------------------------------------------------------------
/**
* Closes this output, writing pending data and releasing the memory.
*
* @throws IOException Thrown, if the pending data could not be written.
*/
public void close() throws IOException {
close(false);
}
/**
* Closes this output, writing pending data and releasing the memory.
*
* @throws IOException Thrown, if the pending data could not be written.
*/
public void closeAndDelete() throws IOException {
close(true);
}
private void close(boolean delete) throws IOException {
try {
// send off set last segment, if we have not been closed before
MemorySegment current = getCurrentSegment();
if (current != null) {
writeSegment(current, getCurrentPositionInSegment());
}
clear();
if (delete) {
writer.closeAndDelete();
} else {
writer.close();
}
} finally {
memManager.release(memory);
}
}
// --------------------------------------------------------------------------------------------
/**
* Gets the number of blocks written by this output view.
*
* @return The number of blocks written by this output view.
*/
public int getBlockCount() {
return numBlocksWritten;
}
/**
* Gets the number of bytes written in the latest memory segment.
*
* @return The number of bytes written in the latest memory segment.
*/
public int getBytesInLatestSegment() {
return bytesInLatestSegment;
}
public long getWriteOffset() {
return ((long) numBlocksWritten) * segmentSize + getCurrentPositionInSegment();
}
@Override
protected MemorySegment nextSegment(MemorySegment current, int posInSegment)
throws IOException {
if (current != null) {
writeSegment(current, posInSegment);
}
return writer.getNextReturnedBlock();
}
private void writeSegment(MemorySegment segment, int writePosition) throws IOException {
writer.writeBlock(segment);
numBlocksWritten++;
bytesInLatestSegment = writePosition;
}
}
|
FileChannelOutputView
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/bulk/FailureStoreDocumentConverterTests.java
|
{
"start": 1222,
"end": 5824
}
|
class ____ extends ESTestCase {
public void testFailureStoreDocumentConversion() throws Exception {
IndexRequest source = new IndexRequest("original_index").routing("fake_routing")
.id("1")
.source(JsonXContent.contentBuilder().startObject().field("key", "value").endObject());
// The exception will be wrapped for the test to make sure the converter correctly unwraps it
ElasticsearchException exception = new ElasticsearchException("Test exception please ignore");
ElasticsearchException ingestException = exception;
if (randomBoolean()) {
ingestException = new ElasticsearchException("Test suppressed exception, please ignore");
exception.addSuppressed(ingestException);
}
boolean withPipelineOrigin = randomBoolean();
if (withPipelineOrigin) {
ingestException.addBodyHeader(
CompoundProcessor.PIPELINE_ORIGIN_EXCEPTION_HEADER,
Arrays.asList("some-failing-pipeline", "some-pipeline")
);
}
boolean withProcessorTag = randomBoolean();
if (withProcessorTag) {
ingestException.addBodyHeader(CompoundProcessor.PROCESSOR_TAG_EXCEPTION_HEADER, "foo-tag");
}
boolean withProcessorType = randomBoolean();
if (withProcessorType) {
ingestException.addBodyHeader(CompoundProcessor.PROCESSOR_TYPE_EXCEPTION_HEADER, "bar-type");
}
if (randomBoolean()) {
exception = new RemoteTransportException("Test exception wrapper, please ignore", exception);
}
String targetIndexName = "rerouted_index";
long testTime = 1702357200000L; // 2023-12-12T05:00:00.000Z
IndexRequest convertedRequest = new FailureStoreDocumentConverter().transformFailedRequest(
source,
exception,
targetIndexName,
() -> testTime
);
// Retargeting write
assertThat(convertedRequest.id(), is(nullValue()));
assertThat(convertedRequest.routing(), is(nullValue()));
assertThat(convertedRequest.index(), is(equalTo(targetIndexName)));
assertThat(convertedRequest.opType(), is(DocWriteRequest.OpType.CREATE));
// Original document content is no longer in same place
assertThat("Expected original document to be modified", convertedRequest.sourceAsMap().get("key"), is(nullValue()));
// Assert document contents
assertThat(ObjectPath.eval("@timestamp", convertedRequest.sourceAsMap()), is(equalTo("2023-12-12T05:00:00.000Z")));
assertThat(ObjectPath.eval("document.id", convertedRequest.sourceAsMap()), is(equalTo("1")));
assertThat(ObjectPath.eval("document.routing", convertedRequest.sourceAsMap()), is(equalTo("fake_routing")));
assertThat(ObjectPath.eval("document.index", convertedRequest.sourceAsMap()), is(equalTo("original_index")));
assertThat(ObjectPath.eval("document.source.key", convertedRequest.sourceAsMap()), is(equalTo("value")));
assertThat(ObjectPath.eval("error.type", convertedRequest.sourceAsMap()), is(equalTo("exception")));
assertThat(ObjectPath.eval("error.message", convertedRequest.sourceAsMap()), is(equalTo("Test exception please ignore")));
assertThat(
ObjectPath.eval("error.stack_trace", convertedRequest.sourceAsMap()),
startsWith("o.e.ElasticsearchException: Test exception please ignore")
);
assertThat(
ObjectPath.eval("error.stack_trace", convertedRequest.sourceAsMap()),
containsString("at o.e.a.b.FailureStoreDocumentConverterTests.testFailureStoreDocumentConversion")
);
assertThat(
ObjectPath.eval("error.pipeline_trace", convertedRequest.sourceAsMap()),
is(equalTo(withPipelineOrigin ? List.of("some-pipeline", "some-failing-pipeline") : null))
);
assertThat(
ObjectPath.eval("error.pipeline", convertedRequest.sourceAsMap()),
is(equalTo(withPipelineOrigin ? "some-failing-pipeline" : null))
);
assertThat(
ObjectPath.eval("error.processor_tag", convertedRequest.sourceAsMap()),
is(equalTo(withProcessorTag ? "foo-tag" : null))
);
assertThat(
ObjectPath.eval("error.processor_type", convertedRequest.sourceAsMap()),
is(equalTo(withProcessorType ? "bar-type" : null))
);
assertThat(convertedRequest.isWriteToFailureStore(), is(true));
}
}
|
FailureStoreDocumentConverterTests
|
java
|
apache__camel
|
components/camel-pgevent/src/main/java/org/apache/camel/component/pgevent/InvalidStateException.java
|
{
"start": 855,
"end": 1100
}
|
class ____ extends RuntimeException {
public InvalidStateException(String message) {
super(message);
}
public InvalidStateException(String message, Throwable cause) {
super(message, cause);
}
}
|
InvalidStateException
|
java
|
apache__maven
|
compat/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/relocation/DistributionManagementArtifactRelocationSource.java
|
{
"start": 1931,
"end": 3322
}
|
class ____ implements MavenArtifactRelocationSource {
public static final String NAME = "distributionManagement";
private static final Logger LOGGER = LoggerFactory.getLogger(DistributionManagementArtifactRelocationSource.class);
@Override
public Artifact relocatedTarget(
RepositorySystemSession session, ArtifactDescriptorResult artifactDescriptorResult, Model model) {
DistributionManagement distMgmt = model.getDistributionManagement();
if (distMgmt != null) {
Relocation relocation = distMgmt.getRelocation();
if (relocation != null) {
Artifact result = new RelocatedArtifact(
artifactDescriptorResult.getRequest().getArtifact(),
relocation.getGroupId(),
relocation.getArtifactId(),
null,
null,
relocation.getVersion(),
relocation.getMessage());
LOGGER.debug(
"The artifact {} has been relocated to {}: {}",
artifactDescriptorResult.getRequest().getArtifact(),
result,
relocation.getMessage());
return result;
}
}
return null;
}
}
|
DistributionManagementArtifactRelocationSource
|
java
|
apache__spark
|
streaming/src/test/java/org/apache/spark/streaming/JavaDurationSuite.java
|
{
"start": 924,
"end": 2426
}
|
class ____ {
// Just testing the methods that are specially exposed for Java.
// This does not repeat all tests found in the Scala suite.
@Test
public void testLess() {
Assertions.assertTrue(new Duration(999).less(new Duration(1000)));
}
@Test
public void testLessEq() {
Assertions.assertTrue(new Duration(1000).lessEq(new Duration(1000)));
}
@Test
public void testGreater() {
Assertions.assertTrue(new Duration(1000).greater(new Duration(999)));
}
@Test
public void testGreaterEq() {
Assertions.assertTrue(new Duration(1000).greaterEq(new Duration(1000)));
}
@Test
public void testPlus() {
Assertions.assertEquals(new Duration(1100), new Duration(1000).plus(new Duration(100)));
}
@Test
public void testMinus() {
Assertions.assertEquals(new Duration(900), new Duration(1000).minus(new Duration(100)));
}
@Test
public void testTimes() {
Assertions.assertEquals(new Duration(200), new Duration(100).times(2));
}
@Test
public void testDiv() {
Assertions.assertEquals(200.0, new Duration(1000).div(new Duration(5)), 1.0e-12);
}
@Test
public void testMilliseconds() {
Assertions.assertEquals(new Duration(100), Durations.milliseconds(100));
}
@Test
public void testSeconds() {
Assertions.assertEquals(new Duration(30 * 1000), Durations.seconds(30));
}
@Test
public void testMinutes() {
Assertions.assertEquals(new Duration(2 * 60 * 1000), Durations.minutes(2));
}
}
|
JavaDurationSuite
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/orderby/OrderByTest.java
|
{
"start": 1395,
"end": 3228
}
|
class ____ {
@BeforeEach
protected void prepareTest(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.persist( new P1( 1L, "abc" ) );
session.persist( new P1( 2L, "abc" ) );
session.persist( new P2( 3L, "def" ) );
Group g1 = new Group();
g1.setName( "g1" );
Group g2 = new Group();
g2.setName( "g2" );
Set<Group> groups = new HashSet();
groups.add( g1 );
groups.add( g2 );
User u = new User();
u.setGroups( groups );
session.persist( u );
Task t = new Task();
t.setId( 1L );
TaskVersion tv1 = new TaskVersion();
tv1.setName("tv1");
tv1.setAssignee(u);
List<TaskVersion> versions = new ArrayList<>();
versions.add( tv1 );
t.setTaskVersions( versions );
tv1.setTask(t);
TaskVersion tv2 = new TaskVersion();
tv2.setName("tv2");
tv2.setAssignee(u);
t.getTaskVersions().add(tv2);
tv2.setTask(t);
session.persist( t );
}
);
}
@AfterEach
protected void cleanupTest(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
@JiraKey(value = "HHH-14351")
public void testOrderBySqlNode(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
List<Person> list = session.createQuery( "from Person p order by type(p) desc, p.id", Person.class )
.getResultList();
assertEquals( 3L, list.get( 0 ).getId().longValue() );
assertEquals( 1L, list.get( 1 ).getId().longValue() );
assertEquals( 2L, list.get( 2 ).getId().longValue() );
}
);
}
@Test
@JiraKey( value = "HHH-15885")
public void testOrderBy(SessionFactoryScope scope) {
scope.inSession(
session -> {
session.get(Task.class, 1L);
}
);
}
@Entity(name = "Person")
public static abstract
|
OrderByTest
|
java
|
quarkusio__quarkus
|
core/deployment/src/main/java/io/quarkus/deployment/steps/CurateOutcomeBuildStep.java
|
{
"start": 491,
"end": 1313
}
|
class ____ {
BootstrapConfig config;
@BuildStep
CurateOutcomeBuildItem curateOutcome(AppModelProviderBuildItem appModelProvider) {
return new CurateOutcomeBuildItem(appModelProvider.validateAndGet(config));
}
@BuildStep
void removeResources(CurateOutcomeBuildItem curateOutcome,
BuildProducer<RemovedResourceBuildItem> removedResourceProducer) {
final Map<ArtifactKey, Set<String>> excludedResources = curateOutcome.getApplicationModel().getRemovedResources();
if (!excludedResources.isEmpty()) {
for (Map.Entry<ArtifactKey, Set<String>> removed : excludedResources.entrySet()) {
removedResourceProducer.produce(new RemovedResourceBuildItem(removed.getKey(), removed.getValue()));
}
}
}
}
|
CurateOutcomeBuildStep
|
java
|
elastic__elasticsearch
|
modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextInfo.java
|
{
"start": 1435,
"end": 10612
}
|
class ____ implements Writeable, ToXContentObject {
public static final ParseField NAME = new ParseField("name");
public static final ParseField CLASSES = new ParseField("classes");
public static final ParseField IMPORTED_METHODS = new ParseField("imported_methods");
public static final ParseField CLASS_BINDINGS = new ParseField("class_bindings");
public static final ParseField INSTANCE_BINDINGS = new ParseField("instance_bindings");
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<PainlessContextInfo, Void> PARSER = new ConstructingObjectParser<>(
PainlessContextInfo.class.getCanonicalName(),
(v) -> new PainlessContextInfo(
(String) v[0],
(List<PainlessContextClassInfo>) v[1],
(List<PainlessContextMethodInfo>) v[2],
(List<PainlessContextClassBindingInfo>) v[3],
(List<PainlessContextInstanceBindingInfo>) v[4]
)
);
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME);
PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), (p, c) -> PainlessContextClassInfo.fromXContent(p), CLASSES);
PARSER.declareObjectArray(
ConstructingObjectParser.constructorArg(),
(p, c) -> PainlessContextMethodInfo.fromXContent(p),
IMPORTED_METHODS
);
PARSER.declareObjectArray(
ConstructingObjectParser.constructorArg(),
(p, c) -> PainlessContextClassBindingInfo.fromXContent(p),
CLASS_BINDINGS
);
PARSER.declareObjectArray(
ConstructingObjectParser.constructorArg(),
(p, c) -> PainlessContextInstanceBindingInfo.fromXContent(p),
INSTANCE_BINDINGS
);
}
private final String name;
private final List<PainlessContextClassInfo> classes;
private final List<PainlessContextMethodInfo> importedMethods;
private final List<PainlessContextClassBindingInfo> classBindings;
private final List<PainlessContextInstanceBindingInfo> instanceBindings;
public PainlessContextInfo(ScriptContext<?> scriptContext, PainlessLookup painlessLookup) {
this(
scriptContext.name,
painlessLookup.getClasses()
.stream()
.map(
javaClass -> new PainlessContextClassInfo(
javaClass,
javaClass == painlessLookup.canonicalTypeNameToType(
javaClass.getName().substring(javaClass.getName().lastIndexOf('.') + 1).replace('$', '.')
),
painlessLookup.lookupPainlessClass(javaClass)
)
)
.collect(Collectors.toList()),
painlessLookup.getImportedPainlessMethodsKeys().stream().map(importedPainlessMethodKey -> {
String[] split = importedPainlessMethodKey.split("/");
String importedPainlessMethodName = split[0];
int importedPainlessMethodArity = Integer.parseInt(split[1]);
PainlessMethod importedPainlessMethod = painlessLookup.lookupImportedPainlessMethod(
importedPainlessMethodName,
importedPainlessMethodArity
);
return new PainlessContextMethodInfo(importedPainlessMethod);
}).collect(Collectors.toList()),
painlessLookup.getPainlessClassBindingsKeys().stream().map(painlessClassBindingKey -> {
String[] split = painlessClassBindingKey.split("/");
String painlessClassBindingName = split[0];
int painlessClassBindingArity = Integer.parseInt(split[1]);
PainlessClassBinding painlessClassBinding = painlessLookup.lookupPainlessClassBinding(
painlessClassBindingName,
painlessClassBindingArity
);
return new PainlessContextClassBindingInfo(painlessClassBinding);
}).collect(Collectors.toList()),
painlessLookup.getPainlessInstanceBindingsKeys().stream().map(painlessInstanceBindingKey -> {
String[] split = painlessInstanceBindingKey.split("/");
String painlessInstanceBindingName = split[0];
int painlessInstanceBindingArity = Integer.parseInt(split[1]);
PainlessInstanceBinding painlessInstanceBinding = painlessLookup.lookupPainlessInstanceBinding(
painlessInstanceBindingName,
painlessInstanceBindingArity
);
return new PainlessContextInstanceBindingInfo(painlessInstanceBinding);
}).collect(Collectors.toList())
);
}
public PainlessContextInfo(
String name,
List<PainlessContextClassInfo> classes,
List<PainlessContextMethodInfo> importedMethods,
List<PainlessContextClassBindingInfo> classBindings,
List<PainlessContextInstanceBindingInfo> instanceBindings
) {
this.name = Objects.requireNonNull(name);
classes = new ArrayList<>(Objects.requireNonNull(classes));
classes.sort(Comparator.comparing(PainlessContextClassInfo::getSortValue));
this.classes = Collections.unmodifiableList(classes);
importedMethods = new ArrayList<>(Objects.requireNonNull(importedMethods));
importedMethods.sort(Comparator.comparing(PainlessContextMethodInfo::getSortValue));
this.importedMethods = Collections.unmodifiableList(importedMethods);
classBindings = new ArrayList<>(Objects.requireNonNull(classBindings));
classBindings.sort(Comparator.comparing(PainlessContextClassBindingInfo::getSortValue));
this.classBindings = Collections.unmodifiableList(classBindings);
instanceBindings = new ArrayList<>(Objects.requireNonNull(instanceBindings));
instanceBindings.sort(Comparator.comparing(PainlessContextInstanceBindingInfo::getSortValue));
this.instanceBindings = Collections.unmodifiableList(instanceBindings);
}
public PainlessContextInfo(StreamInput in) throws IOException {
name = in.readString();
classes = in.readCollectionAsImmutableList(PainlessContextClassInfo::new);
importedMethods = in.readCollectionAsImmutableList(PainlessContextMethodInfo::new);
classBindings = in.readCollectionAsImmutableList(PainlessContextClassBindingInfo::new);
instanceBindings = in.readCollectionAsImmutableList(PainlessContextInstanceBindingInfo::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeCollection(classes);
out.writeCollection(importedMethods);
out.writeCollection(classBindings);
out.writeCollection(instanceBindings);
}
public static PainlessContextInfo fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(NAME.getPreferredName(), name);
builder.field(CLASSES.getPreferredName(), classes);
builder.field(IMPORTED_METHODS.getPreferredName(), importedMethods);
builder.field(CLASS_BINDINGS.getPreferredName(), classBindings);
builder.field(INSTANCE_BINDINGS.getPreferredName(), instanceBindings);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PainlessContextInfo that = (PainlessContextInfo) o;
return Objects.equals(name, that.name)
&& Objects.equals(classes, that.classes)
&& Objects.equals(importedMethods, that.importedMethods)
&& Objects.equals(classBindings, that.classBindings)
&& Objects.equals(instanceBindings, that.instanceBindings);
}
@Override
public int hashCode() {
return Objects.hash(name, classes, importedMethods, classBindings, instanceBindings);
}
@Override
public String toString() {
return "PainlessContextInfo{"
+ "name='"
+ name
+ '\''
+ ", classes="
+ classes
+ ", importedMethods="
+ importedMethods
+ ", classBindings="
+ classBindings
+ ", instanceBindings="
+ instanceBindings
+ '}';
}
public String getName() {
return name;
}
public List<PainlessContextClassInfo> getClasses() {
return classes;
}
public List<PainlessContextMethodInfo> getImportedMethods() {
return importedMethods;
}
public List<PainlessContextClassBindingInfo> getClassBindings() {
return classBindings;
}
public List<PainlessContextInstanceBindingInfo> getInstanceBindings() {
return instanceBindings;
}
}
|
PainlessContextInfo
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ext/javatime/deser/ZonedDateTimeDeserTest.java
|
{
"start": 806,
"end": 1310
}
|
class ____ extends DateTimeTestBase
{
private final ObjectReader READER = newMapper().readerFor(ZonedDateTime.class);
private final ObjectReader READER_NON_NORMALIZED_ZONEID = JsonMapper.builder()
.disable(DateTimeFeature.NORMALIZE_DESERIALIZED_ZONE_ID)
.build()
.readerFor(ZonedDateTime.class);
private final TypeReference<Map<String, ZonedDateTime>> MAP_TYPE_REF = new TypeReference<Map<String, ZonedDateTime>>() { };
static
|
ZonedDateTimeDeserTest
|
java
|
apache__flink
|
flink-clients/src/test/java/org/apache/flink/client/testjar/BlockingJob.java
|
{
"start": 1603,
"end": 3822
}
|
class ____ {
private static final ConcurrentMap<String, CountDownLatch> RUNNING = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, CountDownLatch> BLOCKED = new ConcurrentHashMap<>();
public static PackagedProgram getProgram(String blockId) throws FlinkException {
try {
return PackagedProgram.newBuilder()
.setUserClassPaths(
Collections.singletonList(
new File(CliFrontendTestUtils.getTestJarPath())
.toURI()
.toURL()))
.setEntryPointClassName(BlockingJob.class.getName())
.setArguments(blockId)
.build();
} catch (ProgramInvocationException | FileNotFoundException | MalformedURLException e) {
throw new FlinkException("Could not load the provided entrypoint class.", e);
}
}
public static void cleanUp(String blockId) {
RUNNING.remove(blockId);
BLOCKED.remove(blockId);
}
public static void awaitRunning(String blockId) throws InterruptedException {
RUNNING.computeIfAbsent(blockId, ignored -> new CountDownLatch(1)).await();
}
public static void unblock(String blockId) {
BLOCKED.computeIfAbsent(blockId, ignored -> new CountDownLatch(1)).countDown();
}
public static void main(String[] args) throws Exception {
final String blockId = args[0];
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.fromData(1, 2, 3)
.map(element -> element + 1)
.map(
element -> {
RUNNING.computeIfAbsent(blockId, ignored -> new CountDownLatch(1))
.countDown();
BLOCKED.computeIfAbsent(blockId, ignored -> new CountDownLatch(1))
.await();
return element;
})
.sinkTo(new DiscardingSink<>());
env.execute();
}
}
|
BlockingJob
|
java
|
elastic__elasticsearch
|
plugins/examples/stable-analysis/src/main/java/org/elasticsearch/example/analysis/CustomAnalyzerFactory.java
|
{
"start": 1346,
"end": 2359
}
|
class ____ extends Analyzer {
private final ExampleAnalysisSettings settings;
public CustomAnalyzer(ExampleAnalysisSettings settings) {
this.settings = settings;
}
@Override
protected TokenStreamComponents createComponents(String fieldName) {
var tokenizerListOfChars = settings.singleCharsToSkipInTokenizer().isEmpty() ? List.of("_") : settings.singleCharsToSkipInTokenizer();
var tokenizer = new CharSkippingTokenizer(tokenizerListOfChars);
long tokenFilterNumber = settings.analyzerUseTokenListOfChars() ? settings.digitToSkipInTokenFilter() : -1;
var tokenFilter = new SkipStartingWithDigitTokenFilter(tokenizer, tokenFilterNumber);
return new TokenStreamComponents(
r -> tokenizer.setReader(new ReplaceCharToNumber(r, settings.oldCharToReplaceInCharFilter(), settings.newNumberToReplaceInCharFilter())),
tokenFilter
);
}
}
}
|
CustomAnalyzer
|
java
|
micronaut-projects__micronaut-core
|
inject-java/src/test/groovy/io/micronaut/inject/scope/custom/interceptors/InterceptorScopeTest.java
|
{
"start": 3498,
"end": 3693
}
|
class ____ extends NoSuchBeanException {
protected NoMyScopedKeyException() {
super("No my scoped key present");
}
}
@Singleton
static
|
NoMyScopedKeyException
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingDuplicateTest.java
|
{
"start": 3121,
"end": 4437
}
|
class ____ {
@Id
@GeneratedValue
private Long id;
@Column(name = "sale_number")
private String number;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "saleDocument")
private Set<SaleDocumentItem> items = new HashSet<>();
@JoinColumn(name = "ID_SALE_DOCUMENT_CORRECTION", nullable = true)
@ManyToOne(fetch = FetchType.LAZY)
private SaleDocument corerctionsubject;
private BigDecimal totalPrice;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Set<SaleDocumentItem> getItems() {
return items;
}
public void setItems(Set<SaleDocumentItem> items) {
this.items = items;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public void addItem(SaleDocumentItem sdi) {
this.getItems().add( sdi );
sdi.setSaleDocument( this );
}
public SaleDocument getCorerctionsubject() {
return corerctionsubject;
}
public void setCorerctionsubject(SaleDocument corerctionsubject) {
this.corerctionsubject = corerctionsubject;
}
}
@Entity(name = "SaleDocumentItem")
public
|
SaleDocument
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/date/DateAssert_isEqualTo_Test.java
|
{
"start": 1662,
"end": 2831
}
|
class ____ {
@ParameterizedTest
@MethodSource
void should_pass(Date actual, Object expected) {
// WHEN/THEN
assertThat(actual).isEqualTo(expected);
}
Stream<Arguments> should_pass() {
return Stream.of(arguments(Date.from(Instant.parse("1970-01-01T00:00:00.000000001Z")),
Date.from(Instant.parse("1970-01-01T00:00:00.000000001Z"))),
arguments(Date.from(Instant.parse("1970-01-01T00:00:00.000000001Z")),
Timestamp.from(Instant.parse("1970-01-01T00:00:00.000000001Z"))));
}
@ParameterizedTest
@MethodSource
void should_fail(Date actual, Object expected) {
// WHEN
var error = expectAssertionError(() -> assertThat(actual).isEqualTo(expected));
// THEN
then(error).isInstanceOf(AssertionFailedError.class);
}
Stream<Arguments> should_fail() {
return Stream.of(arguments(Timestamp.from(Instant.parse("1970-01-01T00:00:00.000000001Z")),
Date.from(Instant.parse("1970-01-01T00:00:00.000000001Z"))));
}
}
@Nested
@TestInstance(PER_CLASS)
|
With_Object
|
java
|
spring-projects__spring-boot
|
module/spring-boot-graphql/src/test/java/org/springframework/boot/graphql/autoconfigure/reactive/GraphQlWebFluxAutoConfigurationTests.java
|
{
"start": 11902,
"end": 12374
}
|
class ____ {
@Bean
RuntimeWiringConfigurer bookDataFetcher() {
return (builder) -> {
builder.type(TypeRuntimeWiring.newTypeWiring("Query")
.dataFetcher("bookById", GraphQlTestDataFetchers.getBookByIdDataFetcher()));
builder.type(TypeRuntimeWiring.newTypeWiring("Subscription")
.dataFetcher("booksOnSale", GraphQlTestDataFetchers.getBooksOnSaleDataFetcher()));
};
}
}
@Configuration(proxyBeanMethods = false)
static
|
DataFetchersConfiguration
|
java
|
quarkusio__quarkus
|
extensions/security-webauthn/deployment/src/test/java/io/quarkus/security/webauthn/test/WebAuthnBlockingTestUserProvider.java
|
{
"start": 546,
"end": 1499
}
|
class ____ extends WebAuthnTestUserProvider {
@Override
public Uni<WebAuthnCredentialRecord> findByCredentialId(String credId) {
assertBlockingAllowed();
return super.findByCredentialId(credId);
}
@Override
public Uni<List<WebAuthnCredentialRecord>> findByUsername(String userId) {
assertBlockingAllowed();
return super.findByUsername(userId);
}
@Override
public Uni<Void> update(String credentialId, long counter) {
assertBlockingAllowed();
return super.update(credentialId, counter);
}
@Override
public Uni<Void> store(WebAuthnCredentialRecord credentialRecord) {
assertBlockingAllowed();
return super.store(credentialRecord);
}
private void assertBlockingAllowed() {
if (!BlockingOperationSupport.isBlockingAllowed())
throw new RuntimeException("Blocking is not allowed");
}
}
|
WebAuthnBlockingTestUserProvider
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/optimizer/Optimizer.java
|
{
"start": 44628,
"end": 45942
}
|
class ____ extends OptimizerBasicRule {
@Override
public LogicalPlan apply(LogicalPlan p) {
Map<PercentileKey, Set<Expression>> percentsPerAggKey = new LinkedHashMap<>();
p.forEachExpressionUp(
Percentile.class,
per -> percentsPerAggKey.computeIfAbsent(new PercentileKey(per), v -> new LinkedHashSet<>()).add(per.percent())
);
// create a Percentile agg for each agg key
Map<PercentileKey, Percentiles> percentilesPerAggKey = new LinkedHashMap<>();
percentsPerAggKey.forEach(
(aggKey, percents) -> percentilesPerAggKey.put(
aggKey,
new Percentiles(
percents.iterator().next().source(),
aggKey.field(),
new ArrayList<>(percents),
aggKey.percentilesConfig()
)
)
);
return p.transformExpressionsUp(Percentile.class, per -> {
PercentileKey a = new PercentileKey(per);
Percentiles percentiles = percentilesPerAggKey.get(a);
return new InnerAggregate(per, percentiles);
});
}
}
static
|
ReplaceAggsWithPercentiles
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/mapper/NestedPathFieldMapper.java
|
{
"start": 948,
"end": 1977
}
|
class ____ extends MetadataFieldMapper {
public static final String NAME_PRE_V8 = "_type";
public static final String NAME = "_nested_path";
private static final NestedPathFieldMapper INSTANCE = new NestedPathFieldMapper(NAME);
private static final NestedPathFieldMapper INSTANCE_PRE_V8 = new NestedPathFieldMapper(NAME_PRE_V8);
public static String name(IndexVersion version) {
if (version.before(IndexVersions.V_8_0_0)) {
return NAME_PRE_V8;
}
return NAME;
}
public static Query filter(IndexVersion version, String path) {
return new TermQuery(new Term(name(version), new BytesRef(path)));
}
public static Field field(IndexVersion version, String path) {
return new StringField(name(version), path, Field.Store.NO);
}
public static final TypeParser PARSER = new FixedTypeParser(
c -> c.indexVersionCreated().before(IndexVersions.V_8_0_0) ? INSTANCE_PRE_V8 : INSTANCE
);
public static final
|
NestedPathFieldMapper
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-sns/src/test/java/org/apache/camel/component/aws2/sns/SNSComponentClientRegistryTest.java
|
{
"start": 1129,
"end": 2557
}
|
class ____ extends CamelTestSupport {
@Test
public void createEndpointWithMinimalSNSClientConfiguration() throws Exception {
AmazonSNSClientMock awsSNSClient = new AmazonSNSClientMock();
context.getRegistry().bind("awsSNSClient", awsSNSClient);
Sns2Component component = context.getComponent("aws2-sns", Sns2Component.class);
Sns2Endpoint endpoint = (Sns2Endpoint) component.createEndpoint("aws2-sns://MyTopic");
assertNotNull(endpoint.getConfiguration().getAmazonSNSClient());
}
@Test
public void createEndpointWithMinimalSNSClientMisconfiguration() {
Sns2Component component = context.getComponent("aws2-sns", Sns2Component.class);
assertThrows(IllegalArgumentException.class, () -> {
Sns2Endpoint endpoint = (Sns2Endpoint) component.createEndpoint("aws2-sns://MyTopic");
});
}
@Test
public void createEndpointWithAutowire() throws Exception {
AmazonSNSClientMock awsSNSClient = new AmazonSNSClientMock();
context.getRegistry().bind("awsSNSClient", awsSNSClient);
Sns2Component component = context.getComponent("aws2-sns", Sns2Component.class);
Sns2Endpoint endpoint = (Sns2Endpoint) component.createEndpoint("aws2-sns://MyTopic?accessKey=xxx&secretKey=yyy");
assertSame(awsSNSClient, endpoint.getConfiguration().getAmazonSNSClient());
}
}
|
SNSComponentClientRegistryTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/InconsistentCapitalizationTest.java
|
{
"start": 3461,
"end": 3582
}
|
class ____ {
Object aB;
Nested(Object aa) {
DoesntConflictWithNested.this.aa = aa;
}
|
Nested
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/datastreams/autosharding/DataStreamAutoShardingServiceTests.java
|
{
"start": 57327,
"end": 68236
}
|
class ____ {
List<Decision> highestLoadIncreaseDecisions = new ArrayList<>();
List<Decision> highestLoadNonIncreaseDecisions = new ArrayList<>();
public void record(DataStreamAutoShardingService.PeriodicDecisionLogger.FlushedDecisions flushedDecisions) {
highestLoadIncreaseDecisions.addAll(flushedDecisions.highestLoadIncreaseDecisions());
highestLoadNonIncreaseDecisions.addAll(flushedDecisions.highestLoadNonIncreaseDecisions());
}
public void clear() {
highestLoadIncreaseDecisions.clear();
highestLoadNonIncreaseDecisions.clear();
}
}
public void testPeriodResultLogger_logsPeriodically() {
long start = System.currentTimeMillis();
AtomicLong clock = new AtomicLong(start);
FlushedDecisionsRecorder recorder = new FlushedDecisionsRecorder();
DataStreamAutoShardingService.PeriodicDecisionLogger periodicDecisionLogger =
new DataStreamAutoShardingService.PeriodicDecisionLogger(clock::get, recorder::record);
// Should not flush when logging at the start time:
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(1));
assertThat(recorder.highestLoadNonIncreaseDecisions, empty());
// Should not flush when logging in the past:
clock.set(start - 1);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(2));
assertThat(recorder.highestLoadNonIncreaseDecisions, empty());
// Should not flush when logging just before the interval since the start has elapsed:
clock.set(start + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS - 1);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(3));
assertThat(recorder.highestLoadNonIncreaseDecisions, empty());
// Should flush when logging at exactly the interval since the start has elapsed:
long firstFlushTime = start + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS;
clock.set(firstFlushTime);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(4));
assertThat(
recorder.highestLoadNonIncreaseDecisions.stream().map(d -> d.inputs().dataStream()).toList(),
containsInAnyOrder("data-stream-1", "data-stream-2", "data-stream-3", "data-stream-4")
);
recorder.clear();
// Should not flush a second time when logging again at the same time:
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(5));
assertThat(recorder.highestLoadNonIncreaseDecisions, empty());
// Should not flush a second time when logging just before the interval since the first flush has elapsed:
clock.set(firstFlushTime + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS - 1);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(6));
assertThat(recorder.highestLoadNonIncreaseDecisions, empty());
// Should flush a second time when logging some extra time after the interval since the first flush has elapsed:
long secondFlushTime = firstFlushTime + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS + 123456L;
clock.set(secondFlushTime);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(7));
assertThat(
recorder.highestLoadNonIncreaseDecisions.stream().map(d -> d.inputs().dataStream()).toList(),
containsInAnyOrder("data-stream-5", "data-stream-6", "data-stream-7")
);
recorder.clear();
// Should not flush a third time when logging just before the interval since the second flush has elapsed:
// (N.B. This time is more than two intervals since the start, but we count time from the last flush.)
clock.set(secondFlushTime + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS - 1);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(8));
assertThat(recorder.highestLoadNonIncreaseDecisions, empty());
// Should flush a third time when logging at exactly the interval since the second flush has elapsed:
clock.set(secondFlushTime + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(9));
assertThat(
recorder.highestLoadNonIncreaseDecisions.stream().map(d -> d.inputs().dataStream()).toList(),
containsInAnyOrder("data-stream-8", "data-stream-9")
);
}
public void testPeriodResultLogger_logsHighestLoadNonIncrementDecisions() {
long start = System.nanoTime();
AtomicLong clock = new AtomicLong(start);
FlushedDecisionsRecorder recorder = new FlushedDecisionsRecorder();
DataStreamAutoShardingService.PeriodicDecisionLogger periodicDecisionLogger =
new DataStreamAutoShardingService.PeriodicDecisionLogger(clock::get, recorder::record);
// Pass in 13 decisions, in the order 8, 7, 6, 5; 13, 12, 11, 10; 4, 3, 2, 1; 9. Updating the clock before the last decision.
for (int i = 8; i >= 5; i--) {
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(i));
}
for (int i = 13; i >= 10; i--) {
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(i));
}
for (int i = 4; i >= 1; i--) {
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(i));
}
clock.set(start + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(9));
// Should have logged the 10 decisions with the highest load, in decreasing order, i.e. number 13 down to number 4:
assertThat(
recorder.highestLoadNonIncreaseDecisions.stream().map(d -> d.inputs().dataStream()).toList(),
contains(IntStream.rangeClosed(4, 13).mapToObj(i -> "data-stream-" + i).toList().reversed().toArray())
);
}
public void testPeriodResultLogger_separatesIncreaseAndNonIncreaseDecisions() {
long start = System.nanoTime();
AtomicLong clock = new AtomicLong(start);
FlushedDecisionsRecorder recorder = new FlushedDecisionsRecorder();
DataStreamAutoShardingService.PeriodicDecisionLogger periodicDecisionLogger =
new DataStreamAutoShardingService.PeriodicDecisionLogger(clock::get, recorder::record);
// Pass in 3 decisions. Update the clock before the last decision. The highest load decision has an increment result.
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(1));
periodicDecisionLogger.maybeLogDecision(createIncreaseDecision(3));
clock.set(start + DataStreamAutoShardingService.PeriodicDecisionLogger.FLUSH_INTERVAL_MILLIS);
periodicDecisionLogger.maybeLogDecision(createNoChangeDecision(2));
// Assert that we correctly separated the increase and the non-increase decisions.
assertThat(
recorder.highestLoadIncreaseDecisions.stream().map(d -> d.inputs().dataStream()).toList(),
containsInAnyOrder("data-stream-3")
);
assertThat(
recorder.highestLoadNonIncreaseDecisions.stream().map(d -> d.inputs().dataStream()).toList(),
containsInAnyOrder("data-stream-1", "data-stream-2")
);
}
private DataStreamAutoShardingService.Decision createNoChangeDecision(int writeIndexLoad) {
return new Decision(
createDecisionInputsForPeriodLoggerTests(writeIndexLoad),
new Decision.IncreaseCalculation(1.0 * writeIndexLoad, 2, null),
null,
new AutoShardingResult(AutoShardingType.NO_CHANGE_REQUIRED, 3, 3, TimeValue.ZERO)
);
}
private DataStreamAutoShardingService.Decision createIncreaseDecision(int writeIndexLoad) {
AutoShardingResult result = new AutoShardingResult(INCREASE_SHARDS, 3, 4, TimeValue.ZERO);
return new Decision(
createDecisionInputsForPeriodLoggerTests(writeIndexLoad),
new Decision.IncreaseCalculation(1.0 * writeIndexLoad, 4, result),
null,
result
);
}
private static Decision.Inputs createDecisionInputsForPeriodLoggerTests(int writeIndexLoadForIncreaseAndDataStreamName) {
return new Decision.Inputs(
TimeValue.timeValueSeconds(270),
TimeValue.timeValueDays(3),
2,
32,
WriteLoadMetric.PEAK,
WriteLoadMetric.ALL_TIME,
"data-stream-" + writeIndexLoadForIncreaseAndDataStreamName,
"the-write-index",
0.1,
0.2,
1.0 * writeIndexLoadForIncreaseAndDataStreamName,
3
);
}
public void testCalculateReturnsNotApplicableForLookupIndexMode() {
var projectId = randomProjectIdOrDefault();
ProjectMetadata.Builder builder = ProjectMetadata.builder(projectId);
DataStream dataStream = createLookupModeDataStream(builder);
ClusterState state = createClusterStateWithDataStream(builder);
AutoShardingResult autoShardingResult = service.calculate(
state.projectState(projectId),
dataStream,
createIndexStats(1, 1.0, 1.0, 1.0)
);
assertThat(autoShardingResult, is(NOT_APPLICABLE_RESULT));
assertThat(decisionsLogged, hasSize(0));
}
public void testCalculateReturnsNotApplicableForLookupIndexModeWithNullStats() {
var projectId = randomProjectIdOrDefault();
ProjectMetadata.Builder builder = ProjectMetadata.builder(projectId);
DataStream dataStream = createLookupModeDataStream(builder);
ClusterState state = createClusterStateWithDataStream(builder);
AutoShardingResult autoShardingResult = service.calculate(state.projectState(projectId), dataStream, null);
assertThat(autoShardingResult, is(NOT_APPLICABLE_RESULT));
assertThat(decisionsLogged, hasSize(0));
}
private DataStream createLookupModeDataStream(ProjectMetadata.Builder builder) {
DataStream dataStream = DataStream.builder(dataStreamName, List.of(new Index("test-index", randomUUID())))
.setGeneration(1)
.setIndexMode(IndexMode.LOOKUP)
.build();
builder.put(dataStream);
return dataStream;
}
private ClusterState createClusterStateWithDataStream(ProjectMetadata.Builder builder) {
return ClusterState.builder(ClusterName.DEFAULT)
.nodes(DiscoveryNodes.builder().add(DiscoveryNodeUtils.create("n1")))
.putProjectMetadata(builder.build())
.build();
}
}
|
FlushedDecisionsRecorder
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/TraceBuilder.java
|
{
"start": 2178,
"end": 3655
}
|
class ____ {
Class<? extends InputDemuxer> inputDemuxerClass = DefaultInputDemuxer.class;
@SuppressWarnings("unchecked")
Class<? extends Outputter> clazzTraceOutputter = DefaultOutputter.class;
Path traceOutput;
Path topologyOutput;
List<Path> inputs = new LinkedList<Path>();
MyOptions(String[] args, Configuration conf) throws FileNotFoundException,
IOException, ClassNotFoundException {
int switchTop = 0;
// to determine if the input paths should be recursively scanned or not
boolean doRecursiveTraversal = false;
while (args[switchTop].startsWith("-")) {
if (args[switchTop].equalsIgnoreCase("-demuxer")) {
inputDemuxerClass =
Class.forName(args[++switchTop]).asSubclass(InputDemuxer.class);
} else if (args[switchTop].equalsIgnoreCase("-recursive")) {
doRecursiveTraversal = true;
}
++switchTop;
}
traceOutput = new Path(args[0 + switchTop]);
topologyOutput = new Path(args[1 + switchTop]);
for (int i = 2 + switchTop; i < args.length; ++i) {
inputs.addAll(processInputArgument(
args[i], conf, doRecursiveTraversal));
}
}
/**
* Compare the history file names, not the full paths.
* Job history file name format is such that doing lexicographic sort on the
* history file names should result in the order of jobs' submission times.
*/
private static
|
MyOptions
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/notfound/OptionalLazyNotFoundTest.java
|
{
"start": 9792,
"end": 10363
}
|
class ____ extends Person {
@Id
private Long id;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private City city;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public City getCity() {
return city;
}
@Override
public void setCity(City city) {
this.city = city;
}
}
@Entity
@Table(name = "PersonManyToOneSelectException")
public static
|
PersonOneToOneSelectIgnore
|
java
|
apache__camel
|
core/camel-util/src/main/java/org/apache/camel/util/DoubleMap.java
|
{
"start": 1323,
"end": 7088
}
|
class ____ {
Object k1;
Object k2;
Object v;
Entry next;
}
private final Lock lock = new ReentrantLock();
private Entry[] table;
private int mask;
public DoubleMap(int size) {
table = new Entry[closedTableSize(size)];
mask = table.length - 1;
}
public V get(K1 k1, K2 k2) {
Entry[] table = this.table;
int mask = this.mask;
int index = smear(k1.hashCode() * 31 + k2.hashCode()) & mask;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (k1 == entry.k1 && k2 == entry.k2) {
return (V) entry.v;
}
}
return null;
}
public void forEach(TriConsumer<K1, K2, V> consumer) {
Entry[] table = this.table;
for (Entry entry : table) {
while (entry != null) {
consumer.accept((K1) entry.k1, (K2) entry.k2, (V) entry.v);
entry = entry.next;
}
}
}
public boolean containsKey(K1 k1, K2 k2) {
Entry[] table = this.table;
int mask = this.mask;
int index = smear(k1.hashCode() * 31 + k2.hashCode()) & mask;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (k1 == entry.k1 && k2 == entry.k2) {
return true;
}
}
return false;
}
public void put(K1 k1, K2 k2, V v) {
lock.lock();
try {
Entry[] table = this.table;
int size = size() + 1;
int realSize = closedTableSize(size);
if (realSize <= table.length) {
realSize = table.length;
int index = smear(k1.hashCode() * 31 + k2.hashCode()) & (realSize - 1);
for (Entry oldEntry = table[index]; oldEntry != null; oldEntry = oldEntry.next) {
if (oldEntry.k1 == k1 && oldEntry.k2 == k2) {
oldEntry.v = v;
return;
}
}
Entry entry = new Entry();
entry.k1 = k1;
entry.k2 = k2;
entry.v = v;
entry.next = table[index];
table[index] = entry;
} else {
Entry[] newT = new Entry[realSize];
int index = smear(k1.hashCode() * 31 + k2.hashCode()) & (realSize - 1);
Entry entry = new Entry();
newT[index] = entry;
entry.k1 = k1;
entry.k2 = k2;
entry.v = v;
for (Entry oldEntry : table) {
while (oldEntry != null) {
if (k1 != oldEntry.k1 || k2 != oldEntry.k2) {
index = smear(oldEntry.k1.hashCode() * 31 + oldEntry.k2.hashCode()) & (realSize - 1);
Entry newEntry = new Entry();
newEntry.k1 = oldEntry.k1;
newEntry.k2 = oldEntry.k2;
newEntry.v = oldEntry.v;
newEntry.next = newT[index];
newT[index] = newEntry;
}
oldEntry = oldEntry.next;
}
}
this.table = newT;
this.mask = realSize - 1;
}
} finally {
lock.unlock();
}
}
public boolean remove(K1 k1, K2 k2) {
lock.lock();
try {
Entry[] table = this.table;
int mask = this.mask;
int index = smear(k1.hashCode() * 31 + k2.hashCode()) & mask;
Entry prevEntry = null;
for (Entry oldEntry = table[index]; oldEntry != null; prevEntry = oldEntry, oldEntry = oldEntry.next) {
if (oldEntry.k1 == k1 && oldEntry.k2 == k2) {
if (prevEntry == null) {
table[index] = oldEntry.next;
} else {
prevEntry.next = oldEntry.next;
}
return true;
}
}
return false;
} finally {
lock.unlock();
}
}
public V getFirst(Predicate<K1> p1, Predicate<K2> p2) {
for (Entry entry : table) {
while (entry != null) {
if (p1.test((K1) entry.k1) && p2.test((K2) entry.k2)) {
return (V) entry.v;
}
entry = entry.next;
}
}
return null;
}
public int size() {
Entry[] table = this.table;
int n = 0;
if (table != null) {
for (Entry e : table) {
for (Entry c = e; c != null; c = c.next) {
n++;
}
}
}
return n;
}
public void clear() {
lock.lock();
try {
this.table = new Entry[table.length];
} finally {
lock.unlock();
}
}
static int smear(int hashCode) {
return C2 * Integer.rotateLeft(hashCode * C1, 15);
}
static int closedTableSize(int expectedEntries) {
// Get the recommended table size.
// Round down to the nearest power of 2.
expectedEntries = Math.max(expectedEntries, 2);
int tableSize = Integer.highestOneBit(expectedEntries);
// Check to make sure that we will not exceed the maximum load factor.
if (expectedEntries > (int) (MAX_LOAD_FACTOR * tableSize)) {
tableSize <<= 1;
return (tableSize > 0) ? tableSize : MAX_TABLE_SIZE;
}
return tableSize;
}
}
|
Entry
|
java
|
netty__netty
|
transport/src/test/java/io/netty/bootstrap/BootstrapTest.java
|
{
"start": 19740,
"end": 20219
}
|
class ____ extends DefaultEventLoop {
@Override
public ChannelFuture register(final Channel channel, final ChannelPromise promise) {
// Delay registration
execute(new Runnable() {
@Override
public void run() {
DelayedEventLoopGroup.super.register(channel, promise);
}
});
return promise;
}
}
private static final
|
DelayedEventLoopGroup
|
java
|
mapstruct__mapstruct
|
core/src/main/java/org/mapstruct/AfterMapping.java
|
{
"start": 567,
"end": 3557
}
|
class ____
* interface) referenced in {@link Mapper#uses()}, or in a type used as {@code @}{@link Context} parameter in order to
* be used in a mapping method.
* <p>
* The method invocation is only generated if the return type of the method (if non-{@code void}) is assignable to the
* return type of the mapping method and all parameters can be <em>assigned</em> by the available source, target or
* context parameters of the mapping method:
* <ul>
* <li>A parameter annotated with {@code @}{@link MappingTarget} is populated with the target instance of the mapping.
* </li>
* <li>A parameter annotated with {@code @}{@link TargetType} is populated with the target type of the mapping.</li>
* <li>Parameters annotated with {@code @}{@link Context} are populated with the context parameters of the mapping
* method.</li>
* <li>Any other parameter is populated with a source parameter of the mapping.</li>
* </ul>
* <p>
* For non-{@code void} methods, the return value of the method invocation is returned as the result of the mapping
* method if it is not {@code null}.
* <p>
* All <em>after-mapping</em> methods that can be applied to a mapping method will be used. {@code @}{@link Qualifier} /
* {@code @}{@link Named} can be used to filter the methods to use.
* <p>
* The order of the method invocation is determined by their location of definition:
* <ol>
* <li>Methods declared on {@code @}{@link Context} parameters, ordered by the parameter order.</li>
* <li>Methods implemented in the mapper itself.</li>
* <li>Methods from types referenced in {@link Mapper#uses()}, in the order of the type declaration in the annotation.
* </li>
* <li>Methods declared in one type are used after methods declared in their super-type</li>
* </ol>
* <em>Important:</em> the order of methods declared within one type can not be guaranteed, as it depends on the
* compiler and the processing environment implementation.
* <p>
* Example:
*
* <pre>
* <code>
* @AfterMapping
* public void calledWithoutArgs() {
* // ...
* }
*
* @AfterMapping
* public void calledWithSourceAndTargetType(SourceEntity anySource, @TargetType Class<?> targetType) {
* // ...
* }
*
* @AfterMapping
* public void calledWithSourceAndTarget(Object anySource, @MappingTarget TargetDto target) {
* // ...
* }
*
* public abstract TargetDto toTargetDto(SourceEntity source);
*
* // generates:
*
* public TargetDto toTargetDto(SourceEntity source) {
* if ( source == null ) {
* return null;
* }
*
* TargetDto targetDto = new TargetDto();
*
* // actual mapping code
*
* calledWithoutArgs();
* calledWithSourceAndTargetType( source, TargetDto.class );
* calledWithSourceAndTarget( source, targetDto );
*
* return targetDto;
* }
* </code>
* </pre>
*
* @author Andreas Gudian
* @see BeforeMapping
* @see Context
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @
|
or
|
java
|
apache__flink
|
flink-yarn/src/test/java/org/apache/flink/yarn/YarnApplicationFileUploaderTest.java
|
{
"start": 2068,
"end": 8824
}
|
class ____ {
@Test
void testRegisterProvidedLocalResources(@TempDir File flinkLibDir) throws IOException {
final Map<String, String> libJars = getLibJars();
generateFilesInDirectory(flinkLibDir, libJars);
try (final YarnApplicationFileUploader yarnApplicationFileUploader =
YarnApplicationFileUploader.from(
FileSystem.get(new YarnConfiguration()),
new Path(flinkLibDir.toURI()),
Collections.singletonList(new Path(flinkLibDir.toURI())),
ApplicationId.newInstance(0, 0),
DFSConfigKeys.DFS_REPLICATION_DEFAULT)) {
yarnApplicationFileUploader.registerProvidedLocalResources();
final Set<String> registeredResources =
yarnApplicationFileUploader.getRegisteredLocalResources().keySet();
assertThat(registeredResources).containsExactlyInAnyOrderElementsOf(libJars.keySet());
}
}
@Test
void testRegisterProvidedLocalResourcesWithParentDir(@TempDir File flinkLibDir)
throws IOException {
final String xmlContent = "XML Content";
final Map<String, String> xmlResources =
ImmutableMap.of(
"conf/hive-site.xml", xmlContent, "conf/ivysettings.xml", xmlContent);
generateFilesInDirectory(flinkLibDir, xmlResources);
try (final YarnApplicationFileUploader yarnApplicationFileUploader =
YarnApplicationFileUploader.from(
FileSystem.get(new YarnConfiguration()),
new Path(flinkLibDir.toURI()),
Collections.singletonList(new Path(flinkLibDir.toURI())),
ApplicationId.newInstance(0, 0),
DFSConfigKeys.DFS_REPLICATION_DEFAULT)) {
List<String> classPath = yarnApplicationFileUploader.registerProvidedLocalResources();
List<String> expectedClassPathEntries = Arrays.asList("conf");
assertThat(classPath).containsExactlyInAnyOrderElementsOf(expectedClassPathEntries);
}
}
@Test
void testRegisterProvidedLocalResourcesWithDuplication(@TempDir java.nio.file.Path tempDir)
throws IOException {
final File flinkLibDir1 =
Files.createTempDirectory(tempDir, UUID.randomUUID().toString()).toFile();
final File flinkLibDir2 =
Files.createTempDirectory(tempDir, UUID.randomUUID().toString()).toFile();
generateFilesInDirectory(flinkLibDir1, getLibJars());
generateFilesInDirectory(flinkLibDir2, getLibJars());
final FileSystem fileSystem = FileSystem.get(new YarnConfiguration());
try {
assertThrows(
"Two files with the same filename exist in the shared libs",
RuntimeException.class,
() ->
YarnApplicationFileUploader.from(
fileSystem,
new Path(tempDir.toFile().toURI()),
Arrays.asList(
new Path(flinkLibDir1.toURI()),
new Path(flinkLibDir2.toURI())),
ApplicationId.newInstance(0, 0),
DFSConfigKeys.DFS_REPLICATION_DEFAULT));
} finally {
IOUtils.closeQuietly(fileSystem);
}
}
@Test
void testRegisterProvidedLocalResourcesWithNotAllowedUsrLib(@TempDir File flinkHomeDir)
throws IOException {
final File flinkLibDir = new File(flinkHomeDir, "lib");
final File flinkUsrLibDir = new File(flinkHomeDir, "usrlib");
final Map<String, String> libJars = getLibJars();
final Map<String, String> usrLibJars = getUsrLibJars();
generateFilesInDirectory(flinkLibDir, libJars);
generateFilesInDirectory(flinkUsrLibDir, usrLibJars);
final List<Path> providedLibDirs = new ArrayList<>();
providedLibDirs.add(new Path(flinkLibDir.toURI()));
providedLibDirs.add(new Path(flinkUsrLibDir.toURI()));
assertThatThrownBy(
() ->
YarnApplicationFileUploader.from(
FileSystem.get(new YarnConfiguration()),
new Path(flinkHomeDir.getPath()),
providedLibDirs,
ApplicationId.newInstance(0, 0),
DFSConfigKeys.DFS_REPLICATION_DEFAULT))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(
"Provided lib directories, configured via %s, should not include %s.",
YarnConfigOptions.PROVIDED_LIB_DIRS.key(),
ConfigConstants.DEFAULT_FLINK_USR_LIB_DIR);
}
@Test
void testUploadLocalFileWithoutScheme(@TempDir File flinkHomeDir) throws IOException {
final MockLocalFileSystem fileSystem = new MockLocalFileSystem();
final File tempFile = File.createTempFile(UUID.randomUUID().toString(), "", flinkHomeDir);
final Path pathWithoutScheme = new Path(tempFile.getAbsolutePath());
try (final YarnApplicationFileUploader yarnApplicationFileUploader =
YarnApplicationFileUploader.from(
fileSystem,
new Path(flinkHomeDir.getPath()),
Collections.emptyList(),
ApplicationId.newInstance(0, 0),
DFSConfigKeys.DFS_REPLICATION_DEFAULT)) {
yarnApplicationFileUploader.uploadLocalFileToRemote(pathWithoutScheme, "");
assertThat(fileSystem.getCopiedPaths())
.hasSize(1)
.allMatch(path -> "file".equals(path.toUri().getScheme()));
}
}
private static Map<String, String> getLibJars() {
final HashMap<String, String> libJars = new HashMap<>(4);
final String jarContent = "JAR Content";
libJars.put("flink-dist.jar", jarContent);
libJars.put("log4j.jar", jarContent);
libJars.put("flink-table.jar", jarContent);
return libJars;
}
private static Map<String, String> getUsrLibJars() {
final HashMap<String, String> usrLibJars = new HashMap<>();
final String jarContent = "JAR Content";
usrLibJars.put("udf.jar", jarContent);
return usrLibJars;
}
private static
|
YarnApplicationFileUploaderTest
|
java
|
apache__rocketmq
|
example/src/main/java/org/apache/rocketmq/example/benchmark/TransactionProducer.java
|
{
"start": 2541,
"end": 14459
}
|
class ____ {
private static final long START_TIME = System.currentTimeMillis();
private static final LongAdder MSG_COUNT = new LongAdder();
//broker max check times should less than this value
static final int MAX_CHECK_RESULT_IN_MSG = 20;
public static void main(String[] args) throws MQClientException, UnsupportedEncodingException {
System.setProperty(RemotingCommand.SERIALIZE_TYPE_PROPERTY, SerializeType.ROCKETMQ.name());
Options options = ServerUtil.buildCommandlineOptions(new Options());
CommandLine commandLine = ServerUtil.parseCmdLine("TransactionProducer", args, buildCommandlineOptions(options), new DefaultParser());
TxSendConfig config = new TxSendConfig();
config.topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
config.threadCount = commandLine.hasOption('w') ? Integer.parseInt(commandLine.getOptionValue('w')) : 32;
config.messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 2048;
config.sendRollbackRate = commandLine.hasOption("sr") ? Double.parseDouble(commandLine.getOptionValue("sr")) : 0.0;
config.sendUnknownRate = commandLine.hasOption("su") ? Double.parseDouble(commandLine.getOptionValue("su")) : 0.0;
config.checkRollbackRate = commandLine.hasOption("cr") ? Double.parseDouble(commandLine.getOptionValue("cr")) : 0.0;
config.checkUnknownRate = commandLine.hasOption("cu") ? Double.parseDouble(commandLine.getOptionValue("cu")) : 0.0;
config.batchId = commandLine.hasOption("b") ? Long.parseLong(commandLine.getOptionValue("b")) : System.currentTimeMillis();
config.sendInterval = commandLine.hasOption("i") ? Integer.parseInt(commandLine.getOptionValue("i")) : 0;
config.aclEnable = commandLine.hasOption('a') && Boolean.parseBoolean(commandLine.getOptionValue('a'));
config.msgTraceEnable = commandLine.hasOption('m') && Boolean.parseBoolean(commandLine.getOptionValue('m'));
config.reportInterval = commandLine.hasOption("ri") ? Integer.parseInt(commandLine.getOptionValue("ri")) : 10000;
final ExecutorService sendThreadPool = Executors.newFixedThreadPool(config.threadCount);
final StatsBenchmarkTProducer statsBenchmark = new StatsBenchmarkTProducer();
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("BenchmarkTimerThread-%d").daemon(true).build());
final LinkedList<Snapshot> snapshotList = new LinkedList<>();
executorService.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
snapshotList.addLast(statsBenchmark.createSnapshot());
while (snapshotList.size() > 10) {
snapshotList.removeFirst();
}
}
}, 1000, 1000, TimeUnit.MILLISECONDS);
executorService.scheduleAtFixedRate(new TimerTask() {
private void printStats() {
if (snapshotList.size() >= 10) {
Snapshot begin = snapshotList.getFirst();
Snapshot end = snapshotList.getLast();
final long sendCount = end.sendRequestSuccessCount - begin.sendRequestSuccessCount;
final long sendTps = (sendCount * 1000L) / (end.endTime - begin.endTime);
final double averageRT = (end.sendMessageTimeTotal - begin.sendMessageTimeTotal) / (double) (end.sendRequestSuccessCount - begin.sendRequestSuccessCount);
final long failCount = end.sendRequestFailedCount - begin.sendRequestFailedCount;
final long checkCount = end.checkCount - begin.checkCount;
final long unexpectedCheck = end.unexpectedCheckCount - begin.unexpectedCheckCount;
final long dupCheck = end.duplicatedCheck - begin.duplicatedCheck;
System.out.printf(
"Current Time: %s | Send TPS: %5d | Max RT(ms): %5d | AVG RT(ms): %3.1f | Send Failed: %d | Check: %d | UnexpectedCheck: %d | DuplicatedCheck: %d%n",
UtilAll.timeMillisToHumanString2(System.currentTimeMillis()), sendTps, statsBenchmark.getSendMessageMaxRT().get(), averageRT, failCount, checkCount,
unexpectedCheck, dupCheck);
statsBenchmark.getSendMessageMaxRT().set(0);
}
}
@Override
public void run() {
try {
this.printStats();
} catch (Exception e) {
e.printStackTrace();
}
}
}, config.reportInterval, config.reportInterval, TimeUnit.MILLISECONDS);
RPCHook rpcHook = null;
if (config.aclEnable) {
String ak = commandLine.hasOption("ak") ? String.valueOf(commandLine.getOptionValue("ak")) : AclClient.ACL_ACCESS_KEY;
String sk = commandLine.hasOption("sk") ? String.valueOf(commandLine.getOptionValue("sk")) : AclClient.ACL_SECRET_KEY;
rpcHook = AclClient.getAclRPCHook(ak, sk);
}
final TransactionListener transactionCheckListener = new TransactionListenerImpl(statsBenchmark, config);
final TransactionMQProducer producer = new TransactionMQProducer(
"benchmark_transaction_producer",
rpcHook,
config.msgTraceEnable,
null);
producer.setInstanceName(Long.toString(System.currentTimeMillis()));
producer.setTransactionListener(transactionCheckListener);
producer.setDefaultTopicQueueNums(1000);
if (commandLine.hasOption('n')) {
String ns = commandLine.getOptionValue('n');
producer.setNamesrvAddr(ns);
}
producer.start();
for (int i = 0; i < config.threadCount; i++) {
sendThreadPool.execute(new Runnable() {
@Override
public void run() {
while (true) {
boolean success = false;
final long beginTimestamp = System.currentTimeMillis();
try {
SendResult sendResult =
producer.sendMessageInTransaction(buildMessage(config), null);
success = sendResult != null && sendResult.getSendStatus() == SendStatus.SEND_OK;
} catch (Throwable e) {
success = false;
} finally {
final long currentRT = System.currentTimeMillis() - beginTimestamp;
statsBenchmark.getSendMessageTimeTotal().add(currentRT);
long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
while (currentRT > prevMaxRT) {
boolean updated = statsBenchmark.getSendMessageMaxRT()
.compareAndSet(prevMaxRT, currentRT);
if (updated)
break;
prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
}
if (success) {
statsBenchmark.getSendRequestSuccessCount().increment();
} else {
statsBenchmark.getSendRequestFailedCount().increment();
}
if (config.sendInterval > 0) {
try {
Thread.sleep(config.sendInterval);
} catch (InterruptedException e) {
}
}
}
}
}
});
}
}
private static Message buildMessage(TxSendConfig config) {
byte[] bs = new byte[config.messageSize];
ThreadLocalRandom r = ThreadLocalRandom.current();
r.nextBytes(bs);
ByteBuffer buf = ByteBuffer.wrap(bs);
buf.putLong(config.batchId);
long sendMachineId = START_TIME << 32;
long count = MSG_COUNT.longValue();
long msgId = sendMachineId | count;
MSG_COUNT.increment();
buf.putLong(msgId);
// save send tx result in message
if (r.nextDouble() < config.sendRollbackRate) {
buf.put((byte) LocalTransactionState.ROLLBACK_MESSAGE.ordinal());
} else if (r.nextDouble() < config.sendUnknownRate) {
buf.put((byte) LocalTransactionState.UNKNOW.ordinal());
} else {
buf.put((byte) LocalTransactionState.COMMIT_MESSAGE.ordinal());
}
// save check tx result in message
for (int i = 0; i < MAX_CHECK_RESULT_IN_MSG; i++) {
if (r.nextDouble() < config.checkRollbackRate) {
buf.put((byte) LocalTransactionState.ROLLBACK_MESSAGE.ordinal());
} else if (r.nextDouble() < config.checkUnknownRate) {
buf.put((byte) LocalTransactionState.UNKNOW.ordinal());
} else {
buf.put((byte) LocalTransactionState.COMMIT_MESSAGE.ordinal());
}
}
Message msg = new Message();
msg.setTopic(config.topic);
msg.setBody(bs);
return msg;
}
public static Options buildCommandlineOptions(final Options options) {
Option opt = new Option("w", "threadCount", true, "Thread count, Default: 32");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("s", "messageSize", true, "Message Size, Default: 2048");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("t", "topic", true, "Topic name, Default: BenchmarkTest");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("sr", "send rollback rate", true, "Send rollback rate, Default: 0.0");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("su", "send unknown rate", true, "Send unknown rate, Default: 0.0");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("cr", "check rollback rate", true, "Check rollback rate, Default: 0.0");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("cu", "check unknown rate", true, "Check unknown rate, Default: 0.0");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("b", "test batch id", true, "test batch id, Default: System.currentMillis()");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("i", "send interval", true, "sleep interval in millis between messages, Default: 0");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("a", "aclEnable", true, "Acl Enable, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("ak", "accessKey", true, "Acl access key, Default: 12345678");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("sk", "secretKey", true, "Acl secret key, Default: rocketmq2");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("m", "msgTraceEnable", true, "Message Trace Enable, Default: false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("ri", "reportInterval", true, "The number of ms between reports, Default: 10000");
opt.setRequired(false);
options.addOption(opt);
return options;
}
}
|
TransactionProducer
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/AbstractS3AMockTest.java
|
{
"start": 1324,
"end": 3299
}
|
class ____ {
protected static final String BUCKET = "mock-bucket";
protected static final AwsServiceException NOT_FOUND =
AwsServiceException.builder()
.message("Not Found")
.statusCode(404)
.awsErrorDetails(AwsErrorDetails.builder()
.errorCode("")
.build())
.build();
protected S3AFileSystem fs;
protected S3Client s3;
protected Configuration conf;
@BeforeEach
public void setup() throws Exception {
conf = createConfiguration();
fs = new S3AFileSystem();
URI uri = URI.create(FS_S3A + "://" + BUCKET);
// unset S3CSE property from config to avoid pathIOE.
conf.unset(Constants.S3_ENCRYPTION_ALGORITHM);
fs.initialize(uri, conf);
s3 = fs.getS3AInternals().getAmazonS3Client("mocking");
}
public Configuration createConfiguration() {
Configuration conf = new Configuration();
conf.setClass(S3_CLIENT_FACTORY_IMPL, MockS3ClientFactory.class,
S3ClientFactory.class);
// use minimum multipart size for faster triggering
conf.setLong(Constants.MULTIPART_SIZE, MULTIPART_MIN_SIZE);
conf.setInt(Constants.S3A_BUCKET_PROBE, 1);
// this is so stream draining is always blocking, allowing
// assertions to be safely made without worrying
// about any race conditions
conf.setInt(ASYNC_DRAIN_THRESHOLD, Integer.MAX_VALUE);
// set the region to avoid the getBucketLocation on FS init.
conf.set(AWS_REGION, "eu-west-1");
// tight retry logic as all failures are simulated
final String interval = "1ms";
final int limit = 3;
conf.set(RETRY_THROTTLE_INTERVAL, interval);
conf.setInt(RETRY_THROTTLE_LIMIT, limit);
conf.set(RETRY_INTERVAL, interval);
conf.setInt(RETRY_LIMIT, limit);
return conf;
}
public S3Client getS3Client() {
return s3;
}
@AfterEach
public void teardown() throws Exception {
if (fs != null) {
fs.close();
}
}
}
|
AbstractS3AMockTest
|
java
|
quarkusio__quarkus
|
test-framework/junit5/src/main/java/io/quarkus/test/junit/IntegrationTestUtil.java
|
{
"start": 16872,
"end": 21446
}
|
class ____ implements ArtifactLauncher.InitContext.DevServicesLaunchResult {
private final Map<String, String> properties;
private final String networkId;
private final boolean manageNetwork;
private final CuratedApplication curatedApplication;
DefaultDevServicesLaunchResult(Map<String, String> properties, String networkId,
boolean manageNetwork, CuratedApplication curatedApplication) {
this.properties = properties;
this.networkId = networkId;
this.manageNetwork = manageNetwork;
this.curatedApplication = curatedApplication;
}
public Map<String, String> properties() {
return properties;
}
public String networkId() {
return networkId;
}
@Override
public boolean manageNetwork() {
return manageNetwork;
}
@Override
public CuratedApplication getCuratedApplication() {
return curatedApplication;
}
@Override
public void close() {
curatedApplication.close();
}
}
public static Properties readQuarkusArtifactProperties(ExtensionContext context) {
Path buildOutputDirectory = determineBuildOutputDirectory(context);
Path artifactProperties = buildOutputDirectory.resolve("quarkus-artifact.properties");
if (!Files.exists(artifactProperties)) {
TestLauncher testLauncher = determineTestLauncher();
String errorMessage = "Unable to locate the artifact metadata file created that must be created by Quarkus in order to run integration tests. ";
if (testLauncher == TestLauncher.MAVEN) {
errorMessage += "Make sure this test is run after 'mvn package'. ";
if (context.getTestClass().isPresent()) {
String testClassName = context.getTestClass().get().getName();
if (testClassName.endsWith("Test")) {
errorMessage += "The easiest way to ensure this is by having the 'maven-failsafe-plugin' run the test instead of the 'maven-surefire-plugin'.";
}
}
} else if (testLauncher == TestLauncher.GRADLE) {
errorMessage += "Make sure this test is run after the 'quarkusBuild' Gradle task.";
} else {
errorMessage += "Make sure this test is run after the Quarkus artifact is built from your build tool.";
}
throw new IllegalStateException(errorMessage);
}
Properties properties = new Properties();
try (var fis = new FileInputStream(artifactProperties.toFile())) {
properties.load(fis);
return properties;
} catch (IOException e) {
throw new UncheckedIOException(
"Unable to read artifact metadata file created that must be created by Quarkus in order to run integration tests.",
e);
}
}
static String getEffectiveArtifactType(Properties quarkusArtifactProperties, SmallRyeConfig config) {
Optional<String> maybeType = config.getOptionalValue("quarkus.test.integration-test-artifact-type", String.class);
if (maybeType.isPresent()) {
return maybeType.get();
}
return getArtifactType(quarkusArtifactProperties);
}
static String getArtifactType(Properties quarkusArtifactProperties) {
String artifactType = quarkusArtifactProperties.getProperty("type");
if (artifactType == null) {
throw new IllegalStateException("Unable to determine the type of artifact created by the Quarkus build");
}
return artifactType;
}
private static TestLauncher determineTestLauncher() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
int i = stackTrace.length - 1;
TestLauncher testLauncher = TestLauncher.UNKNOWN;
while (true) {
StackTraceElement element = stackTrace[i--];
String className = element.getClassName();
if (className.startsWith("org.apache.maven")) {
testLauncher = TestLauncher.MAVEN;
break;
}
if (className.startsWith("org.gradle")) {
testLauncher = TestLauncher.GRADLE;
}
if (i == 0) {
break;
}
}
return testLauncher;
}
private
|
DefaultDevServicesLaunchResult
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/MaxLongAggregatorFunctionTests.java
|
{
"start": 735,
"end": 1611
}
|
class ____ extends AggregatorFunctionTestCase {
@Override
protected SourceOperator simpleInput(BlockFactory blockFactory, int size) {
long max = randomLongBetween(1, Long.MAX_VALUE / size);
return new SequenceLongBlockSourceOperator(blockFactory, LongStream.range(0, size).map(l -> randomLongBetween(-max, max)));
}
@Override
protected AggregatorFunctionSupplier aggregatorFunction() {
return new MaxLongAggregatorFunctionSupplier();
}
@Override
protected String expectedDescriptionOfAggregator() {
return "max of longs";
}
@Override
public void assertSimpleOutput(List<Page> input, Block result) {
long max = input.stream().flatMapToLong(p -> allLongs(p.getBlock(0))).max().getAsLong();
assertThat(((LongBlock) result).getLong(0), equalTo(max));
}
}
|
MaxLongAggregatorFunctionTests
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurityTests.java
|
{
"start": 4803,
"end": 13093
}
|
class ____ {
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
WebFilterChainProxy springSecurityFilterChain;
@Test
public void defaultRequiresAuthentication() {
this.spring.register(Config.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain)
.build();
client.get()
.uri("/")
.exchange()
.expectStatus().isUnauthorized()
.expectBody().isEmpty();
// @formatter:on
}
// gh-4831
@Test
public void defaultMediaAllThenUnAuthorized() {
this.spring.register(Config.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain)
.build();
client.get()
.uri("/")
.accept(MediaType.ALL)
.exchange()
.expectStatus().isUnauthorized()
.expectBody().isEmpty();
// @formatter:on
}
@Test
public void authenticateWhenBasicThenNoSession() {
this.spring.register(Config.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain)
.build();
FluxExchangeResult<String> result = client.get()
.headers((headers) -> headers.setBasicAuth("user", "password"))
.exchange()
.expectStatus().isOk()
.returnResult(String.class);
// @formatter:on
result.assertWithDiagnostics(() -> assertThat(result.getResponseCookies().isEmpty()));
}
@Test
public void defaultPopulatesReactorContext() {
this.spring.register(Config.class).autowire();
Authentication currentPrincipal = new TestingAuthenticationToken("user", "password", "ROLE_USER");
WebSessionServerSecurityContextRepository contextRepository = new WebSessionServerSecurityContextRepository();
SecurityContext context = new SecurityContextImpl(currentPrincipal);
// @formatter:off
WebFilter contextRepositoryWebFilter = (exchange, chain) -> contextRepository.save(exchange, context)
.switchIfEmpty(chain.filter(exchange))
.flatMap((e) -> chain.filter(exchange));
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(contextRepositoryWebFilter, this.springSecurityFilterChain, writePrincipalWebFilter())
.build();
client.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo(currentPrincipal.getName()));
// @formatter:on
}
private WebFilter writePrincipalWebFilter() {
// @formatter:off
return (exchange, chain) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMap((principal) -> exchange.getResponse()
.writeWith(Mono.just(toDataBuffer(principal.getName())))
);
// @formatter:on
}
@Test
public void defaultPopulatesReactorContextWhenAuthenticating() {
this.spring.register(Config.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain, writePrincipalWebFilter())
.build();
client.get()
.uri("/")
.headers((headers) -> headers.setBasicAuth("user", "password"))
.exchange()
.expectStatus().isOk()
.expectBody(String.class).consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo("user"));
// @formatter:on
}
@Test
public void requestDataValueProcessor() {
this.spring.register(Config.class).autowire();
ConfigurableApplicationContext context = this.spring.getContext();
CsrfRequestDataValueProcessor rdvp = context.getBean(AbstractView.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME,
CsrfRequestDataValueProcessor.class);
assertThat(rdvp).isNotNull();
}
@Test
public void passwordEncoderBeanIsUsed() {
this.spring.register(CustomPasswordEncoderConfig.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain, writePrincipalWebFilter())
.build();
client.get().uri("/").headers((headers) -> headers.setBasicAuth("user", "password"))
.exchange().expectStatus().isOk()
.expectBody(String.class)
.consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo("user"));
// @formatter:on
}
@Test
public void passwordUpdateManagerUsed() {
this.spring.register(MapReactiveUserDetailsServiceConfig.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain)
.build();
client.get()
.uri("/")
.headers((h) -> h.setBasicAuth("user", "password"))
.exchange()
.expectStatus().isOk();
// @formatter:on
ReactiveUserDetailsService users = this.spring.getContext().getBean(ReactiveUserDetailsService.class);
assertThat(users.findByUsername("user").block().getPassword()).startsWith("{bcrypt}");
}
@Test
public void formLoginWorks() {
this.spring.register(Config.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain, writePrincipalWebFilter())
.build();
// @formatter:on
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
data.add("username", "user");
data.add("password", "password");
// @formatter:off
client.mutateWith(csrf())
.post()
.uri("/login")
.body(BodyInserters.fromFormData(data))
.exchange()
.expectStatus().is3xxRedirection()
.expectHeader().valueMatches("Location", "/");
// @formatter:on
}
@Test
public void multiWorks() {
this.spring.register(MultiSecurityHttpConfig.class).autowire();
// @formatter:off
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(this.springSecurityFilterChain)
.build();
client.get()
.uri("/api/test")
.exchange()
.expectStatus().isUnauthorized()
.expectBody().isEmpty();
client.get()
.uri("/test")
.exchange()
.expectStatus().isOk();
// @formatter:on
}
@Test
@WithMockUser
public void authenticationPrincipalArgumentResolverWhenSpelThenWorks() {
this.spring.register(AuthenticationPrincipalConfig.class).autowire();
// @formatter:off
WebTestClient client = WebTestClient
.bindToApplicationContext(this.spring.getContext())
.build();
client.get()
.uri("/spel")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("user");
// @formatter:on
}
private static DataBuffer toDataBuffer(String body) {
DataBuffer buffer = new DefaultDataBufferFactory().allocateBuffer();
buffer.write(body.getBytes(StandardCharsets.UTF_8));
return buffer;
}
@Test
public void enableWebFluxSecurityWhenNoConfigurationAnnotationThenBeanProxyingEnabled() {
this.spring.register(BeanProxyEnabledByDefaultConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isSameAs(childBean);
}
@Test
public void enableWebFluxSecurityWhenProxyBeanMethodsFalseThenBeanProxyingDisabled() {
this.spring.register(BeanProxyDisabledConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isNotSameAs(childBean);
}
@Test
// gh-8596
public void resolveAuthenticationPrincipalArgumentResolverFirstDoesNotCauseBeanCurrentlyInCreationException() {
this.spring
.register(EnableWebFluxSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
DelegatingWebFluxConfiguration.class)
.autowire();
}
@Test
// gh-10076
public void webFluxConfigurationSupportAndServerHttpSecurityConfigurationDoNotCauseCircularReference() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setAllowCircularReferences(false);
context.register(EnableWebFluxSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
DelegatingWebFluxConfiguration.class);
context.setServletContext(new MockServletContext());
context.refresh();
}
@Configuration
@EnableWebFluxSecurity
@Import(ReactiveAuthenticationTestConfiguration.class)
static
|
EnableWebFluxSecurityTests
|
java
|
micronaut-projects__micronaut-core
|
core/src/main/java/io/micronaut/core/annotation/AnnotationMetadata.java
|
{
"start": 1420,
"end": 1578
}
|
interface ____ at compile time by Micronaut that allows the inspection of annotation metadata and
* stereotypes (meta-annotations)</p>.
*
* <p>This
|
implemented
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/requests/DescribeGroupsRequest.java
|
{
"start": 1262,
"end": 3278
}
|
class ____ extends AbstractRequest.Builder<DescribeGroupsRequest> {
private final DescribeGroupsRequestData data;
public Builder(DescribeGroupsRequestData data) {
super(ApiKeys.DESCRIBE_GROUPS);
this.data = data;
}
@Override
public DescribeGroupsRequest build(short version) {
return new DescribeGroupsRequest(data, version);
}
@Override
public String toString() {
return data.toString();
}
}
private final DescribeGroupsRequestData data;
private DescribeGroupsRequest(DescribeGroupsRequestData data, short version) {
super(ApiKeys.DESCRIBE_GROUPS, version);
this.data = data;
}
@Override
public DescribeGroupsRequestData data() {
return data;
}
@Override
public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
Errors error = Errors.forException(e);
DescribeGroupsResponseData describeGroupsResponseData = new DescribeGroupsResponseData();
data.groups().forEach(groupId ->
describeGroupsResponseData.groups().add(DescribeGroupsResponse.groupError(groupId, error))
);
if (version() >= 1) {
describeGroupsResponseData.setThrottleTimeMs(throttleTimeMs);
}
return new DescribeGroupsResponse(describeGroupsResponseData);
}
public static DescribeGroupsRequest parse(Readable readable, short version) {
return new DescribeGroupsRequest(new DescribeGroupsRequestData(readable, version), version);
}
public static List<DescribeGroupsResponseData.DescribedGroup> getErrorDescribedGroupList(
List<String> groupIds,
Errors error
) {
return groupIds.stream()
.map(groupId -> new DescribeGroupsResponseData.DescribedGroup()
.setGroupId(groupId)
.setErrorCode(error.code())
)
.collect(Collectors.toList());
}
}
|
Builder
|
java
|
greenrobot__greendao
|
examples/DaoExample/src/main/java/org/greenrobot/greendao/example/NoteActivity.java
|
{
"start": 1184,
"end": 4319
}
|
class ____ extends AppCompatActivity {
private EditText editText;
private View addNoteButton;
private NoteDao noteDao;
private Query<Note> notesQuery;
private NotesAdapter notesAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpViews();
// get the note DAO
DaoSession daoSession = ((App) getApplication()).getDaoSession();
noteDao = daoSession.getNoteDao();
// query all notes, sorted a-z by their text
notesQuery = noteDao.queryBuilder().orderAsc(NoteDao.Properties.Text).build();
updateNotes();
}
private void updateNotes() {
List<Note> notes = notesQuery.list();
notesAdapter.setNotes(notes);
}
protected void setUpViews() {
RecyclerView recyclerView = findViewById(R.id.recyclerViewNotes);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
notesAdapter = new NotesAdapter(noteClickListener);
recyclerView.setAdapter(notesAdapter);
addNoteButton = findViewById(R.id.buttonAdd);
addNoteButton.setEnabled(false);
editText = findViewById(R.id.editTextNote);
editText.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
addNote();
return true;
}
return false;
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean enable = s.length() != 0;
addNoteButton.setEnabled(enable);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public void onAddButtonClick(View view) {
addNote();
}
private void addNote() {
String noteText = editText.getText().toString();
editText.setText("");
final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
String comment = "Added on " + df.format(new Date());
Note note = new Note();
note.setText(noteText);
note.setComment(comment);
note.setDate(new Date());
note.setType(NoteType.TEXT);
noteDao.insert(note);
Log.d("DaoExample", "Inserted new note, ID: " + note.getId());
updateNotes();
}
NotesAdapter.NoteClickListener noteClickListener = new NotesAdapter.NoteClickListener() {
@Override
public void onNoteClick(int position) {
Note note = notesAdapter.getNote(position);
Long noteId = note.getId();
noteDao.deleteByKey(noteId);
Log.d("DaoExample", "Deleted note, ID: " + noteId);
updateNotes();
}
};
}
|
NoteActivity
|
java
|
google__guava
|
guava/src/com/google/common/collect/Multisets.java
|
{
"start": 38032,
"end": 41216
}
|
class ____<E extends @Nullable Object> implements Iterator<E> {
private final Multiset<E> multiset;
private final Iterator<Entry<E>> entryIterator;
private @Nullable Entry<E> currentEntry;
/** Count of subsequent elements equal to current element */
private int laterCount;
/** Count of all elements equal to current element */
private int totalCount;
private boolean canRemove;
MultisetIteratorImpl(Multiset<E> multiset, Iterator<Entry<E>> entryIterator) {
this.multiset = multiset;
this.entryIterator = entryIterator;
}
@Override
public boolean hasNext() {
return laterCount > 0 || entryIterator.hasNext();
}
@Override
@ParametricNullness
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (laterCount == 0) {
currentEntry = entryIterator.next();
totalCount = laterCount = currentEntry.getCount();
}
laterCount--;
canRemove = true;
/*
* requireNonNull is safe because laterCount starts at 0, forcing us to initialize
* currentEntry above. After that, we never clear it.
*/
return requireNonNull(currentEntry).getElement();
}
@Override
public void remove() {
checkRemove(canRemove);
if (totalCount == 1) {
entryIterator.remove();
} else {
/*
* requireNonNull is safe because canRemove is set to true only after we initialize
* currentEntry (which we never subsequently clear).
*/
multiset.remove(requireNonNull(currentEntry).getElement());
}
totalCount--;
canRemove = false;
}
}
static <E extends @Nullable Object> Spliterator<E> spliteratorImpl(Multiset<E> multiset) {
Spliterator<Entry<E>> entrySpliterator = multiset.entrySet().spliterator();
return CollectSpliterators.flatMap(
entrySpliterator,
(Entry<E> entry) -> Collections.nCopies(entry.getCount(), entry.getElement()).spliterator(),
Spliterator.SIZED
| (entrySpliterator.characteristics()
& (Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE)),
multiset.size());
}
/** An implementation of {@link Multiset#size}. */
static int linearTimeSizeImpl(Multiset<?> multiset) {
long size = 0;
for (Entry<?> entry : multiset.entrySet()) {
size += entry.getCount();
}
return Ints.saturatedCast(size);
}
/**
* Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order puts
* the highest count first, with ties broken by the iteration order of the original multiset.
*
* @since 11.0
*/
public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) {
@SuppressWarnings("unchecked") // generics+arrays
// TODO(cpovirk): Consider storing an Entry<?> instead of Entry<E>.
Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray((Entry<E>[]) new Entry<?>[0]);
Arrays.sort(entries, DecreasingCount.INSTANCE);
return ImmutableMultiset.copyFromEntries(asList(entries));
}
private static final
|
MultisetIteratorImpl
|
java
|
hibernate__hibernate-orm
|
hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/sqlserver/SqlServerDialectContributor.java
|
{
"start": 476,
"end": 1778
}
|
class ____ implements ContributorImplementor {
private final ServiceRegistry serviceRegistry;
public SqlServerDialectContributor(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
@Override
public void contributeJdbcTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
HSMessageLogger.SPATIAL_MSG_LOGGER.typeContributions( this.getClass().getCanonicalName() );
typeContributions.contributeJdbcType( SqlServerGeometryType.INSTANCE );
typeContributions.contributeJdbcType( SqlServerGeographyType.INSTANCE );
}
@Override
public void contributeFunctions(FunctionContributions functionContributions) {
HSMessageLogger.SPATIAL_MSG_LOGGER.functionContributions( this.getClass().getCanonicalName() );
final SqlServerSqmFunctionDescriptors functions = new SqlServerSqmFunctionDescriptors( functionContributions );
final SqmFunctionRegistry functionRegistry = functionContributions.getFunctionRegistry();
functions.asMap().forEach( (key, desc) -> {
functionRegistry.register( key.getName(), desc );
key.getAltName().ifPresent( altName -> functionRegistry.registerAlternateKey( altName, key.getName() ) );
} );
}
@Override
public ServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
}
|
SqlServerDialectContributor
|
java
|
apache__camel
|
components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcColumnTypeTest.java
|
{
"start": 1253,
"end": 2610
}
|
class ____ extends AbstractJdbcTestSupport {
@Test
@SuppressWarnings("unchecked")
public void testClobColumnType() {
Endpoint directHelloEndpoint = context.getEndpoint("direct:hello");
Exchange directHelloExchange = directHelloEndpoint.createExchange();
directHelloExchange.getIn().setBody("select * from tableWithClob");
Exchange out = template.send(directHelloEndpoint, directHelloExchange);
assertNotNull(out);
List<Map<String, Object>> returnValues = out.getMessage().getBody(List.class);
assertNotNull(returnValues);
assertEquals(1, returnValues.size());
Map<String, Object> row = returnValues.get(0);
assertEquals("id1", row.get("ID"));
assertNotNull(row.get("PICTURE"));
Set<String> columnNames = (Set<String>) out.getMessage().getHeader(JdbcConstants.JDBC_COLUMN_NAMES);
assertNotNull(columnNames);
assertEquals(2, columnNames.size());
assertTrue(columnNames.contains("ID"));
assertTrue(columnNames.contains("PICTURE"));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:hello").to("jdbc:testdb?readSize=100");
}
};
}
}
|
JdbcColumnTypeTest
|
java
|
quarkusio__quarkus
|
extensions/security-jpa-reactive/deployment/src/test/java/io/quarkus/security/jpa/reactive/PanacheEntitiesConfigurationTest.java
|
{
"start": 847,
"end": 3437
}
|
class ____ extends JpaSecurityRealmTest {
private static final String DUPLICATE_USERNAME = "merlin";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(testClasses)
.addClass(PanacheUserEntity.class)
.addClass(PanacheRoleEntity.class)
.addClass(UserResource.class)
.addClass(AuthenticationFailureObserver.class)
.addAsResource("multiple-entities/import.sql", "import.sql")
.addAsResource("multiple-entities/application.properties", "application.properties"));
@Inject
AuthenticationFailureObserver authenticationFailureObserver;
@Test
void duplicateUsernameTest() {
// duplicate username must lead to 401
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
// no user -> unauthenticated
getUsername().statusCode(401);
createUser();
// one user
getUsername().statusCode(200).body(is(DUPLICATE_USERNAME));
createUser();
// two users -> NonUniqueResultException -> 401
authenticationFailureObserver.recordEvents(true);
getUsername().statusCode(401).body(Matchers.emptyOrNullString());
Awaitility.await().untilAsserted(() -> assertNotNull(authenticationFailureObserver.getEvent()));
var authFailureEvent = authenticationFailureObserver.getEvent();
assertInstanceOf(AuthenticationFailedException.class, authFailureEvent.getAuthenticationFailure());
var cause = authFailureEvent.getAuthenticationFailure().getCause();
assertInstanceOf(NonUniqueResultException.class, cause);
assertTrue(cause.getMessage().contains("Query did not return a unique result"));
authenticationFailureObserver.recordEvents(false);
}
private static void createUser() {
RestAssured
.given()
.auth().preemptive().basic("user", "user")
.body(DUPLICATE_USERNAME)
.post("/jaxrs-secured/user")
.then()
.statusCode(201);
}
private static ValidatableResponse getUsername() {
return RestAssured
.given()
.auth().preemptive().basic(DUPLICATE_USERNAME, DUPLICATE_USERNAME)
.body(DUPLICATE_USERNAME)
.get("/jaxrs-secured/user")
.then();
}
@Singleton
public static
|
PanacheEntitiesConfigurationTest
|
java
|
quarkusio__quarkus
|
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/RepeatedConstraintsTest.java
|
{
"start": 3258,
"end": 3487
}
|
class ____ implements ConstraintValidator<MyConstraint, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return false;
}
}
}
|
MyConstraintValidator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
|
{
"start": 60869,
"end": 61498
}
|
class ____ extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return describeMatch(
tree,
SuggestedFix.merge(
SuggestedFixes.removeModifiers(tree, state, Modifier.PUBLIC).orElse(emptyFix()),
SuggestedFixes.addModifiers(tree, state, Modifier.ABSTRACT).orElse(emptyFix())));
}
}
@Test
public void removeAddModifier_rangesCompatible() {
BugCheckerRefactoringTestHelper.newInstance(RemoveAddModifier.class, getClass())
.addInputLines("in/Test.java", "public
|
RemoveAddModifier
|
java
|
elastic__elasticsearch
|
modules/aggregations/src/test/java/org/elasticsearch/aggregations/bucket/AggregationMultiBucketAggregationTestCase.java
|
{
"start": 848,
"end": 1010
}
|
class ____ unit testing multi bucket aggregation's bucket implementations that reside in aggregations module.
*
* @param <T> The bucket type
*/
public abstract
|
for
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/DiscrimSubclassFilterTest.java
|
{
"start": 791,
"end": 3540
}
|
class ____ {
@Test
@SuppressWarnings("unchecked")
public void testFiltersWithSubclass(SessionFactoryScope scope) {
scope.inTransaction(s -> {
s.enableFilter( "region" ).setParameter( "userRegion", "US" );
List results;
Iterator itr;
results = s.createQuery( "from Person" ).list();
assertEquals( 4, results.size(), "Incorrect qry result count" );
s.clear();
results = s.createQuery( "from Employee" ).list();
assertEquals( 2, results.size(), "Incorrect qry result count" );
s.clear();
results = new ArrayList( new HashSet( s.createQuery( "from Person as p left join fetch p.minions" )
.list() ) );
assertEquals( 4, results.size(), "Incorrect qry result count" );
itr = results.iterator();
while ( itr.hasNext() ) {
// find john
final Person p = (Person) itr.next();
if ( p.getName().equals( "John Doe" ) ) {
Employee john = (Employee) p;
assertEquals( 1, john.getMinions().size(), "Incorrect fecthed minions count" );
break;
}
}
s.clear();
results = new ArrayList( new HashSet( s.createQuery( "from Employee as p left join fetch p.minions" )
.list() ) );
assertEquals( 2, results.size(), "Incorrect qry result count" );
itr = results.iterator();
while ( itr.hasNext() ) {
// find john
final Person p = (Person) itr.next();
if ( p.getName().equals( "John Doe" ) ) {
Employee john = (Employee) p;
assertEquals( 1, john.getMinions().size(), "Incorrect fecthed minions count" );
break;
}
}
} );
}
@AfterEach
void tearDown(SessionFactoryScope factoryScope) {
factoryScope.dropData();
}
@BeforeEach
void prepareTestData(SessionFactoryScope factoryScope) {
factoryScope.inTransaction( (s) -> {
Employee john = new Employee( "John Doe" );
john.setCompany( "JBoss" );
john.setDepartment( "hr" );
john.setTitle( "hr guru" );
john.setRegion( "US" );
Employee polli = new Employee( "Polli Wog" );
polli.setCompany( "JBoss" );
polli.setDepartment( "hr" );
polli.setTitle( "hr novice" );
polli.setRegion( "US" );
polli.setManager( john );
john.getMinions().add( polli );
Employee suzie = new Employee( "Suzie Q" );
suzie.setCompany( "JBoss" );
suzie.setDepartment( "hr" );
suzie.setTitle( "hr novice" );
suzie.setRegion( "EMEA" );
suzie.setManager( john );
john.getMinions().add( suzie );
Customer cust = new Customer( "John Q Public" );
cust.setCompany( "Acme" );
cust.setRegion( "US" );
cust.setContactOwner( john );
Person ups = new Person( "UPS guy" );
ups.setCompany( "UPS" );
ups.setRegion( "US" );
s.persist( john );
s.persist( cust );
s.persist( ups );
} );
}
}
|
DiscrimSubclassFilterTest
|
java
|
apache__camel
|
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FromFtpNoEndpointPathRelativeMoveToAbsoluteIT.java
|
{
"start": 1040,
"end": 2468
}
|
class ____ extends FtpServerTestSupport {
protected String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}?password=admin&recursive=true&binary=false"
+ "&move=/.done/${file:name}&initialDelay=2500&delay=5000";
}
@Override
public void doPostSetup() throws Exception {
prepareFtpServer();
}
@Test
public void testPollFileAndShouldBeMoved() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceivedInAnyOrder("Hello", "Bye", "Goodday");
mock.expectedFileExists(service.ftpFile(".done/hello.txt"));
mock.expectedFileExists(service.ftpFile(".done/sub/bye.txt"));
mock.expectedFileExists(service.ftpFile(".done/sub/sub2/goodday.txt"));
mock.assertIsSatisfied();
}
private void prepareFtpServer() {
template.sendBodyAndHeader(getFtpUrl(), "Hello", Exchange.FILE_NAME, "hello.txt");
template.sendBodyAndHeader(getFtpUrl(), "Bye", Exchange.FILE_NAME, "sub/bye.txt");
template.sendBodyAndHeader(getFtpUrl(), "Goodday", Exchange.FILE_NAME, "sub/sub2/goodday.txt");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(getFtpUrl()).to("mock:result");
}
};
}
}
|
FromFtpNoEndpointPathRelativeMoveToAbsoluteIT
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToUnsignedLongSerializationTests.java
|
{
"start": 540,
"end": 786
}
|
class ____ extends AbstractUnaryScalarSerializationTests<ToUnsignedLong> {
@Override
protected ToUnsignedLong create(Source source, Expression child) {
return new ToUnsignedLong(source, child);
}
}
|
ToUnsignedLongSerializationTests
|
java
|
alibaba__nacos
|
auth/src/test/java/com/alibaba/nacos/auth/context/GrpcIdentityContextBuilderTest.java
|
{
"start": 1489,
"end": 2935
}
|
class ____ {
private static final String TEST_PLUGIN = "test";
private static final String IDENTITY_TEST_KEY = "identity-test-key";
private static final String IDENTITY_TEST_VALUE = "identity-test-value";
@Mock
private NacosAuthConfig authConfig;
@Mock
private Request request;
private GrpcIdentityContextBuilder identityContextBuilder;
@BeforeEach
void setUp() throws Exception {
identityContextBuilder = new GrpcIdentityContextBuilder(authConfig);
when(authConfig.getNacosAuthSystemType()).thenReturn(TEST_PLUGIN);
Map<String, String> headers = new HashMap<>();
headers.put(IDENTITY_TEST_KEY, IDENTITY_TEST_VALUE);
when(request.getHeaders()).thenReturn(headers);
when(request.getHeader(Constants.Identity.X_REAL_IP)).thenReturn("1.1.1.1");
}
@Test
void testBuildWithoutPlugin() {
when(authConfig.getNacosAuthSystemType()).thenReturn("non-exist");
IdentityContext actual = identityContextBuilder.build(request);
assertNull(actual.getParameter(IDENTITY_TEST_KEY));
}
@Test
void testBuild() {
IdentityContext actual = identityContextBuilder.build(request);
assertEquals(IDENTITY_TEST_VALUE, actual.getParameter(IDENTITY_TEST_KEY));
assertEquals("1.1.1.1", actual.getParameter(Constants.Identity.REMOTE_IP));
}
}
|
GrpcIdentityContextBuilderTest
|
java
|
quarkusio__quarkus
|
core/devmode-spi/src/main/java/io/quarkus/dev/console/DevConsoleResponse.java
|
{
"start": 112,
"end": 1141
}
|
class ____ {
private int status;
private Map<String, List<String>> headers = new HashMap<>();
private byte[] body;
public DevConsoleResponse(int status, Map<String, List<String>> headers, byte[] body) {
this.status = status;
this.headers = headers;
this.body = body;
}
public DevConsoleResponse() {
this.status = 200;
this.headers = new HashMap<>();
this.body = new byte[0];
}
public int getStatus() {
return status;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public byte[] getBody() {
return body;
}
public DevConsoleResponse setStatus(int status) {
this.status = status;
return this;
}
public DevConsoleResponse setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
return this;
}
public DevConsoleResponse setBody(byte[] body) {
this.body = body;
return this;
}
}
|
DevConsoleResponse
|
java
|
elastic__elasticsearch
|
modules/repository-gcs/src/main/java/org/elasticsearch/repositories/gcs/MeteredStorage.java
|
{
"start": 5347,
"end": 6827
}
|
class ____ {
private final GcsRepositoryStatsCollector statsCollector;
private final OperationPurpose purpose;
private final com.google.api.services.storage.Storage.Objects.Get get;
MeteredObjectsGetRequest(
GcsRepositoryStatsCollector statsCollector,
OperationPurpose purpose,
com.google.api.services.storage.Storage.Objects.Get get
) {
this.statsCollector = statsCollector;
this.purpose = purpose;
this.get = get;
}
public void setReturnRawInputStream(boolean b) {
get.setReturnRawInputStream(b);
}
public void setGeneration(Long generation) {
get.setGeneration(generation);
}
public HttpHeaders getRequestHeaders() {
return get.getRequestHeaders();
}
public HttpResponse executeMedia() throws IOException {
return statsCollector.collectIOSupplier(purpose, GET, get::executeMedia);
}
}
/**
* A delegating WriteChannel. Write channel performs at most one operation for all writes.
* This is implication of GCS billing, all insert operations, even resumable, are counted as one,
* despite number of parts. It's different from ReadChannel and BlobPage, where every read/list
* call is counted as separate operation.
*/
@SuppressForbidden(reason = "wraps GCS channel")
public static
|
MeteredObjectsGetRequest
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ApplicationClientProtocol.java
|
{
"start": 13124,
"end": 13885
}
|
interface ____ by clients to get information about <em>queues</em>
* from the <code>ResourceManager</code>.</p>
*
* <p>The client, via {@link GetQueueInfoRequest}, can ask for details such
* as used/total resources, child queues, running applications etc.</p>
*
* <p> In secure mode,the <code>ResourceManager</code> verifies access before
* providing the information.</p>
*
* @param request request to get queue information
* @return queue information
* @throws YarnException exceptions from yarn servers.
* @throws IOException io error occur.
*/
@Public
@Stable
@Idempotent
public GetQueueInfoResponse getQueueInfo(
GetQueueInfoRequest request)
throws YarnException, IOException;
/**
* <p>The
|
used
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/orderby/OrderByTest.java
|
{
"start": 3852,
"end": 4004
}
|
class ____ extends Person {
public P2() {
}
public P2(Long id, String name) {
super( id, name );
}
}
@Entity(name = "Task")
public static
|
P2
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/conditional/ClampMinIntegerEvaluator.java
|
{
"start": 1090,
"end": 4884
}
|
class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ClampMinIntegerEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator field;
private final EvalOperator.ExpressionEvaluator min;
private final DriverContext driverContext;
private Warnings warnings;
public ClampMinIntegerEvaluator(Source source, EvalOperator.ExpressionEvaluator field,
EvalOperator.ExpressionEvaluator min, DriverContext driverContext) {
this.source = source;
this.field = field;
this.min = min;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (IntBlock fieldBlock = (IntBlock) field.eval(page)) {
try (IntBlock minBlock = (IntBlock) min.eval(page)) {
IntVector fieldVector = fieldBlock.asVector();
if (fieldVector == null) {
return eval(page.getPositionCount(), fieldBlock, minBlock);
}
IntVector minVector = minBlock.asVector();
if (minVector == null) {
return eval(page.getPositionCount(), fieldBlock, minBlock);
}
return eval(page.getPositionCount(), fieldVector, minVector).asBlock();
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += field.baseRamBytesUsed();
baseRamBytesUsed += min.baseRamBytesUsed();
return baseRamBytesUsed;
}
public IntBlock eval(int positionCount, IntBlock fieldBlock, IntBlock minBlock) {
try(IntBlock.Builder result = driverContext.blockFactory().newIntBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (fieldBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (minBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
int field = fieldBlock.getInt(fieldBlock.getFirstValueIndex(p));
int min = minBlock.getInt(minBlock.getFirstValueIndex(p));
result.appendInt(ClampMin.process(field, min));
}
return result.build();
}
}
public IntVector eval(int positionCount, IntVector fieldVector, IntVector minVector) {
try(IntVector.FixedBuilder result = driverContext.blockFactory().newIntVectorFixedBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
int field = fieldVector.getInt(p);
int min = minVector.getInt(p);
result.appendInt(p, ClampMin.process(field, min));
}
return result.build();
}
}
@Override
public String toString() {
return "ClampMinIntegerEvaluator[" + "field=" + field + ", min=" + min + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(field, min);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static
|
ClampMinIntegerEvaluator
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/ShouldBeBefore.java
|
{
"start": 962,
"end": 2227
}
|
class ____ extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldBeBefore}</code>.
* @param actual the actual value in the failed assertion.
* @param other the value used in the failed assertion to compare the actual value to.
* @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldBeBefore(Object actual, Object other, ComparisonStrategy comparisonStrategy) {
return new ShouldBeBefore(actual, other, comparisonStrategy);
}
/**
* Creates a new <code>{@link ShouldBeBefore}</code>.
* @param actual the actual value in the failed assertion.
* @param other the value used in the failed assertion to compare the actual value to.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldBeBefore(Object actual, Object other) {
return new ShouldBeBefore(actual, other, StandardComparisonStrategy.instance());
}
private ShouldBeBefore(Object actual, Object other, ComparisonStrategy comparisonStrategy) {
super("%nExpecting actual:%n %s%nto be strictly before:%n %s%n%s", actual, other, comparisonStrategy);
}
}
|
ShouldBeBefore
|
java
|
apache__avro
|
lang/java/ipc/src/test/java/org/apache/avro/ipc/TestLocalTransceiver.java
|
{
"start": 1541,
"end": 2296
}
|
class ____ extends GenericResponder {
public TestResponder(Protocol local) {
super(local);
}
@Override
public Object respond(Message message, Object request) throws AvroRemoteException {
assertEquals(new Utf8("hello"), ((GenericRecord) request).get("x"));
return new Utf8("there");
}
}
@Test
void singleRpc() throws Exception {
Transceiver t = new LocalTransceiver(new TestResponder(protocol));
GenericRecord params = new GenericData.Record(protocol.getMessages().get("m").getRequest());
params.put("x", new Utf8("hello"));
GenericRequestor r = new GenericRequestor(protocol, t);
for (int x = 0; x < 5; x++)
assertEquals(new Utf8("there"), r.request("m", params));
}
}
|
TestResponder
|
java
|
spring-projects__spring-framework
|
spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointManager.java
|
{
"start": 4413,
"end": 9143
}
|
class ____ (for example, "ActiveMQResourceAdapter" →
* "ActiveMQActivationSpec" in the same package), and populates the
* ActivationSpec properties as suggested by the JCA 1.5 specification
* (plus a couple of autodetected vendor-specific properties).
* @see DefaultJmsActivationSpecFactory
*/
public void setActivationSpecFactory(@Nullable JmsActivationSpecFactory activationSpecFactory) {
this.activationSpecFactory =
(activationSpecFactory != null ? activationSpecFactory : new DefaultJmsActivationSpecFactory());
}
/**
* Set the DestinationResolver to use for resolving destination names
* into the JCA 1.5 ActivationSpec "destination" property.
* <p>If not specified, destination names will simply be passed in as Strings.
* If specified, destination names will be resolved into Destination objects first.
* <p>Note that a DestinationResolver is usually specified on the JmsActivationSpecFactory
* (see {@link StandardJmsActivationSpecFactory#setDestinationResolver}). This is simply
* a shortcut for parameterizing the default JmsActivationSpecFactory; it will replace
* any custom JmsActivationSpecFactory that might have been set before.
* @see StandardJmsActivationSpecFactory#setDestinationResolver
*/
public void setDestinationResolver(DestinationResolver destinationResolver) {
DefaultJmsActivationSpecFactory factory = new DefaultJmsActivationSpecFactory();
factory.setDestinationResolver(destinationResolver);
this.activationSpecFactory = factory;
}
/**
* Specify the {@link JmsActivationSpecConfig} object that this endpoint manager
* should use for activating its listener.
* <p>This config object will be turned into a concrete JCA 1.5 ActivationSpec
* object through a {@link #setActivationSpecFactory JmsActivationSpecFactory}.
*/
public void setActivationSpecConfig(@Nullable JmsActivationSpecConfig activationSpecConfig) {
this.activationSpecConfig = activationSpecConfig;
}
/**
* Return the {@link JmsActivationSpecConfig} object that this endpoint manager
* should use for activating its listener. Return {@code null} if none is set.
*/
public @Nullable JmsActivationSpecConfig getActivationSpecConfig() {
return this.activationSpecConfig;
}
/**
* Set the name of this message endpoint. Populated with the bean name
* automatically when defined within Spring's bean factory.
*/
@Override
public void setBeanName(String beanName) {
this.endpointFactory.setBeanName(beanName);
}
@Override
public void afterPropertiesSet() throws ResourceException {
if (getResourceAdapter() == null) {
throw new IllegalArgumentException("Property 'resourceAdapter' is required");
}
if (this.messageListenerSet) {
setMessageEndpointFactory(this.endpointFactory);
}
if (this.activationSpecConfig != null) {
setActivationSpec(
this.activationSpecFactory.createActivationSpec(getResourceAdapter(), this.activationSpecConfig));
}
super.afterPropertiesSet();
}
@Override
public void setupMessageListener(Object messageListener) {
if (messageListener instanceof MessageListener msgListener) {
setMessageListener(msgListener);
}
else {
throw new IllegalArgumentException("Unsupported message listener '" +
messageListener.getClass().getName() + "': only '" + MessageListener.class.getName() +
"' type is supported");
}
}
@Override
public @Nullable MessageConverter getMessageConverter() {
JmsActivationSpecConfig config = getActivationSpecConfig();
if (config != null) {
return config.getMessageConverter();
}
return null;
}
@Override
public @Nullable DestinationResolver getDestinationResolver() {
if (this.activationSpecFactory instanceof StandardJmsActivationSpecFactory standardFactory) {
return standardFactory.getDestinationResolver();
}
return null;
}
@Override
public boolean isPubSubDomain() {
JmsActivationSpecConfig config = getActivationSpecConfig();
if (config != null) {
return config.isPubSubDomain();
}
throw new IllegalStateException("Could not determine pubSubDomain - no activation spec config is set");
}
@Override
public boolean isReplyPubSubDomain() {
JmsActivationSpecConfig config = getActivationSpecConfig();
if (config != null) {
return config.isReplyPubSubDomain();
}
throw new IllegalStateException("Could not determine reply pubSubDomain - no activation spec config is set");
}
@Override
public @Nullable QosSettings getReplyQosSettings() {
JmsActivationSpecConfig config = getActivationSpecConfig();
if (config != null) {
return config.getReplyQosSettings();
}
throw new IllegalStateException("Could not determine reply qosSettings - no activation spec config is set");
}
}
|
name
|
java
|
spring-projects__spring-boot
|
smoke-test/spring-boot-smoke-test-secure-webflux/src/main/java/smoketest/secure/webflux/WelcomeController.java
|
{
"start": 840,
"end": 978
}
|
class ____ {
@GetMapping("/")
public String welcome(Principal principal) {
return "Hello " + principal.getName();
}
}
|
WelcomeController
|
java
|
alibaba__nacos
|
client-basic/src/main/java/com/alibaba/nacos/client/auth/ram/identify/IdentifyConstants.java
|
{
"start": 728,
"end": 2330
}
|
class ____ {
public static final String ACCESS_KEY = "accessKey";
public static final String SECRET_KEY = "secretKey";
public static final String SECURITY_TOKEN_HEADER = "Spas-SecurityToken";
public static final String TENANT_ID = "tenantId";
public static final String PROPERTIES_FILENAME = "spas.properties";
public static final String CREDENTIAL_PATH = "/home/admin/.spas_key/";
public static final String CREDENTIAL_DEFAULT = "default";
public static final String DOCKER_CREDENTIAL_PATH = "/etc/instanceInfo";
public static final String DOCKER_ACCESS_KEY = "env_spas_accessKey";
public static final String DOCKER_SECRET_KEY = "env_spas_secretKey";
public static final String DOCKER_TENANT_ID = "ebv_spas_tenantId";
public static final String ENV_ACCESS_KEY = "spas_accessKey";
public static final String ENV_SECRET_KEY = "spas_secretKey";
public static final String ENV_TENANT_ID = "tenant.id";
public static final String NO_APP_NAME = "";
public static final String PROJECT_NAME_PROPERTY = "project.name";
public static final String RAM_ROLE_NAME_PROPERTY = "ram.role.name";
public static final String REFRESH_TIME_PROPERTY = "time.to.refresh.in.millisecond";
public static final String SECURITY_PROPERTY = "security.credentials";
public static final String SECURITY_URL_PROPERTY = "security.credentials.url";
public static final String SECURITY_CACHE_PROPERTY = "cache.security.credentials";
}
|
IdentifyConstants
|
java
|
spring-projects__spring-boot
|
buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java
|
{
"start": 8895,
"end": 9551
}
|
class ____ {
private final String id;
private final List<Module> modules;
private final List<String> plugins;
private final List<ImportedBom> boms;
public Group(String id, List<Module> modules, List<String> plugins, List<ImportedBom> boms) {
this.id = id;
this.modules = modules;
this.plugins = plugins;
this.boms = boms;
}
public String getId() {
return this.id;
}
public List<Module> getModules() {
return this.modules;
}
public List<String> getPlugins() {
return this.plugins;
}
public List<ImportedBom> getBoms() {
return this.boms;
}
}
/**
* A module in a group.
*/
public static
|
Group
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/QuarkusErrorHandler.java
|
{
"start": 1422,
"end": 15140
}
|
class ____ implements Handler<RoutingContext> {
private static final Logger log = getLogger(QuarkusErrorHandler.class);
private static final String NL = "\n";
private static final String TAB = "\t";
private static final String HEADING = "500 - Internal Server Error";
/**
* we don't want to generate a new UUID each time as it is slowish. Instead, we just generate one based one
* and then use a counter.
*/
private static final AtomicLong ERROR_COUNT = new AtomicLong();
private final boolean showStack;
private final boolean decorateStack;
private final Optional<PayloadHint> contentTypeDefault;
private final List<ErrorPageAction> actions;
private final List<String> knowClasses;
private final String srcMainJava;
public QuarkusErrorHandler(boolean showStack, boolean decorateStack,
Optional<PayloadHint> contentTypeDefault) {
this(showStack, decorateStack, contentTypeDefault, null, List.of(), List.of());
}
public QuarkusErrorHandler(boolean showStack, boolean decorateStack,
Optional<PayloadHint> contentTypeDefault,
String srcMainJava,
List<String> knowClasses,
List<ErrorPageAction> actions) {
this.showStack = showStack;
this.decorateStack = decorateStack;
this.contentTypeDefault = contentTypeDefault;
this.srcMainJava = srcMainJava;
this.knowClasses = knowClasses;
this.actions = actions;
}
@Override
public void handle(RoutingContext event) {
Throwable exception = event.failure();
try {
if (exception == null) {
event.response().setStatusCode(event.statusCode());
event.response().end();
return;
}
//this can happen if there is no auth mechanisms
if (exception instanceof UnauthorizedException) {
HttpAuthenticator authenticator = event.get(HttpAuthenticator.class.getName());
if (authenticator != null) {
authenticator.sendChallenge(event).subscribe().with(new Consumer<>() {
@Override
public void accept(Boolean aBoolean) {
event.response().end();
}
}, new Consumer<>() {
@Override
public void accept(Throwable throwable) {
event.fail(throwable);
}
});
} else {
event.response().setStatusCode(HttpResponseStatus.UNAUTHORIZED.code()).end();
}
return;
}
if (exception instanceof ForbiddenException) {
event.response().setStatusCode(HttpResponseStatus.FORBIDDEN.code()).end();
return;
}
if (exception instanceof AuthenticationException) {
if (event.response().getStatusCode() == HttpResponseStatus.OK.code()) {
//set 401 if status wasn't set upstream
event.response().setStatusCode(HttpResponseStatus.UNAUTHORIZED.code());
}
//when proactive security is enabled and this wasn't handled elsewhere, we expect event to
//end here as failing event makes it possible to customize response, however when proactive security is
//disabled, this should be handled elsewhere and if we get to this point bad things have happened,
//so it is better to send a response than to hang
if ((exception instanceof AuthenticationCompletionException
|| (exception instanceof AuthenticationFailedException && event.response().getStatusCode() == 401))
&& exception.getMessage() != null
&& LaunchMode.current().isDev()) {
event.response().end(exception.getMessage());
} else {
event.response().end();
}
return;
}
if (exception instanceof RejectedExecutionException) {
log.warn(
"Worker thread pool exhaustion, no more worker threads available - returning a `503 - SERVICE UNAVAILABLE` response.");
event.response().setStatusCode(HttpResponseStatus.SERVICE_UNAVAILABLE.code()).end();
return;
}
} catch (IllegalStateException e) {
//ignore this if the response is already started
if (!event.response().ended()) {
//could be that just the head is committed
event.response().end();
}
return;
}
if (!event.response().headWritten()) {
event.response().setStatusCode(event.statusCode() > 0 ? event.statusCode() : 500);
}
String uuid = LazyHolder.BASE_ID + ERROR_COUNT.incrementAndGet();
String details;
String stack = "";
String responseContentType = null;
try {
responseContentType = ContentTypes.pickFirstSupportedAndAcceptedContentType(event);
} catch (RuntimeException e) {
// Let's shield ourselves from bugs in this parsing code:
// we're already handling an exception,
// so the priority is to return *something* to the user.
// If we can't pick the appropriate content-type, well, so be it.
exception.addSuppressed(e);
}
if (showStack && exception != null) {
details = generateHeaderMessage(exception, uuid);
stack = generateStackTrace(exception);
} else {
details = generateHeaderMessage(uuid);
}
if (exception instanceof IOException) {
log.debugf(exception,
"IOError processing HTTP request to %s failed, the client likely terminated the connection. Error id: %s",
event.request().uri(), uuid);
} else {
log.errorf(exception, "HTTP Request to %s failed, error id: %s", event.request().uri(), uuid);
}
//we have logged the error
//now let's see if we can actually send a response
//if not we just return
if (event.response().ended()) {
return;
} else if (event.response().headWritten()) {
event.response().end();
return;
}
if (responseContentType == null) {
responseContentType = "";
}
switch (responseContentType) {
case ContentTypes.TEXT_HTML:
case ContentTypes.APPLICATION_XHTML:
case ContentTypes.APPLICATION_XML:
case ContentTypes.TEXT_XML:
htmlResponse(event, details, exception);
break;
case ContentTypes.APPLICATION_JSON:
case ContentTypes.TEXT_JSON:
jsonResponse(event, responseContentType, details, stack, exception);
break;
case ContentTypes.TEXT_PLAIN:
textResponse(event, details, stack, exception);
break;
default:
if (contentTypeDefault.isPresent()) {
switch (contentTypeDefault.get()) {
case HTML:
htmlResponse(event, details, exception);
break;
case JSON:
jsonResponse(event, ContentTypes.APPLICATION_JSON, details, stack, exception);
break;
case TEXT:
textResponse(event, details, stack, exception);
break;
default:
defaultResponse(event, details, stack, exception);
break;
}
} else {
defaultResponse(event, details, stack, exception);
break;
}
break;
}
}
private void defaultResponse(RoutingContext event, String details, String stack, Throwable throwable) {
String userAgent = event.request().getHeader("User-Agent");
if (userAgent != null && (userAgent.toLowerCase(Locale.ROOT).startsWith("wget/")
|| userAgent.toLowerCase(Locale.ROOT).startsWith("curl/"))) {
textResponse(event, details, stack, throwable);
} else {
jsonResponse(event, ContentTypes.APPLICATION_JSON, details, stack, throwable);
}
}
private void textResponse(RoutingContext event, String details, String stack, Throwable throwable) {
event.response().headers().set(HttpHeaderNames.CONTENT_TYPE, ContentTypes.TEXT_PLAIN + "; charset=utf-8");
String decoratedString = null;
if (decorateStack && throwable != null) {
decoratedString = DecorateStackUtil.getDecoratedString(throwable, srcMainJava, knowClasses);
}
try (StringWriter sw = new StringWriter()) {
sw.write(NL + HEADING + NL);
sw.write("---------------------------" + NL);
sw.write(NL);
sw.write("Details:");
sw.write(NL);
sw.write(TAB + details);
sw.write(NL);
if (decoratedString != null) {
sw.write("Decorate (Source code):");
sw.write(NL);
sw.write(TAB + decoratedString);
sw.write(NL);
}
sw.write("Stack:");
sw.write(NL);
sw.write(TAB + stack);
sw.write(NL);
writeResponse(event, sw.toString());
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private void jsonResponse(RoutingContext event, String contentType, String details, String stack, Throwable throwable) {
event.response().headers().set(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=utf-8");
String escapedDetails = escapeJsonString(details);
String escapedStack = escapeJsonString(stack);
String decoratedString = null;
if (decorateStack && throwable != null) {
decoratedString = DecorateStackUtil.getDecoratedString(throwable, srcMainJava, knowClasses);
}
StringBuilder jsonPayload = new StringBuilder("{\"details\":\"")
.append(escapedDetails);
if (decoratedString != null) {
jsonPayload = jsonPayload.append("\",\"decorate\":\"")
.append(escapeJsonString(decoratedString));
}
jsonPayload = jsonPayload.append("\",\"stack\":\"")
.append(escapedStack)
.append("\"}");
writeResponse(event, jsonPayload.toString());
}
private void htmlResponse(RoutingContext event, String details, Throwable exception) {
event.response().headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8");
final TemplateHtmlBuilder htmlBuilder = new TemplateHtmlBuilder(showStack, "Internal Server Error", details, details,
this.actions);
if (decorateStack && exception != null) {
htmlBuilder.decorate(exception, this.srcMainJava, this.knowClasses);
}
if (showStack && exception != null) {
htmlBuilder.stack(exception, this.knowClasses);
}
writeResponse(event, htmlBuilder.toString());
}
private void writeResponse(RoutingContext event, String output) {
if (!event.response().ended()) {
event.response().end(output);
}
}
private static String generateStackTrace(final Throwable exception) {
StringWriter stringWriter = new StringWriter();
exception.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString().trim();
}
private static String generateHeaderMessage(final Throwable exception, String uuid) {
return String.format("Error id %s, %s: %s", uuid, exception.getClass().getName(),
extractFirstLine(exception.getMessage()));
}
private static String generateHeaderMessage(String uuid) {
return String.format("Error id %s", uuid);
}
private static String extractFirstLine(final String message) {
if (null == message) {
return "";
}
String[] lines = message.split("\\r?\\n");
return lines[0].trim();
}
static String escapeJsonString(final String text) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
sb.append(ch);
}
}
return sb.toString();
}
private static final
|
QuarkusErrorHandler
|
java
|
netty__netty
|
example/src/main/java/io/netty/example/ocsp/OcspRequestBuilder.java
|
{
"start": 1519,
"end": 3605
}
|
class ____ {
private static final SecureRandom GENERATOR = new SecureRandom();
private SecureRandom generator = GENERATOR;
private DigestCalculator calculator = Digester.sha1();
private X509Certificate certificate;
private X509Certificate issuer;
public OcspRequestBuilder generator(SecureRandom generator) {
this.generator = generator;
return this;
}
public OcspRequestBuilder calculator(DigestCalculator calculator) {
this.calculator = calculator;
return this;
}
public OcspRequestBuilder certificate(X509Certificate certificate) {
this.certificate = certificate;
return this;
}
public OcspRequestBuilder issuer(X509Certificate issuer) {
this.issuer = issuer;
return this;
}
/**
* ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce
* and CA's will (should) reject subsequent requests that have the same nonce value.
*/
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
SecureRandom generator = checkNotNull(this.generator, "generator");
DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
X509Certificate certificate = checkNotNull(this.certificate, "certificate");
X509Certificate issuer = checkNotNull(this.issuer, "issuer");
BigInteger serial = certificate.getSerialNumber();
CertificateID certId = new CertificateID(calculator,
new X509CertificateHolder(issuer.getEncoded()), serial);
OCSPReqBuilder builder = new OCSPReqBuilder();
builder.addRequest(certId);
byte[] nonce = new byte[8];
generator.nextBytes(nonce);
Extension[] extensions = new Extension[] {
new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
new DEROctetString(nonce)) };
builder.setRequestExtensions(new Extensions(extensions));
return builder.build();
}
}
|
OcspRequestBuilder
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.