auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void doTest(String rulesJson, int expectedExecuteCount) throws Exception { new Expectations() {{ mockContext.getComponentOutputFields(anyString, anyString); result = new Fields(IotasEvent.IOTAS_EVENT); mockContext.getComponentId(anyInt); result = "componentid"; }}; RulesBoltDependenciesFactory factory = new RulesBoltDependenciesFactory( new RulesProcessorJsonBuilder(rulesJson), RulesBoltDependenciesFactory.ScriptType.SQL); Window windowConfig = factory.createRuleProcessorRuntime().getRulesRuntime().get(0).getRule().getWindow(); final CountDownLatch latch = new CountDownLatch(expectedExecuteCount); WindowRulesBolt wb = new WindowRulesBolt(factory) { @Override public void execute(TupleWindow inputWindow) { super.execute(inputWindow); latch.countDown(); } }; wb.withWindowConfig(windowConfig); WindowedBoltExecutor wbe = new WindowedBoltExecutor(wb); Map<String, Object> conf = wb.getComponentConfiguration(); conf.put("topology.message.timeout.secs", 30); wbe.prepare(conf, mockContext, mockCollector); for (int i = 1; i <= 20; i++) { wbe.execute(getNextTuple(i)); } <START> latch.await(5, TimeUnit.SECONDS); <END> }</code><technical_language>This change test fail if is executed for expected of times. CountDownLtch#await(long timeout, TimeUnit) returns false if timeout is elapsed. So, result handled in invoking test methods Assert.assertTrue(doTest(rulesJson, 2))</technical_language>

Target:
private boolean doTest(String rulesJson, int expectedExecuteCount) throws Exception { new Expectations() {{ mockContext.getComponentOutputFields(anyString, anyString); result = new Fields(IotasEvent.IOTAS_EVENT); mockContext.getComponentId(anyInt); result = "componentid"; }}; RulesBoltDependenciesFactory factory = new RulesBoltDependenciesFactory( new RulesProcessorJsonBuilder(rulesJson), RulesBoltDependenciesFactory.ScriptType.SQL); Window windowConfig = factory.createRuleProcessorRuntime().getRulesRuntime().get(0).getRule().getWindow(); final CountDownLatch latch = new CountDownLatch(expectedExecuteCount); WindowRulesBolt wb = new WindowRulesBolt(factory) { @Override public void execute(TupleWindow inputWindow) { super.execute(inputWindow); latch.countDown(); } }; wb.withWindowConfig(windowConfig); WindowedBoltExecutor wbe = new WindowedBoltExecutor(wb); Map<String, Object> conf = wb.getComponentConfiguration(); conf.put("topology.message.timeout.secs", 30); wbe.prepare(conf, mockContext, mockCollector); for (int i = 1; i <= 20; i++) { wbe.execute(getNextTuple(i)); } return latch.await(5, TimeUnit.SECONDS); }
Source:
<code>private void finishAndGoBackToSource() { <START> if (source != null && source == Source.STATS) { <END> SiteModel site = (SiteModel) getIntent().getSerializableExtra(SITE); ActivityLauncher.viewBlogStats(this, site); } finish(); }</code><technical_language>I need do a null check here, if null other equality fail anyway</technical_language>

Target:
private void finishAndGoBackToSource() { if (mSource == Source.STATS) { SiteModel site = (SiteModel) getIntent().getSerializableExtra(SITE); mDispatcher.dispatch(SiteActionBuilder.newFetchSiteAction(site)); ActivityLauncher.viewBlogStatsAfterJetpackSetup(this, site); } finish(); }
Source:
<code>public void testNestedPOJOExpression() { Expression expression = createExpression(fqcn, "innerObj.boolVal", boolean.class); assertTrue((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "{$.innerObj.boolVal}", boolean.class); assertTrue((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "$.innerObj.boolVal", boolean.class); assertTrue((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "!{$.innerObj.boolVal}", boolean.class); assertFalse((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "!{$}.innerObj.boolVal", boolean.class); assertFalse((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "{$}.innerObj.boolVal && ({$}.innerObj.intVal == 11)", boolean.class); assertTrue((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "valueOf({$.innerObj.privateIntVal}) + substring({$.innerObj.stringVal}, 2) + {$.innerObj.privateStringVal}.length()", String.class, new String[]{"org.apache.commons.lang3.StringUtils.*", <START> "java.lang.String.valueOf"}); <END> assertEquals("11llo5", expression.execute(testObj)); expression = createExpression(fqcn, "round(pow({$.innerObj.privateFloatVal}, {$.innerObj.privateDoubleVal}))", long.class, new String[] {"java.lang.Math.*"}); assertEquals(46162L, expression.execute(testObj)); }</code><technical_language>Add conflicting imports verify behaves in expected way</technical_language>

Target:
public void testNestedPOJOExpression() { Expression expression = createExpression(fqcn, "innerObj.boolVal", boolean.class); assertTrue((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "{$.innerObj.boolVal}", boolean.class); assertTrue((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "$.innerObj.boolVal", boolean.class); assertTrue((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "!{$.innerObj.boolVal}", boolean.class); assertFalse((Boolean)expression.execute(testObj)); expression = createExpression(fqcn, "!{$}.innerObj.boolVal", boolean.class); assertFalse((Boolean)expression.execute(testObj)); }
Source:
<code>public void createAdminAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(false); String token = getAuthToken(admin.getEmail(), password); <START> MvcResult mvcResult = getClient(token).perform(post("/api/core/bitstreamformats/") <END> .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isCreated()) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); Map<String, Object> map = mapper.readValue(content, Map.class); String newlyCreatedBitstreamID = String.valueOf(map.get("id")); getClient().perform(get("/api/core/bitstreamformats/" + newlyCreatedBitstreamID)) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.description", is(bitstreamFormatRest.getDescription()))) .andExpect(jsonPath("$.shortDescription", is(bitstreamFormatRest.getShortDescription()))) .andExpect(jsonPath("$.mimetype", is(bitstreamFormatRest.getMimetype()))) .andExpect(jsonPath("$.type", is("bitstreamformat"))) .andExpect(jsonPath("$._links.self.href", startsWith(REST_SERVER_URL))) .andExpect(jsonPath("$._links.self.href", endsWith("/api/core/bitstreamformats/" + newlyCreatedBitstreamID))); }</code><technical_language>please org.dspace.app.rest.CommunityRestRepositoryIT.createTest() L98+ for example of test creation of object REST. need assure a proper cleanup of test env object stay affecting other test</technical_language>

Target:
public void createAdminAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(false); String token = getAuthToken(admin.getEmail(), password); AtomicReference<Integer> idRef = new AtomicReference<>(); try { MvcResult mvcResult = getClient(token).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes( bitstreamFormatRest)) .contentType(contentType)) .andExpect(status().isCreated()) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); Map<String, Object> map = mapper.readValue(content, Map.class); String newlyCreatedBitstreamID = String.valueOf(map.get("id")); getClient().perform(get("/api/core/bitstreamformats/" + newlyCreatedBitstreamID)) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", Matchers.is( BitstreamFormatMatcher .matchBitstreamFormat(Integer.parseInt(newlyCreatedBitstreamID), bitstreamFormatRest.getMimetype(), bitstreamFormatRest.getDescription(), bitstreamFormatRest.getShortDescription()) ))) .andDo(result -> idRef .set(read(result.getResponse().getContentAsString(), "$.id"))); } finally { BitstreamFormatBuilder.deleteBitstreamFormat(idRef.get()); } }
Source:
<code>public IBlockState getDefaultDisplayTile() { <START> return IC2Plugin.getBlockState("te","mfe"); <END> }</code><technical_language>mfsu instead of mfe</technical_language>

Target:
public IBlockState getDefaultDisplayTile() { return IC2Plugin.getBlockState("te","mfsu"); }
Source:
<code>private TaskInfo.Builder getTaskInfoBuilder(Offer offer, Request request, TaskID taskId, CommandInfo.Builder commandBuilder) { TaskInfo.Builder builder = TaskInfo.newBuilder() .setName("task " + taskId.getValue()) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .setCommand(commandBuilder.build()); double cpusNeeded = request.request.cpus; double memNeeded = request.request.mem; for (Resource r : offer.getResourcesList()) { <START> if (r.getName().equals("cpus") && cpusNeeded > 0) { <END> double cpus = Math.min(r.getScalar().getValue(), cpusNeeded); builder.addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(r.getRole()) .setScalar( Value.Scalar.newBuilder() .setValue(cpus).build()).build()); cpusNeeded -= cpus; } else if (r.getName().equals("mem") && memNeeded > 0) { double mem = Math.min(r.getScalar().getValue(), memNeeded); builder.addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(r.getRole()) .setScalar( Value.Scalar.newBuilder() .setValue(mem).build()).build()); memNeeded -= mem; } else if (cpusNeeded == 0 && memNeeded == 0) { break; } } return builder; }</code><technical_language>removed jvm overhead factor part of change. a problem</technical_language>

Target:
private TaskInfo.Builder getTaskInfoBuilder(Offer offer, Request request, TaskID taskId, CommandInfo.Builder commandBuilder) { TaskInfo.Builder builder = TaskInfo.newBuilder() .setName("task " + taskId.getValue()) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .setCommand(commandBuilder.build()); double cpusNeeded = request.request.cpus; double memNeeded = (1 + JVM_MEM_OVERHEAD_FACTOR) * request.request.mem; for (Resource r : offer.getResourcesList()) { if (r.getName().equals("cpus") && cpusNeeded > 0) { double cpus = Math.min(r.getScalar().getValue(), cpusNeeded); builder.addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(r.getRole()) .setScalar( Value.Scalar.newBuilder() .setValue(cpus).build()).build()); cpusNeeded -= cpus; } else if (r.getName().equals("mem") && memNeeded > 0) { double mem = Math.min(r.getScalar().getValue(), memNeeded); builder.addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(r.getRole()) .setScalar( Value.Scalar.newBuilder() .setValue(mem).build()).build()); memNeeded -= mem; } else if (cpusNeeded == 0 && memNeeded == 0) { break; } } return builder; }
Source:
<code>public void tearDown() { <START> if (authenticator != null) <END> ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator); }</code><technical_language>Nit: tend braces in selenium codebase. harder chaos accidentally :)</technical_language>

Target:
public void tearDown() { if (authenticator != null) { ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator); } }
Source:
<code>public String getAllowedUnitTypeName() { <START> if(getAllowedUnitType() > UnitType.SIZE || getAllowedUnitType() < 0) { <END> return SPECIAL_UNIT_TYPES.get(getAllowedUnitType()); } else { return UnitType.getTypeDisplayableName(getAllowedUnitType()); } }</code><technical_language>This >= UnitType.SIZE</technical_language>

Target:
public String getAllowedUnitTypeName() { if(getAllowedUnitType() >= UnitType.SIZE || getAllowedUnitType() < 0) { return SPECIAL_UNIT_TYPES.get(getAllowedUnitType()); } else { return UnitType.getTypeDisplayableName(getAllowedUnitType()); } }
Source:
<code>private void setRepository(@NonNull GitHubRepository repository) { Preconditions.checkNotNull(repository, "Repository cannot be null."); titleTextView.setText(repository.getName()); stargazersTextView.setText("stars: " + repository.getStargazersCount()); forksTextView.setText("forks: " + repository.getForksCount()); <START> request = Glide.with(getContext()) <END> .load(repository.getOwner().getAvatarUrl()) .fitCenter() .crossFade() .placeholder(android.R.drawable.sym_def_app_icon) .into(avatarImageView); }</code><technical_language>@jaggernod release request if is ongoing. prevents setting view model twice</technical_language>

Target:
private void setRepository(@NonNull GitHubRepository repository) { Preconditions.checkNotNull(repository, "Repository cannot be null."); titleTextView.setText(repository.getName()); stargazersTextView.setText("stars: " + repository.getStargazersCount()); forksTextView.setText("forks: " + repository.getForksCount()); request.set(Glide.with(getContext()) .load(repository.getOwner().getAvatarUrl()) .fitCenter() .crossFade() .placeholder(android.R.drawable.sym_def_app_icon) .into(avatarImageView)); }
Source:
<code>public void testAccept() throws Exception { RejectionPolicy rejectionPolicy = new MessageTimeRejectionPolicyFactory().create( new Period("PT10M") ); <START> Assert.assertTrue(rejectionPolicy.accept(new DateTime().getMillis())); <END> }</code><technical_language>This test extend cover fact RejectionPolicy is keeping track of max time. So, accept, a a timestamp 10 minutes thrown away. if give another timestamp 10 minutes in future, this timestamp succeeded fail</technical_language>

Target:
public void testAccept() throws Exception { Period period = new Period("PT10M"); RejectionPolicy rejectionPolicy = new MessageTimeRejectionPolicyFactory().create(period); DateTime now = new DateTime(); DateTime past = now.minus(period).minus(1); DateTime future = now.plus(period).plus(1); Assert.assertTrue(rejectionPolicy.accept(now.getMillis())); Assert.assertFalse(rejectionPolicy.accept(past.getMillis())); Assert.assertTrue(rejectionPolicy.accept(future.getMillis())); Assert.assertFalse(rejectionPolicy.accept(now.getMillis())); }
Source:
<code>public void testSaveBulkNullData() throws Exception { List<Document> documents = new Vector<Document>(); documents.add(new Document(UUID.randomUUID().toString(), System.currentTimeMillis(), mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST")))); documents.add(new Document(UUID.randomUUID().toString(), System.currentTimeMillis(), null)); <START> queryStore.save(TestUtils.TEST_TABLE_NAME, documents); <END> }</code><technical_language>Check for equality of error code</technical_language>

Target:
public void testSaveBulkNullData() throws Exception { List<Document> documents = new Vector<Document>(); documents.add(new Document(UUID.randomUUID().toString(), System.currentTimeMillis(), mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST")))); documents.add(new Document(UUID.randomUUID().toString(), System.currentTimeMillis(), null)); try { queryStore.save(TestUtils.TEST_TABLE_NAME, documents); } catch (QueryStoreException e) { assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, e.getErrorCode()); throw e; } }
Source:
<code>public static Resource getYarnResourcesFromMesosOffers(Collection<Offer> offers) { double cpus = 0.0; double mem = 0.0; for (Protos.Offer offer : offers) { for (Protos.Resource resource : offer.getResourcesList()) { if (resource.getName().equalsIgnoreCase("cpus")) { cpus += resource.getScalar().getValue(); } else if (resource.getName().equalsIgnoreCase("mem")) { <START> mem += resource.getScalar().getValue() / vcoreRatio; <END> } } } return Resource.newInstance((int) mem, (int) cpus); }</code><technical_language>do this memory. Youll end ooms</technical_language>

Target:
public static Resource getYarnResourcesFromMesosOffers(Collection<Offer> offers) { double cpus = 0.0; double mem = 0.0; for (Protos.Offer offer : offers) { for (Protos.Resource resource : offer.getResourcesList()) { if (resource.getName().equalsIgnoreCase("cpus")) { cpus += resource.getScalar().getValue() / vcoreRatio; } else if (resource.getName().equalsIgnoreCase("mem")) { mem += resource.getScalar().getValue(); } } } return Resource.newInstance((int) mem, (int) cpus); }
Source:
<code>public void should_return_404_when_validating_3ds_flex_credentials_if_gateway_account_does_not_exist() throws Exception{ givenSetup() .body(getCheck3dsConfigPayloadForValidCredentials()) <START> .post(format(VALIDATE_3DS_FLEX_CREDENTIALS_URL, nextLong(1, 99999))) <END> .then() .statusCode(HttpStatus.SC_NOT_FOUND); }</code><technical_language>test fail if accountId is nextLong(1, 99999). accountId is nextLong(1, 99999)</technical_language>

Target:
public void should_return_404_when_validating_3ds_flex_credentials_if_gateway_account_does_not_exist() throws Exception{ givenSetup() .body(getCheck3dsConfigPayloadForValidCredentials()) .post(format(VALIDATE_3DS_FLEX_CREDENTIALS_URL, accountId-1)) .then() .statusCode(HttpStatus.SC_NOT_FOUND); }
Source:
<code>protected boolean canDoAction() { <START> return true; <END> }</code><technical_language>return true? need inform user wrong vm (vm doesnt exist), other issues</technical_language>

Target:
protected boolean canDoAction() { if(getVmDAO().get(getParameters().getVmId()) == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND); } return super.canDoAction(); }
Source:
<code>public Optional<InterceptorChain<Command, CommandResponse>> create(final TypeToken<?> type) { final Class<?> commandClass = type.getRawType(); final boolean isPublicCommand = commandClass.isAnnotationPresent(XKasperPublic.class); <START> SecurityStrategy securityStrategy = isPublicCommand ? <END> new DefaultPublicSecurityStrategy(securityConfiguration) : new DefaultSecurityStrategy(securityConfiguration); final Interceptor<Command, CommandResponse> interceptor = new CommandSecurityInterceptor(securityStrategy); return Optional.of(InterceptorChain.makeChain(interceptor)); }</code><technical_language>final</technical_language>

Target:
public Optional<InterceptorChain<Command, CommandResponse>> create(final TypeToken<?> type) { final Class<?> commandClass = type.getRawType(); final SecurityStrategy securityStrategy; if (commandClass.isAnnotationPresent(XKasperPublic.class)) { securityStrategy = new DefaultPublicSecurityStrategy(securityConfiguration); } else { securityStrategy = new DefaultSecurityStrategy(securityConfiguration); } final Interceptor<Command, CommandResponse> interceptor = new CommandSecurityInterceptor<>(securityStrategy); return Optional.of(InterceptorChain.makeChain(interceptor)); }
Source:
<code><START> private boolean moveFileToBackup(File file) { <END> log("Moving file as backup"); String backupFilename = getBackupFilename(file.getName()); File backup = new File(file.getParent(), backupFilename); return moveFile(file.toPath(), backup.toPath()); }</code><technical_language>This method is a general 'move file' operation. Write in a more general way</technical_language>

Target:
private void moveFileToBackup(File file) throws IOException { log("Moving file as backup"); String backupFilename = getBackupFilename(file.getName()); File backup = new File(file.getParent(), backupFilename); JarUpdaterFileHandler.moveFileWithReplaceExisting(file.toPath(), backup.toPath()); }
Source:
<code>private int calculateDamageLevel(Entity entity) { if((entity instanceof GunEmplacement) && entity.isDestroyed()) { return Entity.DMG_CRIPPLED; } if(entity.isAirborne() && entity.getCrew().isEjected()) { return Math.max(Entity.DMG_HEAVY, entity.getDamageLevel(false)); } int calculatedDamageLevel = entity.getDamageLevel(); if(calculatedDamageLevel == Entity.DMG_CRIPPLED) { <START> if(entity.getArmorRemainingPercent() == 1.0) { <END> calculatedDamageLevel = Entity.DMG_NONE; } } return calculatedDamageLevel; }</code><technical_language>Floating point math is weird, is this 1.0</technical_language>

Target:
private int calculateDamageLevel(Entity entity) { if((entity instanceof GunEmplacement) && entity.isDestroyed()) { return Entity.DMG_CRIPPLED; } if(entity.isAirborne() && entity.getCrew().isEjected()) { return Math.max(Entity.DMG_HEAVY, entity.getDamageLevel(false)); } int calculatedDamageLevel = entity.getDamageLevel(); if(calculatedDamageLevel == Entity.DMG_CRIPPLED) { if(entity.getArmorRemainingPercent() >= 1.0) { calculatedDamageLevel = Entity.DMG_NONE; } } return calculatedDamageLevel; }
Source:
<code>public Long getStartTime() { <START> return (task != null) ? task.getGenStartTimeAsLong() : null; <END> }</code><technical_language>getStartTimeAsLong() getGenStartTimeAsLong()</technical_language>

Target:
public Long getStartTime() { return (task != null) ? task.getStartTimeAsLong() : null; }
Source:
<code>private boolean canDeleteWorkflow(String path) { Optional<BioWorkflow> workflow = workflowDAO.findByPath(path, false, BioWorkflow.class); if (workflow.isPresent()) { <START> return Objects.equals(workflow.get().getMode(), WorkflowMode.STUB); <END> } else { return false; } }</code><technical_language>Nitpick, == Enums void Object.equals <LINK_0></technical_language>

Target:
private boolean canDeleteWorkflow(String path) { Optional<BioWorkflow> workflow = workflowDAO.findByPath(path, false, BioWorkflow.class); if (workflow.isPresent()) { return workflow.get().getMode() == WorkflowMode.STUB; } return false; }
Source:
<code>protected void run() throws Exception { final TreeWalk walk = new TreeWalk(db); final ObjectReader reader = walk.getObjectReader(); <START> final MutableObjectId buf = new MutableObjectId(); <END> final ZipOutputStream out = new ZipOutputStream(System.out); if (tree == null) throw die(CLIText.get().treeIsRequired); if (reader == null) throw die("BUG: no object reader for tree walker?"); walk.reset(); walk.addTree(tree); walk.setRecursive(true); while (walk.next()) { String name = walk.getPathString(); final FileMode mode = walk.getFileMode(0); walk.getObjectId(buf, 0); if (mode == FileMode.TREE) name += "/"; final ZipEntry entry = new ZipEntry(name); final ObjectLoader loader = reader.open(buf); entry.setSize(loader.getSize()); out.putNextEntry(entry); loader.copyTo(out); if (mode != FileMode.REGULAR_FILE && mode != FileMode.TREE) System.err.println(MessageFormat.format( CLIText.get().archiveEntryModeIgnored, name)); } out.close(); }</code><technical_language>nit: tend prefer call this idbuf. buf in Java is a temporary ByteArrayOutputStream a StringBuilder. idbuf in JGit is a MutableObjectId</technical_language>

Target:
protected void run() throws Exception { final TreeWalk walk = new TreeWalk(db); final ObjectReader reader = walk.getObjectReader(); final MutableObjectId idBuf = new MutableObjectId(); final ZipOutputStream out = new ZipOutputStream(outs); if (tree == null) throw die(CLIText.get().treeIsRequired); walk.reset(); walk.addTree(tree); walk.setRecursive(true); while (walk.next()) { final String name = walk.getPathString(); final FileMode mode = walk.getFileMode(0); walk.getObjectId(idBuf, 0); if (mode == FileMode.TREE) continue; final ZipEntry entry = new ZipEntry(name); final ObjectLoader loader = reader.open(idBuf); entry.setSize(loader.getSize()); out.putNextEntry(entry); loader.copyTo(out); if (mode != FileMode.REGULAR_FILE) System.err.println(MessageFormat.format( CLIText.get().archiveEntryModeIgnored, name)); } out.close(); }
Source:
<code>public void fetchCurrentTheme() { final String siteId = getBlogId(); WordPress.getRestClientUtilsV1_1().getCurrentTheme(siteId, new Listener() { @Override public void onResponse(JSONObject response) { try { mCurrentTheme = Theme.fromJSONV1_1(response); if (mCurrentTheme != null) { mCurrentTheme.setIsCurrent(true); mCurrentTheme.save(); WordPress.wpDB.setCurrentTheme(siteId, mCurrentTheme.getId()); if (mThemeBrowserFragment != null) { mThemeBrowserFragment.setRefreshing(false); if (mThemeBrowserFragment.getCurrentThemeTextView() != null) { mThemeBrowserFragment.getCurrentThemeTextView().setText(mCurrentTheme.getName()); mThemeBrowserFragment.setCurrentThemeId(mCurrentTheme.getId()); } } } } catch (JSONException e) { AppLog.e(T.THEMES, e); } } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError response) { String themeId = WordPress.wpDB.getCurrentThemeId(siteId); mCurrentTheme = WordPress.wpDB.getTheme(siteId, themeId); if (mCurrentTheme != null) { <START> if (mThemeBrowserFragment != null) { <END> if (mThemeBrowserFragment.getCurrentThemeTextView() != null) { mThemeBrowserFragment.getCurrentThemeTextView().setText(mCurrentTheme.getName()); mThemeBrowserFragment.setCurrentThemeId(mCurrentTheme.getId()); } } } } } ); }</code><technical_language>nitpick; conditions condensed</technical_language>

Target:
public void fetchCurrentTheme() { final String siteId = getBlogId(); WordPress.getRestClientUtilsV1_1().getCurrentTheme(siteId, new Listener() { @Override public void onResponse(JSONObject response) { try { mCurrentTheme = Theme.fromJSONV1_1(response); if (mCurrentTheme != null) { mCurrentTheme.setIsCurrent(true); mCurrentTheme.save(); WordPress.wpDB.setCurrentTheme(siteId, mCurrentTheme.getId()); if (mThemeBrowserFragment != null) { mThemeBrowserFragment.setRefreshing(false); if (mThemeBrowserFragment.getCurrentThemeTextView() != null) { mThemeBrowserFragment.getCurrentThemeTextView().setText(mCurrentTheme.getName()); mThemeBrowserFragment.setCurrentThemeId(mCurrentTheme.getId()); } } } } catch (JSONException e) { AppLog.e(T.THEMES, e); } } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError response) { String themeId = WordPress.wpDB.getCurrentThemeId(siteId); mCurrentTheme = WordPress.wpDB.getTheme(siteId, themeId); if (mCurrentTheme != null && mThemeBrowserFragment != null) { if (mThemeBrowserFragment.getCurrentThemeTextView() != null) { mThemeBrowserFragment.getCurrentThemeTextView().setText(mCurrentTheme.getName()); mThemeBrowserFragment.setCurrentThemeId(mCurrentTheme.getId()); } } } } ); }
Source:
<code>private void removeCinderDisks() { if (getParameters().isRemoveDisks()) { List<CinderDisk> cinderDisks = ImagesHandler.filterDisksBasedOnCinder(getVm().getDiskMap().values()); RemoveAllVmCinderDisksParameters param = new RemoveAllVmCinderDisksParameters(getVmId(), cinderDisks); param.setParentHasTasks(!getReturnValue().getVdsmTaskIdList().isEmpty()); Future<VdcReturnValueBase> future = CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.RemoveAllVmCinderDisks, withRootCommandInfo(param, getActionType()), cloneContextAndDetachFromParent()); try { <START> failedRemoveCinderDisks = <END> future.get().getActionReturnValue(); } catch (InterruptedException | ExecutionException e) { failedRemoveCinderDisks.addAll(cinderDisks); log.error("Exception", e); } } }</code><technical_language>return this list instead of keeping a class member</technical_language>

Target:
private Collection<CinderDisk> removeCinderDisks() { Collection<CinderDisk> failedRemoveCinderDisks = null; if (getParameters().isRemoveDisks()) { List<CinderDisk> cinderDisks = ImagesHandler.filterDisksBasedOnCinder(getVm().getDiskMap().values()); RemoveAllVmCinderDisksParameters param = new RemoveAllVmCinderDisksParameters(getVmId(), cinderDisks); param.setParentHasTasks(!getReturnValue().getVdsmTaskIdList().isEmpty()); Future<VdcReturnValueBase> future = CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.RemoveAllVmCinderDisks, withRootCommandInfo(param, getActionType()), cloneContextAndDetachFromParent()); try { failedRemoveCinderDisks = future.get().getActionReturnValue(); } catch (InterruptedException | ExecutionException e) { failedRemoveCinderDisks.addAll(cinderDisks); log.error("Exception", e); } } return failedRemoveCinderDisks; }
Source:
<code><START> protected @Nonnull Rule initRuleId(String rUID, Rule rule) { <END> Rule ruleWithUID = new Rule(rUID, rule.getTriggers(), rule.getConditions(), rule.getActions(), rule.getConfigurationDescriptions(), rule.getConfiguration(), rule.getTemplateUID(), rule.getVisibility()); ruleWithUID.setName(rule.getName()); ruleWithUID.setTags(rule.getTags()); ruleWithUID.setDescription(rule.getDescription()); return ruleWithUID; }</code><technical_language>implementation of this method return a null element. I annotation is overweight of method. IMHO is update java doc method returns null instead of adding a runtime check method call</technical_language>

Target:
protected @NonNull Rule initRuleId(String rUID, Rule rule) { Rule ruleWithUID = new Rule(rUID, rule.getTriggers(), rule.getConditions(), rule.getActions(), rule.getConfigurationDescriptions(), rule.getConfiguration(), rule.getTemplateUID(), rule.getVisibility()); ruleWithUID.setName(rule.getName()); ruleWithUID.setTags(rule.getTags()); ruleWithUID.setDescription(rule.getDescription()); return ruleWithUID; }
Source:
<code>public String processSubmit(@ModelAttribute("experiment") Experiment experiment, ModelMap model, SessionStatus session) throws IOException, MalformedExperimentException { try { User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); if (!experiment.userCanWrite(user)) { throw new SecurityException("Permission denied."); } experiment.setLastModifier(user); <START> experimentService.saveExperiment(experiment); <END> session.setComplete(); model.clear(); return "redirect:/miso/experiment/" + experiment.getId(); } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Failed to save Experiment", ex); } throw ex; } }</code><technical_language>methods, experimentService.saveExperiment(experiment) simply experimentService.save(experiment), getExperimentById(id). convention is more verbose, especially id columns in db! move some point</technical_language>

Target:
public String processSubmit(@ModelAttribute("experiment") Experiment experiment, ModelMap model, SessionStatus session) throws IOException, MalformedExperimentException { try { User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); if (!experiment.userCanWrite(user)) { throw new SecurityException("Permission denied."); } experiment.setLastModifier(user); experimentService.save(experiment); session.setComplete(); model.clear(); return "redirect:/miso/experiment/" + experiment.getId(); } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Failed to save Experiment", ex); } throw ex; } }
Source:
<code>protected void sendDatastreamProducerRecord(DatastreamProducerRecord datastreamProducerRecord, TopicPartition srcTopicPartition, int numBytes) { _producer.send(datastreamProducerRecord, ((metadata, exception) -> { if (exception != null) { _logger.warn("Detect exception being throw from callback for src partition: while sending producer " + "record: {}, exception: ", srcTopicPartition, datastreamProducerRecord, exception); rewindAndPauseTopicPartitionWhenException(srcTopicPartition, exception); } <START> _consumerMetrics.updateBytesProcessedRate(numBytes); <END> })); }</code><technical_language>update process-rate if send successful? (wrap in else{} ?)</technical_language>

Target:
protected void sendDatastreamProducerRecord(DatastreamProducerRecord datastreamProducerRecord, TopicPartition srcTopicPartition, int numBytes) { _producer.send(datastreamProducerRecord, ((metadata, exception) -> { if (exception != null) { _logger.warn("Detect exception being throw from callback for src partition: while sending producer " + "record: {}, exception: ", srcTopicPartition, datastreamProducerRecord, exception); rewindAndPausePartitionOnException(srcTopicPartition, exception); } else { _consumerMetrics.updateBytesProcessedRate(numBytes); } })); }
Source:
<code>public void init() throws FalconException { if (SecurityUtil.isSecurityEnabled()) { LOG.info("Falcon Kerberos Authentication Enabled!"); initializeKerberos(); String authTokenValidity = StartupProperties.get().getProperty(AUTH_TOKEN_VALIDITY_SECONDS); long validateFrequency; try { validateFrequency = (StringUtils.isNotEmpty(authTokenValidity)) <START> ? (Long.parseLong(authTokenValidity) - 100) : 86300; <END> if (validateFrequency < 0) { throw new NumberFormatException("Value provided for startup property \"" + AUTH_TOKEN_VALIDITY_SECONDS + "\" is too small."); } } catch (NumberFormatException nfe) { throw new FalconException("Invalid value provided for startup property \"" + AUTH_TOKEN_VALIDITY_SECONDS + "\", please provide a valid long number", nfe); } timer.schedule(new TokenValidationThread(), 0, validateFrequency*1000); } else { LOG.info("Falcon Simple Authentication Enabled!"); Configuration ugiConf = new Configuration(); ugiConf.set("hadoop.security.authentication", "simple"); UserGroupInformation.setConfiguration(ugiConf); } }</code><technical_language>minor nit: define a constant is 86400 maps -100 this is more readable</technical_language>

Target:
public void init() throws FalconException { if (SecurityUtil.isSecurityEnabled()) { LOG.info("Falcon Kerberos Authentication Enabled!"); initializeKerberos(); String authTokenValidity = StartupProperties.get().getProperty(AUTH_TOKEN_VALIDITY_SECONDS); long validateFrequency; try { validateFrequency = (StringUtils.isNotEmpty(authTokenValidity)) ? (Long.parseLong(authTokenValidity) - 100) : DEFAULT_VALIDATE_FREQUENCY_SECS; if (validateFrequency < 0) { throw new NumberFormatException("Value provided for startup property \"" + AUTH_TOKEN_VALIDITY_SECONDS + "\" should be greater than 100."); } } catch (NumberFormatException nfe) { throw new FalconException("Invalid value provided for startup property \"" + AUTH_TOKEN_VALIDITY_SECONDS + "\", please provide a valid long number", nfe); } timer.schedule(new TokenValidationThread(), 0, validateFrequency*1000); } else { LOG.info("Falcon Simple Authentication Enabled!"); Configuration ugiConf = new Configuration(); ugiConf.set("hadoop.security.authentication", "simple"); UserGroupInformation.setConfiguration(ugiConf); } }
Source:
<code>private static Schema generateSchema() { Schema schema = new Schema("TargetedSweep", TargetedSweepSchema.class.getPackage().getName() + ".generated", NAMESPACE, OptionalType.JAVA8); schema.addTableDefinition("sweepableCells", new TableDefinition() {{ javaTableName("SweepableCells"); allSafeForLoggingByDefault(); rowName(); hashFirstRowComponent(); rowComponent("timestamp_partition", ValueType.VAR_LONG); rowComponent("metadata", ValueType.BLOB); dynamicColumns(); columnComponent("timestamp_modulus", ValueType.VAR_LONG); columnComponent("write_index", ValueType.VAR_LONG); <START> value(ValueType.STRING); <END> sweepStrategy(TableMetadataPersistence.SweepStrategy.NOTHING); conflictHandler(ConflictHandler.IGNORE_ALL); }}); schema.addTableDefinition("sweepableTimestamps", new TableDefinition() {{ javaTableName("SweepableTimestamps"); allSafeForLoggingByDefault(); rowName(); hashFirstRowComponent(); rowComponent("shard", ValueType.VAR_LONG); rowComponent("timestamp_partition", ValueType.VAR_LONG); rowComponent("sweep_mode", ValueType.STRING); columns(); column("timestamp_modulus", "ts_mod", ValueType.VAR_LONG); sweepStrategy(TableMetadataPersistence.SweepStrategy.NOTHING); conflictHandler(ConflictHandler.IGNORE_ALL); }}); schema.validate(); return schema; }</code><technical_language>[non-blocking] Consider TableReferenceAndCell.class a json-based persister for type safety. pretty nontrivial block this</technical_language>

Target:
private static Schema generateSchema() { Schema schema = new Schema("TargetedSweep", TargetedSweepSchema.class.getPackage().getName() + ".generated", NAMESPACE, OptionalType.JAVA8); schema.addTableDefinition("sweepableCells", new TableDefinition() {{ javaTableName("SweepableCells"); allSafeForLoggingByDefault(); rowName(); hashFirstRowComponent(); rowComponent("timestamp_partition", ValueType.VAR_LONG); rowComponent("metadata", ValueType.BLOB); dynamicColumns(); columnComponent("timestamp_modulus", ValueType.VAR_LONG); columnComponent("write_index", ValueType.VAR_LONG); value(TableReferenceAndCell.class); sweepStrategy(TableMetadataPersistence.SweepStrategy.NOTHING); conflictHandler(ConflictHandler.IGNORE_ALL); }}); schema.addTableDefinition("sweepableTimestamps", new TableDefinition() {{ javaTableName("SweepableTimestamps"); allSafeForLoggingByDefault(); rowName(); hashFirstRowComponent(); rowComponent("shard", ValueType.VAR_LONG); rowComponent("timestamp_partition", ValueType.VAR_LONG); rowComponent("sweep_mode", ValueType.STRING); columns(); column("timestamp_modulus", "ts_mod", ValueType.VAR_LONG); sweepStrategy(TableMetadataPersistence.SweepStrategy.NOTHING); conflictHandler(ConflictHandler.IGNORE_ALL); }}); schema.validate(); return schema; }
Source:
<code>private void assembleDatapointName(Long surveyId, Long surveyedLocaleId) { final SurveyedLocaleDao slDao = new SurveyedLocaleDao(); final SurveyInstanceDAO siDao = new SurveyInstanceDAO(); final QuestionDao qDao = new QuestionDao(); final QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); List<SurveyedLocale> locales = null; if (surveyedLocaleId != null) { locales = new ArrayList<>(); locales.add(slDao.getById(surveyedLocaleId)); } else { locales = slDao.listLocalesByCreationSurvey(surveyId, Constants.ALL_RESULTS, null); } List<Question> nameQuestions = qDao.listDisplayNameQuestionsBySurveyId(surveyId); <START> SurveyInstance si; <END> for (SurveyedLocale sl : locales) { try { si = siDao.getRegistrationSurveyInstance(sl); if (si == null) { log.log(Level.WARNING, "Null registartion SurveyInstance for locale: " + sl.getKey().getId()); continue; } List<QuestionAnswerStore> responses = qasDao.listBySurveyInstance(si.getKey().getId()); sl.assembleDisplayName(nameQuestions, responses); log.info("Reassembled display name for SurveyedLocale : " + sl.getKey().getId() + ": " + sl.getDisplayName()); slDao.save(sl); } catch (Exception e) { log.log(Level.SEVERE, "Problem while assembling datapoint name: " + e.getMessage(), e); } } }</code><technical_language>this for scope</technical_language>

Target:
private void assembleDatapointName(Long surveyId, Long surveyedLocaleId) { final SurveyedLocaleDao slDao = new SurveyedLocaleDao(); final SurveyInstanceDAO siDao = new SurveyInstanceDAO(); final QuestionDao qDao = new QuestionDao(); final QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); List<SurveyedLocale> locales = null; if (surveyedLocaleId != null) { locales = new ArrayList<>(); locales.add(slDao.getById(surveyedLocaleId)); } else { locales = slDao.listLocalesByCreationSurvey(surveyId, Constants.ALL_RESULTS, null); } List<Question> nameQuestions = qDao.listDisplayNameQuestionsBySurveyId(surveyId); for (SurveyedLocale sl : locales) { try { SurveyInstance si = siDao.getRegistrationSurveyInstance(sl); if (si == null) { log.log(Level.WARNING, "Null registartion SurveyInstance for locale: " + sl.getKey().getId()); continue; } List<QuestionAnswerStore> responses = qasDao.listBySurveyInstance(si.getKey().getId()); sl.assembleDisplayName(nameQuestions, responses); log.info("Reassembled display name for SurveyedLocale : " + sl.getKey().getId() + ": " + sl.getDisplayName()); slDao.save(sl); } catch (Exception e) { log.log(Level.SEVERE, "Problem while assembling datapoint name: " + e.getMessage(), e); } } }
Source:
<code>private void changeKeyStorePassword() { String password = this.options.getSslKeystorePassword(); char[] oldPassword = this.cryptoService.getKeyStorePassword(this.options.getSslKeyStore()); char[] newPassword = oldPassword; if (password != null) { try { newPassword = this.cryptoService.decryptAes(password.toCharArray()); } catch (KuraException e) { logger.warn("Failed to decrypt keystore password"); } } if (oldPassword != null && !Arrays.equals(oldPassword, newPassword)) { try { if (isKeyStoreAccessible(this.options.getSslKeyStore(), oldPassword)) { changeKeyStorePassword(this.options.getSslKeyStore(), oldPassword, newPassword); } else if (isKeyStoreAccessible(this.options.getSslKeyStore(), newPassword)) { <START> changeKeyStorePassword(this.options.getSslKeyStore(), newPassword, newPassword); <END> } else { throw new KeyStoreException("Keystore not accessible!"); } this.cryptoService.setKeyStorePassword(this.options.getSslKeyStore(), newPassword); } catch (Exception e) { logger.warn("Failed to change keystore password", e); } } }</code><technical_language>is purpose of changing keystore password itself</technical_language>

Target:
private void changeKeyStorePassword() { String password = this.options.getSslKeystorePassword(); char[] oldPassword = this.cryptoService.getKeyStorePassword(this.options.getSslKeyStore()); char[] newPassword = oldPassword; if (password != null) { try { newPassword = this.cryptoService.decryptAes(password.toCharArray()); } catch (KuraException e) { logger.warn("Failed to decrypt keystore password"); } } if (oldPassword != null && newPassword != null && !Arrays.equals(oldPassword, newPassword)) { try { if (isKeyStoreAccessible(this.options.getSslKeyStore(), oldPassword)) { changeKeyStorePassword(this.options.getSslKeyStore(), oldPassword, newPassword); } else if (isKeyStoreAccessible(this.options.getSslKeyStore(), newPassword)) { changeKeyStorePassword(this.options.getSslKeyStore(), newPassword, newPassword); } else { throw new KeyStoreException("Keystore not accessible!"); } this.cryptoService.setKeyStorePassword(this.options.getSslKeyStore(), newPassword); } catch (Exception e) { logger.warn("Failed to change keystore password", e); } } }
Source:
<code>void load(InputStream is) { if (is != null) { for (Object map : yaml.loadAll(is)) { loadMap((Map<String, Object>)map, null); } try { is.close(); } catch (IOException ioe) { <START> } <END> } }</code><technical_language>a good design pattern close resource-parameters in methods. converntions (which violated in cases) - If pass in a resource, caller is responsible close - If wrap a stream (e.g. new BufferedInputStream(is)), closing outer stream close inner. fix resource leak caller side, is in io.ebean.config.properties.Loader: java void loadYaml(String resourcePath, Source source) { if (yamlLoader != null) { try (InputStream is = resource(resourcePath, source)) { yamlLoader.load(is); } catch (Exception e) { log.warn("Failed read yml from:" + resourcePath, e); } } }</technical_language>

Target:
void load(InputStream is) { if (is != null) { for (Object map : yaml.loadAll(is)) { loadMap((Map<String, Object>)map, null); } } }
Source:
<code>public boolean evalConfigSteps(Map<String, DataProvider> dataProviders) throws TaskHandlerException { LOGGER.info("Executing all config steps for task: {}", taskContext.getTask().getName()); Iterator<TaskConfigStep> iterator = taskContext.getTask().getTaskConfig().getSteps().iterator(); boolean result = true; TaskFilterExecutor taskFilterExecutor = new TaskFilterExecutor(); while (result && iterator.hasNext()) { TaskConfigStep step = iterator.next(); if (step instanceof DataSource) { DataSource ds = (DataSource) step; taskContext.addDataSourceObject(ds.getObjectId().toString(), getDataSourceObject(ds, dataProviders), ds.isFailIfDataNotFound()); LOGGER.info("Task data source: for task: added", ds.getName(), taskContext.getTask().getName()); <START> } else if (step instanceof FilterSet && ((FilterSet) step).getActionOrder() == null) { <END> try { FilterSet filterSet = (FilterSet) step; result = taskFilterExecutor.checkFilters(filterSet.getFilters(), filterSet.getOperator(), taskContext); } catch (RuntimeException e) { throw new TaskHandlerException(FILTER, "task.error.filterError", e); } } } return result; }</code><technical_language>add new private method 'isNotActionFilter()'</technical_language>

Target:
public boolean evalConfigSteps(Map<String, DataProvider> dataProviders) throws TaskHandlerException { LOGGER.info("Executing all config steps for task: {}", taskContext.getTask().getName()); Iterator<TaskConfigStep> iterator = taskContext.getTask().getTaskConfig().getSteps().iterator(); boolean result = true; TaskFilterExecutor taskFilterExecutor = new TaskFilterExecutor(); while (result && iterator.hasNext()) { TaskConfigStep step = iterator.next(); if (step instanceof DataSource) { DataSource ds = (DataSource) step; taskContext.addDataSourceObject(ds.getObjectId().toString(), getDataSourceObject(ds, dataProviders), ds.isFailIfDataNotFound()); LOGGER.info("Task data source: for task: added", ds.getName(), taskContext.getTask().getName()); } else if (step instanceof FilterSet && !isActionFilter((FilterSet) step)) { try { FilterSet filterSet = (FilterSet) step; result = taskFilterExecutor.checkFilters(filterSet.getFilters(), filterSet.getOperator(), taskContext); } catch (RuntimeException e) { throw new TaskHandlerException(FILTER, "task.error.filterError", e); } } } return result; }
Source:
<code>private static Predicate<Field> isContainer() { return field -> { boolean isStartable = Startable.class.isAssignableFrom(field.getType()); if (!isStartable) { <START> throw new ExtensionConfigurationException("Annotation is only supported for Startable types"); <END> } return AnnotationSupport.isAnnotated(field, Container.class); }; }</code><technical_language>I need check is annotated Container fail if is startable</technical_language>

Target:
private static Predicate<Field> isContainer() { return field -> { boolean isAnnotatedWithContainer = AnnotationSupport.isAnnotated(field, Container.class); if (isAnnotatedWithContainer) { boolean isStartable = Startable.class.isAssignableFrom(field.getType()); if (!isStartable) { throw new ExtensionConfigurationException("Annotation is only supported for Startable types"); } return true; } return false; }; }
Source:
<code>public void undeploy(DeploymentUnit unit, Function<DeploymentUnit, Boolean> beforeUndeploy) { <START> Function<DeploymentUnit, Boolean> predicate = Optional.ofNullable(beforeUndeploy).orElse(PreUndeployOperations.checkActiveProcessInstances(runtimeDataService)); <END> if (Boolean.TRUE.equals(predicate.apply(unit))) { synchronized (this) { DeployedUnit deployed = deploymentsMap.remove(unit.getIdentifier()); if (deployed != null) { RuntimeManager manager = deployed.getRuntimeManager(); ((AbstractRuntimeManager) manager).close(true); } notifyOnUnDeploy(unit, deployed); } } else { logger.warn("Couldn't undeploy unit '{}'", unit.getIdentifier()); throw new IllegalStateException("Couldn't undeploy unit '" + unit.getIdentifier() + "'"); } }</code><technical_language>I rename this function is a predicate</technical_language>

Target:
public void undeploy(DeploymentUnit unit, Function<DeploymentUnit, Boolean> beforeUndeploy) { Function<DeploymentUnit, Boolean> beforeUpdate = Optional.ofNullable(beforeUndeploy).orElse(PreUndeployOperations.checkActiveProcessInstances(runtimeDataService)); if (Boolean.TRUE.equals(beforeUpdate.apply(unit))) { synchronized (this) { DeployedUnit deployed = deploymentsMap.remove(unit.getIdentifier()); if (deployed != null) { RuntimeManager manager = deployed.getRuntimeManager(); ((AbstractRuntimeManager) manager).close(true); } notifyOnUnDeploy(unit, deployed); } } else { logger.warn("Couldn't undeploy unit '{}'", unit.getIdentifier()); throw new IllegalStateException("Couldn't undeploy unit '" + unit.getIdentifier() + "'"); } }
Source:
<code>public void constructorAmqpValidValues() { final List<BinaryData> listBinaryData = Collections.singletonList(DATA_BYTES); final AmqpDataBody amqpDataBody = new AmqpDataBody(listBinaryData); <START> AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody); <END> AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(expected); assertMessageCreation(actual, AmqpBodyType.DATA, listBinaryData.size()); }</code><technical_language>in general, consistent "final" not. This applies other areas of code</technical_language>

Target:
public void constructorAmqpValidValues() { final List<BinaryData> expectedBinaryData = Collections.singletonList(DATA_BYTES); final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData); final AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody); final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(expected); assertMessageCreation(AmqpBodyType.DATA, expectedBinaryData.size(), actual); }