<commit_before>/* This file is part of Zanshin

   Copyright 2014 Kevin Ottens <ervin@kde.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "availablepagesmodel.h"

#include <QIcon>
#include <QMimeData>

#include "domain/contextqueries.h"
#include "domain/contextrepository.h"
#include "domain/projectqueries.h"
#include "domain/projectrepository.h"
#include "domain/tag.h"
#include "domain/tagqueries.h"
#include "domain/tagrepository.h"
#include "domain/taskrepository.h"

#include "presentation/contextpagemodel.h"
#include "presentation/inboxpagemodel.h"
#include "presentation/metatypes.h"
#include "presentation/projectpagemodel.h"
#include "presentation/querytreemodel.h"
#include "presentation/tagpagemodel.h"

#include "utils/jobhandler.h"

using namespace Presentation;

AvailablePagesModel::AvailablePagesModel(Domain::ArtifactQueries *artifactQueries,
                                         Domain::ProjectQueries *projectQueries,
                                         Domain::ProjectRepository *projectRepository,
                                         Domain::ContextQueries *contextQueries,
                                         Domain::ContextRepository *contextRepository,
                                         Domain::TaskQueries *taskQueries,
                                         Domain::TaskRepository *taskRepository,
                                         Domain::NoteRepository *noteRepository,
                                         Domain::TagQueries *tagQueries,
                                         Domain::TagRepository *tagRepository,
                                         QObject *parent)
    : QObject(parent),
      m_pageListModel(0),
      m_artifactQueries(artifactQueries),
      m_projectQueries(projectQueries),
      m_projectRepository(projectRepository),
      m_contextQueries(contextQueries),
      m_contextRepository(contextRepository),
      m_taskQueries(taskQueries),
      m_taskRepository(taskRepository),
      m_noteRepository(noteRepository),
      m_tagQueries(tagQueries),
      m_tagRepository(tagRepository)
{
}

AvailablePagesModel::~AvailablePagesModel()
{
}

QAbstractItemModel *AvailablePagesModel::pageListModel()
{
    if (!m_pageListModel)
        m_pageListModel = createPageListModel();
    return m_pageListModel;
}

QObject *AvailablePagesModel::createPageForIndex(const QModelIndex &index)
{
    QObjectPtr object = index.data(QueryTreeModelBase::ObjectRole).value<QObjectPtr>();

    if (object == m_inboxObject) {
        return new InboxPageModel(m_artifactQueries,
                                  m_taskQueries, m_taskRepository,
                                  m_noteRepository,
                                  this);

    } else if (auto project = object.objectCast<Domain::Project>()) {
        return new ProjectPageModel(project,
                                    m_projectQueries,
                                    m_taskQueries, m_taskRepository,
                                    m_noteRepository,
                                    this);
    } else if (auto context = object.objectCast<Domain::Context>()) {
        return new ContextPageModel(context,
                                    m_contextQueries,
                                    m_taskQueries,
                                    m_taskRepository,
                                    m_noteRepository,
                                    this);
    } else if (auto tag = object.objectCast<Domain::Tag>()) {
        return new TagPageModel(tag,
                                m_tagQueries,
                                m_taskQueries,
                                m_taskRepository,
                                m_noteRepository,
                                this);
    }

    return 0;
}

void AvailablePagesModel::addProject(const QString &name, const Domain::DataSource::Ptr &source)
{
    auto project = Domain::Project::Ptr::create();
    project->setName(name);
    m_projectRepository->create(project, source);
}

void AvailablePagesModel::addContext(const QString &name)
{
    auto context = Domain::Context::Ptr::create();
    context->setName(name);
    m_contextRepository->create(context);
}

void AvailablePagesModel::addTag(const QString &name)
{
    auto tag = Domain::Tag::Ptr::create();
    tag->setName(name);
    m_tagRepository->create(tag);
}

void AvailablePagesModel::removeItem(const QModelIndex &index)
{
    QObjectPtr object = index.data(QueryTreeModelBase::ObjectRole).value<QObjectPtr>();
    if (auto project = object.objectCast<Domain::Project>()) {
        m_projectRepository->remove(project);
    } else if (auto context = object.objectCast<Domain::Context>()) {
        m_contextRepository->remove(context);
    } else if (auto tag = object.objectCast<Domain::Tag>()) {
        m_tagRepository->remove(tag);
    } else {
        Q_ASSERT(false);
    }
}

QAbstractItemModel *AvailablePagesModel::createPageListModel()
{
    m_inboxObject = QObjectPtr::create();
    m_inboxObject->setProperty("name", tr("Inbox"));
    m_projectsObject = QObjectPtr::create();
    m_projectsObject->setProperty("name", tr("Projects"));
    m_contextsObject = QObjectPtr::create();
    m_contextsObject->setProperty("name", tr("Contexts"));
    m_tagsObject = QObjectPtr::create();
    m_tagsObject->setProperty("name", tr("Tags"));

    m_rootsProvider = Domain::QueryResultProvider<QObjectPtr>::Ptr::create();
    m_rootsProvider->append(m_inboxObject);
    m_rootsProvider->append(m_projectsObject);
    m_rootsProvider->append(m_contextsObject);
    m_rootsProvider->append(m_tagsObject);

    auto query = [this](const QObjectPtr &object) -> Domain::QueryResultInterface<QObjectPtr>::Ptr {
        if (!object)
            return Domain::QueryResult<QObjectPtr>::create(m_rootsProvider);
        else if (object == m_projectsObject)
            return Domain::QueryResult<Domain::Project::Ptr, QObjectPtr>::copy(m_projectQueries->findAll());
        else if (object == m_contextsObject)
            return Domain::QueryResult<Domain::Context::Ptr, QObjectPtr>::copy(m_contextQueries->findAll());
        else if (object == m_tagsObject)
            return Domain::QueryResult<Domain::Tag::Ptr, QObjectPtr>::copy(m_tagQueries->findAll());
        else
            return Domain::QueryResult<QObjectPtr>::Ptr();
    };

    auto flags = [this](const QObjectPtr &object) {
        const Qt::ItemFlags defaultFlags = Qt::ItemIsSelectable
                                         | Qt::ItemIsEnabled
                                         | Qt::ItemIsEditable
                                         | Qt::ItemIsDropEnabled;
        const Qt::ItemFlags immutableNodeFlags = Qt::ItemIsSelectable
                                               | Qt::ItemIsEnabled
                                               | Qt::ItemIsDropEnabled;
        const Qt::ItemFlags structureNodeFlags = Qt::NoItemFlags;

        return object.objectCast<Domain::Project>() ? defaultFlags
             : object.objectCast<Domain::Context>() ? defaultFlags
             : object.objectCast<Domain::Tag>() ? defaultFlags
             : object == m_inboxObject ? immutableNodeFlags
             : structureNodeFlags;
    };

    auto data = [this](const QObjectPtr &object, int role) -> QVariant {
        if (role != Qt::DisplayRole
         && role != Qt::EditRole
         && role != Qt::DecorationRole
         && role != QueryTreeModelBase::IconNameRole) {
            return QVariant();
        }

        if (role == Qt::EditRole
         && (object == m_inboxObject
          || object == m_projectsObject
          || object == m_contextsObject
          || object == m_tagsObject)) {
            return QVariant();
        }

        if (role == Qt::DisplayRole || role == Qt::EditRole) {
            return object->property("name").toString();
        } else if (role == Qt::DecorationRole || role == QueryTreeModelBase::IconNameRole) {
            const QString iconName = object == m_inboxObject ? "mail-folder-inbox"
                                   : (object == m_projectsObject) ? "folder"
                                   : (object == m_contextsObject) ? "folder"
                                   : (object == m_tagsObject)     ? "folder"
                                   : "view-pim-tasks";

            if (role == Qt::DecorationRole)
                return QVariant::fromValue(QIcon::fromTheme(iconName));
            else
                return iconName;
        } else {
            return QVariant();
        }
    };

    auto setData = [this](const QObjectPtr &object, const QVariant &value, int role) {
        if (role != Qt::EditRole) {
            return false;
        }

        if (object == m_inboxObject
         || object == m_projectsObject
         || object == m_contextsObject
         || object == m_tagsObject) {
            return false;
        }

        if (auto project = object.objectCast<Domain::Project>()) {
            project->setName(value.toString());
            m_projectRepository->update(project);
        } else if (auto context = object.objectCast<Domain::Context>()) {
            context->setName(value.toString());
            m_contextRepository->update(context);
        } else if (object.objectCast<Domain::Tag>()) {
            return false; // Tag renaming is NOT allowed
        } else {
            Q_ASSERT(false);
        }

        return true;
    };

    auto drop = [this](const QMimeData *mimeData, Qt::DropAction, const QObjectPtr &object) {
        if (!mimeData->hasFormat("application/x-zanshin-object"))
            return false;

        auto droppedArtifacts = mimeData->property("objects").value<Domain::Artifact::List>();
        if (droppedArtifacts.isEmpty())
            return false;

        if (auto project = object.objectCast<Domain::Project>()) {
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                m_projectRepository->associate(project, droppedArtifact);
            }
            return true;
        } else if (auto context = object.objectCast<Domain::Context>()) {
            if (std::any_of(droppedArtifacts.begin(), droppedArtifacts.end(),
                            [](const Domain::Artifact::Ptr &droppedArtifact) {
                                return !droppedArtifact.objectCast<Domain::Task>();
                            })) {
                return false;
            }
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                auto task = droppedArtifact.staticCast<Domain::Task>();
                m_contextRepository->associate(context, task);
            }
        } else if (auto tag = object.objectCast<Domain::Tag>()) {
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                m_tagRepository->associate(tag, droppedArtifact);
            }
            return true;
        } else if (object == m_inboxObject) {
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                auto job = m_projectRepository->dissociate(droppedArtifact);
                if (auto task = droppedArtifact.objectCast<Domain::Task>()) {
                    Utils::JobHandler::install(job, [this, task] {
                        m_taskRepository->dissociate(task);
                    });
                }
            }
            return true;
        }

        return false;
    };

    auto drag = [](const QObjectPtrList &) -> QMimeData* {
        return 0;
    };

    return new QueryTreeModel<QObjectPtr>(query, flags, data, setData, drop, drag, this);
}
<commit_msg>Fix drop of item on context<commit_after>/* This file is part of Zanshin

   Copyright 2014 Kevin Ottens <ervin@kde.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "availablepagesmodel.h"

#include <QIcon>
#include <QMimeData>

#include "domain/contextqueries.h"
#include "domain/contextrepository.h"
#include "domain/projectqueries.h"
#include "domain/projectrepository.h"
#include "domain/tag.h"
#include "domain/tagqueries.h"
#include "domain/tagrepository.h"
#include "domain/taskrepository.h"

#include "presentation/contextpagemodel.h"
#include "presentation/inboxpagemodel.h"
#include "presentation/metatypes.h"
#include "presentation/projectpagemodel.h"
#include "presentation/querytreemodel.h"
#include "presentation/tagpagemodel.h"

#include "utils/jobhandler.h"

using namespace Presentation;

AvailablePagesModel::AvailablePagesModel(Domain::ArtifactQueries *artifactQueries,
                                         Domain::ProjectQueries *projectQueries,
                                         Domain::ProjectRepository *projectRepository,
                                         Domain::ContextQueries *contextQueries,
                                         Domain::ContextRepository *contextRepository,
                                         Domain::TaskQueries *taskQueries,
                                         Domain::TaskRepository *taskRepository,
                                         Domain::NoteRepository *noteRepository,
                                         Domain::TagQueries *tagQueries,
                                         Domain::TagRepository *tagRepository,
                                         QObject *parent)
    : QObject(parent),
      m_pageListModel(0),
      m_artifactQueries(artifactQueries),
      m_projectQueries(projectQueries),
      m_projectRepository(projectRepository),
      m_contextQueries(contextQueries),
      m_contextRepository(contextRepository),
      m_taskQueries(taskQueries),
      m_taskRepository(taskRepository),
      m_noteRepository(noteRepository),
      m_tagQueries(tagQueries),
      m_tagRepository(tagRepository)
{
}

AvailablePagesModel::~AvailablePagesModel()
{
}

QAbstractItemModel *AvailablePagesModel::pageListModel()
{
    if (!m_pageListModel)
        m_pageListModel = createPageListModel();
    return m_pageListModel;
}

QObject *AvailablePagesModel::createPageForIndex(const QModelIndex &index)
{
    QObjectPtr object = index.data(QueryTreeModelBase::ObjectRole).value<QObjectPtr>();

    if (object == m_inboxObject) {
        return new InboxPageModel(m_artifactQueries,
                                  m_taskQueries, m_taskRepository,
                                  m_noteRepository,
                                  this);

    } else if (auto project = object.objectCast<Domain::Project>()) {
        return new ProjectPageModel(project,
                                    m_projectQueries,
                                    m_taskQueries, m_taskRepository,
                                    m_noteRepository,
                                    this);
    } else if (auto context = object.objectCast<Domain::Context>()) {
        return new ContextPageModel(context,
                                    m_contextQueries,
                                    m_taskQueries,
                                    m_taskRepository,
                                    m_noteRepository,
                                    this);
    } else if (auto tag = object.objectCast<Domain::Tag>()) {
        return new TagPageModel(tag,
                                m_tagQueries,
                                m_taskQueries,
                                m_taskRepository,
                                m_noteRepository,
                                this);
    }

    return 0;
}

void AvailablePagesModel::addProject(const QString &name, const Domain::DataSource::Ptr &source)
{
    auto project = Domain::Project::Ptr::create();
    project->setName(name);
    m_projectRepository->create(project, source);
}

void AvailablePagesModel::addContext(const QString &name)
{
    auto context = Domain::Context::Ptr::create();
    context->setName(name);
    m_contextRepository->create(context);
}

void AvailablePagesModel::addTag(const QString &name)
{
    auto tag = Domain::Tag::Ptr::create();
    tag->setName(name);
    m_tagRepository->create(tag);
}

void AvailablePagesModel::removeItem(const QModelIndex &index)
{
    QObjectPtr object = index.data(QueryTreeModelBase::ObjectRole).value<QObjectPtr>();
    if (auto project = object.objectCast<Domain::Project>()) {
        m_projectRepository->remove(project);
    } else if (auto context = object.objectCast<Domain::Context>()) {
        m_contextRepository->remove(context);
    } else if (auto tag = object.objectCast<Domain::Tag>()) {
        m_tagRepository->remove(tag);
    } else {
        Q_ASSERT(false);
    }
}

QAbstractItemModel *AvailablePagesModel::createPageListModel()
{
    m_inboxObject = QObjectPtr::create();
    m_inboxObject->setProperty("name", tr("Inbox"));
    m_projectsObject = QObjectPtr::create();
    m_projectsObject->setProperty("name", tr("Projects"));
    m_contextsObject = QObjectPtr::create();
    m_contextsObject->setProperty("name", tr("Contexts"));
    m_tagsObject = QObjectPtr::create();
    m_tagsObject->setProperty("name", tr("Tags"));

    m_rootsProvider = Domain::QueryResultProvider<QObjectPtr>::Ptr::create();
    m_rootsProvider->append(m_inboxObject);
    m_rootsProvider->append(m_projectsObject);
    m_rootsProvider->append(m_contextsObject);
    m_rootsProvider->append(m_tagsObject);

    auto query = [this](const QObjectPtr &object) -> Domain::QueryResultInterface<QObjectPtr>::Ptr {
        if (!object)
            return Domain::QueryResult<QObjectPtr>::create(m_rootsProvider);
        else if (object == m_projectsObject)
            return Domain::QueryResult<Domain::Project::Ptr, QObjectPtr>::copy(m_projectQueries->findAll());
        else if (object == m_contextsObject)
            return Domain::QueryResult<Domain::Context::Ptr, QObjectPtr>::copy(m_contextQueries->findAll());
        else if (object == m_tagsObject)
            return Domain::QueryResult<Domain::Tag::Ptr, QObjectPtr>::copy(m_tagQueries->findAll());
        else
            return Domain::QueryResult<QObjectPtr>::Ptr();
    };

    auto flags = [this](const QObjectPtr &object) {
        const Qt::ItemFlags defaultFlags = Qt::ItemIsSelectable
                                         | Qt::ItemIsEnabled
                                         | Qt::ItemIsEditable
                                         | Qt::ItemIsDropEnabled;
        const Qt::ItemFlags immutableNodeFlags = Qt::ItemIsSelectable
                                               | Qt::ItemIsEnabled
                                               | Qt::ItemIsDropEnabled;
        const Qt::ItemFlags structureNodeFlags = Qt::NoItemFlags;

        return object.objectCast<Domain::Project>() ? defaultFlags
             : object.objectCast<Domain::Context>() ? defaultFlags
             : object.objectCast<Domain::Tag>() ? defaultFlags
             : object == m_inboxObject ? immutableNodeFlags
             : structureNodeFlags;
    };

    auto data = [this](const QObjectPtr &object, int role) -> QVariant {
        if (role != Qt::DisplayRole
         && role != Qt::EditRole
         && role != Qt::DecorationRole
         && role != QueryTreeModelBase::IconNameRole) {
            return QVariant();
        }

        if (role == Qt::EditRole
         && (object == m_inboxObject
          || object == m_projectsObject
          || object == m_contextsObject
          || object == m_tagsObject)) {
            return QVariant();
        }

        if (role == Qt::DisplayRole || role == Qt::EditRole) {
            return object->property("name").toString();
        } else if (role == Qt::DecorationRole || role == QueryTreeModelBase::IconNameRole) {
            const QString iconName = object == m_inboxObject ? "mail-folder-inbox"
                                   : (object == m_projectsObject) ? "folder"
                                   : (object == m_contextsObject) ? "folder"
                                   : (object == m_tagsObject)     ? "folder"
                                   : "view-pim-tasks";

            if (role == Qt::DecorationRole)
                return QVariant::fromValue(QIcon::fromTheme(iconName));
            else
                return iconName;
        } else {
            return QVariant();
        }
    };

    auto setData = [this](const QObjectPtr &object, const QVariant &value, int role) {
        if (role != Qt::EditRole) {
            return false;
        }

        if (object == m_inboxObject
         || object == m_projectsObject
         || object == m_contextsObject
         || object == m_tagsObject) {
            return false;
        }

        if (auto project = object.objectCast<Domain::Project>()) {
            project->setName(value.toString());
            m_projectRepository->update(project);
        } else if (auto context = object.objectCast<Domain::Context>()) {
            context->setName(value.toString());
            m_contextRepository->update(context);
        } else if (object.objectCast<Domain::Tag>()) {
            return false; // Tag renaming is NOT allowed
        } else {
            Q_ASSERT(false);
        }

        return true;
    };

    auto drop = [this](const QMimeData *mimeData, Qt::DropAction, const QObjectPtr &object) {
        if (!mimeData->hasFormat("application/x-zanshin-object"))
            return false;

        auto droppedArtifacts = mimeData->property("objects").value<Domain::Artifact::List>();
        if (droppedArtifacts.isEmpty())
            return false;

        if (auto project = object.objectCast<Domain::Project>()) {
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                m_projectRepository->associate(project, droppedArtifact);
            }
            return true;
        } else if (auto context = object.objectCast<Domain::Context>()) {
            if (std::any_of(droppedArtifacts.begin(), droppedArtifacts.end(),
                            [](const Domain::Artifact::Ptr &droppedArtifact) {
                                return !droppedArtifact.objectCast<Domain::Task>();
                            })) {
                return false;
            }
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                auto task = droppedArtifact.staticCast<Domain::Task>();
                m_contextRepository->associate(context, task);
            }
            return true;
        } else if (auto tag = object.objectCast<Domain::Tag>()) {
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                m_tagRepository->associate(tag, droppedArtifact);
            }
            return true;
        } else if (object == m_inboxObject) {
            foreach (const auto &droppedArtifact, droppedArtifacts) {
                auto job = m_projectRepository->dissociate(droppedArtifact);
                if (auto task = droppedArtifact.objectCast<Domain::Task>()) {
                    Utils::JobHandler::install(job, [this, task] {
                        m_taskRepository->dissociate(task);
                    });
                }
            }
            return true;
        }

        return false;
    };

    auto drag = [](const QObjectPtrList &) -> QMimeData* {
        return 0;
    };

    return new QueryTreeModel<QObjectPtr>(query, flags, data, setData, drop, drag, this);
}
<|endoftext|>


<commit_before>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 * $Log$
 * Revision 1.6  2004/04/15 14:00:31  strk
 * Added new cleanup to Unload::Release
 *
 * Revision 1.5  2004/04/01 10:44:34  ybychkov
 * All "geom" classes from JTS 1.3 upgraded to JTS 1.4
 *
 * Revision 1.4  2004/03/29 06:59:25  ybychkov
 * "noding/snapround" package ported (JTS 1.4);
 * "operation", "operation/valid", "operation/relate" and "operation/overlay" upgraded to JTS 1.4;
 * "geom" partially upgraded.
 *
 * Revision 1.3  2004/03/19 09:48:46  ybychkov
 * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4
 *
 * Revision 1.2  2003/11/07 01:23:42  pramsey
 * Add standard CVS headers licence notices and copyrights to all cpp and h
 * files.
 *
 *
 **********************************************************************/

#include "../headers/unload.h"
#include "../headers/opValid.h"
#include "../headers/geomgraph.h"
#include "../headers/operation.h"
#include "../headers/opRelate.h"
#include "../headers/indexQuadtree.h"
#include "../headers/opBuffer.h"

namespace geos {

Unload::Unload(void)
{
}

Unload::~Unload(void)
{
}

void Unload::Release()
{
	delete CoordinateListFactory::internalFactory;
	delete Geometry::geometryChangedFilter;
	delete PlanarGraph::cga;
	delete GeometryGraphOperation::cga;
	delete GeometryGraphOperation::li;
	delete RelateComputer::li;
	delete RelateComputer::ptLocator;
	delete QuadTreeRoot::origin;
	delete PrecisionModel::FIXED;
	delete PrecisionModel::FLOATING;
	delete PrecisionModel::FLOATING_SINGLE;
	delete PrecisionModel::Type::nameToTypeMap;
	delete Geometry::geometryChangedFilter;
	delete Geometry::INTERNAL_GEOMETRY_FACTORY;
	delete BufferBuilder::cga;
}
}
<commit_msg>Commented out deletion that seems to cause segfaults<commit_after>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 * $Log$
 * Revision 1.7  2004/04/15 15:11:38  strk
 * Commented out deletion that seems to cause segfaults
 *
 * Revision 1.6  2004/04/15 14:00:31  strk
 * Added new cleanup to Unload::Release
 *
 * Revision 1.5  2004/04/01 10:44:34  ybychkov
 * All "geom" classes from JTS 1.3 upgraded to JTS 1.4
 *
 * Revision 1.4  2004/03/29 06:59:25  ybychkov
 * "noding/snapround" package ported (JTS 1.4);
 * "operation", "operation/valid", "operation/relate" and "operation/overlay" upgraded to JTS 1.4;
 * "geom" partially upgraded.
 *
 * Revision 1.3  2004/03/19 09:48:46  ybychkov
 * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4
 *
 * Revision 1.2  2003/11/07 01:23:42  pramsey
 * Add standard CVS headers licence notices and copyrights to all cpp and h
 * files.
 *
 *
 **********************************************************************/

#include "../headers/unload.h"
#include "../headers/opValid.h"
#include "../headers/geomgraph.h"
#include "../headers/operation.h"
#include "../headers/opRelate.h"
#include "../headers/indexQuadtree.h"
#include "../headers/opBuffer.h"

namespace geos {

Unload::Unload(void)
{
}

Unload::~Unload(void)
{
}

void Unload::Release()
{
	delete CoordinateListFactory::internalFactory;
	delete Geometry::geometryChangedFilter;
	delete PlanarGraph::cga;
	delete GeometryGraphOperation::cga;
	delete GeometryGraphOperation::li;
	delete RelateComputer::li;
	delete RelateComputer::ptLocator;
	delete QuadTreeRoot::origin;
	//delete PrecisionModel::FIXED;
	//delete PrecisionModel::FLOATING;
	//delete PrecisionModel::FLOATING_SINGLE;
	delete PrecisionModel::Type::nameToTypeMap;
	//delete Geometry::geometryChangedFilter;
	delete Geometry::INTERNAL_GEOMETRY_FACTORY;
	delete BufferBuilder::cga;
}
}
<|endoftext|>


<commit_before>#include "setupwizard_register.h"

#include "warnings-disable.h"

WARNINGS_DISABLE
#include <QDateTime>
#include <QFileDialog>

// This is used for QHostInfo::localHostName().  It could be replaced with
// QSysInfo::machineHostName() to remove the dependency on the Qt network
// library, but only if we require Qt 5.6+.
#include <QHostInfo>

#include "ui_setupwizard_register.h"
WARNINGS_ENABLE

#include <TSettings.h>
#include <TWizardPage.h>

#include "taskstatus.h"
#include "utils.h"

RegisterPage::RegisterPage(QWidget *parent)
    : TWizardPage(parent), _ui(new Ui::RegisterPage), _registering(No)
{
    _ui->setupUi(this);

    // Basic operations on this page.
    connect(_ui->createKeyfileButton, &QPushButton::clicked, this,
            &RegisterPage::createKeyfile);
    connect(_ui->useExistingKeyfileButton, &QPushButton::clicked, this,
            &RegisterPage::useExistingKeyfile);

    // A config field changed.
    connect(_ui->machineNameLineEdit, &QLineEdit::textChanged, this,
            &RegisterPage::checkComplete);
    connect(_ui->tarsnapUserLineEdit, &QLineEdit::textChanged, this,
            &RegisterPage::checkComplete);
    connect(_ui->tarsnapPasswordLineEdit, &QLineEdit::textChanged, this,
            &RegisterPage::checkComplete);
    connect(_ui->keyfilePathComboBrowse, &PathComboBrowse::textChanged, this,
            &RegisterPage::checkComplete);
}

RegisterPage::~RegisterPage()
{
    delete _ui;
}

void RegisterPage::initializePage()
{
    TWizardPage::initializePage();

    // Default machine name.
    _ui->machineNameLineEdit->setText(QHostInfo::localHostName());

    // Find any existing keys.
    TSettings settings;
    QString   appDataDir = settings.value("app/app_data", "").toString();
    for(const QFileInfo &file : Utils::findKeysInPath(appDataDir))
        _ui->keyfilePathComboBrowse->addItem(file.canonicalFilePath());

    // Auto-select "use existing" if we have any.
    if(_ui->keyfilePathComboBrowse->count() > 0)
        _ui->useExistingKeyfileButton->click();

    // Enable keyboard focus if we're ready to go.
    if(checkComplete())
        _ui->nextButton->setFocus();
}

void RegisterPage::createKeyfile()
{
    _ui->registerKeyStackedWidget->setCurrentWidget(_ui->createKeyfileSubpage);

    checkComplete();
}

void RegisterPage::useExistingKeyfile()
{
    _ui->registerKeyStackedWidget->setCurrentWidget(
        _ui->useExistingKeyfileSubpage);

    checkComplete();
}

bool RegisterPage::reportError(const QString &text)
{
    _ui->statusLabel->messageError(text);
    return false;
}

void RegisterPage::next()
{
    if(_registering == Done)
    {
        emit nextPage();
        return;
    }
    else
    {
        registerMachine();
    }
}

bool RegisterPage::checkComplete()
{
    _ui->statusLabel->clear();

    // Check mandatory fields (depending on which tab we're on).
    if(_ui->registerKeyStackedWidget->currentIndex() == CreateKeyfileTab)
    {
        if(_ui->machineNameLineEdit->text().isEmpty())
            return setProceedButton(false);

        if(_ui->tarsnapUserLineEdit->text().isEmpty())
            return setProceedButton(false);

        if(_ui->tarsnapPasswordLineEdit->text().isEmpty())
            return setProceedButton(false);
    }
    else
    {
        if(!checkKeyfile(_ui->keyfilePathComboBrowse->text()))
            return setProceedButton(false);
    }

    // Disable the button if we're already registering.
    if(_registering == Yes)
        return setProceedButton(false);
    else
        return setProceedButton(true);
}

void RegisterPage::registerMachine()
{
    TSettings settings;

    QString tarsnapKeyFile;
    QString appDataDir;

    // Sanity check app data dir.
    appDataDir = settings.value("app/app_data", "").toString();
    if(appDataDir.isEmpty())
    {
        // We should never get here, but handle the error anyway
        reportError("No app data dir set");
        checkComplete();
        return;
    }

    bool useExistingKeyfile = false;
    if(_ui->registerKeyStackedWidget->currentIndex() == CreateKeyfileTab)
    {
        _ui->statusLabel->messageNormal("Generating keyfile...");
        tarsnapKeyFile =
            appDataDir + QDir::separator() + _ui->machineNameLineEdit->text()
            + "-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")
            + ".key";
    }
    else
    {
        useExistingKeyfile = true;
        _ui->statusLabel->messageNormal("Verifying archive integrity...");
        tarsnapKeyFile = _ui->keyfilePathComboBrowse->text();
    }
    Q_ASSERT(!tarsnapKeyFile.isEmpty());

    settings.setValue("tarsnap/key", tarsnapKeyFile);
    settings.setValue("tarsnap/user", _ui->tarsnapUserLineEdit->text());

    if(checkComplete())
    {
        _registering = Yes;
        emit registerMachineRequested(_ui->tarsnapPasswordLineEdit->text(),
                                      _ui->machineNameLineEdit->text(),
                                      useExistingKeyfile);
    }
}

void RegisterPage::registerMachineResponse(TaskStatus status, QString reason)
{
    TSettings settings;

    // Get keyfile and sanity check.
    QString tarsnapKeyFile = settings.value("tarsnap/key", "").toString();
    if((status == TaskStatus::Completed) && (tarsnapKeyFile.isEmpty()))
    {
        // This should never happen.
        status = TaskStatus::Failed;
        reason = "No keyfile set";
    }

    switch(status)
    {
    case TaskStatus::Completed:
        _registering = Done;
        _ui->statusLabel->clear();
        emit next();
        break;
    case TaskStatus::Failed:
        reportError(reason);
        checkComplete();
        break;
    default:
        // We shouldn't receive anything else, so ignore it.
        break;
    }
}

bool RegisterPage::checkKeyfile(const QString &filename)
{
    // Bail if we don't have a filename.
    if(filename.isEmpty())
        return false;

    // Bail if the filename doesn't point to an existing readable file.
    QFileInfo machineKeyFile(filename);
    if(!(machineKeyFile.exists() && machineKeyFile.isFile()
         && machineKeyFile.isReadable()))
        return reportError("Invalid machine key");

    // File is ok.
    return true;
}

void RegisterPage::updateLoadingAnimation(bool idle)
{
    _ui->busyWidget->animate(!idle);
}
<commit_msg>RegisterPage: avoid unnecessary emit<commit_after>#include "setupwizard_register.h"

#include "warnings-disable.h"

WARNINGS_DISABLE
#include <QDateTime>
#include <QFileDialog>

// This is used for QHostInfo::localHostName().  It could be replaced with
// QSysInfo::machineHostName() to remove the dependency on the Qt network
// library, but only if we require Qt 5.6+.
#include <QHostInfo>

#include "ui_setupwizard_register.h"
WARNINGS_ENABLE

#include <TSettings.h>
#include <TWizardPage.h>

#include "taskstatus.h"
#include "utils.h"

RegisterPage::RegisterPage(QWidget *parent)
    : TWizardPage(parent), _ui(new Ui::RegisterPage), _registering(No)
{
    _ui->setupUi(this);

    // Basic operations on this page.
    connect(_ui->createKeyfileButton, &QPushButton::clicked, this,
            &RegisterPage::createKeyfile);
    connect(_ui->useExistingKeyfileButton, &QPushButton::clicked, this,
            &RegisterPage::useExistingKeyfile);

    // A config field changed.
    connect(_ui->machineNameLineEdit, &QLineEdit::textChanged, this,
            &RegisterPage::checkComplete);
    connect(_ui->tarsnapUserLineEdit, &QLineEdit::textChanged, this,
            &RegisterPage::checkComplete);
    connect(_ui->tarsnapPasswordLineEdit, &QLineEdit::textChanged, this,
            &RegisterPage::checkComplete);
    connect(_ui->keyfilePathComboBrowse, &PathComboBrowse::textChanged, this,
            &RegisterPage::checkComplete);
}

RegisterPage::~RegisterPage()
{
    delete _ui;
}

void RegisterPage::initializePage()
{
    TWizardPage::initializePage();

    // Default machine name.
    _ui->machineNameLineEdit->setText(QHostInfo::localHostName());

    // Find any existing keys.
    TSettings settings;
    QString   appDataDir = settings.value("app/app_data", "").toString();
    for(const QFileInfo &file : Utils::findKeysInPath(appDataDir))
        _ui->keyfilePathComboBrowse->addItem(file.canonicalFilePath());

    // Auto-select "use existing" if we have any.
    if(_ui->keyfilePathComboBrowse->count() > 0)
        _ui->useExistingKeyfileButton->click();

    // Enable keyboard focus if we're ready to go.
    if(checkComplete())
        _ui->nextButton->setFocus();
}

void RegisterPage::createKeyfile()
{
    _ui->registerKeyStackedWidget->setCurrentWidget(_ui->createKeyfileSubpage);

    checkComplete();
}

void RegisterPage::useExistingKeyfile()
{
    _ui->registerKeyStackedWidget->setCurrentWidget(
        _ui->useExistingKeyfileSubpage);

    checkComplete();
}

bool RegisterPage::reportError(const QString &text)
{
    _ui->statusLabel->messageError(text);
    return false;
}

void RegisterPage::next()
{
    if(_registering == Done)
    {
        emit nextPage();
        return;
    }
    else
    {
        registerMachine();
    }
}

bool RegisterPage::checkComplete()
{
    _ui->statusLabel->clear();

    // Check mandatory fields (depending on which tab we're on).
    if(_ui->registerKeyStackedWidget->currentIndex() == CreateKeyfileTab)
    {
        if(_ui->machineNameLineEdit->text().isEmpty())
            return setProceedButton(false);

        if(_ui->tarsnapUserLineEdit->text().isEmpty())
            return setProceedButton(false);

        if(_ui->tarsnapPasswordLineEdit->text().isEmpty())
            return setProceedButton(false);
    }
    else
    {
        if(!checkKeyfile(_ui->keyfilePathComboBrowse->text()))
            return setProceedButton(false);
    }

    // Disable the button if we're already registering.
    if(_registering == Yes)
        return setProceedButton(false);
    else
        return setProceedButton(true);
}

void RegisterPage::registerMachine()
{
    TSettings settings;

    QString tarsnapKeyFile;
    QString appDataDir;

    // Sanity check app data dir.
    appDataDir = settings.value("app/app_data", "").toString();
    if(appDataDir.isEmpty())
    {
        // We should never get here, but handle the error anyway
        reportError("No app data dir set");
        checkComplete();
        return;
    }

    bool useExistingKeyfile = false;
    if(_ui->registerKeyStackedWidget->currentIndex() == CreateKeyfileTab)
    {
        _ui->statusLabel->messageNormal("Generating keyfile...");
        tarsnapKeyFile =
            appDataDir + QDir::separator() + _ui->machineNameLineEdit->text()
            + "-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")
            + ".key";
    }
    else
    {
        useExistingKeyfile = true;
        _ui->statusLabel->messageNormal("Verifying archive integrity...");
        tarsnapKeyFile = _ui->keyfilePathComboBrowse->text();
    }
    Q_ASSERT(!tarsnapKeyFile.isEmpty());

    settings.setValue("tarsnap/key", tarsnapKeyFile);
    settings.setValue("tarsnap/user", _ui->tarsnapUserLineEdit->text());

    if(checkComplete())
    {
        _registering = Yes;
        emit registerMachineRequested(_ui->tarsnapPasswordLineEdit->text(),
                                      _ui->machineNameLineEdit->text(),
                                      useExistingKeyfile);
    }
}

void RegisterPage::registerMachineResponse(TaskStatus status, QString reason)
{
    TSettings settings;

    // Get keyfile and sanity check.
    QString tarsnapKeyFile = settings.value("tarsnap/key", "").toString();
    if((status == TaskStatus::Completed) && (tarsnapKeyFile.isEmpty()))
    {
        // This should never happen.
        status = TaskStatus::Failed;
        reason = "No keyfile set";
    }

    switch(status)
    {
    case TaskStatus::Completed:
        _registering = Done;
        _ui->statusLabel->clear();
        next();
        break;
    case TaskStatus::Failed:
        reportError(reason);
        checkComplete();
        break;
    default:
        // We shouldn't receive anything else, so ignore it.
        break;
    }
}

bool RegisterPage::checkKeyfile(const QString &filename)
{
    // Bail if we don't have a filename.
    if(filename.isEmpty())
        return false;

    // Bail if the filename doesn't point to an existing readable file.
    QFileInfo machineKeyFile(filename);
    if(!(machineKeyFile.exists() && machineKeyFile.isFile()
         && machineKeyFile.isReadable()))
        return reportError("Invalid machine key");

    // File is ok.
    return true;
}

void RegisterPage::updateLoadingAnimation(bool idle)
{
    _ui->busyWidget->animate(!idle);
}
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __MESOS_CONTAINERIZER_LAUNCH_HPP__
#define __MESOS_CONTAINERIZER_LAUNCH_HPP__

#include <string>

#include <stout/json.hpp>
#include <stout/option.hpp>
#include <stout/subcommand.hpp>

#include <mesos/mesos.hpp>

namespace mesos {
namespace internal {
namespace slave {

class MesosContainerizerLaunch : public Subcommand
{
public:
  static const std::string NAME;

  struct Flags : public virtual flags::FlagsBase
  {
    Flags();

    Option<JSON::Object> command;
    Option<JSON::Object> environment;
    Option<std::string> working_directory;
#ifndef __WINDOWS__
    Option<std::string> runtime_directory;
    Option<std::string> rootfs;
    Option<std::string> user;
    Option<RLimitInfo> rlimits;
#endif // __WINDOWS__
    Option<int> pipe_read;
    Option<int> pipe_write;
    Option<JSON::Array> pre_exec_commands;
#ifdef __linux__
    Option<CapabilityInfo> capabilities;
    Option<pid_t> namespace_mnt_target;
    bool unshare_namespace_mnt;
#endif // __linux__
  };

  static Flags prepare();

  MesosContainerizerLaunch() : Subcommand(NAME) {}

  Flags flags;

protected:
  virtual int execute();
  virtual flags::FlagsBase* getFlags() { return &flags; }
};

} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __MESOS_CONTAINERIZER_LAUNCH_HPP__
<commit_msg>Removed an unused function in launch helper.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __MESOS_CONTAINERIZER_LAUNCH_HPP__
#define __MESOS_CONTAINERIZER_LAUNCH_HPP__

#include <string>

#include <stout/json.hpp>
#include <stout/option.hpp>
#include <stout/subcommand.hpp>

#include <mesos/mesos.hpp>

namespace mesos {
namespace internal {
namespace slave {

class MesosContainerizerLaunch : public Subcommand
{
public:
  static const std::string NAME;

  struct Flags : public virtual flags::FlagsBase
  {
    Flags();

    Option<JSON::Object> command;
    Option<JSON::Object> environment;
    Option<std::string> working_directory;
#ifndef __WINDOWS__
    Option<std::string> runtime_directory;
    Option<std::string> rootfs;
    Option<std::string> user;
    Option<RLimitInfo> rlimits;
#endif // __WINDOWS__
    Option<int> pipe_read;
    Option<int> pipe_write;
    Option<JSON::Array> pre_exec_commands;
#ifdef __linux__
    Option<CapabilityInfo> capabilities;
    Option<pid_t> namespace_mnt_target;
    bool unshare_namespace_mnt;
#endif // __linux__
  };

  MesosContainerizerLaunch() : Subcommand(NAME) {}

  Flags flags;

protected:
  virtual int execute();
  virtual flags::FlagsBase* getFlags() { return &flags; }
};

} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __MESOS_CONTAINERIZER_LAUNCH_HPP__
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// backend_stats_context.cpp
//
// Identification: src/statistics/backend_stats_context.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <map>

#include "common/types.h"
#include "catalog/catalog.h"
#include "index/index.h"
#include "statistics/backend_stats_context.h"
#include "statistics/stats_aggregator.h"
#include "statistics/counter_metric.h"
#include "storage/database.h"
#include "storage/tile_group.h"

namespace peloton {
namespace stats {

CuckooMap<std::thread::id, std::shared_ptr<BackendStatsContext>>
    BackendStatsContext::stats_context_map_;

BackendStatsContext* BackendStatsContext::GetInstance() {

  // Each thread gets a backend stats context
  std::thread::id this_id = std::this_thread::get_id();
  std::shared_ptr<BackendStatsContext> result(nullptr);
  if (!stats_context_map_.Find(this_id, result)) {
    result.reset(new BackendStatsContext(LATENCY_MAX_HISTORY_THREAD, true));
    stats_context_map_.Insert(this_id, result);
  }
  return result.get();
}

BackendStatsContext::BackendStatsContext(size_t max_latency_history,
                                         bool regiser_to_aggregator)
    : txn_latencies_(LATENCY_METRIC, max_latency_history) {
  std::thread::id this_id = std::this_thread::get_id();
  thread_id_ = this_id;

  is_registered_to_aggregator_ = regiser_to_aggregator;

  // Register to the global aggregator
  if (regiser_to_aggregator == true)
    StatsAggregator::GetInstance().RegisterContext(thread_id_, this);
}

BackendStatsContext::~BackendStatsContext() {
  if (is_registered_to_aggregator_ == true)
    StatsAggregator::GetInstance().UnregisterContext(thread_id_);
}

//===--------------------------------------------------------------------===//
// ACCESSORS
//===--------------------------------------------------------------------===//

// Returns the table metric with the given database ID and table ID
TableMetric* BackendStatsContext::GetTableMetric(oid_t database_id,
                                                 oid_t table_id) {
  TableMetric::TableKey table_key = TableMetric::GetKey(database_id, table_id);
  if (table_metrics_.find(table_key) == table_metrics_.end()) {
    table_metrics_[table_key] = std::unique_ptr<TableMetric>(
        new TableMetric{TABLE_METRIC, database_id, table_id});
  }
  return table_metrics_[table_key].get();
}

// Returns the database metric with the given database ID
DatabaseMetric* BackendStatsContext::GetDatabaseMetric(oid_t database_id) {
  if (database_metrics_.find(database_id) == database_metrics_.end()) {
    database_metrics_[database_id] = std::unique_ptr<DatabaseMetric>(
        new DatabaseMetric{DATABASE_METRIC, database_id});
  }
  return database_metrics_[database_id].get();
}

// Returns the index metric with the given database ID, table ID, and
// index ID
IndexMetric* BackendStatsContext::GetIndexMetric(oid_t database_id,
                                                 oid_t table_id,
                                                 oid_t index_id) {
  IndexMetric::IndexKey index_key =
      IndexMetric::GetKey(database_id, table_id, index_id);
  if (index_metrics_.find(index_key) == index_metrics_.end()) {
    index_metrics_[index_key] = std::unique_ptr<IndexMetric>(
        new IndexMetric{INDEX_METRIC, database_id, table_id, index_id});
  }
  return index_metrics_[index_key].get();
}

LatencyMetric& BackendStatsContext::GetTxnLatencyMetric() {
  return txn_latencies_;
}

void BackendStatsContext::IncrementTableReads(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementReads();
}

void BackendStatsContext::IncrementTableInserts(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementInserts();
}

void BackendStatsContext::IncrementTableUpdates(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementUpdates();
}

void BackendStatsContext::IncrementTableDeletes(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementDeletes();
}

void BackendStatsContext::IncrementIndexReads(size_t read_count,
                                              index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementReads(read_count);
}

void BackendStatsContext::IncrementIndexInserts(
    index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementInserts();
}

void BackendStatsContext::IncrementIndexUpdates(
    index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementUpdates();
}

void BackendStatsContext::IncrementIndexDeletes(
    size_t delete_count, index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementDeletes(delete_count);
}

void BackendStatsContext::IncrementTxnCommitted(oid_t database_id) {
  auto database_metric = GetDatabaseMetric(database_id);
  PL_ASSERT(database_metric != nullptr);
  database_metric->IncrementTxnCommitted();
}

void BackendStatsContext::IncrementTxnAborted(oid_t database_id) {
  auto database_metric = GetDatabaseMetric(database_id);
  PL_ASSERT(database_metric != nullptr);
  database_metric->IncrementTxnAborted();
}

//===--------------------------------------------------------------------===//
// HELPER FUNCTIONS
//===--------------------------------------------------------------------===//

bool BackendStatsContext::operator==(const BackendStatsContext& other) {
  return database_metrics_ == other.database_metrics_ &&
         table_metrics_ == other.table_metrics_ &&
         index_metrics_ == other.index_metrics_;
}

bool BackendStatsContext::operator!=(const BackendStatsContext& other) {
  return !(*this == other);
}

void BackendStatsContext::Aggregate(BackendStatsContext& source) {
  // Aggregate all global metrics
  txn_latencies_.Aggregate(source.txn_latencies_);
  txn_latencies_.ComputeLatencies();

  // Aggregate all per-database metrics
  //  for (auto& database_item : database_metrics_) {
  //    auto worker_db_metric = source->GetDatabaseMetric(database_item.first);
  //    if (worker_db_metric != nullptr) {
  //      database_item.second->Aggregate(*worker_db_metric);
  //    }
  //  }
  for (auto& database_item : source.database_metrics_) {
    GetDatabaseMetric(database_item.first)->Aggregate(*database_item.second);
  }

  // Aggregate all per-table metrics
  //  for (auto& table_item : table_metrics_) {
  //    auto worker_table_metric = source->GetTableMetric(
  //        table_item.second->GetDatabaseId(),
  // table_item.second->GetTableId());
  //    if (worker_table_metric != nullptr) {
  //      table_item.second->Aggregate(*worker_table_metric);
  //    }
  //  }
  for (auto& table_item : source.table_metrics_) {
    GetTableMetric(table_item.second->GetDatabaseId(),
                   table_item.second->GetTableId())
        ->Aggregate(*table_item.second);
  }

  // Aggregate all per-index metrics
  //  for (auto& index_item : source.index_metrics_) {
  //    auto worker_index_metric = GetIndexMetric(
  //        index_item.second->GetDatabaseId(), index_item.second->GetTableId(),
  //        index_item.second->GetIndexId());
  //    if (worker_index_metric != nullptr) {
  //      index_item.second->Aggregate(*worker_index_metric);
  //    }
  //  }
  for (auto& index_item : source.index_metrics_) {
    GetIndexMetric(
        index_item.second->GetDatabaseId(), index_item.second->GetTableId(),
        index_item.second->GetIndexId())->Aggregate(*index_item.second);
  }
}

void BackendStatsContext::Reset() {
  txn_latencies_.Reset();

  for (auto& database_item : database_metrics_) {
    database_item.second->Reset();
  }
  for (auto& table_item : table_metrics_) {
    table_item.second->Reset();
  }
  for (auto& index_item : index_metrics_) {
    index_item.second->Reset();
  }

  oid_t num_databases = catalog::Catalog::GetInstance()->GetDatabaseCount();
  for (oid_t i = 0; i < num_databases; ++i) {
    auto database = catalog::Catalog::GetInstance()->GetDatabaseWithOffset(i);
    oid_t database_id = database->GetOid();

    // Reset database metrics
    if (database_metrics_.find(database_id) == database_metrics_.end()) {
      database_metrics_[database_id] = std::unique_ptr<DatabaseMetric>(
          new DatabaseMetric{DATABASE_METRIC, database_id});
    }

    // Reset table metrics
    oid_t num_tables = database->GetTableCount();
    for (oid_t j = 0; j < num_tables; ++j) {
      auto table = database->GetTable(j);
      oid_t table_id = table->GetOid();
      TableMetric::TableKey table_key =
          TableMetric::GetKey(database_id, table_id);

      if (table_metrics_.find(table_key) == table_metrics_.end()) {
        table_metrics_[table_key] = std::unique_ptr<TableMetric>(
            new TableMetric{TABLE_METRIC, database_id, table_id});
      }

      // Reset indexes metrics
      oid_t num_indexes = table->GetIndexCount();
      for (oid_t k = 0; k < num_indexes; ++k) {
        auto index = table->GetIndex(k);
        oid_t index_id = index->GetOid();
        IndexMetric::IndexKey index_key =
            IndexMetric::GetKey(database_id, table_id, index_id);

        if (index_metrics_.find(index_key) == index_metrics_.end()) {
          index_metrics_[index_key] = std::unique_ptr<IndexMetric>(
              new IndexMetric{INDEX_METRIC, database_id, table_id, index_id});
        }
      }
    }
  }
}

std::string BackendStatsContext::ToString() const {
  std::stringstream ss;

  ss << txn_latencies_.GetInfo() << std::endl;

  for (auto& database_item : database_metrics_) {
    oid_t database_id = database_item.second->GetDatabaseId();
    ss << database_item.second->GetInfo();

    for (auto& table_item : table_metrics_) {
      if (table_item.second->GetDatabaseId() == database_id) {
        ss << table_item.second->GetInfo();

        oid_t table_id = table_item.second->GetTableId();
        for (auto& index_item : index_metrics_) {
          if (index_item.second->GetDatabaseId() == database_id &&
              index_item.second->GetTableId() == table_id) {
            ss << index_item.second->GetInfo();
          }
        }
        if (!index_metrics_.empty()) {
          ss << std::endl;
        }
      }
      if (!table_metrics_.empty()) {
        ss << std::endl;
      }
    }
    if (!database_metrics_.empty()) {
      ss << std::endl;
    }
  }

  return ss.str();
}

}  // namespace stats
}  // namespace peloton
<commit_msg>disable stat context unregistration<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// backend_stats_context.cpp
//
// Identification: src/statistics/backend_stats_context.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <map>

#include "common/types.h"
#include "catalog/catalog.h"
#include "index/index.h"
#include "statistics/backend_stats_context.h"
#include "statistics/stats_aggregator.h"
#include "statistics/counter_metric.h"
#include "storage/database.h"
#include "storage/tile_group.h"

namespace peloton {
namespace stats {

CuckooMap<std::thread::id, std::shared_ptr<BackendStatsContext>>
    BackendStatsContext::stats_context_map_;

BackendStatsContext* BackendStatsContext::GetInstance() {

  // Each thread gets a backend stats context
  std::thread::id this_id = std::this_thread::get_id();
  std::shared_ptr<BackendStatsContext> result(nullptr);
  if (!stats_context_map_.Find(this_id, result)) {
    result.reset(new BackendStatsContext(LATENCY_MAX_HISTORY_THREAD, true));
    stats_context_map_.Insert(this_id, result);
  }
  return result.get();
}

BackendStatsContext::BackendStatsContext(size_t max_latency_history,
                                         bool regiser_to_aggregator)
    : txn_latencies_(LATENCY_METRIC, max_latency_history) {
  std::thread::id this_id = std::this_thread::get_id();
  thread_id_ = this_id;

  is_registered_to_aggregator_ = regiser_to_aggregator;

  // Register to the global aggregator
  if (regiser_to_aggregator == true)
    StatsAggregator::GetInstance().RegisterContext(thread_id_, this);
}

BackendStatsContext::~BackendStatsContext() {
  // TODO clean up aggregator backend context map when a thread exits
  //  if (is_registered_to_aggregator_ == true)
  //    StatsAggregator::GetInstance().UnregisterContext(thread_id_);
}

//===--------------------------------------------------------------------===//
// ACCESSORS
//===--------------------------------------------------------------------===//

// Returns the table metric with the given database ID and table ID
TableMetric* BackendStatsContext::GetTableMetric(oid_t database_id,
                                                 oid_t table_id) {
  TableMetric::TableKey table_key = TableMetric::GetKey(database_id, table_id);
  if (table_metrics_.find(table_key) == table_metrics_.end()) {
    table_metrics_[table_key] = std::unique_ptr<TableMetric>(
        new TableMetric{TABLE_METRIC, database_id, table_id});
  }
  return table_metrics_[table_key].get();
}

// Returns the database metric with the given database ID
DatabaseMetric* BackendStatsContext::GetDatabaseMetric(oid_t database_id) {
  if (database_metrics_.find(database_id) == database_metrics_.end()) {
    database_metrics_[database_id] = std::unique_ptr<DatabaseMetric>(
        new DatabaseMetric{DATABASE_METRIC, database_id});
  }
  return database_metrics_[database_id].get();
}

// Returns the index metric with the given database ID, table ID, and
// index ID
IndexMetric* BackendStatsContext::GetIndexMetric(oid_t database_id,
                                                 oid_t table_id,
                                                 oid_t index_id) {
  IndexMetric::IndexKey index_key =
      IndexMetric::GetKey(database_id, table_id, index_id);
  if (index_metrics_.find(index_key) == index_metrics_.end()) {
    index_metrics_[index_key] = std::unique_ptr<IndexMetric>(
        new IndexMetric{INDEX_METRIC, database_id, table_id, index_id});
  }
  return index_metrics_[index_key].get();
}

LatencyMetric& BackendStatsContext::GetTxnLatencyMetric() {
  return txn_latencies_;
}

void BackendStatsContext::IncrementTableReads(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementReads();
}

void BackendStatsContext::IncrementTableInserts(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementInserts();
}

void BackendStatsContext::IncrementTableUpdates(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementUpdates();
}

void BackendStatsContext::IncrementTableDeletes(oid_t tile_group_id) {
  oid_t table_id =
      catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetTableId();
  oid_t database_id = catalog::Manager::GetInstance()
                          .GetTileGroup(tile_group_id)
                          ->GetDatabaseId();
  auto table_metric = GetTableMetric(database_id, table_id);
  PL_ASSERT(table_metric != nullptr);
  table_metric->GetTableAccess().IncrementDeletes();
}

void BackendStatsContext::IncrementIndexReads(size_t read_count,
                                              index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementReads(read_count);
}

void BackendStatsContext::IncrementIndexInserts(
    index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementInserts();
}

void BackendStatsContext::IncrementIndexUpdates(
    index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementUpdates();
}

void BackendStatsContext::IncrementIndexDeletes(
    size_t delete_count, index::IndexMetadata* metadata) {
  oid_t index_id = metadata->GetOid();
  oid_t table_id = metadata->GetTableOid();
  oid_t database_id = metadata->GetDatabaseOid();
  auto index_metric = GetIndexMetric(database_id, table_id, index_id);
  PL_ASSERT(index_metric != nullptr);
  index_metric->GetIndexAccess().IncrementDeletes(delete_count);
}

void BackendStatsContext::IncrementTxnCommitted(oid_t database_id) {
  auto database_metric = GetDatabaseMetric(database_id);
  PL_ASSERT(database_metric != nullptr);
  database_metric->IncrementTxnCommitted();
}

void BackendStatsContext::IncrementTxnAborted(oid_t database_id) {
  auto database_metric = GetDatabaseMetric(database_id);
  PL_ASSERT(database_metric != nullptr);
  database_metric->IncrementTxnAborted();
}

//===--------------------------------------------------------------------===//
// HELPER FUNCTIONS
//===--------------------------------------------------------------------===//

bool BackendStatsContext::operator==(const BackendStatsContext& other) {
  return database_metrics_ == other.database_metrics_ &&
         table_metrics_ == other.table_metrics_ &&
         index_metrics_ == other.index_metrics_;
}

bool BackendStatsContext::operator!=(const BackendStatsContext& other) {
  return !(*this == other);
}

void BackendStatsContext::Aggregate(BackendStatsContext& source) {
  // Aggregate all global metrics
  txn_latencies_.Aggregate(source.txn_latencies_);
  txn_latencies_.ComputeLatencies();

  // Aggregate all per-database metrics
  //  for (auto& database_item : database_metrics_) {
  //    auto worker_db_metric = source->GetDatabaseMetric(database_item.first);
  //    if (worker_db_metric != nullptr) {
  //      database_item.second->Aggregate(*worker_db_metric);
  //    }
  //  }
  for (auto& database_item : source.database_metrics_) {
    GetDatabaseMetric(database_item.first)->Aggregate(*database_item.second);
  }

  // Aggregate all per-table metrics
  //  for (auto& table_item : table_metrics_) {
  //    auto worker_table_metric = source->GetTableMetric(
  //        table_item.second->GetDatabaseId(),
  // table_item.second->GetTableId());
  //    if (worker_table_metric != nullptr) {
  //      table_item.second->Aggregate(*worker_table_metric);
  //    }
  //  }
  for (auto& table_item : source.table_metrics_) {
    GetTableMetric(table_item.second->GetDatabaseId(),
                   table_item.second->GetTableId())
        ->Aggregate(*table_item.second);
  }

  // Aggregate all per-index metrics
  //  for (auto& index_item : source.index_metrics_) {
  //    auto worker_index_metric = GetIndexMetric(
  //        index_item.second->GetDatabaseId(), index_item.second->GetTableId(),
  //        index_item.second->GetIndexId());
  //    if (worker_index_metric != nullptr) {
  //      index_item.second->Aggregate(*worker_index_metric);
  //    }
  //  }
  for (auto& index_item : source.index_metrics_) {
    GetIndexMetric(
        index_item.second->GetDatabaseId(), index_item.second->GetTableId(),
        index_item.second->GetIndexId())->Aggregate(*index_item.second);
  }
}

void BackendStatsContext::Reset() {
  txn_latencies_.Reset();

  for (auto& database_item : database_metrics_) {
    database_item.second->Reset();
  }
  for (auto& table_item : table_metrics_) {
    table_item.second->Reset();
  }
  for (auto& index_item : index_metrics_) {
    index_item.second->Reset();
  }

  oid_t num_databases = catalog::Catalog::GetInstance()->GetDatabaseCount();
  for (oid_t i = 0; i < num_databases; ++i) {
    auto database = catalog::Catalog::GetInstance()->GetDatabaseWithOffset(i);
    oid_t database_id = database->GetOid();

    // Reset database metrics
    if (database_metrics_.find(database_id) == database_metrics_.end()) {
      database_metrics_[database_id] = std::unique_ptr<DatabaseMetric>(
          new DatabaseMetric{DATABASE_METRIC, database_id});
    }

    // Reset table metrics
    oid_t num_tables = database->GetTableCount();
    for (oid_t j = 0; j < num_tables; ++j) {
      auto table = database->GetTable(j);
      oid_t table_id = table->GetOid();
      TableMetric::TableKey table_key =
          TableMetric::GetKey(database_id, table_id);

      if (table_metrics_.find(table_key) == table_metrics_.end()) {
        table_metrics_[table_key] = std::unique_ptr<TableMetric>(
            new TableMetric{TABLE_METRIC, database_id, table_id});
      }

      // Reset indexes metrics
      oid_t num_indexes = table->GetIndexCount();
      for (oid_t k = 0; k < num_indexes; ++k) {
        auto index = table->GetIndex(k);
        oid_t index_id = index->GetOid();
        IndexMetric::IndexKey index_key =
            IndexMetric::GetKey(database_id, table_id, index_id);

        if (index_metrics_.find(index_key) == index_metrics_.end()) {
          index_metrics_[index_key] = std::unique_ptr<IndexMetric>(
              new IndexMetric{INDEX_METRIC, database_id, table_id, index_id});
        }
      }
    }
  }
}

std::string BackendStatsContext::ToString() const {
  std::stringstream ss;

  ss << txn_latencies_.GetInfo() << std::endl;

  for (auto& database_item : database_metrics_) {
    oid_t database_id = database_item.second->GetDatabaseId();
    ss << database_item.second->GetInfo();

    for (auto& table_item : table_metrics_) {
      if (table_item.second->GetDatabaseId() == database_id) {
        ss << table_item.second->GetInfo();

        oid_t table_id = table_item.second->GetTableId();
        for (auto& index_item : index_metrics_) {
          if (index_item.second->GetDatabaseId() == database_id &&
              index_item.second->GetTableId() == table_id) {
            ss << index_item.second->GetInfo();
          }
        }
        if (!index_metrics_.empty()) {
          ss << std::endl;
        }
      }
      if (!table_metrics_.empty()) {
        ss << std::endl;
      }
    }
    if (!database_metrics_.empty()) {
      ss << std::endl;
    }
  }

  return ss.str();
}

}  // namespace stats
}  // namespace peloton
<|endoftext|>


<commit_before>#include <cwchar>
#include <cstring>
#include "ExecElem_HttpHeader.h"
#include "LowDbAccess.h"
#include <windows.h>

ExecElem_HttpHeader::ExecElem_HttpHeader(int Id) : ExecElem(Id)
{
}

// Destructor
ExecElem_HttpHeader::~ExecElem_HttpHeader()
{
}

int ExecElem_HttpHeader::Execute()
{
	wchar_t tmp_http_header[1024];

	char presented_http_header[1024];
	char* presented_http_header_ptr = presented_http_header;

	int intput_bin = 0;
	bool http_header_del = false;
	bool http_header_add = false;
	size_t Result;
	LowDbAccess::GetInstance()->GetHttpHeaderInfo(ElementId, &intput_bin, tmp_http_header);
	wcstombs_s(&Result, presented_http_header, 1024,  tmp_http_header, 1024);
	if (intput_bin & 0x01) {
		http_header_del = true;
	}
	if (intput_bin & 0x02) {
		http_header_add = true;
	}

	char* data = (char*)GetData();
	char* data_ptr = data;
	char* data_end_ptr = (char*)data + GetDataLength();

	char* new_data = new char[10000000];
	char* new_data_ptr = new_data;

	if (http_header_del) {
		if (strncmp(data, "GET", 3) == 0 ||
			strncmp(data, "HEAD", 4) == 0 ||
			strncmp(data, "POST", 4) == 0 ||
			strncmp(data, "PUT", 3) == 0 ||
			strncmp(data, "DELETE", 6) == 0 ||
			strncmp(data, "CONNECT", 7) == 0 ||
			strncmp(data, "OPTIONS", 7) == 0 ||
			strncmp(data, "TRACE", 5) == 0 ||
			strncmp(data, "PATCH", 5) == 0) {
			for (data_ptr = data; data_ptr < data_end_ptr && strncmp(data_ptr, "\r\n\r\n", 4); data_ptr++);
			if (data_ptr == data_end_ptr) {
				for (data_ptr = data; data_ptr < data_end_ptr && strncmp(data_ptr, "\n\n", 2); data_ptr++);
				if (data_ptr == data_end_ptr) {
					data_ptr = data;
				} else {
					data_ptr += 2;
				}
			} else {
				data_ptr += 4;
			}
		}
	}
	if (http_header_add) {
		char* tmp_ptr = strstr(presented_http_header_ptr, "\r\n");
		while (tmp_ptr) {
			tmp_ptr += 2;
			if (strncmp(presented_http_header_ptr, "Date: <automatically replaced>\r\n", 32) == 0) {
				char date_work[128] = "";
				int date_work_len = 0;
				/***** Make time string begin *****/
				struct tm GmtTime;
				__int64 Ltime;
				_time64(&Ltime);
				_gmtime64_s(&GmtTime, &Ltime);
				char MonStr[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
				char WdayStr[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
				sprintf_s(date_work, 128, "Date: %s, %02d %s %d %02d:%02d:%02d GMT\r\n",
					WdayStr[GmtTime.tm_wday],
					GmtTime.tm_mday,
					MonStr[GmtTime.tm_mon],
					GmtTime.tm_year + 1900,
					GmtTime.tm_hour,
					GmtTime.tm_min,
					GmtTime.tm_sec);
				/***** Make time string end *****/
				date_work_len = strlen(date_work);
				if (new_data_ptr + date_work_len - new_data < 10000000 - 1) {
					strncpy_s(new_data_ptr, 10000000 - (new_data_ptr - new_data), date_work, date_work_len);
					new_data_ptr += date_work_len;
				}
			} else if (strncmp(presented_http_header_ptr, "Content-Length: <automatically replaced>\r\n", 42) == 0) {
				char cont_len_work[128] = "";
				int cont_len_work_len = 0;
				sprintf_s(cont_len_work, 128, "Content-Length: %d\r\n", data_end_ptr - data_ptr);
				cont_len_work_len = strlen(cont_len_work);
				if (new_data_ptr + cont_len_work_len - new_data < 10000000 - 1) {
					strncpy_s(new_data_ptr, 10000000 - (new_data_ptr - new_data), cont_len_work, cont_len_work_len);
					new_data_ptr += cont_len_work_len;
				}
			} else {
				for (char* i = presented_http_header_ptr; i < tmp_ptr; i++) {
					if (new_data_ptr - new_data + 1 < 10000000 - 1) {
						*new_data_ptr = *i;
						*new_data_ptr++;
					}
				}
			}

			presented_http_header_ptr = tmp_ptr;
			tmp_ptr = strstr(presented_http_header_ptr, "\r\n");
		}
		if (new_data_ptr - new_data + 2 < 10000000 - 1) {
			strncpy_s(new_data_ptr, 10000000 - (new_data_ptr - new_data), "\r\n", 2);
			new_data_ptr += 2;
		}
	}
	for (char* i = (char*)data_ptr; i < data_end_ptr; i++) {
		if (new_data_ptr - new_data + 1 < 10000000) {
			*new_data_ptr = *i;
			new_data_ptr++;
		}
	}
	delete data;
	SetData(new_data);
	SetDataLength(new_data_ptr - new_data);
	return 0;
}
<commit_msg>#53 : "HTTP/" checking code has been added.<commit_after>#include <cwchar>
#include <cstring>
#include "ExecElem_HttpHeader.h"
#include "LowDbAccess.h"
#include <windows.h>

ExecElem_HttpHeader::ExecElem_HttpHeader(int Id) : ExecElem(Id)
{
}

// Destructor
ExecElem_HttpHeader::~ExecElem_HttpHeader()
{
}

int ExecElem_HttpHeader::Execute()
{
	wchar_t tmp_http_header[1024];

	char presented_http_header[1024];
	char* presented_http_header_ptr = presented_http_header;

	int intput_bin = 0;
	bool http_header_del = false;
	bool http_header_add = false;
	size_t Result;
	LowDbAccess::GetInstance()->GetHttpHeaderInfo(ElementId, &intput_bin, tmp_http_header);
	wcstombs_s(&Result, presented_http_header, 1024,  tmp_http_header, 1024);
	if (intput_bin & 0x01) {
		http_header_del = true;
	}
	if (intput_bin & 0x02) {
		http_header_add = true;
	}

	char* data = (char*)GetData();
	char* data_ptr = data;
	char* data_end_ptr = (char*)data + GetDataLength();

	char* new_data = new char[10000000];
	char* new_data_ptr = new_data;

	if (http_header_del) {
		if (strncmp(data, "GET", 3) == 0 ||
			strncmp(data, "HEAD", 4) == 0 ||
			strncmp(data, "POST", 4) == 0 ||
			strncmp(data, "PUT", 3) == 0 ||
			strncmp(data, "DELETE", 6) == 0 ||
			strncmp(data, "CONNECT", 7) == 0 ||
			strncmp(data, "OPTIONS", 7) == 0 ||
			strncmp(data, "TRACE", 5) == 0 ||
			strncmp(data, "PATCH", 5) == 0 ||
			strncmp(data, "HTTP/", 5) == 0) {
			for (data_ptr = data; data_ptr < data_end_ptr && strncmp(data_ptr, "\r\n\r\n", 4); data_ptr++);
			if (data_ptr == data_end_ptr) {
				for (data_ptr = data; data_ptr < data_end_ptr && strncmp(data_ptr, "\n\n", 2); data_ptr++);
				if (data_ptr == data_end_ptr) {
					data_ptr = data;
				} else {
					data_ptr += 2;
				}
			} else {
				data_ptr += 4;
			}
		}
	}
	if (http_header_add) {
		char* tmp_ptr = strstr(presented_http_header_ptr, "\r\n");
		while (tmp_ptr) {
			tmp_ptr += 2;
			if (strncmp(presented_http_header_ptr, "Date: <automatically replaced>\r\n", 32) == 0) {
				char date_work[128] = "";
				int date_work_len = 0;
				/***** Make time string begin *****/
				struct tm GmtTime;
				__int64 Ltime;
				_time64(&Ltime);
				_gmtime64_s(&GmtTime, &Ltime);
				char MonStr[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
				char WdayStr[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
				sprintf_s(date_work, 128, "Date: %s, %02d %s %d %02d:%02d:%02d GMT\r\n",
					WdayStr[GmtTime.tm_wday],
					GmtTime.tm_mday,
					MonStr[GmtTime.tm_mon],
					GmtTime.tm_year + 1900,
					GmtTime.tm_hour,
					GmtTime.tm_min,
					GmtTime.tm_sec);
				/***** Make time string end *****/
				date_work_len = strlen(date_work);
				if (new_data_ptr + date_work_len - new_data < 10000000 - 1) {
					strncpy_s(new_data_ptr, 10000000 - (new_data_ptr - new_data), date_work, date_work_len);
					new_data_ptr += date_work_len;
				}
			} else if (strncmp(presented_http_header_ptr, "Content-Length: <automatically replaced>\r\n", 42) == 0) {
				char cont_len_work[128] = "";
				int cont_len_work_len = 0;
				sprintf_s(cont_len_work, 128, "Content-Length: %d\r\n", data_end_ptr - data_ptr);
				cont_len_work_len = strlen(cont_len_work);
				if (new_data_ptr + cont_len_work_len - new_data < 10000000 - 1) {
					strncpy_s(new_data_ptr, 10000000 - (new_data_ptr - new_data), cont_len_work, cont_len_work_len);
					new_data_ptr += cont_len_work_len;
				}
			} else {
				for (char* i = presented_http_header_ptr; i < tmp_ptr; i++) {
					if (new_data_ptr - new_data + 1 < 10000000 - 1) {
						*new_data_ptr = *i;
						*new_data_ptr++;
					}
				}
			}

			presented_http_header_ptr = tmp_ptr;
			tmp_ptr = strstr(presented_http_header_ptr, "\r\n");
		}
		if (new_data_ptr - new_data + 2 < 10000000 - 1) {
			strncpy_s(new_data_ptr, 10000000 - (new_data_ptr - new_data), "\r\n", 2);
			new_data_ptr += 2;
		}
	}
	for (char* i = (char*)data_ptr; i < data_end_ptr; i++) {
		if (new_data_ptr - new_data + 1 < 10000000) {
			*new_data_ptr = *i;
			new_data_ptr++;
		}
	}
	delete data;
	SetData(new_data);
	SetDataLength(new_data_ptr - new_data);
	return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <fstream>

#include <boost/optional.hpp>
#include <boost/filesystem.hpp>

#include <supermarx/util/downloader.hpp>
#include <supermarx/util/base16.hpp>

#include <boost/lexical_cast.hpp>
#include <boost/crc.hpp>

namespace supermarx
{

class cached_downloader
{
	downloader dl;
	boost::optional<std::string> cache_path;

	std::string mangle_url(std::string const& url)
	{
		static constexpr size_t max_length = 128;

		std::string result = url;

		for(char c : {'/', ':', '?', ','})
			std::replace(result.begin(), result.end(), c, '-');

		if(result.size() > max_length)
		{
			boost::crc_32_type crc;
			crc.process_bytes(url.c_str(), url.size());
			result.erase(result.begin()+max_length-9, result.end());
			result += "-" + base16::conv<uint32_t>(crc.checksum());
			std::cerr << result << std::endl;
		}

		return result;
	}

public:
	cached_downloader(const std::string& agent, unsigned int ratelimit = 0, boost::optional<std::string> _cache_path = boost::none)
		: dl(agent, ratelimit)
		, cache_path(_cache_path)
	{}

	downloader::response fetch(std::string const& url)
	{
		std::string mangled_url = mangle_url(url);

		if(!cache_path)
			return dl.fetch(url);

		boost::filesystem::path p(*cache_path);
		if(!boost::filesystem::is_directory(p))
			throw std::runtime_error("Cache path does not exist");

		p /= mangled_url;
		if(boost::filesystem::exists(p))
		{
			std::ifstream fin(p.generic_string(), std::ios::binary);
			return {200, std::string(std::istreambuf_iterator<char>(fin), std::istreambuf_iterator<char>())};
		}

		downloader::response response(dl.fetch(url));

		if(response.code != 200)
			throw downloader::error(std::string("Received HTTP code ") + boost::lexical_cast<std::string>(response.code));

		std::ofstream fout(p.generic_string(), std::ios::binary);
		fout << response.body;

		return {200, response.body}; // HTTP OK
	}
};

}
<commit_msg>Removed debugging code<commit_after>#pragma once

#include <fstream>

#include <boost/optional.hpp>
#include <boost/filesystem.hpp>

#include <supermarx/util/downloader.hpp>
#include <supermarx/util/base16.hpp>

#include <boost/lexical_cast.hpp>
#include <boost/crc.hpp>

namespace supermarx
{

class cached_downloader
{
	downloader dl;
	boost::optional<std::string> cache_path;

	std::string mangle_url(std::string const& url)
	{
		static constexpr size_t max_length = 128;

		std::string result = url;

		for(char c : {'/', ':', '?', ','})
			std::replace(result.begin(), result.end(), c, '-');

		if(result.size() > max_length)
		{
			boost::crc_32_type crc;
			crc.process_bytes(url.c_str(), url.size());
			result.erase(result.begin()+max_length-9, result.end());
			result += "-" + base16::conv<uint32_t>(crc.checksum());
		}

		return result;
	}

public:
	cached_downloader(const std::string& agent, unsigned int ratelimit = 0, boost::optional<std::string> _cache_path = boost::none)
		: dl(agent, ratelimit)
		, cache_path(_cache_path)
	{}

	downloader::response fetch(std::string const& url)
	{
		std::string mangled_url = mangle_url(url);

		if(!cache_path)
			return dl.fetch(url);

		boost::filesystem::path p(*cache_path);
		if(!boost::filesystem::is_directory(p))
			throw std::runtime_error("Cache path does not exist");

		p /= mangled_url;
		if(boost::filesystem::exists(p))
		{
			std::ifstream fin(p.generic_string(), std::ios::binary);
			return {200, std::string(std::istreambuf_iterator<char>(fin), std::istreambuf_iterator<char>())};
		}

		downloader::response response(dl.fetch(url));

		if(response.code != 200)
			throw downloader::error(std::string("Received HTTP code ") + boost::lexical_cast<std::string>(response.code));

		std::ofstream fout(p.generic_string(), std::ios::binary);
		fout << response.body;

		return {200, response.body}; // HTTP OK
	}
};

}
<|endoftext|>


<commit_before>#include <unit_test/unit_test.h>

#include <systemlib/hysteresis/hysteresis.h>

class HysteresisTest : public UnitTest
{
public:
	virtual bool run_tests(void);

private:
	bool _init_false();
	bool _init_true();
	bool _zero_case();
	bool _change_after_time();
	bool _hysteresis_changed();
	bool _change_after_multiple_sets();
	bool _take_change_back();
};

bool HysteresisTest::run_tests()
{
	ut_run_test(_init_false);
	ut_run_test(_init_true);
	ut_run_test(_zero_case);
	ut_run_test(_change_after_time);
	ut_run_test(_hysteresis_changed);
	ut_run_test(_change_after_multiple_sets);
	ut_run_test(_take_change_back);

	return (_tests_failed == 0);
}

bool HysteresisTest::_init_false()
{
	systemlib::Hysteresis hysteresis(false);
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_init_true()
{
	systemlib::Hysteresis hysteresis(true);
	ut_assert_true(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_zero_case()
{
	// Default is 0 hysteresis.
	systemlib::Hysteresis hysteresis(false);
	ut_assert_false(hysteresis.get_state());

	// Change and see result immediately.
	hysteresis.set_state_and_update(true);
	ut_assert_true(hysteresis.get_state());
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());
	hysteresis.set_state_and_update(true);
	ut_assert_true(hysteresis.get_state());

	// A wait won't change anything.
	usleep(1000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_change_after_time()
{
	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(false, 5000);
	hysteresis.set_hysteresis_time_from(true, 3000);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(4000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	usleep(2000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	// Change back to false.
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(1000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_hysteresis_changed()
{
	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(true, 2000);
	hysteresis.set_hysteresis_time_from(false, 5000);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	// Change hysteresis time.
	hysteresis.set_hysteresis_time_from(true, 10000);

	// Change back to false.
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(7000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());
	usleep(5000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_change_after_multiple_sets()
{
	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(true, 5000);
	hysteresis.set_hysteresis_time_from(false, 5000);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(true);
	ut_assert_true(hysteresis.get_state());

	// Change to false.
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_take_change_back()
{
	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(false, 5000);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	// Change your mind to false.
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());
	usleep(6000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());

	// And true again
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	// The other directory is immediate.
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());

	return true;
}

ut_declare_test_c(test_hysteresis, HysteresisTest)
<commit_msg>Hysteresis test: Fix for Mac OS CI<commit_after>#include <unit_test/unit_test.h>

#include <systemlib/hysteresis/hysteresis.h>

class HysteresisTest : public UnitTest
{
public:
	virtual bool run_tests(void);

private:
	bool _init_false();
	bool _init_true();
	bool _zero_case();
	bool _change_after_time();
	bool _hysteresis_changed();
	bool _change_after_multiple_sets();
	bool _take_change_back();
};

bool HysteresisTest::run_tests()
{
	ut_run_test(_init_false);
	ut_run_test(_init_true);
	ut_run_test(_zero_case);
	ut_run_test(_change_after_time);
	ut_run_test(_hysteresis_changed);
	ut_run_test(_change_after_multiple_sets);
	ut_run_test(_take_change_back);

	return (_tests_failed == 0);
}

bool HysteresisTest::_init_false()
{
	systemlib::Hysteresis hysteresis(false);
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_init_true()
{
	systemlib::Hysteresis hysteresis(true);
	ut_assert_true(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_zero_case()
{
	// Default is 0 hysteresis.
	systemlib::Hysteresis hysteresis(false);
	ut_assert_false(hysteresis.get_state());

	// Change and see result immediately.
	hysteresis.set_state_and_update(true);
	ut_assert_true(hysteresis.get_state());
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());
	hysteresis.set_state_and_update(true);
	ut_assert_true(hysteresis.get_state());

	// A wait won't change anything.
	usleep(1000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_change_after_time()
{
	int f = 1;

	// The CI system for Mac OS is not very fast
#ifdef __PX4_DARWIN
	f = 2;
#endif

	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(false, 5000 * f);
	hysteresis.set_hysteresis_time_from(true, 3000 * f);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(4000 * f);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	usleep(2000 * f);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	// Change back to false.
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(1000 * f);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());
	usleep(3000 * f);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_hysteresis_changed()
{
	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(true, 2000);
	hysteresis.set_hysteresis_time_from(false, 5000);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	// Change hysteresis time.
	hysteresis.set_hysteresis_time_from(true, 10000);

	// Change back to false.
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(7000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());
	usleep(5000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_change_after_multiple_sets()
{
	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(true, 5000);
	hysteresis.set_hysteresis_time_from(false, 5000);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(true);
	ut_assert_true(hysteresis.get_state());

	// Change to false.
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(false);
	ut_assert_true(hysteresis.get_state());
	usleep(3000);
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());

	return true;
}

bool HysteresisTest::_take_change_back()
{
	systemlib::Hysteresis hysteresis(false);
	hysteresis.set_hysteresis_time_from(false, 5000);

	// Change to true.
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	// Change your mind to false.
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());
	usleep(6000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());

	// And true again
	hysteresis.set_state_and_update(true);
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_false(hysteresis.get_state());
	usleep(3000);
	hysteresis.update();
	ut_assert_true(hysteresis.get_state());

	// The other directory is immediate.
	hysteresis.set_state_and_update(false);
	ut_assert_false(hysteresis.get_state());

	return true;
}

ut_declare_test_c(test_hysteresis, HysteresisTest)
<|endoftext|>