<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsoundeffect_p.h"

#if defined(QT_MULTIMEDIA_PULSEAUDIO)
#include "qsoundeffect_pulse_p.h"
#elif(QT_MULTIMEDIA_QMEDIAPLAYER)
#include "qsoundeffect_qmedia_p.h"
#else
#include "qsoundeffect_qsound_p.h"
#endif

QT_BEGIN_NAMESPACE

/*!
    \qmlclass SoundEffect QSoundEffect
    \brief The SoundEffect element provides a way to play sound effects in QML.

    This element is part of the \bold{QtMultimediaKit 1.1} module.

    The following example plays a wav file on mouse click.

    \qml
    import Qt 4.7
    import QtMultimediaKit 1.1

    Text {
        text: "Click Me!";
        font.pointSize: 24;
        width: 150; height: 50;

        SoundEffect {
            id: playSound
            source: "soundeffect.wav"
        }
        MouseArea {
            id: playArea
            anchors.fill: parent
            onPressed: { playSound.play() }
        }
    }
    \endqml
*/

/*!
    \qmlproperty url SoundEffect::source

    This property provides a way to control the sound to play.
*/

/*!
    \qmlproperty int SoundEffect::loops

    This property provides a way to control the number of times to repeat the sound on each play().

    Set to -1 (infinite) to enable infinite loop.
*/

/*!
    \qmlproperty int SoundEffect::volume

    This property holds the volume of the playback, from 0.0 (silent) to 1.0 (maximum volume).
*/

/*!
    \qmlproperty bool SoundEffect::muted

    This property provides a way to control muting.
*/

/*!
    \qmlproperty bool SoundEffect::playing

    This property indicates if the soundeffect is playing or not.
*/

/*!
    \qmlproperty int SoundEffect::status

    This property indicates the following status of the soundeffect.

    Null: no source has been set or is null.
    Loading: the soundeffect is trying to load the source.
    Ready: the source is loaded and ready for play.
    Error: some error happened during operation, such as failure of loading the source.
*/

/*!
    \qmlsignal SoundEffect::sourceChanged()

    This handler is called when the source has changed.
*/

/*!
    \qmlsignal SoundEffect::loopsChanged()

    This handler is called when the number of loops has changed.
*/

/*!
    \qmlsignal SoundEffect::volumeChanged()

    This handler is called when the volume has changed.
*/

/*!
    \qmlsignal SoundEffect::mutedChanged()

    This handler is called when the mute state has changed.
*/

/*!
    \qmlsignal SoundEffect::playingChanged()

    This handler is called when the playing property has changed.
*/

/*!
    \qmlsignal SoundEffect::statusChanged()

    This handler is called when the status property has changed.
*/

/*!
    \internal
*/

QSoundEffect::QSoundEffect(QObject *parent) :
    QObject(parent)
{
    d = new QSoundEffectPrivate(this);
    connect(d, SIGNAL(volumeChanged()), SIGNAL(volumeChanged()));
    connect(d, SIGNAL(mutedChanged()), SIGNAL(mutedChanged()));
    connect(d, SIGNAL(loadedChanged()), SIGNAL(loadedChanged()));
    connect(d, SIGNAL(playingChanged()), SIGNAL(playingChanged()));
    connect(d, SIGNAL(statusChanged()), SIGNAL(statusChanged()));
}

QSoundEffect::~QSoundEffect()
{
    d->deleteLater();
}

QStringList QSoundEffect::supportedMimeTypes()
{
    return QSoundEffectPrivate::supportedMimeTypes();
}

QUrl QSoundEffect::source() const
{
    return d->source();
}

void QSoundEffect::setSource(const QUrl &url)
{
    if (d->source() == url)
        return;

    d->setSource(url);

    emit sourceChanged();
}

int QSoundEffect::loopCount() const
{
    return d->loopCount();
}

void QSoundEffect::setLoopCount(int loopCount)
{
    if (loopCount < 0 && loopCount != Infinite) {
        qWarning("SoundEffect: loops should be SoundEffect.Infinite, 0 or positive integer");
        return;
    }
    if (loopCount == 0)
        loopCount = 1;
    if (d->loopCount() == loopCount)
        return;

    d->setLoopCount(loopCount);
    emit loopCountChanged();
}

qreal QSoundEffect::volume() const
{
    return qreal(d->volume()) / 100;
}

void QSoundEffect::setVolume(qreal volume)
{
    if (volume < 0 || volume > 1) {
        qWarning("SoundEffect: volume should be between 0.0 and 1.0");
        return;
    }
    int iVolume = qRound(volume * 100);
    if (d->volume() == iVolume)
        return;

    d->setVolume(iVolume);
    emit volumeChanged();
}

bool QSoundEffect::isMuted() const
{
    return d->isMuted();
}

void QSoundEffect::setMuted(bool muted)
{
    if (d->isMuted() == muted)
        return;

    d->setMuted(muted);
    emit mutedChanged();
}

bool QSoundEffect::isLoaded() const
{
    return d->isLoaded();
}

/*!
  \qmlmethod SoundEffect::play()

  Start playback of the sound effect, looping the effect for the number of
  times as specificed in the loops property.

  This is the default method for SoundEffect.

  \qml
  MouseArea {
      anchors.fill: parent
      onPressed: { SoundEffect { source:"soundeffect.wav" } }
  }
  \endqml
*/
void QSoundEffect::play()
{
    d->play();
}

bool QSoundEffect::isPlaying() const
{
    return d->isPlaying();
}

QSoundEffect::Status QSoundEffect::status() const
{
    return d->status();
}

/*!
  \qmlmethod SoundEffect::stop()

  Stop current playback.
  Note that if the backend is PulseAudio, due to the limitation of the underlying API,
  tis stop will only prevent next looping but will not be able to stop current playback immediately.

 */
void QSoundEffect::stop()
{
    d->stop();
}

QT_END_NAMESPACE

#include "moc_qsoundeffect_p.cpp"
<commit_msg>doc fix: volume is a qreal<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsoundeffect_p.h"

#if defined(QT_MULTIMEDIA_PULSEAUDIO)
#include "qsoundeffect_pulse_p.h"
#elif(QT_MULTIMEDIA_QMEDIAPLAYER)
#include "qsoundeffect_qmedia_p.h"
#else
#include "qsoundeffect_qsound_p.h"
#endif

QT_BEGIN_NAMESPACE

/*!
    \qmlclass SoundEffect QSoundEffect
    \brief The SoundEffect element provides a way to play sound effects in QML.

    This element is part of the \bold{QtMultimediaKit 1.1} module.

    The following example plays a wav file on mouse click.

    \qml
    import Qt 4.7
    import QtMultimediaKit 1.1

    Text {
        text: "Click Me!";
        font.pointSize: 24;
        width: 150; height: 50;

        SoundEffect {
            id: playSound
            source: "soundeffect.wav"
        }
        MouseArea {
            id: playArea
            anchors.fill: parent
            onPressed: { playSound.play() }
        }
    }
    \endqml
*/

/*!
    \qmlproperty url SoundEffect::source

    This property provides a way to control the sound to play.
*/

/*!
    \qmlproperty int SoundEffect::loops

    This property provides a way to control the number of times to repeat the sound on each play().

    Set to -1 (infinite) to enable infinite loop.
*/

/*!
    \qmlproperty qreal SoundEffect::volume

    This property holds the volume of the playback, from 0.0 (silent) to 1.0 (maximum volume).
*/

/*!
    \qmlproperty bool SoundEffect::muted

    This property provides a way to control muting.
*/

/*!
    \qmlproperty bool SoundEffect::playing

    This property indicates if the soundeffect is playing or not.
*/

/*!
    \qmlproperty int SoundEffect::status

    This property indicates the following status of the soundeffect.

    Null: no source has been set or is null.
    Loading: the soundeffect is trying to load the source.
    Ready: the source is loaded and ready for play.
    Error: some error happened during operation, such as failure of loading the source.
*/

/*!
    \qmlsignal SoundEffect::sourceChanged()

    This handler is called when the source has changed.
*/

/*!
    \qmlsignal SoundEffect::loopsChanged()

    This handler is called when the number of loops has changed.
*/

/*!
    \qmlsignal SoundEffect::volumeChanged()

    This handler is called when the volume has changed.
*/

/*!
    \qmlsignal SoundEffect::mutedChanged()

    This handler is called when the mute state has changed.
*/

/*!
    \qmlsignal SoundEffect::playingChanged()

    This handler is called when the playing property has changed.
*/

/*!
    \qmlsignal SoundEffect::statusChanged()

    This handler is called when the status property has changed.
*/

/*!
    \internal
*/

QSoundEffect::QSoundEffect(QObject *parent) :
    QObject(parent)
{
    d = new QSoundEffectPrivate(this);
    connect(d, SIGNAL(volumeChanged()), SIGNAL(volumeChanged()));
    connect(d, SIGNAL(mutedChanged()), SIGNAL(mutedChanged()));
    connect(d, SIGNAL(loadedChanged()), SIGNAL(loadedChanged()));
    connect(d, SIGNAL(playingChanged()), SIGNAL(playingChanged()));
    connect(d, SIGNAL(statusChanged()), SIGNAL(statusChanged()));
}

QSoundEffect::~QSoundEffect()
{
    d->deleteLater();
}

QStringList QSoundEffect::supportedMimeTypes()
{
    return QSoundEffectPrivate::supportedMimeTypes();
}

QUrl QSoundEffect::source() const
{
    return d->source();
}

void QSoundEffect::setSource(const QUrl &url)
{
    if (d->source() == url)
        return;

    d->setSource(url);

    emit sourceChanged();
}

int QSoundEffect::loopCount() const
{
    return d->loopCount();
}

void QSoundEffect::setLoopCount(int loopCount)
{
    if (loopCount < 0 && loopCount != Infinite) {
        qWarning("SoundEffect: loops should be SoundEffect.Infinite, 0 or positive integer");
        return;
    }
    if (loopCount == 0)
        loopCount = 1;
    if (d->loopCount() == loopCount)
        return;

    d->setLoopCount(loopCount);
    emit loopCountChanged();
}

qreal QSoundEffect::volume() const
{
    return qreal(d->volume()) / 100;
}

void QSoundEffect::setVolume(qreal volume)
{
    if (volume < 0 || volume > 1) {
        qWarning("SoundEffect: volume should be between 0.0 and 1.0");
        return;
    }
    int iVolume = qRound(volume * 100);
    if (d->volume() == iVolume)
        return;

    d->setVolume(iVolume);
    emit volumeChanged();
}

bool QSoundEffect::isMuted() const
{
    return d->isMuted();
}

void QSoundEffect::setMuted(bool muted)
{
    if (d->isMuted() == muted)
        return;

    d->setMuted(muted);
    emit mutedChanged();
}

bool QSoundEffect::isLoaded() const
{
    return d->isLoaded();
}

/*!
  \qmlmethod SoundEffect::play()

  Start playback of the sound effect, looping the effect for the number of
  times as specificed in the loops property.

  This is the default method for SoundEffect.

  \qml
  MouseArea {
      anchors.fill: parent
      onPressed: { SoundEffect { source:"soundeffect.wav" } }
  }
  \endqml
*/
void QSoundEffect::play()
{
    d->play();
}

bool QSoundEffect::isPlaying() const
{
    return d->isPlaying();
}

QSoundEffect::Status QSoundEffect::status() const
{
    return d->status();
}

/*!
  \qmlmethod SoundEffect::stop()

  Stop current playback.
  Note that if the backend is PulseAudio, due to the limitation of the underlying API,
  tis stop will only prevent next looping but will not be able to stop current playback immediately.

 */
void QSoundEffect::stop()
{
    d->stop();
}

QT_END_NAMESPACE

#include "moc_qsoundeffect_p.cpp"
<|endoftext|>


<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER 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 Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file nodeDisplayInfo.cpp
 * @author Geoff Lawler <Geoff.Lawler@cobham.com>
 * @date 2009-01-27
 */
#include <boost/foreach.hpp>
#include "singletonConfig.h"
#include "nodeDisplayInfo.h"
#include "colors.h"
#include "logger.h"

using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace watcher::colors;
using namespace libconfig;
using namespace boost;

INIT_LOGGER(NodeDisplayInfo, "DisplayInfo.NodeDisplayInfo");

NodeDisplayInfo::NodeDisplayInfo() :
    DisplayInfo("node"),
    shape(NodePropertiesMessage::CIRCLE),
    nodeProperties(),
    sparkle(false),
    spin(false),
    flash(false),
    size(1.0),
    spinTimeout(100),
    spinIncrement(5.0),
    spinRotation_x(0.0),
    spinRotation_y(0.0),
    spinRotation_z(0.0),
    flashInterval(500),
    nextFlashUpdate(0),
    isFlashed(false),
    label(NodeDisplayInfo::labelDefault2String(NodeDisplayInfo::LAST_OCTET)),
    labelFont("Helvetica"),
    labelPointSize(12.5),
    labelColor(blue),
    color(red)
{
    TRACE_ENTER();

    // create the "default" layer if it's not already there.
    loadConfiguration(layer);

    TRACE_EXIT();
}

// virtual
NodeDisplayInfo::~NodeDisplayInfo()
{
    TRACE_ENTER();
    TRACE_EXIT();
}

bool NodeDisplayInfo::loadConfiguration(const GUILayer &layer_, const NodeIdentifier &nid)
{
    TRACE_ENTER();

    // Convert nodeId into stupid string that libconfig can understand.
    // libconfig path ids cannot start with numbers or contain '.'
    // which is really annoying. So an id for node 192.168.1.123 ends up
    // looking like "node_192_168_1_123". Sigh.
    string nodeIdAsConfigId(categoryName);      // default node config is just under this.
    if (nid!=NodeIdentifier())
    {
        nodeId=nid;
        nodeIdAsConfigId+="_";
        string nodeIdAsString(nid.to_string());
        replace(nodeIdAsString.begin(), nodeIdAsString.end(), '.', '_');
        nodeIdAsConfigId+=nodeIdAsString;
    }

    LOG_DEBUG("Looking up and loading node props for node with id: \"" << nodeIdAsConfigId << "\"");
    categoryName=nodeIdAsConfigId;

    bool retVal=loadConfiguration(layer_);

    TRACE_EXIT_RET_BOOL(retVal);
    return retVal;
}

// virtual
bool NodeDisplayInfo::loadConfiguration(const GUILayer &layer_)
{
    TRACE_ENTER();

    layer=layer_.size()==0 ? PHYSICAL_LAYER : layer_;

    Config &cfg=SingletonConfig::instance();

    // "DisplayOptions.layer.[LAYERNAME].node_123_123_123_123"
    Setting &nodeSetting=cfg.lookup(getBasePath(layer));

    SingletonConfig::lock();

    try {

        string strVal, key;

        key="label";
        if (!nodeSetting.lookupValue(key, label))
            nodeSetting.add(key, Setting::TypeString)=label;

        strVal=color.toString();
        key="color";
        if (!nodeSetting.lookupValue(key, strVal))
            nodeSetting.add(key, Setting::TypeString)=strVal;
        color.fromString(strVal);

        strVal=NodePropertiesMessage::nodeShapeToString(NodePropertiesMessage::CIRCLE);
        key="shape";
        if (!nodeSetting.lookupValue(key, strVal))
            nodeSetting.add(key, Setting::TypeString)=strVal;
        NodePropertiesMessage::stringToNodeShape(strVal, shape);

        key="sparkle";
        if (!nodeSetting.lookupValue(key, sparkle))
            nodeSetting.add(key, Setting::TypeBoolean)=sparkle;

        key="spin";
        if (!nodeSetting.lookupValue(key, spin))
            nodeSetting.add(key, Setting::TypeBoolean)=spin;

        key="spinTimeout";
        if (!nodeSetting.lookupValue(key, spinTimeout))
            nodeSetting.add(key, Setting::TypeInt)=spinTimeout;

        key="spinIncrement";
        if (!nodeSetting.lookupValue(key, spinIncrement))
            nodeSetting.add(key, Setting::TypeFloat)=spinIncrement;

        key="flash";
        if (!nodeSetting.lookupValue(key, flash))
            nodeSetting.add(key, Setting::TypeBoolean)=flash;

        int intVal=(int)flashInterval;
        key="flashInterval";
        if (!nodeSetting.lookupValue(key, intVal))
            nodeSetting.add(key, Setting::TypeInt)=intVal;
        flashInterval=intVal;

        key="size";
        if (!nodeSetting.lookupValue(key, size))
            nodeSetting.add(key, Setting::TypeFloat)=size;

        key="labelFont";
        if (!nodeSetting.lookupValue(key, labelFont))
            nodeSetting.add(key, Setting::TypeString)=labelFont;

        key="labelPointSize";
        if (!nodeSetting.lookupValue(key, labelPointSize))
            nodeSetting.add(key, Setting::TypeFloat)=labelPointSize;

        strVal=blue.toString();
        key="labelColor";
        if (!nodeSetting.lookupValue(key, strVal))
            nodeSetting.add(key, Setting::TypeString)=strVal;
        labelColor.fromString(strVal);

    }
    catch (const SettingException &e) {
        LOG_ERROR("Error in configuration setting \"" << e.getPath() << "\"");
    }

    SingletonConfig::unlock();

    TRACE_EXIT_RET_BOOL(true);
    return true;
}

// static
string NodeDisplayInfo::labelDefault2String(const NodeDisplayInfo::LabelDefault &labDef)
{
    TRACE_ENTER();

    string retVal;
    switch(labDef)
    {
        case FOUR_OCTETS: retVal="fourOctets"; break;
        case THREE_OCTETS: retVal="threeOctets"; break;
        case TWO_OCTETS: retVal="twoOctets"; break;
        case LAST_OCTET: retVal="lastOctet"; break;
        case HOSTNAME: retVal="hostname"; break;
        case FREE_FORM: retVal=""; break;
    }
    TRACE_EXIT_RET(retVal);
    return retVal;
}

void NodeDisplayInfo::saveConfiguration()
{
    TRACE_ENTER();

    Config &cfg=SingletonConfig::instance();

    // "DisplayOptions.layer.[LAYERNAME].node"
    string basePath=getBasePath(layer);
    Setting &nodeSetting=cfg.lookup(basePath);

    SingletonConfig::lock();

    try {
        nodeSetting["label"]=label;
        nodeSetting["color"]=color.toString();
        nodeSetting["shape"]=NodePropertiesMessage::nodeShapeToString(shape);
        nodeSetting["sparkle"]=sparkle;
        nodeSetting["spin"]=spin;
        nodeSetting["spinTimeout"]=spinTimeout;
        nodeSetting["spinIncrement"]=spinIncrement;
        nodeSetting["flash"]=flash;
        nodeSetting["flashInterval"]=(int)flashInterval; // GTL loss of precision here.
        nodeSetting["size"]=size;
    }
    catch (const SettingException &e) {
        LOG_ERROR("Error in configuration setting \"" << e.getPath() << "\"");
    }

    SingletonConfig::unlock();
}

/**
 * Return the label for this node.  The NodeIdentifier for the associated node is passed in order to use the
 * IP address as a basis.
 * @param nodeId the node associated with this label
 * @return the label to use for this node
 */
std::string NodeDisplayInfo::get_label()
{
    // a little awkward since we're mixing enums, reserved strings, and free form strings
    if (!nodeId.is_v4())
        return nodeId.to_string(); //punt

    unsigned long addr = nodeId.to_v4().to_ulong(); // host byte order.
    char buf[64];

    if (label == NodeDisplayInfo::labelDefault2String(NodeDisplayInfo::FOUR_OCTETS))
        snprintf(buf, sizeof(buf), "%lu.%lu.%lu.%lu", ((addr)>>24)&0xFF,((addr)>>16)&0xFF,((addr)>>8)&0xFF,(addr)&0xFF);
    else if (label == labelDefault2String(NodeDisplayInfo::THREE_OCTETS))
        snprintf(buf, sizeof(buf), "%lu.%lu.%lu", ((addr)>>16)&0xFF,((addr)>>8)&0xFF,(addr)&0xFF);
    else if (label == labelDefault2String(NodeDisplayInfo::TWO_OCTETS))
        snprintf(buf, sizeof(buf), "%lu.%lu", ((addr)>>8)&0xFF,(addr)&0xFF);
    else if (label == labelDefault2String(NodeDisplayInfo::LAST_OCTET))
        snprintf(buf, sizeof(buf), "%lu", (addr)&0xFF);
    else if (label == "none")
        buf[0]='\0';
    else if (label == labelDefault2String(NodeDisplayInfo::HOSTNAME)) {
        in_addr saddr;
        saddr.s_addr = htonl(addr);
        hostent *he = gethostbyaddr((const void *)saddr.s_addr, sizeof(saddr.s_addr), AF_INET);
        if (he) {
            snprintf(buf, sizeof(buf), "%s", he->h_name);
            label = buf; // only do the lookup one time successfully per host.
        } else {
            LOG_WARN("Unable to get hostnmae for node " << nodeId);
            label = "UnableToGetHostNameSorry";
        }
        return label;
    } else
        return label;  // use what is ever there.

    return std::string(buf);
}
<commit_msg>0.0.0.0 is a valid, if non-sensical node id.<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER 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 Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file nodeDisplayInfo.cpp
 * @author Geoff Lawler <Geoff.Lawler@cobham.com>
 * @date 2009-01-27
 */
#include <boost/foreach.hpp>
#include "singletonConfig.h"
#include "nodeDisplayInfo.h"
#include "colors.h"
#include "logger.h"

using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace watcher::colors;
using namespace libconfig;
using namespace boost;

INIT_LOGGER(NodeDisplayInfo, "DisplayInfo.NodeDisplayInfo");

NodeDisplayInfo::NodeDisplayInfo() :
    DisplayInfo("node"),
    shape(NodePropertiesMessage::CIRCLE),
    nodeProperties(),
    sparkle(false),
    spin(false),
    flash(false),
    size(1.0),
    spinTimeout(100),
    spinIncrement(5.0),
    spinRotation_x(0.0),
    spinRotation_y(0.0),
    spinRotation_z(0.0),
    flashInterval(500),
    nextFlashUpdate(0),
    isFlashed(false),
    label(NodeDisplayInfo::labelDefault2String(NodeDisplayInfo::LAST_OCTET)),
    labelFont("Helvetica"),
    labelPointSize(12.5),
    labelColor(blue),
    color(red)
{
    TRACE_ENTER();

    // create the "default" layer if it's not already there.
    loadConfiguration(layer);

    TRACE_EXIT();
}

// virtual
NodeDisplayInfo::~NodeDisplayInfo()
{
    TRACE_ENTER();
    TRACE_EXIT();
}

bool NodeDisplayInfo::loadConfiguration(const GUILayer &layer_, const NodeIdentifier &nid)
{
    TRACE_ENTER();

    // Convert nodeId into stupid string that libconfig can understand.
    // libconfig path ids cannot start with numbers or contain '.'
    // which is really annoying. So an id for node 192.168.1.123 ends up
    // looking like "node_192_168_1_123". Sigh.
    string nodeIdAsConfigId(categoryName + "_");      // default node config is just under this.
    string nodeIdAsString(nid.to_string());
    replace(nodeIdAsString.begin(), nodeIdAsString.end(), '.', '_');
    nodeIdAsConfigId+=nodeIdAsString;

    nodeId=nid;

    LOG_DEBUG("Looking up and loading node props for node with id: \"" << nodeIdAsConfigId << "\"");
    categoryName=nodeIdAsConfigId;

    bool retVal=loadConfiguration(layer_);

    TRACE_EXIT_RET_BOOL(retVal);
    return retVal;
}

// virtual
bool NodeDisplayInfo::loadConfiguration(const GUILayer &layer_)
{
    TRACE_ENTER();

    layer=layer_.size()==0 ? PHYSICAL_LAYER : layer_;

    Config &cfg=SingletonConfig::instance();

    // "DisplayOptions.layer.[LAYERNAME].node_123_123_123_123"
    Setting &nodeSetting=cfg.lookup(getBasePath(layer));

    SingletonConfig::lock();

    try {

        string strVal, key;

        key="label";
        if (!nodeSetting.lookupValue(key, label))
            nodeSetting.add(key, Setting::TypeString)=label;

        strVal=color.toString();
        key="color";
        if (!nodeSetting.lookupValue(key, strVal))
            nodeSetting.add(key, Setting::TypeString)=strVal;
        color.fromString(strVal);

        strVal=NodePropertiesMessage::nodeShapeToString(NodePropertiesMessage::CIRCLE);
        key="shape";
        if (!nodeSetting.lookupValue(key, strVal))
            nodeSetting.add(key, Setting::TypeString)=strVal;
        NodePropertiesMessage::stringToNodeShape(strVal, shape);

        key="sparkle";
        if (!nodeSetting.lookupValue(key, sparkle))
            nodeSetting.add(key, Setting::TypeBoolean)=sparkle;

        key="spin";
        if (!nodeSetting.lookupValue(key, spin))
            nodeSetting.add(key, Setting::TypeBoolean)=spin;

        key="spinTimeout";
        if (!nodeSetting.lookupValue(key, spinTimeout))
            nodeSetting.add(key, Setting::TypeInt)=spinTimeout;

        key="spinIncrement";
        if (!nodeSetting.lookupValue(key, spinIncrement))
            nodeSetting.add(key, Setting::TypeFloat)=spinIncrement;

        key="flash";
        if (!nodeSetting.lookupValue(key, flash))
            nodeSetting.add(key, Setting::TypeBoolean)=flash;

        int intVal=(int)flashInterval;
        key="flashInterval";
        if (!nodeSetting.lookupValue(key, intVal))
            nodeSetting.add(key, Setting::TypeInt)=intVal;
        flashInterval=intVal;

        key="size";
        if (!nodeSetting.lookupValue(key, size))
            nodeSetting.add(key, Setting::TypeFloat)=size;

        key="labelFont";
        if (!nodeSetting.lookupValue(key, labelFont))
            nodeSetting.add(key, Setting::TypeString)=labelFont;

        key="labelPointSize";
        if (!nodeSetting.lookupValue(key, labelPointSize))
            nodeSetting.add(key, Setting::TypeFloat)=labelPointSize;

        strVal=blue.toString();
        key="labelColor";
        if (!nodeSetting.lookupValue(key, strVal))
            nodeSetting.add(key, Setting::TypeString)=strVal;
        labelColor.fromString(strVal);

    }
    catch (const SettingException &e) {
        LOG_ERROR("Error in configuration setting \"" << e.getPath() << "\"");
    }

    SingletonConfig::unlock();

    TRACE_EXIT_RET_BOOL(true);
    return true;
}

// static
string NodeDisplayInfo::labelDefault2String(const NodeDisplayInfo::LabelDefault &labDef)
{
    TRACE_ENTER();

    string retVal;
    switch(labDef)
    {
        case FOUR_OCTETS: retVal="fourOctets"; break;
        case THREE_OCTETS: retVal="threeOctets"; break;
        case TWO_OCTETS: retVal="twoOctets"; break;
        case LAST_OCTET: retVal="lastOctet"; break;
        case HOSTNAME: retVal="hostname"; break;
        case FREE_FORM: retVal=""; break;
    }
    TRACE_EXIT_RET(retVal);
    return retVal;
}

void NodeDisplayInfo::saveConfiguration()
{
    TRACE_ENTER();

    Config &cfg=SingletonConfig::instance();

    // "DisplayOptions.layer.[LAYERNAME].node"
    string basePath=getBasePath(layer);
    Setting &nodeSetting=cfg.lookup(basePath);

    SingletonConfig::lock();

    try {
        nodeSetting["label"]=label;
        nodeSetting["color"]=color.toString();
        nodeSetting["shape"]=NodePropertiesMessage::nodeShapeToString(shape);
        nodeSetting["sparkle"]=sparkle;
        nodeSetting["spin"]=spin;
        nodeSetting["spinTimeout"]=spinTimeout;
        nodeSetting["spinIncrement"]=spinIncrement;
        nodeSetting["flash"]=flash;
        nodeSetting["flashInterval"]=(int)flashInterval; // GTL loss of precision here.
        nodeSetting["size"]=size;
    }
    catch (const SettingException &e) {
        LOG_ERROR("Error in configuration setting \"" << e.getPath() << "\"");
    }

    SingletonConfig::unlock();
}

/**
 * Return the label for this node.  The NodeIdentifier for the associated node is passed in order to use the
 * IP address as a basis.
 * @param nodeId the node associated with this label
 * @return the label to use for this node
 */
std::string NodeDisplayInfo::get_label()
{
    // a little awkward since we're mixing enums, reserved strings, and free form strings
    if (!nodeId.is_v4())
        return nodeId.to_string(); //punt

    unsigned long addr = nodeId.to_v4().to_ulong(); // host byte order.
    char buf[64];

    if (label == NodeDisplayInfo::labelDefault2String(NodeDisplayInfo::FOUR_OCTETS))
        snprintf(buf, sizeof(buf), "%lu.%lu.%lu.%lu", ((addr)>>24)&0xFF,((addr)>>16)&0xFF,((addr)>>8)&0xFF,(addr)&0xFF);
    else if (label == labelDefault2String(NodeDisplayInfo::THREE_OCTETS))
        snprintf(buf, sizeof(buf), "%lu.%lu.%lu", ((addr)>>16)&0xFF,((addr)>>8)&0xFF,(addr)&0xFF);
    else if (label == labelDefault2String(NodeDisplayInfo::TWO_OCTETS))
        snprintf(buf, sizeof(buf), "%lu.%lu", ((addr)>>8)&0xFF,(addr)&0xFF);
    else if (label == labelDefault2String(NodeDisplayInfo::LAST_OCTET))
        snprintf(buf, sizeof(buf), "%lu", (addr)&0xFF);
    else if (label == "none")
        buf[0]='\0';
    else if (label == labelDefault2String(NodeDisplayInfo::HOSTNAME)) {
        in_addr saddr;
        saddr.s_addr = htonl(addr);
        hostent *he = gethostbyaddr((const void *)saddr.s_addr, sizeof(saddr.s_addr), AF_INET);
        if (he) {
            snprintf(buf, sizeof(buf), "%s", he->h_name);
            label = buf; // only do the lookup one time successfully per host.
        } else {
            LOG_WARN("Unable to get hostnmae for node " << nodeId);
            label = "UnableToGetHostNameSorry";
        }
        return label;
    } else
        return label;  // use what is ever there.

    return std::string(buf);
}
<|endoftext|>


<commit_before>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <string>
#include <map>

#include "constants.h"

std::map<std::string, std::string> defaultConf;
std::map<uint8, Drop> BLOCKDROPS;

void initConstants()
{
  // Init configuration
  defaultConf.insert(std::pair<std::string, std::string>("ip", "0.0.0.0"));
  defaultConf.insert(std::pair<std::string, std::string>("port", "25565"));
  defaultConf.insert(std::pair<std::string, std::string>("servername", "Minecraft server"));
  defaultConf.insert(std::pair<std::string, std::string>("mapdir", "testmap"));
  defaultConf.insert(std::pair<std::string, std::string>("userlimit", "20"));
  defaultConf.insert(std::pair<std::string, std::string>("map_release_time", "10"));
  defaultConf.insert(std::pair<std::string, std::string>("liquid_physics", "1"));
  defaultConf.insert(std::pair<std::string, std::string>("map_flatland", "false"));
  defaultConf.insert(std::pair<std::string, std::string>("oreDensity", "24"));
  defaultConf.insert(std::pair<std::string, std::string>("seaLevel", "63"));
  defaultConf.insert(std::pair<std::string, std::string>("server_full_message",
                                                         "Server is currently full"));
  defaultConf.insert(std::pair<std::string, std::string>("default_kick_message",
                                                         "You have been kicked"));
  defaultConf.insert(std::pair<std::string, std::string>("wrong_protocol_message",
                                                         "Wrong client protocol"));

  // Block drops (10000 = 100%)
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_STONE, Drop(BLOCK_COBBLESTONE, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_GRASS, Drop(BLOCK_DIRT, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_GRAVEL, Drop(ITEM_FLINT, 850, 1, false)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_COAL_ORE, Drop(ITEM_COAL, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_LEAVES, Drop(BLOCK_SAPLING, 1200, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_DIAMOND_ORE, Drop(ITEM_DIAMOND, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_REDSTONE_ORE, Drop(ITEM_REDSTONE, 10000, 4, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_CLAY, Drop(ITEM_CLAY_BALLS, 10000, 4, true)));

  // Blocks that drop nothing
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_TNT, Drop(BLOCK_TNT, 10000, 0, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_GLASS, Drop(BLOCK_GLASS, 10000, 0, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_MOB_SPAWNER, Drop(BLOCK_MOB_SPAWNER, 10000, 0, true)));

}<commit_msg>ban + whitelist<commit_after>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <string>
#include <map>

#include "constants.h"

std::map<std::string, std::string> defaultConf;
std::map<uint8, Drop> BLOCKDROPS;

void initConstants()
{
  // Init configuration
  defaultConf.insert(std::pair<std::string, std::string>("ip", "0.0.0.0"));
  defaultConf.insert(std::pair<std::string, std::string>("port", "25565"));
  defaultConf.insert(std::pair<std::string, std::string>("servername", "Minecraft server"));
  defaultConf.insert(std::pair<std::string, std::string>("use_whitelist", "false"));
  defaultConf.insert(std::pair<std::string, std::string>("mapdir", "testmap"));
  defaultConf.insert(std::pair<std::string, std::string>("userlimit", "20"));
  defaultConf.insert(std::pair<std::string, std::string>("map_release_time", "10"));
  defaultConf.insert(std::pair<std::string, std::string>("liquid_physics", "1"));
  defaultConf.insert(std::pair<std::string, std::string>("map_flatland", "false"));
  defaultConf.insert(std::pair<std::string, std::string>("oreDensity", "24"));
  defaultConf.insert(std::pair<std::string, std::string>("seaLevel", "63"));
  defaultConf.insert(std::pair<std::string, std::string>("server_full_message",
                                                         "Server is currently full"));
  defaultConf.insert(std::pair<std::string, std::string>("default_banned_message",
                                                         "You have been banned from this server"));
  defaultConf.insert(std::pair<std::string, std::string>("default_whitelist_message",
                                                         "You are not on the whitelist"));
  defaultConf.insert(std::pair<std::string, std::string>("default_kick_message",
                                                         "You have been kicked"));
  defaultConf.insert(std::pair<std::string, std::string>("wrong_protocol_message",
                                                         "Wrong client protocol"));

  // Block drops (10000 = 100%)
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_STONE, Drop(BLOCK_COBBLESTONE, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_GRASS, Drop(BLOCK_DIRT, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_GRAVEL, Drop(ITEM_FLINT, 850, 1, false)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_COAL_ORE, Drop(ITEM_COAL, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_LEAVES, Drop(BLOCK_SAPLING, 1200, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_DIAMOND_ORE, Drop(ITEM_DIAMOND, 10000, 1, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_REDSTONE_ORE, Drop(ITEM_REDSTONE, 10000, 4, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_CLAY, Drop(ITEM_CLAY_BALLS, 10000, 4, true)));

  // Blocks that drop nothing
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_TNT, Drop(BLOCK_TNT, 10000, 0, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_GLASS, Drop(BLOCK_GLASS, 10000, 0, true)));
  BLOCKDROPS.insert(std::pair<uint8, Drop>(BLOCK_MOB_SPAWNER, Drop(BLOCK_MOB_SPAWNER, 10000, 0, true)));

}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 * ddl_database.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/backend/bridge/ddl_database.cpp
 *
 *-------------------------------------------------------------------------
 */

#include "backend/bridge/ddl/ddl_database.h"
#include "backend/common/logger.h"
#include "backend/storage/database.h"

#include "nodes/parsenodes.h"
#include "commands/dbcommands.h"

namespace peloton {
namespace bridge {

//===--------------------------------------------------------------------===//
// Database DDL
//===--------------------------------------------------------------------===//

/**
 * @brief Execute the create db stmt.
 * @param the parse tree
 * @return true if we handled it correctly, false otherwise
 */
bool DDLDatabase::ExecCreatedbStmt(Node* parsetree){
  CreatedbStmt* stmt = (CreatedbStmt*) parsetree;
  DDLDatabase::CreateDatabase(stmt->database_id);
  return true;
}

/**
 * @brief Execute the drop db stmt.
 * @param the parse tree
 * @return true if we handled it correctly, false otherwise
 */
bool DDLDatabase::ExecDropdbStmt(Node* parsetree){
  DropdbStmt *stmt = (DropdbStmt *) parsetree;
  Oid database_oid = get_database_oid(stmt->dbname, stmt->missing_ok);
  DDLDatabase::DropDatabase(database_oid);
  return true;
}

/**
 * @brief Execute the vacuum stmt.
 * @param the parse tree
 * @return true if we handled it correctly, false otherwise
 */
bool DDLDatabase::ExecVacuumStmt(Node* parsetree){
  VacuumStmt* vacuum = (VacuumStmt*) parsetree;
  std::string relation_name = vacuum->relation->relname;

  // Get database oid
  oid_t database_oid = Bridge::GetCurrentDatabaseOid();

  // Get data table based on dabase oid and table name
  auto& manager = catalog::Manager::GetInstance();
  auto db = manager.GetDatabaseWithOid(database_oid);

  // Update every table and index
  if(relation_name.empty()){
    db->UpdateStats();
  }
  // Otherwise, update the specific table
  else{
    oid_t relation_oid = (db->GetTableWithName(relation_name))->GetOid();
    db->UpdateStatsWithOid(relation_oid);
  }

  return true;
}

/**
 * @brief Create database.
 * @param database_oid database id
 * @return true if we created a database, false otherwise
 */
bool DDLDatabase::CreateDatabase(Oid database_oid){
  if(database_oid == INVALID_OID)
    return false;

  auto& manager = catalog::Manager::GetInstance();
  storage::Database* db = new storage::Database(database_oid);
  manager.AddDatabase(db);

  if(db == nullptr){
    LOG_WARN("Failed to create a database (%u)", database_oid);
    return false;
  }

  LOG_INFO("Create database (%u)", database_oid);
  return true;
}

/**
 * @brief Drop database.
 * @param database_oid database id.
 * @return true if we dropped the database, false otherwise
 */
bool DDLDatabase::DropDatabase(Oid database_oid){
  auto& manager = catalog::Manager::GetInstance();
  manager.DropDatabaseWithOid(database_oid);

  LOG_INFO("Dropped database with oid : %u\n", database_oid);
  return true;
}

} // namespace bridge
} // namespace peloton

<commit_msg>Minor fix in vacuumming<commit_after>/*-------------------------------------------------------------------------
 *
 * ddl_database.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/backend/bridge/ddl_database.cpp
 *
 *-------------------------------------------------------------------------
 */

#include "backend/bridge/ddl/ddl_database.h"
#include "backend/common/logger.h"
#include "backend/storage/database.h"

#include "nodes/parsenodes.h"
#include "commands/dbcommands.h"

namespace peloton {
namespace bridge {

//===--------------------------------------------------------------------===//
// Database DDL
//===--------------------------------------------------------------------===//

/**
 * @brief Execute the create db stmt.
 * @param the parse tree
 * @return true if we handled it correctly, false otherwise
 */
bool DDLDatabase::ExecCreatedbStmt(Node* parsetree){
  CreatedbStmt* stmt = (CreatedbStmt*) parsetree;
  DDLDatabase::CreateDatabase(stmt->database_id);
  return true;
}

/**
 * @brief Execute the drop db stmt.
 * @param the parse tree
 * @return true if we handled it correctly, false otherwise
 */
bool DDLDatabase::ExecDropdbStmt(Node* parsetree){
  DropdbStmt *stmt = (DropdbStmt *) parsetree;
  Oid database_oid = get_database_oid(stmt->dbname, stmt->missing_ok);
  DDLDatabase::DropDatabase(database_oid);
  return true;
}

/**
 * @brief Execute the vacuum stmt.
 * @param the parse tree
 * @return true if we handled it correctly, false otherwise
 */
bool DDLDatabase::ExecVacuumStmt(Node* parsetree){
  VacuumStmt* vacuum = (VacuumStmt*) parsetree;
  std::string relation_name;

  if( vacuum->relation != NULL )
    relation_name = vacuum->relation->relname;

  // Get database oid
  oid_t database_oid = Bridge::GetCurrentDatabaseOid();

  // Get data table based on dabase oid and table name
  auto& manager = catalog::Manager::GetInstance();
  auto db = manager.GetDatabaseWithOid(database_oid);

  // Update every table and index
  if(relation_name.empty()){
    printf("Update All Stats\n");
    db->UpdateStats();
  }
  // Otherwise, update the specific table
  else{
    oid_t relation_oid = (db->GetTableWithName(relation_name))->GetOid();
    printf("Update table(%u) Stats\n",relation_oid );
    db->UpdateStatsWithOid(relation_oid);
  }

  return true;
}

/**
 * @brief Create database.
 * @param database_oid database id
 * @return true if we created a database, false otherwise
 */
bool DDLDatabase::CreateDatabase(Oid database_oid){
  if(database_oid == INVALID_OID)
    return false;

  auto& manager = catalog::Manager::GetInstance();
  storage::Database* db = new storage::Database(database_oid);
  manager.AddDatabase(db);

  if(db == nullptr){
    LOG_WARN("Failed to create a database (%u)", database_oid);
    return false;
  }

  LOG_INFO("Create database (%u)", database_oid);
  return true;
}

/**
 * @brief Drop database.
 * @param database_oid database id.
 * @return true if we dropped the database, false otherwise
 */
bool DDLDatabase::DropDatabase(Oid database_oid){
  auto& manager = catalog::Manager::GetInstance();
  manager.DropDatabaseWithOid(database_oid);

  LOG_INFO("Dropped database with oid : %u\n", database_oid);
  return true;
}

} // namespace bridge
} // namespace peloton

<|endoftext|>


<commit_before>//  illarionserver - server for the game Illarion
//  Copyright 2011 Illarion e.V.
//
//  This file is part of illarionserver.
//
//  illarionserver is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  illarionserver 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 Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with illarionserver.  If not, see <http://www.gnu.org/licenses/>.

#include "BasicServerCommand.hpp"

#include "BasicCommand.hpp"
#include "Logger.hpp"
#include "netinterface/NetInterface.hpp"

#include <algorithm>
#include <cassert>
#include <climits>
#include <iostream>

BasicServerCommand::BasicServerCommand(unsigned char defByte) : BasicCommand(defByte) {
    buffer.resize(baseBufferSize);
    initHeader();
}

BasicServerCommand::BasicServerCommand(unsigned char defByte, uint16_t bsize)
        : BasicCommand(defByte), baseBufferSize(bsize) {
    buffer.resize(baseBufferSize);
    initHeader();
}

void BasicServerCommand::initHeader() {
    addUnsignedCharToBuffer(getDefinitionByte());
    addUnsignedCharToBuffer(getDefinitionByte() xor UCHAR_MAX);
    addShortIntToBuffer(0); // dummy for the length
    addShortIntToBuffer(0); // dummy for the checksum
    checkSum = 0;           // reset checksum to 0, since the header is not included in checksum calculation
}

void BasicServerCommand::addHeader() {
    if (bufferPos >= headerSize) { // check if the buffer is large enough to add the data
        constexpr auto twoBytesSet = 0xFFFF;
        const auto crc = static_cast<int16_t>(checkSum % twoBytesSet);
        const auto dataSize = bufferPos - headerSize;

        buffer.at(lengthPosition) = (dataSize >> CHAR_BIT);
        buffer.at(lengthPosition + 1) = (dataSize & UCHAR_MAX);

        buffer.at(crcPosition) = (crc >> CHAR_BIT);
        buffer.at(crcPosition + 1) = (crc & UCHAR_MAX);
    }
}

auto BasicServerCommand::getLength() const -> int { return bufferPos; }

auto BasicServerCommand::cmdData() const -> const std::vector<char> & { return buffer; }

void BasicServerCommand::addStringToBuffer(const std::string &data) {
    auto count = static_cast<short int>(data.length());
    addShortIntToBuffer(count);
    std::for_each(data.cbegin(), data.cend(), [this](auto c) { addUnsignedCharToBuffer(c); });
}

void BasicServerCommand::addIntToBuffer(int data) {
    addUnsignedCharToBuffer((data >> 3 * CHAR_BIT));
    addUnsignedCharToBuffer(((data >> 2 * CHAR_BIT) & UCHAR_MAX));
    addUnsignedCharToBuffer(((data >> CHAR_BIT) & UCHAR_MAX));
    addUnsignedCharToBuffer((data & UCHAR_MAX));
}

void BasicServerCommand::addShortIntToBuffer(short int data) {
    addUnsignedCharToBuffer((data >> CHAR_BIT));
    addUnsignedCharToBuffer((data & UCHAR_MAX));
}

void BasicServerCommand::addUnsignedCharToBuffer(unsigned char data) {
    // resize the buffer if there is not enough place to store
    if ((bufferPos + 1) >= (bufferSizeMod * baseBufferSize)) {
        resizeBuffer();
    }

    assert(bufferPos < (bufferSizeMod * baseBufferSize));
    buffer.at(bufferPos) = data;
    checkSum += data; // add the data to the checksum
    bufferPos++;
}

void BasicServerCommand::resizeBuffer() {
    Logger::info(LogFacility::Other) << "Not enough memory. Resizing the send buffer. Current size: "
                                     << bufferSizeMod * baseBufferSize << " bytes." << Log::end;
    bufferSizeMod *= 2;
    buffer.resize(bufferSizeMod * baseBufferSize);
    Logger::info(LogFacility::Other) << "Resizing the send buffer successful. New size: "
                                     << bufferSizeMod * baseBufferSize << " bytes." << Log::end;
}

void BasicServerCommand::addColourToBuffer(const Colour &c) {
    addUnsignedCharToBuffer(c.red);
    addUnsignedCharToBuffer(c.green);
    addUnsignedCharToBuffer(c.blue);
    addUnsignedCharToBuffer(c.alpha);
}
<commit_msg>Avoid junk network traffic and RAM usage<commit_after>//  illarionserver - server for the game Illarion
//  Copyright 2011 Illarion e.V.
//
//  This file is part of illarionserver.
//
//  illarionserver is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  illarionserver 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 Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with illarionserver.  If not, see <http://www.gnu.org/licenses/>.

#include "BasicServerCommand.hpp"

#include "BasicCommand.hpp"
#include "Logger.hpp"
#include "netinterface/NetInterface.hpp"

#include <algorithm>
#include <cassert>
#include <climits>
#include <iostream>

BasicServerCommand::BasicServerCommand(unsigned char defByte) : BasicCommand(defByte) {
    buffer.resize(baseBufferSize);
    initHeader();
}

BasicServerCommand::BasicServerCommand(unsigned char defByte, uint16_t bsize)
        : BasicCommand(defByte), baseBufferSize(bsize) {
    buffer.resize(baseBufferSize);
    initHeader();
}

void BasicServerCommand::initHeader() {
    bufferPos = 0; // reset buffer position to 0 from previous use
    addUnsignedCharToBuffer(getDefinitionByte());
    addUnsignedCharToBuffer(getDefinitionByte() xor UCHAR_MAX);
    addShortIntToBuffer(0); // dummy for the length
    addShortIntToBuffer(0); // dummy for the checksum
    checkSum = 0;           // reset checksum to 0, since the header is not included in checksum calculation
}

void BasicServerCommand::addHeader() {
    if (bufferPos >= headerSize) { // check if the buffer is large enough to add the data
        constexpr auto twoBytesSet = 0xFFFF;
        const auto crc = static_cast<int16_t>(checkSum % twoBytesSet);
        const auto dataSize = bufferPos - headerSize;

        buffer.at(lengthPosition) = (dataSize >> CHAR_BIT);
        buffer.at(lengthPosition + 1) = (dataSize & UCHAR_MAX);

        buffer.at(crcPosition) = (crc >> CHAR_BIT);
        buffer.at(crcPosition + 1) = (crc & UCHAR_MAX);
    }
}

auto BasicServerCommand::getLength() const -> int { return bufferPos; }

auto BasicServerCommand::cmdData() const -> const std::vector<char> & { return buffer; }

void BasicServerCommand::addStringToBuffer(const std::string &data) {
    auto count = static_cast<short int>(data.length());
    addShortIntToBuffer(count);
    std::for_each(data.cbegin(), data.cend(), [this](auto c) { addUnsignedCharToBuffer(c); });
}

void BasicServerCommand::addIntToBuffer(int data) {
    addUnsignedCharToBuffer((data >> 3 * CHAR_BIT));
    addUnsignedCharToBuffer(((data >> 2 * CHAR_BIT) & UCHAR_MAX));
    addUnsignedCharToBuffer(((data >> CHAR_BIT) & UCHAR_MAX));
    addUnsignedCharToBuffer((data & UCHAR_MAX));
}

void BasicServerCommand::addShortIntToBuffer(short int data) {
    addUnsignedCharToBuffer((data >> CHAR_BIT));
    addUnsignedCharToBuffer((data & UCHAR_MAX));
}

void BasicServerCommand::addUnsignedCharToBuffer(unsigned char data) {
    // resize the buffer if there is not enough place to store
    if ((bufferPos + 1) >= (bufferSizeMod * baseBufferSize)) {
        resizeBuffer();
    }

    assert(bufferPos < (bufferSizeMod * baseBufferSize));
    buffer.at(bufferPos) = data;
    checkSum += data; // add the data to the checksum
    bufferPos++;
}

void BasicServerCommand::resizeBuffer() {
    Logger::info(LogFacility::Other) << "Not enough memory. Resizing the send buffer. Current size: "
                                     << bufferSizeMod * baseBufferSize << " bytes." << Log::end;
    bufferSizeMod *= 2;
    buffer.resize(bufferSizeMod * baseBufferSize);
    Logger::info(LogFacility::Other) << "Resizing the send buffer successful. New size: "
                                     << bufferSizeMod * baseBufferSize << " bytes." << Log::end;
}

void BasicServerCommand::addColourToBuffer(const Colour &c) {
    addUnsignedCharToBuffer(c.red);
    addUnsignedCharToBuffer(c.green);
    addUnsignedCharToBuffer(c.blue);
    addUnsignedCharToBuffer(c.alpha);
}
<|endoftext|>


<commit_before>/*
   This file is part of elemental, a library for distributed-memory dense
   linear algebra.

   Copyright (C) 2009-2010 Jack Poulson <jack.poulson@gmail.com>

   This program is released under the terms of the license contained in the
   file LICENSE.
*/
#include "elemental/environment.hpp"
#include "elemental/wrappers/mpi.hpp"
using namespace elemental;
using namespace std;

elemental::Grid::Grid
( MPI_Comm comm )
{
#ifndef RELEASE
    PushCallStack("Grid::Grid(comm)");
#endif

    // Extract the total number of processes
    MPI_Comm_size( comm, &_p );

    // Factor p
    int r = static_cast<int>(sqrt(static_cast<double>(_p)));
    while( _p % r != 0 )
        ++r;
    int c = _p / r;

    if( _p != r*c )
    {
        ostringstream msg;
        msg << "Number of processes must match grid size:" << endl
            << "  p=" << _p << ", (r,c)=(" << r << "," << c << ")" << endl;
        throw logic_error( msg.str() );
    }

    // Create cartesian communicator
    int dimensions[2] = { r,    c    };
    int periods[2]    = { true, true };
    int reorder       = false;
    MPI_Cart_create( comm, 2, dimensions, periods, reorder, &_comm );
    MPI_Comm_rank( _comm, &_rank  );

    Init( r, c );

#ifndef RELEASE
    PopCallStack();
#endif
}

// Currently forces a columnMajor absolute rank on the grid
elemental::Grid::Grid
( MPI_Comm comm, int r, int c )
{
#ifndef RELEASE
    PushCallStack("Grid::Grid( comm, r, c )");
#endif

    // Extract the total number of processes
    MPI_Comm_size( comm, &_p );

    if( _p != r*c )
    {
        ostringstream msg;
        msg << "Number of processes must match grid size:" << endl
            << "  p=" << _p << ", (r,c)=(" << r << "," << c << ")" << endl;
        throw logic_error( msg.str() );
    }

    // Create a cartesian communicator
    int dimensions[2] = { r,   c     };
    int periods[2]    = { true, true };
    int reorder       = false;
    MPI_Cart_create( comm, 2, dimensions, periods, reorder, &_comm );
    MPI_Comm_rank( _comm, &_rank );

    Init( r, c );

#ifndef RELEASE
    PopCallStack();
#endif
}

void
elemental::Grid::Init
( int r, int c )
{
#ifndef RELEASE
    PushCallStack("Grid::Init(r,c)");
    if( r <= 0 || c <= 0 )
        throw logic_error( "r and c must be positive." );
#endif
    _r = r;
    _c = c;

    _gcd = utilities::GCD( r, c );
    int lcm = _p / _gcd;

#ifndef RELEASE
    if( _rank == 0 )
    {
        cout << "Building process grid with:" << endl;
        cout << "  p=" << _p << ", (r,c)=(" << r << "," << c << ")" << endl;
        cout << "  gcd=" << _gcd << endl;
    }
#endif

    // Set up the MatrixCol and MatrixRow communicators
    int remainingDimensions[2];
    remainingDimensions[0] = true;
    remainingDimensions[1] = false;
    MPI_Cart_sub( _comm, remainingDimensions, &_matrixColComm );
    remainingDimensions[0] = false;
    remainingDimensions[1] = true;
    MPI_Cart_sub( _comm, remainingDimensions, &_matrixRowComm );
    MPI_Comm_rank( _matrixColComm, &_matrixColRank );
    MPI_Comm_rank( _matrixRowComm, &_matrixRowRank );

    // Set up the VectorCol and VectorRow communicators
    int dimensions[2];
    int periods[2];
    int coordinates[2];
    MPI_Cart_get( _comm, 2, dimensions, periods, coordinates );
    int colMajorRank = coordinates[0] + dimensions[0]*coordinates[1];
    int rowMajorRank = coordinates[1] + dimensions[1]*coordinates[0];
    MPI_Comm_split( _comm, 0, colMajorRank, &_vectorColComm );
    MPI_Comm_split( _comm, 0, rowMajorRank, &_vectorRowComm );
    MPI_Comm_rank( _vectorColComm, &_vectorColRank );
    MPI_Comm_rank( _vectorRowComm, &_vectorRowRank );

    // Compute which diagonal 'path' we're in, and what our rank is, then
    // perform AllGather world to store everyone's info
    _diagPathsAndRanks = new int[2*_p];
    int* myDiagPathAndRank = new int[2];
    myDiagPathAndRank[0] = (_matrixRowRank+r-_matrixColRank) % _gcd;
    int diagPathRank = 0;
    int row = 0;
    int col = myDiagPathAndRank[0];
    for( int j=0; j<lcm; ++j )
    {
        if( row == _matrixColRank && col == _matrixRowRank )
        {
            myDiagPathAndRank[1] = diagPathRank;
            break;
        }
        else
        {
            row = (row + 1) % r;
            col = (col + 1) % c;
            ++diagPathRank;
        }
    }
    wrappers::mpi::AllGather
    ( myDiagPathAndRank, 2, _diagPathsAndRanks, 2, _vectorColComm );
    delete myDiagPathAndRank;

#ifndef RELEASE
    MPI_Errhandler_set( _matrixColComm, MPI_ERRORS_RETURN );
    MPI_Errhandler_set( _matrixRowComm, MPI_ERRORS_RETURN );
    MPI_Errhandler_set( _vectorColComm, MPI_ERRORS_RETURN );
    MPI_Errhandler_set( _vectorRowComm, MPI_ERRORS_RETURN );
#endif

#ifndef RELEASE
    PopCallStack();
#endif
}

<commit_msg>Fixing mismatched new[]/delete with new[]/delete[] in Grid::Init.<commit_after>/*
   This file is part of elemental, a library for distributed-memory dense
   linear algebra.

   Copyright (C) 2009-2010 Jack Poulson <jack.poulson@gmail.com>

   This program is released under the terms of the license contained in the
   file LICENSE.
*/
#include "elemental/environment.hpp"
#include "elemental/wrappers/mpi.hpp"
using namespace elemental;
using namespace std;

elemental::Grid::Grid
( MPI_Comm comm )
{
#ifndef RELEASE
    PushCallStack("Grid::Grid(comm)");
#endif

    // Extract the total number of processes
    MPI_Comm_size( comm, &_p );

    // Factor p
    int r = static_cast<int>(sqrt(static_cast<double>(_p)));
    while( _p % r != 0 )
        ++r;
    int c = _p / r;

    if( _p != r*c )
    {
        ostringstream msg;
        msg << "Number of processes must match grid size:" << endl
            << "  p=" << _p << ", (r,c)=(" << r << "," << c << ")" << endl;
        throw logic_error( msg.str() );
    }

    // Create cartesian communicator
    int dimensions[2] = { r,    c    };
    int periods[2]    = { true, true };
    int reorder       = false;
    MPI_Cart_create( comm, 2, dimensions, periods, reorder, &_comm );
    MPI_Comm_rank( _comm, &_rank  );

    Init( r, c );

#ifndef RELEASE
    PopCallStack();
#endif
}

// Currently forces a columnMajor absolute rank on the grid
elemental::Grid::Grid
( MPI_Comm comm, int r, int c )
{
#ifndef RELEASE
    PushCallStack("Grid::Grid( comm, r, c )");
#endif

    // Extract the total number of processes
    MPI_Comm_size( comm, &_p );

    if( _p != r*c )
    {
        ostringstream msg;
        msg << "Number of processes must match grid size:" << endl
            << "  p=" << _p << ", (r,c)=(" << r << "," << c << ")" << endl;
        throw logic_error( msg.str() );
    }

    // Create a cartesian communicator
    int dimensions[2] = { r,   c     };
    int periods[2]    = { true, true };
    int reorder       = false;
    MPI_Cart_create( comm, 2, dimensions, periods, reorder, &_comm );
    MPI_Comm_rank( _comm, &_rank );

    Init( r, c );

#ifndef RELEASE
    PopCallStack();
#endif
}

void
elemental::Grid::Init
( int r, int c )
{
#ifndef RELEASE
    PushCallStack("Grid::Init(r,c)");
    if( r <= 0 || c <= 0 )
        throw logic_error( "r and c must be positive." );
#endif
    _r = r;
    _c = c;

    _gcd = utilities::GCD( r, c );
    int lcm = _p / _gcd;

#ifndef RELEASE
    if( _rank == 0 )
    {
        cout << "Building process grid with:" << endl;
        cout << "  p=" << _p << ", (r,c)=(" << r << "," << c << ")" << endl;
        cout << "  gcd=" << _gcd << endl;
    }
#endif

    // Set up the MatrixCol and MatrixRow communicators
    int remainingDimensions[2];
    remainingDimensions[0] = true;
    remainingDimensions[1] = false;
    MPI_Cart_sub( _comm, remainingDimensions, &_matrixColComm );
    remainingDimensions[0] = false;
    remainingDimensions[1] = true;
    MPI_Cart_sub( _comm, remainingDimensions, &_matrixRowComm );
    MPI_Comm_rank( _matrixColComm, &_matrixColRank );
    MPI_Comm_rank( _matrixRowComm, &_matrixRowRank );

    // Set up the VectorCol and VectorRow communicators
    int dimensions[2];
    int periods[2];
    int coordinates[2];
    MPI_Cart_get( _comm, 2, dimensions, periods, coordinates );
    int colMajorRank = coordinates[0] + dimensions[0]*coordinates[1];
    int rowMajorRank = coordinates[1] + dimensions[1]*coordinates[0];
    MPI_Comm_split( _comm, 0, colMajorRank, &_vectorColComm );
    MPI_Comm_split( _comm, 0, rowMajorRank, &_vectorRowComm );
    MPI_Comm_rank( _vectorColComm, &_vectorColRank );
    MPI_Comm_rank( _vectorRowComm, &_vectorRowRank );

    // Compute which diagonal 'path' we're in, and what our rank is, then
    // perform AllGather world to store everyone's info
    _diagPathsAndRanks = new int[2*_p];
    int* myDiagPathAndRank = new int[2];
    myDiagPathAndRank[0] = (_matrixRowRank+r-_matrixColRank) % _gcd;
    int diagPathRank = 0;
    int row = 0;
    int col = myDiagPathAndRank[0];
    for( int j=0; j<lcm; ++j )
    {
        if( row == _matrixColRank && col == _matrixRowRank )
        {
            myDiagPathAndRank[1] = diagPathRank;
            break;
        }
        else
        {
            row = (row + 1) % r;
            col = (col + 1) % c;
            ++diagPathRank;
        }
    }
    wrappers::mpi::AllGather
    ( myDiagPathAndRank, 2, _diagPathsAndRanks, 2, _vectorColComm );
    delete[] myDiagPathAndRank;

#ifndef RELEASE
    MPI_Errhandler_set( _matrixColComm, MPI_ERRORS_RETURN );
    MPI_Errhandler_set( _matrixRowComm, MPI_ERRORS_RETURN );
    MPI_Errhandler_set( _vectorColComm, MPI_ERRORS_RETURN );
    MPI_Errhandler_set( _vectorRowComm, MPI_ERRORS_RETURN );
#endif

#ifndef RELEASE
    PopCallStack();
#endif
}

<|endoftext|>


<commit_before>/* Copyright 2017 Istio Authors. All Rights Reserved.
 *
 * Licensed 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.
 */

#include "src/envoy/tcp/mixer/filter.h"
#include "common/common/enum_to_int.h"
#include "extensions/filters/network/well_known_names.h"
#include "src/envoy/utils/utils.h"

using ::google::protobuf::util::Status;
using ::istio::mixerclient::CheckResponseInfo;

namespace Envoy {
namespace Tcp {
namespace Mixer {

Filter::Filter(Control &control) : control_(control) {
  ENVOY_LOG(debug, "Called tcp filter: {}", __func__);
}

Filter::~Filter() {
  cancelCheck();
  ENVOY_LOG(debug, "Called tcp filter : {}", __func__);
}

void Filter::initializeReadFilterCallbacks(
    Network::ReadFilterCallbacks &callbacks) {
  ENVOY_LOG(debug, "Called tcp filter: {}", __func__);
  filter_callbacks_ = &callbacks;
  filter_callbacks_->connection().addConnectionCallbacks(*this);
  start_time_ = std::chrono::system_clock::now();
}

void Filter::cancelCheck() {
  if (state_ != State::Calling && handler_) {
    handler_->ResetCancel();
  }
  state_ = State::Closed;
  if (handler_) {
    handler_->CancelCheck();
  }
}

// Makes a Check() call to Mixer.
void Filter::callCheck() {
  handler_ = control_.controller()->CreateRequestHandler();

  state_ = State::Calling;
  filter_callbacks_->connection().readDisable(true);
  calling_check_ = true;
  handler_->Check(
      this, [this](const CheckResponseInfo &info) { completeCheck(info); });
  calling_check_ = false;
}

// TODO(venilnoronha): rewrite this to deep-clone dynamic metadata for all
// filters.
void Filter::cacheFilterMetadata(
    const ::google::protobuf::Map<std::string, ::google::protobuf::Struct>
        &filter_metadata) {
  for (auto &filter_pair : filter_metadata) {
    if (filter_pair.first ==
        Extensions::NetworkFilters::NetworkFilterNames::get().MongoProxy) {
      if (cached_filter_metadata_.count(filter_pair.first) == 0) {
        ProtobufWkt::Struct dynamic_metadata;
        cached_filter_metadata_[filter_pair.first] = dynamic_metadata;
      }

      auto &cached_fields =
          *cached_filter_metadata_[filter_pair.first].mutable_fields();
      for (const auto &message_pair : filter_pair.second.fields()) {
        cached_fields[message_pair.first].mutable_list_value()->CopyFrom(
            message_pair.second.list_value());
      }
    }
  }
}

void Filter::clearCachedFilterMetadata() { cached_filter_metadata_.clear(); }

// Network::ReadFilter
Network::FilterStatus Filter::onData(Buffer::Instance &data, bool) {
  if (state_ == State::NotStarted) {
    // By waiting to invoke the callCheck() at onData(), the call to Mixer
    // will have sufficient SSL information to fill the check Request.
    callCheck();
  }

  ENVOY_CONN_LOG(debug, "Called tcp filter onRead bytes: {}",
                 filter_callbacks_->connection(), data.length());
  received_bytes_ += data.length();

  // Envoy filters like the mongo_proxy filter clear previously set dynamic
  // metadata on each onData call. Since the Mixer filter sends metadata based
  // on a timer event, it's possible that the previously set metadata is cleared
  // off by the time the event is fired. Therefore, we append metadata from each
  // onData call to a local cache and send it all at once when the timer event
  // occurs. The local cache is cleared after reporting it on the timer event.
  cacheFilterMetadata(filter_callbacks_->connection()
                          .streamInfo()
                          .dynamicMetadata()
                          .filter_metadata());

  return (state_ == State::Calling ||
          filter_callbacks_->connection().state() != Network::Connection::State::Open)
             ? Network::FilterStatus::StopIteration
             : Network::FilterStatus::Continue;
}

// Network::WriteFilter
Network::FilterStatus Filter::onWrite(Buffer::Instance &data, bool) {
  ENVOY_CONN_LOG(debug, "Called tcp filter onWrite bytes: {}",
                 filter_callbacks_->connection(), data.length());
  send_bytes_ += data.length();
  return Network::FilterStatus::Continue;
}

Network::FilterStatus Filter::onNewConnection() {
  ENVOY_CONN_LOG(debug,
                 "Called tcp filter onNewConnection: remote {}, local {}",
                 filter_callbacks_->connection(),
                 filter_callbacks_->connection().remoteAddress()->asString(),
                 filter_callbacks_->connection().localAddress()->asString());

  // Wait until onData() is invoked.
  return Network::FilterStatus::Continue;
}

void Filter::completeCheck(const CheckResponseInfo &info) {
  const auto &status = info.status();
  ENVOY_LOG(debug, "Called tcp filter completeCheck: {}", status.ToString());
  handler_->ResetCancel();
  if (state_ == State::Closed) {
    return;
  }
  state_ = State::Completed;

  Utils::CheckResponseInfoToStreamInfo(
      info, filter_callbacks_->connection().streamInfo());

  filter_callbacks_->connection().readDisable(false);

  if (!status.ok()) {
    filter_callbacks_->connection().close(
        Network::ConnectionCloseType::NoFlush);
  } else {
    if (!calling_check_) {
      filter_callbacks_->continueReading();
    }
    handler_->Report(this, ConnectionEvent::OPEN);
    report_timer_ =
        control_.dispatcher().createTimer([this]() { OnReportTimer(); });
    report_timer_->enableTimer(control_.config().report_interval_ms());
  }
}

// Network::ConnectionCallbacks
void Filter::onEvent(Network::ConnectionEvent event) {
  if (filter_callbacks_->upstreamHost()) {
    ENVOY_CONN_LOG(debug, "Called tcp filter onEvent: {} upstream {}",
              filter_callbacks_->connection(),
              enumToInt(event),
              filter_callbacks_->upstreamHost()->address()->asString());
  } else {
    ENVOY_CONN_LOG(debug, "Called tcp filter onEvent: {}",
              filter_callbacks_->connection(),
              enumToInt(event));
  }

  if (event == Network::ConnectionEvent::RemoteClose ||
      event == Network::ConnectionEvent::LocalClose) {
    if (state_ != State::Closed && handler_) {
      if (report_timer_) {
        report_timer_->disableTimer();
      }
      handler_->Report(this, ConnectionEvent::CLOSE);
    }
    cancelCheck();
  }
}

bool Filter::GetSourceIpPort(std::string *str_ip, int *port) const {
  return Utils::GetIpPort(filter_callbacks_->connection().remoteAddress()->ip(),
                          str_ip, port);
}

bool Filter::GetPrincipal(bool peer, std::string *user) const {
  return Utils::GetPrincipal(&filter_callbacks_->connection(), peer, user);
}

bool Filter::IsMutualTLS() const {
  return Utils::IsMutualTLS(&filter_callbacks_->connection());
}

bool Filter::GetRequestedServerName(std::string *name) const {
  return Utils::GetRequestedServerName(&filter_callbacks_->connection(), name);
}

bool Filter::GetDestinationIpPort(std::string *str_ip, int *port) const {
  if (filter_callbacks_->upstreamHost() &&
      filter_callbacks_->upstreamHost()->address()) {
    return Utils::GetIpPort(filter_callbacks_->upstreamHost()->address()->ip(),
                            str_ip, port);
  }
  return false;
}

bool Filter::GetDestinationUID(std::string *uid) const {
  if (filter_callbacks_->upstreamHost()) {
    return Utils::GetDestinationUID(
        *filter_callbacks_->upstreamHost()->metadata(), uid);
  }
  return false;
}

const ::google::protobuf::Map<std::string, ::google::protobuf::Struct>
    &Filter::GetDynamicFilterState() const {
  return cached_filter_metadata_;
}

void Filter::GetReportInfo(
    ::istio::control::tcp::ReportData::ReportInfo *data) const {
  data->received_bytes = received_bytes_;
  data->send_bytes = send_bytes_;
  data->duration = std::chrono::duration_cast<std::chrono::nanoseconds>(
      std::chrono::system_clock::now() - start_time_);
}

std::string Filter::GetConnectionId() const {
  char connection_id_str[32];
  StringUtil::itoa(connection_id_str, 32, filter_callbacks_->connection().id());
  std::string uuid_connection_id = control_.uuid() + "-";
  uuid_connection_id.append(connection_id_str);
  return uuid_connection_id;
}

void Filter::OnReportTimer() {
  handler_->Report(this, ConnectionEvent::CONTINUE);
  clearCachedFilterMetadata();
  report_timer_->enableTimer(control_.config().report_interval_ms());
}

}  // namespace Mixer
}  // namespace Tcp
}  // namespace Envoy
<commit_msg>Fix lint (#2279)<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved.
 *
 * Licensed 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.
 */

#include "src/envoy/tcp/mixer/filter.h"

#include "common/common/enum_to_int.h"
#include "extensions/filters/network/well_known_names.h"
#include "src/envoy/utils/utils.h"

using ::google::protobuf::util::Status;
using ::istio::mixerclient::CheckResponseInfo;

namespace Envoy {
namespace Tcp {
namespace Mixer {

Filter::Filter(Control &control) : control_(control) {
  ENVOY_LOG(debug, "Called tcp filter: {}", __func__);
}

Filter::~Filter() {
  cancelCheck();
  ENVOY_LOG(debug, "Called tcp filter : {}", __func__);
}

void Filter::initializeReadFilterCallbacks(
    Network::ReadFilterCallbacks &callbacks) {
  ENVOY_LOG(debug, "Called tcp filter: {}", __func__);
  filter_callbacks_ = &callbacks;
  filter_callbacks_->connection().addConnectionCallbacks(*this);
  start_time_ = std::chrono::system_clock::now();
}

void Filter::cancelCheck() {
  if (state_ != State::Calling && handler_) {
    handler_->ResetCancel();
  }
  state_ = State::Closed;
  if (handler_) {
    handler_->CancelCheck();
  }
}

// Makes a Check() call to Mixer.
void Filter::callCheck() {
  handler_ = control_.controller()->CreateRequestHandler();

  state_ = State::Calling;
  filter_callbacks_->connection().readDisable(true);
  calling_check_ = true;
  handler_->Check(
      this, [this](const CheckResponseInfo &info) { completeCheck(info); });
  calling_check_ = false;
}

// TODO(venilnoronha): rewrite this to deep-clone dynamic metadata for all
// filters.
void Filter::cacheFilterMetadata(
    const ::google::protobuf::Map<std::string, ::google::protobuf::Struct>
        &filter_metadata) {
  for (auto &filter_pair : filter_metadata) {
    if (filter_pair.first ==
        Extensions::NetworkFilters::NetworkFilterNames::get().MongoProxy) {
      if (cached_filter_metadata_.count(filter_pair.first) == 0) {
        ProtobufWkt::Struct dynamic_metadata;
        cached_filter_metadata_[filter_pair.first] = dynamic_metadata;
      }

      auto &cached_fields =
          *cached_filter_metadata_[filter_pair.first].mutable_fields();
      for (const auto &message_pair : filter_pair.second.fields()) {
        cached_fields[message_pair.first].mutable_list_value()->CopyFrom(
            message_pair.second.list_value());
      }
    }
  }
}

void Filter::clearCachedFilterMetadata() { cached_filter_metadata_.clear(); }

// Network::ReadFilter
Network::FilterStatus Filter::onData(Buffer::Instance &data, bool) {
  if (state_ == State::NotStarted) {
    // By waiting to invoke the callCheck() at onData(), the call to Mixer
    // will have sufficient SSL information to fill the check Request.
    callCheck();
  }

  ENVOY_CONN_LOG(debug, "Called tcp filter onRead bytes: {}",
                 filter_callbacks_->connection(), data.length());
  received_bytes_ += data.length();

  // Envoy filters like the mongo_proxy filter clear previously set dynamic
  // metadata on each onData call. Since the Mixer filter sends metadata based
  // on a timer event, it's possible that the previously set metadata is cleared
  // off by the time the event is fired. Therefore, we append metadata from each
  // onData call to a local cache and send it all at once when the timer event
  // occurs. The local cache is cleared after reporting it on the timer event.
  cacheFilterMetadata(filter_callbacks_->connection()
                          .streamInfo()
                          .dynamicMetadata()
                          .filter_metadata());

  return (state_ == State::Calling || filter_callbacks_->connection().state() !=
                                          Network::Connection::State::Open)
             ? Network::FilterStatus::StopIteration
             : Network::FilterStatus::Continue;
}

// Network::WriteFilter
Network::FilterStatus Filter::onWrite(Buffer::Instance &data, bool) {
  ENVOY_CONN_LOG(debug, "Called tcp filter onWrite bytes: {}",
                 filter_callbacks_->connection(), data.length());
  send_bytes_ += data.length();
  return Network::FilterStatus::Continue;
}

Network::FilterStatus Filter::onNewConnection() {
  ENVOY_CONN_LOG(debug,
                 "Called tcp filter onNewConnection: remote {}, local {}",
                 filter_callbacks_->connection(),
                 filter_callbacks_->connection().remoteAddress()->asString(),
                 filter_callbacks_->connection().localAddress()->asString());

  // Wait until onData() is invoked.
  return Network::FilterStatus::Continue;
}

void Filter::completeCheck(const CheckResponseInfo &info) {
  const auto &status = info.status();
  ENVOY_LOG(debug, "Called tcp filter completeCheck: {}", status.ToString());
  handler_->ResetCancel();
  if (state_ == State::Closed) {
    return;
  }
  state_ = State::Completed;

  Utils::CheckResponseInfoToStreamInfo(
      info, filter_callbacks_->connection().streamInfo());

  filter_callbacks_->connection().readDisable(false);

  if (!status.ok()) {
    filter_callbacks_->connection().close(
        Network::ConnectionCloseType::NoFlush);
  } else {
    if (!calling_check_) {
      filter_callbacks_->continueReading();
    }
    handler_->Report(this, ConnectionEvent::OPEN);
    report_timer_ =
        control_.dispatcher().createTimer([this]() { OnReportTimer(); });
    report_timer_->enableTimer(control_.config().report_interval_ms());
  }
}

// Network::ConnectionCallbacks
void Filter::onEvent(Network::ConnectionEvent event) {
  if (filter_callbacks_->upstreamHost()) {
    ENVOY_CONN_LOG(debug, "Called tcp filter onEvent: {} upstream {}",
                   filter_callbacks_->connection(), enumToInt(event),
                   filter_callbacks_->upstreamHost()->address()->asString());
  } else {
    ENVOY_CONN_LOG(debug, "Called tcp filter onEvent: {}",
                   filter_callbacks_->connection(), enumToInt(event));
  }

  if (event == Network::ConnectionEvent::RemoteClose ||
      event == Network::ConnectionEvent::LocalClose) {
    if (state_ != State::Closed && handler_) {
      if (report_timer_) {
        report_timer_->disableTimer();
      }
      handler_->Report(this, ConnectionEvent::CLOSE);
    }
    cancelCheck();
  }
}

bool Filter::GetSourceIpPort(std::string *str_ip, int *port) const {
  return Utils::GetIpPort(filter_callbacks_->connection().remoteAddress()->ip(),
                          str_ip, port);
}

bool Filter::GetPrincipal(bool peer, std::string *user) const {
  return Utils::GetPrincipal(&filter_callbacks_->connection(), peer, user);
}

bool Filter::IsMutualTLS() const {
  return Utils::IsMutualTLS(&filter_callbacks_->connection());
}

bool Filter::GetRequestedServerName(std::string *name) const {
  return Utils::GetRequestedServerName(&filter_callbacks_->connection(), name);
}

bool Filter::GetDestinationIpPort(std::string *str_ip, int *port) const {
  if (filter_callbacks_->upstreamHost() &&
      filter_callbacks_->upstreamHost()->address()) {
    return Utils::GetIpPort(filter_callbacks_->upstreamHost()->address()->ip(),
                            str_ip, port);
  }
  return false;
}

bool Filter::GetDestinationUID(std::string *uid) const {
  if (filter_callbacks_->upstreamHost()) {
    return Utils::GetDestinationUID(
        *filter_callbacks_->upstreamHost()->metadata(), uid);
  }
  return false;
}

const ::google::protobuf::Map<std::string, ::google::protobuf::Struct>
    &Filter::GetDynamicFilterState() const {
  return cached_filter_metadata_;
}

void Filter::GetReportInfo(
    ::istio::control::tcp::ReportData::ReportInfo *data) const {
  data->received_bytes = received_bytes_;
  data->send_bytes = send_bytes_;
  data->duration = std::chrono::duration_cast<std::chrono::nanoseconds>(
      std::chrono::system_clock::now() - start_time_);
}

std::string Filter::GetConnectionId() const {
  char connection_id_str[32];
  StringUtil::itoa(connection_id_str, 32, filter_callbacks_->connection().id());
  std::string uuid_connection_id = control_.uuid() + "-";
  uuid_connection_id.append(connection_id_str);
  return uuid_connection_id;
}

void Filter::OnReportTimer() {
  handler_->Report(this, ConnectionEvent::CONTINUE);
  clearCachedFilterMetadata();
  report_timer_->enableTimer(control_.config().report_interval_ms());
}

}  // namespace Mixer
}  // namespace Tcp
}  // namespace Envoy
<|endoftext|>


<commit_before>#include "oddlib/compressiontype6or7aepsx.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <vector>
#include <cassert>

namespace Oddlib
{
    template<Uint32 BitsSize>
    Uint32 NextBits(IStream& stream, unsigned int& bitCounter, unsigned int& srcWorkBits, const signed int kFixedMask)
    {
        if (bitCounter < 16)
        {
            const int srcBits = ReadUint16(stream) << bitCounter;
            bitCounter += 16;
            srcWorkBits |= srcBits;
        }

        bitCounter -= BitsSize;
        const Uint32 ret = srcWorkBits & (kFixedMask - 1);
        srcWorkBits >>= BitsSize;
        return ret;
    }

    // Function 0x004ABB90 in AE, function 0x8005B09C in AE PSX demo
    template<Uint32 BitsSize>
    std::vector<Uint8> CompressionType6or7AePsx<BitsSize>::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
    {
        unsigned int kInputSize = (BitsSize * dataSize) >> 3;

        std::vector<Uint8> out(finalW*h * 2);

        Uint32 outputPos = 0;

        unsigned char tmp1[256] = {};
        unsigned char tmp2[256] = {};
        unsigned char tmp3[256] = {};

        const signed int kFixedMask = 1 << BitsSize;
        const unsigned int v36 = ((unsigned int)(kFixedMask) >> 1) - 1;

        unsigned int bitCounter = 0;

        unsigned int srcWorkBits = 0; // Must live for as long as the outer most loop/scope
        const auto kStartPos = stream.Pos();
        while (stream.Pos() < kStartPos+kInputSize)
        {
            unsigned int count = 0;
            do
            {
                const unsigned int maskedSrcBits1 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);

                int maskedSrcBits1Copy = maskedSrcBits1;

                if (maskedSrcBits1 > v36)
                {
                    int remainder = maskedSrcBits1 - v36;
                    maskedSrcBits1Copy = remainder;
                    if (remainder)
                    {
                        int remainderCopy = remainder;
                        do
                        {
                            tmp2[count] = static_cast<char>(count);
                            ++count;
                            --remainder;
                            --remainderCopy;
                        } while (remainderCopy);
                        maskedSrcBits1Copy = remainder;
                    }
                }

                if (count == kFixedMask)
                {
                    break;
                }

                unsigned int count2 = maskedSrcBits1Copy + 1;
                for (;;)
                {
                    const unsigned int v14 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
                    *(&tmp1[count] + (tmp2 - tmp1)) = static_cast<char>(v14);
                    if (count != v14)
                    {
                        const unsigned int v16 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
                        tmp1[count] = static_cast<unsigned char>(v16);
                    }
                    ++count;
                    const char bLastByte = count2-- == 1;
                    if (bLastByte)
                    {
                        break;
                    }
                }
            } while (count != kFixedMask);

            unsigned int v19 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
            v19 = v19 << BitsSize; // Extra

            unsigned int v33 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
            v33 = v33 + v19; // Extra

            int v23 = 0;
            for (;;)
            {
                unsigned int v24 = 0;
                if (v23)
                {
                    --v23;
                    v24 = tmp3[v23];
                }
                else
                {
                    if (!v33--)
                    {
                        break;
                    }

                    v24 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
                }

                for (unsigned int i = tmp2[v24]; v24 != i; i = tmp2[i])
                {
                    unsigned char v28 = tmp1[v24];
                    v24 = i;
                    tmp3[v23++] = v28;
                }
                out[outputPos++] = static_cast<Uint8>(v24);
            }
        }

        return out;
    }

    // Explicit template instantiation
    template class CompressionType6or7AePsx<6>;
    template class CompressionType6or7AePsx<8>;
}
<commit_msg>clean up<commit_after>#include "oddlib/compressiontype6or7aepsx.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <vector>
#include <cassert>

namespace Oddlib
{
    template<Uint32 BitsSize>
    Uint32 NextBits(IStream& stream, unsigned int& bitCounter, unsigned int& srcWorkBits, const signed int kFixedMask)
    {
        if (bitCounter < 16)
        {
            const int srcBits = ReadUint16(stream) << bitCounter;
            bitCounter += 16;
            srcWorkBits |= srcBits;
        }

        bitCounter -= BitsSize;
        const Uint32 ret = srcWorkBits & (kFixedMask - 1);
        srcWorkBits >>= BitsSize;
        return ret;
    }

    // Function 0x004ABB90 in AE, function 0x8005B09C in AE PSX demo
    template<Uint32 BitsSize>
    std::vector<Uint8> CompressionType6or7AePsx<BitsSize>::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
    {
        Uint32 outputPos = 0;
        std::vector<Uint8> out(finalW*h * 2);

        unsigned char tmp1[256] = {};
        unsigned char tmp2[256] = {};
        unsigned char tmp3[256] = {};

        const signed int kFixedMask = 1 << BitsSize;
        const unsigned int v36 = ((unsigned int)(kFixedMask) >> 1) - 1;

        unsigned int bitCounter = 0;
        unsigned int srcWorkBits = 0; // Must live for as long as the outer most loop/scope

        const auto kStartPos = stream.Pos();
        const unsigned int kInputSize = (BitsSize * dataSize) >> 3;
        while (stream.Pos() < kStartPos+kInputSize)
        {
            unsigned int count = 0;
            do
            {
                const unsigned int maskedSrcBits1 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);

                int maskedSrcBits1Copy = maskedSrcBits1;

                if (maskedSrcBits1 > v36)
                {
                    int remainder = maskedSrcBits1 - v36;
                    maskedSrcBits1Copy = remainder;
                    if (remainder)
                    {
                        int remainderCopy = remainder;
                        do
                        {
                            tmp2[count] = static_cast<char>(count);
                            ++count;
                            --remainder;
                            --remainderCopy;
                        } while (remainderCopy);
                        maskedSrcBits1Copy = remainder;
                    }
                }

                if (count == kFixedMask)
                {
                    break;
                }

                unsigned int count2 = maskedSrcBits1Copy + 1;
                for (;;)
                {
                    const unsigned int v14 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
                    *(&tmp1[count] + (tmp2 - tmp1)) = static_cast<char>(v14);
                    if (count != v14)
                    {
                        const unsigned int v16 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
                        tmp1[count] = static_cast<unsigned char>(v16);
                    }
                    ++count;
                    const char bLastByte = count2-- == 1;
                    if (bLastByte)
                    {
                        break;
                    }
                }
            } while (count != kFixedMask);

            unsigned int v19 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
            v19 = v19 << BitsSize; // Extra

            unsigned int v33 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
            v33 = v33 + v19; // Extra

            int v23 = 0;
            for (;;)
            {
                unsigned int v24 = 0;
                if (v23)
                {
                    --v23;
                    v24 = tmp3[v23];
                }
                else
                {
                    if (!v33--)
                    {
                        break;
                    }

                    v24 = NextBits<BitsSize>(stream, bitCounter, srcWorkBits, kFixedMask);
                }

                for (unsigned int i = tmp2[v24]; v24 != i; i = tmp2[i])
                {
                    unsigned char v28 = tmp1[v24];
                    v24 = i;
                    tmp3[v23++] = v28;
                }
                out[outputPos++] = static_cast<Uint8>(v24);
            }
        }

        return out;
    }

    // Explicit template instantiation
    template class CompressionType6or7AePsx<6>;
    template class CompressionType6or7AePsx<8>;
}
<|endoftext|>


<commit_before>#include "sitkImage.h"

namespace itk
{
  namespace simple
  {

    template<class TImageType> void Image::AllocateInternal ( uint64_t Width, uint64_t Height, uint64_t Depth ) {
      typename TImageType::IndexType  index;
      typename TImageType::SizeType   size;
      typename TImageType::RegionType region;
      index.Fill ( 0 );
      size[0] = Width;
      size[1] = Height;
      size[2] = 1; // minimum size along Z must be initialized
      if ( Depth != 0 ) {
        size[2] = Depth;
      }
      region.SetSize ( size );
      region.SetIndex ( index );
      typename TImageType::Pointer image = TImageType::New();
      image->SetRegions ( region );
      image->Allocate();
      image->FillBuffer ( 0.0 );
      m_PimpleImage.reset( new PimpleImage<TImageType>( image ) );
    }

    void Image::Allocate ( uint64_t Width, uint64_t Height, uint64_t Depth, PixelIDValueEnum ValueEnum ) {
      // Allocate an image
      this->m_AllocateMemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType, detail::AllocateMemberFunctionAddressor<MemberFunctionType> > ( this ) );

      this->m_AllocateMemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
      this->m_AllocateMemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
      PixelIDValueType type = ValueEnum;
      if ( Depth == 0 ) {
        this->m_AllocateMemberFactory->GetMemberFunction( type, 2 )( Width, Height, Depth );
      } else {
        this->m_AllocateMemberFactory->GetMemberFunction( type, 3 )( Width, Height, Depth );
      }
    }

    Image::Image( uint64_t Width, uint64_t Height, PixelIDValueType ValueType ) {
      Allocate ( Width, Height, 0, (PixelIDValueEnum) ValueType );
    }
    Image::Image( uint64_t Width, uint64_t Height, uint64_t Depth, PixelIDValueEnum ValueEnum ) {
      Allocate ( Width, Height, Depth, ValueEnum );
    }

    itk::DataObject::Pointer Image::GetImageBase( void )
    {
      assert( m_PimpleImage.get() );
      return m_PimpleImage->GetDataBase();
    }

    itk::DataObject::ConstPointer Image::GetImageBase( void ) const
    {
      assert( m_PimpleImage.get() );
      return m_PimpleImage->GetDataBase().GetPointer();
    }

    PixelIDValueType Image::GetPixelIDValue( void ) const
    {
      return this->m_PimpleImage->GetPixelIDValue();
    }

    unsigned int Image::GetDimension( void ) const
    {
      return this->m_PimpleImage->GetDimension();
    }

    std::string Image::GetPixelIDTypeAsString( void ) const
    {
      return std::string( GetPixelIDValueAsString( this->GetPixelIDValue() ) );
    }

    std::string Image::ToString( void )
    {
      return this->m_PimpleImage->ToString();
    }

    uint64_t Image::GetWidth( void )
    {
      return this->m_PimpleImage->GetWidth();
    }

    uint64_t Image::GetHeight( void )
    {
      return this->m_PimpleImage->GetHeight();
    }

    uint64_t Image::GetDepth( void )
    {
      return this->m_PimpleImage->GetDepth();
    }

    /*
    void Image::Show(const std::string name) const
    {
      // Try to find ImageJ, write out a file and open
#if defined(__WIN32__)
      // Windows
#elseif defined(__APPLE__)
      // Mac
      char *filename = malloc ( sizeof(char) * (100 + name.size()) );
      sprintf ( filename, "/tmp/%s-XXXXX.nrrd", name.c_str() );
      mktemp ( filename );
      ImageFileWriter().SetFilename ( filename ).Execute ( this );
      std::cout << "Show Filename: " << filename << std::endl;
#else
      // Linux
#endif
    }
    */

  }
}
<commit_msg>BUG: Incorrect fix, ImageType maybe a 2D image.<commit_after>#include "sitkImage.h"

namespace itk
{
  namespace simple
  {

    template<class TImageType> void Image::AllocateInternal ( uint64_t Width, uint64_t Height, uint64_t Depth ) {
      typename TImageType::IndexType  index;
      typename TImageType::SizeType   size;
      typename TImageType::RegionType region;
      index.Fill ( 0 );
      size.Fill(1);
      size[0] = Width;
      size[1] = Height;
      if ( Depth != 0 ) {
        size[2] = Depth;
      }
      region.SetSize ( size );
      region.SetIndex ( index );
      typename TImageType::Pointer image = TImageType::New();
      image->SetRegions ( region );
      image->Allocate();
      image->FillBuffer ( 0.0 );
      m_PimpleImage.reset( new PimpleImage<TImageType>( image ) );
    }

    void Image::Allocate ( uint64_t Width, uint64_t Height, uint64_t Depth, PixelIDValueEnum ValueEnum ) {
      // Allocate an image
      this->m_AllocateMemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType, detail::AllocateMemberFunctionAddressor<MemberFunctionType> > ( this ) );

      this->m_AllocateMemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
      this->m_AllocateMemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
      PixelIDValueType type = ValueEnum;
      if ( Depth == 0 ) {
        this->m_AllocateMemberFactory->GetMemberFunction( type, 2 )( Width, Height, Depth );
      } else {
        this->m_AllocateMemberFactory->GetMemberFunction( type, 3 )( Width, Height, Depth );
      }
    }

    Image::Image( uint64_t Width, uint64_t Height, PixelIDValueType ValueType ) {
      Allocate ( Width, Height, 0, (PixelIDValueEnum) ValueType );
    }
    Image::Image( uint64_t Width, uint64_t Height, uint64_t Depth, PixelIDValueEnum ValueEnum ) {
      Allocate ( Width, Height, Depth, ValueEnum );
    }

    itk::DataObject::Pointer Image::GetImageBase( void )
    {
      assert( m_PimpleImage.get() );
      return m_PimpleImage->GetDataBase();
    }

    itk::DataObject::ConstPointer Image::GetImageBase( void ) const
    {
      assert( m_PimpleImage.get() );
      return m_PimpleImage->GetDataBase().GetPointer();
    }

    PixelIDValueType Image::GetPixelIDValue( void ) const
    {
      return this->m_PimpleImage->GetPixelIDValue();
    }

    unsigned int Image::GetDimension( void ) const
    {
      return this->m_PimpleImage->GetDimension();
    }

    std::string Image::GetPixelIDTypeAsString( void ) const
    {
      return std::string( GetPixelIDValueAsString( this->GetPixelIDValue() ) );
    }

    std::string Image::ToString( void )
    {
      return this->m_PimpleImage->ToString();
    }

    uint64_t Image::GetWidth( void )
    {
      return this->m_PimpleImage->GetWidth();
    }

    uint64_t Image::GetHeight( void )
    {
      return this->m_PimpleImage->GetHeight();
    }

    uint64_t Image::GetDepth( void )
    {
      return this->m_PimpleImage->GetDepth();
    }

    /*
    void Image::Show(const std::string name) const
    {
      // Try to find ImageJ, write out a file and open
#if defined(__WIN32__)
      // Windows
#elseif defined(__APPLE__)
      // Mac
      char *filename = malloc ( sizeof(char) * (100 + name.size()) );
      sprintf ( filename, "/tmp/%s-XXXXX.nrrd", name.c_str() );
      mktemp ( filename );
      ImageFileWriter().SetFilename ( filename ).Execute ( this );
      std::cout << "Show Filename: " << filename << std::endl;
#else
      // Linux
#endif
    }
    */

  }
}
<|endoftext|>