auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void processData() { String timeStampString = fData.get(CustomTraceDefinition.TAG_TIMESTAMP); String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); Date date = null; if (timeStampInputFormat != null && timeStampString != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(timeStampInputFormat); try { date = dateFormat.parse(timeStampString); setTimestamp(new TmfTimestamp(date.getTime(), TIMESTAMP_SCALE)); } catch (ParseException e) { setTimestamp(TmfTimestamp.ZERO); } } else { setTimestamp(TmfTimestamp.ZERO); } int i = 0; fColumnData = new TmfEventField[fDefinition.outputs.size()]; for (OutputColumn outputColumn : fDefinition.outputs) { String value = fData.get(outputColumn.name); if (outputColumn.name.equals(CustomTraceDefinition.TAG_TIMESTAMP) && date != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(fDefinition.timeStampOutputFormat); fColumnData[i++] = new TmfEventField(outputColumn.name, dateFormat.format(date)); } else { fColumnData[i++] = new TmfEventField(outputColumn.name, (value != null ? value : "")); } } CustomEventContent curContent = (CustomEventContent) fContent; fContent = new CustomEventContent(curContent.getName(), curContent.getValue(), fColumnData); fData = null; }

Target:
private void processData() { String timeStampString = fData.get(CustomTraceDefinition.TAG_TIMESTAMP); String timeStampInputFormat = fData.get(TIMESTAMP_INPUT_FORMAT_KEY); Date date = null; if (timeStampInputFormat != null && timeStampString != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(timeStampInputFormat); try { date = dateFormat.parse(timeStampString); setTimestamp(new TmfTimestamp(date.getTime(), TIMESTAMP_SCALE)); } catch (ParseException e) { setTimestamp(TmfTimestamp.ZERO); } } else { setTimestamp(TmfTimestamp.ZERO); } int i = 0; fColumnData = new TmfEventField[fDefinition.outputs.size()]; for (OutputColumn outputColumn : fDefinition.outputs) { String value = fData.get(outputColumn.name); if (outputColumn.name.equals(CustomTraceDefinition.TAG_TIMESTAMP) && date != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(fDefinition.timeStampOutputFormat); fColumnData[i++] = new TmfEventField(outputColumn.name, dateFormat.format(date)); } else { fColumnData[i++] = new TmfEventField(outputColumn.name, (value != null ? value : "")); } } CustomEventContent curContent = (CustomEventContent) getContent(); setContent(new CustomEventContent(curContent.getName(), curContent.getValue(), fColumnData)); fData = null; }
Source:
public void testWriteStatistics() throws IOException { Path objectPath = new Path(ghfs.getFileSystemRoot(), "dir/object2.txt"); FileSystem.Statistics statistics = new FileSystem.Statistics(ghfs.getScheme()); GoogleHadoopSyncableOutputStream fout = new GoogleHadoopSyncableOutputStream( ghfs, ghfs.getGcsPath(objectPath), statistics, CreateFileOptions.DEFAULT_OVERWRITE, SyncableOutputStreamOptions.DEFAULT, mockExecutorService); byte[] data1 = new byte[] {0x0f, 0x0e, 0x0e, 0x0d}; byte[] data2 = new byte[] {0x0b, 0x0e, 0x0e, 0x0f}; fout.write(data1, 0, data1.length); fout.sync(); assertThat(statistics.getBytesWritten()).isEqualTo(4); assertThat(statistics.getWriteOps()).isEqualTo(1); fout.write(data2, 0, data2.length); fout.sync(); assertThat(statistics.getBytesWritten()).isEqualTo(8); assertThat(statistics.getWriteOps()).isEqualTo(2); verify(mockExecutorService).submit(any(Callable.class)); }

Target:
public void testWriteStatistics() throws IOException { Path objectPath = new Path(ghfs.getFileSystemRoot(), "dir/object2.txt"); FileSystem.Statistics statistics = new FileSystem.Statistics(ghfs.getScheme()); GoogleHadoopSyncableOutputStream fout = new GoogleHadoopSyncableOutputStream( ghfs, ghfs.getGcsPath(objectPath), statistics, CreateFileOptions.DEFAULT_OVERWRITE, SyncableOutputStreamOptions.DEFAULT, mockExecutorService); byte[] data1 = new byte[] {0x0f, 0x0e, 0x0e, 0x0d}; byte[] data2 = new byte[] {0x0b, 0x0d, 0x0e, 0x0e, 0x0f}; fout.write(data1, 0, data1.length); fout.sync(); assertThat(statistics.getBytesWritten()).isEqualTo(4); assertThat(statistics.getWriteOps()).isEqualTo(1); fout.write(data2, 0, data2.length); fout.sync(); assertThat(statistics.getBytesWritten()).isEqualTo(9); assertThat(statistics.getWriteOps()).isEqualTo(2); verify(mockExecutorService).submit(any(Callable.class)); }
Source:
public static SetDataRequest fromParameterMap(final Map<String, String> requestParameters) { final SetDataRequest setDataRequest = new SetDataRequest(); setDataRequest.setDeviceIdentification(requestParameters.get(Keys.KEY_DEVICE_IDENTIFICATION)); SetDataSystemIdentifier system = new SystemBuilder().withSettings(requestParameters).build(); system.getSetPoint().addAll(new SetPointBuilder().withSettings(requestParameters).buildList()); system.getProfile().addAll(new ProfileBuilder().withSettings(requestParameters).buildList()); setDataRequest.getSystem().add(system); return setDataRequest; }

Target:
public static SetDataRequest fromParameterMap(final Map<String, String> requestParameters) { final SetDataRequest setDataRequest = new SetDataRequest(); setDataRequest.setDeviceIdentification(requestParameters.get(Keys.KEY_DEVICE_IDENTIFICATION)); final List<SetDataSystemIdentifier> systems = new SetDataSystemIdentifierBuilder() .withSettings(requestParameters).buildList(); setDataRequest.getSystem().addAll(systems); return setDataRequest; }
Source:
public void setValues() { fontOverrideProperty.setValue(preferences.getBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE)); fontSizeProperty.setValue(String.valueOf(preferences.getInt(JabRefPreferences.MAIN_FONT_SIZE))); String currentTheme = preferences.get(JabRefPreferences.FX_THEME); if (ThemeLoader.DARK_CSS.equals(currentTheme)) { themeLightProperty.setValue(false); themeDarkProperty.setValue(true); themeCustomProperty.setValue(false); } else if (ThemeLoader.MAIN_CSS.equals(currentTheme) || currentTheme.isBlank() || currentTheme.isEmpty()) { themeLightProperty.setValue(true); themeDarkProperty.setValue(false); themeCustomProperty.setValue(false); } else { themeLightProperty.setValue(false); themeDarkProperty.setValue(false); themeCustomProperty.setValue(true); } }

Target:
public void setValues() { fontOverrideProperty.setValue(preferences.getBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE)); fontSizeProperty.setValue(String.valueOf(preferences.getInt(JabRefPreferences.MAIN_FONT_SIZE))); String currentTheme = preferences.get(JabRefPreferences.FX_THEME); if (ThemeLoader.DARK_CSS.equals(currentTheme)) { themeLightProperty.setValue(false); themeDarkProperty.setValue(true); themeCustomProperty.setValue(false); } else if (ThemeLoader.MAIN_CSS.equals(currentTheme) || currentTheme.isBlank()) { themeLightProperty.setValue(true); themeDarkProperty.setValue(false); themeCustomProperty.setValue(false); } else { themeLightProperty.setValue(false); themeDarkProperty.setValue(false); themeCustomProperty.setValue(true); } }
Source:
public InfoboxBuilderPage verifySelectedComponentBorderStyle(int index) { wait.forElementVisible(component.get(index)); component.get(index).click(); String script = "return window.getComputedStyle(" + "document.querySelector('.active'),':before').getPropertyValue('Border')"; JavascriptExecutor js = (JavascriptExecutor)driver; String borderValues = (String) js.executeScript(script); Assertion.assertEquals(borderValues, "1px solid rgb(26, 94, 184)"); return this; }

Target:
public InfoboxBuilderPage verifySelectedComponentBorderStyle(int index) { JavascriptExecutor js = (JavascriptExecutor)driver; WebElement selectedComponent = component.get(index); wait.forElementVisible(selectedComponent); selectedComponent.click(); String script = "return window.getComputedStyle(" + "document.querySelector('.active'),':before').getPropertyValue('Border')"; String borderValues = js.executeScript(script).toString(); Assertion.assertEquals(borderValues, "1px solid rgb(26, 94, 184)"); return this; }
Source:
private void sortByDuration(final boolean reverse) { Collections.sort(episodes, new Comparator<FeedItem>() { @Override public int compare(FeedItem lhs, FeedItem rhs) { int code = lhs.getMedia().getDuration() - rhs.getMedia().getDuration(); if (reverse) { return -1 * code; } else { return code; } } }); refreshTitles(); refreshCheckboxes(); }

Target:
private void sortByDuration(final boolean reverse) { Collections.sort(episodes, new Comparator<FeedItem>() { @Override public int compare(FeedItem lhs, FeedItem rhs) { int ordering; if (false == lhs.hasMedia()) { ordering = 1; } else if (false == rhs.hasMedia()) { ordering = -1; } else { ordering = lhs.getMedia().getDuration() - rhs.getMedia().getDuration(); } if(reverse) { return -1 * ordering; } else { return ordering; } } }); refreshTitles(); refreshCheckboxes(); }
Source:
public void checkPrivatePatternCall(PatternCall call) { final Pattern calledPattern = call.getPatternRef(); if (calledPattern != null && calledPattern.getModifiers() != null) { if (calledPattern.getModifiers().isPrivate() && calledPattern.eResource() != call.eResource()){ error(String.format("The pattern %s is not visible.", getFormattedPattern(calledPattern)), PatternLanguagePackage.Literals.PATTERN_CALL__PATTERN_REF, IssueCodes.PRIVATE_PATTERN_CALLED); } } }

Target:
public void checkPrivatePatternCall(PatternCall call) { final Pattern calledPattern = call.getPatternRef(); if (calledPattern != null && calledPattern.getModifiers() != null) { if (CorePatternLanguageHelper.isPrivate(calledPattern) && calledPattern.eResource() != call.eResource()){ error(String.format("The pattern %s is not visible.", getFormattedPattern(calledPattern)), PatternLanguagePackage.Literals.PATTERN_CALL__PATTERN_REF, IssueCodes.PRIVATE_PATTERN_CALLED); } } }
Source:
private CloneImageGroupVolumesStructureCommandParameters buildCloneImageGroupVolumesStructureCommandParams() { CloneImageGroupVolumesStructureCommandParameters p = new CloneImageGroupVolumesStructureCommandParameters(getParameters().getStoragePoolId(), getParameters().getSourceStorageDomainId(), getParameters().getTargetStorageDomainId(), getImageGroupId(), getActionType(), getParameters()); p.setDestImageGroupId(getImageGroupId()); p.setEndProcedure(EndProcedure.COMMAND_MANAGED); return p; }

Target:
private CloneImageGroupVolumesStructureCommandParameters buildCloneImageGroupVolumesStructureCommandParams() { CloneImageGroupVolumesStructureCommandParameters p = new CloneImageGroupVolumesStructureCommandParameters(getParameters().getStoragePoolId(), getParameters().getSourceStorageDomainId(), getParameters().getTargetStorageDomainId(), getImageGroupId(), getActionType(), getParameters()); p.setDestImageGroupId(getImageGroupId()); p.setEndProcedure(EndProcedure.COMMAND_MANAGED); p.setJobWeight(Job.MAX_WEIGHT); return p; }
Source:
private void verifyLog(String... expected) throws IOException { File file = new File("audit.log"); List<String> lines = FileUtils.readLines(file, (String)null); final int retry = 5; int i = 0; while (lines.isEmpty() && i < retry) { lines = FileUtils.readLines(file, (String)null); try { Thread.sleep(500 * (i + 1)); } catch(InterruptedException ie) { Thread.currentThread().interrupt(); break; } i++; } assertTrue(lines.size() != 0); for(String exp: expected){ assertTrue(lines.get(0).contains(exp)); } lines.clear(); FileUtils.writeLines(file, lines, false); }

Target:
private void verifyLog(String... expected) throws Exception { File file = new File("audit.log"); final List<String> lines = FileUtils.readLines(file, (String)null); GenericTestUtils.waitFor(() -> (lines != null) ? true : false, 100, 60000); try{ assertTrue(lines.size() != 0); for(String exp: expected){ assertTrue(lines.get(0).contains(exp)); } } catch (AssertionError ex){ LOG.error("Error occurred in log verification", ex); if(lines.size() != 0){ LOG.error("Actual line ::: " + lines.get(0)); LOG.error("Expected tokens ::: " + Arrays.toString(expected)); } throw ex; } finally { emptyAuditLog(); } }
Source:
public Component[] getOwners() { Objects.requireNonNull(listenOnComponents, "listenOnComponents must be initialized " + "(by calling listenOn()) before calling this method!"); return listenOnComponents; }

Target:
public Component[] getOwners() { if (listenOnComponents == null) { return new Component[0]; } return listenOnComponents; }
Source:
public static <ViewModelType extends ViewModel> void initializeViewModel(ViewModelType viewModel) { if (viewModel == null) { return; } try { Method annotatedMethod = getInitializeMethod(viewModel); final Method initMethod = annotatedMethod != null ? annotatedMethod : viewModel.getClass().getMethod("initialize"); if(initMethod.isAnnotationPresent(PostConstruct.class)) { throw new IllegalStateException(String.format("initialize method of ViewModel [%s] is annotated with @PostConstruct. " + "This will lead to unexpected behaviour and duplicate initialization. " + "Please rename the method or remove the @PostConstruct annotation. " + "See mvvmFX wiki for more details: " + "<LINK_0>", viewModel)); } AccessController.doPrivileged((PrivilegedAction<?>) () -> ReflectionUtils.accessMember(initMethod, () -> initMethod.invoke(viewModel), "mvvmFX wasn't able to call the initialize method of ViewModel [" + viewModel + "].")); } catch (NoSuchMethodException e) { } }

Target:
public static <ViewModelType extends ViewModel> void initializeViewModel(ViewModelType viewModel) { if (viewModel == null) { return; } try { Method annotatedMethod = getInitializeMethod(viewModel); final Method initMethod = annotatedMethod != null ? annotatedMethod : viewModel.getClass().getMethod("initialize"); if(initMethod.isAnnotationPresent(PostConstruct.class)) { throw new IllegalStateException(String.format("initialize method of ViewModel [%s] is annotated with @PostConstruct. " + "This will lead to unexpected behaviour and duplicate initialization. " + "Please rename the method or remove the @PostConstruct annotation. " + "See mvvmFX wiki for more details: " + "<LINK_0>", viewModel)); } ReflectionUtils.accessMember(initMethod, () -> initMethod.invoke(viewModel), "mvvmFX wasn't able to call the initialize method of ViewModel [" + viewModel + "]."); } catch (NoSuchMethodException e) { } }
Source:
public ColumnRangesSystemTable(RaptorTableHandle sourceTable, IDBI dbi) { this.sourceTable = requireNonNull(sourceTable, "sourceTable is null"); this.dbi = requireNonNull(dbi, "dbi is null"); this.indexedRaptorColumns = dbi.onDemand(MetadataDao.class).listTableColumns(sourceTable.getTableId()).stream() .filter(column -> isIndexedType(column.getDataType())) .collect(toImmutableList()); List<ColumnMetadata> systemTableColumns = this.indexedRaptorColumns.stream() .flatMap(column -> Stream.of( new ColumnMetadata(column.getColumnName() + MIN_COLUMN_SUFFIX, column.getDataType(), null, false), new ColumnMetadata(column.getColumnName() + MAX_COLUMN_SUFFIX, column.getDataType(), null, false))) .collect(toImmutableList()); SchemaTableName tableName = new SchemaTableName(sourceTable.getSchemaName(), sourceTable.getTableName() + COLUMN_RANGES_TABLE_SUFFIX); this.tableMetadata = new ConnectorTableMetadata(tableName, systemTableColumns); }

Target:
public ColumnRangesSystemTable(RaptorTableHandle sourceTable, IDBI dbi) { this.sourceTable = requireNonNull(sourceTable, "sourceTable is null"); this.dbi = requireNonNull(dbi, "dbi is null"); this.indexedRaptorColumns = dbi.onDemand(MetadataDao.class) .listTableColumns(sourceTable.getTableId()).stream() .filter(column -> isIndexedType(column.getDataType())) .collect(toImmutableList()); List<ColumnMetadata> systemTableColumns = indexedRaptorColumns.stream() .flatMap(column -> Stream.of( new ColumnMetadata(column.getColumnName() + MIN_COLUMN_SUFFIX, column.getDataType(), null, false), new ColumnMetadata(column.getColumnName() + MAX_COLUMN_SUFFIX, column.getDataType(), null, false))) .collect(toImmutableList()); SchemaTableName tableName = new SchemaTableName(sourceTable.getSchemaName(), sourceTable.getTableName() + COLUMN_RANGES_TABLE_SUFFIX); this.tableMetadata = new ConnectorTableMetadata(tableName, systemTableColumns); }
Source:
public static String fetchConsoleUrl(Provider<KubevirtProviderProperties> provider, AuditLogDirector auditLogDirector) throws IOException, ApiException, URISyntaxException { OpenshiftApi api = KubevirtUtils.getOpenshiftApi(provider); Optional<V1Route> route; try { V1RouteList routes = api.listNamespacedRoute("openshift-console", null, "metadata.name=console", null, null, null, null, null, Boolean.FALSE); route = routes.getItems().stream().findAny(); } catch (ApiException e) { KubevirtUtils.auditAuthorizationIssues(e, auditLogDirector, provider); log.error("failed to retrieve console url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); throw e; } if (route.isPresent()) { String host = route.get().getSpec().getHost(); String scheme = route.get().getSpec().getPort().getTargetPort(); try { return new URI(scheme, host, null, null).toString(); } catch (URISyntaxException e) { log.error("failed to retrieve console url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); throw e; } } return null; }

Target:
public static String fetchConsoleUrl(Provider<KubevirtProviderProperties> provider, AuditLogDirector auditLogDirector) throws IOException, ApiException, URISyntaxException { OpenshiftApi api = KubevirtUtils.getOpenshiftApi(provider); Optional<V1Route> route; try { V1RouteList routes = api.listNamespacedRoute("openshift-console", null, "metadata.name=console", null, null, null, null, null, Boolean.FALSE); route = routes.getItems().stream().findAny(); } catch (ApiException e) { KubevirtAuditUtils.auditAuthorizationIssues(e, auditLogDirector, provider); log.error("failed to retrieve console url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); throw e; } if (route.isPresent()) { String host = route.get().getSpec().getHost(); String scheme = route.get().getSpec().getPort().getTargetPort(); try { return new URI(scheme, host, null, null).toString(); } catch (URISyntaxException e) { log.error("failed to retrieve console url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); throw e; } } return null; }
Source:
public void suspend() { LOG.info("Suspending the slot manager."); resourceTracker.clear(); if (taskExecutorManager != null) { taskExecutorManager.close(); for (InstanceID registeredTaskManager : taskExecutorManager.getTaskExecutors()) { unregisterTaskManager(registeredTaskManager, new SlotManagerException("The slot manager is being suspended.")); } } taskExecutorManager = null; resourceManagerId = null; resourceActions = null; started = false; }

Target:
public void suspend() { if (!started) { return; } LOG.info("Suspending the slot manager."); resourceTracker.clear(); if (taskExecutorManager != null) { taskExecutorManager.close(); for (InstanceID registeredTaskManager : taskExecutorManager.getTaskExecutors()) { unregisterTaskManager(registeredTaskManager, new SlotManagerException("The slot manager is being suspended.")); } } taskExecutorManager = null; resourceManagerId = null; resourceActions = null; started = false; }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("HttpServletRequest required"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("HttpServletResponse required"); } try { chain.doFilter(request, response); LOGGER.finer("Chain processed normally"); } catch (AuthenticationException | AccessDeniedException ex) { handleException(request, response, chain, ex); } catch (ServletException ex) { AcegiSecurityException securityException = containsAccessException(ex); if (securityException != null) { handleException(request, response, chain, (AcegiSecurityException) securityException); } else { throw ex; } } catch (IOException ex) { throw ex; } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("HttpServletRequest required"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("HttpServletResponse required"); } try { chain.doFilter(request, response); LOGGER.finer("Chain processed normally"); } catch (AuthenticationException | AccessDeniedException ex) { handleException(request, response, chain, ex); } catch (ServletException ex) { if (ex.getRootCause() instanceof AuthenticationException || ex.getRootCause() instanceof AccessDeniedException) { handleException(request, response, chain, (AcegiSecurityException) ex.getRootCause()); } else { throw ex; } } catch (IOException ex) { throw ex; } }
Source:
public ArrayList<LatLng> getGeometryObject() { List<LatLng> coordinatesList = super.getGeometryObject(); ArrayList<LatLng> coordinatesAList = new ArrayList<>(coordinatesList); return coordinatesAList; }

Target:
public ArrayList<LatLng> getGeometryObject() { List<LatLng> coordinatesList = super.getGeometryObject(); return new ArrayList<>(coordinatesList); }
Source:
public double priceFromYield(double yield, LocalDate settlementDate) { double accrualFactor = dayCount.relativeYearFraction(settlementDate, notional.getDate().getUnadjusted()); if (yieldConvention.equals(DISCOUNT)) { double price = 1.0d - accrualFactor * yield; return price; } if (yieldConvention.equals(INTEREST_AT_MATURITY) || yieldConvention.equals(FRANCE_CD) || yieldConvention.equals(JAPAN_BILLS)) { double price = 1.0d / (1.0d + accrualFactor * yield); return price; } throw new UnsupportedOperationException("The convention " + yieldConvention.name() + " is not supported."); }

Target:
public double priceFromYield(double yield, LocalDate settlementDate) { double accrualFactor = dayCount.relativeYearFraction(settlementDate, notional.getDate().getUnadjusted()); return yieldConvention.priceFromYield(yield, accrualFactor); }
Source:
public void stopJobExecution(long executionId) { String uriTemplate = resources.get("batch/executions").toString() + "/{executionId}"; restTemplate.delete(uriTemplate, Collections.singletonMap("executionId", executionId)); }

Target:
public void stopJobExecution(long executionId) { String uriTemplate = resources.get("batch/executions").toString() + "/{executionId}"; MultiValueMap<String, Object> values = new LinkedMultiValueMap<String, Object>(); values.add("executionId", executionId); restTemplate.put(uriTemplate, values, executionId); }
Source:
RemoteQueryEngine(AdvancedCache<?, ?> cache, boolean isIndexed) { super(cache, isIndexed, ProtobufMatcher.class, new ProtobufFieldBridgeAndAnalyzerProvider()); boolean indexed = cache.getCacheConfiguration().indexing().index().isEnabled(); if (indexed) { this.cache = cache.getAdvancedCache().withWrapper(ProtostreamWrapper.class); } }

Target:
RemoteQueryEngine(AdvancedCache<?, ?> cache, boolean isIndexed) { super(isIndexed ? cache.withWrapping(ByteArrayWrapper.class, ProtostreamWrapper.class) : cache, isIndexed, ProtobufMatcher.class, new ProtobufFieldBridgeAndAnalyzerProvider()); }
Source:
private static synchronized Geometry readGeometry( final String wkt, final CoordinateReferenceSystem mapCRS) throws Exception { String[] wktContents = wkt.split(";"); Geometry geom = reader.read(wktContents[wktContents.length - 1]); if (!(geom.getClass().isAssignableFrom(Polygon.class) || geom.getClass().isAssignableFrom(MultiPolygon.class))) return null; if (wktContents.length == 2 && SRID_REGEX.matcher(wktContents[0].toUpperCase()).matches()) { String sridString = wktContents[0].split("=")[1]; CoordinateReferenceSystem geomCRS = CRS.decode("EPSG:" + sridString, true); CoordinateReferenceSystem mapCRSXY = CRS.decode("EPSG:" + CRS.lookupEpsgCode(mapCRS, false), true); if (CRS.isTransformationRequired(mapCRSXY, geomCRS)) { MathTransform transform = CRS.findMathTransform(geomCRS, mapCRSXY); geom = JTS.transform(geom, transform); } } geom.setSRID(CRS.lookupEpsgCode(mapCRS, false)); return geom; }

Target:
public static synchronized Geometry readGeometry( final String wkt, final CoordinateReferenceSystem mapCRS) throws Exception { String[] wktContents = wkt.split(";"); Geometry geom = reader.read(wktContents[wktContents.length - 1]); if (!(geom.getClass().isAssignableFrom(Polygon.class) || geom.getClass().isAssignableFrom(MultiPolygon.class))) throw new ServiceException( "Clip must be a polygon or multipolygon", "InvalidParameterValue", "clip"); if (wktContents.length == 2 && SRID_REGEX.matcher(wktContents[0].toUpperCase()).matches()) { String sridString = wktContents[0].split("=")[1]; CoordinateReferenceSystem geomCRS = CRS.decode("EPSG:" + sridString, true); CoordinateReferenceSystem mapCRSXY = CRS.decode("EPSG:" + CRS.lookupEpsgCode(mapCRS, false), true); if (CRS.isTransformationRequired(mapCRSXY, geomCRS)) { MathTransform transform = CRS.findMathTransform(geomCRS, mapCRSXY); geom = JTS.transform(geom, transform); } } geom.setSRID(CRS.lookupEpsgCode(mapCRS, false)); return geom; }
Source:
Optional<BufferAndAvailability> getNextBuffer() throws IOException, InterruptedException { checkError(); BufferAndAvailability bufferAndAvailability = getNextRecoveredStateBuffer(); if (bufferAndAvailability != null) { updateMetrics(bufferAndAvailability.buffer()); return Optional.of(bufferAndAvailability); } ResultSubpartitionView subpartitionView = this.subpartitionView; if (subpartitionView == null) { if (isReleased) { return Optional.empty(); } subpartitionView = checkAndWaitForSubpartitionView(); } BufferAndBacklog next = subpartitionView.getNextBuffer(); if (next == null) { if (subpartitionView.isReleased()) { throw new CancelTaskException("Consumed partition " + subpartitionView + " has been released."); } else { return Optional.empty(); } } updateMetrics(next.buffer()); return Optional.of(new BufferAndAvailability(next.buffer(), next.isDataAvailable(), next.buffersInBacklog())); }

Target:
Optional<BufferAndAvailability> getNextBuffer() throws IOException, InterruptedException { checkError(); ResultSubpartitionView subpartitionView = this.subpartitionView; if (subpartitionView == null) { if (isReleased) { return Optional.empty(); } subpartitionView = checkAndWaitForSubpartitionView(); } BufferAndBacklog next = subpartitionView.getNextBuffer(); if (next == null) { if (subpartitionView.isReleased()) { throw new CancelTaskException("Consumed partition " + subpartitionView + " has been released."); } else { return Optional.empty(); } } numBytesIn.inc(next.buffer().getSize()); numBuffersIn.inc(); return Optional.of(new BufferAndAvailability(next.buffer(), next.isDataAvailable(), next.buffersInBacklog())); }
Source:
private void assertNoHead() throws GitAPIException { try { this.git.log().call(); fail(); } catch (NoHeadException e) { } }

Target:
private void assertNoHead() throws IOException { assertNull(db.resolve("HEAD")); }
Source:
public void shouldCreateOneAlertPerSuspiciousComment() throws HttpMalformedHeaderException, URIException { String body = "Some text <script>Some Script Element FIXME: DO something \n FIXME: DO something else </script>\nLine 2\n"; HttpMessage msg = createHttpMessageWithRespBody(body, "text/javascript;charset=ISO-8859-1"); assertTrue(msg.getResponseHeader().isText()); assertTrue(msg.getResponseHeader().isJavaScript()); scanHttpResponseReceive(msg); assertEquals(2, alertsRaised.size()); assertEquals(Alert.CONFIDENCE_LOW, alertsRaised.get(0).getConfidence()); }

Target:
public void shouldCreateOneAlertPerSuspiciousComment() throws HttpMalformedHeaderException, URIException { String body = "Some text <script>Some Script Element FIXME: DO something\nFIXME: DO something else </script>\nLine 2\n"; HttpMessage msg = createHttpMessageWithRespBody(body, "text/javascript;charset=ISO-8859-1"); assertTrue(msg.getResponseHeader().isText()); assertTrue(msg.getResponseHeader().isJavaScript()); scanHttpResponseReceive(msg); assertEquals(2, alertsRaised.size()); assertEquals(Alert.CONFIDENCE_LOW, alertsRaised.get(0).getConfidence()); assertEquals( "Some text <script>Some Script Element FIXME: DO something", alertsRaised.get(0).getEvidence()); assertEquals("FIXME: DO something else </script>", alertsRaised.get(1).getEvidence()); }
Source:
public int calculateProjectProgress() { try { ChunkPlugin chunks = project.getChunkPlugin(new ChunkPluginLoader(context)); int numChapters = chunks.numChapters(); int allChaptersProgress = 0; List<Chapter> chapters = chunks.getChapters(); for (Chapter chapter: chapters) { int chapterProgress = calculateChapterProgress(chapter); allChaptersProgress += chapterProgress; } int projectProgress = (int) Math.ceil((float) allChaptersProgress / numChapters); return projectProgress; } catch (IOException e) { Logger.i(this.toString(), e.getMessage()); } return 0; }

Target:
public int calculateProjectProgress() { int numChapters = numChapters(); int allChaptersProgress = 0; for (Chapter chapter: chapters) { int chapterProgress = calculateChapterProgress(chapter); allChaptersProgress += chapterProgress; } int projectProgress = (int) Math.ceil((float) allChaptersProgress / numChapters); return projectProgress; }
Source:
public GroupData loadFromJson(InputStream json) { GroupData groupFromFile = new GroupData(); try { gson = new Gson(); groupFromFile = gson.fromJson(new InputStreamReader(json), GroupData.class); } catch (Exception e) { groupFromFile.setGroupLabel("ERROR"); e.printStackTrace(); } return groupFromFile; }

Target:
public GroupData loadFromJson(InputStream json) { GroupData groupFromFile = new GroupData(); try { gson = new Gson(); groupFromFile = gson.fromJson(new InputStreamReader(json), GroupData.class); } catch (JsonSyntaxException e) { groupFromFile.setGroupLabel("ERROR - Syntax"); e.printStackTrace(); } catch (JsonIOException e) { groupFromFile.setGroupLabel("ERROR - IO"); e.printStackTrace(); } return groupFromFile; }
Source:
public static void showWhile(Display display, Runnable runnable) { if (runnable == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (display == null) { display = Display.getCurrent(); if (display == null) { runnable.run(); return; } } Integer busyId = Integer.valueOf(nextBusyId); nextBusyId++; Cursor cursor = display.getSystemCursor(SWT.CURSOR_WAIT); stream(display.getShells()) .filter(shell -> !shell.isDisposed() && shell.getData(BUSYID_NAME) == null) .forEach(shell -> { shell.setCursor(cursor); shell.setData(BUSYID_NAME, busyId); }); try { runnable.run(); } finally { stream(display.getShells()) .filter(shell -> !shell.isDisposed() && shell.getData(BUSYID_NAME) == busyId) .forEach(shell -> { shell.setCursor(cursor); shell.setData(BUSYID_NAME, null); }); } }

Target:
public static void showWhile(Display display, Runnable runnable) { if (runnable == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (display == null) { display = Display.getCurrent(); if (display == null) { runnable.run(); return; } } Integer busyId = Integer.valueOf(nextBusyId); nextBusyId++; Cursor cursor = display.getSystemCursor(SWT.CURSOR_WAIT); stream(display.getShells()) .filter(shell -> !shell.isDisposed() && shell.getData(BUSYID_NAME) == null) .forEach(shell -> { shell.setCursor(cursor); shell.setData(BUSYID_NAME, busyId); }); try { runnable.run(); } finally { stream(display.getShells()) .filter(shell -> !shell.isDisposed() && shell.getData(BUSYID_NAME) == busyId) .forEach(shell -> { shell.setCursor(null); shell.setData(BUSYID_NAME, null); }); } }
Source:
public void testDeserialize() throws Exception { String json = getResourceAsString("/api_fixtures/ephemeral_key.json"); EphemeralKey resource = APIResource.GSON.fromJson(json, EphemeralKey.class); assertNotNull(resource); assertEquals("ephkey_123", resource.getId()); assertEquals("ephemeral_key", resource.getObject()); }

Target:
public void testDeserialize() throws Exception { final String json = getResourceAsString("/api_fixtures/ephemeral_key.json"); final EphemeralKey resource = APIResource.GSON.fromJson(json, EphemeralKey.class); assertNotNull(resource); assertEquals("ephkey_123", resource.getId()); assertEquals("ephemeral_key", resource.getObject()); }
Source:
public void setChannelMapping(String key, String channelName) { super.setChannelMapping(key, channelName); this.classNameMappings.put(key, resolveClassFromName(key)); }

Target:
public void setChannelMapping(String key, String channelName) { super.setChannelMapping(key, channelName); Map<String, Class<?>> newClassNameMappings = new ConcurrentHashMap<String, Class<?>>(this.classNameMappings); newClassNameMappings.put(key, resolveClassFromName(key)); this.classNameMappings = newClassNameMappings; }
Source:
public String toString() { return "group " + getItemName() + " changed from " + getOldItemState().toString() + " to " + getItemState().toString() + " caused by member " + memberName; }

Target:
public String toString() { return itemName + " changed from " + oldItemState.toString() + " to " + itemState.toString() + " through " + memberName; }
Source:
public UserTermExpected(SubmitRecord.Label label) { super("A label with the status " + label.toString() + " must contain a user."); }

Target:
public UserTermExpected(SubmitRecord.Label label) { super(String.format("A label with the status %s must contain a user.", label.toString())); }
Source:
void removeHotFolder(String jobIdentifier) { FileAlterationObserver observer = _registeredHotFolders.get(jobIdentifier); _hotFolderMonitor.removeObserver(observer); try { observer.destroy(); } catch (Exception e) { logger.info("Removing hot folder trigger for job {}", jobIdentifier); } }

Target:
void removeHotFolder(String jobIdentifier) { final FileAlterationObserver observer = _registeredHotFolders.get(jobIdentifier); _hotFolderMonitor.removeObserver(observer); try { observer.destroy(); } catch (Exception e) { logger.info("Removing hot folder trigger for job {}", jobIdentifier); } }
Source:
public void testGroupByFloatColumnWithExFn() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { return; } String jsFn = "function(str) { return 'super-' + str; }"; ExtractionFn jsExtractionFn = new JavaScriptExtractionFn(jsFn, false, JavaScriptConfig.getDefault()); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec("index", "index_alias", jsExtractionFn))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults; expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", "super-158.74722290039062", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", "super-166.01605224609375", "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }

Target:
public void testGroupByFloatColumnWithExFn() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("GroupBy v1 does not support dimension selectors with unknown cardinality."); } String jsFn = "function(str) { return 'super-' + str; }"; ExtractionFn jsExtractionFn = new JavaScriptExtractionFn(jsFn, false, JavaScriptConfig.getDefault()); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec("index", "index_alias", jsExtractionFn))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults; expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", "super-158.74722290039062", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", "super-166.01605224609375", "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }
Source:
public void beforeClass(final @Optional String testType) throws IOException { if (testType.equals("buckets")) { throw new SkipException("Directory tests will be skipped in Manta Buckets"); } ConfigContext config = new IntegrationTestConfigContext(); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }

Target:
public void beforeClass(final @Optional String testType) throws IOException { if ("buckets".equals(testType)) { throw new SkipException("Directory tests will be skipped in Manta Buckets"); } ConfigContext config = new IntegrationTestConfigContext(); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }
Source:
public ZeppelinServer() throws Exception { ZeppelinConfiguration conf = ZeppelinConfiguration.create(); this.depResolver = new DependencyResolver( conf.getString(ConfVars.ZEPPELIN_INTERPRETER_LOCALREPO)); this.helium = new Helium(conf.getHeliumConfPath(), conf.getHeliumDefaultLocalRegistryPath()); this.heliumApplicationFactory = new HeliumApplicationFactory(); this.schedulerFactory = new SchedulerFactory(); this.replFactory = new InterpreterFactory(conf, notebookWsServer, notebookWsServer, heliumApplicationFactory, depResolver, SecurityUtils.isAuthenticated()); this.notebookRepo = new NotebookRepoSync(conf); this.noteSearchService = new LuceneSearch(); this.notebookAuthorization = NotebookAuthorization.init(conf); this.credentials = new Credentials(conf.credentialsPersist(), conf.getCredentialsPath()); notebook = new Notebook(conf, notebookRepo, schedulerFactory, replFactory, notebookWsServer, noteSearchService, notebookAuthorization, credentials); heliumApplicationFactory.setNotebook(notebook); heliumApplicationFactory.setApplicationEventListener(notebookWsServer); notebook.addNotebookEventListener(heliumApplicationFactory); notebook.addNotebookEventListener(notebookWsServer.getNotebookInformationListener()); remoteWorksManager = new RemoteWorksManager(notebook); replFactory.setRemoteController(remoteWorksManager.getInstance()); }

Target:
public ZeppelinServer() throws Exception { ZeppelinConfiguration conf = ZeppelinConfiguration.create(); this.depResolver = new DependencyResolver( conf.getString(ConfVars.ZEPPELIN_INTERPRETER_LOCALREPO)); this.helium = new Helium(conf.getHeliumConfPath(), conf.getHeliumDefaultLocalRegistryPath()); this.heliumApplicationFactory = new HeliumApplicationFactory(); this.schedulerFactory = new SchedulerFactory(); this.replFactory = new InterpreterFactory(conf, notebookWsServer, notebookWsServer, heliumApplicationFactory, depResolver, SecurityUtils.isAuthenticated()); this.notebookRepo = new NotebookRepoSync(conf); this.noteSearchService = new LuceneSearch(); this.notebookAuthorization = NotebookAuthorization.init(conf); this.credentials = new Credentials(conf.credentialsPersist(), conf.getCredentialsPath()); notebook = new Notebook(conf, notebookRepo, schedulerFactory, replFactory, notebookWsServer, noteSearchService, notebookAuthorization, credentials); heliumApplicationFactory.setNotebook(notebook); heliumApplicationFactory.setApplicationEventListener(notebookWsServer); notebook.addNotebookEventListener(heliumApplicationFactory); notebook.addNotebookEventListener(notebookWsServer.getNotebookInformationListener()); }
Source:
public void setup() throws MalformedURLException, NotFoundException { MockitoAnnotations.initMocks(this); singleURL = new URL("<LINK_0>"); multipURL = new URL("<LINK_2>"); otherURL = new URL("<LINK_1>"); singleComPatch = new Patch(singleId, singleURL, null, null, null); multipComPatch = new Patch(multipId, multipURL, null, null, null); otherStatPatch = new Patch(otherId, otherURL, null, null, null); org.mockito.Mockito.when(aphrodite.getCommitStatusFromPatch(singleComPatch)).thenReturn(CommitStatus.SUCCESS); org.mockito.Mockito.when(aphrodite.getCommitStatusFromPatch(multipComPatch)).thenReturn(CommitStatus.SUCCESS); org.mockito.Mockito.when(aphrodite.getCommitStatusFromPatch(otherStatPatch)).thenReturn(CommitStatus.FAILURE); }

Target:
public void setup() throws MalformedURLException, NotFoundException { MockitoAnnotations.initMocks(this); singleURL = new URL("<LINK_0>"); multipURL = new URL("<LINK_2>"); otherURL = new URL("<LINK_1>"); singleComPatch = new Patch(singleId, singleURL, null, null, null); multipComPatch = new Patch(multipId, multipURL, null, null, null); otherStatPatch = new Patch(otherId, otherURL, null, null, null); when(aphrodite.getCommitStatusFromPatch(singleComPatch)).thenReturn(CommitStatus.SUCCESS); when(aphrodite.getCommitStatusFromPatch(multipComPatch)).thenReturn(CommitStatus.SUCCESS); when(aphrodite.getCommitStatusFromPatch(otherStatPatch)).thenReturn(CommitStatus.FAILURE); }
Source:
public void testCreateExternalS3FileHandleFromExistingFile() throws Exception { assertNotNull(imageFile); assertTrue(imageFile.exists()); String md5 = MD5ChecksumHelper.getMD5Checksum(imageFile); String baseKey = "integration-test/IT049FileHandleTest/testCreateExternalS3FileHandleFromExistingFile/" + UUID.randomUUID().toString(); String key = baseKey + FILE_NAME; uploadOwnerTxtToS3(config.getS3Bucket(), baseKey, synapse.getUserProfile(userToDelete.toString()).getUserName()); synapseS3Client.putObject(config.getS3Bucket(), key, imageFile); ExternalS3StorageLocationSetting storageLocationSetting = new ExternalS3StorageLocationSetting(); storageLocationSetting.setBucket(config.getS3Bucket()); storageLocationSetting.setBaseKey(baseKey); storageLocationSetting.setUploadType(UploadType.S3); storageLocationSetting = synapse.createStorageLocationSetting(storageLocationSetting); S3FileHandle fh = new S3FileHandle(); fh.setStorageLocationId(storageLocationSetting.getStorageLocationId()); fh.setBucketName(config.getS3Bucket()); fh.setKey(key); fh.setContentMd5(md5); S3FileHandle result = synapse.createExternalS3FileHandle(fh); assertNotNull(result); toDelete.add(result); assertNotNull(result.getFileName()); }

Target:
public void testCreateExternalS3FileHandleFromExistingFile() throws Exception { assertNotNull(imageFile); assertTrue(imageFile.exists()); String md5 = MD5ChecksumHelper.getMD5Checksum(imageFile); String baseKey = "integration-test/IT049FileHandleTest/testCreateExternalS3FileHandleFromExistingFile/" + UUID.randomUUID().toString(); String key = baseKey + FILE_NAME; uploadOwnerTxtToS3(config.getS3Bucket(), baseKey, synapse.getUserProfile(userToDelete.toString()).getUserName()); putToS3WaitForConsistency(config.getS3Bucket(), key, imageFile); ExternalS3StorageLocationSetting storageLocationSetting = new ExternalS3StorageLocationSetting(); storageLocationSetting.setBucket(config.getS3Bucket()); storageLocationSetting.setBaseKey(baseKey); storageLocationSetting.setUploadType(UploadType.S3); storageLocationSetting = synapse.createStorageLocationSetting(storageLocationSetting); S3FileHandle fh = new S3FileHandle(); fh.setStorageLocationId(storageLocationSetting.getStorageLocationId()); fh.setBucketName(config.getS3Bucket()); fh.setKey(key); fh.setContentMd5(md5); S3FileHandle result = synapse.createExternalS3FileHandle(fh); assertNotNull(result); toDelete.add(result); assertNotNull(result.getFileName()); }
Source:
private void loadUrlInWebView() { if (mWebView != null) { ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService( Activity.CONNECTIVITY_SERVICE); if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) { showHideWebView(true); loadValidUrl(); } else { showHideWebView(false); mErrorDemoText.setText( translate(R.string.erro_page_text)); } } }

Target:
private void loadUrlInWebView() { if (mWebView != null) { ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService( Activity.CONNECTIVITY_SERVICE); if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) { showHideWebView(true); loadValidUrl(); } else { showHideWebView(false); mErrorDemoText.setTextTranslation(R.string.erro_page_text); } } }
Source:
public void testSingletonFlatbushXY() { List<Rectangle> items = new ArrayList<>(); items.add(new Rectangle(0, 10, 1, 11)); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); assertEquals(findIntersections(rtree, new Rectangle(1, 11, 2, 12)), items); assertEquals(findIntersections(rtree, new Rectangle(11, 1, 12, 2)), ImmutableList.of()); }

Target:
public void testSingletonFlatbushXY() { List<Rectangle> items = ImmutableList.of(new Rectangle(0, 10, 1, 11)); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); assertEquals(findIntersections(rtree, new Rectangle(1, 11, 2, 12)), items); assertEquals(findIntersections(rtree, new Rectangle(11, 1, 12, 2)), ImmutableList.of()); }
Source:
public static void checkLabelsInDiagramToolBar(SWTBotSiriusDiagramEditor editor, String toolTip, List<String> labelsToCheck) { if (labelsToCheck.isEmpty()) { return; } final SWTBotToolbarDropDownButton toolMenuButton = editor.bot().toolbarDropDownButtonWithTooltip(toolTip); List<? extends SWTBotMenu> menuItems = toolMenuButton.menuItems(WidgetMatcherFactory.widgetOfType(MenuItem.class)); SWTBotMenu menuItemRef = null; for (SWTBotMenu menuItem : menuItems) { if (labelsToCheck.contains(menuItem.getText())) { labelsToCheck.remove(menuItem.getText()); menuItemRef = menuItem; } } Assert.assertTrue("The following menu items have not been found in the " + toolTip + " toolBars contribution : " + labelsToCheck, labelsToCheck.isEmpty()); if (menuItemRef != null) { menuItemRef.click(); } try { toolMenuButton.pressShortcut(KeyStroke.getInstance("ESC")); } catch (ParseException e) { throw new RuntimeException(e); } }

Target:
public static void checkLabelsInDiagramToolBar(SWTBotSiriusDiagramEditor editor, String toolTip, List<String> labelsToCheck) { if (labelsToCheck.isEmpty()) { return; } final SWTBotToolbarDropDownButton toolMenuButton = editor.bot().toolbarDropDownButtonWithTooltip(toolTip); List<? extends SWTBotMenu> menuItems = toolMenuButton.menuItems(WidgetMatcherFactory.widgetOfType(MenuItem.class)); for (SWTBotMenu menuItem : menuItems) { if (labelsToCheck.contains(menuItem.getText())) { labelsToCheck.remove(menuItem.getText()); } } Assert.assertTrue("The following menu items have not been found in the " + toolTip + " toolBars contribution : " + labelsToCheck, labelsToCheck.isEmpty()); try { toolMenuButton.pressShortcut(KeyStroke.getInstance("ESC")); } catch (ParseException e) { throw new RuntimeException(e); } }