auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onDeleteAccountsFromGroup(Account.Id me, Collection<AccountGroupMember> removed) { List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); List<AccountGroupMemberAudit> auditUpdates = Lists.newLinkedList(); ReviewDb reviewDB = db.get(); try { for (AccountGroupMember m : removed) { AccountGroupMemberAudit audit = null; for (AccountGroupMemberAudit a : reviewDB.accountGroupMembersAudit() .byGroupAccount(m.getAccountGroupId(), m.getAccountId())) { if (a.isActive()) { audit = a; break; } } if (audit != null) { audit.removed(me, TimeUtil.nowTs()); auditUpdates.add(audit); } else { audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs()); audit.removedLegacy(); auditInserts.add(audit); } } reviewDB.accountGroupMembersAudit().update(auditUpdates); reviewDB.accountGroupMembersAudit().insert(auditInserts); } catch (OrmException e) { String header = "Cannot log delete accounts from group event performed by user "; logOrmExceptionForAccounts(me, removed, e, header); } }

Target:
public void onDeleteAccountsFromGroup(Account.Id me, Collection<AccountGroupMember> removed) { List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); List<AccountGroupMemberAudit> auditUpdates = Lists.newLinkedList(); ReviewDb reviewDB = db.get(); try { for (AccountGroupMember m : removed) { AccountGroupMemberAudit audit = null; for (AccountGroupMemberAudit a : reviewDB.accountGroupMembersAudit() .byGroupAccount(m.getAccountGroupId(), m.getAccountId())) { if (a.isActive()) { audit = a; break; } } if (audit != null) { audit.removed(me, TimeUtil.nowTs()); auditUpdates.add(audit); } else { audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs()); audit.removedLegacy(); auditInserts.add(audit); } } reviewDB.accountGroupMembersAudit().update(auditUpdates); reviewDB.accountGroupMembersAudit().insert(auditInserts); } catch (OrmException e) { logOrmExceptionForAccounts( "Cannot log delete accounts from group event performed by user", me, removed, e); } }
Source:
public void write(Collection<SinkRecord> records) { for (SinkRecord record: records) { String topic = record.topic(); int partition = record.kafkaPartition(); TopicPartition tp = new TopicPartition(topic, partition); topicPartitionWriters.get(tp).buffer(record); } if (hiveIntegration) { Iterator<Future> iterator = futures.iterator(); while (iterator.hasNext()) { try { Future future = iterator.next(); if (future.isDone()) { future.get(); iterator.remove(); } else { break; } } catch (ExecutionException e) { throw new RuntimeException(e); } catch (InterruptedException e) { } } } for (TopicPartition tp: assignment) { topicPartitionWriters.get(tp).write(); } }

Target:
public void write(Collection<SinkRecord> records) { for (SinkRecord record: records) { String topic = record.topic(); int partition = record.kafkaPartition(); TopicPartition tp = new TopicPartition(topic, partition); topicPartitionWriters.get(tp).buffer(record); } if (hiveIntegration) { Iterator<Future> iterator = hiveUpdateFutures.iterator(); while (iterator.hasNext()) { try { Future future = iterator.next(); if (future.isDone()) { future.get(); iterator.remove(); } else { break; } } catch (ExecutionException e) { throw new RuntimeException(e); } catch (InterruptedException e) { } } } for (TopicPartition tp: assignment) { topicPartitionWriters.get(tp).write(); } }
Source:
public ErrorResponse(long id, ErrorType errorType, Throwable throwable) { this.id = id; this.errorType = errorType; this.message = throwable.getMessage(); this.type = FrameType.Error; this.throwable = throwable; }

Target:
public ErrorResponse(long id, ErrorType errorType, Throwable throwable) { this(id, errorType, throwable.getMessage()); this.throwable = throwable; }
Source:
public static SWTBotTreeItem appFactoryTree() { SWTBotView appList = Util.bot.viewByTitle(AppFactoryConstants.APPLICATIONS_LIST); try { appList.bot().tree().getTreeItem("TestApplicationOne").select(); appList.bot().tree().getTreeItem("TestApplicationOne").contextMenu("Open ").click(); while (!appList.bot().tree().getTreeItem("TestApplicationOne (Opened)").isVisible()) { Util.bot.sleep(1000); } } catch (WidgetNotFoundException | TimeoutException e) { try { appList.bot().tree().getTreeItem("TestApplicationOne (Opened)").isVisible(); } catch (WidgetNotFoundException | TimeoutException erro) { Util.log.error("Application list loading failiure"); fail(); } } SWTBotTreeItem opened = appList.bot().tree().getTreeItem("TestApplicationOne (Opened)"); return opened; }

Target:
public static SWTBotTreeItem appFactoryTree() { SWTBotView appList = WorkbenchElementsValidator.bot .viewByTitle(AppFactoryConstants.APPLICATIONS_LIST); try { appList.bot().tree() .getTreeItem(AppFactoryConstants.TEST_APPLICATION_ONE) .select(); appList.bot().tree() .getTreeItem(AppFactoryConstants.TEST_APPLICATION_ONE) .contextMenu(AppFactoryConstants.OPEN).click(); while (!appList .bot() .tree() .getTreeItem( AppFactoryConstants.TEST_APPLICATION_ONE_OPENED) .isVisible()) { WorkbenchElementsValidator.bot.sleep(1000); } } catch (WidgetNotFoundException | TimeoutException e) { try { appList.bot() .tree() .getTreeItem( AppFactoryConstants.TEST_APPLICATION_ONE_OPENED) .isVisible(); } catch (WidgetNotFoundException | TimeoutException erro) { WorkbenchElementsValidator.log.error( "Application list loading failiure", e); fail(); } } SWTBotTreeItem opened = appList.bot().tree() .getTreeItem(AppFactoryConstants.TEST_APPLICATION_ONE_OPENED); return opened; }
Source:
public void testSingleDynamicFormTextInput() throws Exception { if (!endToEndTestEnabled()) { return; } try { createNewNote(); setTextOfParagraph(1, "%spark println(\"Hello \"+z.input(\"name\", \"world\")) "); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Output text is equal to value specified initially", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Hello world")); driver.findElement(By.xpath(getParagraphXPath(1) + " driver.findElement(By.xpath(getParagraphXPath(1) + " collector.checkThat("After new data in text input form, output should not change", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Hello world")); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Only after paragraph run we should see the new updated output", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Hello Zeppelin")); deleteTestNotebook(driver); } catch (Exception e) { handleException("Exception in ParagraphActionsIT while testSingleDynamicFormTextInput ", e); } }

Target:
public void testSingleDynamicFormTextInput() throws Exception { if (!endToEndTestEnabled()) { return; } try { createNewNote(); setTextOfParagraph(1, "%spark println(\"Hello \"+z.input(\"name\", \"world\")) "); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Output text is equal to value specified initially", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Hello world")); driver.findElement(By.xpath(getParagraphXPath(1) + " driver.findElement(By.xpath(getParagraphXPath(1) + " collector.checkThat("After new data in text input form, output should not be changed", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Hello world")); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Only after running the paragraph, we can see the newly updated output", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Hello Zeppelin")); deleteTestNotebook(driver); } catch (Exception e) { handleException("Exception in ParagraphActionsIT while testSingleDynamicFormTextInput ", e); } }
Source:
public ArbitraryGranularitySpec( @JsonProperty("queryGranularity") QueryGranularity queryGranularity, @JsonProperty("intervals") List<Interval> inputIntervals ) { this.queryGranularity = queryGranularity == null ? DEFAULT_QUERY_GRANULARITY : queryGranularity; this.intervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd()); if (inputIntervals == null) { inputIntervals = Lists.newArrayList(); } for (final Interval inputInterval : inputIntervals) { intervals.add(inputInterval); } final PeekingIterator<Interval> intervalIterator = Iterators.peekingIterator(intervals.iterator()); while (intervalIterator.hasNext()) { final Interval currentInterval = intervalIterator.next(); if (intervalIterator.hasNext()) { final Interval nextInterval = intervalIterator.peek(); if (currentInterval.overlaps(nextInterval)) { throw new IllegalArgumentException( String.format( "Overlapping intervals: %s, %s", currentInterval, nextInterval ) ); } } } }

Target:
public ArbitraryGranularitySpec( @JsonProperty("queryGranularity") QueryGranularity queryGranularity, @JsonProperty("intervals") List<Interval> inputIntervals ) { this.queryGranularity = queryGranularity; this.intervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd()); if (inputIntervals == null) { inputIntervals = Lists.newArrayList(); } for (final Interval inputInterval : inputIntervals) { intervals.add(inputInterval); } final PeekingIterator<Interval> intervalIterator = Iterators.peekingIterator(intervals.iterator()); while (intervalIterator.hasNext()) { final Interval currentInterval = intervalIterator.next(); if (intervalIterator.hasNext()) { final Interval nextInterval = intervalIterator.peek(); if (currentInterval.overlaps(nextInterval)) { throw new IllegalArgumentException( String.format( "Overlapping intervals: %s, %s", currentInterval, nextInterval ) ); } } } }
Source:
public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); }

Target:
public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); token = getAuthToken(admin.getEmail(), password); Group anon = groupService.findByName(context, Group.ANONYMOUS); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(anon.getID(), anon.getName()))); }
Source:
public RegionServerReportResponse replicationServerReport(RpcController controller, RegionServerReportRequest request) throws ServiceException { try { master.checkServiceStarted(); int versionNumber = 0; String version = "0.0.0"; VersionInfo versionInfo = VersionInfoUtil.getCurrentClientVersionInfo(); if (versionInfo != null) { version = versionInfo.getVersion(); versionNumber = VersionInfoUtil.getVersionNumber(versionInfo); } ClusterStatusProtos.ServerLoad sl = request.getLoad(); ServerName serverName = ProtobufUtil.toServerName(request.getServer()); ServerMetrics oldLoad = master.getReplicationServerManager().getLoad(serverName); ServerMetrics newLoad = ServerMetricsBuilder.toServerMetrics(serverName, versionNumber, version, sl); master.getReplicationServerManager().serverReport(serverName, newLoad); if (sl != null && master.metricsMaster != null) { master.metricsMaster.incrementRequests( sl.getTotalNumberOfRequests() - (oldLoad != null ? oldLoad.getRequestCount() : 0)); } } catch (IOException ioe) { throw new ServiceException(ioe); } return RegionServerReportResponse.newBuilder().build(); }

Target:
public RegionServerReportResponse replicationServerReport(RpcController controller, RegionServerReportRequest request) throws ServiceException { try { master.checkServiceStarted(); int versionNumber = 0; String version = "0.0.0"; VersionInfo versionInfo = VersionInfoUtil.getCurrentClientVersionInfo(); if (versionInfo != null) { version = versionInfo.getVersion(); versionNumber = VersionInfoUtil.getVersionNumber(versionInfo); } ClusterStatusProtos.ServerLoad sl = request.getLoad(); ServerName serverName = ProtobufUtil.toServerName(request.getServer()); ServerMetrics oldMetrics = master.getReplicationServerManager().getServerMetrics(serverName); ServerMetrics newMetrics = ServerMetricsBuilder.toServerMetrics(serverName, versionNumber, version, sl); master.getReplicationServerManager().serverReport(serverName, newMetrics); if (sl != null && master.metricsMaster != null) { master.metricsMaster.incrementRequests(sl.getTotalNumberOfRequests() - (oldMetrics != null ? oldMetrics.getRequestCount() : 0)); } } catch (IOException ioe) { throw new ServiceException(ioe); } return RegionServerReportResponse.newBuilder().build(); }
Source:
@Override public FormPage open() { return null; }

Target:
@Override public FormPage open() { driver.get(urlBuilder.getUrlForWiki() + URLsContent.USER_FORGOT_PASSWORD); return this; }
Source:
public void retriesOnExceptionTillSuccess() throws Exception { final int count = 3; final int delay = 1000; final String data = "data"; final Take take = Mockito.mock(Take.class); Mockito.when(take.act(Mockito.any(Request.class))).thenThrow( new IOException() ).thenReturn(new RsText(data)); final long startTime = System.currentTimeMillis(); final RsPrint response = new RsPrint( new TkRetry(count, delay, take).act(new RqFake(RqMethod.GET)) ); MatcherAssert.assertThat( new Long(delay), Matchers.lessThanOrEqualTo(System.currentTimeMillis() - startTime) ); MatcherAssert.assertThat( response.print(), Matchers.containsString(data) ); }

Target:
public void retriesOnExceptionTillSuccess() throws Exception { final int count = Tv.THREE; final int delay = Tv.THOUSAND; final String data = "data"; final Take take = Mockito.mock(Take.class); Mockito .when(take.act(Mockito.any(Request.class))) .thenThrow(new IOException()) .thenReturn(new RsText(data)); final long startTime = System.nanoTime(); final RsPrint response = new RsPrint( new TkRetry(count, delay, take).act(new RqFake(RqMethod.GET)) ); final long spent = System.nanoTime() - startTime; MatcherAssert.assertThat( new Long(delay - Tv.HUNDRED) * Tv.MILLION, Matchers.lessThanOrEqualTo(spent) ); MatcherAssert.assertThat( response.print(), Matchers.containsString(data) ); }
Source:
private Field findHostField(final Structure structure) { final List<Field> fields = FieldsCache.getFieldsByStructureInode(structure.getInode()); for (final Field field : fields) { if (field.getFieldType() .equals(Field.FieldType.HOST_OR_FOLDER.toString())) { return field; } } return null; }

Target:
private Field findHostField(final Structure structure) { return FieldsCache.getFieldsByStructureInode(structure.getInode()).stream() .filter(field -> field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())) .findFirst() .orElse(null); }
Source:
private Collection<BigdataURI> prepareCheckTempStore( AbstractTripleStore database, BigdataValue normalized, BigdataValue entityTimestamp ) throws IOException, RDFParseException, RDFHandlerException { final Collection<BigdataURI> toInsertEntities = new HashSet<>(); BigdataValueFactory vf = database.getValueFactory(); if (entityIds != null) { List<BigdataValue> termsToResolve = new ArrayList<>(); try (InputStream is = this.entityIds.getInputStream(); InputStreamReader isr = new InputStreamReader(decompressStream(is), StandardCharsets.UTF_8); BufferedReader r = new BufferedReader(isr)) { String entityId; while ((entityId = r.readLine()) != null) { toInsertEntities.add(vf.asValue(new URIImpl(uris.entityIdToURI(entityId)))); } } termsToResolve.add(entityTimestamp); termsToResolve.add(normalized); long termsAdded = database.getLexiconRelation().addTerms(termsToResolve.toArray( new BigdataValue[0]), termsToResolve.size(), true); Map<BigdataValue, IV> resolvedTerms = new HashMap<>(); for (BigdataValue term: termsToResolve) { if (term.getIV() != null) { resolvedTerms.put(term, term.getIV()); EntityDataUtil.assignValue(term.getIV(), term); } } int assigned = 0; for (BigdataValue term: termsToResolve) { if (term.getIV() == null) { term.setIV(resolvedTerms.get(term)); assigned++; } } log.debug("Terms added resolved {}, assigned {}", termsAdded, resolvedTerms.size(), assigned); } return toInsertEntities; }

Target:
private Collection<BigdataURI> prepareCheckTempStore( AbstractTripleStore database, BigdataValue normalized, BigdataValue entityTimestamp ) throws IOException { final Collection<BigdataURI> toInsertEntities = new HashSet<>(); BigdataValueFactory vf = database.getValueFactory(); if (entityIds != null) { List<BigdataValue> termsToResolve = new ArrayList<>(); try (InputStream is = this.entityIds.getInputStream(); InputStreamReader isr = new InputStreamReader(decompressStream(is), StandardCharsets.UTF_8); BufferedReader r = new BufferedReader(isr)) { String entityId; while ((entityId = r.readLine()) != null) { toInsertEntities.add(vf.asValue(new URIImpl(uris.entityIdToURI(entityId)))); } } termsToResolve.add(entityTimestamp); termsToResolve.add(normalized); long termsAdded = database.getLexiconRelation().addTerms(termsToResolve.toArray( new BigdataValue[0]), termsToResolve.size(), true); Map<BigdataValue, IV> resolvedTerms = new HashMap<>(); for (BigdataValue term: termsToResolve) { if (term.getIV() != null) { resolvedTerms.put(term, term.getIV()); EntityDataUtil.assignValue(term.getIV(), term); } } int assigned = 0; for (BigdataValue term: termsToResolve) { if (term.getIV() == null) { term.setIV(resolvedTerms.get(term)); assigned++; } } log.debug("Terms added resolved {}, assigned {}", termsAdded, resolvedTerms.size(), assigned); } return toInsertEntities; }
Source:
protected <E extends SQLEntity> void extendBatchQuery(SmartQuery<E> query) { if (!Traced.class.isAssignableFrom(query.getDescriptor().getType())) { throw new IllegalArgumentException("Entitis for which 'ChangeChecks' are created must implement 'Traced'."); } query.where(OMA.FILTERS.gt(Traced.TRACE.inner(TraceData.CHANGED_AT), LocalDateTime.now().minusDays(1))); }

Target:
protected <E extends SQLEntity> void extendBatchQuery(SmartQuery<E> query) { if (!Traced.class.isAssignableFrom(query.getDescriptor().getType())) { throw new IllegalArgumentException("Entities for which 'ChangeChecks' are created must implement 'Traced'."); } query.where(OMA.FILTERS.gt(Traced.TRACE.inner(TraceData.CHANGED_AT), LocalDateTime.now().minusDays(1))); }
Source:
public String[] extractPartitions(Message message) { JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload()); String result[] = { defaultDate }; if (jsonObject != null) { String messageTimestampName = mConfig.getMessageTimestampName(); String messageTimestampSeparator = mConfig.getMessageTimestampNameSeparator(); Object fieldValue = null; if (messageTimestampSeparator != null) { String[] fields = messageTimestampName.split(messageTimestampSeparator); Object finalValue = null; for (int i=0; i < fields.length; i++) { if (!jsonObject.containsKey(fields[i])) { break; } if (i < (fields.length -1)) { jsonObject = (JSONObject) jsonObject.get(fields[i]); } else { finalValue = jsonObject.get(fields[i]); } } fieldValue = finalValue; } else { fieldValue = jsonObject.get(messageTimestampName); } Object inputPattern = mConfig.getMessageTimestampInputPattern(); if (fieldValue != null && inputPattern != null) { try { SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern.toString()); SimpleDateFormat outputFormatter = new SimpleDateFormat(defaultFormatter); Date dateFormat = inputFormatter.parse(fieldValue.toString()); result[0] = "dt=" + outputFormatter.format(dateFormat); return result; } catch (Exception e) { LOG.warn("Impossible to convert date = for the input pattern = . Using date default = {}", fieldValue.toString(), inputPattern.toString(), result[0]); } } } return result; }

Target:
public String[] extractPartitions(Message message) { JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload()); String result[] = { defaultDate }; if (jsonObject != null) { Object fieldValue = getJsonFieldValue(jsonObject); Object inputPattern = mConfig.getMessageTimestampInputPattern(); if (fieldValue != null && inputPattern != null) { try { SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern.toString()); SimpleDateFormat outputFormatter = new SimpleDateFormat(defaultFormatter); Date dateFormat = inputFormatter.parse(fieldValue.toString()); result[0] = "dt=" + outputFormatter.format(dateFormat); return result; } catch (Exception e) { LOG.warn("Impossible to convert date = for the input pattern = . Using date default = {}", fieldValue.toString(), inputPattern.toString(), result[0]); } } } return result; }
Source:
private void checkTimeout() throws TimeoutException { String message = getReturnStatus().message; if ("Internal timeout occured".equals(message)) { throw new TimeoutException(message); } }

Target:
private void checkTimeout() throws TimeoutException { String message = getReturnStatus().message; if (TIMEOUT_MESSAGE.equals(message)) { throw new TimeoutException(message); } }
Source:
public String getTimeZoneId() { return "Europe/Paris"; }

Target:
public String getTimeZoneId() { return "Europe/Amsterdam"; }
Source:
public void checkWontEquivalateToBrands() { Item item = new Item(); item.setPublisher(Publisher.ARQIVA); item.setCanonicalUri("target"); Brand candidate1 = brandWithBroadcast("2500", "6500"); candidate1.setPublisher(Publisher.PA); candidate1.setCanonicalUri("candidate1"); Item candidate2 = itemWithBroadcast("4500", "5500"); candidate2.setPublisher(Publisher.PA); candidate2.setCanonicalUri("candidate2"); List<ScoredCandidates<Identified>> equivalents = ImmutableList.of( DefaultScoredCandidates.<Identified>fromSource("A Source") .addEquivalent(candidate1, Score.valueOf(5.0)) .addEquivalent(candidate2, Score.valueOf(4.8)) .build() ); EquivalenceResult equivalenceResult = resultBuilder.resultFor( item, equivalents, new DefaultDescription() ); assertTrue(equivalenceResult.strongEquivalences().values().size() == 1); }

Target:
public void checkWontEquivalateToBrands() { Item item = new Item(); item.setPublisher(Publisher.ARQIVA); item.setCanonicalUri("target"); Brand candidate1 = brandWithBroadcast( new DateTime().withHourOfDay(2), new DateTime().withHourOfDay(6) ); candidate1.setPublisher(Publisher.PA); candidate1.setCanonicalUri("candidate1"); Item candidate2 = itemWithBroadcast( new DateTime().withHourOfDay(4), new DateTime().withHourOfDay(5) ); candidate2.setPublisher(Publisher.PA); candidate2.setCanonicalUri("candidate2"); List<ScoredCandidates<Identified>> equivalents = ImmutableList.of( DefaultScoredCandidates.<Identified>fromSource("A Source") .addEquivalent(candidate1, Score.valueOf(5.0)) .addEquivalent(candidate2, Score.valueOf(4.8)) .build() ); EquivalenceResult equivalenceResult = resultBuilder.resultFor( item, equivalents, new DefaultDescription() ); assertTrue(equivalenceResult.strongEquivalences().values().size() == 1); }
Source:
private void initSocket(String host, String port) throws IOException { if (host == null || host.isEmpty()) { throw new IllegalArgumentException("host == null || host.isEmpty()"); } char firstDigit = port.charAt(0); if (firstDigit == '+' || firstDigit == '-') { throw new IllegalArgumentException("Illegal port argument " + port); } int p = 0; try { p = Integer.parseInt(port); } catch (NumberFormatException e) { throw new IllegalArgumentException("Illegal port argument " + port); } try { this.socket = new Socket(host, p); } catch (IOException e) { getErrorManager().error("Failed to establish the network connection", e, ErrorManager.OPEN_FAILURE); throw e; } super.internalSetOutputStream(new BufferedOutputStream(this.socket.getOutputStream())); }

Target:
private void initSocket(String host, String port) throws IOException { if (host == null || host.isEmpty()) { throw new IllegalArgumentException("host == null || host.isEmpty()"); } int p = 0; try { p = Integer.parsePositiveInt(port, 10); } catch (NumberFormatException e) { throw new IllegalArgumentException("Illegal port argument " + port); } try { this.socket = new Socket(host, p); } catch (IOException e) { getErrorManager().error("Failed to establish the network connection", e, ErrorManager.OPEN_FAILURE); throw e; } super.internalSetOutputStream(new BufferedOutputStream(this.socket.getOutputStream())); }
Source:
private VideoView showVideoView(final boolean show, boolean wait) { final PhoneApp app = PhoneApp.getInstance(); InCallScreen screen = app.getInCallScreenInstance(); VideoView view = (VideoView)(screen==null? null : screen.findViewById(R.id.video)); if (wait & show) { if ((screen == null) || (view == null)) { for (int i = 0; i < 10; i++) { try { Thread.sleep(100); } catch (java.lang.InterruptedException e) { } screen = app.getInCallScreenInstance(); view = (VideoView)(screen==null? null : screen.findViewById(R.id.video)); if (view != null) { break; } } } } if (view != null) { final VideoView viewf = view; screen.runOnUiThread(new Runnable() { public void run() { viewf.setVisibility(show? View.VISIBLE : View.GONE); } }); } return (show? view : null); }

Target:
private VideoView showVideoView(final boolean show, boolean wait) { final PhoneApp app = PhoneApp.getInstance(); InCallScreen screen = app.getInCallScreenInstance(); VideoView view = (VideoView) (screen == null ? null : screen.findViewById(R.id.video)); if (wait && show) { if ((screen == null) || (view == null)) { for (int i = 0; i < 10; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { } screen = app.getInCallScreenInstance(); view = (VideoView)(screen==null? null : screen.findViewById(R.id.video)); if (view != null) { break; } } } } if (view != null) { final VideoView viewf = view; screen.runOnUiThread(new Runnable() { public void run() { viewf.setVisibility(show? View.VISIBLE : View.GONE); } }); } return (show? view : null); }
Source:
public void testConvertIfTheAttemptOfObtainingBaseFileSystemConfigurationsViewThrowsIOExceptionThenCloudbreakServiceExceptionShouldComeOutside() throws IOException { String ioExceptionMessage = "Unable to obtain BaseFileSystemConfigurationsView"; IOException invokedException = new IOException(ioExceptionMessage); FileSystem sourceFileSystem = new FileSystem(); FileSystem clusterServiceFileSystem = new FileSystem(); ConfigQueryEntries configQueryEntries = new ConfigQueryEntries(); when(sourceCluster.getFileSystem()).thenReturn(sourceFileSystem); when(cluster.getFileSystem()).thenReturn(clusterServiceFileSystem); when(stackMock.getEnvironmentCrn()).thenReturn("envCredentialCRN"); when(fileSystemConfigurationProvider.fileSystemConfiguration(eq(clusterServiceFileSystem), eq(stackMock), any(), eq(new Json("")), eq(configQueryEntries))).thenThrow(invokedException); when(cmCloudStorageConfigProvider.getConfigQueryEntries()).thenReturn(configQueryEntries); assertThatCode(() -> underTest.convert(stackMock)) .isInstanceOf(CloudbreakServiceException.class) .hasMessage(ioExceptionMessage) .hasCause(invokedException); }

Target:
public void testConvertIfTheAttemptOfObtainingBaseFileSystemConfigurationsViewThrowsIOExceptionThenCloudbreakServiceExceptionShouldComeOutside() throws IOException { String ioExceptionMessage = "Unable to obtain BaseFileSystemConfigurationsView"; IOException invokedException = new IOException(ioExceptionMessage); FileSystem sourceFileSystem = new FileSystem(); FileSystem clusterServiceFileSystem = new FileSystem(); ConfigQueryEntries configQueryEntries = new ConfigQueryEntries(); when(sourceCluster.getFileSystem()).thenReturn(sourceFileSystem); when(cluster.getFileSystem()).thenReturn(clusterServiceFileSystem); when(stackMock.getEnvironmentCrn()).thenReturn("envCredentialCRN"); when(fileSystemConfigurationProvider.fileSystemConfiguration(eq(clusterServiceFileSystem), eq(stackMock), any(), eq(new Json("")), eq(configQueryEntries))).thenThrow(invokedException); when(cmCloudStorageConfigProvider.getConfigQueryEntries()).thenReturn(configQueryEntries); CloudbreakServiceException cloudbreakServiceException = assertThrows(CloudbreakServiceException.class, () -> underTest.convert(stackMock)); assertThat(cloudbreakServiceException).hasMessage(ioExceptionMessage).hasCause(invokedException); }
Source:
public void bind(String portalName, String statementName, List<Object> params, @Nullable FormatCodes.FormatCode[] resultFormatCodes) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("method=bind portalName={} statementName={} params={}", portalName, statementName, params); } PreparedStmt preparedStmt; try { preparedStmt = getSafeStmt(statementName); } catch (Throwable t) { jobsLogs.logPreExecutionFailure(UUID.randomUUID(), null, SQLExceptions.messageOf(t), sessionContext.user()); throw t; } AnalyzedStatement analyzedStatement = analyzer.unboundAnalyze( preparedStmt.parsedStatement(), sessionContext, preparedStmt.paramTypes()); Portal portal = new Portal( portalName, preparedStmt, params, analyzedStatement, resultFormatCodes); Portal oldPortal = portals.put(portalName, portal); if (oldPortal != null) { oldPortal.closeActiveConsumer(); } }

Target:
public void bind(String portalName, String statementName, List<Object> params, @Nullable FormatCodes.FormatCode[] resultFormatCodes) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("method=bind portalName={} statementName={} params={}", portalName, statementName, params); } PreparedStmt preparedStmt; try { preparedStmt = getSafeStmt(statementName); } catch (Throwable t) { jobsLogs.logPreExecutionFailure(UUID.randomUUID(), null, SQLExceptions.messageOf(t), sessionContext.user()); throw t; } AnalyzedStatement unboundStatement = preparedStmt.unboundStatement(); AnalyzedStatement analyzedStatement; if (unboundStatement == null) { try { analyzedStatement = analyzer.unboundAnalyze( preparedStmt.parsedStatement(), sessionContext, preparedStmt.paramTypes()); } catch (Throwable t) { jobsLogs.logPreExecutionFailure( UUID.randomUUID(), preparedStmt.rawStatement(), SQLExceptions.messageOf(t), sessionContext.user()); throw t; } } else { analyzedStatement = unboundStatement; } Portal portal = new Portal( portalName, preparedStmt, params, analyzedStatement, resultFormatCodes); Portal oldPortal = portals.put(portalName, portal); if (oldPortal != null) { oldPortal.closeActiveConsumer(); } }
Source:
public void deletedMarker() throws Exception { OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); List<MultiBranchProjectFactory> projectFactories = top.getProjectFactories(); assertEquals(1, projectFactories.size()); assertEquals(MockFactory.class, projectFactories.get(0).getClass()); projectFactories.add(new MockFactory()); top.getNavigators().add(new SingleSCMNavigator("stuff", Collections.<SCMSource>singletonList(new SingleSCMSource("id", "stuffy", new NullSCM())))); top.scheduleBuild2(0).getFuture().get(); top.getComputation().writeWholeLogTo(System.out); assertEquals(1, top.getItems().size()); r.waitUntilNoActivity(); MockFactory.live = false; try { top.scheduleBuild2(0).getFuture().get(); top.getComputation().writeWholeLogTo(System.out); assertEquals(0, top.getItems().size()); } finally { MockFactory.live = true; } }

Target:
public void deletedMarker() throws Exception { OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); List<MultiBranchProjectFactory> projectFactories = top.getProjectFactories(); assertEquals(1, projectFactories.size()); assertEquals(MockFactory.class, projectFactories.get(0).getClass()); top.getNavigators().add(new SingleSCMNavigator("stuff", Collections.<SCMSource>singletonList(new SingleSCMSource("id", "stuffy", new NullSCM())))); top.scheduleBuild2(0).getFuture().get(); top.getComputation().writeWholeLogTo(System.out); assertEquals(1, top.getItems().size()); r.waitUntilNoActivity(); MockFactory.live = false; try { top.scheduleBuild2(0).getFuture().get(); top.getComputation().writeWholeLogTo(System.out); assertEquals(0, top.getItems().size()); } finally { MockFactory.live = true; } }
Source:
public boolean involvesOnlyFilteredEClasses(ModelElementIdToEObjectMapping idToEObjectMapping, AbstractOperation operation) { if (operation instanceof CompositeOperation) { return compositeOperationInvolvesOnlyFilteredEClasses(idToEObjectMapping, operation); } if (isCreateDelete(operation)) { return createDeleteOperationInvolvesOnlyFilteredEClasses(operation); } final ModelElementId id = operation.getModelElementId(); final EObject modelElement = idToEObjectMapping.get(id); if (modelElement == null) { return false; } if (!isFilteredEClass(modelElement.eClass())) { return false; } if (FeatureOperation.class.isInstance(operation)) { try { final EStructuralFeature feature = FeatureOperation.class.cast(operation).getFeature(modelElement); return isFiltered(modelElement.eClass(), feature); } catch (final UnkownFeatureException ex) { return true; } } return true; }

Target:
public boolean involvesOnlyFilteredEClasses(ModelElementIdToEObjectMapping idToEObjectMapping, AbstractOperation operation) { if (isComposite(operation)) { return compositeOperationInvolvesOnlyFilteredEClasses(idToEObjectMapping, operation); } if (isCreateDelete(operation)) { return createDeleteOperationInvolvesOnlyFilteredEClasses(operation); } final ModelElementId id = operation.getModelElementId(); final EObject modelElement = idToEObjectMapping.get(id); if (modelElement == null) { return false; } if (!isFilteredEClass(modelElement.eClass())) { return false; } if (isFeature(operation)) { try { final EStructuralFeature feature = FeatureOperation.class.cast(operation).getFeature(modelElement); return isFiltered(modelElement.eClass(), feature); } catch (final UnkownFeatureException ex) { ModelUtil.log( MessageFormat.format("{0} could not access feature of a feature operation", getClass().getName()), ex, IStatus.WARNING); return true; } } return true; }
Source:
Map.Entry<Boolean, TestSuiteSummary> processSupportiveArtifacts(SynapseTestCase synapseTestCase, TestSuiteSummary testSuiteSummary) { boolean isArtifactDeployed = true; for (int x = 0; x < synapseTestCase.getArtifacts().getSupportiveArtifactCount(); x++) { if (isArtifactDeployed) { try { isArtifactDeployed = processForArtifactTypes(synapseTestCase, x); } catch (Exception e) { log.error("Supportive test artifact deployment failed", e); exception = CommonUtils.stackTraceToString(e); testSuiteSummary.setDeploymentStatus(Constants.FAILED_KEY); testSuiteSummary.setDeploymentException(exception); } } else { log.error(synapseTestCase.getArtifacts().getSupportiveArtifact(x).getArtifactType() + " main test artifact deployment failed"); break; } } return new AbstractMap.SimpleEntry<>(isArtifactDeployed, testSuiteSummary); }

Target:
Map.Entry<Boolean, TestSuiteSummary> processSupportiveArtifacts(SynapseTestCase synapseTestCase, TestSuiteSummary testSuiteSummary) { boolean isArtifactDeployed = true; for (int x = 0; x < synapseTestCase.getArtifacts().getSupportiveArtifactCount(); x++) { if (isArtifactDeployed) { try { isArtifactDeployed = processForArtifactTypes(synapseTestCase, x); } catch (Exception e) { log.error("Supportive test artifact deployment failed", e); exception = CommonUtils.stackTraceToString(e); testSuiteSummary.setDeploymentStatus(Constants.FAILED_KEY); testSuiteSummary.setDeploymentException(exception); } } else { log.error(synapseTestCase.getArtifacts().getSupportiveArtifact(x).getArtifactType() + " primary test artifact deployment failed"); break; } } return new AbstractMap.SimpleEntry<>(isArtifactDeployed, testSuiteSummary); }
Source:
public List<CloudBlobMetadata> findEntriesSince(String partitionPath, CloudFindToken findToken, long maxTotalSizeOfEntries) throws CloudStorageException { SqlQuerySpec entriesSinceQuery = new SqlQuerySpec(ENTRIES_SINCE_QUERY_TEMPLATE, new SqlParameterCollection(new SqlParameter(LIMIT_PARAM, 1000), new SqlParameter(TIME_SINCE_PARAM, findToken.getLatestUploadTime()))); try { List<CloudBlobMetadata> results = cosmosDataAccessor.queryMetadata(partitionPath, entriesSinceQuery, azureMetrics.findSinceQueryTime); if (results.isEmpty()) { return results; } long totalSize = 0; List<CloudBlobMetadata> cappedResults = new ArrayList<>(); boolean foundLastBlob = (findToken.getLatestBlobId() == null); for (CloudBlobMetadata metadata : results) { if (!foundLastBlob) { foundLastBlob = metadata.getId().equals(findToken.getLatestBlobId()); continue; } if (totalSize + metadata.getSize() > maxTotalSizeOfEntries) { if (cappedResults.isEmpty()) { cappedResults.add(metadata); } break; } cappedResults.add(metadata); totalSize += metadata.getSize(); } return cappedResults; } catch (DocumentClientException dex) { throw new CloudStorageException("Failed to query blobs for partition " + partitionPath, dex); } }

Target:
public List<CloudBlobMetadata> findEntriesSince(String partitionPath, CloudFindToken findToken, long maxTotalSizeOfEntries) throws CloudStorageException { SqlQuerySpec entriesSinceQuery = new SqlQuerySpec(ENTRIES_SINCE_QUERY_TEMPLATE, new SqlParameterCollection(new SqlParameter(LIMIT_PARAM, findSinceQueryLimit), new SqlParameter(TIME_SINCE_PARAM, findToken.getLatestUploadTime()))); try { List<CloudBlobMetadata> results = cosmosDataAccessor.queryMetadata(partitionPath, entriesSinceQuery, azureMetrics.findSinceQueryTime); if (results.isEmpty()) { return results; } long totalSize = 0; List<CloudBlobMetadata> cappedResults = new ArrayList<>(); for (CloudBlobMetadata metadata : results) { if (metadata.getId().equals(findToken.getLatestBlobId())) { continue; } if (totalSize + metadata.getSize() > maxTotalSizeOfEntries) { if (cappedResults.isEmpty()) { cappedResults.add(metadata); } break; } cappedResults.add(metadata); totalSize += metadata.getSize(); } return cappedResults; } catch (DocumentClientException dex) { throw new CloudStorageException("Failed to query blobs for partition " + partitionPath, dex); } }
Source:
public NewHostModel() { super(); setExternalHostName(new ListModel()); getExternalHostName().getSelectedItemChangedEvent().addListener(this); getExternalHostName().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly); setExternalHostProviderEnabled(new EntityModel()); setProviders(new ListModel()); getProviders().getSelectedItemChangedEvent().addListener(this); getProviders().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly); IEventListener externalHostsListener = new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { UpdateExternalHostModels(); } }; getExternalHostProviderEnabled().getEntityChangedEvent().addListener(externalHostsListener); getExternalHostProviderEnabled().setEntity(false); getExternalHostName().setIsChangable(false); }

Target:
public NewHostModel() { super(); getExternalHostName().getSelectedItemChangedEvent().addListener(this); getExternalHostName().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly); getExternalHostProviderEnabled().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly); getProviders().getSelectedItemChangedEvent().addListener(this); getProviders().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly); IEventListener externalHostsListener = new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { UpdateExternalHostModels(); } }; getExternalHostProviderEnabled().getEntityChangedEvent().addListener(externalHostsListener); getExternalHostProviderEnabled().setEntity(false); getExternalHostName().setIsChangable(false); }
Source:
protected KitodoOutputHandler() { super(beforeParentConstructor(), null, new int[] {1970, 1, 1 }, null, null); }

Target:
protected KitodoOutputHandler() { super(beforeParentConstructor(), null, EPOCH_ZERO, null, null); }
Source:
static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } FileStore s; try { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } CompletableFuture<FileStoreAttributeCache> f = CompletableFuture .supplyAsync(() -> new FileStoreAttributeCache(s, dir)); f.thenAccept(cache -> attributeCache.put(s, cache)); if (!background) { FileStoreAttributeCache e = f.get(); if (LOG.isDebugEnabled()) { LOG.debug(e.toString()); } return e.getFsTimestampResolution(); } else if (LOG.isDebugEnabled()) { f.thenAccept(cache -> LOG.debug(cache.toString())); } return FALLBACK_TIMESTAMP_RESOLUTION; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return FALLBACK_TIMESTAMP_RESOLUTION; } }

Target:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } FileStore s; try { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); if (lock.tryLock()) { try { CompletableFuture<FileStoreAttributeCache> f = CompletableFuture .supplyAsync(() -> new FileStoreAttributeCache( s, dir)); f.exceptionally(e -> { Throwable cause = e.getCause(); if (!(cause instanceof NoSuchFileException)) { LOG.error(e.getLocalizedMessage(), e); } return null; }); f.thenAccept(cache -> { if (cache != null) { attributeCache.put(s, cache); } }); if (background.get()) { if (LOG.isDebugEnabled()) { f.thenAccept( cache -> LOG.debug(cache.toString())); } } else { FileStoreAttributeCache cache = f.get(); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } return cache.getFsTimestampResolution(); } } finally { lock.unlock(); locks.remove(s); } } return FALLBACK_TIMESTAMP_RESOLUTION; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return FALLBACK_TIMESTAMP_RESOLUTION; } }
Source:
private void handleAssignmentStatement(AssignmentStatement assignmentStatement, SubscriptionContext ctx) { ExpressionList lhs = assignmentStatement.lhsExpressions().get(0); Expression expression = lhs.expressions().get(0); if (expression.is(Tree.Kind.NAME) && isCredential(((Name) expression).name(), variablePatterns())) { checkAssignedValue(assignmentStatement, ctx); } if (expression.is(Tree.Kind.QUALIFIED_EXPR) && isCredential(((QualifiedExpression) expression).name().name(), variablePatterns())) { checkAssignedValue(assignmentStatement, ctx); } if (expression.is(Tree.Kind.SUBSCRIPTION)) { SubscriptionExpression subscriptionExpression = (SubscriptionExpression) expression; if (subscriptionExpression.subscripts().expressions().stream().anyMatch(e -> e.is(Tree.Kind.STRING_LITERAL) && isCredential(((StringLiteral) e).trimmedQuotesValue(), variablePatterns()))) { checkAssignedValue(assignmentStatement, ctx); } } }

Target:
private void handleAssignmentStatement(AssignmentStatement assignmentStatement, SubscriptionContext ctx) { ExpressionList lhs = assignmentStatement.lhsExpressions().get(0); Expression expression = lhs.expressions().get(0); if (expression instanceof HasSymbol) { Symbol symbol = ((HasSymbol) expression).symbol(); if (isSymbolCredential(symbol)) { checkAssignedValue(assignmentStatement, ctx); } } if (expression.is(Kind.SUBSCRIPTION)) { SubscriptionExpression subscriptionExpression = (SubscriptionExpression) expression; if (subscriptionExpression.subscripts().expressions().stream().anyMatch(e -> e.is(Kind.STRING_LITERAL) && isCredential(((StringLiteral) e).trimmedQuotesValue(), variablePatterns()))) { checkAssignedValue(assignmentStatement, ctx); } } }
Source:
public void testGenerateDroolsTestOption() { ScoreDirectorFactoryConfig config = new ScoreDirectorFactoryConfig(); assertThat(config.isGenerateDroolsTestOnError()).isNull(); config.setGenerateDroolsTestOnError(true); assertThat((boolean) config.isGenerateDroolsTestOnError()).isTrue(); config.setGenerateDroolsTestOnError(Boolean.FALSE); assertThat((boolean) config.isGenerateDroolsTestOnError()).isFalse(); config.setGenerateDroolsTestOnError(null); assertThat(config.isGenerateDroolsTestOnError()).isNull(); }

Target:
public void testGenerateDroolsTestOption() { ScoreDirectorFactoryConfig config = new ScoreDirectorFactoryConfig(); assertThat(config.isGenerateDroolsTestOnError()).isNull(); config.setGenerateDroolsTestOnError(true); assertThat(config.isGenerateDroolsTestOnError()).isTrue(); config.setGenerateDroolsTestOnError(Boolean.FALSE); assertThat(config.isGenerateDroolsTestOnError()).isFalse(); config.setGenerateDroolsTestOnError(null); assertThat(config.isGenerateDroolsTestOnError()).isNull(); }
Source:
public RadioButtonItem(String name, ToggleGroup group, int i) { nameOfButton = name; but = new RadioButton(name); but.setToggleGroup(group); but.setCursor(Cursor.CLOSED_HAND); but.setText(name); but.setFont(Font.font(" ", FontWeight.BOLD, 14)); but.setTextFill(Color.ANTIQUEWHITE); but.setTextAlignment(TextAlignment.LEFT); if (i == 1) { but.setSelected(true); } getChildren().addAll(but); }

Target:
public RadioButtonItem(String name, ToggleGroup group, int i) { nameOfButton = name; butItem = new RadioButton(name); butItem.setToggleGroup(group); butItem.setCursor(Cursor.CLOSED_HAND); butItem.setText(name); butItem.setFont(Font.font(" ", FontWeight.BOLD, 14)); butItem.setTextFill(Color.ANTIQUEWHITE); butItem.setTextAlignment(TextAlignment.LEFT); if (i == 1) { butItem.setSelected(true); } getChildren().addAll(butItem); }
Source:
protected boolean canDoAction() { if (getNic() == null) { return failCanDoAction(VdcBllMessages.HOST_NETWORK_INTERFACE_NOT_EXIST); } if (getNic().getLabels() != null && getNic().getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.INTERFACE_ALREADY_LABELED); } if (!ValidationUtils.validateInputs(getValidationGroups(), getNic()).isEmpty()) { return failCanDoAction(VdcBllMessages.IMPROPER_INTERFACE_IS_LABELED); } for (VdsNetworkInterface nic : getHostInterfaces()) { if (!StringUtils.equals(nic.getName(), getNicName()) && nic.getLabels() != null && nic.getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.OTHER_INTERFACE_ALREADY_LABELED, "$LabeledNic " + nic.getName()); } } List<String> assignedNetworks = validateNetworksNotAssignedToIncorrectNics(); if (!assignedNetworks.isEmpty()) { return failCanDoAction(VdcBllMessages.LABELED_NETWORK_ATTACHED_TO_WRONG_INTERFACE, "$AssignedNetworks " + StringUtils.join(assignedNetworks.toArray(new String[assignedNetworks.size()]), ", ")); } return true; }

Target:
protected boolean canDoAction() { if (getNic() == null) { return failCanDoAction(VdcBllMessages.HOST_NETWORK_INTERFACE_NOT_EXIST); } if (getNic().getLabels() != null && getNic().getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.INTERFACE_ALREADY_LABELED); } if (!ValidationUtils.validateInputs(getValidationGroups(), getNic()).isEmpty()) { return failCanDoAction(VdcBllMessages.IMPROPER_INTERFACE_IS_LABELED); } for (VdsNetworkInterface nic : getHostInterfaces()) { if (!StringUtils.equals(nic.getName(), getNicName()) && nic.getLabels() != null && nic.getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.OTHER_INTERFACE_ALREADY_LABELED, "$LabeledNic " + nic.getName()); } } List<String> assignedNetworks = validateNetworksNotAssignedToIncorrectNics(); if (!assignedNetworks.isEmpty()) { return failCanDoAction(VdcBllMessages.LABELED_NETWORK_ATTACHED_TO_WRONG_INTERFACE, "$AssignedNetworks " + StringUtils.join(assignedNetworks, ", ")); } return true; }