<commit_before>#include <QtCore/QDebug>
#include <QtCore/QTimer>

#include <QtDBus/QtDBus>

#include <TelepathyQt4/Constants>
#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/ConnectionManager>

#include <tests/pinocchio/lib.h>

using namespace Telepathy::Client;

class TestConnBasics : public PinocchioTest
{
    Q_OBJECT

private:
    Telepathy::Client::ConnectionManagerInterface* mCM;
    QString mConnBusName;
    QString mConnObjectPath;
    Connection *mConn;

protected Q_SLOTS:
    void expectNotYetConnected(uint);
    void expectReady(uint);
    void expectSuccessfulCall(QDBusPendingCallWatcher*);

private Q_SLOTS:
    void initTestCase();
    void init();

    void testInitialIntrospection();
    void testConnect();
    void testSpecifiedBus();

    void cleanup();
    void cleanupTestCase();
};

void TestConnBasics::initTestCase()
{
    initTestCaseImpl();

    // Wait for the CM to start up
    QVERIFY(waitForPinocchio(5000));

    // Escape to the low-level API to make a Connection; this uses
    // pseudo-blocking calls for simplicity. Do not do this in production code

    mCM = new Telepathy::Client::ConnectionManagerInterface(
        pinocchioBusName(), pinocchioObjectPath());

    QDBusPendingReply<QString, QDBusObjectPath> reply;
    QVariantMap parameters;
    parameters.insert(QLatin1String("account"),
        QVariant::fromValue(QString::fromAscii("empty")));
    parameters.insert(QLatin1String("password"),
        QVariant::fromValue(QString::fromAscii("s3kr1t")));

    reply = mCM->RequestConnection("dummy", parameters);
    reply.waitForFinished();
    if (!reply.isValid()) {
        qWarning().nospace() << reply.error().name()
            << ": " << reply.error().message();
        QVERIFY(reply.isValid());
    }
    mConnBusName = reply.argumentAt<0>();
    mConnObjectPath = reply.argumentAt<1>().path();
}

void TestConnBasics::init()
{
    initImpl();
}

void TestConnBasics::expectNotYetConnected(uint newReadiness)
{
    switch (newReadiness) {
    case Connection::ReadinessJustCreated:
        qWarning() << "Changing from JustCreated to JustCreated is silly";
        mLoop->exit(1);
        break;
    case Connection::ReadinessNotYetConnected:
        qDebug() << "Correctly changed to NotYetConnected";
        mLoop->exit(0);
        break;
    case Connection::ReadinessConnecting:
    case Connection::ReadinessFull:
    case Connection::ReadinessDead:
        qWarning() << "Got too far!";
        mLoop->exit(2);
        break;
    default:
        qWarning().nospace() << "What sort of readiness is "
            << newReadiness << "?!";
        mLoop->exit(3);
        break;
    }
}

void TestConnBasics::testInitialIntrospection()
{
    mConn = new Connection(mConnBusName, mConnObjectPath);

    QCOMPARE(mConn->readiness(), Connection::ReadinessJustCreated);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusDisconnected));

    // Wait for introspection to run (readiness changes to NYC)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
}

void TestConnBasics::expectSuccessfulCall(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<> reply = *watcher;

    if (reply.isError()) {
        qWarning().nospace() << reply.error().name()
            << ": " << reply.error().message();
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void TestConnBasics::expectReady(uint newReadiness)
{
    switch (newReadiness) {
    case Connection::ReadinessJustCreated:
        qWarning() << "Changing from NYC to JustCreated is silly";
        mLoop->exit(1);
        break;
    case Connection::ReadinessNotYetConnected:
        qWarning() << "Changing from NYC to NYC is silly";
        mLoop->exit(2);
        break;
    case Connection::ReadinessConnecting:
        /* do nothing */
        break;
    case Connection::ReadinessFull:
        qDebug() << "Ready";
        mLoop->exit(0);
        break;
    case Connection::ReadinessDead:
        qWarning() << "Dead!";
        mLoop->exit(3);
        break;
    default:
        qWarning().nospace() << "What sort of readiness is "
            << newReadiness << "?!";
        mLoop->exit(4);
        break;
    }
}

void TestConnBasics::testConnect()
{
    testInitialIntrospection();

    // FIXME: should have convenience API
    qDebug() << "calling Connect()";

    QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(
            mConn->Connect());
    QVERIFY(connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
            this, SLOT(expectSuccessfulCall(QDBusPendingCallWatcher*))));
    QCOMPARE(mLoop->exec(), 0);
    delete watcher;

    // Wait for readiness to reach Full

    qDebug() << "waiting for Full readiness";
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));

    QCOMPARE(mConn->readiness(), Connection::ReadinessFull);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusConnected));

    QStringList interfaces = mConn->interfaces();
    QVERIFY(interfaces.contains(QLatin1String(
            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_ALIASING)));
    QVERIFY(interfaces.contains(QLatin1String(
            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS)));
    QVERIFY(interfaces.contains(QLatin1String(
            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CAPABILITIES)));

    watcher = new QDBusPendingCallWatcher(
            mConn->Disconnect());
    QVERIFY(connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
            this, SLOT(expectSuccessfulCall(QDBusPendingCallWatcher*))));
    QCOMPARE(mLoop->exec(), 0);
    delete watcher;
}

void TestConnBasics::cleanup()
{
    delete mConn;
    mConn = NULL;

    cleanupImpl();
}

void TestConnBasics::testSpecifiedBus()
{
    mConn = new Connection(QDBusConnection::sessionBus(),
        mConnBusName, mConnObjectPath);

    QCOMPARE(mConn->readiness(), Connection::ReadinessJustCreated);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusDisconnected));

    // Wait for introspection to run (readiness changes to NYC)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
}

void TestConnBasics::cleanupTestCase()
{
    delete mCM;
    mCM = NULL;

    cleanupTestCaseImpl();
}

QTEST_MAIN(TestConnBasics)
#include "_gen/conn-basics.cpp.moc.hpp"
<commit_msg>conn-basics: fill in some more test coverage<commit_after>#include <QtCore/QDebug>
#include <QtCore/QTimer>

#include <QtDBus/QtDBus>

#include <TelepathyQt4/Constants>
#include <TelepathyQt4/Client/DBus>
#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/ConnectionManager>

#include <tests/pinocchio/lib.h>

using namespace Telepathy::Client;

class TestConnBasics : public PinocchioTest
{
    Q_OBJECT

private:
    Telepathy::Client::ConnectionManagerInterface* mCM;
    QString mConnBusName;
    QString mConnObjectPath;
    Connection *mConn;

protected Q_SLOTS:
    void expectNotYetConnected(uint);
    void expectReady(uint);
    void expectSuccessfulCall(QDBusPendingCallWatcher*);

private Q_SLOTS:
    void initTestCase();
    void init();

    void testInitialIntrospection();
    void testConnect();
    void testSpecifiedBus();
    void testAlreadyConnected();
    void testInterfaceFactory();

    void cleanup();
    void cleanupTestCase();
};

/*
 * Missing test coverage on existing Connection code includes:
 *
 * - pre-Connected introspection (needs Pinocchio support or another CM)
 * - introspecting a Connection that's already Connecting (needs Pinocchio
 *   support or another CM)
 *
 * Out of scope for this test, should be in another test:
 *
 * - SimplePresence introspection (needs Pinocchio support or another CM)
 * - aliasFlags(), presenceStatuses(), simplePresenceStatuses() accessors
 * - requesting a channel
 */

void TestConnBasics::initTestCase()
{
    initTestCaseImpl();

    // Wait for the CM to start up
    QVERIFY(waitForPinocchio(5000));

    // Escape to the low-level API to make a Connection; this uses
    // pseudo-blocking calls for simplicity. Do not do this in production code

    mCM = new Telepathy::Client::ConnectionManagerInterface(
        pinocchioBusName(), pinocchioObjectPath());

    QDBusPendingReply<QString, QDBusObjectPath> reply;
    QVariantMap parameters;
    parameters.insert(QLatin1String("account"),
        QVariant::fromValue(QString::fromAscii("empty")));
    parameters.insert(QLatin1String("password"),
        QVariant::fromValue(QString::fromAscii("s3kr1t")));

    reply = mCM->RequestConnection("dummy", parameters);
    reply.waitForFinished();
    if (!reply.isValid()) {
        qWarning().nospace() << reply.error().name()
            << ": " << reply.error().message();
        QVERIFY(reply.isValid());
    }
    mConnBusName = reply.argumentAt<0>();
    mConnObjectPath = reply.argumentAt<1>().path();
}

void TestConnBasics::init()
{
    initImpl();
}

void TestConnBasics::expectNotYetConnected(uint newReadiness)
{
    switch (newReadiness) {
    case Connection::ReadinessJustCreated:
        qWarning() << "Changing from JustCreated to JustCreated is silly";
        mLoop->exit(1);
        break;
    case Connection::ReadinessNotYetConnected:
        qDebug() << "Correctly changed to NotYetConnected";
        mLoop->exit(0);
        break;
    case Connection::ReadinessConnecting:
    case Connection::ReadinessFull:
    case Connection::ReadinessDead:
        qWarning() << "Got too far!";
        mLoop->exit(2);
        break;
    default:
        qWarning().nospace() << "What sort of readiness is "
            << newReadiness << "?!";
        mLoop->exit(3);
        break;
    }
}

void TestConnBasics::testInitialIntrospection()
{
    mConn = new Connection(mConnBusName, mConnObjectPath);

    QCOMPARE(mConn->readiness(), Connection::ReadinessJustCreated);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusDisconnected));

    // Wait for introspection to run (readiness changes to NYC)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));

    delete mConn;
    mConn = NULL;
}

void TestConnBasics::expectSuccessfulCall(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<> reply = *watcher;

    if (reply.isError()) {
        qWarning().nospace() << reply.error().name()
            << ": " << reply.error().message();
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void TestConnBasics::expectReady(uint newReadiness)
{
    switch (newReadiness) {
    case Connection::ReadinessJustCreated:
        qWarning() << "Changing from NYC to JustCreated is silly";
        mLoop->exit(1);
        break;
    case Connection::ReadinessNotYetConnected:
        qWarning() << "Changing from NYC to NYC is silly";
        mLoop->exit(2);
        break;
    case Connection::ReadinessConnecting:
        /* do nothing */
        break;
    case Connection::ReadinessFull:
        qDebug() << "Ready";
        mLoop->exit(0);
        break;
    case Connection::ReadinessDead:
        qWarning() << "Dead!";
        mLoop->exit(3);
        break;
    default:
        qWarning().nospace() << "What sort of readiness is "
            << newReadiness << "?!";
        mLoop->exit(4);
        break;
    }
}

void TestConnBasics::testConnect()
{
    mConn = new Connection(mConnBusName, mConnObjectPath);

    QCOMPARE(mConn->readiness(), Connection::ReadinessJustCreated);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusDisconnected));

    // Wait for introspection to run (readiness changes to NYC)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));

    // FIXME: should have convenience API
    qDebug() << "calling Connect()";

    QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(
            mConn->Connect());
    QVERIFY(connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
            this, SLOT(expectSuccessfulCall(QDBusPendingCallWatcher*))));
    QCOMPARE(mLoop->exec(), 0);
    delete watcher;

    // Wait for readiness to reach Full

    qDebug() << "waiting for Full readiness";
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));

    QCOMPARE(mConn->readiness(), Connection::ReadinessFull);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusConnected));
    QCOMPARE(static_cast<uint>(mConn->statusReason()),
        static_cast<uint>(Telepathy::ConnectionStatusReasonRequested));

    QStringList interfaces = mConn->interfaces();
    QVERIFY(interfaces.contains(QLatin1String(
            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_ALIASING)));
    QVERIFY(interfaces.contains(QLatin1String(
            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS)));
    QVERIFY(interfaces.contains(QLatin1String(
            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CAPABILITIES)));

    // FIXME: should have convenience API
    watcher = new QDBusPendingCallWatcher(
            mConn->Disconnect());
    QVERIFY(connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
            this, SLOT(expectSuccessfulCall(QDBusPendingCallWatcher*))));
    QCOMPARE(mLoop->exec(), 0);
    delete watcher;

    QCOMPARE(mConn->readiness(), Connection::ReadinessDead);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusDisconnected));
    QCOMPARE(static_cast<uint>(mConn->statusReason()),
        static_cast<uint>(Telepathy::ConnectionStatusReasonRequested));

    delete mConn;
    mConn = NULL;
}

void TestConnBasics::testAlreadyConnected()
{
    mConn = new Connection(mConnBusName, mConnObjectPath);

    // Wait for introspection to run (readiness changes to NYC)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));

    // FIXME: should have convenience API
    qDebug() << "calling Connect()";

    QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(
            mConn->Connect());
    QVERIFY(connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
            this, SLOT(expectSuccessfulCall(QDBusPendingCallWatcher*))));
    QCOMPARE(mLoop->exec(), 0);
    delete watcher;

    // Wait for readiness to reach Full

    qDebug() << "waiting for Full readiness";
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));

    QCOMPARE(mConn->readiness(), Connection::ReadinessFull);

    // delete proxy, make a new one
    delete mConn;
    mConn = new Connection(mConnBusName, mConnObjectPath);

    // Wait for introspection to run (readiness changes to Full immediately)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectReady(uint))));

    watcher = new QDBusPendingCallWatcher(
            mConn->Disconnect());
    QVERIFY(connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
            this, SLOT(expectSuccessfulCall(QDBusPendingCallWatcher*))));
    QCOMPARE(mLoop->exec(), 0);
    delete watcher;

    delete mConn;
    mConn = NULL;
}

void TestConnBasics::testInterfaceFactory()
{
    mConn = new Connection(QDBusConnection::sessionBus(),
        mConnBusName, mConnObjectPath);

    QCOMPARE(mConn->readiness(), Connection::ReadinessJustCreated);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusDisconnected));

    // Wait for introspection to run (readiness changes to NYC)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));

    DBus::PropertiesInterface* props = mConn->propertiesInterface();
    QVERIFY(props != NULL);

    DBus::PropertiesInterface* props2 =
        mConn->optionalInterface<DBus::PropertiesInterface>(Connection::BypassInterfaceCheck);
    QVERIFY(props2 == props);

    DBus::PeerInterface* notListed = mConn->optionalInterface<DBus::PeerInterface>();
    QVERIFY(notListed == NULL);
    notListed = mConn->optionalInterface<DBus::PeerInterface>(Connection::BypassInterfaceCheck);
    QVERIFY(notListed != NULL);

    delete mConn;
    mConn = NULL;
}

void TestConnBasics::cleanup()
{
    cleanupImpl();
}

void TestConnBasics::testSpecifiedBus()
{
    mConn = new Connection(QDBusConnection::sessionBus(),
        mConnBusName, mConnObjectPath);

    QCOMPARE(mConn->readiness(), Connection::ReadinessJustCreated);
    QCOMPARE(static_cast<uint>(mConn->status()),
        static_cast<uint>(Telepathy::ConnectionStatusDisconnected));

    // Wait for introspection to run (readiness changes to NYC)
    QVERIFY(connect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(mConn, SIGNAL(readinessChanged(uint)),
          this, SLOT(expectNotYetConnected(uint))));

    delete mConn;
    mConn = NULL;
}

void TestConnBasics::cleanupTestCase()
{
    delete mCM;
    mCM = NULL;

    cleanupTestCaseImpl();
}

QTEST_MAIN(TestConnBasics)
#include "_gen/conn-basics.cpp.moc.hpp"
<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief functions for T[]
	@author MITSUNARI Shigeo(@herumi)
	@license modified new BSD license
	http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/gmp_util.hpp>
#include <cybozu/bit_operation.hpp>

#ifdef _MSC_VER
	#pragma warning(push)
	#pragma warning(disable : 4456)
	#pragma warning(disable : 4459)
#endif

namespace mcl { namespace fp {

/*
	get pp such that p * pp = -1 mod M,
	where p is prime and M = 1 << 64(or 32).
	@param pLow [in] p mod M
*/
template<class T>
T getMontgomeryCoeff(T pLow)
{
	T ret = 0;
	T t = 0;
	T x = 1;
	for (size_t i = 0; i < sizeof(T) * 8; i++) {
		if ((t & 1) == 0) {
			t += pLow;
			ret += x;
		}
		t >>= 1;
		x <<= 1;
	}
	return ret;
}

template<class T>
int compareArray(const T* x, const T* y, size_t n)
{
	for (size_t i = n - 1; i != size_t(-1); i--) {
		T a = x[i];
		T b = y[i];
		if (a != b) return a < b ? -1 : 1;
	}
	return 0;
}

template<class T>
bool isLessArray(const T *x, const T* y, size_t n)
{
	for (size_t i = n - 1; i != size_t(-1); i--) {
		T a = x[i];
		T b = y[i];
		if (a != b) return a < b;
	}
	return false;
}

template<class T>
bool isGreaterOrEqualArray(const T *x, const T* y, size_t n)
{
	return !isLessArray(x, y, n);
}

template<class T>
bool isLessOrEqualArray(const T *x, const T* y, size_t n)
{
	for (size_t i = n - 1; i != size_t(-1); i--) {
		T a = x[i];
		T b = y[i];
		if (a != b) return a < b;
	}
	return true;
}

template<class T>
bool isGreaterArray(const T *x, const T* y, size_t n)
{
	return !isLessOrEqualArray(x, y, n);
}

template<class T>
bool isEqualArray(const T* x, const T* y, size_t n)
{
	for (size_t i = 0; i < n; i++) {
		if (x[i] != y[i]) return false;
	}
	return true;
}

template<class T>
bool isZeroArray(const T *x, size_t n)
{
	for (size_t i = 0; i < n; i++) {
		if (x[i]) return false;
	}
	return true;
}

template<class T>
void clearArray(T *x, size_t begin, size_t end)
{
	for (size_t i = begin; i < end; i++) x[i] = 0;
}

template<class T>
void copyArray(T *y, const T *x, size_t n)
{
	for (size_t i = 0; i < n; i++) y[i] = x[i];
}

/*
	x &= (1 << bitSize) - 1
*/
template<class T>
void maskArray(T *x, size_t n, size_t bitSize)
{
	const size_t TbitSize = sizeof(T) * 8;
	assert(bitSize <= TbitSize * n);
	const size_t q = bitSize / TbitSize;
	const size_t r = bitSize % TbitSize;
	if (r) {
		x[q] &= (T(1) << r) - 1;
		clearArray(x, q + 1, n);
	} else {
		clearArray(x, q, n);
	}
}

/*
	return non zero size of x[]
	return 1 if x[] == 0
*/
template<class T>
size_t getNonZeroArraySize(const T *x, size_t n)
{
	assert(n > 0);
	while (n > 0) {
		if (x[n - 1]) return n;
		n--;
	}
	return 1;
}

namespace impl {

template<class T, class RG>
static void readN(T* out, size_t n, RG& rg)
{
	if (sizeof(T) == 8) {
		for (size_t i = 0; i < n; i++) {
			T L = rg();
			T H = rg();
			out[i] = L | (uint64_t(H) << 32);
		}
	} else {
		for (size_t i = 0; i < n; i++) {
			out[i] = rg();
		}
	}
}

} // impl
/*
	get random value less than in[]
	n = (bitSize + sizeof(T) * 8) / (sizeof(T) * 8)
	input  in[0..n)
	output out[n..n)
	0 <= out < in
*/
template<class RG, class T>
void getRandVal(T *out, RG& rg, const T *in, size_t bitSize)
{
	const size_t TbitSize = sizeof(T) * 8;
	const size_t n = (bitSize + TbitSize - 1) / TbitSize;
	const size_t rem = bitSize & (TbitSize - 1);
	for (;;) {
		impl::readN(out, n, rg);
//		rg.read(out, n);
		if (rem > 0) out[n - 1] &= (T(1) << rem) - 1;
		if (isLessArray(out, in, n)) return;
	}
}

/*
	@param out [inout] : set element of G ; out = x^y[]
	@param x [in]
	@param y [in]
	@param n [in] size of y[]
	@note &out != x and out = the unit element of G
*/
template<class G, class T>
void powGeneric(G& out, const G& x, const T *y, size_t n, void mul(G&, const G&, const G&) , void sqr(G&, const G&))
{
#if 0
	assert(&out != &x);
	while (n > 0) {
		if (y[n - 1]) break;
		n--;
	}
	if (n == 0) return;
	out = x;
	int m = cybozu::bsr<T>(y[n - 1]);
	if (m == 0) {
		if (n == 1) return;
		n--;
		m = (int)sizeof(T) * 8;
	}
	for (int i = (int)n - 1; i >= 0; i--) {
		T v = y[i];
		if (i < n - 1) {
			m = (int)sizeof(T) * 8;
		}
		for (int j = m - 1; j >= 0; j--) {
			sqr(out, out);
			if (v & (T(1) << j)) {
				mul(out, out, x);
			}
		}
	}
#else
	assert(&out != &x);
	while (n > 0) {
		if (y[n - 1]) break;
		n--;
	}
	if (n == 0) return;
	if (n == 1) {
		switch (y[0]) {
		case 1:
			out = x;
			return;
		case 2:
			mul(out, x, x);
			return;
		case 3:
			mul(out, x, x);
			mul(out, out, x);
			return;
		case 4:
			mul(out, x, x);
			mul(out, out, out);
			return;
		}
	}
	G tbl[3]; // tbl = { x, x^2, x^3 }
	tbl[0] = x;
	mul(tbl[1], x, x); tbl[1].normalize();
	mul(tbl[2], tbl[1], x); tbl[2].normalize();
	T v = y[n - 1];
	int m = cybozu::bsr<T>(v);
	if (m & 1) {
		m--;
		T idx = (v >> m) & 3;
		assert(idx > 0);
		out = tbl[idx - 1];
	} else {
		out = x;
	}
	for (int i = (int)n - 1; i >= 0; i--) {
		T v = y[i];
		for (int j = m - 2; j >= 0; j -= 2) {
			sqr(out, out);
			sqr(out, out);
			T idx = (v >> j) & 3;
			if (idx > 0) {
				mul(out, out, tbl[idx - 1]);
			}
		}
		m = (int)sizeof(T) * 8;
	}
#endif
}

/*
	constant time pow
	@note depends on bit length of y[n]
*/
template<class G, class T>
void powGenericCT(G& out, const G& x, const T *y, size_t n, void mul(G&, const G&, const G&) , void sqr(G&, const G&))
{
	assert(&out != &x);
	while (n > 0) {
		if (y[n - 1]) break;
		n--;
	}
	if (n == 0) return;
	G tbl[4]; // tbl = { x, x^2, x^3 }
	tbl[0] = x; // discard
	tbl[1] = x;
	mul(tbl[2], x, x); tbl[2].normalize();
	mul(tbl[3], tbl[2], x); tbl[3].normalize();
	T v = y[n - 1];
	int m = cybozu::bsr<T>(v);
	if (m & 1) {
		m--;
		T idx = (v >> m) & 3;
		assert(idx > 0);
		out = tbl[idx];
	} else {
		out = x;
	}
	G *pTbl[] = { &tbl[0], &out, &out, &out };

	for (int i = (int)n - 1; i >= 0; i--) {
		T v = y[i];
		for (int j = m - 2; j >= 0; j -= 2) {
			sqr(out, out);
			sqr(out, out);
			T idx = (v >> j) & 3;
			mul(*pTbl[idx], *pTbl[idx], tbl[idx]);
		}
		m = (int)sizeof(T) * 8;
	}
}

/*
	shortcut of multiplication by Unit
*/
template<class T, class U>
bool mulSmallUnit(T& z, const T& x, U y)
{
	switch (y) {
	case 0: z.clear(); break;
	case 1: z = x; break;
	case 2: T::add(z, x, x); break;
	case 3: { T t; T::add(t, x, x); T::add(z, t, x); break; }
	case 4: T::add(z, x, x); T::add(z, z, z); break;
	case 5: { T t; T::add(t, x, x); T::add(t, t, t); T::add(z, t, x); break; }
	case 6: { T t; T::add(t, x, x); T::add(t, t, x); T::add(z, t, t); break; }
	case 7: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::sub(z, t, x); break; }
	case 8: T::add(z, x, x); T::add(z, z, z); T::add(z, z, z); break;
	case 9: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::add(z, t, x); break; }
	case 10: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, x); T::add(z, t, t); break; }
	default:
		return false;
	}
	return true;
}

} } // mcl::fp

#ifdef _MSC_VER
	#pragma warning(pop)
#endif
<commit_msg>fix comment<commit_after>#pragma once
/**
	@file
	@brief functions for T[]
	@author MITSUNARI Shigeo(@herumi)
	@license modified new BSD license
	http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/gmp_util.hpp>
#include <cybozu/bit_operation.hpp>

#ifdef _MSC_VER
	#pragma warning(push)
	#pragma warning(disable : 4456)
	#pragma warning(disable : 4459)
#endif

namespace mcl { namespace fp {

/*
	get pp such that p * pp = -1 mod M,
	where p is prime and M = 1 << 64(or 32).
	@param pLow [in] p mod M
*/
template<class T>
T getMontgomeryCoeff(T pLow)
{
	T ret = 0;
	T t = 0;
	T x = 1;
	for (size_t i = 0; i < sizeof(T) * 8; i++) {
		if ((t & 1) == 0) {
			t += pLow;
			ret += x;
		}
		t >>= 1;
		x <<= 1;
	}
	return ret;
}

template<class T>
int compareArray(const T* x, const T* y, size_t n)
{
	for (size_t i = n - 1; i != size_t(-1); i--) {
		T a = x[i];
		T b = y[i];
		if (a != b) return a < b ? -1 : 1;
	}
	return 0;
}

template<class T>
bool isLessArray(const T *x, const T* y, size_t n)
{
	for (size_t i = n - 1; i != size_t(-1); i--) {
		T a = x[i];
		T b = y[i];
		if (a != b) return a < b;
	}
	return false;
}

template<class T>
bool isGreaterOrEqualArray(const T *x, const T* y, size_t n)
{
	return !isLessArray(x, y, n);
}

template<class T>
bool isLessOrEqualArray(const T *x, const T* y, size_t n)
{
	for (size_t i = n - 1; i != size_t(-1); i--) {
		T a = x[i];
		T b = y[i];
		if (a != b) return a < b;
	}
	return true;
}

template<class T>
bool isGreaterArray(const T *x, const T* y, size_t n)
{
	return !isLessOrEqualArray(x, y, n);
}

template<class T>
bool isEqualArray(const T* x, const T* y, size_t n)
{
	for (size_t i = 0; i < n; i++) {
		if (x[i] != y[i]) return false;
	}
	return true;
}

template<class T>
bool isZeroArray(const T *x, size_t n)
{
	for (size_t i = 0; i < n; i++) {
		if (x[i]) return false;
	}
	return true;
}

template<class T>
void clearArray(T *x, size_t begin, size_t end)
{
	for (size_t i = begin; i < end; i++) x[i] = 0;
}

template<class T>
void copyArray(T *y, const T *x, size_t n)
{
	for (size_t i = 0; i < n; i++) y[i] = x[i];
}

/*
	x &= (1 << bitSize) - 1
*/
template<class T>
void maskArray(T *x, size_t n, size_t bitSize)
{
	const size_t TbitSize = sizeof(T) * 8;
	assert(bitSize <= TbitSize * n);
	const size_t q = bitSize / TbitSize;
	const size_t r = bitSize % TbitSize;
	if (r) {
		x[q] &= (T(1) << r) - 1;
		clearArray(x, q + 1, n);
	} else {
		clearArray(x, q, n);
	}
}

/*
	return non zero size of x[]
	return 1 if x[] == 0
*/
template<class T>
size_t getNonZeroArraySize(const T *x, size_t n)
{
	assert(n > 0);
	while (n > 0) {
		if (x[n - 1]) return n;
		n--;
	}
	return 1;
}

namespace impl {

template<class T, class RG>
static void readN(T* out, size_t n, RG& rg)
{
	if (sizeof(T) == 8) {
		for (size_t i = 0; i < n; i++) {
			T L = rg();
			T H = rg();
			out[i] = L | (uint64_t(H) << 32);
		}
	} else {
		for (size_t i = 0; i < n; i++) {
			out[i] = rg();
		}
	}
}

} // impl
/*
	get random value less than in[]
	n = (bitSize + sizeof(T) * 8) / (sizeof(T) * 8)
	input  in[0..n)
	output out[n..n)
	0 <= out < in
*/
template<class RG, class T>
void getRandVal(T *out, RG& rg, const T *in, size_t bitSize)
{
	const size_t TbitSize = sizeof(T) * 8;
	const size_t n = (bitSize + TbitSize - 1) / TbitSize;
	const size_t rem = bitSize & (TbitSize - 1);
	for (;;) {
		impl::readN(out, n, rg);
//		rg.read(out, n);
		if (rem > 0) out[n - 1] &= (T(1) << rem) - 1;
		if (isLessArray(out, in, n)) return;
	}
}

/*
	@param out [inout] : set element of G ; out = x^y[]
	@param x [in]
	@param y [in]
	@param n [in] size of y[]
	@note &out != x and out = the unit element of G
*/
template<class G, class T>
void powGeneric(G& out, const G& x, const T *y, size_t n, void mul(G&, const G&, const G&) , void sqr(G&, const G&))
{
#if 0
	assert(&out != &x);
	while (n > 0) {
		if (y[n - 1]) break;
		n--;
	}
	if (n == 0) return;
	out = x;
	int m = cybozu::bsr<T>(y[n - 1]);
	if (m == 0) {
		if (n == 1) return;
		n--;
		m = (int)sizeof(T) * 8;
	}
	for (int i = (int)n - 1; i >= 0; i--) {
		T v = y[i];
		if (i < n - 1) {
			m = (int)sizeof(T) * 8;
		}
		for (int j = m - 1; j >= 0; j--) {
			sqr(out, out);
			if (v & (T(1) << j)) {
				mul(out, out, x);
			}
		}
	}
#else
	assert(&out != &x);
	while (n > 0) {
		if (y[n - 1]) break;
		n--;
	}
	if (n == 0) return;
	if (n == 1) {
		switch (y[0]) {
		case 1:
			out = x;
			return;
		case 2:
			mul(out, x, x);
			return;
		case 3:
			mul(out, x, x);
			mul(out, out, x);
			return;
		case 4:
			mul(out, x, x);
			mul(out, out, out);
			return;
		}
	}
	G tbl[3]; // tbl = { x, x^2, x^3 }
	tbl[0] = x;
	mul(tbl[1], x, x); tbl[1].normalize();
	mul(tbl[2], tbl[1], x); tbl[2].normalize();
	T v = y[n - 1];
	int m = cybozu::bsr<T>(v);
	if (m & 1) {
		m--;
		T idx = (v >> m) & 3;
		assert(idx > 0);
		out = tbl[idx - 1];
	} else {
		out = x;
	}
	for (int i = (int)n - 1; i >= 0; i--) {
		T v = y[i];
		for (int j = m - 2; j >= 0; j -= 2) {
			sqr(out, out);
			sqr(out, out);
			T idx = (v >> j) & 3;
			if (idx > 0) {
				mul(out, out, tbl[idx - 1]);
			}
		}
		m = (int)sizeof(T) * 8;
	}
#endif
}

/*
	constant time pow
	@note depends on bit length of y[n]
*/
template<class G, class T>
void powGenericCT(G& out, const G& x, const T *y, size_t n, void mul(G&, const G&, const G&) , void sqr(G&, const G&))
{
	assert(&out != &x);
	while (n > 0) {
		if (y[n - 1]) break;
		n--;
	}
	if (n == 0) return;
	G tbl[4]; // tbl = { discard, x, x^2, x^3 }
	tbl[0] = x;
	tbl[1] = x;
	mul(tbl[2], x, x); tbl[2].normalize();
	mul(tbl[3], tbl[2], x); tbl[3].normalize();
	T v = y[n - 1];
	int m = cybozu::bsr<T>(v);
	if (m & 1) {
		m--;
		T idx = (v >> m) & 3;
		assert(idx > 0);
		out = tbl[idx];
	} else {
		out = x;
	}
	G *pTbl[] = { &tbl[0], &out, &out, &out };

	for (int i = (int)n - 1; i >= 0; i--) {
		T v = y[i];
		for (int j = m - 2; j >= 0; j -= 2) {
			sqr(out, out);
			sqr(out, out);
			T idx = (v >> j) & 3;
			mul(*pTbl[idx], *pTbl[idx], tbl[idx]);
		}
		m = (int)sizeof(T) * 8;
	}
}

/*
	shortcut of multiplication by Unit
*/
template<class T, class U>
bool mulSmallUnit(T& z, const T& x, U y)
{
	switch (y) {
	case 0: z.clear(); break;
	case 1: z = x; break;
	case 2: T::add(z, x, x); break;
	case 3: { T t; T::add(t, x, x); T::add(z, t, x); break; }
	case 4: T::add(z, x, x); T::add(z, z, z); break;
	case 5: { T t; T::add(t, x, x); T::add(t, t, t); T::add(z, t, x); break; }
	case 6: { T t; T::add(t, x, x); T::add(t, t, x); T::add(z, t, t); break; }
	case 7: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::sub(z, t, x); break; }
	case 8: T::add(z, x, x); T::add(z, z, z); T::add(z, z, z); break;
	case 9: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::add(z, t, x); break; }
	case 10: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, x); T::add(z, t, t); break; }
	default:
		return false;
	}
	return true;
}

} } // mcl::fp

#ifdef _MSC_VER
	#pragma warning(pop)
#endif
<|endoftext|>


<commit_before>

/******
 This example is not about CRUD. This is an implementation of key-value storage just like
 NSUserDefaults on iOS or SharedPreferences on Android.
 Here is the deal: we need to have `setValueForKey` and `getValueByKey` interface. All data must ba saved in sqlite
 database.
 To perform this we create schema with table `key_value` and two columns: key:string and value:string. There is no
 primary key so we are unable to use CRUD functions like `get`, `get_no_throw`, `remove`, `update`. And there is no need to use
 these functions actually. We use non-CRUD functions `remove_all`, `insert` (it is non-CRUSH cause it doesn't require a table to have a
 primary key column) and `get_all`. `setValue` function takes two string arguments: key and value. It creates a KeyValue
 object (KeyValue is a class mapped to storage) with arguments and performs a transaction. Within this transaction
 first we call `REMOVE FROM key_value WHERE key = '%key%'` and next `INSERT INTO key_value values (%key%, %value%)`.
 After this there is a row in the `key_value` table with key and value passed into `setValue` function.
 `getValue` performs `get_all` with specific condition: `SELECT * FROM key_value WHERE key = '%key%'` and returns a front value if result
 (std::vector<KeyValue>) is not empty or empty string if there is no row with specified key.
 ******/

#include "sqlite_orm.h"

#include <iostream>

using std::cout;
using std::cerr;
using std::endl;

/**
 *  This is just a mapped type. User doesn't have to interact with it directly.
 */
struct KeyValue {
    std::string key;
    std::string value;
};

auto& getStorage() {
    using namespace sqlite_orm;
    static auto storage = make_storage("key_value_example.sqlite",
                                       make_table("key_value",
                                                  make_column("key",
                                                              &KeyValue::key),
                                                  make_column("value",
                                                              &KeyValue::value)));;
    return storage;
}

void setValue(const std::string &key, const std::string &value) {
    using namespace sqlite_orm;
    KeyValue kv{key, value};
    getStorage().transaction([&] {
        getStorage().remove_all<KeyValue>(where(is_equal(&KeyValue::key, key)));
        getStorage().insert(kv);
        return true;
    });
}

std::string getValue(const std::string &key) {
    using namespace sqlite_orm;
    auto kvs = getStorage().get_all<KeyValue>(where(is_equal(&KeyValue::key, key)));
    if(kvs.size()){
        if(kvs.size() == 1){
            return kvs.front().value;
        }else{
            cerr << "kvs for key *" << key << "* is more that 1 (" << kvs.size() << ")" << endl;
            return kvs.front().value;
        }
    }else{
        return {};
    }
}

int storedKeysCount() {
    return getStorage().count<KeyValue>();
}

int main(int argc, char **argv) {

    cout<<argv[0]<<endl;

    getStorage().sync_schema();

    struct {
        std::string userId = "userId";
        std::string userName = "userName";
        std::string userGender = "userGender";  //  this key will be missing
    } keys; //  to keep keys in one place

    setValue(keys.userId, "6");
    setValue(keys.userName, "Peter");

    auto userId = getValue(keys.userId);
    cout << "userId = " << userId << endl;

    auto userName = getValue(keys.userName);
    cout << "userName = " << userName << endl;

    auto userGender = getValue(keys.userGender);
    cout << "userGender = " << userGender << endl;

    auto kvsCount = storedKeysCount();
    cout << "kvsCount = " << kvsCount << endl;

}
<commit_msg>refactored to int/string/any id in CRUD functions<commit_after>

/******
 This example is not about CRUD. This is an implementation of key-value storage just like
 NSUserDefaults on iOS or SharedPreferences on Android.
 Here is the deal: we need to have `setValueForKey` and `getValueByKey` interface. All data must ba saved in sqlite
 database.
 To perform this we create schema with table `key_value` and two columns: key:string and value:string. There is no
 primary key so we are unable to use CRUD functions like `get`, `get_no_throw`, `remove`, `update`. And there is no need to use
 these functions actually. We use non-CRUD functions `remove_all`, `insert` (it is non-CRUSH cause it doesn't require a table to have a
 primary key column) and `get_all`. `setValue` function takes two string arguments: key and value. It creates a KeyValue
 object (KeyValue is a class mapped to storage) with arguments and performs a transaction. Within this transaction
 first we call `REMOVE FROM key_value WHERE key = '%key%'` and next `INSERT INTO key_value values (%key%, %value%)`.
 After this there is a row in the `key_value` table with key and value passed into `setValue` function.
 `getValue` performs `get_all` with specific condition: `SELECT * FROM key_value WHERE key = '%key%'` and returns a front value if result
 (std::vector<KeyValue>) is not empty or empty string if there is no row with specified key.
 ******/

#include "sqlite_orm.h"

#include <iostream>

using std::cout;
using std::cerr;
using std::endl;

/**
 *  This is just a mapped type. User doesn't have to interact with it directly.
 */
struct KeyValue {
    std::string key;
    std::string value;
};

auto& getStorage() {
    using namespace sqlite_orm;
    static auto storage = make_storage("key_value_example.sqlite",
                                       make_table("key_value",
                                                  make_column("key",
                                                              &KeyValue::key),
                                                  make_column("value",
                                                              &KeyValue::value)));;
    return storage;
}

void setValue(const std::string &key, const std::string &value) {
    using namespace sqlite_orm;
    KeyValue kv{key, value};
    getStorage().transaction([&] {
        getStorage().remove_all<KeyValue>(where(is_equal(&KeyValue::key, key)));
        getStorage().insert(kv);
        return true;
    });
}

std::string getValue(const std::string &key) {
    using namespace sqlite_orm;
    auto kvs = getStorage().get_all<KeyValue>(where(is_equal(&KeyValue::key, key)));
    if(kvs.size()){
        if(kvs.size() == 1){
            return kvs.front().value;
        }else{
            cerr << "kvs for key *" << key << "* is more that 1 (" << kvs.size() << ")" << endl;
            return kvs.front().value;
        }
    }else{
        return {};
    }
}

int storedKeysCount() {
    return getStorage().count<KeyValue>();
}

int main(int argc, char **argv) {

    cout << argv[0] << endl;    //  to know executable path in case if you need to access sqlite directly from sqlite client

    getStorage().sync_schema(); //  to create table if it doesn't exist

    struct {
        std::string userId = "userId";
        std::string userName = "userName";
        std::string userGender = "userGender";  //  this key will be missing
    } keys; //  to keep keys in one place

    setValue(keys.userId, "6");
    setValue(keys.userName, "Peter");

    auto userId = getValue(keys.userId);
    cout << "userId = " << userId << endl;  //  userId = 6

    auto userName = getValue(keys.userName);
    cout << "userName = " << userName << endl;  //  userName = Peter

    auto userGender = getValue(keys.userGender);
    cout << "userGender = " << userGender << endl;  //  userGender =

    auto kvsCount = storedKeysCount();
    cout << "kvsCount = " << kvsCount << endl;  //  kvsCount = 2

}
<|endoftext|>


<commit_before><commit_msg>coverity#738754: Unitialized scalar field<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {qb_RoadExtract.tif}
//    OUTPUTS: {RoadExtractBandMath.tif}, {RoadExtractBandMath-pretty.jpg}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This example demonstrates the use of the
//  \doxygen{otb}{BandMathImageFilter} class which allows
//  to perform mathematical operation on the input images.
//  This filter is based on the mathematical parser library muParser.
//  The built in functions and operators list is available at:
//  \ref{http://muparser.sourceforge.net/mup_features.html} \\
//  In order to use this filter, at least one input image is to be
// set. An associated variable name can be specified or not by using
// the corresponding SetNthInput method. For the nth input image, if
// no associated variable name has been spefified, a default variable
// name is given by concatenating the letter "b" (for band) and the
// corresponding input index. \\
// Next step is to set the expression according to the variable
// names. For example, in the default case with three input images the
// following expression is valid : "(b1+b2)*b3".
//
//  Software Guide : EndLatex

#include "itkExceptionObject.h"
#include <iostream>

#include "otbImage.h"
#include "otbObjectList.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "itkCastImageFilter.h"
//  Software Guide : BeginLatex
//
// We start by including the needed header file.
// The aim of this example is to compute the NDVI indice
// from a multispecral image and perform a threshold on this
// indice.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbBandMathImageFilter.h"
// Software Guide : EndCodeSnippet

int main( int argc, char* argv[])
{
  if (argc != 4)
    {
    std::cerr << "Usage: " << argv[0] << " inputImageFile ";
    std::cerr << " outputImageFile ";
    std::cerr << " outputPrettyImageFile" << std::endl;
    return EXIT_FAILURE;
    }

//  Software Guide : BeginLatex
//
//  We start by the classical \code{typedef}s needed for reading and
//  writing the images.The \doxygen{otb}{BandMathImageFilter} class
// works with \doxygen{otb}{Image} as input so we need to define additional
// filters to extract each layer of the multispectral image
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef double                                                        PixelType;
  typedef otb::VectorImage<PixelType, 2>                                InputImageType;
  typedef otb::Image<PixelType, 2>                                      OutputImageType;
  typedef OutputImageType::PixelType                                    VPixelType;
  typedef otb::MultiToMonoChannelExtractROI<VPixelType, VPixelType>     ExtractROIFilterType;
  typedef otb::ObjectList<ExtractROIFilterType>                         ExtractROIFilterListType;
  typedef otb::ImageFileReader<InputImageType>                          ReaderType;
  typedef otb::ImageFileWriter<OutputImageType>                         WriterType;
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  We can now define the type for the filter:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef otb::BandMathImageFilter<OutputImageType>   FilterType;
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  We instantiate the filter, the reader, and the writer:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  FilterType::Pointer filter = FilterType::New();

  writer->SetInput(filter->GetOutput());
  reader->SetFileName(argv[1]);
  writer->SetFileName(argv[2]);
// Software Guide : EndCodeSnippet

  reader->UpdateOutputInformation();

//  Software Guide : BeginLatex
//
//  We need now to extract bands from the \doxygen{otb}{VectorImage},
//  it illustrates the use of the \doxygen{otb}{MultiToMonoChannelExtractROI}.
//  Each extracted layer are inputs of the \doxygen{otb}{BandMathImageFilter}:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  unsigned int bandId = 0;
  ExtractROIFilterListType::Pointer ChannelExtractorList = ExtractROIFilterListType::New();

  for(unsigned int j = 0; j < reader->GetOutput()->GetNumberOfComponentsPerPixel(); ++j)
    {
    std::ostringstream tmpParserVarName;
    tmpParserVarName << "b" << j+1;

    ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
    extractROIFilter->SetInput(reader->GetOutput());
    extractROIFilter->SetChannel(j+1);
    extractROIFilter->GetOutput()->UpdateOutputInformation();
    ChannelExtractorList->PushBack(extractROIFilter);
    filter->SetNthInput(bandId, ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str());
    ++bandId;
    }
// Software Guide : EndCodeSnippet

  filter->SetExpression("sign(ndvi(b3,b4) - 0.4)");

//  Software Guide : BeginLatex
//
//  Now we can define the mathematical expression to perform on the layers (b1, b2,b3,b4).
//  The filter takes advantage of the parsing capabilities of the muParser library and
//  allows to set the expression as on a digital calculator. \\
//  The expression below returns the sign of the ratio $(NIR-RED)/(NIR+RED) - 0,4$.
//  It uses the built-in function sign(x)  which return -1 if x<0; 1 if x>0:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  filter->SetExpression("sign((b4-b3)/(b4+b3) - 0.4)");
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
// The muParser library offers also the possibility to extended existing built-in functions. For example,
// you can use the OTB expression "ndvi(b3,b4)" with the filter. It will return the same result.
//
//  Software Guide : EndLatex

//  Software Guide : BeginLatex
//
//  We can now plug the pipeline and run it.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  writer->Update();
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
// Figure~\ref{fig:BandMathImageFilter} shows the result of the threshold over the NDVI indice
// to a Quickbird image.
// \begin{figure}
// \center
// \includegraphics[width=0.45\textwidth]{qb_RoadExtract.eps}
// \includegraphics[width=0.45\textwidth]{RoadExtractBandMath-pretty.eps}
// \itkcaption[Band Math]{From left to right:
// Original image, thresholded NDVI indice.}
// \label{fig:BandMathImageFilter}
// \end{figure}
//
// Software Guide : EndLatex

  typedef otb::Image<unsigned char, 2>                                      OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputPrettyImageType>            StreamingImageFileWriterType;
  typedef itk::CastImageFilter<OutputImageType, OutputPrettyImageType> CastImageFilterType;

  StreamingImageFileWriterType::Pointer prettyWriter = StreamingImageFileWriterType::New();
  CastImageFilterType::Pointer caster = CastImageFilterType::New();
  caster->SetInput(filter->GetOutput());
  prettyWriter->SetInput(caster->GetOutput());
  prettyWriter->SetFileName(argv[3]);

  prettyWriter->Update();

  return EXIT_SUCCESS;
}
<commit_msg>Automated merge with http://hg.orfeo-toolbox.org/OTB<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {qb_RoadExtract.tif}
//    OUTPUTS: {RoadExtractBandMath.tif}, {qb_BandMath-pretty.jpg}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This filter is based on the mathematical parser library muParser.
//  The built in functions and operators list is available at:
//  \url{http://muparser.sourceforge.net/mup_features.html} \\
//  In order to use this filter, at least one input image is to be
// set. An associated variable name can be specified or not by using
// the corresponding SetNthInput method. For the nth input image, if
// no associated variable name has been specified, a default variable
// name is given by concatenating the letter "b" (for band) and the
// corresponding input index. \\
// The next step is to set the expression according to the variable
// names. For example, in the default case with three input images the
// following expression is valid : "(b1+b2)*b3".
//
//  Software Guide : EndLatex

#include "itkExceptionObject.h"
#include <iostream>

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkCastImageFilter.h"
#include "otbVectorImageToImageListFilter.h"

//  Software Guide : BeginLatex
//
// We start by including the needed header file.
// The aim of this example is to compute the Normalized Difference Vegetation Index (NDVI)
// from a multispecral image and perform a threshold on this
// indice to extract area containing a dense vegetation canopy.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbBandMathImageFilter.h"
// Software Guide : EndCodeSnippet

int main( int argc, char* argv[])
{
  if (argc != 4)
    {
    std::cerr << "Usage: " << argv[0] << " inputImageFile ";
    std::cerr << " outputImageFile ";
    std::cerr << " outputPrettyImageFile" << std::endl;
    return EXIT_FAILURE;
    }

//  Software Guide : BeginLatex
//
//  We start by the classical \code{typedef}s needed for reading and
//  writing the images. The \doxygen{otb}{BandMathImageFilter} class
// works with \doxygen{otb}{Image} as input so we need to define additional
// filters to extract each layer of the multispectral image
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef double                                                          PixelType;
  typedef otb::VectorImage<PixelType, 2>                                  InputImageType;
  typedef otb::Image<PixelType, 2>                                        OutputImageType;
  typedef otb::ImageList<OutputImageType>                                 ImageListType;
  typedef OutputImageType::PixelType                                      VPixelType;
  typedef otb::VectorImageToImageListFilter<InputImageType,ImageListType>
  VectorImageToImageListType;
  typedef otb::ImageFileReader<InputImageType>                            ReaderType;
  typedef otb::ImageFileWriter<OutputImageType>                           WriterType;
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  We can now define the type for the filter:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef otb::BandMathImageFilter<OutputImageType>   FilterType;
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  We instantiate the filter, the reader, and the writer:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  FilterType::Pointer filter = FilterType::New();

  writer->SetInput(filter->GetOutput());
  reader->SetFileName(argv[1]);
  writer->SetFileName(argv[2]);
// Software Guide : EndCodeSnippet

  reader->UpdateOutputInformation();

//  Software Guide : BeginLatex
//
//  We need now to extract now each band from the input \doxygen{otb}{VectorImage},
//  it illustrates the use of the \doxygen{otb}{VectorImageToImageList}.
//  Each extracted layer are inputs of the \doxygen{otb}{BandMathImageFilter}:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  VectorImageToImageListType::Pointer imageList = VectorImageToImageListType::New();
  imageList->SetInput(reader->GetOutput());

  imageList->UpdateOutputInformation();

  const unsigned int nbBands = reader->GetOutput()->GetNumberOfComponentsPerPixel();

  for(unsigned int j = 0; j < nbBands; ++j)
      {
      filter->SetNthInput(j, imageList->GetOutput()->GetNthElement(j));
      }
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Now we can define the mathematical expression to perform on the layers (b1, b2,b3,b4).
//  The filter takes advantage of the parsing capabilities of the muParser library and
//  allows to set the expression as on a digital calculator. \\
//  The expression below returns 255 if the ratio $(NIR-RED)/(NIR+RED)$ is greater than 0.4 and 0 if not.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  filter->SetExpression("if((b4-b3)/(b4+b3) > 0.4,255,0)");
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  We can now plug the pipeline and run it.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  writer->Update();
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
// The muParser library offers also the possibility to extended existing built-in functions. For example,
// you can use the OTB expression "ndvi(b3,b4)" with the filter. The mathematical expression would be in this case \textit{if($ndvi(b3,b4)>0.4$,255,0)}. It will return the same result.
//
//  Software Guide : EndLatex

//  Software Guide : BeginLatex
//
// Figure~\ref{fig:BandMathImageFilter} shows the result of the threshold over the NDVI indice
// to a Quickbird image.
// \begin{figure}
// \center
// \includegraphics[width=0.45\textwidth]{qb_ExtractRoad_pretty.eps}
// \includegraphics[width=0.45\textwidth]{qb_BandMath-pretty.eps}
// \itkcaption[Band Math]{From left to right:
// Original image, thresholded NDVI indice.}
// \label{fig:BandMathImageFilter}
// \end{figure}
//
// Software Guide : EndLatex

  typedef otb::Image<unsigned char, 2>                                      OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputPrettyImageType>            PrettyImageFileWriterType;
  typedef itk::CastImageFilter<OutputImageType, OutputPrettyImageType> CastImageFilterType;

  PrettyImageFileWriterType::Pointer prettyWriter = PrettyImageFileWriterType::New();
  CastImageFilterType::Pointer caster = CastImageFilterType::New();
  caster->SetInput(filter->GetOutput());

  prettyWriter->SetInput(caster->GetOutput());
  prettyWriter->SetFileName(argv[3]);

  prettyWriter->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: VTable.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: oj $ $Date: 2002-11-12 09:17:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_INDEX_HXX_
#include "connectivity/sdbcx/VIndex.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_
#include "connectivity/sdbcx/VKey.hxx"
#endif

// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTable::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VTableDescriptor");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table");
}

// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OTable::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.TableDescriptor");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OTable::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OTable::OTable(OCollection* _pTables,
               sal_Bool _bCase)
               : OTableDescriptor_BASE(m_aMutex)
                ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase,sal_True)
                ,m_pKeys(NULL)
                ,m_pColumns(NULL)
                ,m_pIndexes(NULL)
                ,m_pTables(_pTables)
{
}
// -----------------------------------------------------------------------------
OTable::OTable( OCollection*    _pTables,
                sal_Bool _bCase,
                const ::rtl::OUString& _Name,       const ::rtl::OUString& _Type,
                const ::rtl::OUString& _Description,const ::rtl::OUString& _SchemaName,
                const ::rtl::OUString& _CatalogName) :  OTableDescriptor_BASE(m_aMutex)
                ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase)
                ,m_pKeys(NULL)
                ,m_pColumns(NULL)
                ,m_pIndexes(NULL)
                ,m_CatalogName(_CatalogName)
                ,m_SchemaName(_SchemaName)
                ,m_Description(_Description)
                ,m_Type(_Type)
                ,m_pTables(_pTables)
{
    m_Name = _Name;
}
// -------------------------------------------------------------------------
OTable::~OTable()
{
    delete m_pKeys;
    delete m_pColumns;
    delete m_pIndexes;
}
// -------------------------------------------------------------------------
void OTable::construct()
{
    ODescriptor::construct();

    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;

    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CATALOGNAME),     PROPERTY_ID_CATALOGNAME,nAttrib,&m_CatalogName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCHEMANAME),      PROPERTY_ID_SCHEMANAME, nAttrib,&m_SchemaName,  ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION),     PROPERTY_ID_DESCRIPTION,nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE),            PROPERTY_ID_TYPE,       nAttrib,&m_Type,        ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
}
// -----------------------------------------------------------------------------
void SAL_CALL OTable::acquire() throw()
{
    OTableDescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OTable::release() throw()
{
    OTableDescriptor_BASE::release();
}

// -------------------------------------------------------------------------
Any SAL_CALL OTable::queryInterface( const Type & rType ) throw(RuntimeException)
{
    Any aRet = ODescriptor::queryInterface( rType);
    if(!aRet.hasValue())
    {
        if(!isNew())
            aRet = OTable_BASE::queryInterface( rType);
        if(isNew() && (rType == getCppuType( (Reference<XIndexesSupplier>*)0)))
            return Any();
        if(!aRet.hasValue())
            aRet = OTableDescriptor_BASE::queryInterface( rType);
    }
    return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OTable::getTypes(  ) throw(RuntimeException)
{
    if(isNew())
        return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes());
    return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes(),OTable_BASE::getTypes());
}
// -------------------------------------------------------------------------
void SAL_CALL OTable::disposing(void)
{
    ODescriptor::disposing();

    ::osl::MutexGuard aGuard(m_aMutex);

    if(m_pKeys)
        m_pKeys->disposing();
    if(m_pColumns)
        m_pColumns->disposing();
    if(m_pIndexes)
        m_pIndexes->disposing();

    m_pTables = NULL;
}
// -----------------------------------------------------------------------------
// XColumnsSupplier
Reference< XNameAccess > SAL_CALL OTable::getColumns(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    try
    {
        if ( !m_pColumns )
            refreshColumns();
    }
    catch( const RuntimeException& )
    {
        // allowed to leave this method
        throw;
    }
    catch( const Exception& )
    {
        // allowed
    }

    return m_pColumns;
}

// -------------------------------------------------------------------------
// XKeysSupplier
Reference< XIndexAccess > SAL_CALL OTable::getKeys(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    try
    {
        if(!m_pKeys)
            refreshKeys();
    }
    catch( const RuntimeException& )
    {
        // allowed to leave this method
        throw;
    }
    catch( const Exception& )
    {
        // allowed
    }

    return m_pKeys;
}
// -----------------------------------------------------------------------------
cppu::IPropertyArrayHelper* OTable::createArrayHelper( sal_Int32 _nId) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    changePropertyAttributte(aProps);
    return new cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
cppu::IPropertyArrayHelper & OTable::getInfoHelper()
{
    return *const_cast<OTable*>(this)->getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OTable::createDataDescriptor(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    return this;
}
// -------------------------------------------------------------------------
// XIndexesSupplier
Reference< XNameAccess > SAL_CALL OTable::getIndexes(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    try
    {
        if ( !m_pIndexes )
            refreshIndexes();
    }
    catch( const RuntimeException& )
    {
        // allowed to leave this method
        throw;
    }
    catch( const Exception& )
    {
        // allowed
    }

    return m_pIndexes;
}
// -------------------------------------------------------------------------
// XRename
void SAL_CALL OTable::rename( const ::rtl::OUString& newName ) throw(SQLException, ElementExistException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    ::rtl::OUString sOldComposedName = getName();
    ::rtl::OUString sNewComposedName;
    sal_Int32 nPos = sOldComposedName.lastIndexOf('.');
    if(nPos != -1)
    {
        sNewComposedName = sOldComposedName.copy(0,nPos);
        sNewComposedName += ::rtl::OUString::createFromAscii(".") ;
        sNewComposedName += newName;
    }
    else
        sNewComposedName = newName;

    m_pTables->renameObject(sOldComposedName,sNewComposedName);
    m_Name = newName;
}
// -------------------------------------------------------------------------
// XAlterTable
void SAL_CALL OTable::alterColumnByName( const ::rtl::OUString& colName, const Reference< XPropertySet >& descriptor ) throw(SQLException, NoSuchElementException, RuntimeException)
{
}
// -------------------------------------------------------------------------
void SAL_CALL OTable::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException)
{
}
// -------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OTable::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTable::getName() throw(::com::sun::star::uno::RuntimeException)
{
    // this is only correct for tables who haven't a schema or catalog name
    OSL_ENSURE(!m_CatalogName.getLength(),"getName(): forgot to overload getName()!");
    OSL_ENSURE(!m_SchemaName.getLength(),"getName(): forgot to overload getName()!");
    return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OTable::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
}
// -----------------------------------------------------------------------------
void OTable::refreshColumns()
{
}
// -----------------------------------------------------------------------------
void OTable::refreshKeys()
{
}
// -----------------------------------------------------------------------------
void OTable::refreshIndexes()
{
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS insight01 (1.16.92); FILE MERGED 2004/06/29 12:55:01 oj 1.16.92.1: #i30626# naming corrected<commit_after>/*************************************************************************
 *
 *  $RCSfile: VTable.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 17:17:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_INDEX_HXX_
#include "connectivity/sdbcx/VIndex.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_
#include "connectivity/sdbcx/VKey.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif

// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTable::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VTableDescriptor");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table");
}

// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OTable::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.TableDescriptor");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OTable::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OTable::OTable(OCollection* _pTables,
               sal_Bool _bCase)
               : OTableDescriptor_BASE(m_aMutex)
                ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase,sal_True)
                ,m_pKeys(NULL)
                ,m_pColumns(NULL)
                ,m_pIndexes(NULL)
                ,m_pTables(_pTables)
{
}
// -----------------------------------------------------------------------------
OTable::OTable( OCollection*    _pTables,
                sal_Bool _bCase,
                const ::rtl::OUString& _Name,       const ::rtl::OUString& _Type,
                const ::rtl::OUString& _Description,const ::rtl::OUString& _SchemaName,
                const ::rtl::OUString& _CatalogName) :  OTableDescriptor_BASE(m_aMutex)
                ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase)
                ,m_pKeys(NULL)
                ,m_pColumns(NULL)
                ,m_pIndexes(NULL)
                ,m_CatalogName(_CatalogName)
                ,m_SchemaName(_SchemaName)
                ,m_Description(_Description)
                ,m_Type(_Type)
                ,m_pTables(_pTables)
{
    m_Name = _Name;
}
// -------------------------------------------------------------------------
OTable::~OTable()
{
    delete m_pKeys;
    delete m_pColumns;
    delete m_pIndexes;
}
// -------------------------------------------------------------------------
void OTable::construct()
{
    ODescriptor::construct();

    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;

    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CATALOGNAME),     PROPERTY_ID_CATALOGNAME,nAttrib,&m_CatalogName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCHEMANAME),      PROPERTY_ID_SCHEMANAME, nAttrib,&m_SchemaName,  ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION),     PROPERTY_ID_DESCRIPTION,nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE),            PROPERTY_ID_TYPE,       nAttrib,&m_Type,        ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
}
// -----------------------------------------------------------------------------
void SAL_CALL OTable::acquire() throw()
{
    OTableDescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OTable::release() throw()
{
    OTableDescriptor_BASE::release();
}

// -------------------------------------------------------------------------
Any SAL_CALL OTable::queryInterface( const Type & rType ) throw(RuntimeException)
{
    Any aRet = ODescriptor::queryInterface( rType);
    if(!aRet.hasValue())
    {
        if(!isNew())
            aRet = OTable_BASE::queryInterface( rType);
        if(isNew() && (rType == getCppuType( (Reference<XIndexesSupplier>*)0)))
            return Any();
        if(!aRet.hasValue())
            aRet = OTableDescriptor_BASE::queryInterface( rType);
    }
    return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OTable::getTypes(  ) throw(RuntimeException)
{
    if(isNew())
        return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes());
    return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes(),OTable_BASE::getTypes());
}
// -------------------------------------------------------------------------
void SAL_CALL OTable::disposing(void)
{
    ODescriptor::disposing();

    ::osl::MutexGuard aGuard(m_aMutex);

    if(m_pKeys)
        m_pKeys->disposing();
    if(m_pColumns)
        m_pColumns->disposing();
    if(m_pIndexes)
        m_pIndexes->disposing();

    m_pTables = NULL;
}
// -----------------------------------------------------------------------------
// XColumnsSupplier
Reference< XNameAccess > SAL_CALL OTable::getColumns(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    try
    {
        if ( !m_pColumns )
            refreshColumns();
    }
    catch( const RuntimeException& )
    {
        // allowed to leave this method
        throw;
    }
    catch( const Exception& )
    {
        // allowed
    }

    return m_pColumns;
}

// -------------------------------------------------------------------------
// XKeysSupplier
Reference< XIndexAccess > SAL_CALL OTable::getKeys(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    try
    {
        if(!m_pKeys)
            refreshKeys();
    }
    catch( const RuntimeException& )
    {
        // allowed to leave this method
        throw;
    }
    catch( const Exception& )
    {
        // allowed
    }

    return m_pKeys;
}
// -----------------------------------------------------------------------------
cppu::IPropertyArrayHelper* OTable::createArrayHelper( sal_Int32 _nId) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    changePropertyAttributte(aProps);
    return new cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
cppu::IPropertyArrayHelper & OTable::getInfoHelper()
{
    return *const_cast<OTable*>(this)->getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OTable::createDataDescriptor(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    OTable* pTable = new OTable(m_pTables,isCaseSensitive(),m_Name,m_Type,m_Description,m_SchemaName,m_CatalogName);
    pTable->setNew(sal_True);
    return pTable;
}
// -------------------------------------------------------------------------
// XIndexesSupplier
Reference< XNameAccess > SAL_CALL OTable::getIndexes(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    try
    {
        if ( !m_pIndexes )
            refreshIndexes();
    }
    catch( const RuntimeException& )
    {
        // allowed to leave this method
        throw;
    }
    catch( const Exception& )
    {
        // allowed
    }

    return m_pIndexes;
}
// -------------------------------------------------------------------------
// XRename
void SAL_CALL OTable::rename( const ::rtl::OUString& newName ) throw(SQLException, ElementExistException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);

    ::rtl::OUString sOldComposedName = getName();
    Reference< XDatabaseMetaData> xMetaData = getMetaData();
    if ( xMetaData.is() )
        ::dbtools::qualifiedNameComponents(xMetaData,newName,m_CatalogName,m_SchemaName,m_Name,::dbtools::eInDataManipulation);
    else
        m_Name = newName;

    m_pTables->renameObject(sOldComposedName,newName);
}
// -----------------------------------------------------------------------------
Reference< XDatabaseMetaData> OTable::getMetaData() const
{
    return NULL;
}
// -------------------------------------------------------------------------
// XAlterTable
void SAL_CALL OTable::alterColumnByName( const ::rtl::OUString& colName, const Reference< XPropertySet >& descriptor ) throw(SQLException, NoSuchElementException, RuntimeException)
{
}
// -------------------------------------------------------------------------
void SAL_CALL OTable::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException)
{
}
// -------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OTable::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTable::getName() throw(::com::sun::star::uno::RuntimeException)
{
    // this is only correct for tables who haven't a schema or catalog name
    OSL_ENSURE(!m_CatalogName.getLength(),"getName(): forgot to overload getName()!");
    OSL_ENSURE(!m_SchemaName.getLength(),"getName(): forgot to overload getName()!");
    return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OTable::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
}
// -----------------------------------------------------------------------------
void OTable::refreshColumns()
{
}
// -----------------------------------------------------------------------------
void OTable::refreshKeys()
{
}
// -----------------------------------------------------------------------------
void OTable::refreshIndexes()
{
}
// -----------------------------------------------------------------------------
<|endoftext|>