auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { parseCommandLine(); Project.NameKey parentProject = null; if (newParent != null) { parentProject = newParent.getProject().getNameKey(); } if (!currentUser.getCapabilityByProject(parentProject).canCreateProject()) { String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } validateParameters(); try { nameKey = new Project.NameKey(projectName); String head = permissionsOnly ? GitRepositoryManager.REF_CONFIG : branch; final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!permissionsOnly && createEmptyCommit) { createEmptyCommit(repo, nameKey, branch); } } finally { repo.close(); } } catch (IllegalStateException err) { try { Repository repo = repoManager.openRepository(nameKey); try { if (repo.getObjectDatabase().exists()) { throw new UnloggedFailure(1, "fatal: project \"" + projectName + "\" exists"); } } finally { repo.close(); } } catch (RepositoryNotFoundException doesNotExist) { throw new Failure(1, "fatal: Cannot create " + projectName, err); } } catch (RepositoryNotFoundException badName) { throw new UnloggedFailure(1, "fatal: " + badName.getMessage()); } catch (Exception err) { throw new Failure(1, "fatal: Cannot create " + projectName, err); } } }); }

Target:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { parseCommandLine(); if ((newParent != null && !newParent.canCreateChildProject()) || (newParent == null && !currentUser.getCapabilityByProject(null) .canCreateProject())) { String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } validateParameters(); try { nameKey = new Project.NameKey(projectName); String head = permissionsOnly ? GitRepositoryManager.REF_CONFIG : branch; final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!permissionsOnly && createEmptyCommit) { createEmptyCommit(repo, nameKey, branch); } } finally { repo.close(); } } catch (IllegalStateException err) { try { Repository repo = repoManager.openRepository(nameKey); try { if (repo.getObjectDatabase().exists()) { throw new UnloggedFailure(1, "fatal: project \"" + projectName + "\" exists"); } } finally { repo.close(); } } catch (RepositoryNotFoundException doesNotExist) { throw new Failure(1, "fatal: Cannot create " + projectName, err); } } catch (RepositoryNotFoundException badName) { throw new UnloggedFailure(1, "fatal: " + badName.getMessage()); } catch (Exception err) { throw new Failure(1, "fatal: Cannot create " + projectName, err); } } }); }
Source:
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId, String principalName) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); return (Mono<T>) databaseClient.sql(LOAD_AUTHORIZED_CLIENT_SQL) .bind("clientRegistrationId", clientRegistrationId).bind("principalName", principalName) .map(this.authorizedClientRowMapper::apply).first() .flatMap(this::getOauth2AuthorizedClient); }

Target:
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId, String principalName) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); return (Mono<T>) this.databaseClient.sql(LOAD_AUTHORIZED_CLIENT_SQL) .bind("clientRegistrationId", clientRegistrationId).bind("principalName", principalName) .map(this.authorizedClientRowMapper::apply).first().flatMap(this::getOauth2AuthorizedClient); }
Source:
public ConceptTree(ConceptTree<T> thatTree) { super(new LabelTree(thatTree.getLabelTree())); try { for (ConceptTreeNode<T> node : getNodes()) { if (isRoot(node)) continue; String label = node.getLabel(); ConceptTreeNode<T> thatNode = thatTree.getNodeFromLabel(label); String description = thatNode.getLabelDescription(); node.setLabelDescription(description); SparseVector<T> vector = SparseVector.<T>deepCopy(thatNode.getConceptVector()); node.setConceptVector(vector); } } catch (Exception e) { e.printStackTrace(); } }

Target:
public ConceptTree(ConceptTree<T> thatTree) { super(new LabelTree(thatTree.getLabelTree())); for (ConceptTreeNode<T> node : getNodes()) { if (isRoot(node)) continue; String labelID = node.getLabelID(); ConceptTreeNode<T> thatNode = thatTree.getNodeFromLabel(labelID); String description = thatNode.getLabelDescription(); node.setLabelDescription(description); SparseVector<T> vector = SparseVector.deepCopy(thatNode.getConceptVector()); node.setConceptVector(vector); } }
Source:
public final List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { if (harvestingWrapper) { return getDropsDefault(world, pos, state, fortune); } IMicroblockContainerTile brokenTile = getMicroblockTile(world, pos); if (brokenTile == null) { brokenTile = this.brokenTile; } if (brokenTile == null) { return getDropsDefault(world, pos, state, fortune); } List<ItemStack> drops = new ArrayList<ItemStack>(); drops.addAll(getDropsDefault(world, pos, state, fortune)); return drops; }

Target:
public final List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { if (harvestingWrapper) { return getDropsDefault(world, pos, state, fortune); } IMicroblockContainerTile tile = getMicroblockTile(world, pos); if (tile == null && (tile = brokenTile) == null) { return getDropsDefault(world, pos, state, fortune); } List<ItemStack> drops = new ArrayList<ItemStack>(); drops.addAll(getDropsDefault(world, pos, state, fortune)); drops.addAll(tile.getMicroblockContainer().getPartContainer().getDrops()); return drops; }
Source:
public static Response manageError(CoapOSException e, Request request) throws OSException { ResponseCode responseCode = e.getResponseCode(); Response error = null; boolean includeErrMess = true; if (request != null) { if (request.getType() != null) { if (ResponseCode.isClientError(responseCode)) { error = Response.createResponse(request, responseCode); Type tmp = Type.NON; Type t = request.getType(); if (t.equals(Type.CON)) { tmp = Type.ACK; } error.setType(tmp); if (includeErrMess) { error.setPayload(e.getMessage()); } error.getOptions().setMaxAge(0); return error; } else { LOGGER.error(Error.CANNOT_CREATE_ERROR_MESS + ": " + Error.ERROR_MESS_NULL); } } else { LOGGER.error(Error.CANNOT_CREATE_ERROR_MESS + ": " + Error.TYPE_NULL); } } else { LOGGER.error(Error.CANNOT_CREATE_ERROR_MESS + ": " + Error.REQUEST_NULL); } return null; }

Target:
public static Response manageError(CoapOSException e, Request request) { ResponseCode responseCode = e.getResponseCode(); Response error = null; if (request != null) { if (request.getType() != null) { if (ResponseCode.isClientError(responseCode)) { error = Response.createResponse(request, responseCode); Type tmp = Type.NON; Type t = request.getType(); if (t.equals(Type.CON)) { tmp = Type.ACK; } error.setType(tmp); error.setPayload(e.getMessage()); error.getOptions().setMaxAge(0); return error; } else { LOGGER.error(ErrorDescriptions.CANNOT_CREATE_ERROR_MESS + ": " + ErrorDescriptions.ERROR_MESS_NULL); } } else { LOGGER.error(ErrorDescriptions.CANNOT_CREATE_ERROR_MESS + ": " + ErrorDescriptions.TYPE_NULL); } } else { LOGGER.error(ErrorDescriptions.CANNOT_CREATE_ERROR_MESS + ": " + ErrorDescriptions.REQUEST_NULL); } return null; }
Source:
public int compareTo(@Nullable ITmfStateValue object) { if (object instanceof NullStateValue){ return -1; } return 1; }

Target:
public int compareTo(@Nullable ITmfStateValue object) { if (object == null || object instanceof NullStateValue) { return 0; } return -1; }
Source:
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.subject_item_grid, parent, false); } SubjectModel model = getItem(position); SubjectItemGridBinding subjectItemBinding = DataBindingUtil.bind(convertView); subjectItemBinding.tvSubjectName.setText(model.name); @DrawableRes final int imageRes = UiUtil.getDrawable(getContext(), model.imageName); ImageUtils.setRoundedCornerImage(subjectItemBinding.ivSubjectLogo, imageRes); return convertView; }

Target:
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.subject_item_grid, parent, false); } final SubjectModel model = getItem(position); final SubjectItemGridBinding subjectItemBinding = DataBindingUtil.bind(convertView); subjectItemBinding.tvSubjectName.setText(model.name); @DrawableRes final int imageRes = UiUtil.getDrawable(getContext(), model.imageName); ImageUtils.setRoundedCornerImage(subjectItemBinding.ivSubjectLogo, imageRes); convertView.setContentDescription( convertView.getResources().getString(R.string.browse_by_subject) + " " + model.name); return convertView; }
Source:
private void deleteGitRepository(final Repository repository) throws RepositoryNotFoundException { File parentFile = repository.getDirectory().getParentFile(); if (!recursiveDelete(repository.getDirectory())) { throw new RepositoryNotFoundException("Error trying to delete " + repository.getDirectory().getAbsolutePath()); } recursiveDeleteParent(parentFile, gitDir); }

Target:
private void deleteGitRepository(final Repository repository) throws IOException { File parentFile = repository.getDirectory().getParentFile(); if (!recursiveDelete(repository.getDirectory())) { throw new IOException("Error trying to delete " + repository.getDirectory().getAbsolutePath()); } recursiveDeleteParent(parentFile, gitDir); }
Source:
public Option[] individualModules() { return options( gradleBundle("org.ehcache.modules:api"), gradleBundle("org.ehcache.modules:core"), gradleBundle("org.ehcache.modules:impl"), gradleBundle("org.ehcache.modules:xml"), jaxbConfiguration(), gradleBundle("org.ehcache:clustered-dist"), jaxbConfiguration(), gradleBundle("org.terracotta.management:management-model"), gradleBundle("org.terracotta.management:sequence-generator"), wrappedGradleBundle("org.terracotta:statistics"), wrappedGradleBundle("org.ehcache:sizeof"), wrappedGradleBundle("org.terracotta:offheap-store"), baseConfiguration("ClusteredOsgiTest", "individualModules") ); }

Target:
public Option[] individualModules() { return options( gradleBundle("org.ehcache.modules:api"), gradleBundle("org.ehcache.modules:core"), gradleBundle("org.ehcache.modules:impl"), gradleBundle("org.ehcache.modules:xml"), jaxbConfiguration(), gradleBundle("org.ehcache:clustered-dist"), gradleBundle("org.terracotta.management:management-model"), gradleBundle("org.terracotta.management:sequence-generator"), wrappedGradleBundle("org.terracotta:statistics"), wrappedGradleBundle("org.ehcache:sizeof"), wrappedGradleBundle("org.terracotta:offheap-store"), baseConfiguration("ClusteredOsgiTest", "individualModules") ); }
Source:
public void blowfishUnableToDecrypt() throws Exception { String aWonderfulString = "aWonderfulString"; final Encryption encryptionAES = new Encryption(KeySources.machineUID(16), CipherSources.getDefault()); String encryptedAESString = encryptionAES.encrypt(aWonderfulString); final Encryption encryptionBlowfish = new Encryption(KeySources.machineUID(16), CipherSources.blowfish()); final String decryptedString = encryptionBlowfish.decrypt(encryptedAESString); assertNotEquals(decryptedString, aWonderfulString); }

Target:
public void blowfishUnableToDecrypt() throws Exception { String aWonderfulString = "aWonderfulString"; final Encryption encryptionAES = new Encryption(KeySources.machineUID(16), CipherSources.getDefault()); String encryptedAESString = encryptionAES.encrypt(aWonderfulString); final Encryption encryptionBlowfish = new Encryption(KeySources.machineUID(16), CipherSources.blowfish()); encryptionBlowfish.decrypt(encryptedAESString); }
Source:
public void setup() { super.setup(); vaultResourceGroup = System.getProperty("test.azurecompute-arm.vault.resource.group"); vaultName = System.getProperty("test.azurecompute-arm.vault.name"); vaultCertificateUrl = System.getProperty("test.azurecompute-arm.vault.certificate.url"); tenantId = System.getProperty("test.azurecompute-arm.tenantId"); }

Target:
public void setup() { super.setup(); vaultResourceGroup = System.getProperty("test.azurecompute-arm.vault.resource.group"); vaultName = System.getProperty("test.azurecompute-arm.vault.name"); vaultCertificateUrl = System.getProperty("test.azurecompute-arm.vault.certificate.url"); }
Source:
public ValidationResult vmNotHavingPassthroughVnics() { for (VM vm : vms) { List<VmNetworkInterface> vnics = DbFacade.getInstance().getVmNetworkInterfaceDao().getAllForVm(vm.getId()); List<VmNetworkInterface> passthroughVnics = LinqUtils.filter(vnics, new org.ovirt.engine.core.utils.linq.Predicate<VmNetworkInterface>() { public boolean eval(VmNetworkInterface vnic) { return vnic.isPassthrough(); } }); Collection<String> replacements = ReplacementUtils.replaceWithNameable("interfaces", passthroughVnics); replacements.add(String.format("$vmName %s", vm.getName())); return ValidationResult.failWith(VdcBllMessages.ACTION_TYPE_FAILED_MIGRATION_OF_PASSTHROUGH_VNICS_IS_NOT_SUPPORTED, replacements.toArray(new String[] {})) .unless(passthroughVnics.isEmpty()); } return ValidationResult.VALID; }

Target:
public ValidationResult vmNotHavingPassthroughVnics() { for (VM vm : vms) { List<VmNetworkInterface> vnics = getDbFacade().getVmNetworkInterfaceDao().getAllForVm(vm.getId()); List<VmNetworkInterface> passthroughVnics = LinqUtils.filter(vnics, new org.ovirt.engine.core.utils.linq.Predicate<VmNetworkInterface>() { public boolean eval(VmNetworkInterface vnic) { return vnic.isPassthrough(); } }); Collection<String> replacements = ReplacementUtils.replaceWithNameable("interfaces", passthroughVnics); replacements.add(String.format("$vmName %s", vm.getName())); if (!passthroughVnics.isEmpty()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_MIGRATION_OF_PASSTHROUGH_VNICS_IS_NOT_SUPPORTED, replacements); } } return ValidationResult.VALID; }
Source:
public void testRootIdNoData() throws JsonProcessingException { String graphQLRequest = "mutation { " + "author(op:DELETE, ids: [\"1\"]) { " + "id " + "name " + "} " + "}"; String expectedResponse = "{" + "\"author\":[{" + "\"id\":\"1\"," + "\"name\":\"Mark Twain\"" + "}]" + "}"; assertQueryEquals(graphQLRequest, expectedResponse); }

Target:
public void testRootIdNoData() throws JsonProcessingException { String graphQLRequest = "mutation { " + "author(op:DELETE, ids: [\"1\"]) { " + "id " + "name " + "} " + "}"; String expectedResponse = "{" + "\"author\":[{" + "\"id\":\"1\"," + "\"name\":\"Mark Twain\"" + "}]" + "}"; assertQueryEquals(graphQLRequest, expectedResponse); String graphQLFetchRequest = "mutation { " + "author(ids: [\"1\"]) { " + "id " + "name " + "} " + "}"; String expectedFetchResponse = "{" + "\"author\":[]" + "}"; assertQueryEquals(graphQLFetchRequest, expectedFetchResponse); }
Source:
public void simple() { assertEquals(True.instance(), True.instance()); assertEquals(False.instance(), False.instance()); assertNotEquals(True.instance(), False.instance()); assertNotEquals(False.instance(), True.instance()); Leaf<String> leaf = new Leaf<>("foo"); assertEquals(leaf, leaf); assertNotEquals(True.instance(), leaf); assertNotEquals(False.instance(), leaf); }

Target:
public void simple() { assertEquals(True.instance(), True.instance()); assertEquals(True.instance().hashCode(), True.instance().hashCode()); assertEquals(False.instance(), False.instance()); assertEquals(False.instance().hashCode(), False.instance().hashCode()); assertNotEquals(True.instance(), False.instance()); assertNotEquals(False.instance(), True.instance()); Leaf<String> leaf = new Leaf<>("foo"); assertEquals(leaf, leaf); assertNotEquals(True.instance(), leaf); assertNotEquals(False.instance(), leaf); }
Source:
private static <A extends Annotation> boolean valuesEqual(Class<A> annotationType, Object a, Object b) { for (Method m : annotationType.getDeclaredMethods()) { Function<Object, Object> invoker = Unchecked.function(m::invoke); Object valueA = invoker.apply(a); Object valueB = invoker.apply(b); if (valueA != null && valueA.getClass().isArray() && valueA.getClass().equals(valueB.getClass()) && Boolean.FALSE.equals(Unchecked.supplier(() -> MethodHandles.publicLookup() .findStatic(Arrays.class, "equals", MethodType.methodType(boolean.class, valueA.getClass(), valueB.getClass())) .invoke(a, b)).get())) { return false; } if (!Objects.equals(valueA, valueB)) { return false; } } return true; }

Target:
private static <A extends Annotation> boolean valuesEqual(Class<A> annotationType, Object a, Object b) { for (Method m : annotationType.getDeclaredMethods()) { Function<Object, Object> invoker = Unchecked.function(m::invoke); Object valueA = invoker.apply(a); Object valueB = invoker.apply(b); if (valueA != null && valueB != null && valueA.getClass().isArray() && valueA.getClass().equals(valueB.getClass()) && Boolean.FALSE.equals(Unchecked.supplier(() -> MethodHandles.publicLookup() .findStatic(Arrays.class, "equals", MethodType.methodType(boolean.class, valueA.getClass(), valueB.getClass())) .invoke(a, b)).get())) { return false; } if (!Objects.equals(valueA, valueB)) { return false; } } return true; }
Source:
public ClassDefItem call() { long now = System.nanoTime(); ClassDefItem clazz = translateClass(name, bytes, classFile); translateTime += System.nanoTime() - now; methodDefs += classFile.getMethods().size(); fieldDefs += classFile.getFields().size(); return clazz; }

Target:
public ClassDefItem call() { ClassDefItem clazz = translateClass(name, bytes, classFile); return clazz; }
Source:
private void fetchDictionaries(File collectionDir, String collectionName, final EntityManager rootEm, Results entity, Gson gson, Integer batchId) { JsonGenerator jgDictionaries = null; try { jgDictionaries = getJsonGenerator(new File(collectionDir + "/" + collectionName + "_" + "dictionaries_" + batchId)); for (Entity et : entity.getEntities()) { Set<String> dictionaries; try { dictionaries = rootEm.getDictionaries(et); jgDictionaries.writeStartArray(); if (dictionaries != null && !dictionaries.isEmpty()) { for (String dictionary : dictionaries) { Map<Object, Object> dict = rootEm.getDictionaryAsMap(et, dictionary); if (dict != null && dict.isEmpty()) { continue; } jgDictionaries.writeStartObject(); jgDictionaries.writeObjectField("Related Entity", et.getUuid()); jgDictionaries.writeObjectField(dictionary, dict); jgDictionaries.writeEndObject(); } jgDictionaries.writeEndArray(); } } catch (Exception e) { logger.error("Exception while trying to fetch dictionaries.", e); } } } catch (Exception e) { logger.error("Exception while trying to fetch dictionaries.", e); } finally { if (jgDictionaries != null) { try { jgDictionaries.close(); } catch (IOException e) { logger.error("Exception while trying to close dictionaries writer.", e); } } } }

Target:
private void fetchDictionaries(File collectionDir, String collectionName, final EntityManager rootEm, Results entity, Gson gson, Integer batchId) { JsonGenerator jgDictionaries = null; try { jgDictionaries = getJsonGenerator(new File(collectionDir + "/" + collectionName + "_" + "dictionaries_" + batchId)); for (Entity et : entity.getEntities()) { Set<String> dictionaries; try { dictionaries = rootEm.getDictionaries(et); jgDictionaries.writeStartArray(); if (dictionaries != null && !dictionaries.isEmpty()) { for (String dictionary : dictionaries) { Map<Object, Object> dict = rootEm.getDictionaryAsMap(et, dictionary); if (dict != null && dict.isEmpty()) { continue; } jgDictionaries.writeStartObject(); jgDictionaries.writeObjectField("Entity", et.getUuid()); jgDictionaries.writeObjectField(dictionary, dict); jgDictionaries.writeEndObject(); } jgDictionaries.writeEndArray(); } } catch (Exception e) { logger.error("Exception while trying to fetch dictionaries.", e); } } } catch (Exception e) { logger.error("Exception while trying to fetch dictionaries.", e); } finally { if (jgDictionaries != null) { try { jgDictionaries.close(); } catch (IOException e) { logger.error("Exception while trying to close dictionaries writer.", e); } } } }
Source:
private static FailedOperationTransformationConfig createFailedOperationConfig(ModelVersion version) { FailedOperationTransformationConfig config = new FailedOperationTransformationConfig(); PathAddress subsystemAddress = PathAddress.pathAddress(InfinispanSubsystemResourceDefinition.PATH); PathAddress containerAddress = subsystemAddress.append(CacheContainerResourceDefinition.WILDCARD_PATH); if (InfinispanModel.VERSION_2_0_0.requiresTransformation(version)) { for (PathElement path : Arrays.asList(DistributedCacheResourceDefinition.WILDCARD_PATH, ReplicatedCacheResourceDefinition.WILDCARD_PATH)) { PathAddress cacheAddress = containerAddress.append(path); config.addFailedAttribute( cacheAddress.append(BackupsResourceDefinition.PATH).append(BackupResourceDefinition.WILDCARD_PATH), FailedOperationTransformationConfig.REJECTED_RESOURCE); config.addFailedAttribute( cacheAddress.append(BackupForResourceDefinition.PATH), FailedOperationTransformationConfig.REJECTED_RESOURCE); } } return config; }

Target:
private static FailedOperationTransformationConfig createFailedOperationConfig(ModelVersion version) { FailedOperationTransformationConfig config = new FailedOperationTransformationConfig(); PathAddress subsystemAddress = PathAddress.pathAddress(InfinispanSubsystemResourceDefinition.PATH); PathAddress containerAddress = subsystemAddress.append(CacheContainerResourceDefinition.WILDCARD_PATH); if (InfinispanModel.VERSION_2_0_0.requiresTransformation(version)) { for (PathElement path : Arrays.asList(DistributedCacheResourceDefinition.WILDCARD_PATH, ReplicatedCacheResourceDefinition.WILDCARD_PATH)) { PathAddress cacheAddress = containerAddress.append(path); config.addFailedAttribute( cacheAddress.append(BackupsResourceDefinition.PATH).append(BackupResourceDefinition.WILDCARD_PATH), FailedOperationTransformationConfig.REJECTED_RESOURCE); config.addFailedAttribute( cacheAddress.append(BackupForResourceDefinition.PATH), FailedOperationTransformationConfig.REJECTED_RESOURCE); } } if (InfinispanModel.VERSION_1_5_0.requiresTransformation(version)) { config.addFailedAttribute( containerAddress, new ChangeToTrueConfig(CacheContainerResourceDefinition.Attribute.STATISTICS_ENABLED.getDefinition().getName())); config.addFailedAttribute( containerAddress.append(LocalCacheResourceDefinition.WILDCARD_PATH), new ChangeToTrueConfig(CacheResourceDefinition.Attribute.STATISTICS_ENABLED.getDefinition().getName())); config.addFailedAttribute( containerAddress.append(DistributedCacheResourceDefinition.WILDCARD_PATH), new ChangeToTrueConfig(CacheResourceDefinition.Attribute.STATISTICS_ENABLED.getDefinition().getName())); config.addFailedAttribute( containerAddress.append(ReplicatedCacheResourceDefinition.WILDCARD_PATH), new ChangeToTrueConfig(CacheResourceDefinition.Attribute.STATISTICS_ENABLED.getDefinition().getName())); config.addFailedAttribute( containerAddress.append(InvalidationCacheResourceDefinition.WILDCARD_PATH), new ChangeToTrueConfig(CacheResourceDefinition.Attribute.STATISTICS_ENABLED.getDefinition().getName())); } return config; }
Source:
public Map<String, Boolean> getLsFileMap(String paramString) throws Exception { HashMap<Object, Object> hashMap = new HashMap<>(); Vector<ChannelSftp.LsEntry> vector = channelSFTP.ls(paramString); for (byte b = 0; b < vector.size(); b++) { ChannelSftp.LsEntry lsEntry = vector.get(b); String str = lsEntry.getFilename(); if (!".".equals(str)) { if (!"..".equals(str)) { String str1 = paramString + "/" + str; boolean bool = isDirectory(str1); this.logger.info("fileName : " + str); hashMap.put(str, Boolean.valueOf(bool)); } } } return (Map) hashMap; }

Target:
public Map<String, Boolean> getLsFileMap(String paramString) throws Exception { Map<String, Boolean> hashMap = new HashMap<>(); Vector<ChannelSftp.LsEntry> vector = channelSFTP.ls(paramString); for(ChannelSftp.LsEntry lsEntry : vector) { String str = lsEntry.getFilename(); if (!".".equals(str)) { if (!"..".equals(str)) { String str1 = paramString + "/" + str; boolean bool = isDirectory(str1); this.logger.info("fileName : " + str); hashMap.put(str, Boolean.valueOf(bool)); } } } return hashMap; }
Source:
public String awaitConfigToExecute() throws TerminateException { if (!registered) { throw new IllegalStateException("must be registered"); } try { statusExchangeThread.setPendingRequestEntity(); String configName; do { configName = statusExchangeThread.nextConfigToExecute.poll(1, TimeUnit.MINUTES); if (!standBy) { throw new TerminateException("Master execution can't be proceeded"); } } while (configName == null); statusExchangeThread.setRunningRequestEntity(configName); synchronized (statusExchangeThread.statusLock) { statusExchangeThread.statusLock.wait(); } return configName; } catch (InterruptedException e) { statusExchangeThread.interrupt(); throw new TerminateException("Master execution can't be proceeded"); } }

Target:
public String awaitConfigToExecute() throws TerminateException { if (!registered) { throw new IllegalStateException("must be registered"); } try { statusExchangeThread.setPendingRequestEntity(); String configName; do { configName = statusExchangeThread.nextConfigToExecute.poll(1, TimeUnit.MINUTES); if (!standBy) { throw new TerminateException("Master execution can't be proceeded"); } } while (configName == null); statusExchangeThread.setRunningRequestEntity(configName); statusExchangeThread.statusSent = false; synchronized (statusExchangeThread.statusLock) { while (!statusExchangeThread.statusSent) { statusExchangeThread.statusLock.wait(statusReportIntervalSeconds * 1000); if (!standBy) throw new TerminateException("Master execution can't be proceeded"); } } return configName; } catch (InterruptedException e) { statusExchangeThread.interrupt(); throw new TerminateException("Master execution can't be proceeded"); } }
Source:
public static void AdminChatMsg(CommandSender sender, String message) { for (Player onlineadmins : Bukkit.getOnlinePlayers()) { if (ICM_Rank.isRankOrHigher(onlineadmins, ICM_Rank.Rank.SUPER)) { onlineadmins.sendMessage("§f[§bADMIN§f] §c" + sender.getName() + ICM_Rank.getRank(sender).actag + "§f: §b " + message); } } }

Target:
public static void AdminChatMsg(CommandSender sender, String message) { for (Player onlineadmins : Bukkit.getOnlinePlayers()) { if (ICM_Rank.isRankOrHigher(onlineadmins, ICM_Rank.Rank.SUPER)) { onlineadmins.sendMessage("§f[§bADMIN§f] §c" + ICM_SqlHandler.getNick(sender) + ICM_Rank.getRank(sender).actag + "§f: §b " + message); } } }
Source:
public void onPlayerQuit(final PlayerQuitEvent event) { final User user = ess.getUser(event.getPlayer()); if (ess.getSettings().allowSilentJoinQuit() && user.isAuthorized("essentials.silentquit")) { event.setQuitMessage(null); } else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) { final Player player = event.getPlayer(); String quitMessage = ess.getSettings().getCustomQuitMessage(); quitMessage.replace("{PLAYER}", player.getDisplayName()) .replace("{USERNAME}", player.getName()); quitMessage = FormatUtil.placeholderAPIFormat(user, quitMessage); event.setQuitMessage(quitMessage); } user.startTransaction(); if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled()) { user.setGodModeEnabled(false); } if (user.isVanished()) { user.setVanished(false); } user.setLogoutLocation(); if (user.isRecipeSee()) { user.getBase().getOpenInventory().getTopInventory().clear(); } for (HumanEntity viewer : user.getBase().getInventory().getViewers()) { if (viewer instanceof Player) { User uviewer = ess.getUser((Player) viewer); if (uviewer.isInvSee()) { uviewer.getBase().closeInventory(); } } } user.updateActivityOnInteract(false); if (!user.isHidden()) { user.setLastLogout(System.currentTimeMillis()); } user.stopTransaction(); user.dispose(); }

Target:
public void onPlayerQuit(final PlayerQuitEvent event) { final User user = ess.getUser(event.getPlayer()); if (ess.getSettings().allowSilentJoinQuit() && user.isAuthorized("essentials.silentquit")) { event.setQuitMessage(null); } else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) { final Player player = event.getPlayer(); String quitMessage = ess.getSettings().getCustomQuitMessage() .replace("{PLAYER}", player.getDisplayName()) .replace("{USERNAME}", player.getName()); quitMessage = FormatUtil.placeholderAPIFormat(user, quitMessage); event.setQuitMessage(quitMessage); } user.startTransaction(); if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled()) { user.setGodModeEnabled(false); } if (user.isVanished()) { user.setVanished(false); } user.setLogoutLocation(); if (user.isRecipeSee()) { user.getBase().getOpenInventory().getTopInventory().clear(); } for (HumanEntity viewer : user.getBase().getInventory().getViewers()) { if (viewer instanceof Player) { User uviewer = ess.getUser((Player) viewer); if (uviewer.isInvSee()) { uviewer.getBase().closeInventory(); } } } user.updateActivityOnInteract(false); if (!user.isHidden()) { user.setLastLogout(System.currentTimeMillis()); } user.stopTransaction(); user.dispose(); }
Source:
public Object visitDataWriteCommand(InvocationContext ctx, DataWriteCommand command, boolean assumeOriginKeptEntryInL1) throws Throwable { Object returnValue = invokeNextInterceptor(ctx, command); Object key; if (shouldUpdateOnWriteCommand(command) && command.isSuccessful() && cdl.localNodeIsPrimaryOwner((key = command.getKey()))) { getLog().tracef("Sending additional invalidation for requestors if necessary."); l1Manager.flushCache(Collections.singleton(key), ctx.getOrigin(), assumeOriginKeptEntryInL1); } return returnValue; }

Target:
public Object visitDataWriteCommand(InvocationContext ctx, DataWriteCommand command, boolean assumeOriginKeptEntryInL1) throws Throwable { Object returnValue = invokeNextInterceptor(ctx, command); Object key; if (shouldUpdateOnWriteCommand(command) && command.isSuccessful() && cdl.localNodeIsPrimaryOwner((key = command.getKey()))) { if (trace) { log.trace("Sending additional invalidation for requestors if necessary."); } l1Manager.flushCache(Collections.singleton(key), ctx.getOrigin(), assumeOriginKeptEntryInL1); } return returnValue; }
Source:
public void write(Object datum) throws IOException { if (!opened) { throw new IOException("Writer is not opened"); } result.totalCount++; if (datum == null) { return; } IndexedRecord record = (IndexedRecord) datum; Schema schema = record.getSchema(); Schema.Field idField = schema.getField(idFieldName); if (idField == null) { throw new IOException("Schema does not contain ID field: " + idFieldName); } int idPos = idField.pos(); Object id = record.get(idPos); if (id == null) { throw new IOException("ID field is null: " + idField.name()); } connection.upsert(id.toString(), datum.toString()); }

Target:
public void write(Object datum) throws IOException { if (!opened) { throw new IOException("Writer is not opened"); } result.totalCount++; if (datum == null) { return; } IndexedRecord record = (IndexedRecord) datum; Schema schema = record.getSchema(); Schema.Field idField = schema.getField(idFieldName); if (idField == null) { throw new IOException("Schema does not contain ID field: " + idFieldName); } int idPos = idField.pos(); Object id = record.get(idPos); if (id == null) { handleException("Record is not processed. ID is null.", new IllegalArgumentException("ID field should not be null")); return; } try { connection.upsert(id.toString(), datum.toString()); result.successCount++; } catch (Exception e) { handleException("Record is not processed. Failed to upsert value - " + datum.toString(), e); } }
Source:
protected IContributionItem[] getContributionItems() { final List<IContributionItem> list = new ArrayList<IContributionItem>(); CommandContributionItemParameter params = new CommandContributionItemParameter(ReviewsUiPlugin.getDefault() .getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .getActivePart() .getSite(), UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND, null, ImageDescriptor.createFromURL(ReviewsUiPlugin.getDefault() .getBundle() .getEntry(UIUtils.NEXT_COMMENT_ANNOTATION_ICON_FILE)), null, null, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND_NAME, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND_MNEMONIC, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND_TOOLTIP, CommandContributionItem.STYLE_PUSH, null, true); list.add(new CommandContributionItem(params)); params = new CommandContributionItemParameter(ReviewsUiPlugin.getDefault() .getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .getActivePart() .getSite(), UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND, null, ImageDescriptor.createFromURL(ReviewsUiPlugin.getDefault() .getBundle() .getEntry(UIUtils.PREVIOUS_COMMENT_ANNOTATION_ICON_FILE)), null, null, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND_NAME, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND_MNEMONIC, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND_TOOLTIP, CommandContributionItem.STYLE_PUSH, null, true); list.add(new CommandContributionItem(params)); UIUtils.setCurrentElement(0); return list.toArray(new IContributionItem[list.size()]); }

Target:
public IContributionItem[] getContributionItems() { final List<IContributionItem> list = new ArrayList<IContributionItem>(); IWorkbenchSite site = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .getActivePart() .getSite(); if (site != null) { CommandContributionItemParameter params = new CommandContributionItemParameter(site, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND, null, ImageDescriptor.createFromURL(ReviewsUiPlugin.getDefault() .getBundle() .getEntry(UIUtils.NEXT_COMMENT_ANNOTATION_ICON_FILE)), null, null, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND_NAME, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND_MNEMONIC, UIUtils.NEXT_COMMENT_ANNOTATION_COMMAND_TOOLTIP, CommandContributionItem.STYLE_PUSH, null, true); list.add(new CommandContributionItem(params)); params = new CommandContributionItemParameter(site, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND, null, ImageDescriptor.createFromURL(ReviewsUiPlugin.getDefault() .getBundle() .getEntry(UIUtils.PREVIOUS_COMMENT_ANNOTATION_ICON_FILE)), null, null, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND_NAME, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND_MNEMONIC, UIUtils.PREVIOUS_COMMENT_ANNOTATION_COMMAND_TOOLTIP, CommandContributionItem.STYLE_PUSH, null, true); list.add(new CommandContributionItem(params)); UIUtils.setCurrentElement(0); return list.toArray(new IContributionItem[list.size()]); } else { return null; } }
Source:
public FileSystem getFileSystem(final URI uri) { return getDefaultFileSystem(); }

Target:
public FileSystem getFileSystem(final URI uri) throws IllegalArgumentException, FileSystemNotFoundException, SecurityException { return getDefaultFileSystem(); }
Source:
public TableName[] listTableNames() throws IOException { ListTablesRequest.Builder builder = ListTablesRequest.newBuilder(); clusterMetadataSetter.setMetadata(builder); ListTablesResponse response; try { response = bigtableAdminClient.listTables(builder.build()); } catch (Throwable throwable) { throw new IOException("Failed to listTables", throwable); } List<Table> tablesList = response.getTablesList(); TableName[] result = new TableName[tablesList.size()]; for (int i=0;i<tablesList.size(); i++) { String name = clusterMetadataSetter.toHBaseTableName(tablesList.get(i).getName()); result[i] = TableName.valueOf(name); } return result; }

Target:
public TableName[] listTableNames() throws IOException { return asTableNames(requestTableList().getTablesList()); }
Source:
abstract void process(ReviewDb db, Account.Id account, Map<Id, Change> outResultChanges) throws OrmException ; } private List<Change.Id> changesCreatedBy(final ReviewDb db, final String userName) { UserNameProcessor processor = new UserNameProcessor(db, userName) { @Override void process(ReviewDb db, Account.Id account, Map<Id, Change> resultChanges) throws OrmException { for (Change change : db.changes().byOwnerOpen(account)) { resultChanges.put(change.getId(), change); } for (Change change : db.changes().byOwnerClosed(account)) { resultChanges.put(change.getId(), change); } } }; return new ArrayList<Change.Id>(processor.call()); }

Target:
abstract void process(ReviewDb db, Account.Id account, Map<Id, Change> outResultChanges) throws OrmException ; } private Set<Change.Id> changesCreatedBy(final ReviewDb db, final String userName) throws OrmException { UserNameProcessor processor = new UserNameProcessor(db, userName) { @Override void process(ReviewDb db, Account.Id account, Map<Id, Change> resultChanges) throws OrmException { for (Change change : db.changes().byOwnerOpen(account)) { resultChanges.put(change.getId(), change); } for (Change change : db.changes().byOwnerClosed(account)) { resultChanges.put(change.getId(), change); } } }; return processor.call(); }
Source:
public boolean removeAll(Collection<?> c) { return innerList.removeAll(c); }

Target:
public boolean removeAll(Collection<?> c) { boolean removeAll = innerList.removeAll(c); for (Object o : c) { if (o != null && o instanceof Node) ((Node) o).setParentNode(null); } return removeAll; }
Source:
public static Arguments buildArgs() { String memory = bytesToString( OsBeanUtil.getTotalPhysicalMemory() ); return new Arguments() .withArgument( new OptionalNamedArg( ARG_MEMORY, memory, memory, "Recommend memory settings with respect to the given amount of memory, " + "instead of the total memory of the system running the command." ) ) .withArgument( new OptionalBooleanArg( ARG_DB, false, "Specific database to calculate page cache memory requirement for. " + "The generic calculation is still a good generic recommendation for this machine, " + "but there will be an additional calculation for minimal required page cache memory " + "for mapping all store and index files that are managed by the page cache." ) ); }

Target:
public static Arguments buildArgs() { String memory = bytesToString( OsBeanUtil.getTotalPhysicalMemory() ); return new Arguments() .withArgument( new OptionalNamedArg( ARG_MEMORY, memory, memory, "Recommend memory settings with respect to the given amount of memory, " + "instead of the total memory of the system running the command." ) ) .withDatabase( "Name of specific database to calculate page cache memory requirement for. " + "The generic calculation is still a good generic recommendation for this machine, " + "but there will be an additional calculation for minimal required page cache memory " + "for mapping all store and index files that are managed by the page cache." ); }
Source:
private static String[] generateRootClassesFromWorkspace() { String classpath = System.getProperty("java.class.path"); Object[] binDirectories = extractBinDirectories(classpath); HashSet<String> classFileNames = HashSetFactory.make(); for (Object binDirectorie : binDirectories) { String dir = (String) binDirectorie; File fdir = new File(dir); classFileNames.addAll(findClassNames(dir, fdir)); } String[] result = new String[classFileNames.size()]; Iterator<String> it = classFileNames.iterator(); Arrays.setAll(result, i -> it.next()); return result; }

Target:
private static String[] generateRootClassesFromWorkspace() { String classpath = System.getProperty("java.class.path"); Object[] binDirectories = extractBinDirectories(classpath); HashSet<String> classFileNames = HashSetFactory.make(); for (Object binDirectorie : binDirectories) { String dir = (String) binDirectorie; File fdir = new File(dir); classFileNames.addAll(findClassNames(dir, fdir)); } return classFileNames.toArray(new String[0]); }
Source:
public void setup() throws IOException { _embeddedZookeeper = new EmbeddedZookeeper(22183); _zkConnectionString = _embeddedZookeeper.getConnection(); _embeddedZookeeper.startup(); }

Target:
public void setup() throws IOException { _embeddedZookeeper = new EmbeddedZookeeper(); _zkConnectionString = _embeddedZookeeper.getConnection(); _embeddedZookeeper.startup(); }
Source:
public void paintControl(PaintEvent event) { if (fTextWidget != null) { try { handleDrawRequest(event.gc); } catch (IllegalStateException e) { String PLUGIN_ID= "org.eclipse.jface.text"; ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, JFaceTextMessages.getString("MatchingCharacterPainter.unexpected_error"), e)); return; } } }

Target:
public void paintControl(PaintEvent event) { if (fTextWidget != null) { try { handleDrawRequest(event.gc); } catch (IllegalStateException e) { String PLUGIN_ID= "org.eclipse.jface.text"; ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, e.getMessage(), e)); } } }
Source:
public void cacheSerializingCopiers() throws Exception { CacheConfiguration<Long, Person> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder() .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()) .add(new DefaultCopierConfiguration<Long>((Class)SerializingCopier.class, CopierConfiguration.Type.VALUE)) .buildConfig(Long.class, Person.class); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("cache", cacheConfiguration) .build(true); Cache<Long, Person> cache = cacheManager.getCache("cache", Long.class, Person.class); Description desc = new Description(1234, "foo"); Person person = new Person("Bar", 24); cache.put(1l, person); assertThat(cache.get(1l), equalTo(person)); assertThat(cache.get(1l), not(sameInstance(person))); cacheManager.close(); }

Target:
public void cacheSerializingCopiers() throws Exception { CacheConfiguration<Long, Person> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder() .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()) .add(new DefaultCopierConfiguration<Person>((Class)SerializingCopier.class, CopierConfiguration.Type.VALUE)) .buildConfig(Long.class, Person.class); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("cache", cacheConfiguration) .build(true); Cache<Long, Person> cache = cacheManager.getCache("cache", Long.class, Person.class); Description desc = new Description(1234, "foo"); Person person = new Person("Bar", 24); cache.put(1l, person); assertThat(cache.get(1l), equalTo(person)); assertThat(cache.get(1l), not(sameInstance(person))); cacheManager.close(); }
Source:
public static String hash(String clearText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(clearText.getBytes("UTF-8")); byte[] bytes = md.digest(); Formatter f = new Formatter(); for (byte b : bytes) f.format("%02x", b); String res = f.toString(); f.close(); return res; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return clearText; }

Target:
public static String hash(String clearText) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(clearText.getBytes("UTF-8")); byte[] bytes = md.digest(); Formatter f = new Formatter(); for (byte b : bytes) f.format("%02x", b); String res = f.toString(); f.close(); return res; } catch (NoSuchAlgorithmException e) { Log.e(K9.LOG_TAG, "", e); } catch (UnsupportedEncodingException e) { Log.e(K9.LOG_TAG, "", e); } return clearText; }
Source:
private List<HtmlContext> performAttack (HttpMessage msg, String param, String attack, HtmlContext targetContext, int ignoreFlags, boolean findDecoded) { if (isStop()) { return null; } HttpMessage msg2 = msg.cloneRequest(); setParameter(msg2, param, attack); try { sendAndReceive(msg2); } catch (URIException e) { if (log.isDebugEnabled()) { log.debug("Failed to send HTTP message, cause: " + e.getMessage()); } return null; } catch (InvalidRedirectLocationException|UnknownHostException e) { return null; } catch (Exception e) { log.error(e.getMessage(), e); } if (isStop()) { return null; } HtmlContextAnalyser hca = new HtmlContextAnalyser(msg2); if (Plugin.AlertThreshold.HIGH.equals(this.getAlertThreshold())) { return hca.getHtmlContexts(attack, targetContext, ignoreFlags); } if (findDecoded) { try { return hca.getHtmlContexts(URLDecoder.decode(attack, UTF8), targetContext, ignoreFlags); } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug("Failed to decode attack payload, cause: " + e.getMessage(), e); } } } return hca.getHtmlContexts(attack); }

Target:
private List<HtmlContext> performAttack (HttpMessage msg, String param, String attack, HtmlContext targetContext, int ignoreFlags, boolean findDecoded) { if (isStop()) { return null; } HttpMessage msg2 = msg.cloneRequest(); setParameter(msg2, param, attack); try { sendAndReceive(msg2); } catch (URIException e) { if (log.isDebugEnabled()) { log.debug("Failed to send HTTP message, cause: " + e.getMessage()); } return null; } catch (InvalidRedirectLocationException|UnknownHostException e) { return null; } catch (Exception e) { log.error(e.getMessage(), e); } if (isStop()) { return null; } HtmlContextAnalyser hca = new HtmlContextAnalyser(msg2); if (Plugin.AlertThreshold.HIGH.equals(this.getAlertThreshold())) { return hca.getHtmlContexts(findDecoded ? getURLDecode(attack) : attack, targetContext, ignoreFlags); } return hca.getHtmlContexts(findDecoded ? getURLDecode(attack) : attack); }
Source:
public void editingTopic_ifSubscribedToBranchOnly_shouldNotReceiveBranchNotification() throws Exception { User topicCreator = Users.signUpAndSignIn(); Topic topic = Topics.createTopic(new Topic().withBranch(NOTIFICATION_BRANCH)); Users.logout(); User subscribedUser = Users.signUpAndSignIn(); Branches.subscribe(topic.getBranch()); Topics.unsubscribe(topic); Users.signIn(topicCreator); Branches.openBranch(NOTIFICATION_BRANCH); Topics.editPost(topic, selectedPost); Users.logout(); Users.signIn(subscribedUser); unsubscribeIgnoringFail(Branch branch); Notifications.assertNotificationOnTopicNotSentBranchNotSent(topic, subscribedUser); }

Target:
public void editingTopic_ifSubscribedToBranchOnly_shouldNotReceiveBranchNotification() throws Exception { User topicCreator = Users.signUpAndSignIn(); Topic topic = Topics.createTopic(new Topic().withBranch(NOTIFICATION_BRANCH)); User subscribedUser = Users.signUpAndSignIn(); Branches.subscribe(topic.getBranch()); Topics.unsubscribe(topic); Users.signIn(topicCreator); Topics.editPost(topic, selectedPost); Users.signIn(subscribedUser); unsubscribeIgnoringFail(Branch branch); Notifications.assertNotificationsOnTopicNotSent(topic, subscribedUser); Notifications.assertNotificationsOnBranchNotSent(topic, subscribedUser); }