<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: seqstream.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:01:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _COMPHELPER_SEQSTREAM_HXX
#include <comphelper/seqstream.hxx>
#endif

#include <memory.h> // for memcpy

namespace comphelper
{
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;
using namespace ::osl;

//---------------------------------------------------------------------------------------------
// class SequenceInputStream
//---------------------------------------------------------------------------------------------

//------------------------------------------------------------------
SequenceInputStream::SequenceInputStream(const ByteSequence& rData)
:   m_aData(rData)
,   m_nPos(0)
{
}

// checks if closed, returns available size, not mutex-protected
//------------------------------------------------------------------
inline sal_Int32 SequenceInputStream::avail()
{
    if (m_nPos == -1)
        throw NotConnectedException(::rtl::OUString(), *this);

    return m_aData.getLength() - m_nPos;
}

// com::sun::star::io::XInputStream
//------------------------------------------------------------------
sal_Int32 SAL_CALL SequenceInputStream::readBytes( Sequence<sal_Int8>& aData, sal_Int32 nBytesToRead )
    throw(NotConnectedException, BufferSizeExceededException,
          IOException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    sal_Int32 nAvail = avail();

    if (nBytesToRead < 0)
        throw BufferSizeExceededException(::rtl::OUString(),*this);

    if (nAvail < nBytesToRead)
        nBytesToRead = nAvail;

    aData.realloc(nBytesToRead);
    memcpy(aData.getArray(), m_aData.getConstArray() + m_nPos, nBytesToRead);
    m_nPos += nBytesToRead;

    return nBytesToRead;
}

//------------------------------------------------------------------
sal_Int32 SAL_CALL SequenceInputStream::readSomeBytes( Sequence<sal_Int8>& aData, sal_Int32 nMaxBytesToRead )
    throw(NotConnectedException, BufferSizeExceededException,
          IOException, RuntimeException)
{
    // all data is available at once
    return readBytes(aData, nMaxBytesToRead);
}

//------------------------------------------------------------------
void SAL_CALL SequenceInputStream::skipBytes( sal_Int32 nBytesToSkip )
    throw(NotConnectedException, BufferSizeExceededException,
          IOException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    sal_Int32 nAvail = avail();

    if (nBytesToSkip < 0)
        throw BufferSizeExceededException(::rtl::OUString(),*this);

    if (nAvail < nBytesToSkip)
        nBytesToSkip = nAvail;

    m_nPos += nBytesToSkip;
}

//------------------------------------------------------------------
sal_Int32 SAL_CALL SequenceInputStream::available(  )
    throw(NotConnectedException, IOException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    return avail();
}

//------------------------------------------------------------------
void SAL_CALL SequenceInputStream::closeInput(  )
    throw(NotConnectedException, IOException, RuntimeException)
{
    if (m_nPos == -1)
        throw NotConnectedException(::rtl::OUString(), *this);

    m_nPos = -1;
}

void SAL_CALL SequenceInputStream::seek( sal_Int64 location ) throw (IllegalArgumentException, IOException, RuntimeException)
{
    if ( location > m_aData.getLength()-1 || location < 0 || location > SAL_MAX_INT32 )
        throw IllegalArgumentException();
    m_nPos = (sal_Int32) location;
}

sal_Int64 SAL_CALL SequenceInputStream::getPosition() throw (IOException, RuntimeException)
{
    return m_nPos;
}

sal_Int64 SAL_CALL SequenceInputStream::getLength(  ) throw (IOException, RuntimeException)
{
    return m_aData.getLength();
}

//--------------------------------------------------------------------------
OSequenceOutputStream::OSequenceOutputStream(Sequence< sal_Int8 >& _rSeq, double _nResizeFactor, sal_Int32 _nMinimumResize, sal_Int32 _nMaximumResize)
    :m_rSequence(_rSeq)
    ,m_nResizeFactor(_nResizeFactor)
    ,m_nMinimumResize(_nMinimumResize)
    ,m_nMaximumResize(_nMaximumResize)
    ,m_nSize(0) // starting at position 0
    ,m_bConnected(sal_True)
{
    OSL_ENSURE(m_nResizeFactor > 1, "OSequenceOutputStream::OSequenceOutputStream : invalid resize factor !");
    OSL_ENSURE((m_nMaximumResize < 0) || (m_nMaximumResize > m_nMinimumResize),
        "OSequenceOutputStream::OSequenceOutputStream : these limits don't make any sense !");

    if (m_nResizeFactor <= 1)
        m_nResizeFactor = 1.3;
    if ((m_nMaximumResize >= 0) && (m_nMaximumResize <= m_nMinimumResize))
        m_nMaximumResize = m_nMinimumResize * 2;
        // this heuristic is as good as any other ... supply better parameters if you don't like it :)
}

//--------------------------------------------------------------------------
void SAL_CALL OSequenceOutputStream::writeBytes( const Sequence< sal_Int8 >& _rData ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!m_bConnected)
        throw NotConnectedException();

    // ensure the sequence has enoungh space left
    if (m_nSize + _rData.getLength() > m_rSequence.getLength())
    {
        sal_Int32 nCurrentLength = m_rSequence.getLength();
        sal_Int32 nNewLength = nCurrentLength * m_nResizeFactor;

        if (m_nMinimumResize > nNewLength - nCurrentLength)
            // we have a minimum so it's not too inefficient for small sequences and small write requests
            nNewLength = nCurrentLength + m_nMinimumResize;

        if ((m_nMaximumResize > 0) && (nNewLength - nCurrentLength > m_nMaximumResize))
            // such a large step is not allowed
            nNewLength = nCurrentLength + m_nMaximumResize;

        if (nNewLength < m_nSize + _rData.getLength())
        {   // it's not enough .... the data would not fit

            // let's take the double amount of the length of the data to be written, as the next write
            // request could be as large as this one
            sal_Int32 nNewGrowth = _rData.getLength() * 2;
            if ((m_nMaximumResize > 0) && (nNewGrowth > m_nMaximumResize))
            {   // we came to the limit, again ...
                nNewGrowth = m_nMaximumResize;
                if (nNewGrowth + nCurrentLength < m_nSize + _rData.getLength())
                    // but it would not fit if we respect the limit
                    nNewGrowth = m_nSize + _rData.getLength() - nCurrentLength;
            }
            nNewLength = nCurrentLength + nNewGrowth;
        }

        // round it off to the next multiple of 4 ...
        nNewLength = (nNewLength + 3) / 4 * 4;

        m_rSequence.realloc(nNewLength);
    }

    OSL_ENSURE(m_rSequence.getLength() >= m_nSize + _rData.getLength(),
        "ooops ... the realloc algorithm seems to be wrong :( !");

    memcpy(m_rSequence.getArray() + m_nSize, _rData.getConstArray(), _rData.getLength());
    m_nSize += _rData.getLength();
}

//--------------------------------------------------------------------------
void SAL_CALL OSequenceOutputStream::flush(  ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!m_bConnected)
        throw NotConnectedException();

    // nothing to do here
}

//--------------------------------------------------------------------------
void SAL_CALL OSequenceOutputStream::closeOutput(  ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!m_bConnected)
        throw NotConnectedException();

    // cut the sequence to the real size
    m_rSequence.realloc(m_nSize);
    // and don't allow any further accesses
    m_bConnected = sal_False;
}

} // namespace comphelper
<commit_msg>INTEGRATION: CWS optstor2 (1.6.26); FILE MERGED 2005/12/12 11:42:11 mav 1.6.26.1: #i59227# it must be possible to seek to the end of the stream<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: seqstream.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-01-20 10:00:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _COMPHELPER_SEQSTREAM_HXX
#include <comphelper/seqstream.hxx>
#endif

#include <memory.h> // for memcpy

namespace comphelper
{
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;
using namespace ::osl;

//---------------------------------------------------------------------------------------------
// class SequenceInputStream
//---------------------------------------------------------------------------------------------

//------------------------------------------------------------------
SequenceInputStream::SequenceInputStream(const ByteSequence& rData)
:   m_aData(rData)
,   m_nPos(0)
{
}

// checks if closed, returns available size, not mutex-protected
//------------------------------------------------------------------
inline sal_Int32 SequenceInputStream::avail()
{
    if (m_nPos == -1)
        throw NotConnectedException(::rtl::OUString(), *this);

    return m_aData.getLength() - m_nPos;
}

// com::sun::star::io::XInputStream
//------------------------------------------------------------------
sal_Int32 SAL_CALL SequenceInputStream::readBytes( Sequence<sal_Int8>& aData, sal_Int32 nBytesToRead )
    throw(NotConnectedException, BufferSizeExceededException,
          IOException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    sal_Int32 nAvail = avail();

    if (nBytesToRead < 0)
        throw BufferSizeExceededException(::rtl::OUString(),*this);

    if (nAvail < nBytesToRead)
        nBytesToRead = nAvail;

    aData.realloc(nBytesToRead);
    memcpy(aData.getArray(), m_aData.getConstArray() + m_nPos, nBytesToRead);
    m_nPos += nBytesToRead;

    return nBytesToRead;
}

//------------------------------------------------------------------
sal_Int32 SAL_CALL SequenceInputStream::readSomeBytes( Sequence<sal_Int8>& aData, sal_Int32 nMaxBytesToRead )
    throw(NotConnectedException, BufferSizeExceededException,
          IOException, RuntimeException)
{
    // all data is available at once
    return readBytes(aData, nMaxBytesToRead);
}

//------------------------------------------------------------------
void SAL_CALL SequenceInputStream::skipBytes( sal_Int32 nBytesToSkip )
    throw(NotConnectedException, BufferSizeExceededException,
          IOException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    sal_Int32 nAvail = avail();

    if (nBytesToSkip < 0)
        throw BufferSizeExceededException(::rtl::OUString(),*this);

    if (nAvail < nBytesToSkip)
        nBytesToSkip = nAvail;

    m_nPos += nBytesToSkip;
}

//------------------------------------------------------------------
sal_Int32 SAL_CALL SequenceInputStream::available(  )
    throw(NotConnectedException, IOException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    return avail();
}

//------------------------------------------------------------------
void SAL_CALL SequenceInputStream::closeInput(  )
    throw(NotConnectedException, IOException, RuntimeException)
{
    if (m_nPos == -1)
        throw NotConnectedException(::rtl::OUString(), *this);

    m_nPos = -1;
}

void SAL_CALL SequenceInputStream::seek( sal_Int64 location ) throw (IllegalArgumentException, IOException, RuntimeException)
{
    if ( location > m_aData.getLength() || location < 0 || location > SAL_MAX_INT32 )
        throw IllegalArgumentException();
    m_nPos = (sal_Int32) location;
}

sal_Int64 SAL_CALL SequenceInputStream::getPosition() throw (IOException, RuntimeException)
{
    return m_nPos;
}

sal_Int64 SAL_CALL SequenceInputStream::getLength(  ) throw (IOException, RuntimeException)
{
    return m_aData.getLength();
}

//--------------------------------------------------------------------------
OSequenceOutputStream::OSequenceOutputStream(Sequence< sal_Int8 >& _rSeq, double _nResizeFactor, sal_Int32 _nMinimumResize, sal_Int32 _nMaximumResize)
    :m_rSequence(_rSeq)
    ,m_nResizeFactor(_nResizeFactor)
    ,m_nMinimumResize(_nMinimumResize)
    ,m_nMaximumResize(_nMaximumResize)
    ,m_nSize(0) // starting at position 0
    ,m_bConnected(sal_True)
{
    OSL_ENSURE(m_nResizeFactor > 1, "OSequenceOutputStream::OSequenceOutputStream : invalid resize factor !");
    OSL_ENSURE((m_nMaximumResize < 0) || (m_nMaximumResize > m_nMinimumResize),
        "OSequenceOutputStream::OSequenceOutputStream : these limits don't make any sense !");

    if (m_nResizeFactor <= 1)
        m_nResizeFactor = 1.3;
    if ((m_nMaximumResize >= 0) && (m_nMaximumResize <= m_nMinimumResize))
        m_nMaximumResize = m_nMinimumResize * 2;
        // this heuristic is as good as any other ... supply better parameters if you don't like it :)
}

//--------------------------------------------------------------------------
void SAL_CALL OSequenceOutputStream::writeBytes( const Sequence< sal_Int8 >& _rData ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!m_bConnected)
        throw NotConnectedException();

    // ensure the sequence has enoungh space left
    if (m_nSize + _rData.getLength() > m_rSequence.getLength())
    {
        sal_Int32 nCurrentLength = m_rSequence.getLength();
        sal_Int32 nNewLength = nCurrentLength * m_nResizeFactor;

        if (m_nMinimumResize > nNewLength - nCurrentLength)
            // we have a minimum so it's not too inefficient for small sequences and small write requests
            nNewLength = nCurrentLength + m_nMinimumResize;

        if ((m_nMaximumResize > 0) && (nNewLength - nCurrentLength > m_nMaximumResize))
            // such a large step is not allowed
            nNewLength = nCurrentLength + m_nMaximumResize;

        if (nNewLength < m_nSize + _rData.getLength())
        {   // it's not enough .... the data would not fit

            // let's take the double amount of the length of the data to be written, as the next write
            // request could be as large as this one
            sal_Int32 nNewGrowth = _rData.getLength() * 2;
            if ((m_nMaximumResize > 0) && (nNewGrowth > m_nMaximumResize))
            {   // we came to the limit, again ...
                nNewGrowth = m_nMaximumResize;
                if (nNewGrowth + nCurrentLength < m_nSize + _rData.getLength())
                    // but it would not fit if we respect the limit
                    nNewGrowth = m_nSize + _rData.getLength() - nCurrentLength;
            }
            nNewLength = nCurrentLength + nNewGrowth;
        }

        // round it off to the next multiple of 4 ...
        nNewLength = (nNewLength + 3) / 4 * 4;

        m_rSequence.realloc(nNewLength);
    }

    OSL_ENSURE(m_rSequence.getLength() >= m_nSize + _rData.getLength(),
        "ooops ... the realloc algorithm seems to be wrong :( !");

    memcpy(m_rSequence.getArray() + m_nSize, _rData.getConstArray(), _rData.getLength());
    m_nSize += _rData.getLength();
}

//--------------------------------------------------------------------------
void SAL_CALL OSequenceOutputStream::flush(  ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!m_bConnected)
        throw NotConnectedException();

    // nothing to do here
}

//--------------------------------------------------------------------------
void SAL_CALL OSequenceOutputStream::closeOutput(  ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!m_bConnected)
        throw NotConnectedException();

    // cut the sequence to the real size
    m_rSequence.realloc(m_nSize);
    // and don't allow any further accesses
    m_bConnected = sal_False;
}

} // namespace comphelper
<|endoftext|>


<commit_before>// Author: Danilo Piparo, Omar Zapata   16/12/2015

#include <unistd.h>
#include <fcntl.h>
#include <string>
#include "TInterpreter.h"

bool JupyROOTExecutorImpl(const char *code);
bool JupyROOTDeclarerImpl(const char *code);

class JupyROOTExecutorHandler {
private:
   bool fCapturing = false;
   std::string fStdoutpipe;
   std::string fStderrpipe;
   int fStdout_pipe[2];
   int fStderr_pipe[2];
   int fSaved_stderr;
   int fSaved_stdout;
public:
   JupyROOTExecutorHandler();
   void Poll();
   void InitCapture();
   void EndCapture();
   void Clear();
   std::string &GetStdout();
   std::string &GetStderr();
};

#ifndef F_LINUX_SPECIFIC_BASE
#define F_LINUX_SPECIFIC_BASE       1024
#endif
#ifndef F_SETPIPE_SZ
#define F_SETPIPE_SZ    (F_LINUX_SPECIFIC_BASE + 7)
#endif

constexpr long MAX_PIPE_SIZE = 1048575;

JupyROOTExecutorHandler::JupyROOTExecutorHandler() {}

static void PollImpl(FILE *stdStream, int *pipeHandle, std::string &pipeContent)
{
   int buf_read;
   char ch;
   fflush(stdStream);
   while (true) {
      buf_read = read(pipeHandle[0], &ch, 1);
      if (buf_read == 1) {
         pipeContent += ch;
      } else break;
   }
}

void JupyROOTExecutorHandler::Poll()
{
   PollImpl(stdout, fStdout_pipe, fStdoutpipe);
   PollImpl(stderr, fStderr_pipe, fStderrpipe);
}

static void InitCaptureImpl(int &savedStdStream, int *pipeHandle, int FILENO)
{
   savedStdStream = dup(FILENO);
   if (pipe(pipeHandle) != 0) {
      return;
   }
   long flags_stdout = fcntl(pipeHandle[0], F_GETFL);
   flags_stdout |= O_NONBLOCK;
   fcntl(pipeHandle[0], F_SETFL, flags_stdout);
   fcntl(pipeHandle[0], F_SETPIPE_SZ, MAX_PIPE_SIZE);
   dup2(pipeHandle[1], FILENO);
   close(pipeHandle[1]);
}

void JupyROOTExecutorHandler::InitCapture()
{
   if (!fCapturing)  {
      InitCaptureImpl(fSaved_stdout, fStdout_pipe, STDOUT_FILENO);
      InitCaptureImpl(fSaved_stderr, fStderr_pipe, STDERR_FILENO);
      fCapturing = true;
   }
}

void JupyROOTExecutorHandler::EndCapture()
{
   if (fCapturing)  {
      Poll();
      dup2(fSaved_stdout, STDOUT_FILENO);
      dup2(fSaved_stderr, STDERR_FILENO);
      fCapturing = false;
   }
}

void JupyROOTExecutorHandler::Clear()
{
   fStdoutpipe = "";
   fStderrpipe = "";
}

std::string &JupyROOTExecutorHandler::GetStdout()
{
   return fStdoutpipe;
}

std::string &JupyROOTExecutorHandler::GetStderr()
{
   return fStderrpipe;
}

////////////////////////////////////////////////////////////////////////////////
bool JupyROOTExecutorImpl(const char *code)
{
   auto status = false;
   try {
      if (gInterpreter->ProcessLine(code))    {
         status = true;
      }
   } catch (...) {
      status = true;
   }
   return status;
}

bool JupyROOTDeclarerImpl(const char *code)
{
   bool status = false;
   try {
      if (gInterpreter->Declare(code)) {
         status = true;
      }
   } catch (...) {
      status = true;
   }
   return status;
}

JupyROOTExecutorHandler *JupyROOTExecutorHandler_ptr = nullptr;

extern "C" {

   int JupyROOTExecutor(const char *code)
   {
      return JupyROOTExecutorImpl(code);
   }
   int JupyROOTDeclarer(const char *code)
   {
      return JupyROOTDeclarerImpl(code);
   }

   void JupyROOTExecutorHandler_Clear()
   {
      JupyROOTExecutorHandler_ptr->Clear();
   }

   void JupyROOTExecutorHandler_Ctor()
   {
      if (!JupyROOTExecutorHandler_ptr) {
         JupyROOTExecutorHandler_ptr = new JupyROOTExecutorHandler();
      }
   }

   void JupyROOTExecutorHandler_Poll()
   {
      JupyROOTExecutorHandler_ptr->Poll();
   }

   void JupyROOTExecutorHandler_EndCapture()
   {
      JupyROOTExecutorHandler_ptr->EndCapture();
   }

   void JupyROOTExecutorHandler_InitCapture()
   {
      JupyROOTExecutorHandler_ptr->InitCapture();
   }

   const char *JupyROOTExecutorHandler_GetStdout()
   {
      auto out = JupyROOTExecutorHandler_ptr->GetStdout();
      return out.c_str();
   }

   const char *JupyROOTExecutorHandler_GetStderr()
   {
      auto out = JupyROOTExecutorHandler_ptr->GetStderr();
      return out.c_str();
   }

   void JupyROOTExecutorHandler_Dtor()
   {
      if (!JupyROOTExecutorHandler_ptr) return;
      delete JupyROOTExecutorHandler_ptr;
      JupyROOTExecutorHandler_ptr = nullptr;
   }

}
<commit_msg>Do not process a cell if curly braces are not balanced<commit_after>// Author: Danilo Piparo, Omar Zapata   16/12/2015

#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <iostream>
#include "TInterpreter.h"

bool JupyROOTExecutorImpl(const char *code);
bool JupyROOTDeclarerImpl(const char *code);

class JupyROOTExecutorHandler {
private:
   bool fCapturing = false;
   std::string fStdoutpipe;
   std::string fStderrpipe;
   int fStdout_pipe[2];
   int fStderr_pipe[2];
   int fSaved_stderr;
   int fSaved_stdout;
public:
   JupyROOTExecutorHandler();
   void Poll();
   void InitCapture();
   void EndCapture();
   void Clear();
   std::string &GetStdout();
   std::string &GetStderr();
};

#ifndef F_LINUX_SPECIFIC_BASE
#define F_LINUX_SPECIFIC_BASE       1024
#endif
#ifndef F_SETPIPE_SZ
#define F_SETPIPE_SZ    (F_LINUX_SPECIFIC_BASE + 7)
#endif

constexpr long MAX_PIPE_SIZE = 1048575;

JupyROOTExecutorHandler::JupyROOTExecutorHandler() {}

static void PollImpl(FILE *stdStream, int *pipeHandle, std::string &pipeContent)
{
   int buf_read;
   char ch;
   fflush(stdStream);
   while (true) {
      buf_read = read(pipeHandle[0], &ch, 1);
      if (buf_read == 1) {
         pipeContent += ch;
      } else break;
   }
}

void JupyROOTExecutorHandler::Poll()
{
   PollImpl(stdout, fStdout_pipe, fStdoutpipe);
   PollImpl(stderr, fStderr_pipe, fStderrpipe);
}

static void InitCaptureImpl(int &savedStdStream, int *pipeHandle, int FILENO)
{
   savedStdStream = dup(FILENO);
   if (pipe(pipeHandle) != 0) {
      return;
   }
   long flags_stdout = fcntl(pipeHandle[0], F_GETFL);
   flags_stdout |= O_NONBLOCK;
   fcntl(pipeHandle[0], F_SETFL, flags_stdout);
   fcntl(pipeHandle[0], F_SETPIPE_SZ, MAX_PIPE_SIZE);
   dup2(pipeHandle[1], FILENO);
   close(pipeHandle[1]);
}

void JupyROOTExecutorHandler::InitCapture()
{
   if (!fCapturing)  {
      InitCaptureImpl(fSaved_stdout, fStdout_pipe, STDOUT_FILENO);
      InitCaptureImpl(fSaved_stderr, fStderr_pipe, STDERR_FILENO);
      fCapturing = true;
   }
}

void JupyROOTExecutorHandler::EndCapture()
{
   if (fCapturing)  {
      Poll();
      dup2(fSaved_stdout, STDOUT_FILENO);
      dup2(fSaved_stderr, STDERR_FILENO);
      fCapturing = false;
   }
}

void JupyROOTExecutorHandler::Clear()
{
   fStdoutpipe = "";
   fStderrpipe = "";
}

std::string &JupyROOTExecutorHandler::GetStdout()
{
   return fStdoutpipe;
}

std::string &JupyROOTExecutorHandler::GetStderr()
{
   return fStderrpipe;
}

JupyROOTExecutorHandler *JupyROOTExecutorHandler_ptr = nullptr;

////////////////////////////////////////////////////////////////////////////////
bool JupyROOTExecutorImpl(const char *code)
{
   auto status = false;
   try {
      TInterpreter::EErrorCode err = TInterpreter::kNoError;
      if (gInterpreter->ProcessLine(code, &err)) {
         status = true;
      }

      if (err == TInterpreter::kProcessing) {
         gInterpreter->ProcessLine(".@");
         gInterpreter->ProcessLine("cerr << \"Unbalanced curly braces. This cell was not processed.\" << endl;");
      }
   } catch (...) {
      status = true;
   }

   return status;
}

bool JupyROOTDeclarerImpl(const char *code)
{
   bool status = false;
   try {
      if (gInterpreter->Declare(code)) {
         status = true;
      }
   } catch (...) {
      status = true;
   }
   return status;
}

extern "C" {

   int JupyROOTExecutor(const char *code)
   {
      return JupyROOTExecutorImpl(code);
   }
   int JupyROOTDeclarer(const char *code)
   {
      return JupyROOTDeclarerImpl(code);
   }

   void JupyROOTExecutorHandler_Clear()
   {
      JupyROOTExecutorHandler_ptr->Clear();
   }

   void JupyROOTExecutorHandler_Ctor()
   {
      if (!JupyROOTExecutorHandler_ptr) {
         JupyROOTExecutorHandler_ptr = new JupyROOTExecutorHandler();
      }
   }

   void JupyROOTExecutorHandler_Poll()
   {
      JupyROOTExecutorHandler_ptr->Poll();
   }

   void JupyROOTExecutorHandler_EndCapture()
   {
      JupyROOTExecutorHandler_ptr->EndCapture();
   }

   void JupyROOTExecutorHandler_InitCapture()
   {
      JupyROOTExecutorHandler_ptr->InitCapture();
   }

   const char *JupyROOTExecutorHandler_GetStdout()
   {
      auto out = JupyROOTExecutorHandler_ptr->GetStdout();
      return out.c_str();
   }

   const char *JupyROOTExecutorHandler_GetStderr()
   {
      auto out = JupyROOTExecutorHandler_ptr->GetStderr();
      return out.c_str();
   }

   void JupyROOTExecutorHandler_Dtor()
   {
      if (!JupyROOTExecutorHandler_ptr) return;
      delete JupyROOTExecutorHandler_ptr;
      JupyROOTExecutorHandler_ptr = nullptr;
   }

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

#include "stdafx.h"
#include "Settings.h"
#ifdef _WIN32
#include <Util/DllVersion.h>
#endif /* ifdef _WIN32 */
#include <Util/File.h>
#include <Util/Process.h>
#include <Util/Error.h>
#include <Util/Quote.h>

LOGGING (com.opengamma.language.connector.Settings);

#ifndef DEFAULT_PIPE_PREFIX
# ifdef _WIN32
#  define DEFAULT_PIPE_PREFIX			TEXT ("\\\\.\\pipe\\OpenGammaLanguageAPI-Client-")
# else /* ifdef _WIN32 */
#  ifndef DEFAULT_PIPE_FOLDER
#   define DEFAULT_PIPE_FOLDER			TEXT ("/var/run/OG-Language/")
#  endif /* ifndef DEFAULT_PIPE_FOLDER */
#  define DEFAULT_PIPE_PREFIX			DEFAULT_PIPE_FOLDER TEXT ("Client-")
# endif /* ifdef _WIN32 */
#endif /* ifndef DEFAULT_PIPE_PREFIX */

#define DEFAULT_CONNECT_TIMEOUT		3000	/* 3s default */
#define DEFAULT_DISPLAY_ALERTS		true
#define DEFAULT_HEARTBEAT_TIMEOUT	3000	/* 3s default */
#define DEFAULT_INPUT_PIPE_PREFIX	DEFAULT_PIPE_PREFIX	TEXT ("Input-")
#define DEFAULT_LOG_CONFIGURATION	NULL
#define DEFAULT_MAX_PIPE_ATTEMPTS	3
#define DEFAULT_OUTPUT_PIPE_PREFIX	DEFAULT_PIPE_PREFIX TEXT ("Output-")
#define DEFAULT_REQUEST_TIMEOUT		2		/* 2x send timeout */
#define DEFAULT_SEND_TIMEOUT		1500	/* 1.5s default */
#ifdef _WIN32
# define DEFAULT_SERVICE_EXECUTABLE	TEXT ("ServiceRunner.exe")
#else
# define DEFAULT_SERVICE_EXECUTABLE	TEXT ("ServiceRunner")
#endif
#define DEFAULT_SERVICE_POLL		250		/* 1/4s default */
#define DEFAULT_START_TIMEOUT		30000	/* 30s default */
#define DEFAULT_STOP_TIMEOUT		2000	/* 2s default */

/// Returns the name of the pipe for sending connection messages to the JVM host process (service).
///
/// @return the pipe name
const TCHAR *CSettings::GetConnectionPipe () const {
	return GetConnectionPipe (ServiceDefaultConnectionPipe ());
}

/// Returns the connection timeout in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetConnectTimeout () const {
	return GetConnectTimeout (DEFAULT_CONNECT_TIMEOUT);
}

/// Returns whether "alert"s are enabled. These are attached to a system tray icon in Windows.
///
/// @return TRUE if enabled, FALSE to disable
bool CSettings::IsDisplayAlerts () const {
	return IsDisplayAlerts (DEFAULT_DISPLAY_ALERTS);
}

/// Returns the heartbeat timeout in milliseconds. Each end of the connection should expect there
/// to be no more than this length of time between messages; requiring each to send messages at
/// least that often (using the no-op heartbeat message if there is no genuine traffic).
///
/// @return the timeout in milliseconds
int CSettings::GetHeartbeatTimeout () const {
	return GetHeartbeatTimeout (DEFAULT_HEARTBEAT_TIMEOUT);
}

/// Returns the prefix to use at the start of pipe names for inbound traffic. This should include
/// a path in the case of Posix and named pipes, or the \\\\.\\pipe\\ prefix in the case of Win32.
///
/// @return the pipe prefix
const TCHAR *CSettings::GetInputPipePrefix () const {
	return GetInputPipePrefix (DEFAULT_INPUT_PIPE_PREFIX);
}

/// Returns the full path to the LOG4CXX configuration file.
///
/// @return the path
const TCHAR *CSettings::GetLogConfiguration () const {
	return GetLogConfiguration (DEFAULT_LOG_CONFIGURATION);
}

/// Returns the maximum number of times to try and create the pipes. Pipe creation is retried to
/// allow different names to be generated to avoid naming conflicts with other processes.
///
/// @return the number of attempts
int CSettings::GetMaxPipeAttempts () const {
	return GetMaxPipeAttempts (DEFAULT_MAX_PIPE_ATTEMPTS);
}

/// Returns the prefix to use at the start of pipe names for outgoing traffic. This should include
/// a path in the case of Posix and named pipes, or the \\\\.\\pipe\\ prefix in the case of Win32.
///
/// @return the pipe prefix
const TCHAR *CSettings::GetOutputPipePrefix () const {
	return GetOutputPipePrefix (DEFAULT_OUTPUT_PIPE_PREFIX);
}

/// Returns the timeout for a request to the Java stack in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetRequestTimeout () const {
	return GetRequestTimeout (DEFAULT_REQUEST_TIMEOUT * GetSendTimeout ());
}

/// Returns the timeout for sending messages to the Java stack in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetSendTimeout () const {
	return GetSendTimeout (DEFAULT_SEND_TIMEOUT);
}

/// Locates a path to the ServiceRunner executable in the same folder as the executing code
/// module.
class CServiceExecutableDefault : public CAbstractSettingProvider {
protected:

	/// Locates the directory of the current module, and looks alongside it for the service executable.
	///
	/// @return the path to the executable, or a default best guess if none was found
	TCHAR *CalculateString () const {
		TCHAR *pszExecutable = NULL;
#ifdef _WIN32
		// TODO: if the service is installed, get the executable from the service settings
#endif /* ifdef _WIN32 */
		do {
			TCHAR szPath[260];
			if (!CProcess::GetCurrentModule (szPath, (sizeof (szPath) / sizeof (TCHAR)) - _tcslen (DEFAULT_SERVICE_EXECUTABLE))) {
				LOGWARN (TEXT ("Couldn't get current module filename, error ") << GetLastError ());
				break;
			}
			TCHAR *pszFolder = _tcsrchr (szPath, PATH_CHAR);
			if (pszFolder) {
				pszFolder++;
			} else {
				pszFolder = szPath;
			}
			// The memcpy is safe because we gave a short buffer length to GetCurrentModule to guarantee room
			memcpy (pszFolder, DEFAULT_SERVICE_EXECUTABLE, (_tcslen (DEFAULT_SERVICE_EXECUTABLE) + 1) * sizeof (TCHAR));
			LOGDEBUG (TEXT ("Executable ") << szPath);
#ifdef _WIN32
			HANDLE hFile = CreateFile (szPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
			if (!hFile) {
				LOGWARN (TEXT ("Couldn't open executable file ") << szPath << TEXT (", error ") << GetLastError ());
				break;
			}
			if (!GetFinalPathNameByHandle (hFile, szPath, MAX_PATH, FILE_NAME_NORMALIZED)) {
				LOGWARN (TEXT ("Couldn't get normalized executable name, error ") << GetLastError ());
				break;
			}
			if (!_tcsncmp (szPath, TEXT ("\\\\?\\UNC\\"), 8)) {
				LOGDEBUG (TEXT ("Removing \\\\?\\UNC\\ prefix"));
				memmove (szPath + 2, szPath + 8, (_tcslen (szPath + 8) + 1) * sizeof (TCHAR));
			} else if (!_tcsncmp (szPath, TEXT ("\\\\?\\"), 4)) {
				LOGDEBUG (TEXT ("Removing \\\\?\\ prefix"));
				memmove (szPath, szPath + 4, (_tcslen (szPath + 4) + 1) * sizeof (TCHAR));
			}
			CloseHandle (hFile);
#else
			int file = open (szPath, O_RDONLY);
			if (file <= 0) {
				LOGWARN (TEXT ("Couldn't open executable file ") << szPath << TEXT (", error ") << GetLastError ());
				break;
			}
			close (file);
#endif /* ifdef _WIN32 */
			pszExecutable = _tcsdup (szPath);
		} while (false);
		if (pszExecutable) {
			LOGDEBUG (TEXT ("Default service executable ") << pszExecutable);
		} else {
			pszExecutable = _tcsdup (DEFAULT_SERVICE_EXECUTABLE);
		}
		return pszExecutable;
	}

};

/// Instance of the provider to retrieve the default service executable path.
static CServiceExecutableDefault g_oServiceExecutableDefault;

/// Returns the path to the ServiceRunner executable.
///
/// @return the path
const TCHAR *CSettings::GetServiceExecutable () const {
	return GetServiceExecutable (&g_oServiceExecutableDefault);
}

/// Returns the name of the service the JVM host is installed as. The exact meaning of a service
/// is O/S dependent.
///
/// @return the service name
const TCHAR *CSettings::GetServiceName () const {
	return GetServiceName (ServiceDefaultServiceName ());
}

/// Returns the polling period in milliseconds for querying the state of a service (i.e. running
/// or stopped).
///
/// @return the period in milliseconds
int CSettings::GetServicePoll () const {
	return GetServicePoll (DEFAULT_SERVICE_POLL);
}

/// Returns the time to wait for a service or executable to startup in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetStartTimeout () const {
	return GetStartTimeout (DEFAULT_START_TIMEOUT);
}

/// Returns the time to wait for a service or executable to stop on being sent a terminate.
///
/// @return the timeout in milliseconds.
int CSettings::GetStopTimeout () const {
	return GetStopTimeout (DEFAULT_STOP_TIMEOUT);
}
<commit_msg>Fetch executable name from service configuration database.<commit_after>/*
 * Copyright (C) 2010 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

#include "stdafx.h"
#include "Settings.h"
#include <Util/Atomic.h>
#ifdef _WIN32
#include <Util/DllVersion.h>
#endif /* ifdef _WIN32 */
#include <Util/File.h>
#include <Util/Process.h>
#include <Util/Error.h>
#include <Util/Quote.h>

LOGGING (com.opengamma.language.connector.Settings);

#ifndef DEFAULT_PIPE_PREFIX
# ifdef _WIN32
#  define DEFAULT_PIPE_PREFIX			TEXT ("\\\\.\\pipe\\OpenGammaLanguageAPI-Client-")
# else /* ifdef _WIN32 */
#  ifndef DEFAULT_PIPE_FOLDER
#   define DEFAULT_PIPE_FOLDER			TEXT ("/var/run/OG-Language/")
#  endif /* ifndef DEFAULT_PIPE_FOLDER */
#  define DEFAULT_PIPE_PREFIX			DEFAULT_PIPE_FOLDER TEXT ("Client-")
# endif /* ifdef _WIN32 */
#endif /* ifndef DEFAULT_PIPE_PREFIX */

#define DEFAULT_CONNECT_TIMEOUT		3000	/* 3s default */
#define DEFAULT_DISPLAY_ALERTS		true
#define DEFAULT_HEARTBEAT_TIMEOUT	3000	/* 3s default */
#define DEFAULT_INPUT_PIPE_PREFIX	DEFAULT_PIPE_PREFIX	TEXT ("Input-")
#define DEFAULT_LOG_CONFIGURATION	NULL
#define DEFAULT_MAX_PIPE_ATTEMPTS	3
#define DEFAULT_OUTPUT_PIPE_PREFIX	DEFAULT_PIPE_PREFIX TEXT ("Output-")
#define DEFAULT_REQUEST_TIMEOUT		2		/* 2x send timeout */
#define DEFAULT_SEND_TIMEOUT		1500	/* 1.5s default */
#ifdef _WIN32
# define DEFAULT_SERVICE_EXECUTABLE	TEXT ("ServiceRunner.exe")
#else
# define DEFAULT_SERVICE_EXECUTABLE	TEXT ("ServiceRunner")
#endif
#define DEFAULT_SERVICE_POLL		250		/* 1/4s default */
#define DEFAULT_START_TIMEOUT		30000	/* 30s default */
#define DEFAULT_STOP_TIMEOUT		2000	/* 2s default */

/// Returns the name of the pipe for sending connection messages to the JVM host process (service).
///
/// @return the pipe name
const TCHAR *CSettings::GetConnectionPipe () const {
	return GetConnectionPipe (ServiceDefaultConnectionPipe ());
}

/// Returns the connection timeout in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetConnectTimeout () const {
	return GetConnectTimeout (DEFAULT_CONNECT_TIMEOUT);
}

/// Returns whether "alert"s are enabled. These are attached to a system tray icon in Windows.
///
/// @return TRUE if enabled, FALSE to disable
bool CSettings::IsDisplayAlerts () const {
	return IsDisplayAlerts (DEFAULT_DISPLAY_ALERTS);
}

/// Returns the heartbeat timeout in milliseconds. Each end of the connection should expect there
/// to be no more than this length of time between messages; requiring each to send messages at
/// least that often (using the no-op heartbeat message if there is no genuine traffic).
///
/// @return the timeout in milliseconds
int CSettings::GetHeartbeatTimeout () const {
	return GetHeartbeatTimeout (DEFAULT_HEARTBEAT_TIMEOUT);
}

/// Returns the prefix to use at the start of pipe names for inbound traffic. This should include
/// a path in the case of Posix and named pipes, or the \\\\.\\pipe\\ prefix in the case of Win32.
///
/// @return the pipe prefix
const TCHAR *CSettings::GetInputPipePrefix () const {
	return GetInputPipePrefix (DEFAULT_INPUT_PIPE_PREFIX);
}

/// Returns the full path to the LOG4CXX configuration file.
///
/// @return the path
const TCHAR *CSettings::GetLogConfiguration () const {
	return GetLogConfiguration (DEFAULT_LOG_CONFIGURATION);
}

/// Returns the maximum number of times to try and create the pipes. Pipe creation is retried to
/// allow different names to be generated to avoid naming conflicts with other processes.
///
/// @return the number of attempts
int CSettings::GetMaxPipeAttempts () const {
	return GetMaxPipeAttempts (DEFAULT_MAX_PIPE_ATTEMPTS);
}

/// Returns the prefix to use at the start of pipe names for outgoing traffic. This should include
/// a path in the case of Posix and named pipes, or the \\\\.\\pipe\\ prefix in the case of Win32.
///
/// @return the pipe prefix
const TCHAR *CSettings::GetOutputPipePrefix () const {
	return GetOutputPipePrefix (DEFAULT_OUTPUT_PIPE_PREFIX);
}

/// Returns the timeout for a request to the Java stack in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetRequestTimeout () const {
	return GetRequestTimeout (DEFAULT_REQUEST_TIMEOUT * GetSendTimeout ());
}

/// Returns the timeout for sending messages to the Java stack in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetSendTimeout () const {
	return GetSendTimeout (DEFAULT_SEND_TIMEOUT);
}

/// Locates a path to the ServiceRunner executable.
class CServiceExecutableDefault : public CAbstractSettingProvider {
private:

	/// The service name (if available).
	CAtomicPointer<TCHAR*> m_pszServiceName;

	/// Locates the executable based on the service name.
	///
	/// @param[in] pszServiceName name of the service
	/// @return the path to the executable, or NULL if none is found (or an error occurs)
	static TCHAR *FindServiceExecutable (const TCHAR *pszServiceName) {
		if (!pszServiceName) return NULL;
		TCHAR *pszExecutable = NULL;
#ifdef _WIN32
		HRESULT hr;
		HKEY hkey;
		if ((hr = RegOpenKeyEx (HKEY_LOCAL_MACHINE, TEXT ("CurrentControlSet\\service"), 0, KEY_READ, &hkey)) == ERROR_SUCCESS) {
			TCHAR szImage[MAX_PATH];
			DWORD cbImage = sizeof (szImage);
			if ((hr = RegGetValue (hkey, pszServiceName, TEXT ("ImagePath"), RRF_RT_REG_SZ, NULL, szImage, &cbImage)) == ERROR_SUCCESS) {
				if (szImage[0] == '\"') {
					int cchImage = (cbImage / sizeof (TCHAR)) - 1;
					ASSERT (cchImage >= 2);
					ASSERT (!szImage[cchImage]);
					ASSERT (szImage[cchImage - 1] == '\"');
					szImage[cchImage - 1] = 0;
					pszExecutable = _tcsdup (szImage + 1);
				} else {
					pszExecutable = _tcsdup (szImage);
				}
			}
			RegCloseKey (hkey);
		} else {
			LOGWARN (TEXT ("Couldn't open HKLM\\CurrentControlSet\\service registry key, error ") << hr);
		}
#endif /* ifdef _WIN32 */
		return pszExecutable;
	}

	/// Locates the executable based on searching the folder of the current path.
	///
	/// @return the path to the executable, or NULL if none is found (or an error occurs)
	static TCHAR *FindLocalExecutable () {
		TCHAR szPath[260];
		if (!CProcess::GetCurrentModule (szPath, (sizeof (szPath) / sizeof (TCHAR)) - _tcslen (DEFAULT_SERVICE_EXECUTABLE))) {
			LOGWARN (TEXT ("Couldn't get current module filename, error ") << GetLastError ());
			return NULL;
		}
		TCHAR *pszFolder = _tcsrchr (szPath, PATH_CHAR);
		if (pszFolder) {
			pszFolder++;
		} else {
			pszFolder = szPath;
		}
		// The memcpy is safe because we have a short buffer length to GetCurrentModule to guarantee room
		memcpy (pszFolder, DEFAULT_SERVICE_EXECUTABLE, (_tcslen (DEFAULT_SERVICE_EXECUTABLE) + 1) * sizeof (TCHAR));
		LOGDEBUG (TEXT ("Executable ") << szPath);
#ifdef _WIN32
		HANDLE hFile = CreateFile (szPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
		if (!hFile) {
			LOGWARN (TEXT ("Couldn't open executable file ") << szPath << TEXT (", error ") << GetLastError ());
			return NULL;
		}
		if (!GetFinalPathNameByHandle (hFile, szPath, MAX_PATH, FILE_NAME_NORMALIZED)) {
			LOGWARN (TEXT ("Couldn't get normalized executable name, error ") << GetLastError ());
			CloseHandle (hFile);
			return NULL;
		}
		CloseHandle (hFile);
		if (!_tcsncmp (szPath, TEXT ("\\\\?\\UNC\\"), 8)) {
			LOGDEBUG (TEXT ("Removing \\\\?\\UNC\\ prefix"));
			memmove (szPath + 2, szPath + 8, (_tcslen (szPath + 8) + 1) * sizeof (TCHAR));
		} else if (!_tcsncmp (szPath, TEXT ("\\\\?\\"), 4)) {
			LOGDEBUG (TEXT ("Removing \\\\?\\ prefix"));
			memmove (szPath, szPath + 4, (_tcslen (szPath + 4) + 1) * sizeof (TCHAR));
		}
#else /* ifdef _WIN32 */
		int file = open (szPath, O_RDONLY);
		if (file <= 0) {
			LOGWARN (TEXT ("Couldn't open executable file ") << szPath << TEXT (", error ") << GetLastError ());
			return NULL;
		}
		close (file);
#endif /* ifdef _WIN32 */
		return _tcsdup (szPath);
	}

protected:

	/// Locates the directory of the current module, and looks alongside it for the service executable.
	///
	/// @return the path to the executable, or a default best guess if none was found
	TCHAR *CalculateString () const {
		TCHAR *pszExecutable = NULL;
		do {
			if ((pszExecutable = FindServiceExecutable (m_pszServiceName.Get ())) != NULL) break;
			if ((pszExecutable = FindLocalExecutable ()) != NULL) break;
		} while (false);
		if (pszExecutable) {
			LOGDEBUG (TEXT ("Default service executable ") << pszExecutable);
		} else {
			pszExecutable = _tcsdup (DEFAULT_SERVICE_EXECUTABLE);
		}
		return pszExecutable;
	}

public:

	/// Destroys the object.
	~CServiceExecutableDefault () {
		TCHAR *psz = m_pszServiceName.GetAndSet (NULL);
		if (psz) {
			free (psz);
		}
	}

	/// Registers the service name being used
	void SetServiceName (const TCHAR *pszServiceName) {
		TCHAR *pszCopy = _tcsdup (pszServiceName);
		TCHAR *pszPrevious = m_pszServiceName.CompareAndSet (pszCopy, NULL);
		if (pszPrevious) {
			free (pszCopy);
		}
	}

};

/// Instance of the provider to retrieve the default service executable path.
static CServiceExecutableDefault g_oServiceExecutableDefault;

/// Returns the path to the ServiceRunner executable.
///
/// @return the path
const TCHAR *CSettings::GetServiceExecutable () const {
	g_oServiceExecutableDefault.SetServiceName (GetServiceName ());
	return GetServiceExecutable (&g_oServiceExecutableDefault);
}

/// Returns the name of the service the JVM host is installed as. The exact meaning of a service
/// is O/S dependent.
///
/// @return the service name
const TCHAR *CSettings::GetServiceName () const {
	return GetServiceName (ServiceDefaultServiceName ());
}

/// Returns the polling period in milliseconds for querying the state of a service (i.e. running
/// or stopped).
///
/// @return the period in milliseconds
int CSettings::GetServicePoll () const {
	return GetServicePoll (DEFAULT_SERVICE_POLL);
}

/// Returns the time to wait for a service or executable to startup in milliseconds.
///
/// @return the timeout in milliseconds
int CSettings::GetStartTimeout () const {
	return GetStartTimeout (DEFAULT_START_TIMEOUT);
}

/// Returns the time to wait for a service or executable to stop on being sent a terminate.
///
/// @return the timeout in milliseconds.
int CSettings::GetStopTimeout () const {
	return GetStopTimeout (DEFAULT_STOP_TIMEOUT);
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <cctype>
#include "util.h"
#include <cmath>
#include <cstring>
#include "hash/fastfnv64a.h"
#include "hash/MurmurHash3.h"
#include "hash/SpookyV2.h"

int
summationSeries(const int n)
{
	return static_cast<int>((std::pow(n, 2) + n) / 2);
}

std::vector<std::string>
listSubStrings(const std::string str)
{
	const size_t vectorLength = summationSeries(str.length());
	std::vector<std::string> result;
	result.reserve(vectorLength);
	for(size_t i = 0; i < str.length(); i++) {
		for(size_t j = 1; j <= str.length()-i; j++) {
			result.push_back(str.substr(i,j));
		}
	}
	return result;
}

std::bitset<BLOOM_SIZE>
generateBloom(const std::string str)
{
	std::bitset<BLOOM_SIZE> bloom;

	// I'm purposely setting the seeds to 0
	const int seed {0};

	// Transform the string to lower case
	std::string lowerStr;
	lowerStr.resize(str.length());
	std::transform(str.begin(), str.end(), lowerStr.begin(), ::tolower);

	for(auto subStr : listSubStrings(lowerStr)) {
		unsigned int murmurHash;
		MurmurHash3_x86_32(subStr.c_str(), subStr.length(), seed, &murmurHash);
		bloom.set(murmurHash % BLOOM_SIZE);

		unsigned int spookyHash = SpookyHash::Hash32(subStr.c_str(), subStr.length(), seed);
		bloom.set(spookyHash % BLOOM_SIZE);

		char* buf = (char*) calloc(subStr.length(), sizeof(char));
		std::strncpy(buf, subStr.c_str(), subStr.length());
		unsigned long long fnvHash = fnv64a(reinterpret_cast<unsigned char*>(buf), (uint64_t)subStr.length());
		bloom.set(fnvHash % BLOOM_SIZE);
	}

	return bloom;
}
<commit_msg>Made temporary variable constant.<commit_after>#include <algorithm>
#include <cctype>
#include "util.h"
#include <cmath>
#include <cstring>
#include "hash/fastfnv64a.h"
#include "hash/MurmurHash3.h"
#include "hash/SpookyV2.h"

int
summationSeries(const int n)
{
	return static_cast<int>((std::pow(n, 2) + n) / 2);
}

std::vector<std::string>
listSubStrings(const std::string str)
{
	const size_t vectorLength = summationSeries(str.length());
	std::vector<std::string> result;
	result.reserve(vectorLength);
	for(size_t i = 0; i < str.length(); i++) {
		for(size_t j = 1; j <= str.length()-i; j++) {
			result.push_back(str.substr(i,j));
		}
	}
	return result;
}

std::bitset<BLOOM_SIZE>
generateBloom(const std::string str)
{
	std::bitset<BLOOM_SIZE> bloom;

	// I'm purposely setting the seeds to 0
	const int seed {0};

	// Transform the string to lower case
	std::string lowerStr;
	lowerStr.resize(str.length());
	std::transform(str.begin(), str.end(), lowerStr.begin(), ::tolower);

	for(const auto subStr : listSubStrings(lowerStr)) {
		unsigned int murmurHash;
		MurmurHash3_x86_32(subStr.c_str(), subStr.length(), seed, &murmurHash);
		bloom.set(murmurHash % BLOOM_SIZE);

		unsigned int spookyHash = SpookyHash::Hash32(subStr.c_str(), subStr.length(), seed);
		bloom.set(spookyHash % BLOOM_SIZE);

		char* buf = (char*) calloc(subStr.length(), sizeof(char));
		std::strncpy(buf, subStr.c_str(), subStr.length());
		unsigned long long fnvHash = fnv64a(reinterpret_cast<unsigned char*>(buf), (uint64_t)subStr.length());
		bloom.set(fnvHash % BLOOM_SIZE);
	}

	return bloom;
}
<|endoftext|>


<commit_before>// Standard libraries
#include "headers.hpp"

/* Templated code (must be visible to the compiler) */

template <typename T>
std::vector<T> getRange(T a, T b, int n) {
	std::vector<T> range;
	range.reserve(n);

	double step = (b - a) / n;

	while (a < (b - step/2)) {
		range.push_back(a);
		a += step;
	}

	return range;
}

template <typename T>
void printMatrix(std::vector< std::vector<T> > matrix) {
	for (const auto& vector: matrix) {
		for (const auto& element: vector) {
			std::cout << element << '\t';
		}
		std::cout << '\n';
	}
	std::cout << std::flush; // std::endl;
}

template <typename T>
void printVector(std::vector<T> vector) {
	for (const auto& element: vector) {
		std::cout << element << '\t';
	}
	std::cout << std::endl;
}

template <typename T>
void transpose(std::vector< std::vector<T> > &input) {
	std::vector< std::vector<T> > copy = input;
	std::vector< std::vector<T> > matrix(copy[0].size(), std::vector<T>(copy.size()));
	for (typename std::vector<T>::size_type i = 0; i < matrix.size(); i++) {
		for (typename std::vector<T>::size_type j = 0; j < matrix[0].size(); j++) {
			matrix[i][j] = copy[j][i];
		}
	}
	input = matrix;
}

template <typename T>
bool checkConvergence(std::vector< std::vector<T> > &A, std::vector< std::vector<T> > &B, const double &delta) {
	for (typename std::vector<T>::size_type i = 0; i < A.size(); i++) {
		for (typename std::vector<T>::size_type j = 0; j < A[0].size(); j++) {
			// std::cout << abs(A[i][j] - B[i][j]) << std::endl;
			if (abs(A[i][j] - B[i][j]) > delta) return false;
		}
	}
	return true;
}
<commit_msg>std::abs from master<commit_after>// Standard libraries
#include "headers.hpp"

/* Templated code (must be visible to the compiler) */

template <typename T>
std::vector<T> getRange(T a, T b, int n) {
	std::vector<T> range;
	range.reserve(n);

	double step = (b - a) / n;

	while (a < (b - step/2)) {
		range.push_back(a);
		a += step;
	}

	return range;
}

template <typename T>
void printMatrix(std::vector< std::vector<T> > matrix) {
	for (const auto& vector: matrix) {
		for (const auto& element: vector) {
			std::cout << element << '\t';
		}
		std::cout << '\n';
	}
	std::cout << std::flush; // std::endl;
}

template <typename T>
void printVector(std::vector<T> vector) {
	for (const auto& element: vector) {
		std::cout << element << '\t';
	}
	std::cout << std::endl;
}

template <typename T>
void transpose(std::vector< std::vector<T> > &input) {
	std::vector< std::vector<T> > copy = input;
	std::vector< std::vector<T> > matrix(copy[0].size(), std::vector<T>(copy.size()));
	for (typename std::vector<T>::size_type i = 0; i < matrix.size(); i++) {
		for (typename std::vector<T>::size_type j = 0; j < matrix[0].size(); j++) {
			matrix[i][j] = copy[j][i];
		}
	}
	input = matrix;
}

template <typename T>
bool checkConvergence(std::vector< std::vector<T> > &A, std::vector< std::vector<T> > &B, const double &delta) {
	for (typename std::vector<T>::size_type i = 0; i < A.size(); i++) {
		for (typename std::vector<T>::size_type j = 0; j < A[0].size(); j++) {
			// std::cout << "DELTA: " << delta << std::endl;
			// std::cout << "ABS: " << abs(A[i][j] - B[i][j]) << std::endl;
			// std::cout << "STDABS: " << std::abs(A[i][j] - B[i][j]) << std::endl;
			// std::cout << A[i][j] << " - " << B[i][j] << " = " << (A[i][j] - B[i][j]) << std::endl;
			if (std::abs(A[i][j] - B[i][j]) > delta) return false;
		}
	}
	return true;
}
<|endoftext|>


<commit_before><commit_msg>[~] PI fits into 80 columns<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <algorithm>

#include <sax/fastattribs.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml;
using namespace ::com::sun::star::xml::sax;
namespace sax_fastparser
{

// wasteage to keep MSVC happy vs. an in-line {}
FastTokenHandlerBase::~FastTokenHandlerBase()
{
}

UnknownAttribute::UnknownAttribute( const OUString& rNamespaceURL, const OString& rName, const OString& value )
    : maNamespaceURL( rNamespaceURL ), maName( rName ), maValue( value )
{
}

UnknownAttribute::UnknownAttribute( const OString& rName, const OString& value )
    : maName( rName ), maValue( value )
{
}

void UnknownAttribute::FillAttribute( Attribute* pAttrib ) const
{
    if( pAttrib )
    {
        pAttrib->Name = OStringToOUString( maName, RTL_TEXTENCODING_UTF8 );
        pAttrib->NamespaceURL = maNamespaceURL;
        pAttrib->Value = OStringToOUString( maValue, RTL_TEXTENCODING_UTF8 );
    }
}

FastAttributeList::FastAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastTokenHandler >& xTokenHandler,
                                      sax_fastparser::FastTokenHandlerBase *pTokenHandler)
: mxTokenHandler( xTokenHandler ),
  mpTokenHandler( pTokenHandler )
{
    // random initial size of buffer to store attribute values
    mnChunkLength = 58;
    mpChunk = (sal_Char *) malloc( mnChunkLength );
    maAttributeValues.push_back( 0 );
}

FastAttributeList::~FastAttributeList()
{
    free( mpChunk );
}

void FastAttributeList::clear()
{
    maAttributeTokens.clear();
    maAttributeValues.resize(1);
    if (maUnknownAttributes.size() > 0)
        maUnknownAttributes.clear();
}

void FastAttributeList::add( sal_Int32 nToken, const sal_Char* pValue, size_t nValueLength )
{
    maAttributeTokens.push_back( nToken );
    sal_Int32 nWritePosition = maAttributeValues.back();
    maAttributeValues.push_back( maAttributeValues.back() + nValueLength + 1 );
    if (maAttributeValues.back() > mnChunkLength)
    {
        mnChunkLength = maAttributeValues.back();
        mpChunk = (sal_Char *) realloc( mpChunk, mnChunkLength );
    }
    strncpy(mpChunk + nWritePosition, pValue, nValueLength);
    mpChunk[nWritePosition + nValueLength] = '\0';
}

void FastAttributeList::add( sal_Int32 nToken, const sal_Char* pValue )
{
    add( nToken, pValue, strlen( pValue ));
}

void FastAttributeList::add( sal_Int32 nToken, const OString& rValue )
{
    add( nToken, rValue.getStr(), rValue.getLength() );
}

void FastAttributeList::addNS( sal_Int32 nNamespaceToken, sal_Int32 nToken, const OString& rValue )
{
    sal_Int32 nCombinedToken = (nNamespaceToken << 16) | nToken;
    add( nCombinedToken, rValue );
}

void FastAttributeList::addUnknown( const OUString& rNamespaceURL, const OString& rName, const OString& value )
{
    maUnknownAttributes.push_back( UnknownAttribute( rNamespaceURL, rName, value ) );
}

void FastAttributeList::addUnknown( const OString& rName, const OString& value )
{
    maUnknownAttributes.push_back( UnknownAttribute( rName, value ) );
}

// XFastAttributeList
sal_Bool FastAttributeList::hasAttribute( ::sal_Int32 Token ) throw (RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return sal_True;

    return sal_False;
}

sal_Int32 FastAttributeList::getValueToken( ::sal_Int32 Token ) throw (SAXException, RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return FastTokenHandlerBase::getTokenFromChars(
                       mxTokenHandler, mpTokenHandler,
                       getFastAttributeValue(i),
                       AttributeValueLength( i ) );

    throw SAXException();
}

sal_Int32 FastAttributeList::getOptionalValueToken( ::sal_Int32 Token, ::sal_Int32 Default ) throw (RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return FastTokenHandlerBase::getTokenFromChars(
                       mxTokenHandler, mpTokenHandler,
                       getFastAttributeValue(i),
                       AttributeValueLength( i ) );

    return Default;
}

// performance sensitive shortcuts to avoid allocation ...
bool FastAttributeList::getAsInteger( sal_Int32 nToken, sal_Int32 &rInt)
{
    rInt = 0;
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == nToken)
        {
            rInt = rtl_str_toInt32( getFastAttributeValue(i), 10 );
            return true;
        }
    return false;
}

bool FastAttributeList::getAsDouble( sal_Int32 nToken, double &rDouble)
{
    rDouble = 0.0;
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == nToken)
        {
            rDouble = rtl_str_toDouble( getFastAttributeValue(i) );
            return true;
        }
    return false;
}

bool FastAttributeList::getAsChar( sal_Int32 nToken, const char*& rPos ) const
{
    for (size_t i = 0, n = maAttributeTokens.size(); i < n; ++i)
    {
        if (maAttributeTokens[i] != nToken)
            continue;

        sal_Int32 nOffset = maAttributeValues[i];
        rPos = mpChunk + nOffset;
        return true;
    }

    return false;
}

OUString FastAttributeList::getValue( ::sal_Int32 Token ) throw (SAXException, RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return OUString( getFastAttributeValue(i), AttributeValueLength(i), RTL_TEXTENCODING_UTF8 );

    throw SAXException();
}

OUString FastAttributeList::getOptionalValue( ::sal_Int32 Token ) throw (RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return OUString( getFastAttributeValue(i), AttributeValueLength(i), RTL_TEXTENCODING_UTF8 );

    return OUString();
}
Sequence< Attribute > FastAttributeList::getUnknownAttributes(  ) throw (RuntimeException, std::exception)
{
    Sequence< Attribute > aSeq( maUnknownAttributes.size() );
    Attribute* pAttr = aSeq.getArray();
    for( UnknownAttributeList::iterator attrIter = maUnknownAttributes.begin(); attrIter != maUnknownAttributes.end(); ++attrIter )
        (*attrIter).FillAttribute( pAttr++ );
    return aSeq;
}
Sequence< FastAttribute > FastAttributeList::getFastAttributes(  ) throw (RuntimeException, std::exception)
{
    Sequence< FastAttribute > aSeq( maAttributeTokens.size() );
    FastAttribute* pAttr = aSeq.getArray();
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
    {
        pAttr->Token = maAttributeTokens[i];
        pAttr->Value = OUString( getFastAttributeValue(i), AttributeValueLength(i), RTL_TEXTENCODING_UTF8 );
        pAttr++;
    }
    return aSeq;
}

sal_Int32 FastTokenHandlerBase::getTokenFromChars(
        const css::uno::Reference< css::xml::sax::XFastTokenHandler > &xTokenHandler,
        FastTokenHandlerBase *pTokenHandler,
        const char *pToken, size_t nLen /* = 0 */ )
{
    sal_Int32 nRet;

    if( !nLen )
        nLen = strlen( pToken );

    if( pTokenHandler )
        nRet = pTokenHandler->getTokenDirect( pToken, (sal_Int32) nLen );
    else
    {
        // heap allocate, copy & then free
        Sequence< sal_Int8 > aSeq( reinterpret_cast<sal_Int8 const *>(pToken), nLen );
        nRet = xTokenHandler->getTokenFromUTF8( aSeq );
    }

    return nRet;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>add assert that first element is 0<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <algorithm>

#include <sax/fastattribs.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml;
using namespace ::com::sun::star::xml::sax;
namespace sax_fastparser
{

// wasteage to keep MSVC happy vs. an in-line {}
FastTokenHandlerBase::~FastTokenHandlerBase()
{
}

UnknownAttribute::UnknownAttribute( const OUString& rNamespaceURL, const OString& rName, const OString& value )
    : maNamespaceURL( rNamespaceURL ), maName( rName ), maValue( value )
{
}

UnknownAttribute::UnknownAttribute( const OString& rName, const OString& value )
    : maName( rName ), maValue( value )
{
}

void UnknownAttribute::FillAttribute( Attribute* pAttrib ) const
{
    if( pAttrib )
    {
        pAttrib->Name = OStringToOUString( maName, RTL_TEXTENCODING_UTF8 );
        pAttrib->NamespaceURL = maNamespaceURL;
        pAttrib->Value = OStringToOUString( maValue, RTL_TEXTENCODING_UTF8 );
    }
}

FastAttributeList::FastAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastTokenHandler >& xTokenHandler,
                                      sax_fastparser::FastTokenHandlerBase *pTokenHandler)
: mxTokenHandler( xTokenHandler ),
  mpTokenHandler( pTokenHandler )
{
    // random initial size of buffer to store attribute values
    mnChunkLength = 58;
    mpChunk = (sal_Char *) malloc( mnChunkLength );
    maAttributeValues.push_back( 0 );
}

FastAttributeList::~FastAttributeList()
{
    free( mpChunk );
}

void FastAttributeList::clear()
{
    maAttributeTokens.clear();
    maAttributeValues.resize(1);
    assert(maAttributeValues[0] == 0);
    if (!maUnknownAttributes.empty())
        maUnknownAttributes.clear();
}

void FastAttributeList::add( sal_Int32 nToken, const sal_Char* pValue, size_t nValueLength )
{
    maAttributeTokens.push_back( nToken );
    sal_Int32 nWritePosition = maAttributeValues.back();
    maAttributeValues.push_back( maAttributeValues.back() + nValueLength + 1 );
    if (maAttributeValues.back() > mnChunkLength)
    {
        mnChunkLength = maAttributeValues.back();
        mpChunk = (sal_Char *) realloc( mpChunk, mnChunkLength );
    }
    strncpy(mpChunk + nWritePosition, pValue, nValueLength);
    mpChunk[nWritePosition + nValueLength] = '\0';
}

void FastAttributeList::add( sal_Int32 nToken, const sal_Char* pValue )
{
    add( nToken, pValue, strlen( pValue ));
}

void FastAttributeList::add( sal_Int32 nToken, const OString& rValue )
{
    add( nToken, rValue.getStr(), rValue.getLength() );
}

void FastAttributeList::addNS( sal_Int32 nNamespaceToken, sal_Int32 nToken, const OString& rValue )
{
    sal_Int32 nCombinedToken = (nNamespaceToken << 16) | nToken;
    add( nCombinedToken, rValue );
}

void FastAttributeList::addUnknown( const OUString& rNamespaceURL, const OString& rName, const OString& value )
{
    maUnknownAttributes.push_back( UnknownAttribute( rNamespaceURL, rName, value ) );
}

void FastAttributeList::addUnknown( const OString& rName, const OString& value )
{
    maUnknownAttributes.push_back( UnknownAttribute( rName, value ) );
}

// XFastAttributeList
sal_Bool FastAttributeList::hasAttribute( ::sal_Int32 Token ) throw (RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return sal_True;

    return sal_False;
}

sal_Int32 FastAttributeList::getValueToken( ::sal_Int32 Token ) throw (SAXException, RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return FastTokenHandlerBase::getTokenFromChars(
                       mxTokenHandler, mpTokenHandler,
                       getFastAttributeValue(i),
                       AttributeValueLength( i ) );

    throw SAXException();
}

sal_Int32 FastAttributeList::getOptionalValueToken( ::sal_Int32 Token, ::sal_Int32 Default ) throw (RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return FastTokenHandlerBase::getTokenFromChars(
                       mxTokenHandler, mpTokenHandler,
                       getFastAttributeValue(i),
                       AttributeValueLength( i ) );

    return Default;
}

// performance sensitive shortcuts to avoid allocation ...
bool FastAttributeList::getAsInteger( sal_Int32 nToken, sal_Int32 &rInt)
{
    rInt = 0;
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == nToken)
        {
            rInt = rtl_str_toInt32( getFastAttributeValue(i), 10 );
            return true;
        }
    return false;
}

bool FastAttributeList::getAsDouble( sal_Int32 nToken, double &rDouble)
{
    rDouble = 0.0;
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == nToken)
        {
            rDouble = rtl_str_toDouble( getFastAttributeValue(i) );
            return true;
        }
    return false;
}

bool FastAttributeList::getAsChar( sal_Int32 nToken, const char*& rPos ) const
{
    for (size_t i = 0, n = maAttributeTokens.size(); i < n; ++i)
    {
        if (maAttributeTokens[i] != nToken)
            continue;

        sal_Int32 nOffset = maAttributeValues[i];
        rPos = mpChunk + nOffset;
        return true;
    }

    return false;
}

OUString FastAttributeList::getValue( ::sal_Int32 Token ) throw (SAXException, RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return OUString( getFastAttributeValue(i), AttributeValueLength(i), RTL_TEXTENCODING_UTF8 );

    throw SAXException();
}

OUString FastAttributeList::getOptionalValue( ::sal_Int32 Token ) throw (RuntimeException, std::exception)
{
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
        if (maAttributeTokens[i] == Token)
            return OUString( getFastAttributeValue(i), AttributeValueLength(i), RTL_TEXTENCODING_UTF8 );

    return OUString();
}
Sequence< Attribute > FastAttributeList::getUnknownAttributes(  ) throw (RuntimeException, std::exception)
{
    Sequence< Attribute > aSeq( maUnknownAttributes.size() );
    Attribute* pAttr = aSeq.getArray();
    for( UnknownAttributeList::iterator attrIter = maUnknownAttributes.begin(); attrIter != maUnknownAttributes.end(); ++attrIter )
        (*attrIter).FillAttribute( pAttr++ );
    return aSeq;
}
Sequence< FastAttribute > FastAttributeList::getFastAttributes(  ) throw (RuntimeException, std::exception)
{
    Sequence< FastAttribute > aSeq( maAttributeTokens.size() );
    FastAttribute* pAttr = aSeq.getArray();
    for (size_t i = 0; i < maAttributeTokens.size(); ++i)
    {
        pAttr->Token = maAttributeTokens[i];
        pAttr->Value = OUString( getFastAttributeValue(i), AttributeValueLength(i), RTL_TEXTENCODING_UTF8 );
        pAttr++;
    }
    return aSeq;
}

sal_Int32 FastTokenHandlerBase::getTokenFromChars(
        const css::uno::Reference< css::xml::sax::XFastTokenHandler > &xTokenHandler,
        FastTokenHandlerBase *pTokenHandler,
        const char *pToken, size_t nLen /* = 0 */ )
{
    sal_Int32 nRet;

    if( !nLen )
        nLen = strlen( pToken );

    if( pTokenHandler )
        nRet = pTokenHandler->getTokenDirect( pToken, (sal_Int32) nLen );
    else
    {
        // heap allocate, copy & then free
        Sequence< sal_Int8 > aSeq( reinterpret_cast<sal_Int8 const *>(pToken), nLen );
        nRet = xTokenHandler->getTokenFromUTF8( aSeq );
    }

    return nRet;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before><commit_msg>Update injector.cpp<commit_after><|endoftext|>


<commit_before>#include "test.h"
#include "../../src/duktape.cpp"
#include <QObject>
#include <QMetaMethod>

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

#include "../../src/abstractcallable.cpp"
#include "../../src/abstractcontext.cpp"

Q_DECLARE_METATYPE(int*)
Q_DECLARE_METATYPE(Test*)
Q_DECLARE_METATYPE(Test**)
Q_DECLARE_METATYPE(Test2*)

int main()
{
    dukpp03::qt::Context ctx;
    ctx.setMaximumExecutionTime(30000);

    dukpp03::qt::registerMetaType<Test>();
    dukpp03::qt::registerMetaType<Test2>();

    dukpp03::qt::ClassBinding* testbinding = new dukpp03::qt::ClassBinding();
    testbinding->addMethod("speak", dukpp03::qt::bind_method::from(&Test::speak));
    testbinding->registerMetaObject<Test>();
    ctx.registerCallable("free_speak", dukpp03::qt::make_method::from(&Test::speak));
    ctx.addClassBinding("Test*", testbinding);
    std::string error;
    ctx.eval("var a = new Test(1.2); a.speak(); a.slot33(2); a.slot2(); a.slot3(); a.slotx(2, 3, \"a\", 4); free_speak(a); a.x = 122; print(a.x);", false, &error);
    std::cout << error << "\n";
    Test f;
    QVariant v;
    Test2* vc;

    return 0;
}
<commit_msg>Ok, even case with unknown class seems to work.<commit_after>#include "test.h"
#include "../../src/duktape.cpp"
#include <QObject>
#include <QMetaMethod>

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

#include "../../src/abstractcallable.cpp"
#include "../../src/abstractcontext.cpp"

Q_DECLARE_METATYPE(int*)
Q_DECLARE_METATYPE(Test*)
Q_DECLARE_METATYPE(Test**)
Q_DECLARE_METATYPE(Test2*)

int main()
{
    dukpp03::qt::Context ctx;
    ctx.setMaximumExecutionTime(30000);

    dukpp03::qt::registerMetaType<Test>();
    dukpp03::qt::registerMetaType<Test2>();

    dukpp03::qt::ClassBinding* testbinding = new dukpp03::qt::ClassBinding();
    testbinding->addMethod("speak", dukpp03::qt::bind_method::from(&Test::speak));
    testbinding->registerMetaObject<Test>();
    ctx.registerCallable("free_speak", dukpp03::qt::make_method::from(&Test::speak));
    ctx.addClassBinding("Test*", testbinding);
    std::string error;
    ctx.eval("var a = new Test(1.2); a.speak(); a.slot33(2); a.slot2(); a.slot3(); a.slotx(2, 3, \"a\", 4); free_speak(a); a.x = 122; print(a.x); print(a.slot(127).slot(127));", false, &error);
    std::cout << error << "\n";
    Test f;
    QVariant v;
    Test2* vc;

    return 0;
}
<|endoftext|>


<commit_before>//===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform manipulations on Modules.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

static void appendToGlobalArray(const char *Array, Module &M, Function *F,
                                int Priority, Constant *Data) {
  IRBuilder<> IRB(M.getContext());
  FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);

  // Get the current set of static global constructors and add the new ctor
  // to the list.
  SmallVector<Constant *, 16> CurrentCtors;
  StructType *EltTy;
  if (GlobalVariable *GVCtor = M.getNamedGlobal(Array)) {
    ArrayType *ATy = cast<ArrayType>(GVCtor->getValueType());
    StructType *OldEltTy = cast<StructType>(ATy->getElementType());
    // Upgrade a 2-field global array type to the new 3-field format if needed.
    if (Data && OldEltTy->getNumElements() < 3)
      EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
                              IRB.getInt8PtrTy(), nullptr);
    else
      EltTy = OldEltTy;
    if (Constant *Init = GVCtor->getInitializer()) {
      unsigned n = Init->getNumOperands();
      CurrentCtors.reserve(n + 1);
      for (unsigned i = 0; i != n; ++i) {
        auto Ctor = cast<Constant>(Init->getOperand(i));
        if (EltTy != OldEltTy)
          Ctor = ConstantStruct::get(
              EltTy, Ctor->getAggregateElement((unsigned)0),
              Ctor->getAggregateElement(1),
              Constant::getNullValue(IRB.getInt8PtrTy()), nullptr);
        CurrentCtors.push_back(Ctor);
      }
    }
    GVCtor->eraseFromParent();
  } else {
    // Use the new three-field struct if there isn't one already.
    EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
                            IRB.getInt8PtrTy(), nullptr);
  }

  // Build a 2 or 3 field global_ctor entry.  We don't take a comdat key.
  Constant *CSVals[3];
  CSVals[0] = IRB.getInt32(Priority);
  CSVals[1] = F;
  // FIXME: Drop support for the two element form in LLVM 4.0.
  if (EltTy->getNumElements() >= 3)
    CSVals[2] = Data ? ConstantExpr::getPointerCast(Data, IRB.getInt8PtrTy())
                     : Constant::getNullValue(IRB.getInt8PtrTy());
  Constant *RuntimeCtorInit =
      ConstantStruct::get(EltTy, makeArrayRef(CSVals, EltTy->getNumElements()));

  CurrentCtors.push_back(RuntimeCtorInit);

  // Create a new initializer.
  ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
  Constant *NewInit = ConstantArray::get(AT, CurrentCtors);

  // Create the new global variable and replace all uses of
  // the old global variable with the new one.
  (void)new GlobalVariable(M, NewInit->getType(), false,
                           GlobalValue::AppendingLinkage, NewInit, Array);
}

void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data) {
  appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
}

void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data) {
  appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
}

GlobalVariable *
llvm::collectUsedGlobalVariables(Module &M, SmallPtrSetImpl<GlobalValue *> &Set,
                                 bool CompilerUsed) {
  const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
  GlobalVariable *GV = M.getGlobalVariable(Name);
  if (!GV || !GV->hasInitializer())
    return GV;

  const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
  for (unsigned I = 0, E = Init->getNumOperands(); I != E; ++I) {
    Value *Op = Init->getOperand(I);
    GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
    Set.insert(G);
  }
  return GV;
}

Function *llvm::checkSanitizerInterfaceFunction(Constant *FuncOrBitcast) {
  if (isa<Function>(FuncOrBitcast))
    return cast<Function>(FuncOrBitcast);
  FuncOrBitcast->dump();
  std::string Err;
  raw_string_ostream Stream(Err);
  Stream << "Sanitizer interface function redefined: " << *FuncOrBitcast;
  report_fatal_error(Err);
}

std::pair<Function *, Function *> llvm::createSanitizerCtorAndInitFunctions(
    Module &M, StringRef CtorName, StringRef InitName,
    ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
    StringRef VersionCheckName) {
  assert(!InitName.empty() && "Expected init function name");
  assert(InitArgTypes.size() == InitArgTypes.size() &&
         "Sanitizer's init function expects different number of arguments");
  Function *Ctor = Function::Create(
      FunctionType::get(Type::getVoidTy(M.getContext()), false),
      GlobalValue::InternalLinkage, CtorName, &M);
  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
  Function *InitFunction =
      checkSanitizerInterfaceFunction(M.getOrInsertFunction(
          InitName, FunctionType::get(IRB.getVoidTy(), InitArgTypes, false),
          AttributeSet()));
  InitFunction->setLinkage(Function::ExternalLinkage);
  IRB.CreateCall(InitFunction, InitArgs);
  if (!VersionCheckName.empty()) {
    Function *VersionCheckFunction =
        checkSanitizerInterfaceFunction(M.getOrInsertFunction(
            VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
            AttributeSet()));
    IRB.CreateCall(VersionCheckFunction, {});
  }
  return std::make_pair(Ctor, InitFunction);
}
<commit_msg>[ModuleUtils] Use range-based loop. NFC.<commit_after>//===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform manipulations on Modules.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

static void appendToGlobalArray(const char *Array, Module &M, Function *F,
                                int Priority, Constant *Data) {
  IRBuilder<> IRB(M.getContext());
  FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);

  // Get the current set of static global constructors and add the new ctor
  // to the list.
  SmallVector<Constant *, 16> CurrentCtors;
  StructType *EltTy;
  if (GlobalVariable *GVCtor = M.getNamedGlobal(Array)) {
    ArrayType *ATy = cast<ArrayType>(GVCtor->getValueType());
    StructType *OldEltTy = cast<StructType>(ATy->getElementType());
    // Upgrade a 2-field global array type to the new 3-field format if needed.
    if (Data && OldEltTy->getNumElements() < 3)
      EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
                              IRB.getInt8PtrTy(), nullptr);
    else
      EltTy = OldEltTy;
    if (Constant *Init = GVCtor->getInitializer()) {
      unsigned n = Init->getNumOperands();
      CurrentCtors.reserve(n + 1);
      for (unsigned i = 0; i != n; ++i) {
        auto Ctor = cast<Constant>(Init->getOperand(i));
        if (EltTy != OldEltTy)
          Ctor = ConstantStruct::get(
              EltTy, Ctor->getAggregateElement((unsigned)0),
              Ctor->getAggregateElement(1),
              Constant::getNullValue(IRB.getInt8PtrTy()), nullptr);
        CurrentCtors.push_back(Ctor);
      }
    }
    GVCtor->eraseFromParent();
  } else {
    // Use the new three-field struct if there isn't one already.
    EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
                            IRB.getInt8PtrTy(), nullptr);
  }

  // Build a 2 or 3 field global_ctor entry.  We don't take a comdat key.
  Constant *CSVals[3];
  CSVals[0] = IRB.getInt32(Priority);
  CSVals[1] = F;
  // FIXME: Drop support for the two element form in LLVM 4.0.
  if (EltTy->getNumElements() >= 3)
    CSVals[2] = Data ? ConstantExpr::getPointerCast(Data, IRB.getInt8PtrTy())
                     : Constant::getNullValue(IRB.getInt8PtrTy());
  Constant *RuntimeCtorInit =
      ConstantStruct::get(EltTy, makeArrayRef(CSVals, EltTy->getNumElements()));

  CurrentCtors.push_back(RuntimeCtorInit);

  // Create a new initializer.
  ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
  Constant *NewInit = ConstantArray::get(AT, CurrentCtors);

  // Create the new global variable and replace all uses of
  // the old global variable with the new one.
  (void)new GlobalVariable(M, NewInit->getType(), false,
                           GlobalValue::AppendingLinkage, NewInit, Array);
}

void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data) {
  appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
}

void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data) {
  appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
}

GlobalVariable *
llvm::collectUsedGlobalVariables(Module &M, SmallPtrSetImpl<GlobalValue *> &Set,
                                 bool CompilerUsed) {
  const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
  GlobalVariable *GV = M.getGlobalVariable(Name);
  if (!GV || !GV->hasInitializer())
    return GV;

  const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
  for (Value *Op : Init->operands()) {
    GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
    Set.insert(G);
  }
  return GV;
}

Function *llvm::checkSanitizerInterfaceFunction(Constant *FuncOrBitcast) {
  if (isa<Function>(FuncOrBitcast))
    return cast<Function>(FuncOrBitcast);
  FuncOrBitcast->dump();
  std::string Err;
  raw_string_ostream Stream(Err);
  Stream << "Sanitizer interface function redefined: " << *FuncOrBitcast;
  report_fatal_error(Err);
}

std::pair<Function *, Function *> llvm::createSanitizerCtorAndInitFunctions(
    Module &M, StringRef CtorName, StringRef InitName,
    ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
    StringRef VersionCheckName) {
  assert(!InitName.empty() && "Expected init function name");
  assert(InitArgTypes.size() == InitArgTypes.size() &&
         "Sanitizer's init function expects different number of arguments");
  Function *Ctor = Function::Create(
      FunctionType::get(Type::getVoidTy(M.getContext()), false),
      GlobalValue::InternalLinkage, CtorName, &M);
  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
  Function *InitFunction =
      checkSanitizerInterfaceFunction(M.getOrInsertFunction(
          InitName, FunctionType::get(IRB.getVoidTy(), InitArgTypes, false),
          AttributeSet()));
  InitFunction->setLinkage(Function::ExternalLinkage);
  IRB.CreateCall(InitFunction, InitArgs);
  if (!VersionCheckName.empty()) {
    Function *VersionCheckFunction =
        checkSanitizerInterfaceFunction(M.getOrInsertFunction(
            VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
            AttributeSet()));
    IRB.CreateCall(VersionCheckFunction, {});
  }
  return std::make_pair(Ctor, InitFunction);
}
<|endoftext|>


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

#ifndef _CONNECTIVITY_ADO_KEYS_HXX_
#include "ado/AKeys.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#include "ado/AKey.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
using namespace com::sun::star::container;

Reference< XNamed > OKeys::createObject(const ::rtl::OUString& _rName)
{
    return new OAdoKey(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OKeys::impl_refresh() throw(RuntimeException)
{
    m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OKeys::createEmptyObject()
{
    return new OAdoKey(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
void OKeys::appendObject( const Reference< XPropertySet >& descriptor )
{
    OAdoKey* pKey = NULL;
    if(getImplementation(pKey,descriptor) && pKey != NULL)
    {
        // To pass as column parameter to Key's Apppend method
        OLEVariant vOptional;
        vOptional.setNoArg();

        KeyTypeEnum eKey = OAdoKey::Map2KeyRule(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))));
        WpADOKey aKey = pKey->getImpl();
        ::rtl::OUString sName = aKey.get_Name();
        if(!sName.getLength())
            aKey.put_Name(::rtl::OUString::createFromAscii("PrimaryKey") );

        ADOKeys* pKeys = m_aCollection;
        if ( FAILED(pKeys->Append(OLEVariant((ADOKey*)aKey),
                                adKeyPrimary, // must be every time adKeyPrimary
                                vOptional)) )
        {
            ADOS::ThrowException(*m_pConnection->getConnection(),*this);
            // just make sure that an SQLExceptionis thrown here
            throw SQLException(::rtl::OUString::createFromAscii("Could not append key!"),*this,OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_HY0000),1000,Any());
        }
    }
    else
        throw SQLException(::rtl::OUString::createFromAscii("Could not append key!"),*this,OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_HY0000),1000,Any());
}
// -------------------------------------------------------------------------
// XDrop
void OKeys::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
    if(!m_aCollection.Delete(OLEVariant(_sElementName)))
        ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
// -----------------------------------------------------------------------------
Reference< XNamed > OKeys::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
    OAdoKey* pKey = NULL;
    if(getImplementation(pKey,_xDescriptor) && pKey != NULL)
        return new OAdoKey(isCaseSensitive(),m_pConnection,pKey->getImpl());
    return Reference< XNamed >();
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba16 (1.12.210); FILE MERGED 2004/10/11 06:12:11 oj 1.12.210.1: #i32931# remove the weak interface, refcount handled by parent<commit_after>/*************************************************************************
 *
 *  $RCSfile: AKeys.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2004-10-22 08:42:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_KEYS_HXX_
#include "ado/AKeys.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#include "ado/AKey.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
using namespace com::sun::star::container;

Reference< XNamed > OKeys::createObject(const ::rtl::OUString& _rName)
{
    return new OAdoKey(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OKeys::impl_refresh() throw(RuntimeException)
{
    m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OKeys::createEmptyObject()
{
    return new OAdoKey(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
void OKeys::appendObject( const Reference< XPropertySet >& descriptor )
{
    OAdoKey* pKey = NULL;
    if(getImplementation(pKey,descriptor) && pKey != NULL)
    {
        // To pass as column parameter to Key's Apppend method
        OLEVariant vOptional;
        vOptional.setNoArg();

        KeyTypeEnum eKey = OAdoKey::Map2KeyRule(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))));
        WpADOKey aKey = pKey->getImpl();
        ::rtl::OUString sName = aKey.get_Name();
        if(!sName.getLength())
            aKey.put_Name(::rtl::OUString::createFromAscii("PrimaryKey") );

        ADOKeys* pKeys = m_aCollection;
        if ( FAILED(pKeys->Append(OLEVariant((ADOKey*)aKey),
                                adKeyPrimary, // must be every time adKeyPrimary
                                vOptional)) )
        {
            ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
            // just make sure that an SQLExceptionis thrown here
            throw SQLException(::rtl::OUString::createFromAscii("Could not append key!"),static_cast<XTypeProvider*>(this),OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_HY0000),1000,Any());
        }
    }
    else
        throw SQLException(::rtl::OUString::createFromAscii("Could not append key!"),static_cast<XTypeProvider*>(this),OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_HY0000),1000,Any());
}
// -------------------------------------------------------------------------
// XDrop
void OKeys::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
    if(!m_aCollection.Delete(OLEVariant(_sElementName)))
        ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
}
// -----------------------------------------------------------------------------
Reference< XNamed > OKeys::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
    OAdoKey* pKey = NULL;
    if(getImplementation(pKey,_xDescriptor) && pKey != NULL)
        return new OAdoKey(isCaseSensitive(),m_pConnection,pKey->getImpl());
    return Reference< XNamed >();
}
// -----------------------------------------------------------------------------

<|endoftext|>