<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: apifactoryimpl.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:54:11 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"
#include <stdio.h>
#include "apifactoryimpl.hxx"

#include "setobjects.hxx"
#include "groupobjects.hxx"

#include "configset.hxx"
#include "configpath.hxx"
#include "template.hxx"
#include "noderef.hxx"
#include "objectregistry.hxx"
#include "attributes.hxx"

namespace configmgr
{
    namespace configapi
    {
        using configuration::Template;
        using configuration::NodeID;
//-----------------------------------------------------------------------------
// class ReadOnlyObjectFactory
//-----------------------------------------------------------------------------

ReadOnlyObjectFactory::ReadOnlyObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry)
: Factory(pRegistry)
, m_rProvider(rProvider)
{
}
//-----------------------------------------------------------------------------

ReadOnlyObjectFactory::~ReadOnlyObjectFactory()
{
}
//-----------------------------------------------------------------------------

NodeElement* ReadOnlyObjectFactory::doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, Template* pSetElementTemplate)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a group member without a tree");
    OSL_ENSURE(aNode.isValid(), "ERROR: trying to create a group member without a node");
    OSL_ENSURE(aTree.isValidNode(aNode), "ERROR: node does not match tree , while trying to create a group member");
    OSL_ENSURE(!aTree.isRootNode(aNode), "ERROR: trying to create a group member on a root node");
    if (aTree.isRootNode(aNode))
        return 0;

    NodeElement* pRootElement = makeElement(aTree,aTree.getRootNode());
    OSL_ENSURE(pRootElement, "Could not create root element of tree - cannot create group member object");
    if (!pRootElement)
        return 0;

    UnoInterfaceRef aRootRelease(pRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
    ApiTreeImpl& rRootContext = getImplementation(*pRootElement);

    NodeElement * pResult = 0;
    if (!pSetElementTemplate)
    {
         OInnerGroupInfo * pNewObject = new OInnerGroupInfo(rRootContext, aNode);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    else
    {
         OInnerSetInfo * pNewObject = new OInnerSetInfo(rRootContext, aNode);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }

    return pResult;
}
//-----------------------------------------------------------------------------

TreeElement* ReadOnlyObjectFactory::doCreateAccessRoot(configuration::Tree const& aTree, Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a root object without a tree");

    TreeElement * pResult = 0;
    if (!pSetElementTemplate)
    {
         ORootElementGroupInfo * pNewObject = new ORootElementGroupInfo(m_rProvider, aTree, _xOptions);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    else
    {
         ORootElementSetInfo * pNewObject = new ORootElementSetInfo(m_rProvider, aTree, _xOptions);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    return pResult;
}

//-----------------------------------------------------------------------------
SetElement* ReadOnlyObjectFactory::doCreateSetElement(configuration::ElementTree const& aElementTree, Template* pSetElementTemplate)
{
    OSL_ENSURE(aElementTree.isValid(), "ERROR: trying to create a set element object without a tree");

    Tree aTree( aElementTree.getTree() );
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a set element object without a tree");

    ApiTreeImpl * pParentContext = 0;
    UnoInterfaceRef aParentRelease;

    configuration::Tree aParentTree = aTree.getContextTree();
    if (!aParentTree.isEmpty())
    {
        //NodeRef aParentNode = aTree.getContextNode();
        NodeRef aParentRoot = aParentTree.getRootNode();
        if (NodeElement* pParentRootElement = makeElement(aParentTree,aParentRoot) )
        {
            aParentRelease = UnoInterfaceRef(pParentRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
            pParentContext = &getImplementation(*pParentRootElement);
        }
    }

    SetElement * pResult = 0;
    if (!pSetElementTemplate)
    {
         OSetElementGroupInfo * pNewObject = new OSetElementGroupInfo(aTree.getRef(),m_rProvider,pParentContext);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    else
    {
         OSetElementSetInfo * pNewObject = new OSetElementSetInfo(aTree.getRef(),m_rProvider,pParentContext);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    return pResult;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// class UpdateObjectFactory
//-----------------------------------------------------------------------------

UpdateObjectFactory::UpdateObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry)
: Factory(pRegistry)
, m_rProvider(rProvider)
{
}
//-----------------------------------------------------------------------------

UpdateObjectFactory::~UpdateObjectFactory()
{
}
//-----------------------------------------------------------------------------

bool UpdateObjectFactory::implIsReadOnly(configuration::Tree const& aTree, configuration::NodeRef const& aNode)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create an object without a tree");
    OSL_ENSURE(aNode.isValid(), "ERROR: trying to create an object without a node");
    OSL_ENSURE(aTree.isValidNode(aNode), "ERROR: node does not match tree , while trying to create an object");

    return aTree.getAttributes(aNode).isReadonly();
}
//-----------------------------------------------------------------------------

NodeElement* UpdateObjectFactory::doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, Template* pSetElementTemplate)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a group member without a tree");
    OSL_ENSURE(aNode.isValid(), "ERROR: trying to create a group member without a node");
    OSL_ENSURE(aTree.isValidNode(aNode), "ERROR: node does not match tree , while trying to create a group");

    NodeElement* pRootElement = makeElement(aTree,aTree.getRootNode());
    OSL_ENSURE(pRootElement, "Could not create root element of tree - cannot create group member object");
    if (!pRootElement)
        return 0;

    UnoInterfaceRef aRootRelease(pRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
    ApiTreeImpl& rRootContext = getImplementation(*pRootElement);

    NodeElement * pResult = 0;

    if (implIsReadOnly(aTree,aNode))
    {
        if (!pSetElementTemplate)
        {
             OInnerGroupInfo * pNewObject = new OInnerGroupInfo(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OInnerSetInfo * pNewObject = new OInnerSetInfo(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    else
    {
        if (!pSetElementTemplate)
        {
             OInnerGroupUpdate * pNewObject = new OInnerGroupUpdate(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else if (pSetElementTemplate->isInstanceValue())
        {
             OInnerValueSetUpdate * pNewObject = new OInnerValueSetUpdate(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OInnerTreeSetUpdate * pNewObject = new OInnerTreeSetUpdate(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }

    return pResult;
}
//-----------------------------------------------------------------------------

TreeElement* UpdateObjectFactory::doCreateAccessRoot(configuration::Tree const& aTree, Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a root object without a tree");

    TreeElement * pResult = 0;
    if (implIsReadOnly(aTree,aTree.getRootNode()))
    {
        OSL_ENSURE(false, "WARNING: Trying to create an 'Update Access' on a read-only tree/node");
        if (!pSetElementTemplate)
        {
             ORootElementGroupInfo * pNewObject = new ORootElementGroupInfo(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             ORootElementSetInfo * pNewObject = new ORootElementSetInfo(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    else
    {
        if (!pSetElementTemplate)
        {
             ORootElementGroupUpdate * pNewObject = new ORootElementGroupUpdate(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else if (pSetElementTemplate->isInstanceValue())
        {
             ORootElementValueSetUpdate * pNewObject = new ORootElementValueSetUpdate(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             ORootElementTreeSetUpdate * pNewObject = new ORootElementTreeSetUpdate(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }

    return pResult;
}

//-----------------------------------------------------------------------------
SetElement* UpdateObjectFactory::doCreateSetElement(configuration::ElementTree const& aElementTree, Template* pSetElementTemplate)
{
    OSL_ENSURE(aElementTree.isValid(), "ERROR: trying to create a set element object without a tree");

    Tree aTree( aElementTree.getTree() );
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a set element object without a tree");

    ApiTreeImpl * pParentContext = 0;
    UnoInterfaceRef aParentRelease;

    configuration::Tree aParentTree = aTree.getContextTree();
    if (!aParentTree.isEmpty())
    {
        //NodeRef aParentNode = aTree.getContextNode();
        NodeRef aParentRoot = aParentTree.getRootNode();
        if (NodeElement* pParentRootElement = makeElement(aParentTree,aParentRoot) )
        {
            aParentRelease = UnoInterfaceRef(pParentRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
            pParentContext = &getImplementation(*pParentRootElement);
        }
    }

    SetElement * pResult = 0;
    if (implIsReadOnly(aTree,aTree.getRootNode()))
    {
        if (!pSetElementTemplate)
        {
             OSetElementGroupInfo * pNewObject = new OSetElementGroupInfo(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OSetElementSetInfo * pNewObject = new OSetElementSetInfo(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    else
    {
        if (!pSetElementTemplate)
        {
             OSetElementGroupUpdate * pNewObject = new OSetElementGroupUpdate(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else if (pSetElementTemplate->isInstanceValue())
        {
             OSetElementValueSetUpdate * pNewObject = new OSetElementValueSetUpdate(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OSetElementTreeSetUpdate * pNewObject = new OSetElementTreeSetUpdate(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    return pResult;
}
//-----------------------------------------------------------------------------
    }
}

<commit_msg>INTEGRATION: CWS changefileheader (1.12.72); FILE MERGED 2008/03/31 12:22:35 rt 1.12.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: apifactoryimpl.cxx,v $
 * $Revision: 1.13 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"
#include <stdio.h>
#include "apifactoryimpl.hxx"

#include "setobjects.hxx"
#include "groupobjects.hxx"

#include "configset.hxx"
#include "configpath.hxx"
#include "template.hxx"
#include "noderef.hxx"
#include "objectregistry.hxx"
#include "attributes.hxx"

namespace configmgr
{
    namespace configapi
    {
        using configuration::Template;
        using configuration::NodeID;
//-----------------------------------------------------------------------------
// class ReadOnlyObjectFactory
//-----------------------------------------------------------------------------

ReadOnlyObjectFactory::ReadOnlyObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry)
: Factory(pRegistry)
, m_rProvider(rProvider)
{
}
//-----------------------------------------------------------------------------

ReadOnlyObjectFactory::~ReadOnlyObjectFactory()
{
}
//-----------------------------------------------------------------------------

NodeElement* ReadOnlyObjectFactory::doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, Template* pSetElementTemplate)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a group member without a tree");
    OSL_ENSURE(aNode.isValid(), "ERROR: trying to create a group member without a node");
    OSL_ENSURE(aTree.isValidNode(aNode), "ERROR: node does not match tree , while trying to create a group member");
    OSL_ENSURE(!aTree.isRootNode(aNode), "ERROR: trying to create a group member on a root node");
    if (aTree.isRootNode(aNode))
        return 0;

    NodeElement* pRootElement = makeElement(aTree,aTree.getRootNode());
    OSL_ENSURE(pRootElement, "Could not create root element of tree - cannot create group member object");
    if (!pRootElement)
        return 0;

    UnoInterfaceRef aRootRelease(pRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
    ApiTreeImpl& rRootContext = getImplementation(*pRootElement);

    NodeElement * pResult = 0;
    if (!pSetElementTemplate)
    {
         OInnerGroupInfo * pNewObject = new OInnerGroupInfo(rRootContext, aNode);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    else
    {
         OInnerSetInfo * pNewObject = new OInnerSetInfo(rRootContext, aNode);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }

    return pResult;
}
//-----------------------------------------------------------------------------

TreeElement* ReadOnlyObjectFactory::doCreateAccessRoot(configuration::Tree const& aTree, Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a root object without a tree");

    TreeElement * pResult = 0;
    if (!pSetElementTemplate)
    {
         ORootElementGroupInfo * pNewObject = new ORootElementGroupInfo(m_rProvider, aTree, _xOptions);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    else
    {
         ORootElementSetInfo * pNewObject = new ORootElementSetInfo(m_rProvider, aTree, _xOptions);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    return pResult;
}

//-----------------------------------------------------------------------------
SetElement* ReadOnlyObjectFactory::doCreateSetElement(configuration::ElementTree const& aElementTree, Template* pSetElementTemplate)
{
    OSL_ENSURE(aElementTree.isValid(), "ERROR: trying to create a set element object without a tree");

    Tree aTree( aElementTree.getTree() );
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a set element object without a tree");

    ApiTreeImpl * pParentContext = 0;
    UnoInterfaceRef aParentRelease;

    configuration::Tree aParentTree = aTree.getContextTree();
    if (!aParentTree.isEmpty())
    {
        //NodeRef aParentNode = aTree.getContextNode();
        NodeRef aParentRoot = aParentTree.getRootNode();
        if (NodeElement* pParentRootElement = makeElement(aParentTree,aParentRoot) )
        {
            aParentRelease = UnoInterfaceRef(pParentRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
            pParentContext = &getImplementation(*pParentRootElement);
        }
    }

    SetElement * pResult = 0;
    if (!pSetElementTemplate)
    {
         OSetElementGroupInfo * pNewObject = new OSetElementGroupInfo(aTree.getRef(),m_rProvider,pParentContext);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    else
    {
         OSetElementSetInfo * pNewObject = new OSetElementSetInfo(aTree.getRef(),m_rProvider,pParentContext);
         pNewObject->acquire();
         pResult = &pNewObject->getElementClass();
    }
    return pResult;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// class UpdateObjectFactory
//-----------------------------------------------------------------------------

UpdateObjectFactory::UpdateObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry)
: Factory(pRegistry)
, m_rProvider(rProvider)
{
}
//-----------------------------------------------------------------------------

UpdateObjectFactory::~UpdateObjectFactory()
{
}
//-----------------------------------------------------------------------------

bool UpdateObjectFactory::implIsReadOnly(configuration::Tree const& aTree, configuration::NodeRef const& aNode)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create an object without a tree");
    OSL_ENSURE(aNode.isValid(), "ERROR: trying to create an object without a node");
    OSL_ENSURE(aTree.isValidNode(aNode), "ERROR: node does not match tree , while trying to create an object");

    return aTree.getAttributes(aNode).isReadonly();
}
//-----------------------------------------------------------------------------

NodeElement* UpdateObjectFactory::doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, Template* pSetElementTemplate)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a group member without a tree");
    OSL_ENSURE(aNode.isValid(), "ERROR: trying to create a group member without a node");
    OSL_ENSURE(aTree.isValidNode(aNode), "ERROR: node does not match tree , while trying to create a group");

    NodeElement* pRootElement = makeElement(aTree,aTree.getRootNode());
    OSL_ENSURE(pRootElement, "Could not create root element of tree - cannot create group member object");
    if (!pRootElement)
        return 0;

    UnoInterfaceRef aRootRelease(pRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
    ApiTreeImpl& rRootContext = getImplementation(*pRootElement);

    NodeElement * pResult = 0;

    if (implIsReadOnly(aTree,aNode))
    {
        if (!pSetElementTemplate)
        {
             OInnerGroupInfo * pNewObject = new OInnerGroupInfo(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OInnerSetInfo * pNewObject = new OInnerSetInfo(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    else
    {
        if (!pSetElementTemplate)
        {
             OInnerGroupUpdate * pNewObject = new OInnerGroupUpdate(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else if (pSetElementTemplate->isInstanceValue())
        {
             OInnerValueSetUpdate * pNewObject = new OInnerValueSetUpdate(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OInnerTreeSetUpdate * pNewObject = new OInnerTreeSetUpdate(rRootContext, aNode);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }

    return pResult;
}
//-----------------------------------------------------------------------------

TreeElement* UpdateObjectFactory::doCreateAccessRoot(configuration::Tree const& aTree, Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions)
{
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a root object without a tree");

    TreeElement * pResult = 0;
    if (implIsReadOnly(aTree,aTree.getRootNode()))
    {
        OSL_ENSURE(false, "WARNING: Trying to create an 'Update Access' on a read-only tree/node");
        if (!pSetElementTemplate)
        {
             ORootElementGroupInfo * pNewObject = new ORootElementGroupInfo(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             ORootElementSetInfo * pNewObject = new ORootElementSetInfo(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    else
    {
        if (!pSetElementTemplate)
        {
             ORootElementGroupUpdate * pNewObject = new ORootElementGroupUpdate(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else if (pSetElementTemplate->isInstanceValue())
        {
             ORootElementValueSetUpdate * pNewObject = new ORootElementValueSetUpdate(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             ORootElementTreeSetUpdate * pNewObject = new ORootElementTreeSetUpdate(m_rProvider, aTree, _xOptions);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }

    return pResult;
}

//-----------------------------------------------------------------------------
SetElement* UpdateObjectFactory::doCreateSetElement(configuration::ElementTree const& aElementTree, Template* pSetElementTemplate)
{
    OSL_ENSURE(aElementTree.isValid(), "ERROR: trying to create a set element object without a tree");

    Tree aTree( aElementTree.getTree() );
    OSL_ENSURE(!aTree.isEmpty(), "ERROR: trying to create a set element object without a tree");

    ApiTreeImpl * pParentContext = 0;
    UnoInterfaceRef aParentRelease;

    configuration::Tree aParentTree = aTree.getContextTree();
    if (!aParentTree.isEmpty())
    {
        //NodeRef aParentNode = aTree.getContextNode();
        NodeRef aParentRoot = aParentTree.getRootNode();
        if (NodeElement* pParentRootElement = makeElement(aParentTree,aParentRoot) )
        {
            aParentRelease = UnoInterfaceRef(pParentRootElement->getUnoInstance(), uno::UNO_REF_NO_ACQUIRE);
            pParentContext = &getImplementation(*pParentRootElement);
        }
    }

    SetElement * pResult = 0;
    if (implIsReadOnly(aTree,aTree.getRootNode()))
    {
        if (!pSetElementTemplate)
        {
             OSetElementGroupInfo * pNewObject = new OSetElementGroupInfo(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OSetElementSetInfo * pNewObject = new OSetElementSetInfo(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    else
    {
        if (!pSetElementTemplate)
        {
             OSetElementGroupUpdate * pNewObject = new OSetElementGroupUpdate(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else if (pSetElementTemplate->isInstanceValue())
        {
             OSetElementValueSetUpdate * pNewObject = new OSetElementValueSetUpdate(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
        else
        {
             OSetElementTreeSetUpdate * pNewObject = new OSetElementTreeSetUpdate(aTree.getRef(),m_rProvider,pParentContext);
             pNewObject->acquire();
             pResult = &pNewObject->getElementClass();
        }
    }
    return pResult;
}
//-----------------------------------------------------------------------------
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: groupnodeaccess.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-01 13:33:00 $
 *
 *  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 CONFIGMGR_GROUPNODEACCESS_HXX
#define CONFIGMGR_GROUPNODEACCESS_HXX

#ifndef CONFIGMGR_NODEACCESS_HXX
#include "nodeaccess.hxx"
#endif

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace data
    {
    // -------------------------------------------------------------------------
        class GroupNodeAccess
        {
        public:
            typedef NodeAccess::Name        Name;
            typedef NodeAccess::Attributes  Attributes;
            typedef GroupNodeAddress                    NodeAddressType;
            typedef GroupNodeAddress::AddressType       AddressType;
            typedef GroupNodeAddress::DataType const    DataType;
            typedef DataType * NodePointerType;
            typedef NodeAddress                         ChildAddressType;
            typedef NodeAccessRef                       ChildAccessType;

            GroupNodeAccess(Accessor const& _aAccessor, NodeAddressType const& _aNodeRef)
            : m_aAccessor(_aAccessor)
            , m_pData(_aNodeRef.m_pData)
            {}

            GroupNodeAccess(Accessor const& _aAccessor, NodePointerType _pNode)
            : m_aAccessor(_aAccessor)
            , m_pData(check(_aAccessor,_pNode))
            {}

            explicit
            GroupNodeAccess(NodeAccess const & _aNode)
            : m_aAccessor(_aNode.accessor())
            , m_pData(check(_aNode))
            {
            }

            explicit
            GroupNodeAccess(NodeAccessRef const & _aNode)
            : m_aAccessor(_aNode.accessor())
            , m_pData(check(_aNode))
            {
            }

            static bool isInstance(NodeAccessRef const & _aNode)
            {
                return check(_aNode) != NULL;
            }

            bool isValid() const { return m_pData != NULL; }

            Name getName() const;
            Attributes getAttributes() const;

            bool isDefault()   const;

            bool hasChild(Name const& _aName) const
            { return implGetChild(_aName).is(); }

            ChildAccessType getChildNode(Name const& _aName) const
            { return NodeAccessRef(&m_aAccessor, implGetChild(_aName)); }

            NodeAddressType address()   const { return NodeAddressType(m_pData); }
            Accessor const& accessor()  const { return m_aAccessor; }

            operator NodeAccessRef()    const { return NodeAccessRef(&m_aAccessor,NodeAddress(m_pData)); }

            DataType& data() const { return *static_cast<NodePointerType>(m_aAccessor.validate(m_pData)); }

        private:
            static AddressType check(NodeAccessRef const&);
            static AddressType check(Accessor const&, NodePointerType);

            ChildAddressType implGetChild(Name const& _aName) const;

            Accessor    m_aAccessor;
            AddressType m_pData;
        };

        GroupNodeAddress toGroupNodeAddress(memory::Accessor const & _aAccess, NodeAddress const & _aNodeAddr);
        GroupNodeAddress toGroupNodeAddress(memory::UpdateAccessor & _aAccess, NodeAddress const & _aNodeAddr);
    // -------------------------------------------------------------------------
        inline
        NodeAccess::Name GroupNodeAccess::getName() const
        { return NodeAccess::wrapName( data().info.getName(m_aAccessor) ); }

        inline
        NodeAccess::Attributes GroupNodeAccess::getAttributes() const
        { return sharable::node(data()).getAttributes(); }

        inline
        bool GroupNodeAccess::isDefault()   const
        { return data().info.isDefault(); }

    // -------------------------------------------------------------------------
    }
// -----------------------------------------------------------------------------
} // namespace configmgr

#endif // CONFIGMGR_GROUPNODEACCESS_HXX

<commit_msg>INTEGRATION: CWS configapi01 (1.3.4); FILE MERGED 2003/04/14 16:02:15 ssmith 1.3.4.1: #108808# fix for OInnerGroupInfoAccess:XElementAccess<commit_after>/*************************************************************************
 *
 *  $RCSfile: groupnodeaccess.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-17 13:28:49 $
 *
 *  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 CONFIGMGR_GROUPNODEACCESS_HXX
#define CONFIGMGR_GROUPNODEACCESS_HXX

#ifndef CONFIGMGR_NODEACCESS_HXX
#include "nodeaccess.hxx"
#endif

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace data
    {
    // -------------------------------------------------------------------------
        class GroupNodeAccess
        {
        public:
            typedef NodeAccess::Name        Name;
            typedef NodeAccess::Attributes  Attributes;
            typedef GroupNodeAddress                    NodeAddressType;
            typedef GroupNodeAddress::AddressType       AddressType;
            typedef GroupNodeAddress::DataType const    DataType;
            typedef DataType * NodePointerType;
            typedef NodeAddress                         ChildAddressType;
            typedef NodeAccessRef                       ChildAccessType;

            GroupNodeAccess(Accessor const& _aAccessor, NodeAddressType const& _aNodeRef)
            : m_aAccessor(_aAccessor)
            , m_pData(_aNodeRef.m_pData)
            {}

            GroupNodeAccess(Accessor const& _aAccessor, NodePointerType _pNode)
            : m_aAccessor(_aAccessor)
            , m_pData(check(_aAccessor,_pNode))
            {}

            explicit
            GroupNodeAccess(NodeAccess const & _aNode)
            : m_aAccessor(_aNode.accessor())
            , m_pData(check(_aNode))
            {
            }

            explicit
            GroupNodeAccess(NodeAccessRef const & _aNode)
            : m_aAccessor(_aNode.accessor())
            , m_pData(check(_aNode))
            {
            }

            static bool isInstance(NodeAccessRef const & _aNode)
            {
                return check(_aNode) != NULL;
            }

            bool isValid() const { return m_pData != NULL; }

            Name getName() const;
            Attributes getAttributes() const;

            bool isDefault()   const;

            bool hasChild(Name const& _aName) const
            { return implGetChild(_aName).is(); }

            bool hasChildren() const;

            ChildAccessType getChildNode(Name const& _aName) const
            { return NodeAccessRef(&m_aAccessor, implGetChild(_aName)); }

            NodeAddressType address()   const { return NodeAddressType(m_pData); }
            Accessor const& accessor()  const { return m_aAccessor; }

            operator NodeAccessRef()    const { return NodeAccessRef(&m_aAccessor,NodeAddress(m_pData)); }

            DataType& data() const { return *static_cast<NodePointerType>(m_aAccessor.validate(m_pData)); }

        private:
            static AddressType check(NodeAccessRef const&);
            static AddressType check(Accessor const&, NodePointerType);

            ChildAddressType implGetChild(Name const& _aName) const;

            Accessor    m_aAccessor;
            AddressType m_pData;
        };

        GroupNodeAddress toGroupNodeAddress(memory::Accessor const & _aAccess, NodeAddress const & _aNodeAddr);
        GroupNodeAddress toGroupNodeAddress(memory::UpdateAccessor & _aAccess, NodeAddress const & _aNodeAddr);
    // -------------------------------------------------------------------------
        inline
        NodeAccess::Name GroupNodeAccess::getName() const
        { return NodeAccess::wrapName( data().info.getName(m_aAccessor) ); }

        inline
        NodeAccess::Attributes GroupNodeAccess::getAttributes() const
        { return sharable::node(data()).getAttributes(); }

        inline
        bool GroupNodeAccess::isDefault()   const
        { return data().info.isDefault(); }

    // -------------------------------------------------------------------------
    }
// -----------------------------------------------------------------------------
} // namespace configmgr

#endif // CONFIGMGR_GROUPNODEACCESS_HXX

<|endoftext|>


<commit_before>#include "trackmouse.h"
#include <QCursor>
#include <QDebug>

trackMouse::trackMouse(QObject *parent) :
    QThread(parent),
    delay(10),
    track(false),
    running(true),
    lastPosActive(false)
{
}

void trackMouse::end() {
    running = false;
    wait();
    terminate();
}

void trackMouse::enable(const bool enable) {
    track = enable;
}

void trackMouse::detectMove(const bool enable) {
    lastPosActive = enable;
}

void trackMouse::setDelay(const int value) {
    delay = value;
}

void trackMouse::run() {
    QPoint lastPos;
    QPoint currentPost;

    while(running) {
        QThread::msleep(delay);
        currentPost = QCursor::pos();
        if (track == true && (lastPosActive == false || lastPos != currentPost)) {
            lastPos = currentPost;
            emit mousePos(currentPost);
        }
    }
}
<commit_msg>Update trackmouse.cpp<commit_after>/*
qt-helper 0.0.1
Copyright (c) 2014 Guilherme Nascimento (brcontainer@yahoo.com.br)

Released under the MIT license
*/

#include "trackmouse.h"
#include <QCursor>
#include <QDebug>

trackMouse::trackMouse(QObject *parent) :
    QThread(parent),
    delay(10),
    track(false),
    running(true),
    lastPosActive(false)
{
}

void trackMouse::end() {
    running = false;
    wait();
    terminate();
}

void trackMouse::enable(const bool enable) {
    track = enable;
}

void trackMouse::detectMove(const bool enable) {
    lastPosActive = enable;
}

void trackMouse::setDelay(const int value) {
    delay = value;
}

void trackMouse::run() {
    QPoint lastPos;
    QPoint currentPost;

    while(running) {
        QThread::msleep(delay);
        currentPost = QCursor::pos();
        if (track == true && (lastPosActive == false || lastPos != currentPost)) {
            lastPos = currentPost;
            emit mousePos(currentPost);
        }
    }
}
<|endoftext|>


<commit_before>#include "testing/testing.hpp"

#include "routing/cross_routing_context.hpp"

#include "platform/local_country_file.hpp"
#include "platform/local_country_file_utils.hpp"
#include "platform/platform.hpp"

#include "geometry/point2d.hpp"

#include "base/logging.hpp"

#include "std/limits.hpp"

using namespace routing;

namespace
{
UNIT_TEST(CheckCrossSections)
{
  static double constexpr kPointEquality = 0.01;
  vector<platform::LocalCountryFile> localFiles;
  platform::FindAllLocalMapsAndCleanup(numeric_limits<int64_t>::max() /* latestVersion */,
                                       localFiles);

  size_t ingoingErrors = 0;
  size_t outgoingErrors = 0;
  size_t noRouting = 0;
  for (auto & file : localFiles)
  {
    LOG(LINFO, ("Checking cross table for country:", file.GetCountryName()));
    CrossRoutingContextReader crossReader;

    file.SyncWithDisk();
    if (file.GetFiles() != MapOptions::MapWithCarRouting)
    {
      noRouting++;
      LOG(LINFO, ("Warning! Routing file not found for:", file.GetCountryName()));
      continue;
    }
    FilesMappingContainer container(file.GetPath(MapOptions::CarRouting));
    if (!container.IsExist(ROUTING_CROSS_CONTEXT_TAG))
    {
      noRouting++;
      LOG(LINFO, ("Warning! Mwm file has not cross mwm section:", file.GetCountryName()));
      continue;
    }
    crossReader.Load(container.GetReader(ROUTING_CROSS_CONTEXT_TAG));

    bool error = false;
    crossReader.ForEachIngoingNode([&error](IngoingCrossNode const & node)
                                   {
                                     if (node.m_point.EqualDxDy(ms::LatLon::Zero(), kPointEquality))
                                       error = true;
                                   });
    if (error)
      ingoingErrors++;

    error = false;
    crossReader.ForEachOutgoingNode([&error](OutgoingCrossNode const & node)
                                    {
                                      if (node.m_point.EqualDxDy(ms::LatLon::Zero(), kPointEquality))
                                        error = true;
                                    });
    if (error)
      outgoingErrors++;
  }
  TEST_EQUAL(ingoingErrors, 0, ("Some countries have zero point incomes."));
  TEST_EQUAL(outgoingErrors, 0, ("Some countries have zero point exits."));
  LOG(LINFO, ("Found", localFiles.size(), "countries.",
              noRouting, "countries are without routing file."));
}
}  // namespace
<commit_msg>OSRM to features mapping integration test.<commit_after>#include "testing/testing.hpp"

#include "routing/cross_routing_context.hpp"
#include "routing/osrm2feature_map.hpp"
#include "routing/routing_mapping.hpp"

#include "platform/local_country_file.hpp"
#include "platform/local_country_file_utils.hpp"
#include "platform/platform.hpp"

#include "geometry/point2d.hpp"

#include "base/buffer_vector.hpp"
#include "base/logging.hpp"

#include "std/limits.hpp"

using namespace routing;

namespace
{
UNIT_TEST(CheckCrossSections)
{
  static double constexpr kPointEquality = 0.01;
  vector<platform::LocalCountryFile> localFiles;
  platform::FindAllLocalMapsAndCleanup(numeric_limits<int64_t>::max() /* latestVersion */,
                                       localFiles);

  size_t ingoingErrors = 0;
  size_t outgoingErrors = 0;
  size_t noRouting = 0;
  for (auto & file : localFiles)
  {
    LOG(LINFO, ("Checking cross table for country:", file.GetCountryName()));
    CrossRoutingContextReader crossReader;

    file.SyncWithDisk();
    if (file.GetFiles() != MapOptions::MapWithCarRouting)
    {
      noRouting++;
      LOG(LINFO, ("Warning! Routing file not found for:", file.GetCountryName()));
      continue;
    }
    FilesMappingContainer container(file.GetPath(MapOptions::CarRouting));
    if (!container.IsExist(ROUTING_CROSS_CONTEXT_TAG))
    {
      noRouting++;
      LOG(LINFO, ("Warning! Mwm file has not cross mwm section:", file.GetCountryName()));
      continue;
    }
    crossReader.Load(container.GetReader(ROUTING_CROSS_CONTEXT_TAG));

    bool error = false;
    crossReader.ForEachIngoingNode([&error](IngoingCrossNode const & node)
                                   {
                                     if (node.m_point.EqualDxDy(ms::LatLon::Zero(), kPointEquality))
                                       error = true;
                                   });
    if (error)
      ingoingErrors++;

    error = false;
    crossReader.ForEachOutgoingNode([&error](OutgoingCrossNode const & node)
                                    {
                                      if (node.m_point.EqualDxDy(ms::LatLon::Zero(), kPointEquality))
                                        error = true;
                                    });
    if (error)
      outgoingErrors++;
  }
  TEST_EQUAL(ingoingErrors, 0, ("Some countries have zero point incomes."));
  TEST_EQUAL(outgoingErrors, 0, ("Some countries have zero point exits."));
  LOG(LINFO, ("Found", localFiles.size(), "countries.",
              noRouting, "countries are without routing file."));
}

UNIT_TEST(CheckOsrmToFeatureMapping)
{
  vector<platform::LocalCountryFile> localFiles;
  platform::FindAllLocalMapsAndCleanup(numeric_limits<int64_t>::max() /* latestVersion */,
                                       localFiles);

  size_t errors = 0;
  size_t checked = 0;
  for (auto & file : localFiles)
  {
    LOG(LINFO, ("Checking nodes for country:", file.GetCountryName()));

    file.SyncWithDisk();
    if (file.GetFiles() != MapOptions::MapWithCarRouting)
    {
      LOG(LINFO, ("Warning! Routing file not found for:", file.GetCountryName()));
      continue;
    }

    FilesMappingContainer container(file.GetPath(MapOptions::CarRouting));
    if (!container.IsExist(ROUTING_FTSEG_FILE_TAG))
    {
      LOG(LINFO, ("Warning! Mwm file has not routing ftseg section:", file.GetCountryName()));
      continue;
    }
    ++checked;

    routing::TDataFacade dataFacade;
    dataFacade.Load(container);

    OsrmFtSegMapping segMapping;
    segMapping.Load(container, file);
    segMapping.Map(container);

    for (size_t i = 0; i < dataFacade.GetNumberOfNodes(); ++i)
    {
      buffer_vector<OsrmMappingTypes::FtSeg, 8> buffer;
      segMapping.ForEachFtSeg(i, MakeBackInsertFunctor(buffer));
      if (buffer.empty())
      {
        LOG(LINFO, ("Error found in ", file.GetCountryName()));
        errors++;
        break;
      }
    }
  }
  LOG(LINFO, ("Found", localFiles.size(), "countries. In", checked, "maps with routing have", errors, "with errors."));
  TEST_EQUAL(errors, 0, ("Some countries have osrm and features mismatch."));
}
}  // namespace
<|endoftext|>


<commit_before>// DiscreteFourierTransform.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cmath>
#include <iostream>

using namespace std;

// naive implementation of discrete fourier transform
// can be used efficiently for small inputs
void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag);

int _tmain(int argc, _TCHAR* argv[])
{
    double input_real[4];
    double input_imag[4];
    double output_real[4];
    double output_imag[4];
    input_real[0] = 1;
    input_real[1] = 2;
    input_real[2] = 3;
    input_real[3] = 4;
    input_imag[0] = 0;
    input_imag[1] = 0;
    input_imag[2] = 0;
    input_imag[3] = 0;
    discrete_fourier_transform(4, input_real, input_imag, output_real, output_imag);
    for (unsigned int i = 0; i < 4; i++)
    {
        cout << output_real[i] << " + " << output_imag[i] << "j" << endl;
    }
	return 0;
}

void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag)
{
    for (unsigned int k = 0; k < length; k++)
    {
        output_real[k] = 0;
        output_imag[k] = 0;
        for (unsigned int n = 0; n < length; n++)
        {
            double angle = -2 * 3.1415926 / length * n * k;
            double complex_real = cos(angle);
            double complex_imag = sin(angle);
            output_real[k] += input_real[n] * complex_real - input_imag[n] * complex_imag;
            output_imag[k] += input_real[n] * complex_imag + input_imag[n] * complex_real;
        }
    }
}
<commit_msg>Fast Fourier Transform<commit_after>#include <cmath>
#include <iostream>

using namespace std;

#define M_PI 3.1415926

// naive implementation of discrete fourier transform
// can be used efficiently for small inputs
void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag);

// my first implementation of fast fourier transform
// note that length has to be a power of 2
void fast_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag, double* temp_real, double* temp_imag);

int _tmain(int argc, _TCHAR* argv[])q
{
    double input_real[4];
    double input_imag[4];
    double output_real[4];
    double output_imag[4];
    double temp_real[4];
    double temp_imag[4];
    input_real[0] = 1;
    input_real[1] = 2;
    input_real[2] = 3;
    input_real[3] = 4;
    input_imag[0] = 0;
    input_imag[1] = 0;
    input_imag[2] = 0;
    input_imag[3] = 0;
    // discrete_fourier_transform(4, input_real, input_imag, output_real, output_imag);
    fast_fourier_transform(4, input_real, input_imag, output_real, output_imag, temp_real, temp_imag);
    for (unsigned int i = 0; i < 4; i++)
    {
        cout << output_real[i] << " " << output_imag[i] << "j" << endl;
    }
    return 0;
}

void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag)
{
    for (unsigned int k = 0; k < length; k++)
    {
        output_real[k] = 0;
        output_imag[k] = 0;
        for (unsigned int n = 0; n < length; n++)
        {
            double angle = -2 * M_PI / length * n * k;
            double complex_real = cos(angle);
            double complex_imag = sin(angle);
            output_real[k] += input_real[n] * complex_real - input_imag[n] * complex_imag;
            output_imag[k] += input_real[n] * complex_imag + input_imag[n] * complex_real;
        }
    }
}

void fast_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag, double* temp_real, double* temp_imag)
{
    // Step 1: Base case handling
    if (length == 1)
    {
        output_real[0] = input_real[0];
        output_imag[0] = input_imag[0];
        return;
    }

    // Step 1: Decimation in time
    unsigned int half = length / 2;
    for (unsigned int i = 0; i < half; i++)
    {
        temp_real[i] = input_real[2 * i];
        temp_imag[i] = input_imag[2 * i];
        temp_real[i + half] = input_real[2 * i + 1];
        temp_imag[i + half] = input_imag[2 * i + 1];
    }
    for (unsigned int i = 0; i < length; i++)
    {
        input_real[i] = temp_real[i];
        input_imag[i] = temp_imag[i];
    }

    // Step 2: Recursive calls
    fast_fourier_transform(half, input_real       , input_imag       , temp_real       , temp_imag       , output_real       , output_imag       );
    fast_fourier_transform(half, input_real + half, input_imag + half, temp_real + half, temp_imag + half, output_real + half, output_imag + half);

    // Step 3: Merge results
    for (unsigned int i = 0; i < half; i++)
    {
        double angle = -2 * M_PI / length * i;
        double cosine = cos(angle);
        double sine = sin(angle);
        output_real[i]        = temp_real[i] + temp_real[i + half] * cosine - temp_imag[i + half] * sine  ;
        output_imag[i]        = temp_imag[i] + temp_real[i + half] * sine   + temp_imag[i + half] * cosine;
        output_real[i + half] = temp_real[i] - temp_real[i + half] * cosine + temp_imag[i + half] * sine  ;
        output_imag[i + half] = temp_imag[i] - temp_real[i + half] * sine   - temp_imag[i + half] * cosine;
    }
}<|endoftext|>


<commit_before>/* @migen@ */
#include <MI.h>
#include "Container_DaemonEvent_Class_Provider.h"

#include <map>
#include <stdio.h>
#include <string>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include <uuid/uuid.h>
#include <vector>

#include "../cjson/cJSON.h"
#include "../dockerapi/DockerRemoteApi.h"
#include "../dockerapi/DockerRestHelper.h"
#include "Container_ContainerLogFileReader.h"

#define LASTQUERYTIMEFILE "/var/opt/microsoft/docker-cimprov/state/LastEventQueryTime.txt"
#define TEST_LASTQUERYTIMEFILE "./LastEventQueryTime.txt"

using namespace std;

class Guid
{
public:
	///
	/// Create a guid and represent it as string
	///
	static string NewToString()
	{
		uuid_t uuid;
		uuid_generate_random(uuid);
		char s[37];
		uuid_unparse(uuid, s);
		return string(s);
	}
};

MI_BEGIN_NAMESPACE

class EventQuery
{
private:
	///
	/// Utility to get file path for LastEventQueryTime
	///
	static char* GetEventQueryTimeFilePath()
	{
		char* lastQueryFile = LASTQUERYTIMEFILE;
		const char *cTestRun = getenv("CONTAINER_TESTRUN_ACTIVE");
		if (cTestRun != NULL)
		{
			lastQueryFile = TEST_LASTQUERYTIMEFILE;
		}
		return lastQueryFile;
	}

	///
	/// Get the previous time if it was stored, otherwise get the current time
	///
	/// \returns Time of previous query if available
	///
	static int GetPreviousTime()
	{
		int fileTime = time(NULL);
		int currentTime = fileTime;
		char* lastQueryFile = GetEventQueryTimeFilePath();
		FILE* file = fopen(lastQueryFile, "r");

		if (file)
		{
			fscanf(file, "%d", &fileTime);
			fclose(file);

			if (fileTime > currentTime)
			{
				syslog(LOG_WARNING, "The time stored in %s is more recent than the current time", lastQueryFile);
			}
		}
		else
		{
			syslog(LOG_ERR, "Attempt in GetPreviousTime to open %s for reading failed", lastQueryFile);
		}

		// Discard stored times that are more recent than the current time
		return fileTime > currentTime ? currentTime : fileTime;
	}

	///
	/// Write the previous time to disk
	///
	/// \param[in] t The time
	///
	static void SetPreviousTime(int t)
	{
		char* lastQueryFile = GetEventQueryTimeFilePath();
		FILE* file = fopen(lastQueryFile, "w");

		if (file)
		{
			fprintf(file, "%d", t);
			fclose(file);
		}
		else
		{
			syslog(LOG_ERR, "Attempt in SetPreviousTime to open %s for writing failed", lastQueryFile);
		}
	}

	///
	/// Map all container ID to name
	///
	/// \returns Map object
	///
	static map<string, string> MapContainerIdToName()
	{
		map<string, string> result;

		// Request list of containers
		vector<string> request(1, DockerRestHelper::restDockerPs());
		vector<cJSON*> response = getResponse(request);

		// See https://docs.docker.com/engine/reference/api/docker_remote_api_v1.21/#list-containers for example output
		if (!response.empty() && response[0])
		{
			for (int i = 0; i < cJSON_GetArraySize(response[0]); i++)
			{
				cJSON* entry = cJSON_GetArrayItem(response[0], i);

				if (entry)
				{
					cJSON* nameField = cJSON_GetObjectItem(entry, "Names");

					if (nameField && cJSON_GetArraySize(nameField))
					{
						// Docker API documentation says that this field contains the short ID but that is not the case; use full ID instead
						result[string(cJSON_GetObjectItem(entry, "Id")->valuestring)] = string(cJSON_GetArrayItem(nameField, 0)->valuestring + 1);
					}
				}
			}
		}
		else
		{
			syslog(LOG_ERR, "Attempt in MapContainerIdToName to list containers failed");
		}

		return result;
	}

	///
	/// Create symbolic links to /dev/stdout or /dev/stderr in the target containers
	///
	/// \param[in] ids Vector of container IDs
	///
	static void LinkFilesNewContainers(vector<string> ids)
	{
		for (unsigned i = 0; i < ids.size(); i++)
		{
			ContainerLogFileReader::LinkFilesToStream(ids[i]);
		}
	}

public:
	///
	/// Get information about Docker events since the last query
	///
	/// \returns Vector containing objects representing each event
	///
	static vector<Container_DaemonEvent_Class> QueryAll()
	{
		openlog("Container_DaemonEvent", LOG_PID | LOG_NDELAY, LOG_LOCAL1);

		vector<Container_DaemonEvent_Class> result;
		int previousTime = GetPreviousTime();
		int currentTime = time(NULL);

		if (currentTime > previousTime)
		{
			// Get computer name
			char name[256];
			string hostname = gethostname(name, 256) ? "" : string(name);

			// Request events
			vector<string> request(1, DockerRestHelper::restDockerEvents(previousTime, currentTime));
			vector<cJSON*> response = getResponse(request, true);

			// See https://docs.docker.com/reference/api/Container_remote_api_v1.21/#monitor-docker-s-events for example output
			if (!response.empty() && response[0])
			{
				map<string, string> idMap = MapContainerIdToName();
				vector<string> newContainers;

				for (int i = 0; i < cJSON_GetArraySize(response[0]); i++)
				{
					cJSON* entry = cJSON_GetArrayItem(response[0], i);

					// the API may return objects that are not of type container (eg: image, network).
					// Some of these objects do not have status or time keys
					if (entry && !strcmp(cJSON_GetObjectItem(entry, "type")->valuestring, "container"))
					{
						// New inventory entry
						Container_DaemonEvent_Class instance;
						instance.Computer_value(hostname.c_str());
						instance.InstanceID_value(Guid::NewToString().c_str());
						instance.Command_value(cJSON_GetObjectItem(entry, "status")->valuestring);

						char buffer[33];
						snprintf(buffer, 33, "%d", cJSON_GetObjectItem(entry, "time")->valueint);
						instance.TimeOfCommand_value(buffer);

						cJSON* tempImageName = cJSON_GetObjectItem(entry, "from");

						if (tempImageName)
						{
							// Container event
							instance.ElementName_value(tempImageName->valuestring);

							char* id = cJSON_GetObjectItem(entry, "id")->valuestring;
							instance.Id_value(id);
							string idStr = string(id);

							// Get the container name
							if (idMap.count(idStr))
							{
								instance.ContainerName_value(idMap[idStr].c_str());
							}
							else
							{
								syslog(LOG_NOTICE, "No container name found for container %s", id);
							}

							// Add newly created containers to list
							if (!strcmp(cJSON_GetObjectItem(entry, "status")->valuestring, "create"))
							{
								newContainers.push_back(string(id));
							}
						}
						else
						{
							// Image event
							instance.ElementName_value(cJSON_GetObjectItem(entry, "id")->valuestring);
							instance.Id_value("");
							instance.ContainerName_value("");
						}

						result.push_back(instance);
					}
					else
					{
						syslog(LOG_WARNING, "Attempt in QueryAll to get element %d of event list returned null", i);
					}
				}

				LinkFilesNewContainers(newContainers);

				// Clean up object
				cJSON_Delete(response[0]);
			}
			else
			{
				syslog(LOG_ERR, "Attempt in QueryAll to get Docker events failed");
			}
		}

		SetPreviousTime(currentTime);
		closelog();
		return result;
	}
};

#ifdef _MSC_VER
#pragma region
#endif

Container_DaemonEvent_Class_Provider::Container_DaemonEvent_Class_Provider(Module* module) : m_Module(module){}

Container_DaemonEvent_Class_Provider::~Container_DaemonEvent_Class_Provider(){}

void Container_DaemonEvent_Class_Provider::Load(Context& context)
{
	context.Post(MI_RESULT_OK);
}

void Container_DaemonEvent_Class_Provider::Unload(Context& context)
{
	context.Post(MI_RESULT_OK);
}

void Container_DaemonEvent_Class_Provider::EnumerateInstances(Context& context, const String& nameSpace, const PropertySet& propertySet, bool keysOnly, const MI_Filter* filter)
{
	vector<Container_DaemonEvent_Class> queryResult = EventQuery::QueryAll();

	for (unsigned i = 0; i < queryResult.size(); i++)
	{
		context.Post(queryResult[i]);
	}

	context.Post(MI_RESULT_OK);
}

void Container_DaemonEvent_Class_Provider::GetInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& instanceName, const PropertySet& propertySet)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

void Container_DaemonEvent_Class_Provider::CreateInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& newInstance)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

void Container_DaemonEvent_Class_Provider::ModifyInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& modifiedInstance, const PropertySet& propertySet)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

void Container_DaemonEvent_Class_Provider::DeleteInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& instanceName)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

#ifdef _MSC_VER
#pragma endregion
#endif

MI_END_NAMESPACE<commit_msg>Eliminate new compiler warnings from prior checkin<commit_after>/* @migen@ */
#include <MI.h>
#include "Container_DaemonEvent_Class_Provider.h"

#include <map>
#include <stdio.h>
#include <string>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include <uuid/uuid.h>
#include <vector>

#include "../cjson/cJSON.h"
#include "../dockerapi/DockerRemoteApi.h"
#include "../dockerapi/DockerRestHelper.h"
#include "Container_ContainerLogFileReader.h"

#define LASTQUERYTIMEFILE "/var/opt/microsoft/docker-cimprov/state/LastEventQueryTime.txt"
#define TEST_LASTQUERYTIMEFILE "./LastEventQueryTime.txt"

using namespace std;

class Guid
{
public:
	///
	/// Create a guid and represent it as string
	///
	static string NewToString()
	{
		uuid_t uuid;
		uuid_generate_random(uuid);
		char s[37];
		uuid_unparse(uuid, s);
		return string(s);
	}
};

MI_BEGIN_NAMESPACE

class EventQuery
{
private:
	///
	/// Utility to get file path for LastEventQueryTime
	///
	static const char* GetEventQueryTimeFilePath()
	{
		const char *cTestRun = getenv("CONTAINER_TESTRUN_ACTIVE");
		if (cTestRun != NULL)
		{
			return TEST_LASTQUERYTIMEFILE;
		}
		else
		{
			return LASTQUERYTIMEFILE;
		}
	}

	///
	/// Get the previous time if it was stored, otherwise get the current time
	///
	/// \returns Time of previous query if available
	///
	static int GetPreviousTime()
	{
		int fileTime = time(NULL);
		int currentTime = fileTime;
		const char* lastQueryFile = GetEventQueryTimeFilePath();
		FILE* file = fopen(lastQueryFile, "r");

		if (file)
		{
			fscanf(file, "%d", &fileTime);
			fclose(file);

			if (fileTime > currentTime)
			{
				syslog(LOG_WARNING, "The time stored in %s is more recent than the current time", lastQueryFile);
			}
		}
		else
		{
			syslog(LOG_ERR, "Attempt in GetPreviousTime to open %s for reading failed", lastQueryFile);
		}

		// Discard stored times that are more recent than the current time
		return fileTime > currentTime ? currentTime : fileTime;
	}

	///
	/// Write the previous time to disk
	///
	/// \param[in] t The time
	///
	static void SetPreviousTime(int t)
	{
		const char* lastQueryFile = GetEventQueryTimeFilePath();
		FILE* file = fopen(lastQueryFile, "w");

		if (file)
		{
			fprintf(file, "%d", t);
			fclose(file);
		}
		else
		{
			syslog(LOG_ERR, "Attempt in SetPreviousTime to open %s for writing failed", lastQueryFile);
		}
	}

	///
	/// Map all container ID to name
	///
	/// \returns Map object
	///
	static map<string, string> MapContainerIdToName()
	{
		map<string, string> result;

		// Request list of containers
		vector<string> request(1, DockerRestHelper::restDockerPs());
		vector<cJSON*> response = getResponse(request);

		// See https://docs.docker.com/engine/reference/api/docker_remote_api_v1.21/#list-containers for example output
		if (!response.empty() && response[0])
		{
			for (int i = 0; i < cJSON_GetArraySize(response[0]); i++)
			{
				cJSON* entry = cJSON_GetArrayItem(response[0], i);

				if (entry)
				{
					cJSON* nameField = cJSON_GetObjectItem(entry, "Names");

					if (nameField && cJSON_GetArraySize(nameField))
					{
						// Docker API documentation says that this field contains the short ID but that is not the case; use full ID instead
						result[string(cJSON_GetObjectItem(entry, "Id")->valuestring)] = string(cJSON_GetArrayItem(nameField, 0)->valuestring + 1);
					}
				}
			}
		}
		else
		{
			syslog(LOG_ERR, "Attempt in MapContainerIdToName to list containers failed");
		}

		return result;
	}

	///
	/// Create symbolic links to /dev/stdout or /dev/stderr in the target containers
	///
	/// \param[in] ids Vector of container IDs
	///
	static void LinkFilesNewContainers(vector<string> ids)
	{
		for (unsigned i = 0; i < ids.size(); i++)
		{
			ContainerLogFileReader::LinkFilesToStream(ids[i]);
		}
	}

public:
	///
	/// Get information about Docker events since the last query
	///
	/// \returns Vector containing objects representing each event
	///
	static vector<Container_DaemonEvent_Class> QueryAll()
	{
		openlog("Container_DaemonEvent", LOG_PID | LOG_NDELAY, LOG_LOCAL1);

		vector<Container_DaemonEvent_Class> result;
		int previousTime = GetPreviousTime();
		int currentTime = time(NULL);

		if (currentTime > previousTime)
		{
			// Get computer name
			char name[256];
			string hostname = gethostname(name, 256) ? "" : string(name);

			// Request events
			vector<string> request(1, DockerRestHelper::restDockerEvents(previousTime, currentTime));
			vector<cJSON*> response = getResponse(request, true);

			// See https://docs.docker.com/reference/api/Container_remote_api_v1.21/#monitor-docker-s-events for example output
			if (!response.empty() && response[0])
			{
				map<string, string> idMap = MapContainerIdToName();
				vector<string> newContainers;

				for (int i = 0; i < cJSON_GetArraySize(response[0]); i++)
				{
					cJSON* entry = cJSON_GetArrayItem(response[0], i);

					// the API may return objects that are not of type container (eg: image, network).
					// Some of these objects do not have status or time keys
					if (entry && !strcmp(cJSON_GetObjectItem(entry, "type")->valuestring, "container"))
					{
						// New inventory entry
						Container_DaemonEvent_Class instance;
						instance.Computer_value(hostname.c_str());
						instance.InstanceID_value(Guid::NewToString().c_str());
						instance.Command_value(cJSON_GetObjectItem(entry, "status")->valuestring);

						char buffer[33];
						snprintf(buffer, 33, "%d", cJSON_GetObjectItem(entry, "time")->valueint);
						instance.TimeOfCommand_value(buffer);

						cJSON* tempImageName = cJSON_GetObjectItem(entry, "from");

						if (tempImageName)
						{
							// Container event
							instance.ElementName_value(tempImageName->valuestring);

							char* id = cJSON_GetObjectItem(entry, "id")->valuestring;
							instance.Id_value(id);
							string idStr = string(id);

							// Get the container name
							if (idMap.count(idStr))
							{
								instance.ContainerName_value(idMap[idStr].c_str());
							}
							else
							{
								syslog(LOG_NOTICE, "No container name found for container %s", id);
							}

							// Add newly created containers to list
							if (!strcmp(cJSON_GetObjectItem(entry, "status")->valuestring, "create"))
							{
								newContainers.push_back(string(id));
							}
						}
						else
						{
							// Image event
							instance.ElementName_value(cJSON_GetObjectItem(entry, "id")->valuestring);
							instance.Id_value("");
							instance.ContainerName_value("");
						}

						result.push_back(instance);
					}
					else
					{
						syslog(LOG_WARNING, "Attempt in QueryAll to get element %d of event list returned null", i);
					}
				}

				LinkFilesNewContainers(newContainers);

				// Clean up object
				cJSON_Delete(response[0]);
			}
			else
			{
				syslog(LOG_ERR, "Attempt in QueryAll to get Docker events failed");
			}
		}

		SetPreviousTime(currentTime);
		closelog();
		return result;
	}
};

#ifdef _MSC_VER
#pragma region
#endif

Container_DaemonEvent_Class_Provider::Container_DaemonEvent_Class_Provider(Module* module) : m_Module(module){}

Container_DaemonEvent_Class_Provider::~Container_DaemonEvent_Class_Provider(){}

void Container_DaemonEvent_Class_Provider::Load(Context& context)
{
	context.Post(MI_RESULT_OK);
}

void Container_DaemonEvent_Class_Provider::Unload(Context& context)
{
	context.Post(MI_RESULT_OK);
}

void Container_DaemonEvent_Class_Provider::EnumerateInstances(Context& context, const String& nameSpace, const PropertySet& propertySet, bool keysOnly, const MI_Filter* filter)
{
	vector<Container_DaemonEvent_Class> queryResult = EventQuery::QueryAll();

	for (unsigned i = 0; i < queryResult.size(); i++)
	{
		context.Post(queryResult[i]);
	}

	context.Post(MI_RESULT_OK);
}

void Container_DaemonEvent_Class_Provider::GetInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& instanceName, const PropertySet& propertySet)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

void Container_DaemonEvent_Class_Provider::CreateInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& newInstance)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

void Container_DaemonEvent_Class_Provider::ModifyInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& modifiedInstance, const PropertySet& propertySet)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

void Container_DaemonEvent_Class_Provider::DeleteInstance(Context& context, const String& nameSpace, const Container_DaemonEvent_Class& instanceName)
{
	context.Post(MI_RESULT_NOT_SUPPORTED);
}

#ifdef _MSC_VER
#pragma endregion
#endif

MI_END_NAMESPACE<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: FTables.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: oj $ $Date: 2002-07-05 08:07:50 $
 *
 *  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_FILE_TABLES_HXX_
#define _CONNECTIVITY_FILE_TABLES_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif

namespace connectivity
{
    namespace file
    {
        class SAL_NO_VTABLE OTables : public sdbcx::OCollection
        {
        protected:
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >   m_xMetaData;

            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed > createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
        public:
            OTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex,
                const TStringVector &_rVector) : sdbcx::OCollection(_rParent,_rMetaData->storesMixedCaseQuotedIdentifiers(),_rMutex,_rVector)
                ,m_xMetaData(_rMetaData)
            {}

            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);

            // only the name is identical to ::cppu::OComponentHelper
            virtual void SAL_CALL disposing(void);
        };
    }
}
#endif // _CONNECTIVITY_FILE_TABLES_HXX_

<commit_msg>INTEGRATION: CWS dba24 (1.6.246); FILE MERGED 2005/02/09 08:07:55 oj 1.6.246.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
 *
 *  $RCSfile: FTables.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 15:39:33 $
 *
 *  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_FILE_TABLES_HXX_
#define _CONNECTIVITY_FILE_TABLES_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif

namespace connectivity
{
    namespace file
    {
        class SAL_NO_VTABLE OTables : public sdbcx::OCollection
        {
        protected:
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >   m_xMetaData;

            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
        public:
            OTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex,
                const TStringVector &_rVector) : sdbcx::OCollection(_rParent,_rMetaData->storesMixedCaseQuotedIdentifiers(),_rMutex,_rVector)
                ,m_xMetaData(_rMetaData)
            {}

            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);

            // only the name is identical to ::cppu::OComponentHelper
            virtual void SAL_CALL disposing(void);
        };
    }
}
#endif // _CONNECTIVITY_FILE_TABLES_HXX_

<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "query.h"
#include "blueprintbuilder.h"
#include "matchdatareservevisitor.h"
#include "resolveviewvisitor.h"
#include "termdataextractor.h"
#include "sameelementmodifier.h"
#include <vespa/document/datatype/positiondatatype.h>
#include <vespa/searchlib/common/location.h>
#include <vespa/searchlib/parsequery/stackdumpiterator.h>
#include <vespa/searchlib/query/tree/point.h>
#include <vespa/searchlib/query/tree/rectangle.h>
#include <vespa/searchlib/queryeval/intermediate_blueprints.h>

#include <vespa/log/log.h>
LOG_SETUP(".proton.matching.query");
#include <vespa/searchlib/query/tree/querytreecreator.h>

using document::PositionDataType;
using search::SimpleQueryStackDumpIterator;
using search::fef::IIndexEnvironment;
using search::fef::ITermData;
using search::fef::MatchData;
using search::fef::MatchDataLayout;
using search::fef::Location;
using search::query::Node;
using search::query::QueryTreeCreator;
using search::query::Weight;
using search::queryeval::AndBlueprint;
using search::queryeval::Blueprint;
using search::queryeval::IRequestContext;
using search::queryeval::SearchIterator;
using vespalib::string;
using std::vector;

namespace proton::matching {

namespace {
void AddLocationNode(const string &location_str, Node::UP &query_tree, Location &fef_location) {
    if (location_str.empty()) {
        return;
    }
    string::size_type pos = location_str.find(':');
    if (pos == string::npos) {
        LOG(warning, "Location string lacks attribute vector specification. loc='%s'", location_str.c_str());
        return;
    }
    const string view = PositionDataType::getZCurveFieldName(location_str.substr(0, pos));
    const string loc = location_str.substr(pos + 1);

    search::common::Location locationSpec;
    if (!locationSpec.parse(loc)) {
        LOG(warning, "Location parse error (location: '%s'): %s", location_str.c_str(), locationSpec.getParseError());
        return;
    }

    int32_t id = -1;
    Weight weight(100);

    auto new_base = std::make_unique<ProtonAnd>();
    new_base->append(std::move(query_tree));

    if (locationSpec.getRankOnDistance()) {
        new_base->append(std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
        fef_location.setAttribute(view);
        fef_location.setXPosition(locationSpec.getX());
        fef_location.setYPosition(locationSpec.getY());
        fef_location.setXAspect(locationSpec.getXAspect());
        fef_location.setValid(true);
    } else if (locationSpec.getPruneOnDistance()) {
        new_base->append(std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
    }
    query_tree = std::move(new_base);
}
}  // namespace

Query::Query() = default;
Query::~Query() = default;

bool
Query::buildTree(const vespalib::stringref &stack, const string &location,
                 const ViewResolver &resolver, const IIndexEnvironment &indexEnv)
{
    SimpleQueryStackDumpIterator stack_dump_iterator(stack);
    _query_tree = QueryTreeCreator<ProtonNodeTypes>::create(stack_dump_iterator);
    if (_query_tree) {
        SameElementModifier prefixSameElementSubIndexes;
        _query_tree->accept(prefixSameElementSubIndexes);
        AddLocationNode(location, _query_tree, _location);
        ResolveViewVisitor resolve_visitor(resolver, indexEnv);
        _query_tree->accept(resolve_visitor);
        return true;
    } else {
        // TODO(havardpe): log warning or pass message upwards
        return false;
    }
}

void
Query::extractTerms(vector<const ITermData *> &terms)
{
    TermDataExtractor::extractTerms(*_query_tree, terms);
}

void
Query::extractLocations(vector<const Location *> &locations)
{
    locations.clear();
    locations.push_back(&_location);
}

void
Query::setWhiteListBlueprint(Blueprint::UP whiteListBlueprint)
{
    _whiteListBlueprint = std::move(whiteListBlueprint);
}

void
Query::reserveHandles(const IRequestContext & requestContext, ISearchContext &context, MatchDataLayout &mdl)
{
    MatchDataReserveVisitor reserve_visitor(mdl);
    _query_tree->accept(reserve_visitor);

    _blueprint = BlueprintBuilder::build(requestContext, *_query_tree, context);
    LOG(debug, "original blueprint:\n%s\n", _blueprint->asString().c_str());
    if (_whiteListBlueprint) {
        auto andBlueprint = std::make_unique<AndBlueprint>();
        if (dynamic_cast<const search::queryeval::RankBlueprint*>(_blueprint.get())) {
            search::queryeval::RankBlueprint * rank = static_cast<search::queryeval::RankBlueprint*>(_blueprint.get());
            (*andBlueprint)
                    .addChild(rank->removeChild(0))
                    .addChild(std::move(_whiteListBlueprint));
            rank->insertChild(0, std::move(andBlueprint));
        } else {
            (*andBlueprint)
                    .addChild(std::move(_blueprint))
                    .addChild(std::move(_whiteListBlueprint));
            _blueprint = std::move(andBlueprint);
        }
        _blueprint->setDocIdLimit(context.getDocIdLimit());
        LOG(debug, "blueprint after white listing:\n%s\n", _blueprint->asString().c_str());
    }
}

void
Query::optimize()
{
    _blueprint = Blueprint::optimize(std::move(_blueprint));
    LOG(debug, "optimized blueprint:\n%s\n", _blueprint->asString().c_str());
}

void
Query::fetchPostings()
{
    _blueprint->fetchPostings(true);
}

void
Query::freeze()
{
    _blueprint->freeze();
}

Blueprint::HitEstimate
Query::estimate() const
{
    return _blueprint->getState().estimate();
}

SearchIterator::UP
Query::createSearch(MatchData &md) const
{
    return _blueprint->createSearch(md, true);
}

}
<commit_msg>Only necessary to do the cast once.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "query.h"
#include "blueprintbuilder.h"
#include "matchdatareservevisitor.h"
#include "resolveviewvisitor.h"
#include "termdataextractor.h"
#include "sameelementmodifier.h"
#include <vespa/document/datatype/positiondatatype.h>
#include <vespa/searchlib/common/location.h>
#include <vespa/searchlib/parsequery/stackdumpiterator.h>
#include <vespa/searchlib/query/tree/point.h>
#include <vespa/searchlib/query/tree/rectangle.h>
#include <vespa/searchlib/queryeval/intermediate_blueprints.h>

#include <vespa/log/log.h>
LOG_SETUP(".proton.matching.query");
#include <vespa/searchlib/query/tree/querytreecreator.h>

using document::PositionDataType;
using search::SimpleQueryStackDumpIterator;
using search::fef::IIndexEnvironment;
using search::fef::ITermData;
using search::fef::MatchData;
using search::fef::MatchDataLayout;
using search::fef::Location;
using search::query::Node;
using search::query::QueryTreeCreator;
using search::query::Weight;
using search::queryeval::AndBlueprint;
using search::queryeval::RankBlueprint;
using search::queryeval::Blueprint;
using search::queryeval::IRequestContext;
using search::queryeval::SearchIterator;
using vespalib::string;
using std::vector;

namespace proton::matching {

namespace {
void AddLocationNode(const string &location_str, Node::UP &query_tree, Location &fef_location) {
    if (location_str.empty()) {
        return;
    }
    string::size_type pos = location_str.find(':');
    if (pos == string::npos) {
        LOG(warning, "Location string lacks attribute vector specification. loc='%s'", location_str.c_str());
        return;
    }
    const string view = PositionDataType::getZCurveFieldName(location_str.substr(0, pos));
    const string loc = location_str.substr(pos + 1);

    search::common::Location locationSpec;
    if (!locationSpec.parse(loc)) {
        LOG(warning, "Location parse error (location: '%s'): %s", location_str.c_str(), locationSpec.getParseError());
        return;
    }

    int32_t id = -1;
    Weight weight(100);

    auto new_base = std::make_unique<ProtonAnd>();
    new_base->append(std::move(query_tree));

    if (locationSpec.getRankOnDistance()) {
        new_base->append(std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
        fef_location.setAttribute(view);
        fef_location.setXPosition(locationSpec.getX());
        fef_location.setYPosition(locationSpec.getY());
        fef_location.setXAspect(locationSpec.getXAspect());
        fef_location.setValid(true);
    } else if (locationSpec.getPruneOnDistance()) {
        new_base->append(std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
    }
    query_tree = std::move(new_base);
}
}  // namespace

Query::Query() = default;
Query::~Query() = default;

bool
Query::buildTree(const vespalib::stringref &stack, const string &location,
                 const ViewResolver &resolver, const IIndexEnvironment &indexEnv)
{
    SimpleQueryStackDumpIterator stack_dump_iterator(stack);
    _query_tree = QueryTreeCreator<ProtonNodeTypes>::create(stack_dump_iterator);
    if (_query_tree) {
        SameElementModifier prefixSameElementSubIndexes;
        _query_tree->accept(prefixSameElementSubIndexes);
        AddLocationNode(location, _query_tree, _location);
        ResolveViewVisitor resolve_visitor(resolver, indexEnv);
        _query_tree->accept(resolve_visitor);
        return true;
    } else {
        // TODO(havardpe): log warning or pass message upwards
        return false;
    }
}

void
Query::extractTerms(vector<const ITermData *> &terms)
{
    TermDataExtractor::extractTerms(*_query_tree, terms);
}

void
Query::extractLocations(vector<const Location *> &locations)
{
    locations.clear();
    locations.push_back(&_location);
}

void
Query::setWhiteListBlueprint(Blueprint::UP whiteListBlueprint)
{
    _whiteListBlueprint = std::move(whiteListBlueprint);
}

void
Query::reserveHandles(const IRequestContext & requestContext, ISearchContext &context, MatchDataLayout &mdl)
{
    MatchDataReserveVisitor reserve_visitor(mdl);
    _query_tree->accept(reserve_visitor);

    _blueprint = BlueprintBuilder::build(requestContext, *_query_tree, context);
    LOG(debug, "original blueprint:\n%s\n", _blueprint->asString().c_str());
    if (_whiteListBlueprint) {
        auto andBlueprint = std::make_unique<AndBlueprint>();
        RankBlueprint * rank = dynamic_cast<RankBlueprint*>(_blueprint.get());
        if (rank != nullptr) {
            (*andBlueprint)
                    .addChild(rank->removeChild(0))
                    .addChild(std::move(_whiteListBlueprint));
            rank->insertChild(0, std::move(andBlueprint));
        } else {
            (*andBlueprint)
                    .addChild(std::move(_blueprint))
                    .addChild(std::move(_whiteListBlueprint));
            _blueprint = std::move(andBlueprint);
        }
        _blueprint->setDocIdLimit(context.getDocIdLimit());
        LOG(debug, "blueprint after white listing:\n%s\n", _blueprint->asString().c_str());
    }
}

void
Query::optimize()
{
    _blueprint = Blueprint::optimize(std::move(_blueprint));
    LOG(debug, "optimized blueprint:\n%s\n", _blueprint->asString().c_str());
}

void
Query::fetchPostings()
{
    _blueprint->fetchPostings(true);
}

void
Query::freeze()
{
    _blueprint->freeze();
}

Blueprint::HitEstimate
Query::estimate() const
{
    return _blueprint->getState().estimate();
}

SearchIterator::UP
Query::createSearch(MatchData &md) const
{
    return _blueprint->createSearch(md, true);
}

}
<|endoftext|>