text:
static const int windowSizeX = 650;
static const int windowSizeY = 300;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), isChanged(false), isClosing(false)
{
    try
    {
        settings = std::make_shared<Settings>();
        settings->load();
        notes = std::make_shared<Notebook>(settings);
    }
    catch(std::exception& e)
    {
        QMessageBox::critical(parent, "MainWindow::MainWindow", e.what());
    }
    this->setUI();
    showTrayMessage();
}

void MainWindow::openEditWindow(Note * const note)
{
    EditWindow *window = new EditWindow(settings);
    window->setWindowFlags(window->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
    window->setWindowModality(Qt::ApplicationModal);
    window->setAttribute(Qt::WA_DeleteOnClose);
    connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(addNote(Note*const)));
    connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(showNotes()));
    connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(showClosestNote()));
    connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(switchButtons()));
    connect(window, SIGNAL(noteEdited()), this, SIGNAL(noteEdited()));
    connect(window, SIGNAL(noteEdited()), this, SLOT(showNotes()));
    connect(window, SIGNAL(noteEdited()), this, SLOT(showClosestNote()));
    connect(window, SIGNAL(noteEdited()), this, SLOT(setChanged()));
    const QDate d = cal->selectedDate();
    if(QObject::sender() == addButton)
    {
        window->loadNotes(d, nullptr);
    }
    else if(QObject::sender() == editButton)
    {
        window->loadNotes(d, notes->getNotesFromDate(d));
    }
    else //Edit button in NoteListWindow
    {
        window->loadNote(note);
    }
    window->show();
    moveToCenter(window);
    cal->setFocus();
}

void MainWindow::setUI()
{
    mainLayout = new QHBoxLayout;
    leftLayout = new QVBoxLayout;

    this->createMenu();
    this->createStatusBar();
    this->createCalendar();
    this->createButtonLayout();
    this->createTrayIcon();
    this->createScrollArea();
    this->setWindowTitle("Note Keeper");

    noteTextTitle = new QLabel("No notes on "+cal->selectedDate().toString(settings->dateFormat));

    leftLayout->addWidget(cal);
    leftLayout->addWidget(noteTextTitle);
    leftLayout->addWidget(scrollArea);

    mainLayout->addLayout(leftLayout);
    mainLayout->addLayout(buttonsLayout);

    QWidget *window = new QWidget;
    window->setLayout(mainLayout);
    this->setCentralWidget(window);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->setFixedSize(this->size());
    this->setWindowFlags(this->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
    MainWindow::moveToCenter(this);
    this->setMinimumSize(windowSizeX,windowSizeY);
    this->setMaximumSize(windowSizeX,windowSizeY*2);
    this->setStyleSheet("QStatusBar::item { border: 0px solid black }; ");
    this->switchButtons();
    this->showNotes();
    this->showClosestNote();
    this->setWindowIcon(QIcon(":/images/icon"));
    connect(this, SIGNAL(noteDeleted()), this, SLOT(switchButtons()));
}

void MainWindow::createMenu()
{
    QMenuBar *menu = this->menuBar();
    QMenu *fileMenu = menu->addMenu("File");
    QMenu *helpMenu = menu->addMenu("Help");

    QList<QAction *> fileActions;
    fileActions.append(new QAction("Save",this));
    fileActions.back()->setShortcut(Qt::CTRL | Qt::Key_S);
    fileActions.append(new QAction("Show all notes...",this));
    fileActions.append(new QAction("Delete outdated notes",this));
    fileActions.append(new QAction("Delete all notes",this));
    QAction *settings = new QAction("Settings...", this);

    connect(fileActions.front(), SIGNAL(triggered()), this, SLOT(saveNotes()));
    connect(fileActions.at(1), SIGNAL(triggered()), this, SLOT(openAllNotesWindow()));
    connect(fileActions.at(2), SIGNAL(triggered()), this, SLOT(deleteOutdated()));
    connect(fileActions.at(3), SIGNAL(triggered()), this, SLOT(deleteAll()));
    connect(settings, SIGNAL(triggered()), this, SLOT(openSettingsWindow()));

    fileMenu->addActions(fileActions);
    fileMenu->addSeparator();
    fileMenu->addAction(settings);

    QAction *aboutAction = new QAction("About...",this);
    helpMenu->addAction(aboutAction);

    connect(aboutAction, SIGNAL(triggered()), this, SLOT(openAboutWindow()));

    connect(this, SIGNAL(noteDeleted()), this, SLOT(showClosestNote()));

    menu->show();
}

void MainWindow::createStatusBar()
{
    QStatusBar *sBar = this->statusBar();
    statusLabel = new QLabel("No noted dates in the future.");
    sBar->setSizeGripEnabled(false);
    sBar->addWidget(statusLabel);
    sBar->setSizeGripEnabled(false);
}

void MainWindow::createTrayIcon()
{
    notificationsAction = new QAction("Show today's notifications", this);
    openAction = new QAction("Open Note Keeper", this);
    quitAction = new QAction("Exit", this);

    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(notificationsAction);
    trayIconMenu->addAction(openAction);
    trayIconMenu->addAction(quitAction);

    connect(notificationsAction, SIGNAL(triggered()), this, SLOT(showTrayMessage()));
    connect(openAction, SIGNAL(triggered()), this, SLOT(showFromTray()));
    openAction->setEnabled(false);
    connect(quitAction, SIGNAL(triggered()), this, SLOT(closeProgram()));

    trayIcon = new QSystemTrayIcon(this);
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setToolTip("Note Keeper");

    trayTimer = new QTimer(this);
    trayTimer->setInterval(10000);
    trayTimer->setSingleShot(true);
    connect(trayTimer, SIGNAL(timeout()), this, SLOT(showTrayMessage()));
    connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(showTrayMessage()));

    trayIcon->setIcon(QIcon(":/images/icon"));
    trayIcon->show();
}

void MainWindow::createButtonLayout()
{
    buttonsLayout = new QVBoxLayout();
    addButton = new QPushButton("Add note");
    editButton = new QPushButton("Edit note");
    removeButton = new QPushButton("Delete note");
    todayButton = new QPushButton("Go to current date");
    quitButton = new QPushButton("Close");

    connect(addButton, SIGNAL(clicked()), this, SLOT(openEditWindow()));
    connect(editButton, SIGNAL(clicked()), this, SLOT(openEditWindow()));
    connect(removeButton, SIGNAL(clicked()), this, SLOT(openDeleteDialogue()));
    connect(todayButton, SIGNAL(clicked()), cal, SLOT(showToday()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

    buttonsLayout->addWidget(addButton);
    buttonsLayout->addWidget(editButton);
    buttonsLayout->addWidget(removeButton);
    buttonsLayout->addWidget(todayButton);
    buttonsLayout->addWidget(quitButton);
    buttonsLayout->setAlignment(Qt::AlignTop);
}

void MainWindow::createScrollArea()
{
    scrollArea = new QScrollArea;
    QWidget *scrollWidget = new QWidget;
    scrollLayout = new QVBoxLayout;
    scrollLayout->setMargin(5);
    scrollLayout->setAlignment(Qt::AlignTop);
    scrollWidget->setLayout(scrollLayout);
    scrollArea->setWidget(scrollWidget);
    scrollArea->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    scrollArea->setFixedWidth(cal->minimumWidth());
    scrollArea->setMaximumHeight(500);
    scrollArea->setMinimumHeight(0);
    scrollArea->setFixedHeight(200);
    scrollArea->setWidgetResizable(true);
    scrollArea->hide();
}

void MainWindow::createCalendar()
{
    cal = new Calendar(notes, settings);
    cal->setMinimumSize(500, 250);
    cal->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    connect(cal, SIGNAL(selectionChanged()), this, SLOT(switchButtons()));
    connect(cal, SIGNAL(selectionChanged()), this, SLOT(showNotes()));

}

void MainWindow::moveToCenter(QWidget * const window)
{
    QDesktopWidget *d = QApplication::desktop();
    int ww = window->width();
    int wh = window->height();
    int dw = d->width();
    int dh = d->height();
    window->move(dw/2 - ww/2, dh/2 - wh/2);
}

void MainWindow::addNote(Note * const note)
{
    notes->addNote(note);
    isChanged = true;
}

void MainWindow::showNotes()
{
    const QDate d = cal->selectedDate();
    scrollArea->hide();
    auto notesList = notes->getNotesFromDate(d);
    const int notesCount = notesList->size();
    int labelsSize = noteLabels.size();
    if(notesCount != 0)
    {
        noteTextTitle->setText(d.toString(settings->dateFormat) + ": ("+QString::number(notesCount)+")");
        while(notesCount > labelsSize)
        {
            addNoteLabel();
            ++labelsSize;
        }
        for(int i = 0; i < labelsSize; i++)
        {
            if(i < notesCount)
            {
                noteLabels[i]->setText(notesList->at(i)->text);
                noteLabels[i]->setEnabled(true);
                noteLabels[i]->show();
            }
            else
            {
                noteLabels[i]->setEnabled(false);
                noteLabels[i]->hide();
            }
        }
    }
    else
    {
        noteTextTitle->setText("No notes on "+d.toString(settings->dateFormat));
    }
    cal->setFocus();
    resizeTimer();
}

void MainWindow::addNoteLabel()
{
    QLabel *label = new QLabel;
    label->setFrameShape(QFrame::StyledPanel);
    label->setContentsMargins(2, 0, 0, 2);
    label->setMargin(5);
    scrollLayout->addWidget(label);
    noteLabels.append(label);
}

void MainWindow::switchButtons()
{
    if(notes->contains(cal->selectedDate()))
    {
        editButton->show();
        removeButton->show();
    }
    else
    {
        editButton->hide();
        removeButton->hide();
    }
}

void MainWindow::resizeMe()
{
    if(noteTextTitle->text().left(8) != "No notes")
    {
        int scrollAreaHeight = 0;
        for(auto label : noteLabels)
        {
            if(label->isEnabled())
            {
                label->adjustSize();
                label->setFixedWidth(scrollArea->widget()->width() - scrollLayout->margin() * 2 - 20);
                scrollAreaHeight += label->frameGeometry().height() + label->margin();
            }
        }
        scrollAreaHeight += scrollLayout->margin() + 5;
        if(scrollAreaHeight > cal->minimumHeight())
        {
            scrollAreaHeight = cal->minimumHeight();
        }
        scrollArea->setFixedHeight(scrollAreaHeight);
        scrollArea->show();
    }
    this->resize(this->minimumSizeHint());
}

void MainWindow::resizeTimer()
{
    QTimer::singleShot(1, this, SLOT(resizeMe()));
}

void MainWindow::saveNotes()
{
    try
    {
        notes->saveNotes();
    }
    catch(std::exception& e)
    {
        QMessageBox::critical(this, "Notebook::saveNotes", QString::fromLocal8Bit(e.what()));
    }
    isChanged = false;
}

void MainWindow::openDeleteDialogue()
{
    auto list = std::move(notes->getNotesFromDate(cal->selectedDate()));
    if(list->size() == 1)
    {
        int i = showDeleteMessageBox(DeleteOption::One);
        if(i == QMessageBox::Yes)
        {
            deleteNote(list->first());
        }
    }
    else
    {
        DeleteDialogue *dialogue = new DeleteDialogue(std::move(list));
        dialogue->setAttribute(Qt::WA_DeleteOnClose);
        connect(dialogue, SIGNAL(deleteNotes(std::shared_ptr<QList<Note*>>)), this, SLOT(deleteNotes(std::shared_ptr<QList<Note*>>)));
        dialogue->show();
        moveToCenter(dialogue);
    }
    cal->setFocus();
}

void MainWindow::deleteNoteFromListWindow(Note * const note)
{
    if(showDeleteMessageBox(DeleteOption::One) == QMessageBox::Yes)
    {
        deleteNote(note);
    }
}

void MainWindow::deleteNote(Note * const note)
{
    notes->deleteNote(note);
    this->showNotes();
    isChanged = true;
    emit noteDeleted();
}

void MainWindow::deleteNotes(std::shared_ptr<QList<Note *>> noteList)
{
    for(auto note : *noteList)
    {
        notes->deleteNote(note);
    }
    this->showNotes();
    isChanged = true;
    emit noteDeleted();
}

void MainWindow::deleteAll()
{
    int i = showDeleteMessageBox(DeleteOption::All);
    if(i == QMessageBox::Yes)
    {
        if(notes->deleteAll() > 0)
            isChanged = true;
        this->showNotes();
        emit noteDeleted();
    }
    cal->setFocus();
}

void MainWindow::deleteOutdated()
{
    int i = showDeleteMessageBox(DeleteOption::Outdated);
    if(i == QMessageBox::Yes)
    {
        if(notes->deleteOutdated(QDate::currentDate()) > 0)
            isChanged = true;
        this->showNotes();
        emit noteDeleted();
    }
    cal->setFocus();
}

int MainWindow::showDeleteMessageBox(const DeleteOption op)
{
    QString title, text;
    switch(op)
    {
    case DeleteOption::One:
        title = "Delete note?";
        text = "Are you sure you want to delete this note?";
        break;
    case DeleteOption::Outdated:
        title = "Delete outdated notes?";
        text = "Are you sure you want to delete all outdated notes?";
        break;
    case DeleteOption::All:
        title = "Delete all notes?";
        text = "Are you sure you want to delete all notes?";
        break;
    default:
        break;
    }
    return QMessageBox::question(this, title, text, QMessageBox::Yes, QMessageBox::No);
}
int MainWindow::showExitWOSavingMessageBox()
{
    QMessageBox mb(this);
    mb.setWindowTitle("Some notes have been changed");
    mb.setText("Do you want to save your changes before quitting?");
    mb.setInformativeText("If you don't save your changes, they will be discarded.");
    mb.setIcon(QMessageBox::Warning);
    mb.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
    return mb.exec();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(isClosing)
    {
        if(isChanged)
        {
            int i = showExitWOSavingMessageBox();
            switch(i)
            {
            case QMessageBox::Yes:
                saveNotes();
                event->accept();
                qApp->quit();
                break;
            case QMessageBox::No:
                event->accept();
                qApp->quit();
                break;
            case QMessageBox::Cancel:
                isClosing = false;
                event->ignore();
                this->showFromTray();
                break;
            default:
                break;
            }
        }
        else
        {
            event->accept();
            qApp->quit();
        }
    }
    else
    {
        event->ignore();
        this->hide();
        openAction->setEnabled(true);
    }
}

void MainWindow::showClosestNote()
{
    int noteTextPieceSize = 25;
    Note *n = notes->findClosest(QDate::currentDate());
    if(n != nullptr)
    {
        QString statusText = "Closest noted date" + n->date.toString("("+settings->dateFormat+"):");
        QString noteTextTrimmed = n->text.trimmed();
        QString noteTextLine = noteTextTrimmed.section('\n',0,0);
        if(noteTextLine.size() > noteTextPieceSize || noteTextTrimmed.size() > noteTextLine.size())
        {
            statusText += noteTextLine.left(noteTextPieceSize) + "...";
        }
        else
        {
            statusText += noteTextLine;
        }
        statusLabel->setText(statusText);
    }
    else
        statusLabel->setText("No noted dates in the future.");
}

void MainWindow::closeProgram()
{
    isClosing = true;
    this->close();
}

void MainWindow::showFromTray()
{
    this->show();
    this->activateWindow();
    cal->setFocus();
    openAction->setEnabled(false);
}

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    case QSystemTrayIcon::Trigger:
        if(!this->isVisible())
        {
            this->showFromTray();
        }
        break;
    default:
        break;
    }
}

void MainWindow::showTrayMessage()
{
    static int noteIndex = -1;
    static std::unique_ptr<QList<Note*>> noteList;
    trayTimer->stop();
    if(noteIndex < 0)
    {
        noteList.reset(notes->getNotificationsFromDate(QDate::currentDate()).release());
        if(!noteList->isEmpty())
        {
            noteIndex = 0;
        }
        else
        {
            if(QObject::sender() == notificationsAction)
                trayIcon->showMessage("Note Keeper", "No notifications today", QSystemTrayIcon::Information, trayTimer->interval());
        }
    }
    if(noteIndex >= 0)
    {
        if(noteIndex < noteList->size())
        {
            Note* note = noteList->at(noteIndex);
            QString Title = note->date.toString(settings->dateFormat);
            qint64 days = QDate::currentDate().daysTo(note->date);
            switch(days)
            {
            case 0:
                Title += " (Today)    ";
                break;
            case 1:
                Title += " (in "+QString::number(days)+" day):";
                break;
            default:
                Title += " (in "+QString::number(days)+" days):";
                break;
            }
            trayIcon->showMessage(Title, note->text, QSystemTrayIcon::Information, trayTimer->interval());
            trayTimer->start();
            ++noteIndex;
        }
        else
        {
            trayIcon->hide();
            trayIcon->show();
            noteIndex = -1;
        }
    }
}

void MainWindow::openSettingsWindow()
{
    SettingsWindow *window = new SettingsWindow(settings);
    window->setWindowFlags(window->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
    window->setWindowModality(Qt::ApplicationModal);
    window->setAttribute(Qt::WA_DeleteOnClose);
    connect(window, SIGNAL(dateFormatChanged()), this, SLOT(showNotes()));
    connect(window, SIGNAL(dateFormatChanged()), this, SLOT(showClosestNote()));
    connect(window, SIGNAL(rDisplayChanged()), this, SLOT(showNotes()));
    window->loadSettings();
    window->show();
}

void MainWindow::openAboutWindow()
{
    QWidget *about = new QWidget;
    QLabel *icon = new QLabel;
    icon->setPixmap(QIcon(":/images/icon").pixmap(64,64));
    QLabel *text = new QLabel("Note Keeper ver. 1.0\n\nMade by Fedor Rebenkov");
    QFont font;
    font.setPointSize(10);
    text->setFont(font);
    QPushButton *close = new QPushButton("Close");
    QVBoxLayout *layout = new QVBoxLayout;
    QHBoxLayout *textIcon = new QHBoxLayout;
    textIcon->addWidget(icon);
    textIcon->addWidget(text);
    layout->addLayout(textIcon);
    layout->addWidget(close,0,Qt::AlignRight);
    connect(close, SIGNAL(clicked()), about, SLOT(close()));
    about->setLayout(layout);
    about->setWindowTitle("About Note Keeper");
    about->setAttribute(Qt::WA_DeleteOnClose);
    about->setWindowFlags(about->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
    about->setWindowModality(Qt::ApplicationModal);
    about->show();
    int aw = about->width();
    int ah = about->height();
    int ww = this->width();
    int wh = this->height();
    about->move(ww/2 - aw/2 + this->x(), wh/2 - ah/2 + this->y());
}

void MainWindow::openAllNotesWindow()
{
    NoteListWindow *window = new NoteListWindow(notes, settings);
    window->setAttribute(Qt::WA_DeleteOnClose);
    connect(window, SIGNAL(editNote(Note*const)), this, SLOT(openEditWindow(Note*const)));
    connect(window, SIGNAL(deleteNote(Note*const)), this, SLOT(deleteNote(Note*const)));
    connect(this, SIGNAL(noteDeleted()), window, SLOT(deleteItem()));
    connect(this, SIGNAL(noteEdited()), window, SLOT(updateItem()));
    window->show();
}

void MainWindow::setChanged()
{
    isChanged = true;
}


text:
shared_context "policy permissions" do
  subject(:policy) { described_class }

  # These have !s because they are always needed and we want them to be created first.
  let!(:cluster) { Defaults.cluster }
  let!(:community) { Defaults.community }

  let(:clusterB) { create(:cluster, name: "Other Cluster") }
  let(:communityB) { create(:community, name: "Community B") }
  let(:communityC) { create(:community, name: "Community C") }
  let(:communityX) { with_tenant(clusterB) { create(:community, name: "Community X") } }
  let(:user) { create(:user, first_name: "user") }
  let(:other_user) { create(:user, first_name: "other_user") }
  let(:user_cmtyB) { create(:user, community: communityB, first_name: "user_cmtyB") }
  let(:user_cmtyC) { create(:user, community: communityC, first_name: "user_cmtyC") }
  let(:user_cmtyX) do
    with_tenant(clusterB) { create(:user, community: communityX, first_name: "user_cmtyX") }
  end
  let(:inactive_user) { create(:user, deactivated_at: Time.current, first_name: "inactive_user") }
  let(:household) { create(:household, users: [user], community: community) }
  let(:inactive_household) do
    create(:household, users: [inactive_user],
                       deactivated_at: Time.current, community: community)
  end
  let(:account) { create(:household, community: community).accounts[0] }
  let(:guardian) { user }
  let(:child) { create(:user, :child, guardians: [guardian], first_name: "child") }
  let(:other_child) { create(:user, :child, guardians: [other_user], first_name: "other_child") }
  let(:child_cmtyB) do
    create(:user, :child, community: communityB, guardians: [user_cmtyB], first_name: "child_cmtyB")
  end
  let(:child_cmtyX) do
    with_tenant(clusterB) do
      create(:user, :child, community: communityX, guardians: [user_cmtyX], first_name: "child_cmtyX")
    end
  end
  let(:inactive_child) do
    create(:user, :child, :inactive, guardians: [inactive_user], first_name: "inactive_child")
  end
  let(:admin) { create(:admin, first_name: "admin") }
  let(:admin2) { create(:admin, first_name: "admin2") }
  let(:cluster_admin) { create(:cluster_admin, first_name: "cluster_admin") }
  let(:cluster_admin2) { create(:cluster_admin, first_name: "cluster_admin2") }
  let(:cluster_admin_cmtyB) do
    create(:cluster_admin, community: communityB, first_name: "cluster_admin_cmtyB")
  end
  let(:cluster_admin_cmtyX) do
    create(:cluster_admin, community: communityB, first_name: "cluster_admin_cmtyX")
  end
  let(:super_admin) { create(:super_admin, first_name: "super_admin") }
  let(:super_admin2) { create(:super_admin, first_name: "super_admin2") }
  let(:super_admin_cmtyX) do
    with_tenant(clusterB) do
      create(:super_admin, community: communityX, first_name: "super_admin_cmtyX")
    end
  end
  let(:admin_cmtyB) { create(:admin, community: communityB, first_name: "admin_cmtyB") }
  let(:inactive_admin) { create(:admin, :inactive, first_name: "inactive_admin") }
  let(:biller) { create(:biller, first_name: "biller") }
  let(:biller_cmtyB) { create(:biller, community: communityB, first_name: "biller_cmtyB") }
  let(:photographer) { create(:photographer, first_name: "photographer") }
  let(:photographer_cmtyB) { create(:photographer, community: communityB, first_name: "photographer_cmtyB") }
  let(:meals_coordinator) { create(:meals_coordinator, first_name: "meals_coord") }
  let(:meals_coordinator_cmtyB) do
    create(:meals_coordinator, community: communityB, first_name: "meals_coord_cmtyB")
  end
  let(:work_coordinator) { create(:work_coordinator, first_name: "work_coordinator") }
  let(:work_coordinator_cmtyB) do
    create(:work_coordinator, community: communityB, first_name: "work_coordinator_cmtyB")
  end
  let(:wikiist) { create(:wikiist, first_name: "wikiist") }
  let(:wikiist_cmtyB) { create(:wikiist, community: communityB, first_name: "wikiist_cmtyB") }

  shared_examples_for "permits super admins only" do
    it "forbids cluster admins from cluster" do
      expect(subject).not_to permit(cluster_admin_cmtyX, record)
    end

    it "permits outside super admins" do
      expect(subject).to permit(super_admin_cmtyX, record)
    end
  end

  shared_examples_for "permits cluster and super admins" do
    it "permits cluster admins from cluster" do
      expect(subject).to permit(cluster_admin_cmtyX, record)
    end

    it "permits outside super admins" do
      expect(subject).to permit(super_admin_cmtyX, record)
    end
  end

  shared_examples_for "permits users in community" do
    it_behaves_like "permits cluster and super admins"

    it "permits users in community" do
      expect(subject).to permit(user, record)
    end
  end

  shared_examples_for "permits users in community only" do
    it_behaves_like "permits users in community"

    it "forbids users from other communities" do
      user_cmtyB.community
      expect(subject).not_to permit(user_cmtyB, record)
    end
  end

  shared_examples_for "permits users in cluster" do
    it_behaves_like "permits users in community"

    it "permits users from other communities in cluster" do
      expect(subject).to permit(user_cmtyB, record)
    end

    it "forbids users from communities outside cluster" do
      expect(subject).not_to permit(user_cmtyX, record)
    end
  end

  shared_examples_for "permits admins from community" do
    context do
      let(:actor) { admin }
      it_behaves_like "errors on permission check without community"
    end
    it_behaves_like "permits cluster and super admins"

    it "permits admins from community" do
      expect(subject).to permit(admin, record)
    end

    it "forbids admins from outside community" do
      expect(subject).not_to permit(admin_cmtyB, record)
    end
  end

  shared_examples_for "permits admins but not regular users" do
    it_behaves_like "permits admins from community"

    it "forbids regular user" do
      expect(subject).not_to permit(user, record)
    end
  end

  shared_examples_for "permits active users only" do
    it "permits active users" do
      expect(subject).to permit(user, record)
    end

    it "forbids inactive users" do
      expect(subject).not_to permit(inactive_user, record)
    end
  end

  shared_examples_for "permits active and inactive users" do
    it "permits active users" do
      expect(subject).to permit(user, record)
    end

    it "permits inactive users" do
      expect(subject).to permit(inactive_user, record)
    end
  end

  shared_examples_for "permits special role but not regular users" do |role_name|
    context do
      let(:actor) { role_member(role_name) }
      it_behaves_like "errors on permission check without community"
    end

    it "forbids regular user" do
      expect(subject).not_to permit(user, record)
    end

    it "permits role from community" do
      expect(subject).to permit(role_member(role_name), record)
    end

    it "forbids role from outside community" do
      expect(subject).not_to permit(role_member("#{role_name}_cmtyB"), record)
    end
  end

  shared_examples_for "permits admins or special role but not regular users" do |role_name|
    it_behaves_like "permits admins but not regular users"
    it_behaves_like "permits special role but not regular users", role_name
  end

  shared_examples_for "permits cluster admins only" do
    it "permits cluster admins" do
      expect(subject).to permit(cluster_admin, record)
      expect(subject).to permit(cluster_admin_cmtyX, record)
    end

    it "forbids admins" do
      expect(subject).not_to permit(admin, record)
    end

    it "forbids regular users" do
      expect(subject).not_to permit(user, record)
    end

    it "forbids billers" do
      expect(subject).not_to permit(biller, record)
    end
  end

  shared_examples_for "permits self (active or not) and guardians" do
    it "permits action on self" do
      expect(subject).to permit(user, user)
    end

    it "permits guardians to edit own children" do
      expect(subject).to permit(guardian, child)
    end

    it "disallows guardians from editing other children" do
      expect(subject).not_to permit(guardian, other_child)
    end

    it "disallows children from editing parent" do
      expect(subject).not_to permit(child, guardian)
    end

    it "permits action on self for inactive user" do
      expect(subject).to permit(inactive_user, inactive_user)
    end
  end

  shared_examples_for "forbids regular users" do
    it do
      expect(subject).not_to permit(user, record)
    end
  end

  shared_examples_for "forbids all" do
    it "doesn't permit super admins" do
      expect(subject).not_to permit(super_admin, record)
    end
  end

  # We know that checking the permission should check the community, so if there is nil community,
  # we should get an error!
  shared_examples_for "errors on permission check without community" do
    context "with nil community" do
      before { expect(record).to receive(:community).at_least(1).and_return(nil) }

      it "errors when checking role permission" do |example|
        example.metadata[:permissions].each do |perm|
          expect { subject.new(actor, record).send(perm) }.to raise_error(
            ApplicationPolicy::CommunityNotSetError
          )
        end
      end
    end
  end

  def role_member(role_name)
    send(role_name)
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.redshift.model;

import java.io.Serializable;

/**
 *

 * Contains the output from the ModifyClusterParameterGroup and
 * ResetClusterParameterGroup actions and indicate the parameter group
 * involved and the status of the operation on the parameter group.
 *

 */
public class ModifyClusterParameterGroupResult implements Serializable, Cloneable {

    /**
     * The name of the cluster parameter group.
     */
    private String parameterGroupName;

    /**
     * The status of the parameter group. For example, if you made a change
     * to a parameter group name-value pair, then the change could be pending
     * a reboot of an associated cluster.
     */
    private String parameterGroupStatus;

    /**
     * The name of the cluster parameter group.
     *
     * @return The name of the cluster parameter group.
     */
    public String getParameterGroupName() {
        return parameterGroupName;
    }

    /**
     * The name of the cluster parameter group.
     *
     * @param parameterGroupName The name of the cluster parameter group.
     */
    public void setParameterGroupName(String parameterGroupName) {
        this.parameterGroupName = parameterGroupName;
    }

    /**
     * The name of the cluster parameter group.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param parameterGroupName The name of the cluster parameter group.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ModifyClusterParameterGroupResult withParameterGroupName(String parameterGroupName) {
        this.parameterGroupName = parameterGroupName;
        return this;
    }

    /**
     * The status of the parameter group. For example, if you made a change
     * to a parameter group name-value pair, then the change could be pending
     * a reboot of an associated cluster.
     *
     * @return The status of the parameter group. For example, if you made a change
     *         to a parameter group name-value pair, then the change could be pending
     *         a reboot of an associated cluster.
     */
    public String getParameterGroupStatus() {
        return parameterGroupStatus;
    }

    /**
     * The status of the parameter group. For example, if you made a change
     * to a parameter group name-value pair, then the change could be pending
     * a reboot of an associated cluster.
     *
     * @param parameterGroupStatus The status of the parameter group. For example, if you made a change
     *         to a parameter group name-value pair, then the change could be pending
     *         a reboot of an associated cluster.
     */
    public void setParameterGroupStatus(String parameterGroupStatus) {
        this.parameterGroupStatus = parameterGroupStatus;
    }

    /**
     * The status of the parameter group. For example, if you made a change
     * to a parameter group name-value pair, then the change could be pending
     * a reboot of an associated cluster.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param parameterGroupStatus The status of the parameter group. For example, if you made a change
     *         to a parameter group name-value pair, then the change could be pending
     *         a reboot of an associated cluster.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ModifyClusterParameterGroupResult withParameterGroupStatus(String parameterGroupStatus) {
        this.parameterGroupStatus = parameterGroupStatus;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getParameterGroupName() != null) sb.append("ParameterGroupName: " + getParameterGroupName() + ",");
        if (getParameterGroupStatus() != null) sb.append("ParameterGroupStatus: " + getParameterGroupStatus() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getParameterGroupName() == null) ? 0 : getParameterGroupName().hashCode());
        hashCode = prime * hashCode + ((getParameterGroupStatus() == null) ? 0 : getParameterGroupStatus().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof ModifyClusterParameterGroupResult == false) return false;
        ModifyClusterParameterGroupResult other = (ModifyClusterParameterGroupResult)obj;

        if (other.getParameterGroupName() == null ^ this.getParameterGroupName() == null) return false;
        if (other.getParameterGroupName() != null && other.getParameterGroupName().equals(this.getParameterGroupName()) == false) return false;
        if (other.getParameterGroupStatus() == null ^ this.getParameterGroupStatus() == null) return false;
        if (other.getParameterGroupStatus() != null && other.getParameterGroupStatus().equals(this.getParameterGroupStatus()) == false) return false;
        return true;
    }

    @Override
    public ModifyClusterParameterGroupResult clone() {
        try {
            return (ModifyClusterParameterGroupResult) super.clone();

        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                    + "even though we're Cloneable!",
                    e);
        }

    }

}


text:
package it.finsiel.siged.dao.jdbc;

import it.finsiel.siged.constant.ReturnValues;
import it.finsiel.siged.exception.DataException;
import it.finsiel.siged.model.organizzazione.Organizzazione;
import it.finsiel.siged.model.organizzazione.Ufficio;
import it.finsiel.siged.model.organizzazione.Utente;
import it.finsiel.siged.mvc.integration.UtenteDAO;
import it.finsiel.siged.mvc.presentation.helper.AssegnatarioView;
import it.finsiel.siged.mvc.vo.organizzazione.PermessoMenuVO;
import it.finsiel.siged.mvc.vo.organizzazione.PermessoRegistroVO;
import it.finsiel.siged.mvc.vo.organizzazione.UtenteVO;
import it.finsiel.siged.rdb.JDBCManager;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class UtenteDAOjdbc implements UtenteDAO {

    protected final static String SELECT_UTENTI = "SELECT * FROM utenti ORDER BY COGNOME, NOME";

    protected final static String SELECT_USER_PROFILE = "SELECT * FROM utenti WHERE user_name=? AND passwd=?";

    protected final static String SELECT_USER_PROFILE_BYID = "SELECT * FROM utenti WHERE utente_id=?";

    protected final static String SELECT_USER_PROFILE_BY_USERNAME = "SELECT * FROM utenti WHERE user_name=?";

    protected final static String CHECK_USER_USERNAME = "SELECT COUNT(*) FROM utenti WHERE user_name=? and utente_id!=?";

    protected final static String INSERT_USER_PROFILE = "INSERT INTO utenti (utente_id, user_name, email, cognome, nome, codicefiscale, matricola, "
            + "passwd, flag_abilitato, data_fine_attivita, aoo_id, row_created_time, row_created_user, row_updated_time, row_updated_user, versione ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )";

    protected final static String UPDATE_USER_PROFILE = "update utenti set user_name=?, email=?, cognome=?, nome=?, codicefiscale=?, matricola=?, "
            + "passwd=?, flag_abilitato=?, data_fine_attivita=?, aoo_id=?, row_updated_time=?, row_updated_user=?, versione=? where utente_id=?";

    protected final static String UPDATE_PASSWORD = "UPDATE UTENTI SET PASSWD=? WHERE UTENTE_ID=?";

    protected final static String SELECT_UFFICI_UTENTI = "SELECT distinct ufficio_id FROM permessi_utente WHERE utente_id=?";

    private final static String SELECT_COUNT_UTENTI = "SELECT count(*) FROM utenti";

    static Logger logger = Logger.getLogger(UtenteDAOjdbc.class.getName());

    IdentificativiDAOjdbc identificativiDAO;

    private JDBCManager jdbcMan = new JDBCManager();

    public Collection getUtenti() throws DataException {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        UtenteVO c = null;
        ArrayList utenti = new ArrayList();
        try {
            connection = jdbcMan.getConnection();
            pstmt = connection.prepareStatement(SELECT_UTENTI);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                c = new UtenteVO();
                // come in getUtente
                c.setId(rs.getInt("utente_id"));
                c.setUsername(rs.getString("user_name"));
                c.setEmailAddress(rs.getString("email"));
                c.setCognome(rs.getString("cognome"));
                c.setNome(rs.getString("nome"));
                c.setCodiceFiscale(rs.getString("codicefiscale"));
                c.setMatricola(rs.getString("matricola"));
                c.setPassword(rs.getString("passwd"));
                c.setDataFineAttivita(rs.getDate("data_fine_attivita"));
                c.setAooId(rs.getInt("aoo_id"));
                c.setRowCreatedTime(rs.getDate("row_created_time"));
                c.setRowCreatedUser(rs.getString("row_created_user"));
                c.setRowUpdatedUser(rs.getString("row_updated_user"));
                c.setRowUpdatedTime(rs.getDate("row_updated_time"));
                c.setVersione(rs.getInt("versione"));
                c.setAbilitato(rs.getBoolean("flag_abilitato"));
                c.setReturnValue(ReturnValues.FOUND);
                utenti.add(c);

            }
        } catch (Exception e) {
            logger.error("getUtenti", e);
            throw new DataException("Cannot load getUtenti");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
        return utenti;
    }

    public UtenteVO getUtente(String username, String password)
            throws DataException {
        Connection connection = null;
        try {
            connection = jdbcMan.getConnection();
            return getUtente(connection, username, password);
        } catch (Exception e) {
            throw new DataException(e.getMessage() + " username :" + username
                    + " password:" + password);
        } finally {
            jdbcMan.close(connection);
        }
    }

    public UtenteVO getUtente(String username) throws DataException {
        Connection connection = null;
        try {
            connection = jdbcMan.getConnection();
            return getUtente(connection, username);
        } catch (Exception e) {
            throw new DataException(e.getMessage() + " username :" + username);
        } finally {
            jdbcMan.close(connection);
        }
    }

    /*
     * Get a Utente VO using username and pwd.
     */

    public UtenteVO getUtente(Connection connection, String username,
            String password) throws DataException {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        UtenteVO c = new UtenteVO();
        c.setReturnValue(ReturnValues.UNKNOWN);
        try {
            pstmt = connection.prepareStatement(SELECT_USER_PROFILE);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                int id = rs.getInt(1);
                c = getUtente(connection, id);
            } else {
                c.setReturnValue(ReturnValues.NOT_FOUND);
            }
        } catch (Exception e) {
            logger.error("Load Utente Profile", e);
            throw new DataException("Cannot load the user profile");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
        }
        return c;
    }

    public UtenteVO getUtente(Connection connection, String username)
            throws DataException {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        UtenteVO c = new UtenteVO();
        c.setReturnValue(ReturnValues.UNKNOWN);
        try {
            pstmt = connection
                    .prepareStatement(SELECT_USER_PROFILE_BY_USERNAME);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                int id = rs.getInt(1);
                c = getUtente(connection, id);
            } else {
                c.setReturnValue(ReturnValues.NOT_FOUND);
            }
        } catch (Exception e) {
            logger.error("Load Utente Profile", e);
            throw new DataException("Cannot load the user profile");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
        }
        return c;
    }

    /*
     * Get a Utente VO using the id.
     */
    public UtenteVO getUtente(int id) throws DataException {
        Connection connection = null;
        try {
            connection = jdbcMan.getConnection();
            return getUtente(connection, id);
        } catch (Exception e) {
            throw new DataException(e.getMessage() + " id :" + id);
        } finally {
            jdbcMan.close(connection);
        }
    }

    /*
     * Get a Utente VO using the id.
     */

    public UtenteVO getUtente(Connection connection, int id)
            throws DataException {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        UtenteVO c = new UtenteVO();
        c.setReturnValue(ReturnValues.UNKNOWN);
        try {
            if (connection == null) {
                logger.warn("getUtente() - Invalid Connection :" + connection);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }
            pstmt = connection.prepareStatement(SELECT_USER_PROFILE_BYID);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                // per essere pi? performante questo codice ? stato duplicato in
                // un'altro metodo
                // in caso di aggiornamento aggiornare la parte nel metodo
                // getUtenti().
                c.setId(rs.getInt("utente_id"));
                c.setUsername(rs.getString("user_name"));
                c.setEmailAddress(rs.getString("email"));
                c.setCognome(rs.getString("cognome"));
                c.setNome(rs.getString("nome"));
                c.setCodiceFiscale(rs.getString("codicefiscale"));
                c.setMatricola(rs.getString("matricola"));
                c.setPassword(rs.getString("passwd"));
                c.setDataFineAttivita(rs.getDate("data_fine_attivita"));
                c.setAooId(rs.getInt("aoo_id"));
                c.setRowCreatedTime(rs.getDate("row_created_time"));
                c.setRowCreatedUser(rs.getString("row_created_user"));
                c.setRowUpdatedUser(rs.getString("row_updated_user"));
                c.setRowUpdatedTime(rs.getDate("row_updated_time"));
                c.setVersione(rs.getInt("versione"));
                c.setAbilitato(rs.getBoolean("flag_abilitato"));
                // fine
                c.setReturnValue(ReturnValues.FOUND);

            } else {
                c.setReturnValue(ReturnValues.NOT_FOUND);
            }
        } catch (Exception e) {
            logger.error("Load Utente Profile", e);
            throw new DataException("Cannot load the user profile");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
        }
        return c;
    }

    /*
     * SINC PASSWORD BETWEEN LDAP AND APPLICATION
     */
    public void sincronizzaPassword(int utenteId, String newPwd)
            throws DataException {
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = jdbcMan.getConnection();
            pstmt = connection.prepareStatement(UPDATE_PASSWORD);
            pstmt.setString(1, newPwd);
            pstmt.setInt(2, utenteId);
            if (pstmt.executeUpdate() < 1)
                logger
                        .warn("Impossibile sincronizzare la password utente per id:"
                                + utenteId);

        } catch (Exception e) {
            throw new DataException(e.getMessage() + " id :" + utenteId);
        } finally {
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
    }

    public boolean isUsernameUsed(Connection connection, String username,
            int utenteId) throws DataException {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean used = true;
        try {
            if (connection == null) {
                logger.warn("isUsernameUsed - Invalid Connection :"
                        + connection);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }
            pstmt = connection.prepareStatement(CHECK_USER_USERNAME);
            pstmt.setString(1, username);
            pstmt.setInt(2, utenteId);
            rs = pstmt.executeQuery();
            rs.next();
            used = rs.getInt(1) > 0;
        } catch (Exception e) {
            logger.error("isUsernameUsed:" + username, e);
            throw new DataException("error.database.missing");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
        }
        return used;
    }

    public UtenteVO newUtenteVO(Connection connection, UtenteVO utenteVO)
            throws DataException {
        PreparedStatement pstmt = null;
        if (isUsernameUsed(connection, utenteVO.getUsername(), utenteVO.getId()
                .intValue()))
            throw new DataException("username_gia_utilizzato");
        try {
            if (connection == null) {
                logger.warn("newUtenteVO - Invalid Connection :" + connection);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }
            pstmt = connection.prepareStatement(INSERT_USER_PROFILE);
            pstmt.setInt(1, utenteVO.getId().intValue());
            pstmt.setString(2, utenteVO.getUsername());
            pstmt.setString(3, utenteVO.getEmailAddress());
            pstmt.setString(4, utenteVO.getCognome());
            pstmt.setString(5, utenteVO.getNome());
            pstmt.setString(6, utenteVO.getCodiceFiscale());
            pstmt.setString(7, utenteVO.getMatricola());
            pstmt.setString(8, utenteVO.getPassword());
            pstmt.setInt(9, utenteVO.isAbilitato() ? 1 : 0);
            if (utenteVO.getDataFineAttivita() != null)
                pstmt.setDate(10, new Date(utenteVO.getDataFineAttivita()
                        .getTime()));
            else
                pstmt.setNull(10, Types.DATE);
            pstmt.setInt(11, utenteVO.getAooId());
            pstmt.setDate(12, new Date(System.currentTimeMillis()));
            pstmt.setString(13, utenteVO.getRowCreatedUser());
            pstmt.setDate(14, null);
            pstmt.setString(15, null);
            pstmt.setInt(16, 1);

            pstmt.executeUpdate();
        } catch (Exception e) {
            logger.error("Save Utente Profile", e);
            throw new DataException("error.database.cannotsave");
        } finally {
            jdbcMan.close(pstmt);
        }

        UtenteVO newVO = getUtente(connection, utenteVO.getId().intValue());
        newVO.setReturnValue(ReturnValues.SAVED);
        return newVO;

    }

    public UtenteVO updateUtenteVO(Connection connection, UtenteVO utenteVO)
            throws DataException {
        PreparedStatement pstmt = null;
        if (isUsernameUsed(connection, utenteVO.getUsername(), utenteVO.getId()
                .intValue()))
            throw new DataException("username_gia_utilizzato");
        try {
            if (connection == null) {
                logger.warn("updateUtenteVO - Invalid Connection :"
                        + connection);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }
            pstmt = connection.prepareStatement(UPDATE_USER_PROFILE);
            // TODO: implementare il controllo della versione!!
            int versione = 1;

            pstmt.setString(1, utenteVO.getUsername());
            pstmt.setString(2, utenteVO.getEmailAddress());
            pstmt.setString(3, utenteVO.getCognome());
            pstmt.setString(4, utenteVO.getNome());
            pstmt.setString(5, utenteVO.getCodiceFiscale());
            pstmt.setString(6, utenteVO.getMatricola());
            pstmt.setString(7, utenteVO.getPassword());
            pstmt.setInt(8, utenteVO.isAbilitato() ? 1 : 0);
            if (utenteVO.getDataFineAttivita() != null)
                pstmt.setDate(9, new Date(utenteVO.getDataFineAttivita()
                        .getTime()));
            else
                pstmt.setNull(9, Types.DATE);
            pstmt.setInt(10, utenteVO.getAooId());
            pstmt.setDate(11, new Date(System.currentTimeMillis()));
            pstmt.setString(12, utenteVO.getRowUpdatedUser());
            pstmt.setInt(13, versione);

            pstmt.setInt(14, utenteVO.getId().intValue());
            pstmt.executeUpdate();
        } catch (Exception e) {
            logger.error("Save Utente Profile", e);
            throw new DataException("error.database.cannotsave");
        } finally {
            jdbcMan.close(pstmt);
        }
        UtenteVO newVO = getUtente(connection, utenteVO.getId().intValue());
        newVO.setReturnValue(ReturnValues.SAVED);
        return newVO;
    }

    public Collection cercaUtenti(int aooId, String username, String cognome,
            String nome) throws DataException {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        UtenteVO c = null;
        ArrayList utenti = new ArrayList();
        try {
            connection = jdbcMan.getConnection();

            String sql = "SELECT UTENTE_ID, USER_NAME, COGNOME, NOME, FLAG_ABILITATO, CODICEFISCALE FROM UTENTI WHERE aoo_id = "
                    + aooId;
            if (username != null)
                sql += " AND UPPER(user_name) like ?";
            if (cognome != null)
                sql += " AND UPPER(cognome) like ?";
            if (nome != null)
                sql += " AND UPPER(nome) like ?";
            sql += " ORDER BY cognome,nome";

            pstmt = connection.prepareStatement(sql);
            int i = 1;
            if (username != null)
                pstmt.setString(i++, username.toUpperCase() + "%");
            if (cognome != null)
                pstmt.setString(i++, cognome.toUpperCase() + "%");
            if (nome != null)
                pstmt.setString(i++, nome.toUpperCase() + "%");

            rs = pstmt.executeQuery();
            while (rs.next()) {
                c = new UtenteVO();
                c.setId(rs.getInt("utente_id"));
                c.setUsername(rs.getString("user_name"));
                c.setCognome(rs.getString("cognome"));
                c.setNome(rs.getString("nome"));
                c.setCodiceFiscale(rs.getString("codicefiscale"));
                // c.setDataFineAttivita(rs.getDate("data_fine_attivita"));
                c.setAbilitato(rs.getBoolean("flag_abilitato"));
                c.setReturnValue(ReturnValues.FOUND);
                utenti.add(c);
                logger.debug("Load Utente Profile" + c);
            }
        } catch (Exception e) {
            logger.error("Cerca Utente Profile", e);
            throw new DataException("Errore nella ricerca degli utenti.");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
        return utenti;
    }

    public Map getUfficiByUtente(Utente utente) throws DataException {
        Map uffici = new HashMap();

        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        AssegnatarioView ufficio = null;
        try {
            connection = jdbcMan.getConnection();
            String sqlStr = "SELECT distinct(u.*) FROM uffici U, permessi_utente P"
                    + " WHERE U.ufficio_id=P.ufficio_id AND utente_id=? AND aoo_id=? ORDER BY descrizione";
            pstmt = connection.prepareStatement(sqlStr);
            pstmt.setInt(1, utente.getValueObject().getId().intValue());
            pstmt.setInt(2, utente.getValueObject().getAooId());
            rs = pstmt.executeQuery();
            while (rs.next()) {
                ufficio = new AssegnatarioView();
                ufficio.setUfficioId(rs.getInt("ufficio_id"));
                ufficio.setDescrizioneUfficio(rs.getString("descrizione"));
                uffici.put(ufficio.getKey(), ufficio);
            }
        } catch (Exception e) {
            logger.error("Load getUfficiByParent", e);
            throw new DataException("Cannot load getUfficiByParent");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
        return uffici;
    }

    public void nuovoPermessoMenu(Connection conn, PermessoMenuVO permesso)
            throws DataException {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            if (conn == null) {
                logger.warn("permessiUtente() - Invalid Connection :" + conn);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }
            String check = "SELECT utente_id FROM permessi_utente WHERE utente_id=? AND ufficio_id=? AND menu_id=?";
            pstmt = conn.prepareStatement(check);
            pstmt.setInt(1, permesso.getUtenteId());
            pstmt.setInt(2, permesso.getUfficioId());
            pstmt.setInt(3, permesso.getMenuId());
            rs = pstmt.executeQuery();
            if(rs.next()){
            	return;
            }
            // riassegno tutti i permessi utente PER
            String sqlStr = "INSERT INTO permessi_utente "
                    + " (utente_id, ufficio_id, menu_id, row_created_time,"
                    + " row_created_user, row_updated_user, row_updated_time, "
                    + "versione) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

            pstmt = conn.prepareStatement(sqlStr);
            pstmt.setInt(1, permesso.getUtenteId());
            pstmt.setInt(2, permesso.getUfficioId());
            pstmt.setInt(3, permesso.getMenuId());
            pstmt.setTimestamp(4, new Timestamp(permesso.getRowCreatedTime()
                    .getTime()));
            pstmt.setString(5, permesso.getRowCreatedUser());
            pstmt.setString(6, permesso.getRowUpdatedUser());
            pstmt.setTimestamp(7, new Timestamp(permesso.getRowUpdatedTime()
                    .getTime()));
            pstmt.setInt(8, permesso.getVersione());
            pstmt.executeUpdate();

        } catch (SQLException e) {
            logger.error("permessiUtente", e);
        } finally {
            jdbcMan.close(pstmt);
        }
    }

    public void cancellaPermessiUtente(Connection conn, int utenteId,
            int ufficioId, Utente utente) throws DataException {
        PreparedStatement pstmt = null;
        try {
            if (conn == null) {
                logger.warn("cancellaPermessiUtente - Invalid Connection :"
                        + conn);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }

            // cancello tutti i permessi utente
            String sqlStr = "DELETE FROM permessi_utente WHERE utente_id=? AND ufficio_id=?";
            pstmt = conn.prepareStatement(sqlStr);
            pstmt.setInt(1, utenteId);
            pstmt.setInt(2, ufficioId);
            pstmt.executeUpdate();

        } catch (Exception e) {
            logger.error("cancellaPermessiUtente", e);
            throw new DataException("error.database.cannotsave");
        } finally {
            jdbcMan.close(pstmt);
        }
    }

    public String[] getPermessiRegistri(int utenteId) throws DataException {

        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList registri = new ArrayList();
        String[] aRegistri = null;
        try {
            connection = jdbcMan.getConnection();
            String sqlStr = "SELECT registro_id FROM utenti$registri WHERE utente_id=?";
            pstmt = connection.prepareStatement(sqlStr);
            pstmt.setInt(1, utenteId);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                registri.add(rs.getString("registro_id"));
            }
            if (registri != null) {
                aRegistri = new String[registri.size()];
                registri.toArray(aRegistri);
            }

        } catch (Exception e) {
            logger.error("Load getPermessiRegistri", e);
            throw new DataException("Cannot load getPermessiRegistri");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
        return aRegistri;

    }

    public void nuovoPermessoRegistro(Connection conn,
            PermessoRegistroVO permesso) throws DataException {
        PreparedStatement pstmt = null;
        try {
            if (conn == null) {
                logger.warn("permessiRegistriUtente() - Invalid Connection :"
                        + conn);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }

            // riassegno tutti i permessi utente PER
            String sqlStr = "INSERT INTO utenti$registri "
                    + " (utente_id, registro_id, row_created_time, "
                    + "row_created_user, row_updated_time, row_updated_user)"
                    + " VALUES (?, ?, ?, ?, ?, ?)";

            if (permesso.getRegistroId() > 0) {
                pstmt = conn.prepareStatement(sqlStr);
                pstmt.setInt(1, permesso.getUtenteId());
                pstmt.setInt(2, permesso.getRegistroId());
                pstmt.setTimestamp(3, new Timestamp(permesso
                        .getRowCreatedTime().getTime()));
                pstmt.setString(4, permesso.getRowCreatedUser());
                pstmt.setTimestamp(5, new Timestamp(permesso
                        .getRowUpdatedTime().getTime()));
                pstmt.setString(6, permesso.getRowUpdatedUser());
                pstmt.executeUpdate();
            }

        } catch (Exception e) {
            logger.error("nuovoPermessoRegistro", e);
            throw new DataException("error.database.cannotsave");
        } finally {
            jdbcMan.close(pstmt);
        }
    }

    public void cancellaPermessiRegistriUtente(Connection conn, int utenteId,
            Utente utente) throws DataException {
        PreparedStatement pstmt = null;
        try {
            if (conn == null) {
                logger
                        .warn("cancellaPermessiRegistriUtente - Invalid Connection :"
                                + conn);
                throw new DataException(
                        "Connessione alla base dati non valida.");
            }
            // cancello tutti i permessi utente
            String sqlStr = "DELETE FROM utenti$registri WHERE utente_id=?";
            pstmt = conn.prepareStatement(sqlStr);
            pstmt.setInt(1, utenteId);
            pstmt.executeUpdate();

        } catch (Exception e) {
            logger.error("cancellaPermessiRegistriUtente", e);
            throw new DataException("error.database.cannotsave");
        } finally {
            jdbcMan.close(pstmt);
        }
    }

    public String[] getFunzioniByUfficioUtente(int utenteId, int ufficioId)
            throws DataException {
        Collection funzioni = new ArrayList();
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String[] aFunzioni = null;
        try {
            connection = jdbcMan.getConnection();
            String sqlStr = "SELECT p.menu_id FROM permessi_utente p, menu m"
                    + " WHERE p.menu_id = m.menu_id and link is not null and utente_id=? AND ufficio_id=?";
            pstmt = connection.prepareStatement(sqlStr);
            pstmt.setInt(1, utenteId);
            pstmt.setInt(2, ufficioId);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                funzioni.add(rs.getString("menu_id"));
            }
            aFunzioni = new String[funzioni.size()];
            funzioni.toArray(aFunzioni);

        } catch (Exception e) {
            logger.error("Load getFunzioniByUfficioUtente", e);
            throw new DataException("Cannot load getFunzioniByUfficioUtente");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
        return aFunzioni;
    }

    public Collection getUfficiByUtente(int utenteId) throws DataException {
        Collection uffici = new ArrayList();
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        // TODO: Organizzazione deve essere rimossa da questo file.
        // accoppia due classi la cui reciproca interazione non dovrebbe
        // esistere.

        Organizzazione org = Organizzazione.getInstance();
        Ufficio uff;

        try {
            connection = jdbcMan.getConnection();
            pstmt = connection.prepareStatement(SELECT_UFFICI_UTENTI);
            pstmt.setInt(1, utenteId);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                uff = org.getUfficio(rs.getInt("ufficio_id"));
                uffici.add(uff);
            }

        } catch (Exception e) {
            logger.error("Load getUfficiByUtente", e);
            throw new DataException("Cannot load getUfficiByUtente");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
        return uffici;
    }

    public long getCountUtenti() throws DataException {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        long num = -1;
        try {
            connection = jdbcMan.getConnection();
            pstmt = connection.prepareStatement(SELECT_COUNT_UTENTI);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                num = rs.getLong(1);
            }
        } catch (Exception e) {
            logger.error("getCountUtenti", e);
            throw new DataException("Cannot load getCountUtenti");
        } finally {
            jdbcMan.close(rs);
            jdbcMan.close(pstmt);
            jdbcMan.close(connection);
        }
        return num;
    }

}


text:
"use strict";

const Promise = require("bluebird");

const config = require("../../config");
const formats = require("../../formats");
let gm = require("gm");
Promise.promisifyAll(gm.prototype);
const log = require("../../log");
const match = require("../match");
const path = require("path");
const writer = require("../writer");
const _ = require("lodash");

const options = [
    require("./resize"),
    require("./unsharp"),
    require("./quality")
];

async function convertSingle(image, album, conversion) {
    if (match.image("convert[" + conversion + "]", image)) {
        const targetFilename = config.get("convert[" + conversion + "].filename");
        log.verbose("Converting image %s/%s to %s", album.id, image.id, targetFilename);

        const outputFormat = formats.getFormat(path.extname(targetFilename));
        const [input, output] = await Promise.all([
            options.filter(option => option.isConfigured(conversion))
            .reduce((output, option) => option.apply(conversion, output), gm(image.path))
            .streamAsync(outputFormat),
            writer.createImageFileStream(album, image, targetFilename)
        ]);

        return input.pipe(output);
    }
}

async function convert(image, index, length, album) {
    await Promise.map(_.range(config.get("convert").length), conversion => convertSingle(image, album, conversion));
}

module.exports = {
    name: "convert",
    processImage: convert
};


text:
<?php

namespace Symfony\Component\Messenger\Tests\Fixtures;

use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;

class CallbackReceiver implements ReceiverInterface
{
    private $callable;

    public function __construct(callable $callable)
    {
        $this->callable = $callable;
    }

    public function receive(callable $handler): void
    {
        $callable = $this->callable;
        $callable($handler);
    }

    public function stop(): void
    {
    }
}