auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void deregisterMetrics() { super.deregisterMetrics(); updateNumTopics(0); updateNumAutoPausedPartitionsAwaitingDestTopic(0); updateNumAutoPausedPartitionsOnError(0); updateNumConfigPausedPartitions(0); updateNumAutoPausedPartitionsOnInFlightMessages(0); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_CONFIG_PAUSED_PARTITIONS); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_AUTO_PAUSED_PARTITIONS_ON_ERROR); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_AUTO_PAUSED_PARTITIONS_ON_INFLIGHT_MESSAGES); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_AUTO_PAUSED_PARTITIONS_WAITING_FOR_DEST_TOPIC); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_TOPICS); if (_pollDurationMsMetric != null) { DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, POLL_DURATION_MS); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, TIME_SPENT_BETWEEN_POLLS_MS); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, PER_EVENT_PROCESSING_TIME_NANOS); } <START> if (_kafkaConsumerMetricsRegistered) { <END> DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, CONSUMER_OFFSET_WATERMARK_SPAN); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, CONSUMER_LICLOSEST_DATA_LOSS_ESTIMATION); } }</code><technical_language>I a strong opinion matter unregisterMetric no-ops if metric registered. This spare maintain check _kafkaConsumerMetricsRegistered</technical_language>

Target:
public void deregisterMetrics() { super.deregisterMetrics(); updateNumTopics(0); updateNumAutoPausedPartitionsAwaitingDestTopic(0); updateNumAutoPausedPartitionsOnError(0); updateNumConfigPausedPartitions(0); updateNumAutoPausedPartitionsOnInFlightMessages(0); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_CONFIG_PAUSED_PARTITIONS); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_AUTO_PAUSED_PARTITIONS_ON_ERROR); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_AUTO_PAUSED_PARTITIONS_ON_INFLIGHT_MESSAGES); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_AUTO_PAUSED_PARTITIONS_WAITING_FOR_DEST_TOPIC); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, NUM_TOPICS); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, CONSUMER_OFFSET_WATERMARK_SPAN); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, CONSUMER_LICLOSEST_DATA_LOSS_ESTIMATION); if (_pollDurationMsMetric != null) { DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, POLL_DURATION_MS); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, TIME_SPENT_BETWEEN_POLLS_MS); DYNAMIC_METRICS_MANAGER.unregisterMetric(_className, _key, PER_EVENT_PROCESSING_TIME_NANOS); } }
Source:
<code>private void configureForOrientation(Configuration newConfig) { LinearLayout mainContainer = getView().findViewById(R.id.cover_fragment); LinearLayout textContainer = getView().findViewById(R.id.cover_fragment_text_container); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imgvCover.getLayoutParams(); LinearLayout.LayoutParams textParams = (LinearLayout.LayoutParams) textContainer.getLayoutParams(); if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { double ratio = (float) newConfig.screenHeightDp / (float) newConfig.screenWidthDp; double percentageWidth = 0.8; if (ratio <= 1.7) { <START> percentageWidth = (ratio / 1.7) * percentageWidth * 0.8; <END> } mainContainer.setOrientation(LinearLayout.VERTICAL); if (newConfig.screenWidthDp > 0) { params.width = (int) (convertDpToPixel(newConfig.screenWidthDp) * percentageWidth); params.height = params.width; textParams.weight = 0; imgvCover.setLayoutParams(params); } } else { double ratio = (float) newConfig.screenHeightDp / (float) newConfig.screenWidthDp; double percentageHeight = 0.4; percentageHeight = (ratio / 0.5) * percentageHeight; mainContainer.setOrientation(LinearLayout.HORIZONTAL); if (newConfig.screenHeightDp > 0) { params.height = (int) (convertDpToPixel(newConfig.screenHeightDp) * percentageHeight); params.width = params.height; textParams.weight = 1; imgvCover.setLayoutParams(params); } } }</code><technical_language>1.7 magic from? (16/9)? I static final float SIXTEEN_BY_NINE = 1.8; more clear</technical_language>

Target:
private void configureForOrientation(Configuration newConfig) { LinearLayout mainContainer = getView().findViewById(R.id.cover_fragment); LinearLayout textContainer = getView().findViewById(R.id.cover_fragment_text_container); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imgvCover.getLayoutParams(); LinearLayout.LayoutParams textParams = (LinearLayout.LayoutParams) textContainer.getLayoutParams(); double ratio = (float) newConfig.screenHeightDp / (float) newConfig.screenWidthDp; if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { double percentageWidth = 0.8; if (ratio <= SIXTEEN_BY_NINE) { percentageWidth = (ratio / SIXTEEN_BY_NINE) * percentageWidth * 0.8; } mainContainer.setOrientation(LinearLayout.VERTICAL); if (newConfig.screenWidthDp > 0) { params.width = (int) (convertDpToPixel(newConfig.screenWidthDp) * percentageWidth); params.height = params.width; textParams.weight = 0; imgvCover.setLayoutParams(params); } } else { double percentageHeight = ratio * 0.8; mainContainer.setOrientation(LinearLayout.HORIZONTAL); if (newConfig.screenHeightDp > 0) { params.height = (int) (convertDpToPixel(newConfig.screenHeightDp) * percentageHeight); params.width = params.height; textParams.weight = 1; imgvCover.setLayoutParams(params); } } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); setTheme(R.style.Theme_Piwigo_Login); super.onCreate(savedInstanceState); idleResource = new CountingIdlingResource("LoginActivity", true); <START> userManager.setIdleResource(idleResource); <END> authenticatorResponse = getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); if (authenticatorResponse != null) { authenticatorResponse.onRequestContinued(); } viewModel = ViewModelProviders.of(this, viewModelFactory).get(LoginViewModel.class); binding = DataBindingUtil.setContentView(this, R.layout.activity_login); binding.setViewModel(viewModel); urlEditText = findViewById(R.id.url); loginButton = findViewById(R.id.login_button); fabProgressCircle = findViewById(R.id.fabLoginCircle); viewModel.getLoginSuccess().observe(this, this::loginSuccess); viewModel.getLoginError().observe(this, this::loginError); loginButton.setOnClickListener(v -> viewModel.onLoginClick(fabProgressCircle)); urlEditText.setOnTouchListener((v, event) -> { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (urlEditText.getRight() - urlEditText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { DialogHelper.INSTANCE.showInfoDialog(R.string.login_url_hint, R.string.login_url_how_to, LoginActivity.this); return true; } } return false; }); handleIntent(getIntent()); }</code><technical_language>ah ok, idling resource IS incremented moreBusy... mh. - I catch it..</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); setTheme(R.style.Theme_Piwigo_Login); super.onCreate(savedInstanceState); authenticatorResponse = getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); if (authenticatorResponse != null) { authenticatorResponse.onRequestContinued(); } viewModel = ViewModelProviders.of(this, viewModelFactory).get(LoginViewModel.class); binding = DataBindingUtil.setContentView(this, R.layout.activity_login); binding.setViewModel(viewModel); urlEditText = findViewById(R.id.url); loginButton = findViewById(R.id.login_button); fabProgressCircle = findViewById(R.id.fabLoginCircle); viewModel.getLoginSuccess().observe(this, this::loginSuccess); viewModel.getLoginError().observe(this, this::loginError); loginButton.setOnClickListener(v -> viewModel.onLoginClick(fabProgressCircle)); urlEditText.setOnTouchListener((v, event) -> { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (urlEditText.getRight() - urlEditText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { DialogHelper.INSTANCE.showInfoDialog(R.string.login_url_hint, R.string.login_url_how_to, LoginActivity.this); return true; } } return false; }); handleIntent(getIntent()); }
Source:
<code>private void reportException(Exception e) { String msg = messageOf(e); try { LOG.error(msg, e); printlnSafely(msg); } catch (Exception reportException) { <START> LOG.error("Unable to report error message - %s.", messageOf(e), reportException); <END> } }</code><technical_language>change this</technical_language>

Target:
private void reportException(Exception e) { String msg = messageOf(e); try { LOG.error(msg, e); printlnSafely(msg); } catch (Exception reportException) { LOG.error("Unable to report error message - {}.", messageOf(e), reportException); } }
Source:
<code>public void initalizeTimestamp(final long intervalOffset) { switch (timeUnits) { case NANOSECONDS: currentTimestamp = System.nanoTime() + getOffset(intervalOffset); startTimestamp = currentTimestamp; break; case MICROSECONDS: currentTimestamp = (System.nanoTime() / 1000) + getOffset(intervalOffset); startTimestamp = currentTimestamp; break; case MILLISECONDS: currentTimestamp = System.currentTimeMillis() + getOffset(intervalOffset); startTimestamp = currentTimestamp; break; case SECONDS: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); startTimestamp = currentTimestamp; break; case MINUTES: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); startTimestamp = currentTimestamp; break; case HOURS: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); startTimestamp = currentTimestamp; break; case DAYS: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); <START> startTimestamp = currentTimestamp; <END> break; default: throw new IllegalArgumentException("Unhandled time unit type: " + timeUnits); } }</code><technical_language>nit: do this startTimestamp = currentTimestamp right return switch/case</technical_language>

Target:
public void initalizeTimestamp(final long intervalOffset) { switch (timeUnits) { case NANOSECONDS: currentTimestamp = System.nanoTime() + getOffset(intervalOffset); break; case MICROSECONDS: currentTimestamp = (System.nanoTime() / 1000) + getOffset(intervalOffset); break; case MILLISECONDS: currentTimestamp = System.currentTimeMillis() + getOffset(intervalOffset); break; case SECONDS: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); break; case MINUTES: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); break; case HOURS: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); break; case DAYS: currentTimestamp = (System.currentTimeMillis() / 1000) + getOffset(intervalOffset); break; default: throw new IllegalArgumentException("Unhandled time unit type: " + timeUnits); } startTimestamp = currentTimestamp; }
Source:
<code><START> public void updateMessage() { <END> long hwnd = hwndToolTip(); if (OS.SendMessage (hwnd, OS.TTM_GETCURRENTTOOL, 0, 0) != 0) { TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; if (OS.SendMessage (hwnd, OS.TTM_GETCURRENTTOOL, 0, lpti) != 0) { long hHeap = OS.GetProcessHeap (); TCHAR buffer = new TCHAR (0, message, true); int byteCount = buffer.length () * TCHAR.sizeof; lpti.lpszText = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount); OS.MoveMemory (lpti.lpszText, buffer, byteCount); OS.SendMessage (hwnd, OS.TTM_UPDATETIPTEXT, 0, lpti); OS.HeapFree(hHeap, 0, lpti.lpszText); } } }</code><technical_language>This method public, instead default. - Add a space method-name braces</technical_language>

Target:
void updateMessage () { long hwnd = hwndToolTip(); if (OS.SendMessage (hwnd, OS.TTM_GETCURRENTTOOL, 0, 0) != 0) { TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; if (OS.SendMessage (hwnd, OS.TTM_GETCURRENTTOOL, 0, lpti) != 0) { long hHeap = OS.GetProcessHeap (); TCHAR buffer = new TCHAR (0, message, true); int byteCount = buffer.length () * TCHAR.sizeof; lpti.lpszText = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount); OS.MoveMemory (lpti.lpszText, buffer, byteCount); OS.SendMessage (hwnd, OS.TTM_UPDATETIPTEXT, 0, lpti); OS.HeapFree(hHeap, 0, lpti.lpszText); } } }
Source:
<code>public void waitOpen() { <START> webDriverWaitFactory.get().until(ExpectedConditions.visibilityOf(form)); <END> }</code><technical_language>ready method SeleniumWebDriverHelper#waitVisibility</technical_language>

Target:
public void waitOpen() { seleniumWebDriverHelper.waitVisibility(form); }
Source:
<code>public Default(final String... users) { <START> this.usernames = convert(users); <END> }</code><technical_language>@sebing lazily calculate in urn</technical_language>

Target:
public Default(final String... users) { this.usernames = converter(users); }
Source:
<code>private void deployAPIsInSyncMode() { isAPIsDeployedInSyncMode = deployArtifactsAtStartup(); <START> if (!isAPIsDeployedInSyncMode) { <END> log.error("Unable to deploy synapse artifacts at gateway"); deployAPIsInAsyncMode(); } }</code><technical_language>need if condition decided in sync</technical_language>

Target:
private void deployAPIsInSyncMode() { syncModeDeploymentCount ++; isAPIsDeployedInSyncMode = deployArtifactsAtStartup(); if (!isAPIsDeployedInSyncMode) { log.error("Deployment attempt : " + syncModeDeploymentCount + " was unsuccessful") ; if (!(syncModeDeploymentCount > retryCount)) { deployAPIsInSyncMode(); } else { log.error("Maximum retry limit exceeded. Server is starting without deploying all synapse artifacts"); } } else { log.info("Deployment attempt : " + syncModeDeploymentCount + " was successful"); } }
Source:
<code>public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { Class<?> erasedType = GenericTypes.getErasedType(type); if (ImmutableList.class.equals(erasedType)) { return GenericTypes.findGenericParameter(type, ImmutableList.class) <START> .flatMap(t -> config.get(ColumnMappers.class).findFor(type, config)) <END> .map(ImmutableListArrayColumnMapper::new); } return Optional.empty(); }</code><technical_language>This splitting hairs, findFor(t, config) (t instead of type)</technical_language>

Target:
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { Class<?> erasedType = GenericTypes.getErasedType(type); if (ImmutableList.class.equals(erasedType)) { return GenericTypes.findGenericParameter(type, ImmutableList.class) .flatMap(t -> config.get(ColumnMappers.class).findFor(t)) .map(ImmutableListArrayColumnMapper::new); } return Optional.empty(); }
Source:
<code>public VisualEditorPageObject typeInParameterField(int i, String parameter) { WebElement element = parametersFieldList.get(i); wait.forElementClickable(element); element.click(); <START> element.sendKeys(parameter); <END> return this; }</code><technical_language>add more descriptive name instead of element? parameterInput input field</technical_language>

Target:
public VisualEditorPageObject typeInParameterField(int i, String parameter) { WebElement field = parametersFieldList.get(i); wait.forElementClickable(field); field.click(); field.sendKeys(parameter); return this; }
Source:
<code>public void testDDiagramSetRemovalMigrationDone() { ResourceSet set = new ResourceSetImpl(); DAnalysis analysis = null; try { analysis = (DAnalysis) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + SESSION_RESOURCE_NAME, true), set); } catch (IOException e) { failCheckData(); } assertNotNull("Check the representation file test data.", analysis); assertTrue("Check the migration logic.", ((XMLResource) <START> analysis.eResource()).getEObjectToExtensionMap().size() == 0); <END> String version = analysis.getVersion(); assertTrue("Before save, the migration framework will return true even if the migration has been done during load.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); try { analysis.eResource().save(Collections.emptyMap()); } catch (IOException e) { failCheckData(); } version = analysis.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); checkFileContainDDiagramSet(analysis.eResource().getURI(), false, "After migration, the resource should not contains any DDiagramSet."); assertFalse(getErrorLoggersMessage(), doesAnErrorOccurs()); }</code><technical_language>isEmpty</technical_language>

Target:
public void testDDiagramSetRemovalMigrationDone() { ResourceSet set = new ResourceSetImpl(); DAnalysis analysis = null; try { analysis = (DAnalysis) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + SESSION_RESOURCE_NAME, true), set); } catch (IOException e) { failCheckData(); } assertNotNull("Check the representation file test data.", analysis); assertTrue("Check the migration logic.", ((XMLResource) analysis.eResource()).getEObjectToExtensionMap().isEmpty()); String version = analysis.getVersion(); assertTrue("Before save, the migration framework will return true even if the migration has been done during load.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); try { analysis.eResource().save(Collections.emptyMap()); } catch (IOException e) { failCheckData(); } version = analysis.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); checkFileContainDDiagramSet(analysis.eResource().getURI(), false, "After migration, the resource should not contains any DDiagramSet."); assertFalse(getErrorLoggersMessage(), doesAnErrorOccurs()); }
Source:
<code>protected void dropCycle(Integer cycle) { WireStore store = getStoreForCycle(cycle); File file = store.file(); if (!file.exists()) { return; <START> } <END> log.info(String.format("Deleting Chronicle file: %s according to retention: %s", file.getAbsolutePath(), retention)); try { Files.delete(file.toPath()); queue.refreshDirectlyListing(); log.debug(file + " deleted"); queue.release(store); } catch (IOException | SecurityException e) { log.warn(String.format("Unable to delete Chronicle file: %s, %s", file.getAbsolutePath(), e.getMessage())); } }</code><technical_language>storecould null, add a check</technical_language>

Target:
protected void dropCycle(Integer cycle) { WireStore store = queue.storeForCycle(cycle, queue.epoch(), false); if (store == null) { return; } File file = store.file(); if (file == null || !file.exists()) { return; } log.info("Deleting Chronicle file: according to retention: {}", file::getAbsolutePath, () -> retention); try { Files.delete(file.toPath()); queue.refreshDirectlyListing(); log.debug(file + " deleted"); queue.release(store); } catch (IOException | SecurityException e) { log.warn("Unable to delete Chronicle file: {}, {}", file::getAbsolutePath, e::getMessage); } }
Source:
<code>protected <S extends Score, W extends TestScoreWrapper<S>> void assertSerializeAndDeserializeXML(S expectedScore, W input) { String xmlString; W output; try { JAXBContext jaxbContext = JAXBContext.newInstance(input.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); StringWriter writer = new StringWriter(); jaxbMarshaller.marshal(input, writer); xmlString = writer.toString(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); StringReader reader = new StringReader(xmlString); output = (W) unmarshaller.unmarshal(reader); } catch (JAXBException e) { throw new IllegalStateException("Marshalling or unmarshalling for input (" + input + ") failed.", e); } assertEquals(expectedScore, output.getScore()); String regex; if (expectedScore != null) { regex = "<\\?[^\\?]*\\?>" + "<([\\w\\-\\.]+)>\\s*" + "<score>" + expectedScore.toString().replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]") + "</score>" + "\\s*</\\1>"; } else { regex = "<\\?[^\\?]*\\?>" + "<([\\w\\-\\.]+)/>"; } if (!xmlString.matches(regex)) { fail(String.format("Regular expression match failed.%nExpected regular expression: " + regex + <START> "%nActual string: " + xmlString)); <END> } }</code><technical_language>If format, concatenate +: format("... Expected regular expression (%s) ...", regex)</technical_language>

Target:
protected <S extends Score, W extends TestScoreWrapper<S>> void assertSerializeAndDeserializeXML(S expectedScore, W input) { String xmlString; W output; try { JAXBContext jaxbContext = JAXBContext.newInstance(input.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); StringWriter writer = new StringWriter(); jaxbMarshaller.marshal(input, writer); xmlString = writer.toString(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); StringReader reader = new StringReader(xmlString); output = (W) unmarshaller.unmarshal(reader); } catch (JAXBException e) { throw new IllegalStateException("Marshalling or unmarshalling for input (" + input + ") failed.", e); } assertEquals(expectedScore, output.getScore()); String regex; if (expectedScore != null) { regex = "<\\?[^\\?]*\\?>" + "<([\\w\\-\\.]+)>\\s*" + "<score>" + expectedScore.toString().replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]") + "</score>" + "\\s*</\\1>"; } else { regex = "<\\?[^\\?]*\\?>" + "<([\\w\\-\\.]+)/>"; } if (!xmlString.matches(regex)) { fail(String.format("Regular expression match failed.%nExpected regular expression: %s%n" + "Actual string: %s", regex, xmlString)); } }
Source:
<code>protected String getRemoveQosMessage(int size) { <START> return ConstantsManager.getInstance().getMessages().removeStorageQoSMessage(); <END> }</code><technical_language>message get 'size'</technical_language>

Target:
protected String getRemoveQosMessage(int size) { return ConstantsManager.getInstance().getMessages().removeStorageQoSMessage(size); }
Source:
<code>public List<Attribute> getAttributes(PerunSession sess, Member member, Group group, List<String> attrNames) throws InternalErrorException, WrongAttributeAssignmentException { if(attrNames.isEmpty()) return new ArrayList<>(); <START> List<Attribute> attributes = getAttributesManagerImpl().getVirtualAttributes(sess, member, group); <END> Iterator<Attribute> attributeIterator = attributes.iterator(); while(attributeIterator.hasNext()) if(attributeIterator.next().getValue() == null) attributeIterator.remove(); attributes.addAll(getAttributesManagerImpl().getAttributes(sess, member, group, attrNames)); return attributes; }</code><technical_language>is filtering virtual attributes. virtual attributes filter non-virtual attributes. correct behavior</technical_language>

Target:
public List<Attribute> getAttributes(PerunSession sess, Member member, Group group, List<String> attrNames) throws InternalErrorException, WrongAttributeAssignmentException { if (attrNames.isEmpty()) return new ArrayList<>(); return getAttributesManagerImpl().getAttributes(sess, member, group, attrNames); }
Source:
<code>public void testApplication() throws IOException, Exception { try { cleanup(); createTopics(); LocalMode.Controller lc = asyncRun(); <START> Thread.sleep(10000); <END> lc.shutdown(); Thread.sleep(1000); checkOutput(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }</code><technical_language>Is a test results</technical_language>

Target:
public void testApplication() throws IOException, Exception { try { cleanup(); createTopics(); Configuration conf = getConfig(); LocalMode lma = LocalMode.newInstance(); lma.prepareDAG(new Application(), conf); ValidationToFile validationToFile = (ValidationToFile)lma.getDAG().getOperatorMeta("validationToFile").getOperator(); LocalMode.Controller lc = lma.getController(); lc.runAsync(); while(!validationToFile.validationDone) { System.out.println("Sleeping ...."); Thread.sleep(500); } lc.shutdown(); Thread.sleep(1000); checkOutput(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }
Source:
<code>public long save(Library library) throws IOException { Date now = new Date(); if (library.getCreationDate() == null) library.setCreationDate(now); long id; if (library.getId() == AbstractLibrary.UNSAVED_ID) { if (!namingScheme.duplicateLibraryAliasAllowed() && !listByAlias(library.getAlias()).isEmpty() <START> && (LimsUtils.isDetailedLibrary(library) && !((DetailedLibrary) library).hasNonStandardAlias())) { <END> throw new IOException("NEW: A library with this alias already exists in the database"); } id = (long) currentSession().save(library); } else { currentSession().update(library); id = library.getId(); } return id; }</code><technical_language>This check in Service alias validation</technical_language>

Target:
public long save(Library library) throws IOException { Date now = new Date(); if (library.getCreationDate() == null) library.setCreationDate(now); long id; if (library.getId() == AbstractLibrary.UNSAVED_ID) { id = (long) currentSession().save(library); } else { if (library.isDiscarded()) { getBoxDao().removeBoxableFromBox(library); } currentSession().update(library); id = library.getId(); } return id; }
Source:
<code>private StateSystemDataProvider getDataProvider() { ITimeGraphDataProvider<@NonNull TimeGraphEntryModel> dataProvider = DataProviderManager .getInstance().getDataProvider(getTrace(), getProviderId(), ITimeGraphDataProvider.class); if (dataProvider instanceof StateSystemDataProvider) { return (StateSystemDataProvider) dataProvider; } <START> return null; <END> }</code><technical_language>This this nullable. If this return null, want throw exception NullPointerException. if null (like trace is set something?) this method @Nullable do a null-check call it</technical_language>

Target:
private StateSystemDataProvider getDataProvider() { ITimeGraphDataProvider<@NonNull TimeGraphEntryModel> dataProvider = DataProviderManager .getInstance().getDataProvider(getTrace(), getProviderId(), ITimeGraphDataProvider.class); if (dataProvider instanceof StateSystemDataProvider) { return (StateSystemDataProvider) dataProvider; } throw new NullPointerException(); }
Source:
<code>public void unzipData(IgniteLogger log) { if (COMPRESSION_LEVEL < 0) <START> return; <END> for (Map.Entry<Integer, byte[]> entry : joiningNodeData.entrySet()) { try { entry.setValue(U.unzip(entry.getValue())); } catch (IgniteCheckedException e) { U.error(log, "Failed to marshal discovery data " + "[comp=" + entry.getKey() + ", data=" + entry.getValue() + ']', e); } } }</code><technical_language>remove this</technical_language>

Target:
public void unzipData(IgniteLogger log) { for (Map.Entry<Integer, byte[]> entry : joiningNodeData.entrySet()) { try { entry.setValue(U.unzip(entry.getValue())); } catch (IgniteCheckedException e) { U.error(log, "Failed to marshal discovery data " + "[comp=" + entry.getKey() + ", data=" + entry.getValue() + ']', e); } } }
Source:
<code><START> public Mono<byte[]> getSessionState(String sessionId) { <END> if (!isSessionReceiver) { return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver.")); } else { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType, sessionId)) .flatMap(channel -> channel.getSessionState()); } }</code><technical_language>sessionId : If this session id is maintained this receiver. validate list of session id this received is actively managing ? if this session id is managed some other receiver, thro error for example "Session id is managed this receiver"</technical_language>

Target:
public Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!isSessionReceiver) { return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver.")); } else { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType, sessionId)) .flatMap(channel -> channel.getSessionState()); } }
Source:
<code>public void init() throws IdentityOAuth2Exception { super.init(); Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); thread.setContextClassLoader(this.getClass().getClassLoader()); try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { log.error(e.getMessage(),e); <START> throw new IdentityOAuth2Exception("Error in bootstrapping the OpenSAML2 library"); <END> } finally { thread.setContextClassLoader(loader); } profileValidator = new SAMLSignatureProfileValidator(); Properties grantTypeProperties = new Properties(); InputStream stream = loader.getResourceAsStream("repository/conf/" + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE); if (stream != null) { try { grantTypeProperties.load(stream); audienceRestrictionValidationEnabled = Boolean.parseBoolean(grantTypeProperties.getProperty("audienceRestrictionValidationEnabled")); log.debug("Audience restriction validation enabled is set to " + audienceRestrictionValidationEnabled); } catch (IOException e) { log.warn("Failed to load the SAML-1.0-BearerGrantType.properties stream. The default configurations are " + "used instead of configurations defined in " + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE + " file."); } finally { try { stream.close(); } catch (IOException e) { log.warn("Failed to close the input stream of " + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE, e); } } } }</code><technical_language>include 'e' throwing exception? "throw new IdentityOAuth2Exception("Error in bootstrapping OpenSAML2 library",e);" specific error msg other e.getMessage() for logging</technical_language>

Target:
public void init() throws IdentityOAuth2Exception { super.init(); Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); thread.setContextClassLoader(this.getClass().getClassLoader()); try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { String errorMessage = "Error in bootstrapping the OpenSAML2 library"; log.error(errorMessage, e); throw new IdentityOAuth2Exception(errorMessage, e); } finally { thread.setContextClassLoader(loader); } profileValidator = new SAMLSignatureProfileValidator(); Properties grantTypeProperties = new Properties(); InputStream stream = loader.getResourceAsStream("repository/conf/" + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE); if (stream != null) { try { grantTypeProperties.load(stream); audienceRestrictionValidationEnabled = Boolean.parseBoolean(grantTypeProperties.getProperty("audienceRestrictionValidationEnabled")); if (log.isDebugEnabled()) { log.debug("Audience restriction validation enabled is set to " + audienceRestrictionValidationEnabled); } } catch (IOException e) { log.warn( "Failed to load the SAML-1.0-BearerGrantType.properties stream. The default configurations are " + "used instead of configurations defined in " + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE + " file."); } finally { try { stream.close(); } catch (IOException e) { log.warn("Failed to close the input stream of " + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE, e); } } } }
Source:
<code>public ContentData updateContent(@PathParam("owner_key") String ownerKey, @PathParam("content_id") String contentId, ContentData content) { Owner owner = this.getOwnerByKey(ownerKey); Content existing = this.fetchContent(owner, contentId); if (existing.isLocked()) { throw new ForbiddenException(i18n.tr("content \"{0}\" is locked", existing.getId())); } existing = this.contentManager.updateContent(content, owner, true); try { ownerManager.refreshOwnerForContentAccess(owner); } catch (Exception e) { <START> log.error("Unable to handle content access certs.", e.getStackTrace().toString()); <END> } return existing.toDTO(); }</code><technical_language>This re-throw, eating exception confusion</technical_language>

Target:
public ContentData updateContent(@PathParam("owner_key") String ownerKey, @PathParam("content_id") String contentId, ContentData content) { Owner owner = this.getOwnerByKey(ownerKey); Content existing = this.fetchContent(owner, contentId); if (existing.isLocked()) { throw new ForbiddenException(i18n.tr("content \"{0}\" is locked", existing.getId())); } existing = this.contentManager.updateContent(content, owner, true); ownerManager.refreshOwnerForContentAccess(owner); return existing.toDTO(); }
Source:
<code>protected void startScan() { if (usbSerialDiscovery != null) { usbSerialDiscovery.doSingleScan(); } else { <START> logger.info("Could not scan, as there is no usb serial discovery service configured."); <END> } }</code><technical_language>**USB**</technical_language>

Target:
protected void startScan() { if (usbSerialDiscovery != null) { usbSerialDiscovery.doSingleScan(); } else { logger.info("Could not scan, as there is no USB-Serial discovery service configured."); } }
Source:
<code>public long executeTask(String taskName, Map<String, String> taskDeploymentProperties, List<String> commandLineArgs) { RequestCriteria requestCriteria = createLaunchRequest(taskName, taskDeploymentProperties,commandLineArgs); <START> String id = this.taskLauncher.launch(requestCriteria.getAppDeploymentRequest()); <END> if (!StringUtils.hasText(id)) { throw new IllegalStateException("Deployment ID is null for the task:" + taskName); } postLaunchProcessing(requestCriteria, id); return requestCriteria.getTaskExecution().getExecutionId(); }</code><technical_language>if taskLauncher throws exception, a commit database for launched</technical_language>

Target:
public long executeTask(String taskName, Map<String, String> taskDeploymentProperties, List<String> commandLineArgs) { RequestCriteria requestCriteria = createLaunchRequest(taskName, taskDeploymentProperties,commandLineArgs); String id; try { id = this.taskLauncher.launch(requestCriteria.getAppDeploymentRequest()); } catch (Throwable throwable) { recordFailedTaskLaunch(requestCriteria.taskExecution.getExecutionId(), "An error occurred while attempting to launch task: " + taskName); throw throwable; } if (!StringUtils.hasText(id)) { recordFailedTaskLaunch(requestCriteria.taskExecution.getExecutionId(), "Deployment ID is null for the task:" + taskName); throw new IllegalStateException("Deployment ID is null for the task:" + taskName); } try { taskExecutionRepository.updateExternalExecutionId( requestCriteria.getTaskExecution().getExecutionId(), id); } catch (Throwable throwable) { logger.warn("Unable to update taskExecution's externalExecutionId", throwable); } postLaunchProcessing(requestCriteria, id); return requestCriteria.getTaskExecution().getExecutionId(); }
Source:
<code>public List<UUID> getDeviceAnonymizedIds() { <START> return Arrays.stream(deviceAnonymizedIds.split(DeviceBase.DEVICE_NAMES_SEPARATOR)).map(UUID::fromString) <END> .collect(Collectors.toList()); }</code><technical_language>is a bit strange reuse DEVICE_NAMES_SEPARATOR here. is cleaner introduce a new constant</technical_language>

Target:
public List<UUID> getDeviceAnonymizedIds() { return Arrays.stream(deviceAnonymizedIds.split(SEPARATOR)).map(UUID::fromString).collect(Collectors.toList()); }
Source:
<code>public String getFirstParam(String param) { <START> throw new RuntimeException("NOT IMPLEMENTED"); <END> }</code><technical_language>This throw UnsupportedOperationException instead of a RuntimeException. Also, standardize error message other UOEs this package</technical_language>

Target:
public String getFirstParam(String param) { throw new UnsupportedOperationException("Not supported yet"); }
Source:
<code>protected void executeQueryCommand() { Map<Guid, DiskImage> imagesAncestors = new HashMap<>(); <START> for (Guid <END> id : getParameters().getIds()) { DiskImage ancestor = diskImageDao.getAncestor(id, getUserID(), getParameters().isFiltered()); if (ancestor != null) { imagesAncestors.put(id, ancestor); } } getQueryReturnValue().setReturnValue(imagesAncestors); }</code><technical_language>Function<Guid, DiskImage> getAncestor = (Guid diskId) -> diskImageDao.getAncestor(diskId, getUserID(), getParameters().isFiltered()); getQueryReturnValue().setReturnValue(getParameters().getIds() .stream() .map(guid -> new Pair<>(guid, getAncestor.apply(guid)) .filter(pair -> pair.getSecond() != null) .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond))); For consideration :)</technical_language>

Target:
protected void executeQueryCommand() { Function<Guid, DiskImage> getAncestor = (Guid imageId) -> diskImageDao.getAncestor(imageId, getUserID(), getParameters().isFiltered()); getQueryReturnValue().setReturnValue(getParameters().getIds().stream() .map(guid -> new Pair<>(guid, getAncestor.apply(guid))) .filter(pair -> pair.getSecond() != null) .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond))); }
Source:
<code>@Test public void fromJsonDoesNotFailOnNullValues() throws Exception { Moshi moshi = new Moshi.Builder().build(); JsonAdapter<Object> adapter = moshi.adapter(Object.class); try { <START> adapter.fromJson("{\"address\":null, \"items\":null}"); <END> } catch (IllegalStateException ex) { fail(); } }</code><technical_language>nit: try/catch necessary. confirm result matches a map keys values null</technical_language>

Target:
@Test public void fromJsonDoesNotFailOnNullValues() throws Exception { Map<Object, Object> emptyDelivery = new LinkedHashMap<>(); emptyDelivery.put("address", null); emptyDelivery.put("items", null); Moshi moshi = new Moshi.Builder().build(); JsonAdapter<Object> adapter = moshi.adapter(Object.class); assertThat(adapter.fromJson("{\"address\":null, \"items\":null}")) .isEqualTo(emptyDelivery); }
Source:
<code>private boolean isSubdeployment(ModuleIdentifier dependency, DeploymentUnit deploymentUnit) { DeploymentUnit top = deploymentUnit.getParent()==null?deploymentUnit:deploymentUnit.getParent(); <START> return top != null && dependency.getName().startsWith(ServiceModuleLoader.MODULE_PREFIX.concat(top.getName())); <END> }</code><technical_language>I understand top null</technical_language>

Target:
private boolean isSubdeployment(ModuleIdentifier dependency, DeploymentUnit deploymentUnit) { DeploymentUnit top = deploymentUnit.getParent()==null?deploymentUnit:deploymentUnit.getParent(); return dependency.getName().startsWith(ServiceModuleLoader.MODULE_PREFIX.concat(top.getName())); }
Source:
<code>public void removeTarget(TelepadTarget target) { if (target == null) { return; } for (TelepadTarget t : targets) { if (target.equals(t)) { <START> targets.remove(t); <END> } } markDirty(); }</code><technical_language>* CME? * remove() does? Removing equals()..</technical_language>

Target:
public void removeTarget(TelepadTarget target) { if (target == null) { return; } targets.remove(target); markDirty(); }
Source:
<code>public HL7Recipient(String recipientName, String recipientUrl) { <START> this.recipientName = recipientName; <END> this.recipientUrl = recipientUrl; this.recipientUsername = null; this.recipientPassword = null; }</code><technical_language>call this(args) proper parameters. a good practice chain constructors, do repeat assignemnts</technical_language>

Target:
public HL7Recipient(String recipientName, String recipientUrl) { this(recipientName, recipientUrl, null, null); }
Source:
<code>public void configure() throws Exception { onException(Exception.class) .maximumRedeliveries("{{error.maxRedeliveries}}") .log("Event Routing Error: ${routeId}"); from("activemq:{{jms.fcrepoEndpoint}}") .routeId("AuditFcrepoRouter") .choice() .when(not(header("org.fcrepo.jms.identifier").startsWith(simple("{{audit.container}}")))) <START> .to("direct:event"); <END> from("direct:event") .routeId("AuditEventRouter") .setHeader(AuditHeaders.EVENT_BASE_URI, simple("{{event.baseUri}}")) .process(new AuditSparqlProcessor()) .log(LoggingLevel.INFO, "org.fcrepo.camel.audit", "Audit Event: ${headers[org.fcrepo.jms.identifier]} :: ${headers[CamelAuditEventUri]}") .to("http4:{{triplestore.baseUrl}}"); }</code><technical_language>this works, filter(...) simpler from("...") .routeId("AuditFcrepoRouter") .filter(not(header(JmsHeaders.IDENTIFIER).startsWith(simple("...")))) .to("direct:event") note fcrep-camel component CONST values for JMS headers</technical_language>

Target:
public void configure() throws Exception { onException(Exception.class) .maximumRedeliveries("{{error.maxRedeliveries}}") .log("Event Routing Error: ${routeId}"); from("activemq:{{jms.fcrepoEndpoint}}") .routeId("AuditFcrepoRouter") .filter(not(or(header(IDENTIFIER).startsWith(simple("{{audit.container}}/")), header(IDENTIFIER).isEqualTo(simple("{{audit.container}}"))))) .to("direct:event"); from("direct:event") .routeId("AuditEventRouter") .setHeader(AuditHeaders.EVENT_BASE_URI, simple("{{event.baseUri}}")) .process(new AuditSparqlProcessor()) .log(LoggingLevel.INFO, "org.fcrepo.camel.audit", "Audit Event: ${headers[org.fcrepo.jms.identifier]} :: ${headers[CamelAuditEventUri]}") .to("http4:{{triplestore.baseUrl}}"); }
Source:
<code>public String getProcessId(Process process) { <START> int timeout = 5000; <END> while(process.isAlive() && timeout>0){ try { timeout-=500; Thread.sleep(500); } catch (InterruptedException e) { log.error("Interrupted while waiting for start process to finish ", e); return super.getProcessId(process); } } File[] pidFiles = FileSystems.getDefault().getPath(service.home, "pids").toFile().listFiles(new PidFileNameFilter()); if (pidFiles.length != 1) { log.error("Multiple or no PID files containing " + service.getPidFileIdent() + " found, something has gone wrong"); return super.getProcessId(process); } char[] buffer = new char[(int) pidFiles[0].length()]; try { FileReader fr = new FileReader(pidFiles[0]); fr.read(buffer); fr.close(); } catch (IOException e) { log.error("Error reading PID file" + pidFiles[0].getName(), e); return super.getProcessId(process); } return new String(buffer).trim(); }</code><technical_language>check current time in loop sleep 5ms ten times</technical_language>

Target:
public String getProcessId(Process process) { long end = TimeService.currentTimeMillis() + service.startupProcessTimeout; while (process.isAlive() && TimeService.currentTimeMillis() <= end) { try { Thread.sleep(500); } catch (InterruptedException e) { log.error("Interrupted while waiting for start process to finish ", e); Thread.currentThread().interrupt(); } } File[] pidFiles = FileSystems.getDefault().getPath(service.home, "pids").toFile().listFiles(new PidFileNameFilter()); if (pidFiles.length != 1) { log.error("Multiple or no PID files containing " + service.getPidFileIdent() + " found, something has gone wrong"); return super.getProcessId(process); } byte[] buffer; try { buffer = Files.readAllBytes(pidFiles[0].toPath()); } catch (IOException e) { log.error("Error reading PID file" + pidFiles[0].getName(), e); return super.getProcessId(process); } return new String(buffer).trim(); }
Source:
<code>public boolean attachDatabase(JournalContext journalContext, String udbType, String udbConnectionUri, String udbDbName, String dbName, Map<String, String> map) throws IOException { try (LockResource l = getLock(dbName, false)) { if (mDBs.containsKey(dbName)) { throw new IOException(String .format("Unable to attach database. Database name %s (type: %s) already exists.", dbName, udbType)); } applyAndJournal(journalContext, Journal.JournalEntry.newBuilder().setAttachDb( alluxio.proto.journal.Table.AttachDbEntry.newBuilder() .setUdbType(udbType) .setUdbConnectionUri(udbConnectionUri) .setUdbDbName(udbDbName) .setDbName(dbName) .putAllConfig(map).build()).build()); mDBs.get(dbName).sync(journalContext); <START> return true; <END> } }</code><technical_language>remove this processing? If fail sync db, attached db, right</technical_language>

Target:
public boolean attachDatabase(JournalContext journalContext, String udbType, String udbConnectionUri, String udbDbName, String dbName, Map<String, String> map) throws IOException { try (LockResource l = getLock(dbName, false)) { if (mDBs.containsKey(dbName)) { throw new IOException(String .format("Unable to attach database. Database name %s (type: %s) already exists.", dbName, udbType)); } applyAndJournal(journalContext, Journal.JournalEntry.newBuilder().setAttachDb( alluxio.proto.journal.Table.AttachDbEntry.newBuilder() .setUdbType(udbType) .setUdbConnectionUri(udbConnectionUri) .setUdbDbName(udbDbName) .setDbName(dbName) .putAllConfig(map).build()).build()); try { mDBs.get(dbName).sync(journalContext); } catch (Exception e) { applyAndJournal(journalContext, Journal.JournalEntry.newBuilder().setDetachDb( alluxio.proto.journal.Table.DetachDbEntry.newBuilder().setDbName(dbName).build()) .build()); throw new IOException(String .format("Failed to connect underDb for Alluxio db '%s': %s", dbName, e.getMessage()), e); } return true; } }
Source:
<code>public LogoutConfigurer<H> defaultLogoutSuccessHandlerFor( LogoutSuccessHandler handler, RequestMatcher preferredMatcher) { <START> this.defaultLogoutSuccessHandlerMappings.put(preferredMatcher, handler); <END> return this; }</code><technical_language>add null assertion checks arguments</technical_language>

Target:
public LogoutConfigurer<H> defaultLogoutSuccessHandlerFor( LogoutSuccessHandler handler, RequestMatcher preferredMatcher) { Assert.notNull(handler, "handler cannot be null"); Assert.notNull(preferredMatcher, "preferredMatcher cannot be null"); this.defaultLogoutSuccessHandlerMappings.put(preferredMatcher, handler); return this; }
Source:
<code>public ContentTag addContentTag(Content content, TagName tagName, String comment, long beginByteOffset, long endByteOffset) throws TskCoreException { TaggingManager.ContentTagChange tagChange = caseDb.getTaggingManager().addContentTag(content, tagName, comment, beginByteOffset, endByteOffset); try { Case currentCase = Case.getCurrentCaseThrows(); for (ContentTag tag : tagChange.getRemovedTags()) { currentCase.notifyContentTagDeleted(tag); <START> } <END> currentCase.notifyContentTagAdded(tagChange.getAddedTag()); } catch (NoCurrentCaseException ex) { throw new TskCoreException("Added a tag to a closed case", ex); } return tagChange.getAddedTag(); }</code><technical_language>want fire tag added event, added tag newValue list of deleted tags oldValue. Other wise trigger multiple GUI refreshes, etc</technical_language>

Target:
public ContentTag addContentTag(Content content, TagName tagName, String comment, long beginByteOffset, long endByteOffset) throws TskCoreException { TaggingManager.ContentTagChange tagChange = caseDb.getTaggingManager().addContentTag(content, tagName, comment, beginByteOffset, endByteOffset); try { Case currentCase = Case.getCurrentCaseThrows(); currentCase.notifyContentTagAdded(tagChange.getAddedTag(), tagChange.getRemovedTags().isEmpty() ? null : tagChange.getRemovedTags().get(0)); } catch (NoCurrentCaseException ex) { throw new TskCoreException("Added a tag to a closed case", ex); } return tagChange.getAddedTag(); }