language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest34.java
{ "start": 1016, "end": 2379 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "CREATE TABLE lookup" + " (id INT, INDEX USING BTREE (id))" + " CHECKSUM = 1;"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("lookup"))); String output = SQLUtils.toMySqlString(stmt); assertEquals("CREATE TABLE lookup (" + "\n\tid INT," + "\n\tINDEX USING BTREE(id)" + "\n) CHECKSUM = 1;", output); } }
MySqlCreateTableTest34
java
apache__flink
flink-queryable-state/flink-queryable-state-runtime/src/test/java/org/apache/flink/queryablestate/itcases/AbstractQueryableStateTestBase.java
{ "start": 51169, "end": 52498 }
class ____ extends AbstractStreamOperator<String> implements OneInputStreamOperator<Tuple2<Integer, Long>, String> { private static final long serialVersionUID = 1L; private final AggregatingStateDescriptor<Tuple2<Integer, Long>, String, String> stateDescriptor; private transient AggregatingState<Tuple2<Integer, Long>, String> state; AggregatingTestOperator( AggregatingStateDescriptor<Tuple2<Integer, Long>, String, String> stateDesc) { this.stateDescriptor = stateDesc; } @Override public void open() throws Exception { super.open(); this.state = getKeyedStateBackend() .getPartitionedState( VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, stateDescriptor); } @Override public void processElement(StreamRecord<Tuple2<Integer, Long>> element) throws Exception { state.add(element.getValue()); } } /** * Test {@link AggregateFunction} concatenating the already stored string with the long passed * as argument. */ private static
AggregatingTestOperator
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ChunkEndpointBuilderFactory.java
{ "start": 14971, "end": 15283 }
class ____ extends AbstractEndpointBuilder implements ChunkEndpointBuilder, AdvancedChunkEndpointBuilder { public ChunkEndpointBuilderImpl(String path) { super(componentName, path); } } return new ChunkEndpointBuilderImpl(path); } }
ChunkEndpointBuilderImpl
java
elastic__elasticsearch
libs/tdigest/src/test/java/org/elasticsearch/tdigest/ScaleFunctionTests.java
{ "start": 1225, "end": 12850 }
class ____ extends ESTestCase { public void asinApproximation() { for (double x = 0; x < 1; x += 1e-4) { assertEquals(Math.asin(x), ScaleFunction.fastAsin(x), 1e-6); } assertEquals(Math.asin(1), ScaleFunction.fastAsin(1), 0); assertTrue(Double.isNaN(ScaleFunction.fastAsin(1.0001))); } /** * Test that the basic single pass greedy t-digest construction has expected behavior with all scale functions. * <p> * This also throws off a diagnostic file that can be visualized if desired under the name of * scale-function-sizes.csv */ public void testSize() { for (double compression : new double[] { 20, 50, 100, 200, 500, 1000, 2000 }) { for (double n : new double[] { 10, 20, 50, 100, 200, 500, 1_000, 10_000, 100_000 }) { Map<String, Integer> clusterCount = new HashMap<>(); for (ScaleFunction k : ScaleFunction.values()) { if (k.toString().equals("K_0")) { continue; } double k0 = k.k(0, compression, n); int m = 0; for (int i = 0; i < n;) { int cnt = 1; while (i + cnt < n && k.k((i + cnt + 1.0) / (n - 1.0), compression, n) - k0 < 1) { cnt++; } double size = n * max(k.max(i / (n - 1), compression, n), k.max((i + cnt) / (n - 1.0), compression, n)); // check that we didn't cross the midline (which makes the size limit very conservative) double left = i - (n - 1) / 2; double right = i + cnt - (n - 1) / 2; boolean sameSide = left * right > 0; if (k.toString().endsWith("NO_NORM") == false && sameSide) { assertTrue(cnt == 1 || cnt <= max(1.1 * size, size + 1)); } i += cnt; k0 = k.k(i / (n - 1), compression, n); m++; } clusterCount.put(k.toString(), m); if (k.toString().endsWith("NO_NORM") == false) { assertTrue( String.format(Locale.ROOT, "%s %d, %.0f", k, m, compression), n < 3 * compression || (m >= compression / 3 && m <= compression) ); } } // make sure that the approximate version gets same results assertEquals(clusterCount.get("K_1"), clusterCount.get("K_1_FAST")); } } } /** * Validates the bounds on the shape of the different scale functions. The basic idea is * that diff difference between minimum and maximum values of k in the region where we * can have centroids with >1 sample should be small enough to meet the size limit of * the digest, but not small enough to degrade accuracy. */ public void testK() { for (ScaleFunction k : ScaleFunction.values()) { if (k.name().contains("NO_NORM")) { continue; } if (k.name().contains("K_0")) { continue; } for (double compression : new double[] { 50, 100, 200, 500, 1000 }) { for (int n : new int[] { 10, 100, 1000, 10000, 100000, 1_000_000, 10_000_000 }) { // first confirm that the shortcut (with norm) and the full version agree double norm = k.normalizer(compression, n); for (double q : new double[] { 0.0001, 0.001, 0.01, 0.1, 0.2, 0.5 }) { if (q * n > 1) { assertEquals( String.format(Locale.ROOT, "%s q: %.4f, compression: %.0f, n: %d", k, q, compression, n), k.k(q, compression, n), k.k(q, norm), 1e-10 ); assertEquals( String.format(Locale.ROOT, "%s q: %.4f, compression: %.0f, n: %d", k, q, compression, n), k.k(1 - q, compression, n), k.k(1 - q, norm), 1e-10 ); } } // now estimate the number of centroids double mink = Double.POSITIVE_INFINITY; double maxk = Double.NEGATIVE_INFINITY; double singletons = 0; while (singletons < n / 2.0) { // could we group more than one sample? double diff2 = k.k((singletons + 2.0) / n, norm) - k.k(singletons / n, norm); if (diff2 < 1) { // yes! double q = singletons / n; mink = Math.min(mink, k.k(q, norm)); maxk = Math.max(maxk, k.k(1 - q, norm)); break; } singletons++; } // did we consume all the data with singletons? if (Double.isInfinite(mink) || Double.isInfinite(maxk)) { // just make sure of this assertEquals(n, 2 * singletons, 0); mink = 0; maxk = 0; } // estimate number of clusters. The real number would be a bit more than this double diff = maxk - mink + 2 * singletons; // mustn't have too many String label = String.format( Locale.ROOT, "max diff: %.3f, scale: %s, compression: %.0f, n: %d", diff, k, compression, n ); assertTrue(label, diff <= Math.min(n, compression / 2 + 10)); // nor too few. This is where issue #151 shows up label = String.format(Locale.ROOT, "min diff: %.3f, scale: %s, compression: %.0f, n: %d", diff, k, compression, n); assertTrue(label, diff >= Math.min(n, compression / 4)); } } } } public void testNonDecreasing() { for (ScaleFunction scale : ScaleFunction.values()) { for (double compression : new double[] { 20, 50, 100, 200, 500, 1000 }) { for (int n : new int[] { 10, 100, 1000, 10000, 100_000, 1_000_000, 10_000_000 }) { double norm = scale.normalizer(compression, n); double last = Double.NEGATIVE_INFINITY; for (double q = -1; q < 2; q += 0.01) { double k1 = scale.k(q, norm); double k2 = scale.k(q, compression, n); String remark = String.format( Locale.ROOT, "Different ways to compute scale function %s should agree, " + "compression=%.0f, n=%d, q=%.2f", scale, compression, n, q ); assertEquals(remark, k1, k2, 1e-10); assertTrue(String.format(Locale.ROOT, "Scale %s function should not decrease", scale), k1 >= last); last = k1; } last = Double.NEGATIVE_INFINITY; for (double k = scale.q(0, norm) - 2; k < scale.q(1, norm) + 2; k += 0.01) { double q1 = scale.q(k, norm); double q2 = scale.q(k, compression, n); String remark = String.format( Locale.ROOT, "Different ways to compute inverse scale function %s should agree, " + "compression=%.0f, n=%d, q=%.2f", scale, compression, n, k ); assertEquals(remark, q1, q2, 1e-10); assertTrue(String.format(Locale.ROOT, "Inverse scale %s function should not decrease", scale), q1 >= last); last = q1; } } } } } /** * Validates the fast asin approximation */ public void testApproximation() { double worst = 0; double old = Double.NEGATIVE_INFINITY; for (double x = -1; x < 1; x += 0.00001) { double ex = Math.asin(x); double actual = ScaleFunction.fastAsin(x); double error = ex - actual; // System.out.printf("%.8f, %.8f, %.8f, %.12f\n", x, ex, actual, error * 1e6); assertEquals("Bad approximation", 0, error, 1e-6); assertTrue("Not monotonic", actual >= old); worst = Math.max(worst, Math.abs(error)); old = actual; } assertEquals(Math.asin(1), ScaleFunction.fastAsin(1), 0); } /** * Validates that the forward and reverse scale functions are as accurate as intended. */ public void testInverseScale() { for (ScaleFunction f : ScaleFunction.values()) { double tolerance = f.toString().contains("FAST") ? 2e-4 : 1e-10; for (double n : new double[] { 1000, 3_000, 10_000 }) { double epsilon = 1.0 / n; for (double compression : new double[] { 20, 100, 1000 }) { double oldK = f.k(0, compression, n); for (int i = 1; i < n; i++) { double q = i / n; double k = f.k(q, compression, n); assertTrue(String.format(Locale.ROOT, "monoticity %s(%.0f, %.0f) @ %.5f", f, compression, n, q), k > oldK); oldK = k; double qx = f.q(k, compression, n); double kx = f.k(qx, compression, n); assertEquals(String.format(Locale.ROOT, "Q: %s(%.0f, %.0f) @ %.5f", f, compression, n, q), q, qx, 1e-6); double absError = abs(k - kx); double relError = absError / max(0.01, max(abs(k), abs(kx))); String info = String.format( Locale.ROOT, "K: %s(%.0f, %.0f) @ %.5f [%.5g, %.5g]", f, compression, n, q, absError, relError ); assertEquals(info, 0, absError, tolerance); assertEquals(info, 0, relError, tolerance); } assertTrue(f.k(0, compression, n) < f.k(epsilon, compression, n)); assertTrue(f.k(1, compression, n) > f.k(1 - epsilon, compression, n)); } } } } }
ScaleFunctionTests
java
alibaba__nacos
config/src/test/java/com/alibaba/nacos/config/server/controller/v3/CapacityControllerV3Test.java
{ "start": 2414, "end": 7804 }
class ____ { @InjectMocks CapacityControllerV3 capacityControllerV3; private MockMvc mockMvc; @Mock private CapacityService capacityService; @Mock private ServletContext servletContext; @BeforeEach void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(capacityControllerV3, "capacityService", capacityService); mockMvc = MockMvcBuilders.standaloneSetup(capacityControllerV3).build(); } @Test void testGetCapacityNormal() throws Exception { Capacity capacity = new Capacity(); capacity.setId(1L); capacity.setMaxAggrCount(1); capacity.setMaxSize(1); capacity.setMaxAggrSize(1); capacity.setGmtCreate(new Timestamp(1)); capacity.setGmtModified(new Timestamp(2)); when(capacityService.getCapacityWithDefault(eq("test"), eq("test"))).thenReturn(capacity); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_V3_ADMIN_PATH).param("groupName", "test") .param("namespaceId", "test"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); Capacity result = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), Capacity.class); assertNotNull(result); assertEquals(capacity.getId(), result.getId()); assertEquals(capacity.getMaxAggrCount(), result.getMaxAggrCount()); assertEquals(capacity.getMaxSize(), result.getMaxSize()); assertEquals(capacity.getMaxAggrSize(), result.getMaxAggrSize()); assertEquals(capacity.getGmtCreate(), result.getGmtCreate()); assertEquals(capacity.getGmtModified(), result.getGmtModified()); } @Test void testGetCapacityException() throws Exception { Capacity capacity = new Capacity(); capacity.setId(1L); capacity.setMaxAggrCount(1); capacity.setMaxSize(1); capacity.setMaxAggrSize(1); capacity.setGmtCreate(new Timestamp(1)); capacity.setGmtModified(new Timestamp(2)); when(capacityService.getCapacityWithDefault(eq("test"), eq("test"))).thenReturn(capacity); // namespaceId & groupName is null MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_V3_ADMIN_PATH); assertThrows(Exception.class, () -> { mockMvc.perform(builder); }); // namespaceId is blank& groupName is null MockHttpServletRequestBuilder builder2 = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_V3_ADMIN_PATH).param("namespaceId", ""); assertThrows(Exception.class, () -> { mockMvc.perform(builder2); }); // namespaceId is not blank && groupName is not blank when(capacityService.getCapacityWithDefault(eq("g1"), eq("123"))).thenThrow(new NullPointerException()); MockHttpServletRequestBuilder builder3 = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_V3_ADMIN_PATH).param("namespaceId", "123") .param("groupName", "g1"); String actualValue3 = mockMvc.perform(builder3).andReturn().getResponse().getContentAsString(); } @Test void testUpdateCapacity1x() throws Exception { when(capacityService.insertOrUpdateCapacity("test", "test", 1, 1, 1, 1)).thenReturn(true); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_V3_ADMIN_PATH).param("groupName", "test") .param("namespaceId", "test").param("quota", "1").param("maxSize", "1").param("maxAggrCount", "1").param("maxAggrSize", "1"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); assertEquals("0", code); assertEquals("true", data); } @Test void testUpdateCapacity4x() throws Exception { UpdateCapacityForm updateCapacityForm = new UpdateCapacityForm(); updateCapacityForm.setGroupName("test"); updateCapacityForm.setNamespaceId("test"); updateCapacityForm.setQuota(1); updateCapacityForm.setMaxSize(1); updateCapacityForm.setMaxAggrCount(1); updateCapacityForm.setMaxSize(1); when(capacityService.insertOrUpdateCapacity("test", "test", 1, 1, 1, 1)).thenReturn(false); MockHttpServletRequestBuilder builder = post(Constants.CAPACITY_CONTROLLER_V3_ADMIN_PATH).param("groupName", "test") .param("namespaceId", "test").param("quota", "1").param("maxSize", "1").param("maxAggrCount", "1").param("maxAggrSize", "1"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); assertEquals("30000", code); assertEquals("null", data); } }
CapacityControllerV3Test
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyAndSecondaryTable.java
{ "start": 1500, "end": 2111 }
class ____ { @Test void testMappingManyToOneMappedByAnyPersistedInSecondaryTable(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Actor actor = new Actor(); actor.addToContacts( new Contact() ); entityManager.persist( actor ); entityManager.flush(); entityManager.clear(); List<Actor> actors = entityManager.createQuery( "select a from actor a", Actor.class ) .getResultList(); Assertions.assertEquals( 2, actors.size() ); } ); } @Entity(name = "actor") @Table(name = "TACTOR") public static
ManyToOneWithAnyAndSecondaryTable
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/PainlessUserTreeToIRTreePhase.java
{ "start": 4045, "end": 23665 }
class ____ extends DefaultUserTreeToIRTreePhase { @Override public void visitFunction(SFunction userFunctionNode, ScriptScope scriptScope) { String functionName = userFunctionNode.getFunctionName(); // This injects additional ir nodes required for // the "execute" method. This includes injection of ir nodes // to convert get methods into local variables for those // that are used and adds additional sandboxing by wrapping // the main "execute" block with several exceptions. if ("execute".equals(functionName)) { ScriptClassInfo scriptClassInfo = scriptScope.getScriptClassInfo(); LocalFunction localFunction = scriptScope.getFunctionTable() .getFunction(functionName, scriptClassInfo.getExecuteArguments().size()); Class<?> returnType = localFunction.getReturnType(); boolean methodEscape = scriptScope.getCondition(userFunctionNode, MethodEscape.class); BlockNode irBlockNode = (BlockNode) visit(userFunctionNode.getBlockNode(), scriptScope); if (methodEscape == false) { ExpressionNode irExpressionNode; if (returnType == void.class) { irExpressionNode = null; } else { if (returnType.isPrimitive()) { ConstantNode irConstantNode = new ConstantNode(userFunctionNode.getLocation()); irConstantNode.attachDecoration(new IRDExpressionType(returnType)); if (returnType == boolean.class) { irConstantNode.attachDecoration(new IRDConstant(false)); } else if (returnType == byte.class || returnType == char.class || returnType == short.class || returnType == int.class) { irConstantNode.attachDecoration(new IRDConstant(0)); } else if (returnType == long.class) { irConstantNode.attachDecoration(new IRDConstant(0L)); } else if (returnType == float.class) { irConstantNode.attachDecoration(new IRDConstant(0f)); } else if (returnType == double.class) { irConstantNode.attachDecoration(new IRDConstant(0d)); } else { throw userFunctionNode.createError(new IllegalStateException("illegal tree structure")); } irExpressionNode = irConstantNode; } else { irExpressionNode = new NullNode(userFunctionNode.getLocation()); irExpressionNode.attachDecoration(new IRDExpressionType(returnType)); } } ReturnNode irReturnNode = new ReturnNode(userFunctionNode.getLocation()); irReturnNode.setExpressionNode(irExpressionNode); irBlockNode.addStatementNode(irReturnNode); } List<String> parameterNames = scriptClassInfo.getExecuteArguments().stream().map(MethodArgument::name).toList(); FunctionNode irFunctionNode = new FunctionNode(userFunctionNode.getLocation()); irFunctionNode.setBlockNode(irBlockNode); irFunctionNode.attachDecoration(new IRDName("execute")); irFunctionNode.attachDecoration(new IRDReturnType(returnType)); irFunctionNode.attachDecoration(new IRDTypeParameters(localFunction.getTypeParameters())); irFunctionNode.attachDecoration(new IRDParameterNames(parameterNames)); irFunctionNode.attachDecoration(new IRDMaxLoopCounter(scriptScope.getCompilerSettings().getMaxLoopCounter())); injectStaticFieldsAndGetters(); injectGetsDeclarations(irBlockNode, scriptScope); injectNeedsMethods(scriptScope); injectSandboxExceptions(irFunctionNode); scriptScope.putDecoration(userFunctionNode, new IRNodeDecoration(irFunctionNode)); } else { super.visitFunction(userFunctionNode, scriptScope); } } // adds static fields and getter methods required by PainlessScript for exception handling protected void injectStaticFieldsAndGetters() { Location internalLocation = new Location("$internal$ScriptInjectionPhase$injectStaticFieldsAndGetters", 0); int modifiers = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC; FieldNode irFieldNode = new FieldNode(internalLocation); irFieldNode.attachDecoration(new IRDModifiers(modifiers)); irFieldNode.attachDecoration(new IRDFieldType(String.class)); irFieldNode.attachDecoration(new IRDName("$NAME")); irClassNode.addFieldNode(irFieldNode); irFieldNode = new FieldNode(internalLocation); irFieldNode.attachDecoration(new IRDModifiers(modifiers)); irFieldNode.attachDecoration(new IRDFieldType(String.class)); irFieldNode.attachDecoration(new IRDName("$SOURCE")); irClassNode.addFieldNode(irFieldNode); irFieldNode = new FieldNode(internalLocation); irFieldNode.attachDecoration(new IRDModifiers(modifiers)); irFieldNode.attachDecoration(new IRDFieldType(BitSet.class)); irFieldNode.attachDecoration(new IRDName("$STATEMENTS")); irClassNode.addFieldNode(irFieldNode); FunctionNode irFunctionNode = new FunctionNode(internalLocation); irFunctionNode.attachDecoration(new IRDName("getName")); irFunctionNode.attachDecoration(new IRDReturnType(String.class)); irFunctionNode.attachDecoration(new IRDTypeParameters(List.of())); irFunctionNode.attachDecoration(new IRDParameterNames(List.of())); irFunctionNode.attachCondition(IRCSynthetic.class); irFunctionNode.attachDecoration(new IRDMaxLoopCounter(0)); irClassNode.addFunctionNode(irFunctionNode); BlockNode irBlockNode = new BlockNode(internalLocation); irBlockNode.attachCondition(IRCAllEscape.class); irFunctionNode.setBlockNode(irBlockNode); ReturnNode irReturnNode = new ReturnNode(internalLocation); irBlockNode.addStatementNode(irReturnNode); LoadFieldMemberNode irLoadFieldMemberNode = new LoadFieldMemberNode(internalLocation); irLoadFieldMemberNode.attachDecoration(new IRDExpressionType(String.class)); irLoadFieldMemberNode.attachDecoration(new IRDName("$NAME")); irLoadFieldMemberNode.attachCondition(IRCStatic.class); irReturnNode.setExpressionNode(irLoadFieldMemberNode); irFunctionNode = new FunctionNode(internalLocation); irFunctionNode.attachDecoration(new IRDName("getSource")); irFunctionNode.attachDecoration(new IRDReturnType(String.class)); irFunctionNode.attachDecoration(new IRDTypeParameters(List.of())); irFunctionNode.attachDecoration(new IRDParameterNames(List.of())); irFunctionNode.attachCondition(IRCSynthetic.class); irFunctionNode.attachDecoration(new IRDMaxLoopCounter(0)); irClassNode.addFunctionNode(irFunctionNode); irBlockNode = new BlockNode(internalLocation); irBlockNode.attachCondition(IRCAllEscape.class); irFunctionNode.setBlockNode(irBlockNode); irReturnNode = new ReturnNode(internalLocation); irBlockNode.addStatementNode(irReturnNode); irLoadFieldMemberNode = new LoadFieldMemberNode(internalLocation); irLoadFieldMemberNode.attachDecoration(new IRDExpressionType(String.class)); irLoadFieldMemberNode.attachDecoration(new IRDName("$SOURCE")); irLoadFieldMemberNode.attachCondition(IRCStatic.class); irReturnNode.setExpressionNode(irLoadFieldMemberNode); irFunctionNode = new FunctionNode(internalLocation); irFunctionNode.attachDecoration(new IRDName("getStatements")); irFunctionNode.attachDecoration(new IRDReturnType(BitSet.class)); irFunctionNode.attachDecoration(new IRDTypeParameters(List.of())); irFunctionNode.attachDecoration(new IRDParameterNames(List.of())); irFunctionNode.attachCondition(IRCSynthetic.class); irFunctionNode.attachDecoration(new IRDMaxLoopCounter(0)); irClassNode.addFunctionNode(irFunctionNode); irBlockNode = new BlockNode(internalLocation); irBlockNode.attachCondition(IRCAllEscape.class); irFunctionNode.setBlockNode(irBlockNode); irReturnNode = new ReturnNode(internalLocation); irBlockNode.addStatementNode(irReturnNode); irLoadFieldMemberNode = new LoadFieldMemberNode(internalLocation); irLoadFieldMemberNode.attachDecoration(new IRDExpressionType(BitSet.class)); irLoadFieldMemberNode.attachDecoration(new IRDName("$STATEMENTS")); irLoadFieldMemberNode.attachCondition(IRCStatic.class); irReturnNode.setExpressionNode(irLoadFieldMemberNode); } // convert gets methods to a new set of inserted ir nodes as necessary - // requires the gets method name be modified from "getExample" to "example" // if a get method variable isn't used it's declaration node is removed from // the ir tree permanently so there is no frivolous variable slotting protected static void injectGetsDeclarations(BlockNode irBlockNode, ScriptScope scriptScope) { Location internalLocation = new Location("$internal$ScriptInjectionPhase$injectGetsDeclarations", 0); for (int i = 0; i < scriptScope.getScriptClassInfo().getGetMethods().size(); ++i) { Method getMethod = scriptScope.getScriptClassInfo().getGetMethods().get(i); String name = getMethod.getName().substring(3); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); if (scriptScope.getUsedVariables().contains(name)) { Class<?> returnType = scriptScope.getScriptClassInfo().getGetReturns().get(i); DeclarationNode irDeclarationNode = new DeclarationNode(internalLocation); irDeclarationNode.attachDecoration(new IRDName(name)); irDeclarationNode.attachDecoration(new IRDDeclarationType(returnType)); irBlockNode.getStatementsNodes().add(0, irDeclarationNode); InvokeCallMemberNode irInvokeCallMemberNode = new InvokeCallMemberNode(internalLocation); irInvokeCallMemberNode.attachDecoration(new IRDExpressionType(returnType)); irInvokeCallMemberNode.attachDecoration( new IRDFunction(new LocalFunction(getMethod.getName(), returnType, List.of(), true, false)) ); irDeclarationNode.setExpressionNode(irInvokeCallMemberNode); } } } // injects needs methods as defined by ScriptClassInfo protected void injectNeedsMethods(ScriptScope scriptScope) { Location internalLocation = new Location("$internal$ScriptInjectionPhase$injectNeedsMethods", 0); for (org.objectweb.asm.commons.Method needsMethod : scriptScope.getScriptClassInfo().getNeedsMethods()) { String name = needsMethod.getName(); name = name.substring(5); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); FunctionNode irFunctionNode = new FunctionNode(internalLocation); irFunctionNode.attachDecoration(new IRDName(needsMethod.getName())); irFunctionNode.attachDecoration(new IRDReturnType(boolean.class)); irFunctionNode.attachDecoration(new IRDTypeParameters(List.of())); irFunctionNode.attachDecoration(new IRDParameterNames(List.of())); irFunctionNode.attachCondition(IRCSynthetic.class); irFunctionNode.attachDecoration(new IRDMaxLoopCounter(0)); irClassNode.addFunctionNode(irFunctionNode); BlockNode irBlockNode = new BlockNode(internalLocation); irBlockNode.attachCondition(IRCAllEscape.class); irFunctionNode.setBlockNode(irBlockNode); ReturnNode irReturnNode = new ReturnNode(internalLocation); irBlockNode.addStatementNode(irReturnNode); ConstantNode irConstantNode = new ConstantNode(internalLocation); irConstantNode.attachDecoration(new IRDExpressionType(boolean.class)); irConstantNode.attachDecoration(new IRDConstant(scriptScope.getUsedVariables().contains(name))); irReturnNode.setExpressionNode(irConstantNode); } } /* * Decorate the execute method with nodes to wrap the user statements with * the sandboxed errors as follows: * * } catch (PainlessExplainError e) { * throw this.convertToScriptException(e, e.getHeaders($DEFINITION)) * } * * and * * } catch (SecurityException e) { * throw e; * } * * and * * } catch (PainlessError | LinkageError | OutOfMemoryError | StackOverflowError | Exception e) { * throw this.convertToScriptException(e, e.getHeaders()) * } * */ protected static void injectSandboxExceptions(FunctionNode irFunctionNode) { try { Location internalLocation = new Location("$internal$ScriptInjectionPhase$injectSandboxExceptions", 0); BlockNode irBlockNode = irFunctionNode.getBlockNode(); TryNode irTryNode = new TryNode(internalLocation); irTryNode.setBlockNode(irBlockNode); ThrowNode irThrowNode = createCatchAndThrow(PainlessExplainError.class, internalLocation, irTryNode); InvokeCallMemberNode irInvokeCallMemberNode = new InvokeCallMemberNode(internalLocation); irInvokeCallMemberNode.attachDecoration(new IRDExpressionType(ScriptException.class)); irInvokeCallMemberNode.attachDecoration( new IRDFunction( new LocalFunction("convertToScriptException", ScriptException.class, List.of(Throwable.class, Map.class), true, false) ) ); irThrowNode.setExpressionNode(irInvokeCallMemberNode); LoadVariableNode irLoadVariableNode = new LoadVariableNode(internalLocation); irLoadVariableNode.attachDecoration(new IRDExpressionType(ScriptException.class)); irLoadVariableNode.attachDecoration(new IRDName("#painlessExplainError")); irInvokeCallMemberNode.addArgumentNode(irLoadVariableNode); BinaryImplNode irBinaryImplNode = new BinaryImplNode(internalLocation); irBinaryImplNode.attachDecoration(new IRDExpressionType(Map.class)); irInvokeCallMemberNode.addArgumentNode(irBinaryImplNode); irLoadVariableNode = new LoadVariableNode(internalLocation); irLoadVariableNode.attachDecoration(new IRDExpressionType(PainlessExplainError.class)); irLoadVariableNode.attachDecoration(new IRDName("#painlessExplainError")); irBinaryImplNode.setLeftNode(irLoadVariableNode); InvokeCallNode irInvokeCallNode = new InvokeCallNode(internalLocation); irInvokeCallNode.attachDecoration(new IRDExpressionType(Map.class)); irInvokeCallNode.setBox(PainlessExplainError.class); irInvokeCallNode.setMethod( new PainlessMethod( PainlessExplainError.class.getMethod("getHeaders", PainlessLookup.class), PainlessExplainError.class, null, List.of(), null, null, Map.of() ) ); irBinaryImplNode.setRightNode(irInvokeCallNode); LoadFieldMemberNode irLoadFieldMemberNode = new LoadFieldMemberNode(internalLocation); irLoadFieldMemberNode.attachDecoration(new IRDExpressionType(PainlessLookup.class)); irLoadFieldMemberNode.attachDecoration(new IRDName("$DEFINITION")); irLoadFieldMemberNode.attachCondition(IRCStatic.class); irInvokeCallNode.addArgumentNode(irLoadFieldMemberNode); irThrowNode = createCatchAndThrow(SecurityException.class, internalLocation, irTryNode); irLoadVariableNode = new LoadVariableNode(internalLocation); irLoadVariableNode.attachDecoration(new IRDExpressionType(SecurityException.class)); irLoadVariableNode.attachDecoration(new IRDName(getExceptionVariableName(SecurityException.class))); irThrowNode.setExpressionNode(irLoadVariableNode); for (Class<? extends Throwable> throwable : List.of( PainlessError.class, PainlessWrappedException.class, LinkageError.class, OutOfMemoryError.class, StackOverflowError.class, Exception.class )) { irThrowNode = createCatchAndThrow(throwable, internalLocation, irTryNode); irInvokeCallMemberNode = new InvokeCallMemberNode(internalLocation); irInvokeCallMemberNode.attachDecoration(new IRDExpressionType(ScriptException.class)); irInvokeCallMemberNode.attachDecoration( new IRDFunction( new LocalFunction( "convertToScriptException", ScriptException.class, List.of(Throwable.class, Map.class), true, false ) ) ); irThrowNode.setExpressionNode(irInvokeCallMemberNode); irLoadVariableNode = new LoadVariableNode(internalLocation); irLoadVariableNode.attachDecoration(new IRDExpressionType(ScriptException.class)); irLoadVariableNode.attachDecoration(new IRDName(getExceptionVariableName(throwable))); irInvokeCallMemberNode.addArgumentNode(irLoadVariableNode); irBinaryImplNode = new BinaryImplNode(internalLocation); irBinaryImplNode.attachDecoration(new IRDExpressionType(Map.class)); irInvokeCallMemberNode.addArgumentNode(irBinaryImplNode); StaticNode irStaticNode = new StaticNode(internalLocation); irStaticNode.attachDecoration(new IRDExpressionType(Collections.class)); irBinaryImplNode.setLeftNode(irStaticNode); irInvokeCallNode = new InvokeCallNode(internalLocation); irInvokeCallNode.attachDecoration(new IRDExpressionType(Map.class)); irInvokeCallNode.setBox(Collections.class); irInvokeCallNode.setMethod( new PainlessMethod(Collections.class.getMethod("emptyMap"), Collections.class, null, List.of(), null, null, Map.of()) ); irBinaryImplNode.setRightNode(irInvokeCallNode); } irBlockNode = new BlockNode(internalLocation); irBlockNode.attachCondition(IRCAllEscape.class); irBlockNode.addStatementNode(irTryNode); irFunctionNode.setBlockNode(irBlockNode); } catch (Exception exception) { throw new RuntimeException(exception); } } // Turn an exception
PainlessUserTreeToIRTreePhase
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh11181CoreExtensionsMetaVersionsTest.java
{ "start": 1031, "end": 4252 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Project wide extensions: use of meta versions is invalid. */ @Test void pwMetaVersionIsInvalid() throws Exception { Path testDir = extractResources("/gh-11181-core-extensions-meta-versions") .toPath() .toAbsolutePath() .resolve("pw-metaversion-is-invalid"); Verifier verifier = newVerifier(testDir.toString()); verifier.setUserHomeDirectory(testDir.resolve("HOME")); verifier.setAutoclean(false); verifier.addCliArgument("validate"); try { verifier.execute(); fail("Expected VerificationException"); } catch (VerificationException e) { // there is not even a log; this is very early failure assertTrue(e.getMessage().contains("Error executing Maven.")); } } /** * User wide extensions: use of meta versions is valid. */ @Test void uwMetaVersionIsValid() throws Exception { Path testDir = extractResources("/gh-11181-core-extensions-meta-versions") .toPath() .toAbsolutePath() .resolve("uw-metaversion-is-valid"); Verifier verifier = newVerifier(testDir.toString()); verifier.setUserHomeDirectory(testDir.resolve("HOME")); verifier.setHandleLocalRepoTail(false); verifier.setAutoclean(false); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); } /** * Same GA different V extensions in project-wide and user-wide: warn for conflict. */ @Test void uwPwDifferentVersionIsConflict() throws Exception { Path testDir = extractResources("/gh-11181-core-extensions-meta-versions") .toPath() .toAbsolutePath() .resolve("uw-pw-different-version-is-conflict"); Verifier verifier = newVerifier(testDir.toString()); verifier.setUserHomeDirectory(testDir.resolve("HOME")); verifier.setHandleLocalRepoTail(false); verifier.setAutoclean(false); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyTextInLog("WARNING"); verifier.verifyTextInLog("Conflicting extension io.takari.maven:takari-smart-builder"); } /** * Same GAV extensions in project-wide and user-wide: do not warn for conflict. */ @Test void uwPwSameVersionIsNotConflict() throws Exception { Path testDir = extractResources("/gh-11181-core-extensions-meta-versions") .toPath() .toAbsolutePath() .resolve("uw-pw-same-version-is-not-conflict"); Verifier verifier = newVerifier(testDir.toString()); verifier.setUserHomeDirectory(testDir.resolve("HOME")); verifier.setHandleLocalRepoTail(false); verifier.setAutoclean(false); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyTextNotInLog("WARNING"); } }
MavenITgh11181CoreExtensionsMetaVersionsTest
java
apache__dubbo
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.java
{ "start": 1008, "end": 1455 }
class ____ extends LongContainer<AtomicLong> { public AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper) { super(metricsKeyWrapper, AtomicLong::new, (responseTime, longAccumulator) -> longAccumulator.set(responseTime)); } public AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper, BiConsumer<Long, AtomicLong> consumerFunc) { super(metricsKeyWrapper, AtomicLong::new, consumerFunc); } }
AtomicLongContainer
java
qos-ch__slf4j
slf4j-jdk14/src/test/java/org/slf4j/jul/CountingHandler.java
{ "start": 149, "end": 468 }
class ____ extends Handler { final AtomicLong eventCount = new AtomicLong(0); @Override public void publish(LogRecord record) { eventCount.getAndIncrement(); } @Override public void flush() { } @Override public void close() throws SecurityException { } }
CountingHandler
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/server/header/ContentSecurityPolicyServerHttpHeadersWriterTests.java
{ "start": 1173, "end": 3588 }
class ____ { private static final String DEFAULT_POLICY_DIRECTIVES = "default-src 'self'"; private ServerWebExchange exchange; private ContentSecurityPolicyServerHttpHeadersWriter writer; @BeforeEach public void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new ContentSecurityPolicyServerHttpHeadersWriter(); } @Test public void writeHeadersWhenUsingDefaultsThenDoesNotWrite() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers.headerNames()).isEmpty(); } @Test public void writeHeadersWhenUsingPolicyThenWritesPolicy() { this.writer.setPolicyDirectives(DEFAULT_POLICY_DIRECTIVES); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers.headerNames()).hasSize(1); assertThat(headers.get(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY)) .containsOnly(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersWhenReportPolicyThenWritesReportPolicy() { this.writer.setPolicyDirectives(DEFAULT_POLICY_DIRECTIVES); this.writer.setReportOnly(true); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers.headerNames()).hasSize(1); assertThat(headers.get(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY_REPORT_ONLY)) .containsOnly(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersWhenOnlyReportOnlySetThenDoesNotWrite() { this.writer.setReportOnly(true); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers.headerNames()).isEmpty(); } @Test public void writeHeadersWhenAlreadyWrittenThenWritesHeader() { String headerValue = "default-src https: 'self'"; this.exchange.getResponse() .getHeaders() .set(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, headerValue); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers.headerNames()).hasSize(1); assertThat(headers.get(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY)) .containsOnly(headerValue); } }
ContentSecurityPolicyServerHttpHeadersWriterTests
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableSwitchOnNextTest.java
{ "start": 1027, "end": 3519 }
class ____ extends RxJavaTest { @Test public void normal() { Runnable run = mock(Runnable.class); Completable.switchOnNext( Flowable.range(1, 10) .map(v -> { if (v % 2 == 0) { return Completable.fromRunnable(run); } return Completable.complete(); }) ) .test() .assertResult(); verify(run, times(5)).run(); } @Test public void normalDelayError() { Runnable run = mock(Runnable.class); Completable.switchOnNextDelayError( Flowable.range(1, 10) .map(v -> { if (v % 2 == 0) { return Completable.fromRunnable(run); } return Completable.complete(); }) ) .test() .assertResult(); verify(run, times(5)).run(); } @Test public void noDelaySwitch() { PublishProcessor<Completable> pp = PublishProcessor.create(); TestObserver<Void> to = Completable.switchOnNext(pp).test(); assertTrue(pp.hasSubscribers()); to.assertEmpty(); CompletableSubject cs1 = CompletableSubject.create(); CompletableSubject cs2 = CompletableSubject.create(); pp.onNext(cs1); assertTrue(cs1.hasObservers()); pp.onNext(cs2); assertFalse(cs1.hasObservers()); assertTrue(cs2.hasObservers()); pp.onComplete(); assertTrue(cs2.hasObservers()); cs2.onComplete(); to.assertResult(); } @Test public void delaySwitch() { PublishProcessor<Completable> pp = PublishProcessor.create(); TestObserver<Void> to = Completable.switchOnNextDelayError(pp).test(); assertTrue(pp.hasSubscribers()); to.assertEmpty(); CompletableSubject cs1 = CompletableSubject.create(); CompletableSubject cs2 = CompletableSubject.create(); pp.onNext(cs1); assertTrue(cs1.hasObservers()); pp.onNext(cs2); assertFalse(cs1.hasObservers()); assertTrue(cs2.hasObservers()); assertTrue(cs2.hasObservers()); cs2.onError(new TestException()); assertTrue(pp.hasSubscribers()); to.assertEmpty(); pp.onComplete(); to.assertFailure(TestException.class); } }
CompletableSwitchOnNextTest
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/ReadOnlyTask.java
{ "start": 1333, "end": 7642 }
class ____ implements Task { private final Task task; public ReadOnlyTask(final Task task) { this.task = task; } @Override public TaskId id() { return task.id(); } @Override public boolean isActive() { return task.isActive(); } @Override public Set<TopicPartition> inputPartitions() { return task.inputPartitions(); } @Override public Set<TopicPartition> changelogPartitions() { return task.changelogPartitions(); } @Override public State state() { return task.state(); } @Override public boolean commitRequested() { return task.commitRequested(); } @Override public boolean needsInitializationOrRestoration() { return task.needsInitializationOrRestoration(); } @Override public void initializeIfNeeded() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void addPartitionsForOffsetReset(final Set<TopicPartition> partitionsForOffsetReset) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void completeRestoration(final Consumer<Set<TopicPartition>> offsetResetter) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void suspend() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void resume() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void closeDirty() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void closeClean() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void updateInputPartitions(final Set<TopicPartition> topicPartitions, final Map<String, List<String>> allTopologyNodesToSourceTopics) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void maybeCheckpoint(final boolean enforceCheckpoint) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void markChangelogAsCorrupted(final Collection<TopicPartition> partitions) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void revive() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void prepareRecycle() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void resumePollingForPartitionsWithAvailableSpace() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void updateLags() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void addRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> records) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void updateNextOffsets(final TopicPartition partition, final OffsetAndMetadata offsetAndMetadata) { throw new UnsupportedOperationException("This task is read-only"); } @Override public boolean process(final long wallClockTime) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void recordProcessBatchTime(final long processBatchTime) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void recordProcessTimeRatioAndBufferSize(final long allTaskProcessMs, final long now) { throw new UnsupportedOperationException("This task is read-only"); } @Override public boolean maybePunctuateStreamTime() { throw new UnsupportedOperationException("This task is read-only"); } @Override public boolean maybePunctuateSystemTime() { throw new UnsupportedOperationException("This task is read-only"); } @Override public Map<TopicPartition, OffsetAndMetadata> prepareCommit(final boolean clean) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void postCommit(final boolean enforceCheckpoint) { throw new UnsupportedOperationException("This task is read-only"); } @Override public Map<TopicPartition, Long> purgeableOffsets() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void maybeInitTaskTimeoutOrThrow(final long currentWallClockMs, final Exception cause) { throw new UnsupportedOperationException("This task is read-only"); } @Override public void clearTaskTimeout() { throw new UnsupportedOperationException("This task is read-only"); } @Override public void recordRestoration(final Time time, final long numRecords, final boolean initRemaining) { throw new UnsupportedOperationException("This task is read-only"); } @Override public boolean commitNeeded() { if (task.isActive()) { throw new UnsupportedOperationException("This task is read-only"); } return task.commitNeeded(); } @Override public StateStore store(final String name) { return task.store(name); } @Override public Map<TopicPartition, Long> changelogOffsets() { return task.changelogOffsets(); } @Override public Map<TopicPartition, Long> committedOffsets() { throw new UnsupportedOperationException("This task is read-only"); } @Override public Map<TopicPartition, Long> highWaterMark() { throw new UnsupportedOperationException("This task is read-only"); } @Override public Optional<Long> timeCurrentIdlingStarted() { throw new UnsupportedOperationException("This task is read-only"); } @Override public ProcessorStateManager stateManager() { throw new UnsupportedOperationException("This task is read-only"); } }
ReadOnlyTask
java
apache__dubbo
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java
{ "start": 1760, "end": 2851 }
class ____ implements Cache { /** * Thread local variable to store cached data. */ private final ThreadLocal<Map<Object, Object>> store; /** * Taken URL as an argument to create an instance of ThreadLocalCache. In this version of implementation constructor * argument is not getting used in the scope of this class. * @param url */ public ThreadLocalCache(URL url) { this.store = ThreadLocal.withInitial(HashMap::new); } /** * API to store value against a key in the calling thread scope. * @param key Unique identifier for the object being store. * @param value Value getting store */ @Override public void put(Object key, Object value) { store.get().put(key, value); } /** * API to return stored value using a key against the calling thread specific store. * @param key Unique identifier for cache lookup * @return Return stored object against key */ @Override public Object get(Object key) { return store.get().get(key); } }
ThreadLocalCache
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/RolloverStep.java
{ "start": 1203, "end": 6758 }
class ____ extends AsyncActionStep { private static final Logger logger = LogManager.getLogger(RolloverStep.class); public static final String NAME = "attempt-rollover"; public RolloverStep(StepKey key, StepKey nextStepKey, Client client) { super(key, nextStepKey, client); } @Override public boolean isRetryable() { return true; } @Override public void performAction( IndexMetadata indexMetadata, ProjectState currentState, ClusterStateObserver observer, ActionListener<Void> listener ) { String indexName = indexMetadata.getIndex().getName(); boolean indexingComplete = LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE_SETTING.get(indexMetadata.getSettings()); if (indexingComplete) { logger.trace("{} has lifecycle complete set, skipping {}", indexMetadata.getIndex(), RolloverStep.NAME); listener.onResponse(null); return; } IndexAbstraction indexAbstraction = currentState.metadata().getIndicesLookup().get(indexName); assert indexAbstraction != null : "expected the index " + indexName + " to exist in the lookup but it didn't"; final String rolloverTarget; final boolean targetFailureStore; DataStream dataStream = indexAbstraction.getParentDataStream(); if (dataStream != null) { boolean isFailureStoreWriteIndex = indexMetadata.getIndex().equals(dataStream.getWriteFailureIndex()); targetFailureStore = dataStream.isFailureStoreIndex(indexMetadata.getIndex().getName()); if (isFailureStoreWriteIndex == false && dataStream.getWriteIndex().equals(indexMetadata.getIndex()) == false) { logger.warn( "index [{}] is not the {}write index for data stream [{}]. skipping rollover for policy [{}]", indexName, targetFailureStore ? "failure store " : "", dataStream.getName(), indexMetadata.getLifecyclePolicyName() ); listener.onResponse(null); return; } rolloverTarget = dataStream.getName(); } else { String rolloverAlias = RolloverAction.LIFECYCLE_ROLLOVER_ALIAS_SETTING.get(indexMetadata.getSettings()); if (Strings.isNullOrEmpty(rolloverAlias)) { listener.onFailure( new IllegalArgumentException( Strings.format( "setting [%s] for index [%s] is empty or not defined, it must be set to the name of the alias " + "pointing to the group of indices being rolled over", RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, indexName ) ) ); return; } if (indexMetadata.getRolloverInfos().get(rolloverAlias) != null) { logger.info( "index [{}] was already rolled over for alias [{}], not attempting to roll over again", indexName, rolloverAlias ); listener.onResponse(null); return; } if (indexMetadata.getAliases().containsKey(rolloverAlias) == false) { listener.onFailure( new IllegalArgumentException( Strings.format( "%s [%s] does not point to index [%s]", RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, rolloverAlias, indexName ) ) ); return; } rolloverTarget = rolloverAlias; targetFailureStore = false; } // Calling rollover with no conditions will always roll over the index RolloverRequest rolloverRequest = new RolloverRequest(rolloverTarget, null).masterNodeTimeout(TimeValue.MAX_VALUE); if (targetFailureStore) { rolloverRequest.setRolloverTarget(IndexNameExpressionResolver.combineSelector(rolloverTarget, IndexComponentSelector.FAILURES)); } // We don't wait for active shards when we perform the rollover because the // {@link org.elasticsearch.xpack.core.ilm.WaitForActiveShardsStep} step will do so rolloverRequest.setWaitForActiveShards(ActiveShardCount.NONE); getClient(currentState.projectId()).admin() .indices() .rolloverIndex(rolloverRequest, listener.delegateFailureAndWrap((l, response) -> { assert response.isRolledOver() : "the only way this rollover call should fail is with an exception"; if (response.isRolledOver()) { l.onResponse(null); } else { l.onFailure(new IllegalStateException("unexepected exception on unconditional rollover")); } })); } @Override public int hashCode() { return Objects.hash(super.hashCode()); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RolloverStep other = (RolloverStep) obj; return super.equals(obj); } }
RolloverStep
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/AbstractCachedRoleService.java
{ "start": 1262, "end": 3267 }
class ____ implements NacosRoleService { protected static final int DEFAULT_PAGE_NO = 1; private volatile Set<String> roleSet = new ConcurrentHashSet<>(); private volatile Map<String, List<RoleInfo>> roleInfoMap = new ConcurrentHashMap<>(); private volatile Map<String, List<PermissionInfo>> permissionInfoMap = new ConcurrentHashMap<>(); protected Set<String> getCachedRoleSet() { return roleSet; } protected Map<String, List<RoleInfo>> getCachedRoleInfoMap() { return roleInfoMap; } protected Map<String, List<PermissionInfo>> getCachedPermissionInfoMap() { return permissionInfoMap; } @Scheduled(initialDelay = 5000, fixedDelay = 15000) protected void reload() { try { List<RoleInfo> roleInfoPage = getAllRoles(); Set<String> tmpRoleSet = new HashSet<>(16); Map<String, List<RoleInfo>> tmpRoleInfoMap = new ConcurrentHashMap<>(16); for (RoleInfo roleInfo : roleInfoPage) { if (!tmpRoleInfoMap.containsKey(roleInfo.getUsername())) { tmpRoleInfoMap.put(roleInfo.getUsername(), new ArrayList<>()); } tmpRoleInfoMap.get(roleInfo.getUsername()).add(roleInfo); tmpRoleSet.add(roleInfo.getRole()); } Map<String, List<PermissionInfo>> tmpPermissionInfoMap = new ConcurrentHashMap<>(16); for (String role : tmpRoleSet) { Page<PermissionInfo> permissionInfoPage = getPermissions(role, DEFAULT_PAGE_NO, Integer.MAX_VALUE); tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems()); } roleSet = tmpRoleSet; roleInfoMap = tmpRoleInfoMap; permissionInfoMap = tmpPermissionInfoMap; } catch (Exception e) { Loggers.AUTH.warn("[LOAD-ROLES] load failed", e); } } }
AbstractCachedRoleService
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/vectors/VectorDVLeafFieldData.java
{ "start": 4298, "end": 6175 }
class ____ implements FormattedDocValues { private final int dims; private byte[] vector; private ByteVectorValues byteVectorValues; // use when indexed private KnnVectorValues.DocIndexIterator iterator; // use when indexed private BinaryDocValues binary; // use when not indexed ByteDocValues(int dims) { this.dims = dims; this.vector = new byte[dims]; try { if (indexed) { byteVectorValues = reader.getByteVectorValues(field); iterator = (byteVectorValues == null) ? null : byteVectorValues.iterator(); } else { binary = DocValues.getBinary(reader, field); } } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public boolean advanceExact(int docId) throws IOException { if (indexed) { if (iteratorAdvanceExact(iterator, docId) == false) { return false; } vector = byteVectorValues.vectorValue(iterator.index()); } else { if (binary == null || binary.advanceExact(docId) == false) { return false; } BytesRef ref = binary.binaryValue(); System.arraycopy(ref.bytes, ref.offset, vector, 0, dims); } return true; } @Override public int docValueCount() { return 1; } public Object nextValue() { Byte[] vectorValue = new Byte[dims]; for (int i = 0; i < dims; i++) { vectorValue[i] = vector[i]; } return vectorValue; } } private
ByteDocValues
java
resilience4j__resilience4j
resilience4j-spring-boot3/src/test/java/io/github/resilience4j/springboot3/circuitbreaker/CircuitBreakerAutoConfigurationTest.java
{ "start": 2521, "end": 10990 }
class ____ { @Rule public WireMockRule wireMockRule = new WireMockRule(8090); @Autowired CircuitBreakerRegistry circuitBreakerRegistry; @Autowired CircuitBreakerProperties circuitBreakerProperties; @Autowired CircuitBreakerAspect circuitBreakerAspect; @Autowired DummyService dummyService; @Autowired private TestRestTemplate restTemplate; /** * The test verifies that a CircuitBreaker instance is created and configured properly when the * DummyService is invoked and that the CircuitBreaker records successful and failed calls. */ @Test public void testCircuitBreakerAutoConfiguration() throws IOException { assertThat(circuitBreakerRegistry).isNotNull(); assertThat(circuitBreakerProperties).isNotNull(); assertThat(circuitBreakerAspect.getOrder()).isEqualTo(400); CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker(DummyService.BACKEND); verifyCircuitBreakerAutoConfiguration(circuitBreaker); AtomicInteger eventCounter = new AtomicInteger(0);; circuitBreaker.getEventPublisher() .onSuccess(event -> eventCounter.incrementAndGet()) .onError(event -> eventCounter.incrementAndGet()); int circuitBreakerEventsBefore = getCircuitBreakersEvents().size(); int circuitBreakerEventsForABefore = getCircuitBreakerEvents(DummyService.BACKEND).size(); try { dummyService.doSomething(true); } catch (IOException ex) { // Do nothing. The IOException is recorded by the CircuitBreaker as part of the recordFailurePredicate as a failure. } // The invocation is recorded by the CircuitBreaker as a success. dummyService.doSomething(false); await().atMost(5, SECONDS).untilAtomic(eventCounter, equalTo(2)); // expect circuitbreaker-event actuator endpoint recorded all events assertThat(getCircuitBreakersEvents()) .hasSize(circuitBreakerEventsBefore + 2); assertThat(getCircuitBreakerEvents(DummyService.BACKEND)) .hasSize(circuitBreakerEventsForABefore + 2); // Create CircuitBreaker dynamically with default config CircuitBreaker dynamicCircuitBreaker = circuitBreakerRegistry.circuitBreaker("dynamicBackend"); // expect no health indicator for backendB, as it is disabled via properties ResponseEntity<CompositeHealthResponse> healthResponse = restTemplate .getForEntity("/actuator/health/circuitBreakers", CompositeHealthResponse.class); verifyHealthIndicatorResponse(healthResponse); // expect all shared configs share the same values and are from the application.yml file CircuitBreaker sharedA = circuitBreakerRegistry.circuitBreaker("backendSharedA"); CircuitBreaker sharedB = circuitBreakerRegistry.circuitBreaker("backendSharedB"); CircuitBreaker backendB = circuitBreakerRegistry.circuitBreaker("backendB"); CircuitBreaker backendC = circuitBreakerRegistry.circuitBreaker("backendC"); verifyCircuitBreakerAutoConfiguration(dynamicCircuitBreaker, sharedA, sharedB, backendB, backendC); } private void verifyCircuitBreakerAutoConfiguration(CircuitBreaker dynamicCircuitBreaker, CircuitBreaker sharedA, CircuitBreaker sharedB, CircuitBreaker backendB, CircuitBreaker backendC) { long defaultWaitDuration = 10_000; float defaultFailureRate = 60f; int defaultPermittedNumberOfCallsInHalfOpenState = 10; int defaultSlidingWindowSize = 100; // test the customizer effect which overload the sliding widow size assertThat(backendC.getCircuitBreakerConfig().getSlidingWindowSize()).isEqualTo(100); assertThat(backendB.getCircuitBreakerConfig().getSlidingWindowType()) .isEqualTo(CircuitBreakerConfig.SlidingWindowType.TIME_BASED); assertThat(sharedA.getCircuitBreakerConfig().getSlidingWindowSize()).isEqualTo(6); assertThat(sharedA.getCircuitBreakerConfig().getPermittedNumberOfCallsInHalfOpenState()) .isEqualTo(defaultPermittedNumberOfCallsInHalfOpenState); assertThat(sharedA.getCircuitBreakerConfig().getFailureRateThreshold()) .isEqualTo(defaultFailureRate); assertThat(sharedA.getCircuitBreakerConfig().getWaitIntervalFunctionInOpenState().apply(1)) .isEqualTo(defaultWaitDuration); assertThat(sharedB.getCircuitBreakerConfig().getSlidingWindowSize()) .isEqualTo(defaultSlidingWindowSize); assertThat(sharedB.getCircuitBreakerConfig().getSlidingWindowType()) .isEqualTo(CircuitBreakerConfig.SlidingWindowType.TIME_BASED); assertThat(sharedB.getCircuitBreakerConfig().getPermittedNumberOfCallsInHalfOpenState()) .isEqualTo(defaultPermittedNumberOfCallsInHalfOpenState); assertThat(sharedB.getCircuitBreakerConfig().getFailureRateThreshold()) .isEqualTo(defaultFailureRate); assertThat(sharedB.getCircuitBreakerConfig().getWaitIntervalFunctionInOpenState().apply(1)) .isEqualTo(defaultWaitDuration); assertThat(dynamicCircuitBreaker.getCircuitBreakerConfig().getSlidingWindowSize()) .isEqualTo(defaultSlidingWindowSize); assertThat(dynamicCircuitBreaker.getCircuitBreakerConfig() .getPermittedNumberOfCallsInHalfOpenState()) .isEqualTo(defaultPermittedNumberOfCallsInHalfOpenState); assertThat(dynamicCircuitBreaker.getCircuitBreakerConfig().getFailureRateThreshold()) .isEqualTo(defaultFailureRate); assertThat(dynamicCircuitBreaker.getCircuitBreakerConfig().getWaitIntervalFunctionInOpenState().apply(1)) .isEqualTo(defaultWaitDuration); } private void verifyHealthIndicatorResponse(ResponseEntity<CompositeHealthResponse> healthResponse) { Assertions.assertThat(healthResponse.getBody().getDetails()).isNotNull(); assertThat(healthResponse.getBody().getDetails().get("backendA")).isNotNull(); assertThat(healthResponse.getBody().getDetails().get("backendB")).isNull(); assertThat(healthResponse.getBody().getDetails().get("backendSharedA")).isNotNull(); assertThat(healthResponse.getBody().getDetails().get("backendSharedB")).isNotNull(); assertThat(healthResponse.getBody().getDetails().get("dynamicBackend")).isNotNull(); } private void verifyCircuitBreakerAutoConfiguration(CircuitBreaker circuitBreaker) { int ok=HttpStatus.SC_OK; assertThat(circuitBreaker).isNotNull(); // expect CircuitBreaker is configured as defined in application.yml assertThat(circuitBreaker.getCircuitBreakerConfig().getSlidingWindowSize()).isEqualTo(6); assertThat( circuitBreaker.getCircuitBreakerConfig().getPermittedNumberOfCallsInHalfOpenState()) .isEqualTo(2); assertThat(circuitBreaker.getCircuitBreakerConfig().getFailureRateThreshold()) .isEqualTo(70f); assertThat(circuitBreaker.getCircuitBreakerConfig().getWaitIntervalFunctionInOpenState().apply(1)) .isEqualByComparingTo(5000L); assertThat(circuitBreaker.getCircuitBreakerConfig().getRecordExceptionPredicate() .test(new RecordedException())).isTrue(); assertThat(circuitBreaker.getCircuitBreakerConfig().getIgnoreExceptionPredicate() .test(new IgnoredException())).isTrue(); assertThat(circuitBreaker.getCircuitBreakerConfig().getRecordResultPredicate() .test(ok)).isFalse(); // Verify that an exception for which setRecordFailurePredicate returns false and it is not included in // setRecordExceptions evaluates to false. assertThat(circuitBreaker.getCircuitBreakerConfig().getRecordExceptionPredicate() .test(new Exception())).isFalse(); } private List<CircuitBreakerEventDTO> getCircuitBreakersEvents() { return getEventsFrom("/actuator/circuitbreakerevents"); } private List<CircuitBreakerEventDTO> getCircuitBreakerEvents(String name) { return getEventsFrom("/actuator/circuitbreakerevents/" + name); } private List<CircuitBreakerEventDTO> getEventsFrom(String path) { return restTemplate.getForEntity(path, CircuitBreakerEventsEndpointResponse.class) .getBody().getCircuitBreakerEvents(); } }
CircuitBreakerAutoConfigurationTest
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/optimizer/Optimizer.java
{ "start": 48650, "end": 49057 }
class ____ extends org.elasticsearch.xpack.ql.optimizer.OptimizerRules.SkipQueryOnLimitZero { @Override protected LogicalPlan skipPlan(Limit limit) { return Optimizer.skipPlan(limit); } } private static LogicalPlan skipPlan(UnaryPlan plan) { return new LocalRelation(plan.source(), new EmptyExecutable(plan.output())); } static
SkipQueryOnLimitZero
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/embeddedid/RelationInsideEmbeddableNotAuditedTest.java
{ "start": 6482, "end": 6981 }
class ____ implements Serializable { private Integer id; @ManyToOne(fetch = FetchType.LAZY) private Author author; BookId() { } BookId(Integer id, Author author) { this.id = id; this.author = author; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } } @Entity(name = "Author") public static
BookId
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/errorhandler/RedeliveryErrorHandler.java
{ "start": 3162, "end": 14393 }
class ____ extends ErrorHandlerSupport implements ErrorHandlerRedeliveryCustomizer, AsyncProcessor, ShutdownPrepared, Navigate<Processor> { private static final Logger LOG = LoggerFactory.getLogger(RedeliveryErrorHandler.class); // factory protected PooledExchangeTaskFactory taskFactory; // state protected final AtomicInteger redeliverySleepCounter = new AtomicInteger(); protected ScheduledExecutorService executorService; protected volatile boolean preparingShutdown; // output protected Processor output; protected AsyncProcessor outputAsync; // configuration protected final CamelContext camelContext; protected final ReactiveExecutor reactiveExecutor; protected final AsyncProcessorAwaitManager awaitManager; protected final ShutdownStrategy shutdownStrategy; protected final Processor deadLetter; protected final String deadLetterUri; protected final boolean deadLetterHandleNewException; protected final Processor redeliveryProcessor; protected final RedeliveryPolicy redeliveryPolicy; protected final Predicate retryWhilePolicy; protected final CamelLogger logger; protected final boolean useOriginalMessagePolicy; protected final boolean useOriginalBodyPolicy; protected boolean redeliveryEnabled; protected boolean simpleTask; protected final ExchangeFormatter exchangeFormatter; protected final boolean customExchangeFormatter; protected final Processor onPrepareProcessor; protected final Processor onExceptionProcessor; public RedeliveryErrorHandler(CamelContext camelContext, Processor output, CamelLogger logger, Processor redeliveryProcessor, RedeliveryPolicy redeliveryPolicy, Processor deadLetter, String deadLetterUri, boolean deadLetterHandleNewException, boolean useOriginalMessagePolicy, boolean useOriginalBodyPolicy, Predicate retryWhile, ScheduledExecutorService executorService, Processor onPrepareProcessor, Processor onExceptionProcessor) { ObjectHelper.notNull(camelContext, "CamelContext", this); ObjectHelper.notNull(redeliveryPolicy, "RedeliveryPolicy", this); this.camelContext = camelContext; this.reactiveExecutor = requireNonNull(camelContext.getCamelContextExtension().getReactiveExecutor()); this.awaitManager = PluginHelper.getAsyncProcessorAwaitManager(camelContext); this.shutdownStrategy = requireNonNull(camelContext.getShutdownStrategy()); this.redeliveryProcessor = redeliveryProcessor; this.deadLetter = deadLetter; this.output = output; this.outputAsync = AsyncProcessorConverterHelper.convert(output); this.redeliveryPolicy = redeliveryPolicy; this.logger = logger; this.deadLetterUri = deadLetterUri; this.deadLetterHandleNewException = deadLetterHandleNewException; this.useOriginalMessagePolicy = useOriginalMessagePolicy; this.useOriginalBodyPolicy = useOriginalBodyPolicy; this.retryWhilePolicy = retryWhile; this.executorService = executorService; this.onPrepareProcessor = onPrepareProcessor; this.onExceptionProcessor = onExceptionProcessor; if (ObjectHelper.isNotEmpty(redeliveryPolicy.getExchangeFormatterRef())) { ExchangeFormatter formatter = camelContext.getRegistry() .lookupByNameAndType(redeliveryPolicy.getExchangeFormatterRef(), ExchangeFormatter.class); if (formatter != null) { this.exchangeFormatter = formatter; this.customExchangeFormatter = true; } else { throw new IllegalArgumentException( "Cannot find the exchangeFormatter by using reference id " + redeliveryPolicy.getExchangeFormatterRef()); } } else { this.customExchangeFormatter = false; this.exchangeFormatter = DEFAULT_EXCHANGE_FORMATTER; try { Integer maxChars = CamelContextHelper.parseInteger(camelContext, camelContext.getGlobalOption(Exchange.LOG_DEBUG_BODY_MAX_CHARS)); if (maxChars != null) { DEFAULT_EXCHANGE_FORMATTER.setMaxChars(maxChars); } } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeCamelException(e); } } ExceptionPolicyStrategy customExceptionPolicy = CamelContextHelper.findSingleByType(camelContext, ExceptionPolicyStrategy.class); if (customExceptionPolicy != null) { exceptionPolicy = customExceptionPolicy; } } @Override public void process(Exchange exchange) { if (output == null) { // no output then just return return; } awaitManager.process(this, exchange); } /** * Process the exchange using redelivery error handling. */ @Override public boolean process(final Exchange exchange, final AsyncCallback callback) { try { // Create the redelivery task object for this exchange (optimize to only create task can do redelivery or not) Runnable task = taskFactory.acquire(exchange, callback); // Run it if (exchange.isTransacted()) { reactiveExecutor.scheduleQueue(task); } else { reactiveExecutor.scheduleMain(task); } return false; } catch (Exception e) { exchange.setException(e); callback.done(true); return true; } } @Override public CompletableFuture<Exchange> processAsync(Exchange exchange) { AsyncCallbackToCompletableFutureAdapter<Exchange> callback = new AsyncCallbackToCompletableFutureAdapter<>(exchange); process(exchange, callback); return callback.getFuture(); } @Override public void changeOutput(Processor output) { this.output = output; this.outputAsync = AsyncProcessorConverterHelper.convert(output); } @Override public boolean supportTransacted() { return false; } @Override public boolean hasNext() { return output != null; } @Override public List<Processor> next() { if (!hasNext()) { return null; } List<Processor> answer = new ArrayList<>(1); answer.add(output); return answer; } protected boolean isRunAllowedOnPreparingShutdown() { return false; } @Override public void prepareShutdown(boolean suspendOnly, boolean forced) { // prepare for shutdown, eg do not allow redelivery if configured LOG.trace("Prepare shutdown on error handler: {}", this); preparingShutdown = true; } /** * <p> * Determines the redelivery delay time by first inspecting the Message header {@link Exchange#REDELIVERY_DELAY} and * if not present, defaulting to {@link RedeliveryPolicy#calculateRedeliveryDelay(long, int)} * </p> * * <p> * In order to prevent manipulation of the RedeliveryData state, the values of * {@link RedeliveryTask#redeliveryDelay} and {@link RedeliveryTask#redeliveryCounter} are copied in. * </p> * * @param exchange The current exchange in question. * @param redeliveryPolicy The RedeliveryPolicy to use in the calculation. * @param redeliveryDelay The default redelivery delay from RedeliveryData * @param redeliveryCounter The redeliveryCounter * @return The time to wait before the next redelivery. */ protected long determineRedeliveryDelay( Exchange exchange, RedeliveryPolicy redeliveryPolicy, long redeliveryDelay, int redeliveryCounter) { Message message = exchange.getIn(); Long delay = message.getHeader(Exchange.REDELIVERY_DELAY, Long.class); if (delay == null) { delay = redeliveryPolicy.calculateRedeliveryDelay(redeliveryDelay, redeliveryCounter); LOG.debug("Redelivery delay calculated as {}", delay); } else { LOG.debug("Redelivery delay is {} from Message Header [{}]", delay, Exchange.REDELIVERY_DELAY); } return delay; } /** * Performs a defensive copy of the exchange if needed * * @param exchange the exchange * @return the defensive copy, or <tt>null</tt> if not needed (redelivery is not enabled). */ protected Exchange defensiveCopyExchangeIfNeeded(Exchange exchange) { // only do a defensive copy if redelivery is enabled if (redeliveryEnabled) { return ExchangeHelper.createCopy(exchange, true); } else { return null; } } /** * Strategy to determine if the exchange is done so we can continue */ protected boolean isDone(Exchange exchange) { if (exchange.getExchangeExtension().isInterrupted()) { // mark the exchange to stop continue routing when interrupted // as we do not want to continue routing (for example a task has been cancelled) if (LOG.isTraceEnabled()) { LOG.trace("Is exchangeId: {} interrupted? true", exchange.getExchangeId()); } exchange.setRouteStop(true); return true; } // only done if the exchange hasn't failed // and it has not been handled by the failure processor // or we are exhausted boolean answer = exchange.getException() == null || ExchangeHelper.isFailureHandled(exchange) || exchange.getExchangeExtension().isRedeliveryExhausted(); if (LOG.isTraceEnabled()) { LOG.trace("Is exchangeId: {} done? {}", exchange.getExchangeId(), answer); } return answer; } @Override public Processor getOutput() { return output; } /** * Returns the dead letter that message exchanges will be sent to if the redelivery attempts fail */ public Processor getDeadLetter() { return deadLetter; } public String getDeadLetterUri() { return deadLetterUri; } public boolean isUseOriginalMessagePolicy() { return useOriginalMessagePolicy; } public boolean isUseOriginalBodyPolicy() { return useOriginalBodyPolicy; } public boolean isDeadLetterHandleNewException() { return deadLetterHandleNewException; } public RedeliveryPolicy getRedeliveryPolicy() { return redeliveryPolicy; } public CamelLogger getLogger() { return logger; } protected Predicate getDefaultHandledPredicate() { // Default is not not handle errors return null; } /** * Simple task to perform calling the processor with no redelivery support */ protected
RedeliveryErrorHandler
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/internal/ResultSetMappingSecondPass.java
{ "start": 457, "end": 3902 }
class ____ implements QuerySecondPass { // private static final CoreMessageLogger LOG = CoreLogging.messageLogger( ResultsetMappingSecondPass.class ); private final SqlResultSetMapping annotation; private final MetadataBuildingContext context; private final boolean isDefault; public ResultSetMappingSecondPass(SqlResultSetMapping annotation, MetadataBuildingContext context, boolean isDefault) { this.annotation = annotation; this.context = context; this.isDefault = isDefault; } @Override public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws MappingException { if ( annotation == null ) { return; } final var mappingDefinition = SqlResultSetMappingDescriptor.from( annotation ); if ( isDefault ) { context.getMetadataCollector().addDefaultResultSetMapping( mappingDefinition ); } else { context.getMetadataCollector().addResultSetMapping( mappingDefinition ); } //TODO add parameters checkings // if ( ann == null ) return; // ResultSetMappingDescriptor definition = new ResultSetMappingDescriptor( ann.name() ); // LOG.tracef( "Binding result set mapping: %s", definition.getName() ); // // int entityAliasIndex = 0; // // for (EntityResult entity : ann.entities()) { // //TODO parameterize lock mode? // List<FieldResult> properties = new ArrayList<FieldResult>(); // List<String> propertyNames = new ArrayList<String>(); // for (FieldResult field : entity.fields()) { // //use an ArrayList cause we might have several columns per root property // String name = field.name(); // if ( name.indexOf( '.' ) == -1 ) { // //regular property // properties.add( field ); // propertyNames.add( name ); // } // else { // /** // * Reorder properties // * 1. get the parent property // * 2. list all the properties following the expected one in the parent property // * 3. calculate the lowest index and insert the property // */ // PersistentClass pc = context.getMetadataCollector().getEntityBinding( // entity.entityClass().getName() // ); // if ( pc == null ) { // throw new MappingException( // String.format( // Locale.ENGLISH, // "Could not resolve entity [%s] referenced in SqlResultSetMapping [%s]", // entity.entityClass().getName(), // ann.name() // ) // ); // } // int dotIndex = name.lastIndexOf( '.' ); // String reducedName = name.substring( 0, dotIndex ); // Iterator parentPropItr = getSubPropertyIterator( pc, reducedName ); // List<String> followers = getFollowers( parentPropItr, reducedName, name ); // // int index = propertyNames.size(); // for ( String follower : followers ) { // int currentIndex = getIndexOfFirstMatchingProperty( propertyNames, follower ); // index = currentIndex != -1 && currentIndex < index ? currentIndex : index; // } // propertyNames.add( index, name ); // properties.add( index, field ); // } // } // // Set<String> uniqueReturnProperty = new HashSet<String>(); // Map<String, ArrayList<String>> propertyResultsTmp = new HashMap<String, ArrayList<String>>(); // for ( Object property : properties ) { // final FieldResult propertyresult = ( FieldResult ) property; // final String name = propertyresult.name(); // if ( "class".equals( name ) ) { // throw new MappingException( // "
ResultSetMappingSecondPass
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/IndexService.java
{ "start": 52389, "end": 52941 }
class ____ extends BaseAsyncTask { AsyncRefreshTask(IndexService indexService) { super( indexService, indexService.threadPool.executor(ThreadPool.Names.REFRESH), indexService.getIndexSettings().getRefreshInterval() ); } @Override protected void runInternal() { indexService.maybeRefreshEngine(false); } @Override public String toString() { return "refresh"; } } final
AsyncRefreshTask
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/event/FilterArgsEvent.java
{ "start": 760, "end": 1141 }
class ____ extends ApplicationEvent { private final Map<String, Object> args; private String routeId; public FilterArgsEvent(Object source, String routeId, Map<String, Object> args) { super(source); this.routeId = routeId; this.args = args; } public String getRouteId() { return routeId; } public Map<String, Object> getArgs() { return args; } }
FilterArgsEvent
java
google__guava
android/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java
{ "start": 20076, "end": 20798 }
class ____ extends TestDoubleListGenerator { @Override protected List<Double> create(Double[] elements) { Double[] prefix = {Double.MIN_VALUE, Double.MAX_VALUE}; Double[] suffix = {86.0, 99.0}; Double[] all = concat(concat(prefix, elements), suffix); return makeArray(all).subArray(2, elements.length + 2).asList(); } } @J2ktIncompatible @GwtIncompatible // used only from suite @AndroidIncompatible private static Double[] concat(Double[] a, Double[] b) { return ObjectArrays.concat(a, b, Double.class); } @J2ktIncompatible @GwtIncompatible // used only from suite @AndroidIncompatible public abstract static
ImmutableDoubleArrayMiddleSubListAsListGenerator
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvMaxBooleanEvaluator.java
{ "start": 4896, "end": 5385 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final EvalOperator.ExpressionEvaluator.Factory field; public Factory(EvalOperator.ExpressionEvaluator.Factory field) { this.field = field; } @Override public MvMaxBooleanEvaluator get(DriverContext context) { return new MvMaxBooleanEvaluator(field.get(context), context); } @Override public String toString() { return "MvMax[field=" + field + "]"; } } }
Factory
java
quarkusio__quarkus
extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/checker/PermissionChecker6thMethodArg.java
{ "start": 245, "end": 712 }
class ____ extends AbstractNthMethodArgChecker { @Inject SecurityIdentity identity; @PermissionChecker("6th-arg") boolean is6thMethodArgOk(Object six) { return this.argsOk(6, six, identity); } @PermissionChecker("another-6th-arg") boolean is6thMethodArgOk_Another(Object six) { if (six instanceof Long) { return false; } return this.argsOk(6, six, identity); } }
PermissionChecker6thMethodArg
java
apache__spark
common/network-common/src/test/java/org/apache/spark/network/ssl/SslSampleConfigs.java
{ "start": 1740, "end": 10430 }
class ____ { public static final String keyStorePath = getAbsolutePath("/keystore"); public static final String privateKeyPath = getAbsolutePath("/key.pem"); public static final String certChainPath = getAbsolutePath("/certchain.pem"); public static final String untrustedKeyStorePath = getAbsolutePath("/untrusted-keystore"); public static final String trustStorePath = getAbsolutePath("/truststore"); public static final String unencryptedPrivateKeyPath = getAbsolutePath("/unencrypted-key.pem"); public static final String unencryptedCertChainPath = getAbsolutePath("/unencrypted-certchain.pem"); /** * Creates a config map containing the settings needed to enable the RPC SSL feature * All the settings (except the enabled one) are intentionally set on the parent namespace * so that we can verify settings inheritance works. We intentionally set conflicting * options for the key password to verify that is handled correctly. */ public static Map<String, String> createDefaultConfigMap() { Map<String, String> confMap = new HashMap<String, String>(); confMap.put("spark.ssl.rpc.enabled", "true"); confMap.put("spark.ssl.rpc.openSslEnabled", "true"); confMap.put("spark.ssl.rpc.privateKey", SslSampleConfigs.unencryptedPrivateKeyPath); // intentionally not set // confMap.put("spark.ssl.rpc.privateKeyPassword", "password"); confMap.put("spark.ssl.rpc.certChain", SslSampleConfigs.unencryptedCertChainPath); confMap.put("spark.ssl.enabled", "true"); confMap.put("spark.ssl.keyPassword", "password"); confMap.put("spark.ssl.trustStoreReloadingEnabled", "false"); confMap.put("spark.ssl.trustStoreReloadIntervalMs", "10000"); confMap.put("spark.ssl.keyStore", SslSampleConfigs.keyStorePath); confMap.put("spark.ssl.keyStorePassword", "password"); confMap.put("spark.ssl.trustStore", SslSampleConfigs.trustStorePath); confMap.put("spark.ssl.trustStorePassword", "password"); confMap.put("spark.ssl.protocol", "TLSv1.3"); confMap.put("spark.ssl.standalone.enabled", "true"); confMap.put("spark.ssl.ui.enabled", "true"); return confMap; } /** * Similar to the above, but sets the settings directly in the spark.ssl.rpc namespace * This is needed for testing in the lower level modules (like network-common) where inheritance * does not work as there is no access to SSLOptions. */ public static Map<String, String> createDefaultConfigMapForRpcNamespace() { Map<String, String> confMap = new HashMap<String, String>(); confMap.put("spark.ssl.rpc.enabled", "true"); confMap.put("spark.ssl.rpc.trustStoreReloadingEnabled", "false"); confMap.put("spark.ssl.rpc.openSslEnabled", "false"); confMap.put("spark.ssl.rpc.trustStoreReloadIntervalMs", "10000"); confMap.put("spark.ssl.rpc.keyStore", SslSampleConfigs.keyStorePath); confMap.put("spark.ssl.rpc.keyStorePassword", "password"); confMap.put("spark.ssl.rpc.privateKey", SslSampleConfigs.privateKeyPath); confMap.put("spark.ssl.rpc.keyPassword", "password"); confMap.put("spark.ssl.rpc.privateKeyPassword", "password"); confMap.put("spark.ssl.rpc.certChain", SslSampleConfigs.certChainPath); confMap.put("spark.ssl.rpc.trustStore", SslSampleConfigs.trustStorePath); confMap.put("spark.ssl.rpc.trustStorePassword", "password"); return confMap; } /** * Create ConfigProvider based on the method above */ public static ConfigProvider createDefaultConfigProviderForRpcNamespace() { return new MapConfigProvider(createDefaultConfigMapForRpcNamespace()); } /** * Create ConfigProvider based on the method above */ public static ConfigProvider createDefaultConfigProviderForRpcNamespaceWithAdditionalEntries( Map<String, String> entries) { Map<String, String> confMap = createDefaultConfigMapForRpcNamespace(); confMap.putAll(entries); return new MapConfigProvider(confMap); } public static void createTrustStore( File trustStore, String password, String alias, Certificate cert) throws GeneralSecurityException, IOException { KeyStore ks = createEmptyKeyStore(); ks.setCertificateEntry(alias, cert); saveKeyStore(ks, trustStore, password); } /** * Creates a keystore with multiple keys and saves it to a file. */ public static <T extends Certificate> void createTrustStore( File trustStore, String password, Map<String, T> certs) throws GeneralSecurityException, IOException { KeyStore ks = createEmptyKeyStore(); for (Map.Entry<String, T> cert : certs.entrySet()) { ks.setCertificateEntry(cert.getKey(), cert.getValue()); } saveKeyStore(ks, trustStore, password); } /** * Create a self-signed X.509 Certificate. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate */ @SuppressWarnings("deprecation") public static X509Certificate generateCertificate( String dn, KeyPair pair, int days, String algorithm) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException { Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); KeyPair keyPair = pair; X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal dnName = new X500Principal(dn); certGen.setSerialNumber(sn); certGen.setIssuerDN(dnName); certGen.setNotBefore(from); certGen.setNotAfter(to); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(algorithm); X509Certificate cert = certGen.generate(pair.getPrivate()); return cert; } public static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(1024); return keyGen.genKeyPair(); } /** * Creates a keystore with a single key and saves it to a file. * * @param keyStore File keystore to save * @param password String store password to set on keystore * @param keyPassword String key password to set on key * @param alias String alias to use for the key * @param privateKey Key to save in keystore * @param cert Certificate to use as certificate chain associated to key * @throws GeneralSecurityException for any error with the security APIs * @throws IOException if there is an I/O error saving the file */ public static void createKeyStore( File keyStore, String password, String keyPassword, String alias, Key privateKey, Certificate cert) throws GeneralSecurityException, IOException { KeyStore ks = createEmptyKeyStore(); ks.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), new Certificate[]{cert}); saveKeyStore(ks, keyStore, password); } public static void createKeyStore( File keyStore, String password, String alias, Key privateKey, Certificate cert) throws GeneralSecurityException, IOException { KeyStore ks = createEmptyKeyStore(); ks.setKeyEntry(alias, privateKey, password.toCharArray(), new Certificate[]{cert}); saveKeyStore(ks, keyStore, password); } private static KeyStore createEmptyKeyStore() throws GeneralSecurityException, IOException { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); // initialize return ks; } private static void saveKeyStore( KeyStore ks, File keyStore, String password) throws GeneralSecurityException, IOException { // Write the file atomically to ensure tests don't read a partial write File tempFile = File.createTempFile("temp-key-store", "jks"); FileOutputStream out = new FileOutputStream(tempFile); try { ks.store(out, password.toCharArray()); out.close(); Files.move( tempFile.toPath(), keyStore.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); } finally { out.close(); } } public static String getAbsolutePath(String path) { try { return new File(SslSampleConfigs.class.getResource(path).getFile()).getCanonicalPath(); } catch (IOException e) { throw new RuntimeException("Failed to resolve path " + path, e); } } }
SslSampleConfigs
java
elastic__elasticsearch
x-pack/plugin/fleet/src/internalClusterTest/java/org/elasticsearch/xpack/fleet/action/SearchUsageStatsIT.java
{ "start": 1169, "end": 5223 }
class ____ extends ESIntegTestCase { @Override protected boolean addMockHttpTransport() { return false; // enable http } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Stream.of(Fleet.class, LocalStateCompositeXPackPlugin.class, IndexLifecycle.class).collect(Collectors.toList()); } public void testSearchUsageStats() throws IOException { { SearchUsageStats stats = clusterAdmin().prepareClusterStats().get().getIndicesStats().getSearchUsageStats(); assertEquals(0, stats.getTotalSearchCount()); assertEquals(0, stats.getQueryUsage().size()); assertEquals(0, stats.getSectionsUsage().size()); } indicesAdmin().prepareCreate("index").get(); ensureGreen("index"); // doesn't get counted because it doesn't specify a request body getRestClient().performRequest(new Request("GET", "/index/_fleet/_fleet_search")); { Request request = new Request("GET", "/index/_fleet/_fleet_search"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchQuery("field", "value")); request.setJsonEntity(Strings.toString(searchSourceBuilder)); getRestClient().performRequest(request); } { Request request = new Request("GET", "/index/_fleet/_fleet_search"); // error at parsing: request not counted request.setJsonEntity("{\"unknown]\":10}"); expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); } { // non existent index: request counted Request request = new Request("GET", "/unknown/_fleet/_fleet_search"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.termQuery("field", "value")); request.setJsonEntity(Strings.toString(searchSourceBuilder)); ResponseException responseException = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); assertEquals(404, responseException.getResponse().getStatusLine().getStatusCode()); } { Request request = new Request("GET", "/index/_fleet/_fleet_search"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query( QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("field").from(10)) ); request.setJsonEntity(Strings.toString(searchSourceBuilder)); getRestClient().performRequest(request); } { Request request = new Request("POST", "/index/_fleet/_fleet_msearch"); SearchSourceBuilder searchSourceBuilder1 = new SearchSourceBuilder().aggregation( new TermsAggregationBuilder("name").field("field") ); SearchSourceBuilder searchSourceBuilder2 = new SearchSourceBuilder().query(QueryBuilders.termQuery("field", "value")); request.setJsonEntity( "{}\n" + Strings.toString(searchSourceBuilder1) + "\n" + "{}\n" + Strings.toString(searchSourceBuilder2) + "\n" ); getRestClient().performRequest(request); } SearchUsageStats stats = clusterAdmin().prepareClusterStats().get().getIndicesStats().getSearchUsageStats(); assertEquals(5, stats.getTotalSearchCount()); assertEquals(4, stats.getQueryUsage().size()); assertEquals(1, stats.getQueryUsage().get("match").longValue()); assertEquals(2, stats.getQueryUsage().get("term").longValue()); assertEquals(1, stats.getQueryUsage().get("range").longValue()); assertEquals(1, stats.getQueryUsage().get("bool").longValue()); assertEquals(2, stats.getSectionsUsage().size()); assertEquals(4, stats.getSectionsUsage().get("query").longValue()); assertEquals(1, stats.getSectionsUsage().get("aggs").longValue()); } }
SearchUsageStatsIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlWithArrayEmbeddableTest.java
{ "start": 2450, "end": 13343 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new XmlHolder( 1L, EmbeddableWithArrayAggregate.createAggregate1() ) ); session.persist( new XmlHolder( 2L, EmbeddableWithArrayAggregate.createAggregate2() ) ); } ); } @AfterEach protected void cleanupTest(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( session -> { XmlHolder XmlHolder = session.find( XmlHolder.class, 1L ); XmlHolder.setAggregate( EmbeddableWithArrayAggregate.createAggregate2() ); session.flush(); session.clear(); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test public void testFetch(SessionFactoryScope scope) { scope.inSession( session -> { List<XmlHolder> XmlHolders = session.createQuery( "from XmlHolder b where b.id = 1", XmlHolder.class ).getResultList(); assertEquals( 1, XmlHolders.size() ); assertEquals( 1L, XmlHolders.get( 0 ).getId() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), XmlHolders.get( 0 ).getAggregate() ); } ); } @Test public void testFetchNull(SessionFactoryScope scope) { scope.inSession( session -> { List<XmlHolder> XmlHolders = session.createQuery( "from XmlHolder b where b.id = 2", XmlHolder.class ).getResultList(); assertEquals( 1, XmlHolders.size() ); assertEquals( 2L, XmlHolders.get( 0 ).getId() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), XmlHolders.get( 0 ).getAggregate() ); } ); } @Test public void testDomainResult(SessionFactoryScope scope) { scope.inSession( session -> { List<EmbeddableWithArrayAggregate> structs = session.createQuery( "select b.aggregate from XmlHolder b where b.id = 1", EmbeddableWithArrayAggregate.class ).getResultList(); assertEquals( 1, structs.size() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), structs.get( 0 ) ); } ); } @Test public void testSelectionItems(SessionFactoryScope scope) { scope.inSession( session -> { List<Tuple> tuples = session.createQuery( "select " + "b.aggregate.theInt," + "b.aggregate.theDouble," + "b.aggregate.theBoolean," + "b.aggregate.theNumericBoolean," + "b.aggregate.theStringBoolean," + "b.aggregate.theString," + "b.aggregate.theInteger," + "b.aggregate.theUrl," + "b.aggregate.theClob," + "b.aggregate.theBinary," + "b.aggregate.theDate," + "b.aggregate.theTime," + "b.aggregate.theTimestamp," + "b.aggregate.theInstant," + "b.aggregate.theUuid," + "b.aggregate.gender," + "b.aggregate.convertedGender," + "b.aggregate.ordinalGender," + "b.aggregate.theDuration," + "b.aggregate.theLocalDateTime," + "b.aggregate.theLocalDate," + "b.aggregate.theLocalTime," + "b.aggregate.theZonedDateTime," + "b.aggregate.theOffsetDateTime," + "b.aggregate.mutableValue " + "from XmlHolder b where b.id = 1", Tuple.class ).getResultList(); assertEquals( 1, tuples.size() ); final Tuple tuple = tuples.get( 0 ); final EmbeddableWithArrayAggregate struct = new EmbeddableWithArrayAggregate(); struct.setTheInt( tuple.get( 0, int[].class ) ); struct.setTheDouble( tuple.get( 1, double[].class ) ); struct.setTheBoolean( tuple.get( 2, Boolean[].class ) ); struct.setTheNumericBoolean( tuple.get( 3, Boolean[].class ) ); struct.setTheStringBoolean( tuple.get( 4, Boolean[].class ) ); struct.setTheString( tuple.get( 5, String[].class ) ); struct.setTheInteger( tuple.get( 6, Integer[].class ) ); struct.setTheUrl( tuple.get( 7, URL[].class ) ); struct.setTheClob( tuple.get( 8, String[].class ) ); struct.setTheBinary( tuple.get( 9, byte[][].class ) ); struct.setTheDate( tuple.get( 10, Date[].class ) ); struct.setTheTime( tuple.get( 11, Time[].class ) ); struct.setTheTimestamp( tuple.get( 12, Timestamp[].class ) ); struct.setTheInstant( tuple.get( 13, Instant[].class ) ); struct.setTheUuid( tuple.get( 14, UUID[].class ) ); struct.setGender( tuple.get( 15, EntityOfBasics.Gender[].class ) ); struct.setConvertedGender( tuple.get( 16, EntityOfBasics.Gender[].class ) ); struct.setOrdinalGender( tuple.get( 17, EntityOfBasics.Gender[].class ) ); struct.setTheDuration( tuple.get( 18, Duration[].class ) ); struct.setTheLocalDateTime( tuple.get( 19, LocalDateTime[].class ) ); struct.setTheLocalDate( tuple.get( 20, LocalDate[].class ) ); struct.setTheLocalTime( tuple.get( 21, LocalTime[].class ) ); struct.setTheZonedDateTime( tuple.get( 22, ZonedDateTime[].class ) ); struct.setTheOffsetDateTime( tuple.get( 23, OffsetDateTime[].class ) ); struct.setMutableValue( tuple.get( 24, MutableValue[].class ) ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), struct ); } ); } @Test public void testDeleteWhere(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "delete XmlHolder b where b.aggregate is not null" ).executeUpdate(); assertNull( session.find( XmlHolder.class, 1L ) ); } ); } @Test public void testUpdateAggregate(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "update XmlHolder b set b.aggregate = null" ).executeUpdate(); assertNull( session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) public void testUpdateAggregateMember(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); EmbeddableWithArrayAggregate.assertEquals( struct, session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); EmbeddableWithArrayAggregate.assertEquals( struct, session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) @SkipForDialect( dialectClass = OracleDialect.class, reason = "External driver fix required") public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( session -> { EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); session.createMutationQuery( "update XmlHolder b set " + "b.aggregate.theInt = :theInt," + "b.aggregate.theDouble = :theDouble," + "b.aggregate.theBoolean = :theBoolean," + "b.aggregate.theNumericBoolean = :theNumericBoolean," + "b.aggregate.theStringBoolean = :theStringBoolean," + "b.aggregate.theString = :theString," + "b.aggregate.theInteger = :theInteger," + "b.aggregate.theUrl = :theUrl," + "b.aggregate.theClob = :theClob," + "b.aggregate.theBinary = :theBinary," + "b.aggregate.theDate = :theDate," + "b.aggregate.theTime = :theTime," + "b.aggregate.theTimestamp = :theTimestamp," + "b.aggregate.theInstant = :theInstant," + "b.aggregate.theUuid = :theUuid," + "b.aggregate.gender = :gender," + "b.aggregate.convertedGender = :convertedGender," + "b.aggregate.ordinalGender = :ordinalGender," + "b.aggregate.theDuration = :theDuration," + "b.aggregate.theLocalDateTime = :theLocalDateTime," + "b.aggregate.theLocalDate = :theLocalDate," + "b.aggregate.theLocalTime = :theLocalTime," + "b.aggregate.theZonedDateTime = :theZonedDateTime," + "b.aggregate.theOffsetDateTime = :theOffsetDateTime," + "b.aggregate.mutableValue = :mutableValue " + "where b.id = 2" ) .setParameter( "theInt", struct.getTheInt() ) .setParameter( "theDouble", struct.getTheDouble() ) .setParameter( "theBoolean", struct.getTheBoolean() ) .setParameter( "theNumericBoolean", struct.getTheNumericBoolean() ) .setParameter( "theStringBoolean", struct.getTheStringBoolean() ) .setParameter( "theString", struct.getTheString() ) .setParameter( "theInteger", struct.getTheInteger() ) .setParameter( "theUrl", struct.getTheUrl() ) .setParameter( "theClob", struct.getTheClob() ) .setParameter( "theBinary", struct.getTheBinary() ) .setParameter( "theDate", struct.getTheDate() ) .setParameter( "theTime", struct.getTheTime() ) .setParameter( "theTimestamp", struct.getTheTimestamp() ) .setParameter( "theInstant", struct.getTheInstant() ) .setParameter( "theUuid", struct.getTheUuid() ) .setParameter( "gender", struct.getGender() ) .setParameter( "convertedGender", struct.getConvertedGender() ) .setParameter( "ordinalGender", struct.getOrdinalGender() ) .setParameter( "theDuration", struct.getTheDuration() ) .setParameter( "theLocalDateTime", struct.getTheLocalDateTime() ) .setParameter( "theLocalDate", struct.getTheLocalDate() ) .setParameter( "theLocalTime", struct.getTheLocalTime() ) .setParameter( "theZonedDateTime", struct.getTheZonedDateTime() ) .setParameter( "theOffsetDateTime", struct.getTheOffsetDateTime() ) .setParameter( "mutableValue", struct.getMutableValue() ) .executeUpdate(); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), session.find( XmlHolder.class, 2L ).getAggregate() ); } ); } @Entity(name = "XmlHolder") public static
XmlWithArrayEmbeddableTest
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/Key.java
{ "start": 150, "end": 675 }
interface ____ uniquely identifies some put of data. Implementations must implement {@link * Object#equals(Object)} and {@link Object#hashCode()}. Implementations are generally expected to * add all uniquely identifying information used in in {@link java.lang.Object#equals(Object)}} and * {@link Object#hashCode()}} to the given {@link java.security.MessageDigest} in {@link * #updateDiskCacheKey(java.security.MessageDigest)}}, although this requirement is not as strict * for partial cache key signatures. */ public
that
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/datageneration/matchers/Matcher.java
{ "start": 1828, "end": 3428 }
class ____<T> implements SettingsStep<T>, CompareStep<T>, ExpectedStep<T> { private final XContentBuilder expectedMappings; private final XContentBuilder actualMappings; private Settings.Builder expectedSettings; private Settings.Builder actualSettings; private T expected; private T actual; private boolean ignoringSort; @Override public ExpectedStep<T> settings(Settings.Builder actualSettings, Settings.Builder expectedSettings) { this.actualSettings = actualSettings; this.expectedSettings = expectedSettings; return this; } private Builder( final XContentBuilder actualMappings, final XContentBuilder expectedMappings ) { this.actualMappings = actualMappings; this.expectedMappings = expectedMappings; } @Override public MatchResult isEqualTo(T actual) { return new GenericEqualsMatcher<>( actualMappings, actualSettings, expectedMappings, expectedSettings, actual, expected, ignoringSort ).match(); } @Override public CompareStep<T> ignoringSort(boolean ignoringSort) { this.ignoringSort = ignoringSort; return this; } @Override public CompareStep<T> expected(T expected) { this.expected = expected; return this; } } private static
Builder
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/CachePoolInfo.java
{ "start": 1378, "end": 1557 }
class ____ used in RPCs to create and modify cache pools. * It is serializable and can be stored in the edit log. */ @InterfaceAudience.Public @InterfaceStability.Evolving public
is
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/language/XPathExpression.java
{ "start": 7664, "end": 8572 }
class ____ extends AbstractNamespaceAwareBuilder<Builder, XPathExpression> { private Class<?> documentType; private XPathFactory xpathFactory; private String documentTypeName; private String resultQName; private String saxon; private String factoryRef; private String objectModel; private String logNamespaces; private String threadSafety; private String preCompile; /** * Class for document type to use * <p/> * The default value is org.w3c.dom.Document */ public Builder documentType(Class<?> documentType) { this.documentType = documentType; return this; } public Builder xpathFactory(XPathFactory xpathFactory) { this.xpathFactory = xpathFactory; return this; } /** * Name of
Builder
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/HeaderFilterStrategyComponent.java
{ "start": 1066, "end": 1183 }
class ____ components to support configuring a {@link org.apache.camel.spi.HeaderFilterStrategy}. */ public abstract
for
java
apache__kafka
generator/src/main/java/org/apache/kafka/message/CoordinatorRecordJsonConvertersGenerator.java
{ "start": 3144, "end": 8856 }
class ____ {%n"); buffer.incrementIndent(); generateWriteKeyJson(); buffer.printf("%n"); generateWriteValueJson(); buffer.printf("%n"); generateReadKeyFromJson(); buffer.printf("%n"); generateReadValueFromJson(); buffer.printf("%n"); buffer.decrementIndent(); buffer.printf("}%n"); headerGenerator.generate(); headerGenerator.buffer().write(writer); buffer.write(writer); } private void generateWriteKeyJson() { headerGenerator.addImport(MessageGenerator.JSON_NODE_CLASS); headerGenerator.addImport(MessageGenerator.API_MESSAGE_CLASS); buffer.printf("public static JsonNode writeRecordKeyAsJson(ApiMessage key) {%n"); buffer.incrementIndent(); buffer.printf("switch (key.apiKey()) {%n"); buffer.incrementIndent(); for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) { String apiMessageClassName = MessageGenerator.capitalizeFirst(entry.getValue().key.name()); buffer.printf("case %d:%n", entry.getKey()); buffer.incrementIndent(); buffer.printf("return %sJsonConverter.write((%s) key, (short) 0);%n", apiMessageClassName, apiMessageClassName); buffer.decrementIndent(); } buffer.printf("default:%n"); buffer.incrementIndent(); headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS); buffer.printf("throw new UnsupportedVersionException(\"Unknown record id \"" + " + key.apiKey());%n"); buffer.decrementIndent(); buffer.decrementIndent(); buffer.printf("}%n"); buffer.decrementIndent(); buffer.printf("}%n"); } private void generateWriteValueJson() { headerGenerator.addImport(MessageGenerator.JSON_NODE_CLASS); headerGenerator.addImport(MessageGenerator.API_MESSAGE_CLASS); buffer.printf("public static JsonNode writeRecordValueAsJson(ApiMessage value, short version) {%n"); buffer.incrementIndent(); buffer.printf("switch (value.apiKey()) {%n"); buffer.incrementIndent(); for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) { String apiMessageClassName = MessageGenerator.capitalizeFirst(entry.getValue().value.name()); buffer.printf("case %d:%n", entry.getKey()); buffer.incrementIndent(); buffer.printf("return %sJsonConverter.write((%s) value, version);%n", apiMessageClassName, apiMessageClassName); buffer.decrementIndent(); } buffer.printf("default:%n"); buffer.incrementIndent(); headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS); buffer.printf("throw new UnsupportedVersionException(\"Unknown record id \"" + " + value.apiKey());%n"); buffer.decrementIndent(); buffer.decrementIndent(); buffer.printf("}%n"); buffer.decrementIndent(); buffer.printf("}%n"); } private void generateReadKeyFromJson() { headerGenerator.addImport(MessageGenerator.JSON_NODE_CLASS); headerGenerator.addImport(MessageGenerator.API_MESSAGE_CLASS); buffer.printf("public static ApiMessage readRecordKeyFromJson(JsonNode json, short apiKey) {%n"); buffer.incrementIndent(); buffer.printf("switch (apiKey) {%n"); buffer.incrementIndent(); for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) { String apiMessageClassName = MessageGenerator.capitalizeFirst(entry.getValue().key.name()); buffer.printf("case %d:%n", entry.getKey()); buffer.incrementIndent(); buffer.printf("return %sJsonConverter.read(json, (short) 0);%n", apiMessageClassName); buffer.decrementIndent(); } buffer.printf("default:%n"); buffer.incrementIndent(); headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS); buffer.printf("throw new UnsupportedVersionException(\"Unknown record id \"" + " + apiKey);%n"); buffer.decrementIndent(); buffer.decrementIndent(); buffer.printf("}%n"); buffer.decrementIndent(); buffer.printf("}%n"); } private void generateReadValueFromJson() { headerGenerator.addImport(MessageGenerator.JSON_NODE_CLASS); headerGenerator.addImport(MessageGenerator.API_MESSAGE_CLASS); buffer.printf("public static ApiMessage readRecordValueFromJson(JsonNode json, short apiKey, short version) {%n"); buffer.incrementIndent(); buffer.printf("switch (apiKey) {%n"); buffer.incrementIndent(); for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) { String apiMessageClassName = MessageGenerator.capitalizeFirst(entry.getValue().value.name()); buffer.printf("case %d:%n", entry.getKey()); buffer.incrementIndent(); buffer.printf("return %sJsonConverter.read(json, version);%n", apiMessageClassName); buffer.decrementIndent(); } buffer.printf("default:%n"); buffer.incrementIndent(); headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS); buffer.printf("throw new UnsupportedVersionException(\"Unknown record id \"" + " + apiKey);%n"); buffer.decrementIndent(); buffer.decrementIndent(); buffer.printf("}%n"); buffer.decrementIndent(); buffer.printf("}%n"); } }
CoordinatorRecordJsonConverters
java
elastic__elasticsearch
libs/x-content/src/test/java/org/elasticsearch/xcontent/ObjectParserTests.java
{ "start": 7356, "end": 8580 }
class ____ { public final ClassicParser parser; CustomParseContext(ClassicParser parser) { this.parser = parser; } public URI parseURI(XContentParser xContentParser) { try { return this.parser.parseURI(xContentParser); } catch (IOException e) { throw new UncheckedIOException(e); } } } XContentParser parser = createParser(JsonXContent.jsonXContent, """ {"url" : { "host": "http://foobar", "port" : 80}, "name" : "foobarbaz"}"""); ObjectParser<Foo, CustomParseContext> objectParser = new ObjectParser<>("foo"); objectParser.declareString(Foo::setName, new ParseField("name")); objectParser.declareObjectOrDefault(Foo::setUri, (p, s) -> s.parseURI(p), () -> null, new ParseField("url")); Foo s = objectParser.parse(parser, new Foo(), new CustomParseContext(new ClassicParser())); assertEquals(s.uri.getHost(), "foobar"); assertEquals(s.uri.getPort(), 80); assertEquals(s.name, "foobarbaz"); } public void testExceptions() throws IOException {
CustomParseContext
java
elastic__elasticsearch
modules/data-streams/src/yamlRestTest/java/org/elasticsearch/datastreams/DataStreamsClientYamlTestSuiteIT.java
{ "start": 1214, "end": 3380 }
class ____ extends ESClientYamlSuiteTestCase { public DataStreamsClientYamlTestSuiteIT(final ClientYamlTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return createParameters(); } private static final String BASIC_AUTH_VALUE = basicAuthHeaderValue("x_pack_rest_user", new SecureString("x-pack-test-password")); @Override protected Settings restClientSettings() { return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", BASIC_AUTH_VALUE).build(); } @ClassRule public static ElasticsearchCluster cluster = createCluster(); private static ElasticsearchCluster createCluster() { LocalClusterSpecBuilder<ElasticsearchCluster> clusterBuilder = ElasticsearchCluster.local() .distribution(DistributionType.DEFAULT) .setting("xpack.security.enabled", "true") .keystore("bootstrap.password", "x-pack-test-password") .user("x_pack_rest_user", "x-pack-test-password") .feature(FeatureFlag.LOGS_STREAM) .systemProperty("es.queryable_built_in_roles_enabled", "false"); if (initTestSeed().nextBoolean()) { clusterBuilder.setting("xpack.license.self_generated.type", "trial"); } boolean setNodes = Booleans.parseBoolean(System.getProperty("yaml.rest.tests.set_num_nodes", "true")); if (setNodes) { clusterBuilder.nodes(2); } // We need to disable ILM history based on a setting, to avoid errors in Serverless where the setting is not available. boolean disableILMHistory = Booleans.parseBoolean(System.getProperty("yaml.rest.tests.disable_ilm_history", "true")); if (disableILMHistory) { // disable ILM history, since it disturbs tests clusterBuilder.setting("indices.lifecycle.history_index_enabled", "false"); } return clusterBuilder.build(); } @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } }
DataStreamsClientYamlTestSuiteIT
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/beanmapping/SourceReference.java
{ "start": 14882, "end": 16447 }
class ____ { private String name; private ReadAccessor readAccessor; private PresenceCheckAccessor presenceChecker; private Type type; private Parameter sourceParameter; public BuilderFromProperty name(String name) { this.name = name; return this; } public BuilderFromProperty readAccessor(ReadAccessor readAccessor) { this.readAccessor = readAccessor; return this; } public BuilderFromProperty presenceChecker(PresenceCheckAccessor presenceChecker) { this.presenceChecker = presenceChecker; return this; } public BuilderFromProperty type(Type type) { this.type = type; return this; } public BuilderFromProperty sourceParameter(Parameter sourceParameter) { this.sourceParameter = sourceParameter; return this; } public SourceReference build() { List<PropertyEntry> sourcePropertyEntries = new ArrayList<>(); if ( readAccessor != null ) { sourcePropertyEntries.add( forSourceReference( new String[] { name }, readAccessor, presenceChecker, type ) ); } return new SourceReference( sourceParameter, sourcePropertyEntries, true ); } } /** * Builds a {@link SourceReference} from a property. */ public static
BuilderFromProperty
java
micronaut-projects__micronaut-core
http-netty/src/main/java/io/micronaut/http/netty/cookies/NettyCookieFactory.java
{ "start": 869, "end": 1043 }
class ____ implements CookieFactory { @Override public Cookie create(String name, String value) { return new NettyCookie(name, value); } }
NettyCookieFactory
java
quarkusio__quarkus
.github/ModuleBuildDurationReport.java
{ "start": 5764, "end": 5836 }
enum ____ { execution, name, duration } private static
Sort
java
google__dagger
examples/bazel/java/example/common/Pump.java
{ "start": 670, "end": 704 }
interface ____ { void pump(); }
Pump
java
apache__camel
components/camel-couchdb/src/main/java/org/apache/camel/component/couchdb/CouchDbComponent.java
{ "start": 1040, "end": 1501 }
class ____ extends DefaultComponent { public CouchDbComponent() { } public CouchDbComponent(CamelContext context) { super(context); } @Override protected CouchDbEndpoint createEndpoint(String uri, String remaining, Map<String, Object> params) throws Exception { CouchDbEndpoint endpoint = new CouchDbEndpoint(uri, remaining, this); setProperties(endpoint, params); return endpoint; } }
CouchDbComponent
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/LeadLagInputTypeStrategyTest.java
{ "start": 1072, "end": 2745 }
class ____ extends InputTypeStrategiesTestBase { @Override protected Stream<TestSpec> testData() { return Stream.of( TestSpec.forStrategy(SpecificInputTypeStrategies.LEAD_LAG) .calledWithArgumentTypes( DataTypes.BIGINT(), DataTypes.SMALLINT(), DataTypes.INT()) .calledWithLiteralAt(1) .expectSignature( "f(<ANY>)\n" + "f(<ANY>, <NUMERIC>)\n" + "f(<COMMON>, <NUMERIC>, <COMMON>)") .expectArgumentTypes( DataTypes.BIGINT(), DataTypes.SMALLINT(), DataTypes.BIGINT()), TestSpec.forStrategy(SpecificInputTypeStrategies.LEAD_LAG) .calledWithArgumentTypes( DataTypes.BIGINT(), DataTypes.SMALLINT(), DataTypes.STRING()) .expectErrorMessage( "The default value must have a" + " common type with the given expression. ARG0: BIGINT, " + "default: STRING"), TestSpec.forStrategy(SpecificInputTypeStrategies.LEAD_LAG) .calledWithArgumentTypes(DataTypes.BIGINT(), DataTypes.STRING()) .expectErrorMessage( "Unsupported argument type. " + "Expected type of family 'NUMERIC' but actual type was 'STRING'.")); } }
LeadLagInputTypeStrategyTest
java
quarkusio__quarkus
integration-tests/devtools/src/test/java/io/quarkus/devtools/commands/RemoveGradleExtensionsTest.java
{ "start": 616, "end": 3051 }
class ____ extends AbstractRemoveExtensionsTest<List<String>> { @Disabled void addExtensionTwiceInTwoBatches() throws IOException { //FIXME This is currently not working } @Override protected List<String> createProject() throws IOException, QuarkusCommandException { SnapshotTesting.deleteTestDirectory(getProjectPath().toFile()); new CreateProject(getQuarkusProject()) .groupId("org.acme") .artifactId("add-gradle-extension-test") .version("0.0.1-SNAPSHOT") .execute(); return readProject(); } @Override protected List<String> readProject() throws IOException { return Files.readAllLines(getProjectPath().resolve("build.gradle")); } @Override protected QuarkusCommandOutcome addExtensions(final List<String> extensions) throws IOException, QuarkusCommandException { return new AddExtensions(getQuarkusProject()) .extensions(new HashSet<>(extensions)) .execute(); } @Override protected QuarkusCommandOutcome removeExtensions(final List<String> extensions) throws IOException, QuarkusCommandException { return new RemoveExtensions(getQuarkusProject()) .extensions(new HashSet<>(extensions)) .execute(); } @Override protected long countDependencyOccurrences(final List<String> buildFile, final String groupId, final String artifactId, final String version) { return buildFile.stream() .filter(d -> d.equals(getBuildFileDependencyString(groupId, artifactId, version))) .count(); } protected QuarkusProject getQuarkusProject() throws QuarkusCommandException { try { return QuarkusProjectHelper.getProject(getProjectPath(), new TestingGradleBuildFile(getProjectPath(), getExtensionsCatalog())); } catch (RegistryResolutionException e) { throw new QuarkusCommandException("Failed to initialize Quarkus project", e); } } private static String getBuildFileDependencyString(final String groupId, final String artifactId, final String version) { final String versionPart = version != null ? ":" + version : ""; return " implementation '" + groupId + ":" + artifactId + versionPart + "'"; } }
RemoveGradleExtensionsTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericMappedSuperclassPropertyUpdateTest.java
{ "start": 1387, "end": 2646 }
class ____ implements SessionFactoryScopeAware { private SessionFactoryScope scope; @AfterAll public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @ParameterizedTest @MethodSource("criteriaUpdateFieldSetters") void testGenericHierarchy(Consumer<UpdateContext> updater) { scope.inTransaction( session -> { SpecificEntity relative = new SpecificEntity(); SpecificEntity base = new SpecificEntity(); session.persist( relative ); session.persist( base ); final CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaUpdate<SpecificEntity> criteriaUpdate = cb.createCriteriaUpdate( SpecificEntity.class ); Root<SpecificEntity> root = criteriaUpdate.from( SpecificEntity.class ); updater.accept( new UpdateContext( criteriaUpdate, root, base.getId(), relative ) ); criteriaUpdate.where( cb.equal( root.get( GenericMappedSuperclassPropertyUpdateTest_.SpecificEntity_.id ), base.getId() ) ); int updates = session.createQuery( criteriaUpdate ).executeUpdate(); session.refresh( base ); assertThat( updates ) .isEqualTo( 1L ); assertThat( base.getRelative() ) .isEqualTo( relative ); } ); } static
GenericMappedSuperclassPropertyUpdateTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialDisjointGeoSourceAndSourceGridEvaluator.java
{ "start": 4081, "end": 5060 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory wkb; private final EvalOperator.ExpressionEvaluator.Factory gridId; private final DataType gridType; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory wkb, EvalOperator.ExpressionEvaluator.Factory gridId, DataType gridType) { this.source = source; this.wkb = wkb; this.gridId = gridId; this.gridType = gridType; } @Override public SpatialDisjointGeoSourceAndSourceGridEvaluator get(DriverContext context) { return new SpatialDisjointGeoSourceAndSourceGridEvaluator(source, wkb.get(context), gridId.get(context), gridType, context); } @Override public String toString() { return "SpatialDisjointGeoSourceAndSourceGridEvaluator[" + "wkb=" + wkb + ", gridId=" + gridId + ", gridType=" + gridType + "]"; } } }
Factory
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/atomic/long_/AtomicLongAssert_hasValueGreaterThanOrEqualTo_Test.java
{ "start": 805, "end": 1186 }
class ____ extends AtomicLongAssertBaseTest { @Override protected AtomicLongAssert invoke_api_method() { return assertions.hasValueGreaterThanOrEqualTo(7L); } @Override protected void verify_internal_effects() { verify(longs).assertGreaterThanOrEqualTo(getInfo(assertions), getActual(assertions).get(), 7L); } }
AtomicLongAssert_hasValueGreaterThanOrEqualTo_Test
java
google__guice
core/test/com/google/inject/BindingTest.java
{ "start": 5370, "end": 5468 }
class ____ { @Inject protected ProtectedNoArgAnnotated() { } } static
ProtectedNoArgAnnotated
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2RefreshTokenGeneratorTests.java
{ "start": 1369, "end": 3038 }
class ____ { private final OAuth2RefreshTokenGenerator tokenGenerator = new OAuth2RefreshTokenGenerator(); @Test public void setClockWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> this.tokenGenerator.setClock(null)) .withMessage("clock cannot be null"); } @Test public void generateWhenUnsupportedTokenTypeThenReturnNull() { // @formatter:off OAuth2TokenContext tokenContext = DefaultOAuth2TokenContext.builder() .tokenType(OAuth2TokenType.ACCESS_TOKEN) .build(); // @formatter:on assertThat(this.tokenGenerator.generate(tokenContext)).isNull(); } @Test public void generateWhenRefreshTokenTypeThenReturnRefreshToken() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); // @formatter:off OAuth2TokenContext tokenContext = DefaultOAuth2TokenContext.builder() .registeredClient(registeredClient) .tokenType(OAuth2TokenType.REFRESH_TOKEN) .build(); // @formatter:on Clock clock = Clock.offset(Clock.systemUTC(), Duration.ofMinutes(5)); this.tokenGenerator.setClock(clock); OAuth2RefreshToken refreshToken = this.tokenGenerator.generate(tokenContext); assertThat(refreshToken).isNotNull(); Instant issuedAt = clock.instant(); Instant expiresAt = issuedAt .plus(tokenContext.getRegisteredClient().getTokenSettings().getRefreshTokenTimeToLive()); assertThat(refreshToken.getIssuedAt()).isBetween(issuedAt.minusSeconds(1), issuedAt.plusSeconds(1)); assertThat(refreshToken.getExpiresAt()).isBetween(expiresAt.minusSeconds(1), expiresAt.plusSeconds(1)); } }
OAuth2RefreshTokenGeneratorTests
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/voyageai/request/VoyageAIRerankRequestEntityTests.java
{ "start": 813, "end": 6836 }
class ____ extends ESTestCase { public void testXContent_SingleRequest_WritesAllFieldsIfDefined() throws IOException { var entity = new VoyageAIRerankRequestEntity( "query", List.of("abc"), Boolean.TRUE, 12, new VoyageAIRerankTaskSettings(8, Boolean.FALSE, null), "model" ); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString(""" { "model": "model", "query": "query", "documents": [ "abc" ], "return_documents": true, "top_k": 12 } """)); } public void testXContent_SingleRequest_WritesMinimalFields() throws IOException { var entity = new VoyageAIRerankRequestEntity( "query", List.of("abc"), null, null, new VoyageAIRerankTaskSettings(null, true, null), "model" ); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString(""" { "model": "model", "query": "query", "documents": [ "abc" ], "return_documents": true } """)); } public void testXContent_SingleRequest_WritesModelAndTopKIfDefined_TruncationTrue() throws IOException { var entity = new VoyageAIRerankRequestEntity( "query", List.of("abc"), null, null, new VoyageAIRerankTaskSettings(8, false, true), "model" ); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString(""" { "model": "model", "query": "query", "documents": [ "abc" ], "return_documents": false, "top_k": 8, "truncation": true } """)); } public void testXContent_SingleRequest_WritesModelAndTopKIfDefined_TruncationFalse() throws IOException { var entity = new VoyageAIRerankRequestEntity( "query", List.of("abc"), null, null, new VoyageAIRerankTaskSettings(8, false, false), "model" ); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString(""" { "model": "model", "query": "query", "documents": [ "abc" ], "return_documents": false, "top_k": 8, "truncation": false } """)); } public void testXContent_MultipleRequests_WritesAllFieldsIfDefined() throws IOException { var entity = new VoyageAIRerankRequestEntity( "query", List.of("abc", "def"), Boolean.FALSE, 11, new VoyageAIRerankTaskSettings(8, null, null), "model" ); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString(""" { "model": "model", "query": "query", "documents": [ "abc", "def" ], "return_documents": false, "top_k": 11 } """)); } public void testXContent_MultipleRequests_DoesNotWriteTopKIfNull() throws IOException { var entity = new VoyageAIRerankRequestEntity("query", List.of("abc", "def"), null, null, null, "model"); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString(""" { "model": "model", "query": "query", "documents": [ "abc", "def" ] } """)); } public void testXContent_UsesTaskSettingsTopNIfRootIsNotDefined() throws IOException { var entity = new VoyageAIRerankRequestEntity( "query", List.of("abc"), null, null, new VoyageAIRerankTaskSettings(8, Boolean.FALSE, null), "model" ); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); String xContentResult = Strings.toString(builder); assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString(""" { "model": "model", "query": "query", "documents": [ "abc" ], "return_documents": false, "top_k": 8 } """)); } }
VoyageAIRerankRequestEntityTests
java
apache__avro
lang/java/ipc/src/main/java/org/apache/avro/ipc/DatagramTransceiver.java
{ "start": 1267, "end": 2878 }
class ____ extends Transceiver { private static final Logger LOG = LoggerFactory.getLogger(DatagramTransceiver.class); private static final int MAX_SIZE = 16 * 1024; private DatagramChannel channel; private SocketAddress remote; private ByteBuffer buffer = ByteBuffer.allocate(MAX_SIZE); @Override public String getRemoteName() { return remote.toString(); } public DatagramTransceiver(SocketAddress remote) throws IOException { this(DatagramChannel.open()); this.remote = remote; } public DatagramTransceiver(DatagramChannel channel) { this.channel = channel; } @Override public synchronized List<ByteBuffer> readBuffers() throws IOException { ((Buffer) buffer).clear(); remote = channel.receive(buffer); LOG.info("received from " + remote); ((Buffer) buffer).flip(); List<ByteBuffer> buffers = new ArrayList<>(); while (true) { int length = buffer.getInt(); if (length == 0) { // end of buffers return buffers; } ByteBuffer chunk = buffer.slice(); // use data without copying ((Buffer) chunk).limit(length); ((Buffer) buffer).position(buffer.position() + length); buffers.add(chunk); } } @Override public synchronized void writeBuffers(List<ByteBuffer> buffers) throws IOException { ((Buffer) buffer).clear(); for (ByteBuffer b : buffers) { buffer.putInt(b.remaining()); buffer.put(b); // copy data. sigh. } buffer.putInt(0); ((Buffer) buffer).flip(); channel.send(buffer, remote); LOG.info("sent to " + remote); } }
DatagramTransceiver
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Vote.java
{ "start": 437, "end": 816 }
class ____ { @Id private Long id; @Column(name = "vote_choice") @Convert( converter = YesNoConverter.class ) private boolean voteChoice; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public boolean isVoteChoice() { return voteChoice; } public void setVoteChoice(boolean voteChoice) { this.voteChoice = voteChoice; } }
Vote
java
spring-projects__spring-security
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/MockResponses.java
{ "start": 986, "end": 1441 }
class ____ { private MockResponses() { } public static MockResponse json(String path) { try { String json = new ClassPathResource(path).getContentAsString(StandardCharsets.UTF_8); return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setBody(json); } catch (IOException ex) { throw new RuntimeException("Unable to read %s as a classpath resource".formatted(path), ex); } } }
MockResponses
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTesterTest.java
{ "start": 1484, "end": 1621 }
class ____ extends ForwardingObject implements Runnable { @Override public void run() {} } private abstract static
FailToForward
java
apache__logging-log4j2
log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlReconfigurationTest.java
{ "start": 3069, "end": 3255 }
class ____ implements ConfigurationListener { public synchronized void onChange(final Reconfigurable reconfigurable) { toggle.countDown(); } } }
TestListener
java
google__auto
common/src/test/java/com/google/auto/common/BasicAnnotationProcessorTest.java
{ "start": 21778, "end": 22802 }
class ____ {", "@" + RequiresGeneratedCode.class.getCanonicalName() + " String s;", "}"); requiresGeneratedCodeRejectionTest(classAFileObject); } @Test public void properlyDefersProcessing_rejectsRecordComponent() { double version = Double.parseDouble(Objects.requireNonNull(JAVA_SPECIFICATION_VERSION.value())); assume().that(version).isAtLeast(16.0); JavaFileObject classAFileObject = JavaFileObjects.forSourceLines( "test.RecordA", "package test;", "", "public record RecordA(@" + RequiresGeneratedCode.class.getCanonicalName() + " String s) {", "}"); requiresGeneratedCodeRejectionTest(classAFileObject); } @Test public void properlyDefersProcessing_rejectsTypeParameterElementInMethod() { JavaFileObject classAFileObject = JavaFileObjects.forSourceLines( "test.ClassA", "package test;", "", "public
ClassA
java
apache__hadoop
hadoop-tools/hadoop-fs2img/src/main/java/org/apache/hadoop/hdfs/server/namenode/SingleUGIResolver.java
{ "start": 1293, "end": 2629 }
class ____ extends UGIResolver implements Configurable { public static final String UID = "hdfs.image.writer.ugi.single.uid"; public static final String USER = "hdfs.image.writer.ugi.single.user"; public static final String GID = "hdfs.image.writer.ugi.single.gid"; public static final String GROUP = "hdfs.image.writer.ugi.single.group"; private int uid; private int gid; private String user; private String group; private Configuration conf; @Override public void setConf(Configuration conf) { this.conf = conf; uid = conf.getInt(UID, 0); user = conf.get(USER); if (null == user) { try { user = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException e) { user = "hadoop"; } } gid = conf.getInt(GID, 1); group = conf.get(GROUP); if (null == group) { group = user; } resetUGInfo(); addUser(user, uid); addGroup(group, gid); } @Override public Configuration getConf() { return conf; } @Override public String user(String s) { return user; } @Override public String group(String s) { return group; } @Override public void addUser(String name) { // do nothing } @Override public void addGroup(String name) { // do nothing } }
SingleUGIResolver
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/json/JsonObjectArgumentsValidator.java
{ "start": 1040, "end": 3275 }
class ____ implements ArgumentsValidator { @Override public void validate( List<? extends SqmTypedNode<?>> arguments, String functionName, BindingContext bindingContext) { if ( !arguments.isEmpty() ) { final var lastArgument = arguments.get( arguments.size() - 1 ); final int argumentsCount = lastArgument instanceof SqmJsonNullBehavior ? arguments.size() - 1 : arguments.size(); checkArgumentsCount( argumentsCount ); for ( int i = 0; i < argumentsCount; i += 2 ) { final var key = arguments.get( i ); final var nodeType = key.getNodeType(); final var javaType = nodeType == null ? null : nodeType.getRelationalJavaType(); if ( !isUnknown( javaType ) && key.getExpressible().getSqmType() instanceof JdbcMapping jdbcMapping ) { checkArgumentType( i, functionName, FunctionParameterType.STRING, jdbcMapping.getJdbcType(), javaType.getJavaTypeClass() ); } } } } @Override public void validateSqlTypes(List<? extends SqlAstNode> arguments, String functionName) { if ( !arguments.isEmpty() ) { final var lastArgument = arguments.get( arguments.size() - 1 ); final int argumentsCount = lastArgument instanceof JsonNullBehavior ? arguments.size() - 1 : arguments.size(); checkArgumentsCount( argumentsCount ); for ( int i = 0; i < argumentsCount; i += 2 ) { final var argument = arguments.get( i ); if ( argument instanceof Expression expression ) { final var expressionType = expression.getExpressionType(); if ( expressionType != null && !isUnknownExpressionType( expressionType ) ) { final var mapping = expressionType.getSingleJdbcMapping(); checkArgumentType( i, functionName, FunctionParameterType.STRING, mapping.getJdbcType(), mapping.getJavaTypeDescriptor().getJavaType() ); } } } } } private void checkArgumentsCount(int size) { if ( ( size & 1 ) == 1 ) { throw new FunctionArgumentException( String.format( "json_object must have an even number of arguments, but found %d", size ) ); } } }
JsonObjectArgumentsValidator
java
alibaba__nacos
core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilTest.java
{ "start": 1961, "end": 13613 }
class ____ { private static final String IP = "1.1.1.1"; private static final int PORT = 8848; @Mock private ServerMemberManager memberManager; private ConfigurableEnvironment environment; private Member originalMember; private Set<String> mockMemberAddressInfos; private String nacosHome; @BeforeEach void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); EnvUtil.setIsStandalone(true); nacosHome = EnvUtil.getNacosHome(); EnvUtil.setNacosHomePath(nacosHome + File.separator + "MemberUtilTest"); originalMember = buildMember(); mockMemberAddressInfos = new HashSet<>(); when(memberManager.getMemberAddressInfos()).thenReturn(mockMemberAddressInfos); } private Member buildMember() { return Member.builder().ip(IP).port(PORT).state(NodeState.UP).build(); } @AfterEach void tearDown() throws NacosException { EnvUtil.setNacosHomePath(nacosHome); } @Test void testCopy() { Member expected = Member.builder().build(); expected.setIp("2.2.2.2"); expected.setPort(9999); expected.setState(NodeState.SUSPICIOUS); expected.setExtendVal(MemberMetaDataConstants.VERSION, "test"); expected.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); MemberUtil.copy(expected, originalMember); assertEquals(expected.getIp(), originalMember.getIp()); assertEquals(expected.getPort(), originalMember.getPort()); assertEquals(expected.getAddress(), originalMember.getAddress()); assertEquals(NodeState.SUSPICIOUS, originalMember.getState()); assertEquals("test", originalMember.getExtendVal(MemberMetaDataConstants.VERSION)); assertTrue(originalMember.getAbilities().getRemoteAbility().isSupportRemoteConnection()); } @Test void testSingleParseWithPort() { Member actual = MemberUtil.singleParse(IP + ":2222"); assertEquals(IP, actual.getIp()); assertEquals(2222, actual.getPort()); assertEquals(IP + ":2222", actual.getAddress()); assertEquals(NodeState.UP, actual.getState()); assertTrue((Boolean) actual.getExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE)); assertEquals("1222", actual.getExtendVal(MemberMetaDataConstants.RAFT_PORT)); assertFalse(actual.getAbilities().getRemoteAbility().isSupportRemoteConnection()); } @Test void testSingleParseWithoutPort() { Member actual = MemberUtil.singleParse(IP); assertEquals(IP, actual.getIp()); assertEquals(PORT, actual.getPort()); assertEquals(IP + ":" + PORT, actual.getAddress()); assertEquals(NodeState.UP, actual.getState()); assertTrue((Boolean) actual.getExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE)); assertEquals("7848", actual.getExtendVal(MemberMetaDataConstants.RAFT_PORT)); assertFalse(actual.getAbilities().getRemoteAbility().isSupportRemoteConnection()); } @Test void testIsSupportedLongCon() { assertFalse(MemberUtil.isSupportedLongCon(originalMember)); originalMember.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); assertTrue(MemberUtil.isSupportedLongCon(originalMember)); originalMember.getAbilities().setRemoteAbility(null); assertFalse(MemberUtil.isSupportedLongCon(originalMember)); originalMember.setAbilities(null); assertFalse(MemberUtil.isSupportedLongCon(originalMember)); } @Test void testMultiParse() { Collection<String> address = new HashSet<>(); address.add("1.1.1.1:3306"); address.add("1.1.1.1"); Collection<Member> actual = MemberUtil.multiParse(address); assertEquals(2, actual.size()); } @Test void testSyncToFile() throws IOException { File file = new File(EnvUtil.getClusterConfFilePath()); file.getParentFile().mkdirs(); assertTrue(file.createNewFile()); MemberUtil.syncToFile(Collections.singleton(originalMember)); try (BufferedReader reader = new BufferedReader(new FileReader(EnvUtil.getClusterConfFilePath()))) { String line = ""; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { assertEquals(IP + ":" + PORT, line.trim()); return; } } fail("No found member info in cluster.conf"); } finally { file.delete(); } } @Test void testReadServerConf() { Collection<String> address = new HashSet<>(); address.add("1.1.1.1:3306"); address.add("1.1.1.1"); Collection<Member> actual = MemberUtil.readServerConf(address); assertEquals(2, actual.size()); } @Test void testSelectTargetMembers() { Collection<Member> input = new HashSet<>(); input.add(originalMember); Member member = buildMember(); member.setIp("2.2.2.2"); input.add(member); Set<Member> actual = MemberUtil.selectTargetMembers(input, member1 -> member1.getIp().equals(IP)); assertEquals(1, actual.size()); } @Test void testIsBasicInfoChangedNoChangeWithoutExtendInfo() { Member newMember = buildMember(); assertFalse(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedNoChangeWithExtendInfo() { Member newMember = buildMember(); newMember.setExtendVal("test", "test"); assertFalse(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForIp() { Member newMember = buildMember(); newMember.setIp("1.1.1.2"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForPort() { Member newMember = buildMember(); newMember.setPort(PORT + 1); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForAddress() { Member newMember = buildMember(); newMember.setAddress("test"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForStatus() { Member newMember = buildMember(); newMember.setState(NodeState.DOWN); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForMoreBasicExtendInfo() { Member newMember = buildMember(); newMember.setExtendVal(MemberMetaDataConstants.VERSION, "TEST"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForChangedBasicExtendInfo() { Member newMember = buildMember(); newMember.setExtendVal(MemberMetaDataConstants.WEIGHT, "100"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForChangedAbilities() { Member newMember = buildMember(); newMember.setGrpcReportEnabled(true); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test void testIsBasicInfoChangedForChangedNull() { Member newMember = buildMember(); assertTrue(MemberUtil.isBasicInfoChanged(newMember, null)); } @Test void testMemberOnFailWhenReachMaxFailAccessCnt() { final Member remote = buildMember(); mockMemberAddressInfos.add(remote.getAddress()); remote.setState(NodeState.SUSPICIOUS); remote.setFailAccessCnt(2); MemberUtil.onFail(memberManager, remote); assertEquals(3, remote.getFailAccessCnt()); assertEquals(NodeState.SUSPICIOUS, remote.getState()); verify(memberManager, never()).notifyMemberChange(remote); assertTrue(mockMemberAddressInfos.isEmpty()); MemberUtil.onFail(memberManager, remote); assertEquals(4, remote.getFailAccessCnt()); assertEquals(NodeState.DOWN, remote.getState()); verify(memberManager).notifyMemberChange(remote); } @Test void testMemberOnFailWhenConnectRefused() { final Member remote = buildMember(); mockMemberAddressInfos.add(remote.getAddress()); remote.setFailAccessCnt(1); MemberUtil.onFail(memberManager, remote, new ConnectException(MemberUtil.TARGET_MEMBER_CONNECT_REFUSE_ERRMSG)); assertEquals(2, remote.getFailAccessCnt()); assertEquals(NodeState.DOWN, remote.getState()); assertTrue(mockMemberAddressInfos.isEmpty()); verify(memberManager).notifyMemberChange(remote); } @SuppressWarnings("checkstyle:AbbreviationAsWordInName") @Test void testMemberOnFailWhenMemberAlreadyNOUP() { final Member remote = buildMember(); remote.setState(NodeState.DOWN); remote.setFailAccessCnt(4); MemberUtil.onFail(memberManager, remote); verify(memberManager, never()).notifyMemberChange(remote); } @Test void testMemberOnSuccessFromDown() { final Member remote = buildMember(); remote.setState(NodeState.DOWN); remote.setFailAccessCnt(4); MemberUtil.onSuccess(memberManager, remote); assertEquals(NodeState.UP, remote.getState()); assertEquals(0, remote.getFailAccessCnt()); verify(memberManager).notifyMemberChange(remote); } @Test void testMemberOnSuccessWhenMemberAlreadyUP() { final Member remote = buildMember(); memberManager.updateMember(remote); MemberUtil.onSuccess(memberManager, remote); verify(memberManager, never()).notifyMemberChange(remote); } @Test void testMemberOnSuccessWhenMemberNotUpdated() { final Member remote = buildMember(); final Member reportResult = buildMember(); MemberUtil.onSuccess(memberManager, remote, reportResult); assertFalse(remote.getAbilities().getRemoteAbility().isSupportRemoteConnection()); assertTrue(mockMemberAddressInfos.contains(remote.getAddress())); verify(memberManager, never()).notifyMemberChange(remote); } @Test void testMemberOnSuccessWhenMemberUpdatedAbilities() { final Member remote = buildMember(); final Member reportResult = buildMember(); reportResult.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); MemberUtil.onSuccess(memberManager, remote, reportResult); assertTrue(remote.getAbilities().getRemoteAbility().isSupportRemoteConnection()); assertTrue(mockMemberAddressInfos.contains(remote.getAddress())); verify(memberManager).notifyMemberChange(remote); } @Test void testMemberOnSuccessWhenMemberUpdatedExtendInfo() { final Member remote = buildMember(); final Member reportResult = buildMember(); reportResult.setExtendVal(MemberMetaDataConstants.VERSION, "test"); MemberUtil.onSuccess(memberManager, remote, reportResult); assertEquals("test", remote.getExtendVal(MemberMetaDataConstants.VERSION)); assertTrue(mockMemberAddressInfos.contains(remote.getAddress())); verify(memberManager).notifyMemberChange(remote); } }
MemberUtilTest
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/streams/AnalyticsRequestCallback.java
{ "start": 1041, "end": 1096 }
interface ____ tracks analytics operations. */ public
that
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeExtractionTest.java
{ "start": 29220, "end": 29958 }
class ____<A> implements MapFunction<PojoWithParameterizedFields1<A>, A> { private static final long serialVersionUID = 1L; @Override public A map(PojoWithParameterizedFields1<A> value) throws Exception { return null; } } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference4() { MyMapper4<Byte> function = new MyMapper4<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of(new TypeHint<PojoWithParameterizedFields1<Byte>>() {})); assertThat(ti).isEqualTo(BasicTypeInfo.BYTE_TYPE_INFO); } public static
MyMapper4
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/LastIntByTimestampGroupingAggregatorFunction.java
{ "start": 1126, "end": 15846 }
class ____ implements GroupingAggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("timestamps", ElementType.LONG), new IntermediateStateDesc("values", ElementType.INT) ); private final LastIntByTimestampAggregator.GroupingState state; private final List<Integer> channels; private final DriverContext driverContext; public LastIntByTimestampGroupingAggregatorFunction(List<Integer> channels, LastIntByTimestampAggregator.GroupingState state, DriverContext driverContext) { this.channels = channels; this.state = state; this.driverContext = driverContext; } public static LastIntByTimestampGroupingAggregatorFunction create(List<Integer> channels, DriverContext driverContext) { return new LastIntByTimestampGroupingAggregatorFunction(channels, LastIntByTimestampAggregator.initGrouping(driverContext), driverContext); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public GroupingAggregatorFunction.AddInput prepareProcessRawInputPage(SeenGroupIds seenGroupIds, Page page) { IntBlock valueBlock = page.getBlock(channels.get(0)); LongBlock timestampBlock = page.getBlock(channels.get(1)); IntVector valueVector = valueBlock.asVector(); if (valueVector == null) { maybeEnableGroupIdTracking(seenGroupIds, valueBlock, timestampBlock); return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void close() { } }; } LongVector timestampVector = timestampBlock.asVector(); if (timestampVector == null) { maybeEnableGroupIdTracking(seenGroupIds, valueBlock, timestampBlock); return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void close() { } }; } return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueVector, timestampVector); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueVector, timestampVector); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, valueVector, timestampVector); } @Override public void close() { } }; } private void addRawInput(int positionOffset, IntArrayBlock groups, IntBlock valueBlock, LongBlock timestampBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; if (valueBlock.isNull(valuesPosition)) { continue; } if (timestampBlock.isNull(valuesPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valueStart = valueBlock.getFirstValueIndex(valuesPosition); int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition); for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { int valueValue = valueBlock.getInt(valueOffset); int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition); int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition); for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) { long timestampValue = timestampBlock.getLong(timestampOffset); LastIntByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } } } private void addRawInput(int positionOffset, IntArrayBlock groups, IntVector valueVector, LongVector timestampVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valueValue = valueVector.getInt(valuesPosition); long timestampValue = timestampVector.getLong(valuesPosition); LastIntByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } @Override public void addIntermediateInput(int positionOffset, IntArrayBlock groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block timestampsUncast = page.getBlock(channels.get(0)); if (timestampsUncast.areAllValuesNull()) { return; } LongBlock timestamps = (LongBlock) timestampsUncast; Block valuesUncast = page.getBlock(channels.get(1)); if (valuesUncast.areAllValuesNull()) { return; } IntBlock values = (IntBlock) valuesUncast; assert timestamps.getPositionCount() == values.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valuesPosition = groupPosition + positionOffset; LastIntByTimestampAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition); } } } private void addRawInput(int positionOffset, IntBigArrayBlock groups, IntBlock valueBlock, LongBlock timestampBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; if (valueBlock.isNull(valuesPosition)) { continue; } if (timestampBlock.isNull(valuesPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valueStart = valueBlock.getFirstValueIndex(valuesPosition); int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition); for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { int valueValue = valueBlock.getInt(valueOffset); int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition); int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition); for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) { long timestampValue = timestampBlock.getLong(timestampOffset); LastIntByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } } } private void addRawInput(int positionOffset, IntBigArrayBlock groups, IntVector valueVector, LongVector timestampVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valueValue = valueVector.getInt(valuesPosition); long timestampValue = timestampVector.getLong(valuesPosition); LastIntByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } @Override public void addIntermediateInput(int positionOffset, IntBigArrayBlock groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block timestampsUncast = page.getBlock(channels.get(0)); if (timestampsUncast.areAllValuesNull()) { return; } LongBlock timestamps = (LongBlock) timestampsUncast; Block valuesUncast = page.getBlock(channels.get(1)); if (valuesUncast.areAllValuesNull()) { return; } IntBlock values = (IntBlock) valuesUncast; assert timestamps.getPositionCount() == values.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valuesPosition = groupPosition + positionOffset; LastIntByTimestampAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition); } } } private void addRawInput(int positionOffset, IntVector groups, IntBlock valueBlock, LongBlock timestampBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int valuesPosition = groupPosition + positionOffset; if (valueBlock.isNull(valuesPosition)) { continue; } if (timestampBlock.isNull(valuesPosition)) { continue; } int groupId = groups.getInt(groupPosition); int valueStart = valueBlock.getFirstValueIndex(valuesPosition); int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition); for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { int valueValue = valueBlock.getInt(valueOffset); int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition); int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition); for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) { long timestampValue = timestampBlock.getLong(timestampOffset); LastIntByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } } private void addRawInput(int positionOffset, IntVector groups, IntVector valueVector, LongVector timestampVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int valuesPosition = groupPosition + positionOffset; int groupId = groups.getInt(groupPosition); int valueValue = valueVector.getInt(valuesPosition); long timestampValue = timestampVector.getLong(valuesPosition); LastIntByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } @Override public void addIntermediateInput(int positionOffset, IntVector groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block timestampsUncast = page.getBlock(channels.get(0)); if (timestampsUncast.areAllValuesNull()) { return; } LongBlock timestamps = (LongBlock) timestampsUncast; Block valuesUncast = page.getBlock(channels.get(1)); if (valuesUncast.areAllValuesNull()) { return; } IntBlock values = (IntBlock) valuesUncast; assert timestamps.getPositionCount() == values.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int groupId = groups.getInt(groupPosition); int valuesPosition = groupPosition + positionOffset; LastIntByTimestampAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition); } } private void maybeEnableGroupIdTracking(SeenGroupIds seenGroupIds, IntBlock valueBlock, LongBlock timestampBlock) { if (valueBlock.mayHaveNulls()) { state.enableGroupIdTracking(seenGroupIds); } if (timestampBlock.mayHaveNulls()) { state.enableGroupIdTracking(seenGroupIds); } } @Override public void selectedMayContainUnseenGroups(SeenGroupIds seenGroupIds) { state.enableGroupIdTracking(seenGroupIds); } @Override public void evaluateIntermediate(Block[] blocks, int offset, IntVector selected) { state.toIntermediate(blocks, offset, selected, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, IntVector selected, GroupingAggregatorEvaluationContext ctx) { blocks[offset] = LastIntByTimestampAggregator.evaluateFinal(state, selected, ctx); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
LastIntByTimestampGroupingAggregatorFunction
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceTransactedWithFileOnExceptionTest.java
{ "start": 1224, "end": 3722 }
class ____ extends TransactionClientDataSourceSupport { @Test public void testTransactionSuccess() throws Exception { template.sendBodyAndHeader(fileUri("okay"), "Hello World", Exchange.FILE_NAME, "okay.txt"); await().atMost(3, TimeUnit.SECONDS).untilAsserted(() -> { // wait for route to complete int count = jdbc.queryForObject("select count(*) from books", Integer.class); assertEquals(3, count, "Number of books"); }); } @Test public void testTransactionRollback() throws Exception { MockEndpoint error = getMockEndpoint("mock:error"); error.expectedMessageCount(1); error.message(0).header(Exchange.EXCEPTION_CAUGHT).isNotNull(); error.message(0).header(Exchange.EXCEPTION_CAUGHT).isInstanceOf(IllegalArgumentException.class); error.expectedFileExists(testFile("failed/fail.txt")); template.sendBodyAndHeader(fileUri("fail"), "Hello World", Exchange.FILE_NAME, "fail.txt"); // wait for route to complete await().atMost(3, TimeUnit.SECONDS).untilAsserted(() -> { // should not be able to process the file so we still got 1 book as we did from the start int count = jdbc.queryForObject("select count(*) from books", Integer.class); assertEquals(1, count, "Number of books"); }); assertMockEndpointsSatisfied(); } @Override // The API is deprecated, we can remove warnings safely as the tests will disappear when removing this component. @SuppressWarnings("deprecation") protected RouteBuilder createRouteBuilder() throws Exception { return new SpringRouteBuilder() { public void configure() throws Exception { onException(IllegalArgumentException.class).handled(false).to("mock:error"); from(fileUri("okay?initialDelay=0&delay=10")) .transacted() .setBody(constant("Tiger in Action")).bean("bookService") .setBody(constant("Elephant in Action")).bean("bookService"); from(fileUri("fail?initialDelay=0&delay=10&moveFailed=../failed")) .transacted() .setBody(constant("Tiger in Action")).bean("bookService") .setBody(constant("Donkey in Action")).bean("bookService"); } }; } }
TransactionalClientDataSourceTransactedWithFileOnExceptionTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/file/ProducerMergedPartitionFileReaderTest.java
{ "start": 2179, "end": 10260 }
class ____ { private static final int DEFAULT_NUM_SUBPARTITION = 1; private static final int DEFAULT_SEGMENT_NUM = 1; private static final int DEFAULT_SEGMENT_ID = 0; private static final int DEFAULT_BUFFER_NUMBER = 5; private static final int DEFAULT_BUFFER_SIZE = 10; private static final String DEFAULT_TEST_FILE_NAME = "testFile"; private static final String DEFAULT_TEST_INDEX_NAME = "testIndex"; private static final TieredStoragePartitionId DEFAULT_PARTITION_ID = TieredStorageIdMappingUtils.convertId(new ResultPartitionID()); private static final TieredStorageSubpartitionId DEFAULT_SUBPARTITION_ID = new TieredStorageSubpartitionId(0); @TempDir private Path tempFolder; private Path testFilePath; private ProducerMergedPartitionFileReader partitionFileReader; @BeforeEach void before() throws ExecutionException, InterruptedException { Path testIndexPath = new File(tempFolder.toFile(), DEFAULT_TEST_INDEX_NAME).toPath(); ProducerMergedPartitionFileIndex partitionFileIndex = new ProducerMergedPartitionFileIndex( DEFAULT_NUM_SUBPARTITION, testIndexPath, 256, Long.MAX_VALUE); testFilePath = new File(tempFolder.toFile(), DEFAULT_TEST_FILE_NAME).toPath(); ProducerMergedPartitionFileWriter partitionFileWriter = new ProducerMergedPartitionFileWriter(testFilePath, partitionFileIndex); // Write buffers to disk by writer List<PartitionFileWriter.SubpartitionBufferContext> subpartitionBuffers = generateBuffersToWrite( DEFAULT_NUM_SUBPARTITION, DEFAULT_SEGMENT_NUM, DEFAULT_BUFFER_NUMBER, DEFAULT_BUFFER_SIZE); partitionFileWriter.write(DEFAULT_PARTITION_ID, subpartitionBuffers).get(); partitionFileReader = new ProducerMergedPartitionFileReader(testFilePath, partitionFileIndex); } @Test void testReadBuffer() throws IOException { for (int bufferIndex = 0; bufferIndex < DEFAULT_BUFFER_NUMBER; ++bufferIndex) { List<Buffer> buffers = readBuffer(bufferIndex, DEFAULT_SUBPARTITION_ID); assertThat(buffers).isNotNull(); buffers.forEach(Buffer::recycleBuffer); } MemorySegment memorySegment = MemorySegmentFactory.allocateUnpooledSegment(DEFAULT_BUFFER_SIZE); assertThat( partitionFileReader.readBuffer( DEFAULT_PARTITION_ID, DEFAULT_SUBPARTITION_ID, DEFAULT_SEGMENT_ID, DEFAULT_BUFFER_NUMBER + 1, memorySegment, FreeingBufferRecycler.INSTANCE, null, null)) .isNull(); } @Test void testGetPriority() throws IOException { ProducerMergedPartitionFileReader.ProducerMergedReadProgress readProgress = null; CompositeBuffer partialBuffer = null; for (int bufferIndex = 0; bufferIndex < DEFAULT_BUFFER_NUMBER; ) { PartitionFileReader.ReadBufferResult readBufferResult = readBuffer(bufferIndex, DEFAULT_SUBPARTITION_ID, readProgress, partialBuffer); assertThat(readBufferResult).isNotNull(); assertThat(readBufferResult.getReadProgress()) .isInstanceOf( ProducerMergedPartitionFileReader.ProducerMergedReadProgress.class); readProgress = (ProducerMergedPartitionFileReader.ProducerMergedReadProgress) readBufferResult.getReadProgress(); for (Buffer buffer : readBufferResult.getReadBuffers()) { if (buffer instanceof CompositeBuffer) { partialBuffer = (CompositeBuffer) buffer; if (partialBuffer.missingLength() == 0) { bufferIndex++; partialBuffer.recycleBuffer(); partialBuffer = null; } } else { bufferIndex++; buffer.recycleBuffer(); } } long expectedBufferOffset; if (bufferIndex < DEFAULT_BUFFER_NUMBER) { expectedBufferOffset = readProgress == null ? 0 : readProgress.getCurrentBufferOffset(); } else { expectedBufferOffset = Long.MAX_VALUE; } assertThat( partitionFileReader.getPriority( DEFAULT_PARTITION_ID, DEFAULT_SUBPARTITION_ID, DEFAULT_SEGMENT_ID, bufferIndex, readProgress)) .isEqualTo(expectedBufferOffset); } } @Test void testReadProgress() throws IOException { long currentFileOffset = 0; ProducerMergedPartitionFileReader.ProducerMergedReadProgress readProgress = null; CompositeBuffer partialBuffer = null; for (int bufferIndex = 0; bufferIndex < DEFAULT_BUFFER_NUMBER; ) { PartitionFileReader.ReadBufferResult readBufferResult = readBuffer(bufferIndex, DEFAULT_SUBPARTITION_ID, readProgress, partialBuffer); assertThat(readBufferResult).isNotNull(); assertThat(readBufferResult.getReadProgress()) .isInstanceOf( ProducerMergedPartitionFileReader.ProducerMergedReadProgress.class); readProgress = (ProducerMergedPartitionFileReader.ProducerMergedReadProgress) readBufferResult.getReadProgress(); for (Buffer buffer : readBufferResult.getReadBuffers()) { if (buffer instanceof CompositeBuffer) { partialBuffer = (CompositeBuffer) buffer; if (partialBuffer.missingLength() == 0) { bufferIndex++; currentFileOffset += partialBuffer.readableBytes() + HEADER_LENGTH; partialBuffer.recycleBuffer(); partialBuffer = null; } } else { bufferIndex++; currentFileOffset += buffer.readableBytes() + HEADER_LENGTH; buffer.recycleBuffer(); } } assertThat(readProgress.getCurrentBufferOffset()).isEqualTo(currentFileOffset); } } @Test void testRelease() { assertThat(testFilePath.toFile().exists()).isTrue(); partitionFileReader.release(); assertThat(testFilePath.toFile().exists()).isFalse(); } private List<Buffer> readBuffer(int bufferIndex, TieredStorageSubpartitionId subpartitionId) throws IOException { return readBuffer(bufferIndex, subpartitionId, null, null).getReadBuffers(); } private PartitionFileReader.ReadBufferResult readBuffer( int bufferIndex, TieredStorageSubpartitionId subpartitionId, PartitionFileReader.ReadProgress readProgress, CompositeBuffer partialBuffer) throws IOException { MemorySegment memorySegment = MemorySegmentFactory.allocateUnpooledSegment(DEFAULT_BUFFER_SIZE); return partitionFileReader.readBuffer( DEFAULT_PARTITION_ID, subpartitionId, DEFAULT_SEGMENT_ID, bufferIndex, memorySegment, FreeingBufferRecycler.INSTANCE, readProgress, partialBuffer); } }
ProducerMergedPartitionFileReaderTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptorTests.java
{ "start": 967, "end": 1255 }
class ____ { @Test @SuppressWarnings("unused") public void testGetExecutorQualifier() throws SecurityException, NoSuchMethodException { AnnotationAsyncExecutionInterceptor i = new AnnotationAsyncExecutionInterceptor(null); { // method level
AnnotationAsyncExecutionInterceptorTests
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java
{ "start": 15514, "end": 16946 }
class ____<C> implements Executor.Action<SimpleConnectionPool<C>> { private final Predicate<C> predicate; private final Completable<List<C>> handler; public Evict(Predicate<C> predicate, Completable<List<C>> handler) { this.predicate = predicate; this.handler = handler; } @Override public Task execute(SimpleConnectionPool<C> pool) { if (pool.closed) { return new Task() { @Override public void run() { handler.fail(POOL_CLOSED_EXCEPTION); } }; } List<C> res = new ArrayList<>(); List<Slot<C>> removed = new ArrayList<>(); for (int i = pool.size - 1;i >= 0;i--) { Slot<C> slot = pool.slots[i]; if (slot.connection != null && slot.usage == 0 && predicate.test(slot.connection)) { removed.add(slot); res.add(slot.connection); } } Task head = new Task() { @Override public void run() { handler.succeed(res); } }; Task tail = head; for (Slot<C> slot : removed) { Task next = new Remove<>(slot).execute(pool); if (next != null) { tail.next(next); tail = next; } } return head; } } @Override public void evict(Predicate<C> predicate, Completable<List<C>> handler) { execute(new Evict<>(predicate, handler)); } private static
Evict
java
apache__maven
compat/maven-compat/src/main/java/org/apache/maven/project/validation/DefaultModelValidator.java
{ "start": 1337, "end": 1995 }
class ____ implements ModelValidator { @Inject private org.apache.maven.model.validation.ModelValidator modelValidator; @Override public ModelValidationResult validate(Model model) { ModelValidationResult result = new ModelValidationResult(); ModelBuildingRequest request = new DefaultModelBuildingRequest().setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0); SimpleModelProblemCollector problems = new SimpleModelProblemCollector(result); modelValidator.validateEffectiveModel(model, request, problems); return result; } private static
DefaultModelValidator
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1566/Target.java
{ "start": 614, "end": 895 }
class ____ extends AbstractBuilder<Builder> { private String name; public Builder name(String name) { this.name = name; return this; } public Target build() { return new Target( id, name ); } } }
Builder
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/NameNodeProxiesClient.java
{ "start": 3362, "end": 3664 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger( NameNodeProxiesClient.class); /** * Wrapper for a client proxy as well as its associated service ID. * This is simply used as a tuple-like return type for created NN proxy. */ public static
NameNodeProxiesClient
java
quarkusio__quarkus
integration-tests/jpa-db2/src/main/java/io/quarkus/it/jpa/db2/WorkAddress.java
{ "start": 212, "end": 410 }
class ____ { private String company; public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } }
WorkAddress
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/model/ast/builder/TableDeleteBuilderStandard.java
{ "start": 808, "end": 3281 }
class ____ extends AbstractRestrictedTableMutationBuilder<JdbcDeleteMutation, TableDelete> implements TableDeleteBuilder { private final boolean isCustomSql; private String sqlComment; private final String whereFragment; public TableDeleteBuilderStandard( MutationTarget<?> mutationTarget, TableMapping table, SessionFactoryImplementor sessionFactory) { this( mutationTarget, new MutatingTableReference( table ), sessionFactory, null ); } public TableDeleteBuilderStandard( MutationTarget<?> mutationTarget, MutatingTableReference tableReference, SessionFactoryImplementor sessionFactory) { this( mutationTarget, tableReference, sessionFactory, null ); } public TableDeleteBuilderStandard( MutationTarget<?> mutationTarget, MutatingTableReference tableReference, SessionFactoryImplementor sessionFactory, String whereFragment) { super( MutationType.DELETE, mutationTarget, tableReference, sessionFactory ); this.isCustomSql = tableReference.getTableMapping().getDeleteDetails().getCustomSql() != null; this.sqlComment = "delete for " + mutationTarget.getRolePath(); this.whereFragment = whereFragment; } public String getSqlComment() { return sqlComment; } public void setSqlComment(String sqlComment) { this.sqlComment = sqlComment; } public String getWhereFragment() { return whereFragment; } @Override public void setWhere(String fragment) { if ( isCustomSql && fragment != null ) { throw new HibernateException( "Invalid attempt to apply where-restriction on top of custom sql-delete mapping : " + getMutationTarget().getNavigableRole().getFullPath() ); } } @Override public void addWhereFragment(String fragment) { if ( isCustomSql && fragment != null ) { throw new HibernateException( "Invalid attempt to apply where-filter on top of custom sql-delete mapping : " + getMutationTarget().getNavigableRole().getFullPath() ); } } @Override public TableDelete buildMutation() { if ( isCustomSql ) { return new TableDeleteCustomSql( getMutatingTable(), getMutationTarget(), sqlComment, getKeyRestrictionBindings(), getOptimisticLockBindings(), getParameters() ); } return new TableDeleteStandard( getMutatingTable(), getMutationTarget(), sqlComment, getKeyRestrictionBindings(), getOptimisticLockBindings(), getParameters(), whereFragment ); } }
TableDeleteBuilderStandard
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/outlierdetection/ConfusionMatrix.java
{ "start": 4195, "end": 6290 }
class ____ implements EvaluationMetricResult { private final double[] thresholds; private final long[] tp; private final long[] fp; private final long[] tn; private final long[] fn; public Result(double[] thresholds, long[] tp, long[] fp, long[] tn, long[] fn) { assert thresholds.length == tp.length; assert thresholds.length == fp.length; assert thresholds.length == tn.length; assert thresholds.length == fn.length; this.thresholds = thresholds; this.tp = tp; this.fp = fp; this.tn = tn; this.fn = fn; } public Result(StreamInput in) throws IOException { this.thresholds = in.readDoubleArray(); this.tp = in.readLongArray(); this.fp = in.readLongArray(); this.tn = in.readLongArray(); this.fn = in.readLongArray(); } @Override public String getWriteableName() { return registeredMetricName(OutlierDetection.NAME, NAME); } @Override public String getMetricName() { return NAME.getPreferredName(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeDoubleArray(thresholds); out.writeLongArray(tp); out.writeLongArray(fp); out.writeLongArray(tn); out.writeLongArray(fn); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); for (int i = 0; i < thresholds.length; i++) { builder.startObject(String.valueOf(thresholds[i])); builder.field("tp", tp[i]); builder.field("fp", fp[i]); builder.field("tn", tn[i]); builder.field("fn", fn[i]); builder.endObject(); } builder.endObject(); return builder; } } }
Result
java
apache__camel
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/legacy/TestInstanceDefaultTest.java
{ "start": 1269, "end": 1400 }
class ____ that a new camel context is created for each test method. */ @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
ensuring
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/subclasses/InterceptorSubclassesAreSharedTest.java
{ "start": 551, "end": 1173 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(MyBinding.class, WeirdInterceptor.class, SomeBean.class); @Test public void testInterception() throws IOException { ArcContainer arc = Arc.container(); SomeBean bean = arc.instance(SomeBean.class).get(); String resultOfFirstInterception = bean.bar(); String resultOfSecondInterception = bean.foo(); assertEquals(2, WeirdInterceptor.timesInvoked); assertEquals(resultOfFirstInterception, resultOfSecondInterception); } }
InterceptorSubclassesAreSharedTest
java
google__guava
android/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
{ "start": 2630, "end": 3073 }
class ____<L> { // TODO(cpovirk): consider using the logger associated with listener.getClass(). private static final LazyLogger logger = new LazyLogger(ListenerCallQueue.class); // TODO(chrisn): promote AppendOnlyCollection for use here. private final List<PerListenerQueue<L>> listeners = Collections.synchronizedList(new ArrayList<PerListenerQueue<L>>()); /** Method reference-compatible listener event. */
ListenerCallQueue
java
micronaut-projects__micronaut-core
http-server/src/main/java/io/micronaut/http/server/types/files/SystemFile.java
{ "start": 989, "end": 2834 }
class ____ implements FileCustomizableResponseType { private final File file; private final MediaType mediaType; private String attachmentName; /** * @param file The file to respond with */ public SystemFile(File file) { this.file = file; this.mediaType = MediaType.forFilename(file.getName()); } /** * @param file The file to respond with * @param mediaType The content type of the response */ public SystemFile(File file, MediaType mediaType) { this.file = file; this.mediaType = mediaType; } @Override public long getLastModified() { return file.lastModified(); } @Override public long getLength() { return file.length(); } @Override public MediaType getMediaType() { return mediaType; } /** * @return The file */ public File getFile() { return file; } /** * Sets the file to be downloaded as an attachment. * The file name is set in the Content-Disposition header. * * @return The same SystemFile instance */ public SystemFile attach() { this.attachmentName = file.getName(); return this; } /** * Sets the file to be downloaded as an attachment. * The name is set in the Content-Disposition header. * * @param attachmentName The attachment name. * @return The same SystemFile instance */ public SystemFile attach(String attachmentName) { this.attachmentName = attachmentName; return this; } @Override public void process(MutableHttpResponse response) { if (attachmentName != null) { response.header(HttpHeaders.CONTENT_DISPOSITION, StreamedFile.buildAttachmentHeader(attachmentName)); } } }
SystemFile
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/IbmWatsonSpeechToTextComponentBuilderFactory.java
{ "start": 10763, "end": 13756 }
class ____ extends AbstractComponentBuilder<WatsonSpeechToTextComponent> implements IbmWatsonSpeechToTextComponentBuilder { @Override protected WatsonSpeechToTextComponent buildConcreteComponent() { return new WatsonSpeechToTextComponent(); } private org.apache.camel.component.ibm.watson.stt.WatsonSpeechToTextConfiguration getOrCreateConfiguration(WatsonSpeechToTextComponent component) { if (component.getConfiguration() == null) { component.setConfiguration(new org.apache.camel.component.ibm.watson.stt.WatsonSpeechToTextConfiguration()); } return component.getConfiguration(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "configuration": ((WatsonSpeechToTextComponent) component).setConfiguration((org.apache.camel.component.ibm.watson.stt.WatsonSpeechToTextConfiguration) value); return true; case "serviceUrl": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setServiceUrl((java.lang.String) value); return true; case "contentType": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setContentType((java.lang.String) value); return true; case "lazyStartProducer": ((WatsonSpeechToTextComponent) component).setLazyStartProducer((boolean) value); return true; case "model": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setModel((java.lang.String) value); return true; case "operation": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setOperation((org.apache.camel.component.ibm.watson.stt.WatsonSpeechToTextOperations) value); return true; case "speakerLabels": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setSpeakerLabels((boolean) value); return true; case "timestamps": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setTimestamps((boolean) value); return true; case "wordConfidence": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setWordConfidence((boolean) value); return true; case "autowiredEnabled": ((WatsonSpeechToTextComponent) component).setAutowiredEnabled((boolean) value); return true; case "healthCheckConsumerEnabled": ((WatsonSpeechToTextComponent) component).setHealthCheckConsumerEnabled((boolean) value); return true; case "healthCheckProducerEnabled": ((WatsonSpeechToTextComponent) component).setHealthCheckProducerEnabled((boolean) value); return true; case "apiKey": getOrCreateConfiguration((WatsonSpeechToTextComponent) component).setApiKey((java.lang.String) value); return true; default: return false; } } } }
IbmWatsonSpeechToTextComponentBuilderImpl
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/util/introspection/FieldUtils.java
{ "start": 2302, "end": 2603 }
class ____ not be null"); checkArgument(fieldName != null, "The field name must not be null"); // Sun Java 1.3 has a bugged implementation of getField hence we write the // code ourselves // getField() will return the Field object with the declaring class // set correctly to the
must
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/queries/SemanticQueryBuilderTests.java
{ "start": 5904, "end": 6416 }
enum ____ { NONE, SPARSE_EMBEDDING, TEXT_EMBEDDING } private Integer queryTokenCount; public SemanticQueryBuilderTests(boolean useLegacyFormat) { this.useLegacyFormat = useLegacyFormat; } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return List.of(new Object[] { true }, new Object[] { false }); } @BeforeClass public static void setInferenceResultType() { // These are
InferenceResultType
java
dropwizard__dropwizard
dropwizard-metrics/src/main/java/io/dropwizard/metrics/common/CsvReporterFactory.java
{ "start": 1400, "end": 2364 }
class ____ extends BaseFormattedReporterFactory { @Nullable private File file; @JsonProperty @Nullable public File getFile() { return file; } @JsonProperty public void setFile(@Nullable File file) { this.file = file; } @Override public ScheduledReporter build(MetricRegistry registry) { final File directory = requireNonNull(getFile(), "File is not set"); final boolean creation = directory.mkdirs(); if (!creation && !directory.exists()) { throw new RuntimeException("Failed to create" + directory.getAbsolutePath()); } return CsvReporter.forRegistry(registry) .convertDurationsTo(getDurationUnit()) .convertRatesTo(getRateUnit()) .filter(getFilter()) .formatFor(getLocale()) .build(directory); } }
CsvReporterFactory
java
resilience4j__resilience4j
resilience4j-framework-common/src/main/java/io/github/resilience4j/common/retry/monitoring/endpoint/RetryEventDTO.java
{ "start": 801, "end": 2239 }
class ____ { private String retryName; private RetryEvent.Type type; private String creationTime; private String errorMessage; private int numberOfAttempts; RetryEventDTO() { } RetryEventDTO(String retryName, RetryEvent.Type type, String creationTime, String errorMessage, int numberOfAttempts) { this.retryName = retryName; this.type = type; this.creationTime = creationTime; this.errorMessage = errorMessage; this.numberOfAttempts = numberOfAttempts; } public String getRetryName() { return retryName; } public void setRetryName(String retryName) { this.retryName = retryName; } public RetryEvent.Type getType() { return type; } public void setType(RetryEvent.Type type) { this.type = type; } public String getCreationTime() { return creationTime; } public void setCreationTime(String creationTime) { this.creationTime = creationTime; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public int getNumberOfAttempts() { return numberOfAttempts; } public void setNumberOfAttempts(int numberOfAttempts) { this.numberOfAttempts = numberOfAttempts; } }
RetryEventDTO
java
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/json/TestCustomEscaping.java
{ "start": 1069, "end": 9032 }
class ____ extends CharacterEscapes { private final int[] _asciiEscapes; private final SerializedString _customRepl; public MyEscapes(String custom) { _customRepl = new SerializedString(custom); _asciiEscapes = standardAsciiEscapesForJSON(); _asciiEscapes['a'] = 'A'; // to basically give us "\A" _asciiEscapes['b'] = CharacterEscapes.ESCAPE_STANDARD; // to force "\u0062" _asciiEscapes['d'] = CharacterEscapes.ESCAPE_CUSTOM; } @Override public int[] getEscapeCodesForAscii() { return _asciiEscapes; } @Override public SerializableString getEscapeSequence(int ch) { if (ch == 'd') { return _customRepl; } if (ch == TWO_BYTE_ESCAPED) { return TWO_BYTE_ESCAPED_STRING; } if (ch == THREE_BYTE_ESCAPED) { return THREE_BYTE_ESCAPED_STRING; } return null; } } /* /******************************************************** /* Unit tests /******************************************************** */ /** * Test to ensure that it is possible to force escaping * of non-ASCII characters. * Related to [JACKSON-102] */ @Test void aboveAsciiEscapeWithReader() throws Exception { _testEscapeAboveAscii(false, false); // reader _testEscapeAboveAscii(false, true); } @Test void aboveAsciiEscapeWithUTF8Stream() throws Exception { _testEscapeAboveAscii(true, false); // stream (utf-8) _testEscapeAboveAscii(true, true); } // // // Tests for [JACKSON-106] @Test void escapeCustomWithReader() throws Exception { _testEscapeCustom(false, false, "[x]"); // reader _testEscapeCustom(false, true, "[x]"); // and with longer (above 6 characters) _testEscapeCustom(false, false, "[abcde]"); _testEscapeCustom(false, true, "[12345]"); _testEscapeCustom(false, false, "[xxyyzz4321]"); _testEscapeCustom(false, true, "[zzyyxx1234]"); } @Test void escapeCustomWithUTF8Stream() throws Exception { _testEscapeCustom(true, false, "[x]"); // stream (utf-8) _testEscapeCustom(true, true, "[x]"); // and with longer (above 6 characters) _testEscapeCustom(true, false, "[12345]"); _testEscapeCustom(true, true, "[abcde]"); _testEscapeCustom(true, false, "[abcdefghiz]"); _testEscapeCustom(true, true, "[123456789ABCDEF]"); } @Test void jsonpEscapes() throws Exception { _testJsonpEscapes(false, false); _testJsonpEscapes(false, true); _testJsonpEscapes(true, false); _testJsonpEscapes(true, true); } @SuppressWarnings("resource") private void _testJsonpEscapes(boolean useStream, boolean stringAsChars) throws Exception { JsonFactory f = JsonFactory.builder() .characterEscapes(JsonpCharacterEscapes.instance()) .build(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); JsonGenerator g; // First: output normally; should not add escaping if (useStream) { g = f.createGenerator(ObjectWriteContext.empty(), bytes, JsonEncoding.UTF8); } else { g = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bytes, "UTF-8")); } final String VALUE_TEMPLATE = "String with JS 'linefeeds': %s and %s..."; final String INPUT_VALUE = String.format(VALUE_TEMPLATE, "\u2028", "\u2029"); g.writeStartArray(); _writeString(g, INPUT_VALUE, stringAsChars); g.writeEndArray(); g.close(); String json = bytes.toString("UTF-8"); assertEquals(String.format("[%s]", q(String.format(VALUE_TEMPLATE, "\\u2028", "\\u2029"))), json); } /* /******************************************************** /* Secondary test methods /******************************************************** */ @SuppressWarnings({ "resource" }) private void _testEscapeAboveAscii(boolean useStream, boolean stringAsChars) throws Exception { JsonFactory f = new JsonFactory(); final String VALUE = "chars: [\u00A0]-[\u1234]"; final String KEY = "fun:\u0088:\u3456"; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); JsonGenerator g; // First: output normally; should not add escaping if (useStream) { g = f.createGenerator(ObjectWriteContext.empty(), bytes, JsonEncoding.UTF8); } else { g = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bytes, "UTF-8")); } g.writeStartArray(); _writeString(g, VALUE, stringAsChars); g.writeEndArray(); g.close(); String json = bytes.toString("UTF-8"); assertEquals("["+q(VALUE)+"]", json); // And then with forced ASCII; first, values f = f.rebuild() .enable(JsonWriteFeature.ESCAPE_NON_ASCII) .build(); bytes = new ByteArrayOutputStream(); if (useStream) { g = f.createGenerator(ObjectWriteContext.empty(), bytes, JsonEncoding.UTF8); } else { g = f.createGenerator(ObjectWriteContext.empty(),new OutputStreamWriter(bytes, "UTF-8")); } g.writeStartArray(); _writeString(g, VALUE+"\\", stringAsChars); g.writeEndArray(); g.close(); json = bytes.toString("UTF-8"); assertEquals("["+q("chars: [\\u00A0]-[\\u1234]\\\\")+"]", json); // and then keys f = f.rebuild() .enable(JsonWriteFeature.ESCAPE_NON_ASCII) .build(); bytes = new ByteArrayOutputStream(); if (useStream) { g = f.createGenerator(ObjectWriteContext.empty(), bytes, JsonEncoding.UTF8); } else { g = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bytes, "UTF-8")); } g.writeStartObject(); g.writeName(KEY+"\\"); g.writeBoolean(true); g.writeEndObject(); g.close(); json = bytes.toString("UTF-8"); assertEquals("{"+q("fun:\\u0088:\\u3456\\\\")+":true}", json); } @SuppressWarnings("resource") private void _testEscapeCustom(boolean useStream, boolean stringAsChars, String customRepl) throws Exception { JsonFactory f = JsonFactory.builder() .characterEscapes(new MyEscapes(customRepl)) .build(); final String STR_IN = "[abcd-"+((char) TWO_BYTE_ESCAPED)+"-"+((char) THREE_BYTE_ESCAPED)+"]"; final String STR_OUT = "[\\A\\u0062c"+customRepl+"-"+TWO_BYTE_ESCAPED_STRING+"-"+THREE_BYTE_ESCAPED_STRING+"]"; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); JsonGenerator g; // First: output normally; should not add escaping if (useStream) { g = f.createGenerator(ObjectWriteContext.empty(), bytes, JsonEncoding.UTF8); } else { g = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bytes, "UTF-8")); } g.writeStartObject(); g.writeName(STR_IN); _writeString(g, STR_IN, stringAsChars); g.writeEndObject(); g.close(); String json = bytes.toString("UTF-8"); assertEquals("{"+q(STR_OUT)+":"+q(STR_OUT)+"}", json); } private void _writeString(JsonGenerator g, String str, boolean stringAsChars) throws Exception { if (stringAsChars) { g.writeString(str); } else { char[] ch = str.toCharArray(); g.writeString(ch, 0, ch.length); } } }
MyEscapes
java
quarkusio__quarkus
extensions/keycloak-admin-rest-client/deployment/src/test/java/io/quarkus/keycloak/admin/rest/client/deployment/test/KeycloakAdminClientMutualTlsDevServicesTest.java
{ "start": 1105, "end": 2530 }
class ____ { @RegisterExtension final static QuarkusUnitTest app = new QuarkusUnitTest() .withApplicationRoot(jar -> jar .addClasses(MtlsResource.class) .addAsResource(new File("target/certs/mtls-test-keystore.p12"), "server-keystore.p12") .addAsResource(new File("target/certs/mtls-test-server-ca.crt"), "server-ca.crt") .addAsResource(new File("target/certs/mtls-test-client-keystore.p12"), "client-keystore.p12") .addAsResource(new File("target/certs/mtls-test-client-truststore.p12"), "client-truststore.p12") .addAsResource("app-mtls-config.properties", "application.properties")) // intention of this forced dependency is to test backwards compatibility // when users started Keycloak Dev Service by adding OIDC extension and configured 'server-url' .setForcedDependencies( List.of(Dependency.of("io.quarkus", "quarkus-oidc-deployment", Version.getVersion()))); @Test public void testCreateRealm() { // create realm RestAssured.given().post("/api/mtls").then().statusCode(204); // test realm created RestAssured.given().get("/api/mtls/Ron").then().statusCode(200).body(Matchers.is("Weasley")); } @Path("/api/mtls") public static
KeycloakAdminClientMutualTlsDevServicesTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
{ "start": 55323, "end": 56084 }
class ____ { public int invoke() { return 123; } public int foo(Suit suit) { switch (suit) { case HEART: case DIAMOND: return invoke(); case SPADE: throw new RuntimeException(); case CLUB: throw new NullPointerException(); } // This should never happen int z = invoke(); z++; throw new RuntimeException("Switch was not exhaustive at runtime " + z); } } """) .addOutputLines( "Test.java", """
Test
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/producer/illegal/IllegalProducerTest.java
{ "start": 541, "end": 1285 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(IllegalProducer.class); @Test public void testNormalScopedProducerMethodReturnsNull() { Serializable serializable = Arc.container().instance(Serializable.class).get(); try { serializable.toString(); fail(); } catch (IllegalProductException expected) { } } @Test public void testNormalScopedProducerFieldIsNull() { Temporal temporal = Arc.container().instance(Temporal.class).get(); try { temporal.toString(); fail(); } catch (IllegalProductException expected) { } } @Dependent static
IllegalProducerTest
java
apache__kafka
tools/src/main/java/org/apache/kafka/tools/consumer/NoOpMessageFormatter.java
{ "start": 977, "end": 1151 }
class ____ implements MessageFormatter { @Override public void writeTo(ConsumerRecord<byte[], byte[]> consumerRecord, PrintStream output) { } }
NoOpMessageFormatter
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultArtifactManager.java
{ "start": 1875, "end": 4519 }
class ____ implements ArtifactManager { @Nonnull private final InternalMavenSession session; private final Map<String, Path> paths = new ConcurrentHashMap<>(); @Inject public DefaultArtifactManager(@Nonnull InternalMavenSession session) { this.session = session; } @Nonnull @Override public Optional<Path> getPath(@Nonnull Artifact artifact) { String id = id(requireNonNull(artifact, "artifact cannot be null")); if (session.getMavenSession().getAllProjects() != null) { for (MavenProject project : session.getMavenSession().getAllProjects()) { if (id.equals(id(project.getArtifact())) && project.getArtifact().getFile() != null) { return Optional.of(project.getArtifact().getFile().toPath()); } } } Path path = paths.get(id); if (path == null && artifact instanceof DefaultArtifact defaultArtifact) { path = defaultArtifact.getArtifact().getPath(); } return Optional.ofNullable(path); } @Override public void setPath(@Nonnull ProducedArtifact artifact, Path path) { String id = id(requireNonNull(artifact, "artifact cannot be null")); if (session.getMavenSession().getAllProjects() != null) { session.getMavenSession().getAllProjects().stream() .flatMap(this::getProjectArtifacts) .filter(a -> Objects.equals(id, id(a))) .forEach(a -> a.setFile(path != null ? path.toFile() : null)); } if (path == null) { paths.remove(id); } else { paths.put(id, path); } } /** * Retrieve a stream of the project's artifacts. * Do not include the POM artifact as the file can't be set anyway. */ private Stream<org.apache.maven.artifact.Artifact> getProjectArtifacts(MavenProject project) { return Stream.concat(Stream.of(project.getArtifact()), project.getAttachedArtifacts().stream()); } private String id(org.apache.maven.artifact.Artifact artifact) { return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getArtifactHandler().getExtension() + (artifact.getClassifier() == null || artifact.getClassifier().isEmpty() ? "" : ":" + artifact.getClassifier()) + ":" + artifact.getVersion(); } private String id(Artifact artifact) { return artifact.key(); } }
DefaultArtifactManager
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/common/SourceRHS.java
{ "start": 685, "end": 5577 }
class ____ extends ModelElement implements Assignment { private final String sourceReference; private final Type sourceType; private String sourceLocalVarName; private String sourceLoopVarName; private final Set<String> existingVariableNames; private final String sourceErrorMessagePart; private PresenceCheck sourcePresenceCheckerReference; private boolean useElementAsSourceTypeForMatching = false; private final String sourceParameterName; public SourceRHS(String sourceReference, Type sourceType, Set<String> existingVariableNames, String sourceErrorMessagePart ) { this( sourceReference, sourceReference, null, sourceType, existingVariableNames, sourceErrorMessagePart ); } public SourceRHS(String sourceParameterName, String sourceReference, PresenceCheck sourcePresenceCheckerReference, Type sourceType, Set<String> existingVariableNames, String sourceErrorMessagePart ) { this.sourceReference = sourceReference; this.sourceType = sourceType; this.existingVariableNames = existingVariableNames; this.sourceErrorMessagePart = sourceErrorMessagePart; this.sourcePresenceCheckerReference = sourcePresenceCheckerReference; this.sourceParameterName = sourceParameterName; } @Override public String getSourceReference() { return sourceReference; } @Override public boolean isSourceReferenceParameter() { return sourceReference.equals( sourceParameterName ); } @Override public PresenceCheck getSourcePresenceCheckerReference() { return sourcePresenceCheckerReference; } public void setSourcePresenceCheckerReference(PresenceCheck sourcePresenceCheckerReference) { this.sourcePresenceCheckerReference = sourcePresenceCheckerReference; } @Override public Type getSourceType() { return sourceType; } @Override public String createUniqueVarName(String desiredName) { String result = Strings.getSafeVariableName( desiredName, existingVariableNames ); existingVariableNames.add( result ); return result; } @Override public String getSourceLocalVarName() { return sourceLocalVarName; } @Override public void setSourceLocalVarName(String sourceLocalVarName) { this.sourceLocalVarName = sourceLocalVarName; } public String getSourceLoopVarName() { return sourceLoopVarName; } public void setSourceLoopVarName(String sourceLoopVarName) { this.sourceLoopVarName = sourceLoopVarName; } @Override public Set<Type> getImportTypes() { if ( sourcePresenceCheckerReference != null ) { return sourcePresenceCheckerReference.getImportTypes(); } return Collections.emptySet(); } @Override public List<Type> getThrownTypes() { return Collections.emptyList(); } @Override public void setAssignment( Assignment assignment ) { throw new UnsupportedOperationException( "Not supported." ); } @Override public AssignmentType getType() { return AssignmentType.DIRECT; } @Override public boolean isCallingUpdateMethod() { return false; } @Override public String toString() { return sourceReference; } public String getSourceErrorMessagePart() { return sourceErrorMessagePart; } /** * The source type that is to be used when resolving the mapping from source to target. * * @return the source type to be used in the matching process. */ public Type getSourceTypeForMatching() { if ( useElementAsSourceTypeForMatching ) { if ( sourceType.isCollectionType() ) { return first( sourceType.determineTypeArguments( Collection.class ) ); } else if ( sourceType.isStreamType() ) { return first( sourceType.determineTypeArguments( Stream.class ) ); } else if ( sourceType.isArrayType() ) { return sourceType.getComponentType(); } else if ( sourceType.isIterableType() ) { return first( sourceType.determineTypeArguments( Iterable.class ) ); } } return sourceType; } /** * For collection type, use element as source type to find a suitable mapping method. * * @param useElementAsSourceTypeForMatching uses the element of a collection as source type for the matching process */ public void setUseElementAsSourceTypeForMatching(boolean useElementAsSourceTypeForMatching) { this.useElementAsSourceTypeForMatching = useElementAsSourceTypeForMatching; } @Override public String getSourceParameterName() { return sourceParameterName; } }
SourceRHS
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/PropertiesSourceFactory.java
{ "start": 914, "end": 1526 }
interface ____ { /** * New file based {@link PropertiesSource} * * @param location location of the file */ PropertiesSource newFilePropertiesSource(String location); /** * New classpath based {@link PropertiesSource} * * @param location location of the file in the classpath */ PropertiesSource newClasspathPropertiesSource(String location); /** * New ref based {@link PropertiesSource} * * @param ref id for the {@link java.util.Properties} bean. */ PropertiesSource newRefPropertiesSource(String ref); }
PropertiesSourceFactory
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
{ "start": 20563, "end": 20877 }
class ____ via ASM for determining @Bean method order", ex); // No worries, let's continue with the reflection metadata we started with... } } return beanMethods; } /** * Remove known superclasses for the given removed class, potentially replacing * the superclass exposure on a different config
file
java
apache__flink
flink-table/flink-table-code-splitter/src/main/java/org/apache/flink/table/codesplit/DeclarationRewriter.java
{ "start": 2212, "end": 3129 }
class ____ implements CodeRewriter { private final String code; private final int maxMethodLength; private final CommonTokenStream tokenStream; private final TokenStreamRewriter rewriter; private boolean hasRewrite = false; public DeclarationRewriter(String code, int maxMethodLength) { this.code = code; this.maxMethodLength = maxMethodLength; this.tokenStream = new CommonTokenStream(new JavaLexer(CharStreams.fromString(code))); this.rewriter = new TokenStreamRewriter(tokenStream); } public String rewrite() { JavaParser javaParser = new JavaParser(tokenStream); javaParser.getInterpreter().setPredictionMode(PredictionMode.SLL); new OuterBlockStatementExtractor().visit(javaParser.compilationUnit()); String text = rewriter.getText(); return hasRewrite ? text : null; } private
DeclarationRewriter
java
apache__avro
lang/java/mapred/src/main/java/org/apache/avro/mapreduce/AvroKeyValueOutputFormat.java
{ "start": 2083, "end": 3052 }
class ____<K, V> extends AvroOutputFormatBase<K, V> { /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public RecordWriter<K, V> getRecordWriter(TaskAttemptContext context) throws IOException { Configuration conf = context.getConfiguration(); AvroDatumConverterFactory converterFactory = new AvroDatumConverterFactory(conf); AvroDatumConverter<K, ?> keyConverter = converterFactory.create((Class<K>) context.getOutputKeyClass()); AvroDatumConverter<V, ?> valueConverter = converterFactory.create((Class<V>) context.getOutputValueClass()); GenericData dataModel = AvroSerialization.createDataModel(conf); OutputStream out = getAvroFileOutputStream(context); try { return new AvroKeyValueRecordWriter<>(keyConverter, valueConverter, dataModel, getCompressionCodec(context), out, getSyncInterval(context)); } catch (IOException e) { out.close(); throw e; } } }
AvroKeyValueOutputFormat
java
spring-projects__spring-framework
spring-core-test/src/test/java/org/springframework/core/test/tools/CompiledTests.java
{ "start": 1340, "end": 4446 }
class ____ implements java.util.function.Supplier<String> { public String get() { return "Hello Spring!"; // !! } } """; @Test void getSourceFileWhenSingleReturnsSourceFile() { SourceFile sourceFile = SourceFile.of(HELLO_WORLD); TestCompiler.forSystem().compile(sourceFile, compiled -> assertThat(compiled.getSourceFile()).isSameAs(sourceFile)); } @Test void getSourceFileWhenMultipleThrowsException() { SourceFiles sourceFiles = SourceFiles.of(SourceFile.of(HELLO_WORLD), SourceFile.of(HELLO_SPRING)); TestCompiler.forSystem().compile(sourceFiles, compiled -> assertThatIllegalStateException().isThrownBy( compiled::getSourceFile)); } @Test void getSourceFileWhenNoneThrowsException() { TestCompiler.forSystem().compile( compiled -> assertThatIllegalStateException().isThrownBy( compiled::getSourceFile)); } @Test void getSourceFilesReturnsSourceFiles() { SourceFiles sourceFiles = SourceFiles.of(SourceFile.of(HELLO_WORLD), SourceFile.of(HELLO_SPRING)); TestCompiler.forSystem().compile(sourceFiles, compiled -> assertThat(compiled.getSourceFiles()).isEqualTo(sourceFiles)); } @Test void getResourceFileWhenSingleReturnsSourceFile() { ResourceFile resourceFile = ResourceFile.of("META-INF/myfile", "test"); TestCompiler.forSystem().withResources(resourceFile).compile( compiled -> assertThat(compiled.getResourceFile()).isSameAs( resourceFile)); } @Test void getResourceFileWhenMultipleThrowsException() { ResourceFiles resourceFiles = ResourceFiles.of( ResourceFile.of("META-INF/myfile1", "test1"), ResourceFile.of("META-INF/myfile2", "test2")); TestCompiler.forSystem().withResources(resourceFiles).compile( compiled -> assertThatIllegalStateException().isThrownBy(compiled::getResourceFile)); } @Test void getResourceFileWhenNoneThrowsException() { TestCompiler.forSystem().compile( compiled -> assertThatIllegalStateException().isThrownBy(compiled::getResourceFile)); } @Test void getResourceFilesReturnsResourceFiles() { ResourceFiles resourceFiles = ResourceFiles.of( ResourceFile.of("META-INF/myfile1", "test1"), ResourceFile.of("META-INF/myfile2", "test2")); TestCompiler.forSystem().withResources(resourceFiles).compile( compiled -> assertThat(compiled.getResourceFiles()).isEqualTo( resourceFiles)); } @Test void getInstanceWhenNoneMatchesThrowsException() { TestCompiler.forSystem().compile(SourceFile.of(HELLO_WORLD), compiled -> assertThatIllegalStateException().isThrownBy( () -> compiled.getInstance(Callable.class))); } @Test void getInstanceWhenMultipleMatchesThrowsException() { SourceFiles sourceFiles = SourceFiles.of(SourceFile.of(HELLO_WORLD), SourceFile.of(HELLO_SPRING)); TestCompiler.forSystem().compile(sourceFiles, compiled -> assertThatIllegalStateException().isThrownBy( () -> compiled.getInstance(Supplier.class))); } @Test void getInstanceWhenNoDefaultConstructorThrowsException() { SourceFile sourceFile = SourceFile.of(""" package com.example; public
HelloSpring
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/GrpcXdsClientImplV3Test.java
{ "start": 6584, "end": 8997 }
class ____ extends GrpcXdsClientImplTestBase { /** Parameterized test cases. */ @Parameters(name = "ignoreResourceDeletion={0}") public static Iterable<? extends Boolean> data() { return ImmutableList.of(false, true); } @Parameter public boolean ignoreResourceDeletion; @Override protected BindableService createAdsService() { return new AggregatedDiscoveryServiceImplBase() { @Override public StreamObserver<DiscoveryRequest> streamAggregatedResources( final StreamObserver<DiscoveryResponse> responseObserver) { assertThat(adsEnded.get()).isTrue(); // ensure previous call was ended adsEnded.set(false); @SuppressWarnings("unchecked") StreamObserver<DiscoveryRequest> requestObserver = mock(StreamObserver.class, delegatesTo(new MockStreamObserver())); DiscoveryRpcCall call = new DiscoveryRpcCallV3(requestObserver, responseObserver); resourceDiscoveryCalls.offer(call); Context.current().addListener( new CancellationListener() { @Override public void cancelled(Context context) { adsEnded.set(true); } }, MoreExecutors.directExecutor()); return requestObserver; } }; } @Override protected BindableService createLrsService() { return new LoadReportingServiceImplBase() { @Override public StreamObserver<LoadStatsRequest> streamLoadStats( StreamObserver<LoadStatsResponse> responseObserver) { assertThat(lrsEnded.get()).isTrue(); lrsEnded.set(false); @SuppressWarnings("unchecked") StreamObserver<LoadStatsRequest> requestObserver = mock(StreamObserver.class); LrsRpcCall call = new LrsRpcCallV3(requestObserver, responseObserver); Context.current().addListener( new CancellationListener() { @Override public void cancelled(Context context) { lrsEnded.set(true); } }, MoreExecutors.directExecutor()); loadReportCalls.offer(call); return requestObserver; } }; } @Override protected MessageFactory createMessageFactory() { return new MessageFactoryV3(); } @Override protected boolean ignoreResourceDeletion() { return ignoreResourceDeletion; } private static
GrpcXdsClientImplV3Test
java
apache__camel
components/camel-jaxb/src/test/java/org/apache/camel/example/Bar.java
{ "start": 1102, "end": 1497 }
class ____ { @XmlAttribute private String name; @XmlAttribute private String value; public Bar() { } public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } public String getName() { return name; } public String getValue() { return value; } }
Bar
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/MapEntity.java
{ "start": 241, "end": 610 }
class ____ { @Id @Column(name="key_") private String key; @ElementCollection(fetch=FetchType.LAZY) @CollectionTable(name="MAP_ENTITY_NAME", joinColumns=@JoinColumn(name="key_")) @MapKeyColumn(name="lang_") private Map<String, MapEntityLocal> localized; public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
MapEntity
java
google__dagger
javatests/dagger/internal/codegen/XExecutableTypesTest.java
{ "start": 9923, "end": 10882 }
class ____ extends Foo {", " <T> List<T> toList(Collection<T> c) { throw new RuntimeException(); }", "}"); CompilerTests.invocationCompiler(foo, bar) .compile( invocation -> { XTypeElement fooType = invocation.getProcessingEnv().requireTypeElement("test.Foo"); XMethodElement m1 = fooType.getDeclaredMethods().get(0); XTypeElement barType = invocation.getProcessingEnv().requireTypeElement("test.Bar"); XMethodElement m2 = barType.getDeclaredMethods().get(0); assertThat(XExecutableTypes.isSubsignature(m2, m1)).isTrue(); assertThat(XExecutableTypes.isSubsignature(m1, m2)).isTrue(); }); } @Test public void subsignatureSameSignatureUnrelatedClasses() { Source foo = CompilerTests.javaSource( "test.Foo", "package test;", "import java.util.*;", "
Bar
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAnonymousTests.java
{ "start": 2523, "end": 4222 }
class ____ { @Autowired MockMvc mvc; public final SpringTestContext spring = new SpringTestContext(this); @Test public void anonymousRequestWhenUsingDefaultAnonymousConfigurationThenUsesAnonymousAuthentication() throws Exception { this.spring.register(AnonymousConfig.class, AnonymousController.class).autowire(); this.mvc.perform(get("/type")).andExpect(content().string(AnonymousAuthenticationToken.class.getSimpleName())); } @Test public void anonymousRequestWhenDisablingAnonymousThenDenies() throws Exception { this.spring.register(AnonymousDisabledConfig.class, AnonymousController.class).autowire(); this.mvc.perform(get("/type")).andExpect(status().isForbidden()); } @Test public void requestWhenAnonymousThenSendsAnonymousConfiguredAuthorities() throws Exception { this.spring.register(AnonymousGrantedAuthorityConfig.class, AnonymousController.class).autowire(); this.mvc.perform(get("/type")).andExpect(content().string(AnonymousAuthenticationToken.class.getSimpleName())); } @Test public void anonymousRequestWhenAnonymousKeyConfiguredThenKeyIsUsed() throws Exception { this.spring.register(AnonymousKeyConfig.class, AnonymousController.class).autowire(); this.mvc.perform(get("/key")).andExpect(content().string(String.valueOf("AnonymousKeyConfig".hashCode()))); } @Test public void anonymousRequestWhenAnonymousUsernameConfiguredThenUsernameIsUsed() throws Exception { this.spring.register(AnonymousUsernameConfig.class, AnonymousController.class).autowire(); this.mvc.perform(get("/principal")).andExpect(content().string("AnonymousUsernameConfig")); } @Configuration @EnableWebSecurity @EnableWebMvc static
NamespaceHttpAnonymousTests
java
spring-projects__spring-security
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoder.java
{ "start": 1759, "end": 2076 }
interface ____ { /** * Decodes the JWT from its compact claims representation format and returns a * {@link Jwt}. * @param token the JWT value * @return a {@link Jwt} * @throws JwtException if an error occurs while attempting to decode the JWT */ Jwt decode(String token) throws JwtException; }
JwtDecoder