auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public byte[] serialize(Object record) throws ZkMarshallingError { if (!(record instanceof ZNRecord)) { LOG.error( "Input object must be of type ZNRecord but it is " + record + ". Will not write to zk"); throw new HelixException("Input object is not of type ZNRecord (was " + record + ")"); } ZNRecord znRecord = (ZNRecord) record; try { return OBJECT_MAPPER.writeValueAsBytes(znRecord); } catch (Exception e) { throw new HelixException( String.format("Exception during serialization. ZNRecord id: %s", znRecord.getId()), e); } }

Target:
public byte[] serialize(Object record) throws ZkMarshallingError { if (!(record instanceof ZNRecord)) { throw new HelixException("Input object is not of type ZNRecord (was " + record + ")"); } ZNRecord znRecord = (ZNRecord) record; try { return OBJECT_MAPPER.writeValueAsBytes(znRecord); } catch (IOException e) { throw new HelixException( String.format("Exception during serialization. ZNRecord id: %s", znRecord.getId()), e); } }
Source:
private static SSAInstruction[] getMethodArrayStatements( MethodReference ref, Collection<IMethod> returnValues, Context context, Map<Integer, ConstantValue> constants) { ArrayList<SSAInstruction> statements = new ArrayList<>(); int nextLocal = ref.getNumberOfParameters() + 2; int retValue = nextLocal++; IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType(); SSAInstructionFactory insts = ((TypeAbstraction) context.get(ContextKey.RECEIVER)) .getType() .getClassLoader() .getInstructionFactory(); if (cls != null) { TypeReference arrType = ref.getReturnType(); NewSiteReference site = new NewSiteReference(retValue, arrType); int sizeVn = nextLocal++; constants.put(sizeVn, new ConstantValue(returnValues.size())); SSANewInstruction allocArr = insts.NewInstruction(statements.size(), retValue, site, new int[] {sizeVn}); statements.add(allocArr); int i = 0; for (IMethod m : returnValues) { int c = nextLocal++; constants.put(c, new ConstantValue(m)); int index = i++; int indexVn = nextLocal++; constants.put(indexVn, new ConstantValue(index)); SSAArrayStoreInstruction store = insts.ArrayStoreInstruction( statements.size(), retValue, indexVn, c, TypeReference.JavaLangReflectConstructor); statements.add(store); } SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), retValue, false); statements.add(R); } else { } SSAInstruction[] result = new SSAInstruction[statements.size()]; Iterator<SSAInstruction> it = statements.iterator(); Arrays.setAll(result, i -> it.next()); return result; }

Target:
private static SSAInstruction[] getMethodArrayStatements( MethodReference ref, Collection<IMethod> returnValues, Context context, Map<Integer, ConstantValue> constants) { ArrayList<SSAInstruction> statements = new ArrayList<>(); int nextLocal = ref.getNumberOfParameters() + 2; int retValue = nextLocal++; IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType(); SSAInstructionFactory insts = ((TypeAbstraction) context.get(ContextKey.RECEIVER)) .getType() .getClassLoader() .getInstructionFactory(); if (cls != null) { TypeReference arrType = ref.getReturnType(); NewSiteReference site = new NewSiteReference(retValue, arrType); int sizeVn = nextLocal++; constants.put(sizeVn, new ConstantValue(returnValues.size())); SSANewInstruction allocArr = insts.NewInstruction(statements.size(), retValue, site, new int[] {sizeVn}); statements.add(allocArr); int i = 0; for (IMethod m : returnValues) { int c = nextLocal++; constants.put(c, new ConstantValue(m)); int index = i++; int indexVn = nextLocal++; constants.put(indexVn, new ConstantValue(index)); SSAArrayStoreInstruction store = insts.ArrayStoreInstruction( statements.size(), retValue, indexVn, c, TypeReference.JavaLangReflectConstructor); statements.add(store); } SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), retValue, false); statements.add(R); } else { } return statements.toArray(new SSAInstruction[0]); }
Source:
private void stopServer(final String serverName) { ModelNode op = new ModelNode(); op.get(OP_ADDR).add(HOST, MASTER); op.get(OP_ADDR).add(SERVER_CONFIG, FIRST_SERVER_NAME); op.get(OP).set(STOP); op.get(TIMEOUT).set(0); op.get(ADMIN_ONLY).set(false); domainMasterLifecycleUtil.executeForResult(op); try { waitUntilState(FIRST_SERVER_NAME, "STOPPED"); } catch (TimeoutException e) { fail("After \"stop(timeout=0)\" was called sever never reached the desired STOPPED state."); } }

Target:
private void stopServer(final String serverName) { ModelNode op = new ModelNode(); op.get(OP_ADDR).add(HOST, MASTER); op.get(OP_ADDR).add(SERVER_CONFIG, FIRST_SERVER_NAME); op.get(OP).set(STOP); op.get(TIMEOUT).set(0); domainMasterLifecycleUtil.executeForResult(op); try { waitUntilState(FIRST_SERVER_NAME, "STOPPED"); } catch (TimeoutException e) { fail("After \"stop(timeout=0)\" was called sever never reached the desired STOPPED state."); } }
Source:
public boolean onBlockDestroyed(ItemStack stack, World worldIn, BlockState state, BlockPos pos, LivingEntity entityLiving) { if(state == harvestedBlock.get().getDefaultState()) { int harvestCounter = 0; for(Float i = entityLiving.getRNG().nextFloat(); i <= percentage || harvestCounter >= maxBonusItems; i = entityLiving.getRNG().nextFloat()) { ItemEntity item = new ItemEntity(worldIn, pos.getX(), pos.getY(), pos.getZ(), itemDropped.get().getDefaultInstance()); worldIn.addEntity(item); harvestCounter++; } if(melonOverload && harvestCounter >= 9 && entityLiving instanceof PlayerEntity) { ITextComponent message = new TranslationTextComponent(getTranslationKey() + ".message"); message.getStyle().setColor(TextFormatting.GREEN); message.getStyle().setBold(true); if(!worldIn.isRemote) { entityLiving.sendMessage(message); entityLiving.addPotionEffect(new EffectInstance(Effects.STRENGTH, 1800, 3)); entityLiving.addPotionEffect(new EffectInstance(Effects.RESISTANCE, 1800, 3)); entityLiving.addPotionEffect(new EffectInstance(Effects.HASTE, 1800, 3)); } MSCriteriaTriggers.MELON_OVERLOAD.trigger((ServerPlayerEntity) entityLiving); } } return super.onBlockDestroyed(stack, worldIn, state, pos, entityLiving); }

Target:
public boolean onBlockDestroyed(ItemStack stack, World worldIn, BlockState state, BlockPos pos, LivingEntity entityLiving) { if(state == harvestedBlock.get().getDefaultState() && !worldIn.isRemote) { int harvestCounter = 0; for(Float i = entityLiving.getRNG().nextFloat(); i <= percentage && harvestCounter < maxBonusItems; i = entityLiving.getRNG().nextFloat()) { ItemEntity item = new ItemEntity(worldIn, pos.getX(), pos.getY(), pos.getZ(), itemDropped.get().getDefaultInstance()); worldIn.addEntity(item); harvestCounter++; } if(melonOverload && harvestCounter >= 9 && entityLiving instanceof PlayerEntity) { ITextComponent message = new TranslationTextComponent(getTranslationKey() + ".message"); message.getStyle().setColor(TextFormatting.GREEN); message.getStyle().setBold(true); entityLiving.sendMessage(message); entityLiving.addPotionEffect(new EffectInstance(Effects.STRENGTH, 1800, 3)); entityLiving.addPotionEffect(new EffectInstance(Effects.RESISTANCE, 1800, 3)); entityLiving.addPotionEffect(new EffectInstance(Effects.HASTE, 1800, 3)); MSCriteriaTriggers.MELON_OVERLOAD.trigger((ServerPlayerEntity) entityLiving); } } return super.onBlockDestroyed(stack, worldIn, state, pos, entityLiving); }
Source:
public void run() { try { Threads.setDaemonThreadRunning(new Thread() { @Override public void run() { for (;;) { try { if (!Strings.isNullOrEmpty(ZKClusterId.readClusterIdZNode(zooKeeper))) { setupClusterConnection(); break; } } catch (Throwable t) { LOG.warn("failed to initialize cluster connection, retrying..."); } Threads.sleep(1000); } } }, getName() + ":initClusterConnection"); if (!conf.getBoolean("hbase.testing.nocluster", false)) { Threads.setDaemonThreadRunning(new Thread(() -> { try { int infoPort = putUpJettyServer(); startActiveMasterManager(infoPort); } catch (Throwable t) { String error = "Failed to become Active Master"; LOG.error(error, t); if (!isAborted()) { abort(error, t); } } }), getName() + ":becomeActiveMaster"); } super.run(); } finally { if (this.clusterSchemaService != null) { this.clusterSchemaService.stopAsync(); try { this.clusterSchemaService.awaitTerminated( getConfiguration().getInt(HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS, DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS), TimeUnit.SECONDS); } catch (TimeoutException te) { LOG.warn("Failed shutdown of clusterSchemaService", te); } } this.activeMaster = false; } }

Target:
public void run() { try { Threads.setDaemonThreadRunning(new Thread(() -> { for (;;) { try { if (!Strings.isNullOrEmpty(ZKClusterId.readClusterIdZNode(zooKeeper))) { setupClusterConnection(); break; } else { LOG.trace("cluster id is still null, waiting..."); } } catch (Throwable t) { LOG.warn("failed to initialize cluster connection, retrying..."); } Threads.sleep(1000); } }), getName() + ":initClusterConnection"); if (!conf.getBoolean("hbase.testing.nocluster", false)) { Threads.setDaemonThreadRunning(new Thread(() -> { try { int infoPort = putUpJettyServer(); startActiveMasterManager(infoPort); } catch (Throwable t) { String error = "Failed to become Active Master"; LOG.error(error, t); if (!isAborted()) { abort(error, t); } } }), getName() + ":becomeActiveMaster"); } super.run(); } finally { if (this.clusterSchemaService != null) { this.clusterSchemaService.stopAsync(); try { this.clusterSchemaService.awaitTerminated( getConfiguration().getInt(HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS, DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS), TimeUnit.SECONDS); } catch (TimeoutException te) { LOG.warn("Failed shutdown of clusterSchemaService", te); } } this.activeMaster = false; } }
Source:
public void testExecutorFilter() throws Exception { MockFlowObject dispatchingObj = new MockFlowObject("flow1",3096, 1500,4200,2); MockFilter mFilter = new MockFilter(); mFilter.registerFilterforRemainingMemory(); boolean result = mFilter.check(this.getExecutorByName("Executor1"), dispatchingObj); Assert.assertTrue(result); result = mFilter.check(this.getExecutorByName("Executor3"), dispatchingObj); Assert.assertTrue(result); mFilter.registerFilterforPriority(); result = mFilter.check(this.getExecutorByName("Executor3"), dispatchingObj); Assert.assertFalse(result); mFilter.registerFilterforRemainingTmpSpace(); result = mFilter.check(this.getExecutorByName("Executor2"), dispatchingObj); Assert.assertTrue(result); result = mFilter.check(this.getExecutorByName("Executor8"), dispatchingObj); Assert.assertFalse(result); }

Target:
public void testExecutorFilter() throws Exception { MockFlowObject dispatchingObj = new MockFlowObject("flow1",3096, 1500,4200,2); MockFilter mFilter = new MockFilter(); mFilter.registerFilterforRemainingMemory(); boolean result = mFilter.filterTarget(this.getExecutorByName("Executor1"), dispatchingObj); Assert.assertTrue(result); result = mFilter.filterTarget(this.getExecutorByName("Executor3"), dispatchingObj); Assert.assertTrue(result); mFilter.registerFilterforPriority(); result = mFilter.filterTarget(this.getExecutorByName("Executor3"), dispatchingObj); Assert.assertFalse(result); mFilter.registerFilterforRemainingTmpSpace(); result = mFilter.filterTarget(this.getExecutorByName("Executor2"), dispatchingObj); Assert.assertTrue(result); result = mFilter.filterTarget(this.getExecutorByName("Executor8"), dispatchingObj); Assert.assertFalse(result); }
Source:
public CellTrait trait(){ return new CellTrait() { @Override public Object get(Cell cell, CellTraitPropertySpec<?> spec) { if (spec == PROPERTY) { return SelectionController.this; } else { return super.get(cell, spec); } } @Override public void onAdd(Cell cell) { SelectionSupport<?> selectionSupport = cell.get(SelectionSupport.SELECTION_SUPPORT); if (selectionSupport != null) { selectionSupport.setSelectionController(SelectionController.this); } } }; }

Target:
private CellTrait trait(){ return new CellTrait() { @Override public Object get(Cell cell, CellTraitPropertySpec<?> spec) { if (spec == PROPERTY) { return SelectionController.this; } else { return super.get(cell, spec); } } @Override public void onAdd(Cell cell) { SelectionSupport<?> selectionSupport = cell.get(SelectionSupport.SELECTION_SUPPORT); if (selectionSupport != null) { selectionSupport.setSelectionController(SelectionController.this); } } }; }
Source:
protected String stringify(Collection<?> value) { Method saveAsString = null; if (paramConverter == null && headerDelegate == null) { try { Object o = value.iterator().next(); saveAsString = o.getClass().getMethod("saveAsString"); } catch (Exception e) { } } char separatorChar = getSeparatorChar(); StringBuilder sb = new StringBuilder(); boolean first = true; for (Object v : value) { if (first) { first = false; } else { sb.append(separatorChar); } if (v instanceof String) { sb.append(v); } else if (paramConverter != null) { sb.append(paramConverter.toString(v)); } else if (headerDelegate != null) { sb.append(headerDelegate.toString(v)); } else if (saveAsString != null) { try { sb.append(saveAsString.invoke(v)); } catch (Exception e) { throw new RuntimeException(Messages.MESSAGES.errorCallingSaveAsString(v)); } } else { sb.append(v.toString()); } } return sb.toString(); }

Target:
protected String stringify(Collection<?> value) { char separatorChar = getSeparatorChar(); StringBuilder sb = new StringBuilder(); boolean first = true; for (Object v : value) { if (first) { first = false; } else { sb.append(separatorChar); } if (v instanceof String) { sb.append(v); } else if (paramConverter != null) { sb.append(paramConverter.toString(v)); } else if (headerDelegate != null) { sb.append(headerDelegate.toString(v)); } else { sb.append(v.toString()); } } return sb.toString(); }
Source:
private void createDeleteTool(ToolSection toolSection, DiagramElementMapping... mappings) { if (!globalDeleteTool) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName(BASE_ID + "global.delete"); deleteElement.setLabel("Delete Tool"); toolSection.getOwnedTools().add(deleteElement); for (DiagramElementMapping dem : mappings) { deleteElement.getMappings().add(dem); } } else { for (DiagramElementMapping dem : mappings) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName(BASE_ID + "global.delete" + "." + dem.getLabel()); deleteElement.setLabel("Delete Tool" + " " + dem.getLabel()); toolSection.getOwnedTools().add(deleteElement); deleteElement.getMappings().add(dem); } } }

Target:
private void createDeleteTool(ToolSection toolSection, DiagramElementMapping... mappings) { if (!globalDeleteTool) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName(baseId + "global.delete"); deleteElement.setLabel("Delete Tool"); toolSection.getOwnedTools().add(deleteElement); for (DiagramElementMapping dem : mappings) { deleteElement.getMappings().add(dem); } } else { for (DiagramElementMapping dem : mappings) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName("global.delete" + "." + dem.getLabel()); deleteElement.setLabel("Delete Tool" + " " + dem.getLabel()); toolSection.getOwnedTools().add(deleteElement); deleteElement.getMappings().add(dem); } } }
Source:
protected void writeTupleGenerator( String function, TupleGenerator generator) { Long seed = generator.getRandomSeed(); writer_.writeElement( TUPLEGENERATOR_TAG, MapBuilder .of( FUNCTION_ATR, function) .putIf( SEED_ATR, Optional.ofNullable( seed != null? String.valueOf( seed) : null)) .put( TUPLES_ATR, String.valueOf( generator.getDefaultTupleSize())) .build(), () -> { for( TupleCombiner combiner : generator.getCombiners()) { writeCombiner( combiner); } }); }

Target:
protected void writeTupleGenerator( String function, TupleGenerator generator) { Long seed = generator.getRandomSeed(); writer_ .element( TUPLEGENERATOR_TAG) .attribute( FUNCTION_ATR, function) .attributeIf( seed != null, SEED_ATR, String.valueOf( seed)) .attribute( TUPLES_ATR, String.valueOf( generator.getDefaultTupleSize())) .content( () -> { for( TupleCombiner combiner : generator.getCombiners()) { writeCombiner( combiner); } }) .write(); }
Source:
protected boolean isInpatientCqmsValid() { int cqmCount = 0; for (String cqm : INPATIENT_CQMS) { if (this.cqmsMet.containsKey(cqm)) { ++cqmCount; } } if(!(this.counts.get("cqmsInpatientRequiredMet") >= this.counts.get("cqmsInpatientRequired"))){ String needed = String.valueOf((this.counts.get("cqmsInpatientRequired") - cqmCount)); TreeMap<String,ArrayList<String>> missingInpatient = new TreeMap<String,ArrayList<String>>(); missingInpatient.put(needed, (ArrayList<String>)INPATIENT_CQMS); missingX.add(missingInpatient); } this.counts.put("cqmsInpatientRequiredMet", cqmCount); return (this.counts.get("cqmsInpatientRequiredMet") >= this.counts.get("cqmsInpatientRequired")); }

Target:
protected boolean isInpatientCqmsValid() { int cqmCount = 0; for (String cqm : INPATIENT_CQMS) { if (this.cqmsMet.containsKey(cqm)) { ++cqmCount; } } if (this.counts.get("cqmsInpatientRequiredMet") < this.counts.get("cqmsInpatientRequired")) { String needed = String.valueOf((this.counts.get("cqmsInpatientRequired") - cqmCount)); TreeMap<String, ArrayList<String>> missingInpatient = new TreeMap<String, ArrayList<String>>(); missingInpatient.put(needed, (ArrayList<String>) INPATIENT_CQMS); missingX.add(missingInpatient); } this.counts.put("cqmsInpatientRequiredMet", cqmCount); return (this.counts.get("cqmsInpatientRequiredMet") >= this.counts.get("cqmsInpatientRequired")); }
Source:
public File get(String bsn, Version version, Map<String, String> properties, DownloadListener... listeners) throws Exception { prepare(); if (!isOk()) { return null; } Archive archive; ResourceInfo resource = bridge.getInfo(bsn, version); if (resource == null) { archive = trySources(bsn, version); if (archive == null) return null; } else { String name = resource.getInfo() .name(); archive = Archive.valueOf(name); } Promise<File> p = repoImpl.getMavenRepository() .get(archive); if (listeners.length == 0) return p.getValue(); new DownloadListenerPromise(reporter, name + ": get " + bsn + ";" + version, p, listeners); return repoImpl.getMavenRepository() .toLocalFile(archive); }

Target:
public File get(String bsn, Version version, Map<String, String> properties, DownloadListener... listeners) throws Exception { if (!init()) { return null; } Archive archive; ResourceInfo resource = bridge.getInfo(bsn, version); if (resource == null) { archive = trySources(bsn, version); if (archive == null) return null; } else { String name = resource.getInfo() .name(); archive = Archive.valueOf(name); } Promise<File> p = repoImpl.getMavenRepository() .get(archive); if (listeners.length == 0) return p.getValue(); new DownloadListenerPromise(reporter, name + ": get " + bsn + ";" + version, p, listeners); return repoImpl.getMavenRepository() .toLocalFile(archive); }
Source:
public static void createMessages(final ZulipApp app, final List<Message> messages) { try { TransactionManager.callInTransaction(app.getDatabaseHelper() .getConnectionSource(), new Callable<Void>() { public Void call() throws Exception { RuntimeExceptionDao<Message, Object> messageDao = app.getDao(Message.class); for (Message m : messages) { Person person = Person.getOrUpdate(app, m.getSenderEmail(), m.getSenderFullName(), m.getAvatarUrl()); m.setSender(person); Stream stream = Stream.getByName(app, m.getRecipients()); m.setStream(stream); messageDao.createOrUpdate(m); } return null; } }); } catch (SQLException e) { throw new RuntimeException(e); } }

Target:
public static void createMessages(final ZulipApp app, final List<Message> messages) { try { TransactionManager.callInTransaction(app.getDatabaseHelper() .getConnectionSource(), new Callable<Void>() { public Void call() throws Exception { RuntimeExceptionDao<Message, Object> messageDao = app.getDao(Message.class); for (Message m : messages) { Person person = Person.getOrUpdate(app, m.getSenderEmail(), m.getSenderFullName(), m.getAvatarUrl()); m.setSender(person); Stream stream = null; if (m.getType() == MessageType.STREAM_MESSAGE) { stream = Stream.getByName(app, m.getRecipients()); } m.setStream(stream); messageDao.createOrUpdate(m); } return null; } }); } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
public static void parseQuestion(FormEntryPrompt prompt, JSONObject questionJson) { parseCaption(prompt, questionJson); questionJson.put("help", jsonNullIfNull(prompt.getHelpText())); questionJson.put("binding", jsonNullIfNull(prompt.getQuestion().getBind().getReference().toString())); questionJson.put("style", jsonNullIfNull(parseStyle(prompt))); questionJson.put("datatype", jsonNullIfNull(parseControlType(prompt))); questionJson.put("required", prompt.isRequired() ? 1 : 0); try { parseQuestionAnswer(questionJson, prompt); } catch (Exception e) { e.printStackTrace(); } questionJson.put("ix", jsonNullIfNull(prompt.getIndex())); if (prompt.getDataType() == Constants.DATATYPE_CHOICE || prompt.getDataType() == Constants.DATATYPE_CHOICE_LIST) { questionJson.put("choices", parseSelect(prompt)); } }

Target:
public static void parseQuestion(FormEntryPrompt prompt, JSONObject questionJson) { parseCaption(prompt, questionJson); questionJson.put("help", jsonNullIfNull(prompt.getHelpText())); questionJson.put("binding", jsonNullIfNull(prompt.getQuestion().getBind().getReference().toString())); questionJson.put("style", jsonNullIfNull(parseStyle(prompt))); questionJson.put("datatype", jsonNullIfNull(parseControlType(prompt))); questionJson.put("required", prompt.isRequired() ? 1 : 0); parseQuestionAnswer(questionJson, prompt); questionJson.put("ix", jsonNullIfNull(prompt.getIndex())); if (prompt.getDataType() == Constants.DATATYPE_CHOICE || prompt.getDataType() == Constants.DATATYPE_CHOICE_LIST) { questionJson.put("choices", parseSelect(prompt)); } }
Source:
private void updateDisordersFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json) { try { JSONArray inputDisorders = json.optJSONArray(JSON_KEY_DISORDERS); if (inputDisorders != null) { this.disorders = new TreeSet<Disorder>(); List<String> disorderValues = new LinkedList<String>(); for (int i = 0; i < inputDisorders.length(); i++) { JSONObject disorderJSON = inputDisorders.optJSONObject(i); if (disorderJSON == null) { continue; } Disorder phenotipsDisorder = new PhenoTipsDisorder(disorderJSON); this.disorders.add(phenotipsDisorder); disorderValues.add(phenotipsDisorder.getValue()); } this.disorders = Collections.unmodifiableSet(this.disorders); data.set(DISORDER_PROPERTIES_OMIMID, null, context); data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context); context.getWiki().saveDocument(doc, "Updated disorders from JSON", true, context); } } catch (Exception ex) { this.logger.warn("Failed to update patient disorders from JSON [{}]: {}", ex.getMessage(), ex); } }

Target:
private void updateDisordersFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json) { try { if (!json.has(JSON_KEY_DISORDERS)) { return; } JSONArray inputDisorders = json.optJSONArray(JSON_KEY_DISORDERS); if (inputDisorders != null) { this.disorders = new TreeSet<Disorder>(); List<String> disorderValues = new LinkedList<String>(); for (int i = 0; i < inputDisorders.length(); i++) { JSONObject disorderJSON = inputDisorders.optJSONObject(i); if (disorderJSON == null) { continue; } Disorder phenotipsDisorder = new PhenoTipsDisorder(disorderJSON); this.disorders.add(phenotipsDisorder); disorderValues.add(phenotipsDisorder.getValue()); } this.disorders = Collections.unmodifiableSet(this.disorders); data.set(DISORDER_PROPERTIES_OMIMID, null, context); data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context); context.getWiki().saveDocument(doc, "Updated disorders from JSON", true, context); } } catch (Exception ex) { this.logger.warn("Failed to update patient disorders from JSON [{}]: {}", ex.getMessage(), ex); } }
Source:
private final void visit(ProjectState st, Set<Project.NameKey> seen) { if (st == null) { order.add(allProjectsName); return; } Project pr = st.getProject(); if (pr == null) return; order.add(pr.getNameKey()); if (!seen.add(pr.getNameKey())) return; List<Project.NameKey> parents = pr.getParents(); if (parents == null || parents.size() < 1) { order.add(allProjectsName); return; } for (Project.NameKey parentKey : pr.getParents()) visit(cache.get(parentKey), seen); }

Target:
private final void visit(ProjectState st, Set<Project.NameKey> seen) { if (st == null) { order.add(allProjectsName); return; } Project pr = st.getProject(); if (pr == null) { return; } order.add(pr.getNameKey()); if (!seen.add(pr.getNameKey())) { return; } List<Project.NameKey> parents = pr.getParents(); if (parents == null || parents.size() < 1) { order.add(allProjectsName); return; } for (Project.NameKey parentKey : pr.getParents()) { visit(cache.get(parentKey), seen); } }
Source:
private static boolean getExecutablePermission(int permission) { return permission % 2 == 1; }

Target:
private static boolean getExecutablePermission(int permission) { return (permission & 1) == 1; }
Source:
private Directory loadInstance(File file) { Properties configuration = new Properties(); InputStream in = null; try { in = new FileInputStream(file); configuration.load(in); } catch (IOException exception) { log.error( "Can't load directory configuration file \"" + file.getAbsolutePath() + "\".", exception ); return null; } finally { if (in != null) { try { in.close(); } catch (IOException exception) { log.warn( "Can't close directory configuration file \"" + file.getAbsolutePath() + "\".", exception ); } } } return loadInstance(file, configuration); }

Target:
private Directory loadInstance(File file) { Properties configuration = new Properties(); try (InputStream in = new FileInputStream(file)) { configuration.load(in); } catch (IOException exception) { log.error( "Can't load directory configuration file \"" + file.getAbsolutePath() + "\".", exception ); return null; } return loadInstance(file, configuration); }
Source:
protected void handleGenericException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException { sendErrorResponse(request, response, ex, "An Exception has occured", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); }

Target:
protected void handleGenericException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException { ResponseStatus responseStatusAnnotation = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); int returnCode = 0; if (responseStatusAnnotation != null) { returnCode = responseStatusAnnotation.code().value(); } else { returnCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } sendErrorResponse(request, response, ex, "An Exception has occured", returnCode); }
Source:
public void onBackPressed() { if (getFragment().onBackPressed()) { return; } WikipediaApp.getInstance().getApplicationContext().startService(AnalyticsIntentService.getIntent(EventLoggingConfig.EXIT_PUSH)); finish(); }

Target:
public void onBackPressed() { if (getFragment().onBackPressed()) { return; } finish(); }
Source:
public void clickEnableMinRankOptions(int questionNumber) { WebElement minNumberOfOptionsToRankCheckbox = getMinOptionsToBeRankedCheckbox(questionNumber); waitForPageToScroll(); minNumberOfOptionsToRankCheckbox.click(); }

Target:
public void clickEnableMinRankOptions(int questionNumber) { WebElement minNumberOfOptionsToRankCheckbox = getMinOptionsToBeRankedCheckbox(questionNumber); minNumberOfOptionsToRankCheckbox.click(); }
Source:
private static void assertMethodSource(Method expectedMethod, TestDescriptor testDescriptor) { assertThat(testDescriptor.getSource()).containsInstanceOf(JavaMethodSource.class); JavaMethodSource methodSource = (JavaMethodSource) testDescriptor.getSource().get(); assertThat(methodSource.getMethodName()).isEqualTo(expectedMethod.getName()); assertThat(methodSource.getMethodParameterTypes()).isEqualTo( StringUtils.nullSafeToString(expectedMethod.getParameterTypes())); }

Target:
private static void assertMethodSource(Method expectedMethod, TestDescriptor testDescriptor) { assertThat(testDescriptor.getSource()).containsInstanceOf(JavaMethodSource.class); JavaMethodSource methodSource = (JavaMethodSource) testDescriptor.getSource().get(); assertThat(methodSource.getClassName()).isEqualTo(expectedMethod.getDeclaringClass().getName()); assertThat(methodSource.getMethodName()).isEqualTo(expectedMethod.getName()); assertThat(methodSource.getMethodParameterTypes()).isEqualTo( StringUtils.nullSafeToString(expectedMethod.getParameterTypes())); }
Source:
public void excecuteCommand() throws MojoExecutionException, MojoFailureException { kieServerGateway.deploy(project, container); }

Target:
public void excecuteCommand() throws MojoExecutionException, MojoFailureException { RuntimeStrategy strategy; try { strategy = RuntimeStrategy.valueOf(runtimeStrategy); } catch (IllegalArgumentException ex) { throw new MojoFailureException("Runtime Strategy Not Found: " + runtimeStrategy); } getLog().info("Runtime Strategy: " + runtimeStrategy); kieServerGateway.deploy(project, container, strategy); }
Source:
private Map<String, VersionNumber> difference(Map<String, VersionNumber> base, Map<String, VersionNumber> toAdd) { for (Map.Entry<String,VersionNumber> adding : toAdd.entrySet()) { if (!base.containsKey(adding.getKey())) { base.put(adding.getKey(), adding.getValue()); } } return base; }

Target:
private Map<String, VersionNumber> difference(Map<String, VersionNumber> base, Map<String, VersionNumber> toAdd) { Map<String, VersionNumber> diff = new HashMap<String, VersionNumber>(); for (Map.Entry<String,VersionNumber> adding : toAdd.entrySet()) { if (!base.containsKey(adding.getKey())) { diff.put(adding.getKey(), adding.getValue()); } } return diff; }
Source:
public AttributeDescriptor getAttributeDescriptor(String attributeName) { if (attributeName == null) { return null; } if (descriptors.size() != descriptorNameMap.size()) { descriptorNameMap.clear(); for (AttributeDescriptor descriptor : descriptors) { descriptorNameMap.put(descriptor.getName(), descriptor); } } return descriptorNameMap.get(attributeName); }

Target:
public AttributeDescriptor getAttributeDescriptor(String attributeName) { if (attributeName == null) { return null; } return descriptors.get(attributeName); }
Source:
private void checkMultipleSubnetsCombinedWithUseData(Network network){ if (_ntwkOfferingSrvcDao.listServicesForNetworkOffering(network.getNetworkOfferingId()).contains(Network.Service.UserData.getName()) && _vlanDao.listVlansByNetworkId(network.getId()).size() > 1) { List<VlanVO> vlanVOs = _vlanDao.listVlansByNetworkId(network.getId()); for(VlanVO vlanVoItem : vlanVOs){ for(VlanVO VlanVoItem2 : vlanVOs){ if(!vlanVoItem.equals(VlanVoItem2) && !VlanVoItem2.getVlanGateway().equals(vlanVoItem.getVlanGateway())){ s_logger.error("NuageVsp provider does not support multiple subnets in combination with user data."); throw new UnsupportedServiceException("NuageVsp provider does not support multiple subnets in combination with user data."); } } } } }

Target:
private void checkMultipleSubnetsCombinedWithUseData(Network network) { if (_ntwkOfferingSrvcDao.listServicesForNetworkOffering(network.getNetworkOfferingId()).contains(Network.Service.UserData.getName())) { List<VlanVO> vlanVOs = _vlanDao.listVlansByNetworkId(network.getId()); if (vlanVOs.size() > 1) { VlanVO vlanVoItem = vlanVOs.get(0); for (VlanVO VlanVoItem2 : FluentIterable.from(vlanVOs).skip(1)) { if (!vlanVoItem.equals(VlanVoItem2) && !VlanVoItem2.getVlanGateway().equals(vlanVoItem.getVlanGateway())) { s_logger.error("NuageVsp provider does not support multiple subnets in combination with user data. Network: " + network + ", vlans: " + vlanVOs); throw new UnsupportedServiceException("NuageVsp provider does not support multiple subnets in combination with user data."); } } } } }
Source:
protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { LOGGER.debug( "Loading verifier web worker" ); try { final String requestURI = request.getRequestURI(); final int indexOf = requestURI.indexOf( "/verifier" ); if ( indexOf >= 0 ) { final String fileName = requestURI.substring( indexOf ); if ( fileName.endsWith( "cache.js" ) ) { final byte[] bytes = loadResource( fileName ).getBytes(); response.setHeader( "Content-Disposition", format( "attachment; filename=\"%s\";", requestURI ) ); response.setContentType( "application/javascript" ); response.getOutputStream() .write( bytes, 0, bytes.length ); } } } catch ( final Exception e ) { LOGGER.error( "Failed to load verifier web worker." ); } }

Target:
protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { LOGGER.debug( "Loading verifier web worker" ); try { final String requestURI = request.getRequestURI(); final int indexOf = requestURI.indexOf( "/verifier" ); if ( indexOf >= 0 ) { final String fileName = requestURI.substring( indexOf ); if ( fileName.endsWith( "cache.js" ) ) { final byte[] bytes = loadResource( fileName ).getBytes(); response.setContentType( "application/javascript" ); response.getOutputStream() .write( bytes, 0, bytes.length ); } } } catch ( final Exception e ) { LOGGER.error( "Failed to load verifier web worker." ); } }
Source:
public AllowUsingTool(String name, Domain domain, IngredientRecipe ingredient) { super(name, domain, new String[] {AgentFactory.ClassName, ToolFactory.ClassName, ContainerFactory.ClassName} ,ingredient); this.recipe = null; }

Target:
public AllowUsingTool(String name, Domain domain, IngredientRecipe ingredient) { super(name, domain, new String[] {AgentFactory.ClassName, ToolFactory.ClassName, ContainerFactory.ClassName} ,ingredient); }
Source:
public String eval(NetworkAttachment networkAttachment) { final String networkName = networkAttachment.getNetworkName(); return StringUtils.isEmpty(networkName) ? networkAttachment.getId().toString() : networkName; }

Target:
public String eval(NetworkAttachment networkAttachment) { final String networkName = networkAttachment.getNetworkName(); if (!StringUtils.isEmpty(networkName)) { return networkName; } final Guid networkId = networkAttachment.getNetworkId(); return networkId == null ? null : networkId.toString(); }
Source:
public void testCacheDecreasesAfterGC() { generateJunkCacheEntries(); Long initialSize = Namespace.ID.cache.asMap().entrySet().stream().count(); Long postGCSize; System.out.println("Namespace.ID.cache.asMap().entrySet().stream().count() = " + initialSize); do { System.gc(); try { Thread.sleep(5000); } catch (InterruptedException e) { fail("Thread interrupted while waiting for GC"); } postGCSize = Namespace.ID.cache.asMap().entrySet().stream().count(); System.out.println("After GC: Namespace.ID.cache.asMap().entrySet().stream().count() = " + postGCSize); } while (postGCSize == initialSize); assertTrue("Cache did not decrease with GC.", Namespace.ID.cache.asMap().entrySet().stream().count() < initialSize); }

Target:
public void testCacheDecreasesAfterGC() { Long initialSize = Namespace.ID.cache.asMap().entrySet().stream().count(); generateJunkCacheEntries(); Long postGCSize; do { System.gc(); try { Thread.sleep(500); } catch (InterruptedException e) { fail("Thread interrupted while waiting for GC"); } postGCSize = Namespace.ID.cache.asMap().entrySet().stream().count(); } while (postGCSize > initialSize); assertTrue("Cache did not decrease with GC.", Namespace.ID.cache.asMap().entrySet().stream().count() < initialSize); }
Source:
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.isAssignableFrom(SingleResultView.class) || type.isAssignableFrom(ListResultView.class); }

Target:
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return SingleResultView.class.isAssignableFrom(type) || ListResultView.class.isAssignableFrom(type); }
Source:
public String getText(final Object element) { String text = "<UNKNOWN>"; if (element instanceof RefactorScope) { text = element.toString(); } return text; }

Target:
public String getText(final Object element) { String text = "<UNKNOWN>"; if (element instanceof RefactorScope) { text = ((RefactorScope) element).getName(); } return text; }
Source:
public IdentityHashPartitionFunction( @JsonProperty(value = "index", required = true) final Integer index) { super(null); this.index = java.util.Objects.requireNonNull(index, "missing property index"); Preconditions.checkArgument(this.index >= 0, "IdentityHash field index cannot take negative value %s", this.index); }

Target:
public IdentityHashPartitionFunction( @JsonProperty(value = "index", required = true) final Integer index) { super(null); this.index = Objects.requireNonNull(index, "missing property index"); Preconditions.checkArgument(this.index >= 0, "IdentityHash field index cannot take negative value %s", this.index); }
Source:
public boolean checkCode(String name, String code) { String savedCode = captchaCodes.get(name.toLowerCase()); if (savedCode != null && savedCode.equalsIgnoreCase(code)) { captchaCodes.remove(name); return true; } else { generateCode(name); } return false; }

Target:
public boolean checkCode(String name, String code) { String lowerCaseName = name.toLowerCase(); String savedCode = captchaCodes.get(lowerCaseName); if (savedCode != null && savedCode.equalsIgnoreCase(code)) { captchaCodes.remove(lowerCaseName); return true; } else { generateCode(name); } return false; }
Source:
public Object[][] sortBundles(BundleDescription[] toSort) { List<Object[]> references = new ArrayList<>(toSort.length); for (BundleDescription toSort1 : toSort) { if (toSort1.isResolved()) { buildReferences(toSort1, references); } } Object[][] cycles = ComputeNodeOrder.computeNodeOrder(toSort, references.toArray(new Object[references.size()][])); if (cycles.length == 0) return cycles; for (Object[] cycle : cycles) { for (Object c : cycle) { BundleDescription fragment = (BundleDescription) c; if (fragment.getHost() == null) continue; BundleDescription host = (BundleDescription) fragment.getHost().getSupplier(); if (host == null) continue; fixFragmentOrder(host, fragment, toSort); } } return cycles; }

Target:
public Object[][] sortBundles(BundleDescription[] toSort) { List<Object[]> references = new ArrayList<>(toSort.length); for (BundleDescription toAddReference : toSort) { if (toAddReference.isResolved()) { buildReferences(toAddReference, references); } } Object[][] cycles = ComputeNodeOrder.computeNodeOrder(toSort, references.toArray(new Object[references.size()][])); if (cycles.length == 0) return cycles; for (Object[] cycle : cycles) { for (Object possibleFragment : cycle) { BundleDescription fragment = (BundleDescription) possibleFragment; if (fragment.getHost() == null) continue; BundleDescription host = (BundleDescription) fragment.getHost().getSupplier(); if (host == null) continue; fixFragmentOrder(host, fragment, toSort); } } return cycles; }
Source:
private String _evtGetExtendedStatus(String query) { EVT_HANDLE handle = null; String result; try { handle = Wevtapi.INSTANCE.EvtQuery(null, "Application", query, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath); result = WevtapiUtil.EvtGetExtendedStatus(); } finally { if (handle != null) { Wevtapi.INSTANCE.EvtClose(handle); } } System.out.println(result); return result; }

Target:
private String _evtGetExtendedStatus(String query) { EVT_HANDLE handle = null; String result; try { handle = Wevtapi.INSTANCE.EvtQuery(null, "Application", query, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath); result = WevtapiUtil.EvtGetExtendedStatus(); } finally { if (handle != null) { Wevtapi.INSTANCE.EvtClose(handle); } } return result; }
Source:
public void contextDestroyed(ServletContextEvent event) { if (storage != null) { storage.close(); logger.debug("Template storage closed successfully", storage); } healthCheck.stop(); executorService.shutdown(); }

Target:
public void contextDestroyed(ServletContextEvent event) { if (storage != null) { storage.close(); logger.debug("Template storage closed successfully", storage); } healthCheck.stop(); executorService.shutdownNow(); }
Source:
private GetSpecificAttributeValueResponse getSpecificAttributeValues(final Map<String, String> settings) throws WebServiceSecurityException, GeneralSecurityException, IOException { final GetSpecificAttributeValueRequest request = new GetSpecificAttributeValueRequest(); request.setClassId(BigInteger.valueOf(40L)); request.setObisCode(this.getObisCodeValues()); request.setAttribute(BigInteger.valueOf(3L)); request.setDeviceIdentification(settings.get(PlatformSmartmeteringKeys.KEY_DEVICE_IDENTIFICATION)); GetSpecificAttributeValueAsyncResponse asyncResponse; asyncResponse = this.adHocRequestclient.doRequest(request); final GetSpecificAttributeValueAsyncRequest asyncRequest = new GetSpecificAttributeValueAsyncRequest(); asyncRequest.setDeviceIdentification(asyncResponse.getDeviceIdentification()); asyncRequest.setCorrelationUid(asyncResponse.getCorrelationUid()); return this.adHocResponseClient.getResponse(asyncRequest); }

Target:
private GetSpecificAttributeValueResponse getSpecificAttributeValues(final Map<String, String> settings) throws WebServiceSecurityException, GeneralSecurityException, IOException { final GetSpecificAttributeValueRequest request = new GetSpecificAttributeValueRequest(); request.setClassId(BigInteger.valueOf(40L)); request.setObisCode(this.getObisCodeValues()); request.setAttribute(BigInteger.valueOf(3L)); request.setDeviceIdentification(settings.get(PlatformSmartmeteringKeys.KEY_DEVICE_IDENTIFICATION)); final GetSpecificAttributeValueAsyncResponse asyncResponse = this.adHocRequestclient.doRequest(request); final GetSpecificAttributeValueAsyncRequest asyncRequest = new GetSpecificAttributeValueAsyncRequest(); asyncRequest.setDeviceIdentification(asyncResponse.getDeviceIdentification()); asyncRequest.setCorrelationUid(asyncResponse.getCorrelationUid()); return this.adHocResponseClient.getResponse(asyncRequest); }
Source:
public void releaseTaskManager(ResourceID resourceId) { try { supplyInMainThreadExecutor(() -> slotPool.releaseTaskManager(resourceId, new Exception("Test Exception"))); } catch (Exception e) { throw new RuntimeException("Should not have happened.", e); } }

Target:
public void releaseTaskManager(ResourceID resourceId) { try { supplyInMainThreadExecutor( () -> slotPool.releaseTaskManager( resourceId, new Exception("Releasing TaskManager in SlotPool for tests"))); } catch (Exception e) { throw new RuntimeException("Should not have happened.", e); } }
Source:
protected MessageGroupPreparedStatementSetter() { this.serializer = new SerializingConverter(); this.lobHandler = new DefaultLobHandler(); }

Target:
protected MessageGroupPreparedStatementSetter() { this.serializer = null; this.lobHandler = null; }
Source:
public <T> void reconcile(final String key, final long record, final T... values) { reconcile(key, record, Lists.newArrayList(values)); }

Target:
public <T> void reconcile(final String key, final long record, final T... values) { reconcile(key, record, Sets.newHashSet(values)); }
Source:
public Map<SubpopulationGuid, ConsentStatus> withdrawAllConsents(Study study, StudyParticipant participant, CriteriaContext context, Withdrawal withdrawal, long withdrewOn) { checkNotNull(study); checkNotNull(context); checkNotNull(withdrawal); checkArgument(withdrewOn > 0); Account account = accountDao.getAccount(context.getAccountId()); for (SubpopulationGuid subpopGuid : account.getAllConsentSignatureHistories().keySet()) { withdrawSignatures(account, subpopGuid, withdrewOn); } account.setSharingScope(SharingScope.NO_SHARING); accountDao.updateAccount(account, false); for (SubpopulationGuid subpopGuid : account.getAllConsentSignatureHistories().keySet()) { Subpopulation subpop = subpopService.getSubpopulation(study.getStudyIdentifier(), subpopGuid); if (!subpop.isAutoSendConsentSuppressed()) { sendWithdrawEmail(study, participant.getExternalId(), account, withdrawal, withdrewOn); } } return getConsentStatuses(context, account); }

Target:
public Map<SubpopulationGuid, ConsentStatus> withdrawAllConsents(Study study, StudyParticipant participant, CriteriaContext context, Withdrawal withdrawal, long withdrewOn) { checkNotNull(study); checkNotNull(context); checkNotNull(withdrawal); checkArgument(withdrewOn > 0); Account account = accountDao.getAccount(context.getAccountId()); for (SubpopulationGuid subpopGuid : account.getAllConsentSignatureHistories().keySet()) { withdrawSignatures(account, subpopGuid, withdrewOn); } account.setSharingScope(SharingScope.NO_SHARING); accountDao.updateAccount(account, false); sendWithdrawEmail(study, participant.getExternalId(), account, withdrawal, withdrewOn); return getConsentStatuses(context, account); }
Source:
protected Void execute0(StatsCmd command, ResultCallback<Statistics> resultCallback) { WebTarget webTarget = getBaseResource().path("/containers/{id}/stats").resolveTemplate("id", command.getContainerId()); if (isTrue(command.getNoStream())) { webTarget = webTarget.queryParam("stream", "0"); } LOGGER.trace("GET: {}", webTarget); webTarget.request().get(new TypeReference<Statistics>() { }, resultCallback); return null; }

Target:
protected Void execute0(StatsCmd command, ResultCallback<Statistics> resultCallback) { WebTarget webTarget = getBaseResource().path("/containers/{id}/stats").resolveTemplate("id", command.getContainerId()); if (Boolean.TRUE.equals(command.hasNoStream())) { webTarget = webTarget.queryParam("stream", "0"); } LOGGER.trace("GET: {}", webTarget); webTarget.request().get(new TypeReference<Statistics>() { }, resultCallback); return null; }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permissionCheckSubjects == null) { permissionCheckSubjects = new ArrayList<PermissionSubject>(); permissionCheckSubjects.addAll(super.getPermissionCheckSubjects()); permissionCheckSubjects.add(new PermissionSubject( getParameters().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); } return permissionCheckSubjects; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); }
Source:
protected void removeUnits(final IDelegateBridge bridge, final Predicate<Unit> unitMatch) { final Collection<Unit> deadAttackers = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.OFFENSE), unitMatch.and(Matches.unitIsSuicideOnAttack())); final Collection<Unit> deadDefenders = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.DEFENSE), unitMatch.and(Matches.unitIsSuicideOnDefense())); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getAttacker(), deadAttackers, getDependents(deadAttackers)); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getDefender(), deadDefenders, getDependents(deadDefenders)); final List<Unit> deadUnits = new ArrayList<>(deadAttackers); deadUnits.addAll(deadDefenders); battleActions.remove(deadUnits, bridge, battleState.getBattleSite(), null); }

Target:
protected void removeUnits(final IDelegateBridge bridge, final Predicate<Unit> unitMatch) { final Collection<Unit> suicideAttackers = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.OFFENSE), unitMatch.and(Matches.unitIsSuicideOnAttack())); final Collection<Unit> suicideDefenders = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.DEFENSE), unitMatch.and(Matches.unitIsSuicideOnDefense())); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getAttacker(), suicideAttackers, getDependents(suicideAttackers)); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getDefender(), suicideDefenders, getDependents(suicideDefenders)); final List<Unit> deadUnits = new ArrayList<>(suicideAttackers); deadUnits.addAll(suicideDefenders); battleActions.remove(deadUnits, bridge, battleState.getBattleSite(), null); }