auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testCreateContentWithCats_AnonymousUser_RESTAPICONTENTALLOWFRONTENDSAVINGtrue_shouldSucceed200() throws DotSecurityException, DotDataException, JSONException { <START> final String REST_API_CONTENT_ALLOW_FRONT_END_SAVING = "REST_API_CONTENT_ALLOW_FRONT_END_SAVING"; <END> boolean restAPIContentAllowFrontEndSavingValue = Config.getBooleanProperty(REST_API_CONTENT_ALLOW_FRONT_END_SAVING); try { long time = System.currentTimeMillis(); final String TITLE_FIELD_VARIABLE = "title"+time; final String CAT_FIELD_VARIABLE = "eventType"+time; ContentType type = createContentTypeWithCatAndTextField(TITLE_FIELD_VARIABLE, CAT_FIELD_VARIABLE); Config.setProperty(REST_API_CONTENT_ALLOW_FRONT_END_SAVING, true); Response response = webTarget.path("/save/1/").request() .put(Entity.entity(new JSONObject() .put("stInode", type.id()) .put("languageId", 1) .put(TITLE_FIELD_VARIABLE, "Test content from ContentResourceTest") .put(CAT_FIELD_VARIABLE, "seminars") .toString(), MediaType.APPLICATION_JSON_TYPE)); assertTrue(response.getStatus() == Response.Status.OK.getStatusCode()); } finally { Config.setProperty("REST_API_CONTENT_ALLOW_FRONT_END_SAVING", restAPIContentAllowFrontEndSavingValue); } }</code><technical_language>a constant</technical_language>

Target:
public void testCreateContentWithCats_AnonymousUser_RESTAPICONTENTALLOWFRONTENDSAVINGtrue_shouldSucceed200() throws DotSecurityException, DotDataException, JSONException { final boolean restAPIContentAllowFrontEndSavingValue = Config.getBooleanProperty(REST_API_CONTENT_ALLOW_FRONT_END_SAVING); try { final long time = System.currentTimeMillis(); final String TITLE_FIELD_VARIABLE = "title"+time; final String CAT_FIELD_VARIABLE = "eventType"+time; final ContentType type = createContentTypeWithCatAndTextField(TITLE_FIELD_VARIABLE, CAT_FIELD_VARIABLE); Config.setProperty(REST_API_CONTENT_ALLOW_FRONT_END_SAVING, true); final Response response = webTarget.path("/save/1/").request() .put(Entity.entity(new JSONObject() .put("stInode", type.id()) .put("languageId", 1) .put(TITLE_FIELD_VARIABLE, "Test content from ContentResourceTest") .put(CAT_FIELD_VARIABLE, "seminars") .toString(), MediaType.APPLICATION_JSON_TYPE)); assertTrue(response.getStatus() == Response.Status.OK.getStatusCode()); } finally { Config.setProperty(REST_API_CONTENT_ALLOW_FRONT_END_SAVING, restAPIContentAllowFrontEndSavingValue); } }
Source:
<code>public ChargeEntity markChargeAsCaptureApproved(String externalId) { return chargeDao.findByExternalId(externalId).map(charge -> { <START> ChargeStatus currentStatus = fromString(charge.getStatus()); <END> if (charge.hasStatus(IGNORABLE_CAPTURE_STATES)) { logger.info("Skipping charge [charge_external_id={}] with status from marking as CAPTURE APPROVED", currentStatus, externalId); return charge; } ChargeStatus targetStatus = CAPTURE_APPROVED; try { updateChargeStatus(charge, CAPTURE_APPROVED); } catch (InvalidStateTransitionException e) { logger.error("Charge with state cannot proceed to [charge_external_id={}, charge_status={}]", currentStatus, targetStatus, charge.getExternalId(), currentStatus); throw new ConflictRuntimeException(charge.getExternalId(), format("attempt to perform delayed capture on charge not in %s state.", AWAITING_CAPTURE_REQUEST)); } return charge; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }</code><technical_language>need catch this</technical_language>

Target:
public ChargeEntity markChargeAsCaptureApproved(String externalId) { return chargeDao.findByExternalId(externalId).map(charge -> { ChargeStatus currentStatus = fromString(charge.getStatus()); if (charge.hasStatus(IGNORABLE_CAPTURE_STATES)) { logger.info("Skipping charge [charge_external_id={}] with status from marking as CAPTURE APPROVED", currentStatus, externalId); return charge; } try { updateChargeStatus(charge, CAPTURE_APPROVED); } catch (InvalidStateTransitionException e) { throw new ConflictRuntimeException(charge.getExternalId(), format("attempt to perform delayed capture on charge not in %s state.", AWAITING_CAPTURE_REQUEST)); } return charge; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }
Source:
<code>public Optional<ConnectorNewTableLayout> getNewTableLayout(ConnectorSession session, ConnectorTableMetadata tableMetadata) { Optional<HiveBucketProperty> bucketProperty = getBucketProperty(tableMetadata.getProperties()); if (!bucketProperty.isPresent()) { return Optional.empty(); } if (!bucketWritingEnabled) { <START> throw new PrestoException(NOT_SUPPORTED, "Writing to bucketed Hive table has been temporarily disabled"); <END> } if (!bucketProperty.get().getSortedBy().isEmpty() && !isSortedWritingEnabled(session)) { throw new PrestoException(NOT_SUPPORTED, "Writing to bucketed sorted Hive tables is disabled"); } List<String> bucketedBy = bucketProperty.get().getBucketedBy(); Map<String, HiveType> hiveTypeMap = tableMetadata.getColumns().stream() .collect(toMap(ColumnMetadata::getName, column -> toHiveType(typeTranslator, column.getType()))); return Optional.of(new ConnectorNewTableLayout( new HivePartitioningHandle( bucketProperty.get().getBucketCount(), bucketedBy.stream() .map(hiveTypeMap::get) .collect(toList())), bucketedBy)); }</code><technical_language>interesting this message is message, effectively thing</technical_language>

Target:
public Optional<ConnectorNewTableLayout> getNewTableLayout(ConnectorSession session, ConnectorTableMetadata tableMetadata) { Optional<HiveBucketProperty> bucketProperty = getBucketProperty(tableMetadata.getProperties()); if (!bucketProperty.isPresent()) { return Optional.empty(); } if (!bucketProperty.get().getSortedBy().isEmpty() && !isSortedWritingEnabled(session)) { throw new PrestoException(NOT_SUPPORTED, "Writing to bucketed sorted Hive tables is disabled"); } List<String> bucketedBy = bucketProperty.get().getBucketedBy(); Map<String, HiveType> hiveTypeMap = tableMetadata.getColumns().stream() .collect(toMap(ColumnMetadata::getName, column -> toHiveType(typeTranslator, column.getType()))); return Optional.of(new ConnectorNewTableLayout( new HivePartitioningHandle( bucketProperty.get().getBucketCount(), bucketedBy.stream() .map(hiveTypeMap::get) .collect(toList())), bucketedBy)); }
Source:
<code>private Predicate<RefundEntity> refundsWithNoRefundTransaction(PaymentRequestEntity paymentRequestEntity) { return refund -> paymentRequestEntity.getRefundTransactions().stream() <START> .noneMatch(refundTransaction -> refundTransaction.getRefundReference().equals(refund.getReference())); <END> }</code><technical_language>I external ID is a safer here: some REFUND ERROR refunds references</technical_language>

Target:
private Predicate<RefundEntity> refundsWithNoRefundTransaction(PaymentRequestEntity paymentRequestEntity) { return refund -> paymentRequestEntity.getRefundTransactions().stream() .noneMatch(refundTransaction -> refundTransaction.getRefundExternalId().equals(refund.getExternalId())); }
Source:
<code>public void testPRGatherCancellationWhileAddingResults() { final VM server1 = VM.getVM(0); final VM server2 = VM.getVM(1); final VM client = VM.getVM(2); final int numObjects = 200; try { final int[] port = AvailablePortHelper.getRandomAvailableTCPPorts(2); startCacheServer(server1, port[0], false, -1, true); startCacheServer(server2, port[1], true, -1, true); startClient(client, port[0]); populateData(server2); createCancelDuringAddResultsTestHook(server1); client.invoke("executing query to be canceled during add results", () -> { QueryService qs; try { qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); query.execute(); throw new CacheException("should have hit low memory") {}; } catch (Exception e) { handleException(e, true, false, -1); } return 0; }); verifyRejectedObjects(server1); vmRecoversFromCriticalHeap(server1); client.invoke("Executing query when system is 'Normal'", () -> { try { QueryService qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); SelectResults results = (SelectResults) query.execute(); assertThat(results.size()).isEqualTo(numObjects); <START> } catch (QueryInvocationTargetException | FunctionDomainException | TypeMismatchException <END> | NameResolutionException e) { fail(""); } }); vmRecoversFromCriticalHeap(server1); } finally { stopServer(server1); stopServer(server2); } }</code><technical_language>Another catch-block delete</technical_language>

Target:
public void testPRGatherCancellationWhileAddingResults() { final VM server1 = VM.getVM(0); final VM server2 = VM.getVM(1); final VM client = VM.getVM(2); final int numObjects = 200; try { final int[] port = AvailablePortHelper.getRandomAvailableTCPPorts(2); startCacheServer(server1, port[0], false, -1, true); startCacheServer(server2, port[1], true, -1, true); startClient(client, port[0]); populateData(server2); createCancelDuringAddResultsTestHook(server1); client.invoke("executing query to be canceled during add results", () -> { QueryService qs; try { qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); query.execute(); throw new CacheException("should have hit low memory") {}; } catch (Exception e) { handleException(e, true, false, -1); } return 0; }); verifyRejectedObjects(server1); vmRecoversFromCriticalHeap(server1); client.invoke("Executing query when system is 'Normal'", () -> { QueryService qs = getCache().getQueryService(); Query query = qs.newQuery("Select * From /" + "portfolios"); SelectResults results = (SelectResults) query.execute(); assertThat(results.size()).isEqualTo(numObjects); }); vmRecoversFromCriticalHeap(server1); } finally { stopServer(server1); stopServer(server2); } }
Source:
<code>void loadObjectsUsesCache() { <START> QueryResult queryResult = QueryResult.builder().data(DATA).build(); <END> when(cache.get(anyString())).thenReturn(queryResult); when(queryEngine.getTableVersion(playerStatsTable, qeTransaction)).thenReturn("foo"); AggregationDataStoreTransaction transaction = new MyAggregationDataStoreTransaction(queryEngine, cache); EntityProjection entityProjection = EntityProjection.builder().type(PlayerStats.class).build(); assertEquals(DATA, transaction.loadObjects(entityProjection, scope)); String cacheKey = "foo;" + queryKey; Mockito.verify(queryEngine, never()).executeQuery(any(), any()); Mockito.verify(cache).get(cacheKey); Mockito.verifyNoMoreInteractions(cache); }</code><technical_language>this test execution depend prior test executing first? I test stand own</technical_language>

Target:
public void loadObjectsUsesCache() { String cacheKey = "foo;" + queryKey; QueryResult queryResult = QueryResult.builder().data(DATA).build(); when(cache.get(cacheKey)).thenReturn(queryResult); when(queryEngine.getTableVersion(playerStatsTable, qeTransaction)).thenReturn("foo"); AggregationDataStoreTransaction transaction = new MyAggregationDataStoreTransaction(queryEngine, cache); EntityProjection entityProjection = EntityProjection.builder().type(PlayerStats.class).build(); assertEquals(DATA, transaction.loadObjects(entityProjection, scope)); Mockito.verify(queryEngine, never()).executeQuery(any(), any()); Mockito.verify(cache).get(cacheKey); Mockito.verifyNoMoreInteractions(cache); }
Source:
<code>public void testENG13271() throws Exception { String pathToCatalog = Configuration.getPathToCatalogForTest("adhocddl.jar"); VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addLiteralSchema( "CREATE TABLE T (\n" + " COLUMN_CASE tinyint\n" + ");\n" + "CREATE PROCEDURE PROC1\n" + "AS BEGIN\n" + <START> " INSERT INTO T (COLUMN_CASE) VALUES (?);\n" + <END> "END;\n" + "CREATE PROCEDURE PROC2\n" + "AS BEGIN\n" + " SELECT * FROM T;\n" + "END;\n" ); builder.setUseDDLSchema(true); boolean success = builder.compile(pathToCatalog, 2, 1, 0); assertTrue("Schema compilation failed", success); }</code><technical_language>issue _case in identifier? testing for _ well</technical_language>

Target:
public void testENG13271() throws Exception { String pathToCatalog = Configuration.getPathToCatalogForTest("adhocddl.jar"); VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addLiteralSchema( "CREATE TABLE T (\n" + " COLUMN_CASE tinyint,\n" + " CASE_COLUMN tinyint,\n" + " AS_BEGIN tinyint,\n" + " END_COLUMN tinyint\n" + ");\n" + "CREATE PROCEDURE PROC1\n" + "AS BEGIN\n" + " INSERT INTO T (COLUMN_CASE) VALUES (?);\n" + " INSERT INTO T (CASE_COLUMN) VALUES (?);\n" + "END;\n" + "CREATE PROCEDURE PROC2\n" + "AS BEGIN\n" + " SELECT * FROM T;\n" + "END;\n" ); builder.setUseDDLSchema(true); boolean success = builder.compile(pathToCatalog, 2, 1, 0); assertTrue("Schema compilation failed", success); }
Source:
<code>public void runOperation(VariableMap variableMap, IProgressMonitor monitor) throws Exception { String script = variableMap.getString("Console"); String params = variableMap.getString("Parameters"); String filename = variableMap.getString("Filename"); boolean debug = variableMap.getBoolean("Debug"); boolean excel = variableMap.getBoolean("Excel"); if (Strings.isValid(script)) { Writer writer = null; MediaType mediaType = null; File outfile = null; if (excel) { <START> mediaType = MediaType.APPLICATION_XML_TYPE; <END> outfile = OseeData.getFile(filename + Lib.getDateTimeString() + ".xml"); writer = new FileWriter(outfile); } else { mediaType = MediaType.APPLICATION_JSON_TYPE; writer = new StringWriter(); } try { OseeClient oseeClient = ServiceUtil.getOseeClient(); Properties props = getParameters(params); oseeClient.executeScript(script, props, debug, mediaType, writer); if (!excel) { log(writer.toString()); } else { log("Excel XML file produced: "); log(outfile.getCanonicalPath()); Program.launch(outfile.getCanonicalPath()); } } finally { Lib.close(writer); } } else { log("Console was empty - Type script in console."); } }</code><technical_language>chance this called in minute? getDateTimeString minute</technical_language>

Target:
public void runOperation(VariableMap variableMap, IProgressMonitor monitor) throws Exception { String script = variableMap.getString("Console"); String params = variableMap.getString("Parameters"); String filename = variableMap.getString("Filename"); boolean debug = variableMap.getBoolean("Debug"); boolean excel = variableMap.getBoolean("Excel"); if (Strings.isValid(script)) { Writer writer = null; MediaType mediaType = null; File outfile = null; if (excel) { mediaType = MediaType.APPLICATION_XML_TYPE; outfile = OseeData.getFile(filename + Lib.getDateTimeString() + ".xml"); writer = new FileWriter(outfile); } else { mediaType = MediaType.APPLICATION_JSON_TYPE; writer = new StringWriter(); } try { OseeClient oseeClient = ServiceUtil.getOseeClient(); Properties props = getParameters(params); oseeClient.executeScript(script, props, debug, mediaType, writer); if (excel) { log("Excel XML file produced: "); log(outfile.getCanonicalPath()); Program.launch(outfile.getCanonicalPath()); } else { log(writer.toString()); } } finally { Lib.close(writer); } } else { log("Console was empty - Type script in console."); } }
Source:
<code>public static Calibration create(final String senseId, final Integer dustOffset, final String metadata) { <START> return new Calibration(senseId, dustOffset, Math.round(DUST_CALIBRATION_BASE - dustOffset * DUST_CALIBRATION_K_FACTOR), metadata); <END> }</code><technical_language>dustOffset is Integer is multiplied a Float. need check this, a rounding error intend round</technical_language>

Target:
public static Calibration create(final String senseId, final Integer dustOffset, final String metadata) { return new Calibration(senseId, dustOffset, Math.round(DUST_CALIBRATION_BASE - (float)dustOffset * DUST_CALIBRATION_K_FACTOR), metadata); }
Source:
<code>public void setQuotaName(String value) { <START> if (!privateQuotaName.equals(value)) <END> { privateQuotaName = value; onPropertyChanged(new PropertyChangedEventArgs("Quota Name")); } }</code><technical_language>nullity check :)</technical_language>

Target:
public void setQuotaName(String value) { if (privateQuotaName != null && !privateQuotaName.equals(value)) { privateQuotaName = value; onPropertyChanged(new PropertyChangedEventArgs("Quota Name")); } }
Source:
<code>protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final ServiceName serviceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR))); final ServiceName jmsServiceName = JMSServices.getJmsManagerBaseServiceName(serviceName); final String name = context.getCurrentAddress().getLastElement().getValue(); <START> ServiceController<?> service = context.getServiceRegistry(false).getService(jmsServiceName); <END> JMSServerManager server = JMSServerManager.class.cast(service.getValue()); try { server.destroyTopic(name, true); } catch (Exception e) { throw new OperationFailedException(e); } context.removeService(JMSServices.getJmsTopicBaseServiceName(serviceName).append(name)); for (String entry : CommonAttributes.DESTINATION_ENTRIES.unwrap(context, model)) { final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(entry); ServiceName binderServiceName = bindInfo.getBinderServiceName(); context.removeService(binderServiceName); } for (String legacyEntry : CommonAttributes.LEGACY_ENTRIES.unwrap(context, model)) { final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(legacyEntry); ServiceName binderServiceName = bindInfo.getBinderServiceName(); context.removeService(binderServiceName); } }</code><technical_language>getServiceRegistry(true)</technical_language>

Target:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final ServiceName serviceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR))); final ServiceName jmsServiceName = JMSServices.getJmsManagerBaseServiceName(serviceName); final String name = context.getCurrentAddress().getLastElement().getValue(); ServiceController<?> service = context.getServiceRegistry(true).getService(jmsServiceName); JMSServerManager server = JMSServerManager.class.cast(service.getValue()); try { server.destroyTopic("jms.topic." + name, true); } catch (Exception e) { throw new OperationFailedException(e); } context.removeService(JMSServices.getJmsTopicBaseServiceName(serviceName).append(name)); for (String entry : CommonAttributes.DESTINATION_ENTRIES.unwrap(context, model)) { final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(entry); ServiceName binderServiceName = bindInfo.getBinderServiceName(); context.removeService(binderServiceName); } for (String legacyEntry : CommonAttributes.LEGACY_ENTRIES.unwrap(context, model)) { final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(legacyEntry); ServiceName binderServiceName = bindInfo.getBinderServiceName(); context.removeService(binderServiceName); } }
Source:
<code>private static boolean isUsageInClassBody(Usage usage, ClassDef classDef) { if (usage.kind() == Usage.Kind.FUNC_DECLARATION) { return false; } Tree tree = usage.tree(); <START> return classDef.equals(TreeUtils.firstAncestorOfKind(tree, Tree.Kind.CLASSDEF)) <END> && TreeUtils.firstAncestorOfKind(tree, Tree.Kind.FUNCDEF) == null; }</code><technical_language>I refactor this code: java return classDef.equals(TreeUtils.firstAncestorOfKind(tree, Tree.Kind.CLASSDEF, Tree.Kind.FUNCDEF))</technical_language>

Target:
private static boolean isUsageInClassBody(Usage usage, ClassDef classDef) { return usage.kind() != Usage.Kind.FUNC_DECLARATION && classDef.equals(TreeUtils.firstAncestorOfKind(usage.tree(), Tree.Kind.CLASSDEF, Tree.Kind.FUNCDEF)); }
Source:
<code>public void datastoreReadWriteTest() { final Long assignmentId = 1L; final Long deviceId = 1L; final List<Long> dataPointIds = Collections.singletonList(0L); final Long surveyId = 1L; createDataPointAssignment(assignmentId, deviceId, dataPointIds, surveyId); final DataPointAssignmentDao dataPointAssignmentDao = new DataPointAssignmentDao(); final List<DataPointAssignment> dataPointAssignments = dataPointAssignmentDao.listByDeviceAndSurvey(deviceId, surveyId); assertFalse(dataPointAssignments.isEmpty()); final DataPointAssignment assignment = dataPointAssignments.get(0); <START> assertEquals(assignment.getDataPointIds(), dataPointIds); <END> assertEquals(assignment.getDeviceId(), deviceId); assertEquals(assignment.getSurveyId(), surveyId); final List<Long> deviceIds = Arrays.asList(1L, 2L); final List<Long> formIds = Arrays.asList(100L, 200L); createAssingment(surveyId, deviceIds, formIds); final SurveyAssignmentDao saDao = new SurveyAssignmentDao(); final List<SurveyAssignment> surveyAssignments = saDao.listAllContainingDevice(2L); assertFalse(surveyAssignments.isEmpty()); final SurveyAssignment sa = surveyAssignments.get(0); assertEquals(sa.getSurveyId(), surveyId); assertTrue(sa.getDeviceIds().contains(2L)); assertEquals(sa.getFormIds(), formIds); }</code><technical_language>assertEquals params reversed I believe. assertEquals(expected, actual)</technical_language>

Target:
public void datastoreReadWriteTest() { final Long assignmentId = randomId(); final Long deviceId = randomId(); final Long surveyId = randomId(); createDataPointAssignment(assignmentId, deviceId, ALL_DATA_POINTS, surveyId); final DataPointAssignmentDao dataPointAssignmentDao = new DataPointAssignmentDao(); final List<DataPointAssignment> dataPointAssignments = dataPointAssignmentDao.listByDeviceAndSurvey(deviceId, surveyId); assertFalse(dataPointAssignments.isEmpty()); final DataPointAssignment assignment = dataPointAssignments.get(0); assertEquals(ALL_DATA_POINTS, assignment.getDataPointIds()); assertEquals(deviceId, assignment.getDeviceId()); assertEquals(surveyId, assignment.getSurveyId()); final List<Long> deviceIds = Arrays.asList(randomId(), randomId()); final List<Long> formIds = Arrays.asList(randomId(), randomId()); createAssignment(surveyId, deviceIds, formIds); final SurveyAssignmentDao saDao = new SurveyAssignmentDao(); final List<SurveyAssignment> surveyAssignments = saDao.listAllContainingDevice(deviceIds.get(1)); assertFalse(surveyAssignments.isEmpty()); final SurveyAssignment sa = surveyAssignments.get(0); assertEquals(surveyId, sa.getSurveyId()); assertTrue(sa.getDeviceIds().contains(deviceIds.get(1))); assertEquals(formIds, sa.getFormIds()); }
Source:
<code>public PojoPropertyArguments(String prefix, Object obj, StatementContext ctx) { this(prefix, obj, <START> ctx.getConfig(PojoTypes.class).propertiesOf(obj.getClass()) <END> .orElseThrow(() -> new UnableToCreateStatementException("Couldn't find pojo type of " + obj.getClass(), ctx)), ctx); }</code><technical_language>name this method findFor() stay consistent other registries</technical_language>

Target:
public PojoPropertyArguments(String prefix, Object obj, StatementContext ctx) { this(prefix, obj, ctx.getConfig(PojoTypes.class).findFor(obj.getClass()) .orElseThrow(() -> new UnableToCreateStatementException("Couldn't find pojo type of " + obj.getClass(), ctx)), ctx); }
Source:
<code>public void checkField(VariableTree fieldTree) { <START> if (!(fieldTree.initializer() instanceof LiteralTree)) { <END> return; } boolean explicitInit = false; LiteralTree initTree = (LiteralTree) fieldTree.initializer(); try { if (!initTree.symbolType().isPrimitive() && "null".equals(initTree.value())) { explicitInit = true; } else if (initTree.symbolType().isPrimitive() && initTree.symbolType().isNumerical() && NumberFormat.getInstance().parse(initTree.value()).shortValue() == 0) { explicitInit = true; } else if (initTree.symbolType().isPrimitive(Primitives.BOOLEAN) && !Boolean.parseBoolean(initTree.value())) { explicitInit = true; } } catch (ParseException e) { if (initTree.symbolType().isPrimitive(Primitives.CHAR) && "'\\0'".equals(initTree.value())) { explicitInit = true; } } if (explicitInit) { addIssue(fieldTree, String.format("Remove this initialization to \"%s\", the compiler will do that for you.", fieldTree.symbol().name())); } }</code><technical_language>instance of operator check for nullity is() method Kinds</technical_language>

Target:
public void checkField(VariableTree fieldTree) { if (!isLiteral(fieldTree.initializer())) { return; } LiteralTree initTree = (LiteralTree) fieldTree.initializer(); if (isInitObjectNull(initTree) || isInitNumericalZero(initTree) || isInitBooleanFalse(initTree)) { addIssue(fieldTree, String.format("Remove this initialization to \"%s\", the compiler will do that for you.", fieldTree.symbol().name())); } }
Source:
<code>public boolean accept(Path path) { String name = path.getName(); if (name.startsWith("_") || name.startsWith(".")) { return false; } return true; <START> } <END></code><technical_language>replace this return !(name.startsWith("_") || name.startsWith(".")) add java docs for this class</technical_language>

Target:
public boolean accept(Path path) { String name = path.getName(); return !(name.startsWith("_") || name.startsWith(".")); }
Source:
<code>public void requestBodyIsIgnored() throws Exception { final Take take = new Take() { @Override public Response act(final Request req) throws IOException { <START> return new RsText("response ok"); <END> } }; new FtRemote(new TkReadAlways(take)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST").header( "Content-Type", "application/x-www-form-urlencoded" ).body() .formParam("name", "Jeff Warraby") .formParam("age", "4") .back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody( Matchers.equalTo( Joiner.on(" ").join("response", "ok") ) ); } } ); }</code><technical_language>@danff please "response ok" a variable, reuse in matcher</technical_language>

Target:
public void requestBodyIsIgnored() throws Exception { final String expected = "response ok"; final Take take = new Take() { @Override public Response act(final Request req) throws IOException { return new RsText(expected); } }; new FtRemote(new TkReadAlways(take)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST").header( "Content-Type", "application/x-www-form-urlencoded" ).body() .formParam("name", "Jeff Warraby") .formParam("age", "4") .back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.equalTo(expected)); } } ); }
Source:
<code>static String generate( List<AsciiTableAlignment> alignments, List<String> headers, <START> List<? extends List<String>> cells) { <END> int colCount = alignments.size(); int[] colLengths = new int[colCount]; for (int colIdx = 0; colIdx < colCount; colIdx++) { colLengths[colIdx] = headers.get(colIdx).length(); } for (List<String> row : cells) { for (int colIdx = 0; colIdx < colCount; colIdx++) { colLengths[colIdx] = Math.max(colLengths[colIdx], row.get(colIdx).length()); } } StringBuilder buf = new StringBuilder(2048); writeSeparatorLine(buf, colLengths); writeDataLine(buf, colLengths, alignments, headers); writeSeparatorLine(buf, colLengths); for (int rowIdx = 0; rowIdx < cells.size(); rowIdx++) { writeDataLine(buf, colLengths, alignments, cells.get(rowIdx)); } writeSeparatorLine(buf, colLengths); return buf.toString(); }</code><technical_language>initially ensure inputs consistent (i.e. number of columns throughout) avoid IndexOutOfBoundsException helpful message</technical_language>

Target:
static String generate( List<AsciiTableAlignment> alignments, List<String> headers, List<? extends List<String>> cells) { int colCount = alignments.size(); int rowCount = cells.size(); ArgChecker.isTrue( headers.size() == colCount, "Number of headers must match number of alignments {}", headers.size(), colCount); int[] colLengths = new int[colCount]; for (int colIdx = 0; colIdx < colCount; colIdx++) { colLengths[colIdx] = headers.get(colIdx).length(); } for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { List<String> row = cells.get(rowIdx); ArgChecker.isTrue( row.size() == colCount, "Table of cells has incorrect number of columns in row {}", row.size(), rowIdx); for (int colIdx = 0; colIdx < colCount; colIdx++) { colLengths[colIdx] = Math.max(colLengths[colIdx], row.get(colIdx).length()); } } int colTotalLength = 3; for (int colIdx = 0; colIdx < colCount; colIdx++) { colTotalLength += colLengths[colIdx] + 3; } StringBuilder buf = new StringBuilder((rowCount + 3) * colTotalLength); writeSeparatorLine(buf, colLengths); writeDataLine(buf, colLengths, alignments, headers); writeSeparatorLine(buf, colLengths); for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { writeDataLine(buf, colLengths, alignments, cells.get(rowIdx)); } writeSeparatorLine(buf, colLengths); return buf.toString(); }
Source:
<code>public void mongoConfigShouldSetMongoUriPrefsOnScanResult() throws Exception { setValidMongoOnlyWithIntentResult(); <START> assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_URI, null), is("mongodb://user:pass@test.com/cgm_data")); <END> }</code><technical_language>thoughts AndroidPreferences instead of a raw SharedPrefs</technical_language>

Target:
public void mongoConfigShouldSetMongoUriPrefsOnScanResult() throws Exception { setValidMongoOnlyWithIntentResult(); assertThat(prefs.getMongoClientUri(), is("mongodb://user:pass@test.com/cgm_data")); }
Source:
<code><START> public void onRewardedVideoAdClicked(String instanceId, Placement placement) { <END> onLog("onRewardedVideoAdClicked"); }</code><technical_language>Notify MoPub's onRewardedVideoClicked()</technical_language>

Target:
public void onRewardedVideoAdClicked(String instanceId, Placement placement) { onLog("onRewardedVideoAdClicked"); onRewardedVideoClicked(IronSourceRewardedVideo.class, instanceId); }
Source:
<code><START> public Example(T probe) { <END> Assert.notNull(probe, "Probe must not be null!"); this.probe = probe; this.exampleSpec = ExampleSpec.of((Class<T>) probe.getClass()); }</code><technical_language>private of( ) is create instances of Example</technical_language>

Target:
private Example(T probe) { Assert.notNull(probe, "Probe must not be null!"); this.probe = probe; this.exampleSpec = ExampleSpec.untyped(); }
Source:
<code>public static ArrayList<ObsRow> sortObsRows(final ArrayList<ObsRow> rows, final ArrayList<String> conceptUuids) { <START> Collections.sort(rows, new Comparator<ObsRow>() { <END> @Override public int compare(ObsRow obsRow1, ObsRow obsRow2) { int indexObsRow1 = conceptUuids.indexOf(obsRow1.conceptUid); int indexObsRow2 = conceptUuids.indexOf(obsRow2.conceptUid); if (indexObsRow1 == -1) { indexObsRow1 += rows.size(); } if (indexObsRow2 == -1) { indexObsRow2 += rows.size(); } return Integer.compare(indexObsRow1, indexObsRow2); } } ); return rows; }</code><technical_language>Avoid names similar hard apart, e.g. in indexObsRow1, indexObsRow part conveys information 1 is critical, visually find a needle in a haystack detect a typo. common advice avoid single-letter names is correct, comparison methods a special case of everything. In this situation, a b easier obsRow1 obsRow2: public int compare(ObsRow a, ObsRow b) { int ai = conceptUuids.indexOf(a.conceptUuid); int bi = conceptUuids.indexOf(b.conceptUuid); ... etc. }</technical_language>

Target:
public static ArrayList<ObsRow> sortObsRows(final ArrayList<ObsRow> rows, final ArrayList<String> conceptUuids) { Collections.sort(rows, new Comparator<ObsRow>() { @Override public int compare(ObsRow a, ObsRow b) { int aIndex = conceptUuids.indexOf(a.conceptUuid); int bIndex = conceptUuids.indexOf(b.conceptUuid); int pastLastIndex = rows.size(); if (aIndex == -1) { aIndex = pastLastIndex; } if (bIndex == -1) { bIndex = pastLastIndex; } if (aIndex == bIndex) { return a.conceptName.compareTo(b.conceptName); } else { return Integer.compare(aIndex, bIndex); } } }); return rows; }
Source:
<code>public void TestWikiaLogoInGlobalNav_001_centralWikiExists(String wikiName, String expectedCentralUrl) { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki(wikiName)); VenusGlobalNavPageObject globalNav = homePage.getVenusGlobalNav(); globalNav.waitForCorrectUrl(config.getEnv()); <START> globalNav.clickWikiaLogo(); <END> Assertion.assertStringContains(urlBuilder.getUrlForWiki(expectedCentralUrl), driver.getCurrentUrl()); }</code><technical_language>fluent interface in</technical_language>

Target:
public void TestWikiaLogoInGlobalNav_001_centralWikiExists(String wikiName, String expectedCentralUrl) { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki(wikiName)); homePage.getVenusGlobalNav() .clickWikiaLogo(); Assertion.assertStringContains(urlBuilder.getUrlForWiki(expectedCentralUrl), driver.getCurrentUrl()); }
Source:
<code>public void onConfigChanged(OnConfigChangedEvent event) { <START> if (getMetadata().modId.equals(event.getModID())) END> { if (Configuration.CATEGORY_GENERAL.equals(event.getConfigID()) || Configuration.CATEGORY_CLIENT.equals(event.getConfigID())) { syncConfig(false); } else if ("chunkLoader".equals(event.getConfigID())) { ForgeChunkManager.syncConfigDefaults(); ForgeChunkManager.loadConfiguration(); } else if (VERSION_CHECK_CAT.equals(event.getConfigID())) { syncConfig(false); } } }</code><technical_language>This left intentionally</technical_language>

Target:
public void onConfigChanged(OnConfigChangedEvent event) { if (getMetadata().modId.equals(event.getModID()) && !event.isWorldRunning()) { if (Configuration.CATEGORY_GENERAL.equals(event.getConfigID())) { syncConfig(false); } else if ("chunkLoader".equals(event.getConfigID())) { ForgeChunkManager.syncConfigDefaults(); ForgeChunkManager.loadConfiguration(); } else if (VERSION_CHECK_CAT.equals(event.getConfigID())) { syncConfig(false); } } }
Source:
<code>private Map<String, String> getEnvFromInterpreterProperty(Properties property) { Map<String, String> env = new HashMap<String, String>(); StringBuilder sparkConfBuilder = new StringBuilder(); for (String key : property.stringPropertyNames()) { if (RemoteInterpreterUtils.isEnvString(key)) { env.put(key, property.getProperty(key)); } <START> if (key.equals("master")) { <END> sparkConfBuilder.append(" --master " + property.getProperty("master")); } if (isSparkConf(key, property.getProperty(key))) { sparkConfBuilder.append(" --conf " + key + "=" + property.getProperty(key)); } } env.put("ZEPPELIN_SPARK_CONF", sparkConfBuilder.toString()); return env; }</code><technical_language>special case this? ask "spark.master"</technical_language>

Target:
private Map<String, String> getEnvFromInterpreterProperty(Properties property) { Map<String, String> env = new HashMap<String, String>(); StringBuilder sparkConfBuilder = new StringBuilder(); for (String key : property.stringPropertyNames()) { if (RemoteInterpreterUtils.isEnvString(key)) { env.put(key, property.getProperty(key)); } if (key.equals("master")) { sparkConfBuilder.append(" --master " + property.getProperty("master")); } if (isSparkConf(key, property.getProperty(key))) { sparkConfBuilder.append(" --conf " + key + "=\"" + toShellFormat(property.getProperty(key)) + "\""); } } env.put("ZEPPELIN_SPARK_CONF", sparkConfBuilder.toString()); return env; }
Source:
<code>public void testSimpleOperation() throws Exception { SFSBHibernateSessionFactory sfsb = lookup("SFSBHibernateSessionFactory", SFSBHibernateSessionFactory.class); sfsb.setupConfig(); try { Student s1 = sfsb.createStudent("MADHUMITA", "SADHUKHAN", "99 Purkynova REDHAT BRNO CZ", 1); Student s2 = sfsb.createStudent("REDHAT", "LINUX", "Worldwide", 3); Student st = sfsb.getStudent(s1.getStudentId()); <START> assertTrue( "name read from hibernate session is MADHUMITA", "MADHUMITA".equals( st.getFirstName() ) ); <END> } finally { sfsb.cleanup(); } }</code><technical_language>a big deal, is a reason assertEquals() here</technical_language>

Target:
public void testSimpleOperation() throws Exception { SFSBHibernateSessionFactory sfsb = lookup("SFSBHibernateSessionFactory", SFSBHibernateSessionFactory.class); sfsb.setupConfig(); try { Student s1 = sfsb.createStudent("MADHUMITA", "SADHUKHAN", "99 Purkynova REDHAT BRNO CZ", 1); Student s2 = sfsb.createStudent("REDHAT", "LINUX", "Worldwide", 3); Student st = sfsb.getStudent(s1.getStudentId()); assertEquals( "name read from hibernate session is MADHUMITA", "MADHUMITA", st.getFirstName() ); } finally { sfsb.cleanup(); } }
Source:
<code>public void visitNode(Tree tree) { ExpressionTree expression = ExpressionsHelper.skipParentheses(((UnaryExpressionTree) tree).expression()); if (expression.is( Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO, Tree.Kind.LESS_THAN, Tree.Kind.GREATER_THAN, Tree.Kind.LESS_THAN_OR_EQUAL_TO, Tree.Kind.GREATER_THAN_OR_EQUAL_TO)) { <START> context.reportIssue(this, expression, "Use the opposite operator (\"" + OPERATORS.get(((BinaryExpressionTree) expression).operatorToken().text()) + "\") instead."); <END> } }</code><technical_language>@benzonico is highlight tree includes !</technical_language>

Target:
public void visitNode(Tree tree) { ExpressionTree expression = ExpressionsHelper.skipParentheses(((UnaryExpressionTree) tree).expression()); if (expression.is( Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO, Tree.Kind.LESS_THAN, Tree.Kind.GREATER_THAN, Tree.Kind.LESS_THAN_OR_EQUAL_TO, Tree.Kind.GREATER_THAN_OR_EQUAL_TO)) { context.reportIssue(this, tree, "Use the opposite operator (\"" + OPERATORS.get(((BinaryExpressionTree) expression).operatorToken().text()) + "\") instead."); } }
Source:
<code>public Meteor(ItemStack catalystStack, List<MeteorComponent> components, float explosionStrength, int radius) { this.catalystStack = catalystStack; this.components = components; this.explosionStrength = explosionStrength; this.radius = radius; int weight = 0; for (MeteorComponent component : components) weight += component.getWeight(); this.maxWeight = weight; <START> this.cost = 1000000; <END> }</code><technical_language>GSON initializes classes reflection constructor. default definition set field declaration</technical_language>

Target:
public Meteor(ItemStack catalystStack, List<MeteorComponent> components, float explosionStrength, int radius) { this.catalystStack = catalystStack; this.components = components; this.explosionStrength = explosionStrength; this.radius = radius; int weight = 0; for (MeteorComponent component : components) weight += component.getWeight(); this.maxWeight = weight; }
Source:
<code>public void run() { running.inc(); <START> Timer.Context context = duration.time(); <END> try { task.run(); } finally { context.stop(); running.dec(); completed.mark(); } }</code><technical_language>this final</technical_language>

Target:
public void run() { running.inc(); final Timer.Context context = duration.time(); try { task.run(); } finally { context.stop(); running.dec(); completed.mark(); } }
Source:
<code>protected void onSetUp(SystemTestData testData) throws Exception { super.onSetUp(testData); testData.addRasterLayer(POLYPHEMUS, "pol.zip", null, null, this.getClass(), getCatalog()); setupRasterDimension(getLayerId(NO2), ResourceInfo.TIME, DimensionPresentation.LIST, null); setupRasterDimension( getLayerId(NO2), ResourceInfo.ELEVATION, DimensionPresentation.LIST, null); setupRasterDimension(getLayerId(O3), ResourceInfo.TIME, DimensionPresentation.LIST, null); setupRasterDimension( getLayerId(O3), ResourceInfo.ELEVATION, DimensionPresentation.LIST, null); <START> setupRasterDimension(getLayerId(O3), ResourceInfo.TIME, DimensionPresentation.LIST, null); <END> testData.addRasterLayer( TEMPERATURE_SURFACE_NETCDF, "rotated-pole.nc", null, null, this.getClass(), getCatalog()); testData.addRasterLayer( TEMPERATURE_SURFACE_GRIB, "rap-native.grib2", null, null, this.getClass(), getCatalog()); testData.addRasterLayer( SNOW_DEPTH_GRIB, "cosmo-eu.grib2", null, null, this.getClass(), getCatalog()); }</code><technical_language>a typo here. added line 80</technical_language>

Target:
protected void onSetUp(SystemTestData testData) throws Exception { super.onSetUp(testData); testData.addRasterLayer(POLYPHEMUS, "pol.zip", null, null, this.getClass(), getCatalog()); setupRasterDimension(getLayerId(NO2), ResourceInfo.TIME, DimensionPresentation.LIST, null); setupRasterDimension( getLayerId(NO2), ResourceInfo.ELEVATION, DimensionPresentation.LIST, null); setupRasterDimension(getLayerId(O3), ResourceInfo.TIME, DimensionPresentation.LIST, null); setupRasterDimension( getLayerId(O3), ResourceInfo.ELEVATION, DimensionPresentation.LIST, null); testData.addRasterLayer( TEMPERATURE_SURFACE_NETCDF, "rotated-pole.nc", null, null, this.getClass(), getCatalog()); testData.addRasterLayer( TEMPERATURE_SURFACE_GRIB, "rap-native.grib2", null, null, this.getClass(), getCatalog()); testData.addRasterLayer( SNOW_DEPTH_GRIB, "cosmo-eu.grib2", null, null, this.getClass(), getCatalog()); }
Source:
<code>protected HeaderMatcher createHeaderMatcher(Collection<String> patterns) { List<HeaderMatcher> matchers = new ArrayList<HeaderMatcher>(); for (String pattern : patterns) { if (STANDARD_REQUEST_HEADER_NAME_PATTERN.equals(pattern)) { matchers.add(new ContentBasedHeaderMatcher(true, this.requestHeaderNames)); } else if (STANDARD_REPLY_HEADER_NAME_PATTERN.equals(pattern)) { matchers.add(new ContentBasedHeaderMatcher(true, this.replyHeaderNames)); } else if (NON_STANDARD_HEADER_NAME_PATTERN.equals(pattern)) { matchers.add(new PrefixBasedMatcher(false, this.standardHeaderPrefix)); } else { String thePattern = pattern; boolean negate = false; if (pattern.startsWith("!")) { thePattern = pattern.substring(1); negate = true; } else if (pattern.startsWith("\\!")) { thePattern = pattern.substring(1); } if (negate) { matchers.add(0, new PatternBasedHeaderMatcher(Collections.singleton(thePattern), negate)); } else { <START> matchers.add(new PatternBasedHeaderMatcher(Collections.singleton(thePattern), negate)); <END> } } } return new CompositeHeaderMatcher(matchers); }</code><technical_language>PatternBasedHeaderMatcher **single** pattern. some overhead extra Collection object iteration matchHeader(). I agree good break PatternBasedHeaderMatcher some AbstractHeaderMapper Collection. other side rework logic PatternBasedHeaderMatcher collection of patterns including negate</technical_language>

Target:
protected HeaderMatcher createHeaderMatcher(Collection<String> patterns) { List<HeaderMatcher> matchers = new ArrayList<HeaderMatcher>(); for (String pattern : patterns) { if (STANDARD_REQUEST_HEADER_NAME_PATTERN.equals(pattern)) { matchers.add(new ContentBasedHeaderMatcher(true, this.requestHeaderNames)); } else if (STANDARD_REPLY_HEADER_NAME_PATTERN.equals(pattern)) { matchers.add(new ContentBasedHeaderMatcher(true, this.replyHeaderNames)); } else if (NON_STANDARD_HEADER_NAME_PATTERN.equals(pattern)) { matchers.add(new PrefixBasedMatcher(false, this.standardHeaderPrefix)); } else { String thePattern = pattern; boolean negate = false; if (pattern.startsWith("!")) { thePattern = pattern.substring(1); negate = true; } else if (pattern.startsWith("\\!")) { thePattern = pattern.substring(1); } if (negate) { matchers.add(0, new SinglePatternBasedHeaderMatcher(thePattern, negate)); } else { matchers.add(new SinglePatternBasedHeaderMatcher(thePattern, negate)); } } } return new CompositeHeaderMatcher(matchers); }
Source:
<code>public void testMixedSitesPerHostSubOptimal() throws InterruptedException { if (!MiscUtils.isPro()) { return; } MixedSitesPerHostCluster cluster = null; Map<Integer, Integer> subOptimalSphMap = Maps.newHashMap(); subOptimalSphMap.put(0, 2); subOptimalSphMap.put(1, 6); subOptimalSphMap.put(2, 3); cluster = new MixedSitesPerHostCluster(subOptimalSphMap); try { cluster.start(); fail(); } <START> catch (RuntimeException e) <END> finally { cluster.shutdown(); } }</code><technical_language>verify error message well. fails. other reasons expected</technical_language>

Target:
public void testMixedSitesPerHostSubOptimal() throws InterruptedException { if (!MiscUtils.isPro()) { return; } MixedSitesPerHostCluster cluster = null; Map<Integer, Integer> subOptimalSphMap = Maps.newHashMap(); subOptimalSphMap.put(0, 2); subOptimalSphMap.put(1, 6); subOptimalSphMap.put(2, 3); cluster = new MixedSitesPerHostCluster(subOptimalSphMap); try { cluster.start(); fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().endsWith("external processes failed to start")); } finally { cluster.shutdown(); } }
Source:
<code>private String getSessionDescription(ISarosSession session) { String description = "Projects: "; IReferencePointManager referencePointManager = session.getComponent(IReferencePointManager.class); Set<IReferencePoint> referencePoints = session.getReferencePoints(); int i = 0; <START> int numOfProjects = referencePoints.size(); <END> for (IReferencePoint referencePoint : referencePoints) { description += referencePointManager.getName(referencePoint); if (!session.isCompletelyShared(referencePoint)) description += " (partial)"; if (i < numOfProjects - 1) description += ", "; i++; } if (numOfProjects == 0) { description += "none"; } return description; }</code><technical_language>suggestion int numOfReferencePoints = referencePoints.size();</technical_language>

Target:
private String getSessionDescription(ISarosSession session) { String description = "Projects: "; IReferencePointManager referencePointManager = session.getComponent(IReferencePointManager.class); Set<IReferencePoint> referencePoints = session.getReferencePoints(); int i = 0; int numOfReferencePoints = referencePoints.size(); for (IReferencePoint referencePoint : referencePoints) { description += referencePointManager.getName(referencePoint); if (!session.isCompletelyShared(referencePoint)) description += " (partial)"; if (i < numOfReferencePoints - 1) description += ", "; i++; } if (numOfReferencePoints == 0) { description += "none"; } return description; }
Source:
<code>public EventValidator materialize(final EventType eventType, final ValidationStrategyConfiguration vsc) { final JSONSchemaValidator defaultSchemaValidator = new JSONSchemaValidator(eventType.getEventTypeSchema() .getSchema()); if (vsc.getAdditionalConfiguration() == null) { return defaultSchemaValidator; } final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonOrgModule()); final Function<OverrideDefinition, OverrideDefinition> enhanceWithQualifiedSchema = definition -> { final JSONObject schema = eventType.getEventTypeSchema().getSchema(); final JSONObject copy = new JSONObject(schema, JSONObject.getNames(schema)); <START> definition.getIgnoredProperties().forEach(new Consumer<String>() { <END> @Override public void accept(final String name) { copy.getJSONObject("properties").remove(name); final JSONArray array = copy.getJSONArray("required"); final int idx = findElement(array, name); if (idx > -1) { array.remove(idx); } } }); definition.setEffectiveSchema(copy); return definition; }; final List<QualifiedJSONSchemaValidator> qualifiedValidators = mapper.convertValue( vsc.getAdditionalConfiguration(), SchemaValidationOverrides.class) .getOverrides().stream() .map(enhanceWithQualifiedSchema) .map(toQualifiedJSONSchemaValidator) .collect(Collectors.toList()); return new QualifiedJSONSchemaValidationChain(qualifiedValidators, defaultSchemaValidator); }</code><technical_language>lambda</technical_language>

Target:
public EventValidator materialize(final EventType eventType, final ValidationStrategyConfiguration vsc) { final JSONSchemaValidator defaultSchemaValidator = new JSONSchemaValidator(eventType.getEventTypeSchema() .getSchema()); if (vsc.getAdditionalConfiguration() == null) { return defaultSchemaValidator; } final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonOrgModule()); final Function<OverrideDefinition, OverrideDefinition> enhanceWithQualifiedSchema = definition -> { final JSONObject schema = eventType.getEventTypeSchema().getSchema(); final JSONObject copy = new JSONObject(schema, JSONObject.getNames(schema)); definition.getIgnoredProperties().forEach(name -> { copy.getJSONObject("properties").remove(name); final JSONArray array = copy.getJSONArray("required"); final int idx = findElement(array, name); if (idx > -1) { array.remove(idx); } }); definition.setEffectiveSchema(copy); return definition; }; final List<QualifiedJSONSchemaValidator> qualifiedValidators = mapper.convertValue( vsc.getAdditionalConfiguration(), SchemaValidationOverrides.class) .getOverrides().stream() .map(enhanceWithQualifiedSchema) .map(toQualifiedJSONSchemaValidator) .collect(Collectors.toList()); return new QualifiedJSONSchemaValidationChain(qualifiedValidators, defaultSchemaValidator); }