<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "ImageDataSTB.hpp"
#include "utils/Log.hpp"
#include "core/Engine.hpp"
#include "files/FileSystem.hpp"
#define STBI_NO_PSD
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_GIF
#define STBI_NO_PNM
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

namespace ouzel
{
    namespace graphics
    {
        bool ImageDataSTB::init(const std::string& filename,
                                PixelFormat newPixelFormat)
        {
            std::vector<uint8_t> newData;
            if (!engine->getFileSystem()->readFile(filename, newData))
            {
                return false;
            }

            return init(newData, newPixelFormat);
        }

        bool ImageDataSTB::init(const std::vector<uint8_t>& newData,
                                PixelFormat newPixelFormat)
        {
            int width;
            int height;
            int comp;

            int reqComp;
            switch (newPixelFormat)
            {
                case PixelFormat::R8_UNORM: reqComp = STBI_grey; break;
                case PixelFormat::RG8_UNORM: reqComp = STBI_grey_alpha; break;
                case PixelFormat::RGBA8_UNORM: reqComp = STBI_rgb_alpha; break;
                default: reqComp = STBI_default;
            }

            stbi_uc* tempData = stbi_load_from_memory(newData.data(), static_cast<int>(newData.size()), &width, &height, &comp, reqComp);

            if (!tempData)
            {
                Log(Log::Level::ERR) << "Failed to load texture, reason: " << stbi_failure_reason();
                return false;
            }

            if (reqComp != STBI_default) comp = reqComp;

            size_t pixelSize;
            switch (comp)
            {
                case STBI_grey: pixelFormat = PixelFormat::R8_UNORM; pixelSize = 1; break;
                case STBI_grey_alpha: pixelFormat = PixelFormat::RG8_UNORM; pixelSize = 2; break;
                case STBI_rgb_alpha: pixelFormat = PixelFormat::RGBA8_UNORM; pixelSize = 4; break;
                default:
                    Log(Log::Level::ERR) << "Unknown pixel size";
                    return false;
            }

            data.assign(tempData, tempData + (width * height * pixelSize));

            stbi_image_free(tempData);

            size.width = static_cast<float>(width);
            size.height = static_cast<float>(height);

            return true;
        }

        bool ImageDataSTB::writeToFile(const std::string& newFilename)
        {
            int depth = static_cast<int>(getPixelSize(pixelFormat));
            int width = static_cast<int>(size.width);
            int height = static_cast<int>(size.height);

            if (!stbi_write_png(newFilename.c_str(), width, height, depth, data.data(), width * depth))
            {
                Log(Log::Level::ERR) << "Failed to save image to file";
                return false;
            }

            return true;
        }

    } // namespace graphics
} // namespace ouzel
<commit_msg>FIx memory leak in ImageDataSTB<commit_after>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "ImageDataSTB.hpp"
#include "utils/Log.hpp"
#include "core/Engine.hpp"
#include "files/FileSystem.hpp"
#define STBI_NO_PSD
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_GIF
#define STBI_NO_PNM
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

namespace ouzel
{
    namespace graphics
    {
        bool ImageDataSTB::init(const std::string& filename,
                                PixelFormat newPixelFormat)
        {
            std::vector<uint8_t> newData;
            if (!engine->getFileSystem()->readFile(filename, newData))
            {
                return false;
            }

            return init(newData, newPixelFormat);
        }

        bool ImageDataSTB::init(const std::vector<uint8_t>& newData,
                                PixelFormat newPixelFormat)
        {
            int width;
            int height;
            int comp;

            int reqComp;
            switch (newPixelFormat)
            {
                case PixelFormat::R8_UNORM: reqComp = STBI_grey; break;
                case PixelFormat::RG8_UNORM: reqComp = STBI_grey_alpha; break;
                case PixelFormat::RGBA8_UNORM: reqComp = STBI_rgb_alpha; break;
                default: reqComp = STBI_default;
            }

            stbi_uc* tempData = stbi_load_from_memory(newData.data(), static_cast<int>(newData.size()), &width, &height, &comp, reqComp);

            if (!tempData)
            {
                Log(Log::Level::ERR) << "Failed to load texture, reason: " << stbi_failure_reason();
                return false;
            }

            if (reqComp != STBI_default) comp = reqComp;

            size_t pixelSize;
            switch (comp)
            {
                case STBI_grey: pixelFormat = PixelFormat::R8_UNORM; pixelSize = 1; break;
                case STBI_grey_alpha: pixelFormat = PixelFormat::RG8_UNORM; pixelSize = 2; break;
                case STBI_rgb_alpha: pixelFormat = PixelFormat::RGBA8_UNORM; pixelSize = 4; break;
                default:
                    Log(Log::Level::ERR) << "Unknown pixel size";
                    stbi_image_free(tempData);
                    return false;
            }

            data.assign(tempData, tempData + (width * height * pixelSize));

            stbi_image_free(tempData);

            size.width = static_cast<float>(width);
            size.height = static_cast<float>(height);

            return true;
        }

        bool ImageDataSTB::writeToFile(const std::string& newFilename)
        {
            int depth = static_cast<int>(getPixelSize(pixelFormat));
            int width = static_cast<int>(size.width);
            int height = static_cast<int>(size.height);

            if (!stbi_write_png(newFilename.c_str(), width, height, depth, data.data(), width * depth))
            {
                Log(Log::Level::ERR) << "Failed to save image to file";
                return false;
            }

            return true;
        }

    } // namespace graphics
} // namespace ouzel
<|endoftext|>


<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <algorithm>
#include "RenderDevice.hpp"
#include "thread/Lock.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace graphics
    {
        RenderDevice::RenderDevice(Renderer::Driver aDriver):
            driver(aDriver),
            projectionTransform(Matrix4::IDENTITY),
            renderTargetProjectionTransform(Matrix4::IDENTITY),
            refillQueue(true),
            currentFPS(0.0F),
            accumulatedFPS(0.0F)
        {
        }

        RenderDevice::~RenderDevice()
        {
        }

        bool RenderDevice::init(Window* newWindow,
                                const Size2& newSize,
                                uint32_t newSampleCount,
                                Texture::Filter newTextureFilter,
                                uint32_t newMaxAnisotropy,
                                bool newVerticalSync,
                                bool newDepth,
                                bool newDebugRenderer)
        {
            window = newWindow;
            size = newSize;
            sampleCount = newSampleCount;
            textureFilter = newTextureFilter;
            maxAnisotropy = newMaxAnisotropy;
            verticalSync = newVerticalSync;
            depth = newDepth;
            debugRenderer = newDebugRenderer;
            clearColor = Color::BLACK;

            previousFrameTime = std::chrono::steady_clock::now();

            return true;
        }

        bool RenderDevice::process()
        {
            std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();
            auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime - previousFrameTime);
            previousFrameTime = currentTime;

            float delta = diff.count() / 1000000000.0F;

            if (delta > 0.0F)
            {
                currentFPS = 1.0F / delta;
            }

            accumulatedTime += delta;
            currentAccumulatedFPS += 1.0F;

            if (accumulatedTime > 1.0F)
            {
                accumulatedFPS = currentAccumulatedFPS;
                accumulatedTime = 0.0F;
                currentAccumulatedFPS = 0.0F;
            }

            std::vector<std::unique_ptr<RenderResource>> deleteResources; // will be cleared at the end of the scope
            {
                Lock lock(resourceMutex);
                deleteResources = std::move(resourceDeleteSet);
            }

            executeAll();

            {
#if OUZEL_MULTITHREADED
                Lock lock(commandQueueMutex);
                while (!queueFinished) commandQueueCondition.wait(commandQueueMutex);
#endif

                processCommands(*renderBuffer);

                queueFinished = false;
                // refills the draw queue
                refillQueue = true;
            }

            return true;
        }

        void RenderDevice::setClearColorBuffer(bool clear)
        {
            clearColorBuffer = clear;
        }

        void RenderDevice::setClearDepthBuffer(bool clear)
        {
            clearDepthBuffer = clear;
        }

        void RenderDevice::setClearColor(Color color)
        {
            clearColor = color;
        }

        void RenderDevice::setClearDepth(float newClearDepth)
        {
            clearDepth = newClearDepth;
        }

        void RenderDevice::setSize(const Size2& newSize)
        {
            size = newSize;
        }

        std::vector<Size2> RenderDevice::getSupportedResolutions() const
        {
            return std::vector<Size2>();
        }

        void RenderDevice::deleteResource(RenderResource* resource)
        {
            Lock lock(resourceMutex);

            auto resourceIterator = std::find_if(resources.begin(), resources.end(), [resource](const std::unique_ptr<RenderResource>& ptr) {
                return ptr.get() == resource;
            });

            if (resourceIterator != resources.end())
            {
                resourceDeleteSet.push_back(std::move(*resourceIterator));
                resources.erase(resourceIterator);
            }
        }

        bool RenderDevice::addCommand(Command&& command)
        {
            fillBuffer->push_back(std::move(command));

            return true;
        }

        void RenderDevice::flushCommands()
        {
#if OUZEL_MULTITHREADED
            Lock lock(commandQueueMutex);
#endif

            refillQueue = false;

            std::swap(fillBuffer, renderBuffer);
            fillBuffer->clear();

            queueFinished = true;
            drawCallCount = static_cast<uint32_t>(renderBuffer->size());

#if OUZEL_MULTITHREADED
            commandQueueCondition.signal();
#endif
        }

        bool RenderDevice::generateScreenshot(const std::string&)
        {
            return true;
        }

        void RenderDevice::executeOnRenderThread(const std::function<void(void)>& func)
        {
            Lock lock(executeMutex);

            executeQueue.push(func);
        }

        void RenderDevice::executeAll()
        {
            std::function<void(void)> func;

            for (;;)
            {
                {
                    Lock lock(executeMutex);
                    if (executeQueue.empty()) break;

                    func = std::move(executeQueue.front());
                    executeQueue.pop();
                }

                if (func)
                {
                    func();
                }
            }
        }
    } // namespace graphics
} // namespace ouzel
<commit_msg>Allow filling the render queue paralelly to rendering<commit_after>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <algorithm>
#include "RenderDevice.hpp"
#include "thread/Lock.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace graphics
    {
        RenderDevice::RenderDevice(Renderer::Driver aDriver):
            driver(aDriver),
            projectionTransform(Matrix4::IDENTITY),
            renderTargetProjectionTransform(Matrix4::IDENTITY),
            refillQueue(true),
            currentFPS(0.0F),
            accumulatedFPS(0.0F)
        {
        }

        RenderDevice::~RenderDevice()
        {
        }

        bool RenderDevice::init(Window* newWindow,
                                const Size2& newSize,
                                uint32_t newSampleCount,
                                Texture::Filter newTextureFilter,
                                uint32_t newMaxAnisotropy,
                                bool newVerticalSync,
                                bool newDepth,
                                bool newDebugRenderer)
        {
            window = newWindow;
            size = newSize;
            sampleCount = newSampleCount;
            textureFilter = newTextureFilter;
            maxAnisotropy = newMaxAnisotropy;
            verticalSync = newVerticalSync;
            depth = newDepth;
            debugRenderer = newDebugRenderer;
            clearColor = Color::BLACK;

            previousFrameTime = std::chrono::steady_clock::now();

            return true;
        }

        bool RenderDevice::process()
        {
            std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();
            auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime - previousFrameTime);
            previousFrameTime = currentTime;

            float delta = diff.count() / 1000000000.0F;

            if (delta > 0.0F)
            {
                currentFPS = 1.0F / delta;
            }

            accumulatedTime += delta;
            currentAccumulatedFPS += 1.0F;

            if (accumulatedTime > 1.0F)
            {
                accumulatedFPS = currentAccumulatedFPS;
                accumulatedTime = 0.0F;
                currentAccumulatedFPS = 0.0F;
            }

            std::vector<std::unique_ptr<RenderResource>> deleteResources; // will be cleared at the end of the scope
            {
                Lock lock(resourceMutex);
                deleteResources = std::move(resourceDeleteSet);
            }

            executeAll();

#if OUZEL_MULTITHREADED
            Lock lock(commandQueueMutex);
            while (!queueFinished) commandQueueCondition.wait(commandQueueMutex);
#endif

            std::swap(fillBuffer, renderBuffer);
            fillBuffer->clear();

            queueFinished = false;

            // refills the draw queue
            refillQueue = true;

            processCommands(*renderBuffer);

            return true;
        }

        void RenderDevice::setClearColorBuffer(bool clear)
        {
            clearColorBuffer = clear;
        }

        void RenderDevice::setClearDepthBuffer(bool clear)
        {
            clearDepthBuffer = clear;
        }

        void RenderDevice::setClearColor(Color color)
        {
            clearColor = color;
        }

        void RenderDevice::setClearDepth(float newClearDepth)
        {
            clearDepth = newClearDepth;
        }

        void RenderDevice::setSize(const Size2& newSize)
        {
            size = newSize;
        }

        std::vector<Size2> RenderDevice::getSupportedResolutions() const
        {
            return std::vector<Size2>();
        }

        void RenderDevice::deleteResource(RenderResource* resource)
        {
            Lock lock(resourceMutex);

            auto resourceIterator = std::find_if(resources.begin(), resources.end(), [resource](const std::unique_ptr<RenderResource>& ptr) {
                return ptr.get() == resource;
            });

            if (resourceIterator != resources.end())
            {
                resourceDeleteSet.push_back(std::move(*resourceIterator));
                resources.erase(resourceIterator);
            }
        }

        bool RenderDevice::addCommand(Command&& command)
        {
            fillBuffer->push_back(std::move(command));

            return true;
        }

        void RenderDevice::flushCommands()
        {
#if OUZEL_MULTITHREADED
            Lock lock(commandQueueMutex);
#endif

            drawCallCount = static_cast<uint32_t>(fillBuffer->size());

            refillQueue = false;
            queueFinished = true;

#if OUZEL_MULTITHREADED
            commandQueueCondition.signal();
#endif
        }

        bool RenderDevice::generateScreenshot(const std::string&)
        {
            return true;
        }

        void RenderDevice::executeOnRenderThread(const std::function<void(void)>& func)
        {
            Lock lock(executeMutex);

            executeQueue.push(func);
        }

        void RenderDevice::executeAll()
        {
            std::function<void(void)> func;

            for (;;)
            {
                {
                    Lock lock(executeMutex);
                    if (executeQueue.empty()) break;

                    func = std::move(executeQueue.front());
                    executeQueue.pop();
                }

                if (func)
                {
                    func();
                }
            }
        }
    } // namespace graphics
} // namespace ouzel
<|endoftext|>


<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>

#include "xmlParse/xmlRequest.h"
#include "jsonParse/jsonRequest.h"

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "common/statistics.h"
#include "common/string.h"
#include "rest/ConnectionInfo.h"
#include "rest/OrionError.h"
#include "rest/RestService.h"
#include "rest/restReply.h"
#include "rest/rest.h"
#include "ngsi/ParseData.h"

/* ****************************************************************************
*
* payloadParse -
*/
std::string payloadParse(ConnectionInfo* ciP, ParseData* parseDataP, RestService* service, XmlRequest** reqPP, JsonRequest** jsonPP)
{
  std::string result = "NONE";

  LM_T(LmtParsedPayload, ("parsing data for service '%s'. Method: '%s'", requestType(service->request), ciP->method.c_str()));
  LM_T(LmtParsedPayload, ("outFormat: %s", formatToString(ciP->outFormat)));

  if (ciP->inFormat == XML)
  {
    LM_T(LmtParsedPayload, ("Calling xmlTreat for service request %d, payloadWord '%s'", service->request, service->payloadWord.c_str()));
    result = xmlTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, reqPP);
  }
  else if (ciP->inFormat == JSON)
    result = jsonTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, jsonPP);
  else
  {
    LM_E(("Bad inFormat: %d", (int) ciP->inFormat));
    return "Bad inFormat";
  }

  LM_T(LmtParsedPayload, ("result: '%s'", result.c_str()));
  LM_T(LmtParsedPayload, ("outFormat: %s", formatToString(ciP->outFormat)));

  if (result != "OK")
  {
    restReply(ciP, result);
  }

  return result;
}

/* ****************************************************************************
*
* tenantCheck -
*/
static std::string tenantCheck(std::string tenant)
{
  const char* ctenant = tenant.c_str();

  if ((strcasecmp(ctenant, "ngsi9")       == 0) ||
      (strcasecmp(ctenant, "ngsi10")      == 0) ||
      (strcasecmp(ctenant, "log")         == 0) ||
      (strcasecmp(ctenant, "version")     == 0) ||
      (strcasecmp(ctenant, "statistics")  == 0) ||
      (strcasecmp(ctenant, "leak")        == 0) ||
      (strcasecmp(ctenant, "exit")        == 0))
  {
    LM_E(("tenant name coincides with Orion reserved name: '%s'", tenant.c_str()));
    return "tenant name coincides with Orion reserved name";
  }

  char* name = (char*) tenant.c_str();

  if (strlen(name) > 20)
  {
    LM_E(("bad length - a tenant name can be max 20 characters long (length: %d)", strlen(name)));
    return "bad length - a tenant name can be max 20 characters long";
  }

  while (*name != 0)
  {
    if ((!isalnum(*name)) && (*name != '_'))
    {
      LM_E(("offending character: %c", *name));
      return "bad character in tenant name - only underscore and alphanumeric characters are allowed";
    }

    ++name;
  }

  return "OK";
}

/* ****************************************************************************
*
* restService -
*/
std::string restService(ConnectionInfo* ciP, RestService* serviceV)
{
  std::vector<std::string>  compV;
  int                       components;
  XmlRequest*               reqP       = NULL;
  JsonRequest*              jsonReqP   = NULL;
  ParseData                 parseData;

  if ((ciP->url.length() == 0) || ((ciP->url.length() == 1) && (ciP->url.c_str()[0] == '/')))
  {
    OrionError  error(SccBadRequest, "The Orion Context Broker is a REST service, not a 'web page'");
    std::string response = error.render(ciP->outFormat, "");
    restReply(ciP, response);
    return std::string("Empty URL");
  }

  ciP->httpStatusCode = SccOk;

  components = stringSplit(ciP->url, '/', compV);

  for (unsigned int ix = 0; serviceV[ix].treat != NULL; ++ix)
  {
    if ((serviceV[ix].components != 0) && (serviceV[ix].components != components))
      continue;

    if ((ciP->method != serviceV[ix].verb) && (serviceV[ix].verb != "*"))
      continue;

    strncpy(ciP->payloadWord, serviceV[ix].payloadWord.c_str(), sizeof(ciP->payloadWord));
    bool match = true;
    for (int compNo = 0; compNo < components; ++compNo)
    {
      if (serviceV[ix].compV[compNo] == "*")
        continue;

      if (strcasecmp(serviceV[ix].compV[compNo].c_str(), compV[compNo].c_str()) != 0)
      {
        match = false;
        break;
      }
    }

    if (match == false)
      continue;

    if ((ciP->payload != NULL) && (ciP->payloadSize != 0) && (serviceV[ix].verb != "*"))
    {
      std::string response;

      LM_T(LmtParsedPayload, ("Parsing payload for URL '%s', method '%s', service vector index: %d", ciP->url.c_str(), ciP->method.c_str(), ix));
      ciP->parseDataP = &parseData;
      response = payloadParse(ciP, &parseData, &serviceV[ix], &reqP, &jsonReqP);
      LM_T(LmtParsedPayload, ("payloadParse returns '%s'", response.c_str()));
      if (response != "OK")
      {
        restReply(ciP, response);

        if (reqP != NULL)
          reqP->release(&parseData);
        if (jsonReqP != NULL)
          jsonReqP->release(&parseData);

        compV.clear();
        return response;
      }
    }

    LM_T(LmtService, ("Treating service %s %s", serviceV[ix].verb.c_str(), ciP->url.c_str())); // Sacred - used in 'heavyTest'
    statisticsUpdate(serviceV[ix].request, ciP->inFormat);

    // Tenant to connectionInfo
    if (serviceV[ix].compV[0] == "*")
    {
      LM_T(LmtTenant, ("URL tenant: '%s'", compV[0].c_str()));
      ciP->tenantFromUrl = compV[0];
    }

    if (multitenant == "url")
      ciP->tenant = ciP->tenantFromUrl;
    else if (multitenant == "header")
      ciP->tenant = ciP->tenantFromHttpHeader;
    else // multitenant == "off"
      ciP->tenant = "";

    //
    // A tenant string must not be longer that 20 characters and may only contain
    // underscores and alphanumeric characters.
    //
    std::string result;
    if ((ciP->tenant != "") && ((result = tenantCheck(ciP->tenant)) != "OK"))
    {
      OrionError   error(SccBadRequest, "tenant format not accepted (a tenant string must not be longer that 20 characters and may only contain underscores and alphanumeric characters)");
      std::string  response = error.render(ciP->outFormat, "");

      LM_E(("tenant name error: %s", result.c_str()));
      restReply(ciP, response);
      return response;
    }

    LM_T(LmtTenant, ("tenant: '%s'", ciP->tenant.c_str()));
    std::string response = serviceV[ix].treat(ciP, components, compV, &parseData);

    if (reqP != NULL)
    {
      reqP->release(&parseData);
    }

    if (jsonReqP != NULL)
    {
      jsonReqP->release(&parseData);
    }

    compV.clear();

    if (response == "DIE")
      orionExitFunction(1, "Received a 'DIE' request");

    restReply(ciP, response);
    return response;
  }

  LM_E(("Service '%s' not recognized", ciP->url.c_str()));
  ciP->httpStatusCode = SccBadRequest;
  std::string answer = restErrorReplyGet(ciP, ciP->outFormat, "", ciP->payloadWord, SccBadRequest, std::string("Service not recognized: ") + ciP->url);
  restReply(ciP, answer);

  compV.clear();
  return answer;
}
<commit_msg>Fixed a memory leak<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>

#include "xmlParse/xmlRequest.h"
#include "jsonParse/jsonRequest.h"

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "common/statistics.h"
#include "common/string.h"
#include "rest/ConnectionInfo.h"
#include "rest/OrionError.h"
#include "rest/RestService.h"
#include "rest/restReply.h"
#include "rest/rest.h"
#include "ngsi/ParseData.h"

/* ****************************************************************************
*
* payloadParse -
*/
std::string payloadParse(ConnectionInfo* ciP, ParseData* parseDataP, RestService* service, XmlRequest** reqPP, JsonRequest** jsonPP)
{
  std::string result = "NONE";

  LM_T(LmtParsedPayload, ("parsing data for service '%s'. Method: '%s'", requestType(service->request), ciP->method.c_str()));
  LM_T(LmtParsedPayload, ("outFormat: %s", formatToString(ciP->outFormat)));

  if (ciP->inFormat == XML)
  {
    LM_T(LmtParsedPayload, ("Calling xmlTreat for service request %d, payloadWord '%s'", service->request, service->payloadWord.c_str()));
    result = xmlTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, reqPP);
  }
  else if (ciP->inFormat == JSON)
    result = jsonTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, jsonPP);
  else
  {
    LM_E(("Bad inFormat: %d", (int) ciP->inFormat));
    return "Bad inFormat";
  }

  LM_T(LmtParsedPayload, ("result: '%s'", result.c_str()));
  LM_T(LmtParsedPayload, ("outFormat: %s", formatToString(ciP->outFormat)));

  if (result != "OK")
  {
    restReply(ciP, result);
  }

  return result;
}

/* ****************************************************************************
*
* tenantCheck -
*/
static std::string tenantCheck(std::string tenant)
{
  const char* ctenant = tenant.c_str();

  if ((strcasecmp(ctenant, "ngsi9")       == 0) ||
      (strcasecmp(ctenant, "ngsi10")      == 0) ||
      (strcasecmp(ctenant, "log")         == 0) ||
      (strcasecmp(ctenant, "version")     == 0) ||
      (strcasecmp(ctenant, "statistics")  == 0) ||
      (strcasecmp(ctenant, "leak")        == 0) ||
      (strcasecmp(ctenant, "exit")        == 0))
  {
    LM_E(("tenant name coincides with Orion reserved name: '%s'", tenant.c_str()));
    return "tenant name coincides with Orion reserved name";
  }

  char* name = (char*) tenant.c_str();

  if (strlen(name) > 20)
  {
    LM_E(("bad length - a tenant name can be max 20 characters long (length: %d)", strlen(name)));
    return "bad length - a tenant name can be max 20 characters long";
  }

  while (*name != 0)
  {
    if ((!isalnum(*name)) && (*name != '_'))
    {
      LM_E(("offending character: %c", *name));
      return "bad character in tenant name - only underscore and alphanumeric characters are allowed";
    }

    ++name;
  }

  return "OK";
}

/* ****************************************************************************
*
* restService -
*/
std::string restService(ConnectionInfo* ciP, RestService* serviceV)
{
  std::vector<std::string>  compV;
  int                       components;
  XmlRequest*               reqP       = NULL;
  JsonRequest*              jsonReqP   = NULL;
  ParseData                 parseData;

  if ((ciP->url.length() == 0) || ((ciP->url.length() == 1) && (ciP->url.c_str()[0] == '/')))
  {
    OrionError  error(SccBadRequest, "The Orion Context Broker is a REST service, not a 'web page'");
    std::string response = error.render(ciP->outFormat, "");
    restReply(ciP, response);
    return std::string("Empty URL");
  }

  ciP->httpStatusCode = SccOk;

  components = stringSplit(ciP->url, '/', compV);

  for (unsigned int ix = 0; serviceV[ix].treat != NULL; ++ix)
  {
    if ((serviceV[ix].components != 0) && (serviceV[ix].components != components))
      continue;

    if ((ciP->method != serviceV[ix].verb) && (serviceV[ix].verb != "*"))
      continue;

    strncpy(ciP->payloadWord, serviceV[ix].payloadWord.c_str(), sizeof(ciP->payloadWord));
    bool match = true;
    for (int compNo = 0; compNo < components; ++compNo)
    {
      if (serviceV[ix].compV[compNo] == "*")
        continue;

      if (strcasecmp(serviceV[ix].compV[compNo].c_str(), compV[compNo].c_str()) != 0)
      {
        match = false;
        break;
      }
    }

    if (match == false)
      continue;

    if ((ciP->payload != NULL) && (ciP->payloadSize != 0) && (serviceV[ix].verb != "*"))
    {
      std::string response;

      LM_T(LmtParsedPayload, ("Parsing payload for URL '%s', method '%s', service vector index: %d", ciP->url.c_str(), ciP->method.c_str(), ix));
      ciP->parseDataP = &parseData;
      response = payloadParse(ciP, &parseData, &serviceV[ix], &reqP, &jsonReqP);
      LM_T(LmtParsedPayload, ("payloadParse returns '%s'", response.c_str()));
      if (response != "OK")
      {
        restReply(ciP, response);

        if (reqP != NULL)
          reqP->release(&parseData);
        if (jsonReqP != NULL)
          jsonReqP->release(&parseData);

        compV.clear();
        return response;
      }
    }

    LM_T(LmtService, ("Treating service %s %s", serviceV[ix].verb.c_str(), ciP->url.c_str())); // Sacred - used in 'heavyTest'
    statisticsUpdate(serviceV[ix].request, ciP->inFormat);

    // Tenant to connectionInfo
    if (serviceV[ix].compV[0] == "*")
    {
      LM_T(LmtTenant, ("URL tenant: '%s'", compV[0].c_str()));
      ciP->tenantFromUrl = compV[0];
    }

    if (multitenant == "url")
      ciP->tenant = ciP->tenantFromUrl;
    else if (multitenant == "header")
      ciP->tenant = ciP->tenantFromHttpHeader;
    else // multitenant == "off"
      ciP->tenant = "";

    //
    // A tenant string must not be longer that 20 characters and may only contain
    // underscores and alphanumeric characters.
    //
    std::string result;
    if ((ciP->tenant != "") && ((result = tenantCheck(ciP->tenant)) != "OK"))
    {
      OrionError   error(SccBadRequest, "tenant format not accepted (a tenant string must not be longer that 20 characters and may only contain underscores and alphanumeric characters)");
      std::string  response = error.render(ciP->outFormat, "");

      LM_E(("tenant name error: %s", result.c_str()));
      restReply(ciP, response);

      if (reqP != NULL)
        reqP->release(&parseData);
      if (jsonReqP != NULL)
        jsonReqP->release(&parseData);

      compV.clear();

      return response;
    }

    LM_T(LmtTenant, ("tenant: '%s'", ciP->tenant.c_str()));
    std::string response = serviceV[ix].treat(ciP, components, compV, &parseData);

    if (reqP != NULL)
    {
      reqP->release(&parseData);
    }

    if (jsonReqP != NULL)
    {
      jsonReqP->release(&parseData);
    }

    compV.clear();

    if (response == "DIE")
      orionExitFunction(1, "Received a 'DIE' request");

    restReply(ciP, response);
    return response;
  }

  LM_E(("Service '%s' not recognized", ciP->url.c_str()));
  ciP->httpStatusCode = SccBadRequest;
  std::string answer = restErrorReplyGet(ciP, ciP->outFormat, "", ciP->payloadWord, SccBadRequest, std::string("Service not recognized: ") + ciP->url);
  restReply(ciP, answer);

  compV.clear();
  return answer;
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2014 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "StringHelper.h"

using namespace std;

namespace avg {

bool isWhitespace(const string& s)
{
    return s.find_first_not_of(" \n\r\t") == s.npos;
}

void skipWhitespace(std::istream& is)
{
    string sWhitespace(" \n\r\t");
    bool bWhitespace;
    do {
        int i = is.peek();
        if (i == EOF) {
            bWhitespace = false;
        } else {
            bWhitespace = (sWhitespace.find(char(i)) != sWhitespace.npos);
        }
        if (bWhitespace) {
            is.ignore();
        }
    } while (bWhitespace);
}

void skipToken(std::istream& is, char token)
{
    skipWhitespace(is);
    int i = is.peek();
    if (i == token) {
        is.ignore();
    } else {
        is.setstate(ios::failbit);
    }
}

int stringToInt(const string& s)
{
    int i;
    fromString(s, i);
    return i;
}

float stringToFloat(const string& s)
{
    float d;
    fromString(s, d);
    return d;
}

bool stringToBool(const string& s)
{
    // avg usually wants xml attributes in lowercase, but python only
    // sees 'True' as true, so we'll accept that too. Also, python 2.3
    // has 1 as true, so that has to be ok too.
    if (s == "True" || s == "true" || s == "1") {
        return true;
    }
    if (s == "False" || s == "false" || s == "0") {
        return false;
    }
    throw (Exception(AVG_ERR_TYPE, string("Could not convert ")+s+" to bool."));
}

std::string removeStartEndSpaces(const string& s)
{
    string sResult = s;
    while (sResult.size() > 0 && (sResult[0] == ' ' || sResult[0] == '\n'
            || sResult[0] == '\r' || sResult[0] == '\t'))
    {
        sResult.erase(0, 1);
    }
    if (sResult.size() == 0) {
        return sResult;
    }
    char c = sResult[sResult.length()-1];
    while (c == ' ' || c == '\n' || c == '\r' || c == '\t') {
        sResult.erase(sResult.length()-1, 1);
        c = sResult[sResult.length()-1];
    }
    return sResult;
}

string toLowerCase(const string& s)
{
    string sResult;
    for (unsigned i=0; i<s.length(); ++i) {
        sResult.push_back(::tolower(s[i]));
    }
    return sResult;
}

bool equalIgnoreCase(const string& s1, const string& s2)
{
    if (s1.length() != s2.length()) {
        return false;
    }
    string sUpper1;
    string sUpper2;
    transform(s1.begin(), s1.end(), std::back_inserter(sUpper1), (int(*)(int)) toupper);
    transform(s2.begin(), s2.end(), std::back_inserter(sUpper2), (int(*)(int)) toupper);
    return sUpper1 == sUpper2;
}

string toString(const bool& b)
{
    if (b) {
        return "true";
    } else {
        return "false";
    }
}

}

<commit_msg>Linux build fix.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2014 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "StringHelper.h"

#include <cstdio>
#include <algorithm>

using namespace std;

namespace avg {

bool isWhitespace(const string& s)
{
    return s.find_first_not_of(" \n\r\t") == s.npos;
}

void skipWhitespace(std::istream& is)
{
    string sWhitespace(" \n\r\t");
    bool bWhitespace;
    do {
        int i = is.peek();
        if (i == EOF) {
            bWhitespace = false;
        } else {
            bWhitespace = (sWhitespace.find(char(i)) != sWhitespace.npos);
        }
        if (bWhitespace) {
            is.ignore();
        }
    } while (bWhitespace);
}

void skipToken(std::istream& is, char token)
{
    skipWhitespace(is);
    int i = is.peek();
    if (i == token) {
        is.ignore();
    } else {
        is.setstate(ios::failbit);
    }
}

int stringToInt(const string& s)
{
    int i;
    fromString(s, i);
    return i;
}

float stringToFloat(const string& s)
{
    float d;
    fromString(s, d);
    return d;
}

bool stringToBool(const string& s)
{
    // avg usually wants xml attributes in lowercase, but python only
    // sees 'True' as true, so we'll accept that too. Also, python 2.3
    // has 1 as true, so that has to be ok too.
    if (s == "True" || s == "true" || s == "1") {
        return true;
    }
    if (s == "False" || s == "false" || s == "0") {
        return false;
    }
    throw (Exception(AVG_ERR_TYPE, string("Could not convert ")+s+" to bool."));
}

std::string removeStartEndSpaces(const string& s)
{
    string sResult = s;
    while (sResult.size() > 0 && (sResult[0] == ' ' || sResult[0] == '\n'
            || sResult[0] == '\r' || sResult[0] == '\t'))
    {
        sResult.erase(0, 1);
    }
    if (sResult.size() == 0) {
        return sResult;
    }
    char c = sResult[sResult.length()-1];
    while (c == ' ' || c == '\n' || c == '\r' || c == '\t') {
        sResult.erase(sResult.length()-1, 1);
        c = sResult[sResult.length()-1];
    }
    return sResult;
}

string toLowerCase(const string& s)
{
    string sResult;
    for (unsigned i=0; i<s.length(); ++i) {
        sResult.push_back(::tolower(s[i]));
    }
    return sResult;
}

bool equalIgnoreCase(const string& s1, const string& s2)
{
    if (s1.length() != s2.length()) {
        return false;
    }
    string sUpper1;
    string sUpper2;
    transform(s1.begin(), s1.end(), std::back_inserter(sUpper1), (int(*)(int)) toupper);
    transform(s2.begin(), s2.end(), std::back_inserter(sUpper2), (int(*)(int)) toupper);
    return sUpper1 == sUpper2;
}

string toString(const bool& b)
{
    if (b) {
        return "true";
    } else {
        return "false";
    }
}

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: RelationDlg.cxx,v $
 * $Revision: 1.27 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
//#ifndef _SVX_TABWIN_HXX
//#include "tabwin.hxx"
//#endif
#ifndef DBAUI_RELATIONDIALOG_HRC
#include "RelationDlg.hrc"
#endif
#ifndef DBAUI_RELATIONDIALOG_HXX
#include "RelationDlg.hxx"
#endif

#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif

#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef DBAUI_RTABLECONNECTIONDATA_HXX
#include "RTableConnectionData.hxx"
#endif
#ifndef DBAUI_RELATIONCONTROL_HXX
#include "RelationControl.hxx"
#endif

#include <algorithm>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace ::dbaui;
using namespace ::dbtools;

//========================================================================
// class ORelationDialog
DBG_NAME(ORelationDialog)
//========================================================================
ORelationDialog::ORelationDialog( OJoinTableView* pParent,
                                 const TTableConnectionData::value_type& pConnectionData,
                                 BOOL bAllowTableSelect )
    :ModalDialog( pParent, ModuleRes(DLG_REL_PROPERTIES) )
    ,m_pTableMap(pParent->GetTabWinMap())

    ,aFL_CascUpd(           this, ModuleRes(FL_CASC_UPD) )
    ,aRB_NoCascUpd(         this, ModuleRes(RB_NO_CASC_UPD) )
    ,aRB_CascUpd(           this, ModuleRes(RB_CASC_UPD) )
    ,aRB_CascUpdNull(       this, ModuleRes(RB_CASC_UPD_NULL) )
    ,aRB_CascUpdDefault(    this, ModuleRes(RB_CASC_UPD_DEFAULT) )
    ,aFL_CascDel(           this, ModuleRes(FL_CASC_DEL) )
    ,aRB_NoCascDel(         this, ModuleRes(RB_NO_CASC_DEL) )
    ,aRB_CascDel(           this, ModuleRes(RB_CASC_DEL) )
    ,aRB_CascDelNull(       this, ModuleRes(RB_CASC_DEL_NULL) )
    ,aRB_CascDelDefault(    this, ModuleRes(RB_CASC_DEL_DEFAULT) )

    ,aPB_OK( this, ModuleRes( PB_OK ) )
    ,aPB_CANCEL( this, ModuleRes( PB_CANCEL ) )
    ,aPB_HELP( this, ModuleRes( PB_HELP ) )

    ,m_pOrigConnData( pConnectionData )
    ,m_bTriedOneUpdate(FALSE)
{
    DBG_CTOR(ORelationDialog,NULL);

    m_xConnection = pParent->getDesignView()->getController()->getConnection();

    //////////////////////////////////////////////////////////////////////
    // Connection kopieren
    m_pConnData.reset( static_cast<ORelationTableConnectionData*>(pConnectionData->NewInstance()) );
    m_pConnData->CopyFrom( *pConnectionData );

    Init(m_pConnData);
    m_pTableControl.reset( new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this) );

    aPB_OK.SetClickHdl( LINK(this, ORelationDialog, OKClickHdl) );

    m_pTableControl->Init( m_pConnData );
    if ( bAllowTableSelect )
        m_pTableControl->fillListBoxes();
    else
        m_pTableControl->fillAndDisable(pConnectionData);

    m_pTableControl->lateInit();

    m_pTableControl->NotifyCellChange();

    FreeResource();
}

//------------------------------------------------------------------------
void ORelationDialog::Init(const TTableConnectionData::value_type& _pConnectionData)
{
    ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(_pConnectionData.get());
    // Update Rules
    switch (pConnData->GetUpdateRules())
    {
    case KeyRule::NO_ACTION:
    case KeyRule::RESTRICT:
        aRB_NoCascUpd.Check( TRUE );
        break;

    case KeyRule::CASCADE:
        aRB_CascUpd.Check( TRUE );
        break;

    case KeyRule::SET_NULL:
        aRB_CascUpdNull.Check( TRUE );
        break;
    case KeyRule::SET_DEFAULT:
        aRB_CascUpdDefault.Check( TRUE );
        break;
    }

    // Delete Rules
    switch (pConnData->GetDeleteRules())
    {
    case KeyRule::NO_ACTION:
    case KeyRule::RESTRICT:
        aRB_NoCascDel.Check( TRUE );
        break;

    case KeyRule::CASCADE:
        aRB_CascDel.Check( TRUE );
        break;

    case KeyRule::SET_NULL:
        aRB_CascDelNull.Check( TRUE );
        break;
    case KeyRule::SET_DEFAULT:
        aRB_CascDelDefault.Check( TRUE );
        break;
    }
}

//------------------------------------------------------------------------
ORelationDialog::~ORelationDialog()
{
    DBG_DTOR(ORelationDialog,NULL);
}

//------------------------------------------------------------------------

//------------------------------------------------------------------------
IMPL_LINK( ORelationDialog, OKClickHdl, Button*, /*pButton*/ )
{
    //////////////////////////////////////////////////////////////////////
    // RadioButtons auslesen
    UINT16 nAttrib = 0;

    // Delete Rules
    if( aRB_NoCascDel.IsChecked() )
        nAttrib |= KeyRule::NO_ACTION;
    if( aRB_CascDel.IsChecked() )
        nAttrib |= KeyRule::CASCADE;
    if( aRB_CascDelNull.IsChecked() )
        nAttrib |= KeyRule::SET_NULL;
    if( aRB_CascDelDefault.IsChecked() )
        nAttrib |= KeyRule::SET_DEFAULT;

    ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(m_pConnData.get());
    pConnData->SetDeleteRules( nAttrib );

    // Update Rules
    nAttrib = 0;
    if( aRB_NoCascUpd.IsChecked() )
        nAttrib |= KeyRule::NO_ACTION;
    if( aRB_CascUpd.IsChecked() )
        nAttrib |= KeyRule::CASCADE;
    if( aRB_CascUpdNull.IsChecked() )
        nAttrib |= KeyRule::SET_NULL;
    if( aRB_CascUpdDefault.IsChecked() )
        nAttrib |= KeyRule::SET_DEFAULT;
    pConnData->SetUpdateRules( nAttrib );

    m_pTableControl->SaveModified();

    //// wenn die ComboBoxen fuer die Tabellenauswahl enabled sind (Constructor mit bAllowTableSelect==TRUE), dann muss ich in die
    //// Connection auch die Tabellennamen stecken
    //m_pConnData->SetSourceWinName(m_pTableControl->getSourceWinName());
    //m_pConnData->SetDestWinName(m_pTableControl->getDestWinName());

    // try to create the relation
    try
    {
        ORelationTableConnectionData* pOrigConnData = static_cast<ORelationTableConnectionData*>(m_pOrigConnData.get());
        if (*pConnData != *pOrigConnData || pConnData->Update())
        {
            m_pOrigConnData->CopyFrom( *m_pConnData );
            EndDialog( RET_OK );
            return 0L;
        }
    }
    catch(const SQLException& e)
    {
        ::dbaui::showError( SQLExceptionInfo(e),
                            this,
                            static_cast<OJoinTableView*>(GetParent())->getDesignView()->getController()->getORB());
    }
    catch(const Exception&)
    {
        //OSL_ENSURE(sal_False, "ORelationDialog, OKClickHdl: caught an exception!");
    }

    m_bTriedOneUpdate = TRUE;
    // this means that the original connection may be lost (if m_pConnData was not a newly created but an
    // existent conn to be modified), which we reflect by returning RET_NO (see ::Execute)

    // try again
    Init(m_pConnData);
    m_pTableControl->Init( m_pConnData );
    m_pTableControl->lateInit();

    return 0;
}

//------------------------------------------------------------------------
short ORelationDialog::Execute()
{
    short nResult = ModalDialog::Execute();
    if ((nResult != RET_OK) && m_bTriedOneUpdate)
        return RET_NO;

    return nResult;
}
// -----------------------------------------------------------------------------
TTableConnectionData::value_type ORelationDialog::getConnectionData() const
{
    return m_pConnData;
}
// -----------------------------------------------------------------------------
void ORelationDialog::setValid(sal_Bool _bValid)
{
    aPB_OK.Enable(_bValid);
}
// -----------------------------------------------------------------------------
void ORelationDialog::notifyConnectionChange()
{
    Init(m_pConnData);
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba30b (1.26.78); FILE MERGED 2008/04/15 22:13:23 fs 1.26.78.2: RESYNC: (1.26-1.27); FILE MERGED 2008/03/16 14:09:02 fs 1.26.78.1: some exception handling re-factoring<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: RelationDlg.cxx,v $
 * $Revision: 1.28 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
//#ifndef _SVX_TABWIN_HXX
//#include "tabwin.hxx"
//#endif
#ifndef DBAUI_RELATIONDIALOG_HRC
#include "RelationDlg.hrc"
#endif
#ifndef DBAUI_RELATIONDIALOG_HXX
#include "RelationDlg.hxx"
#endif

#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif

#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef DBAUI_RTABLECONNECTIONDATA_HXX
#include "RTableConnectionData.hxx"
#endif
#ifndef DBAUI_RELATIONCONTROL_HXX
#include "RelationControl.hxx"
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif

#include <algorithm>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace ::dbaui;
using namespace ::dbtools;

//========================================================================
// class ORelationDialog
DBG_NAME(ORelationDialog)
//========================================================================
ORelationDialog::ORelationDialog( OJoinTableView* pParent,
                                 const TTableConnectionData::value_type& pConnectionData,
                                 BOOL bAllowTableSelect )
    :ModalDialog( pParent, ModuleRes(DLG_REL_PROPERTIES) )
    ,m_pTableMap(pParent->GetTabWinMap())

    ,aFL_CascUpd(           this, ModuleRes(FL_CASC_UPD) )
    ,aRB_NoCascUpd(         this, ModuleRes(RB_NO_CASC_UPD) )
    ,aRB_CascUpd(           this, ModuleRes(RB_CASC_UPD) )
    ,aRB_CascUpdNull(       this, ModuleRes(RB_CASC_UPD_NULL) )
    ,aRB_CascUpdDefault(    this, ModuleRes(RB_CASC_UPD_DEFAULT) )
    ,aFL_CascDel(           this, ModuleRes(FL_CASC_DEL) )
    ,aRB_NoCascDel(         this, ModuleRes(RB_NO_CASC_DEL) )
    ,aRB_CascDel(           this, ModuleRes(RB_CASC_DEL) )
    ,aRB_CascDelNull(       this, ModuleRes(RB_CASC_DEL_NULL) )
    ,aRB_CascDelDefault(    this, ModuleRes(RB_CASC_DEL_DEFAULT) )

    ,aPB_OK( this, ModuleRes( PB_OK ) )
    ,aPB_CANCEL( this, ModuleRes( PB_CANCEL ) )
    ,aPB_HELP( this, ModuleRes( PB_HELP ) )

    ,m_pOrigConnData( pConnectionData )
    ,m_bTriedOneUpdate(FALSE)
{
    DBG_CTOR(ORelationDialog,NULL);

    m_xConnection = pParent->getDesignView()->getController()->getConnection();

    //////////////////////////////////////////////////////////////////////
    // Connection kopieren
    m_pConnData.reset( static_cast<ORelationTableConnectionData*>(pConnectionData->NewInstance()) );
    m_pConnData->CopyFrom( *pConnectionData );

    Init(m_pConnData);
    m_pTableControl.reset( new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this) );

    aPB_OK.SetClickHdl( LINK(this, ORelationDialog, OKClickHdl) );

    m_pTableControl->Init( m_pConnData );
    if ( bAllowTableSelect )
        m_pTableControl->fillListBoxes();
    else
        m_pTableControl->fillAndDisable(pConnectionData);

    m_pTableControl->lateInit();

    m_pTableControl->NotifyCellChange();

    FreeResource();
}

//------------------------------------------------------------------------
void ORelationDialog::Init(const TTableConnectionData::value_type& _pConnectionData)
{
    ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(_pConnectionData.get());
    // Update Rules
    switch (pConnData->GetUpdateRules())
    {
    case KeyRule::NO_ACTION:
    case KeyRule::RESTRICT:
        aRB_NoCascUpd.Check( TRUE );
        break;

    case KeyRule::CASCADE:
        aRB_CascUpd.Check( TRUE );
        break;

    case KeyRule::SET_NULL:
        aRB_CascUpdNull.Check( TRUE );
        break;
    case KeyRule::SET_DEFAULT:
        aRB_CascUpdDefault.Check( TRUE );
        break;
    }

    // Delete Rules
    switch (pConnData->GetDeleteRules())
    {
    case KeyRule::NO_ACTION:
    case KeyRule::RESTRICT:
        aRB_NoCascDel.Check( TRUE );
        break;

    case KeyRule::CASCADE:
        aRB_CascDel.Check( TRUE );
        break;

    case KeyRule::SET_NULL:
        aRB_CascDelNull.Check( TRUE );
        break;
    case KeyRule::SET_DEFAULT:
        aRB_CascDelDefault.Check( TRUE );
        break;
    }
}

//------------------------------------------------------------------------
ORelationDialog::~ORelationDialog()
{
    DBG_DTOR(ORelationDialog,NULL);
}

//------------------------------------------------------------------------

//------------------------------------------------------------------------
IMPL_LINK( ORelationDialog, OKClickHdl, Button*, /*pButton*/ )
{
    //////////////////////////////////////////////////////////////////////
    // RadioButtons auslesen
    UINT16 nAttrib = 0;

    // Delete Rules
    if( aRB_NoCascDel.IsChecked() )
        nAttrib |= KeyRule::NO_ACTION;
    if( aRB_CascDel.IsChecked() )
        nAttrib |= KeyRule::CASCADE;
    if( aRB_CascDelNull.IsChecked() )
        nAttrib |= KeyRule::SET_NULL;
    if( aRB_CascDelDefault.IsChecked() )
        nAttrib |= KeyRule::SET_DEFAULT;

    ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(m_pConnData.get());
    pConnData->SetDeleteRules( nAttrib );

    // Update Rules
    nAttrib = 0;
    if( aRB_NoCascUpd.IsChecked() )
        nAttrib |= KeyRule::NO_ACTION;
    if( aRB_CascUpd.IsChecked() )
        nAttrib |= KeyRule::CASCADE;
    if( aRB_CascUpdNull.IsChecked() )
        nAttrib |= KeyRule::SET_NULL;
    if( aRB_CascUpdDefault.IsChecked() )
        nAttrib |= KeyRule::SET_DEFAULT;
    pConnData->SetUpdateRules( nAttrib );

    m_pTableControl->SaveModified();

    //// wenn die ComboBoxen fuer die Tabellenauswahl enabled sind (Constructor mit bAllowTableSelect==TRUE), dann muss ich in die
    //// Connection auch die Tabellennamen stecken
    //m_pConnData->SetSourceWinName(m_pTableControl->getSourceWinName());
    //m_pConnData->SetDestWinName(m_pTableControl->getDestWinName());

    // try to create the relation
    try
    {
        ORelationTableConnectionData* pOrigConnData = static_cast<ORelationTableConnectionData*>(m_pOrigConnData.get());
        if (*pConnData != *pOrigConnData || pConnData->Update())
        {
            m_pOrigConnData->CopyFrom( *m_pConnData );
            EndDialog( RET_OK );
            return 0L;
        }
    }
    catch( const SQLException& )
    {
        ::dbaui::showError( SQLExceptionInfo( ::cppu::getCaughtException() ),
                            this,
                            static_cast<OJoinTableView*>(GetParent())->getDesignView()->getController()->getORB());
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
    }

    m_bTriedOneUpdate = TRUE;
    // this means that the original connection may be lost (if m_pConnData was not a newly created but an
    // existent conn to be modified), which we reflect by returning RET_NO (see ::Execute)

    // try again
    Init(m_pConnData);
    m_pTableControl->Init( m_pConnData );
    m_pTableControl->lateInit();

    return 0;
}

//------------------------------------------------------------------------
short ORelationDialog::Execute()
{
    short nResult = ModalDialog::Execute();
    if ((nResult != RET_OK) && m_bTriedOneUpdate)
        return RET_NO;

    return nResult;
}
// -----------------------------------------------------------------------------
TTableConnectionData::value_type ORelationDialog::getConnectionData() const
{
    return m_pConnData;
}
// -----------------------------------------------------------------------------
void ORelationDialog::setValid(sal_Bool _bValid)
{
    aPB_OK.Enable(_bValid);
}
// -----------------------------------------------------------------------------
void ORelationDialog::notifyConnectionChange()
{
    Init(m_pConnData);
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>#pragma once

#include <list>
#include <random>
#include <unordered_map>
#include <utility>
#include <vector>

#include "abstract_cache.hpp"

namespace opossum {

// Generic cache implementation using a random eviction policy.
// Note: This implementation is not thread-safe.
template <typename Key, typename Value>
class RandomCache : public AbstractCache<Key, Value> {
 public:
  typedef typename std::pair<Key, Value> KeyValuePair;

  explicit RandomCache(size_t capacity) : AbstractCache<Key, Value>(capacity), _gen(_rd()), _rand(0, capacity - 1) {
    _list.reserve(capacity);
  }

  // Sets the value to be cached at the given key.
  void set(const Key& key, const Value& value, double cost = 1.0, double size = 1.0) {
    // Override old element at that key, if it exists.
    auto it = _map.find(key);
    if (it != _map.end()) {
      _list[it->second].second = value;
      return;
    }

    // If capacity is exceeded, pick a random element and replace it.
    if (_list.size() >= this->_capacity) {
      size_t index = _rand(_gen);
      _map.erase(_list[index].first);

      _list[index] = KeyValuePair(key, value);
      _map[key] = index;
      return;
    }

    // Otherwise simply add to the end of the vector.
    _list.push_back(KeyValuePair(key, value));
    _map[key] = _list.size() - 1;
  }

  // Retrieves the value cached at the key.
  Value& get(const Key& key) {
    auto it = _map.find(key);
    return _list[it->second].second;
  }

  bool has(const Key& key) const { return _map.find(key) != _map.end(); }

  size_t size() const { return _map.size(); }

  void clear() {
    _list.clear();
    _map.clear();
  }

  void resize(size_t capacity) {
    while (_list.size() > capacity) {
      _evict();
    }

    this->_capacity = capacity;
    _rand = std::uniform_int_distribution<>(0, capacity - 1);
  }

 protected:
  // List to hold all elements.
  std::vector<KeyValuePair> _list;

  // Map to point towards element in the list.
  std::unordered_map<Key, size_t> _map;

  // Random number generation to determine which item to evict.
  std::random_device _rd;
  std::mt19937 _gen;
  std::uniform_int_distribution<> _rand;

  void _evict() {
    _map.erase(_list[0].first);
    _list.erase(_list.cbegin());
  }
};

}  // namespace opossum
<commit_msg>Add fix for random_cache evict (#925)<commit_after>#pragma once

#include <list>
#include <random>
#include <unordered_map>
#include <utility>
#include <vector>

#include "abstract_cache.hpp"

namespace opossum {

// Generic cache implementation using a random eviction policy.
// Note: This implementation is not thread-safe.
template <typename Key, typename Value>
class RandomCache : public AbstractCache<Key, Value> {
 public:
  typedef typename std::pair<Key, Value> KeyValuePair;

  explicit RandomCache(size_t capacity) : AbstractCache<Key, Value>(capacity), _gen(_rd()), _rand(0, capacity - 1) {
    _list.reserve(capacity);
  }

  // Sets the value to be cached at the given key.
  void set(const Key& key, const Value& value, double cost = 1.0, double size = 1.0) {
    // Override old element at that key, if it exists.
    auto it = _map.find(key);
    if (it != _map.end()) {
      _list[it->second].second = value;
      return;
    }

    // If capacity is exceeded, pick a random element and replace it.
    if (_list.size() >= this->_capacity) {
      size_t index = _rand(_gen);
      _map.erase(_list[index].first);

      _list[index] = KeyValuePair(key, value);
      _map[key] = index;
      return;
    }

    // Otherwise simply add to the end of the vector.
    _list.push_back(KeyValuePair(key, value));
    _map[key] = _list.size() - 1;
  }

  // Retrieves the value cached at the key.
  Value& get(const Key& key) {
    auto it = _map.find(key);
    return _list[it->second].second;
  }

  bool has(const Key& key) const { return _map.find(key) != _map.end(); }

  size_t size() const { return _map.size(); }

  void clear() {
    _list.clear();
    _map.clear();
  }

  void resize(size_t capacity) {
    while (_list.size() > capacity) {
      _evict();
    }

    this->_capacity = capacity;
    _rand = std::uniform_int_distribution<>(0, capacity - 1);
  }

 protected:
  // List to hold all elements.
  std::vector<KeyValuePair> _list;

  // Map to point towards element in the list.
  std::unordered_map<Key, size_t> _map;

  // Random number generation to determine which item to evict.
  std::random_device _rd;
  std::mt19937 _gen;
  std::uniform_int_distribution<> _rand;

  void _evict() {
    _map.erase(_list[0].first);
    _list.erase(_list.cbegin());

    for (auto it = _map.cbegin(); it != _map.cend();) {
      _map[it->first] = it->second - 1;
      ++it;
    }
  }
};

}  // namespace opossum
<|endoftext|>


<commit_before>#include <bitstring.h>
#include <command.h>
#include <ict.h>

using std::cerr;

void out_bits() {
}

template <typename Op>
void time_op(int n, Op op) {
    ict::timer time;
    time.start();
    for (int i = 0; i < n; ++i) op();
    time.stop();
    cerr << time << '\n';
};

template <typename Op, typename EndOp>
void time_op(int n, Op op, EndOp end_op) {
    ict::timer time;
    time.start();
    for (int i = 0; i < n; ++i) op();
    end_op();
    time.stop();
    cerr << time << '\n';
};

void in_bits(int s, int n) {
    // create a giant bitstring
    auto bits = ict::random_bitstring(1024);

    time_op(n, [&]() {
        ict::ibitstream ibs(bits);
        while (!ibs.eobits()) {
            auto bits = ibs.read(s);
        }
    });
}

void out_bits(int s, int n) {
    // create a giant bitstring
    auto bits = ict::random_bitstring(s);

    ict::obitstream obs;
    time_op(n,
    [&]() {
        obs << bits;
    },
    [&]() {
        auto x = obs.bits();
    }
    );
}

int main(int argc, char **argv) {
    bool input = false;
    bool output = false;
    try {
        ict::command line("ictperf", "ict performance tests", "ictperf [options]");
        line.add(ict::option("ibits", 'i', "input bitstream", [&]{ input = true; }));
        line.add(ict::option("obits", 'o', "output bitstream", [&]{ output = true; }));

        line.parse(argc, argv);
        if (input) {
            in_bits(3, 100000);
            in_bits(5, 100000);
            in_bits(8, 100000);
            in_bits(11, 100000);
        };

        if (output) {
            out_bits(3, 10000000);
            out_bits(5, 10000000);
            out_bits(8, 10000000);
            out_bits(11, 10000000);
        }
    } catch (std::exception & e) {
    }

}
<commit_msg>cleaned up perf test<commit_after>#include <bitstring.h>
#include <command.h>
#include <ict.h>

using std::cerr;

void out_bits() {}

template <typename Op> void time_op(int n, Op op) {
    ict::timer time;
    time.start();
    for (int i = 0; i < n; ++i)
        op();
    time.stop();
    cerr << time << '\n';
}

template <typename Op, typename EndOp>
void time_op(int n, Op op, EndOp end_op) {
    ict::timer time;
    time.start();
    for (int i = 0; i < n; ++i)
        op();
    end_op();
    time.stop();
    cerr << time << '\n';
}

void in_bits(int s, int n) {
    // create a giant bitstring
    auto bits = ict::random_bitstring(1024);

    time_op(n, [&]() {
        ict::ibitstream ibs(bits);
        while (!ibs.eobits()) {
            auto bits = ibs.read(s);
        }
    });
}

void out_bits(int s, int n) {
    // create a giant bitstring
    auto bits = ict::random_bitstring(s);

    ict::obitstream obs;
    time_op(n, [&]() { obs << bits; }, [&]() { auto x = obs.bits(); });
}

int main(int argc, char **argv) {
    bool input = false;
    bool output = false;
    try {
        ict::command line("ictperf", "ict performance tests",
                          "ictperf [options]");
        line.add(ict::option("ibits", 'i', "input bitstream",
                             [&] { input = true; }));
        line.add(ict::option("obits", 'o', "output bitstream",
                             [&] { output = true; }));

        line.parse(argc, argv);
        if (input) {
            in_bits(3, 100000);
            in_bits(5, 100000);
            in_bits(8, 100000);
            in_bits(11, 100000);
        };

        if (output) {
            out_bits(3, 10000000);
            out_bits(5, 10000000);
            out_bits(8, 10000000);
            out_bits(11, 10000000);
        }
    } catch (std::exception &e) {
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: generalpage.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2005-06-30 16:33:40 $
 *
 *  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 EXPRESS 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 _DBAUI_GENERALPAGE_HXX_
#define _DBAUI_GENERALPAGE_HXX_

#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBACCESS_SOURCE_UI_INC_OPENDOCCONTROLS_HXX
#include "opendoccontrols.hxx"
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#include <memory>

//.........................................................................
namespace dbaui
{
//.........................................................................
    class IAdminHelper;
    class RadioDependentEnabler;
    //=========================================================================
    //= OGeneralPage
    //=========================================================================
    class OGeneralPage : public OGenericAdministrationPage
    {
        OGeneralPage(Window* pParent, const SfxItemSet& _rItems, sal_Bool _bDBWizardMode = sal_False);
        ~OGeneralPage();

    public:
        enum CreationMode
        {
            eCreateNew,
            eConnectExternal,
            eOpenExisting
        };

        struct DocumentDescriptor
        {
            String  sURL;
            String  sFilter;
        };

    private:
        // dialog controls
        FixedText           m_aFTHeaderText;
        FixedText           m_aFTHelpText;
        FixedText           m_aFT_DatasourceTypeHeader;
        RadioButton         m_aRB_CreateDatabase;
        RadioButton         m_aRB_OpenDocument;
        RadioButton         m_aRB_GetExistingDatabase;
        FixedText           m_aFT_DocListLabel;
        ::std::auto_ptr< OpenDocumentListBox >
                            m_pLB_DocumentList;
        OpenDocumentButton  m_aPB_OpenDocument;
        FixedText           m_aTypePreLabel;
        FixedText           m_aDatasourceTypeLabel;
        ListBox             m_aDatasourceType;
        FixedText           m_aFTDataSourceAppendix;
        FixedText           m_aTypePostLabel;
        FixedText           m_aSpecialMessage;
        sal_Bool            m_DBWizardMode;
        String              m_sMySQLEntry;
        CreationMode        m_eOriginalCreationMode;
        DocumentDescriptor  m_aBrowsedDocument;

        ::std::auto_ptr< RadioDependentEnabler >
                            m_pSelectTypeController;
        ::std::auto_ptr< RadioDependentEnabler >
                            m_pOpenDocController;

        ODsnTypeCollection* m_pCollection;  /// the DSN type collection instance
        DECLARE_STL_MAP(DATASOURCE_TYPE, String, ::std::less< DATASOURCE_TYPE >, SelectionHistory);
        DATASOURCE_TYPE     m_eCurrentSelection;    /// currently selected type
        DATASOURCE_TYPE     m_eNotSupportedKnownType;   /// if a data source of an unsupported, but known type is encountered ....
        SelectionHistory    m_aSelectionHistory;    /// last selected ConnectURLs for all types

        enum SPECIAL_MESSAGE
        {
            smNone,
            smUnsupportedType
        };
        SPECIAL_MESSAGE     m_eLastMessage;

        Link                m_aTypeSelectHandler;   /// to be called if a new type is selected
        Link                m_aCreationModeHandler; /// to be called if a new type is selected
        Link                m_aDocumentSelectionHandler;    /// to be called when a document in the RecentDoc list is selected
        Link                m_aChooseDocumentHandler;       /// to be called when a recent document has been definately chosen
        sal_Bool            m_bDisplayingInvalid : 1;   // the currently displayed data source is deleted
        sal_Bool            m_bUserGrabFocus : 1;
        String              VerifyDisplayName(DATASOURCE_TYPE eType, String _sDisplayName);
        void                insertDatasourceTypeEntryData(DATASOURCE_TYPE eType, String sDisplayName);

    public:
        static SfxTabPage*  Create(Window* pParent, const SfxItemSet& _rAttrSet, sal_Bool _bDBWizardMode = sal_False);

        /// set a handler which gets called every time the user selects a new type
        void            SetTypeSelectHandler(const Link& _rHandler) { m_aTypeSelectHandler = _rHandler; }
        void            SetCreationModeHandler(const Link& _rHandler) { m_aCreationModeHandler = _rHandler; }
        void            SetDocumentSelectionHandler( const Link& _rHandler) { m_aDocumentSelectionHandler = _rHandler; }
        void            SetChooseDocumentHandler( const Link& _rHandler) { m_aChooseDocumentHandler = _rHandler; }
        CreationMode    GetDatabaseCreationMode() const;

        DocumentDescriptor  GetSelectedDocument() const;

        /// get the currently selected datasource type
        DATASOURCE_TYPE GetSelectedType() const { return m_eCurrentSelection; }

    protected:
        // SfxTabPage overridables
        virtual BOOL FillItemSet(SfxItemSet& _rCoreAttrs);
        virtual void Reset(const SfxItemSet& _rCoreAttrs);

        virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);

        virtual void GetFocus();

        // <method>OGenericAdministrationPage::fillControls</method>
        virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList);
        // <method>OGenericAdministrationPage::fillWindows</method>
        virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList);

    protected:

        void onTypeSelected(const DATASOURCE_TYPE _eType);
        void initializeHistory();
        void initializeTypeList();

        void implSetCurrentType( const DATASOURCE_TYPE _eType );

        void switchMessage(sal_Bool _bDeleted,const DATASOURCE_TYPE _eType);

        /// sets the the title of the parent dialog
        void setParentTitle(DATASOURCE_TYPE _eSelectedType);

        DECL_LINK(OnDatasourceTypeSelected, ListBox*);
        DECL_LINK(OnSetupModeSelected, RadioButton*);
        DECL_LINK(OnDocumentSelected, ListBox*);
        DECL_LINK(OnOpenDocument, PushButton*);
    };

//.........................................................................
}   // namespace dbaui
//.........................................................................
#endif // _DBAUI_GENERALPAGE_HXX_
<commit_msg>INTEGRATION: CWS dba20blocker (1.13.134); FILE MERGED 2005/07/04 08:25:59 fs 1.13.134.2: RESYNC: (1.13-1.14); FILE MERGED 2005/06/23 15:22:37 fs 1.13.134.1: copying fix for #i45899# into this CWS<commit_after>/*************************************************************************
 *
 *  $RCSfile: generalpage.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: obo $ $Date: 2005-07-08 10:39:24 $
 *
 *  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 EXPRESS 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 _DBAUI_GENERALPAGE_HXX_
#define _DBAUI_GENERALPAGE_HXX_

#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBACCESS_SOURCE_UI_INC_OPENDOCCONTROLS_HXX
#include "opendoccontrols.hxx"
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#include <memory>

//.........................................................................
namespace dbaui
{
//.........................................................................
    class IAdminHelper;
    class RadioDependentEnabler;
    //=========================================================================
    //= OGeneralPage
    //=========================================================================
    class OGeneralPage : public OGenericAdministrationPage
    {
        OGeneralPage(Window* pParent, const SfxItemSet& _rItems, sal_Bool _bDBWizardMode = sal_False);
        ~OGeneralPage();

    public:
        enum CreationMode
        {
            eCreateNew,
            eConnectExternal,
            eOpenExisting
        };

        struct DocumentDescriptor
        {
            String  sURL;
            String  sFilter;
        };

    private:
        // dialog controls
        FixedText           m_aFTHeaderText;
        FixedText           m_aFTHelpText;
        FixedText           m_aFT_DatasourceTypeHeader;
        RadioButton         m_aRB_CreateDatabase;
        RadioButton         m_aRB_OpenDocument;
        RadioButton         m_aRB_GetExistingDatabase;
        FixedText           m_aFT_DocListLabel;
        ::std::auto_ptr< OpenDocumentListBox >
                            m_pLB_DocumentList;
        OpenDocumentButton  m_aPB_OpenDocument;
        FixedText           m_aTypePreLabel;
        FixedText           m_aDatasourceTypeLabel;
        ::std::auto_ptr< ListBox >
                            m_pDatasourceType;
        FixedText           m_aFTDataSourceAppendix;
        FixedText           m_aTypePostLabel;
        FixedText           m_aSpecialMessage;
        sal_Bool            m_DBWizardMode;
        String              m_sMySQLEntry;
        CreationMode        m_eOriginalCreationMode;
        DocumentDescriptor  m_aBrowsedDocument;

        ::std::auto_ptr< RadioDependentEnabler >
                            m_pSelectTypeController;
        ::std::auto_ptr< RadioDependentEnabler >
                            m_pOpenDocController;

        ODsnTypeCollection* m_pCollection;  /// the DSN type collection instance
        DECLARE_STL_MAP(DATASOURCE_TYPE, String, ::std::less< DATASOURCE_TYPE >, SelectionHistory);
        DATASOURCE_TYPE     m_eCurrentSelection;    /// currently selected type
        DATASOURCE_TYPE     m_eNotSupportedKnownType;   /// if a data source of an unsupported, but known type is encountered ....
        SelectionHistory    m_aSelectionHistory;    /// last selected ConnectURLs for all types

        enum SPECIAL_MESSAGE
        {
            smNone,
            smUnsupportedType
        };
        SPECIAL_MESSAGE     m_eLastMessage;

        Link                m_aTypeSelectHandler;   /// to be called if a new type is selected
        Link                m_aCreationModeHandler; /// to be called if a new type is selected
        Link                m_aDocumentSelectionHandler;    /// to be called when a document in the RecentDoc list is selected
        Link                m_aChooseDocumentHandler;       /// to be called when a recent document has been definately chosen
        sal_Bool            m_bDisplayingInvalid : 1;   // the currently displayed data source is deleted
        sal_Bool            m_bUserGrabFocus : 1;
        String              VerifyDisplayName(DATASOURCE_TYPE eType, String _sDisplayName);
        void                insertDatasourceTypeEntryData(DATASOURCE_TYPE eType, String sDisplayName);

    public:
        static SfxTabPage*  Create(Window* pParent, const SfxItemSet& _rAttrSet, sal_Bool _bDBWizardMode = sal_False);

        /// set a handler which gets called every time the user selects a new type
        void            SetTypeSelectHandler(const Link& _rHandler) { m_aTypeSelectHandler = _rHandler; }
        void            SetCreationModeHandler(const Link& _rHandler) { m_aCreationModeHandler = _rHandler; }
        void            SetDocumentSelectionHandler( const Link& _rHandler) { m_aDocumentSelectionHandler = _rHandler; }
        void            SetChooseDocumentHandler( const Link& _rHandler) { m_aChooseDocumentHandler = _rHandler; }
        CreationMode    GetDatabaseCreationMode() const;

        DocumentDescriptor  GetSelectedDocument() const;

        /// get the currently selected datasource type
        DATASOURCE_TYPE GetSelectedType() const { return m_eCurrentSelection; }

    protected:
        // SfxTabPage overridables
        virtual BOOL FillItemSet(SfxItemSet& _rCoreAttrs);
        virtual void Reset(const SfxItemSet& _rCoreAttrs);

        virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);

        virtual void GetFocus();

        // <method>OGenericAdministrationPage::fillControls</method>
        virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList);
        // <method>OGenericAdministrationPage::fillWindows</method>
        virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList);

    protected:

        void onTypeSelected(const DATASOURCE_TYPE _eType);
        void initializeHistory();
        void initializeTypeList();

        void implSetCurrentType( const DATASOURCE_TYPE _eType );

        void switchMessage(sal_Bool _bDeleted,const DATASOURCE_TYPE _eType);

        /// sets the the title of the parent dialog
        void setParentTitle(DATASOURCE_TYPE _eSelectedType);

        DECL_LINK(OnDatasourceTypeSelected, ListBox*);
        DECL_LINK(OnSetupModeSelected, RadioButton*);
        DECL_LINK(OnDocumentSelected, ListBox*);
        DECL_LINK(OnOpenDocument, PushButton*);
    };

//.........................................................................
}   // namespace dbaui
//.........................................................................
#endif // _DBAUI_GENERALPAGE_HXX_
<|endoftext|>


<commit_before>
#pragma once

#include <functional>

#include "geometry/hilbert.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"

namespace principia {
namespace numerics {
namespace internal_gradient_descent {

using geometry::Hilbert;
using quantities::Difference;
using quantities::Length;
using quantities::Product;
using quantities::Quotient;

// In this file |Argument| must be a 3-dimensional entity.

template<typename Scalar, typename Argument>
using Field = std::function<Scalar(Argument const&)>;

template<typename Scalar, typename Argument>
using Gradient =
    Product<Scalar,
            Quotient<Difference<Argument>,
                     typename Hilbert<Difference<Argument>>::NormType>>;

template<typename Scalar, typename Argument>
Argument BroydenFletcherGoldfarbShanno(
    Argument const& start_argument,
    Field<Scalar, Argument> const& f,
    Field<Gradient<Scalar, Argument>, Argument> const& grad_f,
    Length const& tolerance);

}  // namespace internal_gradient_descent

using internal_gradient_descent::BroydenFletcherGoldfarbShanno;

}  // namespace numerics
}  // namespace principia

#include "numerics/gradient_descent_body.hpp"
<commit_msg>Comment.<commit_after>
#pragma once

#include <functional>

#include "geometry/hilbert.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"

namespace principia {
namespace numerics {
namespace internal_gradient_descent {

using geometry::Hilbert;
using quantities::Difference;
using quantities::Length;
using quantities::Product;
using quantities::Quotient;

// In this file |Argument| must be such that its difference belongs to a Hilbert
// space.

template<typename Scalar, typename Argument>
using Field = std::function<Scalar(Argument const&)>;

template<typename Scalar, typename Argument>
using Gradient =
    Product<Scalar,
            Quotient<Difference<Argument>,
                     typename Hilbert<Difference<Argument>>::NormType>>;

template<typename Scalar, typename Argument>
Argument BroydenFletcherGoldfarbShanno(
    Argument const& start_argument,
    Field<Scalar, Argument> const& f,
    Field<Gradient<Scalar, Argument>, Argument> const& grad_f,
    Length const& tolerance);

}  // namespace internal_gradient_descent

using internal_gradient_descent::BroydenFletcherGoldfarbShanno;

}  // namespace numerics
}  // namespace principia

#include "numerics/gradient_descent_body.hpp"
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

#ifndef REALM_PROPERTY_HPP
#define REALM_PROPERTY_HPP

#include <string>

namespace realm {
    enum PropertyType {
        /** Integer type: NSInteger, int, long, Int (Swift) */
        PropertyTypeInt    = 0,
        /** Boolean type: BOOL, bool, Bool (Swift) */
        PropertyTypeBool   = 1,
        /** Float type: CGFloat (32bit), float, Float (Swift) */
        PropertyTypeFloat  = 9,
        /** Double type: CGFloat (64bit), double, Double (Swift) */
        PropertyTypeDouble = 10,
        /** String type: NSString, String (Swift) */
        PropertyTypeString = 2,
        /** Data type: NSData */
        PropertyTypeData   = 4,
        /** Any type: id, **not supported in Swift** */
        PropertyTypeAny    = 6,
        /** Date type: NSDate */
        PropertyTypeDate   = 7,
        /** Object type. See [Realm Models](http://realm.io/docs/cocoa/latest/#models) */
        PropertyTypeObject = 12,
        /** Array type. See [Realm Models](http://realm.io/docs/cocoa/latest/#models) */
        PropertyTypeArray  = 13,
    };

    struct Property {
    public:
        Property() : object_type(""), is_primary(false), is_indexed(false), is_nullable(false) {}

        std::string name;
        PropertyType type;
        std::string object_type;
        bool is_primary;
        bool is_indexed;
        bool is_nullable;

        size_t table_column;
        bool requires_index() { return is_primary || is_indexed; }
    };

    static inline const char *string_for_property_type(PropertyType type) {
        switch (type) {
            case PropertyTypeString:
                return "string";
            case PropertyTypeInt:
                return "int";
            case PropertyTypeBool:
                return "bool";
            case PropertyTypeDate:
                return "date";
            case PropertyTypeData:
                return "data";
            case PropertyTypeDouble:
                return "double";
            case PropertyTypeFloat:
                return "float";
            case PropertyTypeAny:
                return "any";
            case PropertyTypeObject:
                return "object";
            case PropertyTypeArray:
                return "array";
        }
    }
}

#endif /* REALM_PROPERTY_HPP */
<commit_msg>Use NSDMIs for realm::Property<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

#ifndef REALM_PROPERTY_HPP
#define REALM_PROPERTY_HPP

#include <string>

namespace realm {
    enum PropertyType {
        /** Integer type: NSInteger, int, long, Int (Swift) */
        PropertyTypeInt    = 0,
        /** Boolean type: BOOL, bool, Bool (Swift) */
        PropertyTypeBool   = 1,
        /** Float type: CGFloat (32bit), float, Float (Swift) */
        PropertyTypeFloat  = 9,
        /** Double type: CGFloat (64bit), double, Double (Swift) */
        PropertyTypeDouble = 10,
        /** String type: NSString, String (Swift) */
        PropertyTypeString = 2,
        /** Data type: NSData */
        PropertyTypeData   = 4,
        /** Any type: id, **not supported in Swift** */
        PropertyTypeAny    = 6,
        /** Date type: NSDate */
        PropertyTypeDate   = 7,
        /** Object type. See [Realm Models](http://realm.io/docs/cocoa/latest/#models) */
        PropertyTypeObject = 12,
        /** Array type. See [Realm Models](http://realm.io/docs/cocoa/latest/#models) */
        PropertyTypeArray  = 13,
    };

    struct Property {
        std::string name;
        PropertyType type;
        std::string object_type;
        bool is_primary = false;
        bool is_indexed = false;
        bool is_nullable = false;

        size_t table_column;
        bool requires_index() { return is_primary || is_indexed; }
    };

    static inline const char *string_for_property_type(PropertyType type) {
        switch (type) {
            case PropertyTypeString:
                return "string";
            case PropertyTypeInt:
                return "int";
            case PropertyTypeBool:
                return "bool";
            case PropertyTypeDate:
                return "date";
            case PropertyTypeData:
                return "data";
            case PropertyTypeDouble:
                return "double";
            case PropertyTypeFloat:
                return "float";
            case PropertyTypeAny:
                return "any";
            case PropertyTypeObject:
                return "object";
            case PropertyTypeArray:
                return "array";
        }
    }
}

#endif /* REALM_PROPERTY_HPP */
<|endoftext|>