language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__hadoop
hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/WorkloadMapper.java
{ "start": 1501, "end": 2611 }
class ____<KEYIN, VALUEIN, KEYOUT, VALUEOUT> extends Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> { /** * Get the description of the behavior of this mapper. * @return description string. */ public abstract String getDescription(); /** * Get a list of the description of each configuration that this mapper * accepts. * @return list of the description of each configuration. */ public abstract List<String> getConfigDescriptions(); /** * Verify that the provided configuration contains all configurations required * by this mapper. * @param conf configuration. * @return whether or not all configurations required are provided. */ public abstract boolean verifyConfigurations(Configuration conf); /** * Setup input and output formats and optional reducer. */ public void configureJob(Job job) { job.setInputFormatClass(VirtualInputFormat.class); job.setNumReduceTasks(0); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(NullWritable.class); job.setOutputFormatClass(NullOutputFormat.class); } }
WorkloadMapper
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/TriggerId.java
{ "start": 2288, "end": 2816 }
class ____ extends StdSerializer<TriggerId> { private static final long serialVersionUID = 1L; protected TriggerIdSerializer() { super(TriggerId.class); } @Override public void serialize( final TriggerId value, final JsonGenerator gen, final SerializerProvider provider) throws IOException { gen.writeString(value.toString()); } } /** JSON deserializer for {@link TriggerId}. */ public static
TriggerIdSerializer
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/jwt/JwtStringClaimValidatorTests.java
{ "start": 710, "end": 24632 }
class ____ extends ESTestCase { public void testClaimIsNotString() throws ParseException { final String claimName = randomAlphaOfLength(10); final String fallbackClaimName = randomAlphaOfLength(12); final JwtStringClaimValidator validator; final JWTClaimsSet jwtClaimsSet; if (randomBoolean()) { validator = new JwtStringClaimValidator(claimName, randomBoolean(), List.of(), List.of()); // fallback claim is ignored jwtClaimsSet = JWTClaimsSet.parse(Map.of(claimName, List.of(42), fallbackClaimName, randomAlphaOfLength(8))); } else { validator = new JwtStringClaimValidator(claimName, randomBoolean(), Map.of(claimName, fallbackClaimName), List.of(), List.of()); jwtClaimsSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, List.of(42))); } final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), jwtClaimsSet) ); assertThat(e.getMessage(), containsString("cannot parse string claim")); assertThat(e.getCause(), instanceOf(ParseException.class)); } public void testClaimIsNotSingleValued() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final JwtStringClaimValidator validator; final JWTClaimsSet jwtClaimsSet; if (randomBoolean()) { validator = new JwtStringClaimValidator(claimName, true, List.of(), List.of()); // fallback claim is ignored jwtClaimsSet = JWTClaimsSet.parse(Map.of(claimName, List.of("foo", "bar"), fallbackClaimName, randomAlphaOfLength(8))); } else { validator = new JwtStringClaimValidator(claimName, true, Map.of(claimName, fallbackClaimName), List.of(), List.of()); jwtClaimsSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, List.of("foo", "bar"))); } final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), jwtClaimsSet) ); assertThat(e.getMessage(), containsString("cannot parse string claim")); assertThat(e.getCause(), instanceOf(ParseException.class)); } public void testClaimDoesNotExist() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final JwtStringClaimValidator validator; final JWTClaimsSet jwtClaimsSet; if (randomBoolean()) { validator = new JwtStringClaimValidator(claimName, randomBoolean(), List.of(), List.of()); } else { validator = new JwtStringClaimValidator(claimName, randomBoolean(), Map.of(claimName, fallbackClaimName), List.of(), List.of()); } jwtClaimsSet = JWTClaimsSet.parse(Map.of()); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), jwtClaimsSet) ); assertThat(e.getMessage(), containsString("missing required string claim")); } public void testMatchingClaimValues() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final String claimValue = randomAlphaOfLength(10); final boolean singleValuedClaim = randomBoolean(); final List<String> allowedClaimValues = List.of(claimValue, randomAlphaOfLengthBetween(11, 20)); final Object incomingClaimValue = singleValuedClaim ? claimValue : randomFrom(claimValue, List.of(claimValue, "other-stuff")); final JwtStringClaimValidator validator; final JWTClaimsSet validJwtClaimsSet; final boolean noFallback = randomBoolean(); if (noFallback) { validator = new JwtStringClaimValidator(claimName, singleValuedClaim, allowedClaimValues, List.of()); // fallback claim is ignored validJwtClaimsSet = JWTClaimsSet.parse(Map.of(claimName, incomingClaimValue, fallbackClaimName, List.of(42))); } else { validator = new JwtStringClaimValidator( claimName, singleValuedClaim, Map.of(claimName, fallbackClaimName), allowedClaimValues, List.of() ); validJwtClaimsSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, incomingClaimValue)); } try { validator.validate(getJwsHeader(), validJwtClaimsSet); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } String invalidClaimValue; if (randomBoolean()) { invalidClaimValue = "not-" + claimValue; } else { // letter case mismatch: invert case at pos i int i = randomIntBetween(0, claimValue.length() - 1); invalidClaimValue = claimValue.substring(0, i); if (Character.isUpperCase(claimValue.charAt(i))) { invalidClaimValue += claimValue.substring(i, i).toLowerCase(Locale.ROOT); } else if (Character.isLowerCase(claimValue.charAt(i))) { invalidClaimValue += claimValue.substring(i, i).toUpperCase(Locale.ROOT); } else { throw new AssertionError("Unrecognized case"); } invalidClaimValue += claimValue.substring(i + 1); } { final JWTClaimsSet invalidJwtClaimsSet; if (noFallback) { // fallback is ignored (even when it has a valid value) since the main claim exists invalidJwtClaimsSet = JWTClaimsSet.parse(Map.of(claimName, invalidClaimValue, fallbackClaimName, claimValue)); } else { invalidJwtClaimsSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, invalidClaimValue)); } final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidJwtClaimsSet) ); assertThat(e.getMessage(), containsString("does not match allowed claim values")); } } public void testWildcardAndRegexMatchingClaimValues() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final List<String> allowedClaimPatterns = List.of("a?\\**", "/https?://[^/]+/?/"); final boolean noFallback = randomBoolean(); final JwtStringClaimValidator validator; if (noFallback) { validator = new JwtStringClaimValidator(claimName, false, List.of(), allowedClaimPatterns); } else { validator = new JwtStringClaimValidator( claimName, false, Map.of(claimName, fallbackClaimName), List.of(), allowedClaimPatterns ); } for (String incomingClaimValue : List.of("a1*", "ab*whatever", "https://elastic.co/")) { final JWTClaimsSet validJwtClaimsSet; if (noFallback) { // fallback claim is ignored validJwtClaimsSet = JWTClaimsSet.parse( Map.of( claimName, randomBoolean() ? incomingClaimValue : List.of(incomingClaimValue, "other_stuff"), fallbackClaimName, List.of(42) ) ); } else { validJwtClaimsSet = JWTClaimsSet.parse( Map.of(fallbackClaimName, randomBoolean() ? incomingClaimValue : List.of(incomingClaimValue, "other_stuff")) ); } try { validator.validate(getJwsHeader(), validJwtClaimsSet); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } } for (String invalidIncomingClaimValue : List.of("a", "abc", "abc*", "https://elastic.co/guide")) { final JWTClaimsSet invalidJwtClaimsSet; if (noFallback) { // fallback claim is ignored invalidJwtClaimsSet = JWTClaimsSet.parse( Map.of( claimName, randomBoolean() ? invalidIncomingClaimValue : List.of(invalidIncomingClaimValue, "other_stuff"), fallbackClaimName, List.of(42) ) ); } else { invalidJwtClaimsSet = JWTClaimsSet.parse( Map.of( fallbackClaimName, randomBoolean() ? invalidIncomingClaimValue : List.of(invalidIncomingClaimValue, "other_stuff") ) ); } final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidJwtClaimsSet) ); assertThat(e.getMessage(), containsString("does not match allowed claim values")); } } public void testValueAllowSettingDoesNotSupportWildcardOrRegex() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final String claimValue = randomFrom("*", "/.*/"); final JwtStringClaimValidator validator; final JWTClaimsSet invalidJwtClaimsSet; final boolean noFallback = randomBoolean(); if (noFallback) { validator = new JwtStringClaimValidator(claimName, randomBoolean(), List.of(claimValue), List.of()); // fallback is ignored (even when it has a valid value) since the main claim exists invalidJwtClaimsSet = JWTClaimsSet.parse(Map.of(claimName, randomAlphaOfLengthBetween(1, 10), fallbackClaimName, claimValue)); } else { validator = new JwtStringClaimValidator( claimName, randomBoolean(), Map.of(claimName, fallbackClaimName), List.of(claimValue), List.of() ); invalidJwtClaimsSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, randomAlphaOfLengthBetween(1, 10))); } // It should not match arbitrary claim value because wildcard or regex is not supported final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidJwtClaimsSet) ); assertThat(e.getMessage(), containsString("does not match allowed claim values")); // It should support literal matching final JWTClaimsSet validJwtClaimsSet; if (noFallback) { // fallback claim is ignored validJwtClaimsSet = JWTClaimsSet.parse(Map.of(claimName, claimValue, fallbackClaimName, randomAlphaOfLength(10))); } else { validJwtClaimsSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, claimValue)); } try { validator.validate(getJwsHeader(), validJwtClaimsSet); } catch (Exception e2) { throw new AssertionError("validation should have passed without exception", e2); } } public void testSinglePatternSingleClaim() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final String claimPattern = randomFrom("a*", "/a.*/"); final JwtStringClaimValidator validator; final JWTClaimsSet singleValueClaimSet; final boolean noFallback = randomBoolean(); if (noFallback) { validator = new JwtStringClaimValidator(claimName, randomBoolean(), List.of(), List.of(claimPattern)); singleValueClaimSet = JWTClaimsSet.parse( Map.of(claimName, "a_claim", fallbackClaimName, randomFrom(List.of("invalid", "invalid2"), "invalid"), "something", "else") ); } else { validator = new JwtStringClaimValidator( claimName, randomBoolean(), Map.of(claimName, fallbackClaimName), List.of(), List.of(claimPattern) ); singleValueClaimSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, "a_fallback_claim", "something", "else")); } try { validator.validate(getJwsHeader(), singleValueClaimSet); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } { JWTClaimsSet invalidClaimSet = JWTClaimsSet.parse( Map.of(claimName, "invalid", fallbackClaimName, randomFrom(List.of("a_claim", "a_claim2"), "a_claim"), "something", "else") ); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidClaimSet) ); assertThat(e.getMessage(), containsString("does not match allowed claim values")); } { JWTClaimsSet invalidClaimSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, "invalid", "something", "else")); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidClaimSet) ); if (noFallback) { assertThat(e.getMessage(), containsString("missing required string claim")); } else { assertThat(e.getMessage(), containsString("does not match allowed claim values")); } } } public void testPatternListSingleClaim() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final List<String> claimPatterns = List.of("a*", "/b.*b/"); final JwtStringClaimValidator validator; final JWTClaimsSet singleValueClaimSet; final boolean noFallback = randomBoolean(); if (noFallback) { validator = new JwtStringClaimValidator(claimName, randomBoolean(), List.of(), claimPatterns); singleValueClaimSet = JWTClaimsSet.parse( Map.of( claimName, "b_claim_b", fallbackClaimName, randomFrom(List.of("invalid", "invalid2"), "invalid"), "something", "else" ) ); } else { validator = new JwtStringClaimValidator( claimName, randomBoolean(), Map.of(claimName, fallbackClaimName), List.of(), claimPatterns ); singleValueClaimSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, "b_fallback_claim_b", "something", "else")); } try { validator.validate(getJwsHeader(), singleValueClaimSet); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } { JWTClaimsSet invalidClaimSet = JWTClaimsSet.parse( Map.of( claimName, "invalid", fallbackClaimName, randomFrom(List.of("b_claim_b", "b_claim2_b"), "b_claim_b"), "something", "else" ) ); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidClaimSet) ); assertThat(e.getMessage(), containsString("does not match allowed claim values")); } { JWTClaimsSet invalidClaimSet = JWTClaimsSet.parse(Map.of(fallbackClaimName, "invalid", "something", "else")); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidClaimSet) ); if (noFallback) { assertThat(e.getMessage(), containsString("missing required string claim")); } else { assertThat(e.getMessage(), containsString("does not match allowed claim values")); } } } public void testPatternListClaimList() throws ParseException { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomAlphaOfLength(8); final List<String> claimPatterns = List.of("a*", "/b.*b/"); final JwtStringClaimValidator validator; final JWTClaimsSet singleValueClaimSet; final boolean noFallback = randomBoolean(); if (noFallback) { validator = new JwtStringClaimValidator(claimName, false, List.of(), claimPatterns); singleValueClaimSet = JWTClaimsSet.parse( Map.of( claimName, List.of("invalid", "b_claim_b"), fallbackClaimName, randomFrom(List.of("invalid", "invalid2"), "invalid"), "something", "else" ) ); } else { validator = new JwtStringClaimValidator(claimName, false, Map.of(claimName, fallbackClaimName), List.of(), claimPatterns); singleValueClaimSet = JWTClaimsSet.parse( Map.of(fallbackClaimName, List.of("invalid", "b_fallback_claim_b"), "something", "else") ); } try { validator.validate(getJwsHeader(), singleValueClaimSet); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } { JWTClaimsSet invalidClaimSet = JWTClaimsSet.parse( Map.of( claimName, List.of("invalid", "invalid2"), fallbackClaimName, randomFrom(List.of("b_claim_b", "a_claim"), "b_claim_b"), "something", "else" ) ); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidClaimSet) ); assertThat(e.getMessage(), containsString("does not match allowed claim values")); } { JWTClaimsSet invalidClaimSet = JWTClaimsSet.parse( Map.of(fallbackClaimName, List.of("invalid", "invalid2"), "something", "else") ); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> validator.validate(getJwsHeader(), invalidClaimSet) ); if (noFallback) { assertThat(e.getMessage(), containsString("missing required string claim")); } else { assertThat(e.getMessage(), containsString("does not match allowed claim values")); } } } public void testBothPatternAndSimpleValue() { final String claimName = randomAlphaOfLengthBetween(10, 18); final String fallbackClaimName = randomFrom(randomAlphaOfLength(8), null); final List<String> claimPatterns = List.of("a*", "/.*Z.*/", "*b"); final List<String> claimValues = List.of("c", "dd", "eZe"); final JwtStringClaimValidator singleValueValidator = new JwtStringClaimValidator( claimName, randomBoolean(), fallbackClaimName == null ? null : Map.of(claimName, fallbackClaimName), claimValues, claimPatterns ); for (String claimValue : List.of("a_claim", "anotZer_claim", "Z", "claim_b", "c", "dd", "eZe")) { if (fallbackClaimName != null) { try { singleValueValidator.validate( getJwsHeader(), JWTClaimsSet.parse(Map.of(fallbackClaimName, claimValue, "something", "else")) ); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } } else { try { singleValueValidator.validate(getJwsHeader(), JWTClaimsSet.parse(Map.of(claimName, claimValue, "something", "else"))); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } } } for (String invalidClaimValue : List.of("invalid", "cc", "ca", "dda", "ba")) { IllegalArgumentException e; if (fallbackClaimName != null) { e = expectThrows( IllegalArgumentException.class, () -> singleValueValidator.validate( getJwsHeader(), JWTClaimsSet.parse(Map.of(fallbackClaimName, invalidClaimValue, "something", "else")) ) ); } else { e = expectThrows( IllegalArgumentException.class, () -> singleValueValidator.validate( getJwsHeader(), JWTClaimsSet.parse(Map.of(claimName, invalidClaimValue, "something", "else")) ) ); } assertThat(e.getMessage(), containsString("does not match allowed claim values")); } } public void testInvalidPatternThrows() { String claimName = randomAlphaOfLength(4); SettingsException e = expectThrows( SettingsException.class, () -> new JwtStringClaimValidator( claimName, randomBoolean(), randomBoolean() ? null : Map.of(randomAlphaOfLength(4), randomAlphaOfLength(8)), randomBoolean() ? List.of() : List.of("dummy"), List.of("/invalid pattern") ) ); assertThat(e.getMessage(), containsString("Invalid patterns for allowed claim values for [" + claimName + "].")); } public void testAllowAllSubjects() { try { JwtStringClaimValidator.ALLOW_ALL_SUBJECTS.validate( getJwsHeader(), JWTClaimsSet.parse(Map.of("sub", randomAlphaOfLengthBetween(1, 10))) ); } catch (Exception e) { throw new AssertionError("validation should have passed without exception", e); } final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> JwtStringClaimValidator.ALLOW_ALL_SUBJECTS.validate(getJwsHeader(), JWTClaimsSet.parse(Map.of())) ); assertThat(e.getMessage(), containsString("missing required string claim")); } private JWSHeader getJwsHeader() throws ParseException { return JWSHeader.parse(Map.of("alg", randomAlphaOfLengthBetween(3, 8))); } }
JwtStringClaimValidatorTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/graph/spi/SubGraphImplementor.java
{ "start": 360, "end": 755 }
interface ____<J> extends SubGraph<J>, GraphImplementor<J> { @Override SubGraphImplementor<J> makeCopy(boolean mutable); @Override @Deprecated(forRemoval = true) SubGraphImplementor<J> makeSubGraph(boolean mutable); @Override @Deprecated(forRemoval = true) RootGraphImplementor<J> makeRootGraph(String name, boolean mutable) throws CannotBecomeEntityGraphException; }
SubGraphImplementor
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java
{ "start": 24663, "end": 24892 }
class ____ extends AbstractService { @Override protected void doStart() { notifyStarted(); } @Override protected void doStop() { notifyFailed(EXCEPTION); } } private static
StopFailingService
java
alibaba__druid
core/src/main/java/com/alibaba/druid/util/jdbc/PreparedStatementBase.java
{ "start": 976, "end": 9573 }
class ____ extends StatementBase implements PreparedStatement { private List<Object> parameters = new ArrayList<Object>(); private MockParameterMetaData metadata = new MockParameterMetaData(); private MockResultSetMetaData resultSetMetaData = new MockResultSetMetaData(); public PreparedStatementBase(Connection connection) { super(connection); } public List<Object> getParameters() { return parameters; } @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { parameters.add(parameterIndex - 1, null); } @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setByte(int parameterIndex, byte x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setShort(int parameterIndex, short x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setInt(int parameterIndex, int x) throws SQLException { for (int i = parameters.size(); i < parameterIndex; ++i) { parameters.add(null); } parameters.add(parameterIndex - 1, x); } @Override public void setLong(int parameterIndex, long x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setFloat(int parameterIndex, float x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setDouble(int parameterIndex, double x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setString(int parameterIndex, String x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setDate(int parameterIndex, Date x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setTime(int parameterIndex, Time x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void clearParameters() throws SQLException { checkOpen(); parameters.clear(); } @Override public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setObject(int parameterIndex, Object x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void addBatch() throws SQLException { checkOpen(); } @Override public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { parameters.add(parameterIndex - 1, reader); } @Override public void setRef(int parameterIndex, Ref x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setClob(int parameterIndex, Clob x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setArray(int parameterIndex, Array x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public ResultSetMetaData getMetaData() throws SQLException { checkOpen(); return resultSetMetaData; } @Override public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { parameters.add(parameterIndex - 1, null); } @Override public void setURL(int parameterIndex, URL x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public ParameterMetaData getParameterMetaData() throws SQLException { checkOpen(); return metadata; } @Override public void setRowId(int parameterIndex, RowId x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setNString(int parameterIndex, String value) throws SQLException { parameters.add(parameterIndex - 1, value); } @Override public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { parameters.add(parameterIndex - 1, value); } @Override public void setNClob(int parameterIndex, NClob value) throws SQLException { parameters.add(parameterIndex - 1, value); } @Override public void setClob(int parameterIndex, Reader value, long length) throws SQLException { parameters.add(parameterIndex - 1, value); } @Override public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { parameters.add(parameterIndex - 1, inputStream); } @Override public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { parameters.add(parameterIndex - 1, reader); } @Override public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { parameters.add(parameterIndex - 1, xmlObject); } @Override public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { parameters.add(parameterIndex - 1, reader); } @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { parameters.add(parameterIndex - 1, x); } @Override public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { parameters.add(parameterIndex - 1, reader); } @Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { parameters.add(parameterIndex - 1, value); } @Override public void setClob(int parameterIndex, Reader reader) throws SQLException { parameters.add(parameterIndex - 1, reader); } @Override public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { parameters.add(parameterIndex - 1, inputStream); } @Override public void setNClob(int parameterIndex, Reader reader) throws SQLException { parameters.add(parameterIndex - 1, reader); } }
PreparedStatementBase
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/JpaEntityInformationSupport.java
{ "start": 2821, "end": 3291 }
class ____ {@link Metamodel}. * * @param domainClass must not be {@literal null}. * @param metamodel must not be {@literal null}. * @param persistenceUnitUtil must not be {@literal null}. * @return * @since 4.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> JpaEntityInformation<T, ?> getEntityInformation(Class<T> domainClass, Metamodel metamodel, PersistenceUnitUtil persistenceUnitUtil) { Assert.notNull(domainClass, "Domain
and
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java
{ "start": 1866, "end": 4844 }
class ____ { @Captor private ArgumentCaptor<HttpServletRequest> requestCaptor; @Captor private ArgumentCaptor<String> logCaptor; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private FilterChain filterChain; @Mock private FilterChainProxy fcp; @Mock private Logger logger; private String requestAttr; private DebugFilter filter; @BeforeEach public void setUp() { this.filter = new DebugFilter(this.fcp); ReflectionTestUtils.setField(this.filter, "logger", this.logger); this.requestAttr = DebugFilter.ALREADY_FILTERED_ATTR_NAME; } private void setupMocks() { given(this.request.getHeaderNames()).willReturn(Collections.enumeration(Collections.<String>emptyList())); given(this.request.getServletPath()).willReturn("/login"); } @Test public void doFilterProcessesRequests() throws Exception { setupMocks(); this.filter.doFilter(this.request, this.response, this.filterChain); verify(this.logger).info(anyString()); verify(this.request).setAttribute(this.requestAttr, Boolean.TRUE); verify(this.fcp).doFilter(this.requestCaptor.capture(), eq(this.response), eq(this.filterChain)); assertThat(this.requestCaptor.getValue().getClass()).isEqualTo(DebugRequestWrapper.class); verify(this.request).removeAttribute(this.requestAttr); } // SEC-1901 @Test public void doFilterProcessesForwardedRequests() throws Exception { setupMocks(); given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE); HttpServletRequest request = new DebugRequestWrapper(this.request); this.filter.doFilter(request, this.response, this.filterChain); verify(this.logger).info(anyString()); verify(this.fcp).doFilter(request, this.response, this.filterChain); verify(this.request, never()).removeAttribute(this.requestAttr); } @Test public void doFilterDoesNotWrapWithDebugRequestWrapperAgain() throws Exception { setupMocks(); given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE); HttpServletRequest fireWalledRequest = new HttpServletRequestWrapper(new DebugRequestWrapper(this.request)); this.filter.doFilter(fireWalledRequest, this.response, this.filterChain); verify(this.fcp).doFilter(fireWalledRequest, this.response, this.filterChain); } @Test public void doFilterLogsProperly() throws Exception { MockHttpServletRequest request = get().requestUri(null, "/path", "/").build(); request.addHeader("A", "A Value"); request.addHeader("A", "Another Value"); request.addHeader("B", "B Value"); this.filter.doFilter(request, this.response, this.filterChain); verify(this.logger).info(this.logCaptor.capture()); assertThat(this.logCaptor.getValue()).isEqualTo("Request received for GET '/path/':\n" + "\n" + request + "\n" + "\n" + "servletPath:/path\n" + "pathInfo:/\n" + "headers: \n" + "A: A Value, Another Value\n" + "B: B Value\n" + "\n" + "\n" + "Security filter chain: no match"); } }
DebugFilterTests
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/ReadOnlyAttributeException.java
{ "start": 130, "end": 402 }
class ____ extends Exception { public ReadOnlyAttributeException() { } public ReadOnlyAttributeException(final String attributeName, final String newValue) { super("Could not set " + attributeName + " to " + newValue); } }
ReadOnlyAttributeException
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ClassUtils.java
{ "start": 20014, "end": 20159 }
class ____ an array of primitive wrappers, * i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double. * @param clazz the
represents
java
apache__flink
flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/TwoInputNonBroadcastWindowProcessOperator.java
{ "start": 3310, "end": 36183 }
class ____<K, IN1, IN2, OUT, W extends Window> extends BaseKeyedTwoInputNonBroadcastProcessOperator<K, IN1, IN2, OUT> implements Triggerable<K, W> { private static final long serialVersionUID = 1L; // ------------------------------------------------------------------------ // Configuration values and user functions // ------------------------------------------------------------------------ private final TwoInputNonBroadcastWindowStreamProcessFunction<IN1, IN2, OUT> windowProcessFunction; /** * The allowed lateness for elements. This is used for: * * <ul> * <li>Deciding if an element should be dropped from a window due to lateness. * <li>Clearing the state of a window if the time out-of the {@code window.maxTimestamp + * allowedLateness} landmark. * </ul> */ protected final long allowedLateness; // ------------------------------------------------------------------------ // Operator components // ------------------------------------------------------------------------ protected transient InternalTimerService<W> internalTimerService; /** For serializing the window in checkpoints. */ private final TypeSerializer<W> windowSerializer; // ------------------------------------------------------------------------ // Window assigner and trigger // ------------------------------------------------------------------------ private final WindowAssigner<? super TaggedUnion<IN1, IN2>, W> windowAssigner; private transient WindowAssigner.WindowAssignerContext windowAssignerContext; private final Trigger<? super TaggedUnion<IN1, IN2>, ? super W> trigger; private transient WindowTriggerContext<K, ? super TaggedUnion<IN1, IN2>, W> triggerContext; private transient DefaultTwoInputWindowContext<K, IN1, IN2, W> windowFunctionContext; // ------------------------------------------------------------------------ // State that is not checkpointed // ------------------------------------------------------------------------ private final StateDescriptor<IN1> leftWindowStateDescriptor; private final StateDescriptor<IN2> rightWindowStateDescriptor; /** * The state in which the window contents from the left input are stored. Each window is a * namespace. */ private transient InternalAppendingState<K, W, IN1, IN1, StateIterator<IN1>, Iterable<IN1>> leftWindowState; /** * The state in which the window contents from the right input are stored. Each window is a * namespace */ private transient InternalAppendingState<K, W, IN2, IN2, StateIterator<IN2>, Iterable<IN2>> rightWindowState; /** * The {@link #leftWindowState}, typed to merging state for merging windows. Null if the window * state is not mergeable. */ private transient InternalMergingState<K, W, IN1, IN1, StateIterator<IN1>, Iterable<IN1>> leftWindowMergingState; /** * The {@link #rightWindowState}, typed to merging state for merging windows. Null if the window * state is not mergeable. */ private transient InternalMergingState<K, W, IN2, IN2, StateIterator<IN2>, Iterable<IN2>> rightWindowMergingState; /** The state that holds the merging window metadata (the sets that describe what is merged). */ private transient InternalListState<K, VoidNamespace, Tuple2<W, W>> mergingSetsState; public TwoInputNonBroadcastWindowProcessOperator( InternalTwoInputWindowStreamProcessFunction<IN1, IN2, OUT, W> windowFunction, WindowAssigner<? super TaggedUnion<IN1, IN2>, W> windowAssigner, Trigger<? super TaggedUnion<IN1, IN2>, ? super W> trigger, TypeSerializer<W> windowSerializer, StateDescriptor<IN1> leftWindowStateDescriptor, StateDescriptor<IN2> rightWindowStateDescriptor, long allowedLateness) { super(windowFunction); checkArgument(allowedLateness >= 0); this.windowProcessFunction = windowFunction.getWindowProcessFunction(); this.windowAssigner = windowAssigner; this.trigger = trigger; this.windowSerializer = windowSerializer; this.leftWindowStateDescriptor = leftWindowStateDescriptor; this.rightWindowStateDescriptor = rightWindowStateDescriptor; this.allowedLateness = allowedLateness; } @Override public void open() throws Exception { super.open(); internalTimerService = getInternalTimerService("process-window-timers", windowSerializer, this); // create (or restore) the state that hold the actual window contents // NOTE - the state may be null in the case of the overriding evicting window operator if (leftWindowStateDescriptor != null) { leftWindowState = getOrCreateKeyedState( windowSerializer.createInstance(), windowSerializer, leftWindowStateDescriptor); } if (rightWindowStateDescriptor != null) { rightWindowState = getOrCreateKeyedState( windowSerializer.createInstance(), windowSerializer, rightWindowStateDescriptor); } // create the typed and helper states for merging windows if (windowAssigner instanceof MergingWindowAssigner) { // store a typed reference for the state of merging windows - sanity check if (leftWindowState instanceof InternalMergingState) { leftWindowMergingState = (InternalMergingState<K, W, IN1, IN1, StateIterator<IN1>, Iterable<IN1>>) leftWindowState; } else if (leftWindowState != null) { throw new IllegalStateException( "The window uses a merging assigner, but the window state is not mergeable."); } if (rightWindowState instanceof InternalMergingState) { rightWindowMergingState = (InternalMergingState<K, W, IN2, IN2, StateIterator<IN2>, Iterable<IN2>>) rightWindowState; } else if (rightWindowState != null) { throw new IllegalStateException( "The window uses a merging assigner, but the window state is not mergeable."); } @SuppressWarnings("unchecked") final Class<Tuple2<W, W>> typedTuple = (Class<Tuple2<W, W>>) (Class<?>) Tuple2.class; final TupleSerializer<Tuple2<W, W>> tupleSerializer = new TupleSerializer<>( typedTuple, new TypeSerializer[] {windowSerializer, windowSerializer}); final ListStateDescriptor<Tuple2<W, W>> mergingSetsStateDescriptor = new ListStateDescriptor<>("merging-window-set", tupleSerializer); // get the state that stores the merging sets mergingSetsState = getOrCreateKeyedState( VoidNamespaceSerializer.INSTANCE.createInstance(), VoidNamespaceSerializer.INSTANCE, mergingSetsStateDescriptor); mergingSetsState.setCurrentNamespace(VoidNamespace.INSTANCE); } triggerContext = new WindowTriggerContext<>( null, null, this, internalTimerService, trigger, windowSerializer); windowAssignerContext = new WindowAssigner.WindowAssignerContext() { @Override public long getCurrentProcessingTime() { return internalTimerService.currentProcessingTime(); } }; windowFunctionContext = new DefaultTwoInputWindowContext<>( null, leftWindowState, rightWindowState, windowProcessFunction, this, windowSerializer, leftWindowMergingState != null); } @Override public void processElement1(StreamRecord<IN1> element) throws Exception { final Collection<W> elementWindows = windowAssigner.assignWindows( TaggedUnion.one(element.getValue()), element.getTimestamp(), windowAssignerContext); // if element is handled by none of assigned elementWindows boolean isSkippedElement = true; final K key = (K) this.getCurrentKey(); if (windowAssigner instanceof MergingWindowAssigner) { MergingWindowSet<W> mergingWindows = getMergingWindowSet(); for (W window : elementWindows) { // adding the new window might result in a merge, in that case the actualWindow // is the merged window and we work with that. If we don't merge then // actualWindow == window W actualWindow = mergingWindows.addWindow( window, new MergingWindowSet.MergeFunction<>() { @Override public void merge( W mergeResult, Collection<W> mergedWindows, W stateWindowResult, Collection<W> mergedStateWindows) throws Exception { if ((windowAssigner.isEventTime() && mergeResult.maxTimestamp() + allowedLateness <= internalTimerService .currentWatermark())) { throw new UnsupportedOperationException( "The end timestamp of an " + "event-time window cannot become earlier than the current watermark " + "by merging. Current event time: " + internalTimerService .currentWatermark() + " window: " + mergeResult); } else if (!windowAssigner.isEventTime()) { long currentProcessingTime = internalTimerService.currentProcessingTime(); if (mergeResult.maxTimestamp() <= currentProcessingTime) { throw new UnsupportedOperationException( "The end timestamp of a " + "processing-time window cannot become earlier than the current processing time " + "by merging. Current processing time: " + currentProcessingTime + " window: " + mergeResult); } } triggerContext.setKey(key); triggerContext.setWindow(mergeResult); triggerContext.onMerge(mergedWindows); for (W m : mergedWindows) { triggerContext.setWindow(m); triggerContext.clear(); WindowUtils.deleteCleanupTimer( m, windowAssigner, triggerContext, allowedLateness); } // merge the merged state windows into the newly resulting // state window leftWindowMergingState.mergeNamespaces( stateWindowResult, mergedStateWindows); rightWindowMergingState.mergeNamespaces( stateWindowResult, mergedStateWindows); } }); // drop if the window is already late if (WindowUtils.isWindowLate( actualWindow, windowAssigner, internalTimerService, allowedLateness)) { mergingWindows.retireWindow(actualWindow); continue; } isSkippedElement = false; W stateWindow = mergingWindows.getStateWindow(actualWindow); if (stateWindow == null) { throw new IllegalStateException( "Window " + window + " is not in in-flight window set."); } leftWindowState.setCurrentNamespace(stateWindow); collector.setTimestamp(window.maxTimestamp()); windowFunctionContext.setWindow(window); windowProcessFunction.onRecord1( element.getValue(), collector, partitionedContext, windowFunctionContext); triggerContext.setKey(key); triggerContext.setWindow(actualWindow); TriggerResult triggerResult = triggerContext.onElement( new StreamRecord<>( TaggedUnion.one(element.getValue()), element.getTimestamp())); if (triggerResult.isFire()) { emitWindowContents(actualWindow); } if (triggerResult.isPurge()) { leftWindowState.clear(); rightWindowState.clear(); } WindowUtils.registerCleanupTimer( actualWindow, windowAssigner, triggerContext, allowedLateness); } // need to make sure to update the merging state in state mergingWindows.persist(); } else { for (W window : elementWindows) { // drop if the window is already late if (WindowUtils.isWindowLate( window, windowAssigner, internalTimerService, allowedLateness)) { continue; } isSkippedElement = false; leftWindowState.setCurrentNamespace(window); collector.setTimestamp(window.maxTimestamp()); windowFunctionContext.setWindow(window); windowProcessFunction.onRecord1( element.getValue(), collector, partitionedContext, windowFunctionContext); triggerContext.setKey(key); triggerContext.setWindow(window); TriggerResult triggerResult = triggerContext.onElement( new StreamRecord<>( TaggedUnion.one(element.getValue()), element.getTimestamp())); if (triggerResult.isFire()) { emitWindowContents(window); } if (triggerResult.isPurge()) { leftWindowState.clear(); rightWindowState.clear(); } WindowUtils.registerCleanupTimer( window, windowAssigner, triggerContext, allowedLateness); } } // side output input event if element not handled by any window late arriving tag has been // set windowAssigner is event time and current timestamp + allowed lateness no less than // element timestamp. if (isSkippedElement && WindowUtils.isElementLate( element, windowAssigner, allowedLateness, internalTimerService)) { windowProcessFunction.onLateRecord1(element.getValue(), collector, partitionedContext); } } @Override public void processElement2(StreamRecord<IN2> element) throws Exception { final Collection<W> elementWindows = windowAssigner.assignWindows( TaggedUnion.two(element.getValue()), element.getTimestamp(), windowAssignerContext); // if element is handled by none of assigned elementWindows boolean isSkippedElement = true; final K key = (K) this.getCurrentKey(); if (windowAssigner instanceof MergingWindowAssigner) { MergingWindowSet<W> mergingWindows = getMergingWindowSet(); for (W window : elementWindows) { // adding the new window might result in a merge, in that case the actualWindow // is the merged window and we work with that. If we don't merge then // actualWindow == window W actualWindow = mergingWindows.addWindow( window, new MergingWindowSet.MergeFunction<>() { @Override public void merge( W mergeResult, Collection<W> mergedWindows, W stateWindowResult, Collection<W> mergedStateWindows) throws Exception { if ((windowAssigner.isEventTime() && mergeResult.maxTimestamp() + allowedLateness <= internalTimerService .currentWatermark())) { throw new UnsupportedOperationException( "The end timestamp of an " + "event-time window cannot become earlier than the current watermark " + "by merging. Current event time: " + internalTimerService .currentWatermark() + " window: " + mergeResult); } else if (!windowAssigner.isEventTime()) { long currentProcessingTime = internalTimerService.currentProcessingTime(); if (mergeResult.maxTimestamp() <= currentProcessingTime) { throw new UnsupportedOperationException( "The end timestamp of a " + "processing-time window cannot become earlier than the current processing time " + "by merging. Current processing time: " + currentProcessingTime + " window: " + mergeResult); } } triggerContext.setKey(key); triggerContext.setWindow(mergeResult); triggerContext.onMerge(mergedWindows); for (W m : mergedWindows) { triggerContext.setWindow(m); triggerContext.clear(); WindowUtils.deleteCleanupTimer( m, windowAssigner, triggerContext, allowedLateness); } // merge the merged state windows into the newly resulting // state window leftWindowMergingState.mergeNamespaces( stateWindowResult, mergedStateWindows); rightWindowMergingState.mergeNamespaces( stateWindowResult, mergedStateWindows); } }); // drop if the window is already late if (WindowUtils.isWindowLate( actualWindow, windowAssigner, internalTimerService, allowedLateness)) { mergingWindows.retireWindow(actualWindow); continue; } isSkippedElement = false; W stateWindow = mergingWindows.getStateWindow(actualWindow); if (stateWindow == null) { throw new IllegalStateException( "Window " + window + " is not in in-flight window set."); } rightWindowState.setCurrentNamespace(stateWindow); collector.setTimestamp(window.maxTimestamp()); windowFunctionContext.setWindow(window); windowProcessFunction.onRecord2( element.getValue(), collector, partitionedContext, windowFunctionContext); triggerContext.setKey(key); triggerContext.setWindow(actualWindow); TriggerResult triggerResult = triggerContext.onElement( new StreamRecord<>( TaggedUnion.two(element.getValue()), element.getTimestamp())); if (triggerResult.isFire()) { emitWindowContents(actualWindow); } if (triggerResult.isPurge()) { leftWindowState.clear(); rightWindowState.clear(); } WindowUtils.registerCleanupTimer( actualWindow, windowAssigner, triggerContext, allowedLateness); } // need to make sure to update the merging state in state mergingWindows.persist(); } else { for (W window : elementWindows) { // drop if the window is already late if (WindowUtils.isWindowLate( window, windowAssigner, internalTimerService, allowedLateness)) { continue; } isSkippedElement = false; rightWindowState.setCurrentNamespace(window); collector.setTimestamp(window.maxTimestamp()); windowFunctionContext.setWindow(window); windowProcessFunction.onRecord2( element.getValue(), collector, partitionedContext, windowFunctionContext); triggerContext.setKey(key); triggerContext.setWindow(window); TriggerResult triggerResult = triggerContext.onElement( new StreamRecord<>( TaggedUnion.two(element.getValue()), element.getTimestamp())); if (triggerResult.isFire()) { emitWindowContents(window); } if (triggerResult.isPurge()) { leftWindowState.clear(); rightWindowState.clear(); } WindowUtils.registerCleanupTimer( window, windowAssigner, triggerContext, allowedLateness); } } // side output input event if element not handled by any window late arriving tag has been // set windowAssigner is event time and current timestamp + allowed lateness no less than // element timestamp. if (isSkippedElement && WindowUtils.isElementLate( element, windowAssigner, allowedLateness, internalTimerService)) { windowProcessFunction.onLateRecord2(element.getValue(), collector, partitionedContext); } } @Override public void onEventTime(InternalTimer<K, W> timer) throws Exception { triggerContext.setKey(timer.getKey()); triggerContext.setWindow(timer.getNamespace()); MergingWindowSet<W> mergingWindows; if (windowAssigner instanceof MergingWindowAssigner) { mergingWindows = getMergingWindowSet(); W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); if (stateWindow == null) { // Timer firing for non-existent window, this can only happen if a // trigger did not clean up timers. We have already cleared the merging // window and therefore the Trigger state, however, so nothing to do. return; } else { leftWindowState.setCurrentNamespace(stateWindow); rightWindowState.setCurrentNamespace(stateWindow); } } else { leftWindowState.setCurrentNamespace(triggerContext.getWindow()); rightWindowState.setCurrentNamespace(triggerContext.getWindow()); mergingWindows = null; } TriggerResult triggerResult = triggerContext.onEventTime(timer.getTimestamp()); if (triggerResult.isFire()) { emitWindowContents(triggerContext.getWindow()); } if (triggerResult.isPurge()) { leftWindowState.clear(); rightWindowState.clear(); } if (windowAssigner.isEventTime() && WindowUtils.isCleanupTime( triggerContext.getWindow(), timer.getTimestamp(), windowAssigner, allowedLateness)) { clearAllState( triggerContext.getWindow(), leftWindowState, rightWindowState, mergingWindows); } if (mergingWindows != null) { // need to make sure to update the merging state in state mergingWindows.persist(); } } @Override public void onProcessingTime(InternalTimer<K, W> timer) throws Exception { triggerContext.setKey(timer.getKey()); triggerContext.setWindow(timer.getNamespace()); MergingWindowSet<W> mergingWindows; if (windowAssigner instanceof MergingWindowAssigner) { mergingWindows = getMergingWindowSet(); W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); if (stateWindow == null) { // Timer firing for non-existent window, this can only happen if a // trigger did not clean up timers. We have already cleared the merging // window and therefore the Trigger state, however, so nothing to do. return; } else { leftWindowState.setCurrentNamespace(stateWindow); rightWindowState.setCurrentNamespace(stateWindow); } } else { leftWindowState.setCurrentNamespace(triggerContext.getWindow()); rightWindowState.setCurrentNamespace(triggerContext.getWindow()); mergingWindows = null; } TriggerResult triggerResult = triggerContext.onProcessingTime(timer.getTimestamp()); if (triggerResult.isFire()) { emitWindowContents(triggerContext.getWindow()); } if (triggerResult.isPurge()) { leftWindowState.clear(); rightWindowState.clear(); } if (!windowAssigner.isEventTime() && WindowUtils.isCleanupTime( triggerContext.getWindow(), timer.getTimestamp(), windowAssigner, allowedLateness)) { clearAllState( triggerContext.getWindow(), leftWindowState, rightWindowState, mergingWindows); } if (mergingWindows != null) { // need to make sure to update the merging state in state mergingWindows.persist(); } } @Override protected ProcessingTimeManager getProcessingTimeManager() { // we don't support user utilize processing time in window operators return UnsupportedProcessingTimeManager.INSTANCE; } /** * Drops all state for the given window and calls {@link Trigger#clear(Window, * Trigger.TriggerContext)}. * * <p>The caller must ensure that the correct key is set in the state backend and the * triggerContext object. */ private void clearAllState( W window, AppendingState<IN1, StateIterator<IN1>, Iterable<IN1>> leftWindowState, AppendingState<IN2, StateIterator<IN2>, Iterable<IN2>> rightWindowState, MergingWindowSet<W> mergingWindows) throws Exception { leftWindowState.clear(); rightWindowState.clear(); triggerContext.clear(); windowFunctionContext.setWindow(window); windowProcessFunction.onClear(collector, partitionedContext, windowFunctionContext); if (mergingWindows != null) { mergingWindows.retireWindow(window); mergingWindows.persist(); } } /** * Emits the contents of the given window using the user-defined {@link * TwoInputNonBroadcastWindowStreamProcessFunction}. */ private void emitWindowContents(W window) throws Exception { // only time window touch the time concept. collector.setTimestamp(window.maxTimestamp()); windowFunctionContext.setWindow(window); windowProcessFunction.onTrigger(collector, partitionedContext, windowFunctionContext); } /** * Retrieves the {@link MergingWindowSet} for the currently active key. The caller must ensure * that the correct key is set in the state backend. * * <p>The caller must also ensure to properly persist changes to state using {@link * MergingWindowSet#persist()}. */ protected MergingWindowSet<W> getMergingWindowSet() throws Exception { MergingWindowAssigner<? super TaggedUnion<IN1, IN2>, W> mergingAssigner = (MergingWindowAssigner<? super TaggedUnion<IN1, IN2>, W>) windowAssigner; return new MergingWindowSet<>(mergingAssigner, mergingSetsState); } }
TwoInputNonBroadcastWindowProcessOperator
java
spring-projects__spring-framework
spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java
{ "start": 35158, "end": 36387 }
class ____ extends AttachmentUnmarshaller { private final MimeContainer mimeContainer; public Jaxb2AttachmentUnmarshaller(MimeContainer mimeContainer) { this.mimeContainer = mimeContainer; } @Override public byte[] getAttachmentAsByteArray(String cid) { try { DataHandler dataHandler = getAttachmentAsDataHandler(cid); return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); } catch (IOException ex) { throw new UnmarshallingFailureException("Could not read attachment", ex); } } @Override public DataHandler getAttachmentAsDataHandler(String contentId) { if (contentId.startsWith(CID)) { contentId = contentId.substring(CID.length()); contentId = URLDecoder.decode(contentId, StandardCharsets.UTF_8); contentId = '<' + contentId + '>'; } DataHandler dataHandler = this.mimeContainer.getAttachment(contentId); if (dataHandler == null) { throw new IllegalArgumentException("No attachment found for " + contentId); } return dataHandler; } @Override public boolean isXOPPackage() { return this.mimeContainer.isXopPackage(); } } /** * DataSource that wraps around a byte array. */ private static
Jaxb2AttachmentUnmarshaller
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SASKeyGeneratorInterface.java
{ "start": 1342, "end": 2491 }
interface ____ { /** * Interface method to retrieve SAS Key for a container within the storage * account. * * @param accountName * - Storage account name * @param container * - Container name within the storage account. * @return SAS URI for the container. * @throws SASKeyGenerationException Exception that gets thrown during * generation of SAS Key. */ URI getContainerSASUri(String accountName, String container) throws SASKeyGenerationException; /** * Interface method to retrieve SAS Key for a blob within the container of the * storage account. * * @param accountName * - Storage account name * @param container * - Container name within the storage account. * @param relativePath * - Relative path within the container * @return SAS URI for the relative path blob. * @throws SASKeyGenerationException Exception that gets thrown during * generation of SAS Key. */ URI getRelativeBlobSASUri(String accountName, String container, String relativePath) throws SASKeyGenerationException; }
SASKeyGeneratorInterface
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowablePublish.java
{ "start": 15005, "end": 15977 }
class ____<T> extends AtomicLong implements Subscription { private static final long serialVersionUID = 2845000326761540265L; final Subscriber<? super T> downstream; final PublishConnection<T> parent; long emitted; InnerSubscription(Subscriber<? super T> downstream, PublishConnection<T> parent) { this.downstream = downstream; this.parent = parent; } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.addCancel(this, n); parent.drain(); } } @Override public void cancel() { if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) { parent.remove(this); parent.drain(); } } public boolean isCancelled() { return get() == Long.MIN_VALUE; } } }
InnerSubscription
java
apache__flink
flink-python/src/test/java/org/apache/flink/python/util/PartitionCustomTestMapFunction.java
{ "start": 1162, "end": 2086 }
class ____ extends RichMapFunction<Row, Row> { private int currentTaskIndex; @Override public void open(OpenContext openContext) { this.currentTaskIndex = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); } @Override public Row map(Row value) throws Exception { int expectedPartitionIndex = (Integer) (value.getField(1)) % getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(); if (expectedPartitionIndex != currentTaskIndex) { throw new RuntimeException( String.format( "the data: Row<%s> was sent to the wrong partition[%d], " + "expected partition is [%d].", value.toString(), currentTaskIndex, expectedPartitionIndex)); } return value; } }
PartitionCustomTestMapFunction
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/testshell/ExternalMapReduce.java
{ "start": 4034, "end": 4201 }
class ____ libjar try { testConf.getClassByName("testjar.ClassWordCount"); } catch (ClassNotFoundException e) { System.out.println("Could not find
from
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/polymorphic/PolymorphicQueriesTest.java
{ "start": 6904, "end": 7411 }
class ____ implements I { @Id private Long id; private String displayName; @ManyToOne private EntityC entityC; @OneToMany private List<EntityC> cs; public EntityB() { } public EntityB(Long id, String displayName, EntityC entityC) { this.id = id; this.displayName = displayName; this.entityC = entityC; } public Long getId() { return id; } @Override public String getDisplayName() { return displayName; } } @Entity(name = "EntityC") public static
EntityB
java
eclipse-vertx__vert.x
vertx-core-logging/src/main/java/io/vertx/core/logging/SLF4JLogDelegateFactory.java
{ "start": 787, "end": 1586 }
class ____ implements LogDelegateFactory { static { // Check we have a valid ILoggerFactory // Replace the error stream since SLF4J will actually log the classloading error // when no implementation is available PrintStream err = System.err; try { System.setErr(new PrintStream(new ByteArrayOutputStream())); LoggerFactory.getILoggerFactory(); } finally { System.setErr(err); } } @Override public boolean isAvailable() { // SLF might be available on the classpath but without configuration ILoggerFactory fact = LoggerFactory.getILoggerFactory(); return !(fact instanceof NOPLoggerFactory); } @Override public LogDelegate createDelegate(final String clazz) { return new SLF4JLogDelegate(clazz); } }
SLF4JLogDelegateFactory
java
elastic__elasticsearch
modules/lang-painless/src/test/java/org/elasticsearch/painless/LookupTests.java
{ "start": 2326, "end": 2575 }
interface ____ extends X { // in whitelist String getString2(int x, int y); // in whitelist String getString1(int param0); // in whitelist String getString0(); // not in whitelist } public
U
java
elastic__elasticsearch
x-pack/plugin/stack/src/test/java/org/elasticsearch/xpack/stack/LegacyStackTemplateRegistryTests.java
{ "start": 1095, "end": 2540 }
class ____ extends ESTestCase { private LegacyStackTemplateRegistry registry; private ThreadPool threadPool; @Before public void createRegistryAndClient() { threadPool = new TestThreadPool(this.getClass().getName()); Client client = new NoOpClient(threadPool); ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool); registry = new LegacyStackTemplateRegistry(Settings.EMPTY, clusterService, threadPool, client, NamedXContentRegistry.EMPTY); } @After @Override public void tearDown() throws Exception { super.tearDown(); threadPool.shutdownNow(); } public void testThatTemplatesAreDeprecated() { for (ComposableIndexTemplate it : registry.getComposableTemplateConfigs().values()) { assertTrue(it.isDeprecated()); } for (LifecyclePolicy ilm : registry.getLifecyclePolicies()) { assertTrue(ilm.isDeprecated()); } for (ComponentTemplate ct : registry.getComponentTemplateConfigs().values()) { assertTrue(ct.deprecated()); } registry.getIngestPipelines() .stream() .map(ipc -> new PipelineConfiguration(ipc.getId(), ipc.loadConfig(), XContentType.JSON)) .map(PipelineConfiguration::getConfig) .forEach(p -> assertTrue((Boolean) p.get("deprecated"))); } }
LegacyStackTemplateRegistryTests
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/AnnotationIntrospector.java
{ "start": 14900, "end": 15217 }
class ____ introspect * * @return Subclass or instance of {@link EnumNamingStrategy}, if one * is specified for given class; null if not. */ public Object findEnumNamingStrategy(MapperConfig<?> config, AnnotatedClass ac) { return null; } /** * Method used to check whether specified
to
java
spring-projects__spring-boot
core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/lifecycle/DockerComposeServicesReadyEvent.java
{ "start": 1287, "end": 1873 }
class ____ extends ApplicationEvent { private final List<RunningService> runningServices; DockerComposeServicesReadyEvent(ApplicationContext source, List<RunningService> runningServices) { super(source); this.runningServices = runningServices; } @Override public ApplicationContext getSource() { return (ApplicationContext) super.getSource(); } /** * Return the relevant Docker Compose services that are running. * @return the running services */ public List<RunningService> getRunningServices() { return this.runningServices; } }
DockerComposeServicesReadyEvent
java
apache__flink
flink-filesystems/flink-s3-fs-base/src/main/java/org/apache/flink/fs/s3/common/writer/S3Recoverable.java
{ "start": 1243, "end": 3739 }
class ____ implements RecoverableWriter.ResumeRecoverable { private final String uploadId; private final String objectName; private final List<PartETag> parts; @Nullable private final String lastPartObject; private long numBytesInParts; private long lastPartObjectLength; S3Recoverable(String objectName, String uploadId, List<PartETag> parts, long numBytesInParts) { this(objectName, uploadId, parts, numBytesInParts, null, -1L); } S3Recoverable( String objectName, String uploadId, List<PartETag> parts, long numBytesInParts, @Nullable String lastPartObject, long lastPartObjectLength) { checkArgument(numBytesInParts >= 0L); checkArgument(lastPartObject == null || lastPartObjectLength > 0L); this.objectName = checkNotNull(objectName); this.uploadId = checkNotNull(uploadId); this.parts = checkNotNull(parts); this.numBytesInParts = numBytesInParts; this.lastPartObject = lastPartObject; this.lastPartObjectLength = lastPartObjectLength; } // ------------------------------------------------------------------------ public String uploadId() { return uploadId; } public String getObjectName() { return objectName; } public List<PartETag> parts() { return parts; } public long numBytesInParts() { return numBytesInParts; } @Nullable public String incompleteObjectName() { return lastPartObject; } public long incompleteObjectLength() { return lastPartObjectLength; } // ------------------------------------------------------------------------ @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("S3Recoverable: "); buf.append("key=").append(objectName); buf.append(", uploadId=").append(uploadId); buf.append(", bytesInParts=").append(numBytesInParts); buf.append(", parts=["); int num = 0; for (PartETag part : parts) { if (0 != num++) { buf.append(", "); } buf.append(part.getPartNumber()).append('=').append(part.getETag()); } buf.append("], trailingPart=").append(lastPartObject); buf.append("trailingPartLen=").append(lastPartObjectLength); return buf.toString(); } }
S3Recoverable
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/SendInputStreamTest.java
{ "start": 1130, "end": 1266 }
interface ____ { @POST @Path("count") long count(InputStream is); } @Path("test") public static
Client
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/SchemaBuilder.java
{ "start": 70817, "end": 71297 }
class ____<R> extends FieldDefault<R, IntDefault<R>> { private IntDefault(FieldBuilder<R> field) { super(field); } /** Completes this field with the default value provided **/ public final FieldAssembler<R> intDefault(int defaultVal) { return super.usingDefault(defaultVal); } @Override final IntDefault<R> self() { return this; } } /** Choose whether to use a default value for the field or not. **/ public static
IntDefault
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/conversion/DateDateConverter.java
{ "start": 1102, "end": 1497 }
class ____ implements DataStructureConverter<Integer, java.sql.Date> { private static final long serialVersionUID = 1L; @Override public Integer toInternal(java.sql.Date external) { return DateTimeUtils.toInternal(external); } @Override public java.sql.Date toExternal(Integer internal) { return DateTimeUtils.toSQLDate(internal); } }
DateDateConverter
java
hibernate__hibernate-orm
tooling/hibernate-gradle-plugin/src/test/resources/projects/multi-part-source-set-name/src/mySpecialSourceSet/java/TheEmbeddable.java
{ "start": 59, "end": 395 }
class ____ { private String valueOne; private String valueTwo; public String getValueOne() { return valueOne; } public void setValueOne(String valueOne) { this.valueOne = valueOne; } public String getValueTwo() { return valueTwo; } public void setValueTwo(String valueTwo) { this.valueTwo = valueTwo; } }
TheEmbeddable
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/analytics/action/TransportGetAnalyticsCollectionAction.java
{ "start": 1479, "end": 3110 }
class ____ extends TransportMasterNodeReadAction< GetAnalyticsCollectionAction.Request, GetAnalyticsCollectionAction.Response> { private final AnalyticsCollectionService analyticsCollectionService; @Inject public TransportGetAnalyticsCollectionAction( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters, AnalyticsCollectionService analyticsCollectionService ) { super( GetAnalyticsCollectionAction.NAME, transportService, clusterService, threadPool, actionFilters, GetAnalyticsCollectionAction.Request::new, GetAnalyticsCollectionAction.Response::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.analyticsCollectionService = analyticsCollectionService; } @Override protected void masterOperation( Task task, GetAnalyticsCollectionAction.Request request, ClusterState state, ActionListener<GetAnalyticsCollectionAction.Response> listener ) { DeprecationLogger.getLogger(TransportDeleteAnalyticsCollectionAction.class) .warn(DeprecationCategory.API, BEHAVIORAL_ANALYTICS_API_ENDPOINT, BEHAVIORAL_ANALYTICS_DEPRECATION_MESSAGE); analyticsCollectionService.getAnalyticsCollection(state, request, listener); } @Override protected ClusterBlockException checkBlock(GetAnalyticsCollectionAction.Request request, ClusterState state) { return null; } }
TransportGetAnalyticsCollectionAction
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/UnresolvedForwardReference.java
{ "start": 363, "end": 2816 }
class ____ extends DatabindException { private static final long serialVersionUID = 1L; private ReadableObjectId _roid; private List<UnresolvedId> _unresolvedIds; public UnresolvedForwardReference(JsonParser p, String msg, TokenStreamLocation loc, ReadableObjectId roid) { super(p, msg, loc); _roid = roid; } public UnresolvedForwardReference(JsonParser p, String msg) { super(p, msg); _unresolvedIds = new ArrayList<UnresolvedId>(); } /* /********************************************************** /* Accessor methods /********************************************************** */ public ReadableObjectId getRoid() { return _roid; } public Object getUnresolvedId() { return _roid.getKey().key; } public void addUnresolvedId(Object id, Class<?> type, TokenStreamLocation where) { _unresolvedIds.add(new UnresolvedId(id, type, where)); } public List<UnresolvedId> getUnresolvedIds(){ return _unresolvedIds; } @Override public String getMessage() { String msg = super.getMessage(); if (_unresolvedIds == null) { return msg; } StringBuilder sb = new StringBuilder(msg); Iterator<UnresolvedId> iterator = _unresolvedIds.iterator(); while (iterator.hasNext()) { UnresolvedId unresolvedId = iterator.next(); sb.append(unresolvedId.toString()); if (iterator.hasNext()) { sb.append(", "); } } sb.append('.'); return sb.toString(); } /** * This method is overridden to prevent filling of the stack trace when * constructors are called (unfortunately alternative constructors can * not be used due to historical reasons). * To explicitly fill in stack traces method {@link #withStackTrace()} * needs to be called after construction. * * @since 2.14 */ @Override public synchronized UnresolvedForwardReference fillInStackTrace() { return this; } /** * "Mutant" factory method for filling in stack trace; needed since the default * constructors will not fill in stack trace. * * @since 2.14 */ public UnresolvedForwardReference withStackTrace() { super.fillInStackTrace(); return this; } }
UnresolvedForwardReference
java
apache__camel
components/camel-graphql/src/test/java/org/apache/camel/component/graphql/server/Author.java
{ "start": 862, "end": 1150 }
class ____ { private final String id; private final String name; public Author(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } }
Author
java
spring-projects__spring-security
access/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java
{ "start": 1688, "end": 4265 }
class ____ { private Authentication user = new TestingAuthenticationToken("user", "pass", "X"); @Test public void supportsWebConfigAttributeAndFilterInvocation() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports( new WebExpressionConfigAttribute(mock(Expression.class), mock(EvaluationContextPostProcessor.class)))) .isTrue(); assertThat(voter.supports(FilterInvocation.class)).isTrue(); assertThat(voter.supports(MethodInvocation.class)).isFalse(); } @Test public void abstainsIfNoAttributeFound() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat( voter.vote(this.user, new FilterInvocation("/path", "GET"), SecurityConfig.createList("A", "B", "C"))) .isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN); } @Test public void grantsAccessIfExpressionIsTrueDeniesIfFalse() { WebExpressionVoter voter = new WebExpressionVoter(); Expression ex = mock(Expression.class); EvaluationContextPostProcessor postProcessor = mock(EvaluationContextPostProcessor.class); given(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class))) .willAnswer((invocation) -> invocation.getArgument(0)); WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex, postProcessor); EvaluationContext ctx = mock(EvaluationContext.class); SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class); FilterInvocation fi = new FilterInvocation("/path", "GET"); voter.setExpressionHandler(eh); given(eh.createEvaluationContext(this.user, fi)).willReturn(ctx); given(ex.getValue(ctx, Boolean.class)).willReturn(Boolean.TRUE, Boolean.FALSE); ArrayList attributes = new ArrayList(); attributes.addAll(SecurityConfig.createList("A", "B", "C")); attributes.add(weca); assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED); // Second time false assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED); } // SEC-2507 @Test public void supportFilterInvocationSubClass() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports(FilterInvocationChild.class)).isTrue(); } @Test public void supportFilterInvocation() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports(FilterInvocation.class)).isTrue(); } @Test public void supportsObjectIsFalse() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports(Object.class)).isFalse(); } private static
WebExpressionVoterTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ConstructorInjectionTestClassScopedExtensionContextNestedTests.java
{ "start": 2811, "end": 3108 }
class ____ { final String bar; @Autowired AutowiredConstructorTests(String bar) { this.bar = bar; } @Test void nestedTest() { assertThat(foo).isEqualTo("foo"); assertThat(bar).isEqualTo("bar"); } } @Nested @SpringJUnitConfig(NestedConfig.class)
AutowiredConstructorTests
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/HandlerMethodArgumentResolverComposite.java
{ "start": 1345, "end": 4556 }
class ____ implements HandlerMethodArgumentResolver { private final List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); private final Map<MethodParameter, HandlerMethodArgumentResolver> argumentResolverCache = new ConcurrentHashMap<>(256); /** * Add the given {@link HandlerMethodArgumentResolver}. */ public HandlerMethodArgumentResolverComposite addResolver(HandlerMethodArgumentResolver resolver) { this.argumentResolvers.add(resolver); return this; } /** * Add the given {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers}. */ public HandlerMethodArgumentResolverComposite addResolvers(@Nullable HandlerMethodArgumentResolver... resolvers) { if (resolvers != null) { Collections.addAll(this.argumentResolvers, resolvers); } return this; } /** * Add the given {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers}. */ public HandlerMethodArgumentResolverComposite addResolvers( @Nullable List<? extends HandlerMethodArgumentResolver> resolvers) { if (resolvers != null) { this.argumentResolvers.addAll(resolvers); } return this; } /** * Return a read-only list with the contained resolvers, or an empty list. */ public List<HandlerMethodArgumentResolver> getResolvers() { return Collections.unmodifiableList(this.argumentResolvers); } /** * Clear the list of configured resolvers and the resolver cache. */ public void clear() { this.argumentResolvers.clear(); this.argumentResolverCache.clear(); } /** * Whether the given {@linkplain MethodParameter method parameter} is * supported by any registered {@link HandlerMethodArgumentResolver}. */ @Override public boolean supportsParameter(MethodParameter parameter) { return getArgumentResolver(parameter) != null; } /** * Iterate over registered * {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers} and * invoke the one that supports it. * @throws IllegalStateException if no suitable * {@link HandlerMethodArgumentResolver} is found. */ @Override public Mono<Object> resolveArgument( MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) { HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); if (resolver == null) { throw new IllegalArgumentException("Unsupported parameter type [" + parameter.getParameterType().getName() + "]. supportsParameter should be called first."); } return resolver.resolveArgument(parameter, bindingContext, exchange); } /** * Find a registered {@link HandlerMethodArgumentResolver} that supports * the given method parameter. */ private @Nullable HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) { HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter); if (result == null) { for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) { if (methodArgumentResolver.supportsParameter(parameter)) { result = methodArgumentResolver; this.argumentResolverCache.put(parameter, result); break; } } } return result; } }
HandlerMethodArgumentResolverComposite
java
apache__camel
components/camel-vertx/camel-vertx-http/src/test/java/org/apache/camel/component/vertx/http/VertxHttpFileUploadMultipartTest.java
{ "start": 1429, "end": 2938 }
class ____ extends VertxHttpTestSupport { @Test public void testVertxFileUpload() { File f = new File("src/test/resources/log4j2.properties"); Exchange out = template.request(getProducerUri() + "/upload", exchange -> { Buffer buf = Buffer.buffer(Files.readAllBytes(f.toPath())); var b = MultipartForm.create().textFileUpload("mydata", "log4j2.properties", buf, "text/plain"); exchange.getMessage().setBody(b); }); assertNotNull(out); assertFalse(out.isFailed(), "Should not fail"); assertEquals("log4j2.properties", out.getMessage().getBody(String.class)); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(getTestServerUri() + "/upload") .process(new Processor() { @Override public void process(Exchange exchange) { // undertow store the multipart-form as map in the camel message DataHandler dh = (DataHandler) exchange.getMessage().getBody(Map.class).get("mydata"); String out = dh.getDataSource().getName(); exchange.getMessage().setBody(out); } }); } }; } }
VertxHttpFileUploadMultipartTest
java
apache__camel
test-infra/camel-test-infra-kafka/src/main/java/org/apache/camel/test/infra/kafka/services/RedpandaTransactionsEnabledContainer.java
{ "start": 1221, "end": 2341 }
class ____ extends RedpandaContainer { public static final String REDPANDA_CONTAINER = LocalPropertyResolver.getProperty( RedpandaTransactionsEnabledContainer.class, KafkaProperties.REDPANDA_CONTAINER); public static final int REDPANDA_PORT = 9092; public RedpandaTransactionsEnabledContainer(String image) { super(DockerImageName.parse(System.getProperty(KafkaProperties.REDPANDA_CONTAINER, REDPANDA_CONTAINER)) .asCompatibleSubstituteFor("redpandadata/redpanda")); } protected void containerIsStarting(InspectContainerResponse containerInfo) { super.containerIsStarting(containerInfo); String command = "#!/bin/bash\n"; command += "/usr/bin/rpk redpanda start --mode dev-container "; command += "--kafka-addr PLAINTEXT://0.0.0.0:29092,OUTSIDE://0.0.0.0:9092 "; command += "--advertise-kafka-addr PLAINTEXT://kafka:29092,OUTSIDE://" + getHost() + ":" + getMappedPort(9092); this.copyFileToContainer(Transferable.of(command, 511), "/testcontainers_start.sh"); } }
RedpandaTransactionsEnabledContainer
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/ResourceMetricsChecker.java
{ "start": 6610, "end": 11588 }
enum ____ { ALLOCATED_MB("AllocatedMB", GAUGE_LONG), ALLOCATED_V_CORES("AllocatedVCores", GAUGE_INT), ALLOCATED_CONTAINERS("AllocatedContainers", GAUGE_INT), AGGREGATE_CONTAINERS_ALLOCATED("AggregateContainersAllocated", COUNTER_LONG), AGGREGATE_CONTAINERS_RELEASED("AggregateContainersReleased", COUNTER_LONG), AVAILABLE_MB("AvailableMB", GAUGE_LONG), AVAILABLE_V_CORES("AvailableVCores", GAUGE_INT), PENDING_MB("PendingMB", GAUGE_LONG), PENDING_V_CORES("PendingVCores", GAUGE_INT), PENDING_CONTAINERS("PendingContainers", GAUGE_INT), RESERVED_MB("ReservedMB", GAUGE_LONG), RESERVED_V_CORES("ReservedVCores", GAUGE_INT), RESERVED_CONTAINERS("ReservedContainers", GAUGE_INT), AGGREGATE_VCORE_SECONDS_PREEMPTED( "AggregateVcoreSecondsPreempted", COUNTER_LONG), AGGREGATE_MEMORY_MB_SECONDS_PREEMPTED( "AggregateMemoryMBSecondsPreempted", COUNTER_LONG), ALLOCATED_CUSTOM_RES1("AllocatedResource.custom_res_1", GAUGE_LONG), ALLOCATED_CUSTOM_RES2("AllocatedResource.custom_res_2", GAUGE_LONG), AVAILABLE_CUSTOM_RES1("AvailableResource.custom_res_1", GAUGE_LONG), AVAILABLE_CUSTOM_RES2("AvailableResource.custom_res_2", GAUGE_LONG), PENDING_CUSTOM_RES1("PendingResource.custom_res_1",GAUGE_LONG), PENDING_CUSTOM_RES2("PendingResource.custom_res_2",GAUGE_LONG), RESERVED_CUSTOM_RES1("ReservedResource.custom_res_1",GAUGE_LONG), RESERVED_CUSTOM_RES2("ReservedResource.custom_res_2", GAUGE_LONG), AGGREGATE_PREEMPTED_SECONDS_CUSTOM_RES1("AggregatePreemptedSeconds.custom_res_1", GAUGE_LONG), AGGREGATE_PREEMPTED_SECONDS_CUSTOM_RES2("AggregatePreemptedSeconds.custom_res_2", GAUGE_LONG); private String value; private ResourceMetricType type; ResourceMetricsKey(String value, ResourceMetricType type) { this.value = value; this.type = type; } public String getValue() { return value; } public ResourceMetricType getType() { return type; } } private final Map<ResourceMetricsKey, Long> gaugesLong; private final Map<ResourceMetricsKey, Integer> gaugesInt; private final Map<ResourceMetricsKey, Long> counters; private ResourceMetricsChecker() { this.gaugesLong = Maps.newHashMap(); this.gaugesInt = Maps.newHashMap(); this.counters = Maps.newHashMap(); } private ResourceMetricsChecker(ResourceMetricsChecker checker) { this.gaugesLong = Maps.newHashMap(checker.gaugesLong); this.gaugesInt = Maps.newHashMap(checker.gaugesInt); this.counters = Maps.newHashMap(checker.counters); } public static ResourceMetricsChecker createFromChecker( ResourceMetricsChecker checker) { return new ResourceMetricsChecker(checker); } public static ResourceMetricsChecker create() { return new ResourceMetricsChecker(INITIAL_CHECKER); } public static ResourceMetricsChecker createMandatoryResourceChecker() { return new ResourceMetricsChecker(INITIAL_MANDATORY_RES_CHECKER); } ResourceMetricsChecker gaugeLong(ResourceMetricsKey key, long value) { ensureTypeIsCorrect(key, GAUGE_LONG); gaugesLong.put(key, value); return this; } ResourceMetricsChecker gaugeInt(ResourceMetricsKey key, int value) { ensureTypeIsCorrect(key, GAUGE_INT); gaugesInt.put(key, value); return this; } ResourceMetricsChecker counter(ResourceMetricsKey key, long value) { ensureTypeIsCorrect(key, COUNTER_LONG); counters.put(key, value); return this; } private void ensureTypeIsCorrect(ResourceMetricsKey key, ResourceMetricType actualType) { if (key.type != actualType) { throw new IllegalStateException("Metrics type should be " + key.type + " instead of " + actualType + " for metrics: " + key.value); } } ResourceMetricsChecker checkAgainst(MetricsSource source) { if (source == null) { throw new IllegalStateException("MetricsSource should not be null!"); } MetricsRecordBuilder recordBuilder = getMetrics(source); logAssertingMessage(source); for (Map.Entry<ResourceMetricsKey, Long> gauge : gaugesLong.entrySet()) { assertGauge(gauge.getKey().value, gauge.getValue(), recordBuilder); } for (Map.Entry<ResourceMetricsKey, Integer> gauge : gaugesInt.entrySet()) { assertGauge(gauge.getKey().value, gauge.getValue(), recordBuilder); } for (Map.Entry<ResourceMetricsKey, Long> counter : counters.entrySet()) { assertCounter(counter.getKey().value, counter.getValue(), recordBuilder); } return this; } private void logAssertingMessage(MetricsSource source) { String queueName = ((QueueMetrics) source).queueName; Map<String, QueueMetrics> users = ((QueueMetrics) source).users; if (LOG.isDebugEnabled()) { LOG.debug("Asserting Resource metrics.. QueueName: " + queueName + ", users: " + (users != null && !users.isEmpty() ? users : "")); } } }
ResourceMetricsKey
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/shortcircuit/DfsClientShm.java
{ "start": 2008, "end": 4024 }
class ____ extends ShortCircuitShm implements DomainSocketWatcher.Handler { /** * The EndpointShmManager associated with this shared memory segment. */ private final EndpointShmManager manager; /** * The UNIX domain socket associated with this DfsClientShm. * We rely on the DomainSocketWatcher to close the socket associated with * this DomainPeer when necessary. */ private final DomainPeer peer; /** * True if this shared memory segment has lost its connection to the * DataNode. * * {@link DfsClientShm#handle} sets this to true. */ private boolean disconnected = false; DfsClientShm(ShmId shmId, FileInputStream stream, EndpointShmManager manager, DomainPeer peer) throws IOException { super(shmId, stream); this.manager = manager; this.peer = peer; } public EndpointShmManager getEndpointShmManager() { return manager; } public DomainPeer getPeer() { return peer; } /** * Determine if the shared memory segment is disconnected from the DataNode. * * This must be called with the DfsClientShmManager lock held. * * @return True if the shared memory segment is stale. */ public synchronized boolean isDisconnected() { return disconnected; } /** * Handle the closure of the UNIX domain socket associated with this shared * memory segment by marking this segment as stale. * * If there are no slots associated with this shared memory segment, it will * be freed immediately in this function. */ @Override public boolean handle(DomainSocket sock) { manager.unregisterShm(getShmId()); synchronized (this) { Preconditions.checkState(!disconnected); disconnected = true; boolean hadSlots = false; for (Iterator<Slot> iter = slotIterator(); iter.hasNext(); ) { Slot slot = iter.next(); slot.makeInvalid(); hadSlots = true; } if (!hadSlots) { free(); } } return true; } }
DfsClientShm
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/role/PutRoleRequestBuilder.java
{ "start": 771, "end": 3439 }
class ____ extends ActionRequestBuilder<PutRoleRequest, PutRoleResponse> { private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().allowDescription(true).build(); public PutRoleRequestBuilder(ElasticsearchClient client) { super(client, PutRoleAction.INSTANCE, new PutRoleRequest()); } /** * Populate the put role request from the source and the role's name */ public PutRoleRequestBuilder source(String name, BytesReference source, XContentType xContentType) throws IOException { // we want to reject the request if field permissions are given in 2.x syntax, hence we do not allow2xFormat RoleDescriptor descriptor = ROLE_DESCRIPTOR_PARSER.parse(name, source, xContentType); assert name.equals(descriptor.getName()); request.name(name); request.cluster(descriptor.getClusterPrivileges()); request.conditionalCluster(descriptor.getConditionalClusterPrivileges()); request.addIndex(descriptor.getIndicesPrivileges()); request.addRemoteIndex(descriptor.getRemoteIndicesPrivileges()); request.putRemoteCluster(descriptor.getRemoteClusterPermissions()); request.addApplicationPrivileges(descriptor.getApplicationPrivileges()); request.runAs(descriptor.getRunAs()); request.metadata(descriptor.getMetadata()); request.description(descriptor.getDescription()); return this; } public PutRoleRequestBuilder name(String name) { request.name(name); return this; } public PutRoleRequestBuilder description(String description) { request.description(description); return this; } public PutRoleRequestBuilder cluster(String... cluster) { request.cluster(cluster); return this; } public PutRoleRequestBuilder runAs(String... runAsUsers) { request.runAs(runAsUsers); return this; } public PutRoleRequestBuilder addIndices( String[] indices, String[] privileges, String[] grantedFields, String[] deniedFields, @Nullable BytesReference query, boolean allowRestrictedIndices ) { request.addIndex(indices, privileges, grantedFields, deniedFields, query, allowRestrictedIndices); return this; } public PutRoleRequestBuilder metadata(Map<String, Object> metadata) { request.metadata(metadata); return this; } public PutRoleRequestBuilder setRefreshPolicy(@Nullable String refreshPolicy) { request.setRefreshPolicy(refreshPolicy); return this; } }
PutRoleRequestBuilder
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/MultiToSingleValueMapAdapter.java
{ "start": 1204, "end": 1391 }
class ____ in the opposite * direction. * * @author Arjen Poutsma * @since 6.2 * @param <K> the key type * @param <V> the value element type */ @SuppressWarnings("serial") final
adapts
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/notifications/InferenceAuditor.java
{ "start": 565, "end": 1110 }
class ____ extends AbstractMlAuditor<InferenceAuditMessage> { private final boolean includeNodeInfo; public InferenceAuditor( Client client, ClusterService clusterService, IndexNameExpressionResolver indexNameExpressionResolver, boolean includeNodeInfo ) { super(client, InferenceAuditMessage::new, clusterService, indexNameExpressionResolver); this.includeNodeInfo = includeNodeInfo; } public boolean includeNodeInfo() { return includeNodeInfo; } }
InferenceAuditor
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java
{ "start": 1866, "end": 7116 }
class ____ { private NativeWebRequest request; private final HandlerMethodArgumentResolverComposite composite = new HandlerMethodArgumentResolverComposite(); @BeforeEach void setUp() { this.request = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse()); } @Test void resolveArg() throws Exception { this.composite.addResolver(new StubArgumentResolver(99)); this.composite.addResolver(new StubArgumentResolver("value")); Object value = getInvocable(Integer.class, String.class).invokeForRequest(request, null); assertThat(getStubResolver(0).getResolvedParameters()).hasSize(1); assertThat(getStubResolver(1).getResolvedParameters()).hasSize(1); assertThat(value).isEqualTo("99-value"); assertThat(getStubResolver(0).getResolvedParameters().get(0).getParameterName()).isEqualTo("intArg"); assertThat(getStubResolver(1).getResolvedParameters().get(0).getParameterName()).isEqualTo("stringArg"); } @Test void resolveNoArgValue() throws Exception { this.composite.addResolver(new StubArgumentResolver(Integer.class)); this.composite.addResolver(new StubArgumentResolver(String.class)); Object returnValue = getInvocable(Integer.class, String.class).invokeForRequest(request, null); assertThat(getStubResolver(0).getResolvedParameters()).hasSize(1); assertThat(getStubResolver(1).getResolvedParameters()).hasSize(1); assertThat(returnValue).isEqualTo("null-null"); } @Test void cannotResolveArg() { assertThatIllegalStateException().isThrownBy(() -> getInvocable(Integer.class, String.class).invokeForRequest(request, null)) .withMessageContaining("Could not resolve parameter [0]"); } @Test void resolveProvidedArg() throws Exception { Object value = getInvocable(Integer.class, String.class).invokeForRequest(request, null, 99, "value"); assertThat(value).isNotNull(); assertThat(value.getClass()).isEqualTo(String.class); assertThat(value).isEqualTo("99-value"); } @Test void resolveProvidedArgFirst() throws Exception { this.composite.addResolver(new StubArgumentResolver(1)); this.composite.addResolver(new StubArgumentResolver("value1")); Object value = getInvocable(Integer.class, String.class).invokeForRequest(request, null, 2, "value2"); assertThat(value).isEqualTo("2-value2"); } @Test void resolveHandlerMethodArgToNull() throws Exception { Object value = getInvocable(HandlerMethod.class).invokeForRequest(request, null); assertThat(value).isNotNull(); assertThat(value).isEqualTo("success"); } @Test void exceptionInResolvingArg() { this.composite.addResolver(new ExceptionRaisingArgumentResolver()); assertThatIllegalArgumentException().isThrownBy(() -> getInvocable(Integer.class, String.class).invokeForRequest(request, null)); } @Test void illegalArgumentException() { this.composite.addResolver(new StubArgumentResolver(Integer.class, "__not_an_int__")); this.composite.addResolver(new StubArgumentResolver("value")); assertThatIllegalStateException().isThrownBy(() -> getInvocable(Integer.class, String.class).invokeForRequest(request, null)) .withCauseInstanceOf(IllegalArgumentException.class) .withMessageContaining("Controller [") .withMessageContaining("Method [") .withMessageContaining("with argument values:") .withMessageContaining("[0] [type=java.lang.String] [value=__not_an_int__]") .withMessageContaining("[1] [type=java.lang.String] [value=value"); } @Test void invocationTargetException() { RuntimeException runtimeException = new RuntimeException("error"); assertThatRuntimeException() .isThrownBy(() -> getInvocable(Throwable.class).invokeForRequest(this.request, null, runtimeException)) .isSameAs(runtimeException); Error error = new Error("error"); assertThatExceptionOfType(Error.class) .isThrownBy(() -> getInvocable(Throwable.class).invokeForRequest(this.request, null, error)) .isSameAs(error); Exception exception = new Exception("error"); assertThatException() .isThrownBy(() -> getInvocable(Throwable.class).invokeForRequest(this.request, null, exception)) .isSameAs(exception); Throwable throwable = new Throwable("error"); assertThatIllegalStateException() .isThrownBy(() -> getInvocable(Throwable.class).invokeForRequest(this.request, null, throwable)) .withCause(throwable) .withMessageContaining("Invocation failure"); } @Test // SPR-13917 public void invocationErrorMessage() { this.composite.addResolver(new StubArgumentResolver(double.class)); assertThatIllegalStateException() .isThrownBy(() -> getInvocable(double.class).invokeForRequest(this.request, null)) .withMessageContaining("Illegal argument"); } private InvocableHandlerMethod getInvocable(Class<?>... argTypes) { Method method = ResolvableMethod.on(Handler.class).argTypes(argTypes).resolveMethod(); InvocableHandlerMethod handlerMethod = new InvocableHandlerMethod(new Handler(), method); handlerMethod.setHandlerMethodArgumentResolvers(this.composite); return handlerMethod; } private StubArgumentResolver getStubResolver(int index) { return (StubArgumentResolver) this.composite.getResolvers().get(index); } @SuppressWarnings("unused") private static
InvocableHandlerMethodTests
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java
{ "start": 17328, "end": 17845 }
class ____ { static AuthenticationManager AUTHENTICATION_MANAGER; @Bean AuthenticationManager authenticationManager() { return AUTHENTICATION_MANAGER; } @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((requests) -> requests .anyRequest().authenticated()) .formLogin(withDefaults()); return http.build(); // @formatter:on } } @Configuration @EnableWebSecurity static
AuthenticationManagerRefConfig
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java
{ "start": 1515, "end": 3126 }
class ____ { @Test void testVanillaExchange(@TempDir Path temp) { File inputDir = new File(temp.toFile(), "input"); File outputDir = new File(temp.toFile(), "output"); try (ConfigurableApplicationContext app = SpringApplication.run(SampleParentContextApplication.class, "--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir)) { try (ConfigurableApplicationContext producer = SpringApplication.run(ProducerApplication.class, "--service.input-dir=" + inputDir, "--service.output-dir=" + outputDir, "World")) { awaitOutputContaining(outputDir, "Hello World"); } } } private void awaitOutputContaining(File outputDir, String requiredContents) { Awaitility.waitAtMost(Duration.ofSeconds(30)) .until(() -> outputIn(outputDir), containsString(requiredContents)); } private String outputIn(File outputDir) throws IOException { Resource[] resources = findResources(outputDir); if (resources.length == 0) { return null; } return readResources(resources); } private Resource[] findResources(File outputDir) throws IOException { return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); } private String readResources(Resource[] resources) throws IOException { StringBuilder builder = new StringBuilder(); for (Resource resource : resources) { try (InputStream input = resource.getInputStream()) { builder.append(new String(StreamUtils.copyToByteArray(input))); } } return builder.toString(); } }
SampleIntegrationParentApplicationTests
java
quarkusio__quarkus
integration-tests/hibernate-search-orm-elasticsearch/src/main/java/io/quarkus/it/hibernate/search/orm/elasticsearch/analysis/BackendAnalysisConfigurer.java
{ "start": 413, "end": 1172 }
class ____ implements ElasticsearchAnalysisConfigurer { @Inject MyCdiContext cdiContext; @Override public void configure(ElasticsearchAnalysisConfigurationContext context) { MyCdiContext.checkAvailable(cdiContext); context.analyzer("standard").type("standard"); context.normalizer("lowercase").custom().tokenFilters("lowercase"); context.analyzer("backend-level-analyzer").custom() .tokenizer("keyword") .tokenFilters("backend-level-tokenfilter"); context.tokenFilter("backend-level-tokenfilter").type("pattern_replace") .param("pattern", ".+") .param("replacement", "token_inserted_by_backend_analysis"); } }
BackendAnalysisConfigurer
java
dropwizard__dropwizard
docs/source/examples/getting-started/src/main/java/com/example/helloworld/HelloWorldApplication.java
{ "start": 286, "end": 1470 }
class ____ extends Application<HelloWorldConfiguration> { public static void main(String[] args) throws Exception { new HelloWorldApplication().run(args); } @Override public String getName() { return "hello-world"; } @Override public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) { // nothing to do yet } @Override public void run(HelloWorldConfiguration configuration, Environment environment) { // getting-started: HelloWorldApplication#run->HelloWorldResource HelloWorldResource resource = new HelloWorldResource( configuration.getTemplate(), configuration.getDefaultName() ); environment.jersey().register(resource); // getting-started: HelloWorldApplication#run->HelloWorldResource // getting-started: HelloWorldApplication#run->TemplateHealthCheck TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate()); environment.healthChecks().register("template", healthCheck); // getting-started: HelloWorldApplication#run->TemplateHealthCheck } }
HelloWorldApplication
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/api/reader/AbstractReaderTest.java
{ "start": 6373, "end": 6516 }
class ____ extends AbstractReader { protected MockReader(InputGate inputGate) { super(inputGate); } } }
MockReader
java
elastic__elasticsearch
x-pack/plugin/security/qa/security-basic/src/javaRestTest/java/org/elasticsearch/xpack/security/SecuritySlowLogIT.java
{ "start": 1473, "end": 16057 }
class ____ extends ESRestTestCase { private record TestIndexData( String name, boolean searchSlowLogEnabled, boolean indexSlowLogEnabled, boolean searchSlowLogUserEnabled, boolean indexSlowLogUserEnabled ) {} private static int currentSearchLogIndex = 0; private static int currentIndexLogIndex = 0; @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local() .nodes(1) .distribution(DistributionType.DEFAULT) .setting("xpack.security.enabled", "true") .user("admin_user", "admin-password") .user("api_user", "api-password", "superuser", false) .build(); @Override protected Settings restAdminSettings() { String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray())); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } @Override protected Settings restClientSettings() { String token = basicAuthHeaderValue("api_user", new SecureString("api-password".toCharArray())); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } public void testSlowLogWithApiUser() throws Exception { List<TestIndexData> testIndices = randomTestIndexData(); for (TestIndexData testData : testIndices) { searchSomeData(testData.name); indexSomeData(testData.name); } Map<String, Object> expectedUser = Map.of("user.name", "api_user", "user.realm", "default_file", "auth.type", "REALM"); verifySearchSlowLogMatchesTestData(testIndices, expectedUser); verifyIndexSlowLogMatchesTestData(testIndices, expectedUser); } public void testSlowLogWithUserWithFullName() throws Exception { List<TestIndexData> testIndices = randomTestIndexData(); createUserWithFullName("full_name", "full-name-password", "Full Name", new String[] { "superuser" }); for (TestIndexData testData : testIndices) { final RequestOptions requestOptions = RequestOptions.DEFAULT.toBuilder() .addHeader("Authorization", basicAuthHeaderValue("full_name", new SecureString("full-name-password".toCharArray()))) .build(); searchSomeData(testData.name, requestOptions); indexSomeData(testData.name, requestOptions); } Map<String, Object> expectedUser = Map.of( "user.name", "full_name", "user.full_name", "Full Name", "user.realm", "default_native", "auth.type", "REALM" ); verifySearchSlowLogMatchesTestData(testIndices, expectedUser); verifyIndexSlowLogMatchesTestData(testIndices, expectedUser); } public void testSlowLogWithUserWithFullNameWithRunAs() throws Exception { List<TestIndexData> testIndices = randomTestIndexData(); createUserWithFullName("full_name", "full-name-password", "Full Name", new String[] { "superuser" }); for (TestIndexData testData : testIndices) { final RequestOptions requestOptions = RequestOptions.DEFAULT.toBuilder() .addHeader("es-security-runas-user", "full_name") .addHeader("Authorization", basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray()))) .build(); searchSomeData(testData.name, requestOptions); indexSomeData(testData.name, requestOptions); } Map<String, Object> expectedUser = Map.of( "user.name", "admin_user", "user.effective.full_name", "Full Name", "user.realm", "default_file", "auth.type", "REALM" ); verifySearchSlowLogMatchesTestData(testIndices, expectedUser); verifyIndexSlowLogMatchesTestData(testIndices, expectedUser); } public void testSlowLogWithApiKey() throws Exception { List<TestIndexData> testIndices = randomTestIndexData(); String apiKeyName = randomAlphaOfLengthBetween(10, 15); Map<String, Object> createApiKeyResponse = createApiKey( apiKeyName, basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray())) ); String apiKeyHeader = Base64.getEncoder() .encodeToString( (createApiKeyResponse.get("id") + ":" + createApiKeyResponse.get("api_key").toString()).getBytes(StandardCharsets.UTF_8) ); for (TestIndexData testData : testIndices) { final RequestOptions requestOptions = RequestOptions.DEFAULT.toBuilder() .addHeader("Authorization", "ApiKey " + apiKeyHeader) .build(); searchSomeData(testData.name, requestOptions); indexSomeData(testData.name, requestOptions); } Map<String, Object> expectedUser = Map.of( "user.name", "admin_user", "user.realm", "_es_api_key", "auth.type", "API_KEY", "apikey.id", createApiKeyResponse.get("id"), "apikey.name", apiKeyName ); verifySearchSlowLogMatchesTestData(testIndices, expectedUser); verifyIndexSlowLogMatchesTestData(testIndices, expectedUser); } public void testSlowLogWithRunAs() throws Exception { List<TestIndexData> testIndices = randomTestIndexData(); for (TestIndexData testData : testIndices) { final RequestOptions requestOptions = RequestOptions.DEFAULT.toBuilder() .addHeader("es-security-runas-user", "api_user") .addHeader("Authorization", basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray()))) .build(); searchSomeData(testData.name, requestOptions); indexSomeData(testData.name, requestOptions); } Map<String, Object> expectedUser = Map.of( "user.name", "admin_user", "user.effective.name", "api_user", "user.realm", "default_file", "user.effective.realm", "default_file", "auth.type", "REALM" ); verifySearchSlowLogMatchesTestData(testIndices, expectedUser); verifyIndexSlowLogMatchesTestData(testIndices, expectedUser); } public void testSlowLogWithServiceAccount() throws Exception { List<TestIndexData> testIndices = randomTestIndexData(); Map<String, Object> createServiceAccountResponse = createServiceAccountToken(); @SuppressWarnings("unchecked") String tokenValue = ((Map<String, Object>) createServiceAccountResponse.get("token")).get("value").toString(); for (TestIndexData testData : testIndices) { final RequestOptions requestOptions = RequestOptions.DEFAULT.toBuilder() .addHeader("Authorization", "Bearer " + tokenValue) .build(); searchSomeData(testData.name, requestOptions); indexSomeData(testData.name, requestOptions); } Map<String, Object> expectedUser = Map.of( "user.name", "elastic/fleet-server", "user.realm", "_service_account", "auth.type", "TOKEN" ); verifySearchSlowLogMatchesTestData(testIndices, expectedUser); verifyIndexSlowLogMatchesTestData(testIndices, expectedUser); } private static void enableSearchSlowLog(String index, boolean includeUser) throws IOException { final Request request = new Request("PUT", "/" + index + "/_settings"); request.setJsonEntity( "{\"index.search.slowlog.threshold.query." + randomFrom("trace", "warn", "debug", "info") + "\": \"0\", " + "\"index.search.slowlog.include.user\": " + includeUser + "}" ); client().performRequest(request); } private static void enableIndexingSlowLog(String index, boolean includeUser) throws IOException { final Request request = new Request("PUT", "/" + index + "/_settings"); request.setJsonEntity( "{\"index.indexing.slowlog.threshold.index." + randomFrom("trace", "warn", "debug", "info") + "\": \"0\", " + "\"index.indexing.slowlog.include.user\": " + includeUser + "}" ); client().performRequest(request); } private static void indexSomeData(String index) throws IOException { indexSomeData(index, RequestOptions.DEFAULT.toBuilder().build()); } private static void searchSomeData(String index) throws IOException { searchSomeData(index, RequestOptions.DEFAULT.toBuilder().build()); } private static void indexSomeData(String index, RequestOptions requestOptions) throws IOException { final Request request = new Request("PUT", "/" + index + "/_doc/1"); request.setOptions(requestOptions); request.setJsonEntity("{ \"foobar\" : true }"); client().performRequest(request); } private static void searchSomeData(String index, RequestOptions requestOptions) throws IOException { Request request = new Request("GET", "/" + index + "/_search"); request.setOptions(requestOptions); client().performRequest(request); } private static void setupTestIndex(TestIndexData testIndexData) throws IOException { indexSomeData(testIndexData.name); if (testIndexData.indexSlowLogEnabled) { enableIndexingSlowLog(testIndexData.name, testIndexData.indexSlowLogUserEnabled); } if (testIndexData.searchSlowLogEnabled) { enableSearchSlowLog(testIndexData.name, testIndexData.searchSlowLogUserEnabled); } } private static void createUserWithFullName(String user, String password, String fullName, String[] roles) throws IOException { Request request = new Request("POST", "/_security/user/" + user); request.setJsonEntity( "{ \"full_name\" : \"" + fullName + "\", \"roles\": [\"" + String.join("\",\"", roles) + "\"], \"password\": \"" + password + "\" }" ); Response response = client().performRequest(request); assertOK(response); } private static List<TestIndexData> randomTestIndexData() throws IOException { List<TestIndexData> testData = new ArrayList<>(); for (int i = 0; i < randomIntBetween(1, 10); i++) { TestIndexData randomTestData = new TestIndexData( "agentless-" + randomAlphaOfLengthBetween(5, 10).toLowerCase() + "-" + i, randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean() ); setupTestIndex(randomTestData); testData.add(randomTestData); } return testData; } private void verifySearchSlowLogMatchesTestData(List<TestIndexData> testIndices, Map<String, Object> expectedUserData) throws Exception { verifySlowLog(logLines -> { for (TestIndexData testIndex : testIndices) { if (testIndex.searchSlowLogEnabled) { Map<String, Object> logLine = logLines.get(currentSearchLogIndex); if (testIndex.searchSlowLogUserEnabled) { assertThat(expectedUserData.entrySet(), everyItem(in(logLine.entrySet()))); } else { assertThat(expectedUserData.entrySet(), everyItem(not(in(logLine.entrySet())))); } currentSearchLogIndex++; } } }, LogType.SEARCH_SLOW); } private void verifyIndexSlowLogMatchesTestData(List<TestIndexData> testIndices, Map<String, Object> expectedUserData) throws Exception { verifySlowLog(logLines -> { for (TestIndexData testIndex : testIndices) { if (testIndex.indexSlowLogEnabled) { Map<String, Object> logLine = logLines.get(currentIndexLogIndex); if (testIndex.indexSlowLogUserEnabled) { assertThat(expectedUserData.entrySet(), everyItem(in(logLine.entrySet()))); } else { assertThat(expectedUserData.entrySet(), everyItem(not(in(logLine.entrySet())))); } currentIndexLogIndex++; } } }, LogType.INDEXING_SLOW); } private static void verifySlowLog(Consumer<List<Map<String, Object>>> logVerifier, LogType logType) throws Exception { assertBusy(() -> { try (var slowLog = cluster.getNodeLog(0, logType)) { final List<String> lines = Streams.readAllLines(slowLog); logVerifier.accept( lines.stream().map(line -> XContentHelper.convertToMap(XContentType.JSON.xContent(), line, true)).toList() ); } }, 5, TimeUnit.SECONDS); } private static Map<String, Object> createApiKey(String name, String authHeader) throws IOException { final Request request = new Request("POST", "/_security/api_key"); request.setJsonEntity(Strings.format(""" {"name":"%s"}""", name)); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, authHeader)); final Response response = client().performRequest(request); assertOK(response); return responseAsMap(response); } private static Map<String, Object> createServiceAccountToken() throws IOException { final Request createServiceTokenRequest = new Request("POST", "/_security/service/elastic/fleet-server/credential/token"); final Response createServiceTokenResponse = adminClient().performRequest(createServiceTokenRequest); assertOK(createServiceTokenResponse); return responseAsMap(createServiceTokenResponse); } }
SecuritySlowLogIT
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/jpa/HibernatePersistenceConfiguration.java
{ "start": 3652, "end": 5093 }
class ____ extends PersistenceConfiguration { private final URL rootUrl; private final List<URL> jarFileUrls = new ArrayList<>(); /** * Create a new empty configuration. An empty configuration does not * typically hold enough information for successful invocation of * {@link #createEntityManagerFactory()}. * * @param name the name of the persistence unit, which may be used by * the persistence provider for logging and error reporting */ public HibernatePersistenceConfiguration(String name) { super( name ); this.rootUrl = null; } /** * Create a new empty configuration with a given {@linkplain #rootUrl root URL} * used for {@linkplain PersistenceSettings#SCANNER_DISCOVERY entity discovery} * via scanning. * <p> * The module {@code hibernate-scan-jandex} must be added as a dependency, * or some other implementation of the service * {@link org.hibernate.boot.archive.scan.spi.ScannerFactory} must be made * available. * * @param name the name of the persistence unit, which may be used by * the persistence provider for logging and error reporting * @param rootURL the root URL of the persistence unit * * @since 7.1 */ public HibernatePersistenceConfiguration(String name, URL rootURL) { super( name ); this.rootUrl = rootURL; } /** * Create a new empty configuration with the {@linkplain #rootUrl root URL} * inferred from the given
HibernatePersistenceConfiguration
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java
{ "start": 2603, "end": 2912 }
class ____ { private final AtomicLong children = new AtomicLong(); private final String id; ContextId(String id) { this.id = id; } ContextId createChildId() { return new ContextId(this.id + "-" + this.children.incrementAndGet()); } String getId() { return this.id; } } }
ContextId
java
apache__rocketmq
namesrv/src/main/java/org/apache/rocketmq/namesrv/NamesrvStartup.java
{ "start": 1954, "end": 9884 }
class ____ { private static final Logger log = LoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME); private static final Logger logConsole = LoggerFactory.getLogger(LoggerName.NAMESRV_CONSOLE_LOGGER_NAME); private static Properties properties = null; private static NamesrvConfig namesrvConfig = null; private static NettyServerConfig nettyServerConfig = null; private static NettyClientConfig nettyClientConfig = null; private static ControllerConfig controllerConfig = null; public static void main(String[] args) { main0(args); controllerManagerMain(); } public static NamesrvController main0(String[] args) { try { parseCommandlineAndConfigFile(args); NamesrvController controller = createAndStartNamesrvController(); return controller; } catch (Throwable e) { e.printStackTrace(); System.exit(-1); } return null; } public static ControllerManager controllerManagerMain() { try { if (namesrvConfig.isEnableControllerInNamesrv()) { return createAndStartControllerManager(); } } catch (Throwable e) { e.printStackTrace(); System.exit(-1); } return null; } public static void parseCommandlineAndConfigFile(String[] args) throws Exception { System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION)); Options options = ServerUtil.buildCommandlineOptions(new Options()); CommandLine commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new DefaultParser()); if (null == commandLine) { System.exit(-1); return; } namesrvConfig = new NamesrvConfig(); nettyServerConfig = new NettyServerConfig(); nettyClientConfig = new NettyClientConfig(); nettyServerConfig.setListenPort(9876); if (commandLine.hasOption('c')) { String file = commandLine.getOptionValue('c'); if (file != null) { InputStream in = new BufferedInputStream(Files.newInputStream(Paths.get(file))); properties = new Properties(); properties.load(in); MixAll.properties2Object(properties, namesrvConfig); MixAll.properties2Object(properties, nettyServerConfig); MixAll.properties2Object(properties, nettyClientConfig); if (namesrvConfig.isEnableControllerInNamesrv()) { controllerConfig = new ControllerConfig(); JraftConfig jraftConfig = new JraftConfig(); controllerConfig.setJraftConfig(jraftConfig); MixAll.properties2Object(properties, controllerConfig); MixAll.properties2Object(properties, jraftConfig); } namesrvConfig.setConfigStorePath(file); System.out.printf("load config properties file OK, %s%n", file); in.close(); } } MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig); if (commandLine.hasOption('p')) { MixAll.printObjectProperties(logConsole, namesrvConfig); MixAll.printObjectProperties(logConsole, nettyServerConfig); MixAll.printObjectProperties(logConsole, nettyClientConfig); if (namesrvConfig.isEnableControllerInNamesrv()) { MixAll.printObjectProperties(logConsole, controllerConfig); } System.exit(0); } if (null == namesrvConfig.getRocketmqHome()) { System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV); System.exit(-2); } MixAll.printObjectProperties(log, namesrvConfig); MixAll.printObjectProperties(log, nettyServerConfig); } public static NamesrvController createAndStartNamesrvController() throws Exception { NamesrvController controller = createNamesrvController(); start(controller); NettyServerConfig serverConfig = controller.getNettyServerConfig(); String tip = String.format("The Name Server boot success. serializeType=%s, address %s:%d", RemotingCommand.getSerializeTypeConfigInThisServer(), serverConfig.getBindAddress(), serverConfig.getListenPort()); log.info(tip); System.out.printf("%s%n", tip); return controller; } public static NamesrvController createNamesrvController() { final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig, nettyClientConfig); // remember all configs to prevent discard controller.getConfiguration().registerConfig(properties); return controller; } public static NamesrvController start(final NamesrvController controller) throws Exception { if (null == controller) { throw new IllegalArgumentException("NamesrvController is null"); } boolean initResult = controller.initialize(); if (!initResult) { controller.shutdown(); System.exit(-3); } Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, (Callable<Void>) () -> { controller.shutdown(); return null; })); controller.start(); return controller; } public static ControllerManager createAndStartControllerManager() throws Exception { ControllerManager controllerManager = createControllerManager(); start(controllerManager); String tip = "The ControllerManager boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer(); log.info(tip); System.out.printf("%s%n", tip); return controllerManager; } public static ControllerManager createControllerManager() throws Exception { NettyServerConfig controllerNettyServerConfig = (NettyServerConfig) nettyServerConfig.clone(); ControllerManager controllerManager = new ControllerManager(controllerConfig, controllerNettyServerConfig, nettyClientConfig); // remember all configs to prevent discard controllerManager.getConfiguration().registerConfig(properties); return controllerManager; } public static ControllerManager start(final ControllerManager controllerManager) throws Exception { if (null == controllerManager) { throw new IllegalArgumentException("ControllerManager is null"); } boolean initResult = controllerManager.initialize(); if (!initResult) { controllerManager.shutdown(); System.exit(-3); } Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, (Callable<Void>) () -> { controllerManager.shutdown(); return null; })); controllerManager.start(); return controllerManager; } public static void shutdown(final NamesrvController controller) { controller.shutdown(); } public static void shutdown(final ControllerManager controllerManager) { controllerManager.shutdown(); } public static Options buildCommandlineOptions(final Options options) { Option opt = new Option("c", "configFile", true, "Name server config properties file"); opt.setRequired(false); options.addOption(opt); opt = new Option("p", "printConfigItem", false, "Print all config items"); opt.setRequired(false); options.addOption(opt); return options; } public static Properties getProperties() { return properties; } }
NamesrvStartup
java
apache__avro
lang/java/mapred/src/test/java/org/apache/avro/hadoop/io/TestAvroSerializer.java
{ "start": 1291, "end": 2551 }
class ____ { @Test void serialize() throws IOException { // Create a serializer. Schema writerSchema = Schema.create(Schema.Type.STRING); AvroSerializer<CharSequence> serializer = new AvroSerializer<>(writerSchema); // Check the writer schema. assertEquals(writerSchema, serializer.getWriterSchema()); // Serialize two records, 'record1' and 'record2'. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.open(outputStream); serializer.serialize(new AvroKey<>("record1")); serializer.serialize(new AvroKey<>("record2")); serializer.close(); // Make sure the records were serialized correctly. ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); Schema readerSchema = Schema.create(Schema.Type.STRING); DatumReader<CharSequence> datumReader = new GenericDatumReader<>(readerSchema); Decoder decoder = DecoderFactory.get().binaryDecoder(inputStream, null); CharSequence record = null; record = datumReader.read(record, decoder); assertEquals("record1", record.toString()); record = datumReader.read(record, decoder); assertEquals("record2", record.toString()); inputStream.close(); } }
TestAvroSerializer
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/visitors/InterfaceGenVisitor.java
{ "start": 250, "end": 796 }
class ____ implements TypeElementVisitor<InterfaceGen, Object> { @Override public void visitClass(ClassElement element, VisitorContext context) { context.visitGeneratedSourceFile( "test", "GeneratedInterface", element ).ifPresent(sourceFile -> { try { sourceFile.write(writer -> writer.write(""" package test; import io.micronaut.context.annotation.Executable; public
InterfaceGenVisitor
java
apache__avro
lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Foo.java
{ "start": 28412, "end": 29340 }
class ____ extends org.apache.thrift.scheme.TupleScheme<ping_args> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; } @Override public void read(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } } public static
ping_argsTupleScheme
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/AnySetterTest.java
{ "start": 5404, "end": 6062 }
class ____ { private MyGeneric<String> myStringGeneric; private MyGeneric<Integer> myIntegerGeneric; public MyGeneric<String> getMyStringGeneric() { return myStringGeneric; } public void setMyStringGeneric(MyGeneric<String> myStringGeneric) { this.myStringGeneric = myStringGeneric; } public MyGeneric<Integer> getMyIntegerGeneric() { return myIntegerGeneric; } public void setMyIntegerGeneric(MyGeneric<Integer> myIntegerGeneric) { this.myIntegerGeneric = myIntegerGeneric; } } // [databind#349] static
MyWrapper
java
micronaut-projects__micronaut-core
function/src/main/java/io/micronaut/function/DefaultLocalFunctionRegistry.java
{ "start": 1668, "end": 8029 }
class ____ implements BeanDefinitionProcessor<FunctionBean>, LocalFunctionRegistry, MediaTypeCodecRegistry { private final Map<String, ExecutableMethod<?, ?>> consumers = new LinkedHashMap<>(1); private final Map<String, ExecutableMethod<?, ?>> functions = new LinkedHashMap<>(1); private final Map<String, ExecutableMethod<?, ?>> biFunctions = new LinkedHashMap<>(1); private final Map<String, ExecutableMethod<?, ?>> suppliers = new LinkedHashMap<>(1); private final MediaTypeCodecRegistry decoderRegistry; /** * Constructor. * * @param decoders decoders */ public DefaultLocalFunctionRegistry(MediaTypeCodec... decoders) { this.decoderRegistry = MediaTypeCodecRegistry.of(decoders); } /** * Constructor. * * @param decoders decoders */ @Inject public DefaultLocalFunctionRegistry(List<MediaTypeCodec> decoders) { this.decoderRegistry = MediaTypeCodecRegistry.of(decoders); } /** * Constructor. * * @param codecRegistry codecRegistry */ public DefaultLocalFunctionRegistry(MediaTypeCodecRegistry codecRegistry) { this.decoderRegistry = codecRegistry; } @SuppressWarnings("unchecked") @Override public Optional<? extends ExecutableMethod<?, ?>> findFirst() { return Stream.of(functions, suppliers, consumers, biFunctions) .map(all -> { Collection<ExecutableMethod<?, ?>> values = all.values(); return values.stream().findFirst(); }).filter(Optional::isPresent) .map(Optional::get) .findFirst(); } @SuppressWarnings("unchecked") @Override public Optional<? extends ExecutableMethod<?, ?>> find(String name) { return Stream.of(functions, suppliers, consumers, biFunctions) .flatMap(map -> { ExecutableMethod<?, ?> method = map.get(name); return Stream.ofNullable(method); }) .findFirst(); } @Override public Map<String, URI> getAvailableFunctions() { return Collections.emptyMap(); } @SuppressWarnings("unchecked") @Override public <T> Optional<ExecutableMethod<Supplier<T>, T>> findSupplier(String name) { ExecutableMethod method = suppliers.get(name); if (method != null) { return Optional.of(method); } return Optional.empty(); } @SuppressWarnings("unchecked") @Override public <T> Optional<ExecutableMethod<Consumer<T>, Void>> findConsumer(String name) { ExecutableMethod method = consumers.get(name); if (method != null) { return Optional.of(method); } return Optional.empty(); } @SuppressWarnings("unchecked") @Override public <T, R> Optional<ExecutableMethod<java.util.function.Function<T, R>, R>> findFunction(String name) { ExecutableMethod method = functions.get(name); if (method != null) { return Optional.of(method); } return Optional.empty(); } @SuppressWarnings("unchecked") @Override public <T, U, R> Optional<ExecutableMethod<BiFunction<T, U, R>, R>> findBiFunction(String name) { ExecutableMethod method = biFunctions.get(name); if (method != null) { return Optional.of(method); } return Optional.empty(); } @Override public void process(BeanDefinition<?> beanDefinition, BeanContext beanContext) { for (ExecutableMethod<?, ?> executableMethod : beanDefinition.getExecutableMethods()) { if (!executableMethod.hasAnnotation(FunctionBean.class)) { continue; } String functionId = executableMethod.stringValue(FunctionBean.class).orElse(null); Class<?> declaringType = executableMethod.getDeclaringType(); if (StringUtils.isEmpty(functionId)) { String typeName = declaringType.getSimpleName(); if (typeName.contains("$")) { // generated lambda functionId = NameUtils.hyphenate(executableMethod.getMethodName()); } else { functionId = NameUtils.hyphenate(typeName); } } String methodName = executableMethod.stringValue(FunctionBean.class, "method").orElse(null); if (methodName != null && !methodName.equals(executableMethod.getMethodName())) { continue; } if (Function.class.isAssignableFrom(declaringType) && executableMethod.getMethodName().equals("apply")) { registerFunction(executableMethod, functionId); } else if (Consumer.class.isAssignableFrom(declaringType) && executableMethod.getMethodName().equals("accept")) { registerConsumer(executableMethod, functionId); } else if (BiFunction.class.isAssignableFrom(declaringType) && executableMethod.getMethodName().equals("apply")) { registerBiFunction(executableMethod, functionId); } else if (Supplier.class.isAssignableFrom(declaringType) && executableMethod.getMethodName().equals("get")) { registerSupplier(executableMethod, functionId); } } } @Override public Optional<MediaTypeCodec> findCodec(@Nullable MediaType mediaType) { return decoderRegistry.findCodec(mediaType); } @Override public Optional<MediaTypeCodec> findCodec(@Nullable MediaType mediaType, Class<?> type) { return decoderRegistry.findCodec(mediaType, type); } @Override public Collection<MediaTypeCodec> getCodecs() { return decoderRegistry.getCodecs(); } private void registerSupplier(ExecutableMethod<?, ?> method, String functionId) { suppliers.put(functionId, method); } private void registerBiFunction(ExecutableMethod<?, ?> method, String functionId) { biFunctions.put(functionId, method); } private void registerConsumer(ExecutableMethod<?, ?> method, String functionId) { consumers.put(functionId, method); } private void registerFunction(ExecutableMethod<?, ?> method, String functionId) { functions.put(functionId, method); } }
DefaultLocalFunctionRegistry
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/orm/hibernate/domain/Person.java
{ "start": 761, "end": 1638 }
class ____ { private Long id; private String name; private DriversLicense driversLicense; public Person() { } public Person(Long id) { this(id, null, null); } public Person(String name) { this(name, null); } public Person(String name, DriversLicense driversLicense) { this(null, name, driversLicense); } public Person(Long id, String name, DriversLicense driversLicense) { this.id = id; this.name = name; this.driversLicense = driversLicense; } public Long getId() { return this.id; } protected void setId(Long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public DriversLicense getDriversLicense() { return this.driversLicense; } public void setDriversLicense(DriversLicense driversLicense) { this.driversLicense = driversLicense; } }
Person
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/node/EConditional.java
{ "start": 695, "end": 1879 }
class ____ extends AExpression { private final AExpression conditionNode; private final AExpression trueNode; private final AExpression falseNode; public EConditional(int identifier, Location location, AExpression conditionNode, AExpression trueNode, AExpression falseNode) { super(identifier, location); this.conditionNode = Objects.requireNonNull(conditionNode); this.trueNode = Objects.requireNonNull(trueNode); this.falseNode = Objects.requireNonNull(falseNode); } public AExpression getConditionNode() { return conditionNode; } public AExpression getTrueNode() { return trueNode; } public AExpression getFalseNode() { return falseNode; } @Override public <Scope> void visit(UserTreeVisitor<Scope> userTreeVisitor, Scope scope) { userTreeVisitor.visitConditional(this, scope); } @Override public <Scope> void visitChildren(UserTreeVisitor<Scope> userTreeVisitor, Scope scope) { conditionNode.visit(userTreeVisitor, scope); trueNode.visit(userTreeVisitor, scope); falseNode.visit(userTreeVisitor, scope); } }
EConditional
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerCustomizer.java
{ "start": 757, "end": 910 }
interface ____ can be used to customize a {@link ThreadPoolTaskScheduler}. * * @author Stephane Nicoll * @since 3.2.0 */ @FunctionalInterface public
that
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/AsyncDiskService.java
{ "start": 1372, "end": 1789 }
class ____ a container of multiple thread pools, each for a volume, * so that we can schedule async disk operations easily. * * Examples of async disk operations are deletion of files. * We can move the files to a "TO_BE_DELETED" folder before asychronously * deleting it, to make sure the caller can run it faster. */ @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"}) @InterfaceStability.Unstable public
is
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_4.java
{ "start": 307, "end": 806 }
class ____ extends TestCase { public void test_for_issue() throws Exception { String text = "{\"models\":[{\"x\":\"y\"},{\"x\":\"y\"}]}"; Root root = JSONObject.parseObject(text, Root.class); System.out.println(JSON.toJSONString(root)); String jsonpath = "$..x"; String value="y2"; JSONPath.set(root, jsonpath, value); assertEquals("{\"models\":[{\"x\":\"y2\"},{\"x\":\"y2\"}]}", JSON.toJSONString(root)); } public static
Issue1177_4
java
quarkusio__quarkus
extensions/smallrye-fault-tolerance/runtime/src/main/java/io/quarkus/smallrye/faulttolerance/runtime/SmallRyeFaultToleranceRecorder.java
{ "start": 554, "end": 2798 }
class ____ { public void createFaultToleranceOperation(List<FaultToleranceMethod> ftMethods) { List<Throwable> allExceptions = new ArrayList<>(); Map<QuarkusFaultToleranceOperationProvider.CacheKey, FaultToleranceOperation> operationCache = new HashMap<>( ftMethods.size()); for (FaultToleranceMethod ftMethod : ftMethods) { FaultToleranceOperation operation = new FaultToleranceOperation(ftMethod); try { operation.validate(); QuarkusFaultToleranceOperationProvider.CacheKey cacheKey = new QuarkusFaultToleranceOperationProvider.CacheKey( ftMethod.beanClass, ftMethod.method.reflect()); operationCache.put(cacheKey, operation); } catch (FaultToleranceDefinitionException | NoSuchMethodException e) { allExceptions.add(e); } } if (!allExceptions.isEmpty()) { if (allExceptions.size() == 1) { Throwable error = allExceptions.get(0); if (error instanceof DeploymentException) { throw (DeploymentException) error; } else { throw new DeploymentException(error); } } else { StringBuilder message = new StringBuilder("Found " + allExceptions.size() + " deployment problems: "); int idx = 1; for (Throwable error : allExceptions) { message.append("\n").append("[").append(idx++).append("] ").append(error.getMessage()); } DeploymentException deploymentException = new DeploymentException(message.toString()); for (Throwable error : allExceptions) { deploymentException.addSuppressed(error); } throw deploymentException; } } Arc.container().instance(QuarkusFaultToleranceOperationProvider.class).get().init(operationCache); } public void initExistingCircuitBreakerNames(Set<String> names) { Arc.container().instance(QuarkusExistingCircuitBreakerNames.class).get().init(names); } }
SmallRyeFaultToleranceRecorder
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/expr/SQLDateTimeExpr.java
{ "start": 872, "end": 3617 }
class ____ extends SQLDateTypeExpr { public SQLDateTimeExpr() { super(new SQLDataTypeImpl(SQLDataType.Constants.DATETIME)); } public SQLDateTimeExpr(Date now, TimeZone timeZone) { this(); setValue(now, timeZone); } public void setValue(Date x, TimeZone timeZone) { if (x == null) { this.value = null; return; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (timeZone != null) { format.setTimeZone(timeZone); } String text = format.format(x); setValue(text); } public SQLDateTimeExpr(String literal) { this(); this.setValue(literal); } public void setValue(String literal) { value = literal; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, this.dataType); } visitor.endVisit(this); } @Override public String getValue() { return (String) value; } public SQLDateTimeExpr clone() { SQLDateTimeExpr x = new SQLDateTimeExpr(); x.value = this.value; return x; } public static long supportDbTypes = DbType.of( DbType.mysql, DbType.oracle, DbType.presto, DbType.trino, DbType.postgresql, DbType.mariadb, DbType.tidb, DbType.polardbx ); public static boolean isSupport(DbType dbType) { return (dbType.mask & supportDbTypes) != 0; } public static boolean check(String str) { if (str == null || str.length() != 8) { return false; } if (str.charAt(2) != ':' && str.charAt(5) != ':') { return false; } char c0 = str.charAt(0); char c1 = str.charAt(1); char c3 = str.charAt(3); char c4 = str.charAt(4); char c6 = str.charAt(6); char c7 = str.charAt(7); if (c0 < '0' || c0 > '9') { return false; } if (c1 < '0' || c1 > '9') { return false; } if (c3 < '0' || c3 > '9') { return false; } if (c4 < '0' || c4 > '9') { return false; } if (c6 < '0' || c6 > '9') { return false; } if (c7 < '0' || c7 > '9') { return false; } int HH = (c0 - '0') * 10 + (c1 - '0'); int mm = (c3 - '0') * 10 + (c4 - '0'); int ss = (c6 - '0') * 10 + (c7 - '0'); if (HH > 24 || mm > 60 || ss > 60) { return false; } return true; } }
SQLDateTimeExpr
java
quarkusio__quarkus
integration-tests/opentelemetry-jdbc-instrumentation/src/test/java/io/quarkus/it/opentelemetry/Db2LifecycleManager.java
{ "start": 298, "end": 1777 }
class ____ implements QuarkusTestResourceLifecycleManager { private static final Logger LOGGER = Logger.getLogger(Db2LifecycleManager.class); private static final String QUARKUS = "quarkus"; private static final String DB2_IMAGE = System.getProperty("db2.image"); private StartedDb2Container db2Container; @Override public Map<String, String> start() { db2Container = new StartedDb2Container(); LOGGER.info(db2Container.getLogs()); Map<String, String> properties = new HashMap<>(); properties.put("quarkus.datasource.db2.jdbc.url", String.format("jdbc:db2://%s:%s/%s", db2Container.getHost(), db2Container.getFirstMappedPort(), QUARKUS)); properties.put("quarkus.datasource.db2.password", QUARKUS); properties.put("quarkus.datasource.db2.username", QUARKUS); properties.put("quarkus.hibernate-orm.db2.schema-management.strategy", "drop-and-create"); properties.put("quarkus.hibernate-orm.db2.active", "true"); properties.put("quarkus.hibernate-orm.oracle.active", "false"); properties.put("quarkus.hibernate-orm.postgresql.active", "false"); properties.put("quarkus.hibernate-orm.mariadb.active", "false"); properties.put("quarkus.hibernate-orm.h2.active", "false"); return properties; } @Override public void stop() { db2Container.stop(); } private static final
Db2LifecycleManager
java
google__dagger
javatests/dagger/internal/codegen/ComponentCreatorTest.java
{ "start": 34874, "end": 35173 }
interface ____ {", " Foo foo();", "}"); Source component = preprocessedJavaSource( "test.HasSupertype", "package test;", "", "import dagger.Component;", "", "@Component", "
Supertype
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/linux/resources/gpu/GpuResourceAllocator.java
{ "start": 3364, "end": 11817 }
class ____ { private Set<GpuDevice> allowed = Collections.emptySet(); private Set<GpuDevice> denied = Collections.emptySet(); GpuAllocation(Set<GpuDevice> allowed, Set<GpuDevice> denied) { if (allowed != null) { this.allowed = ImmutableSet.copyOf(allowed); } if (denied != null) { this.denied = ImmutableSet.copyOf(denied); } } public Set<GpuDevice> getAllowedGPUs() { return allowed; } public Set<GpuDevice> getDeniedGPUs() { return denied; } } /** * Add GPU to the allowed list of GPUs. * @param gpuDevice gpu device */ public synchronized void addGpu(GpuDevice gpuDevice) { allowedGpuDevices.add(gpuDevice); } @VisibleForTesting public synchronized int getAvailableGpus() { return allowedGpuDevices.size() - usedDevices.size(); } public synchronized void recoverAssignedGpus(ContainerId containerId) throws ResourceHandlerException { Container c = nmContext.getContainers().get(containerId); if (c == null) { throw new ResourceHandlerException( "Cannot find container with id=" + containerId + ", this should not occur under normal circumstances!"); } LOG.info("Starting recovery of GpuDevice for {}.", containerId); for (Serializable gpuDeviceSerializable : c.getResourceMappings() .getAssignedResources(GPU_URI)) { if (!(gpuDeviceSerializable instanceof GpuDevice)) { throw new ResourceHandlerException( "Trying to recover device id, however it" + " is not an instance of " + GpuDevice.class.getName() + ", this should not occur under normal circumstances!"); } GpuDevice gpuDevice = (GpuDevice) gpuDeviceSerializable; // Make sure it is in allowed GPU device. if (!allowedGpuDevices.contains(gpuDevice)) { throw new ResourceHandlerException( "Try to recover device = " + gpuDevice + " however it is not in the allowed device list:" + StringUtils.join(",", allowedGpuDevices)); } // Make sure it is not occupied by anybody else if (usedDevices.containsKey(gpuDevice)) { throw new ResourceHandlerException( "Try to recover device id = " + gpuDevice + " however it is already assigned to container=" + usedDevices .get(gpuDevice) + ", please double check what happened."); } usedDevices.put(gpuDevice, containerId); LOG.info("ContainerId {} is assigned to GpuDevice {} on recovery.", containerId, gpuDevice); } LOG.info("Finished recovery of GpuDevice for {}.", containerId); } /** * Get number of requested GPUs from resource. * @param requestedResource requested resource * @return #gpus. */ public static int getRequestedGpus(Resource requestedResource) { try { return Long.valueOf(requestedResource.getResourceValue( GPU_URI)).intValue(); } catch (ResourceNotFoundException e) { return 0; } } /** * Assign GPU to the specified container. * @param container container to allocate * @return allocation results. * @throws ResourceHandlerException When failed to assign GPUs. */ public GpuAllocation assignGpus(Container container) throws ResourceHandlerException { GpuAllocation allocation = internalAssignGpus(container); // Wait for a maximum of waitPeriodForResource seconds if no // available GPU are there which are yet to be released. int timeWaiting = 0; while (allocation == null) { if (timeWaiting >= waitPeriodForResource) { break; } // Sleep for 1 sec to ensure there are some free GPU devices which are // getting released. try { LOG.info("Container : " + container.getContainerId() + " is waiting for free GPU devices."); Thread.sleep(WAIT_MS_PER_LOOP); timeWaiting += WAIT_MS_PER_LOOP; allocation = internalAssignGpus(container); } catch (InterruptedException e) { // On any interrupt, break the loop and continue execution. Thread.currentThread().interrupt(); LOG.warn("Interrupted while waiting for available GPU"); break; } } if(allocation == null) { String message = "Could not get valid GPU device for container '" + container.getContainerId() + "' as some other containers might not releasing GPUs."; LOG.warn(message); throw new ResourceHandlerException(message); } return allocation; } private synchronized GpuAllocation internalAssignGpus(Container container) throws ResourceHandlerException { Resource requestedResource = container.getResource(); ContainerId containerId = container.getContainerId(); int numRequestedGpuDevices = getRequestedGpus(requestedResource); // Assign GPUs to container if requested some. if (numRequestedGpuDevices > 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Trying to assign %d GPUs to container: %s" + ", #AvailableGPUs=%d, #ReleasingGPUs=%d", numRequestedGpuDevices, containerId, getAvailableGpus(), getReleasingGpus())); } if (numRequestedGpuDevices > getAvailableGpus()) { // If there are some devices which are getting released, wait for few // seconds to get it. if (numRequestedGpuDevices <= getReleasingGpus() + getAvailableGpus()) { return null; } } if (numRequestedGpuDevices > getAvailableGpus()) { throw new ResourceHandlerException( "Failed to find enough GPUs, requestor=" + containerId + ", #RequestedGPUs=" + numRequestedGpuDevices + ", #AvailableGPUs=" + getAvailableGpus()); } Set<GpuDevice> assignedGpus = new TreeSet<>(); for (GpuDevice gpu : allowedGpuDevices) { if (!usedDevices.containsKey(gpu)) { usedDevices.put(gpu, containerId); assignedGpus.add(gpu); if (assignedGpus.size() == numRequestedGpuDevices) { break; } } } // Record in state store if we allocated anything if (!assignedGpus.isEmpty()) { try { // Update state store. nmContext.getNMStateStore().storeAssignedResources(container, GPU_URI, new ArrayList<>(assignedGpus)); } catch (IOException e) { unassignGpus(containerId); throw new ResourceHandlerException(e); } } return new GpuAllocation(assignedGpus, Sets.differenceInTreeSets(allowedGpuDevices, assignedGpus)); } return new GpuAllocation(null, allowedGpuDevices); } private synchronized long getReleasingGpus() { long releasingGpus = 0; for (ContainerId containerId : ImmutableSet.copyOf(usedDevices.values())) { Container container; if ((container = nmContext.getContainers().get(containerId)) != null) { if (container.isContainerInFinalStates()) { releasingGpus = releasingGpus + container.getResource() .getResourceInformation(ResourceInformation.GPU_URI).getValue(); } } } return releasingGpus; } /** * Clean up all GPUs assigned to containerId. * @param containerId containerId */ public synchronized void unassignGpus(ContainerId containerId) { if (LOG.isDebugEnabled()) { LOG.debug("Trying to unassign GPU device from container " + containerId); } usedDevices.entrySet().removeIf(entry -> entry.getValue().equals(containerId)); } @VisibleForTesting public synchronized Map<GpuDevice, ContainerId> getDeviceAllocationMapping() { return ImmutableMap.copyOf(usedDevices); } public synchronized List<GpuDevice> getAllowedGpus() { return ImmutableList.copyOf(allowedGpuDevices); } public synchronized List<AssignedGpuDevice> getAssignedGpus() { return usedDevices.entrySet().stream() .map(e -> { final GpuDevice gpu = e.getKey(); ContainerId containerId = e.getValue(); return new AssignedGpuDevice(gpu.getIndex(), gpu.getMinorNumber(), containerId); }).collect(Collectors.toList()); } @Override public String toString() { return GpuResourceAllocator.class.getName(); } }
GpuAllocation
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java
{ "start": 1234, "end": 2837 }
class ____ { @BeforeEach @AfterEach void cleanup() { FileSystemUtils.deleteRecursively(new ApplicationTemp().getDir()); } @Test void generatesConsistentTemp() { ApplicationTemp t1 = new ApplicationTemp(); ApplicationTemp t2 = new ApplicationTemp(); assertThat(t1.getDir()).isNotNull(); assertThat(t1.getDir()).isEqualTo(t2.getDir()); } @Test void differentBasedOnUserDir() { String userDir = System.getProperty("user.dir"); try { File t1 = new ApplicationTemp().getDir(); System.setProperty("user.dir", "abc"); File t2 = new ApplicationTemp().getDir(); assertThat(t1).isNotEqualTo(t2); } finally { System.setProperty("user.dir", userDir); } } @Test void getSubDir() { ApplicationTemp temp = new ApplicationTemp(); assertThat(temp.getDir("abc")).isEqualTo(new File(temp.getDir(), "abc")); } @Test void posixPermissions() throws IOException { ApplicationTemp temp = new ApplicationTemp(); Path path = temp.getDir().toPath(); FileSystem fileSystem = path.getFileSystem(); if (fileSystem.supportedFileAttributeViews().contains("posix")) { assertDirectoryPermissions(path); assertDirectoryPermissions(temp.getDir("sub").toPath()); } } private void assertDirectoryPermissions(Path path) throws IOException { Set<PosixFilePermission> permissions = Files.getFileAttributeView(path, PosixFileAttributeView.class) .readAttributes() .permissions(); assertThat(permissions).containsExactlyInAnyOrder(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE); } }
ApplicationTempTests
java
quarkusio__quarkus
integration-tests/gradle/src/main/resources/custom-filesystem-provider/application/src/test/java/org/acme/TestResource.java
{ "start": 183, "end": 493 }
class ____ implements QuarkusTestResourceLifecycleManager { @Override public Map<String, String> start() { final CommonBean bean = new CommonBean(); System.out.println("TestResource start " + bean.getClass().getName()); return Collections.emptyMap(); } @Override public void stop() { } }
TestResource
java
spring-projects__spring-boot
module/spring-boot-data-elasticsearch/src/test/java/org/springframework/boot/data/elasticsearch/autoconfigure/DataElasticsearchAutoConfigurationTests.java
{ "start": 2593, "end": 5654 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, ElasticsearchClientAutoConfiguration.class, DataElasticsearchAutoConfiguration.class)); @Test void defaultRestBeansRegistered() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ElasticsearchTemplate.class) .hasSingleBean(ReactiveElasticsearchTemplate.class) .hasSingleBean(ElasticsearchConverter.class) .hasSingleBean(ElasticsearchConverter.class) .hasSingleBean(ElasticsearchCustomConversions.class)); } @Test void defaultConversionsRegisterBigDecimalAsSimpleType() { this.contextRunner.run((context) -> { SimpleElasticsearchMappingContext mappingContext = context.getBean(SimpleElasticsearchMappingContext.class); assertThat(mappingContext) .extracting("simpleTypeHolder", InstanceOfAssertFactories.type(SimpleTypeHolder.class)) .satisfies((simpleTypeHolder) -> assertThat(simpleTypeHolder.isSimpleType(BigDecimal.class)).isTrue()); }); } @Test void customConversionsShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomElasticsearchCustomConversions.class).run((context) -> { assertThat(context).hasSingleBean(ElasticsearchCustomConversions.class).hasBean("testCustomConversions"); assertThat(context.getBean(ElasticsearchConverter.class) .getConversionService() .canConvert(ElasticsearchTemplate.class, Boolean.class)).isTrue(); }); } @Test void customRestTemplateShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomRestTemplate.class) .run((context) -> assertThat(context).getBeanNames(ElasticsearchTemplate.class) .hasSize(1) .contains("elasticsearchTemplate")); } @Test void customReactiveRestTemplateShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomReactiveElasticsearchTemplate.class) .run((context) -> assertThat(context).getBeanNames(ReactiveElasticsearchTemplate.class) .hasSize(1) .contains("reactiveElasticsearchTemplate")); } @Test void shouldFilterInitialEntityScanWithDocumentAnnotation() { this.contextRunner.withUserConfiguration(EntityScanConfig.class).run((context) -> { SimpleElasticsearchMappingContext mappingContext = context.getBean(SimpleElasticsearchMappingContext.class); assertThat(mappingContext.hasPersistentEntityFor(City.class)).isTrue(); }); } @Test void configureWithRestClientShouldCreateTransportAndClient() { this.contextRunner.withUserConfiguration(RestClientConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class)); } @Test void configureWhenCustomClientShouldBackOff() { this.contextRunner.withUserConfiguration(RestClientConfiguration.class, CustomClientConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) .hasBean("customClient")); } @Configuration(proxyBeanMethods = false) static
DataElasticsearchAutoConfigurationTests
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java
{ "start": 848, "end": 991 }
class ____ implements DemoService { @Override public String sayHello(String name) { return "hello " + name; } }
DemoServiceImpl
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/ExtractionContextImpl.java
{ "start": 709, "end": 3172 }
class ____ implements ExtractionContext { private final ServiceRegistry serviceRegistry; private final JdbcEnvironment jdbcEnvironment; private final SqlStringGenerationContext context; private final JdbcConnectionAccess jdbcConnectionAccess; private final DatabaseObjectAccess registeredTableAccess; private Connection jdbcConnection; private DatabaseMetaData jdbcDatabaseMetaData; public ExtractionContextImpl( ServiceRegistry serviceRegistry, JdbcEnvironment jdbcEnvironment, SqlStringGenerationContext context, JdbcConnectionAccess jdbcConnectionAccess, DatabaseObjectAccess registeredTableAccess) { this.serviceRegistry = serviceRegistry; this.jdbcEnvironment = jdbcEnvironment; this.context = context; this.jdbcConnectionAccess = jdbcConnectionAccess; this.registeredTableAccess = registeredTableAccess; } @Override public ServiceRegistry getServiceRegistry() { return serviceRegistry; } @Override public JdbcEnvironment getJdbcEnvironment() { return jdbcEnvironment; } @Override public SqlStringGenerationContext getSqlStringGenerationContext() { return context; } @Override public Connection getJdbcConnection() { if ( jdbcConnection == null ) { try { jdbcConnection = jdbcConnectionAccess.obtainConnection(); } catch (SQLException e) { throw jdbcEnvironment.getSqlExceptionHelper() .convert( e, "Unable to obtain JDBC Connection" ); } } return jdbcConnection; } @Override public DatabaseMetaData getJdbcDatabaseMetaData() { if ( jdbcDatabaseMetaData == null ) { try { jdbcDatabaseMetaData = getJdbcConnection().getMetaData(); } catch (SQLException e) { throw jdbcEnvironment.getSqlExceptionHelper() .convert( e, "Unable to obtain JDBC DatabaseMetaData" ); } } return jdbcDatabaseMetaData; } @Override public Identifier getDefaultCatalog() { return context.getDefaultCatalog(); } @Override public Identifier getDefaultSchema() { return context.getDefaultSchema(); } @Override public DatabaseObjectAccess getDatabaseObjectAccess() { return registeredTableAccess; } @Override public void cleanup() { if ( jdbcDatabaseMetaData != null ) { jdbcDatabaseMetaData = null; } if ( jdbcConnection != null ) { try { jdbcConnectionAccess.releaseConnection( jdbcConnection ); } catch (SQLException exception) { JDBC_LOGGER.unableToReleaseConnection( exception ); } } } }
ExtractionContextImpl
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/DataTypeExtractorTest.java
{ "start": 40107, "end": 40200 }
interface ____<T> { // no implementation } private abstract static
BaseInterface
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java
{ "start": 5190, "end": 5699 }
enum ____ { ONE, TWO, THREE, UNRECOGNIZED } boolean m(Case c) { switch (c) { case ONE: case TWO: case THREE: return true; default: } return false; } } """) .addOutputLines( "out/Test.java", """
Case
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionMetrics.java
{ "start": 5719, "end": 7901 }
class ____ extends RemotingSerializable { private ConcurrentMap<String, Metric> transactionCount = new ConcurrentHashMap<>(1024); private DataVersion dataVersion = new DataVersion(); public ConcurrentMap<String, Metric> getTransactionCount() { return transactionCount; } public void setTransactionCount( ConcurrentMap<String, Metric> transactionCount) { this.transactionCount = transactionCount; } public DataVersion getDataVersion() { return dataVersion; } public void setDataVersion(DataVersion dataVersion) { this.dataVersion = dataVersion; } } @Override public synchronized void persist() { try { // bak metrics file String config = configFilePath(); String backup = config + ".bak"; File configFile = new File(config); File bakFile = new File(backup); if (configFile.exists()) { // atomic move Files.move(configFile.toPath(), bakFile.toPath(), StandardCopyOption.ATOMIC_MOVE); // sync the directory, ensure that the bak file is visible MixAll.fsyncDirectory(Paths.get(bakFile.getParent())); } File dir = new File(configFile.getParent()); if (!dir.exists()) { Files.createDirectories(dir.toPath()); } // persist metrics file StringWriter stringWriter = new StringWriter(); write0(stringWriter); try (RandomAccessFile randomAccessFile = new RandomAccessFile(config, "rw")) { randomAccessFile.write(stringWriter.toString().getBytes(StandardCharsets.UTF_8)); randomAccessFile.getChannel().force(true); // sync the directory, ensure that the config file is visible MixAll.fsyncDirectory(Paths.get(configFile.getParent())); } } catch (Throwable t) { log.error("Failed to persist", t); } } public static
TransactionMetricsSerializeWrapper
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/transport/actions/stats/WatcherStatsAction.java
{ "start": 441, "end": 737 }
class ____ extends ActionType<WatcherStatsResponse> { public static final WatcherStatsAction INSTANCE = new WatcherStatsAction(); public static final String NAME = "cluster:monitor/xpack/watcher/stats/dist"; private WatcherStatsAction() { super(NAME); } }
WatcherStatsAction
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/index/mapper/NumberFieldBlockLoaderTestCase.java
{ "start": 650, "end": 2711 }
class ____<T extends Number> extends BlockLoaderTestCase { public NumberFieldBlockLoaderTestCase(FieldType fieldType, Params params) { super(fieldType.toString(), params); } @Override @SuppressWarnings("unchecked") protected Object expected(Map<String, Object> fieldMapping, Object value, TestContext testContext) { var nullValue = fieldMapping.get("null_value") != null ? convert((Number) fieldMapping.get("null_value"), fieldMapping) : null; if (value instanceof List<?> == false) { return convert(value, nullValue, fieldMapping); } boolean hasDocValues = hasDocValues(fieldMapping, true); boolean useDocValues = params.preference() == MappedFieldType.FieldExtractPreference.NONE || params.preference() == MappedFieldType.FieldExtractPreference.DOC_VALUES || params.syntheticSource(); if (hasDocValues && useDocValues) { // Sorted var resultList = ((List<Object>) value).stream() .map(v -> convert(v, nullValue, fieldMapping)) .filter(Objects::nonNull) .sorted() .toList(); return maybeFoldList(resultList); } // parsing from source var resultList = ((List<Object>) value).stream().map(v -> convert(v, nullValue, fieldMapping)).filter(Objects::nonNull).toList(); return maybeFoldList(resultList); } @SuppressWarnings("unchecked") private T convert(Object value, T nullValue, Map<String, Object> fieldMapping) { if (value == null) { return nullValue; } // String coercion is true by default if (value instanceof String s && s.isEmpty()) { return nullValue; } if (value instanceof Number n) { return convert(n, fieldMapping); } // Malformed values are excluded return null; } protected abstract T convert(Number value, Map<String, Object> fieldMapping); }
NumberFieldBlockLoaderTestCase
java
apache__camel
components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcRemoveConfirmOrderAggregateTest.java
{ "start": 1681, "end": 2272 }
class ____ extends DataSourceTransactionManager { int count; @Override protected void doCommit(DefaultTransactionStatus status) { if ("main".equals(Thread.currentThread().getName()) && ++count == 2) { try { LOG.debug("sleeping while committing..."); Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } super.doCommit(status); } } public static
SlowCommitDataSourceTransactionManager
java
google__dagger
javatests/dagger/internal/codegen/ComponentCreatorTest.java
{ "start": 33515, "end": 34319 }
interface ____ {}"); CompilerTests.daggerCompiler( moduleFile, module2File, module3File, componentFile, otherComponent) .withProcessingOptions(compilerOptions) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining( // Ignores Test2Module because we can construct it ourselves. // TODO(sameb): Ignore Test3Module because it's not used within transitive // dependencies. String.format( messages.missingSetters(), "[test.TestModule, test.Test3Module, test.OtherComponent]")) .onSource(componentFile) .onLineContaining(process("
OtherComponent
java
apache__logging-log4j2
log4j-1.2-api/src/main/java/org/apache/log4j/helpers/FileWatchdog.java
{ "start": 1094, "end": 3457 }
class ____ extends Thread { /** * The default delay between every file modification check, set to 60 seconds. */ public static final long DEFAULT_DELAY = 60_000; /** * The name of the file to observe for changes. */ protected String filename; /** * The delay to observe between every check. By default set {@link #DEFAULT_DELAY}. */ protected long delay = DEFAULT_DELAY; File file; long lastModified; boolean warnedAlready; boolean interrupted; @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "The filename comes from a system property.") protected FileWatchdog(final String fileName) { super("FileWatchdog"); this.filename = fileName; this.file = new File(fileName); setDaemon(true); checkAndConfigure(); } protected void checkAndConfigure() { boolean fileExists; try { fileExists = file.exists(); } catch (final SecurityException e) { LogLog.warn("Was not allowed to read check file existence, file:[" + filename + "]."); interrupted = true; // there is no point in continuing return; } if (fileExists) { final long fileLastMod = file.lastModified(); // this can also throw a SecurityException if (fileLastMod > lastModified) { // however, if we reached this point this lastModified = fileLastMod; // is very unlikely. doOnChange(); warnedAlready = false; } } else { if (!warnedAlready) { LogLog.debug("[" + filename + "] does not exist."); warnedAlready = true; } } } protected abstract void doOnChange(); @Override public void run() { while (!interrupted) { try { Thread.sleep(delay); } catch (final InterruptedException e) { // no interruption expected } checkAndConfigure(); } } /** * Sets the delay in milliseconds to observe between each check of the file changes. * * @param delayMillis the delay in milliseconds */ public void setDelay(final long delayMillis) { this.delay = delayMillis; } }
FileWatchdog
java
spring-projects__spring-boot
module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/OnEnabledLoggingExportCondition.java
{ "start": 1335, "end": 3060 }
class ____ extends SpringBootCondition { private static final String GLOBAL_PROPERTY = "management.logging.export.enabled"; private static final String EXPORTER_PROPERTY = "management.logging.export.%s.enabled"; @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String loggingExporter = getExporterName(metadata); if (StringUtils.hasLength(loggingExporter)) { String formattedExporterProperty = EXPORTER_PROPERTY.formatted(loggingExporter); Boolean exporterLoggingEnabled = context.getEnvironment() .getProperty(formattedExporterProperty, Boolean.class); if (exporterLoggingEnabled != null) { return new ConditionOutcome(exporterLoggingEnabled, ConditionMessage.forCondition(ConditionalOnEnabledLoggingExport.class) .because(formattedExporterProperty + " is " + exporterLoggingEnabled)); } } Boolean globalLoggingEnabled = context.getEnvironment().getProperty(GLOBAL_PROPERTY, Boolean.class); if (globalLoggingEnabled != null) { return new ConditionOutcome(globalLoggingEnabled, ConditionMessage.forCondition(ConditionalOnEnabledLoggingExport.class) .because(GLOBAL_PROPERTY + " is " + globalLoggingEnabled)); } return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnEnabledLoggingExport.class) .because("is enabled by default")); } private static @Nullable String getExporterName(AnnotatedTypeMetadata metadata) { Map<String, @Nullable Object> attributes = metadata .getAnnotationAttributes(ConditionalOnEnabledLoggingExport.class.getName()); if (attributes == null) { return null; } return (String) attributes.get("value"); } }
OnEnabledLoggingExportCondition
java
elastic__elasticsearch
libs/tdigest/src/test/java/org/elasticsearch/tdigest/TDigestTestCase.java
{ "start": 1723, "end": 1926 }
class ____ arrays that will be automatically closed after the test. * It will also test that all memory have been freed, as the arrays use a counting CircuitBreaker. * </p> */ public abstract
provides
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-examples/src/test/java/org/apache/hadoop/examples/pi/math/TestLongLong.java
{ "start": 1011, "end": 2640 }
class ____ { static final Random RAN = new Random(); static final long MASK = (1L << (LongLong.SIZE >> 1)) - 1; static long nextPositiveLong() { return RAN.nextLong() & MASK; } static void verifyMultiplication(long a, long b) { final LongLong ll = LongLong.multiplication(new LongLong(), a, b); final BigInteger bi = BigInteger.valueOf(a).multiply(BigInteger.valueOf(b)); final String s = String.format( "\na = %x\nb = %x\nll= " + ll + "\nbi= " + bi.toString(16) + "\n", a, b); //System.out.println(s); assertEquals(bi, ll.toBigInteger(), s); } @Test void testMultiplication() { for (int i = 0; i < 100; i++) { final long a = nextPositiveLong(); final long b = nextPositiveLong(); verifyMultiplication(a, b); } final long max = Long.MAX_VALUE & MASK; verifyMultiplication(max, max); } @Test void testRightShift() { for (int i = 0; i < 1000; i++) { final long a = nextPositiveLong(); final long b = nextPositiveLong(); verifyRightShift(a, b); } } private static void verifyRightShift(long a, long b) { final LongLong ll = new LongLong().set(a, b); final BigInteger bi = ll.toBigInteger(); final String s = String.format( "\na = %x\nb = %x\nll= " + ll + "\nbi= " + bi.toString(16) + "\n", a, b); assertEquals(bi, ll.toBigInteger(), s); for (int i = 0; i < LongLong.SIZE >> 1; i++) { final long result = ll.shiftRight(i) & MASK; final long expected = bi.shiftRight(i).longValue() & MASK; assertEquals(expected, result, s); } } }
TestLongLong
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/util/ClassSecurityValidator.java
{ "start": 3145, "end": 3419 }
class ____ trusted, false otherwise */ boolean isTrusted(Class<?> clazz); /** * Throws a {@link SecurityException} with a message indicating that the class * is not trusted to be included in Avro schemas. * * @param className the name of the
is
java
apache__flink
flink-python/src/main/java/org/apache/flink/python/env/AbstractPythonEnvironmentManager.java
{ "start": 2188, "end": 18105 }
class ____ implements PythonEnvironmentManager { private static final Logger LOG = LoggerFactory.getLogger(AbstractPythonEnvironmentManager.class); private static final long CHECK_INTERVAL = 20; private static final long CHECK_TIMEOUT = 1000; private transient Thread shutdownHook; protected transient PythonLeasedResource resource; protected final PythonDependencyInfo dependencyInfo; private final Map<String, String> systemEnv; private final String[] tmpDirectories; private final JobID jobID; @VisibleForTesting public static final String PYTHON_REQUIREMENTS_DIR = "python-requirements"; @VisibleForTesting public static final String PYTHON_REQUIREMENTS_FILE = "_PYTHON_REQUIREMENTS_FILE"; @VisibleForTesting public static final String PYTHON_REQUIREMENTS_CACHE = "_PYTHON_REQUIREMENTS_CACHE"; @VisibleForTesting public static final String PYTHON_REQUIREMENTS_INSTALL_DIR = "_PYTHON_REQUIREMENTS_INSTALL_DIR"; @VisibleForTesting public static final String PYTHON_WORKING_DIR = "_PYTHON_WORKING_DIR"; @VisibleForTesting public static final String PYTHON_FILES_DIR = "python-files"; @VisibleForTesting public static final String PYTHON_ARCHIVES_DIR = "python-archives"; @VisibleForTesting public static final String PYFLINK_GATEWAY_DISABLED = "PYFLINK_GATEWAY_DISABLED"; public AbstractPythonEnvironmentManager( PythonDependencyInfo dependencyInfo, String[] tmpDirectories, Map<String, String> systemEnv, JobID jobID) { this.dependencyInfo = Objects.requireNonNull(dependencyInfo); this.tmpDirectories = Objects.requireNonNull(tmpDirectories); this.systemEnv = Objects.requireNonNull(systemEnv); this.jobID = Objects.requireNonNull(jobID); } @Override public void open() throws Exception { resource = PythonEnvResources.getOrAllocateSharedResource( jobID, jobID -> { String baseDirectory = createBaseDirectory(tmpDirectories); File baseDirectoryFile = new File(baseDirectory); if (!baseDirectoryFile.exists() && !baseDirectoryFile.mkdir()) { throw new IOException( "Could not create the base directory: " + baseDirectory); } try { Map<String, String> env = constructEnvironmentVariables(baseDirectory); installRequirements(baseDirectory, env); return Tuple2.of(baseDirectory, env); } catch (Throwable e) { deleteBaseDirectory(baseDirectory); LOG.warn("Failed to create resource.", e); throw e; } }); shutdownHook = ShutdownHookUtil.addShutdownHook( this, AbstractPythonEnvironmentManager.class.getSimpleName(), LOG); } @Override public void close() throws Exception { try { PythonEnvResources.release(jobID); } finally { if (shutdownHook != null) { ShutdownHookUtil.removeShutdownHook( shutdownHook, AbstractPythonEnvironmentManager.class.getSimpleName(), LOG); shutdownHook = null; } } } @VisibleForTesting public String getBaseDirectory() { return resource.baseDirectory; } @VisibleForTesting public Map<String, String> getPythonEnv() { return resource.env; } /** * Constructs the environment variables which is used to launch the python UDF worker. * * @return The environment variables which contain the paths of the python dependencies. */ @VisibleForTesting public Map<String, String> constructEnvironmentVariables(String baseDirectory) throws IOException { Map<String, String> env = new HashMap<>(this.systemEnv); constructFilesDirectory(env, baseDirectory); if (dependencyInfo.getPythonPath().isPresent()) { appendToPythonPath( env, Collections.singletonList(dependencyInfo.getPythonPath().get())); } LOG.info("PYTHONPATH of python worker: {}", env.get("PYTHONPATH")); constructRequirementsDirectory(env, baseDirectory); constructArchivesDirectory(env, baseDirectory); // set BOOT_LOG_DIR. env.put("BOOT_LOG_DIR", baseDirectory); // disable the launching of gateway server to prevent from this dead loop: // launch UDF worker -> import udf -> import job code // ^ | (If the job code is not enclosed in a // | | if name == 'main' statement) // | V // execute job in local mode <- launch gateway server and submit job to local executor env.put(PYFLINK_GATEWAY_DISABLED, "true"); // set the path of python interpreter, it will be used to execute the udf worker. env.put("python", dependencyInfo.getPythonExec()); LOG.info("Python interpreter path: {}", dependencyInfo.getPythonExec()); return env; } private static String createBaseDirectory(String[] tmpDirectories) throws IOException { Random rnd = new Random(); // try to find a unique file name for the base directory int maxAttempts = 10; for (int attempt = 0; attempt < maxAttempts; attempt++) { String directory = tmpDirectories[rnd.nextInt(tmpDirectories.length)]; File baseDirectory = new File(directory, "python-dist-" + UUID.randomUUID().toString()); if (baseDirectory.mkdirs()) { return baseDirectory.getAbsolutePath(); } } throw new IOException( "Could not find a unique directory name in '" + Arrays.toString(tmpDirectories) + "' for storing the generated files of python dependency."); } private static void deleteBaseDirectory(String baseDirectory) { int retries = 0; while (true) { try { FileUtils.deleteDirectory(new File(baseDirectory)); break; } catch (Throwable t) { retries++; if (retries <= CHECK_TIMEOUT / CHECK_INTERVAL) { LOG.warn( String.format( "Failed to delete the working directory %s of the Python UDF worker. Retrying...", baseDirectory), t); } else { LOG.warn( String.format( "Failed to delete the working directory %s of the Python UDF worker.", baseDirectory), t); break; } } } } private void installRequirements(String baseDirectory, Map<String, String> env) throws IOException { // Directory for storing the installation result of the requirements file. String requirementsDirectory = String.join(File.separator, baseDirectory, PYTHON_REQUIREMENTS_DIR); if (dependencyInfo.getRequirementsFilePath().isPresent()) { LOG.info("Trying to pip install the Python requirements..."); PythonEnvironmentManagerUtils.pipInstallRequirements( dependencyInfo.getRequirementsFilePath().get(), dependencyInfo.getRequirementsCacheDir().orElse(null), requirementsDirectory, dependencyInfo.getPythonExec(), env); } } private void constructFilesDirectory(Map<String, String> env, String baseDirectory) throws IOException { // link or copy python files to filesDirectory and add them to PYTHONPATH List<String> pythonFilePaths = new ArrayList<>(); // Directory for storing the uploaded python files. String filesDirectory = String.join(File.separator, baseDirectory, PYTHON_FILES_DIR); for (Map.Entry<String, String> entry : dependencyInfo.getPythonFiles().entrySet()) { // The origin file name will be wiped when downloaded from the distributed cache, // restore the origin name to // make sure the python files could be imported. // The path of the restored python file will be as following: // ${baseDirectory}/${PYTHON_FILES_DIR}/${distributedCacheFileName}/${originFileName} String distributedCacheFileName = new File(entry.getKey()).getName(); String originFileName = entry.getValue(); Path target = FileSystems.getDefault() .getPath(filesDirectory, distributedCacheFileName, originFileName); if (!target.getParent().toFile().mkdirs()) { throw new IOException( String.format( "Could not create the directory: %s !", target.getParent().toString())); } Path src = FileSystems.getDefault().getPath(entry.getKey()); try { Files.createSymbolicLink(target, src); } catch (IOException e) { LOG.warn( String.format( "Could not create the symbolic link of: %s, the link path is %s, fallback to copy.", src, target), e); FileUtils.copy( new org.apache.flink.core.fs.Path(src.toUri()), new org.apache.flink.core.fs.Path(target.toUri()), false); } File pythonFile = new File(entry.getKey()); String pythonPath; if (pythonFile.isFile() && originFileName.endsWith(".py")) { // If the python file is file with suffix .py, add the parent directory to // PYTHONPATH. pythonPath = String.join(File.separator, filesDirectory, distributedCacheFileName); } else if (pythonFile.isFile() && originFileName.endsWith(".zip")) { // Expand the zip file and add the root directory to PYTHONPATH // as not all zip files are importable org.apache.flink.core.fs.Path targetDirectory = new org.apache.flink.core.fs.Path( filesDirectory, String.join( File.separator, distributedCacheFileName, originFileName.substring( 0, originFileName.lastIndexOf(".")))); FileUtils.expandDirectory( new org.apache.flink.core.fs.Path(pythonFile.getAbsolutePath()), targetDirectory); pythonPath = targetDirectory.toString(); } else { pythonPath = String.join( File.separator, filesDirectory, distributedCacheFileName, originFileName); } pythonFilePaths.add(pythonPath); } appendToPythonPath(env, pythonFilePaths); } private void constructRequirementsDirectory(Map<String, String> env, String baseDirectory) throws IOException { String requirementsDirectory = String.join(File.separator, baseDirectory, PYTHON_REQUIREMENTS_DIR); if (dependencyInfo.getRequirementsFilePath().isPresent()) { File requirementsDirectoryFile = new File(requirementsDirectory); if (!requirementsDirectoryFile.mkdirs()) { throw new IOException( String.format( "Creating the requirements target directory: %s failed!", requirementsDirectory)); } env.put(PYTHON_REQUIREMENTS_FILE, dependencyInfo.getRequirementsFilePath().get()); LOG.info( "Requirements.txt of python worker: {}", dependencyInfo.getRequirementsFilePath().get()); if (dependencyInfo.getRequirementsCacheDir().isPresent()) { env.put(PYTHON_REQUIREMENTS_CACHE, dependencyInfo.getRequirementsCacheDir().get()); LOG.info( "Requirements cache dir of python worker: {}", dependencyInfo.getRequirementsCacheDir().get()); } env.put(PYTHON_REQUIREMENTS_INSTALL_DIR, requirementsDirectory); LOG.info("Requirements install directory of python worker: {}", requirementsDirectory); } } private void constructArchivesDirectory(Map<String, String> env, String baseDirectory) throws IOException { // Directory for storing the extracted result of the archive files. String archivesDirectory = String.join(File.separator, baseDirectory, PYTHON_ARCHIVES_DIR); if (!dependencyInfo.getArchives().isEmpty()) { // set the archives directory as the working directory, then user could access the // content of the archives via relative path env.put(PYTHON_WORKING_DIR, archivesDirectory); LOG.info("Python working dir of python worker: {}", archivesDirectory); // extract archives to archives directory for (Map.Entry<String, String> entry : dependencyInfo.getArchives().entrySet()) { String srcFilePath = entry.getKey(); String originalFileName; String targetDirName; if (entry.getValue().contains(PARAM_DELIMITER)) { String[] filePathAndTargetDir = entry.getValue().split(PARAM_DELIMITER, 2); originalFileName = filePathAndTargetDir[0]; targetDirName = filePathAndTargetDir[1]; } else { originalFileName = entry.getValue(); targetDirName = originalFileName; } String targetDirPath = String.join(File.separator, archivesDirectory, targetDirName); CompressionUtils.extractFile(srcFilePath, targetDirPath, originalFileName); } } } private static void appendToPythonPath( Map<String, String> env, List<String> pythonDependencies) { if (pythonDependencies.isEmpty()) { return; } String pythonDependencyPath = String.join(File.pathSeparator, pythonDependencies); String pythonPath = env.get("PYTHONPATH"); if (Strings.isNullOrEmpty(pythonPath)) { env.put("PYTHONPATH", pythonDependencyPath); } else { env.put( "PYTHONPATH", String.join(File.pathSeparator, pythonDependencyPath, pythonPath)); } } private static final
AbstractPythonEnvironmentManager
java
bumptech__glide
annotation/compiler/test/src/test/resources/GlideExtensionOptionsTest/OverrideReplace/GlideOptions.java
{ "start": 1010, "end": 15219 }
class ____ extends RequestOptions implements Cloneable { private static GlideOptions fitCenterTransform0; private static GlideOptions centerInsideTransform1; private static GlideOptions centerCropTransform2; private static GlideOptions circleCropTransform3; private static GlideOptions noTransformation4; private static GlideOptions noAnimation5; /** * @see RequestOptions#sizeMultiplierOf(float) */ @CheckResult @NonNull public static GlideOptions sizeMultiplierOf(@FloatRange(from = 0.0, to = 1.0) float value) { return new GlideOptions().sizeMultiplier(value); } /** * @see RequestOptions#diskCacheStrategyOf(DiskCacheStrategy) */ @CheckResult @NonNull public static GlideOptions diskCacheStrategyOf(@NonNull DiskCacheStrategy strategy) { return new GlideOptions().diskCacheStrategy(strategy); } /** * @see RequestOptions#priorityOf(Priority) */ @CheckResult @NonNull public static GlideOptions priorityOf(@NonNull Priority priority) { return new GlideOptions().priority(priority); } /** * @see RequestOptions#placeholderOf(Drawable) */ @CheckResult @NonNull public static GlideOptions placeholderOf(@Nullable Drawable drawable) { return new GlideOptions().placeholder(drawable); } /** * @see RequestOptions#placeholderOf(int) */ @CheckResult @NonNull public static GlideOptions placeholderOf(@DrawableRes int id) { return new GlideOptions().placeholder(id); } /** * @see RequestOptions#errorOf(Drawable) */ @CheckResult @NonNull public static GlideOptions errorOf(@Nullable Drawable drawable) { return new GlideOptions().error(drawable); } /** * @see RequestOptions#errorOf(int) */ @CheckResult @NonNull public static GlideOptions errorOf(@DrawableRes int id) { return new GlideOptions().error(id); } /** * @see RequestOptions#skipMemoryCacheOf(boolean) */ @CheckResult @NonNull public static GlideOptions skipMemoryCacheOf(boolean skipMemoryCache) { return new GlideOptions().skipMemoryCache(skipMemoryCache); } /** * @see RequestOptions#overrideOf(int, int) */ @CheckResult @NonNull public static GlideOptions overrideOf(int width, int height) { return new GlideOptions().override(width, height); } /** * @see RequestOptions#overrideOf(int) */ @CheckResult @NonNull public static GlideOptions overrideOf(int size) { return new GlideOptions().override(size); } /** * @see RequestOptions#signatureOf(Key) */ @CheckResult @NonNull public static GlideOptions signatureOf(@NonNull Key key) { return new GlideOptions().signature(key); } /** * @see RequestOptions#fitCenterTransform() */ @CheckResult @NonNull public static GlideOptions fitCenterTransform() { if (GlideOptions.fitCenterTransform0 == null) { GlideOptions.fitCenterTransform0 = new GlideOptions().fitCenter().autoClone(); } return GlideOptions.fitCenterTransform0; } /** * @see RequestOptions#centerInsideTransform() */ @CheckResult @NonNull public static GlideOptions centerInsideTransform() { if (GlideOptions.centerInsideTransform1 == null) { GlideOptions.centerInsideTransform1 = new GlideOptions().centerInside().autoClone(); } return GlideOptions.centerInsideTransform1; } /** * @see RequestOptions#centerCropTransform() */ @CheckResult @NonNull public static GlideOptions centerCropTransform() { if (GlideOptions.centerCropTransform2 == null) { GlideOptions.centerCropTransform2 = new GlideOptions().centerCrop().autoClone(); } return GlideOptions.centerCropTransform2; } /** * @see RequestOptions#circleCropTransform() */ @CheckResult @NonNull public static GlideOptions circleCropTransform() { if (GlideOptions.circleCropTransform3 == null) { GlideOptions.circleCropTransform3 = new GlideOptions().circleCrop().autoClone(); } return GlideOptions.circleCropTransform3; } /** * @see RequestOptions#bitmapTransform(Transformation) */ @CheckResult @NonNull public static GlideOptions bitmapTransform(@NonNull Transformation<Bitmap> transformation) { return new GlideOptions().transform(transformation); } /** * @see RequestOptions#noTransformation() */ @CheckResult @NonNull public static GlideOptions noTransformation() { if (GlideOptions.noTransformation4 == null) { GlideOptions.noTransformation4 = new GlideOptions().dontTransform().autoClone(); } return GlideOptions.noTransformation4; } /** * @see RequestOptions#option(Option, T) */ @CheckResult @NonNull public static <T> GlideOptions option(@NonNull Option<T> option, @NonNull T t) { return new GlideOptions().set(option, t); } /** * @see RequestOptions#decodeTypeOf(Class) */ @CheckResult @NonNull public static GlideOptions decodeTypeOf(@NonNull Class<?> clazz) { return new GlideOptions().decode(clazz); } /** * @see RequestOptions#formatOf(DecodeFormat) */ @CheckResult @NonNull public static GlideOptions formatOf(@NonNull DecodeFormat format) { return new GlideOptions().format(format); } /** * @see RequestOptions#frameOf(long) */ @CheckResult @NonNull public static GlideOptions frameOf(@IntRange(from = 0) long value) { return new GlideOptions().frame(value); } /** * @see RequestOptions#downsampleOf(DownsampleStrategy) */ @CheckResult @NonNull public static GlideOptions downsampleOf(@NonNull DownsampleStrategy strategy) { return new GlideOptions().downsample(strategy); } /** * @see RequestOptions#timeoutOf(int) */ @CheckResult @NonNull public static GlideOptions timeoutOf(@IntRange(from = 0) int value) { return new GlideOptions().timeout(value); } /** * @see RequestOptions#encodeQualityOf(int) */ @CheckResult @NonNull public static GlideOptions encodeQualityOf(@IntRange(from = 0, to = 100) int value) { return new GlideOptions().encodeQuality(value); } /** * @see RequestOptions#encodeFormatOf(CompressFormat) */ @CheckResult @NonNull public static GlideOptions encodeFormatOf(@NonNull Bitmap.CompressFormat format) { return new GlideOptions().encodeFormat(format); } /** * @see RequestOptions#noAnimation() */ @CheckResult @NonNull public static GlideOptions noAnimation() { if (GlideOptions.noAnimation5 == null) { GlideOptions.noAnimation5 = new GlideOptions().dontAnimate().autoClone(); } return GlideOptions.noAnimation5; } @Override @NonNull @CheckResult public GlideOptions sizeMultiplier(@FloatRange(from = 0.0, to = 1.0) float value) { return (GlideOptions) super.sizeMultiplier(value); } @Override @NonNull @CheckResult public GlideOptions useUnlimitedSourceGeneratorsPool(boolean flag) { return (GlideOptions) super.useUnlimitedSourceGeneratorsPool(flag); } @Override @NonNull @CheckResult public GlideOptions useAnimationPool(boolean flag) { return (GlideOptions) super.useAnimationPool(flag); } @Override @NonNull @CheckResult public GlideOptions onlyRetrieveFromCache(boolean flag) { return (GlideOptions) super.onlyRetrieveFromCache(flag); } @Override @NonNull @CheckResult public GlideOptions diskCacheStrategy(@NonNull DiskCacheStrategy strategy) { return (GlideOptions) super.diskCacheStrategy(strategy); } @Override @NonNull @CheckResult public GlideOptions priority(@NonNull Priority priority) { return (GlideOptions) super.priority(priority); } @Override @NonNull @CheckResult public GlideOptions placeholder(@Nullable Drawable drawable) { return (GlideOptions) super.placeholder(drawable); } @Override @NonNull @CheckResult public GlideOptions placeholder(@DrawableRes int id) { return (GlideOptions) super.placeholder(id); } @Override @NonNull @CheckResult public GlideOptions fallback(@Nullable Drawable drawable) { return (GlideOptions) super.fallback(drawable); } @Override @NonNull @CheckResult public GlideOptions fallback(@DrawableRes int id) { return (GlideOptions) super.fallback(id); } @Override @NonNull @CheckResult public GlideOptions error(@Nullable Drawable drawable) { return (GlideOptions) super.error(drawable); } @Override @NonNull @CheckResult public GlideOptions error(@DrawableRes int id) { return (GlideOptions) super.error(id); } @Override @NonNull @CheckResult public GlideOptions theme(@Nullable Resources.Theme theme) { return (GlideOptions) super.theme(theme); } @Override @NonNull @CheckResult public GlideOptions skipMemoryCache(boolean skip) { return (GlideOptions) super.skipMemoryCache(skip); } @Override @NonNull @CheckResult public GlideOptions override(int width, int height) { return (GlideOptions) super.override(width, height); } @Override @NonNull @CheckResult public GlideOptions override(int size) { return (GlideOptions) super.override(size); } @Override @NonNull @CheckResult public GlideOptions signature(@NonNull Key key) { return (GlideOptions) super.signature(key); } @Override @CheckResult public GlideOptions clone() { return (GlideOptions) super.clone(); } @Override @NonNull @CheckResult public <Y> GlideOptions set(@NonNull Option<Y> option, @NonNull Y y) { return (GlideOptions) super.set(option, y); } @Override @NonNull @CheckResult public GlideOptions decode(@NonNull Class<?> clazz) { return (GlideOptions) super.decode(clazz); } @Override @NonNull @CheckResult public GlideOptions encodeFormat(@NonNull Bitmap.CompressFormat format) { return (GlideOptions) super.encodeFormat(format); } @Override @NonNull @CheckResult public GlideOptions encodeQuality(@IntRange(from = 0, to = 100) int value) { return (GlideOptions) super.encodeQuality(value); } @Override @NonNull @CheckResult public GlideOptions frame(@IntRange(from = 0) long value) { return (GlideOptions) super.frame(value); } @Override @NonNull @CheckResult public GlideOptions format(@NonNull DecodeFormat format) { return (GlideOptions) super.format(format); } @Override @NonNull @CheckResult public GlideOptions disallowHardwareConfig() { return (GlideOptions) super.disallowHardwareConfig(); } @Override @NonNull @CheckResult public GlideOptions downsample(@NonNull DownsampleStrategy strategy) { return (GlideOptions) super.downsample(strategy); } @Override @NonNull @CheckResult public GlideOptions timeout(@IntRange(from = 0) int value) { return (GlideOptions) super.timeout(value); } @Override @NonNull @CheckResult public GlideOptions optionalCenterCrop() { return (GlideOptions) super.optionalCenterCrop(); } @Override @NonNull @CheckResult public GlideOptions optionalFitCenter() { return (GlideOptions) super.optionalFitCenter(); } @Override @NonNull @CheckResult public GlideOptions fitCenter() { return (GlideOptions) super.fitCenter(); } @Override @NonNull @CheckResult public GlideOptions optionalCenterInside() { return (GlideOptions) super.optionalCenterInside(); } @Override @NonNull @CheckResult public GlideOptions centerInside() { return (GlideOptions) super.centerInside(); } @Override @NonNull @CheckResult public GlideOptions optionalCircleCrop() { return (GlideOptions) super.optionalCircleCrop(); } @Override @NonNull @CheckResult public GlideOptions circleCrop() { return (GlideOptions) super.circleCrop(); } @Override @NonNull @CheckResult public GlideOptions transform(@NonNull Transformation<Bitmap> transformation) { return (GlideOptions) super.transform(transformation); } @Override @SafeVarargs @SuppressWarnings("varargs") @NonNull @CheckResult public final GlideOptions transform(@NonNull Transformation<Bitmap>... transformations) { return (GlideOptions) super.transform(transformations); } @Override @SafeVarargs @SuppressWarnings("varargs") @Deprecated @NonNull @CheckResult public final GlideOptions transforms(@NonNull Transformation<Bitmap>... transformations) { return (GlideOptions) super.transforms(transformations); } @Override @NonNull @CheckResult public GlideOptions optionalTransform(@NonNull Transformation<Bitmap> transformation) { return (GlideOptions) super.optionalTransform(transformation); } @Override @NonNull @CheckResult public <Y> GlideOptions optionalTransform(@NonNull Class<Y> clazz, @NonNull Transformation<Y> transformation) { return (GlideOptions) super.optionalTransform(clazz, transformation); } @Override @NonNull @CheckResult public <Y> GlideOptions transform(@NonNull Class<Y> clazz, @NonNull Transformation<Y> transformation) { return (GlideOptions) super.transform(clazz, transformation); } @Override @NonNull @CheckResult public GlideOptions dontTransform() { return (GlideOptions) super.dontTransform(); } @Override @NonNull @CheckResult public GlideOptions dontAnimate() { return (GlideOptions) super.dontAnimate(); } @Override @NonNull @CheckResult public GlideOptions apply(@NonNull BaseRequestOptions<?> options) { return (GlideOptions) super.apply(options); } @Override @NonNull public GlideOptions lock() { return (GlideOptions) super.lock(); } @Override @NonNull public GlideOptions autoClone() { return (GlideOptions) super.autoClone(); } /** * @see Extension#centerCrop(BaseRequestOptions) */ @SuppressWarnings("unchecked") @CheckResult @NonNull public GlideOptions centerCrop() { return (GlideOptions) Extension.centerCrop(this); } /** * @see Extension#centerCrop(BaseRequestOptions) */ @CheckResult public static GlideOptions centerCropOf() { return new GlideOptions().centerCrop(); } }
GlideOptions
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/servlet/setup/RouterFunctionMockMvcBuilder.java
{ "start": 3613, "end": 10073 }
class ____ extends AbstractMockMvcBuilder<RouterFunctionMockMvcBuilder> { private final RouterFunction<?> routerFunction; private List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); private final List<MappedInterceptor> mappedInterceptors = new ArrayList<>(); private @Nullable List<HandlerExceptionResolver> handlerExceptionResolvers; private @Nullable Long asyncRequestTimeout; private @Nullable List<ViewResolver> viewResolvers; private @Nullable PathPatternParser patternParser; private Supplier<RouterFunctionMapping> handlerMappingFactory = RouterFunctionMapping::new; protected RouterFunctionMockMvcBuilder(RouterFunction<?>... routerFunctions) { Assert.notEmpty(routerFunctions, "RouterFunctions must not be empty"); this.routerFunction = Arrays.stream(routerFunctions).reduce(RouterFunction::andOther).orElseThrow(); } /** * Set the message converters to use in argument resolvers and in return value * handlers, which support reading and/or writing to the body of the request * and response. If no message converters are added to the list, a default * list of converters is added instead. */ public RouterFunctionMockMvcBuilder setMessageConverters(HttpMessageConverter<?>...messageConverters) { this.messageConverters = Arrays.asList(messageConverters); return this; } /** * Add interceptors mapped to all incoming requests. */ public RouterFunctionMockMvcBuilder addInterceptors(HandlerInterceptor... interceptors) { addMappedInterceptors(null, interceptors); return this; } /** * Add interceptors mapped to a set of path patterns. */ public RouterFunctionMockMvcBuilder addMappedInterceptors(String @Nullable [] pathPatterns, HandlerInterceptor... interceptors) { for (HandlerInterceptor interceptor : interceptors) { this.mappedInterceptors.add(new MappedInterceptor(pathPatterns, null, interceptor)); } return this; } /** * Set the HandlerExceptionResolver types to use as a list. */ public RouterFunctionMockMvcBuilder setHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { this.handlerExceptionResolvers = exceptionResolvers; return this; } /** * Set the HandlerExceptionResolver types to use as an array. */ public RouterFunctionMockMvcBuilder setHandlerExceptionResolvers(HandlerExceptionResolver... exceptionResolvers) { this.handlerExceptionResolvers = Arrays.asList(exceptionResolvers); return this; } /** * Configure the factory to create a custom {@link RequestMappingHandlerMapping}. * @param factory the factory */ public RouterFunctionMockMvcBuilder setCustomHandlerMapping(Supplier<RouterFunctionMapping> factory) { this.handlerMappingFactory = factory; return this; } /** * Set up view resolution with the given {@link ViewResolver ViewResolvers}. * <p>If not set, an {@link InternalResourceViewResolver} is used by default. */ public RouterFunctionMockMvcBuilder setViewResolvers(ViewResolver...resolvers) { this.viewResolvers = Arrays.asList(resolvers); return this; } /** * Set up a single {@link ViewResolver} that always returns the provided * view instance. * <p>This is a convenient shortcut if you need to use one {@link View} * instance only &mdash; for example, rendering generated content (JSON, XML, * Atom). */ public RouterFunctionMockMvcBuilder setSingleView(View view) { this.viewResolvers = Collections.singletonList(new StaticViewResolver(view)); return this; } /** * Specify the timeout value for async execution. * <p>In Spring MVC Test, this value is used to determine how long to wait * for async execution to complete so that a test can verify the results * synchronously. * @param timeout the timeout value in milliseconds */ public RouterFunctionMockMvcBuilder setAsyncRequestTimeout(long timeout) { this.asyncRequestTimeout = timeout; return this; } /** * Configure the parser to use for * {@link org.springframework.web.util.pattern.PathPattern PathPatterns}. * <p>By default, this is a default instance of {@link PathPatternParser}. * @param parser the parser to use */ public RouterFunctionMockMvcBuilder setPatternParser(@Nullable PathPatternParser parser) { this.patternParser = parser; return this; } @Override protected WebApplicationContext initWebAppContext() { MockServletContext servletContext = new MockServletContext(); StubWebApplicationContext wac = new StubWebApplicationContext(servletContext); registerRouterFunction(wac); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); return wac; } private void registerRouterFunction(StubWebApplicationContext wac) { HandlerFunctionConfiguration config = new HandlerFunctionConfiguration(); config.setApplicationContext(wac); ServletContext sc = wac.getServletContext(); wac.addBean("routerFunction", this.routerFunction); FormattingConversionService mvcConversionService = config.mvcConversionService(); wac.addBean("mvcConversionService", mvcConversionService); ResourceUrlProvider resourceUrlProvider = config.mvcResourceUrlProvider(); wac.addBean("mvcResourceUrlProvider", resourceUrlProvider); ContentNegotiationManager mvcContentNegotiationManager = config.mvcContentNegotiationManager(); wac.addBean("mvcContentNegotiationManager", mvcContentNegotiationManager); RouterFunctionMapping hm = config.getHandlerMapping(mvcConversionService, resourceUrlProvider); if (sc != null) { hm.setServletContext(sc); } hm.setApplicationContext(wac); hm.afterPropertiesSet(); wac.addBean("routerFunctionMapping", hm); HandlerFunctionAdapter ha = config.handlerFunctionAdapter(); wac.addBean("handlerFunctionAdapter", ha); wac.addBean("handlerExceptionResolver", config.handlerExceptionResolver(mvcContentNegotiationManager)); wac.addBeans(initViewResolvers(wac)); } private List<ViewResolver> initViewResolvers(WebApplicationContext wac) { this.viewResolvers = (this.viewResolvers != null ? this.viewResolvers : Collections.singletonList(new InternalResourceViewResolver())); for (Object viewResolver : this.viewResolvers) { if (viewResolver instanceof WebApplicationObjectSupport support) { support.setApplicationContext(wac); } } return this.viewResolvers; } /** Using the MVC Java configuration as the starting point for the "standalone" setup. */ private
RouterFunctionMockMvcBuilder
java
apache__camel
components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/client/impl/KinesisAsyncClientSessionTokenImpl.java
{ "start": 1895, "end": 5325 }
class ____ implements KinesisAsyncInternalClient { private static final Logger LOG = LoggerFactory.getLogger(KinesisAsyncClientSessionTokenImpl.class); private Kinesis2Configuration configuration; /** * Constructor that uses the config file. */ public KinesisAsyncClientSessionTokenImpl(Kinesis2Configuration configuration) { LOG.trace("Creating an AWS Async Kinesis manager using static credentials."); this.configuration = configuration; } /** * Getting the Kinesis Async client that is used. * * @return Amazon Kinesis Async Client. */ @Override public KinesisAsyncClient getKinesisAsyncClient() { var clientBuilder = KinesisAsyncClient.builder(); var isClientConfigFound = false; SdkAsyncHttpClient.Builder httpClientBuilder = null; if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) { var proxyConfig = ProxyConfiguration .builder() .scheme(configuration.getProxyProtocol().toString()) .host(configuration.getProxyHost()) .port(configuration.getProxyPort()) .build(); httpClientBuilder = NettyNioAsyncHttpClient .builder() .proxyConfiguration(proxyConfig); isClientConfigFound = true; } if (Objects.nonNull(configuration.getAccessKey()) && Objects.nonNull(configuration.getSecretKey()) && Objects.nonNull(configuration.getSessionToken())) { var 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(null); } } 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 = NettyNioAsyncHttpClient.builder(); } SdkAsyncHttpClient 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); } return clientBuilder.build(); } }
KinesisAsyncClientSessionTokenImpl
java
spring-projects__spring-framework
spring-core-test/src/test/java/org/springframework/core/test/tools/TestCompilerTests.java
{ "start": 2543, "end": 3917 }
class ____ implements Supplier<String> { @Deprecated public String get() { return "Hello Deprecated"; } } """; @Test @SuppressWarnings("unchecked") void compileWhenHasDifferentClassesWithSameClassNameCompilesBoth() { TestCompiler.forSystem().withSources(SourceFile.of(HELLO_WORLD)).compile( compiled -> { Supplier<String> supplier = compiled.getInstance(Supplier.class, "com.example.Hello"); assertThat(supplier.get()).isEqualTo("Hello World!"); }); TestCompiler.forSystem().withSources(SourceFile.of(HELLO_SPRING)).compile( compiled -> { Supplier<String> supplier = compiled.getInstance(Supplier.class, "com.example.Hello"); assertThat(supplier.get()).isEqualTo("Hello Spring!"); }); } @Test void compileAndGetSourceFile() { TestCompiler.forSystem().withSources(SourceFile.of(HELLO_SPRING)).compile( compiled -> assertThat(compiled.getSourceFile()).contains("// !!")); } @Test void compileWhenSourceHasCompileErrors() { assertThatExceptionOfType(CompilationException.class).isThrownBy( () -> TestCompiler.forSystem().withSources( SourceFile.of(HELLO_BAD)).compile(compiled -> { })); } @Test @SuppressWarnings("unchecked") void compileWhenSourceUseDeprecateCodeAndNoOptionSet() { SourceFile main = SourceFile.of(""" package com.example; public
Hello
java
apache__flink
flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/api/java/hadoop/mapred/wrapper/HadoopInputSplit.java
{ "start": 1453, "end": 4814 }
class ____ extends LocatableInputSplit { private static final long serialVersionUID = -6990336376163226160L; private final Class<? extends org.apache.hadoop.mapred.InputSplit> splitType; private transient org.apache.hadoop.mapred.InputSplit hadoopInputSplit; @Nullable private transient JobConf jobConf; public HadoopInputSplit( int splitNumber, org.apache.hadoop.mapred.InputSplit hInputSplit, @Nullable JobConf jobconf) { super(splitNumber, (String) null); if (hInputSplit == null) { throw new NullPointerException("Hadoop input split must not be null"); } if (needsJobConf(hInputSplit) && jobconf == null) { throw new NullPointerException( "Hadoop JobConf must not be null when input split is configurable."); } this.splitType = hInputSplit.getClass(); this.jobConf = jobconf; this.hadoopInputSplit = hInputSplit; } // ------------------------------------------------------------------------ // Properties // ------------------------------------------------------------------------ @Override public String[] getHostnames() { try { return this.hadoopInputSplit.getLocations(); } catch (IOException e) { return new String[0]; } } public org.apache.hadoop.mapred.InputSplit getHadoopInputSplit() { return hadoopInputSplit; } public JobConf getJobConf() { return jobConf; } // ------------------------------------------------------------------------ // Serialization // ------------------------------------------------------------------------ private void writeObject(ObjectOutputStream out) throws IOException { // serialize the parent fields and the final fields out.defaultWriteObject(); if (needsJobConf(hadoopInputSplit)) { // the job conf knows how to serialize itself // noinspection ConstantConditions jobConf.write(out); } // write the input split hadoopInputSplit.write(out); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read the parent fields and the final fields in.defaultReadObject(); try { hadoopInputSplit = (org.apache.hadoop.mapred.InputSplit) WritableFactories.newInstance(splitType); } catch (Exception e) { throw new RuntimeException("Unable to instantiate Hadoop InputSplit", e); } if (needsJobConf(hadoopInputSplit)) { // the job conf knows how to deserialize itself jobConf = new JobConf(); jobConf.readFields(in); if (hadoopInputSplit instanceof Configurable) { ((Configurable) hadoopInputSplit).setConf(this.jobConf); } else if (hadoopInputSplit instanceof JobConfigurable) { ((JobConfigurable) hadoopInputSplit).configure(this.jobConf); } } hadoopInputSplit.readFields(in); } private static boolean needsJobConf(org.apache.hadoop.mapred.InputSplit split) { return split instanceof Configurable || split instanceof JobConfigurable; } }
HadoopInputSplit
java
apache__rocketmq
common/src/test/java/org/apache/rocketmq/common/message/MessageTest.java
{ "start": 989, "end": 2292 }
class ____ { @Test(expected = RuntimeException.class) public void putUserPropertyWithRuntimeException() throws Exception { Message m = new Message(); m.putUserProperty(PROPERTY_TRACE_SWITCH, ""); } @Test(expected = IllegalArgumentException.class) public void putUserNullValuePropertyWithException() throws Exception { Message m = new Message(); m.putUserProperty("prop1", null); } @Test(expected = IllegalArgumentException.class) public void putUserEmptyValuePropertyWithException() throws Exception { Message m = new Message(); m.putUserProperty("prop1", " "); } @Test(expected = IllegalArgumentException.class) public void putUserNullNamePropertyWithException() throws Exception { Message m = new Message(); m.putUserProperty(null, "val1"); } @Test(expected = IllegalArgumentException.class) public void putUserEmptyNamePropertyWithException() throws Exception { Message m = new Message(); m.putUserProperty(" ", "val1"); } @Test public void putUserProperty() throws Exception { Message m = new Message(); m.putUserProperty("prop1", "val1"); Assert.assertEquals("val1", m.getUserProperty("prop1")); } }
MessageTest
java
google__dagger
javatests/dagger/internal/codegen/MapRequestRepresentationTest.java
{ "start": 5179, "end": 5972 }
interface ____ {", " UsesInaccessible usesInaccessible();", "}"); Compilation compilation = daggerCompilerWithoutGuava().compile(module, inaccessible, usesInaccessible, componentFile); assertThat(compilation).succeeded(); assertThat(compilation) .generatedSourceFile("test.DaggerTestComponent") .hasSourceEquivalentTo(goldenFileRule.goldenFile("test.DaggerTestComponent")); } @Test public void subcomponentOmitsInheritedBindings() throws Exception { JavaFileObject parent = JavaFileObjects.forSourceLines( "test.Parent", "package test;", "", "import dagger.Component;", "", "@Component(modules = ParentModule.class)", "
TestComponent
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest110.java
{ "start": 804, "end": 1142 }
class ____ extends TestCase { public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); provider.getConfig().setCommentAllow(false); String sql = "select * from t where id = ? or 1 NOT between 79 and 126"; assertFalse(provider.checkValid(sql)); } }
MySqlWallTest110
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/typesafe/Machine.java
{ "start": 107, "end": 474 }
class ____ { public Integer ping = 1; private MachineStatus status; public Machine setStatus(MachineStatus status) { this.status = status; return this; } public MachineStatus getStatus() { return status; } public List<String> getNames(int pings) { return Collections.singletonList("ping"); } }
Machine
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/bindings/inherited/InheritedBindingOnInterceptorTest.java
{ "start": 1495, "end": 1710 }
class ____ { void doSomething() { } } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @InterceptorBinding @Inherited @
MyBean
java
apache__logging-log4j2
log4j-1.2-api/src/test/java/org/apache/log4j/BasicConfiguratorTest.java
{ "start": 953, "end": 1785 }
class ____ { @Test void testConfigure() { // TODO More... BasicConfigurator.configure(); } @Test void testResetConfiguration() { // TODO More... BasicConfigurator.resetConfiguration(); } @Test void testConfigureAppender() { BasicConfigurator.configure(null); // TODO More... } @Test void testConfigureConsoleAppender() { // TODO What to do? Map to Log4j 2 Appender deeper in the code? BasicConfigurator.configure(new ConsoleAppender()); } @Test void testConfigureNullAppender() { // The NullAppender name is null and we do not want an NPE when the name is used as a key in a // ConcurrentHashMap. BasicConfigurator.configure(NullAppender.getNullAppender()); } }
BasicConfiguratorTest
java
google__dagger
javatests/dagger/internal/codegen/InjectConstructorFactoryGeneratorTest.java
{ "start": 50587, "end": 50793 }
interface ____ {}"); Source differentPackageInterface = CompilerTests.javaSource( "other.pkg.CommonName", "package other.pkg;", "", "public
CommonName
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/internal/Byte2DArrays.java
{ "start": 845, "end": 6113 }
class ____ { private static final Byte2DArrays INSTANCE = new Byte2DArrays(); /** * Returns the singleton instance of this class. * @return the singleton instance of this class. */ public static Byte2DArrays instance() { return INSTANCE; } private Arrays2D arrays = Arrays2D.instance(); // TODO reduce the visibility of the fields annotated with @VisibleForTesting Failures failures = Failures.instance(); // TODO reduce the visibility of the fields annotated with @VisibleForTesting public void setArrays(Arrays2D arrays) { this.arrays = arrays; } /** * Asserts that the given array is {@code null} or empty. * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is not {@code null} *and* contains one or more elements. */ public void assertNullOrEmpty(AssertionInfo info, byte[][] actual) { arrays.assertNullOrEmpty(info, failures, actual); } /** * Asserts that the given array is empty. * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is {@code null}. * @throws AssertionError if the given array is not empty. */ public void assertEmpty(AssertionInfo info, byte[][] actual) { arrays.assertEmpty(info, failures, actual); } /** * Asserts that the given array is not empty. * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is {@code null}. * @throws AssertionError if the given array is empty. */ public void assertNotEmpty(AssertionInfo info, byte[][] actual) { arrays.assertNotEmpty(info, failures, actual); } /** * Asserts that the number of elements in the given array is equal to the expected one. * * @param info contains information about the assertion. * @param actual the given array. * @param expectedFirstDimension the expected first dimension size of {@code actual}. * @param expectedSecondDimension the expected second dimension size of {@code actual}. * @throws AssertionError if the given array is {@code null}. * @throws AssertionError if the actual array's dimensions are not equal to the given ones. */ public void assertHasDimensions(AssertionInfo info, byte[][] actual, int expectedFirstDimension, int expectedSecondDimension) { arrays.assertHasDimensions(info, failures, actual, expectedFirstDimension, expectedSecondDimension); } /** * Assert that the actual array has the same dimensions as the other array. * @param info contains information about the assertion. * @param actual the given array. * @param other the group to compare * @throws AssertionError if the actual group is {@code null}. * @throws AssertionError if the other group is {@code null}. * @throws AssertionError if the actual group does not have the same dimension. */ public void assertHasSameDimensionsAs(AssertionInfo info, byte[][] actual, Object other) { arrays.assertHasSameDimensionsAs(info, actual, other); } /** * Asserts that the number of rows in the given array is equal to the expected one. * * @param info contains information about the assertion. * @param actual the given array. * @param expectedNumberOfRows the expected first dimension size of {@code actual}. */ public void assertNumberOfRows(AssertionInfo info, byte[][] actual, int expectedNumberOfRows) { arrays.assertNumberOfRows(info, failures, actual, expectedNumberOfRows); } /** * Verifies that the given array contains the given value at the given index. * @param info contains information about the assertion. * @param actual the given array. * @param value the value to look for. * @param index the index where the value should be stored in the given array. * @throws AssertionError if the given array is {@code null} or empty. * @throws NullPointerException if the given {@code Index} is {@code null}. * @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of the given * array. * @throws AssertionError if the given array does not contain the given value at the given index. */ public void assertContains(AssertionInfo info, byte[][] actual, byte[] value, Index index) { arrays.assertContains(info, failures, actual, value, index); } /** * Verifies that the given array does not contain the given value at the given index. * @param info contains information about the assertion. * @param actual the given array. * @param value the value to look for. * @param index the index where the value should be stored in the given array. * @throws AssertionError if the given array is {@code null}. * @throws NullPointerException if the given {@code Index} is {@code null}. * @throws AssertionError if the given array contains the given value at the given index. */ public void assertDoesNotContain(AssertionInfo info, byte[][] actual, byte[] value, Index index) { arrays.assertDoesNotContain(info, failures, actual, value, index); } }
Byte2DArrays
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableTimestampTest.java
{ "start": 1171, "end": 4848 }
class ____ extends RxJavaTest { Subscriber<Object> subscriber; @Before public void before() { subscriber = TestHelper.mockSubscriber(); } @Test public void timestampWithScheduler() { TestScheduler scheduler = new TestScheduler(); PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<Timed<Integer>> m = source.timestamp(scheduler); m.subscribe(subscriber); source.onNext(1); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); source.onNext(2); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); source.onNext(3); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber, times(1)).onNext(new Timed<>(1, 0, TimeUnit.MILLISECONDS)); inOrder.verify(subscriber, times(1)).onNext(new Timed<>(2, 100, TimeUnit.MILLISECONDS)); inOrder.verify(subscriber, times(1)).onNext(new Timed<>(3, 200, TimeUnit.MILLISECONDS)); verify(subscriber, never()).onError(any(Throwable.class)); verify(subscriber, never()).onComplete(); } @Test public void timestampWithScheduler2() { TestScheduler scheduler = new TestScheduler(); PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<Timed<Integer>> m = source.timestamp(scheduler); m.subscribe(subscriber); source.onNext(1); source.onNext(2); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); source.onNext(3); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber, times(1)).onNext(new Timed<>(1, 0, TimeUnit.MILLISECONDS)); inOrder.verify(subscriber, times(1)).onNext(new Timed<>(2, 0, TimeUnit.MILLISECONDS)); inOrder.verify(subscriber, times(1)).onNext(new Timed<>(3, 200, TimeUnit.MILLISECONDS)); verify(subscriber, never()).onError(any(Throwable.class)); verify(subscriber, never()).onComplete(); } @Test public void timeIntervalDefault() { final TestScheduler scheduler = new TestScheduler(); RxJavaPlugins.setComputationSchedulerHandler(new Function<Scheduler, Scheduler>() { @Override public Scheduler apply(Scheduler v) throws Exception { return scheduler; } }); try { Flowable.range(1, 5) .timestamp() .map(new Function<Timed<Integer>, Long>() { @Override public Long apply(Timed<Integer> v) throws Exception { return v.time(); } }) .test() .assertResult(0L, 0L, 0L, 0L, 0L); } finally { RxJavaPlugins.reset(); } } @Test public void timeIntervalDefaultSchedulerCustomUnit() { final TestScheduler scheduler = new TestScheduler(); RxJavaPlugins.setComputationSchedulerHandler(new Function<Scheduler, Scheduler>() { @Override public Scheduler apply(Scheduler v) throws Exception { return scheduler; } }); try { Flowable.range(1, 5) .timestamp(TimeUnit.SECONDS) .map(new Function<Timed<Integer>, Long>() { @Override public Long apply(Timed<Integer> v) throws Exception { return v.time(); } }) .test() .assertResult(0L, 0L, 0L, 0L, 0L); } finally { RxJavaPlugins.reset(); } } }
FlowableTimestampTest
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/net/ssl/MemoryPasswordProvider.java
{ "start": 1370, "end": 1884 }
class ____ implements PasswordProvider { private final char[] password; public MemoryPasswordProvider(final char[] chars) { if (chars != null) { password = chars.clone(); } else { password = null; } } @Override public char[] getPassword() { if (password == null) { return null; } return password.clone(); } public void clearSecrets() { Arrays.fill(password, '\0'); } }
MemoryPasswordProvider
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/async/TestRouterAsyncErasureCoding.java
{ "start": 2987, "end": 9028 }
class ____ { private static Configuration routerConf; /** Federated HDFS cluster. */ private static MiniRouterDFSCluster cluster; private static String ns0; /** Random Router for this federated cluster. */ private MiniRouterDFSCluster.RouterContext router; private FileSystem routerFs; private RouterRpcServer routerRpcServer; private AsyncErasureCoding asyncErasureCoding; private final String testfilePath = "/testdir/testAsyncErasureCoding.file"; @BeforeAll public static void setUpCluster() throws Exception { cluster = new MiniRouterDFSCluster(true, 1, 2, DEFAULT_HEARTBEAT_INTERVAL_MS, 1000); cluster.setNumDatanodesPerNameservice(3); cluster.setRacks( new String[] {"/rack1", "/rack2", "/rack3"}); cluster.startCluster(); // Making one Namenode active per nameservice if (cluster.isHighAvailability()) { for (String ns : cluster.getNameservices()) { cluster.switchToActive(ns, NAMENODES[0]); cluster.switchToStandby(ns, NAMENODES[1]); } } // Start routers with only an RPC service routerConf = new RouterConfigBuilder() .rpc() .build(); // Reduce the number of RPC clients threads to overload the Router easy routerConf.setInt(RBFConfigKeys.DFS_ROUTER_CLIENT_THREADS_SIZE, 1); routerConf.setInt(DFS_ROUTER_ASYNC_RPC_HANDLER_COUNT_KEY, 1); routerConf.setInt(DFS_ROUTER_ASYNC_RPC_RESPONDER_COUNT_KEY, 1); // We decrease the DN cache times to make the test faster routerConf.setTimeDuration( RBFConfigKeys.DN_REPORT_CACHE_EXPIRE, 1, TimeUnit.SECONDS); cluster.addRouterOverrides(routerConf); // Start routers with only an RPC service cluster.startRouters(); // Register and verify all NNs with all routers cluster.registerNamenodes(); cluster.waitNamenodeRegistration(); cluster.waitActiveNamespaces(); ns0 = cluster.getNameservices().get(0); } @AfterAll public static void shutdownCluster() throws Exception { if (cluster != null) { cluster.shutdown(); } } @BeforeEach public void setUp() throws IOException { router = cluster.getRandomRouter(); routerFs = router.getFileSystem(); routerRpcServer = router.getRouterRpcServer(); routerRpcServer.initAsyncThreadPools(routerConf); RouterAsyncRpcClient asyncRpcClient = new RouterAsyncRpcClient( routerConf, router.getRouter(), routerRpcServer.getNamenodeResolver(), routerRpcServer.getRPCMonitor(), routerRpcServer.getRouterStateIdContext()); RouterRpcServer spy = Mockito.spy(routerRpcServer); Mockito.when(spy.getRPCClient()).thenReturn(asyncRpcClient); asyncErasureCoding = new AsyncErasureCoding(spy); // Create mock locations MockResolver resolver = (MockResolver) router.getRouter().getSubclusterResolver(); resolver.addLocation("/", ns0, "/"); FsPermission permission = new FsPermission("705"); routerFs.mkdirs(new Path("/testdir"), permission); FSDataOutputStream fsDataOutputStream = routerFs.create( new Path(testfilePath), true); fsDataOutputStream.write(new byte[1024]); fsDataOutputStream.close(); } @AfterEach public void tearDown() throws IOException { // clear client context CallerContext.setCurrent(null); boolean delete = routerFs.delete(new Path("/testdir")); assertTrue(delete); if (routerFs != null) { routerFs.close(); } } @Test public void testRouterAsyncErasureCoding() throws Exception { String ecPolicyName = StripedFileTestUtil.getDefaultECPolicy().getName(); HdfsFileStatus fileInfo = cluster.getNamenodes().get(0).getClient().getFileInfo(testfilePath); assertNotNull(fileInfo); asyncErasureCoding.setErasureCodingPolicy("/testdir", ecPolicyName); syncReturn(null); asyncErasureCoding.getErasureCodingPolicy("/testdir"); ErasureCodingPolicy ecPolicy = syncReturn(ErasureCodingPolicy.class); assertEquals(StripedFileTestUtil.getDefaultECPolicy().getName(), ecPolicy.getName()); asyncErasureCoding.getErasureCodingPolicies(); ErasureCodingPolicyInfo[] erasureCodingPolicies = syncReturn(ErasureCodingPolicyInfo[].class); int numECPolicies = erasureCodingPolicies.length; ErasureCodingPolicyInfo[] erasureCodingPoliciesFromNameNode = cluster.getNamenodes().get(0).getClient().getErasureCodingPolicies(); assertArrayEquals(erasureCodingPoliciesFromNameNode, erasureCodingPolicies); asyncErasureCoding.getErasureCodingCodecs(); Map<String, String> erasureCodingCodecs = syncReturn(Map.class); Map<String, String> erasureCodingCodecsFromNameNode = cluster.getNamenodes().get(0).getClient().getErasureCodingCodecs(); assertEquals(erasureCodingCodecs, erasureCodingCodecsFromNameNode); // RS-12-4-1024k final ECSchema schema = new ECSchema("rs", 12, 4); ErasureCodingPolicy erasureCodingPolicy = new ErasureCodingPolicy(schema, 1024 * 1024); asyncErasureCoding.addErasureCodingPolicies(new ErasureCodingPolicy[]{erasureCodingPolicy}); AddErasureCodingPolicyResponse[] response = syncReturn(AddErasureCodingPolicyResponse[].class); assertEquals(response[0].isSucceed(), true); asyncErasureCoding.getErasureCodingPolicies(); ErasureCodingPolicyInfo[] erasureCodingPolicies2 = syncReturn(ErasureCodingPolicyInfo[].class); int numNewECPolicies = erasureCodingPolicies2.length; assertEquals(numECPolicies + 1, numNewECPolicies); asyncErasureCoding.getECTopologyResultForPolicies( new String[]{"RS-6-3-1024k", "RS-12-4-1024k"}); ECTopologyVerifierResult ecTResultForPolicies = syncReturn(ECTopologyVerifierResult.class); assertEquals(false, ecTResultForPolicies.isSupported()); asyncErasureCoding.getECTopologyResultForPolicies( new String[]{"XOR-2-1-1024k"}); ECTopologyVerifierResult ecTResultForPolicies2 = syncReturn(ECTopologyVerifierResult.class); assertEquals(true, ecTResultForPolicies2.isSupported()); } }
TestRouterAsyncErasureCoding
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DistinctVarargsCheckerTest.java
{ "start": 6606, "end": 7243 }
class ____ { void testFunction() { int first = 1, second = 2; Set.of(first, first); ImmutableSet.of(first, first); ImmutableSet.of(first, first, second); ImmutableSortedSet.of(first, first); ImmutableSortedSet.of(first, first, second); } } """) .addOutputLines( "Test.java", """ import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import java.util.Set; public
Test