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 | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest56.java | {
"start": 1026,
"end": 6441
} | class ____ extends OracleTest {
public void test_types() throws Exception {
String sql = //
" \n" +
" CREATE TABLE \"SC_001\".\"TB_001\" \n" +
" ( \"SNAP_ID\" NUMBER(6,0) NOT NULL ENABLE, \n" +
" \"DBID\" NUMBER NOT NULL ENABLE, \n" +
" \"INSTANCE_NUMBER\" NUMBER NOT NULL ENABLE, \n" +
" \"EVENT\" VARCHAR2(64) NOT NULL ENABLE, \n" +
" \"TOTAL_WAITS\" NUMBER, \n" +
" \"TOTAL_TIMEOUTS\" NUMBER, \n" +
" \"TIME_WAITED_MICRO\" NUMBER, \n" +
" CONSTRAINT \"STATS$BG_EVENT_SUMMARY_PK\" PRIMARY KEY (\"SNAP_ID\", \"DBID\", \"INSTANCE_NUMBER\", \"EVENT\")\n" +
" USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS \n" +
" STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)\n" +
" TABLESPACE \"PERFSTAT\" ENABLE, \n" +
" CONSTRAINT \"STATS$BG_EVENT_SUMMARY_FK\" FOREIGN KEY (\"SNAP_ID\", \"DBID\", \"INSTANCE_NUMBER\")\n" +
" REFERENCES \"PERFSTAT\".\"STATS$SNAPSHOT\" (\"SNAP_ID\", \"DBID\", \"INSTANCE_NUMBER\") ON DELETE CASCADE ENABLE\n" +
" ) PCTFREE 5 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING\n" +
" STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" +
" PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)\n" +
" TABLESPACE \"PERFSTAT\" ";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
assertEquals("CREATE TABLE \"SC_001\".\"TB_001\" (\n" +
"\t\"SNAP_ID\" NUMBER(6, 0) NOT NULL ENABLE,\n" +
"\t\"DBID\" NUMBER NOT NULL ENABLE,\n" +
"\t\"INSTANCE_NUMBER\" NUMBER NOT NULL ENABLE,\n" +
"\t\"EVENT\" VARCHAR2(64) NOT NULL ENABLE,\n" +
"\t\"TOTAL_WAITS\" NUMBER,\n" +
"\t\"TOTAL_TIMEOUTS\" NUMBER,\n" +
"\t\"TIME_WAITED_MICRO\" NUMBER,\n" +
"\tCONSTRAINT \"STATS$BG_EVENT_SUMMARY_PK\" PRIMARY KEY (\"SNAP_ID\", \"DBID\", \"INSTANCE_NUMBER\", \"EVENT\")\n" +
"\t\tUSING INDEX\n" +
"\t\tPCTFREE 10\n" +
"\t\tINITRANS 2\n" +
"\t\tMAXTRANS 255\n" +
"\t\tTABLESPACE \"PERFSTAT\"\n" +
"\t\tSTORAGE (\n" +
"\t\t\tINITIAL 1048576\n" +
"\t\t\tNEXT 1048576\n" +
"\t\t\tMINEXTENTS 1\n" +
"\t\t\tMAXEXTENTS 2147483645\n" +
"\t\t\tPCTINCREASE 0\n" +
"\t\t\tFREELISTS 1\n" +
"\t\t\tFREELIST GROUPS 1\n" +
"\t\t\tBUFFER_POOL DEFAULT\n" +
"\t\t)\n" +
"\t\tCOMPUTE STATISTICS\n" +
"\t\tENABLE,\n" +
"\tCONSTRAINT \"STATS$BG_EVENT_SUMMARY_FK\" FOREIGN KEY (\"SNAP_ID\", \"DBID\", \"INSTANCE_NUMBER\")\n" +
"\t\tREFERENCES \"PERFSTAT\".\"STATS$SNAPSHOT\" (\"SNAP_ID\", \"DBID\", \"INSTANCE_NUMBER\")\n" +
"\t\tON DELETE CASCADE ENABLE\n" +
")\n" +
"PCTFREE 5\n" +
"PCTUSED 40\n" +
"INITRANS 1\n" +
"MAXTRANS 255\n" +
"NOCOMPRESS\n" +
"LOGGING\n" +
"TABLESPACE \"PERFSTAT\"\n" +
"STORAGE (\n" +
"\tINITIAL 1048576\n" +
"\tNEXT 1048576\n" +
"\tMINEXTENTS 1\n" +
"\tMAXEXTENTS 2147483645\n" +
"\tPCTINCREASE 0\n" +
"\tFREELISTS 1\n" +
"\tFREELIST GROUPS 1\n" +
"\tBUFFER_POOL DEFAULT\n" +
")",
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(2, visitor.getTables().size());
assertEquals(10, visitor.getColumns().size());
assertTrue(visitor.containsColumn("SC_001.TB_001", "SNAP_ID"));
}
}
| OracleCreateTableTest56 |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/delegation/web/DelegationTokenAuthenticator.java | {
"start": 3261,
"end": 14344
} | enum ____ {
GETDELEGATIONTOKEN(HTTP_GET, true),
RENEWDELEGATIONTOKEN(HTTP_PUT, true),
CANCELDELEGATIONTOKEN(HTTP_PUT, false);
private String httpMethod;
private boolean requiresKerberosCredentials;
private DelegationTokenOperation(String httpMethod,
boolean requiresKerberosCredentials) {
this.httpMethod = httpMethod;
this.requiresKerberosCredentials = requiresKerberosCredentials;
}
public String getHttpMethod() {
return httpMethod;
}
public boolean requiresKerberosCredentials() {
return requiresKerberosCredentials;
}
}
private Authenticator authenticator;
private ConnectionConfigurator connConfigurator;
public DelegationTokenAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
@Override
public void setConnectionConfigurator(ConnectionConfigurator configurator) {
authenticator.setConnectionConfigurator(configurator);
connConfigurator = configurator;
}
private boolean hasDelegationToken(URL url, AuthenticatedURL.Token token) {
boolean hasDt = false;
if (token instanceof DelegationTokenAuthenticatedURL.Token) {
hasDt = ((DelegationTokenAuthenticatedURL.Token) token).
getDelegationToken() != null;
if (hasDt) {
LOG.trace("Delegation token found: {}",
((DelegationTokenAuthenticatedURL.Token) token)
.getDelegationToken());
}
}
if (!hasDt) {
String queryStr = url.getQuery();
hasDt = (queryStr != null) && queryStr.contains(DELEGATION_PARAM + "=");
LOG.trace("hasDt={}, queryStr={}", hasDt, queryStr);
}
return hasDt;
}
@Override
public void authenticate(URL url, AuthenticatedURL.Token token)
throws IOException, AuthenticationException {
if (!hasDelegationToken(url, token)) {
try {
// check and renew TGT to handle potential expiration
UserGroupInformation.getCurrentUser().checkTGTAndReloginFromKeytab();
LOG.debug("No delegation token found for url={}, "
+ "authenticating with {}", url, authenticator.getClass());
authenticator.authenticate(url, token);
} catch (IOException ex) {
throw NetUtils.wrapException(url.getHost(), url.getPort(),
null, 0, ex);
}
} else {
LOG.debug("Authenticated from delegation token. url={}, token={}",
url, token);
}
}
/**
* Requests a delegation token using the configured <code>Authenticator</code>
* for authentication.
*
* @param url the URL to get the delegation token from. Only HTTP/S URLs are
* supported.
* @param token the authentication token being used for the user where the
* Delegation token will be stored.
* @param renewer the renewer user.
* @throws IOException if an IO error occurred.
* @throws AuthenticationException if an authentication exception occurred.
* @return abstract delegation token identifier.
*/
public Token<AbstractDelegationTokenIdentifier> getDelegationToken(URL url,
AuthenticatedURL.Token token, String renewer)
throws IOException, AuthenticationException {
return getDelegationToken(url, token, renewer, null);
}
/**
* Requests a delegation token using the configured <code>Authenticator</code>
* for authentication.
*
* @param url the URL to get the delegation token from. Only HTTP/S URLs are
* supported.
* @param token the authentication token being used for the user where the
* Delegation token will be stored.
* @param renewer the renewer user.
* @param doAsUser the user to do as, which will be the token owner.
* @throws IOException if an IO error occurred.
* @throws AuthenticationException if an authentication exception occurred.
* @return abstract delegation token identifier.
*/
public Token<AbstractDelegationTokenIdentifier> getDelegationToken(URL url,
AuthenticatedURL.Token token, String renewer, String doAsUser)
throws IOException, AuthenticationException {
Map json = doDelegationTokenOperation(url, token,
DelegationTokenOperation.GETDELEGATIONTOKEN, renewer, null, true,
doAsUser);
json = (Map) json.get(DELEGATION_TOKEN_JSON);
String tokenStr = (String) json.get(DELEGATION_TOKEN_URL_STRING_JSON);
Token<AbstractDelegationTokenIdentifier> dToken =
new Token<AbstractDelegationTokenIdentifier>();
dToken.decodeFromUrlString(tokenStr);
InetSocketAddress service = new InetSocketAddress(url.getHost(),
url.getPort());
SecurityUtil.setTokenService(dToken, service);
return dToken;
}
/**
* Renews a delegation token from the server end-point using the
* configured <code>Authenticator</code> for authentication.
*
* @param url the URL to renew the delegation token from. Only HTTP/S URLs are
* supported.
* @param token the authentication token with the Delegation Token to renew.
* @param dToken abstract delegation token identifier.
* @throws IOException if an IO error occurred.
* @throws AuthenticationException if an authentication exception occurred.
* @return delegation token long value.
*/
public long renewDelegationToken(URL url,
AuthenticatedURL.Token token,
Token<AbstractDelegationTokenIdentifier> dToken)
throws IOException, AuthenticationException {
return renewDelegationToken(url, token, dToken, null);
}
/**
* Renews a delegation token from the server end-point using the
* configured <code>Authenticator</code> for authentication.
*
* @param url the URL to renew the delegation token from. Only HTTP/S URLs are
* supported.
* @param token the authentication token with the Delegation Token to renew.
* @param doAsUser the user to do as, which will be the token owner.
* @param dToken abstract delegation token identifier.
* @throws IOException if an IO error occurred.
* @throws AuthenticationException if an authentication exception occurred.
* @return delegation token long value.
*/
public long renewDelegationToken(URL url,
AuthenticatedURL.Token token,
Token<AbstractDelegationTokenIdentifier> dToken, String doAsUser)
throws IOException, AuthenticationException {
Map json = doDelegationTokenOperation(url, token,
DelegationTokenOperation.RENEWDELEGATIONTOKEN, null, dToken, true,
doAsUser);
return (Long) json.get(RENEW_DELEGATION_TOKEN_JSON);
}
/**
* Cancels a delegation token from the server end-point. It does not require
* being authenticated by the configured <code>Authenticator</code>.
*
* @param url the URL to cancel the delegation token from. Only HTTP/S URLs
* are supported.
* @param token the authentication token with the Delegation Token to cancel.
* @param dToken abstract delegation token identifier.
* @throws IOException if an IO error occurred.
*/
public void cancelDelegationToken(URL url,
AuthenticatedURL.Token token,
Token<AbstractDelegationTokenIdentifier> dToken)
throws IOException {
cancelDelegationToken(url, token, dToken, null);
}
/**
* Cancels a delegation token from the server end-point. It does not require
* being authenticated by the configured <code>Authenticator</code>.
*
* @param url the URL to cancel the delegation token from. Only HTTP/S URLs
* are supported.
* @param token the authentication token with the Delegation Token to cancel.
* @param dToken abstract delegation token identifier.
* @param doAsUser the user to do as, which will be the token owner.
* @throws IOException if an IO error occurred.
*/
public void cancelDelegationToken(URL url,
AuthenticatedURL.Token token,
Token<AbstractDelegationTokenIdentifier> dToken, String doAsUser)
throws IOException {
try {
doDelegationTokenOperation(url, token,
DelegationTokenOperation.CANCELDELEGATIONTOKEN, null, dToken, false,
doAsUser);
} catch (AuthenticationException ex) {
throw new IOException("This should not happen: " + ex.getMessage(), ex);
}
}
private Map doDelegationTokenOperation(URL url,
AuthenticatedURL.Token token, DelegationTokenOperation operation,
String renewer, Token<?> dToken, boolean hasResponse, String doAsUser)
throws IOException, AuthenticationException {
Map ret = null;
Map<String, String> params = new HashMap<String, String>();
params.put(OP_PARAM, operation.toString());
if (renewer != null) {
params.put(RENEWER_PARAM, renewer);
}
if (dToken != null) {
params.put(TOKEN_PARAM, dToken.encodeToUrlString());
}
// proxyuser
if (doAsUser != null) {
params.put(DelegationTokenAuthenticatedURL.DO_AS, doAsUser);
}
String urlStr = url.toExternalForm();
StringBuilder sb = new StringBuilder(urlStr);
String separator = (urlStr.contains("?")) ? "&" : "?";
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(separator).append(entry.getKey()).append("=").
append(URLEncoder.encode(entry.getValue(), "UTF8"));
separator = "&";
}
url = new URL(sb.toString());
AuthenticatedURL aUrl = new AuthenticatedURL(this, connConfigurator);
org.apache.hadoop.security.token.Token<AbstractDelegationTokenIdentifier>
dt = null;
if (token instanceof DelegationTokenAuthenticatedURL.Token
&& operation.requiresKerberosCredentials()) {
// Unset delegation token to trigger fall-back authentication.
dt = ((DelegationTokenAuthenticatedURL.Token) token).getDelegationToken();
((DelegationTokenAuthenticatedURL.Token) token).setDelegationToken(null);
}
HttpURLConnection conn = null;
try {
conn = aUrl.openConnection(url, token);
conn.setRequestMethod(operation.getHttpMethod());
HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_OK);
if (hasResponse) {
String contentType = conn.getHeaderField(CONTENT_TYPE);
contentType =
(contentType != null) ? StringUtils.toLowerCase(contentType) : null;
if (contentType != null &&
contentType.contains(APPLICATION_JSON_MIME)) {
try {
ret = JsonSerialization.mapReader().readValue(conn.getInputStream());
} catch (Exception ex) {
throw new AuthenticationException(String.format(
"'%s' did not handle the '%s' delegation token operation: %s",
url.getAuthority(), operation, ex.getMessage()), ex);
}
} else {
throw new AuthenticationException(String.format("'%s' did not " +
"respond with JSON to the '%s' delegation token operation",
url.getAuthority(), operation));
}
}
} finally {
if (dt != null) {
((DelegationTokenAuthenticatedURL.Token) token).setDelegationToken(dt);
}
if (conn != null) {
conn.disconnect();
}
}
return ret;
}
}
| DelegationTokenOperation |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/BeanParameterInvalidSyntaxTest.java | {
"start": 2447,
"end": 2928
} | class ____ {
public String echo(String body, int times) {
if (body == null) {
// use an empty string for no body
return "";
}
if (times > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++) {
sb.append(body);
}
return sb.toString();
}
return body;
}
}
}
| MyBean |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/unmappedsource/ErroneousStrictSourceTargetMapper.java | {
"start": 521,
"end": 767
} | interface ____ {
ErroneousStrictSourceTargetMapper INSTANCE = Mappers.getMapper( ErroneousStrictSourceTargetMapper.class );
Target sourceToTarget(Source source);
Source targetToSource(Target target);
}
| ErroneousStrictSourceTargetMapper |
java | elastic__elasticsearch | modules/dot-prefix-validation/src/test/java/org/elasticsearch/validation/DotPrefixValidatorTests.java | {
"start": 1148,
"end": 6110
} | class ____ extends ESTestCase {
private final OperatorValidator<?> opV = new OperatorValidator<>(true);
private final NonOperatorValidator<?> nonOpV = new NonOperatorValidator<>(true);
private static ClusterService clusterService;
@BeforeClass
public static void beforeClass() {
List<String> allowed = new ArrayList<>(DotPrefixValidator.IGNORED_INDEX_PATTERNS_SETTING.getDefault(Settings.EMPTY));
// Add a new allowed pattern for testing
allowed.add("\\.potato\\d+");
Settings settings = Settings.builder()
.put(DotPrefixValidator.IGNORED_INDEX_PATTERNS_SETTING.getKey(), Strings.collectionToCommaDelimitedString(allowed))
.build();
clusterService = mock(ClusterService.class);
ClusterSettings clusterSettings = new ClusterSettings(
settings,
Sets.newHashSet(DotPrefixValidator.VALIDATE_DOT_PREFIXES, DotPrefixValidator.IGNORED_INDEX_PATTERNS_SETTING)
);
when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
when(clusterService.getSettings()).thenReturn(settings);
when(clusterService.threadPool()).thenReturn(mock(ThreadPool.class));
}
public void testValidation() {
nonOpV.validateIndices(Set.of("regular"));
opV.validateIndices(Set.of("regular"));
assertFails(Set.of(".regular"));
opV.validateIndices(Set.of(".regular"));
assertFails(Set.of("first", ".second"));
assertFails(Set.of("<.regular-{MM-yy-dd}>"));
assertFails(Set.of(".this_index_contains_an_excepted_pattern.ml-annotations-1"));
// Test ignored names
nonOpV.validateIndices(Set.of(".elastic-connectors-v1"));
nonOpV.validateIndices(Set.of(".elastic-connectors-sync-jobs-v1"));
nonOpV.validateIndices(Set.of(".ml-state"));
nonOpV.validateIndices(Set.of(".ml-state-000001"));
nonOpV.validateIndices(Set.of(".ml-stats-000001"));
nonOpV.validateIndices(Set.of(".ml-anomalies-unrelated"));
// Test ignored patterns
nonOpV.validateIndices(Set.of(".ml-annotations-21309"));
nonOpV.validateIndices(Set.of(".ml-annotations-2"));
nonOpV.validateIndices(Set.of(".ml-state-21309"));
nonOpV.validateIndices(Set.of("<.ml-state-21309>"));
nonOpV.validateIndices(Set.of(".slo-observability.sli-v2"));
nonOpV.validateIndices(Set.of(".slo-observability.sli-v2.3"));
nonOpV.validateIndices(Set.of(".slo-observability.sli-v2.3-2024-01-01"));
nonOpV.validateIndices(Set.of("<.slo-observability.sli-v3.3.{2024-10-16||/M{yyyy-MM-dd|UTC}}>"));
nonOpV.validateIndices(Set.of(".slo-observability.summary-v2"));
nonOpV.validateIndices(Set.of(".slo-observability.summary-v2.3"));
nonOpV.validateIndices(Set.of(".slo-observability.summary-v2.3-2024-01-01"));
nonOpV.validateIndices(Set.of("<.slo-observability.summary-v3.3.{2024-10-16||/M{yyyy-MM-dd|UTC}}>"));
nonOpV.validateIndices(Set.of(".entities.v1.latest.builtin_services_from_ecs_data"));
nonOpV.validateIndices(Set.of(".entities.v1.history.2025-09-16.security_host_default"));
nonOpV.validateIndices(Set.of(".entities.v2.history.2025-09-16.security_user_custom"));
nonOpV.validateIndices(Set.of(".entities.v5.reset.security_user_custom"));
nonOpV.validateIndices(Set.of(".entities.v1.latest.noop"));
nonOpV.validateIndices(Set.of(".entities.v92.latest.eggplant.potato"));
nonOpV.validateIndices(Set.of("<.entities.v12.latest.eggplant-{M{yyyy-MM-dd|UTC}}>"));
nonOpV.validateIndices(Set.of(".monitoring-es-8-thing"));
nonOpV.validateIndices(Set.of("<.monitoring-es-8-thing>"));
nonOpV.validateIndices(Set.of(".monitoring-logstash-8-thing"));
nonOpV.validateIndices(Set.of("<.monitoring-logstash-8-thing>"));
nonOpV.validateIndices(Set.of(".monitoring-kibana-8-thing"));
nonOpV.validateIndices(Set.of("<.monitoring-kibana-8-thing>"));
nonOpV.validateIndices(Set.of(".monitoring-beats-8-thing"));
nonOpV.validateIndices(Set.of("<.monitoring-beats-8-thing>"));
nonOpV.validateIndices(Set.of(".monitoring-ent-search-8-thing"));
nonOpV.validateIndices(Set.of("<.monitoring-ent-search-8-thing>"));
// Test pattern added to the settings
nonOpV.validateIndices(Set.of(".potato5"));
nonOpV.validateIndices(Set.of("<.potato5>"));
}
private void assertFails(Set<String> indices) {
var validator = new NonOperatorValidator<>(false);
validator.validateIndices(indices);
assertWarnings(
"Index ["
+ indices.stream().filter(i -> i.startsWith(".") || i.startsWith("<.")).toList().get(0)
+ "] name begins with a dot (.), which is deprecated, and will not be allowed in a future Elasticsearch version."
);
}
private | DotPrefixValidatorTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/JUnit3TestNotRunTest.java | {
"start": 9029,
"end": 9613
} | class ____ extends TestCase {
public void testDoesStuff() {}
}
""")
.doTest();
}
@Test
public void negativeCase1() {
compilationHelper
.addSourceLines(
"JUnit3TestNotRunNegativeCase1.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import junit.framework.TestCase;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author rburny@google.com (Radoslaw Burny)
*/
public | DoesStuffTest |
java | jhy__jsoup | src/main/java/org/jsoup/helper/HttpConnection.java | {
"start": 48832,
"end": 50921
} | class ____ implements Connection.KeyVal {
private String key;
private String value;
private @Nullable InputStream stream;
private @Nullable String contentType;
public static KeyVal create(String key, String value) {
return new KeyVal(key, value);
}
public static KeyVal create(String key, String filename, InputStream stream) {
return new KeyVal(key, filename)
.inputStream(stream);
}
private KeyVal(String key, String value) {
Validate.notEmptyParam(key, "key");
Validate.notNullParam(value, "value");
this.key = key;
this.value = value;
}
@Override
public KeyVal key(String key) {
Validate.notEmptyParam(key, "key");
this.key = key;
return this;
}
@Override
public String key() {
return key;
}
@Override
public KeyVal value(String value) {
Validate.notNullParam(value, "value");
this.value = value;
return this;
}
@Override
public String value() {
return value;
}
@Override
public KeyVal inputStream(InputStream inputStream) {
Validate.notNullParam(value, "inputStream");
this.stream = inputStream;
return this;
}
@Override @Nullable
public InputStream inputStream() {
return stream;
}
@Override
public boolean hasInputStream() {
return stream != null;
}
@Override
public Connection.KeyVal contentType(String contentType) {
Validate.notEmpty(contentType);
this.contentType = contentType;
return this;
}
@Override @Nullable
public String contentType() {
return contentType;
}
@Override
public String toString() {
return key + "=" + value;
}
}
}
| KeyVal |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/chararray/CharArrayAssert_containsOnly_Test.java | {
"start": 965,
"end": 1318
} | class ____ extends CharArrayAssertBaseTest {
@Override
protected CharArrayAssert invoke_api_method() {
return assertions.containsOnly('a', 'b');
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertContainsOnly(getInfo(assertions), getActual(assertions), arrayOf('a', 'b'));
}
}
| CharArrayAssert_containsOnly_Test |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/results/ClassificationFeatureImportanceTests.java | {
"start": 782,
"end": 3326
} | class ____ extends AbstractXContentSerializingTestCase<ClassificationFeatureImportance> {
@Override
protected ClassificationFeatureImportance doParseInstance(XContentParser parser) throws IOException {
return ClassificationFeatureImportance.fromXContent(parser);
}
@Override
protected Writeable.Reader<ClassificationFeatureImportance> instanceReader() {
return ClassificationFeatureImportance::new;
}
@Override
protected ClassificationFeatureImportance createTestInstance() {
return createRandomInstance();
}
@Override
protected ClassificationFeatureImportance mutateInstance(ClassificationFeatureImportance instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@SuppressWarnings("unchecked")
public static ClassificationFeatureImportance createRandomInstance() {
Supplier<Object> classNameGenerator = randomFrom(
() -> randomAlphaOfLength(10),
ESTestCase::randomBoolean,
() -> randomIntBetween(0, 10)
);
return new ClassificationFeatureImportance(
randomAlphaOfLength(10),
Stream.generate(classNameGenerator)
.limit(randomLongBetween(2, 10))
.map(name -> new ClassificationFeatureImportance.ClassImportance(name, randomDoubleBetween(-10, 10, false)))
.collect(Collectors.toList())
);
}
public void testGetTotalImportance_GivenBinary() {
ClassificationFeatureImportance featureImportance = new ClassificationFeatureImportance(
"binary",
Arrays.asList(
new ClassificationFeatureImportance.ClassImportance("a", 0.15),
new ClassificationFeatureImportance.ClassImportance("not-a", -0.15)
)
);
assertThat(featureImportance.getTotalImportance(), equalTo(0.15));
}
public void testGetTotalImportance_GivenMulticlass() {
ClassificationFeatureImportance featureImportance = new ClassificationFeatureImportance(
"multiclass",
Arrays.asList(
new ClassificationFeatureImportance.ClassImportance("a", 0.15),
new ClassificationFeatureImportance.ClassImportance("b", -0.05),
new ClassificationFeatureImportance.ClassImportance("c", 0.30)
)
);
assertThat(featureImportance.getTotalImportance(), closeTo(0.50, 0.00000001));
}
}
| ClassificationFeatureImportanceTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_2795/Issue2795Mapper.java | {
"start": 332,
"end": 725
} | interface ____ {
void update(Source update, @MappingTarget Target destination);
void update(NestedDto update, @MappingTarget Nested destination);
static <T> T unwrap(Optional<T> optional) {
return optional.orElse( null );
}
@Condition
static <T> boolean isNotEmpty(Optional<T> field) {
return field != null && field.isPresent();
}
}
| Issue2795Mapper |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/IdentifierName.java | {
"start": 3624,
"end": 5280
} | class ____ extends BugChecker
implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher {
private static final Supplier<ImmutableSet<Name>> EXEMPTED_CLASS_ANNOTATIONS =
VisitorState.memoize(
s ->
Stream.of("org.robolectric.annotation.Implements")
.map(s::getName)
.collect(toImmutableSet()));
private static final Supplier<ImmutableSet<Name>> EXEMPTED_METHOD_ANNOTATIONS =
VisitorState.memoize(
s ->
Stream.of(
"com.pholser.junit.quickcheck.Property",
"com.google.caliper.Benchmark",
"com.google.caliper.api.Macrobenchmark",
"com.google.caliper.api.Footprint")
.map(s::getName)
.collect(toImmutableSet()));
private static final String STATIC_VARIABLE_FINDING =
"Static variables should be named in UPPER_SNAKE_CASE if deeply immutable or lowerCamelCase"
+ " if not";
private static final String INITIALISM_DETAIL =
", with acronyms treated as words"
+ " (https://google.github.io/styleguide/javaguide.html#s5.3-camel-case)";
private final IdentifierNames identifierNames;
@Inject
IdentifierName(IdentifierNames identifierNames) {
this.identifierNames = identifierNames;
}
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ClassSymbol symbol = getSymbol(tree);
String name = tree.getSimpleName().toString();
if (name.isEmpty() || identifierNames.isConformantTypeName(name)) {
// The name can be empty for | IdentifierName |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/StringFieldTest2.java | {
"start": 658,
"end": 947
} | class ____ {
@JSONField(serialzeFeatures=SerializerFeature.WriteNullStringAsEmpty)
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
| V0 |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/method/annotation/MethodArgumentTypeMismatchException.java | {
"start": 1098,
"end": 1873
} | class ____ extends TypeMismatchException {
private final String name;
private final MethodParameter parameter;
public MethodArgumentTypeMismatchException(@Nullable Object value,
@Nullable Class<?> requiredType, String name, MethodParameter param, @Nullable Throwable cause) {
super(value, requiredType, cause);
this.name = name;
this.parameter = param;
initPropertyName(name);
}
/**
* Return the name of the method argument.
*/
public String getName() {
return this.name;
}
/**
* Return the target method parameter.
*/
public MethodParameter getParameter() {
return this.parameter;
}
@Override
public String getMessage() {
return "Method parameter '" + getName() + "': " + super.getMessage();
}
}
| MethodArgumentTypeMismatchException |
java | apache__flink | flink-clients/src/main/java/org/apache/flink/client/cli/CliFrontend.java | {
"start": 49509,
"end": 49708
} | interface ____ encapsulate cluster actions which are executed via the {@link
* ClusterClient}.
*
* @param <ClusterID> type of the cluster id
*/
@FunctionalInterface
private | to |
java | apache__spark | common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/OneForOneBlockFetcher.java | {
"start": 11693,
"end": 14210
} | class ____ implements ChunkReceivedCallback {
@Override
public void onSuccess(int chunkIndex, ManagedBuffer buffer) {
// On receipt of a chunk, pass it upwards as a block.
listener.onBlockFetchSuccess(blockIds[chunkIndex], buffer);
}
@Override
public void onFailure(int chunkIndex, Throwable e) {
// On receipt of a failure, fail every block from chunkIndex onwards.
String[] remainingBlockIds = Arrays.copyOfRange(blockIds, chunkIndex, blockIds.length);
failRemainingBlocks(remainingBlockIds, e);
}
}
/**
* Begins the fetching process, calling the listener with every block fetched.
* The given message will be serialized with the Java serializer, and the RPC must return a
* {@link StreamHandle}. We will send all fetch requests immediately, without throttling.
*/
public void start() {
client.sendRpc(message.toByteBuffer(), new RpcResponseCallback() {
@Override
public void onSuccess(ByteBuffer response) {
try {
streamHandle = (StreamHandle) BlockTransferMessage.Decoder.fromByteBuffer(response);
logger.trace("Successfully opened blocks {}, preparing to fetch chunks.", streamHandle);
// Immediately request all chunks -- we expect that the total size of the request is
// reasonable due to higher level chunking in [[ShuffleBlockFetcherIterator]].
for (int i = 0; i < streamHandle.numChunks; i++) {
if (downloadFileManager != null) {
client.stream(OneForOneStreamManager.genStreamChunkId(streamHandle.streamId, i),
new DownloadCallback(i));
} else {
client.fetchChunk(streamHandle.streamId, i, chunkCallback);
}
}
} catch (Exception e) {
logger.error("Failed while starting block fetches after success", e);
failRemainingBlocks(blockIds, e);
}
}
@Override
public void onFailure(Throwable e) {
logger.error("Failed while starting block fetches", e);
failRemainingBlocks(blockIds, e);
}
});
}
/** Invokes the "onBlockFetchFailure" callback for every listed block id. */
private void failRemainingBlocks(String[] failedBlockIds, Throwable e) {
for (String blockId : failedBlockIds) {
try {
listener.onBlockFetchFailure(blockId, e);
} catch (Exception e2) {
logger.error("Error in block fetch failure callback", e2);
}
}
}
private | ChunkCallback |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/jbang/JBangAugmentorImpl.java | {
"start": 1471,
"end": 3850
} | class ____ implements BiConsumer<CuratedApplication, Map<String, Object>> {
private static final Logger log = Logger.getLogger(JBangAugmentorImpl.class);
@Override
public void accept(CuratedApplication curatedApplication, Map<String, Object> resultMap) {
QuarkusClassLoader classLoader = curatedApplication.getOrCreateAugmentClassLoader();
try (QuarkusClassLoader deploymentClassLoader = curatedApplication.createDeploymentClassLoader()) {
QuarkusBootstrap quarkusBootstrap = curatedApplication.getQuarkusBootstrap();
QuarkusAugmentor.Builder builder = QuarkusAugmentor.builder()
.setRoot(quarkusBootstrap.getApplicationRoot())
.setClassLoader(classLoader)
.addFinal(ApplicationClassNameBuildItem.class)
.setTargetDir(quarkusBootstrap.getTargetDirectory())
.setDeploymentClassLoader(curatedApplication.createDeploymentClassLoader())
.setBuildSystemProperties(quarkusBootstrap.getBuildSystemProperties())
.setRuntimeProperties(quarkusBootstrap.getRuntimeProperties())
.setEffectiveModel(curatedApplication.getApplicationModel());
if (quarkusBootstrap.getBaseName() != null) {
builder.setBaseName(quarkusBootstrap.getBaseName());
}
if (quarkusBootstrap.getOriginalBaseName() != null) {
builder.setOriginalBaseName(quarkusBootstrap.getOriginalBaseName());
}
boolean auxiliaryApplication = curatedApplication.getQuarkusBootstrap().isAuxiliaryApplication();
builder.setAuxiliaryApplication(auxiliaryApplication);
builder.setAuxiliaryDevModeType(
curatedApplication.getQuarkusBootstrap().isHostApplicationIsTestOnly() ? DevModeType.TEST_ONLY
: (auxiliaryApplication ? DevModeType.LOCAL : null));
builder.setLaunchMode(LaunchMode.NORMAL);
builder.setRebuild(quarkusBootstrap.isRebuild());
builder.setLiveReloadState(
new LiveReloadBuildItem(false, Collections.emptySet(), new HashMap<>(), null));
for (AdditionalDependency i : quarkusBootstrap.getAdditionalApplicationArchives()) {
//this gets added to the | JBangAugmentorImpl |
java | apache__camel | components/camel-kubernetes/src/generated/java/org/apache/camel/component/kubernetes/services/KubernetesServicesComponentConfigurer.java | {
"start": 746,
"end": 3263
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
KubernetesServicesComponent target = (KubernetesServicesComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "kubernetesclient":
case "kubernetesClient": target.setKubernetesClient(property(camelContext, io.fabric8.kubernetes.client.KubernetesClient.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public String[] getAutowiredNames() {
return new String[]{"kubernetesClient"};
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "kubernetesclient":
case "kubernetesClient": return io.fabric8.kubernetes.client.KubernetesClient.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
KubernetesServicesComponent target = (KubernetesServicesComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "kubernetesclient":
case "kubernetesClient": return target.getKubernetesClient();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
default: return null;
}
}
}
| KubernetesServicesComponentConfigurer |
java | quarkusio__quarkus | extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/checker/PermissionChecker4thMethodArg.java | {
"start": 273,
"end": 525
} | class ____ extends AbstractNthMethodArgChecker {
@Inject
SecurityIdentity identity;
@PermissionChecker("4th-arg")
boolean is4thMethodArgOk(Object four) {
return this.argsOk(4, four, identity);
}
}
| PermissionChecker4thMethodArg |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java | {
"start": 17293,
"end": 17923
} | class ____ {
// both are reference beans, same bean name and type, but difference attributes from xml config
@DubboReference(
group = "demo",
version = "1.2.3",
consumer = "my-consumer",
init = false,
scope = "local",
timeout = 100)
private DemoService demoService;
}
@Configuration
@ImportResource({
"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml",
"classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"
})
static | ConsumerConfiguration2 |
java | apache__camel | components/camel-saxon/src/test/java/org/apache/camel/component/xquery/XQueryEndpointConfigurationTest.java | {
"start": 1365,
"end": 2747
} | class ____ extends CamelSpringTestSupport {
@Test
public void testComponentConfiguration() {
Configuration configuration = context.getRegistry().lookupByNameAndType("saxon-configuration", Configuration.class);
Map<String, Object> properties = context.getRegistry().lookupByNameAndType("saxon-properties", Map.class);
XQueryComponent component = context.getComponent("xquery", XQueryComponent.class);
XQueryEndpoint endpoint = null;
assertNotNull(configuration);
assertNotNull(properties);
for (Endpoint ep : context.getEndpoints()) {
if (ep instanceof XQueryEndpoint) {
endpoint = (XQueryEndpoint) ep;
break;
}
}
assertNotNull(component);
assertNotNull(endpoint);
assertNull(component.getConfiguration());
assertTrue(component.getConfigurationProperties().isEmpty());
assertNotNull(endpoint.getConfiguration());
assertNotNull(endpoint.getConfigurationProperties());
assertEquals(configuration, endpoint.getConfiguration());
assertEquals(properties, endpoint.getConfigurationProperties());
}
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return newAppContext("XQueryEndpointConfigurationTest.xml");
}
}
| XQueryEndpointConfigurationTest |
java | spring-projects__spring-security | config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/NamespaceLdapAuthenticationProviderTestsConfigs.java | {
"start": 3651,
"end": 4183
} | class ____ {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
.groupSearchBase("ou=groups")
.userSearchFilter("(uid={0})")
.passwordCompare()
.passwordEncoder(new BCryptPasswordEncoder()) // ldap-authentication-provider/password-compare/password-encoder@ref
.passwordAttribute("userPassword"); // ldap-authentication-provider/password-compare@password-attribute
// @formatter:on
}
}
}
| PasswordCompareLdapConfig |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/junit/jupiter/BDDSoftAssertionsExtensionIntegrationTest.java | {
"start": 2801,
"end": 3591
} | class ____ {
@Test
@Order(1)
void multipleFailures(BDDSoftAssertions softly) {
softly.then(1).isEqualTo(0);
softly.then(2).isEqualTo(2);
softly.then(3).isEqualTo(4);
}
@Test
@Order(2)
void allAssertionsShouldPass(BDDSoftAssertions softly) {
softly.then(1).isEqualTo(1);
softly.then(list(1, 2)).containsOnly(1, 2);
}
@ParameterizedTest
@CsvSource({ "1, 1, 2", "1, 2, 3" })
@Order(3)
void parameterizedTest(int a, int b, int sum, BDDSoftAssertions softly) {
softly.then(a + b).as("sum").isEqualTo(sum);
softly.then(a).as("operand 1 is equal to operand 2").isEqualTo(b);
}
}
@TestInstance(PER_METHOD)
@Disabled("Executed via the JUnit Platform Test Kit")
static | AbstractSoftAssertionsExample |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/spi/EnumMappingStrategy.java | {
"start": 574,
"end": 800
} | enum ____ mapping strategy
*
* @param processingEnvironment environment for facilities
*/
default void init(MapStructProcessingEnvironment processingEnvironment) {
}
/**
* Return the default | value |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsInOutBeanReturnNullTest.java | {
"start": 4500,
"end": 4787
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
public final String name;
public MyBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
| MyBean |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/DecommissioningNodesWatcher.java | {
"start": 9380,
"end": 13783
} | class ____ extends TimerTask {
private final RMContext rmContext;
public PollTimerTask(RMContext rmContext) {
this.rmContext = rmContext;
}
public void run() {
logDecommissioningNodesStatus();
long now = mclock.getTime();
Set<NodeId> staleNodes = new HashSet<NodeId>();
for (Iterator<Map.Entry<NodeId, DecommissioningNodeContext>> it =
decomNodes.entrySet().iterator(); it.hasNext();) {
Map.Entry<NodeId, DecommissioningNodeContext> e = it.next();
DecommissioningNodeContext d = e.getValue();
// Skip node recently updated (NM usually updates every second).
if (now - d.lastUpdateTime < 5000L) {
continue;
}
// Remove stale non-DECOMMISSIONING node
if (d.nodeState != NodeState.DECOMMISSIONING) {
LOG.debug("remove {} {}", d.nodeState, d.nodeId);
it.remove();
continue;
} else if (now - d.lastUpdateTime > 60000L) {
// Node DECOMMISSIONED could become stale, remove as necessary.
RMNode rmNode = getRmNode(d.nodeId);
if (rmNode != null &&
rmNode.getState() == NodeState.DECOMMISSIONED) {
LOG.debug("remove {} {}", rmNode.getState(), d.nodeId);
it.remove();
continue;
}
}
if (d.timeoutMs >= 0 &&
d.decommissioningStartTime + d.timeoutMs < now) {
staleNodes.add(d.nodeId);
LOG.debug("Identified stale and timeout node {}", d.nodeId);
}
}
for (NodeId nodeId : staleNodes) {
RMNode rmNode = this.rmContext.getRMNodes().get(nodeId);
if (rmNode == null || rmNode.getState() != NodeState.DECOMMISSIONING) {
remove(nodeId);
continue;
}
if (rmNode.getState() == NodeState.DECOMMISSIONING &&
checkReadyToBeDecommissioned(rmNode.getNodeID())) {
LOG.info("DECOMMISSIONING " + nodeId + " timeout");
this.rmContext.getDispatcher().getEventHandler().handle(
new RMNodeEvent(nodeId, RMNodeEventType.DECOMMISSION));
}
}
}
}
private RMNode getRmNode(NodeId nodeId) {
RMNode rmNode = this.rmContext.getRMNodes().get(nodeId);
if (rmNode == null) {
rmNode = this.rmContext.getInactiveRMNodes().get(nodeId);
}
return rmNode;
}
// Time in second to be decommissioned.
private int getTimeoutInSec(DecommissioningNodeContext context) {
if (context.nodeState == NodeState.DECOMMISSIONED) {
return 0;
} else if (context.nodeState != NodeState.DECOMMISSIONING) {
return -1;
}
if (context.appIds.size() == 0 && context.numActiveContainers == 0) {
return 0;
}
// negative timeout value means no timeout (infinite timeout).
if (context.timeoutMs < 0) {
return -1;
}
long now = mclock.getTime();
long timeout = context.decommissioningStartTime + context.timeoutMs - now;
return Math.max(0, (int)(timeout / 1000));
}
private void logDecommissioningNodesStatus() {
if (!LOG.isDebugEnabled() || decomNodes.size() == 0) {
return;
}
long now = mclock.getTime();
for (DecommissioningNodeContext d : decomNodes.values()) {
StringBuilder sb = new StringBuilder();
DecommissioningNodeStatus s = checkDecommissioningStatus(d.nodeId);
sb.append(String.format(
"%n %-34s %4ds fresh:%3ds containers:%2d %14s",
d.nodeId.getHost(),
(now - d.decommissioningStartTime) / 1000,
(now - d.lastUpdateTime) / 1000,
d.numActiveContainers,
s));
if (s == DecommissioningNodeStatus.WAIT_APP ||
s == DecommissioningNodeStatus.WAIT_CONTAINER) {
sb.append(String.format(" timeout:%4ds", getTimeoutInSec(d)));
}
for (ApplicationId aid : d.appIds) {
sb.append("\n " + aid);
RMApp rmApp = rmContext.getRMApps().get(aid);
if (rmApp != null) {
sb.append(String.format(
" %s %9s %5.2f%% %5ds",
rmApp.getState(),
(rmApp.getApplicationType() == null)?
"" : rmApp.getApplicationType(),
100.0 * rmApp.getProgress(),
(mclock.getTime() - rmApp.getStartTime()) / 1000));
}
}
LOG.debug("Decommissioning node: " + sb.toString());
}
}
}
| PollTimerTask |
java | alibaba__fastjson | src/test/java/data/media/writeAsArray/MediaContentSerializer.java | {
"start": 353,
"end": 1304
} | class ____ implements ObjectSerializer {
private MediaSerializer mediaSerilaizer = new MediaSerializer();
private ImageSerializer imageSerilaizer = new ImageSerializer();
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
MediaContent entity = (MediaContent) object;
SerializeWriter out = serializer.getWriter();
out.write('[');
mediaSerilaizer.write(serializer, entity.getMedia(), "media", Media.class, 0);
out.write(',');
out.write('[');
for (int i = 0; i < entity.getImages().size(); ++i) {
if (i != 0) {
out.write(',');
}
Image image = entity.getImages().get(i);
imageSerilaizer.write(serializer, image, i, fieldType, 0);
}
out.write(']');
out.write(']');
}
} | MediaContentSerializer |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/metrics/DefaultCommandLatencyCollectorOptionsUnitTests.java | {
"start": 294,
"end": 1185
} | class ____ {
@Test
void testDefault() {
DefaultCommandLatencyCollectorOptions sut = DefaultCommandLatencyCollectorOptions.create();
assertThat(sut.targetPercentiles()).hasSize(5);
assertThat(sut.targetUnit()).isEqualTo(TimeUnit.MICROSECONDS);
}
@Test
void testDisabled() {
DefaultCommandLatencyCollectorOptions sut = DefaultCommandLatencyCollectorOptions.disabled();
assertThat(sut.isEnabled()).isEqualTo(false);
}
@Test
void testBuilder() {
DefaultCommandLatencyCollectorOptions sut = DefaultCommandLatencyCollectorOptions.builder().targetUnit(TimeUnit.HOURS)
.targetPercentiles(new double[] { 1, 2, 3 }).build();
assertThat(sut.targetPercentiles()).hasSize(3);
assertThat(sut.targetUnit()).isEqualTo(TimeUnit.HOURS);
}
}
| DefaultCommandLatencyCollectorOptionsUnitTests |
java | quarkusio__quarkus | integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/ProtectedResource3.java | {
"start": 222,
"end": 587
} | class ____ {
@GET
public String getName() {
// CodeFlowTest#testAuthenticationCompletionFailedNoStateCookie checks that if a state cookie is missing
// then 401 is returned when a redirect targets the endpoint requiring authentication
throw new InternalServerErrorException("This method must not be invoked");
}
}
| ProtectedResource3 |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java | {
"start": 103247,
"end": 103778
} | class ____ {
private final ClassInfo classInfo;
private final Set<String> classNameBindings;
private final MethodInfo methodInfo;
private final DotName httpMethod;
private FoundEndpoint(ClassInfo classInfo, Set<String> classNameBindings, MethodInfo methodInfo, DotName httpMethod) {
this.classInfo = classInfo;
this.classNameBindings = classNameBindings;
this.methodInfo = methodInfo;
this.httpMethod = httpMethod;
}
}
}
| FoundEndpoint |
java | quarkusio__quarkus | extensions/smallrye-fault-tolerance/runtime/src/main/java/io/quarkus/smallrye/faulttolerance/runtime/config/SmallRyeFaultToleranceConfig.java | {
"start": 10639,
"end": 11672
} | interface ____ {
/**
* Whether the {@code @ExponentialBackoff} strategy is enabled.
*/
@ConfigDocDefault("true")
Optional<Boolean> enabled();
/**
* The multiplicative factor used when determining a delay between two retries. A delay is computed
* as {@code factor * previousDelay}, resulting in an exponential growth.
*
* @see ExponentialBackoff#factor()
*/
@ConfigDocDefault("2")
OptionalInt factor();
/**
* The maximum delay between retries.
*
* @see ExponentialBackoff#maxDelay()
*/
@ConfigDocDefault("1 minute")
OptionalLong maxDelay();
/**
* The unit for {@link #maxDelay()}.
*
* @see ExponentialBackoff#maxDelayUnit()
*/
Optional<ChronoUnit> maxDelayUnit();
}
| ExponentialBackoffConfig |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportAnnotationDetectionTests.java | {
"start": 3951,
"end": 4063
} | class ____ {
@Bean
TestBean testBean2() {
return new TestBean("2a");
}
}
@Configuration
static | Config2a |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_contains_CharSequence_Test.java | {
"start": 922,
"end": 1269
} | class ____ extends CharSequenceAssertBaseTest {
@Override
protected CharSequenceAssert invoke_api_method() {
return assertions.contains("od");
}
@Override
protected void verify_internal_effects() {
verify(strings).assertContains(getInfo(assertions), getActual(assertions), "od");
}
}
| CharSequenceAssert_contains_CharSequence_Test |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/state/v2/StateDescriptor.java | {
"start": 1419,
"end": 1680
} | class ____ state descriptors. A {@code StateDescriptor} is used for creating partitioned
* State in stateful operations internally.
*
* @param <T> The type of the value of the state object described by this state descriptor.
*/
@Experimental
public abstract | for |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java | {
"start": 2319,
"end": 6856
} | class ____ implements ContextSelector, LoggerContextShutdownAware {
protected static final StatusLogger LOGGER = StatusLogger.getLogger();
protected static final ConcurrentMap<String, AtomicReference<WeakReference<LoggerContext>>> CONTEXT_MAP =
new ConcurrentHashMap<>();
private final Lazy<LoggerContext> defaultLoggerContext = Lazy.lazy(() -> createContext(defaultContextName(), null));
@Override
public void shutdown(
final String fqcn, final ClassLoader loader, final boolean currentContext, final boolean allContexts) {
LoggerContext ctx = null;
if (currentContext) {
ctx = ContextAnchor.THREAD_CONTEXT.get();
} else if (loader != null) {
ctx = findContext(loader);
} else {
final Class<?> clazz = StackLocatorUtil.getCallerClass(fqcn);
if (clazz != null) {
ctx = findContext(clazz.getClassLoader());
}
if (ctx == null) {
ctx = ContextAnchor.THREAD_CONTEXT.get();
}
}
if (ctx != null) {
ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS);
}
}
@Override
public void contextShutdown(final org.apache.logging.log4j.spi.LoggerContext loggerContext) {
if (loggerContext instanceof LoggerContext) {
removeContext((LoggerContext) loggerContext);
}
}
@Override
public boolean hasContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
LoggerContext ctx;
if (currentContext) {
ctx = ContextAnchor.THREAD_CONTEXT.get();
} else if (loader != null) {
ctx = findContext(loader);
} else {
final Class<?> clazz = StackLocatorUtil.getCallerClass(fqcn);
if (clazz != null) {
ctx = findContext(clazz.getClassLoader());
} else {
ctx = ContextAnchor.THREAD_CONTEXT.get();
}
}
return ctx != null && ctx.isStarted();
}
private LoggerContext findContext(final ClassLoader loaderOrNull) {
final ClassLoader loader = loaderOrNull != null ? loaderOrNull : ClassLoader.getSystemClassLoader();
final String name = toContextMapKey(loader);
final AtomicReference<WeakReference<LoggerContext>> ref = CONTEXT_MAP.get(name);
if (ref != null) {
final WeakReference<LoggerContext> weakRef = ref.get();
return weakRef.get();
}
return null;
}
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
return getContext(fqcn, loader, currentContext, null);
}
@Override
public LoggerContext getContext(
final String fqcn, final ClassLoader loader, final boolean currentContext, final URI configLocation) {
return getContext(fqcn, loader, null, currentContext, configLocation);
}
@Override
public LoggerContext getContext(
final String fqcn,
final ClassLoader loader,
final Map.Entry<String, Object> entry,
final boolean currentContext,
final URI configLocation) {
if (currentContext) {
final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
if (ctx != null) {
return ctx;
}
return getDefault();
} else if (loader != null) {
return locateContext(loader, entry, configLocation);
} else {
final Class<?> clazz = StackLocatorUtil.getCallerClass(fqcn);
if (clazz != null) {
return locateContext(clazz.getClassLoader(), entry, configLocation);
}
final LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
if (lc != null) {
return lc;
}
return getDefault();
}
}
@Override
public void removeContext(final LoggerContext context) {
for (final Map.Entry<String, AtomicReference<WeakReference<LoggerContext>>> entry : CONTEXT_MAP.entrySet()) {
final LoggerContext ctx = entry.getValue().get().get();
if (ctx == context) {
CONTEXT_MAP.remove(entry.getKey());
}
}
}
@Override
public boolean isClassLoaderDependent() {
// By definition the ClassLoaderContextSelector depends on the callers | ClassLoaderContextSelector |
java | elastic__elasticsearch | build-tools/src/testFixtures/java/org/elasticsearch/gradle/internal/test/NormalizeOutputGradleRunner.java | {
"start": 1150,
"end": 4447
} | class ____ extends GradleRunner {
private GradleRunner delegate;
public NormalizeOutputGradleRunner(GradleRunner delegate) {
this.delegate = delegate;
}
@Override
public GradleRunner withGradleVersion(String gradleVersion) {
delegate.withGradleVersion(gradleVersion);
return this;
}
@Override
public GradleRunner withGradleInstallation(File file) {
delegate.withGradleInstallation(file);
return this;
}
@Override
public GradleRunner withGradleDistribution(URI uri) {
delegate.withGradleDistribution(uri);
return this;
}
@Override
public GradleRunner withTestKitDir(File file) {
delegate.withTestKitDir(file);
return this;
}
@Override
public File getProjectDir() {
return delegate.getProjectDir();
}
@Override
public GradleRunner withProjectDir(File projectDir) {
delegate.withProjectDir(projectDir);
return this;
}
@Override
public List<String> getArguments() {
return delegate.getArguments();
}
@Override
public GradleRunner withArguments(List<String> arguments) {
delegate.withArguments(arguments);
return this;
}
@Override
public GradleRunner withArguments(String... arguments) {
withArguments(List.of(arguments));
return this;
}
@Override
public List<? extends File> getPluginClasspath() {
return delegate.getPluginClasspath();
}
@Override
public GradleRunner withPluginClasspath() throws InvalidPluginMetadataException {
delegate.withPluginClasspath();
return this;
}
@Override
public GradleRunner withPluginClasspath(Iterable<? extends File> iterable) {
delegate.withPluginClasspath(iterable);
return this;
}
@Override
public boolean isDebug() {
return delegate.isDebug();
}
@Override
public GradleRunner withDebug(boolean b) {
delegate.withDebug(b);
return this;
}
@Override
public Map<String, String> getEnvironment() {
return delegate.getEnvironment();
}
@Override
public GradleRunner withEnvironment(Map<String, String> map) {
delegate.withEnvironment(map);
return this;
}
@Override
public GradleRunner forwardStdOutput(Writer writer) {
delegate.forwardStdOutput(writer);
return this;
}
@Override
public GradleRunner forwardStdError(Writer writer) {
delegate.forwardStdOutput(writer);
return this;
}
@Override
public GradleRunner forwardOutput() {
delegate.forwardOutput();
return this;
}
@Override
public BuildResult build() throws InvalidRunnerConfigurationException, UnexpectedBuildFailure {
return new NormalizedBuildResult(delegate.build());
}
@Override
public BuildResult buildAndFail() throws InvalidRunnerConfigurationException, UnexpectedBuildSuccess {
return new NormalizedBuildResult(delegate.buildAndFail());
}
@Override
public BuildResult run() throws InvalidRunnerConfigurationException {
return new NormalizedBuildResult(delegate.run());
}
private | NormalizeOutputGradleRunner |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsWithGenericTypeHierarchiesTests.java | {
"start": 5056,
"end": 5268
} | interface ____
extends InterfaceWithGenericNumberParameter {
default <T extends Object> void foo(@SuppressWarnings("unused") T a) {
}
}
public static | InterfaceExtendingNumberInterfaceWithGenericObjectMethod |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/requestcontext/RequestScopedEndpointTest.java | {
"start": 1573,
"end": 1999
} | class ____ {
static final CountDownLatch DESTROYED_LATCH = new CountDownLatch(3);
@OnTextMessage
String echo(String message) {
if (!Arc.container().requestContext().isActive()) {
throw new IllegalStateException();
}
return message;
}
@PreDestroy
void destroy() {
DESTROYED_LATCH.countDown();
}
}
}
| Echo |
java | apache__camel | components/camel-dropbox/src/main/java/org/apache/camel/component/dropbox/integration/producer/DropboxGetProducer.java | {
"start": 1462,
"end": 2868
} | class ____ extends DropboxProducer {
private static final Logger LOG = LoggerFactory.getLogger(DropboxGetProducer.class);
public DropboxGetProducer(DropboxEndpoint endpoint, DropboxConfiguration configuration) {
super(endpoint, configuration);
}
@Override
public void process(Exchange exchange) throws Exception {
String remotePath = DropboxHelper.getRemotePath(configuration, exchange);
DropboxConfigurationValidator.validateGetOp(remotePath);
DropboxFileDownloadResult result = new DropboxAPIFacade(configuration.getClient(), exchange)
.get(remotePath);
Map<String, Object> map = result.getEntries();
if (map.size() == 1) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
exchange.getIn().setHeader(DropboxConstants.DOWNLOADED_FILE, entry.getKey());
exchange.getIn().setBody(entry.getValue());
}
} else {
StringBuilder pathsExtracted = new StringBuilder();
for (Map.Entry<String, Object> entry : map.entrySet()) {
pathsExtracted.append(entry.getKey()).append('\n');
}
exchange.getIn().setHeader(DropboxConstants.DOWNLOADED_FILES, pathsExtracted.toString());
exchange.getIn().setBody(map);
}
LOG.debug("Downloaded: {}", result);
}
}
| DropboxGetProducer |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/dataformat/IcalDataFormatReifier.java | {
"start": 1027,
"end": 1426
} | class ____ extends DataFormatReifier<IcalDataFormat> {
public IcalDataFormatReifier(CamelContext camelContext, DataFormatDefinition definition) {
super(camelContext, (IcalDataFormat) definition);
}
@Override
protected void prepareDataFormatConfig(Map<String, Object> properties) {
properties.put("validating", definition.getValidating());
}
}
| IcalDataFormatReifier |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/bind/annotation/ControllerMappingReflectiveProcessorTests.java | {
"start": 9860,
"end": 10725
} | class ____ {
@GetMapping
@ResponseBody
Response get() {
return new Response("response");
}
@PostMapping
void post(@RequestBody Request request) {
}
@PostMapping
void postForm(@ModelAttribute Request request) {
}
@GetMapping
@ResponseBody
String message() {
return "";
}
@GetMapping
HttpEntity<Response> getHttpEntity() {
return new HttpEntity<>(new Response("response"));
}
@GetMapping
@SuppressWarnings({ "rawtypes", "unchecked" })
HttpEntity getRawHttpEntity() {
return new HttpEntity(new Response("response"));
}
@PostMapping
void postHttpEntity(HttpEntity<Request> entity) {
}
@PostMapping
@SuppressWarnings("rawtypes")
void postRawHttpEntity(HttpEntity entity) {
}
@PostMapping
void postPartToConvert(@RequestPart Request request) {
}
}
@RestController
static | SampleController |
java | apache__flink | flink-formats/flink-avro-confluent-registry/src/main/java/org/apache/flink/formats/avro/registry/confluent/ConfluentRegistryAvroDeserializationSchema.java | {
"start": 6009,
"end": 6582
} | class ____ record to be produced
* @param url url of schema registry to connect
* @return deserialized record
*/
public static <T extends SpecificRecord>
ConfluentRegistryAvroDeserializationSchema<T> forSpecific(Class<T> tClass, String url) {
return forSpecific(tClass, url, DEFAULT_IDENTITY_MAP_CAPACITY, null);
}
/**
* Creates {@link AvroDeserializationSchema} that produces classes that were generated from Avro
* schema and looks up the writer schema in the Confluent Schema Registry.
*
* @param tClass | of |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/LocalizerEventType.java | {
"start": 883,
"end": 994
} | enum ____ {
/** See {@link LocalizerResourceRequestEvent} */
REQUEST_RESOURCE_LOCALIZATION
}
| LocalizerEventType |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/insert/MySqlInsertTest_17.java | {
"start": 358,
"end": 4875
} | class ____ extends MysqlTest {
public void test_insert_rollback_on_fail() throws Exception {
String sql = "/*+engine=MPP, mppNativeInsertFromSelect=true*/\n"
+ "INSERT INTO dashboard_crowd_analysis(cname,cvalue,orders,users,dt,tagid)\n"
+ "SELECT x.cname as cname,\n" + " x.cvalue as cvalue,\n" + " x.orders as orders,\n"
+ " x.users as users,\n" + " 20171211 as dt,\n" + " 91 as tagid\n"
+ "FROM (WITH h AS\n" + " (SELECT a.userid,\n" + " a.col_1,\n"
+ " a.col_2,\n" + " a.col_3,\n" + " a.col_4,\n"
+ " a.col_5,\n" + " a.col_6,\n" + " c.orders_week\n"
+ " FROM\n" + " (SELECT userid,\n" + " col_1,\n"
+ " col_2,\n" + " col_3,\n" + " col_4,\n"
+ " col_5,\n" + " col_6\n"
+ " FROM ofo_personas_dimensions\n" + " WHERE dt=20171211)a\n"
+ " JOIN\n" + " (SELECT userid\n" + " FROM personas_user_tag\n"
+ " WHERE tagid=91)b ON a.userid=b.userid\n" + " JOIN\n"
+ " (SELECT userid,\n" + " orders_week\n"
+ " FROM ofo_personas_metrics\n"
+ " WHERE dt=20171211)c ON a.userid=c.userid)\n" + " SELECT 'col_1' as cname,\n"
+ " col_1 as cvalue,\n" + " sum(orders_week) AS orders,\n"
+ " count(userid) AS users\n" + " FROM h\n" + " GROUP BY col_1\n"
+ " UNION ALL\n" + " SELECT 'col_2' as cname,\n" + " col_2 as cvalue,\n"
+ " sum(orders_week) AS orders,\n" + " count(userid) AS users\n"
+ " FROM h\n" + " GROUP BY col_2)x";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
MySqlInsertStatement insertStmt = (MySqlInsertStatement) stmt;
// System.out.println(SQLUtils.toMySqlString(insertStmt));
String formatSql = "/*+engine=MPP, mppNativeInsertFromSelect=true*/\n" +
"INSERT INTO dashboard_crowd_analysis (cname, cvalue, orders, users, dt\n" +
"\t, tagid)\n" +
"SELECT x.cname AS cname, x.cvalue AS cvalue, x.orders AS orders, x.users AS users, 20171211 AS dt\n" +
"\t, 91 AS tagid\n" +
"FROM (\n" +
"\tWITH h AS (\n" +
"\t\t\tSELECT a.userid, a.col_1, a.col_2, a.col_3, a.col_4\n" +
"\t\t\t\t, a.col_5, a.col_6, c.orders_week\n" +
"\t\t\tFROM (\n" +
"\t\t\t\tSELECT userid, col_1, col_2, col_3, col_4\n" +
"\t\t\t\t\t, col_5, col_6\n" +
"\t\t\t\tFROM ofo_personas_dimensions\n" +
"\t\t\t\tWHERE dt = 20171211\n" +
"\t\t\t) a\n" +
"\t\t\t\tJOIN (\n" +
"\t\t\t\t\tSELECT userid\n" +
"\t\t\t\t\tFROM personas_user_tag\n" +
"\t\t\t\t\tWHERE tagid = 91\n" +
"\t\t\t\t) b\n" +
"\t\t\t\tON a.userid = b.userid\n" +
"\t\t\t\tJOIN (\n" +
"\t\t\t\t\tSELECT userid, orders_week\n" +
"\t\t\t\t\tFROM ofo_personas_metrics\n" +
"\t\t\t\t\tWHERE dt = 20171211\n" +
"\t\t\t\t) c\n" +
"\t\t\t\tON a.userid = c.userid\n" +
"\t\t)\n" +
"\tSELECT 'col_1' AS cname, col_1 AS cvalue, sum(orders_week) AS orders\n" +
"\t\t, count(userid) AS users\n" +
"\tFROM h\n" +
"\tGROUP BY col_1\n" +
"\tUNION ALL\n" +
"\tSELECT 'col_2' AS cname, col_2 AS cvalue, sum(orders_week) AS orders\n" +
"\t\t, count(userid) AS users\n" +
"\tFROM h\n" +
"\tGROUP BY col_2\n" +
") x";
assertEquals(formatSql, SQLUtils.toMySqlString(insertStmt));
}
}
| MySqlInsertTest_17 |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpExpressionHandlerTests.java | {
"start": 4960,
"end": 5093
} | class ____ {
@GetMapping("/whoami")
String whoami(Principal user) {
return user.getName();
}
}
}
| ExpressionHandlerController |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerBase.java | {
"start": 33420,
"end": 41360
} | interface ____ FileSystem if
// needed.
return true;
}
private static String uriEscape(String input) {
// All reserved characters (RFC 2396) will be removed. This is enough for flink's resource
// id, job id and operator id.
// Ref: https://docs.oracle.com/javase/8/docs/api/index.html?java/net/URI.html
return input.replaceAll("[;/?:@&=+$,\\[\\]]", "-");
}
// ------------------------------------------------------------------------
// utilities
// ------------------------------------------------------------------------
/**
* Create managed directory.
*
* @param managedPath the path.
* @return true if new created.
*/
private boolean createManagedDirectory(Path managedPath) {
try {
FileStatus fileStatus = null;
try {
fileStatus = fs.getFileStatus(managedPath);
} catch (FileNotFoundException e) {
// expected exception when the path not exist, and we ignore it.
}
if (fileStatus == null) {
fs.mkdirs(managedPath);
LOG.info("Created a directory {} for checkpoint file-merging.", managedPath);
return true;
} else if (fileStatus.isDir()) {
LOG.info("Reusing previous directory {} for checkpoint file-merging.", managedPath);
return false;
} else {
throw new FlinkRuntimeException(
"The managed path "
+ managedPath
+ " for file-merging is occupied by another file. Cannot create directory.");
}
} catch (IOException e) {
throw new FlinkRuntimeException(
"Cannot create directory " + managedPath + " for file-merging ", e);
}
}
@Override
public void close() throws IOException {
if (fileSystemInitiated) {
quietlyCleanupManagedDir();
}
}
private void quietlyCleanupManagedDir() {
// Quietly clean up useless shared state dir.
managedSharedStateDirHandles.forEach(
(subtaskKey, handleWithTrack) -> handleWithTrack.tryCleanupQuietly());
// Quietly clean up useless exclusive state dir.
managedExclusiveStateDirHandle.tryCleanupQuietly();
}
@VisibleForTesting
public String getId() {
return id;
}
// ------------------------------------------------------------------------
// restore
// ------------------------------------------------------------------------
@Override
public void restoreStateHandles(
long checkpointId, SubtaskKey subtaskKey, Stream<SegmentFileStateHandle> stateHandles) {
synchronized (lock) {
Set<LogicalFile> restoredLogicalFiles =
uploadedStates.computeIfAbsent(checkpointId, id -> new HashSet<>());
Map<Path, PhysicalFile> knownPhysicalFiles = new HashMap<>();
knownLogicalFiles.values().stream()
.map(LogicalFile::getPhysicalFile)
.forEach(file -> knownPhysicalFiles.putIfAbsent(file.getFilePath(), file));
stateHandles.forEach(
fileHandle -> {
PhysicalFile physicalFile =
knownPhysicalFiles.computeIfAbsent(
fileHandle.getFilePath(),
path -> {
boolean managedByFileMergingManager =
fileSystemInitiated
&& isManagedByFileMergingManager(
path,
subtaskKey,
fileHandle.getScope());
PhysicalFile file =
new PhysicalFile(
null,
path,
physicalFileDeleter,
fileHandle.getScope(),
managedByFileMergingManager);
try {
file.updateSize(getFileSize(file));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (managedByFileMergingManager) {
spaceStat.onPhysicalFileCreate();
spaceStat.onPhysicalFileUpdate(file.getSize());
}
return file;
});
LogicalFileId logicalFileId = fileHandle.getLogicalFileId();
LogicalFile logicalFile =
new LogicalFile(
logicalFileId,
physicalFile,
fileHandle.getStartPos(),
fileHandle.getStateSize(),
subtaskKey);
if (physicalFile.isOwned()) {
spaceStat.onLogicalFileCreate(logicalFile.getLength());
}
knownLogicalFiles.put(logicalFileId, logicalFile);
logicalFile.advanceLastCheckpointId(checkpointId);
restoredLogicalFiles.add(logicalFile);
});
}
}
private long getFileSize(PhysicalFile file) throws IOException {
FileStatus fileStatus =
file.getFilePath().getFileSystem().getFileStatus(file.getFilePath());
if (fileStatus == null || fileStatus.isDir()) {
throw new FileNotFoundException("File " + file.getFilePath() + " does not exist.");
} else {
return fileStatus.getLen();
}
}
/**
* Distinguish whether the given filePath is managed by the FileMergingSnapshotManager. If the
* filePath is located under managedDir (managedSharedStateDir or managedExclusiveStateDir) as a
* subFile, it should be managed by the FileMergingSnapshotManager.
*/
private boolean isManagedByFileMergingManager(
Path filePath, SubtaskKey subtaskKey, CheckpointedStateScope scope) {
if (scope == CheckpointedStateScope.SHARED) {
Path managedDir = managedSharedStateDir.get(subtaskKey);
return filePath.toString().startsWith(managedDir.toString());
}
if (scope == CheckpointedStateScope.EXCLUSIVE) {
return filePath.toString().startsWith(managedExclusiveStateDir.toString());
}
throw new UnsupportedOperationException("Unsupported CheckpointStateScope " + scope);
}
@VisibleForTesting
public LogicalFile getLogicalFile(LogicalFileId fileId) {
return knownLogicalFiles.get(fileId);
}
@VisibleForTesting
TreeMap<Long, Set<LogicalFile>> getUploadedStates() {
return uploadedStates;
}
@VisibleForTesting
boolean isCheckpointDiscard(long checkpointId) {
return notifiedCheckpoint.contains(checkpointId);
}
/**
* This | to |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/testresources/Inventor.java | {
"start": 4123,
"end": 6693
} | class ____ extends Exception {}
public String throwException(PlaceOfBirth pob) {
return pob.getCity();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean getWonNobelPrize() {
return wonNobelPrize;
}
public void setWonNobelPrize(boolean wonNobelPrize) {
this.wonNobelPrize = wonNobelPrize;
}
public PlaceOfBirth[] getPlacesLived() {
return placesLived;
}
public void setPlacesLived(PlaceOfBirth[] placesLived) {
this.placesLived = placesLived;
}
public List<PlaceOfBirth> getPlacesLivedList() {
return placesLivedList;
}
public void setPlacesLivedList(List<PlaceOfBirth> placesLivedList) {
this.placesLivedList = placesLivedList;
}
public String echo(Object o) {
return o.toString();
}
public String sayHelloTo(String person) {
return "hello " + person;
}
public String printDouble(Double d) {
return d.toString();
}
public String printDoubles(double[] d) {
return ObjectUtils.nullSafeToString(d);
}
public List<String> getDoublesAsStringList() {
List<String> result = new ArrayList<>();
result.add("14.35");
result.add("15.45");
return result;
}
public String joinThreeStrings(String a, String b, String c) {
return a + b + c;
}
public String aVarargsMethod(String... strings) {
return Arrays.toString(strings);
}
public String aVarargsMethod2(int i, String... strings) {
return i + "-" + Arrays.toString(strings);
}
@SuppressWarnings("unchecked")
public String optionalVarargsMethod(Optional<String>... values) {
return Arrays.toString(values);
}
public String aVarargsMethod3(String str1, String... strings) {
if (ObjectUtils.isEmpty(strings)) {
return str1;
}
return str1 + "-" + String.join("-", strings);
}
public String formatObjectVarargs(String format, Object... args) {
return String.format(format, args);
}
public String formatPrimitiveVarargs(String format, int... nums) {
Object[] args = new Object[nums.length];
for (int i = 0; i < nums.length; i++) {
args[i] = nums[i];
}
return String.format(format, args);
}
public Inventor(String... strings) {
if (strings.length > 0) {
this.name = strings[0];
}
}
public boolean getSomeProperty() {
return accessedThroughGetSet;
}
public void setSomeProperty(boolean b) {
this.accessedThroughGetSet = b;
}
public Date getBirthdate() { return birthdate;}
public String getFoo() { return foo; }
public void setFoo(String s) { foo = s; }
public String getNationality() { return nationality; }
}
| TestException |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/assertion/RecursiveAssertionAssert_hasNoNullFields_Test.java | {
"start": 3940,
"end": 4548
} | class ____ {
byte[] array = null;
}
@Test
public void should_report_null_arrays() {
// GIVEN
Object testObject = new OuterWithArray();
// WHEN
var error = expectAssertionError(() -> assertThat(testObject).usingRecursiveAssertion()
.withCollectionAssertionPolicy(COLLECTION_OBJECT_AND_ELEMENTS)
.hasNoNullFields());
// THEN
then(error).hasMessageContainingAll("arrayOuter", "inner.array");
}
@SuppressWarnings("unused")
static | InnerWithArray |
java | spring-projects__spring-boot | module/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationTests.java | {
"start": 55638,
"end": 55875
} | class ____ {
@Bean
ConsumerAwareRebalanceListener rebalanceListener() {
return mock(ConsumerAwareRebalanceListener.class);
}
}
@Configuration(proxyBeanMethods = false)
@EnableKafkaStreams
static | RebalanceListenerConfiguration |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlNamespaceInjectionTests.java | {
"start": 2164,
"end": 5481
} | class ____ {
@Test
@DomainModel(annotatedClasses = CustomSchemaEntity.class)
@SessionFactory(exportSchema = false, useCollectingStatementInspector = true)
void testSchemaReplacement(SessionFactoryScope sessionFactoryScope) {
verifyReplacements( sessionFactoryScope, CustomSchemaEntity.class, "my_schema.the_table" );
}
@Test
@DomainModel(annotatedClasses = CustomCatalogEntity.class)
@SessionFactory(exportSchema = false, useCollectingStatementInspector = true)
void testCatalogReplacement(SessionFactoryScope sessionFactoryScope) {
verifyReplacements( sessionFactoryScope, CustomCatalogEntity.class, "my_catalog.the_table" );
}
@Test
@DomainModel(annotatedClasses = CustomDomainEntity.class)
@SessionFactory(exportSchema = false, useCollectingStatementInspector = true)
void testDomainReplacement(SessionFactoryScope sessionFactoryScope) {
verifyReplacements( sessionFactoryScope, CustomDomainEntity.class, "my_catalog.my_schema.the_table" );
}
private void verifyReplacements(
SessionFactoryScope sessionFactoryScope,
Class<?> entityClass,
String expectedTableName) {
final SessionFactoryImplementor sessionFactory = sessionFactoryScope.getSessionFactory();
final MappingMetamodelImplementor mappingMetamodel = sessionFactory.getMappingMetamodel();
final EntityPersister persister = mappingMetamodel.getEntityDescriptor( entityClass );
verifySelectSql( sessionFactoryScope, persister, expectedTableName );
verifyDmlSql( sessionFactoryScope, persister, expectedTableName );
}
private static void verifyDmlSql(SessionFactoryScope sessionFactoryScope, EntityPersister persister, String expectedTableName) {
verifyDmlSql( persister.getInsertCoordinator(), expectedTableName );
verifyDmlSql( persister.getUpdateCoordinator(), expectedTableName );
verifyDmlSql( persister.getDeleteCoordinator(), expectedTableName );
}
private static void verifyDmlSql(MutationCoordinator mutationCoordinator, String expectedTableName) {
final MutationOperationGroup mutationOperationGroup = mutationCoordinator.getStaticMutationOperationGroup();
final MutationOperation mutationOperation = mutationOperationGroup.getSingleOperation();
final String sql = ( (JdbcMutationOperation) mutationOperation ).getSqlString();
assertThat( sql ).contains( expectedTableName );
}
private static void verifySelectSql(SessionFactoryScope sessionFactoryScope, EntityPersister persister, String expectedTableName) {
final SQLStatementInspector sqlStatementCollector = sessionFactoryScope.getCollectingStatementInspector();
sqlStatementCollector.clear();
try {
sessionFactoryScope.inTransaction( (session) -> {
persister.load( 1, null, LockMode.NONE, session );
} );
}
catch (Exception ignore) {
}
assertThat( sqlStatementCollector.getSqlQueries() ).hasSize( 1 );
final String query = sqlStatementCollector.getSqlQueries().get( 0 );
assertThat( query ).contains( expectedTableName );
}
@Entity(name = "CustomSchemaEntity")
@SQLSelect(sql = "select id, name from {h-schema}the_table where id = ?")
@SQLInsert(sql = "insert into {h-schema}the_table (name) values (?)")
@SQLDelete(sql = "delete from {h-schema}the_table where id = ?")
@SQLUpdate(sql = "update {h-schema}the_table set name = ? where id = ? ")
public static | CustomSqlNamespaceInjectionTests |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/chararray/CharArrayAssert_usingComparator_Test.java | {
"start": 1162,
"end": 1845
} | class ____ extends CharArrayAssertBaseTest {
private Comparator<char[]> comparator = alwaysEqual();
private CharArrays arraysBefore;
@BeforeEach
void before() {
arraysBefore = getArrays(assertions);
}
@Override
protected CharArrayAssert invoke_api_method() {
// in that test, the comparator type is not important, we only check that we correctly switch of comparator
return assertions.usingComparator(comparator);
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions).getComparator()).isSameAs(comparator);
assertThat(getArrays(assertions)).isSameAs(arraysBefore);
}
}
| CharArrayAssert_usingComparator_Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ListOperationTests.java | {
"start": 1275,
"end": 4811
} | class ____ {
@BeforeEach
public void createTestData(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final EntityOfLists entityContainingLists = new EntityOfLists( 1, "first" );
entityContainingLists.addBasic( "abc" );
entityContainingLists.addBasic( "def" );
entityContainingLists.addBasic( "ghi" );
entityContainingLists.addConvertedEnum( EnumValue.TWO );
entityContainingLists.addEnum( EnumValue.ONE );
entityContainingLists.addEnum( EnumValue.THREE );
entityContainingLists.addComponent( new SimpleComponent( "first-a1", "first-another-a1" ) );
entityContainingLists.addComponent( new SimpleComponent( "first-a2", "first-another-a2" ) );
session.persist( entityContainingLists );
}
);
}
@AfterEach
public void dropTestData(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void listBaselineTest(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final Query<EntityOfLists> query = session.createQuery(
"select e from EntityOfLists e",
EntityOfLists.class
);
final EntityOfLists result = query.uniqueResult();
assertThat( result, notNullValue() );
assertThat( result.getListOfBasics(), notNullValue() );
assertThat( Hibernate.isInitialized( result.getListOfBasics() ), is( false ) );
}
);
}
@Test
public void listEagerBasicTest(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
final Query<EntityOfLists> query = session.createQuery(
"select e from EntityOfLists e join fetch e.listOfBasics",
EntityOfLists.class
);
final EntityOfLists result = query.uniqueResult();
assertThat( result, notNullValue() );
assertThat( result.getListOfBasics(), notNullValue() );
assertThat( Hibernate.isInitialized( result.getListOfBasics() ), is( true ) );
assertTrue( session.getPersistenceContext().containsCollection( (PersistentCollection) result.getListOfBasics() ) );
assertThat( result.getListOfBasics(), hasSize( 3 ) );
assertThat( result.getListOfConvertedEnums(), notNullValue() );
assertThat( Hibernate.isInitialized( result.getListOfConvertedEnums() ), is( false ) );
assertTrue( session.getPersistenceContext().containsCollection( (PersistentCollection) result.getListOfConvertedEnums() ) );
assertThat( result.getListOfEnums(), notNullValue() );
assertThat( Hibernate.isInitialized( result.getListOfEnums() ), is( false ) );
assertTrue( session.getPersistenceContext().containsCollection( (PersistentCollection) result.getListOfEnums() ) );
assertThat( result.getListOfComponents(), notNullValue() );
assertThat( Hibernate.isInitialized( result.getListOfComponents() ), is( false ) );
assertTrue( session.getPersistenceContext().containsCollection( (PersistentCollection) result.getListOfComponents() ) );
assertThat( result.getListOfOneToMany(), notNullValue() );
assertThat( Hibernate.isInitialized( result.getListOfOneToMany() ), is( false ) );
assertTrue( session.getPersistenceContext().containsCollection( (PersistentCollection) result.getListOfOneToMany() ) );
assertThat( result.getListOfManyToMany(), notNullValue() );
assertThat( Hibernate.isInitialized( result.getListOfManyToMany() ), is( false ) );
assertTrue( session.getPersistenceContext().containsCollection( (PersistentCollection) result.getListOfManyToMany() ) );
}
);
}
}
| ListOperationTests |
java | netty__netty | codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdyRstStreamFrame.java | {
"start": 790,
"end": 2391
} | class ____ extends DefaultSpdyStreamFrame
implements SpdyRstStreamFrame {
private SpdyStreamStatus status;
/**
* Creates a new instance.
*
* @param streamId the Stream-ID of this frame
* @param statusCode the Status code of this frame
*/
public DefaultSpdyRstStreamFrame(int streamId, int statusCode) {
this(streamId, SpdyStreamStatus.valueOf(statusCode));
}
/**
* Creates a new instance.
*
* @param streamId the Stream-ID of this frame
* @param status the status of this frame
*/
public DefaultSpdyRstStreamFrame(int streamId, SpdyStreamStatus status) {
super(streamId);
setStatus(status);
}
@Override
public SpdyRstStreamFrame setStreamId(int streamId) {
super.setStreamId(streamId);
return this;
}
@Override
public SpdyRstStreamFrame setLast(boolean last) {
super.setLast(last);
return this;
}
@Override
public SpdyStreamStatus status() {
return status;
}
@Override
public SpdyRstStreamFrame setStatus(SpdyStreamStatus status) {
this.status = status;
return this;
}
@Override
public String toString() {
return new StringBuilder()
.append(StringUtil.simpleClassName(this))
.append(StringUtil.NEWLINE)
.append("--> Stream-ID = ")
.append(streamId())
.append(StringUtil.NEWLINE)
.append("--> Status: ")
.append(status())
.toString();
}
}
| DefaultSpdyRstStreamFrame |
java | apache__camel | dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/LoggerAction.java | {
"start": 1769,
"end": 6410
} | class ____ extends ActionBaseCommand {
@CommandLine.Parameters(description = "Name or pid of running Camel integration", arity = "0..1")
String name = "*";
@CommandLine.Option(names = { "--sort" }, completionCandidates = PidNameAgeCompletionCandidates.class,
description = "Sort by pid, name or age", defaultValue = "pid")
String sort;
@CommandLine.Option(names = { "--logging-level" }, completionCandidates = LoggingLevelCompletionCandidates.class,
description = "To change logging level (${COMPLETION-CANDIDATES})")
String loggingLevel;
@CommandLine.Option(names = { "--logger" },
description = "The logger name", defaultValue = "root")
String logger;
public LoggerAction(CamelJBangMain main) {
super(main);
}
@Override
public Integer doCall() throws Exception {
if (loggingLevel == null) {
return callList();
}
if (name == null) {
name = "*";
}
return callChangeLoggingLevel();
}
protected Integer callChangeLoggingLevel() throws Exception {
List<Long> pids = findPids(name);
for (long pid : pids) {
JsonObject root = new JsonObject();
root.put("action", "logger");
Path f = getActionFile(Long.toString(pid));
root.put("command", "set-logging-level");
root.put("logger-name", logger);
root.put("logging-level", loggingLevel);
Files.writeString(f, root.toJson());
}
return 0;
}
protected Integer callList() {
List<Row> rows = new ArrayList<>();
List<Long> pids = findPids("*");
ProcessHandle.allProcesses()
.filter(ph -> pids.contains(ph.pid()))
.forEach(ph -> {
JsonObject root = loadStatus(ph.pid());
if (root != null) {
Row row = new Row();
row.pid = Long.toString(ph.pid());
row.uptime = extractSince(ph);
row.ago = TimeUtils.printSince(row.uptime);
JsonObject context = (JsonObject) root.get("context");
if (context == null) {
return;
}
row.name = context.getString("name");
if ("CamelJBang".equals(row.name)) {
row.name = ProcessHelper.extractName(root, ph);
}
JsonObject jo = (JsonObject) root.get("logger");
if (jo != null) {
Map<String, String> levels = jo.getMap("levels");
levels.forEach((k, v) -> {
// create a copy for 2+ levels
Row cp = row.copy();
cp.logger = k;
cp.level = v;
rows.add(cp);
});
}
}
});
// sort rows
rows.sort(this::sortRow);
if (!rows.isEmpty()) {
printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, rows, Arrays.asList(
new Column().header("PID").headerAlign(HorizontalAlign.CENTER).with(r -> r.pid),
new Column().header("NAME").dataAlign(HorizontalAlign.LEFT)
.maxWidth(40, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(r -> r.name),
new Column().header("AGE").headerAlign(HorizontalAlign.CENTER).with(r -> r.ago),
new Column().header("LOGGER").dataAlign(HorizontalAlign.LEFT).with(r -> r.logger),
new Column().header("LEVEL").dataAlign(HorizontalAlign.RIGHT).with(r -> r.level))));
}
return 0;
}
protected int sortRow(Row o1, Row o2) {
String s = sort;
int negate = 1;
if (s.startsWith("-")) {
s = s.substring(1);
negate = -1;
}
switch (s) {
case "pid":
return Long.compare(Long.parseLong(o1.pid), Long.parseLong(o2.pid)) * negate;
case "name":
return o1.name.compareToIgnoreCase(o2.name) * negate;
case "age":
return Long.compare(o1.uptime, o2.uptime) * negate;
default:
return 0;
}
}
private static | LoggerAction |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/propertyeditors/InputSourceEditor.java | {
"start": 1430,
"end": 2605
} | class ____ extends PropertyEditorSupport {
private final ResourceEditor resourceEditor;
/**
* Create a new InputSourceEditor,
* using the default ResourceEditor underneath.
*/
public InputSourceEditor() {
this.resourceEditor = new ResourceEditor();
}
/**
* Create a new InputSourceEditor,
* using the given ResourceEditor underneath.
* @param resourceEditor the ResourceEditor to use
*/
public InputSourceEditor(ResourceEditor resourceEditor) {
Assert.notNull(resourceEditor, "ResourceEditor must not be null");
this.resourceEditor = resourceEditor;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
this.resourceEditor.setAsText(text);
Resource resource = (Resource) this.resourceEditor.getValue();
try {
setValue(resource != null ? new InputSource(resource.getURL().toString()) : null);
}
catch (IOException ex) {
throw new IllegalArgumentException(
"Could not retrieve URL for " + resource + ": " + ex.getMessage());
}
}
@Override
public String getAsText() {
InputSource value = (InputSource) getValue();
return (value != null ? value.getSystemId() : "");
}
}
| InputSourceEditor |
java | apache__camel | components/camel-aws/camel-aws2-ec2/src/main/java/org/apache/camel/component/aws2/ec2/client/impl/AWS2EC2ClientSessionTokenImpl.java | {
"start": 1865,
"end": 5219
} | class ____ implements AWS2EC2InternalClient {
private static final Logger LOG = LoggerFactory.getLogger(AWS2EC2ClientSessionTokenImpl.class);
private AWS2EC2Configuration configuration;
/**
* Constructor that uses the config file.
*/
public AWS2EC2ClientSessionTokenImpl(AWS2EC2Configuration configuration) {
LOG.trace("Creating an AWS EC2 manager using static credentials.");
this.configuration = configuration;
}
/**
* Getting the EC2 AWS client that is used.
*
* @return Amazon EC2 Client.
*/
@Override
public Ec2Client getEc2Client() {
Ec2Client client = null;
Ec2ClientBuilder clientBuilder = Ec2Client.builder();
ProxyConfiguration.Builder proxyConfig = null;
ApacheHttpClient.Builder httpClientBuilder = null;
boolean isClientConfigFound = false;
if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) {
proxyConfig = ProxyConfiguration.builder();
URI proxyEndpoint = URI.create(configuration.getProxyProtocol() + "://" + configuration.getProxyHost() + ":"
+ configuration.getProxyPort());
proxyConfig.endpoint(proxyEndpoint);
httpClientBuilder = ApacheHttpClient.builder().proxyConfiguration(proxyConfig.build());
isClientConfigFound = true;
}
if (configuration.getAccessKey() != null && configuration.getSecretKey() != null
&& configuration.getSessionToken() != null) {
AwsSessionCredentials cred = AwsSessionCredentials.create(configuration.getAccessKey(),
configuration.getSecretKey(), configuration.getSessionToken());
if (isClientConfigFound) {
clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder)
.credentialsProvider(StaticCredentialsProvider.create(cred));
} else {
clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider.create(cred));
}
} else {
if (!isClientConfigFound) {
clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder);
}
}
if (ObjectHelper.isNotEmpty(configuration.getRegion())) {
clientBuilder = clientBuilder.region(Region.of(configuration.getRegion()));
}
if (configuration.isOverrideEndpoint()) {
clientBuilder.endpointOverride(URI.create(configuration.getUriEndpointOverride()));
}
if (configuration.isTrustAllCertificates()) {
if (httpClientBuilder == null) {
httpClientBuilder = ApacheHttpClient.builder();
}
SdkHttpClient ahc = httpClientBuilder.buildWithDefaults(AttributeMap
.builder()
.put(
SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES,
Boolean.TRUE)
.build());
// set created http client to use instead of builder
clientBuilder.httpClient(ahc);
clientBuilder.httpClientBuilder(null);
}
client = clientBuilder.build();
return client;
}
}
| AWS2EC2ClientSessionTokenImpl |
java | micronaut-projects__micronaut-core | http-client-core/src/main/java/io/micronaut/http/client/ProxyRequestOptions.java | {
"start": 762,
"end": 2196
} | class ____ {
private static final ProxyRequestOptions DEFAULT = builder().build();
private final boolean retainHostHeader;
private ProxyRequestOptions(Builder builder) {
this.retainHostHeader = builder.retainHostHeader;
}
/**
* @return A new options builder.
*/
public static Builder builder() {
return new Builder();
}
/**
* @return A default {@link ProxyRequestOptions} that will behave the same way as
* {@link ProxyHttpClient#proxy(io.micronaut.http.HttpRequest)}
*/
public static ProxyRequestOptions getDefault() {
return DEFAULT;
}
/**
* If {@code true}, retain the host header from the given request. If {@code false}, it will be recomputed
* based on the request URI (same behavior as {@link ProxyHttpClient#proxy(io.micronaut.http.HttpRequest)}).
*
* @return Whether to retain the host header from the proxy request instead of recomputing it based on URL.
*/
public boolean isRetainHostHeader() {
return retainHostHeader;
}
@Override
public boolean equals(Object o) {
return o instanceof ProxyRequestOptions pro &&
isRetainHostHeader() == pro.isRetainHostHeader();
}
@Override
public int hashCode() {
return Objects.hashCode(isRetainHostHeader());
}
/**
* Builder class.
*/
public static final | ProxyRequestOptions |
java | apache__camel | components/camel-openapi-java/src/test/java/org/apache/camel/openapi/model/GenericData.java | {
"start": 859,
"end": 965
} | interface ____ to validate that inheritance and generics also works with the camel open-api compoment
*/
| used |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/json/TestCustomEscaping.java | {
"start": 431,
"end": 1069
} | class ____ extends tools.jackson.core.unittest.JacksonCoreTestBase
{
final static int TWO_BYTE_ESCAPED = 0x111;
final static int THREE_BYTE_ESCAPED = 0x1111;
final static SerializedString TWO_BYTE_ESCAPED_STRING = new SerializedString("&111;");
final static SerializedString THREE_BYTE_ESCAPED_STRING = new SerializedString("&1111;");
/*
/********************************************************
/* Helper types
/********************************************************
*/
/**
* Trivial simple custom escape definition set.
*/
@SuppressWarnings("serial")
static | TestCustomEscaping |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/FetchProfilesAnnotation.java | {
"start": 730,
"end": 1816
} | class ____ implements FetchProfiles, RepeatableContainer<FetchProfile> {
private org.hibernate.annotations.FetchProfile[] value;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public FetchProfilesAnnotation(ModelsContext modelContext) {
}
/**
* Used in creating annotation instances from JDK variant
*/
public FetchProfilesAnnotation(FetchProfiles annotation, ModelsContext modelContext) {
this.value = extractJdkValue( annotation, HibernateAnnotations.FETCH_PROFILES, "value", modelContext );
}
/**
* Used in creating annotation instances from Jandex variant
*/
public FetchProfilesAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) {
this.value = (FetchProfile[]) attributeValues.get( "value" );
}
@Override
public Class<? extends Annotation> annotationType() {
return FetchProfiles.class;
}
@Override
public org.hibernate.annotations.FetchProfile[] value() {
return value;
}
public void value(org.hibernate.annotations.FetchProfile[] value) {
this.value = value;
}
}
| FetchProfilesAnnotation |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/upgrade/GlobalHttpUpgradeCheckTest.java | {
"start": 6813,
"end": 7032
} | class ____ extends ChainHttpUpgradeCheckBase {
@Override
protected int priority() {
return 100;
}
}
@Priority(1000)
@Dependent
public static final | ChainHttpUpgradeCheck3 |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/TemplateDataTest.java | {
"start": 2671,
"end": 2833
} | enum ____ {
FOO,
BAR
}
// namespace is io_quarkus_qute_deployment_TemplateDataTest_Foos
@TemplateData
public static | TransactionType |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java | {
"start": 945,
"end": 2162
} | class ____ implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
public DemoServiceImpl() {
super();
}
public void sayHello(String name) {
logger.info("hello {}", name);
}
public String echo(String text) {
return text;
}
public long timestamp() {
return System.currentTimeMillis();
}
public String getThreadName() {
return Thread.currentThread().getName();
}
public int getSize(String[] strs) {
if (strs == null) return -1;
return strs.length;
}
public int getSize(Object[] os) {
if (os == null) return -1;
return os.length;
}
public Object invoke(String service, String method) throws Exception {
logger.info(
"RpcContext.getServerAttachment().getRemoteHost()={}",
RpcContext.getServiceContext().getRemoteHost());
return service + ":" + method;
}
public Type enumlength(Type... types) {
if (types.length == 0) return Type.Lower;
return types[0];
}
public int stringLength(String str) {
return str.length();
}
}
| DemoServiceImpl |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DoubleBraceInitializationTest.java | {
"start": 5634,
"end": 6223
} | class ____ {
static final ImmutableSet<Integer> a = ImmutableSet.of(1, 2);
static final ImmutableSet<Integer> b = ImmutableSet.of(1, 2);
Set<Integer> c = new HashSet<Integer>(ImmutableSet.of(1, 2));
}
""")
.doTest();
}
@Test
public void collection() {
testHelper
.addInputLines(
"in/Test.java",
"""
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
| Test |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/specific/InnerClassHierarchicalProperties.java | {
"start": 1002,
"end": 1177
} | class ____ {
private Foo foo;
public Foo getFoo() {
return this.foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
public static | InnerClassHierarchicalProperties |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringProfileArbiter.java | {
"start": 2398,
"end": 3836
} | class ____ implements org.apache.logging.log4j.core.util.Builder<SpringProfileArbiter> {
private static final Logger statusLogger = StatusLogger.getLogger();
@PluginBuilderAttribute
@SuppressWarnings("NullAway.Init")
private String name;
@PluginConfiguration
@SuppressWarnings("NullAway.Init")
private Configuration configuration;
@PluginLoggerContext
@SuppressWarnings("NullAway.Init")
private LoggerContext loggerContext;
private Builder() {
}
/**
* Sets the profile name or expression.
* @param name the profile name or expression
* @return this
* @see Profiles#of(String...)
*/
public Builder setName(String name) {
this.name = name;
return this;
}
@Override
public SpringProfileArbiter build() {
Environment environment = Log4J2LoggingSystem.getEnvironment(this.loggerContext);
if (environment == null) {
statusLogger.debug("Creating Arbiter without a Spring Environment");
}
String name = this.configuration.getStrSubstitutor().replace(this.name);
String[] profiles = trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
return new SpringProfileArbiter(environment, profiles);
}
// The array has no nulls in it, but StringUtils.trimArrayElements return
// @Nullable String[]
@SuppressWarnings("NullAway")
private String[] trimArrayElements(String[] array) {
return StringUtils.trimArrayElements(array);
}
}
}
| Builder |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/ClientCallImpl.java | {
"start": 21383,
"end": 22383
} | class ____ implements ClientStreamListener {
private final Listener<RespT> observer;
private Status exceptionStatus;
public ClientStreamListenerImpl(Listener<RespT> observer) {
this.observer = checkNotNull(observer, "observer");
}
/**
* Cancels call and schedules onClose() notification. May only be called from the application
* thread.
*/
private void exceptionThrown(Status status) {
// Since each RPC can have its own executor, we can only call onClose() when we are sure there
// will be no further callbacks. We set the status here and overwrite the onClose() details
// when it arrives.
exceptionStatus = status;
stream.cancel(status);
}
@Override
public void headersRead(final Metadata headers) {
try (TaskCloseable ignore = PerfMark.traceTask("ClientStreamListener.headersRead")) {
PerfMark.attachTag(tag);
final Link link = PerfMark.linkOut();
final | ClientStreamListenerImpl |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/FileChannelBoundedDataTest.java | {
"start": 8151,
"end": 8516
} | class ____
implements BufferAvailabilityListener {
private boolean isAvailable;
@Override
public void notifyDataAvailable(ResultSubpartitionView view) {
isAvailable = true;
}
private void resetAvailable() {
isAvailable = false;
}
}
}
| VerifyNotificationBufferAvailabilityListener |
java | apache__kafka | trogdor/src/main/java/org/apache/kafka/trogdor/fault/Kibosh.java | {
"start": 2845,
"end": 4238
} | class ____ {
private final Path controlPath;
KiboshProcess(String mountPath) {
this.controlPath = Paths.get(mountPath, KIBOSH_CONTROL);
if (!Files.exists(controlPath)) {
throw new RuntimeException("Can't find file " + controlPath);
}
}
synchronized void addFault(KiboshFaultSpec toAdd) throws IOException {
KiboshControlFile file = KiboshControlFile.read(controlPath);
List<KiboshFaultSpec> faults = new ArrayList<>(file.faults());
faults.add(toAdd);
new KiboshControlFile(faults).write(controlPath);
}
synchronized void removeFault(KiboshFaultSpec toRemove) throws IOException {
KiboshControlFile file = KiboshControlFile.read(controlPath);
List<KiboshFaultSpec> faults = new ArrayList<>();
boolean foundToRemove = false;
for (KiboshFaultSpec fault : file.faults()) {
if (fault.equals(toRemove)) {
foundToRemove = true;
} else {
faults.add(fault);
}
}
if (!foundToRemove) {
throw new RuntimeException("Failed to find fault " + toRemove + ". ");
}
new KiboshControlFile(faults).write(controlPath);
}
}
public static | KiboshProcess |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHeadersAdapter.java | {
"start": 4793,
"end": 5148
} | class ____ implements Iterator<Entry<String, List<String>>> {
private final Enumeration<String> names = headers.names();
@Override
public boolean hasNext() {
return this.names.hasMoreElements();
}
@Override
public Entry<String, List<String>> next() {
return new HeaderEntry(this.names.nextElement());
}
}
private final | EntryIterator |
java | apache__hadoop | hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/EagerKeyGeneratorKeyProviderCryptoExtension.java | {
"start": 2401,
"end": 2499
} | class ____
implements KeyProviderCryptoExtension.CryptoExtension {
private | CryptoExtension |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng5805PkgTypeMojoConfiguration2.java | {
"start": 903,
"end": 2454
} | class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void testPkgTypeMojoConfiguration() throws Exception {
File testDir = extractResources("/mng-5805-pkg-type-mojo-configuration2");
// First, build the test plugin dependency
Verifier verifier = newVerifier(new File(testDir, "mng5805-plugin-dep").getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
// Then, build the test extension2
verifier = newVerifier(new File(testDir, "mng5805-extension2").getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
// Then, build the test plugin
verifier = newVerifier(new File(testDir, "mng5805-plugin").getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
// Finally, run the test project
verifier = newVerifier(testDir.getAbsolutePath());
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyTextInLog("CLASS_NAME=org.apache.maven.its.mng5805.TestClass1");
}
}
| MavenITmng5805PkgTypeMojoConfiguration2 |
java | apache__maven | impl/maven-impl/src/main/java/org/apache/maven/impl/model/DefaultPluginManagementInjector.java | {
"start": 2069,
"end": 4888
} | class ____ extends MavenModelMerger {
public Model mergeManagedBuildPlugins(Model model) {
Build build = model.getBuild();
if (build != null) {
PluginManagement pluginManagement = build.getPluginManagement();
if (pluginManagement != null) {
return model.withBuild(mergePluginContainerPlugins(build, pluginManagement));
}
}
return model;
}
private Build mergePluginContainerPlugins(Build target, PluginContainer source) {
List<Plugin> src = source.getPlugins();
if (!src.isEmpty()) {
Map<Object, Plugin> managedPlugins = new LinkedHashMap<>(src.size() * 2);
Map<Object, Object> context = Collections.emptyMap();
for (Plugin element : src) {
Object key = getPluginKey().apply(element);
managedPlugins.put(key, element);
}
List<Plugin> newPlugins = new ArrayList<>();
for (Plugin element : target.getPlugins()) {
Object key = getPluginKey().apply(element);
Plugin managedPlugin = managedPlugins.get(key);
if (managedPlugin != null) {
element = mergePlugin(element, managedPlugin, false, context);
}
newPlugins.add(element);
}
return target.withPlugins(newPlugins);
}
return target;
}
@Override
protected void mergePlugin_Executions(
Plugin.Builder builder,
Plugin target,
Plugin source,
boolean sourceDominant,
Map<Object, Object> context) {
List<PluginExecution> src = source.getExecutions();
if (!src.isEmpty()) {
List<PluginExecution> tgt = target.getExecutions();
Map<Object, PluginExecution> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (PluginExecution element : src) {
Object key = getPluginExecutionKey().apply(element);
merged.put(key, element);
}
for (PluginExecution element : tgt) {
Object key = getPluginExecutionKey().apply(element);
PluginExecution existing = merged.get(key);
if (existing != null) {
element = mergePluginExecution(element, existing, sourceDominant, context);
}
merged.put(key, element);
}
builder.executions(merged.values());
}
}
}
}
| ManagementModelMerger |
java | apache__dubbo | dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java | {
"start": 1451,
"end": 5273
} | class ____ implements Filter {
private static final String CLASSPATH_PREFIX = "classpath:";
private final long start = System.currentTimeMillis();
private final List<String> resources = new ArrayList<>();
public void init(FilterConfig filterConfig) throws ServletException {
String config = filterConfig.getInitParameter("resources");
if (config != null && config.length() > 0) {
String[] configs = Constants.COMMA_SPLIT_PATTERN.split(config);
for (String c : configs) {
if (c != null && c.length() > 0) {
c = c.replace('\\', '/');
if (c.endsWith("/")) {
c = c.substring(0, c.length() - 1);
}
resources.add(c);
}
}
}
}
public void destroy() {}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (response.isCommitted()) {
return;
}
String uri = request.getRequestURI();
String context = request.getContextPath();
if (uri.endsWith("/favicon.ico")) {
uri = "/favicon.ico";
} else if (context != null && !"/".equals(context)) {
uri = uri.substring(context.length());
}
if (!uri.startsWith("/")) {
uri = "/" + uri;
}
long lastModified = getLastModified(uri);
long since = request.getDateHeader("If-Modified-Since");
if (since >= lastModified) {
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
byte[] data;
InputStream input = getInputStream(uri);
if (input == null) {
chain.doFilter(req, res);
return;
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
data = output.toByteArray();
} finally {
input.close();
}
response.setDateHeader("Last-Modified", lastModified);
OutputStream output = response.getOutputStream();
output.write(data);
output.flush();
}
private boolean isFile(String path) {
return path.startsWith("/") || path.indexOf(":") <= 1;
}
private long getLastModified(String uri) {
for (String resource : resources) {
if (resource != null && resource.length() > 0) {
String path = resource + uri;
if (isFile(path)) {
File file = new File(path);
if (file.exists()) {
return file.lastModified();
}
}
}
}
return start;
}
private InputStream getInputStream(String uri) {
for (String resource : resources) {
String path = resource + uri;
try {
if (isFile(path)) {
return new FileInputStream(path);
} else if (path.startsWith(CLASSPATH_PREFIX)) {
return Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(path.substring(CLASSPATH_PREFIX.length()));
} else {
return new URL(path).openStream();
}
} catch (IOException e) {
}
}
return null;
}
}
| ResourceFilter |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/override/Location.java | {
"start": 284,
"end": 436
} | class ____ {
private String name;
@Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| Location |
java | apache__camel | tooling/camel-tooling-model/src/test/java/org/apache/camel/tooling/model/StringsTest.java | {
"start": 1273,
"end": 3924
} | class ____ {
static Stream<Arguments> getClassShortNameTypeVariations() {
return Stream.of(arguments("String", "String"), arguments("String", "java.lang.String"),
arguments("List", "List<String>"), arguments("List", "java.util.List<String>"),
arguments("List", "List<java.lang.String>"),
arguments("List", "java.util.List.List<org.apache.camel.Exchange>"),
arguments("List", "java.util.List<Map<String,Integer>>"),
arguments("List", "java.util.List<Map<java.lang.String,Integer>>"),
arguments("List", "java.util.List<Map<String,java.lang.Integer>>"),
arguments("List", "java.util.List<Map<java.lang.String,java.lang.Integer>>"),
arguments("List", "java.util.List<java.util.Map<java.lang.String,java.lang.Integer>>"));
}
@ParameterizedTest
@MethodSource("getClassShortNameTypeVariations")
public void getClassShortName(String expectedBaseClassName, String className) {
assertEquals(expectedBaseClassName, Strings.getClassShortName(className));
}
@Test
public void testWrap() {
assertEquals("Hello WorldFoo Nar", wrap("HelloWorldFooNar", 8));
assertEquals("UseMessageIDAs CorrelationID", wrap("useMessageIDAsCorrelationID", 25));
assertEquals("ReplyToCacheLevelName", wrap("replyToCacheLevelName", 25));
assertEquals("AllowReplyManagerQuick Stop", wrap("allowReplyManagerQuickStop", 25));
assertEquals("AcknowledgementModeName", wrap("acknowledgementModeName", 25));
assertEquals("ReplyToCacheLevelName", wrap("replyToCacheLevelName", 25));
assertEquals("ReplyToOnTimeoutMax ConcurrentConsumers", wrap("replyToOnTimeoutMaxConcurrentConsumers", 25));
assertEquals("ReplyToOnTimeoutMax ConcurrentConsumers", wrap("replyToOnTimeoutMaxConcurrentConsumers", 23));
assertEquals("ReplyToMaxConcurrent Consumers", wrap("replyToMaxConcurrentConsumers", 23));
}
@Test
public void testWrapWords() throws Exception {
assertEquals("Setting something up for a night out\nthat is going to last a long time",
wrapWords("Setting something up for a night out that is going to last a long time", " ", "\n", 40, false));
assertEquals("Setting something up for a night out\n that is going to last a long time",
wrapWords("Setting something up for a night out that is going to last a long time", " ", "\n ", 40, false));
}
private String wrap(String str, int watermark) {
return Strings.wrapCamelCaseWords(str, watermark, " ");
}
}
| StringsTest |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationPredicatesTests.java | {
"start": 4863,
"end": 4930
} | interface ____ {
}
@TestAnnotation("test")
static | MissingAnnotation |
java | elastic__elasticsearch | test/fixtures/gcs-fixture/src/main/java/fixture/gcs/MultipartUpload.java | {
"start": 6603,
"end": 7683
} | class ____ implements Iterator<BytesReference> {
private final InputStream input;
private final byte[] bodyPartDelimiter;
private boolean done;
MultipartContentReader(String boundary, InputStream input) throws IOException {
this.input = input;
this.bodyPartDelimiter = ("\r\n--" + boundary).getBytes();
byte[] dashBoundary = ("--" + boundary).getBytes();
skipUntilDelimiter(input, dashBoundary);
readCloseDelimiterOrCRLF(input);
}
@Override
public boolean hasNext() {
return done == false;
}
@Override
public BytesReference next() {
try {
skipUntilDelimiter(input, BODY_PART_HEADERS_DELIMITER);
BytesReference buf = readUntilDelimiter(input, bodyPartDelimiter);
done = readCloseDelimiterOrCRLF(input);
return buf;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| MultipartContentReader |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/operators/drivers/GroupReduceDriverTest.java | {
"start": 2072,
"end": 13224
} | class ____ {
@Test
void testAllReduceDriverImmutableEmpty() {
try {
TestTaskContext<
GroupReduceFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>,
Tuple2<String, Integer>>
context = new TestTaskContext<>();
List<Tuple2<String, Integer>> data = DriverTestData.createReduceImmutableData();
TupleTypeInfo<Tuple2<String, Integer>> typeInfo =
(TupleTypeInfo<Tuple2<String, Integer>>)
TypeExtractor.getForObject(data.get(0));
MutableObjectIterator<Tuple2<String, Integer>> input = EmptyMutableObjectIterator.get();
TypeComparator<Tuple2<String, Integer>> comparator =
typeInfo.createComparator(
new int[] {0}, new boolean[] {true}, 0, new ExecutionConfig());
context.setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);
GatheringCollector<Tuple2<String, Integer>> result =
new GatheringCollector<>(typeInfo.createSerializer(new SerializerConfigImpl()));
context.setInput1(input, typeInfo.createSerializer(new SerializerConfigImpl()));
context.setComparator1(comparator);
context.setCollector(result);
GroupReduceDriver<Tuple2<String, Integer>, Tuple2<String, Integer>> driver =
new GroupReduceDriver<>();
driver.setup(context);
driver.prepare();
driver.run();
assertThat(result.getList()).isEmpty();
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
void testAllReduceDriverImmutable() {
try {
TestTaskContext<
GroupReduceFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>,
Tuple2<String, Integer>>
context = new TestTaskContext<>();
List<Tuple2<String, Integer>> data = DriverTestData.createReduceImmutableData();
TupleTypeInfo<Tuple2<String, Integer>> typeInfo =
(TupleTypeInfo<Tuple2<String, Integer>>)
TypeExtractor.getForObject(data.get(0));
MutableObjectIterator<Tuple2<String, Integer>> input =
new RegularToMutableObjectIterator<>(
data.iterator(), typeInfo.createSerializer(new SerializerConfigImpl()));
TypeComparator<Tuple2<String, Integer>> comparator =
typeInfo.createComparator(
new int[] {0}, new boolean[] {true}, 0, new ExecutionConfig());
GatheringCollector<Tuple2<String, Integer>> result =
new GatheringCollector<>(typeInfo.createSerializer(new SerializerConfigImpl()));
context.setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);
context.setInput1(input, typeInfo.createSerializer(new SerializerConfigImpl()));
context.setCollector(result);
context.setComparator1(comparator);
context.setUdf(new ConcatSumReducer());
GroupReduceDriver<Tuple2<String, Integer>, Tuple2<String, Integer>> driver =
new GroupReduceDriver<>();
driver.setup(context);
driver.prepare();
driver.run();
Object[] res = result.getList().toArray();
Object[] expected = DriverTestData.createReduceImmutableDataGroupedResult().toArray();
DriverTestData.compareTupleArrays(expected, res);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
void testAllReduceDriverMutable() {
try {
TestTaskContext<
GroupReduceFunction<
Tuple2<StringValue, IntValue>, Tuple2<StringValue, IntValue>>,
Tuple2<StringValue, IntValue>>
context = new TestTaskContext<>();
List<Tuple2<StringValue, IntValue>> data = DriverTestData.createReduceMutableData();
TupleTypeInfo<Tuple2<StringValue, IntValue>> typeInfo =
(TupleTypeInfo<Tuple2<StringValue, IntValue>>)
TypeExtractor.getForObject(data.get(0));
MutableObjectIterator<Tuple2<StringValue, IntValue>> input =
new RegularToMutableObjectIterator<>(
data.iterator(), typeInfo.createSerializer(new SerializerConfigImpl()));
TypeComparator<Tuple2<StringValue, IntValue>> comparator =
typeInfo.createComparator(
new int[] {0}, new boolean[] {true}, 0, new ExecutionConfig());
GatheringCollector<Tuple2<StringValue, IntValue>> result =
new GatheringCollector<>(typeInfo.createSerializer(new SerializerConfigImpl()));
context.setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);
context.setInput1(input, typeInfo.createSerializer(new SerializerConfigImpl()));
context.setComparator1(comparator);
context.setCollector(result);
context.setUdf(new ConcatSumMutableReducer());
GroupReduceDriver<Tuple2<StringValue, IntValue>, Tuple2<StringValue, IntValue>> driver =
new GroupReduceDriver<>();
driver.setup(context);
driver.prepare();
driver.run();
Object[] res = result.getList().toArray();
Object[] expected = DriverTestData.createReduceMutableDataGroupedResult().toArray();
DriverTestData.compareTupleArrays(expected, res);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
void testAllReduceDriverIncorrectlyAccumulatingMutable() {
try {
TestTaskContext<
GroupReduceFunction<
Tuple2<StringValue, IntValue>, Tuple2<StringValue, IntValue>>,
Tuple2<StringValue, IntValue>>
context = new TestTaskContext<>();
List<Tuple2<StringValue, IntValue>> data = DriverTestData.createReduceMutableData();
TupleTypeInfo<Tuple2<StringValue, IntValue>> typeInfo =
(TupleTypeInfo<Tuple2<StringValue, IntValue>>)
TypeExtractor.getForObject(data.get(0));
MutableObjectIterator<Tuple2<StringValue, IntValue>> input =
new RegularToMutableObjectIterator<>(
data.iterator(), typeInfo.createSerializer(new SerializerConfigImpl()));
TypeComparator<Tuple2<StringValue, IntValue>> comparator =
typeInfo.createComparator(
new int[] {0}, new boolean[] {true}, 0, new ExecutionConfig());
GatheringCollector<Tuple2<StringValue, IntValue>> result =
new GatheringCollector<>(typeInfo.createSerializer(new SerializerConfigImpl()));
context.setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);
context.setInput1(input, typeInfo.createSerializer(new SerializerConfigImpl()));
context.setComparator1(comparator);
context.setCollector(result);
context.setUdf(new ConcatSumMutableAccumulatingReducer());
context.getExecutionConfig().enableObjectReuse();
GroupReduceDriver<Tuple2<StringValue, IntValue>, Tuple2<StringValue, IntValue>> driver =
new GroupReduceDriver<>();
driver.setup(context);
driver.prepare();
driver.run();
Object[] res = result.getList().toArray();
Object[] expected = DriverTestData.createReduceMutableDataGroupedResult().toArray();
assertThatExceptionOfType(AssertionError.class)
.as("Accumulationg mutable objects is expected to result in incorrect values.")
.isThrownBy(() -> DriverTestData.compareTupleArrays(expected, res));
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
void testAllReduceDriverAccumulatingImmutable() {
try {
TestTaskContext<
GroupReduceFunction<
Tuple2<StringValue, IntValue>, Tuple2<StringValue, IntValue>>,
Tuple2<StringValue, IntValue>>
context = new TestTaskContext<>();
List<Tuple2<StringValue, IntValue>> data = DriverTestData.createReduceMutableData();
TupleTypeInfo<Tuple2<StringValue, IntValue>> typeInfo =
(TupleTypeInfo<Tuple2<StringValue, IntValue>>)
TypeExtractor.getForObject(data.get(0));
MutableObjectIterator<Tuple2<StringValue, IntValue>> input =
new RegularToMutableObjectIterator<>(
data.iterator(), typeInfo.createSerializer(new SerializerConfigImpl()));
TypeComparator<Tuple2<StringValue, IntValue>> comparator =
typeInfo.createComparator(
new int[] {0}, new boolean[] {true}, 0, new ExecutionConfig());
GatheringCollector<Tuple2<StringValue, IntValue>> result =
new GatheringCollector<>(typeInfo.createSerializer(new SerializerConfigImpl()));
context.setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);
context.setInput1(input, typeInfo.createSerializer(new SerializerConfigImpl()));
context.setComparator1(comparator);
context.setCollector(result);
context.setUdf(new ConcatSumMutableAccumulatingReducer());
context.getExecutionConfig().disableObjectReuse();
GroupReduceDriver<Tuple2<StringValue, IntValue>, Tuple2<StringValue, IntValue>> driver =
new GroupReduceDriver<>();
driver.setup(context);
driver.prepare();
driver.run();
Object[] res = result.getList().toArray();
Object[] expected = DriverTestData.createReduceMutableDataGroupedResult().toArray();
DriverTestData.compareTupleArrays(expected, res);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail(e.getMessage());
}
}
// --------------------------------------------------------------------------------------------
// Test UDFs
// --------------------------------------------------------------------------------------------
public static final | GroupReduceDriverTest |
java | apache__flink | flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunResponseBodyTest.java | {
"start": 1261,
"end": 1860
} | class ____ extends RestResponseMarshallingTestBase<JarRunResponseBody> {
@Override
protected Class<JarRunResponseBody> getTestResponseClass() {
return JarRunResponseBody.class;
}
@Override
protected JarRunResponseBody getTestResponseInstance() throws Exception {
return new JarRunResponseBody(new JobID());
}
@Override
protected void assertOriginalEqualsToUnmarshalled(
final JarRunResponseBody expected, final JarRunResponseBody actual) {
assertThat(actual.getJobId()).isEqualTo(expected.getJobId());
}
}
| JarRunResponseBodyTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/stat/HashMapMemoryTest.java | {
"start": 201,
"end": 973
} | class ____ extends TestCase {
public void test_0() throws Exception {
HashMap item = new HashMap();
gc();
long memoryStart = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
final int COUNT = 1024 * 1024;
Map[] items = new Map[COUNT];
for (int i = 0; i < COUNT; ++i) {
items[i] = new HashMap();
// items[i] = Histogram.makeHistogram(20);
}
long memoryEnd = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
System.out.println("memory used : " + NumberFormat.getInstance().format(memoryEnd - memoryStart));
}
private void gc() {
for (int i = 0; i < 10; ++i) {
System.gc();
}
}
}
| HashMapMemoryTest |
java | elastic__elasticsearch | x-pack/plugin/security/qa/multi-cluster/src/javaRestTest/java/org/elasticsearch/xpack/remotecluster/RemoteClusterSecurityWithSameModelRemotesRestIT.java | {
"start": 609,
"end": 5993
} | class ____ extends AbstractRemoteClusterSecurityWithMultipleRemotesRestIT {
private static final AtomicReference<Map<String, Object>> API_KEY_MAP_REF = new AtomicReference<>();
private static final AtomicReference<Map<String, Object>> OTHER_API_KEY_MAP_REF = new AtomicReference<>();
static {
fulfillingCluster = ElasticsearchCluster.local()
.name("fulfilling-cluster")
.apply(commonClusterConfig)
.setting("remote_cluster_server.enabled", "true")
.setting("remote_cluster.port", "0")
.setting("xpack.security.remote_cluster_server.ssl.enabled", "true")
.setting("xpack.security.remote_cluster_server.ssl.key", "remote-cluster.key")
.setting("xpack.security.remote_cluster_server.ssl.certificate", "remote-cluster.crt")
.keystore("xpack.security.remote_cluster_server.ssl.secure_key_passphrase", "remote-cluster-password")
.build();
otherFulfillingCluster = ElasticsearchCluster.local()
.name("fulfilling-cluster-2")
.apply(commonClusterConfig)
.setting("remote_cluster_server.enabled", "true")
.setting("remote_cluster.port", "0")
.setting("xpack.security.remote_cluster_server.ssl.enabled", "true")
.setting("xpack.security.remote_cluster_server.ssl.key", "remote-cluster.key")
.setting("xpack.security.remote_cluster_server.ssl.certificate", "remote-cluster.crt")
.keystore("xpack.security.remote_cluster_server.ssl.secure_key_passphrase", "remote-cluster-password")
.build();
queryCluster = ElasticsearchCluster.local()
.name("query-cluster")
.apply(commonClusterConfig)
.setting("xpack.security.remote_cluster_client.ssl.enabled", "true")
.setting("xpack.security.remote_cluster_client.ssl.certificate_authorities", "remote-cluster-ca.crt")
.keystore("cluster.remote.my_remote_cluster.credentials", () -> {
if (API_KEY_MAP_REF.get() == null) {
final Map<String, Object> apiKeyMap = createCrossClusterAccessApiKey("""
{
"search": [
{
"names": ["cluster1_index*"]
}
]
}""");
API_KEY_MAP_REF.set(apiKeyMap);
}
return (String) API_KEY_MAP_REF.get().get("encoded");
})
.keystore("cluster.remote.my_remote_cluster_2.credentials", () -> {
initOtherFulfillingClusterClient();
if (OTHER_API_KEY_MAP_REF.get() == null) {
final Map<String, Object> apiKeyMap = createCrossClusterAccessApiKey(otherFulfillingClusterClient, """
{
"search": [
{
"names": ["cluster2_index*"]
}
]
}""");
OTHER_API_KEY_MAP_REF.set(apiKeyMap);
}
return (String) OTHER_API_KEY_MAP_REF.get().get("encoded");
})
.build();
}
@ClassRule
// Use a RuleChain to ensure that fulfilling clusters are started before query cluster
public static TestRule clusterRule = RuleChain.outerRule(fulfillingCluster).around(otherFulfillingCluster).around(queryCluster);
@Override
protected void configureRolesOnClusters() throws IOException {
// Query cluster
{
// Create user role with privileges for remote and local indices
final var putRoleRequest = new Request("PUT", "/_security/role/" + REMOTE_SEARCH_ROLE);
putRoleRequest.setJsonEntity("""
{
"indices": [
{
"names": ["local_index"],
"privileges": ["read"]
}
],
"remote_indices": [
{
"names": ["cluster1_index1"],
"privileges": ["read", "read_cross_cluster"],
"clusters": ["my_remote_cluster"]
},
{
"names": ["cluster2_index1"],
"privileges": ["read", "read_cross_cluster"],
"clusters": ["my_remote_cluster_2"]
}
]
}""");
assertOK(adminClient().performRequest(putRoleRequest));
final var putUserRequest = new Request("PUT", "/_security/user/" + REMOTE_SEARCH_USER);
putUserRequest.setJsonEntity("""
{
"password": "x-pack-test-password",
"roles" : ["remote_search"]
}""");
assertOK(adminClient().performRequest(putUserRequest));
}
}
@Override
protected void configureRemoteCluster() throws Exception {
super.configureRemoteCluster();
configureRemoteCluster("my_remote_cluster_2", otherFulfillingCluster, false, randomBoolean(), randomBoolean());
}
}
| RemoteClusterSecurityWithSameModelRemotesRestIT |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/introspect/ClassIntrospector.java | {
"start": 417,
"end": 1423
} | class ____
{
protected ClassIntrospector() { }
/**
* Method called to create an instance to be exclusive used by specified
* mapper. Needed to ensure that no sharing through cache occurs.
*<p>
* Basic implementation just returns instance itself.
*
* @since 3.0
*/
public abstract ClassIntrospector forMapper();
/**
* Method called to further create an instance to be used for a single operation
* (read or write, typically matching {@link ObjectMapper} {@code readValue()} or
* {@code writeValue()}).
*/
public abstract ClassIntrospector forOperation(MapperConfig<?> config);
/*
/**********************************************************************
/* Public API: annotation introspection
/**********************************************************************
*/
/**
* Factory method that introspects a {@link AnnotatedClass} that only has
* information regarding annotations | ClassIntrospector |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/Gender.java | {
"start": 220,
"end": 672
} | enum ____ {
MALE('M'),
FEMALE('F');
private final char code;
Gender(char code) {
this.code = code;
}
public static Gender fromCode(char code) {
if (code == 'M' || code == 'm') {
return MALE;
}
if (code == 'F' || code == 'f') {
return FEMALE;
}
throw new UnsupportedOperationException(
"The code " + code + " is not supported!"
);
}
public char getCode() {
return code;
}
}
//end::basic-enums-converter-example[]
| Gender |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/expressions/aggregate/UserDefinedAggregateFunc.java | {
"start": 1472,
"end": 2854
} | class ____ extends ExpressionWithToString implements AggregateFunc {
private final String name;
private String canonicalName;
private final boolean isDistinct;
private final Expression[] children;
public UserDefinedAggregateFunc(
String name, String canonicalName, boolean isDistinct, Expression[] children) {
this.name = name;
this.canonicalName = canonicalName;
this.isDistinct = isDistinct;
this.children = children;
}
public String name() { return name; }
public String canonicalName() { return canonicalName; }
public boolean isDistinct() { return isDistinct; }
@Override
public Expression[] children() { return children; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDefinedAggregateFunc that = (UserDefinedAggregateFunc) o;
if (isDistinct != that.isDistinct) return false;
if (!name.equals(that.name)) return false;
if (!canonicalName.equals(that.canonicalName)) return false;
return Arrays.equals(children, that.children);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + canonicalName.hashCode();
result = 31 * result + (isDistinct ? 1 : 0);
result = 31 * result + Arrays.hashCode(children);
return result;
}
}
| UserDefinedAggregateFunc |
java | apache__camel | core/camel-core-processor/src/main/java/org/apache/camel/processor/errorhandler/RedeliveryPolicy.java | {
"start": 3632,
"end": 27880
} | class ____ implements Cloneable, Serializable {
// default policy using out of the box settings which can be shared
public static final RedeliveryPolicy DEFAULT_POLICY = new RedeliveryPolicy();
protected static Random randomNumberGenerator;
private static final Lock LOCK = new ReentrantLock();
private static final @Serial long serialVersionUID = -338222777701473252L;
private static final Logger LOG = LoggerFactory.getLogger(RedeliveryPolicy.class);
protected long redeliveryDelay = 1000L;
protected int maximumRedeliveries;
protected long maximumRedeliveryDelay = 60 * 1000L;
protected double backOffMultiplier = 2;
protected boolean useExponentialBackOff;
// +/-15% for a 30% spread -cgs
protected double collisionAvoidanceFactor = 0.15d;
protected boolean useCollisionAvoidance;
protected LoggingLevel retriesExhaustedLogLevel = LoggingLevel.ERROR;
protected LoggingLevel retryAttemptedLogLevel = LoggingLevel.DEBUG;
protected int retryAttemptedLogInterval = 1;
protected boolean logStackTrace = true;
protected boolean logRetryStackTrace;
protected boolean logHandled;
protected boolean logContinued;
protected boolean logExhausted = true;
protected boolean logNewException = true;
protected Boolean logExhaustedMessageHistory;
protected Boolean logExhaustedMessageBody;
protected boolean logRetryAttempted = true;
protected String delayPattern;
protected boolean asyncDelayedRedelivery;
protected boolean allowRedeliveryWhileStopping = true;
protected String exchangeFormatterRef;
public RedeliveryPolicy() {
}
@Override
public String toString() {
return "RedeliveryPolicy[maximumRedeliveries=" + maximumRedeliveries
+ ", redeliveryDelay=" + redeliveryDelay
+ ", maximumRedeliveryDelay=" + maximumRedeliveryDelay
+ ", asyncDelayedRedelivery=" + asyncDelayedRedelivery
+ ", allowRedeliveryWhileStopping=" + allowRedeliveryWhileStopping
+ ", retriesExhaustedLogLevel=" + retriesExhaustedLogLevel
+ ", retryAttemptedLogLevel=" + retryAttemptedLogLevel
+ ", retryAttemptedLogInterval=" + retryAttemptedLogInterval
+ ", logRetryAttempted=" + logRetryAttempted
+ ", logStackTrace=" + logStackTrace
+ ", logRetryStackTrace=" + logRetryStackTrace
+ ", logHandled=" + logHandled
+ ", logContinued=" + logContinued
+ ", logExhausted=" + logExhausted
+ ", logNewException=" + logNewException
+ ", logExhaustedMessageHistory=" + logExhaustedMessageHistory
+ ", logExhaustedMessageBody=" + logExhaustedMessageBody
+ ", useExponentialBackOff=" + useExponentialBackOff
+ ", backOffMultiplier=" + backOffMultiplier
+ ", useCollisionAvoidance=" + useCollisionAvoidance
+ ", collisionAvoidanceFactor=" + collisionAvoidanceFactor
+ ", delayPattern=" + delayPattern
+ ", exchangeFormatterRef=" + exchangeFormatterRef + "]";
}
public RedeliveryPolicy copy() {
try {
return (RedeliveryPolicy) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Could not clone: " + e, e);
}
}
/**
* Returns true if the policy decides that the message exchange should be redelivered.
*
* @param exchange the current exchange
* @param redeliveryCounter the current retry counter
* @param retryWhile an optional predicate to determine if we should redeliver or not
* @return true to redeliver, false to stop
*/
public boolean shouldRedeliver(Exchange exchange, int redeliveryCounter, Predicate retryWhile) {
// predicate is always used if provided
if (retryWhile != null) {
return retryWhile.matches(exchange);
}
if (getMaximumRedeliveries() < 0) {
// retry forever if negative value
return true;
}
// redeliver until we hit the max
return redeliveryCounter <= getMaximumRedeliveries();
}
/**
* Calculates the new redelivery delay based on the last one and then <b>sleeps</b> for the necessary amount of
* time.
* <p/>
* This implementation will block while sleeping.
*
* @param redeliveryDelay previous redelivery delay
* @param redeliveryCounter number of previous redelivery attempts
* @return the calculate delay
* @throws InterruptedException is thrown if the sleep is interrupted likely because of shutdown
*/
public long sleep(long redeliveryDelay, int redeliveryCounter) throws InterruptedException {
redeliveryDelay = calculateRedeliveryDelay(redeliveryDelay, redeliveryCounter);
if (redeliveryDelay > 0) {
sleep(redeliveryDelay);
}
return redeliveryDelay;
}
/**
* Sleeps for the given delay
*
* @param redeliveryDelay the delay
* @throws InterruptedException is thrown if the sleep is interrupted likely because of shutdown
*/
public void sleep(long redeliveryDelay) throws InterruptedException {
LOG.debug("Sleeping for: {} millis until attempting redelivery", redeliveryDelay);
Thread.sleep(redeliveryDelay);
}
/**
* Calculates the new redelivery delay based on the last one
*
* @param previousDelay previous redelivery delay
* @param redeliveryCounter number of previous redelivery attempts
* @return the calculate delay
*/
public long calculateRedeliveryDelay(long previousDelay, int redeliveryCounter) {
if (ObjectHelper.isNotEmpty(delayPattern)) {
// calculate delay using the pattern
return calculateRedeliverDelayUsingPattern(delayPattern, redeliveryCounter);
}
// calculate the delay using the conventional parameters
long redeliveryDelayResult;
if (previousDelay == 0) {
redeliveryDelayResult = redeliveryDelay;
} else if (useExponentialBackOff && backOffMultiplier > 1) {
redeliveryDelayResult = Math.round(backOffMultiplier * previousDelay);
} else {
redeliveryDelayResult = previousDelay;
}
if (useCollisionAvoidance) {
/*
* First random determines +/-, second random determines how far to
* go in that direction. -cgs
*/
Random random = getRandomNumberGenerator(); // NOSONAR
double variance = (random.nextBoolean() ? collisionAvoidanceFactor : -collisionAvoidanceFactor)
* random.nextDouble();
redeliveryDelayResult += (long) (redeliveryDelayResult * variance);
}
// ensure the calculated result is not bigger than the max delay (if configured)
if (maximumRedeliveryDelay > 0 && redeliveryDelayResult > maximumRedeliveryDelay) {
redeliveryDelayResult = maximumRedeliveryDelay;
}
return redeliveryDelayResult;
}
/**
* Calculates the delay using the delay pattern
*/
protected static long calculateRedeliverDelayUsingPattern(String delayPattern, int redeliveryCounter) {
String[] groups = delayPattern.split(";");
// find the group where the redelivery counter matches
long answer = 0;
for (String group : groups) {
long delay = Long.parseLong(StringHelper.after(group, ":"));
int count = Integer.parseInt(StringHelper.before(group, ":"));
if (count > redeliveryCounter) {
break;
} else {
answer = delay;
}
}
return answer;
}
// Builder methods
// -------------------------------------------------------------------------
/**
* Sets the initial redelivery delay in milliseconds
*/
public RedeliveryPolicy redeliveryDelay(long delay) {
setRedeliveryDelay(delay);
return this;
}
/**
* Sets the maximum number of times a message exchange will be redelivered
*/
public RedeliveryPolicy maximumRedeliveries(int maximumRedeliveries) {
setMaximumRedeliveries(maximumRedeliveries);
return this;
}
/**
* Enables collision avoidance which adds some randomization to the backoff timings to reduce contention probability
*/
public RedeliveryPolicy useCollisionAvoidance() {
setUseCollisionAvoidance(true);
return this;
}
/**
* Enables exponential backoff using the {@link #getBackOffMultiplier()} to increase the time between retries
*/
public RedeliveryPolicy useExponentialBackOff() {
setUseExponentialBackOff(true);
return this;
}
/**
* Enables exponential backoff and sets the multiplier used to increase the delay between redeliveries
*/
public RedeliveryPolicy backOffMultiplier(double multiplier) {
useExponentialBackOff();
setBackOffMultiplier(multiplier);
return this;
}
/**
* Enables collision avoidance and sets the percentage used
*/
public RedeliveryPolicy collisionAvoidancePercent(double collisionAvoidancePercent) {
useCollisionAvoidance();
setCollisionAvoidancePercent(collisionAvoidancePercent);
return this;
}
/**
* Sets the maximum redelivery delay if using exponential back off. Use -1 if you wish to have no maximum
*/
public RedeliveryPolicy maximumRedeliveryDelay(long maximumRedeliveryDelay) {
setMaximumRedeliveryDelay(maximumRedeliveryDelay);
return this;
}
/**
* Sets the logging level to use for log messages when retries have been exhausted.
*/
public RedeliveryPolicy retriesExhaustedLogLevel(LoggingLevel retriesExhaustedLogLevel) {
setRetriesExhaustedLogLevel(retriesExhaustedLogLevel);
return this;
}
/**
* Sets the logging level to use for log messages when retries are attempted.
*/
public RedeliveryPolicy retryAttemptedLogLevel(LoggingLevel retryAttemptedLogLevel) {
setRetryAttemptedLogLevel(retryAttemptedLogLevel);
return this;
}
/**
* Sets the interval to log retry attempts
*/
public RedeliveryPolicy retryAttemptedLogInterval(int logRetryAttemptedInterval) {
setRetryAttemptedLogInterval(logRetryAttemptedInterval);
return this;
}
/**
* Sets whether to log retry attempts
*/
public RedeliveryPolicy logRetryAttempted(boolean logRetryAttempted) {
setLogRetryAttempted(logRetryAttempted);
return this;
}
/**
* Sets whether to log stacktrace for failed messages.
*/
public RedeliveryPolicy logStackTrace(boolean logStackTrace) {
setLogStackTrace(logStackTrace);
return this;
}
/**
* Sets whether to log stacktrace for failed redelivery attempts
*/
public RedeliveryPolicy logRetryStackTrace(boolean logRetryStackTrace) {
setLogRetryStackTrace(logRetryStackTrace);
return this;
}
/**
* Sets whether to log errors even if its handled
*/
public RedeliveryPolicy logHandled(boolean logHandled) {
setLogHandled(logHandled);
return this;
}
/**
* Sets whether errors should be logged when a new exception occurred during handling a previous exception
*/
public RedeliveryPolicy logNewException(boolean logNewException) {
setLogNewException(logNewException);
return this;
}
/**
* Sets whether to log exhausted errors
*/
public RedeliveryPolicy logExhausted(boolean logExhausted) {
setLogExhausted(logExhausted);
return this;
}
/**
* Sets whether to log exhausted errors including message history
*/
public RedeliveryPolicy logExhaustedMessageHistory(boolean logExhaustedMessageHistory) {
setLogExhaustedMessageHistory(logExhaustedMessageHistory);
return this;
}
/**
* Sets whether to log exhausted errors including message body (requires message history to be enabled)
*/
public RedeliveryPolicy logExhaustedMessageBody(boolean logExhaustedMessageBody) {
setLogExhaustedMessageBody(logExhaustedMessageBody);
return this;
}
/**
* Sets the delay pattern with delay intervals.
*/
public RedeliveryPolicy delayPattern(String delayPattern) {
setDelayPattern(delayPattern);
return this;
}
/**
* Disables redelivery by setting maximum redeliveries to 0.
*/
public RedeliveryPolicy disableRedelivery() {
setMaximumRedeliveries(0);
return this;
}
/**
* Allow asynchronous delayed redelivery.
*
* @see #setAsyncDelayedRedelivery(boolean)
*/
public RedeliveryPolicy asyncDelayedRedelivery() {
setAsyncDelayedRedelivery(true);
return this;
}
/**
* Controls whether to allow redelivery while stopping/shutting down a route that uses error handling.
*
* @param redeliverWhileStopping <tt>true</tt> to allow redelivery, <tt>false</tt> to reject redeliveries
*/
public RedeliveryPolicy allowRedeliveryWhileStopping(boolean redeliverWhileStopping) {
setAllowRedeliveryWhileStopping(redeliverWhileStopping);
return this;
}
/**
* Sets the reference of the instance of {@link org.apache.camel.spi.ExchangeFormatter} to generate the log message
* from exchange.
*
* @param exchangeFormatterRef name of the instance of {@link org.apache.camel.spi.ExchangeFormatter}
* @return the builder
*/
public RedeliveryPolicy exchangeFormatterRef(String exchangeFormatterRef) {
setExchangeFormatterRef(exchangeFormatterRef);
return this;
}
// Properties
// -------------------------------------------------------------------------
public long getRedeliveryDelay() {
return redeliveryDelay;
}
/**
* Sets the initial redelivery delay in milliseconds
*/
public void setRedeliveryDelay(long redeliverDelay) {
this.redeliveryDelay = redeliverDelay;
// if max enabled then also set max to this value in case max was too low
if (maximumRedeliveryDelay > 0 && redeliverDelay > maximumRedeliveryDelay) {
this.maximumRedeliveryDelay = redeliverDelay;
}
}
public double getBackOffMultiplier() {
return backOffMultiplier;
}
/**
* Sets the multiplier used to increase the delay between redeliveries if {@link #setUseExponentialBackOff(boolean)}
* is enabled
*/
public void setBackOffMultiplier(double backOffMultiplier) {
this.backOffMultiplier = backOffMultiplier;
}
public long getCollisionAvoidancePercent() {
return Math.round(collisionAvoidanceFactor * 100);
}
/**
* Sets the percentage used for collision avoidance if enabled via {@link #setUseCollisionAvoidance(boolean)}
*/
public void setCollisionAvoidancePercent(double collisionAvoidancePercent) {
this.collisionAvoidanceFactor = collisionAvoidancePercent * 0.01d;
}
public double getCollisionAvoidanceFactor() {
return collisionAvoidanceFactor;
}
/**
* Sets the factor used for collision avoidance if enabled via {@link #setUseCollisionAvoidance(boolean)}
*/
public void setCollisionAvoidanceFactor(double collisionAvoidanceFactor) {
this.collisionAvoidanceFactor = collisionAvoidanceFactor;
}
public int getMaximumRedeliveries() {
return maximumRedeliveries;
}
/**
* Sets the maximum number of times a message exchange will be redelivered. Setting a negative value will retry
* forever.
*/
public void setMaximumRedeliveries(int maximumRedeliveries) {
this.maximumRedeliveries = maximumRedeliveries;
}
public long getMaximumRedeliveryDelay() {
return maximumRedeliveryDelay;
}
/**
* Sets the maximum redelivery delay. Use -1 if you wish to have no maximum
*/
public void setMaximumRedeliveryDelay(long maximumRedeliveryDelay) {
this.maximumRedeliveryDelay = maximumRedeliveryDelay;
}
public boolean isUseCollisionAvoidance() {
return useCollisionAvoidance;
}
/**
* Enables/disables collision avoidance which adds some randomization to the backoff timings to reduce contention
* probability
*/
public void setUseCollisionAvoidance(boolean useCollisionAvoidance) {
this.useCollisionAvoidance = useCollisionAvoidance;
}
public boolean isUseExponentialBackOff() {
return useExponentialBackOff;
}
/**
* Enables/disables exponential backoff using the {@link #getBackOffMultiplier()} to increase the time between
* retries
*/
public void setUseExponentialBackOff(boolean useExponentialBackOff) {
this.useExponentialBackOff = useExponentialBackOff;
}
protected static Random getRandomNumberGenerator() {
LOCK.lock();
try {
if (randomNumberGenerator == null) {
randomNumberGenerator = new Random(); // NOSONAR
}
return randomNumberGenerator;
} finally {
LOCK.unlock();
}
}
/**
* Sets the logging level to use for log messages when retries have been exhausted.
*/
public void setRetriesExhaustedLogLevel(LoggingLevel retriesExhaustedLogLevel) {
this.retriesExhaustedLogLevel = retriesExhaustedLogLevel;
}
public LoggingLevel getRetriesExhaustedLogLevel() {
return retriesExhaustedLogLevel;
}
/**
* Sets the logging level to use for log messages when retries are attempted.
*/
public void setRetryAttemptedLogLevel(LoggingLevel retryAttemptedLogLevel) {
this.retryAttemptedLogLevel = retryAttemptedLogLevel;
}
public LoggingLevel getRetryAttemptedLogLevel() {
return retryAttemptedLogLevel;
}
public int getRetryAttemptedLogInterval() {
return retryAttemptedLogInterval;
}
/**
* Sets the interval to log retry attempts
*/
public void setRetryAttemptedLogInterval(int retryAttemptedLogInterval) {
this.retryAttemptedLogInterval = retryAttemptedLogInterval;
}
public String getDelayPattern() {
return delayPattern;
}
/**
* Sets an optional delay pattern to use instead of fixed delay.
*/
public void setDelayPattern(String delayPattern) {
this.delayPattern = delayPattern;
}
public boolean isLogStackTrace() {
return logStackTrace;
}
/**
* Sets whether stack traces should be logged or not
*/
public void setLogStackTrace(boolean logStackTrace) {
this.logStackTrace = logStackTrace;
}
public boolean isLogRetryStackTrace() {
return logRetryStackTrace;
}
/**
* Sets whether stack traces should be logged or not
*/
public void setLogRetryStackTrace(boolean logRetryStackTrace) {
this.logRetryStackTrace = logRetryStackTrace;
}
public boolean isLogHandled() {
return logHandled;
}
/**
* Sets whether errors should be logged even if its handled
*/
public void setLogHandled(boolean logHandled) {
this.logHandled = logHandled;
}
public boolean isLogNewException() {
return logNewException;
}
/**
* Sets whether errors should be logged when a new exception occurred during handling a previous exception
*/
public void setLogNewException(boolean logNewException) {
this.logNewException = logNewException;
}
public boolean isLogContinued() {
return logContinued;
}
/**
* Sets whether errors should be logged even if its continued
*/
public void setLogContinued(boolean logContinued) {
this.logContinued = logContinued;
}
public boolean isLogRetryAttempted() {
return logRetryAttempted;
}
/**
* Sets whether retry attempts should be logged or not
*/
public void setLogRetryAttempted(boolean logRetryAttempted) {
this.logRetryAttempted = logRetryAttempted;
}
public boolean isLogExhausted() {
return logExhausted;
}
/**
* Sets whether exhausted exceptions should be logged or not
*/
public void setLogExhausted(boolean logExhausted) {
this.logExhausted = logExhausted;
}
public boolean isLogExhaustedMessageHistory() {
// should default be enabled
return logExhaustedMessageHistory == null || logExhaustedMessageHistory;
}
/**
* Whether the option logExhaustedMessageHistory has been configured or not
*
* @return <tt>null</tt> if not configured, or the configured value as true or false
* @see #isLogExhaustedMessageHistory()
*/
public Boolean getLogExhaustedMessageHistory() {
return logExhaustedMessageHistory;
}
/**
* Sets whether exhausted exceptions should be logged with message history included.
*/
public void setLogExhaustedMessageHistory(boolean logExhaustedMessageHistory) {
this.logExhaustedMessageHistory = logExhaustedMessageHistory;
}
public boolean isLogExhaustedMessageBody() {
// should default be disabled
return logExhaustedMessageBody != null && logExhaustedMessageBody;
}
/**
* Whether the option logExhaustedMessageBody has been configured or not
*
* @return <tt>null</tt> if not configured, or the configured value as true or false
* @see #isLogExhaustedMessageBody()
*/
public Boolean getLogExhaustedMessageBody() {
return logExhaustedMessageBody;
}
/**
* Sets whether exhausted message body/headers should be logged with message history included (requires
* logExhaustedMessageHistory to be enabled).
*/
public void setLogExhaustedMessageBody(Boolean logExhaustedMessageBody) {
this.logExhaustedMessageBody = logExhaustedMessageBody;
}
public boolean isAsyncDelayedRedelivery() {
return asyncDelayedRedelivery;
}
/**
* Sets whether asynchronous delayed redelivery is allowed.
* <p/>
* This is disabled by default.
* <p/>
* When enabled it allows Camel to schedule a future task for delayed redelivery which prevents current thread from
* blocking while waiting.
* <p/>
* Exchange which is transacted will however always use synchronous delayed redelivery because the transaction must
* execute in the same thread context.
*
* @param asyncDelayedRedelivery whether asynchronous delayed redelivery is allowed
*/
public void setAsyncDelayedRedelivery(boolean asyncDelayedRedelivery) {
this.asyncDelayedRedelivery = asyncDelayedRedelivery;
}
public boolean isAllowRedeliveryWhileStopping() {
return allowRedeliveryWhileStopping;
}
/**
* Controls whether to allow redelivery while stopping/shutting down a route that uses error handling.
*
* @param allowRedeliveryWhileStopping <tt>true</tt> to allow redelivery, <tt>false</tt> to reject redeliveries
*/
public void setAllowRedeliveryWhileStopping(boolean allowRedeliveryWhileStopping) {
this.allowRedeliveryWhileStopping = allowRedeliveryWhileStopping;
}
public String getExchangeFormatterRef() {
return exchangeFormatterRef;
}
/**
* Sets the reference of the instance of {@link org.apache.camel.spi.ExchangeFormatter} to generate the log message
* from exchange.
*/
public void setExchangeFormatterRef(String exchangeFormatterRef) {
this.exchangeFormatterRef = exchangeFormatterRef;
}
}
| RedeliveryPolicy |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/inheritance/SourceBase.java | {
"start": 199,
"end": 427
} | class ____ {
//CHECKSTYLE:OFF
public int publicFoo;
//CHECKSTYLE:ON
private int foo;
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
}
| SourceBase |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/saml/SamlMessageBuilder.java | {
"start": 785,
"end": 890
} | class ____ object that build some sort of {@link org.opensaml.saml.common.SAMLObject}
*/
public abstract | for |
java | spring-projects__spring-boot | module/spring-boot-hazelcast/src/main/java/org/springframework/boot/hazelcast/autoconfigure/HazelcastServerConfiguration.java | {
"start": 1900,
"end": 2457
} | class ____ {
static final String CONFIG_SYSTEM_PROPERTY = "hazelcast.config";
static final String HAZELCAST_LOGGING_TYPE = "hazelcast.logging.type";
private static HazelcastInstance getHazelcastInstance(Config config) {
if (StringUtils.hasText(config.getInstanceName())) {
return Hazelcast.getOrCreateHazelcastInstance(config);
}
return Hazelcast.newHazelcastInstance(config);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(Config.class)
@Conditional(ConfigAvailableCondition.class)
static | HazelcastServerConfiguration |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DifferentNameButSameTest.java | {
"start": 4661,
"end": 5025
} | interface ____ {
@TypeUseAnnotation
B test();
B test2();
}
""")
.doTest();
}
@Test
public void typeUseAnnotation_leftInCorrectPosition() {
helper
.addInputLines(
"Test.java",
"""
package pkg;
import pkg.A.B;
| Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/EmbeddableMetaModelTest.java | {
"start": 873,
"end": 2965
} | class ____ {
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-11111" )
public void testEmbeddableCanBeResolvedWhenUsedAsInterface(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
assertNotNull( entityManager.getMetamodel().embeddable( LocalizedValue.class ) );
assertEquals( LocalizedValue.class, ProductEntity_.description.getElementType().getJavaType() );
assertNotNull( LocalizedValue_.value );
} );
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-12124" )
public void testEmbeddableEquality(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
assertTrue( entityManager.getMetamodel().getEmbeddables().contains( Company_.address.getType() ) );
assertTrue( entityManager.getMetamodel().getEmbeddables().contains( Person_.height.getType() ) );
} );
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-18103" )
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final EmbeddableDomainType<Height> embeddable = (EmbeddableDomainType<Height>) entityManager.getMetamodel()
.embeddable( Height.class );
assertNotNull( embeddable.getSuperType() );
assertEquals( MAPPED_SUPERCLASS, embeddable.getSuperType().getPersistenceType() );
assertEquals( Measurement.class, embeddable.getSuperType().getJavaType() );
assertNotNull( Height_.height );
assertNotNull( Measurement_.unit );
} );
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-18819" )
public void testIdClass(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final EmbeddableDomainType<Weight> embeddable = (EmbeddableDomainType<Weight>) entityManager.getMetamodel()
.embeddable( Weight.class );
assertNotNull( embeddable.getSuperType() );
assertEquals( MAPPED_SUPERCLASS, embeddable.getSuperType().getPersistenceType() );
assertEquals( Measurement.class, embeddable.getSuperType().getJavaType() );
assertNotNull( Weight_.weight );
assertNotNull( Measurement_.unit );
} );
}
}
| EmbeddableMetaModelTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/jdk/BigDecimalForFloatDisabled3133Test.java | {
"start": 694,
"end": 1018
} | class ____
extends DatabindTestUtil
{
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = TestMapContainer3133.class, name = "MAP"),
})
| BigDecimalForFloatDisabled3133Test |
java | netty__netty | transport/src/main/java/io/netty/channel/AbstractChannelHandlerContext.java | {
"start": 44469,
"end": 47245
} | class ____ implements Runnable {
private static final Recycler<WriteTask> RECYCLER = new Recycler<WriteTask>() {
@Override
protected WriteTask newObject(Handle<WriteTask> handle) {
return new WriteTask(handle);
}
};
static WriteTask newInstance(AbstractChannelHandlerContext ctx,
Object msg, ChannelPromise promise, boolean flush) {
WriteTask task = RECYCLER.get();
init(task, ctx, msg, promise, flush);
return task;
}
private static final boolean ESTIMATE_TASK_SIZE_ON_SUBMIT =
SystemPropertyUtil.getBoolean("io.netty.transport.estimateSizeOnSubmit", true);
// Assuming compressed oops, 12 bytes obj header, 4 ref fields and one int field
private static final int WRITE_TASK_OVERHEAD =
SystemPropertyUtil.getInt("io.netty.transport.writeTaskSizeOverhead", 32);
private final Handle<WriteTask> handle;
private AbstractChannelHandlerContext ctx;
private Object msg;
private ChannelPromise promise;
private int size; // sign bit controls flush
private WriteTask(Handle<WriteTask> handle) {
this.handle = handle;
}
static void init(WriteTask task, AbstractChannelHandlerContext ctx,
Object msg, ChannelPromise promise, boolean flush) {
task.ctx = ctx;
task.msg = msg;
task.promise = promise;
if (ESTIMATE_TASK_SIZE_ON_SUBMIT) {
task.size = ctx.pipeline.estimatorHandle().size(msg) + WRITE_TASK_OVERHEAD;
ctx.pipeline.incrementPendingOutboundBytes(task.size);
} else {
task.size = 0;
}
if (flush) {
task.size |= Integer.MIN_VALUE;
}
}
@Override
public void run() {
try {
decrementPendingOutboundBytes();
ctx.write(msg, size < 0, promise);
} finally {
recycle();
}
}
void cancel() {
try {
decrementPendingOutboundBytes();
} finally {
recycle();
}
}
private void decrementPendingOutboundBytes() {
if (ESTIMATE_TASK_SIZE_ON_SUBMIT) {
ctx.pipeline.decrementPendingOutboundBytes(size & Integer.MAX_VALUE);
}
}
private void recycle() {
// Set to null so the GC can collect them directly
ctx = null;
msg = null;
promise = null;
handle.recycle(this);
}
}
static final | WriteTask |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotCloseToPercentage_Double_Test.java | {
"start": 1012,
"end": 1492
} | class ____ extends DoubleAssertBaseTest {
private final Percentage percentage = withPercentage(5.0);
private final Double value = 10.0;
@Override
protected DoubleAssert invoke_api_method() {
return assertions.isNotCloseTo(value, percentage);
}
@Override
protected void verify_internal_effects() {
verify(doubles).assertIsNotCloseToPercentage(getInfo(assertions), getActual(assertions), value, percentage);
}
}
| DoubleAssert_isNotCloseToPercentage_Double_Test |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_3300/Issue3334.java | {
"start": 1409,
"end": 2569
} | class ____ {
private byte id8;
private short id16;
private int id;
private long id64;
private Float floatValue;
private Double doubleValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getId64() {
return id64;
}
public void setId64(long id64) {
this.id64 = id64;
}
public short getId16() {
return id16;
}
public void setId16(short id16) {
this.id16 = id16;
}
public byte getId8() {
return id8;
}
public void setId8(byte id8) {
this.id8 = id8;
}
public Float getFloatValue() {
return floatValue;
}
public void setFloatValue(Float floatValue) {
this.floatValue = floatValue;
}
public Double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
}
}
| VO |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RemoveUnusedImportsTest.java | {
"start": 9019,
"end": 9100
} | class ____ {
List x;
}
| MultipleTopLevelClasses |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java | {
"start": 4837,
"end": 5444
} | class ____ {
public static final Object lock = new Object();
@GuardedBy("lock")
public static int x;
void m() {
synchronized (Test.lock) {
Test.x++;
}
}
}
""")
.doTest();
}
@Test
public void guardedStaticFieldAccess_2() {
compilationHelper
.addSourceLines(
"threadsafety/Test.java",
"""
package threadsafety;
import com.google.errorprone.annotations.concurrent.GuardedBy;
| Test |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/reifier/ProcessorReifierTest.java | {
"start": 1052,
"end": 1532
} | class ____ {
@Test
public void testHandleCustomProcessorDefinition() {
Route ctx = new DefaultRoute(null, null, null, null, null, null, null);
ProcessorReifier.registerReifier(MyProcessorDefinition.class, ProcessReifier::new);
ProcessReifier ref = (ProcessReifier) ProcessorReifier.reifier(ctx, new MyProcessorDefinition());
Assertions.assertInstanceOf(MyProcessorDefinition.class, ref.definition);
}
public static | ProcessorReifierTest |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java | {
"start": 16730,
"end": 16839
} | class ____, followed by "#" as
* separator, and then the method name. For example "PC#getPerson"
* for a | name |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java | {
"start": 5402,
"end": 9012
} | class ____'re searching on.
// MergedAnnotation implementations do not implement equals()/hashCode(),
// so we use a List and a 'visited' Set below.
List<MergedAnnotation<Annotation>> mergedAnnotations = metadata.getAnnotations().stream()
.filter(MergedAnnotation::isDirectlyPresent)
.toList();
Set<AnnotationAttributes> visited = new HashSet<>();
for (MergedAnnotation<Annotation> mergedAnnotation : mergedAnnotations) {
AnnotationAttributes attributes = mergedAnnotation.asAnnotationAttributes(ADAPTATIONS);
if (visited.add(attributes)) {
String annotationType = mergedAnnotation.getType().getName();
Set<String> metaAnnotationTypes = this.metaAnnotationTypesCache.computeIfAbsent(annotationType,
key -> getMetaAnnotationTypes(mergedAnnotation));
if (isStereotypeWithNameValue(annotationType, metaAnnotationTypes, attributes)) {
Object value = attributes.get(MergedAnnotation.VALUE);
if (value instanceof String currentName && !currentName.isBlank() &&
!hasExplicitlyAliasedValueAttribute(mergedAnnotation.getType())) {
if (conventionBasedStereotypeCheckCache.add(annotationType) &&
metaAnnotationTypes.contains(COMPONENT_ANNOTATION_CLASSNAME) && logger.isWarnEnabled()) {
logger.warn("""
Support for convention-based @Component names is deprecated and will \
be removed in a future version of the framework. Please annotate the \
'value' attribute in @%s with @AliasFor(annotation=Component.class) \
to declare an explicit alias for @Component's 'value' attribute."""
.formatted(annotationType));
}
if (beanName != null && !currentName.equals(beanName)) {
throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
"component names: '" + beanName + "' versus '" + currentName + "'");
}
beanName = currentName;
}
}
}
}
return beanName;
}
private Set<String> getMetaAnnotationTypes(MergedAnnotation<Annotation> mergedAnnotation) {
Set<String> result = MergedAnnotations.from(mergedAnnotation.getType()).stream()
.map(metaAnnotation -> metaAnnotation.getType().getName())
.collect(Collectors.toCollection(LinkedHashSet::new));
return (result.isEmpty() ? Collections.emptySet() : result);
}
/**
* Get the explicit bean name for the underlying class, as configured via
* {@link org.springframework.stereotype.Component @Component} and taking into
* account {@link org.springframework.core.annotation.AliasFor @AliasFor}
* semantics for annotation attribute overrides for {@code @Component}'s
* {@code value} attribute.
* @param metadata the {@link AnnotationMetadata} for the underlying class
* @return the explicit bean name, or {@code null} if not found
* @since 6.1
* @see org.springframework.stereotype.Component#value()
*/
private @Nullable String getExplicitBeanName(AnnotationMetadata metadata) {
List<String> names = metadata.getAnnotations().stream(COMPONENT_ANNOTATION_CLASSNAME)
.map(annotation -> annotation.getString(MergedAnnotation.VALUE))
.filter(StringUtils::hasText)
.map(String::trim)
.distinct()
.toList();
if (names.size() == 1) {
return names.get(0);
}
if (names.size() > 1) {
throw new IllegalStateException(
"Stereotype annotations suggest inconsistent component names: " + names);
}
return null;
}
/**
* Check whether the given annotation is a stereotype that is allowed
* to suggest a component name through its {@code value()} attribute.
* @param annotationType the name of the annotation | we |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/misc/TestBlocking.java | {
"start": 351,
"end": 1510
} | class ____
extends DatabindTestUtil
{
/**
* This is an indirect test that should trigger problems if (and only if)
* underlying parser is advanced beyond the only element array.
* Basically, although content is invalid, this should be encountered
* quite yet.
*/
@Test
public void testEagerAdvance() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.build();
JsonParser p = createParserUsingReader("[ 1 ");
assertToken(JsonToken.START_ARRAY, p.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
// And then try to map just a single entry: shouldn't fail:
Integer I = mapper.readValue(p, Integer.class);
assertEquals(Integer.valueOf(1), I);
// and should fail only now:
try {
p.nextToken();
fail("Should not pass");
} catch (JacksonException ioe) {
verifyException(ioe, "Unexpected end-of-input: expected close marker for ARRAY");
}
p.close();
}
}
| TestBlocking |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.