List<Unit> allTopUnits = unit.getTopUnits(); if (!allTopUnits.isEmpty()) { for (Unit topUnit : allTopUnits) { if (topUnit.getType() != null && topUnit.getType().equals(UnitType.DEPARTMENT) && topUnit.getDepartment() != null && (!onlyActiveEmployees || topUnit.getDepartment() .getCurrentActiveWorkingEmployees().contains(this))) { return topUnit.getDepartment();
List<Unit> parentUnits = unit.getParentUnits(); if (!parentUnits.isEmpty()) { for (Unit parentUnit : parentUnits) { if (unitDepartment(parentUnit, onlyActiveEmployees)) { return parentUnit.getDepartment(); } else if (parentUnit.hasAnyParentUnits()) { Department department = getEmployeeUnitDepartment(parentUnit, onlyActiveEmployees); if (department != null) { return department; }
    private Department getEmployeeUnitDepartment(Unit unit, boolean onlyActiveEmployees) {        List<Unit> allTopUnits = unit.getTopUnits();        if (!allTopUnits.isEmpty()) {            for (Unit topUnit : allTopUnits) {                if (topUnit.getType() != null                        && topUnit.getType().equals(UnitType.DEPARTMENT)                        && topUnit.getDepartment() != null                        && (!onlyActiveEmployees || topUnit.getDepartment()                                .getCurrentActiveWorkingEmployees().contains(this))) {                    return topUnit.getDepartment();                }            }        } else if (unit.getType() != null && unit.getType().equals(UnitType.DEPARTMENT)) {            return unit.getDepartment();        }        return null;    }