auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static PCollection<Read> getReadsFromAPI() throws IOException { final String rgsId = pipelineOptions.getReadGroupSetId(); LOG.info("Sharded reading of ReadGroupSet: " + rgsId); List<StreamReadsRequest> requests = Lists.newArrayList(); if (pipelineOptions.isAllReferences()) { requests.addAll(ShardUtils.getReadRequests(rgsId, SexChromosomeFilter.INCLUDE_XY, pipelineOptions.getBasesPerShard(), auth)); } else { requests.addAll( ShardUtils.getReadRequests(Collections.singletonList(rgsId), pipelineOptions.getReferences(), pipelineOptions.getBasesPerShard())); } LOG.info("Reading form the API with: "+ requests.size() + " shards"); PCollection<Read> reads = pipeline.apply(Create.of(requests)) .apply(new ReadStreamer(auth, ShardBoundary.Requirement.STRICT, null)); return reads; }

Target:
private static PCollection<Read> getReadsFromAPI() throws IOException { final String rgsId = pipelineOptions.getReadGroupSetId(); LOG.info("Sharded reading of ReadGroupSet: " + rgsId); List<StreamReadsRequest> requests = Lists.newArrayList(); if (pipelineOptions.isAllReferences()) { requests.addAll(ShardUtils.getReadRequests(rgsId, SexChromosomeFilter.INCLUDE_XY, pipelineOptions.getBasesPerShard(), auth)); } else { requests.addAll( ShardUtils.getReadRequests(Collections.singletonList(rgsId), pipelineOptions.getReferences(), pipelineOptions.getBasesPerShard())); } LOG.info("Reading from the API with: " + requests.size() + " shards"); PCollection<Read> reads = pipeline.apply(Create.of(requests)) .apply(new ReadStreamer(auth, ShardBoundary.Requirement.STRICT, null)); return reads; }
Source:
private Region resolveRegion(String id) throws IOException { ChannelGroup<?> channelGroup = resolveChannelGroup(id); if (channelGroup instanceof Platform) { return (Region) channelGroup; } else { Throwables.propagate(new NotAcceptableException( String.format( "%s is a channel group of type '%s', should be 'region", id, channelGroup ) )); return null; } }

Target:
private Region resolveRegion(String id) throws IOException { ChannelGroup<?> channelGroup = resolveChannelGroup(id); if (channelGroup instanceof Region) { return (Region) channelGroup; } else { throw new RuntimeException(new NotAcceptableException( String.format( "%s is a channel group of type '%s', should be 'region", id, channelGroup ) )); } }
Source:
public BaseShadowSystem (NearFarAnalyzer nearFarAnalyzer, ShadowMapAllocator allocator, DirectionalAnalyzer directionalAnalyzer, LightFilter lightFilter) { this.nearFarAnalyzer = nearFarAnalyzer; this.allocator = allocator; this.directionalAnalyzer = directionalAnalyzer; this.lightFilter = lightFilter; frameBuffers = new FrameBuffer[getPassQuantity()]; passShaderProviders = new ShaderProvider[getPassQuantity()]; init(); }

Target:
public BaseShadowSystem (NearFarAnalyzer nearFarAnalyzer, ShadowMapAllocator allocator, DirectionalAnalyzer directionalAnalyzer, LightFilter lightFilter) { this.nearFarAnalyzer = nearFarAnalyzer; this.allocator = allocator; this.directionalAnalyzer = directionalAnalyzer; this.lightFilter = lightFilter; }
Source:
public static Long getWSClientConnectionTimeout() throws Exception { String defaultTimeout = "60000"; String inputTimeout = System.getProperty(WS_CLIENT_CONNECTION_TIME_VALUE); if (inputTimeout != null) { try { long timeout = Long.parseLong(inputTimeout); if (timeout > 0) { return new Long(inputTimeout); } } catch (Exception exception) { throw new RuntimeException("Webservice client connection timeout value '" + inputTimeout + "' is invalid", exception); } } return new Long(defaultTimeout); }

Target:
public static int getWSClientConnectionTimeout() throws Exception { int defaultTimeout = 60000; String inputTimeout = System.getProperty(WS_CLIENT_CONNECTION_TIME_VALUE); if (inputTimeout != null) { try { int timeout = Integer.parseInt(inputTimeout); if (timeout > 0) { return timeout; } } catch (Exception exception) { throw new RuntimeException("Webservice client connection timeout value '" + inputTimeout + "' is invalid", exception); } } return defaultTimeout; }
Source:
public void fireEvent(ExecEvent eo) { List<ISessionEventListener> v; synchronized (this) { if (_listeners.size() == 0) { return; } v = new ArrayList<>(_listeners); } for (Object aV : v) { ISessionEventListener target = (ISessionEventListener) aV; try { target.sessionUpdate(eo); } catch (Exception ex) { LOG.log(Level.SEVERE, "Couldn't invoke method sessionUpdate() on " + target, ex); } } }

Target:
public void fireEvent(ExecEvent eo) { List<ISessionEventListener> v; synchronized (this) { if (_listeners.size() == 0) { return; } v = new ArrayList<>(_listeners); } for (ISessionEventListener target : v) { try { target.sessionUpdate(eo); } catch (Exception ex) { LOG.log(Level.SEVERE, "Couldn't invoke method sessionUpdate() on " + target, ex); } } }
Source:
public static <T> T getParameterValue(final WorkflowActionClassParameter parameter) { T paramValue = null; try { paramValue = (T) parameter.getValue(); } catch (Exception e) { } return paramValue; }

Target:
public static <T> T getParameterValue(final WorkflowActionClassParameter parameter) { T paramValue = null; try { if (null != parameter && UtilMethods.isSet(parameter.getValue())) { paramValue = (T) parameter.getValue(); } } catch (Exception e) { Logger.debug(WorkflowActionletUtil.class, "Value of parameter '" + parameter.getId() + "' could not be returned.", e); } return paramValue; }
Source:
private static String toHostName(String inetAddressStringRepresentation) { try { String[] parts = inetAddressStringRepresentation.split("/"); String ip = parts[parts.length - 1]; InetAddress addr = InetAddress.getByName(ip); return addr.getHostName(); } catch (UnknownHostException e) { return inetAddressStringRepresentation; } }

Target:
private static String toHostName(String inetAddressStringRepresentation) { String[] parts = inetAddressStringRepresentation.split("/"); String ip = parts[parts.length - 1]; try { InetAddress addr = InetAddress.getByName(ip); return addr.getHostName(); } catch (UnknownHostException e) { return inetAddressStringRepresentation; } }
Source:
private void syncLunsForBlockStorageDomains() { Collection<VDS> hosts = new LinkedList<>(vdsDao.getAllForStoragePoolAndStatus( getStoragePool().getId(), VDSStatus.Up)); if (hosts.isEmpty()) { return; } Collection<StorageDomain> unSyncedStorageDomains = syncLunsForStorageDomains(storageDomainDao.getAllForStoragePool(getStoragePoolId()), hosts); if (!unSyncedStorageDomains.isEmpty()) { String unSyncedStorageDomainsList = unSyncedStorageDomains.stream() .map(StorageDomain::getId) .map(Guid::toString) .collect(Collectors.joining(", ")); addCustomValue("StorageDomainsIds", unSyncedStorageDomainsList); auditLogDirector.log(this, AuditLogType.STORAGE_DOMAINS_COULD_NOT_BE_SYNCED); } }

Target:
private void syncLunsForBlockStorageDomains() { if (getOldStoragePool().getCompatibilityVersion().lessOrEquals(Version.v4_0) && getStoragePool().getCompatibilityVersion().greaterOrEquals(Version.v4_1)) { Collection<StorageDomain> unSyncedStorageDomains = syncLunsForStorageDomains(storageDomainDao.getAllForStoragePool(getStoragePoolId())); if (!unSyncedStorageDomains.isEmpty()) { String unSyncedStorageDomainsList = unSyncedStorageDomains.stream() .map(StorageDomain::getId) .map(Guid::toString) .collect(Collectors.joining(", ")); addCustomValue("StorageDomainsIds", unSyncedStorageDomainsList); auditLogDirector.log(this, AuditLogType.STORAGE_DOMAINS_COULD_NOT_BE_SYNCED); } } }
Source:
public Map<String, Integer> getNumberOpenedSockets() { Map<String, Integer> numberOpenedSocketByUri = new LinkedHashMap<>(); for (Map.Entry<String, List<Socket>> socketByUri : socketsByUri.entrySet()) { numberOpenedSocketByUri.put(socketByUri.getKey(), socketByUri.getValue().size()); } return numberOpenedSocketByUri; }

Target:
public Map<String, Integer> getNumberOpenedSockets() { Map<String, Integer> numberOpenedSocketByUri = new LinkedHashMap<>(); synchronized (this) { for (Map.Entry<String, List<Socket>> socketByUri : socketsByUri.entrySet()) { numberOpenedSocketByUri.put(socketByUri.getKey(), socketByUri.getValue().size()); } } return numberOpenedSocketByUri; }
Source:
private void onPreviewImage(DocDisplay docDisplay, String href, Position position, Range tokenRange) { String srcPath = href; if (!href.startsWith("http")) { srcPath = href.startsWith("~/") ? "files/" + href.substring(2) : "file_show?path=" + StringUtil.encodeURIComponent(href); } String encoded = StringUtil.encodeURIComponent(srcPath); Element el = Document.get().getElementById(encoded); if (el != null) return; ImageElement imgEl = Document.get().createImageElement(); imgEl.setAttribute("src", srcPath); imgEl.getStyle().setProperty("maxWidth", "100px"); ScreenCoordinates coordinates = docDisplay.documentPositionToScreenCoordinates(position); AnchoredPopupPanel panel = new AnchoredPopupPanel(docDisplay, tokenRange); panel.getElement().setId(encoded); panel.getElement().appendChild(imgEl); panel.setPopupPosition(coordinates.getPageX(), coordinates.getPageY() + 20); panel.show(); }

Target:
private void onPreviewImage(DocDisplay docDisplay, String href, Position position, Range tokenRange) { String srcPath = imgSrcPathFromHref(href); String encoded = StringUtil.encodeURIComponent(srcPath); Element el = Document.get().getElementById(encoded); if (el != null) return; AnchoredPopupPanel panel = new AnchoredPopupPanel(docDisplay, tokenRange, srcPath); panel.getElement().setId(encoded); ScreenCoordinates coordinates = docDisplay.documentPositionToScreenCoordinates(position); panel.setPopupPosition(coordinates.getPageX(), coordinates.getPageY() + 20); panel.show(); }
Source:
public boolean isUnset(String key) { Attribute a = map.get(key); return a != null ? a.getState() == State.UNSET : false; }

Target:
public boolean isUnset(String key) { return (getState(key) == State.UNSET); }
Source:
protected String gatherRevision(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(true, event); try { final RevWalk walk = new RevWalk(repository); ObjectId commitId = repository.resolve(repository.getFullBranch()); RevCommit commit = walk.parseCommit(commitId); int parentCount = commit.getParentCount(); if (parentCount == 0) { MessageDialog .openError( getShell(event), UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogTitle, UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogMessage); throw new OperationCanceledException(); } else if (parentCount > 1) { List<RevCommit> commits = new ArrayList<RevCommit>(); for (int i = 0; i < parentCount; i++) commits.add(walk.parseCommit(commit.getParent(i))); CommitSelectDialog dlg = new CommitSelectDialog( getShell(event), commits); if (dlg.open() == Window.OK) return dlg.getSelectedCommit().getName(); else throw new OperationCanceledException(); } else return commit.getParent(0).getName(); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } }

Target:
protected String gatherRevision(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(true, event); IResource[] resources = getSelectedResources(event); if (resources.length != 1) throw new ExecutionException( "Unexpected number of selected Resources"); try { List<RevCommit> previousCommits = findPreviousCommits(repository, resources[0]); int parentCount = previousCommits.size(); if (parentCount == 0) { MessageDialog .openError( getShell(event), UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogTitle, UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogMessage); throw new OperationCanceledException(); } else if (parentCount > 1) { CommitSelectDialog dlg = new CommitSelectDialog( getShell(event), previousCommits); if (dlg.open() == Window.OK) return dlg.getSelectedCommit().getName(); else throw new OperationCanceledException(); } else return previousCommits.get(0).getName(); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } }
Source:
private boolean addToResources(OffHeapResourceIdentifier identifier, long capacityInBytes) { boolean added = resources.putIfAbsent(identifier, createOffheapResource(identifier, capacityInBytes)) == null; if (added) { updateConfiguredOffheap(capacityInBytes); } return added; }

Target:
private boolean addToResources(OffHeapResourceIdentifier identifier, long capacityInBytes) { AtomicBoolean status = new AtomicBoolean(); resources.computeIfAbsent(identifier, (id) -> { status.compareAndSet(false, true); OffHeapResourceImpl offHeapResource = new OffHeapResourceImpl( identifier.getName(), capacityInBytes, (res, update) -> { for (EntityManagementRegistry registry : registries) { Map<String, String> attrs = new HashMap<>(); attrs.put("oldThreshold", String.valueOf(update.old)); attrs.put("threshold", String.valueOf(update.now)); attrs.put("capacity", String.valueOf(res.capacity())); attrs.put("available", String.valueOf(res.available())); registry.pushServerEntityNotification(res.getManagementBinding(), "OFFHEAP_RESOURCE_THRESHOLD_REACHED", attrs); } }, (res, oldCapacity, newCapacity) -> { updateConfiguredOffheap(newCapacity - oldCapacity); for (EntityManagementRegistry registry : registries) { Map<String, String> attrs = new HashMap<>(); attrs.put("oldCapacity", Long.toString(oldCapacity)); attrs.put("newCapacity", Long.toString(newCapacity)); registry.pushServerEntityNotification(res.getManagementBinding(), "OFFHEAP_RESOURCE_CAPACITY_CHANGED", attrs); } } ); Map<String, Object> properties = new HashMap<>(); properties.put("discriminator", "OffHeapResource"); properties.put("offHeapResourceIdentifier", identifier.getName()); StatisticsManager.createPassThroughStatistic( offHeapResource, "allocatedMemory", new HashSet<>(Arrays.asList("OffHeapResource", "tier")), properties, StatisticType.GAUGE, () -> offHeapResource.capacity() - offHeapResource.available() ); updateConfiguredOffheap(capacityInBytes); return offHeapResource; }); return status.get(); }
Source:
public BlobUtils(AzureClient client, String containerName, String blobName, long length) { this.blobClient = client.getBlobClient(); try { this.container = blobClient.getContainerReference(containerName); container.createIfNotExists(); this.blob = container.getPageBlobReference(blobName); if (!blob.exists()) { blob.create(length); } } catch (URISyntaxException e) { LOG.error("Container name: " + containerName + " or blob name: " + blobName + " invalid.", e); throw new AzureException(e); } catch (StorageException e) { LOG.error("Azure Storage Exception!", e); throw new AzureException(e); } }

Target:
public BlobUtils(AzureClient client, String containerName, String blobName, long length) { this.blobClient = client.getBlobClient(); try { this.container = blobClient.getContainerReference(containerName); container.createIfNotExists(); this.blob = container.getPageBlobReference(blobName); if (!blob.exists()) { blob.create(length, AccessCondition.generateIfNotExistsCondition(), null, null); } } catch (URISyntaxException e) { LOG.error("Container name: " + containerName + " or blob name: " + blobName + " invalid.", e); throw new AzureException(e); } catch (StorageException e) { int httpStatusCode = e.getHttpStatusCode(); if (httpStatusCode == HttpStatus.CONFLICT_409) { LOG.info("The blob you're trying to create exists already.", e); } else { LOG.error("Azure Storage Exception!", e); throw new AzureException(e); } } }
Source:
public void editFeedbackResponseComment(String commentIdSuffix, String newCommentText) { executeScript("scroll(0,300)"); WebElement commentRow = waitForElementPresence(By.id("responseCommentRow" + commentIdSuffix)); click(commentRow.findElements(By.tagName("a")).get(1)); WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + commentIdSuffix)); fillRichTextEditor("responsecommenttext" + commentIdSuffix, newCommentText); click(commentEditForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a"))); ThreadHelper.waitFor(1000); }

Target:
public void editFeedbackResponseComment(String commentIdSuffix, String newCommentText) { WebElement commentRow = waitForElementPresence(By.id("responseCommentRow" + commentIdSuffix)); click(commentRow.findElements(By.tagName("a")).get(1)); WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + commentIdSuffix)); fillRichTextEditor("responsecommenttext" + commentIdSuffix, newCommentText); click(commentEditForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a"))); ThreadHelper.waitFor(1000); }
Source:
private static void runCheckCodeStyle(Map<String, Path> paths) { Optional<ValidationResult> validationResult = executor.runCheckCodeStyle(paths.get(EXERCISE_PATH)); if (validationResult.isPresent()) { JsonWriter.writeObjectIntoJsonFormat(validationResult.get(), paths.get(OUTPUT_PATH)); System.out.println("Codestyle report can be found at " + paths.get(OUTPUT_PATH)); } else { System.out.println("ERROR: Something went wrong, could not output validation result!"); } }

Target:
private static void runCheckCodeStyle(Map<String, Path> paths) { ValidationResult validationResult = null; try { validationResult = executor.runCheckCodeStyle(paths.get(EXERCISE_PATH)); } catch (NoLanguagePluginFoundException e) { printErrAndExit("ERROR: Could not find suitable language plugin for the given exercise path."); } try { JsonWriter.writeObjectIntoJsonFormat(validationResult, paths.get(OUTPUT_PATH)); System.out.println("Codestyle report can be found at " + paths.get(OUTPUT_PATH)); } catch (IOException e) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Could not write result into given output file", e); printErrAndExit("ERROR: Could not write the results to the given file."); } }
Source:
public void testExcludeTable() throws Exception { MaxwellAbstractRowsEvent e; List<RowMap> list; MaxwellFilter filter = new MaxwellFilter(); filter.excludeTable("minimal"); list = getRowsForSQL(filter, insertSQL, createDBs); assertThat(list.size(), is(1)); assertThat(list.get(0).getTable(), is("bars")); }

Target:
public void testExcludeTable() throws Exception { List<RowMap> list; MaxwellFilter filter = new MaxwellFilter(); filter.excludeTable("minimal"); list = getRowsForSQL(filter, insertSQL, createDBs); assertThat(list.size(), is(1)); assertThat(list.get(0).getTable(), is("bars")); }
Source:
public static void execShell(String command) { String[] args = { "/system/bin/sh", "-c", command }; try { Libcore.os.execv("/system/bin/sh", args); } catch (ErrnoException e) { throw new RuntimeException(e); } }

Target:
public static void execShell(String command) { String[] args = { "/system/bin/sh", "-c", command }; try { Libcore.os.execv(args[0], args); } catch (ErrnoException e) { throw new RuntimeException(e); } }
Source:
private boolean read(ByteBuffer buffer, boolean canTruncate) throws IOException { do { try { int read = m_fc.read(buffer); if (read == -1) { String message = "EOF encountered reading " + m_file + " at position " + m_fc.position() + " expected to be able to read " + buffer.remaining() + " more bytes"; if (canTruncate) { LOG.warn(message); truncateToCurrentReadIndex(); return false; } throw new EOFException(message); } } catch (IOException e) { if (canTruncate) { LOG.warn("Error encountered reading: " + m_file, e); return false; } throw new IOException("Error encountered reading: " + m_file, e); } } while (buffer.hasRemaining()); return true; }

Target:
private boolean read(ByteBuffer buffer, boolean canTruncate) throws IOException { do { try { int read = m_fc.read(buffer); if (read == -1) { String message = "EOF encountered reading " + m_file + " at position " + m_fc.position() + " expected to be able to read " + buffer.remaining() + " more bytes"; if (canTruncate) { LOG.warn(message); truncateToCurrentReadIndex(); return false; } throw new EOFException(message); } } catch (IOException e) { if (canTruncate) { LOG.warn("Error encountered reading: " + m_file, e); truncateToCurrentReadIndex(); return false; } throw new IOException("Error encountered reading: " + m_file, e); } } while (buffer.hasRemaining()); return true; }
Source:
public void deleteAllMetadataRecords(String prefix) { }

Target:
public void deleteAllMetadataRecords(String prefix) { Iterator<DataStore> iter = delegateHandler.getAllDelegatesIterator(); while (iter.hasNext()) { DataStore ds = iter.next(); if (ds instanceof SharedDataStore) { ((SharedDataStore) ds).deleteAllMetadataRecords(prefix); } } }
Source:
public boolean remove(String oxdId) { try { RpObject rpFromPersistance = getRpObject(oxdId, new String[0]); this.persistenceEntryManager.remove(rpFromPersistance); LOG.debug("Removed rp successfully. oxdId: ", oxdId); return true; } catch (Exception e) { LOG.error("Failed to remove rp with oxdId: ", oxdId, e); } return false; }

Target:
public boolean remove(String oxdId) { try { this.persistenceEntryManager.remove(getDnForRp(oxdId)); LOG.debug("Removed rp successfully. oxdId: ", oxdId); return true; } catch (Exception e) { LOG.error("Failed to remove rp with oxdId: ", oxdId, e); } return false; }
Source:
public void copyAllLeftToRight(Iterable<? extends Diff> differences, Monitor monitor) { long start = 0; if (LOGGER.isDebugEnabled()) { start = System.currentTimeMillis(); LOGGER.debug("copyAllLeftToRight(differences, monitor) - Start"); } ComputeDiffsToMerge computer = new ComputeDiffsToMerge(false, registry, null); for (Diff diff : Iterables.filter(differences, filter)) { if (!AbstractMerger.isInTerminalState(diff)) { Set<Diff> diffsToMerge = computer.getAllDiffsToMergeFor(diff); for (Diff toMerge : diffsToMerge) { if (!AbstractMerger.isInTerminalState(toMerge)) { final IMerger merger = registry.getHighestRankingMerger(toMerge); if (LOGGER.isDebugEnabled()) { LOGGER.debug("copyAllLeftToRight - Selected merger: " + merger.getClass().getSimpleName()); } merger.copyLeftToRight(toMerge, monitor); } } } } if (LOGGER.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; LOGGER.debug("copyAllLeftToRight(differences, monitor) - Stop - Time spent: " + duration + "ms"); } }

Target:
public void copyAllLeftToRight(Iterable<? extends Diff> differences, Monitor monitor) { long start = 0; if (LOGGER.isDebugEnabled()) { start = System.currentTimeMillis(); LOGGER.debug("copyAllLeftToRight(differences, monitor) - Start"); } ComputeDiffsToMerge computer = new ComputeDiffsToMerge(false, registry); for (Diff diff : Iterables.filter(differences, filter)) { if (!AbstractMerger.isInTerminalState(diff)) { Set<Diff> diffsToMerge = computer.getAllDiffsToMerge(diff); for (Diff toMerge : diffsToMerge) { if (!AbstractMerger.isInTerminalState(toMerge)) { final IMerger merger = registry.getHighestRankingMerger(toMerge); if (LOGGER.isDebugEnabled()) { LOGGER.debug("copyAllLeftToRight - Selected merger: " + merger.getClass().getSimpleName()); } merger.copyLeftToRight(toMerge, monitor); } } } } if (LOGGER.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; LOGGER.debug("copyAllLeftToRight(differences, monitor) - Stop - Time spent: " + duration + "ms"); } }
Source:
public long getBucketStartTime(int index) { return fFirstBucketTime + (long) (index * fBucketDuration + .5); }

Target:
public long getBucketStartTime(int index) { return fFirstBucketTime + (long) (index * fBucketDuration); }
Source:
public void updateToManyRelation(DataStoreTransaction relationTx, Object entity, String relationName, Set<Object> newRelationships, Set<Object> deletedRelationships, RequestScope scope) { relationTx = getRelationTransaction(entity, relationName); DataStoreTransaction entityTransaction = getTransaction(getType(entity.getClass())); entityTransaction.updateToManyRelation(relationTx, entity, relationName, newRelationships, deletedRelationships, scope); }

Target:
public void updateToManyRelation(DataStoreTransaction relationTx, Object entity, String relationName, Set<Object> newRelationships, Set<Object> deletedRelationships, RequestScope scope) { relationTx = getRelationTransaction(entity, relationName); DataStoreTransaction entityTransaction = getTransaction(EntityDictionary.getType(entity)); entityTransaction.updateToManyRelation(relationTx, entity, relationName, newRelationships, deletedRelationships, scope); }
Source:
public void addMembershipToCohort_shouldAddMembershipToCohort() throws Exception { executeDataSet(COHORT_XML); CohortMembership memberToAdd = new CohortMembership(new Patient(4)); service.addMembershipToCohort(service.getCohort(1), memberToAdd); assertTrue(service.getCohort(1).contains(memberToAdd)); }

Target:
public void addMembershipToCohort_shouldAddMembershipToCohort() throws Exception { executeDataSet(COHORT_XML); Patient p = new Patient(4); CohortMembership memberToAdd = new CohortMembership(p); service.addMembershipToCohort(service.getCohort(1), memberToAdd); assertTrue(service.getCohort(1).contains(p)); }
Source:
public String executeSupportRequest(HttpUriRequest request) throws OpenStackException { log.debug("executeSupportRequest " + request.getURI().toString()); CloseableHttpClient httpClient = getHttpClient(); HttpResponse response = null; String result = null; try { response = httpClient.execute(request); log.debug("Status : " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == http_code_ok) { InputStream is = response.getEntity().getContent(); result = convertStreamToString(is); log.debug("Result " + result); is.close(); response.getEntity().getContent().close(); } } catch (Exception e) { log.warn("Error in the request, message:" + e.getMessage()); if (response.getStatusLine().getStatusCode() == http_code_accepted) { return response.getStatusLine().getReasonPhrase(); } else { throw new OpenStackException(e.getMessage()); } } return result; }

Target:
public String executeSupportRequest(HttpUriRequest request) { log.debug("executeSupportRequest " + request.getURI().toString()); CloseableHttpClient httpClient = getHttpClient(); HttpResponse response = null; String result = null; try { response = httpClient.execute(request); log.debug("Status : " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == http_code_ok) { InputStream is = response.getEntity().getContent(); result = convertStreamToString(is); log.debug("Result " + result); is.close(); response.getEntity().getContent().close(); } } catch (Exception e) { log.warn("Error in the request, message:" + response.getStatusLine().getStatusCode() + " : " + e.getMessage()); } return result; }
Source:
public void sourceNoLongerAdvertised(AdvertisedDataSource source) { if (m_producer != null) try { m_producer.close(); } catch (Exception ignoreIt) m_es.shutdown(); try { if (!m_es.awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { LOG.warn("Forcing executor shutdown on source: " + m_source); try { m_es.shutdownNow(); } catch (Exception e) { LOG.error("Failed to force executor shutdown on source: " + m_source, e); } } } catch (InterruptedException e) { throw new KafkaExportException("Interrupted while awaiting executor shutdown on source:" + m_source, e); } }

Target:
public void sourceNoLongerAdvertised(AdvertisedDataSource source) { if (m_producer != null) try { m_producer.close(); } catch (Exception ignoreIt) m_es.shutdown(); try { if (!m_es.awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { forceExecutorShutdown(); } } catch (InterruptedException e) { LOG.warn("Interrupted while awaiting executor shutdown on source:" + m_source); forceExecutorShutdown(); } }
Source:
private void downloadDatabase( StoreId localStoreId ) { try { localDatabase.stopForStoreCopy(); startStopOnStoreCopy.stop(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } try { CatchupAddressProvider.UpstreamStrategyBoundAddressProvider upstreamStrategyBoundAddressProvider = new CatchupAddressProvider.UpstreamStrategyBoundAddressProvider( topologyService, selectionStrategyPipeline ); storeCopyProcess.replaceWithStoreFrom( upstreamStrategyBoundAddressProvider, localStoreId ); } catch ( IOException | StoreCopyFailedException | StreamingTransactionsFailedException e ) { log.warn( "Error copying store. Will retry shortly." ); return; } try { localDatabase.start(); startStopOnStoreCopy.start(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } latestTxIdOfUpStream = 0; state = TX_PULLING; applier.refreshFromNewStore(); }

Target:
private void downloadDatabase( StoreId localStoreId ) { try { localDatabase.stopForStoreCopy(); startStopOnStoreCopy.stop(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } try { CatchupAddressProvider.UpstreamStrategyBoundAddressProvider upstreamStrategyBoundAddressProvider = new CatchupAddressProvider.UpstreamStrategyBoundAddressProvider( topologyService, selectionStrategyPipeline ); storeCopyProcess.replaceWithStoreFrom( upstreamStrategyBoundAddressProvider, localStoreId ); } catch ( IOException | StoreCopyFailedException | StreamingTransactionsFailedException e ) { log.warn( "Error copying store. Will retry shortly.", e ); return; } try { localDatabase.start(); startStopOnStoreCopy.start(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } latestTxIdOfUpStream = 0; state = TX_PULLING; applier.refreshFromNewStore(); }
Source:
public void completeQuery(AsyncAPI query, User user, String apiVersion) { AsyncAPIUpdateThread queryUpdateWorker = futureTask.get(); if (queryUpdateWorker != null) { log.debug("Task has not completed"); updater.execute(queryUpdateWorker); futureTask.remove(); } else { log.debug("Task has completed"); } }

Target:
public void completeQuery(AsyncAPI query, User user, String apiVersion) { AsyncAPIResultFuture asyncAPIResultFuture = asyncResultFutureThreadLocal.get(); if (asyncAPIResultFuture.isSynchronousTimeout()) { log.debug("Task has not completed"); updater.execute(new AsyncAPIUpdateThread(elide, asyncAPIResultFuture.getAsyncFuture(), query, asyncAPIDao)); asyncResultFutureThreadLocal.remove(); } else { log.debug("Task has completed"); } }
Source:
private boolean hasOSGiManifest(IContainer container) { try { IFile manifestResource = container.getFile(new Path("META-INF/MANIFEST.MF")); if (manifestResource.exists()) { Manifest manifest = new Manifest(); InputStream stream = manifestResource.getContents(); manifest.read(stream); stream.close(); return manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME) != null; } } catch (Exception ex) { PDEPlugin.log(ex); } return false; }

Target:
private boolean hasOSGiManifest(IContainer container) { IFile manifestResource = container.getFile(new Path(ICoreConstants.BUILD_FILENAME_DESCRIPTOR)); if (manifestResource.exists()) { Manifest manifest = new Manifest(); try (InputStream stream = manifestResource.getContents()) { manifest.read(stream); return manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME) != null; } catch (CoreException | IOException ex) { PDEPlugin.log(ex); } } return false; }
Source:
private List<ImageView> createObjects(int count, Activity activity, ViewGroup parent) { ArrayList<ImageView> objects = new ArrayList<>(count); for (int i = 0; i < count; i++) { ImageView object = new ImageView(activity); int size = getBallSize(); Bitmap circle = createCircle(activity.getResources(), size, size); object.setImageBitmap(circle); object.setLayoutParams(new ActionBar.LayoutParams(size, size)); object.setX(RANDOM.nextInt(parent.getWidth())); object.setY(parent.getHeight()); objects.add(object); object.setX(RANDOM.nextInt(parent.getWidth())); } return objects; }

Target:
private List<ImageView> createObjects(int count, Activity activity, ViewGroup parent) { ArrayList<ImageView> objects = new ArrayList<>(count); for (int i = 0; i < count; i++) { ImageView object = new ImageView(activity); int size = getBallSize(); Bitmap circle = createCircle(activity.getResources(), size, size); object.setImageBitmap(circle); object.setLayoutParams(new ActionBar.LayoutParams(size, size)); object.setX(RANDOM.nextInt(parent.getWidth())); object.setY(parent.getHeight()); objects.add(object); } return objects; }
Source:
public void testGoogleAnalyticsTrackingSettingSerialization() throws Exception { GoogleAnalyticsSetting setting = new GoogleAnalyticsSetting(); setting.setEnable(false); String jsonTwo = mapper.writeValueAsString(setting); System.out.println(jsonTwo); Assert.assertEquals(jsonTwo, "{\"enable\":false}"); }

Target:
public void testGoogleAnalyticsTrackingSettingSerialization() throws Exception { GoogleAnalyticsSetting setting = new GoogleAnalyticsSetting(); setting.setEnable(false); String json = mapper.writeValueAsString(setting); System.out.println(json); Assert.assertEquals(json, "{\"enable\":false}"); }
Source:
public void run(final int iteration) { final int workload = memoryStore.getNumBlocks(); final long sleepTime = workload * computationRate; LOG.log(Level.INFO, "iteration start: {0}, workload: {1}, computationRate: {2}, sleepTime: {3}", new Object[]{iteration, workload, computationRate, sleepTime}); try { Thread.sleep(sleepTime); } catch (final InterruptedException e) { throw new RuntimeException("InterruptedException during sleeping", e); } final int finWorkload = memoryStore.getNumBlocks(); LOG.log(Level.INFO, "iteration finish: {0}, finWorkload: {1}", new Object[]{iteration, finWorkload}); }

Target:
public void run(final int iteration) { final int numBlocks = memoryStore.getNumBlocks(); final long sleepTime = numBlocks * computationRate; LOG.log(Level.INFO, "iteration start: {0}, numBlocks: {1}, computationRate: {2}, sleepTime: {3}", new Object[]{iteration, numBlocks, computationRate, sleepTime}); try { Thread.sleep(sleepTime); } catch (final InterruptedException e) { throw new RuntimeException("InterruptedException during sleeping", e); } final int numBlocksAfterSleep = memoryStore.getNumBlocks(); LOG.log(Level.INFO, "iteration finish: {0}, numBlocks after sleep: {1}", new Object[]{iteration, numBlocksAfterSleep}); }
Source:
public List<NuxeoOAuth2Token> getTokens(@Context HttpServletRequest request) throws IOException, RestOperationException { if (!((NuxeoPrincipal)getContext().getCoreSession().getPrincipal()).isAdministrator()) { return Collections.emptyList(); } return getTokens(); }

Target:
public List<NuxeoOAuth2Token> getTokens(@Context HttpServletRequest request) throws IOException, RestOperationException { checkPermission(); return getTokens(); }
Source:
private static boolean isExcluded(Collection<String> excludedGroups, String... groups) { boolean noGroups = (groups == null || groups.length == 0); if (!excludedGroups.isEmpty() && noGroups) { return true; } return isMemberOf(excludedGroups, groups); }

Target:
private static boolean isExcluded(Collection<String> excludedGroups, String... groups) { if (!excludedGroups.isEmpty() && groups.length == 0) { return true; } return isMemberOf(excludedGroups, groups); }
Source:
private boolean doTest() { try { this.channel.stat(this.channel.getHome()); return true; } catch (Exception e) { return false; } }

Target:
private boolean doTest() { try { this.channel.lstat(this.channel.getHome()); return true; } catch (Exception e) { return false; } }
Source:
@Override public VirtualMachineTO implement(VirtualMachineProfile vm) { vmwareVmImplementer = ComponentContext.inject(new VmwareVmImplementer(this)); return vmwareVmImplementer.implement(vm); }

Target:
@Override public VirtualMachineTO implement(VirtualMachineProfile vm) { vmwareVmImplementer.setGlobalNestedVirtualisationEnabled(VmwareEnableNestedVirtualization.value()); vmwareVmImplementer.setGlobalNestedVPerVMEnabled(VmwareEnableNestedVirtualizationPerVM.value()); return vmwareVmImplementer.implement(vm, toVirtualMachineTO(vm), getClusterId(vm.getId())); }
Source:
public void put(MessageWriteSet messageSetToWrite) throws StoreException { checkStarted(); if (messageSetToWrite.getMessageSetInfo().isEmpty()) { throw new IllegalArgumentException("Message write set cannot be empty"); } checkDuplicates(messageSetToWrite); CloudWriteChannel cloudWriter = new CloudWriteChannel(this, messageSetToWrite.getMessageSetInfo()); messageSetToWrite.writeTo(cloudWriter); logPutCountsPeriodically(); }

Target:
public void put(MessageWriteSet messageSetToWrite) throws StoreException { checkStarted(); if (messageSetToWrite.getMessageSetInfo().isEmpty()) { throw new IllegalArgumentException("Message write set cannot be empty"); } checkDuplicates(messageSetToWrite); CloudWriteChannel cloudWriter = new CloudWriteChannel(this, messageSetToWrite.getMessageSetInfo()); messageSetToWrite.writeTo(cloudWriter); logCountsPeriodically(); }
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_GROUP_RESOURCE_ATTR_DEF); attr.setFriendlyName("projectName"); attr.setDisplayName("projectName"); attr.setType(String.class.getName()); attr.setDescription("Name of project, directory where the project exists."); return attr; }

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_GROUP_RESOURCE_ATTR_DEF); attr.setFriendlyName("projectName"); attr.setDisplayName("Project name"); attr.setType(String.class.getName()); attr.setDescription("Name of project, directory where the project exists."); return attr; }
Source:
private void InitVdsBroker() { log.infoFormat("vdsBroker({0},{1})", _vds.gethost_name(), _vds.getport()); String clusterVersion = Config.DefaultConfigurationVersion; if (_vds != null) { clusterVersion = _vds.getvds_group_compatibility_version().getValue(); } int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout, clusterVersion) * 1000; int connectionTimeOut = Config.<Integer>GetValue(ConfigValues.vdsConnectionTimeout, clusterVersion) * 1000; int clientRetries = Config.<Integer>GetValue(ConfigValues.vdsRetries, clusterVersion); Pair<VdsServerConnector, HttpClient> returnValue = XmlRpcUtils.getConnection(_vds.gethost_name(), _vds.getport(), clientTimeOut, connectionTimeOut, clientRetries, VdsServerConnector.class, Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)); _vdsProxy = new VdsServerWrapper(returnValue.getFirst(), returnValue.getSecond()); }

Target:
private void InitVdsBroker() { log.infoFormat("vdsBroker({0},{1})", _vds.gethost_name(), _vds.getport()); String clusterVersion = _vds.getvds_group_compatibility_version().getValue(); int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout, clusterVersion) * 1000; int connectionTimeOut = Config.<Integer>GetValue(ConfigValues.vdsConnectionTimeout, clusterVersion) * 1000; int clientRetries = Config.<Integer>GetValue(ConfigValues.vdsRetries, clusterVersion); Pair<VdsServerConnector, HttpClient> returnValue = XmlRpcUtils.getConnection(_vds.gethost_name(), _vds.getport(), clientTimeOut, connectionTimeOut, clientRetries, VdsServerConnector.class, Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)); _vdsProxy = new VdsServerWrapper(returnValue.getFirst(), returnValue.getSecond()); }
Source:
public List<ProcessDTO> findAll(String sort, Integer offset, Integer size, Map filters) throws DataException { if (Objects.equals(filters, null) || filters.isEmpty()) { return findAll(sort, offset, size); } ProzessverwaltungForm form = (ProzessverwaltungForm) Helper.getManagedBeanValue("#{ProzessverwaltungForm}"); Map<String, String> filterMap = (Map<String, String>) filters; BoolQueryBuilder query = null; for (Map.Entry<String, String> entry : filterMap.entrySet()) { boolean isTemplate = form.getModusAnzeige().equals("vorlagen"); query = serviceManager.getFilterService().queryBuilder(entry.getValue(), ObjectType.PROCESS, isTemplate, false, false); if (!form.isShowClosedProcesses()) { query.must(serviceManager.getProcessService().getQuerySortHelperStatus(false)); } if (!form.isShowArchivedProjects()) { query.must(serviceManager.getProcessService().getQueryProjectArchived(false)); } } return convertJSONObjectsToDTOs(searcher.findDocuments(query.toString(), sort, offset, size), false); }

Target:
public List<ProcessDTO> findAll(String sort, Integer offset, Integer size, Map filters) throws DataException { ProzessverwaltungForm form = (ProzessverwaltungForm) Helper.getManagedBeanValue("#{ProzessverwaltungForm}"); if (Objects.equals(form, null)) { form = new ProzessverwaltungForm(); } boolean isTemplate = Objects.equals(form.getDisplayMode(), ObjectMode.TEMPLATE); Map<String, String> filterMap = (Map<String, String>) filters; BoolQueryBuilder query = null; if (Objects.equals(filters, null) || filters.isEmpty()) { return convertJSONObjectsToDTOs(findBySort(false, false, isTemplate, sort, offset, size), false); } for (Map.Entry<String, String> entry : filterMap.entrySet()) { query = serviceManager.getFilterService().queryBuilder(entry.getValue(), ObjectType.PROCESS, isTemplate, false, false); if (!form.isShowClosedProcesses()) { query.must(serviceManager.getProcessService().getQuerySortHelperStatus(false)); } if (!form.isShowArchivedProjects()) { query.must(serviceManager.getProcessService().getQueryProjectArchived(false)); } } String queryString = ""; if (!Objects.equals(query, null)) { queryString = query.toString(); } return convertJSONObjectsToDTOs(searcher.findDocuments(queryString, sort, offset, size), false); }
Source:
public void registerConsumer( EventConsumer consumer, String publisherName, String... eventTypes) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } Set<String> eventTypesSet = new HashSet<>(); if (eventTypes != null) { eventTypesSet.addAll(asList(eventTypes)); } regMgmtLock.lock(); try { log.debug( "registerConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = nameToPublisher.get(publisherName); if (publisher == null) { danglingConsumers.add( new RegisteredConsumer(consumer, eventTypesSet, publisherName)); } else { publisher.addConsumer(new RegisteredConsumer(consumer, eventTypesSet)); } } finally { regMgmtLock.unlock(); } }

Target:
public void registerConsumer( EventConsumer consumer, String publisherName, String... eventTypes) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } Set<String> eventTypesSet = eventTypes == null ? emptySet() : new HashSet<>(asList(eventTypes)); regMgmtLock.lock(); try { log.debug( "registerConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = nameToPublisher.get(publisherName); if (publisher == null) { danglingConsumers.add( new RegisteredConsumer(consumer, eventTypesSet, publisherName)); } else { publisher.addConsumer(new RegisteredConsumer(consumer, eventTypesSet)); } } finally { regMgmtLock.unlock(); } }
Source:
private static ImmutableList<String> getImports(final Ds3Request ds3Request) { ImmutableSet.Builder<String> importsBuilder = ImmutableSet.builder(); importsBuilder = getImportsFromParamList(importsBuilder, ds3Request.getRequiredQueryParams()); importsBuilder = getImportsFromParamList(importsBuilder, ds3Request.getOptionalQueryParams()); return importsBuilder.build().asList(); }

Target:
private static ImmutableList<String> getImports(final Ds3Request ds3Request) { final ImmutableSet.Builder<String> importsBuilder = ImmutableSet.builder(); importsBuilder.addAll(getImportsFromParamList(ds3Request.getRequiredQueryParams())); importsBuilder.addAll(getImportsFromParamList(ds3Request.getOptionalQueryParams())); return importsBuilder.build().asList(); }
Source:
private AWSCredentialsProvider getCredentialsProvider() { if (null == awsSecretKey || null == awsAccessKey) { return new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return new BasicAWSCredentials(awsAccessKey, awsSecretKey); } @Override public void refresh() { } }; } return new DefaultAWSCredentialsProviderChain(); }

Target:
private AWSCredentialsProvider getCredentialsProvider() { if (null != awsSecretKey && null != awsAccessKey) { return new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return new BasicAWSCredentials(awsAccessKey, awsSecretKey); } @Override public void refresh() { } }; } return new DefaultAWSCredentialsProviderChain(); }
Source:
protected abstract BatchJob createJob(ProcessContext process) throws Exception; protected void logParameters(ProcessContext process) { List<Parameter<?, ?>> parameters = getParameters(); StringBuilder output = new StringBuilder(); output.append("Parameter:\n\n"); appendParameterValues(process, output, parameters, Parameter::shouldBeNormalLogged); process.log(ProcessLog.info().withMessage(output.toString().trim())); if (parameters.stream().anyMatch(Parameter::shouldBeSystemLogged)) { logSystemParameters(process, parameters); } }

Target:
protected abstract BatchJob createJob(ProcessContext process) throws Exception; protected void logParameters(ProcessContext process) { List<Parameter<?, ?>> parameters = getParameters(); makeParameterLog(process, parameters, Parameter.LogVisibility.NORMAL).ifPresent(process::log); makeParameterLog(process, parameters, Parameter.LogVisibility.SYSTEM).ifPresent(processLog -> process.log( processLog.asSystemMessage())); }
Source:
public WikiArticleEditMode clickCloseButton() { waitForElementByElement(closeButton); scrollAndClick(closeButton); PageObjectLogging.log("updateVideoButton", "update video button clicked", true); return new WikiArticleEditMode(driver); }

Target:
public WikiArticleEditMode clickCloseButton() { waitForElementByElement(closeButton); scrollAndClick(closeButton); PageObjectLogging.log("clickCloseButton", "close button clicked", true); return new WikiArticleEditMode(driver); }
Source:
InflightRequest(HttpServletRequest req) { String query = req.getQueryString(); url = req.getRequestURL() + (query == null ? "" : "?" + query); startTime = System.currentTimeMillis(); userName = Jenkins.getAuthentication().getName(); referer = ((StaplerRequest)req).getReferer(); }

Target:
InflightRequest(HttpServletRequest req) { String query = req.getQueryString(); url = req.getRequestURL() + (query == null ? "" : "?" + query); startTime = System.currentTimeMillis(); userName = Jenkins.getAuthentication().getName(); referer = req.getHeader("Referer"); }
Source:
private Guid getClusterId() { Guid clusterId = getParameters().getVdsGroupId(); if (Guid.Empty.equals(getParameters().getVdsGroupId())) { clusterId = Guid.createGuidFromStringDefaultEmpty( Config.<String> getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID)); log.debug( "Cluster id was not provided for registering the host {}, the cluster id is taken from the config value {}", getParameters().getVdsName(), clusterId, ConfigValues.AutoRegistrationDefaultVdsGroupID.name()); } if (Guid.isNullOrEmpty(clusterId)) { VdsGroupDAO clusterDao = getDbFacade().getVdsGroupDao(); VDSGroup cluster = clusterDao.getByName("Default"); if (cluster != null) { clusterId = cluster.getId(); } else { List<VDSGroup> clusters = clusterDao.getAll(); if (clusters.isEmpty()) { clusterId = clusters.get(0).getId(); } } } return clusterId; }

Target:
private Guid getClusterId() { Guid clusterId = getParameters().getVdsGroupId(); if (Guid.Empty.equals(getParameters().getVdsGroupId())) { clusterId = Guid.createGuidFromStringDefaultEmpty( Config.<String> getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID)); log.debug( "Cluster id was not provided for registering the host {}, the cluster id is taken from the config value {}", getParameters().getVdsName(), clusterId, ConfigValues.AutoRegistrationDefaultVdsGroupID.name()); } if (Guid.isNullOrEmpty(clusterId)) { VdsGroupDAO clusterDao = getDbFacade().getVdsGroupDao(); VDSGroup cluster = clusterDao.getByName("Default"); if (cluster != null) { clusterId = cluster.getId(); } else { List<VDSGroup> clusters = clusterDao.getAll(); if (!clusters.isEmpty()) { clusterId = clusters.get(0).getId(); } } } return clusterId; }