auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private LinuxStyles() { ImmutableMap.Builder<String, LinuxStyle> builder = new Builder<>(); builder.put("UNKNOWN", new LinuxStyle(new RGB(100, 100, 100), 33)); builder.put("WAIT_UNKNOWN", new LinuxStyle(new RGB(200, 200, 200), 50)); builder.put("WAIT_BLOCKED", new LinuxStyle(new RGB(200, 200, 0), 50)); builder.put("WAIT_FOR_CPU", new LinuxStyle(new RGB(200, 100, 0), 50)); builder.put("IDLE", new LinuxStyle(new RGB(200, 200, 200), 66)); builder.put("USERMODE", new LinuxStyle(new RGB(0, 200, 0), 100)); builder.put("SYSCALL", new LinuxStyle(new RGB(0, 0, 200), 100)); LinuxStyle irqStyle = new LinuxStyle(new RGB(200, 0, 100), 75); builder.put("INTERRUPTED", irqStyle); builder.put("IRQ", irqStyle); builder.put("IRQ_ACTIVE", irqStyle); <START> builder.put("SOFT_IRQ_RAISED", new LinuxStyle(new RGB(200, 200, 0), 50)); END> LinuxStyle softIrqStyle = new LinuxStyle(new RGB(200, 150, 100), 75); builder.put("SOFT_IRQ", softIrqStyle); builder.put("SOFT_IRQ_ACTIVE", softIrqStyle); fRegistry = builder.build(); }</code><technical_language>wondering if height hint view instead of global... some views want a varying treatment IRQ state..</technical_language>

Target:
private LinuxStyles() { ImmutableMap.Builder<String, LinuxStyle> builder = new Builder<>(); builder.put("UNKNOWN", new LinuxStyle(Messages.LinuxStyles_unknown, new RGB(100, 100, 100), 0.33f)); builder.put("WAIT_UNKNOWN", new LinuxStyle(Messages.LinuxStyles_wait, new RGB(200, 200, 200), 0.50f)); builder.put("WAIT_BLOCKED", new LinuxStyle(Messages.LinuxStyles_waitBlocked, new RGB(200, 200, 0), 0.50f)); builder.put("WAIT_FOR_CPU", new LinuxStyle(Messages.LinuxStyles_waitForCPU, new RGB(200, 100, 0), 0.50f)); builder.put("IDLE", new LinuxStyle(Messages.LinuxStyles_idle, new RGB(200, 200, 200), 0.66f)); builder.put("USERMODE", new LinuxStyle(Messages.LinuxStyles_usermode, new RGB(0, 200, 0), 1.00f)); builder.put("SYSCALL", new LinuxStyle(Messages.LinuxStyles_systemCall, new RGB(0, 0, 200), 1.00f)); builder.put("INTERRUPTED", new LinuxStyle(Messages.LinuxStyles_Interrupt, new RGB(200, 0, 100), 0.75f)); builder.put("IRQ", new LinuxStyle(Messages.LinuxStyles_Interrupt, new RGB(200, 0, 100), 0.75f)); builder.put("IRQ_ACTIVE", new LinuxStyle(Messages.LinuxStyles_Interrupt, new RGB(200, 0, 100), 0.75f)); builder.put("SOFT_IRQ_RAISED", new LinuxStyle(Messages.LinuxStyles_softIrqRaised, new RGB(200, 200, 0), 1.00f)); builder.put("SOFT_IRQ", new LinuxStyle(Messages.LinuxStyles_softrq, new RGB(200, 150, 100), 1.00f)); builder.put("SOFT_IRQ_ACTIVE", new LinuxStyle(Messages.LinuxStyles_softrq, new RGB(200, 150, 100), 1.00f)); fRegistry = builder.build(); }
Source:
<code>private void processCheckpoint(StreamAddressSpace streamAddressSpace, Function<ILogData, BackpointerOp> filter, NavigableSet<Long> queue) { List<Long> checkpointAddresses = new ArrayList<>(); streamAddressSpace.getAddressMap().forEach(checkpointAddresses::add); Collections.reverse(checkpointAddresses); Iterable<List<Long>> batches = Iterables.partition(checkpointAddresses, runtime.getParameters().getCheckpointReadBatchSize()); boolean checkpointResolved = false; for (List<Long> batch : batches) { if (checkpointResolved) { break; } try { List<ILogData> entries = readAll(batch); for (ILogData data : entries) { checkpointResolved = filterCheckpointEntry(data, filter, queue); if (checkpointResolved) { break; } } } catch (TrimmedException te) { long lastReadAddress = Address.NON_ADDRESS; <START> try { <END> for (long address : batch) { lastReadAddress = address; ILogData data = read(address); checkpointResolved = filterCheckpointEntry(data, filter, queue); if (checkpointResolved) { break; } } } catch (TrimmedException ste) { if (options.ignoreTrimmed) { log.warn("processCheckpoint[{}]: Ignoring trimmed exception for address[{}]," + " stream[{}]", this, lastReadAddress, id); } else { throw ste; } } } } }</code><technical_language>refactor this block? throwing a trimmed exception a catch block of a trimmed exception</technical_language>

Target:
private void processCheckpoint(StreamAddressSpace streamAddressSpace, Function<ILogData, BackpointerOp> filter, NavigableSet<Long> queue) { List<Long> checkpointAddresses = new ArrayList<>(); streamAddressSpace.getAddressMap().forEach(checkpointAddresses::add); checkpointAddresses.sort(null); Collections.reverse(checkpointAddresses); Iterable<List<Long>> batches = Iterables.partition(checkpointAddresses, runtime.getParameters().getCheckpointReadBatchSize()); boolean checkpointResolved = false; for (List<Long> batch : batches) { if (checkpointResolved) { break; } try { List<ILogData> entries = readAll(batch); for (ILogData data : entries) { checkpointResolved = filterCheckpointEntry(data, filter, queue); if (checkpointResolved) { break; } } } catch (TrimmedException te) { checkpointResolved = processCheckpointBatchByEntry(batch, filter, queue); } } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < sortParameters.size(); i++) { sb.append(sortParameters.get(i).toString()); <START> if (i < sortParameters.size() - 1) sb.append(";"); <END> } return sb.toString(); }</code><technical_language>sortParameters.size() - 1 computed result stored in a variable is in loop. Curly braces _if_ please :)</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); int paddedSize = sortParameters.size() - 1; for (int i = 0 ; i < sortParameters.size(); i++) { sb.append(sortParameters.get(i).toString()); if (i < paddedSize) { sb.append(";"); } } return sb.toString(); }
Source:
<code>public static String parseProcess(String processField, Map<String, Object> fieldsMap) { @Nullable JsonObject root = G_SON.fromJson(processField, JsonObject.class); String name = String.valueOf(optString(root, IOpenTracingConstants.SERVICE_NAME)); if (name == "null") { return ""; } JsonArray tags = optJSONArray(root, IOpenTracingConstants.TAGS); if (tags != null) { for (int i = 0; i < tags.size(); i++) { String key = Objects.requireNonNull(tags.get(i).getAsJsonObject().get("key").getAsString()); JsonElement element = Objects.requireNonNull(tags.get(i).getAsJsonObject().get("value")); String value = String.valueOf(element.isJsonPrimitive() ? element.getAsJsonPrimitive().getAsString() : element.toString()); fieldsMap.put(IOpenTracingConstants.PROCESS_TAGS + <START> "/" + <END> key, value); } } fieldsMap.put(IOpenTracingConstants.PROCESS_ID, name); return name; }</code><technical_language>'/'</technical_language>

Target:
public static String parseProcess(String processField, Map<String, Object> fieldsMap) { @Nullable JsonObject root = G_SON.fromJson(processField, JsonObject.class); String name = String.valueOf(optString(root, IOpenTracingConstants.SERVICE_NAME)); if (name == "null") { return ""; } JsonArray tags = optJSONArray(root, IOpenTracingConstants.TAGS); if (tags != null) { for (int i = 0; i < tags.size(); i++) { String key = Objects.requireNonNull(tags.get(i).getAsJsonObject().get("key").getAsString()); JsonElement element = Objects.requireNonNull(tags.get(i).getAsJsonObject().get("value")); String value = String.valueOf(element.isJsonPrimitive() ? element.getAsJsonPrimitive().getAsString() : element.toString()); fieldsMap.put(IOpenTracingConstants.PROCESS_TAGS + '/' + key, value); } } fieldsMap.put(IOpenTracingConstants.PROCESS_ID, name); return name; }
Source:
<code>private BulkFormat<RowData, ? super HiveSourceSplit> createBulkFormatForSplit(HiveSourceSplit split) { if (!useMapRedReader && useParquetVectorizedRead(split.getHiveTablePartition())) { return ParquetColumnarRowInputFormat.createPartitionedFormat( jobConfWrapper.conf(), (RowType) producedDataType.getLogicalType(), partitionKeys, jobConfWrapper.conf().get(HiveConf.ConfVars.DEFAULTPARTITIONNAME.varname, HiveConf.ConfVars.DEFAULTPARTITIONNAME.defaultStrVal), <START> (PartitionValueConverter) (colName, valStr, type) -> split.getHiveTablePartition().getPartitionSpec().get(colName), <END> DEFAULT_SIZE, hiveVersion.startsWith("3"), false ); } else { return new HiveMapRedBulkFormat(); } }</code><technical_language>This fail partition values in path. I create <LINK_0> refactor this</technical_language>

Target:
private BulkFormat<RowData, ? super HiveSourceSplit> createBulkFormatForSplit(HiveSourceSplit split) { if (!useMapRedReader && useParquetVectorizedRead(split.getHiveTablePartition())) { PartitionFieldExtractor<HiveSourceSplit> extractor = (PartitionFieldExtractor<HiveSourceSplit>) (split1, fieldName, fieldType) -> split1.getHiveTablePartition().getPartitionSpec().get(fieldName); return ParquetColumnarRowInputFormat.createPartitionedFormat( jobConfWrapper.conf(), producedRowType, partitionKeys, extractor, DEFAULT_SIZE, hiveVersion.startsWith("3"), false ); } else { return new HiveMapRedBulkFormat(); } }
Source:
<code>public void importDCTerms(String xmlToParse, DatasetVersion datasetVersion, DatasetFieldServiceBean datasetFieldSvc, MetadataBlockServiceBean blockService, SettingsServiceBean settingsService) { DatasetDTO datasetDTO = this.initializeDataset(); try { Map fileMap = mapDCTerms(xmlToParse, datasetDTO); Gson gson = new Gson(); String json = gson.toJson(datasetDTO.getDatasetVersion()); JsonReader jsonReader = Json.createReader(new StringReader(json)); JsonObject obj = jsonReader.readObject(); DatasetVersion dv = new JsonParser(datasetFieldSvc, blockService, settingsService).parseDatasetVersion(obj, datasetVersion); } catch (XMLStreamException | JsonParseException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>printing stacktraces please. I part of making code more beautiful, still</technical_language>

Target:
public void importDCTerms(String xmlToParse, DatasetVersion datasetVersion, DatasetFieldServiceBean datasetFieldSvc, MetadataBlockServiceBean blockService, SettingsServiceBean settingsService) { DatasetDTO datasetDTO = this.initializeDataset(); try { Map<String, String> fileMap = mapDCTerms(xmlToParse, datasetDTO); Gson gson = new Gson(); String json = gson.toJson(datasetDTO.getDatasetVersion()); JsonReader jsonReader = Json.createReader(new StringReader(json)); JsonObject obj = jsonReader.readObject(); DatasetVersion dv = new JsonParser(datasetFieldSvc, blockService, settingsService).parseDatasetVersion(obj, datasetVersion); } catch (XMLStreamException | JsonParseException e) { e.printStackTrace(); } }
Source:
<code>public void testCompleteFailure() throws InterruptedException, TimeoutException { MutateRowsRequest request = createRequest(2); final RetryingMutateRowsOperation underTest = createOperation(request); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { invocation.getArgumentAt(1, ClientCall.Listener.class) .onClose(io.grpc.Status.DEADLINE_EXCEEDED, new Metadata()); return null; } }).when(mutateRows).start(any(MutateRowsRequest.class), any(ClientCall.Listener.class), any(Metadata.class), any(ClientCall.class)); try { underTest.getAsyncResult().get(1, TimeUnit.MINUTES); Assert.fail("Expecting a DEADLINE_EXCEEDED exception"); } catch (ExecutionException e) { <START> e.printStackTrace(); <END> Assert.assertEquals(io.grpc.Status.DEADLINE_EXCEEDED.getCode(), io.grpc.Status.fromThrowable(e).getCode()); } clock.assertTimeWithinExpectations( TimeUnit.MILLISECONDS.toNanos(RETRY_OPTIONS.getMaxElapsedBackoffMillis())); }</code><technical_language>please remove</technical_language>

Target:
public void testCompleteFailure() throws InterruptedException, TimeoutException { MutateRowsRequest request = createRequest(2); final RetryingMutateRowsOperation underTest = createOperation(request); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { invocation.getArgumentAt(1, ClientCall.Listener.class) .onClose(io.grpc.Status.DEADLINE_EXCEEDED, new Metadata()); return null; } }).when(mutateRows).start(any(MutateRowsRequest.class), any(ClientCall.Listener.class), any(Metadata.class), any(ClientCall.class)); try { underTest.getAsyncResult().get(1, TimeUnit.MINUTES); Assert.fail("Expecting a DEADLINE_EXCEEDED exception"); } catch (ExecutionException e) { Assert.assertEquals(io.grpc.Status.DEADLINE_EXCEEDED.getCode(), io.grpc.Status.fromThrowable(e).getCode()); } clock.assertTimeWithinExpectations( TimeUnit.MILLISECONDS.toNanos(RETRY_OPTIONS.getMaxElapsedBackoffMillis())); }
Source:
<code>public void failTasksForWorker(long workerId) { synchronized (mPlanInfo) { List<Long> taskIds = mWorkerIdToTaskIds.get(workerId); if (taskIds == null) { return; } boolean statusChanged = false; for (Long taskId : taskIds) { TaskInfo taskInfo = mPlanInfo.getTaskInfo(taskId); if (taskInfo.getStatus().isFinished()) { return; } <START> if (!mPlanInfo.getStatus().isFinished()) { <END> taskInfo.setStatus(Status.FAILED); taskInfo.setErrorMessage("Job worker was lost before the task could complete"); statusChanged = true; } } if (statusChanged) { updateStatus(); } } }</code><technical_language>condition guarantee this is true if reach this statement</technical_language>

Target:
public void failTasksForWorker(long workerId) { synchronized (mPlanInfo) { if (mPlanInfo.getStatus().isFinished()) { return; } List<Long> taskIds = mWorkerIdToTaskIds.get(workerId); if (taskIds == null) { return; } boolean statusChanged = false; for (Long taskId : taskIds) { TaskInfo taskInfo = mPlanInfo.getTaskInfo(taskId); if (taskInfo == null || taskInfo.getStatus().isFinished()) { continue; } taskInfo.setStatus(Status.FAILED); taskInfo.setErrorMessage("Job worker was lost before the task could complete"); statusChanged = true; } if (statusChanged) { updateStatus(); } } }
Source:
<code>protected void unmapSecondaryIndexes(K key, V value) { if (value == null) { <START> log.trace("Attempting to build an index with a null value, skipping."); <END> return; } try { for (Index<K, V, ? extends Comparable> index : indexSpec) { String indexName = index.getName().get(); Map<Comparable, Map<K, V>> secondaryIndex = secondaryIndexes.get(indexName); for (Comparable indexKey : index.getMultiValueIndexFunction().apply(key, value)) { Map<K, V> slot = secondaryIndex.get(indexKey); if (slot != null) { slot.remove(key, value); } } } } catch (Exception e) { log.error("Received an exception while computing the index. " + "This is most likely an issue with the client's indexing function. {}", e); clearIndex(); throw e; } }</code><technical_language>I warn level logs. Trace is disabled default clients</technical_language>

Target:
protected void unmapSecondaryIndexes(K key, V value) { if (value == null) { log.warn("Attempting to build an index with a null value, skipping."); return; } try { for (Index<K, V, ? extends Comparable> index : indexSpec) { String indexName = index.getName().get(); Map<Comparable, Map<K, V>> secondaryIndex = secondaryIndexes.get(indexName); for (Comparable indexKey : index.getMultiValueIndexFunction().apply(key, value)) { Map<K, V> slot = secondaryIndex.get(indexKey); if (slot != null) { slot.remove(key, value); } } } } catch (Exception e) { log.error("Received an exception while computing the index. " + "This is most likely an issue with the client's indexing function. {}", e); clearIndex(); throw e; } }
Source:
<code>public String sitemap() { List<String> urls = new ArrayList<>(); addToolPaths(urls); addBioWorkflowPaths(urls); addOrganizationAndCollectionPaths(urls); Collections.sort(urls); <START> return String.join(System.lineSeparator(), urls); <END> }</code><technical_language>Awesome! Do cache (and invalidate) this resulting String</technical_language>

Target:
public String sitemap() { List<String> urls = new ArrayList<>(); urls.addAll(getToolPaths()); urls.addAll(getBioWorkflowPaths()); urls.addAll(getOrganizationAndCollectionPaths()); Collections.sort(urls); return String.join(System.lineSeparator(), urls); }
Source:
<code>public void next() { if (currentStation != null) <START> new GetRealLinkAndPlayTask(itsContext, currentStation, itsBinder).execute(); <END> }</code><technical_language>This plays current, next station</technical_language>

Target:
public void next() { RadioDroidApp radioDroidApp = (RadioDroidApp) getApplication(); DataRadioStation station = radioDroidApp.getFavouriteManager().getNextById(currentStation.StationUuid); if (station != null) { Utils.Play(radioDroidApp, station, itsContext, false); } }
Source:
<code><START> public InetSocketAddress getRMHAAddress(String rmId) { <END> String propName = YarnConfiguration.RM_ADDRESS + "." + rmId; String rmAddress = conf.get(propName); if (rmAddress == null) { propName = RM_HOSTNAME_PREFIX + rmId; rmAddress = conf.get(propName); } return NetUtils.createSocketAddr(rmAddress, YarnConfiguration.DEFAULT_RM_PORT, propName); }</code><technical_language>Checkstyle fails of this.' {' next line</technical_language>

Target:
public InetSocketAddress getRMHAAddress(String rmId) { YarnConfiguration yarnConf; if (conf instanceof YarnConfiguration) { yarnConf = (YarnConfiguration)conf; } else { yarnConf = new YarnConfiguration(conf); } yarnConf.set(ConfigUtils.RM_HA_ID, rmId); InetSocketAddress socketAddr = yarnConf.getSocketAddr(YarnConfiguration.RM_ADDRESS, YarnConfiguration.DEFAULT_RM_ADDRESS, YarnConfiguration.DEFAULT_RM_PORT); yarnConf.unset(ConfigUtils.RM_HA_ID); return socketAddr; }
Source:
<code>private static IconCompat getIcon(@NonNull Context context, final String url, int width, int height, @DrawableRes int defaultIcon) { Bitmap bitmap = null; try { final OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder() .url(url) .get() .build(); <START> final Response response = client.newCall(request).execute(); <END> if (response.isSuccessful()) { final InputStream inputStream = response.body().byteStream(); bitmap = BitmapFactory.decodeStream(inputStream); final Bitmap thumb = ThumbnailUtils.extractThumbnail(bitmap, width, height); final IconCompat icon = IconCompat.createWithBitmap(createCircleBitmap(thumb)); thumb.recycle(); return icon; } else { return IconCompat.createWithResource(context, defaultIcon); } } catch (Exception e) { return IconCompat.createWithResource(context, defaultIcon); } finally { if (bitmap != null) { bitmap.recycle(); } } }</code><technical_language>This job of image loader, fetch and, time, cached ready go. ###### yeah, image loader is _very_ outdated, handle this fine</technical_language>

Target:
private static IconCompat getIcon(@NonNull Context context, final String url, int width, int height, @DrawableRes int defaultIcon) { Bitmap bitmap = ImageLoader.getInstance().loadImageSync(url, new ImageSize(width, height), ImageDisplayConstants.DISPLAY_AVATAR_OPTIONS); return bitmap != null ? IconCompat.createWithBitmap(createCircleBitmap(bitmap, true)) : IconCompat.createWithResource(context, defaultIcon); }
Source:
<code>protected void updateInspect(MenuItem inspect) { boolean visible = mFeatures.isInspectorEnabled(); inspect.setVisible(visible); <START> inspect.setEnabled(visible && mState.stack.peek() != null && mModel.doc != null); <END> }</code><technical_language>Suggest push this (and logic checks stack too) a nice method in DirectoryDetails. Hide implementation MenuManager, testing test setup simple. name it. DirectoryDetails.canInspectDirectory? a more fundamental name DirectoryDetails.inValidDirectory()</technical_language>

Target:
protected void updateInspect(MenuItem inspect) { boolean visible = mFeatures.isInspectorEnabled(); inspect.setVisible(visible); inspect.setEnabled(visible && mDirDetails.canInspectDirectory()); }
Source:
<code>public void test_create_table_with_check_fail_on_update() { execute("create table t (id integer primary key, qty integer constraint check_1 check (qty > 0))"); execute("insert into t(id, qty) values(0, 1)"); refresh(); execute("select id, qty from t order by id"); assertEquals(1, response.rowCount()); assertEquals(printedTable(response.rows()), "0| 1\n"); execute("update t set qty = 1 where id = 0 returning id, qty"); <START> assertEquals(1, response.rowCount()); <END> assertEquals(printedTable(response.rows()), "0| 1\n"); expectedException.expectMessage(containsString("Failed CONSTRAINT check_1 CHECK (\"qty\" > 0) and values")); execute("update t set qty = -1 where id = 0"); }</code><technical_language>suggestion</technical_language>

Target:
public void test_create_table_with_check_fail_on_update() { execute("create table t (id integer primary key, qty integer constraint check_1 check (qty > 0))"); execute("insert into t(id, qty) values(0, 1)"); refresh(); execute("select id, qty from t order by id"); assertEquals(printedTable(response.rows()), "0| 1\n"); execute("update t set qty = 1 where id = 0 returning id, qty"); assertEquals(printedTable(response.rows()), "0| 1\n"); expectedException.expectMessage(containsString("Failed CONSTRAINT check_1 CHECK (\"qty\" > 0) and values")); execute("update t set qty = -1 where id = 0"); }
Source:
<code>public void onMissingGamePathEvent(MissingGamePathEvent event) { List<Action> actions = Collections.singletonList( new Action(i18n.get("missingGamePath.locate"), chooseEvent -> eventBus.post(new GameDirectoryChooseEvent())) ); String message = i18n.get("missingGamePath.notification"); <START> notificationService.addNotification(new ImmediateNotification(message, message, Severity.WARN, actions)); <END> }</code><technical_language>client aims non-intrusive possible. notifications sparingly in cases a user's action is required. client installed for chatting in #aeolus, a client developer game installed starts often. This user annoying notification now, time starts client. This is a PersistentNotification</technical_language>

Target:
public void onMissingGamePathEvent(MissingGamePathEvent event) { List<Action> actions = Collections.singletonList( new Action(i18n.get("missingGamePath.locate"), chooseEvent -> eventBus.post(new GameDirectoryChooseEvent())) ); String notificationText = i18n.get("missingGamePath.notification"); if (event.isImmediateUserActionRequired()) { notificationService.addNotification(new ImmediateNotification(notificationText, notificationText, Severity.WARN, actions)); } else { notificationService.addNotification(new PersistentNotification(notificationText, Severity.WARN, actions)); } }
Source:
<code><START> public boolean isAbstract() { <END> return typeElement != null && typeElement.getKind().isClass() && typeElement.getModifiers().contains( Modifier.ABSTRACT ); }</code><technical_language>kick in for interfaces, too? I need cases apart, interfaces a form of abstract type. In error message "result type abstract class interface"</technical_language>

Target:
public boolean isAbstract() { return typeElement != null && typeElement.getModifiers().contains( Modifier.ABSTRACT ); }
Source:
<code>public String getPageTitleFromUri(String uriPath, String uriQuery) { String normPath = normalizeUriPath(uriPath); boolean pathWiki = ((normPath.contains("/wiki/") && (! normPath.contains("index."))) || normPath.contains("/w/index.php/")); String titleQueryParam = null; String pageQueryParam = null; uriQuery = (uriQuery == null) ? "" : uriQuery; uriQuery = (uriQuery.startsWith("?")) ? uriQuery.substring(1): uriQuery; final String[] pairs = uriQuery.split("&"); for (String pair : pairs) { <START> final int idx = pair.indexOf("="); <END> final String key = idx > 0 ? pair.substring(0, idx) : pair; if ((key.equals("title") && (titleQueryParam == null))) titleQueryParam = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1).replace("+", "_") : null; if ((key.equals("page")) && (pageQueryParam == null)) pageQueryParam = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1).replace("+", "_") : null; if ((titleQueryParam != null) && (pageQueryParam != null)) break; } String pageTitle = UNKNOWN_PAGE_TITLE_VALUE; if (pathWiki) if (titleQueryParam != null) pageTitle = titleQueryParam; else pageTitle = getPageTitleFromPath(normPath); else if (titleQueryParam != null) pageTitle = titleQueryParam; else if (pageQueryParam != null) pageTitle = pageQueryParam; else if (! normPath.contains("index.")) pageTitle = getPageTitleFromPath(normPath); return PercentDecoder.decode(pageTitle); }</code><technical_language>Ah, a lib extract query params instead of this logic here</technical_language>

Target:
public String getPageTitleFromUri(String uriPath, String uriQuery) { String normPath = normalizeUriPath(uriPath); boolean pathWiki = ((normPath.contains("/wiki/") && (! normPath.contains("index."))) || normPath.contains("/w/index.php/")); String titleQueryParam = null; String pageQueryParam = null; uriQuery = (uriQuery == null) ? "" : uriQuery; uriQuery = (uriQuery.startsWith("?")) ? uriQuery.substring(1): uriQuery; final String[] pairs = uriQuery.split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? pair.substring(0, idx) : pair; if ((key.equals("title") && (titleQueryParam == null))) titleQueryParam = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1).replace("+", "_") : null; if ((key.equals("page")) && (pageQueryParam == null)) pageQueryParam = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1).replace("+", "_") : null; if ((titleQueryParam != null) && (pageQueryParam != null)) break; } String pageTitle = UNKNOWN_PAGE_TITLE_VALUE; if (titleQueryParam != null) pageTitle = titleQueryParam; else if (pathWiki) pageTitle = getPageTitleFromPath(normPath); else if (pageQueryParam != null) pageTitle = pageQueryParam; else if (! normPath.contains("index.")) pageTitle = getPageTitleFromPath(normPath); return PercentDecoder.decode(pageTitle); }
Source:
<code>public void shouldShowUser() { when(userDao.find(user.getLogin())).thenReturn(user); controller.show(user); assertEquals(user, result.included().get("user")); <START> } <END></code><technical_language>Matchers.is</technical_language>

Target:
public void shouldShowUser() { when(userDao.find(user.getLogin())).thenReturn(user); controller.show(user); assertThat((User) result.included().get("user"), is(user)); }
Source:
<code>protected Warning createWarning(final Matcher matcher) { final String fileName = matcher.group(1); final String lineNumber = matcher.group(2); final String category = matcher.group(3); final String message = matcher.group(4); <START> return createWarning(fileName, Integer.parseInt(lineNumber), category, message); <END> }</code><technical_language>getLineNumber exception handling</technical_language>

Target:
protected Warning createWarning(final Matcher matcher) { final String fileName = matcher.group(1); final String lineNumber = matcher.group(2); final String category = matcher.group(3); final String message = matcher.group(4); return createWarning(fileName, getLineNumber(lineNumber), category, message); }
Source:
<code>private boolean rollingRestartVpc(final Vpc vpc, final ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { s_logger.debug("Performing rolling restart of routers of VPC " + vpc); _ntwkMgr.destroyExpendableRouters(_routerDao.listByVpcId(vpc.getId()), context); final DeployDestination dest = new DeployDestination(_dcDao.findById(vpc.getZoneId()), null, null, null); final List<DomainRouterVO> oldRouters = _routerDao.listByVpcId(vpc.getId()); if (oldRouters.size() > 0) { vpc.setRollingRestart(true); } startVpc(vpc, dest, context); if (oldRouters.size() > 0) { vpc.setRollingRestart(false); } if (vpc.isRedundant() || (oldRouters.size() == 1 && oldRouters.get(0).getIsRedundantRouter())) { try { <START> Thread.sleep(10000L); <END> } catch (final InterruptedException ignored) { } } for (final DomainRouterVO oldRouter : oldRouters) { _routerService.destroyRouter(oldRouter.getId(), context.getAccount(), context.getCaller().getId()); } if (!startVpc(vpc, dest, context)) { s_logger.debug("Failed to re-program VPC router or deploy a new backup router for VPC" + vpc); return false; } return _ntwkMgr.validateNewRouters(_routerDao.listByVpcId(vpc.getId())); }</code><technical_language>do extracting 10000L a static variable</technical_language>

Target:
private boolean rollingRestartVpc(final Vpc vpc, final ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { s_logger.debug("Performing rolling restart of routers of VPC " + vpc); _ntwkMgr.destroyExpendableRouters(_routerDao.listByVpcId(vpc.getId()), context); final DeployDestination dest = new DeployDestination(_dcDao.findById(vpc.getZoneId()), null, null, null); final List<DomainRouterVO> oldRouters = _routerDao.listByVpcId(vpc.getId()); if (oldRouters.size() > 0) { vpc.setRollingRestart(true); } startVpc(vpc, dest, context); if (oldRouters.size() > 0) { vpc.setRollingRestart(false); } if (vpc.isRedundant() || (oldRouters.size() == 1 && oldRouters.get(0).getIsRedundantRouter())) { try { Thread.sleep(NetworkOrchestrationService.RVRHandoverTime); } catch (final InterruptedException ignored) { } } for (final DomainRouterVO oldRouter : oldRouters) { _routerService.destroyRouter(oldRouter.getId(), context.getAccount(), context.getCaller().getId()); } if (!startVpc(vpc, dest, context)) { s_logger.debug("Failed to re-program VPC router or deploy a new backup router for VPC" + vpc); return false; } return _ntwkMgr.areRoutersRunning(_routerDao.listByVpcId(vpc.getId())); }
Source:
<code>protected SQLServerOutputConnector getConnector(PluginTask task, boolean retryableMetadataOperation) { SQLServerPluginTask sqlServerTask = (SQLServerPluginTask) task; Driver driver; boolean useJtdsDriver = false; if (sqlServerTask.getDriverPath().isPresent()) { loadDriverJar(sqlServerTask.getDriverPath().get()); try { driver = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); } catch(Exception e) { throw new ConfigException("Driver set at field 'driver_path' doesn't include Microsoft SQLServerDriver", e); } } else { try { driver = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); } catch(Exception e) { logger.info("Using jTDS Driver"); driver = new net.sourceforge.jtds.jdbc.Driver(); useJtdsDriver = true; } } UrlAndProperties urlProps = getUrlAndProperties(sqlServerTask, useJtdsDriver); <START> logger.info("Connecting to options {}", urlProps.getUrl(), urlProps.getProps()); <END> return new SQLServerOutputConnector(driver, urlProps.getUrl(), urlProps.getProps(), null); }</code><technical_language>log database password for security reason. (Original SQLServerOutputPlugin logs properties setting password.)</technical_language>

Target:
protected SQLServerOutputConnector getConnector(PluginTask task, boolean retryableMetadataOperation) { SQLServerPluginTask sqlServerTask = (SQLServerPluginTask) task; boolean useJtdsDriver = false; if (sqlServerTask.getDriverPath().isPresent()) { loadDriverJar(sqlServerTask.getDriverPath().get()); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) { throw new ConfigException("Driver set at field 'driver_path' doesn't include Microsoft SQLServerDriver", e); } } else { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) { logger.info("Using jTDS Driver"); try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); } catch(Exception e2) { throw new ConfigException("'driver_path' doesn't set and can't found jTDS driver", e2); } useJtdsDriver = true; } } UrlAndProperties urlProps = getUrlAndProperties(sqlServerTask, useJtdsDriver); logger.info("Connecting to options {}", urlProps.getUrl(), getPropsWithMaskedSecret(urlProps)); return new SQLServerOutputConnector(urlProps.getUrl(), urlProps.getProps(), null); }
Source:
<code>protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { <START> super.checkFile(file, problemsHolder); <END> if (((ScratchFileType)ScratchFileType.INSTANCE).isMyFileType(file.getVirtualFile())) return; GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)) return; PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoPackageUtil.getAllPackagesInDirectory(dir, null, true); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { Collection<LocalQuickFix> fixes = ContainerUtil.newArrayList(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } }</code><technical_language>super.checkFile</technical_language>

Target:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (((ScratchFileType)ScratchFileType.INSTANCE).isMyFileType(file.getVirtualFile())) return; GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)) return; PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoPackageUtil.getAllPackagesInDirectory(dir, null, true); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { Collection<LocalQuickFix> fixes = ContainerUtil.newArrayList(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } }
Source:
<code>public Set<CoordinatorStreamMessage> getBoostrappedStream() { log.info("Returning the bootstrapped data from the stream"); <START> bootstrap(); <END> return bootstrappedStreamSet; }</code><technical_language>reason remove isBootstrap flag? I thought need avoid repeatedly pulling coordinatorStream</technical_language>

Target:
public Set<CoordinatorStreamMessage> getBoostrappedStream() { log.info("Returning the bootstrapped data from the stream"); if (!isBootstrapped) bootstrap(); return bootstrappedStreamSet; }
Source:
<code>public void registerBundle(String bundleUrl) { try { String nv = urlToBundleIdentifier.get(bundleUrl); if (nv!=null) { if (Osgis.bundleFinder(framework).id(nv).requiringFromUrl(bundleUrl).find().isPresent()) { log.trace("Bundle from "+bundleUrl+" already installed as "+nv+"; not re-registering"); return; } else { log.debug("Bundle "+nv+" from "+bundleUrl+" is known in map but not installed; perhaps in the process of installing?"); } } Bundle b = Osgis.install(framework, bundleUrl); nv = b.getSymbolicName()+":"+b.getVersion().toString(); List<Bundle> matches = Osgis.bundleFinder(framework).id(nv).findAll(); if (matches.isEmpty()) { <START> log.error("OSGi not find bundle "+nv+" in search after installing it from "+bundleUrl); <END> } else if (matches.size()==1) { log.debug("Bundle from "+bundleUrl+" successfully installed as " + nv + " ("+b+")"); } else { log.warn("OSGi has multiple bundles matching "+nv+", when just installed from "+bundleUrl+": "+matches+"; " + "brooklyn will prefer the URL-based bundle for top-level references but any dependencies or " + "import-packages will be at the mercy of OSGi. " + "It is recommended to use distinct versions for different bundles, and the same URL for the same bundles."); } urlToBundleIdentifier.put(bundleUrl, nv); } catch (BundleException e) { log.debug("Bundle from "+bundleUrl+" failed to install (rethrowing): "+e); throw Throwables.propagate(e); } }</code><technical_language>typo: "OSGi find"</technical_language>

Target:
public void registerBundle(String bundleUrl) { try { String nv = urlToBundleIdentifier.get(bundleUrl); if (nv!=null) { if (Osgis.bundleFinder(framework).id(nv).requiringFromUrl(bundleUrl).find().isPresent()) { log.trace("Bundle from "+bundleUrl+" already installed as "+nv+"; not re-registering"); return; } else { log.debug("Bundle "+nv+" from "+bundleUrl+" is known in map but not installed; perhaps in the process of installing?"); } } Bundle b = Osgis.install(framework, bundleUrl); nv = b.getSymbolicName()+":"+b.getVersion().toString(); List<Bundle> matches = Osgis.bundleFinder(framework).id(nv).findAll(); if (matches.isEmpty()) { log.error("OSGi could not find bundle "+nv+" in search after installing it from "+bundleUrl); } else if (matches.size()==1) { log.debug("Bundle from "+bundleUrl+" successfully installed as " + nv + " ("+b+")"); } else { log.warn("OSGi has multiple bundles matching "+nv+", when just installed from "+bundleUrl+": "+matches+"; " + "brooklyn will prefer the URL-based bundle for top-level references but any dependencies or " + "import-packages will be at the mercy of OSGi. " + "It is recommended to use distinct versions for different bundles, and the same URL for the same bundles."); } urlToBundleIdentifier.put(bundleUrl, nv); } catch (BundleException e) { log.debug("Bundle from "+bundleUrl+" failed to install (rethrowing): "+e); throw Throwables.propagate(e); } }
Source:
<code>public int center(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); Vector center = region.getCenter(); Vector vec1 = new Vector((int) center.getX(), (int) center.getY(), (int) center.getZ()); Vector vec2 = center.toBlockVector(); boolean condX = (region.getWidth() % 2) == 0; boolean condZ = (region.getLength() % 2) == 0; <START> Vector vec3 = new Vector(vec2.getX() + (condX ? 0.5*Math.signum(vec2.getX()) : 0), vec2.getY(), vec2.getZ() + (condZ ? 0.5*Math.signum(vec2.getZ()) : 0)); <END> Region centerRegion = new CuboidRegion( getWorld(), vec1, vec3); return setBlocks(centerRegion, pattern); }</code><technical_language>pull this logic out a method, explain it</technical_language>

Target:
public int center(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); Vector center = region.getCenter(); Vector vec2 = center.toBlockVector(); Region centerRegion = new CuboidRegion( getWorld(), new Vector((int) center.getX(), (int) center.getY(), (int) center.getZ()), new Vector(MathUtils.round(vec2.getX()), vec2.getY(), MathUtils.round(vec2.getZ()))); return setBlocks(centerRegion, pattern); }
Source:
<code>public void okPressed(Kontakt k) { for (int i = 0; i < fieldDefinitions.length; i++) { String value = values[i].getText(); if ((savedValues == null && !value.isEmpty()) || (savedValues[i] != null && !savedValues[i].equals(value))) { k.setInfoElement(fields[i], value); String xid = xids.get(fields[i]); if (xid != null) { logger.debug("okPressed: Updating field {}: key value -> {}", i, fields[i], xid, <START> savedValues[i], value); <END> k.addXid(xid, value, true); } } } }</code><technical_language>please</technical_language>

Target:
public void okPressed(Kontakt k) { for (int i = 0; i < fieldDefinitions.length; i++) { String value = values[i].getText(); if ((savedValues == null && !value.isEmpty()) || (savedValues[i] != null && !savedValues[i].equals(value))) { k.setInfoElement(fields[i], value); String xid = xids.get(fields[i]); if (xid != null) { k.addXid(xid, value, true); } } } }
Source:
<code>public int getLinePixel(int lineIndex) { checkWidget(); int lineCount = content.getLineCount(); lineIndex = Math.max(0, Math.min(lineCount, lineIndex)); if (isFixedLineHeight()) { int lineHeight = renderer.getLineHeight(); return lineIndex * lineHeight - getVerticalScrollOffset() + topMargin; } if (lineIndex == topIndex) return topIndexY + topMargin; int height = topIndexY; if (lineIndex > topIndex) { for (int i = topIndex; i < lineIndex; i++) { height += renderer.getCachedLineHeight(i); } } else { for (int i = topIndex - 1; i >= lineIndex; i--) { <START> height -= renderer.getCachedLineHeight(i); <END> } } return height + topMargin; }</code><technical_language>thing, this method getLinePixel method return erroneous result, regressions in customers (I code minings this method extensively compute draw for instance)</technical_language>

Target:
public int getLinePixel(int lineIndex) { checkWidget(); int lineCount = content.getLineCount(); lineIndex = Math.max(0, Math.min(lineCount, lineIndex)); if (isFixedLineHeight()) { int lineHeight = renderer.getLineHeight(); return lineIndex * lineHeight - getVerticalScrollOffset() + topMargin; } if (lineIndex == topIndex) return topIndexY + topMargin; int height = topIndexY; if (lineIndex > topIndex) { for (int i = topIndex; i < lineIndex; i++) { height += renderer.getLineHeight(i); } } else { for (int i = topIndex - 1; i >= lineIndex; i--) { height -= renderer.getLineHeight(i); } } return height + topMargin; }
Source:
<code>private String renderGibibyteSize(long size) { long <START> sizeInGB = <END> (unit == SizeUnit.GiB) ? size : SizeConverter.convert(size, unit, SizeUnit.GiB).longValue(); return messages.gibibytes(sizeInGB >= 1 ? String.valueOf(sizeInGB) : "< 1"); }</code><technical_language>sizeInGiB</technical_language>

Target:
private String renderGibibyteSize(long size) { long sizeInGiB = (unit == SizeUnit.GiB) ? size : SizeConverter.convert(size, unit, SizeUnit.GiB).longValue(); return messages.gibibytes(sizeInGiB >= 1 ? String.valueOf(sizeInGiB) : "< 1"); }
Source:
<code>public static String resolveWildCardForJarSpec(String workingDirectory, String unresolvedJarSpec, Logger log) { log.debug("resolveWildCardForJarSpec: unresolved jar specification: " + unresolvedJarSpec); if (unresolvedJarSpec == null || unresolvedJarSpec.isEmpty()) return null; StringBuilder resolvedJarSpec = new StringBuilder(); String[] unresolvedJarSpecList = unresolvedJarSpec.split(","); for (String s : unresolvedJarSpecList) { if (s.endsWith("*")) { String fileName = String.format("%s/%s", workingDirectory, s.substring(0, s.length() - 2)); String[] jarList = new File(fileName).list(jarFilter); for (String ls : jarList) { <START> String lsFilename = fileName + "/" + ls + ","; <END> resolvedJarSpec.append(lsFilename); } } else { resolvedJarSpec.append(s + ","); } } log.debug("resolveWildCardForJarSpec: resolvedJarSpec: " + resolvedJarSpec); int lastCharIndex = resolvedJarSpec.length() - 1; if (lastCharIndex >= 0 && resolvedJarSpec.charAt(lastCharIndex) == ',') { resolvedJarSpec.deleteCharAt(lastCharIndex); } return resolvedJarSpec.toString(); }</code><technical_language>if this directory files other jars</technical_language>

Target:
public static String resolveWildCardForJarSpec(String workingDirectory, String unresolvedJarSpec, Logger log) { log.debug("resolveWildCardForJarSpec: unresolved jar specification: " + unresolvedJarSpec); log.debug("working directory: " + workingDirectory); if (unresolvedJarSpec == null || unresolvedJarSpec.isEmpty()) return ""; StringBuilder resolvedJarSpec = new StringBuilder(); String[] unresolvedJarSpecList = unresolvedJarSpec.split(","); for (String s : unresolvedJarSpecList) { if (s.endsWith("*")) { String dirName = String.format("%s/%s", workingDirectory, s.substring(0, s.length() - 2)); File[] jars = null; try { jars = getFilesInFolderByRegex(new File(dirName), ".*jar"); } catch (FileNotFoundException fnfe) { log.warn("folder does not exist: " + dirName); continue; } for (File jar : jars) { resolvedJarSpec.append(jar.toString()).append(","); } } else { resolvedJarSpec.append(s).append(","); } } log.debug("resolveWildCardForJarSpec: resolvedJarSpec: " + resolvedJarSpec); int lastCharIndex = resolvedJarSpec.length() - 1; if (lastCharIndex >= 0 && resolvedJarSpec.charAt(lastCharIndex) == ',') { resolvedJarSpec.deleteCharAt(lastCharIndex); } return resolvedJarSpec.toString(); }
Source:
<code>public static Parameter[] filter(final Parameter[] parameters, final Set<InjectableParameter> filters) { if (filters != null && !filters.isEmpty()) { boolean firstMethodFiltered = false; final List<Parameter> filterList = new ArrayList<>(parameters.length); for (final Parameter parameter : parameters) { boolean omit = false; for (final InjectableParameter injectableParameter : filters) { <START> if (injectableParameter == null) { <END> continue; } omit = canInject(parameter, injectableParameter); switch (injectableParameter) { case CURRENT_TEST_METHOD: if (omit && !firstMethodFiltered) { firstMethodFiltered = true; } else { omit = false; } break; default: break; } if (omit) { break; } } if (!omit) { filterList.add(parameter); } } final Parameter[] filteredArray = new Parameter[filterList.size()]; return filterList.toArray(filteredArray); } else { return parameters; } }</code><technical_language>is internal code, enforce pass null values in set</technical_language>

Target:
public static Parameter[] filter(final Parameter[] parameters, final Set<InjectableParameter> filters) { if (filters != null && !filters.isEmpty()) { boolean firstMethodFiltered = false; final List<Parameter> filterList = new ArrayList<>(parameters.length); for (final Parameter parameter : parameters) { boolean omit = false; for (final InjectableParameter injectableParameter : filters) { omit = canInject(parameter, injectableParameter); switch (injectableParameter) { case CURRENT_TEST_METHOD: if (omit && !firstMethodFiltered) { firstMethodFiltered = true; } else { omit = false; } break; default: break; } if (omit) { break; } } if (!omit) { filterList.add(parameter); } } final Parameter[] filteredArray = new Parameter[filterList.size()]; return filterList.toArray(filteredArray); } else { return parameters; } }
Source:
<code>public void reconnect(final long hostId) throws CloudRuntimeException, AgentUnavailableException{ HostVO host; host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { throw new CloudRuntimeException("Unable to find host " + hostId); } if (host.getStatus() == Status.Disconnected) { <START> throw new CloudRuntimeException("Host is already disconnected, no work to be done"); <END> } if (host.getStatus() != Status.Up && host.getStatus() != Status.Alert && host.getStatus() != Status.Rebalancing) { throw new CloudRuntimeException("Unable to disconnect host because it is not in the correct state: host=" + hostId + "; Status=" + host.getStatus()); } final AgentAttache attache = findAttache(hostId); if (attache == null) { throw new CloudRuntimeException("Unable to disconnect host because it is not connected to this server: " + hostId); } disconnectWithoutInvestigation(attache, Event.ShutdownRequested); }</code><technical_language>This wrong me, throwing exception done</technical_language>

Target:
public void reconnect(final long hostId) throws AgentUnavailableException { HostVO host = _hostDao.findById(hostId); if (host == null) { throw new CloudRuntimeException("Unable to find host: " + hostId); } if (host.getRemoved() != null) { throw new CloudRuntimeException("Host has already been removed: " + hostId); } if (host.getStatus() == Status.Disconnected) { s_logger.debug("Host is already disconnected, no work to be done: " + hostId); return; } if (host.getStatus() != Status.Up && host.getStatus() != Status.Alert && host.getStatus() != Status.Rebalancing) { throw new CloudRuntimeException("Unable to disconnect host because it is not in the correct state: host=" + hostId + "; Status=" + host.getStatus()); } AgentAttache attache = findAttache(hostId); if (attache == null) { throw new CloudRuntimeException("Unable to disconnect host because it is not connected to this server: " + hostId); } disconnectWithoutInvestigation(attache, Event.ShutdownRequested); }