auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private IStatus validateTool(final EObject eObj, final IValidationContext ctx, final IStatus statusInput) { final ToolSwitchValidator toolSwitchValidator = new ToolSwitchValidator(ctx, statusInput); <START> final IStatus status = toolSwitchValidator.doSwitch(eObj); <END> return status; }</code><technical_language>this method new DiagramToolSwitchValidator too</technical_language>

Target:
private IStatus validateTool(final EObject eObj, final IValidationContext ctx, final IStatus statusInput) { final ToolSwitchValidator toolSwitchValidator = new ToolSwitchValidator(ctx, statusInput); final IStatus statusCoreTool = toolSwitchValidator.doSwitch(eObj); final DiagramToolSwitchValidator diagramToolSwitchValidator = new DiagramToolSwitchValidator(ctx, statusInput); final IStatus statusDiagramTool = diagramToolSwitchValidator.doSwitch(eObj); MultiStatus status = null; if (statusCoreTool != null || statusDiagramTool != null) { if (statusCoreTool != null) { status = new MultiStatus(statusCoreTool.getPlugin(), statusCoreTool.getCode(), null, null); status.add(statusCoreTool); } if (statusDiagramTool != null) { if (status == null) { status = new MultiStatus(statusDiagramTool.getPlugin(), statusDiagramTool.getCode(), null, null); } status.add(statusDiagramTool); } } return status; }
Source:
<code>private void restoreSavedLayout() { for (LogicalWindow window : panes_) window.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); maximizedWindow_.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); ArrayList<Double> leftStart = new ArrayList<>(); ArrayList<Double> leftEnd = new ArrayList<>(); if (leftList_.size() > 0) { for (int i = 0; i < leftList_.size(); i++) leftStart.add(0.0); if (leftWidgetSizePriorToZoom_.size() != leftList_.size()) leftEnd = getValidColumnWidths(leftList_, leftWidgetSizePriorToZoom_, false); else { for (Double size : leftWidgetSizePriorToZoom_) <START> leftEnd.add(size); <END> } } resizeHorizontally(panel_.getWidgetSize(right_), widgetSizePriorToZoom_, leftStart, leftEnd); invalidateSavedLayoutState(true); }</code><technical_language>Nit: addAll do this in line</technical_language>

Target:
private void restoreSavedLayout() { for (LogicalWindow window : panes_) window.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); maximizedWindow_.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); ArrayList<Double> leftStart = new ArrayList<>(); ArrayList<Double> leftEnd = new ArrayList<>(); if (leftList_.size() > 0) { for (int i = 0; i < leftList_.size(); i++) leftStart.add(0.0); if (leftWidgetSizePriorToZoom_.size() != leftList_.size()) leftEnd = getValidColumnWidths(leftList_, leftWidgetSizePriorToZoom_, false); else leftEnd.addAll(leftWidgetSizePriorToZoom_); } resizeHorizontally(panel_.getWidgetSize(right_), widgetSizePriorToZoom_, leftStart, leftEnd); invalidateSavedLayoutState(true); }
Source:
<code><START> public void close() throws IOException { <END> if (!closed.get()) { flush(); closed.set(true); } }</code><technical_language>This is vulnerable a race condition, a mutation sneak flush() closed.set(true)</technical_language>

Target:
public void close() throws IOException { WriteLock lock = mutationLock.writeLock(); lock.lock(); try { if (!closed) { doFlush(); closed = true; } } finally { lock.unlock(); } }
Source:
<code>CircuitBreakerFuture(CircuitBreaker circuitBreaker, Future<T> future) { <START> this(circuitBreaker, future, Clock.systemUTC()); <END> }</code><technical_language>is Clock.systemDefaultZone() instead</technical_language>

Target:
CircuitBreakerFuture(CircuitBreaker circuitBreaker, Future<T> future) { this(circuitBreaker, future, circuitBreaker.getCurrentTimestamp()); }
Source:
<code>public synchronized void start() { checkValidLoadBalancingSettings(); <START> random = ThreadLocalRandom.current(); <END> if (httpClient != null) { log.warn("Service already started"); return; } httpClient = new ResteasyClientBuilder().httpEngine(new URLConnectionEngine()) .establishConnectionTimeout(connectionTimeout, TimeUnit.MILLISECONDS) .socketTimeout(socketTimeout, TimeUnit.MILLISECONDS).connectionPoolSize(maxConnections) .maxPooledPerRoute(maxConnectionsPerHost).hostnameVerification(HostnameVerificationPolicy.ANY).build(); if (username != null) { BasicAuthentication auth = new BasicAuthentication(username, password); httpClient.register(auth); } }</code><technical_language>kidding, sharing thread local random threads</technical_language>

Target:
public synchronized void start() { if (httpClient != null) { log.warn("Service already started"); return; } httpClient = new ResteasyClientBuilder().httpEngine(new URLConnectionEngine()) .establishConnectionTimeout(connectionTimeout, TimeUnit.MILLISECONDS) .socketTimeout(socketTimeout, TimeUnit.MILLISECONDS).connectionPoolSize(maxConnections) .maxPooledPerRoute(maxConnectionsPerHost).hostnameVerification(HostnameVerificationPolicy.ANY).build(); if (username != null) { BasicAuthentication auth = new BasicAuthentication(username, password); httpClient.register(auth); } }
Source:
<code>public static int scoreAddr(NetworkInterface iface, InetAddress addr) { int score = 0; if (addr instanceof Inet4Address) { score += 300; } try { if (!iface.isLoopback() && !addr.isLoopbackAddress()) { score += 100; if (iface.isUp()) { score += 100; } } } catch (SocketException e) { <START> ; <END> } return score; }</code><technical_language>log re-raise</technical_language>

Target:
public static int scoreAddr(NetworkInterface iface, InetAddress addr) { int score = 0; if (addr instanceof Inet4Address) { score += 300; } try { if (!iface.isLoopback() && !addr.isLoopbackAddress()) { score += 100; if (iface.isUp()) { score += 100; } } } catch (SocketException e) { logger.error("Unable to score IP of interface {}", addr, iface, e); } return score; }
Source:
<code>private List<String> getExcludedAttrs() { List<String> attrs = new ArrayList<>(); <START> return attrs; <END> }</code><technical_language>This throw redundancy warnings in IntelliJ</technical_language>

Target:
private List<String> getExcludedAttrs() { return new ArrayList<>(); }
Source:
<code>public String read(int fileId) { try { InputStream in = context.getResources().openRawResource(fileId); return getFileContent(in); } catch (Exception e) { <START> e.printStackTrace(); <END> return ""; } }</code><technical_language>log throw</technical_language>

Target:
public String read(int fileId) { try { InputStream in = context.getResources().openRawResource(fileId); return getFileContent(in); } catch (Exception e) { return ""; } }
Source:
<code>public List<Deployment> listDeployments(String namespace) { DeploymentList list = kubernetesClient.extensions().deployments().inNamespace(namespace) .withLabel(WSO2_DEPLOYMENT_LABEL).list(); if (list == null || list.getItems() == null || list.getItems().isEmpty()) { <START> return new ArrayList<>(); <END> } return list.getItems().stream() .map(deployment -> { Map<String, String> labels = deployment.getSpec().getTemplate().getMetadata().getLabels(); return new Deployment( deployment.getMetadata().getUid(), labels.get(PRODUCT), labels.get(VERSION), Integer.parseInt(labels.get(PATTERN))); }) .collect(Collectors.toList()); }</code><technical_language>caller of this method expects add new elements returned List. If Collections.emptyList();</technical_language>

Target:
public List<Deployment> listDeployments(String namespace) { DeploymentList list = kubernetesClient.extensions().deployments().inNamespace(namespace) .withLabel(WSO2_DEPLOYMENT_LABEL).list(); if (list == null || list.getItems() == null || list.getItems().isEmpty()) { return Collections.emptyList(); } return list.getItems().stream() .map(deployment -> { Map<String, String> labels = deployment.getSpec().getTemplate().getMetadata().getLabels(); return new Deployment( deployment.getMetadata().getUid(), labels.get(PRODUCT), labels.get(VERSION), Integer.parseInt(labels.get(PATTERN))); }) .collect(Collectors.toList()); }
Source:
<code>private void reportTripleCount(AtomicLong tripleCount, boolean force, Consumer<String> statusUpdate) { final long curCount = tripleCount.incrementAndGet(); if (force || curCount % 100 == 0) { final String message = String.format("Processed %d triples", curCount); statusUpdate.accept(message); <START> LOG.info(message); <END> } }</code><technical_language>LOG.debug, this data information</technical_language>

Target:
private void reportTripleCount(AtomicLong tripleCount, boolean force, Consumer<String> statusUpdate) { final long curCount = tripleCount.incrementAndGet(); if (force || curCount % 100 == 0) { final String message = String.format("Processed %d triples", curCount); statusUpdate.accept(message); LOG.debug(message); } }
Source:
<code>public JobIdData reSubmit(String sessionId, String jobId, PathSegment pathSegment, UriInfo contextInfos) throws JobCreationRestException, NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, IOException { Scheduler scheduler = checkAccess(sessionId, "reSubmit"); File tmpJobFile = File.createTempFile("job", "d"); JobId newJobId; try { final String jobContent = scheduler.getJobContent(JobIdImpl.makeJobId(jobId)); FileUtils.write(tmpJobFile, jobContent, Charset.forName("UTF-8")); } catch (NotConnectedException e) { e.printStackTrace(); } catch (UnknownJobException e) { e.printStackTrace(); } catch (PermissionException e) { e.printStackTrace(); } catch (SubmissionClosedException e) { e.printStackTrace(); <START> } catch (JobCreationException e) { <END> e.printStackTrace(); } Map<String, String> jobVariables = workflowVariablesTransformer.getWorkflowVariablesFromPathSegment(pathSegment); Map<String, String> genericInfos = null; if (contextInfos != null) genericInfos = getMapWithFirstValues(contextInfos.getQueryParameters()); WorkflowSubmitter workflowSubmitter = new WorkflowSubmitter(scheduler); newJobId = workflowSubmitter.submit(tmpJobFile, jobVariables, genericInfos); return mapper.map(newJobId, JobIdData.class); }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Combine this catch line 2247, body. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public JobIdData reSubmit(String sessionId, String jobId, PathSegment pathSegment, UriInfo contextInfos) throws JobCreationRestException, NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, IOException, UnknownJobRestException { Scheduler scheduler = checkAccess(sessionId, "reSubmit"); File tmpJobFile = File.createTempFile("job", "d"); JobId newJobId; try { String jobContent = scheduler.getJobContent(JobIdImpl.makeJobId(jobId)); FileUtils.write(tmpJobFile, jobContent, Charset.forName("UTF-8")); } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (UnknownJobException e) { throw new UnknownJobRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } catch (SubmissionClosedException e) { throw new SubmissionClosedRestException(e); } catch (JobCreationException e) { throw new JobCreationRestException(e); } Map<String, String> jobVariables = workflowVariablesTransformer.getWorkflowVariablesFromPathSegment(pathSegment); Map<String, String> genericInfos = null; if (contextInfos != null) { genericInfos = getMapWithFirstValues(contextInfos.getQueryParameters()); } WorkflowSubmitter workflowSubmitter = new WorkflowSubmitter(scheduler); newJobId = workflowSubmitter.submit(tmpJobFile, jobVariables, genericInfos); return mapper.map(newJobId, JobIdData.class); }
Source:
<code>public void updateSelectedCertificateKS() { LOG.info("updateSelectedCertificate"); <START> if (selectedTSCertificate != null) { <END> String alias = selectedTSCertificate.getAlias(); if (StringUtils.isNotBlank(alias) && !service.isAliasInUse(alias, service.fetchKeyStores())) { try { boolean updateStatus = service.updateCertificateKS(oldAlias, selectedTSCertificate); postUpdateAction(updateStatus, VIEW_CERT_ERROR_MSG_KS); } catch (CertificateManagerException ex) { LOG.error("Unable to update certificate {}", ex.getLocalizedMessage(), ex); HelperUtil.addMessageError(VIEW_CERT_ERROR_MSG_KS, ex.getLocalizedMessage()); } } else { selectedTSCertificate.setAlias(oldAlias); HelperUtil.addMessageError(VIEW_CERT_ERROR_MSG_KS, "Alias already in use"); } } }</code><technical_language>move common logic in a private method call method updateSelectedCertificateKS updateSelectedCertificate</technical_language>

Target:
public void updateSelectedCertificateKS() { if (selectedTSCertificate != null) { updateCertificate(service.fetchKeyStores(), VIEW_CERT_ERROR_MSG_KS, RefreshAction.KEYSTORE); } }
Source:
<code>public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes fs = logic.getFeedbackSession(feedbackSessionName, courseId); if (fs == null) { throw new EntityNotFoundException(new EntityDoesNotExistException("Feedback session is not found")); } Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case INSTRUCTOR_RESULT: <START> if (userInfo == null) { throw new UnauthorizedAccessException("Instructor account is required to access this resource"); } else { InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible(instructor, fs); } <END> break; case STUDENT_RESULT: StudentAttributes student = getStudent(courseId); gateKeeper.verifyAccessible(student, fs); if (!fs.isPublished()) { throw new UnauthorizedAccessException("This feedback session is not yet published."); } break; case INSTRUCTOR_SUBMISSION: case STUDENT_SUBMISSION: throw new InvalidHttpParameterException("Invalid intent for this action"); default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }</code><technical_language>worthwhile factor this out a method getInstructor consistent getStudent below</technical_language>

Target:
public void checkSpecificAccessControl() { if (userInfo != null && userInfo.isAdmin) { return; } String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes fs = logic.getFeedbackSession(feedbackSessionName, courseId); if (fs == null) { throw new EntityNotFoundException(new EntityDoesNotExistException("Feedback session is not found")); } Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case INSTRUCTOR_RESULT: if (userInfo == null) { throw new UnauthorizedAccessException("Instructor account is required to access this resource"); } else { InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible(instructor, fs); } break; case STUDENT_RESULT: if (userInfo == null && StringHelper.isEmpty(getRequestParamValue(Const.ParamsNames.REGKEY))) { throw new UnauthorizedAccessException("Student account is required to access this resource."); } StudentAttributes student = getStudent(courseId); gateKeeper.verifyAccessible(student, fs); if (!fs.isPublished()) { throw new UnauthorizedAccessException("This feedback session is not yet published."); } break; case INSTRUCTOR_SUBMISSION: case STUDENT_SUBMISSION: throw new InvalidHttpParameterException("Invalid intent for this action"); default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }
Source:
<code>public void testTimeTravelWorks() throws Exception { <START> String tbl = GenerateTableName(); <END> watcher.executeUpdate("CREATE TABLE " + tbl + "(a INT)"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 1"); long txId = GetTxId(); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 2"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 3"); ResultSet rs = watcher.executeQuery("SELECT * FROM " + tbl + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(2, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(3, rs.getInt(1)); Assert.assertFalse(rs.next()); rs = watcher.executeQuery("SELECT * FROM " + tbl + " AS OF " + txId + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertFalse(rs.next()); }</code><technical_language>do need this? sth "testTimeTravelWorksT" more intuitive? SpliceWatcher drop tables automatically, run test multiple times</technical_language>

Target:
public void testTimeTravelWorks() throws Exception { String tbl = generateTableName(); watcher.executeUpdate("CREATE TABLE " + tbl + "(a INT)"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 1"); long txId = getTxId(); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 2"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 3"); ResultSet rs = watcher.executeQuery("SELECT * FROM " + tbl + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(2, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(3, rs.getInt(1)); Assert.assertFalse(rs.next()); rs = watcher.executeQuery("SELECT * FROM " + tbl + " AS OF " + txId + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertFalse(rs.next()); }
Source:
<code>private void setOATag(SAMRecord rec) { if (rec.getReferenceName().contains(",")) { throw new PicardException(String.format("Reference name for record %s contains a comma character.", rec.getReadName())); } final String OAValue; if (rec.getReadUnmappedFlag()) { OAValue = String.format("*,0,%s,*,255,;", rec.getReadNegativeStrandFlag() ? "-" : "+"); } else { OAValue = String.format("%s,%s,%s,%s,%s,%s;", <START> (rec.getReferenceName()), <END> (rec.getAlignmentStart()), ((rec.getReadNegativeStrandFlag() ? "-" : "+")), (rec.getCigarString()), (rec.getMappingQuality()), (Optional.ofNullable(rec.getAttribute(SAMTag.NM.name())).orElse("").toString())); } rec.setAttribute(OA,Optional.ofNullable(rec.getAttribute(OA)).orElse("") + OAValue); }</code><technical_language>unnecessary parens lines suggestion rec.getReferenceName(),</technical_language>

Target:
private void setOATag(SAMRecord rec) { if (rec.getReferenceName().contains(",")) { throw new PicardException(String.format("Reference name for record %s contains a comma character.", rec.getReadName())); } final String oaValue; if (rec.getReadUnmappedFlag()) { oaValue = String.format("*,0,%s,*,255,;", rec.getReadNegativeStrandFlag() ? "-" : "+"); } else { oaValue = String.format("%s,%s,%s,%s,%s,%s;", rec.getReferenceName(), rec.getAlignmentStart(), rec.getReadNegativeStrandFlag() ? "-" : "+", rec.getCigarString(), rec.getMappingQuality(), Optional.ofNullable(rec.getAttribute(SAMTag.NM.name())).orElse("")); } rec.setAttribute(OA, Optional.ofNullable(rec.getAttribute(OA)).orElse("") + oaValue); }
Source:
<code>private static ImmutableList<String> filterMetricNames( final List<String> metricNames, final Optional<String> containing, final boolean filterRollups) { final Predicate<String> baseFilter; if (filterRollups) { baseFilter = IS_ROLLUP.negate(); } else { baseFilter = s -> true; } final Predicate<String> containsFilter; if (containing.isPresent() && !containing.get().isEmpty()) { <START> final String lowerContaining = containing.get().toLowerCase(Locale.ENGLISH); <END> containsFilter = s -> s.toLowerCase(Locale.getDefault()).contains(lowerContaining); } else { containsFilter = s -> true; } return metricNames.stream() .filter(baseFilter) .filter(IS_PT1M.negate()) .filter(containsFilter) .collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf)); }</code><technical_language>Locale.getDefault()</technical_language>

Target:
private static ImmutableList<String> filterMetricNames( final List<String> metricNames, final Optional<String> containing, final boolean filterRollups) { final Predicate<String> baseFilter; if (filterRollups) { baseFilter = IS_ROLLUP.negate(); } else { baseFilter = s -> true; } final Predicate<String> containsFilter; if (containing.isPresent() && !containing.get().isEmpty()) { final String lowerContaining = containing.get().toLowerCase(Locale.getDefault()); containsFilter = s -> s.toLowerCase(Locale.getDefault()).contains(lowerContaining); } else { containsFilter = s -> true; } return metricNames.stream() .filter(baseFilter) .filter(IS_PT1M.negate()) .filter(containsFilter) .collect(ImmutableList.toImmutableList()); }
Source:
<code>private boolean isAnApiRequest(HttpServletRequest httpRequest) { <START> return httpRequest.getRequestURI().contains("/api/"); <END> }</code><technical_language>err side of a startsWith avoid situations accessing files/:pipeline_name/:pipeline_counter/:stage_name/:stage_counter/:job_name/foo/api/index.html</technical_language>

Target:
private boolean isAnApiRequest(HttpServletRequest httpRequest) { return httpRequest.getRequestURI().startsWith("/go/api/"); }
Source:
<code>public void completeCompile(StatementNode qt) throws StandardException { paramTypeDescriptors = qt.getParameterTypes(); if (targetTable != null) { targetTable = null; updateMode = 0; updateColumns = null; targetColumns = null; } resultDesc = qt.makeResultDescription(); if (resultDesc != null) { CursorInfo cursorInfo = (CursorInfo) qt.getCursorInfo(); if (cursorInfo != null) { targetTable = cursorInfo.targetTable; targetColumns = cursorInfo.targetColumns; updateColumns = cursorInfo.updateColumns; updateMode = cursorInfo.updateMode; } } <START> synchronized (this) { isValid = true; } <END> }</code><technical_language>setValid()</technical_language>

Target:
public void completeCompile(StatementNode qt) throws StandardException { paramTypeDescriptors = qt.getParameterTypes(); if (targetTable != null) { targetTable = null; updateMode = 0; updateColumns = null; targetColumns = null; } resultDesc = qt.makeResultDescription(); if (resultDesc != null) { CursorInfo cursorInfo = (CursorInfo) qt.getCursorInfo(); if (cursorInfo != null) { targetTable = cursorInfo.targetTable; targetColumns = cursorInfo.targetColumns; updateColumns = cursorInfo.updateColumns; updateMode = cursorInfo.updateMode; } } setValid(); }
Source:
<code>public Object getObject(String category, String url, String username, String password) throws RestClientException { prepareRestTemplate(username, password); try { return restTemplate.getForObject(url, resolveCategory(category)); } catch(RestClientException e) { <START> log.error(String.format("Exception occurred when getting object. Category: %s, url: %s", category, url), <END> e); throw e; } }</code><technical_language>Log & (Re)throw anti-pattern</technical_language>

Target:
public Object getObject(String category, String url, String username, String password) throws RestClientException { prepareRestTemplate(username, password); return restTemplate.getForObject(url, resolveCategory(category)); }
Source:
<code>public boolean canHideLabel() { boolean canHideLabel = false; if (!isLabelEmpty()) { if (element instanceof DEdge) { canHideLabel = true; <START> } else if (element instanceof DNode) { <END> if (LabelPosition.BORDER_LITERAL.equals(((DNode) element).getOwnedStyle().getLabelPosition())) { canHideLabel = true; } } else if (element instanceof DNodeContainer) { canHideLabel = true; } else if (element instanceof DNodeList) { canHideLabel = true; } } return canHideLabel; }</code><technical_language>create a bugzilla allow hide label nodes</technical_language>

Target:
public boolean canHideLabel() { boolean canHideLabel = false; if (!isLabelEmpty()) { if (element instanceof DEdge) { canHideLabel = true; } else if (element instanceof DNode) { if (LabelPosition.BORDER_LITERAL.equals(((DNode) element).getOwnedStyle().getLabelPosition())) { canHideLabel = true; } } else if (element instanceof DDiagramElementContainer) { canHideLabel = true; } } return canHideLabel; }
Source:
<code>public void testBuilder() { Element doc = XmlUtils.getElementInFile(fTestXmlFile.getPath(), TmfXmlStrings.PATTERN, ANALYSIS_ID); NodeList patternSegments = doc.getElementsByTagName(TmfXmlStrings.SEGMENT); assertEquals("Number of pattern segments", 2, patternSegments.getLength()); final Node item2 = patternSegments.item(1); assertNotNull("pattern segment 2", item2); TmfXmlPatternSegmentBuilder builder = new TmfXmlPatternSegmentBuilder(fModelFactory, (Element) item2, fContainer); assertNotNull("builder", builder); <START> final ITmfEvent startEvent = new TmfEvent(null, ITmfContext.UNKNOWN_RANK, new TmfTimestamp(1, ITmfTimestamp.NANOSECOND_SCALE), null, null); <END> final ITmfEvent endEvent = new TmfEvent(null, ITmfContext.UNKNOWN_RANK, new TmfTimestamp(10, ITmfTimestamp.NANOSECOND_SCALE), null, null); TmfXmlPatternSegment segment = builder.generatePatternSegment(endEvent, startEvent.getTimestamp(), endEvent.getTimestamp()); testPatternSegmentData(segment); }</code><technical_language>2 places need change values for in this test here..</technical_language>

Target:
public void testBuilder() { Element doc = XmlUtils.getElementInFile(fTestXmlFile.getPath(), TmfXmlStrings.PATTERN, ANALYSIS_ID); NodeList patternSegments = doc.getElementsByTagName(TmfXmlStrings.SEGMENT); assertEquals("Number of pattern segments", 2, patternSegments.getLength()); final Node item2 = patternSegments.item(1); assertNotNull("pattern segment 2", item2); TmfXmlPatternSegmentBuilder builder = new TmfXmlPatternSegmentBuilder(fModelFactory, (Element) item2, fContainer); assertNotNull("builder", builder); TmfXmlPatternSegment segment = builder.generatePatternSegment(PatternSegmentFactoryStub.TEST_2_END_EVENT, PatternSegmentFactoryStub.TEST_2_START_EVENT.getTimestamp(), PatternSegmentFactoryStub.TEST_2_END_EVENT.getTimestamp()); XmlUtilsTest.testPatternSegmentData(PatternSegmentFactoryStub.TEST_2, segment); }
Source:
<code>protected void reduce(ImmutableBytesWritable arg0, Iterable<IntWritable> arg1, Reducer<ImmutableBytesWritable, IntWritable, NullWritable, NullWritable>.Context context) throws IOException, InterruptedException { <START> synchronized (this) { <END> if (calledOnce) { return; } calledOnce = true; } IndexTool.IndexVerifyType verifyType = getIndexVerifyType(context.getConfiguration()); if (verifyType != IndexTool.IndexVerifyType.NONE) { updateCounters(verifyType, context); } }</code><technical_language>AtomicBoolean instead of a synchronized block</technical_language>

Target:
protected void reduce(ImmutableBytesWritable arg0, Iterable<IntWritable> arg1, Reducer<ImmutableBytesWritable, IntWritable, NullWritable, NullWritable>.Context context) throws IOException, InterruptedException { if (!calledOnce.compareAndSet(false, true)) { return; } IndexTool.IndexVerifyType verifyType = getIndexVerifyType(context.getConfiguration()); if (verifyType != IndexTool.IndexVerifyType.NONE) { updateCounters(verifyType, context); } }
Source:
<code>public void testEncodeUrlInApiCall() throws Exception { try { Map result = api.subFolders("sub^folder test", null); assertEquals("sub%5Efolder%20test", ((Map) ((org.cloudinary.json.JSONArray) result.get("folders")).get(0)).get("path")); <START> } catch (Exception ignored) { <END> } }</code><technical_language>Remove try/catch test fails if exception is thrown</technical_language>

Target:
public void testEncodeUrlInApiCall() throws Exception { String apiTestEncodeUrlInApiCall = "sub^folder test"; createdFolders.add(apiTestEncodeUrlInApiCall); Map result = api.createFolder(apiTestEncodeUrlInApiCall, null); assertEquals("sub^folder test", result.get("path")); }
Source:
<code><START> private List<AuditEvent> resolveEvent(PerunSessionImpl sess, User user) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { <END> List<AuditEvent> resolvingMessages = new ArrayList<>(); Attribute attribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, A_U_V_LOA); if (attribute.getValue() == null) { resolvingMessages.add(new AttributeRemovedForUser(new AttributeDefinition(attribute),user)); } else { resolvingMessages.add(new AttributeSetForUser(attribute,user)); } return resolvingMessages; }</code><technical_language>is output of this method list of audit events if message is generated</technical_language>

Target:
private AuditEvent resolveEvent(PerunSessionImpl sess, User user) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { Attribute attribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, A_U_V_LOA); if (attribute.getValue() == null) { return new AttributeRemovedForUser(new AttributeDefinition(attribute),user); } else { return new AttributeSetForUser(attribute,user); } }
Source:
<code>public void testDeprecatedAttributeXPathQuery() throws JaxenException { final StringWriter writer = new StringWriter(); class MyRootNode extends DummyNode implements RootNode { private MyRootNode(int id) { super(id); } } Logger.getLogger(Attribute.class.getName()).setLevel(Level.WARNING); <START> Logger.getLogger(Attribute.class.getName()).addHandler(new Handler() { <END> @Override public void publish(LogRecord record) { writer.write(record.getMessage()); writer.write('\n'); } @Override public void flush() { writer.flush(); } @Override public void close() throws SecurityException { } }); addChild(new MyRootNode(nextId()), new DummyNodeWithDeprecatedAttribute(2)).findChildNodesWithXPath(" writer.flush(); assertTrue(writer.toString().contains("deprecated")); assertTrue(writer.toString().contains("attribute")); assertTrue(writer.toString().contains("dummyNode/@Size")); }</code><technical_language>pmd test codebase is a JavaUtilLoggingRule junit @Rule this. tests, RuleSetFactoryTest check proper warnings logged</technical_language>

Target:
public void testDeprecatedAttributeXPathQuery() throws JaxenException { class MyRootNode extends DummyNode implements RootNode { private MyRootNode(int id) { super(id); } } addChild(new MyRootNode(nextId()), new DummyNodeWithDeprecatedAttribute(2)).findChildNodesWithXPath(" String log = loggingRule.getLog(); assertTrue(log.contains("deprecated")); assertTrue(log.contains("attribute")); assertTrue(log.contains("dummyNode/@Size")); }
Source:
<code>public void setUp() throws Exception { amazonEC2Client = EasyMock.createMock(AmazonEC2Client.class); <START> mockAmazonEC2Client = new EC2MockClient(); <END> describeInstancesResult = EasyMock.createMock(DescribeInstancesResult.class); reservation = EasyMock.createMock(Reservation.class); instance = new Instance() .withInstanceId(INSTANCE_ID) .withLaunchTime(new Date()) .withImageId(AMI_ID) .withPrivateIpAddress(IP); managementConfig = new SimpleResourceManagementConfig().setWorkerPort(8080).setWorkerVersion(""); }</code><technical_language>EasyMock instead of creating a new class ? do custom else get/set region</technical_language>

Target:
public void setUp() throws Exception { amazonEC2Client = EasyMock.createMock(AmazonEC2Client.class); describeInstancesResult = EasyMock.createMock(DescribeInstancesResult.class); reservation = EasyMock.createMock(Reservation.class); instance = new Instance() .withInstanceId(INSTANCE_ID) .withLaunchTime(new Date()) .withImageId(AMI_ID) .withPrivateIpAddress(IP); managementConfig = new SimpleResourceManagementConfig().setWorkerPort(8080).setWorkerVersion(""); }
Source:
<code>public void testCloneRepositoryWhenDestinationDirectoryExistsAndIsNotEmpty() { try { String dirName = "testCloneTargetDirectoryNotEmpty"; File directory = createTempDirectory(dirName); CloneCommand command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); Git git2 = command.call(); assertNotNull(git2); command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); try { git2 = command.call(); fail("destination directory already exists and is not an empty folder, cloning should fail"); } catch (JGitInternalException e) { assertTrue(e.getMessage().contains("not an empty directory")); assertTrue(e.getMessage().contains(dirName)); } <START> } catch (Exception e) { <END> fail(e.getMessage()); } }</code><technical_language>Please throw Exception</technical_language>

Target:
public void testCloneRepositoryWhenDestinationDirectoryExistsAndIsNotEmpty() throws IOException { String dirName = "testCloneTargetDirectoryNotEmpty"; File directory = createTempDirectory(dirName); CloneCommand command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); Git git2 = command.call(); assertNotNull(git2); command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); try { git2 = command.call(); fail("destination directory already exists and is not an empty folder, cloning should fail"); } catch (JGitInternalException e) { assertTrue(e.getMessage().contains("not an empty directory")); assertTrue(e.getMessage().contains(dirName)); } }
Source:
<code>void accept(ExpressionWriter writer, int lprec, int rprec) { if (writer.requireParentheses(this, lprec, rprec)) { return; } if (nodeType == ExpressionType.Equal || nodeType == ExpressionType.NotEqual) { Primitive boxPrimitive0 = Primitive.ofBox(expression0.getType()); Primitive boxPrimitive1 = Primitive.ofBox(expression1.getType()); if (boxPrimitive0 != null && boxPrimitive1 != null && !isConstantNullExpression(expression0) <START> && !isConstantNullExpression(expression1)) { <END> if (nodeType == ExpressionType.NotEqual) { writer.append("!"); } writer.append("java.util.Objects.equals("); expression0.accept(writer, lprec, nodeType.lprec); writer.append(", "); expression1.accept(writer, nodeType.rprec, rprec); writer.append(")"); return; } } expression0.accept(writer, lprec, nodeType.lprec); writer.append(nodeType.op); expression1.accept(writer, nodeType.rprec, rprec); }</code><technical_language>I move this logic [1] [1] <LINK_0></technical_language>

Target:
void accept(ExpressionWriter writer, int lprec, int rprec) { if (writer.requireParentheses(this, lprec, rprec)) { return; } expression0.accept(writer, lprec, nodeType.lprec); writer.append(nodeType.op); expression1.accept(writer, nodeType.rprec, rprec); }
Source:
<code>public Observable<Product> getProduct(final Long productId) { if (productId == null) { throw new NullPointerException("productId cannot be null"); } final Observable<Product> apiRequest = retrofitService .getProducts(appId, String.valueOf(productId)) .retryWhen(networkRetryPolicyProvider.provide()) .doOnNext(new RetrofitSuccessHttpStatusCodeHandler<>()) .compose(new UnwrapRetrofitBodyTransformer<ProductListings, List<Product>>()) .compose(new FirstListItemOrDefaultTransformer<Product>()) .onErrorResumeNext(new BuyClientExceptionHandler<Product>()); return ApiRequestInterceptWrapper.wrap( apiRequest, <START> new ApiRequestInterceptWrapper.InterceptorCall<ProductApiInterceptor, Product>(requestInterceptor) { <END> @Override public Observable<Product> call(ProductApiInterceptor interceptor, Observable<Product> originalObservable) { return interceptor.getProduct(productId, originalObservable); } }, new ApiRequestInterceptWrapper.InterceptorCall<ProductApiInterceptor, Product>(responseInterceptor) { @Override public Observable<Product> call(ProductApiInterceptor interceptor, Observable<Product> originalObservable) { return interceptor.getProduct(productId, originalObservable); } } ).observeOn(callbackScheduler); }</code><technical_language>is here. request response do - factor this out</technical_language>

Target:
public Observable<Product> getProduct(final Long productId) { if (productId == null) { throw new NullPointerException("productId cannot be null"); } final Observable<Product> apiRequest = retrofitService .getProducts(appId, String.valueOf(productId)) .retryWhen(networkRetryPolicyProvider.provide()) .doOnNext(new RetrofitSuccessHttpStatusCodeHandler<>()) .compose(new UnwrapRetrofitBodyTransformer<ProductListings, List<Product>>()) .compose(new FirstListItemOrDefaultTransformer<Product>()) .onErrorResumeNext(new BuyClientExceptionHandler<Product>()); return ApiInterceptWrapper.wrap( apiRequest, requestInterceptor, responseInterceptor, new ApiInterceptWrapper.InterceptorCall<ProductApiInterceptor, Product>() { @Override public Observable<Product> call(ProductApiInterceptor interceptor, Observable<Product> originalObservable) { return interceptor.getProduct(productId, originalObservable); } } ).observeOn(callbackScheduler); }
Source:
<code><START> public static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { <END> DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }</code><technical_language>is this public</technical_language>

Target:
private static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }
Source:
<code>public StateItem[] getStateTable() { if (fStateTable == null) { Map<@NonNull String, @NonNull OutputElementStyle> styles = getStyles(); if (styles == null || styles.isEmpty()) { return new StateItem[0]; } List<StateItem> stateItemList = new ArrayList<>(); int tableIndex = 0; for (Entry<@NonNull String, @NonNull OutputElementStyle> styleEntry : fStylesMap.entrySet()) { @NonNull Map<@NonNull String, @NonNull Object> elementStyle = styleEntry.getValue().getStyleValues(); Object color = elementStyle.get(OutputElementStyleProperties.BACKGROUND_COLOR); RGB rgb = new RGB(0, 0, 0); <START> if (color instanceof String) { RGB rgbColor = RGBAUtil.fromHexColor((String) color); rgb = rgbColor != null ? rgbColor : new RGB(0, 0, 0); } <END> fLabelToIndex.put(styleEntry.getKey(), tableIndex); tableIndex++; Map<String, Object> styleMap = new HashMap<>(); styleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); styleMap.put(ITimeEventStyleStrings.fillColor(), new RGBAColor(rgb.red, rgb.green, rgb.blue).toInt()); styleMap.put(ITimeEventStyleStrings.label(), styleEntry.getKey()); styleMap.put(ITimeEventStyleStrings.group(), elementStyle.get(OutputElementStyleProperties.STYLE_GROUP)); stateItemList.add(new StateItem(styleMap)); } fStateTable = stateItemList.toArray(new StateItem[stateItemList.size()]); return fStateTable; } return fStateTable; }</code><technical_language>opacity get right rgba</technical_language>

Target:
public StateItem[] getStateTable() { if (fStateTable == null) { Map<@NonNull String, @NonNull OutputElementStyle> styles = getStyles(); if (styles == null || styles.isEmpty()) { return new StateItem[0]; } List<StateItem> stateItemList = new ArrayList<>(); int tableIndex = 0; for (Entry<@NonNull String, @NonNull OutputElementStyle> styleEntry : fStylesMap.entrySet()) { @NonNull Map<@NonNull String, @NonNull Object> elementStyle = styleEntry.getValue().getStyleValues(); Object color = elementStyle.get(OutputElementStyleProperties.BACKGROUND_COLOR); RGB rgb = new RGB(0, 0, 0); if (color instanceof String) { RGB rgbColor = ColorUtils.fromHexColor((String) color); rgb = rgbColor != null ? rgbColor : new RGB(0, 0, 0); } fLabelToIndex.put(styleEntry.getKey(), tableIndex); tableIndex++; Map<String, Object> styleMap = new HashMap<>(); styleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); styleMap.put(ITimeEventStyleStrings.fillColor(), new RGBAColor(rgb.red, rgb.green, rgb.blue).toInt()); styleMap.put(ITimeEventStyleStrings.label(), styleEntry.getKey()); Object styleGroup = elementStyle.get(OutputElementStyleProperties.STYLE_GROUP); if (styleGroup != null) { styleMap.put(ITimeEventStyleStrings.group(), styleGroup); } stateItemList.add(new StateItem(styleMap)); } fStateTable = stateItemList.toArray(new StateItem[stateItemList.size()]); return fStateTable; } return fStateTable; }
Source:
<code>public LogEntry getByUniqueId(String uniqueId) { <START> return null; <END> }</code><technical_language>assume contained in uniqueId is internal integer id fetch it</technical_language>

Target:
public LogEntry getByUniqueId(String uniqueId) { List<LogEntry> logentries = Context.getService(IdentifierSourceService.class).getLogEntries(null, null, null, uniqueId, null, null); if (logentries.size() != 0) { return logentries.get(0); } else { return null; } }
Source:
<code>private void drawTextEntrySeparator(UiDrawer uiDrawer) { <START> uiDrawer.drawLine(TOP_LEFT.x + 2 * FRAME_WIDTH, getLineY(20.333f), 0, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 4 * FRAME_WIDTH, Color.WHITE); <END> }</code><technical_language>Magic constants a field. Applies of</technical_language>

Target:
private void drawTextEntrySeparator(UiDrawer uiDrawer) { uiDrawer.drawLine(TOP_LEFT.x + 2 * FRAME_WIDTH, getLineY(INPUT_LINE_SEPARATOR_Y), 0, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 4 * FRAME_WIDTH, Color.WHITE); }
Source:
<code>public final T load(GeoServer gs, Resource directory) throws Exception { Resource file; if ( Resources.exists(file = directory.get(getFilename()))) { BufferedInputStream in = <START> new BufferedInputStream( file.in() ); <END> try { XStreamPersister xp = xpf.createXMLPersister(); initXStreamPersister(xp, gs); return initialize( xp.load( in, getServiceClass() ) ); } finally { in.close(); } } else { ServiceInfo service = createServiceFromScratch( gs ); return initialize( (T) service ); } }</code><technical_language>try-with-resources</technical_language>

Target:
public final T load(GeoServer gs, Resource directory) throws Exception { Resource file; if ( Resources.exists(file = directory.get(getFilename()))) { try (BufferedInputStream in = new BufferedInputStream(file.in())) { XStreamPersister xp = xpf.createXMLPersister(); initXStreamPersister(xp, gs); return initialize( xp.load( in, getServiceClass() ) ); } } else { ServiceInfo service = createServiceFromScratch( gs ); return initialize( (T) service ); } }
Source:
<code>public void store_command_with_error_and_generate_ID_if_needed() { <START> final Command command = Commands.create(org.spine3.server.storage.Given.CommandMessage.createProject(), CommandContext.getDefaultInstance()); <END> final Error error = newError(); storage.store(command, error); final List<CommandStorageRecord> records = Lists.newArrayList(storage.read(ERROR)); assertEquals(1, records.size()); assertFalse(records.get(0) .getCommandId() .trim() .isEmpty()); }</code><technical_language>Please adjust code fit 120-symbols-per-line</technical_language>

Target:
public void store_command_with_error_and_generate_ID_if_needed() { final Command command = Commands.create(Given.CommandMessage.createProject(), CommandContext.getDefaultInstance()); final Error error = newError(); storage.store(command, error); final List<CommandStorageRecord> records = Lists.newArrayList(storage.read(ERROR)); assertEquals(1, records.size()); assertFalse(records.get(0) .getCommandId() .trim() .isEmpty()); }
Source:
<code>public Page getNextPage() { try { Page page = recordReader.getNextPage(); if (page == null) { close(); } return page; } <START> catch (PrestoException | InvalidFunctionArgumentException e) { <END> closeWithSuppression(e); throw e; } catch (OrcCorruptionException e) { closeWithSuppression(e); throw new PrestoException(HIVE_BAD_DATA, e); } catch (IOException | RuntimeException e) { closeWithSuppression(e); throw new PrestoException(HIVE_CURSOR_ERROR, format("Failed to read ORC file: %s", orcDataSource.getId()), e); } }</code><technical_language>rethrow java catch (InvalidFunctionArgumentException e) { closeWithSuppression(e); throw new PrestoException(INVALID_.....); }</technical_language>

Target:
public Page getNextPage() { try { Page page = recordReader.getNextPage(); if (page == null) { close(); } return page; } catch (InvalidFunctionArgumentException e) { closeWithSuppression(e); throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e.getMessage(), e); } catch (PrestoException e) { closeWithSuppression(e); throw e; } catch (OrcCorruptionException e) { closeWithSuppression(e); throw new PrestoException(HIVE_BAD_DATA, e); } catch (IOException | RuntimeException e) { closeWithSuppression(e); throw new PrestoException(HIVE_CURSOR_ERROR, format("Failed to read ORC file: %s", orcDataSource.getId()), e); } }
Source:
<code>public boolean isUsersWithRetirementTeacherSituations(GiafProfessionalData giafProfessionalData, Set<ContractSituation> retirementSituations, LocalDate today) { <START> Set<PersonContractSituation> personContractSituations = new HashSet<PersonContractSituation>(); <END> for (PersonContractSituation personContractSituation : giafProfessionalData.getPersonContractSituationsSet()) { if (personContractSituation.isValid() && personContractSituation.getAnulationDate() == null && personContractSituation.isActive(today) && (personContractSituation.getProfessionalCategory() != null && personContractSituation.getProfessionalCategory().getCategoryType().equals(CategoryType.TEACHER)) && retirementSituations.contains(personContractSituation.getContractSituation())) { return true; } } return false; }</code><technical_language>This variable is used. removed</technical_language>

Target:
public boolean isUsersWithRetirementTeacherSituations(GiafProfessionalData giafProfessionalData, Set<ContractSituation> retirementSituations, LocalDate today) { for (PersonContractSituation personContractSituation : giafProfessionalData.getPersonContractSituationsSet()) { if (personContractSituation.isValid() && personContractSituation.getAnulationDate() == null && personContractSituation.isActive(today) && (personContractSituation.getProfessionalCategory() != null && personContractSituation.getProfessionalCategory().getCategoryType().equals(CategoryType.TEACHER)) && retirementSituations.contains(personContractSituation.getContractSituation())) { return true; } } return false; }
Source:
<code>private void deleteQualityGates(DbSession dbSession, OrganizationDto organization) { <START> Collection<QualityGateDto> qualityGates = dbClient.qualityGateDao().selectAll(dbSession, organization); <END> dbClient.qualityGateDao().deleteByUuids(dbSession, qualityGates.stream().map(QualityGateDto::getUuid).collect(MoreCollectors.toList())); }</code><technical_language>**not** remove built-in quality gate</technical_language>

Target:
private void deleteQualityGates(DbSession dbSession, OrganizationDto organization) { Collection<QualityGateDto> qualityGates = dbClient.qualityGateDao().selectAll(dbSession, organization); dbClient.qualityGateDao().deleteByUuids(dbSession, qualityGates.stream() .filter(q -> !q.isBuiltIn()) .map(QualityGateDto::getUuid) .collect(MoreCollectors.toList())); }
Source:
<code>public void testItTimesOutProperly() throws Exception { String validationQuery = "select 1"; Jdbi jdbi = mock(Jdbi.class); Handle handle = mock(Handle.class); when(jdbi.open()).thenReturn(handle); when(jdbi.withHandle(Mockito.any())).thenCallRealMethod(); <START> Mockito.doAnswer(invocation -> { <END> try { TimeUnit.SECONDS.sleep(10); } catch (Exception ignored) { } return null; }).when(handle).execute(validationQuery); ExecutorService executorService = Executors.newSingleThreadExecutor(); JdbiHealthCheck jdbiHealthCheck = new JdbiHealthCheck(executorService, Duration.milliseconds(5), jdbi, validationQuery); HealthCheck.Result result = jdbiHealthCheck.check(); executorService.shutdown(); assertThat("is unhealthy", false, is(result.isHealthy())); }</code><technical_language>handle.execute method returns int instead of void, when().doAnswer form</technical_language>

Target:
public void testItTimesOutProperly() throws Exception { when(handle.execute(VALIDATION_QUERY)).thenAnswer((Answer<Integer>) invocation -> { TimeUnit.SECONDS.sleep(10); return null; }); HealthCheck.Result result = sut.check(); assertThat(result.isHealthy()).isFalse(); }