auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void write(final IDocument document, final OutputStream out) throws IOException { final org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(); docPrintln(doc, "<?xml version='1.0' encoding='UTF-8'?>"); writeNode(document, doc, ""); final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(out, "UTF-8")); printWriter.print(doc.get()); printWriter.flush(); }

Target:
public void write(final IDocument document, final OutputStream out) throws IOException { final org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(); docPrintln(doc, "<?xml version='1.0' encoding='UTF-8'?>"); writeNode(document, doc, ""); writeToOutputStream(out, doc); }
Source:
public void allBindingsChanged(BindingProvider provider) { logger.trace("allBindingsChanged() called."); if (provider instanceof VeluxBindingProvider) { } super.allBindingsChanged(provider); }

Target:
public void allBindingsChanged(BindingProvider provider) { logger.trace("allBindingsChanged() called."); super.allBindingsChanged(provider); }
Source:
private void configureForOrientation(Configuration newConfig) { LinearLayout mainContainer = getView().findViewById(R.id.cover_fragment); if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { mainContainer.setOrientation(LinearLayout.VERTICAL); if (newConfig.screenWidthDp > 0) { imgvCover.getLayoutParams().width = (int) (convertDpToPixel(newConfig.screenWidthDp) * .80); imgvCover.getLayoutParams().height = imgvCover.getLayoutParams().width; } } else { mainContainer.setOrientation(LinearLayout.HORIZONTAL); if (newConfig.screenHeightDp > 0) { imgvCover.getLayoutParams().height = (int) (convertDpToPixel(newConfig.screenHeightDp) * .40); imgvCover.getLayoutParams().width = imgvCover.getLayoutParams().height; } } }

Target:
private void configureForOrientation(Configuration newConfig) { LinearLayout mainContainer = getView().findViewById(R.id.cover_fragment); ViewGroup.LayoutParams params = imgvCover.getLayoutParams(); if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { mainContainer.setOrientation(LinearLayout.VERTICAL); if (newConfig.screenWidthDp > 0) { params.width = (int) (convertDpToPixel(newConfig.screenWidthDp) * .80); params.height = params.width; imgvCover.setLayoutParams(params); } } else { mainContainer.setOrientation(LinearLayout.HORIZONTAL); if (newConfig.screenHeightDp > 0) { params.height = (int) (convertDpToPixel(newConfig.screenHeightDp) * .40); params.width = params.height; imgvCover.setLayoutParams(params); } } }
Source:
public void testListBookiesCmdReadOnly() throws Exception { assertEquals(0, shell.run(new String[] { "listbookies", "-ro" })); verifyNew(ListBookiesCommand.class, times(1)) .withArguments(same(mockListBookiesFlags)); verify(mockListBookiesCommand, times(1)) .apply(same(shell.bkConf), same(mockListBookiesFlags)); verify(mockListBookiesFlags, times(1)).readonly(true); verify(mockListBookiesFlags, times(1)).readwrite(false); verify(mockListBookiesFlags, times(1)).all(true); }

Target:
public void testListBookiesCmdReadOnly() throws Exception { assertEquals(0, shell.run(new String[] { "listbookies", "-ro" })); verifyNew(ListBookiesCommand.class, times(1)) .withArguments(same(mockListBookiesFlags)); verify(mockListBookiesCommand, times(1)) .apply(same(shell.bkConf), same(mockListBookiesFlags)); verify(mockListBookiesFlags, times(1)).readonly(true); verify(mockListBookiesFlags, times(1)).readwrite(false); verify(mockListBookiesFlags, times(1)).all(false); }
Source:
private void undeployName(CommandContext ctx, String name, boolean allServerGroups, String serverGroups, boolean keepContent, ModelNode headers) throws CommandException { try { ModelNode request = buildRequest(ctx, name, allServerGroups, serverGroups, keepContent, headers); final ModelNode result = ctx. getModelControllerClient().execute(request); if (!Util.isSuccess(result)) { throw new CommandException(Util.getFailureDescription(result)); } } catch (IOException e) { throw new CommandException("Failed to deploy", e); } catch (CommandFormatException ex) { throw new CommandException(ex); } }

Target:
static void undeployName(CommandContext ctx, String name, boolean allServerGroups, String serverGroups, boolean keepContent, ModelNode headers) throws CommandException { try { ModelNode request = buildRequest(ctx, name, allServerGroups, serverGroups, keepContent, headers); final ModelNode result = ctx. getModelControllerClient().execute(request); if (!Util.isSuccess(result)) { throw new CommandException(Util.getFailureDescription(result)); } } catch (IOException e) { throw new CommandException("Failed to deploy", e); } catch (CommandFormatException ex) { throw new CommandException(ex); } }
Source:
Point getLocationInPixels(int offset, boolean trailing) { computeRuns(); int length = text.length(); if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); offset = translateOffset(offset); long ptr = OS.pango_layout_get_text(layout); int byteOffset = (int) (OS.g_utf16_offset_to_pointer(ptr, offset) - ptr); int strlen = C.strlen(ptr); byteOffset = Math.min(byteOffset, strlen); PangoRectangle pos = new PangoRectangle(); OS.pango_layout_index_to_pos(layout, byteOffset, pos); int x = trailing ? pos.x + pos.width : pos.x; int y = pos.y; x = OS.PANGO_PIXELS(x); if (OS.pango_context_get_base_dir(context) == OS.PANGO_DIRECTION_RTL) { x = width() - x; } x += Math.min (indent, wrapIndent); return new Point(x, OS.PANGO_PIXELS(y + getScaledVerticalIndent())); }

Target:
Point getLocationInPixels(int offset, boolean trailing) { computeRuns(); int length = text.length(); if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); offset = translateOffset(offset); long ptr = OS.pango_layout_get_text(layout); int byteOffset = (int) (OS.g_utf16_offset_to_pointer(ptr, offset) - ptr); int strlen = C.strlen(ptr); byteOffset = Math.min(byteOffset, strlen); PangoRectangle pos = new PangoRectangle(); OS.pango_layout_index_to_pos(layout, byteOffset, pos); int x = trailing ? pos.x + pos.width : pos.x; int y = pos.y; x = OS.PANGO_PIXELS(x); if (OS.pango_context_get_base_dir(context) == OS.PANGO_DIRECTION_RTL) { x = width() - x; } x += Math.min (indent, wrapIndent); return new Point(x, OS.PANGO_PIXELS(y) + getScaledVerticalIndent()); }
Source:
public void verifyModal() { MainPage main = (MainPage) new MainPage(driver).open(); CuratedContentToolModal modal = main.clickCuratedContentToolButton(); modal.verify(); }

Target:
public void verifyModal() { MainPage main = new MainPage(driver).open(); CuratedContentToolModal modal = main.clickCuratedContentToolButton(); Assertion.assertTrue(modal.isModalVisible()); }
Source:
@Test public void filerPassesOriginatingElements() throws IOException { ClassName name1 = ClassName.create("example", "Test1"); ClassWriter test1 = ClassWriter.forClassName(name1); Element element1 = Mockito.mock(Element.class); test1.addOriginatingElement(element1); ClassName name2 = ClassName.create("example", "Test2"); ClassWriter test2 = ClassWriter.forClassName(name2); Element element2_1 = Mockito.mock(Element.class); Element element2_2 = Mockito.mock(Element.class); test2.addOriginatingElement(element2_1, element2_2); javaWriter.addTypeWriter(test1).addTypeWriter(test2).writeTo(filer); Path testPath1 = fsRoot.resolve(fs.getPath("example", "Test1.java")); assertThat(filer.getOriginatingElements(testPath1)).containsExactly(element1); Path testPath2 = fsRoot.resolve(fs.getPath("example", "Test2.java")); assertThat(filer.getOriginatingElements(testPath2)).containsExactly(element2_1, element2_2); }

Target:
@Test public void filerPassesOriginatingElements() throws IOException { ClassName name1 = ClassName.create("example", "Test1"); ClassWriter test1 = ClassWriter.forClassName(name1); Element element1_1 = Mockito.mock(Element.class); test1.addOriginatingElement(element1_1); ClassName name2 = ClassName.create("example", "Test2"); ClassWriter test2 = ClassWriter.forClassName(name2); Element element2_1 = Mockito.mock(Element.class); Element element2_2 = Mockito.mock(Element.class); test2.addOriginatingElement(element2_1, element2_2); javaWriter.addTypeWriter(test1).addTypeWriter(test2).writeTo(filer); Path testPath1 = fsRoot.resolve(fs.getPath("example", "Test1.java")); assertThat(filer.getOriginatingElements(testPath1)).containsExactly(element1_1); Path testPath2 = fsRoot.resolve(fs.getPath("example", "Test2.java")); assertThat(filer.getOriginatingElements(testPath2)).containsExactly(element2_1, element2_2); }
Source:
public void testHttpHeadersProperties_multipleHeaders() { Configuration config = new Configuration(); config.set(GCS_HTTP_HEADERS.getKey() + "test-header", "test-VAL"); config.set(GCS_HTTP_HEADERS.getKey() + "key-in-header", "+G2Ap33m5NVOgmXznSGTEvG0I="); GoogleCloudStorageFileSystemOptions options = GoogleHadoopFileSystemConfiguration.getGcsFsOptionsBuilder(config).build(); String encryptionAlgorithm = options.getCloudStorageOptions().getEncryptionAlgorithm(); assertThat(options.getCloudStorageOptions().getHttpRequestHeaders()) .containsExactly("test-header", "test-VAL", "key-in-header", "+G2Ap33m5NVOgmXznSGTEvG0I="); }

Target:
public void testHttpHeadersProperties_multipleHeaders() { Configuration config = new Configuration(); config.set(GCS_HTTP_HEADERS.getKey() + "test-header", "test-VAL"); config.set(GCS_HTTP_HEADERS.getKey() + "key-in-header", "+G2Ap33m5NVOgmXznSGTEvG0I="); GoogleCloudStorageFileSystemOptions options = GoogleHadoopFileSystemConfiguration.getGcsFsOptionsBuilder(config).build(); assertThat(options.getCloudStorageOptions().getHttpRequestHeaders()) .containsExactly("test-header", "test-VAL", "key-in-header", "+G2Ap33m5NVOgmXznSGTEvG0I="); }
Source:
private int getQueryThreadPoolSize() { return Runtime.getRuntime().availableProcessors() / 2; }

Target:
private int getQueryThreadPoolSize() { return Math.max(Runtime.getRuntime().availableProcessors() / 2, 1); }
Source:
private void setCurrentLimit(String type, TimestampBoundStoreEntry newEntry) { checkLimitNotDecreasing(newEntry); currentLimit = newEntry.getTimestampOrInitialValue(); log.info("{} Setting cached timestamp limit to {}.", type, currentLimit); }

Target:
private void setCurrentLimit(String type, TimestampBoundStoreEntry newEntry) { checkLimitNotDecreasing(newEntry); currentLimit = newEntry.getTimestampOrValue(null); log.info("[{}] Setting cached timestamp limit to {}.", type, currentLimit); }
Source:
public void push(RowMap r) throws Exception { String key = r.pkToJson(keyFormat); String value = r.toJSON(outputConfig); if ( value == null ) { inflightMessages.addMessage(r.getPosition()); BinlogPosition newPosition = inflightMessages.completeMessage(r.getPosition()); if ( newPosition != null ) { context.setPosition(newPosition); } return; } ProducerRecord<String, String> record; if (r instanceof DDLMap) { String topic = generateTopic(this.ddlTopic, r); record = new ProducerRecord<>(topic, this.ddlPartitioner.kafkaPartition(r, getNumPartitions(topic)), key, value); } else { String topic = generateTopic(this.topic, r); record = new ProducerRecord<>(topic, this.partitioner.kafkaPartition(r, getNumPartitions(topic)), key, value); } if ( r.isTXCommit() ) inflightMessages.addMessage(r.getPosition()); if ( !KafkaCallback.LOGGER.isDebugEnabled() ) value = null; KafkaCallback callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, key, value); kafka.send(record, callback); }

Target:
public void push(RowMap r) throws Exception { String key = r.pkToJson(keyFormat); String value = r.toJSON(outputConfig); if ( value == null ) { inflightMessages.addMessage(r.getPosition()); BinlogPosition newPosition = inflightMessages.completeMessage(r.getPosition()); if ( newPosition != null ) { context.setPosition(newPosition); } return; } ProducerRecord<String, String> record; if (r instanceof DDLMap) { record = new ProducerRecord<>(this.ddlTopic, this.ddlPartitioner.kafkaPartition(r, getNumPartitions(this.ddlTopic)), key, value); } else { String topic = generateTopic(this.topic, r); record = new ProducerRecord<>(topic, this.partitioner.kafkaPartition(r, getNumPartitions(topic)), key, value); } if ( r.isTXCommit() ) inflightMessages.addMessage(r.getPosition()); if ( !KafkaCallback.LOGGER.isDebugEnabled() ) value = null; KafkaCallback callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, key, value); kafka.send(record, callback); }
Source:
private void setupServer(IntegrationMBeanExporter exporter) { String server = this.attributes.getString("server"); if (server != null && this.environment != null) { server = this.environment.resolvePlaceholders(server); } if (StringUtils.hasText(server)) { exporter.setServer(this.beanFactory.getBean(server, MBeanServer.class)); } else { exporter.setServer(MBeanServerFactory.createMBeanServer()); } }

Target:
private void setupServer(IntegrationMBeanExporter exporter) { String server = this.attributes.getString("server"); if (server != null && this.environment != null) { server = this.environment.resolvePlaceholders(server); } if (StringUtils.hasText(server)) { MBeanServer bean = null; if (server.startsWith("#{") && server.endsWith("}")) { bean = (MBeanServer) this.resolver.evaluate(server, this.expressionContext); } else { bean = this.beanFactory.getBean(server, MBeanServer.class); } exporter.setServer(bean); } else { exporter.setServer(MBeanServerFactory.createMBeanServer()); } }
Source:
public AdaptiveMetropolisSampler(final double xInitial, final double initialStepSize, final double lowerBound, final double upperBound, final double adjustmentRate, final double timeScale) { if (lowerBound > upperBound) { throw new IllegalArgumentException("Maximum bound must be larger than minimum bound."); } ParamUtils.isPositive(initialStepSize, "Step size must be positive."); ParamUtils.isPositive(timeScale, "Time scale must be positive."); xCurrent = xInitial; stepSize = initialStepSize; this.lowerBound = lowerBound; this.upperBound = upperBound; this.adjustmentRate = adjustmentRate; this.timeScale = timeScale; }

Target:
public AdaptiveMetropolisSampler(final double xInitial, final double initialStepSize, final double lowerBound, final double upperBound, final double adjustmentRate, final double timeScale) { Utils.validateArg(lowerBound <= upperBound, "Maximum bound must be greater than or equal to minimum bound."); ParamUtils.isPositive(initialStepSize, "Step size must be positive."); ParamUtils.isPositive(timeScale, "Time scale must be positive."); xCurrent = xInitial; stepSize = initialStepSize; this.lowerBound = lowerBound; this.upperBound = upperBound; this.adjustmentRate = adjustmentRate; this.timeScale = timeScale; }
Source:
public MotorControlAccelCap(Motor motor, Controller controller, int axis, double scale, double accel_cap) { super("motorControlAccelCap", motor); this.motor = motor; this.controller = controller; this.axis = axis; this.scale = scale; this.accel_cap = accel_cap; this.last_speed = 0.0; last_t = System.currentTimeMillis(); LogKitten.d("MotorControl created for " + motor.getName()); }

Target:
public MotorControlAccelCap(Motor motor, Controller controller, int axis, double scale, double accel_cap) { this("MotorControlAccelCap", motor, controller, axis, scale, accel_cap); }
Source:
public void setInput(IEditorInput input) { if (input instanceof CSourceNotFoundEditorInput) { isDebugElement = false; isTranslationUnit = false; Object artifact = ((CSourceNotFoundEditorInput) input).getArtifact(); if (artifact instanceof CSourceNotFoundElement) { CSourceNotFoundElement element = (CSourceNotFoundElement) artifact; missingFile = element.getFile(); launch = element.getLaunch(); context = element.getElement(); isDebugElement = true; } else if (artifact instanceof ITranslationUnit) { isTranslationUnit = true; tunit = (ITranslationUnit) artifact; IPath tuPath = tunit.getLocation(); if (tuPath != null) missingFile = tuPath.toOSString(); } else { missingFile = ""; } } super.setInput(input); if (fText != null) { fText.setText(getText()); } }

Target:
public void setInput(IEditorInput input) { if (input instanceof CSourceNotFoundEditorInput) { isDebugElement = false; isTranslationUnit = false; Object artifact = ((CSourceNotFoundEditorInput) input).getArtifact(); if (artifact instanceof CSourceNotFoundElement) { CSourceNotFoundElement element = (CSourceNotFoundElement) artifact; missingFile = element.getFile(); launch = element.getLaunch(); context = element.getElement(); isDebugElement = true; } else if (artifact instanceof ITranslationUnit) { isTranslationUnit = true; tunit = (ITranslationUnit) artifact; IPath tuPath = tunit.getLocation(); if (tuPath != null) missingFile = tuPath.toOSString(); } else { missingFile = ""; } } super.setInput(input); if (fText != null) { fText.setText(getText()); } syncButtons(); }
Source:
public void g_V_repeatXin_outX_timesX3X_tailX7X_count() { final Traversal<Vertex, Long> traversal = get_g_V_repeatXin_outX_timesX3X_tailX7X_count(); printTraversalForm(traversal); long count = 0L; if (traversal.hasNext()) { count = traversal.next(); } assertEquals(7L, count); }

Target:
public void g_V_repeatXin_outX_timesX3X_tailX7X_count() { final Traversal<Vertex, Long> traversal = get_g_V_repeatXin_outX_timesX3X_tailX7X_count(); printTraversalForm(traversal); checkResults(Collections.singletonList(7L), traversal); }
Source:
private void throwIfPreCommitRequirementsNotMet(@Nullable LockTokenV2 commitLocksToken) { Set<LockTokenV2> expiredLocks = refreshExternalAndCommitLocks(commitLocksToken); if (!expiredLocks.isEmpty()) { final String baseMsg = "Required locks are no longer valid. "; String expiredLocksErrorString = getExpiredLocksErrorString(commitLocksToken, expiredLocks); TransactionLockTimeoutException ex = new TransactionLockTimeoutException(baseMsg + expiredLocksErrorString); log.error(baseMsg + "{}", expiredLocksErrorString, ex); throw ex; } preCommitValidation.check(); }

Target:
private void throwIfPreCommitRequirementsNotMet(@Nullable LockTokenV2 commitLocksToken) { throwIfImmutableTsOrCommitLocksExpired(commitLocksToken); advisoryLockCheck.throwIfLocksExpired(); }
Source:
private void doRefreshData() throws Exception { if ( treeState.get() == TreeState.STARTED ) { if ( dataIsCompressed ) { if (createZkWatches) { client.getData().decompressed().usingWatcher(this).inBackground(this).forPath(path); } else { client.getData().decompressed().inBackground(this).forPath(path); } } else { if (createZkWatches) { client.getData().usingWatcher(this).inBackground(this).forPath(path); } else { client.getData().inBackground(this).forPath(path); } } } }

Target:
private void doRefreshData() throws Exception { if ( treeState.get() == TreeState.STARTED ) { if ( dataIsCompressed ) { maybeWatch(client.getData().decompressed()).forPath(path); } else { maybeWatch(client.getData()).forPath(path); } } }
Source:
private void addAuditLogForPartialVMs() { StringBuilder missingEntities = new StringBuilder(); if (getParameters().isAllowPartialImport() && !failedDisksToImportForAuditLog.isEmpty()) { missingEntities.append("Disks: "); missingEntities.append(StringUtils.join(failedDisksToImportForAuditLog.values(), ", ") + " "); } if (!missingUsers.isEmpty()) { missingEntities.append("Users: "); missingEntities.append(StringUtils.join(missingUsers, ", ") + " "); } if (!missingRoles.isEmpty()) { missingEntities.append("Roles: "); missingEntities.append(StringUtils.join(missingRoles, ", ") + " "); } if (missingEntities.length() > 0) { addCustomValue("MissingEntities", missingEntities.toString()); auditLogDirector.log(this, AuditLogType.IMPORTEXPORT_PARTIAL_VM_MISSING_ENTITIES); } }

Target:
private void addAuditLogForPartialVMs() { StringBuilder missingEntities = new StringBuilder(); if (getParameters().isAllowPartialImport() && !failedDisksToImportForAuditLog.isEmpty()) { missingEntities.append("Disks: "); missingEntities.append(StringUtils.join(failedDisksToImportForAuditLog.values(), ", ") + " "); } if (!missingUsers.isEmpty()) { missingEntities.append("Users: "); missingEntities.append(StringUtils.join(missingUsers, ", ") + " "); } if (!missingRoles.isEmpty()) { missingEntities.append("Roles: "); missingEntities.append(StringUtils.join(missingRoles, ", ") + " "); } if (missingEntities.length() > 0) { addCustomValue("MissingEntities", missingEntities.toString()); auditLogDirector.log(this, AuditLogType.IMPORTEXPORT_PARTIAL_TEMPLATE_MISSING_ENTITIES); } }
Source:
private void setInputTypePassword(EditText editText) { editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); }

Target:
private void setInputTypePassword(EditText editText) { editText.setInputType((editText.getInputType() & ~InputType.TYPE_MASK_VARIATION) | InputType.TYPE_TEXT_VARIATION_PASSWORD); }
Source:
private JSONArray formatEventsAndInitialize() { ConcurrentHashMap<List<StackTraceElement>, MissingClassEvent> toReport = MissingClassTelemetry.events.getEventsAndClean(); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Cleaned events for missing classes"); return formatEvents(toReport); }

Target:
private JSONArray formatEventsAndInitialize() { ConcurrentHashMap<List<StackTraceElement>, MissingClassEvent> toReport = MissingClassTelemetry.events.getEventsAndClean(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Cleaned events for missing classes"); } return formatEvents(toReport); }
Source:
private void broadcastToNoteBindedInterpreter(String interpreterGroupId, Message m) { Notebook notebook = notebook(); List<Note> notes = notebook.getAllNotes(); for (Note note : notes) { List<String> ids = notebook.getInterpreterFactory().getInterpreters(note.getId()); for (String id : ids) { if (id.equals(interpreterGroupId)) { broadcast(note.getId(), m); broadcastToWatchers(note.getId(), StringUtils.EMPTY, m); } } } }

Target:
private void broadcastToNoteBindedInterpreter(String interpreterGroupId, Message m) { Notebook notebook = notebook(); List<Note> notes = notebook.getAllNotes(); for (Note note : notes) { List<String> ids = notebook.getInterpreterFactory().getInterpreters(note.getId()); for (String id : ids) { if (id.equals(interpreterGroupId)) { broadcast(note.getId(), m); } } } }
Source:
public void notifyTableChanged(TableName tableName, long updateTime) { LOG.debug("Table changed: {}, at {}", tableName.getNotEmptyDbTable(), updateTime); List<CacheEntry> entriesToInvalidate = null; rwLock.writeLock().lock(); try { String key = (tableName.getNotEmptyDbTable().toLowerCase()); Set<CacheEntry> entriesForTable = tableToEntryMap.get(key); if (entriesForTable != null) { entriesToInvalidate = new ArrayList<>(entriesForTable); } if (entriesToInvalidate != null) { for (CacheEntry entry : entriesToInvalidate) { if (entry.getQueryInfo().getQueryTime() <= updateTime) { removeEntry(entry); } } } } finally { rwLock.writeLock().unlock(); } }

Target:
public void notifyTableChanged(TableName tableName, long updateTime) { LOG.debug("Table changed: {}, at {}", tableName, updateTime); List<CacheEntry> entriesToInvalidate = null; rwLock.writeLock().lock(); try { String key = (tableName.getNotEmptyDbTable()); Set<CacheEntry> entriesForTable = tableToEntryMap.get(key); if (entriesForTable != null) { entriesToInvalidate = new ArrayList<>(entriesForTable); } if (entriesToInvalidate != null) { for (CacheEntry entry : entriesToInvalidate) { if (entry.getQueryInfo().getQueryTime() <= updateTime) { removeEntry(entry); } } } } finally { rwLock.writeLock().unlock(); } }
Source:
public void deletePhenotype(final Integer phenotypeId) { final Phenotype phenotype = new Phenotype(); phenotype.setPhenotypeId(phenotypeId); this.daoFactory.getPhenotypeDAO().makeTransient(phenotype); }

Target:
public void deletePhenotype(final Integer phenotypeId) { final Phenotype phenotype = this.daoFactory.getPhenotypeDAO().getById(phenotypeId); final Integer observableId = phenotype.getObservableId(); final Integer observationUnitId = phenotype.getExperiment().getNdExperimentId(); this.daoFactory.getPhenotypeDAO().makeTransient(phenotype); this.updateDependentPhenotypesStatus(observableId, observationUnitId); }
Source:
public int getNumberOfTypes(Player player) { if (player == null || player.getInheritance() == null || !this.equals(Cards.estate)) { return types.length; } return player.getInheritance().getNumberOfTypes(player); }

Target:
public int getNumberOfTypes(Player player) { if (player == null || player.getInheritance() == null || !this.equals(Cards.estate)) { return types.length; } Set<Type> typeSet = new HashSet<Type>(); typeSet.addAll(Arrays.asList(player.getInheritance().getTypes())); typeSet.addAll(Arrays.asList(types)); return typeSet.size(); }
Source:
public Void presentation(String programName, String programEditor, String applicationHomepage, String scriptorName) { final String htmlToShow = "<body>" + tr("Installation Wizard for {0}", programName) + ".<br><br>" + tr("Installation Script by {0}", programEditor) + "<br><br>" + tr("For more information about this program, visit:") + String.format("<br><a href=\"%1$s\">%1$s</a><br><br>", applicationHomepage) + tr("Installation Script by {0}", scriptorName) + "<br><br>" + "<br><br>" + tr("{0} will be installed in: {1}", programName, applicationUserRoot) + "<br><br>" + tr("{0} is not responsible for anything that might happen as a result of using these scripts.", applicationName) + "<br><br>" + tr("Click \"Next\" to start.") + "</body>"; return messageSender.runAndWait(message -> setupUi.showHtmlPresentationStep(message, htmlToShow)); }

Target:
public Void presentation(String programName, String programEditor, String applicationHomepage, String scriptorName) { final String htmlToShow = "<body>" + tr("Installation wizard for {0}", programName) + ".<br><br>" + tr("Installation script by {0}", programEditor) + "<br><br>" + tr("For more information about this program, visit:") + String.format("<br><a href=\"%1$s\">%1$s</a><br><br>", applicationHomepage) + tr("Installation script by {0}", scriptorName) + "<br><br>" + "<br><br>" + tr("{0} will be installed in: {1}", programName, applicationUserRoot) + "<br><br>" + tr("{0} is not responsible for anything that might happen as a result of using these scripts.", applicationName) + "<br><br>" + tr("Click \"Next\" to start.") + "</body>"; return messageSender.runAndWait(message -> setupUi.showHtmlPresentationStep(message, htmlToShow)); }
Source:
public ListIterator<T> listIterator(final int index) { try { return this.origin.listIterator(index); } catch (final IndexOutOfBoundsException ex) { throw new IllegalArgumentException(this.message, ex); } }

Target:
public ListIterator<T> listIterator(final int index) { try { return this.origin.listIterator(index); } catch (final IndexOutOfBoundsException ex) { throw this.wrapException(ex); } }
Source:
private void initAttestation() { List<VDSGroup> vdsGroups = DbFacade.getInstance().getVdsGroupDao().getTrustedClusters(); List<VDS> trustedVdsList = new ArrayList<>(); List<String> trustedVdsNames = new ArrayList<>(); if (vdsGroups == null || vdsGroups.size() == 0) { return; } for (VDSGroup vdsGroup : vdsGroups) { List<VDS> vdssInGroup = DbFacade.getInstance().getVdsDao().getAllForVdsGroup(vdsGroup.getId()); if (vdssInGroup != null) { trustedVdsList.addAll(vdssInGroup); } } for (VDS vds : trustedVdsList) { trustedVdsNames.add(vds.getHostName()); setNonOperational(NonOperationalReason.UNINITIALIZED, vds); } try { AttestThread attestThread = new AttestThread(trustedVdsNames); attestThread.start(); } catch (Exception e) { log.error("Failed to initialize attestation cache", e); } }

Target:
private void initAttestation() { List<VDSGroup> vdsGroups = DbFacade.getInstance().getVdsGroupDao().getTrustedClusters(); List<VDS> trustedVdsList = new ArrayList<>(); List<String> trustedVdsNames = new ArrayList<>(); if (vdsGroups == null || vdsGroups.size() == 0) { return; } for (VDSGroup vdsGroup : vdsGroups) { List<VDS> vdssInGroup = DbFacade.getInstance().getVdsDao(). getAllForVdsGroupWithStatus(vdsGroup.getId(), VDSStatus.Up); if (vdssInGroup != null) { trustedVdsList.addAll(vdssInGroup); } } for (VDS vds : trustedVdsList) { trustedVdsNames.add(vds.getHostName()); setNonOperational(NonOperationalReason.UNINITIALIZED, vds); } try { AttestThread attestThread = new AttestThread(trustedVdsNames); attestThread.start(); } catch (Exception e) { log.error("Failed to initialize attestation cache", e); } }
Source:
protected ArrayList<TaskAttribute> parseFromJson(InputStreamReader in) { TypeToken<ArrayList<TaskAttribute>> type = new TypeToken<ArrayList<TaskAttribute>>() { }; return new GsonBuilder().registerTypeAdapter(type.getType(), new JSonTaskDataDeserializer()) .setExclusionStrategies(exclustionStrategy) .create() .fromJson(in, type.getType()); }

Target:
protected ArrayList<TaskAttribute> parseFromJson(InputStreamReader in) { TypeToken<ArrayList<TaskAttribute>> type = new TypeToken<ArrayList<TaskAttribute>>() { }; return new GsonBuilder().registerTypeAdapter(type.getType(), new JSonTaskDataDeserializer()) .create() .fromJson(in, type.getType()); }
Source:
public ISelectionListener addPredicate(Predicate<ISelectionModel> predicate) { if (predicate != null) { fPredicate = fPredicate.and(predicate); } return this; }

Target:
public PartSelectionListener addPredicate(Predicate<ISelectionModel> predicate) { if (predicate != null) { fPredicate = fPredicate.and(predicate); } return this; }
Source:
private FormatterStep createLazyLicenseHeaderStep(Project project) { String delimiter = "(?! \\*|/\\*| \\*/)"; Supplier<FormatterStep> realStep = Suppliers.memoize(() -> { String header = computeCopyrightHeader(project); return LicenseHeaderStep.createFromHeader(header, delimiter); }); return (FormatterStep) Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class[] {FormatterStep.class}, (_proxy, method, args) -> method.invoke(realStep.get(), args)); }

Target:
private FormatterStep createLazyLicenseHeaderStep(Project project) { String delimiter = "(?! \\*|/\\*| \\*/)"; return new LazyFormatterStep(MultiLicenseHeaderStep.name(), () -> { List<String> headers = computeCopyrightHeaders(project); return MultiLicenseHeaderStep.createFromHeaders(headers, delimiter); }); }
Source:
protected void deriveNodeDetails(Trace trace, List<Node> nodes, List<NodeDetails> rts, boolean initial, Set<Property> commonProperties) { for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); boolean ignoreNode = false; boolean ignoreChildNodes = false; if (n.getClass() == Consumer.class && ((Consumer) n).getEndpointType() == null) { ignoreNode = true; } else if (n.getClass() == Producer.class && ((Producer) n).getEndpointType() == null) { ignoreNode = true; ignoreChildNodes = true; } if (!ignoreNode) { NodeDetails nd = new NodeDetails(); nd.setId(UUID.randomUUID().toString()); nd.setTraceId(trace.getTraceId()); nd.setFragmentId(trace.getFragmentId()); nd.setTransaction(trace.getTransaction()); nd.setCorrelationIds(n.getCorrelationIds()); nd.setElapsed(n.getDuration()); nd.setActual(n.getDuration() - calculateChildElapsedTime(n)); if (n.getType() == NodeType.Component) { nd.setComponentType(((Component) n).getComponentType()); } else { nd.setComponentType(n.getType().name()); } if (trace.getHostName() != null && !trace.getHostName().trim().isEmpty()) { nd.setHostName(trace.getHostName()); } if (initial) { nd.setProperties(trace.allProperties()); nd.setInitial(true); } else { nd.getProperties().addAll(n.getProperties()); nd.getProperties().addAll(commonProperties); } nd.setTimestamp(n.getTimestamp()); nd.setType(n.getType()); nd.setUri(n.getUri()); nd.setOperation(n.getOperation()); rts.add(nd); } initial = false; if (!ignoreChildNodes && n.interactionNode()) { deriveNodeDetails(trace, ((InteractionNode) n).getNodes(), rts, initial, commonProperties); } } }

Target:
protected void deriveNodeDetails(Trace trace, List<Node> nodes, List<NodeDetails> rts, boolean initial, Set<Property> commonProperties) { for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); boolean ignoreNode = false; boolean ignoreChildNodes = false; if (n.getClass() == Consumer.class && ((Consumer) n).getEndpointType() == null) { ignoreNode = true; } else if (n.getClass() == Producer.class && ((Producer) n).getEndpointType() == null) { ignoreNode = true; ignoreChildNodes = true; } if (!ignoreNode) { NodeDetails nd = new NodeDetails(); nd.setId(UUID.randomUUID().toString()); nd.setTraceId(trace.getTraceId()); nd.setFragmentId(trace.getFragmentId()); nd.setTransaction(trace.getTransaction()); nd.setCorrelationIds(n.getCorrelationIds()); nd.setElapsed(n.getDuration()); nd.setActual(calculateActualTime(n)); if (n.getType() == NodeType.Component) { nd.setComponentType(((Component) n).getComponentType()); } else { nd.setComponentType(n.getType().name()); } if (trace.getHostName() != null && !trace.getHostName().trim().isEmpty()) { nd.setHostName(trace.getHostName()); } if (initial) { nd.setProperties(trace.allProperties()); nd.setInitial(true); } else { nd.getProperties().addAll(n.getProperties()); nd.getProperties().addAll(commonProperties); } nd.setTimestamp(n.getTimestamp()); nd.setType(n.getType()); nd.setUri(n.getUri()); nd.setOperation(n.getOperation()); rts.add(nd); } initial = false; if (!ignoreChildNodes && n.interactionNode()) { deriveNodeDetails(trace, ((InteractionNode) n).getNodes(), rts, initial, commonProperties); } } }
Source:
public void onChange(Saveable o, XmlFile file) { if (o instanceof Hudson) { MinimumInstanceChecker.checkForMinimumInstances(); } }

Target:
public void onChange(Saveable o, XmlFile file) { if (o instanceof Jenkins) { MinimumInstanceChecker.checkForMinimumInstances(); } }
Source:
private void setPreferencesFromSiteSettings() { assignPrefListeners(false); try { if (!mSiteSettings.isSharingModuleEnabled()) { mSharingDisabledNotification.setVisibility(View.VISIBLE); mSharingSettingsWrapper.setVisibility(View.GONE); } mPrefLabel.setTextEntry(mSiteSettings.getSharingLabel()); mPrefButtonStyle.setSummary(mSiteSettings.getSharingButtonStyleDisplayText(getActivity())); mPrefShowReblog.setChecked(mSiteSettings.getAllowReblogButton()); mPrefShowLike.setChecked(mSiteSettings.getAllowLikeButton()); mPrefAllowCommentLikes.setChecked(mSiteSettings.getAllowCommentLikes()); mPrefTwitterName.setTextEntry(mSiteSettings.getTwitterUsername()); String selectedName = mSiteSettings.getSharingButtonStyleDisplayText(getActivity()); String[] names = getResources().getStringArray(R.array.sharing_button_style_display_array); String[] values = getResources().getStringArray(R.array.sharing_button_style_array); PrefListItems listItems = new PrefListItems(); for (int i = 0; i < names.length; i++) { PrefListItem item = new PrefListItem(names[i], values[i], false); listItems.add(item); } listItems.setSelectedName(selectedName); mPrefButtonStyle.setListItems(listItems); mPrefButtonStyle.setSummary(selectedName); } finally { assignPrefListeners(true); } }

Target:
private void setPreferencesFromSiteSettings() { assignPrefListeners(false); try { boolean sharingModuleEnabled = mSiteSettings.isSharingModuleEnabled(); mSharingDisabledNotification.setVisibility(sharingModuleEnabled ? View.GONE : View.VISIBLE); mSharingSettingsWrapper.setVisibility(sharingModuleEnabled ? View.VISIBLE : View.GONE); mPrefLabel.setTextEntry(mSiteSettings.getSharingLabel()); mPrefButtonStyle.setSummary(mSiteSettings.getSharingButtonStyleDisplayText(getActivity())); mPrefShowReblog.setChecked(mSiteSettings.getAllowReblogButton()); mPrefShowLike.setChecked(mSiteSettings.getAllowLikeButton()); mPrefAllowCommentLikes.setChecked(mSiteSettings.getAllowCommentLikes()); mPrefTwitterName.setTextEntry(mSiteSettings.getTwitterUsername()); String selectedName = mSiteSettings.getSharingButtonStyleDisplayText(getActivity()); String[] names = getResources().getStringArray(R.array.sharing_button_style_display_array); String[] values = getResources().getStringArray(R.array.sharing_button_style_array); PrefListItems listItems = new PrefListItems(); for (int i = 0; i < names.length; i++) { PrefListItem item = new PrefListItem(names[i], values[i], false); listItems.add(item); } listItems.setSelectedName(selectedName); mPrefButtonStyle.setListItems(listItems); mPrefButtonStyle.setSummary(selectedName); } finally { assignPrefListeners(true); } }
Source:
public JsonResponse add(@Valid @RequestBody SpamRuleDto ruleDto, BindingResult result) throws org.jtalks.common.service.exceptions.NotFoundException, InterruptedException { checkForAdminPermissions(); trimAndValidate(ruleDto, result); if (result.hasFieldErrors() || result.hasGlobalErrors()) { return new JsonResponse(JsonResponseStatus.FAIL, result.getAllErrors()); } SpamRule spamRule = SpamRule.toEntity(ruleDto); return saveOrUpdateSpamRule(result, spamRule); }

Target:
public JsonResponse add(@Valid @RequestBody SpamRuleDto ruleDto, BindingResult result) throws org.jtalks.common.service.exceptions.NotFoundException, InterruptedException { checkForAdminPermissions(); trimAndValidate(ruleDto, result); if (result.hasFieldErrors() || result.hasGlobalErrors()) { return new JsonResponse(JsonResponseStatus.FAIL, result.getAllErrors()); } SpamRule spamRule = ruleDto.toEntity(); return saveOrUpdateSpamRule(result, spamRule); }
Source:
private void processMethod(DetailAST ast) { final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS); if (violateImpliedPublicMethod && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) == null) { log(ast, MSG_KEY, PUBLIC_ACCESS_MODIFIER); } if (violateImpliedAbstractMethod && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null && modifiers.findFirstToken(TokenTypes.LITERAL_DEFAULT) == null && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null && modifiers.findFirstToken(TokenTypes.ABSTRACT) == null) { log(ast, MSG_KEY, ABSTRACT_KEYWORD); } }

Target:
private void processMethod(DetailAST ast) { final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS); if (violateImpliedPublicMethod && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) == null) { log(ast, MSG_KEY, PUBLIC_ACCESS_MODIFIER); } if (violateImpliedAbstractMethod && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null && modifiers.findFirstToken(TokenTypes.LITERAL_DEFAULT) == null && modifiers.findFirstToken(TokenTypes.ABSTRACT) == null) { log(ast, MSG_KEY, ABSTRACT_KEYWORD); } }
Source:
public Description matchMethod(MethodTree tree, VisitorState state) { if (IS_OVERRIDE.matches(tree, state)) { return Description.NO_MATCH; } Symbol.MethodSymbol symbol = ASTHelpers.getSymbol(tree); if (symbol == null || symbol.isConstructor()) { return Description.NO_MATCH; } if (tree.getParameters().size() > MAX_NUM_ARGS) { return buildDescription(tree) .setMessage("Interfaces can take at most " + MAX_NUM_ARGS + " arguments.") .build(); } return Description.NO_MATCH; }

Target:
public Description matchMethod(MethodTree tree, VisitorState state) { if (IS_OVERRIDE.matches(tree, state)) { return Description.NO_MATCH; } Symbol.MethodSymbol symbol = ASTHelpers.getSymbol(tree); if (symbol == null || symbol.isConstructor()) { return Description.NO_MATCH; } if (tree.getParameters().size() > MAX_NUM_ARGS) { return buildDescription(tree) .setMessage("Interfaces can take at most " + MAX_NUM_ARGS + " arguments. Consider the following ways of soling the problem:\n" + "- Define an object with Immutables that contains all of the arguments\n" + "- Expose smaller interfaces by refactorings concepts into separate interfaces") .build(); } return Description.NO_MATCH; }
Source:
public void deleteProjectOverviewNote(ProjectOverview projectOverview, Long noteId) throws IOException { authorizationManager.throwIfNonAdmin(); if (noteId == null || noteId.equals(Note.UNSAVED_ID)) { throw new IllegalArgumentException("Cannot delete an unsaved Note"); } ProjectOverview managed = projectStore.getProjectOverviewById(projectOverview.getId()); Note deleteNote = null; for (Note note : managed.getNotes()) { if (note.getNoteId().equals(noteId)) { deleteNote = note; break; } } if (deleteNote == null) { throw new IOException("Note " + noteId + " not found for ProjectOverview " + projectOverview.getId()); } managed.getNotes().remove(deleteNote); projectStore.saveOverview(managed); }

Target:
public void deleteProjectOverviewNote(ProjectOverview projectOverview, Long noteId) throws IOException { if (noteId == null || noteId.equals(Note.UNSAVED_ID)) { throw new IllegalArgumentException("Cannot delete an unsaved Note"); } ProjectOverview managed = projectStore.getProjectOverviewById(projectOverview.getId()); Note deleteNote = null; for (Note note : managed.getNotes()) { if (note.getNoteId().equals(noteId)) { deleteNote = note; break; } } if (deleteNote == null) { throw new IOException("Note " + noteId + " not found for ProjectOverview " + projectOverview.getId()); } authorizationManager.throwIfNonAdminOrMatchingOwner(deleteNote.getOwner()); managed.getNotes().remove(deleteNote); projectStore.saveOverview(managed); }
Source:
private Map<String, Double> calculateWeightedPercentagePerOption(Map<String, Integer> answerFrequency) { Map<String, Double> weightedPercentagePerOption = new LinkedHashMap<>(); if (!hasAssignedWeights) { return weightedPercentagePerOption; } for (int i = 0; i < mcqChoices.size(); i++) { String option = mcqChoices.get(i); double weight = mcqWeights.get(i); weightedPercentagePerOption.put(option, weight); } if (otherEnabled) { weightedPercentagePerOption.put("Other", mcqOtherWeight); } for (String key : weightedPercentagePerOption.keySet()) { int frequency = answerFrequency.get(key); double weight = weightedPercentagePerOption.get(key); double weightedPercentage = 100 * ((frequency * weight) / calculateTotalWeightedResponseCount(answerFrequency)); weightedPercentagePerOption.put(key, weightedPercentage); } return weightedPercentagePerOption; }

Target:
private Map<String, Double> calculateWeightedPercentagePerOption(Map<String, Integer> answerFrequency) { Map<String, Double> weightedPercentagePerOption = new LinkedHashMap<>(); Assumption.assertTrue("Weights should be enabled when calling the function", hasAssignedWeights); double totalWeightedResponseCount = calculateTotalWeightedResponseCount(answerFrequency); for (int i = 0; i < mcqChoices.size(); i++) { String option = mcqChoices.get(i); double weight = mcqWeights.get(i); weightedPercentagePerOption.put(option, weight); } if (otherEnabled) { weightedPercentagePerOption.put("Other", mcqOtherWeight); } for (String key : weightedPercentagePerOption.keySet()) { int frequency = answerFrequency.get(key); double weight = weightedPercentagePerOption.get(key); double weightedPercentage = totalWeightedResponseCount == 0 ? 0 : 100 * ((frequency * weight) / totalWeightedResponseCount); weightedPercentagePerOption.put(key, weightedPercentage); } return weightedPercentagePerOption; }
Source:
public static Optional<GameData> parse(final URI mapUri) { final Optional<InputStream> inputStream = UrlStreams.openStream(mapUri); if (inputStream.isEmpty()) { return Optional.empty(); } try (InputStream input = inputStream.get()) { return Optional.of(parse(mapUri.toString(), input, new XmlGameElementMapper())); } catch (final EngineVersionException e) { log.log(Level.WARNING, "Game engine not compatible with: " + mapUri, e); return Optional.empty(); } catch (final GameParseException e) { log.log(Level.WARNING, "Could not parse:" + mapUri, e); return Optional.empty(); } catch (final IOException e) { log.log(Level.SEVERE, "Error opening file: " + mapUri + ", " + e.getMessage(), e); return Optional.empty(); } }

Target:
public static Optional<GameData> parse(final URI mapUri) { return UrlStreams.openStream( mapUri, inputStream -> { try { return parse(mapUri.toString(), inputStream, new XmlGameElementMapper()); } catch (final EngineVersionException e) { log.log(Level.WARNING, "Game engine not compatible with: " + mapUri, e); return null; } catch (final GameParseException e) { log.log(Level.WARNING, "Could not parse:" + mapUri, e); return null; } }); }
Source:
public QueryResult query(final Query query, final TimeUnit timeUnit) { Call<QueryResult> call = null; if (query instanceof BoundParameterQuery) { BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query; call = this.influxDBService.query(this.username, this.password, query.getDatabase(), TimeUtil.toTimePrecision(timeUnit), query.getCommandWithUrlEncoded(), boundParameterQuery.getParameterJsonWithUrlEncoded()); } else { call = this.influxDBService.query(this.username, this.password, query.getDatabase(), TimeUtil.toTimePrecision(timeUnit), query.getCommandWithUrlEncoded()); } return execute(call); }

Target:
public QueryResult query(final Query query, final TimeUnit timeUnit) { Call<QueryResult> call = null; if (query instanceof BoundParameterQuery) { BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query; call = this.influxDBService.query(this.username, this.password, query.getDatabase(), TimeUtil.toTimePrecision(timeUnit), query.getCommandWithUrlEncoded(), boundParameterQuery.getParameterJsonWithUrlEncoded()); } else { call = this.influxDBService.query(this.username, this.password, query.getDatabase(), TimeUtil.toTimePrecision(timeUnit), query.getCommandWithUrlEncoded()); } return executeQuery(call); }
Source:
private EventResult runConnectHostToPoolEvent(final Guid storagePoolId, final VDS vds) { EventResult result = new EventResult(true, EventType.VDSCONNECTTOPOOL); storage_pool storagePool = getStoragePoolDAO().get(storagePoolId); StorageDomain masterDomain = getStorageDomainDAO().getStorageDomainForPoolByType(storagePoolId, StorageDomainType.Master); boolean shouldProceedVdsStats = true; try { runVdsCommand(VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), storagePoolId, vds.getVdsSpmId(), masterDomain.getId(), storagePool.getmaster_domain_version())).getSucceeded(); } catch (VdcBLLException e) { boolean isMasterDomainInactiveOrUnknown = (masterDomain.getStatus() == StorageDomainStatus.InActive || masterDomain.getStatus() == StorageDomainStatus.Unknown); if (e.getErrorCode() != VdcBllErrors.VDS_NETWORK_ERROR && isMasterDomainInactiveOrUnknown) { shouldProceedVdsStats = false; result.setSuccess(true); } else { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } } catch (RuntimeException exp) { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } if (result.isSuccess() && shouldProceedVdsStats) { result.setSuccess(proceedVdsStats()); if (!result.isSuccess()) { AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.VDS_STORAGE_VDS_STATS_FAILED); } } return result; }

Target:
private EventResult runConnectHostToPoolEvent(final Guid storagePoolId, final VDS vds) { EventResult result = new EventResult(true, EventType.VDSCONNECTTOPOOL); storage_pool storagePool = getStoragePoolDAO().get(storagePoolId); StorageDomain masterDomain = getStorageDomainDAO().getStorageDomainByTypeAndPool(storagePoolId, StorageDomainType.Master); boolean shouldProceedVdsStats = true; try { runVdsCommand(VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), storagePoolId, vds.getVdsSpmId(), masterDomain.getId(), storagePool.getmaster_domain_version())).getSucceeded(); } catch (VdcBLLException e) { if (e.getErrorCode() != VdcBllErrors.VDS_NETWORK_ERROR && e.getErrorCode() != VdcBllErrors.PROTOCOL_ERROR && (masterDomain.getStatus() == StorageDomainStatus.InActive || masterDomain.getStatus() == StorageDomainStatus.Unknown)) { shouldProceedVdsStats = false; } else { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } } catch (RuntimeException exp) { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } if (result.isSuccess() && shouldProceedVdsStats) { result.setSuccess(proceedVdsStats()); if (!result.isSuccess()) { AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.VDS_STORAGE_VDS_STATS_FAILED); } } return result; }