auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void setPartitionState(String partition, PartitionState partitionState) { for (IdealState entry : resourcesToIdealStates.values()) { <START> for (String partitionStr : entry.getPartitionSet()) { <END> if (partitionStr.equals(partition) && partitionStates.containsKey(partition)) { partitionStates.put(partition, partitionState); } } } }</code><technical_language>Calling this partitionStr is confusing partition is a partition string. this more readable</technical_language>

Target:
void setPartitionState(String partition, PartitionState partitionState) { for (IdealState entry : resourcesToIdealStates.values()) { for (String partitionInIdealState : entry.getPartitionSet()) { if (partitionInIdealState.equals(partition)) { partitionToPartitionStates.put(partition, partitionState); } } } }
Source:
<code>private RetryingMutateRowsOperation createOperation(MutateRowsRequest request) { return new RetryingMutateRowsOperation(RETRY_OPTIONS, request, mutateRows, CallOptions.DEFAULT, executorService, new Metadata()) { @Override protected ApiClock getApiClock() { <START> return clock; <END> } }; }</code><technical_language>nit: I nicer pass a constructor arg</technical_language>

Target:
private RetryingMutateRowsOperation createOperation(MutateRowsRequest request) { return new RetryingMutateRowsOperation(RETRY_OPTIONS, request, mutateRows, CallOptions.DEFAULT, executorService, new Metadata(), clock); }
Source:
<code>private boolean isPostgreSQLIntegrityConstraintViolation(SQLException sqlException) { <START> return sqlException instanceof PSQLException && sqlException.getSQLState().matches("23\\d{3}"); <END> }</code><technical_language>While regexp clever, is that? if code clashes somehow</technical_language>

Target:
private boolean isPostgreSQLIntegrityConstraintViolation(SQLException sqlException) { return sqlException instanceof PSQLException && sqlException.getSQLState().length() == 5 && sqlException.getSQLState().startsWith("23"); }
Source:
<code>public static WebArchive createWebApplication() { return ShrinkWrap.create(WebArchive.class, "spring-test.war") .addClasses(Employee.class, EmployeeService.class, DefaultEmployeeService.class, EmployeeRepository.class, DefaultEmployeeRepository.class, NullEmployeeRepository.class, <START> EmployeeController.class, ClassPathResourceLocationsProcessor.class) <END> .addAsLibraries(springDependencies()) .addAsLibraries(mockitoDependencies()); }</code><technical_language>extension internal class here. Good added archive appender, removed here</technical_language>

Target:
public static WebArchive createWebApplication() { return ShrinkWrap.create(WebArchive.class, "spring-test.war") .addClasses(Employee.class, EmployeeService.class, DefaultEmployeeService.class, EmployeeRepository.class, DefaultEmployeeRepository.class, NullEmployeeRepository.class, EmployeeController.class) .addAsLibraries(springDependencies()) .addAsLibraries(mockitoDependencies()); }
Source:
<code>public Deserializer getDeserializer(String type) throws HessianProtocolException { <START> if (type == null || type.equals("") || typeNotFoundDeserializer.contains(type)) { <END> return null; } Deserializer deserializer = super.getDeserializer(type); if (deserializer == null) { typeNotFoundDeserializer.add(type); logger.warn("unable to find deserializer for string type:" + type); } return deserializer; }</code><technical_language>StringUtils#isEmpty this method replace</technical_language>

Target:
public Deserializer getDeserializer(String type) throws HessianProtocolException { if (StringUtils.isEmpty(type) || typeNotFoundDeserializer.contains(type)) { return null; } Deserializer deserializer = super.getDeserializer(type); if (deserializer == null) { typeNotFoundDeserializer.add(type); logger.warn("unable to find deserializer for string type:" + type); } return deserializer; }
Source:
<code>public void setUp() throws Exception { <START> Constant.getInstance(); I18N i18n = Mockito.mock(I18N.class, withSettings().lenient()); given(i18n.getString(anyString())).willReturn(""); given(i18n.getString(anyString(), any())).willReturn(""); <END> given(i18n.getLocal()).willReturn(Locale.getDefault()); Constant.messages = i18n; type = new FormBasedAuthenticationMethodType(); method = Mockito.mock(AuthenticationMethod.class, Mockito.CALLS_REAL_METHODS); method.setAuthCheckingStrategy(AuthCheckingStrategy.POLL_URL); method.setPollFrequencyUnits(AuthPollFrequencyUnits.REQUESTS); method.setPollFrequency(5); method.setLoggedInIndicatorPattern(LOGGED_IN_INDICATOR); type = new FormBasedAuthenticationMethodType(); Mockito.when(method.getType()).thenReturn(type); mockedSessionManagementMethod = Mockito.mock(SessionManagementMethod.class); doNothing() .when(mockedSessionManagementMethod) .processMessageToMatchSession((HttpMessage) any(), (WebSession) any()); mockedContext = Mockito.mock(Context.class); when(mockedContext.getSessionManagementMethod()).thenReturn(mockedSessionManagementMethod); this.startServer(); }</code><technical_language>Worth exposing a method, e.g. WithConfigsTest#setupConstant() instead of duplicating here</technical_language>

Target:
public void setUp() throws Exception { WithConfigsTest.setUpConstant(); type = new FormBasedAuthenticationMethodType(); method = type.createAuthenticationMethod(1); method.setAuthCheckingStrategy(AuthCheckingStrategy.POLL_URL); method.setPollFrequencyUnits(AuthPollFrequencyUnits.REQUESTS); method.setPollFrequency(5); method.setLoggedInIndicatorPattern(LOGGED_IN_INDICATOR); mockedSessionManagementMethod = Mockito.mock(SessionManagementMethod.class); doNothing() .when(mockedSessionManagementMethod) .processMessageToMatchSession((HttpMessage) any(), (WebSession) any()); mockedContext = Mockito.mock(Context.class); when(mockedContext.getSessionManagementMethod()).thenReturn(mockedSessionManagementMethod); this.startServer(); }
Source:
<code>private <T> T uncachedValue(Class<?> cls) throws BinaryObjectException { assert cls != null; <START> GridBinaryMarshaller.USE_CACHE.set(Boolean.FALSE); <END> if (ord >= 0) { Object[] vals = cls.getEnumConstants(); if (ord < vals.length) return (T)vals[ord]; else throw new BinaryObjectException("Failed to get enum value for ordinal (do you have correct class " + "version?) [cls=" + cls.getName() + ", ordinal=" + ord + ", totalValues=" + vals.length + ']'); } else return null; }</code><technical_language>return true</technical_language>

Target:
private <T> T uncachedValue(Class<?> cls) throws BinaryObjectException { assert cls != null; assert !GridBinaryMarshaller.USE_CACHE.get(); if (ord >= 0) { Object[] vals = cls.getEnumConstants(); if (ord < vals.length) return (T)vals[ord]; else throw new BinaryObjectException("Failed to get enum value for ordinal (do you have correct class " + "version?) [cls=" + cls.getName() + ", ordinal=" + ord + ", totalValues=" + vals.length + ']'); } else return null; }
Source:
<code>@Test public void unableToConnectWrongPort() { configureSSHSlaveLauncher(sshd.ipBound(22), 1234).pwdCredentials("test", "test"); slave.save(); <START> elasticSleep(3000); <END> verifyLog("Connection refused"); }</code><technical_language>need sleep - waitUntil log contains... a timeout,</technical_language>

Target:
@Test public void unableToConnectWrongPort() { configureSSHSlaveLauncher(sshd.ipBound(22), 1234).pwdCredentials("test", "test"); slave.save(); waitForLogMessage("Connection refused"); }
Source:
<code>protected boolean canDoAction() { boolean retValue = false; String event; if (getVds() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); return false; } if (getParameters().getAction() == FenceActionType.Start) { event = AuditLogType.USER_VDS_STOP.name(); } else { event = AuditLogType.USER_VDS_START.name(); } if (getVds().getpm_enabled() && isPowerManagementLegal()) { Date waitTo = Backend.getInstance() .getStartedAt() .addSeconds((Integer) Config.getValue(ConfigValues.DisableFenceAtStartupInSec)); Date now = new Date(); if (waitTo.before(now) || waitTo.equals(now)) { int secondsLeftToNextPmOp = (isInternalExecution() || (getParameters().getParentCommand() == VdcActionType.RestartVds)) ? 0 : DbFacade.getInstance() .getAuditLogDao() .getTimeToWaitForNextPmOp(getVds().getName(), event); if (secondsLeftToNextPmOp <= 0) { if (createFenceExecutor().isProxyHostAvailable()) { retValue = true; } else { addCanDoActionMessage(VdcBllMessages.VDS_NO_VDS_PROXY_FOUND); } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_QUIET_TIME); <START> addCanDoActionMessage(String.format("$seconds %1$s", secondsLeftToNextPmOp)); <END> } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_SYSTEM_STARTUP_INTERVAL); } } if (!retValue) { handleError(); } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED); handleError(); } getReturnValue().setSucceeded(retValue); return retValue; }</code><technical_language>added this format , I this is original OK please do git grep addCanDoActionMessageVariable correct usage</technical_language>

Target:
protected boolean canDoAction() { boolean retValue = false; String event; if (getVds() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); return false; } if (getParameters().getAction() == FenceActionType.Start) { event = AuditLogType.USER_VDS_STOP.name(); } else { event = AuditLogType.USER_VDS_START.name(); } if (getVds().getpm_enabled() && isPowerManagementLegal()) { Date waitTo = Backend.getInstance() .getStartedAt() .addSeconds((Integer) Config.getValue(ConfigValues.DisableFenceAtStartupInSec)); Date now = new Date(); if (waitTo.before(now) || waitTo.equals(now)) { int secondsLeftToNextPmOp = (isInternalExecution() || (getParameters().getParentCommand() == VdcActionType.RestartVds)) ? 0 : DbFacade.getInstance() .getAuditLogDao() .getTimeToWaitForNextPmOp(getVds().getName(), event); if (secondsLeftToNextPmOp <= 0) { if (createProxyHostLocator().isProxyHostAvailable()) { retValue = true; } else { addCanDoActionMessage(VdcBllMessages.VDS_NO_VDS_PROXY_FOUND); } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_QUIET_TIME); addCanDoActionMessage(String.format("$seconds %1$s", secondsLeftToNextPmOp)); } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_SYSTEM_STARTUP_INTERVAL); } } if (!retValue) { handleError(); } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED); handleError(); } getReturnValue().setSucceeded(retValue); return retValue; }
Source:
<code>private static void saveIssue(SensorContext context, Flake8ReportReader.Issue issue, Set<String> unresolvedInputFiles) { InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(issue.filePath)); if (inputFile == null) { unresolvedInputFiles.add(issue.filePath); return; } NewExternalIssue newExternalIssue = context.newExternalIssue(); newExternalIssue .type(RuleType.CODE_SMELL) <START> .severity(Severity.MAJOR) <END> .remediationEffortMinutes(DEFAULT_CONSTANT_DEBT_MINUTES); NewIssueLocation primaryLocation = newExternalIssue.newLocation() .message(issue.message) .on(inputFile); primaryLocation.at(inputFile.selectLine(issue.lineNumber)); newExternalIssue.at(primaryLocation); newExternalIssue.engineId(LINTER_KEY).ruleId(issue.ruleKey); newExternalIssue.save(); }</code><technical_language>a distinction for severity error warning</technical_language>

Target:
private static void saveIssue(SensorContext context, Flake8ReportReader.Issue issue, Set<String> unresolvedInputFiles) { InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(issue.filePath)); if (inputFile == null) { unresolvedInputFiles.add(issue.filePath); return; } NewExternalIssue newExternalIssue = context.newExternalIssue(); newExternalIssue .type(RuleType.CODE_SMELL) .severity(Severity.MAJOR) .remediationEffortMinutes(DEFAULT_CONSTANT_DEBT_MINUTES); NewIssueLocation primaryLocation = newExternalIssue.newLocation() .message(issue.message) .on(inputFile); if (issue.columnNumber != null && issue.columnNumber < inputFile.selectLine(issue.lineNumber).end().lineOffset() + 1) { inputFile.selectLine(issue.lineNumber).end().lineOffset(); primaryLocation.at(inputFile.newRange(issue.lineNumber, issue.columnNumber - 1, issue.lineNumber, issue.columnNumber)); } else { primaryLocation.at(inputFile.selectLine(issue.lineNumber)); } newExternalIssue.at(primaryLocation); newExternalIssue.engineId(LINTER_KEY).ruleId(issue.ruleKey); newExternalIssue.save(); }
Source:
<code>public void testWithParallelism() throws Exception { tEnv().executeSql("create table print_t (" + "f0 int," + "f1 double" + ") with (" + "'connector' = 'print'," + "'print-identifier' = 'test_print'," + "'sink.parallelism' = '2'," + "'standard-error'='false')"); DataType type = tEnv().from("print_t").getSchema().toRowDataType(); Row row = Row.of(1, 1.1); <START> tEnv().fromValues(type, Arrays.asList(row)).executeInsert("print_t").await(); <END> String expectedLine1 = "test_print:1> +I(" + "1," + "1.1" + ")"; String expectedLine2 = "test_print:2> +I(" + "1," + "1.1" + ")"; Assert.assertTrue(arrayOutputStream.toString().equals(expectedLine1 + "\n") || arrayOutputStream.toString().equals(expectedLine2 + "\n")); }</code><technical_language>Arrays.asList -> Collections.singletonList</technical_language>

Target:
public void testWithParallelism() throws Exception { tEnv().executeSql("create table print_t (" + "f0 int," + "f1 double" + ") with (" + "'connector' = 'print'," + "'print-identifier' = 'test_print'," + "'sink.parallelism' = '2'," + "'standard-error'='false')"); DataType type = tEnv().from("print_t").getSchema().toRowDataType(); Row row = Row.of(1, 1.1); tEnv().fromValues(type, Collections.singleton(row)).executeInsert("print_t").await(); String expectedLine1 = "test_print:1> +I(" + "1," + "1.1" + ")"; String expectedLine2 = "test_print:2> +I(" + "1," + "1.1" + ")"; Assert.assertTrue(arrayOutputStream.toString().equals(expectedLine1 + "\n") || arrayOutputStream.toString().equals(expectedLine2 + "\n")); }
Source:
<code>public List<ConnectionSlot> acquireConnectionSlots(final String client, final String eventType, final List<String> partitions) throws NoConnectionSlotsException, ServiceUnavailableException { final List<Optional<ConnectionSlot>> slots = new ArrayList<>(); try { for (final String partition : partitions) { Optional<ConnectionSlot> connectionSlot = Optional.empty(); try { <START> connectionSlot = executeWithRetry( <END> () -> acquireConnectionSlot(client, eventType, partition), new RetryForSpecifiedCountStrategy<Optional<ConnectionSlot>>(5) .withExceptionsThatForceRetry(ConnectionSlotOccupiedException.class) .withWaitBetweenEachTry(0L, 100L)); } catch (ConnectionSlotOccupiedException e) { LOG.info(format("Failed to capture consuming connection slot after 5 tries for client '{0}', " + "event-type '{1}', partition {2}", client, eventType, partition)); } slots.add(connectionSlot); } if (slots.stream().allMatch(Optional::isPresent)) { return slots.stream() .map(Optional::get) .collect(Collectors.toList()); } else { final String failedPartitions = partitions.stream() .filter(p -> !slots.stream().anyMatch(s -> s.isPresent() && s.get().getPartition().equals(p))) .collect(Collectors.joining(", ")); final String msg = format(ERROR_MSG, eventType, failedPartitions, maxConnections); throw new NoConnectionSlotsException(msg); } } catch (final Exception e) { slots.stream() .filter(Optional::isPresent) .map(Optional::get) .forEach(this::releaseConnectionSlot); if (e instanceof NoConnectionSlotsException) { throw e; } else { throw new ServiceUnavailableException("Error communicating with zookeeper", e); } } }</code><technical_language>for is clear retry</technical_language>

Target:
public List<ConnectionSlot> acquireConnectionSlots(final String client, final String eventType, final List<String> partitions) throws NoConnectionSlotsException, ServiceUnavailableException { final List<String> partitionsWithNoFreeSlots = getPartitionsWithNoFreeSlots(client, eventType, partitions); if (partitionsWithNoFreeSlots.size() == 0) { final List<ConnectionSlot> slots = new ArrayList<>(); final String lockZkPath = format("{0}/{1}|{2}", LOCKS_ZK_PATH, client, eventType); try { return runLocked(() -> { final List<String> occupiedPartitions = getPartitionsWithNoFreeSlots(client, eventType, partitions); if (occupiedPartitions.size() > 0) { throw generateNoConnectionSlotsException(eventType, partitionsWithNoFreeSlots); } for (final String partition : partitions) { final ConnectionSlot connectionSlot = acquireConnectionSlot(client, eventType, partition); slots.add(connectionSlot); } return slots; }, zkLockFactory.createLock(lockZkPath)); } catch (final NoConnectionSlotsException e) { throw e; } catch (final Exception e) { slots.forEach(this::releaseConnectionSlot); throw new ServiceUnavailableException("Error communicating with zookeeper", e); } } else { throw generateNoConnectionSlotsException(eventType, partitionsWithNoFreeSlots); } }
Source:
<code>public void testRetainAll() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); <START> <END> IntSet intSet2 = new SmallIntSet(); intSet2.add(4); intSet2.add(5); intSet2.add(7); intSet.retainAll(intSet2); assertEquals(2, intSet.size()); assertTrue(intSet.contains(4)); assertTrue(intSet.contains(7)); }</code><technical_language>Sure, CollectionFactory.makeSet() sounds good. long respond, initially I thought CollectionFactory.makeSet() delegate internal implementations, I idea of depending JDK types in tests</technical_language>

Target:
public void testRetainAll() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); IntSet intSet2 = new SmallIntSet(); intSet2.add(4); intSet2.add(5); intSet2.add(7); intSet.retainAll(intSet2); assertEquals(CollectionFactory.makeSet(4, 7), intSet); }
Source:
<code>private Builder() { try { this.configDirectory = Files.createTempDirectory("ccm"); } catch (IOException e) { throw new RuntimeException(e); } withCassandraConfiguration("auto_snapshot", "false"); if (this.configDirectory != null) { <START> this.configDirectory.toFile().deleteOnExit(); <END> } }</code><technical_language>this directory empty? If not, I suggest instead: Runtime.getRuntime() .addShutdownHook( new Thread( () -> { try (Stream<Path> walk = Files.walk(configDirectory)) { walk.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } catch (IOException e) { logger.error("Could walk " + configDirectory, e); } }));</technical_language>

Target:
private Builder() { try { this.configDirectory = Files.createTempDirectory("ccm"); this.configDirectory.toFile().deleteOnExit(); } catch (IOException e) { throw new RuntimeException(e); } withCassandraConfiguration("auto_snapshot", "false"); }
Source:
<code>public void process(final K key, final Change<V1> change) { if (key == null) { LOG.warn( "Skipping record due to null key. change=[{}] topic=[{}] partition=[{}] offset=[{}]", change, context().topic(), context().partition(), context().offset() ); metrics.skippedRecordsSensor().record(); return; } final R newValue; final long resultTimestamp; R oldValue = null; final ValueAndTimestamp<V2> valueAndTimestampLeft = valueGetter.get(key); final V2 valueLeft = getValueOrNull(valueAndTimestampLeft); if (valueLeft == null) { return; } if (change.newValue != null) { resultTimestamp = Math.max(context().timestamp(), valueAndTimestampLeft.timestamp()); } else { <START> resultTimestamp = valueAndTimestampLeft.timestamp(); <END> } newValue = joiner.apply(change.newValue, valueLeft); if (sendOldValues) { oldValue = joiner.apply(change.oldValue, valueLeft); } context().forward(key, new Change<>(newValue, oldValue), To.all().withTimestamp(resultTimestamp)); }</code><technical_language>Similar question here. if left is null, null record's timestamp contribute join result time</technical_language>

Target:
public void process(final K key, final Change<V1> change) { if (key == null) { LOG.warn( "Skipping record due to null key. change=[{}] topic=[{}] partition=[{}] offset=[{}]", change, context().topic(), context().partition(), context().offset() ); metrics.skippedRecordsSensor().record(); return; } final R newValue; final long resultTimestamp; R oldValue = null; final ValueAndTimestamp<V2> valueAndTimestampLeft = valueGetter.get(key); final V2 valueLeft = getValueOrNull(valueAndTimestampLeft); if (valueLeft == null) { return; } resultTimestamp = Math.max(context().timestamp(), valueAndTimestampLeft.timestamp()); newValue = joiner.apply(change.newValue, valueLeft); if (sendOldValues) { oldValue = joiner.apply(change.oldValue, valueLeft); } context().forward(key, new Change<>(newValue, oldValue), To.all().withTimestamp(resultTimestamp)); }
Source:
<code><START> private void loadNodeMap() { <END> this.nodeMap = new HashMap<>(); for (Node n : this.getAllNodes()) { this.nodeMap.put(n.getNodeName(), n); } LOGGER.info("We currently have nodes assigned to this Jenkins instance, which we will check", this.nodeMap.size()); }</code><technical_language>prefer this method return a Map caller's responsibility store somewhere</technical_language>

Target:
private Map<String, Node> loadNodeMap() { Map<String, Node> nodeMap = new HashMap<>(); for (Node n : getAllNodes()) { nodeMap.put(n.getNodeName(), n); } LOGGER.info("We currently have nodes assigned to this Jenkins instance, which we will check", nodeMap.size()); return nodeMap; }
Source:
<code>public List<TaskDetails> getJobTasksById(@PathParam("cluster") String cluster, @PathParam("jobId") String jobId) throws IOException { LOG.info("Fetching tasks info for jobId=" + jobId); serializationContext.set(new SerializationContext( <START> SerializationContext.DetailLevel.EVERYTHING)); <END> JobDetails jobDetails = getJobHistoryService().getJobByJobID(cluster, jobId, true); return jobDetails.getTasks(); }</code><technical_language>minor: I this setting unnecessary (yet) a custom serializer for TaskDetails</technical_language>

Target:
public List<TaskDetails> getJobTasksById(@PathParam("cluster") String cluster, @PathParam("jobId") String jobId) throws IOException { LOG.info("Fetching tasks info for jobId=" + jobId); Stopwatch timer = new Stopwatch().start(); serializationContext.set(new SerializationContext( SerializationContext.DetailLevel.EVERYTHING)); JobDetails jobDetails = getJobHistoryService().getJobByJobID(cluster, jobId, true); timer.stop(); List<TaskDetails> tasks = jobDetails.getTasks(); if(tasks != null && !tasks.isEmpty()) { LOG.info("For endpoint /tasks/" + cluster + "/" + jobId + ", fetched " + tasks.size() + " tasks, spent time " + timer); } else { LOG.info("For endpoint /tasks/" + cluster + "/" + jobId + ", found no tasks, spent time " + timer); } return tasks; }
Source:
<code>private double[] createDoubleArrayFromINDArray(@Nonnull final INDArray x) { <START> final double[] xDoubleArray = new double[fftSize]; <END> for (int i = 0; i < dimension; i++) { xDoubleArray[i] = x.getDouble(i); } return xDoubleArray; }</code><technical_language>return new IndexRange(0, fftSize).mapToDouble(x::getDouble);</technical_language>

Target:
private double[] createDoubleArrayFromINDArray(@Nonnull final INDArray x) { return zeroPad(new IndexRange(0, getDimension()).mapToDouble(x::getDouble)); }
Source:
<code>public synchronized ServerTemplate update(ServerTemplate serverTemplate) { <START> delete(serverTemplate.getId()); <END> store(serverTemplate); return serverTemplate; }</code><technical_language>I while is update a serverTemplate, other thread a store sample template. is ok</technical_language>

Target:
public ServerTemplate update(ServerTemplate serverTemplate) { synchronized (store) { delete(serverTemplate.getId()); store(serverTemplate); } return serverTemplate; }
Source:
<code>SendThread(ClientCnxnSocket clientCnxnSocket) { super(makeThreadName("-SendThread()")); try { changeZkState(States.CONNECTING); } catch (IOException e) { <START> throw new RuntimeException("Connection setup failed when migrate state to CONNECTING"); <END> } this.clientCnxnSocket = clientCnxnSocket; setDaemon(true); }</code><technical_language>Throwing a RuntimeException lead unexpected behaviour. a throw a checked exception deal explicitly this case</technical_language>

Target:
SendThread(ClientCnxnSocket clientCnxnSocket) throws IOException { super(makeThreadName("-SendThread()")); changeZkState(States.CONNECTING); this.clientCnxnSocket = clientCnxnSocket; setDaemon(true); }
Source:
<code>public void testJWTAuthShouldFailWithoutToken() { String defaultExpectedErrorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, Locale.ENGLISH); String expectedErrorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, defaultExpectedErrorMessage); <START> String utf8ExpectedErrorMessage = new String(expectedErrorMessage.getBytes(ISO_8859_1), UTF_8); <END> String url = getContextBaseUrl() + "/users"; given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(url) .then() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body("error", equalTo(utf8ExpectedErrorMessage)); }</code><technical_language>suggestion String utf8ExpectedErrorMessage = new String(expectedErrorMessage.getBytes(ISO_8859_1), Charset.defaultCharset());</technical_language>

Target:
public void testJWTAuthShouldFailWithoutToken() { String defaultErrorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, Locale.ENGLISH); String errorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, defaultErrorMessage); String decodedErrorMessage = new String(errorMessage.getBytes(ISO_8859_1), Charset.defaultCharset()); String url = getContextBaseUrl() + "/users"; given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(url) .then() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body("error", equalTo(decodedErrorMessage)); }
Source:
<code>protected void fireEvent(CoreSession session, String eventId, Collection<DocumentRef> refs) { EventService eventService = Framework.getService(EventService.class); <START> DocumentModelList docs = session.getDocuments(refs.toArray(new DocumentRef[refs.size()])); <END> docs.forEach(d -> { DocumentEventContext ctx = new DocumentEventContext(session, session.getPrincipal(), d); ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY); ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, session.getRepositoryName()); ctx.setProperty(CoreEventConstants.SESSION_ID, session.getSessionId()); Event event = ctx.newEvent(eventId); event.setInline(false); event.setImmediate(false); eventService.fireEvent(event); }); }</code><technical_language>give 0 array size (more performant)</technical_language>

Target:
protected void fireEvent(CoreSession session, String eventId, Collection<DocumentRef> refs) { EventService eventService = Framework.getService(EventService.class); DocumentModelList docs = session.getDocuments(refs.toArray(new DocumentRef[0])); docs.forEach(d -> { DocumentEventContext ctx = new DocumentEventContext(session, session.getPrincipal(), d); ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY); ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, session.getRepositoryName()); ctx.setProperty(CoreEventConstants.SESSION_ID, session.getSessionId()); Event event = ctx.newEvent(eventId); event.setInline(false); event.setImmediate(false); eventService.fireEvent(event); }); }
Source:
<code>public boolean areEqual(MapObject o1, MapObject o2) { if (o1 == null ^ o2 == null) { return false; <START> } else if (o1 == o2) { <END> return true; } else { return o1.id.equals(o2.id); } }</code><technical_language>This block is useless</technical_language>

Target:
public boolean areEqual(MapObject o1, MapObject o2) { if (o1 == null) { return o2 == null; } else { return o1.id.equals(o2.id); } }
Source:
<code>public void handleResponse(AbstractResponse response) { TxnOffsetCommitResponse txnOffsetCommitResponse = (TxnOffsetCommitResponse) response; boolean coordinatorReloaded = false; Map<TopicPartition, Errors> errors = txnOffsetCommitResponse.errors(); log.debug("Received TxnOffsetCommit response for consumer group {}: {}", builder.data.groupId(), errors); for (Map.Entry<TopicPartition, Errors> entry : errors.entrySet()) { TopicPartition topicPartition = entry.getKey(); Errors error = entry.getValue(); if (error == Errors.NONE) { pendingTxnOffsetCommits.remove(topicPartition); } else if (error == Errors.COORDINATOR_NOT_AVAILABLE || error == Errors.NOT_COORDINATOR || error == Errors.REQUEST_TIMED_OUT) { if (!coordinatorReloaded) { coordinatorReloaded = true; lookupCoordinator(FindCoordinatorRequest.CoordinatorType.GROUP, builder.data.groupId()); } } else if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION || error == Errors.COORDINATOR_LOAD_IN_PROGRESS <START> || error == Errors.UNKNOWN_MEMBER_ID) { <END> continue; } else if (error == Errors.GROUP_AUTHORIZATION_FAILED) { abortableError(GroupAuthorizationException.forGroupId(builder.data.groupId())); break; } else if (isFatalException(error)) { fatalError(error.exception()); break; } else { fatalError(new KafkaException("Unexpected error in TxnOffsetCommitResponse: " + error.message())); break; } } if (result.isCompleted()) { pendingTxnOffsetCommits.clear(); } else if (pendingTxnOffsetCommits.isEmpty()) { result.done(); } else { reenqueue(); } }</code><technical_language>qq: Hmm, retry UNKNOWN_MEMBER_ID</technical_language>

Target:
public void handleResponse(AbstractResponse response) { TxnOffsetCommitResponse txnOffsetCommitResponse = (TxnOffsetCommitResponse) response; boolean coordinatorReloaded = false; Map<TopicPartition, Errors> errors = txnOffsetCommitResponse.errors(); log.debug("Received TxnOffsetCommit response for consumer group {}: {}", builder.data.groupId(), errors); for (Map.Entry<TopicPartition, Errors> entry : errors.entrySet()) { TopicPartition topicPartition = entry.getKey(); Errors error = entry.getValue(); if (error == Errors.NONE) { pendingTxnOffsetCommits.remove(topicPartition); } else if (error == Errors.COORDINATOR_NOT_AVAILABLE || error == Errors.NOT_COORDINATOR || error == Errors.REQUEST_TIMED_OUT) { if (!coordinatorReloaded) { coordinatorReloaded = true; lookupCoordinator(FindCoordinatorRequest.CoordinatorType.GROUP, builder.data.groupId()); } } else if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION || error == Errors.COORDINATOR_LOAD_IN_PROGRESS) { continue; } else if (error == Errors.GROUP_AUTHORIZATION_FAILED) { abortableError(GroupAuthorizationException.forGroupId(builder.data.groupId())); break; } else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED || error == Errors.INVALID_PRODUCER_EPOCH || error == Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT) { fatalError(error.exception()); break; } else { fatalError(new KafkaException("Unexpected error in TxnOffsetCommitResponse: " + error.message())); break; } } if (result.isCompleted()) { pendingTxnOffsetCommits.clear(); } else if (pendingTxnOffsetCommits.isEmpty()) { result.done(); } else { reenqueue(); } }
Source:
<code>protected Module wrapPluginSink( final Key<? extends PluginSink> input, final Key<PluginSink> output ) { return new PrivateModule() { @Override protected void configure() { Key<PluginSink> sinkKey = (Key<PluginSink>) input; if (flushInterval.isPresent() || BatchedPluginSink.class.isAssignableFrom( sinkKey.getTypeLiteral().getRawType())) { <START> final Key<PluginSink> nextKey = Key.get(PluginSink.class, Names.named("flushing")); <END> install(new OutputDelegatingModule<>(sinkKey, nextKey, new FlushingPluginSink(flushInterval.get()))); sinkKey = nextKey; } if (filter.isPresent()) { final Key<PluginSink> next = Key.get(PluginSink.class, Names.named("filtered")); install(new OutputDelegatingModule<>(sinkKey, next, new FilteringPluginSink(filter.get()))); sinkKey = next; } bind(output).to(sinkKey); expose(output); } }; }</code><technical_language>rename this variable nextKey? flushingPluginKey</technical_language>

Target:
protected Module wrapPluginSink( final Key<? extends PluginSink> input, final Key<PluginSink> output ) { return new PrivateModule() { @Override protected void configure() { Key<PluginSink> sinkKey = (Key<PluginSink>) input; if (flushInterval != null && flushInterval.isPresent() && BatchedPluginSink.class.isAssignableFrom( sinkKey.getTypeLiteral().getRawType())) { final Key<PluginSink> flushingKey = Key.get(PluginSink.class, Names.named("flushing")); install(new OutputDelegatingModule<>(sinkKey, flushingKey, new FlushingPluginSink(flushInterval.get()))); sinkKey = flushingKey; } if (filter != null && filter.isPresent()) { final Key<PluginSink> filteringKey = Key.get(PluginSink.class, Names.named("filtered")); install(new OutputDelegatingModule<>(sinkKey, filteringKey, new FilteringPluginSink(filter.get()))); sinkKey = filteringKey; } bind(output).to(sinkKey); expose(output); } }; }
Source:
<code>private List<Variant> regionWsHelper(String testRegion, HttpStatus status) { <START> String url = "/v2/regions/" + testRegion + "?species=mmusculus&assembly=grcm38"; <END> ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertEquals(status, response.getStatusCode()); Configuration configuration = Configuration.defaultConfiguration() .jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider(objectMapper)) .addOptions(Option.SUPPRESS_EXCEPTIONS); List<Variant> variantList = JsonPath.using(configuration).parse(response.getBody()) .read("$['_embedded']['variantList']", new TypeRef<List<Variant>>() { }); return variantList; }</code><technical_language>suggestion String url = "/v2/regions/" + testRegion + "/variants?species=mmusculus&assembly=grcm38";</technical_language>

Target:
private List<Variant> regionWsHelper(String testRegion, HttpStatus status) { String url = "/v2/regions/" + testRegion + "/variants?species=mmusculus&assembly=grcm38"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertEquals(status, response.getStatusCode()); Configuration configuration = Configuration.defaultConfiguration() .jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider(objectMapper)) .addOptions(Option.SUPPRESS_EXCEPTIONS); List<Variant> variantList = JsonPath.using(configuration).parse(response.getBody()) .read("$['_embedded']['variantList']", new TypeRef<List<Variant>>() { }); return variantList; }
Source:
<code>protected void releaseMonitorLock(EngineLock monitoringLock, String commandName) { <START> final VDS vds = getVds(); <END> getLockManager().releaseLock(monitoringLock); log.infoFormat(commandName + " finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); }</code><technical_language>This line lock is released, then</technical_language>

Target:
protected void releaseMonitorLock(EngineLock monitoringLock, String commandName) { getLockManager().releaseLock(monitoringLock); final VDS vds = getVds(); log.infoFormat(commandName + " finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); }
Source:
<code>public void run() { long startTime; long lastTime; try { while (isOpen.get()) { startTime = time.milliseconds(); lastTime = startTime; List<RequestInfo> requestInfoList = pollForRequests(); <START> routerMetrics.operationControllerPollforRequestTimeMs.update(time.milliseconds() - lastTime); <END> lastTime = time.milliseconds(); List<ResponseInfo> responseInfoList = networkClient.sendAndPoll(requestInfoList); routerMetrics.numOfRequestInfosPerPoll.update(requestInfoList.size()); routerMetrics.operationControllerSendAndPollTimeMs.update(time.milliseconds() - lastTime); lastTime = time.milliseconds(); onResponse(responseInfoList); routerMetrics.operationControllerProcessResponseTimeMs.update(time.milliseconds() - lastTime); routerMetrics.operationControllerOnePollCycleTimeMs.update(time.milliseconds() - startTime); } } catch (Throwable e) { logger.error("Aborting, as requestResponseHandlerThread received an unexpected error: ", e); } finally { networkClient.close(); shutDownLatch.countDown(); shutDownOperationControllers(); } }</code><technical_language>This metric is unnecessary, calculating metrics for individual polls this method</technical_language>

Target:
public void run() { try { while (isOpen.get()) { List<RequestInfo> requestInfoList = pollForRequests(); List<ResponseInfo> responseInfoList = networkClient.sendAndPoll(requestInfoList); onResponse(responseInfoList); } } catch (Throwable e) { logger.error("Aborting, as requestResponseHandlerThread received an unexpected error: ", e); } finally { networkClient.close(); shutDownLatch.countDown(); shutDownOperationControllers(); } }
Source:
<code>public boolean isUserOnChat() { try { <START> wait.forElementVisible(chatInlineAlert); <END> return chatInlineAlert.isDisplayed(); } catch (Exception e) { return false; } }</code><technical_language>wait.forElementVisible checks if element is displayed? if yes, return true instead of running chatInlineAlert.isDisplayed()</technical_language>

Target:
public boolean isUserOnChat() { try { wait.forElementVisible(chatInlineAlert); return true; } catch (Exception e) { return false; } }
Source:
<code>public String getNiogitRepoPath(org.uberfire.java.nio.file.Path path) { try { <START> final File directory = path.toFile(); <END> return directory.toURI().toString(); } catch (ClassCastException cce) { throw new IllegalArgumentException("Cannot get .niogit directory for non-jgit path.", cce); } }</code><technical_language>@adrielparedes elaborate a bit more this 'path.toFile()' compatible previous 'JGitPathImpl.getFileSystem.getGit.getRepository.getDirectory'? Thanks</technical_language>

Target:
public String getNiogitRepoPath(org.uberfire.java.nio.file.Path path) { try { Path p = path.getFileSystem().getPath(path.toString()); final File directory = p.toFile(); return directory.toURI().toString(); } catch (ClassCastException cce) { throw new IllegalArgumentException("Cannot get .niogit directory for non-jgit path.", cce); } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Appointment)) return false; Appointment that = (Appointment) o; <START> <END> if (durationTime != that.durationTime) return false; if (startTime != that.startTime) return false; if (!applicantId.equals(that.applicantId)) return false; if (!userIdList.equals(that.userIdList)) return false; return true; }</code><technical_language>Equals & HashCode convention. equal objects this methods</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Appointment)) return false; Appointment that = (Appointment) o; if (actualStartTime != that.actualStartTime) return false; if (durationTime != that.durationTime) return false; if (startTime != that.startTime) return false; if (applicantId != null ? !applicantId.equals(that.applicantId) : that.applicantId != null) return false; if (appointmentId != null ? !appointmentId.equals(that.appointmentId) : that.appointmentId != null) return false; if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; if (userIdList != null ? !userIdList.equals(that.userIdList) : that.userIdList != null) return false; return true; }
Source:
<code>public void testCacheLoaderWriterOverriding() { MutableConfiguration<Long, Product> conf = new MutableConfiguration<Long, Product>(); conf.setTypes(Long.class, Product.class); javax.cache.Cache<Long, Product> c1 = cm.createCache("productCache", conf); ProductCacheLoaderWriter.written.clear(); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(true)); cm.destroyCache("productCache"); <START> conf.setReadThrough(true); <END> c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); cm.destroyCache("productCache"); ProductCacheLoaderWriter.written.clear(); conf.setReadThrough(false); conf.setWriteThrough(true); c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); ProductCacheLoaderWriter.written.clear(); cm.destroyCache("productCache"); }</code><technical_language>I extract base config creation in a method call time. Here, if decided piggy MutableConfiguration modify code, test break</technical_language>

Target:
public void testCacheLoaderWriterOverriding() { javax.cache.Cache<Long, Product> c1 = cm.createCache("productCache", createProductCacheConf()); ProductCacheLoaderWriter.written.clear(); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(true)); cm.destroyCache("productCache"); MutableConfiguration conf = createProductCacheConf(); conf.setReadThrough(true); c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); cm.destroyCache("productCache"); conf = createProductCacheConf(); ProductCacheLoaderWriter.written.clear(); conf.setReadThrough(false); conf.setWriteThrough(true); c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); ProductCacheLoaderWriter.written.clear(); cm.destroyCache("productCache"); try { conf = createProductCacheConf(); conf.setReadThrough(true); cm.createCache("p1", conf); fail("Cache creation should have failed for illegal cache loader/writer configuration"); } catch (MultiCacheException e) { assertThat(e.getThrowables().get(0).getMessage(), is(equalTo("Unable to construct (read/write)through cache without either a templated loader/writer or configured loader/writer"))); } }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == RC_SIGN_IN) { mSignInClicked = false; mResolvingConnectionFailure = false; if (resultCode == RESULT_OK) { mGoogleApiClient.connect(); } else { BaseGameUtils.showActivityResultError(this, requestCode, resultCode, R.string.signin_failure, R.string.signin_other_error); } <START> } <END> }</code><technical_language>need call super.onActivityResult()</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == RC_SIGN_IN) { mSignInClicked = false; mResolvingConnectionFailure = false; if (resultCode == RESULT_OK) { mGoogleApiClient.connect(); } else { BaseGameUtils.showActivityResultError(this, requestCode, resultCode, R.string.signin_failure, R.string.signin_other_error); } } }
Source:
<code>Optional<DecisionNavigatorItem> findItem(final Node<View, Edge> node) { return getItems() .stream() <START> .filter(item -> item.getUUID().equals(node.getUUID())) <END> .findFirst(); }</code><technical_language>Objects.equals is more safe, moved class</technical_language>

Target:
Optional<DecisionNavigatorItem> findItem(final Node<View, Edge> node) { return getItems() .stream() .filter(item -> Objects.equals(item.getUUID(), node.getUUID())) .findFirst(); }
Source:
<code>public void validTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; File file = new File(binaryBase + "/61/67/3d/" + checksum); file.getParentFile().mkdirs(); file.createNewFile(); Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message).setHeader(CdrBinaryPath, file.getAbsolutePath()); <START> verify(message).setHeader(CdrBinarySubPath, idToPath(RESC_ID, HASHED_PATH_DEPTH, HASHED_PATH_SIZE)); <END> }</code><technical_language>suggest providing a hard coded instead of computing of is supposed be</technical_language>

Target:
public void validTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; File file = new File(binaryBase + "/61/67/3d/" + checksum); file.getParentFile().mkdirs(); file.createNewFile(); Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message).setHeader(CdrBinaryPath, file.getAbsolutePath()); }
Source:
<code>public void closesExplicitlyAllParts() throws IOException { final String body = "RqMultipartTest.closesExplicitlyAllParts"; final RqMultipart request = new RqMultipart.Fake( new RqFake(), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader( (long) body.getBytes().length ), RqMultipartTest.contentDispositionHeader( "form-data; name=\"foo\"" ) ) ), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader(0L), RqMultipartTest.contentDispositionHeader( "form-data; name=\"bar\"; filename=\"a.bin\"" ) ) ) ); final RqMultipart.Base multi = new RqMultipart.Base(request); multi.body().close(); MatcherAssert.assertThat( multi.part("foo").iterator().next(), Matchers.notNullValue() ); multi.part("foo").iterator().next().body().close(); MatcherAssert.assertThat( multi.part("bar").iterator().next(), Matchers.notNullValue() ); <START> multi.part("bar").iterator().next().body().close(); <END> }</code><technical_language>@essobedo need assertion this line</technical_language>

Target:
public void closesExplicitlyAllParts() throws Exception { final String body = "RqMultipartTest.closesExplicitlyAllParts"; final RqMultipart request = new RqMultipart.Fake( new RqFake(), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader( (long) body.getBytes().length ), RqMultipartTest.contentDispositionHeader( "form-data; name=\"foo\"" ) ) ), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader(0L), RqMultipartTest.contentDispositionHeader( "form-data; name=\"bar\"; filename=\"a.bin\"" ) ) ) ); final RqMultipart.Base multi = new RqMultipart.Base(request); multi.body().close(); MatcherAssert.assertThat( multi.part("foo").iterator().next(), Matchers.notNullValue() ); multi.part("foo").iterator().next().body().close(); MatcherAssert.assertThat( multi.part("bar").iterator().next(), Matchers.notNullValue() ); multi.part("bar").iterator().next().body().close(); }
Source:
<code>public Object get(DataFetchingEnvironment env) { <START> Object source = env.getSource(); <END> if (source == null) return null; try { if (isBooleanProperty(env.getFieldType())) { try { return getProperty(source, "is"); } catch (NoSuchMethodException e) { return getProperty(source, "get"); } } else { return getProperty(source, "get"); } } catch (NoSuchMethodException e) { return null; } }</code><technical_language>env is null</technical_language>

Target:
public Object get(DataFetchingEnvironment env) { Object source = env.getSource(); if (source == null) return null; try { return getProperty(source); } catch (NoSuchMethodException e) { return null; } }
Source:
<code>public void testDeployChildOnParentUndeploy() throws Exception { class ParentVerticle extends AbstractVerticle { @Override public void stop(Promise<Void> stopPromise) { vertx.deployVerticle(ChildVerticle.class.getName()) .<Void>mapEmpty() .setHandler(stopPromise); } } CountDownLatch latch = new CountDownLatch(1); vertx.deployVerticle(new ParentVerticle(), ar1 -> { assertTrue(ar1.succeeded()); <START> vertx.undeploy(ar1.result(), ar2 -> { <END> assertFalse(ar2.succeeded()); latch.countDown(); }); }); awaitLatch(latch); }</code><technical_language>helper methods onSuccess / onFailure test shorter easier read</technical_language>

Target:
public void testDeployChildOnParentUndeploy() { class ParentVerticle extends AbstractVerticle { @Override public void stop(Promise<Void> stopPromise) { vertx.deployVerticle(ChildVerticle.class.getName()) .<Void>mapEmpty() .setHandler(stopPromise); } } vertx.deployVerticle(new ParentVerticle(), onSuccess(id -> vertx.undeploy(id, onFailure(u -> testComplete())))); await(); }