<commit_before>//
//  ofxInFocusSerial.cpp
//  greveGulv
//
//  Created by Tobias Ebsen on 13/05/14.
//
//

#include "ofxInFocusSerial.h"

bool ofxInFocusSerial::setup(string portName) {

    bool result = ofSerial::setup(portName, 19200);

    // Disable hardware flow control
    struct termios options;
	tcgetattr(fd, &options);
    options.c_iflag &= ~(IXON | IXOFF);
    options.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    options.c_cflag &= ~CRTSCTS;
    tcsetattr(fd, TCSANOW, &options);

    return result;
}

vector<string> ofxInFocusSerial::getPortNames() {
    vector<string> names;
    vector<ofSerialDeviceInfo> list = ofSerial::getDeviceList();
    vector<ofSerialDeviceInfo>::iterator it = list.begin();
    for (; it!=list.end(); ++it) {
        names.push_back(it->getDeviceName());
    }
    return names;
}

bool ofxInFocusSerial::isPowerOn() {
    commandRead("PWR");
    return getResponseInt() == 1;
}

void ofxInFocusSerial::setPowerOn(bool on) {
    commandWrite("PWR", on ? 1 : 0);
}

int ofxInFocusSerial::getLampHoursNormal() {
    commandRead("LMO");
    return getResponseInt();
}

int ofxInFocusSerial::getLampHoursEco() {
    commandRead("LME");
    return getResponseInt();
}

bool ofxInFocusSerial::isLampEco() {
    commandRead("IPM");
    return getResponseInt() == 1;
}

void ofxInFocusSerial::setLampEco(bool eco) {
    commandWrite("IPM", eco ? 1 : 0);
}

string ofxInFocusSerial::getFirmwareVersion() {
    commandRead("FVS");
    return getResponseString();
}

int ofxInFocusSerial::getSystemState() {
    commandRead("SYS");
    return getResponseInt();
}

void ofxInFocusSerial::write(string str) {
    ofSerial::writeBytes((unsigned char*)str.c_str(), str.length());
}

string ofxInFocusSerial::read() {
    char str[64];
    int n = ofSerial::readBytes((unsigned char*)str, sizeof(str));
    if (n > 0)
        str[n] = 0;
    else
        str[0] = 0;
    return str;
}

void ofxInFocusSerial::commandWrite(string cmd, int value) {
    write("(" + cmd + ofToString(value) + ")");
    ofSerial::drain();
}

string ofxInFocusSerial::commandRead(string cmd) {

    ofSerial::flush();
    write("(" + cmd + "?)");
    ofSerial::drain();

    unsigned long long before = ofGetElapsedTimeMillis();
    response = read();
    while (response.find(")") == -1 && ofGetElapsedTimeMillis() - before < 2000) {
        ofSleepMillis(1);
        response.append(read());
    };
    return response;
}

int ofxInFocusSerial::getResponseInt() {
    int b = response.find(",");
    int e = response.find(")");
    if (b != -1 && e != -1) {
        string str = response.substr(b+1,e-b-1);
        return  ofToInt(str);
    }
    return -1;
}

string ofxInFocusSerial::getResponseString() {
    int b = response.find("\"");
    int e = response.find_last_of('\"');
    if (b != -1 && e != -1)
        return response.substr(b+1, e-b-1);
    else
        return "";
}
<commit_msg>Do some checks<commit_after>//
//  ofxInFocusSerial.cpp
//  greveGulv
//
//  Created by Tobias Ebsen on 13/05/14.
//
//

#include "ofxInFocusSerial.h"

bool ofxInFocusSerial::setup(string portName) {

    bool success = ofSerial::setup(portName, 19200);

    if (success) {

        // Disable hardware flow control
        struct termios options;
        tcgetattr(fd, &options);
        options.c_iflag &= ~(IXON | IXOFF);
        options.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
        options.c_cflag &= ~CRTSCTS;
        tcsetattr(fd, TCSANOW, &options);
    }
    return success;
}

vector<string> ofxInFocusSerial::getPortNames() {
    vector<string> names;
    vector<ofSerialDeviceInfo> list = ofSerial::getDeviceList();
    vector<ofSerialDeviceInfo>::iterator it = list.begin();
    for (; it!=list.end(); ++it) {
        names.push_back(it->getDeviceName());
    }
    return names;
}

bool ofxInFocusSerial::isPowerOn() {
    commandRead("PWR");
    return getResponseInt() == 1;
}

void ofxInFocusSerial::setPowerOn(bool on) {
    commandWrite("PWR", on ? 1 : 0);
}

int ofxInFocusSerial::getLampHoursNormal() {
    commandRead("LMO");
    return getResponseInt();
}

int ofxInFocusSerial::getLampHoursEco() {
    commandRead("LME");
    return getResponseInt();
}

bool ofxInFocusSerial::isLampEco() {
    commandRead("IPM");
    return getResponseInt() == 1;
}

void ofxInFocusSerial::setLampEco(bool eco) {
    commandWrite("IPM", eco ? 1 : 0);
}

string ofxInFocusSerial::getFirmwareVersion() {
    commandRead("FVS");
    return getResponseString();
}

int ofxInFocusSerial::getSystemState() {
    commandRead("SYS");
    return getResponseInt();
}

void ofxInFocusSerial::write(string str) {
    if (!isInitialized())
        return;

    ofSerial::writeBytes((unsigned char*)str.c_str(), str.length());
}

string ofxInFocusSerial::read() {

    if (!isInitialized())
        return "";

    char str[64];
    int n = ofSerial::readBytes((unsigned char*)str, sizeof(str));
    if (n > 0)
        str[n] = 0;
    else
        str[0] = 0;

    return str;
}

void ofxInFocusSerial::commandWrite(string cmd, int value) {
    write("(" + cmd + ofToString(value) + ")");
    ofSerial::drain();
}

string ofxInFocusSerial::commandRead(string cmd) {

    ofSerial::flush();
    write("(" + cmd + "?)");
    ofSerial::drain();

    unsigned long long before = ofGetElapsedTimeMillis();
    response = read();
    while (response.find(")") == -1 && ofGetElapsedTimeMillis() - before < 2000) {
        ofSleepMillis(1);
        response.append(read());
    };
    return response;
}

int ofxInFocusSerial::getResponseInt() {
    int b = response.find(",");
    int e = response.find(")");
    if (b != -1 && e != -1) {
        string str = response.substr(b+1,e-b-1);
        return  ofToInt(str);
    }
    return -1;
}

string ofxInFocusSerial::getResponseString() {
    int b = response.find("\"");
    int e = response.find_last_of('\"');
    if (b != -1 && e != -1)
        return response.substr(b+1, e-b-1);
    else
        return "";
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#include <uv.h>
#include <cstdlib>
#include <yajr/internal/comms.hpp>
#include <opflex/logging/internal/logging.hpp>
#include <boost/scoped_ptr.hpp>
#include <yajr/rpc/rpc.hpp>

#include <cstdio>

int ::yajr::initLoop(uv_loop_t * loop) {

    if (!(loop->data = new (std::nothrow)
                ::yajr::comms::internal::Peer::LoopData(loop))) {
        LOG(WARNING) <<
            ": out of memory, cannot instantiate uv_loop LoopData";
        return UV_ENOMEM;
    }

    return 0;

}

void ::yajr::finiLoop(uv_loop_t * loop) {
    LOG(INFO);

    static_cast< ::yajr::comms::internal::Peer::LoopData *>(loop->data)->destroy();

}

namespace yajr { namespace comms {

using namespace yajr::comms::internal;

void internal::Peer::LoopData::onIdleLoop() {

    uint64_t now = uv_now(idle_.loop);

    peers[TO_RESOLVE]
        .clear_and_dispose(RetryPeer());

    peers[TO_LISTEN]
        .clear_and_dispose(RetryPeer());

    if (now - lastRun_ < 30000) {
        return;
    }

    LOG(DEBUG);

    lastRun_ = now;

    /* retry all listeners */
    peers[RETRY_TO_LISTEN]
        .clear_and_dispose(RetryPeer());

    /* retry just the first active peer in the queue */
    peers[RETRY_TO_CONNECT]
        .erase_and_dispose(peers[RETRY_TO_CONNECT].begin(), RetryPeer());

}

void internal::Peer::LoopData::onIdleLoop(uv_idle_t * h) {

    static_cast< ::yajr::comms::internal::Peer::LoopData *>(h->data)
        ->onIdleLoop();

}

void internal::Peer::LoopData::fini(uv_handle_t * h) {
    LOG(INFO);

    static_cast< ::yajr::comms::internal::Peer::LoopData *>(h->data)->down();
}

void internal::Peer::LoopData::destroy() {
    LOG(INFO);

    uv_idle_stop(&idle_);
    uv_close((uv_handle_t*)&idle_, &fini);

    assert(idle_.data == this);

    destroying_ = 1;

    for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
        Peer::LoopData::getPeerList(uv_default_loop(),
                    Peer::LoopData::PeerState(i))
            ->clear_and_dispose(PeerDisposer());

    }
}

/*
                    ____
                   / ___|___  _ __ ___  _ __ ___   ___  _ __
                  | |   / _ \| '_ ` _ \| '_ ` _ \ / _ \| '_ \
                  | |__| (_) | | | | | | | | | | | (_) | | | |
                   \____\___/|_| |_| |_|_| |_| |_|\___/|_| |_|

                     ____      _ _ _                _
                    / ___|__ _| | | |__   __ _  ___| | _____
                   | |   / _` | | | '_ \ / _` |/ __| |/ / __|
                   | |__| (_| | | | |_) | (_| | (__|   <\__ \
                    \____\__,_|_|_|_.__/ \__,_|\___|_|\_\___/

                                                              (Common Callbacks)
*/

namespace internal {

void alloc_cb(uv_handle_t * _, size_t size, uv_buf_t* buf) {

    LOG(DEBUG);

    *buf = uv_buf_init((char*) malloc(size + 1), size);

    return;
}

void on_close(uv_handle_t * h) {

    CommunicationPeer * peer = Peer::get<CommunicationPeer>(h);

    LOG(DEBUG) << peer;

    LOG(DEBUG) << peer << " down() for an on_close()";
    peer->down();

    return;
}

void on_write(uv_write_t *req, int status) {

    LOG(DEBUG);

    if (status == UV_ECANCELED || status == UV_ECONNRESET) {
        LOG(INFO) << "[" << uv_err_name(status) << "] " << uv_strerror(status);
        return;  /* Handle has been closed. */
    }

    /* see here if more output can be dequeued */

    CommunicationPeer * peer = Peer::get(req);

    peer->onWrite();

    return;
}

void on_read(uv_stream_t * h, ssize_t nread, uv_buf_t const * buf)
{

    CommunicationPeer * peer = Peer::get<CommunicationPeer>(h);

    LOG(DEBUG) << peer;

    if (nread < 0) {
        LOG(INFO) << "nread = " << nread << " [" << uv_err_name(nread) <<
            "] " << uv_strerror(nread) << " => closing";
        peer->onDisconnect();
    }

    if (nread > 0) {

        LOG(INFO) << peer
            << " read " << nread << " into buffer of size " << buf->len;

        char * buffer = buf->base;
        size_t chunk_size;
        buffer[nread++]='\0';

        while (--nread > 0) {
            chunk_size = peer->readChunk(buffer);
            nread -= chunk_size++;

            LOG(DEBUG) << "nread=" << nread << " chunk_size=" << chunk_size;

            if(nread) {

                LOG(DEBUG) << "got: " << chunk_size;

                buffer += chunk_size;

                boost::scoped_ptr<yajr::rpc::InboundMessage> msg(
                        peer->parseFrame()
                    );

                if (!msg) {
                    LOG(ERROR) << "skipping inbound message";
                    continue;
                }

                msg->process();

            }
        }
    }

    if (buf->base) {
        free(buf->base);
    }

}

} /* yajr::comms::internal namespace */

}} /* yajr::comms and opflex namespaces */
<commit_msg>tweak retry to connect interval, fix crash<commit_after>/*
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#include <uv.h>
#include <cstdlib>
#include <yajr/internal/comms.hpp>
#include <opflex/logging/internal/logging.hpp>
#include <boost/scoped_ptr.hpp>
#include <yajr/rpc/rpc.hpp>

#include <cstdio>

int ::yajr::initLoop(uv_loop_t * loop) {

    if (!(loop->data = new (std::nothrow)
                ::yajr::comms::internal::Peer::LoopData(loop))) {
        LOG(WARNING) <<
            ": out of memory, cannot instantiate uv_loop LoopData";
        return UV_ENOMEM;
    }

    return 0;

}

void ::yajr::finiLoop(uv_loop_t * loop) {
    LOG(INFO);

    static_cast< ::yajr::comms::internal::Peer::LoopData *>(loop->data)->destroy();

}

namespace yajr { namespace comms {

using namespace yajr::comms::internal;

void internal::Peer::LoopData::onIdleLoop() {

    uint64_t now = uv_now(idle_.loop);

    peers[TO_RESOLVE]
        .clear_and_dispose(RetryPeer());

    peers[TO_LISTEN]
        .clear_and_dispose(RetryPeer());

    if (now - lastRun_ < 750) {
        return;
    }

    if (peers[RETRY_TO_CONNECT].begin() !=
        peers[RETRY_TO_CONNECT].begin()) {

        LOG(INFO) << "retrying first RETRY_TO_CONNECT peer";

        /* retry just the first active peer in the queue */
        peers[RETRY_TO_CONNECT]
            .erase_and_dispose(peers[RETRY_TO_CONNECT].begin(), RetryPeer());

    }

    if (now - lastRun_ > 15000) {

        LOG(INFO) << "retrying all RETRY_TO_LISTEN peers";

        /* retry all listeners */
        peers[RETRY_TO_LISTEN]
            .clear_and_dispose(RetryPeer());
    }

    lastRun_ = now;

}

void internal::Peer::LoopData::onIdleLoop(uv_idle_t * h) {

    static_cast< ::yajr::comms::internal::Peer::LoopData *>(h->data)
        ->onIdleLoop();

}

void internal::Peer::LoopData::fini(uv_handle_t * h) {
    LOG(INFO);

    static_cast< ::yajr::comms::internal::Peer::LoopData *>(h->data)->down();
}

void internal::Peer::LoopData::destroy() {
    LOG(INFO);

    uv_idle_stop(&idle_);
    uv_close((uv_handle_t*)&idle_, &fini);

    assert(idle_.data == this);

    destroying_ = 1;

    for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
        Peer::LoopData::getPeerList(uv_default_loop(),
                    Peer::LoopData::PeerState(i))
            ->clear_and_dispose(PeerDisposer());

    }
}

/*
                    ____
                   / ___|___  _ __ ___  _ __ ___   ___  _ __
                  | |   / _ \| '_ ` _ \| '_ ` _ \ / _ \| '_ \
                  | |__| (_) | | | | | | | | | | | (_) | | | |
                   \____\___/|_| |_| |_|_| |_| |_|\___/|_| |_|

                     ____      _ _ _                _
                    / ___|__ _| | | |__   __ _  ___| | _____
                   | |   / _` | | | '_ \ / _` |/ __| |/ / __|
                   | |__| (_| | | | |_) | (_| | (__|   <\__ \
                    \____\__,_|_|_|_.__/ \__,_|\___|_|\_\___/

                                                              (Common Callbacks)
*/

namespace internal {

void alloc_cb(uv_handle_t * _, size_t size, uv_buf_t* buf) {

    LOG(DEBUG);

    *buf = uv_buf_init((char*) malloc(size + 1), size);

    return;
}

void on_close(uv_handle_t * h) {

    CommunicationPeer * peer = Peer::get<CommunicationPeer>(h);

    LOG(DEBUG) << peer;

    LOG(DEBUG) << peer << " down() for an on_close()";
    peer->down();

    return;
}

void on_write(uv_write_t *req, int status) {

    LOG(DEBUG);

    if (status == UV_ECANCELED || status == UV_ECONNRESET) {
        LOG(INFO) << "[" << uv_err_name(status) << "] " << uv_strerror(status);
        return;  /* Handle has been closed. */
    }

    /* see here if more output can be dequeued */

    CommunicationPeer * peer = Peer::get(req);

    peer->onWrite();

    return;
}

void on_read(uv_stream_t * h, ssize_t nread, uv_buf_t const * buf)
{

    CommunicationPeer * peer = Peer::get<CommunicationPeer>(h);

    LOG(DEBUG) << peer;

    if (nread < 0) {
        LOG(INFO) << "nread = " << nread << " [" << uv_err_name(nread) <<
            "] " << uv_strerror(nread) << " => closing";
        peer->onDisconnect();
    }

    if (nread > 0) {

        LOG(INFO) << peer
            << " read " << nread << " into buffer of size " << buf->len;

        char * buffer = buf->base;
        size_t chunk_size;
        buffer[nread++]='\0';

        while (--nread > 0) {
            chunk_size = peer->readChunk(buffer);
            nread -= chunk_size++;

            LOG(DEBUG) << "nread=" << nread << " chunk_size=" << chunk_size;

            if(nread) {

                LOG(DEBUG) << "got: " << chunk_size;

                buffer += chunk_size;

                boost::scoped_ptr<yajr::rpc::InboundMessage> msg(
                        peer->parseFrame()
                    );

                if (!msg) {
                    LOG(ERROR) << "skipping inbound message";
                    continue;
                }

                msg->process();

            }
        }
    }

    if (buf->base) {
        free(buf->base);
    }

}

} /* yajr::comms::internal namespace */

}} /* yajr::comms and opflex namespaces */
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include "onimeshfunctions.h"

namespace onimesh
{
	const int FRAME_DATA_MOD = 100;

	/// <summary>
	/// Creates a name for an output file
	/// </summary>
	std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
	{
		// If the path contains '/' characters
		if (std::string(inputFile).find_last_of('/') != std::string::npos)
		{
			// Check if the directory needs a trailing '/'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));

			return std::string(outputDirectory + std::string("/") + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
		}
		// If the path contains '\' characters
		else if (std::string(inputFile).find_last_of('\\') == std::string::npos)
		{
			// Check if the directory needs a trailing '\'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));

			return std::string(outputDirectory + std::string("\\") + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));
		}

		// Otherwise the input file does not contain a path
		// Check if the directory needs a trailing '/'
		if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
			return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));

		return std::string(std::string(outputDirectory) + std::string("/") + std::string(inputFile) + std::string(fileExtension));
	}

	/// <summary>
	/// Reads oni input and exports data as excel docs
	/// </summary>
	void outputExcel(const int argc, const char** argv)
	{
		std::cout << "Start excel data output...\n";

        const char* outputDirectory = argv[1];
        char* inputFile;
		const int numberInputFiles = argc - 2;
		openni::Device device;
		openni::VideoStream ir;
		openni::VideoFrameRef irf;
		OniDepthPixel* pDepth;
		int frameHeight, frameWidth;
		long frameIndex, numberOfFrames;
		std::ofstream out;

        // Initialize openni
        openni::Status rc = openni::OpenNI::initialize();
        if (rc != openni::STATUS_OK)
        {
            printf("Initialize failed\n%s\n", openni::OpenNI::getExtendedError());
            exit(2);
        }

		// Output excel doc for each input file
		for (int w = 0; w < numberInputFiles; ++w)
		{
			inputFile = (char*)argv[w + 2];
			std::cout << "Working on file " << inputFile << "...\n";

			// Open the .oni file
			rc = device.open(inputFile);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError());
                exit(3);
            }

            // Create the Video Stream
			rc = ir.create(device, openni::SENSOR_DEPTH);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't create depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(4);
            }

			// Device Check
			if (!device.isValid())
			{
				std::cerr << "\nThe device is not valid.\n";
				exit(5);
			}

			// Verify the device is a file
			if (!device.isFile())
			{
				std::cerr << "\nThe device is not a file.\n";
				exit(6);
			}
			std::cout << "File open success...\n";

			// Set playback controls
			openni::PlaybackControl* pbc = device.getPlaybackControl();
			pbc->setSpeed(-1);
			pbc->setRepeatEnabled(false);

			// Open output file
			std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
			out.open(outputFile);

			// Read all frames
			numberOfFrames = pbc->getNumberOfFrames(ir);
			std::cout << "Start reading frame data...\n";
			rc = ir.start();
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't start the depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(7);
            }

			while (true)
			{
				// Read a frame
				rc = ir.readFrame(&irf);
                if (rc != openni::STATUS_OK)
                {
                    printf("Read failed!\n%s\n", openni::OpenNI::getExtendedError());
                    continue;
                }

				// Verify frame data is valid
				if (!irf.isValid())
				{
					std::cerr << "Error reading video stream frame\n";
					break;
				}

				// Gather frame data
				pDepth = (OniDepthPixel*)irf.getData();
				frameIndex = irf.getFrameIndex();

				// Skip unneeded frames
				if (frameIndex % FRAME_DATA_MOD == 0)
				{
					frameHeight = irf.getHeight();
					frameWidth = irf.getWidth();
					std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
					out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
					for (int y = 0; y < frameHeight; ++y)  // All heights
					{
						for (int x = 0; x < frameWidth; ++x, ++pDepth)  // All witdths
						{
							out << *pDepth << ",";
						}
						out << "\n";
					}
					out << ",\n";
				}
				else
				{
					//std::cout << "Skipping frame " << frameIndex << "\n";
				}

				// Break if reading the last frame
				if (numberOfFrames == frameIndex)
				{
					std::cout << "Last frame has been read...\n";
					break;
				}
			}

			// Cleanup
			out.clear();
			out.close();
			ir.stop();
			ir.destroy();
			device.close();
		}

		// OpenNI cleanup
		openni::OpenNI::shutdown();
		std::cout << "Excel data output complete.\n";
	}

	/// <summary>
	/// Reads oni input and exports data as point clouds
	/// </summary>
	void outputPointCloud(const int argc, const char** argv)
	{

	}
}<commit_msg>Fix to output path generation<commit_after>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include "onimeshfunctions.h"

namespace onimesh
{
	const int FRAME_DATA_MOD = 100;

	/// <summary>
	/// Creates a name for an output file
	/// </summary>
	std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
	{
		// If the path contains '/' characters
		if (std::string(inputFile).find_last_of('/') != std::string::npos)
		{
			// Check if the directory needs a trailing '/'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(std::string(outputDirectory) + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));

			return std::string(std::string(outputDirectory) + std::string("/") + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
		}
		// If the path contains '\' characters
		else if (std::string(inputFile).find_last_of('\\') == std::string::npos)
		{
			// Check if the directory needs a trailing '\'
			if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
				return std::string(std::string(outputDirectory) + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));

			return std::string(std::string(outputDirectory) + std::string("\\") + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));
		}

		// Otherwise the input file does not contain a path
		// Check if the directory needs a trailing '/'
		if (std::string(outputDirectory).back() == '/' || std::string(outputDirectory).back() == '\\')
			return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));

		return std::string(std::string(outputDirectory) + std::string("/") + std::string(inputFile) + std::string(fileExtension));
	}

	/// <summary>
	/// Reads oni input and exports data as excel docs
	/// </summary>
	void outputExcel(const int argc, const char** argv)
	{
		std::cout << "Start excel data output...\n";

        const char* outputDirectory = argv[1];
        char* inputFile;
		const int numberInputFiles = argc - 2;
		openni::Device device;
		openni::VideoStream ir;
		openni::VideoFrameRef irf;
		OniDepthPixel* pDepth;
		int frameHeight, frameWidth;
		long frameIndex, numberOfFrames;
		std::ofstream out;

        // Initialize openni
        openni::Status rc = openni::OpenNI::initialize();
        if (rc != openni::STATUS_OK)
        {
            printf("Initialize failed\n%s\n", openni::OpenNI::getExtendedError());
            exit(2);
        }

		// Output excel doc for each input file
		for (int w = 0; w < numberInputFiles; ++w)
		{
			inputFile = (char*)argv[w + 2];
			std::cout << "Working on file " << inputFile << "...\n";

			// Open the .oni file
			rc = device.open(inputFile);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError());
                exit(3);
            }

            // Create the Video Stream
			rc = ir.create(device, openni::SENSOR_DEPTH);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't create depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(4);
            }

			// Device Check
			if (!device.isValid())
			{
				std::cerr << "\nThe device is not valid.\n";
				exit(5);
			}

			// Verify the device is a file
			if (!device.isFile())
			{
				std::cerr << "\nThe device is not a file.\n";
				exit(6);
			}
			std::cout << "File open success...\n";

			// Set playback controls
			openni::PlaybackControl* pbc = device.getPlaybackControl();
			pbc->setSpeed(-1);
			pbc->setRepeatEnabled(false);

			// Open output file
			std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
			out.open(outputFile);

			// Read all frames
			numberOfFrames = pbc->getNumberOfFrames(ir);
			std::cout << "Start reading frame data...\n";
			rc = ir.start();
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't start the depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(7);
            }

			while (true)
			{
				// Read a frame
				rc = ir.readFrame(&irf);
                if (rc != openni::STATUS_OK)
                {
                    printf("Read failed!\n%s\n", openni::OpenNI::getExtendedError());
                    continue;
                }

				// Verify frame data is valid
				if (!irf.isValid())
				{
					std::cerr << "Error reading video stream frame\n";
					break;
				}

				// Gather frame data
				pDepth = (OniDepthPixel*)irf.getData();
				frameIndex = irf.getFrameIndex();

				// Skip unneeded frames
				if (frameIndex % FRAME_DATA_MOD == 0)
				{
					frameHeight = irf.getHeight();
					frameWidth = irf.getWidth();
					std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
					out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
					for (int y = 0; y < frameHeight; ++y)  // All heights
					{
						for (int x = 0; x < frameWidth; ++x, ++pDepth)  // All witdths
						{
							out << *pDepth << ",";
						}
						out << "\n";
					}
					out << ",\n";
				}
				else
				{
					//std::cout << "Skipping frame " << frameIndex << "\n";
				}

				// Break if reading the last frame
				if (numberOfFrames == frameIndex)
				{
					std::cout << "Last frame has been read...\n";
					break;
				}
			}

			// Cleanup
			out.clear();
			out.close();
			ir.stop();
			ir.destroy();
			device.close();
		}

		// OpenNI cleanup
		openni::OpenNI::shutdown();
		std::cout << "Excel data output complete.\n";
	}

	/// <summary>
	/// Reads oni input and exports data as point clouds
	/// </summary>
	void outputPointCloud(const int argc, const char** argv)
	{

	}
}<|endoftext|>


<commit_before>/*
 *  glContext.cpp
 *  MonkVG-OpenGL
 *
 *  Created by Micah Pearlman on 8/6/10.
 *  Copyright 2010 MP Engineering. All rights reserved.
 *
 */

#include "glContext.h"
#include "glPath.h"
#include "glPaint.h"
#include "mkCommon.h"

namespace MonkVG {

	OpenGLContext::OpenGLContext()
		:	IContext()
	{
	}

	void OpenGLContext::checkGLError() {

		int err = glGetError();

		const char* RVAL = "GL_UNKNOWN_ERROR";

		switch( err )
		{
			case GL_NO_ERROR:
				RVAL =  "GL_NO_ERROR";
				break;
			case GL_INVALID_ENUM:
				RVAL =  "GL_INVALID_ENUM";
				break;
			case GL_INVALID_VALUE:
				RVAL =  "GL_INVALID_VALUE";
				break;
			case GL_INVALID_OPERATION:
				RVAL = "GL_INVALID_OPERATION";
				break;
			case GL_STACK_OVERFLOW:
				RVAL =  "GL_STACK_OVERFLOW";
				break;
			case GL_STACK_UNDERFLOW:
				RVAL =  "GL_STACK_UNDERFLOW";
				break;
			case GL_OUT_OF_MEMORY:
				RVAL =  "GL_OUT_OF_MEMORY";
				break;
			default:
				break;
		}

		if( err != GL_NO_ERROR ) {
			printf("GL_ERROR: %s\n", RVAL );
			MK_ASSERT(0);
		}
	}

	bool OpenGLContext::Initialize() {

//		/* setup GL projection */
//		glViewport(0,0, _width, _height);
//
//		glMatrixMode(GL_PROJECTION);
//		glLoadIdentity();
//		glOrthof(0, _width, _height, 0, -1, 1);
//		glMatrixMode(GL_MODELVIEW);
//		glLoadIdentity();

		return true;
	}

	bool OpenGLContext::Terminate() {
		return true;
	}

	void OpenGLContext::beginRender() {

		CHECK_GL_ERROR;

		// get viewport to restore back when we are done
		glGetIntegerv( GL_VIEWPORT, _viewport );
		glGetFloatv( GL_PROJECTION_MATRIX, _projection );
		glGetFloatv( GL_MODELVIEW_MATRIX, _modelview );

		// get the color to back up when we are done
		glGetFloatv( GL_CURRENT_COLOR, _color );

		// setup GL projection
		glViewport(0,0, _width, _height);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrthof(0, _width, _height, 0, -1, 1);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glDisable( GL_CULL_FACE );

		// turn on blending
		glEnable(GL_BLEND);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		CHECK_GL_ERROR;

	}
	void OpenGLContext::endRender() {

		CHECK_GL_ERROR;

		// todo: restore state to be nice to other apps
		// restore the old viewport
		glMatrixMode( GL_PROJECTION );
		glLoadMatrixf( _projection );
		glViewport( _viewport[0], _viewport[1], _viewport[2], _viewport[3] );
		glMatrixMode( GL_MODELVIEW );
		glLoadMatrixf( _modelview );

		// restore color
		glColor4f( _color[0], _color[1], _color[2], _color[3] );

		CHECK_GL_ERROR;
	}

	IPath* OpenGLContext::createPath( VGint pathFormat, VGPathDatatype datatype, VGfloat scale, VGfloat bias, VGint segmentCapacityHint, VGint coordCapacityHint, VGbitfield capabilities ) {

		OpenGLPath *path = new OpenGLPath(pathFormat, datatype, scale, bias, segmentCapacityHint, coordCapacityHint, capabilities  &= VG_PATH_CAPABILITY_ALL);
		if( path == 0 )
			setError( VG_OUT_OF_MEMORY_ERROR );

		return (IPath*)path;
	}

	void OpenGLContext::destroyPath( IPath* path ) {
		delete (OpenGLPath*)path;
	}

	void OpenGLContext::destroyPaint( IPaint* paint ) {
		delete (OpenGLPaint*)paint;
	}

	IPaint* OpenGLContext::createPaint() {
		OpenGLPaint *paint = new OpenGLPaint();
		if( paint == 0 )
			setError( VG_OUT_OF_MEMORY_ERROR );
		return (IPaint*)paint;
	}

	void OpenGLContext::stroke() {
		if ( _stroke_paint ) {
			const VGfloat* c = _stroke_paint->getPaintColor();
			glColor4f(c[0], c[1], c[2], c[3] );
		}
	}

	void OpenGLContext::fill() {
		if ( _fill_paint ) {
			const VGfloat* c = _fill_paint->getPaintColor();
			glColor4f(c[0], c[1], c[2], c[3] );
		}

	}

	void OpenGLContext::clear(VGint x, VGint y, VGint width, VGint height) {
	}

	void OpenGLContext::setIdentity() {
		Matrix33* active = getActiveMatrix();
		active->setIdentity();
	}

	void OpenGLContext::transform( VGfloat* t ) {
		// a	b	0
		// c	d	0
		// tx	ty	1
		Matrix33* active = getActiveMatrix();
		for ( int x = 0; x < 3; x++ ) {
			for ( int y = 0; y < 3; y++ ) {
				t[(y*3)+x] = active->get( y, x );
			}
		}
	}

	void OpenGLContext::setTransform( const VGfloat* t )  {
		//	OpenVG:
		//	sh	shx	tx
		//	shy	sy	ty
		//	0	0	1
		//
		// OpenGL
		// a	b	0
		// c	d	0
		// tx	ty	1

		Matrix33* active = getActiveMatrix();
		// transpose:  see above
		for ( int x = 0; x < 3; x++ ) {
			for ( int y = 0; y < 3; y++ ) {
				active->set( y, x, t[(y*3)+x] );
			}
		}
	}

	void OpenGLContext::multiply( const VGfloat* t ) {
		Matrix33 m;
		for ( int x = 0; x < 3; x++ ) {
			for ( int y = 0; y < 3; y++ ) {
				m.set( y, x, t[(y*3)+x] );
			}
		}
		Matrix33* active = getActiveMatrix();
		//m.multiply( *active );
		//active->copy( m );
		//active->multiply( m );
		active->postMultiply( m );
	}

	void OpenGLContext::scale( VGfloat sx, VGfloat sy ) {
		Matrix33* active = getActiveMatrix();
		Matrix33 scale;
		scale.setIdentity();
		scale.setScale( sx, sy );
        Matrix33 tmp;
        Matrix33::multiply( tmp, scale, *active );
		active->copy( tmp );
	}
	void OpenGLContext::translate( VGfloat x, VGfloat y ) {

		Matrix33* active = getActiveMatrix();
		Matrix33 translate;
		translate.setTranslate( x, y );
		Matrix33 tmp;
		tmp.setIdentity();
		//Matrix33::multiply( tmp, *active, translate );
		Matrix33::multiply( tmp, translate, *active );
		active->copy( tmp );
	}
	void OpenGLContext::rotate( VGfloat angle ) {
		Matrix33* active = getActiveMatrix();
		Matrix33 rotate;
		rotate.setRotate( radians( -angle ) );
		Matrix33 tmp;
		tmp.setIdentity();
		Matrix33::multiply( tmp, rotate, *active );
		active->copy( tmp );
	}

	//// singleton implementation ////
	static OpenGLContext g_context;
	IContext& IContext::instance()
	{
		return g_context;
	}

}<commit_msg>MonkVG set origin to lower left (instead of the previous upper left)<commit_after>/*
 *  glContext.cpp
 *  MonkVG-OpenGL
 *
 *  Created by Micah Pearlman on 8/6/10.
 *  Copyright 2010 MP Engineering. All rights reserved.
 *
 */

#include "glContext.h"
#include "glPath.h"
#include "glPaint.h"
#include "mkCommon.h"

namespace MonkVG {

	OpenGLContext::OpenGLContext()
		:	IContext()
	{
	}

	void OpenGLContext::checkGLError() {

		int err = glGetError();

		const char* RVAL = "GL_UNKNOWN_ERROR";

		switch( err )
		{
			case GL_NO_ERROR:
				RVAL =  "GL_NO_ERROR";
				break;
			case GL_INVALID_ENUM:
				RVAL =  "GL_INVALID_ENUM";
				break;
			case GL_INVALID_VALUE:
				RVAL =  "GL_INVALID_VALUE";
				break;
			case GL_INVALID_OPERATION:
				RVAL = "GL_INVALID_OPERATION";
				break;
			case GL_STACK_OVERFLOW:
				RVAL =  "GL_STACK_OVERFLOW";
				break;
			case GL_STACK_UNDERFLOW:
				RVAL =  "GL_STACK_UNDERFLOW";
				break;
			case GL_OUT_OF_MEMORY:
				RVAL =  "GL_OUT_OF_MEMORY";
				break;
			default:
				break;
		}

		if( err != GL_NO_ERROR ) {
			printf("GL_ERROR: %s\n", RVAL );
			MK_ASSERT(0);
		}
	}

	bool OpenGLContext::Initialize() {

//		/* setup GL projection */
//		glViewport(0,0, _width, _height);
//
//		glMatrixMode(GL_PROJECTION);
//		glLoadIdentity();
//		glOrthof(0, _width, _height, 0, -1, 1);
//		glMatrixMode(GL_MODELVIEW);
//		glLoadIdentity();

		return true;
	}

	bool OpenGLContext::Terminate() {
		return true;
	}

	void OpenGLContext::beginRender() {

		CHECK_GL_ERROR;

		// get viewport to restore back when we are done
		glGetIntegerv( GL_VIEWPORT, _viewport );
		glGetFloatv( GL_PROJECTION_MATRIX, _projection );
		glGetFloatv( GL_MODELVIEW_MATRIX, _modelview );

		// get the color to back up when we are done
		glGetFloatv( GL_CURRENT_COLOR, _color );

		// setup GL projection
		glViewport(0,0, _width, _height);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrthof(0, _width,		// left, right
				 0, _height,	// top, botton
				 -1, 1);		// near value, far value (depth)

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glDisable( GL_CULL_FACE );

		// turn on blending
		glEnable(GL_BLEND);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		CHECK_GL_ERROR;

	}
	void OpenGLContext::endRender() {

		CHECK_GL_ERROR;

		// todo: restore state to be nice to other apps
		// restore the old viewport
		glMatrixMode( GL_PROJECTION );
		glLoadMatrixf( _projection );
		glViewport( _viewport[0], _viewport[1], _viewport[2], _viewport[3] );
		glMatrixMode( GL_MODELVIEW );
		glLoadMatrixf( _modelview );

		// restore color
		glColor4f( _color[0], _color[1], _color[2], _color[3] );

		CHECK_GL_ERROR;
	}

	IPath* OpenGLContext::createPath( VGint pathFormat, VGPathDatatype datatype, VGfloat scale, VGfloat bias, VGint segmentCapacityHint, VGint coordCapacityHint, VGbitfield capabilities ) {

		OpenGLPath *path = new OpenGLPath(pathFormat, datatype, scale, bias, segmentCapacityHint, coordCapacityHint, capabilities  &= VG_PATH_CAPABILITY_ALL);
		if( path == 0 )
			setError( VG_OUT_OF_MEMORY_ERROR );

		return (IPath*)path;
	}

	void OpenGLContext::destroyPath( IPath* path ) {
		delete (OpenGLPath*)path;
	}

	void OpenGLContext::destroyPaint( IPaint* paint ) {
		delete (OpenGLPaint*)paint;
	}

	IPaint* OpenGLContext::createPaint() {
		OpenGLPaint *paint = new OpenGLPaint();
		if( paint == 0 )
			setError( VG_OUT_OF_MEMORY_ERROR );
		return (IPaint*)paint;
	}

	void OpenGLContext::stroke() {
		if ( _stroke_paint ) {
			const VGfloat* c = _stroke_paint->getPaintColor();
			glColor4f(c[0], c[1], c[2], c[3] );
		}
	}

	void OpenGLContext::fill() {
		if ( _fill_paint ) {
			const VGfloat* c = _fill_paint->getPaintColor();
			glColor4f(c[0], c[1], c[2], c[3] );
		}

	}

	void OpenGLContext::clear(VGint x, VGint y, VGint width, VGint height) {
	}

	void OpenGLContext::setIdentity() {
		Matrix33* active = getActiveMatrix();
		active->setIdentity();
	}

	void OpenGLContext::transform( VGfloat* t ) {
		// a	b	0
		// c	d	0
		// tx	ty	1
		Matrix33* active = getActiveMatrix();
		for ( int x = 0; x < 3; x++ ) {
			for ( int y = 0; y < 3; y++ ) {
				t[(y*3)+x] = active->get( y, x );
			}
		}
	}

	void OpenGLContext::setTransform( const VGfloat* t )  {
		//	OpenVG:
		//	sh	shx	tx
		//	shy	sy	ty
		//	0	0	1
		//
		// OpenGL
		// a	b	0
		// c	d	0
		// tx	ty	1

		Matrix33* active = getActiveMatrix();
		// transpose:  see above
		for ( int x = 0; x < 3; x++ ) {
			for ( int y = 0; y < 3; y++ ) {
				active->set( y, x, t[(y*3)+x] );
			}
		}
	}

	void OpenGLContext::multiply( const VGfloat* t ) {
		Matrix33 m;
		for ( int x = 0; x < 3; x++ ) {
			for ( int y = 0; y < 3; y++ ) {
				m.set( y, x, t[(y*3)+x] );
			}
		}
		Matrix33* active = getActiveMatrix();
		//m.multiply( *active );
		//active->copy( m );
		//active->multiply( m );
		active->postMultiply( m );
	}

	void OpenGLContext::scale( VGfloat sx, VGfloat sy ) {
		Matrix33* active = getActiveMatrix();
		Matrix33 scale;
		scale.setIdentity();
		scale.setScale( sx, sy );
        Matrix33 tmp;
        Matrix33::multiply( tmp, scale, *active );
		active->copy( tmp );
	}
	void OpenGLContext::translate( VGfloat x, VGfloat y ) {

		Matrix33* active = getActiveMatrix();
		Matrix33 translate;
		translate.setTranslate( x, y );
		Matrix33 tmp;
		tmp.setIdentity();
		//Matrix33::multiply( tmp, *active, translate );
		Matrix33::multiply( tmp, translate, *active );
		active->copy( tmp );
	}
	void OpenGLContext::rotate( VGfloat angle ) {
		Matrix33* active = getActiveMatrix();
		Matrix33 rotate;
		rotate.setRotate( radians( -angle ) );
		Matrix33 tmp;
		tmp.setIdentity();
		Matrix33::multiply( tmp, rotate, *active );
		active->copy( tmp );
	}

	//// singleton implementation ////
	static OpenGLContext g_context;
	IContext& IContext::instance()
	{
		return g_context;
	}

}<|endoftext|>


<commit_before>//  (C) Copyright Gennadiy Rozental 2001-2002.
//  (C) Copyright Ullrich Koethe 2001.
//  Permission to copy, use, modify, sell and distribute this software
//  is granted provided this copyright notice appears in all copies.
//  This software is provided "as is" without express or implied warranty,
//  and with no claim as to its suitability for any purpose.

//  See http://www.boost.org for updates, documentation, and revision history.
//
//  File        : $RCSfile$
//
//  Version     : $Id$
//
//  Description : implements specific subclass of Executon Monitor used by Unit
//  Test Framework to monitor test cases run.
// ***************************************************************************

// Boost.Test
#include <boost/test/detail/unit_test_monitor.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/unit_test_result.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/test_tools.hpp>

namespace boost {

namespace unit_test_framework {

namespace detail {

// ************************************************************************** //
// **************               unit_test_monitor              ************** //
// ************************************************************************** //

bool unit_test_monitor::s_catch_system_errors = true;

unit_test_monitor::error_level
unit_test_monitor::execute_and_translate( int timeout )
{
    try {
        execute( s_catch_system_errors, timeout );
    }
    catch( execution_exception const& exex ) {
        report_level report_level =
             exex.code() <= execution_exception::cpp_exception_error ? report_cpp_exception_errors :
            (exex.code() <= execution_exception::timeout_error       ? report_system_errors :
                                                                       report_fatal_errors);
        unit_test_log::instance()
            << begin() << level( report_level ) << report_exception( exex.what() ) << end();

        unit_test_result::instance().caught_exception();

        // translate execution_exception::error_code to detail::error_level
        switch( exex.code() ) {
        case execution_exception::no_error:             return test_ok;
        case execution_exception::user_error:           return unexpected_exception;
        case execution_exception::cpp_exception_error:  return unexpected_exception;
        case execution_exception::system_error:         return os_exception;
        case execution_exception::timeout_error:        return os_timeout;
        case execution_exception::user_fatal_error:
        case execution_exception::system_fatal_error:   return fatal_error;
        default:                                        return unexpected_exception;
        }
    }

    return test_ok;
}

//____________________________________________________________________________//

int
unit_test_monitor::function()
{
    try {
        (m_test_case.*m_test_case_function)();
    }
    catch( test_toolbox::detail::test_tool_failed const& /*e*/ ) { // e not used; error already reported
        // nothing to do
    }

    return 0;
}

//____________________________________________________________________________//

} // namespace detail

} // namespace unit_test_framework

} // namespace boost

// ***************************************************************************
//  Revision History :
//
//  $Log$
//  Revision 1.6  2002/12/08 18:19:06  rogeeff
//  catch system errors switch introduced
//
//  Revision 1.5  2002/11/02 20:04:42  rogeeff
//  release 1.29.0 merged into the main trank
//

// ***************************************************************************

// EOF
<commit_msg>report_level -> log_level<commit_after>//  (C) Copyright Gennadiy Rozental 2001-2002.
//  (C) Copyright Ullrich Koethe 2001.
//  Permission to copy, use, modify, sell and distribute this software
//  is granted provided this copyright notice appears in all copies.
//  This software is provided "as is" without express or implied warranty,
//  and with no claim as to its suitability for any purpose.

//  See http://www.boost.org for updates, documentation, and revision history.
//
//  File        : $RCSfile$
//
//  Version     : $Id$
//
//  Description : implements specific subclass of Executon Monitor used by Unit
//  Test Framework to monitor test cases run.
// ***************************************************************************

// Boost.Test
#include <boost/test/detail/unit_test_monitor.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/unit_test_result.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/test_tools.hpp>

namespace boost {

namespace unit_test_framework {

namespace detail {

// ************************************************************************** //
// **************               unit_test_monitor              ************** //
// ************************************************************************** //

bool unit_test_monitor::s_catch_system_errors = true;

unit_test_monitor::error_level
unit_test_monitor::execute_and_translate( int timeout )
{
    try {
        execute( s_catch_system_errors, timeout );
    }
    catch( execution_exception const& exex ) {
        log_level loglevel =
             exex.code() <= execution_exception::cpp_exception_error ? log_cpp_exception_errors :
            (exex.code() <= execution_exception::timeout_error       ? log_system_errors :
                                                                       log_fatal_errors);
        unit_test_log::instance()
            << begin() << level( loglevel ) << log_exception( exex.what() ) << end();

        unit_test_result::instance().caught_exception();

        // translate execution_exception::error_code to detail::error_level
        switch( exex.code() ) {
        case execution_exception::no_error:             return test_ok;
        case execution_exception::user_error:           return unexpected_exception;
        case execution_exception::cpp_exception_error:  return unexpected_exception;
        case execution_exception::system_error:         return os_exception;
        case execution_exception::timeout_error:        return os_timeout;
        case execution_exception::user_fatal_error:
        case execution_exception::system_fatal_error:   return fatal_error;
        default:                                        return unexpected_exception;
        }
    }

    return test_ok;
}

//____________________________________________________________________________//

int
unit_test_monitor::function()
{
    try {
        (m_test_case.*m_test_case_function)();
    }
    catch( test_toolbox::detail::test_tool_failed const& /*e*/ ) { // e not used; error already reported
        // nothing to do
    }

    return 0;
}

//____________________________________________________________________________//

} // namespace detail

} // namespace unit_test_framework

} // namespace boost

// ***************************************************************************
//  Revision History :
//
//  $Log$
//  Revision 1.7  2003/02/13 08:40:44  rogeeff
//  report_level -> log_level
//
//  Revision 1.6  2002/12/08 18:19:06  rogeeff
//  catch system errors switch introduced
//
//  Revision 1.5  2002/11/02 20:04:42  rogeeff
//  release 1.29.0 merged into the main trank
//

// ***************************************************************************

// EOF
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/RefHashTableOf.hpp>
#include <util/XML88591Transcoder.hpp>
#include <util/XMLASCIITranscoder.hpp>
#include <util/XMLChTranscoder.hpp>
#include <util/XMLEBCDICTranscoder.hpp>
#include <util/XMLIBM1140Transcoder.hpp>
#include <util/XMLUCS4Transcoder.hpp>
#include <util/XMLUTF8Transcoder.hpp>
#include <util/XMLUTF16Transcoder.hpp>
#include <util/XMLWin1252Transcoder.hpp>
#include <util/XMLUni.hpp>
#include <util/TransENameMap.hpp>

// ---------------------------------------------------------------------------
//  Local, static data
//
//  gMappings
//      This is a hash table of ENameMap objects. It is created and filled
//      in when the platform init calls our initTransService() method.
//
//  gDisallow1
//  gDisallowX
//      These area small set of encoding names that, for temporary reasons,
//      we disallow at this time.
//
//  gDisallowList
//  gDisallowListSize
//      An array of the disallow strings, for easier searching below.
//
//  gDisallowPre
//      All of the disallowed encodings start with 'IBM', so we have a prefix
//      we can check for and quickly decide if we need to search the list.
// ---------------------------------------------------------------------------
static RefHashTableOf<ENameMap>*    gMappings = 0;
static XMLCh                        gDisallow1[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
      , chDigit_7, chNull
};
static XMLCh                        gDisallow2[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chNull
};
static XMLCh                        gDisallow3[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
    ,   chDigit_7, chDash, chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh                        gDisallow4[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chDash
    ,   chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh                        gDisallow5[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
      , chDigit_1, chDigit_4, chDigit_0, chNull
};
static XMLCh                        gDisallow6[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
      , chDigit_1, chDigit_4, chDigit_0, chDash, chLatin_S, chDigit_3
      , chDigit_9, chDigit_0, chNull
};
static const unsigned int           gDisallowListSize = 6;
static XMLCh*                       gDisallowList[gDisallowListSize] =
{
    gDisallow1, gDisallow2, gDisallow3, gDisallow4, gDisallow5, gDisallow6
};
static XMLCh                        gDisallowPre[] =
{
        chLatin_I, chLatin_B, chLatin_M, chNull
};

// ---------------------------------------------------------------------------
//  XLMTransService: Constructors and destructor
// ---------------------------------------------------------------------------
XMLTransService::XMLTransService()
{
}

XMLTransService::~XMLTransService()
{
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Non-virtual API
// ---------------------------------------------------------------------------
XMLTranscoder*
XMLTransService::makeNewTranscoderFor(  const   XMLCh* const            encodingName
                                        ,       XMLTransService::Codes& resValue
                                        , const unsigned int            blockSize)
{
    //
    //  First try to find it in our list of mappings to intrinsically
    //  supported encodings. We have to upper case the passed encoding
    //  name because we use a hash table and we stored all our mappings
    //  in all uppercase.
    //
    const unsigned int bufSize = 2048;
    XMLCh upBuf[bufSize + 1];
    if (!XMLString::copyNString(upBuf, encodingName, bufSize))
        return 0;
    XMLString::upperCase(upBuf);
    ENameMap* ourMapping = gMappings->get(upBuf);

    // If we found it, then call the factory method for it
    if (ourMapping)
        return ourMapping->makeNew(blockSize);

    //
    //  For now, we have a little list of encodings that we disallow
    //  explicitly. So lets check for them up front. They all start with
    //  IBM, so we can do a quick check to see if we should even do
    //  anything at all.
    //
    if (XMLString::startsWith(upBuf, gDisallowPre))
    {
        for (unsigned int index = 0; index < gDisallowListSize; index++)
        {
            // If its one of our guys, then pretend we don't understand it
            if (!XMLString::compareString(upBuf, gDisallowList[index]))
                return 0;
        }
    }

    //
    //  It wasn't an intrinsic and it wasn't disallowed, so pass it on
    //  to the trans service to see if he can make anything of it.
    //
    return makeNewXMLTranscoder(encodingName, resValue, blockSize);
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLTranscoder::~XMLTranscoder()
{
    delete [] fEncodingName;
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLTranscoder::XMLTranscoder(const  XMLCh* const    encodingName
                            , const unsigned int    blockSize) :
    fEncodingName(0)
    , fBlockSize(blockSize)
{
    fEncodingName = XMLString::replicate(encodingName);
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Protected helpers
// ---------------------------------------------------------------------------
void XMLTranscoder::checkBlockSize(const unsigned int toCheck)
{
    if (toCheck > fBlockSize)
    {
        // <TBD> Throw an exception here
    }
}

// ---------------------------------------------------------------------------
//  XLMLCPTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLLCPTranscoder::XMLLCPTranscoder()
{
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLLCPTranscoder::~XMLLCPTranscoder()
{
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Hidden Init Method
//
//  This is called by platform utils during startup.
// ---------------------------------------------------------------------------
void XMLTransService::initTransService()
{
    //
    //  Create our hash table that we will fill with mappings. The default
    //  is to adopt the elements, which is fine with us.
    //
    gMappings = new RefHashTableOf<ENameMap>(103);

    //
    //  Add in the magical mapping for the native XMLCh transcoder. This
    //  is used for internal entities.
    //
    gMappings->put(new ENameMapFor<XMLChTranscoder>(XMLUni::fgXMLChEncodingString));

    //
    //  Add in our mappings for ASCII.
    //
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString));
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString2));
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString3));
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString4));

    //
    //  Add in our mappings for UTF-8
    //
    gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString));
    gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString2));

    //
    //  Add in our mappings for Latin1
    //
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString2));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString3));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString4));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString5));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString6));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString7));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString8));

    //
    //  Add in our mappings for UTF-16 and UCS-4, little endian
    //
    bool swapped = false;

    #if defined(ENDIANMODE_BIG)
    swapped = true;
    #endif
    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16LEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16LEncodingString2
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4LEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4LEncodingString2
            , swapped
        )
    );

    //
    //  Add in our mappings for UTF-16 and UCS-4, big endian
    //
    swapped = false;
    #if defined(ENDIANMODE_LITTLE)
    swapped = true;
    #endif
    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16BEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16BEncodingString2
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4BEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4BEncodingString2
            , swapped
        )
    );

    //
    //  Add in our mappings for IBM037, and the one alias we support for
    //  it, which is EBCDIC-CP-US.
    //
    gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString));
    gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString2));

    //
    //  Add in our mappings for IBM037 with Euro update, i.e. IBM1140. It
    //  has no aliases
    //
    gMappings->put(new ENameMapFor<XMLIBM1140Transcoder>(XMLUni::fgIBM1140EncodingString));

    //
    //  Add in our mappings for Windows-1252. We don't have any aliases for
    //  this one, so there is just one mapping.
    //
    gMappings->put(new ENameMapFor<XMLWin1252Transcoder>(XMLUni::fgWin1252EncodingString));
}
<commit_msg>Fix wrong encoding name.  ibm-11140 becomes ibm-1140<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/RefHashTableOf.hpp>
#include <util/XML88591Transcoder.hpp>
#include <util/XMLASCIITranscoder.hpp>
#include <util/XMLChTranscoder.hpp>
#include <util/XMLEBCDICTranscoder.hpp>
#include <util/XMLIBM1140Transcoder.hpp>
#include <util/XMLUCS4Transcoder.hpp>
#include <util/XMLUTF8Transcoder.hpp>
#include <util/XMLUTF16Transcoder.hpp>
#include <util/XMLWin1252Transcoder.hpp>
#include <util/XMLUni.hpp>
#include <util/TransENameMap.hpp>

// ---------------------------------------------------------------------------
//  Local, static data
//
//  gMappings
//      This is a hash table of ENameMap objects. It is created and filled
//      in when the platform init calls our initTransService() method.
//
//  gDisallow1
//  gDisallowX
//      These area small set of encoding names that, for temporary reasons,
//      we disallow at this time.
//
//  gDisallowList
//  gDisallowListSize
//      An array of the disallow strings, for easier searching below.
//
//  gDisallowPre
//      All of the disallowed encodings start with 'IBM', so we have a prefix
//      we can check for and quickly decide if we need to search the list.
// ---------------------------------------------------------------------------
static RefHashTableOf<ENameMap>*    gMappings = 0;
static XMLCh                        gDisallow1[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
      , chDigit_7, chNull
};
static XMLCh                        gDisallow2[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chNull
};
static XMLCh                        gDisallow3[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
    ,   chDigit_7, chDash, chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh                        gDisallow4[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chDash
    ,   chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh                        gDisallow5[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
      , chDigit_4, chDigit_0, chNull
};
static XMLCh                        gDisallow6[] =
{
        chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
      , chDigit_4, chDigit_0, chDash, chLatin_S, chDigit_3
      , chDigit_9, chDigit_0, chNull
};
static const unsigned int           gDisallowListSize = 6;
static XMLCh*                       gDisallowList[gDisallowListSize] =
{
    gDisallow1, gDisallow2, gDisallow3, gDisallow4, gDisallow5, gDisallow6
};
static XMLCh                        gDisallowPre[] =
{
        chLatin_I, chLatin_B, chLatin_M, chNull
};

// ---------------------------------------------------------------------------
//  XLMTransService: Constructors and destructor
// ---------------------------------------------------------------------------
XMLTransService::XMLTransService()
{
}

XMLTransService::~XMLTransService()
{
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Non-virtual API
// ---------------------------------------------------------------------------
XMLTranscoder*
XMLTransService::makeNewTranscoderFor(  const   XMLCh* const            encodingName
                                        ,       XMLTransService::Codes& resValue
                                        , const unsigned int            blockSize)
{
    //
    //  First try to find it in our list of mappings to intrinsically
    //  supported encodings. We have to upper case the passed encoding
    //  name because we use a hash table and we stored all our mappings
    //  in all uppercase.
    //
    const unsigned int bufSize = 2048;
    XMLCh upBuf[bufSize + 1];
    if (!XMLString::copyNString(upBuf, encodingName, bufSize))
        return 0;
    XMLString::upperCase(upBuf);
    ENameMap* ourMapping = gMappings->get(upBuf);

    // If we found it, then call the factory method for it
    if (ourMapping)
        return ourMapping->makeNew(blockSize);

    //
    //  For now, we have a little list of encodings that we disallow
    //  explicitly. So lets check for them up front. They all start with
    //  IBM, so we can do a quick check to see if we should even do
    //  anything at all.
    //
    if (XMLString::startsWith(upBuf, gDisallowPre))
    {
        for (unsigned int index = 0; index < gDisallowListSize; index++)
        {
            // If its one of our guys, then pretend we don't understand it
            if (!XMLString::compareString(upBuf, gDisallowList[index]))
                return 0;
        }
    }

    //
    //  It wasn't an intrinsic and it wasn't disallowed, so pass it on
    //  to the trans service to see if he can make anything of it.
    //
    return makeNewXMLTranscoder(encodingName, resValue, blockSize);
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLTranscoder::~XMLTranscoder()
{
    delete [] fEncodingName;
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLTranscoder::XMLTranscoder(const  XMLCh* const    encodingName
                            , const unsigned int    blockSize) :
    fEncodingName(0)
    , fBlockSize(blockSize)
{
    fEncodingName = XMLString::replicate(encodingName);
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Protected helpers
// ---------------------------------------------------------------------------
void XMLTranscoder::checkBlockSize(const unsigned int toCheck)
{
    if (toCheck > fBlockSize)
    {
        // <TBD> Throw an exception here
    }
}

// ---------------------------------------------------------------------------
//  XLMLCPTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLLCPTranscoder::XMLLCPTranscoder()
{
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLLCPTranscoder::~XMLLCPTranscoder()
{
}

// ---------------------------------------------------------------------------
//  XLMTranscoder: Hidden Init Method
//
//  This is called by platform utils during startup.
// ---------------------------------------------------------------------------
void XMLTransService::initTransService()
{
    //
    //  Create our hash table that we will fill with mappings. The default
    //  is to adopt the elements, which is fine with us.
    //
    gMappings = new RefHashTableOf<ENameMap>(103);

    //
    //  Add in the magical mapping for the native XMLCh transcoder. This
    //  is used for internal entities.
    //
    gMappings->put(new ENameMapFor<XMLChTranscoder>(XMLUni::fgXMLChEncodingString));

    //
    //  Add in our mappings for ASCII.
    //
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString));
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString2));
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString3));
    gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString4));

    //
    //  Add in our mappings for UTF-8
    //
    gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString));
    gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString2));

    //
    //  Add in our mappings for Latin1
    //
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString2));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString3));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString4));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString5));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString6));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString7));
    gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString8));

    //
    //  Add in our mappings for UTF-16 and UCS-4, little endian
    //
    bool swapped = false;

    #if defined(ENDIANMODE_BIG)
    swapped = true;
    #endif
    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16LEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16LEncodingString2
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4LEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4LEncodingString2
            , swapped
        )
    );

    //
    //  Add in our mappings for UTF-16 and UCS-4, big endian
    //
    swapped = false;
    #if defined(ENDIANMODE_LITTLE)
    swapped = true;
    #endif
    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16BEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUTF16Transcoder>
        (
            XMLUni::fgUTF16BEncodingString2
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4BEncodingString
            , swapped
        )
    );

    gMappings->put
    (
        new EEndianNameMapFor<XMLUCS4Transcoder>
        (
            XMLUni::fgUCS4BEncodingString2
            , swapped
        )
    );

    //
    //  Add in our mappings for IBM037, and the one alias we support for
    //  it, which is EBCDIC-CP-US.
    //
    gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString));
    gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString2));

    //
    //  Add in our mappings for IBM037 with Euro update, i.e. IBM1140. It
    //  has no aliases
    //
    gMappings->put(new ENameMapFor<XMLIBM1140Transcoder>(XMLUni::fgIBM1140EncodingString));

    //
    //  Add in our mappings for Windows-1252. We don't have any aliases for
    //  this one, so there is just one mapping.
    //
    gMappings->put(new ENameMapFor<XMLWin1252Transcoder>(XMLUni::fgWin1252EncodingString));
}
<|endoftext|>