<commit_before>/*************************************************************************
 *
 *  $RCSfile: EventOASISTContext.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:48:41 $
 *
 *  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 _XMLOFF_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif

#include <hash_map>

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;

class XMLTransformerOASISEventMap_Impl:
    public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
                            NameHash_Impl, NameHash_Impl >
{
public:
    XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
    ~XMLTransformerOASISEventMap_Impl();
};

XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
    if( pInit )
    {
        XMLTransformerOASISEventMap_Impl::key_type aKey;
        XMLTransformerOASISEventMap_Impl::data_type aData;
        while( pInit->m_pOASISName )
        {
            aKey.m_nPrefix = pInit->m_nOASISPrefix;
            aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);

            OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );

            aData = OUString::createFromAscii(pInit->m_pOOoName);

            XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );

            insert( aVal );
            ++pInit;
        }
    }
}

XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}

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

TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);

XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
        XMLTransformerBase& rImp,
        const OUString& rQName ) :
    XMLRenameElemTransformerContext( rImp, rQName,
         rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}

XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}

XMLTransformerOASISEventMap_Impl
    *XMLEventOASISTransformerContext::CreateEventMap()
{
    return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}

void XMLEventOASISTransformerContext::FlushEventMap(
        XMLTransformerOASISEventMap_Impl *p )
{
    delete p;
}

OUString XMLEventOASISTransformerContext::GetEventName(
        sal_uInt16 nPrefix,
        const OUString& rName,
           XMLTransformerOASISEventMap_Impl& rMap )
{
    XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
    XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
    if( aIter == rMap.end() )
        return rName;
    else
        return (*aIter).second;
}

void XMLEventOASISTransformerContext::StartElement(
    const Reference< XAttributeList >& rAttrList )
{
    XMLTransformerActions *pActions =
        GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
    OSL_ENSURE( pActions, "go no actions" );

    Reference< XAttributeList > xAttrList( rAttrList );
    XMLMutableAttributeList *pMutableAttrList = 0;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix =
            GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
                                                                 &aLocalName );
        XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
        XMLTransformerActions::const_iterator aIter =
            pActions->find( aKey );
        if( !(aIter == pActions->end() ) )
        {
            if( !pMutableAttrList )
            {
                pMutableAttrList =
                        new XMLMutableAttributeList( xAttrList );
                xAttrList = pMutableAttrList;
            }
            const OUString& rAttrValue = xAttrList->getValueByIndex( i );
            switch( (*aIter).second.m_nActionType )
            {
            case XML_ATACTION_HREF:
                // TODO
                break;
            case XML_ATACTION_EVENT_NAME:
                pMutableAttrList->SetValueByIndex( i,
                               GetTransformer().GetEventName( rAttrValue ) );
                break;
            case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
                {
                    OUString aAttrValue( rAttrValue );
                    sal_uInt16 nValPrefix =
                        static_cast<sal_uInt16>((*aIter).second.m_nParam1);
                    if( GetTransformer().RemoveNamespacePrefix(
                                aAttrValue, nValPrefix ) )
                        pMutableAttrList->SetValueByIndex( i, aAttrValue );
                }
                break;
            case XML_ATACTION_MACRO_NAME:
                {
                    const OUString& rApp = GetXMLToken( XML_APPLICATION );
                    const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
                    OUString aLocation;
                    OUString aAttrValue;
                    if( rAttrValue.getLength() > rApp.getLength()+1 &&
                        rAttrValue.copy(0,rApp.getLength()).
                                    equalsIgnoreAsciiCase( rApp ) &&
                        ':' == rAttrValue[rApp.getLength()] )
                    {
                        aLocation = rApp;
                        aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
                    }
                    else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
                             rAttrValue.copy(0,rDoc.getLength()).
                                     equalsIgnoreAsciiCase( rDoc ) &&
                        ':' == rAttrValue[rDoc.getLength()] )
                    {
                        aLocation= rDoc;
                        aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
                    }
                    if( aAttrValue.getLength() )
                        pMutableAttrList->SetValueByIndex( i,
                                            aAttrValue );
                    if( aLocation.getLength() )
                    {
                        OUString aAttrQName( GetTransformer().GetNamespaceMap().
                                GetQNameByKey( XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                        // draw bug
                        aAttrQName = GetTransformer().GetNamespaceMap().
                                GetQNameByKey( XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_LIBRARY ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                    }

                }
                break;
            case XML_ATACTION_COPY:
                break;
            default:
                OSL_ENSURE( !this, "unknown action" );
                break;
            }
        }
    }

    XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<commit_msg>INTEGRATION: CWS oasisbf1 (1.2.38); FILE MERGED 2004/09/16 10:35:54 toconnor 1.2.38.3: #i33735# - add conditional compilation of UNO URL parsing code 2004/09/14 17:07:35 toconnor 1.2.38.2: #i33735# export of bindings to Scripting Framework macros and dlg:border attributes from Oasis to OOo 2004/08/18 12:53:13 mib 1.2.38.1: #i32840#: some form events had different names<commit_after>/*************************************************************************
 *
 *  $RCSfile: EventOASISTContext.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:21:53 $
 *
 *  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 _XMLOFF_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif

#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif

#include <hash_map>

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;

class XMLTransformerOASISEventMap_Impl:
    public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
                            NameHash_Impl, NameHash_Impl >
{
public:
    XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
    ~XMLTransformerOASISEventMap_Impl();
};

XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
    if( pInit )
    {
        XMLTransformerOASISEventMap_Impl::key_type aKey;
        XMLTransformerOASISEventMap_Impl::data_type aData;
        while( pInit->m_pOASISName )
        {
            aKey.m_nPrefix = pInit->m_nOASISPrefix;
            aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);

            OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );

            aData = OUString::createFromAscii(pInit->m_pOOoName);

            XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );

            insert( aVal );
            ++pInit;
        }
    }
}

XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}

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

TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);

XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
        XMLTransformerBase& rImp,
        const OUString& rQName ) :
    XMLRenameElemTransformerContext( rImp, rQName,
         rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}

XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}

XMLTransformerOASISEventMap_Impl
    *XMLEventOASISTransformerContext::CreateEventMap()
{
    return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}

XMLTransformerOASISEventMap_Impl
    *XMLEventOASISTransformerContext::CreateFormEventMap()
{
    return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}

void XMLEventOASISTransformerContext::FlushEventMap(
        XMLTransformerOASISEventMap_Impl *p )
{
    delete p;
}

OUString XMLEventOASISTransformerContext::GetEventName(
        sal_uInt16 nPrefix,
        const OUString& rName,
           XMLTransformerOASISEventMap_Impl& rMap,
           XMLTransformerOASISEventMap_Impl *pMap2)
{
    XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
    if( pMap2 )
    {
        XMLTransformerOASISEventMap_Impl::const_iterator aIter =
            pMap2->find( aKey );
        if( !(aIter == pMap2->end()) )
            return (*aIter).second;
    }

    XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
    if( aIter == rMap.end() )
        return rName;
    else
        return (*aIter).second;
}

bool ParseURLAsString(
    const OUString& rAttrValue,
    OUString* pName, OUString* pLocation )
{
    OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );

    sal_Int32 params = rAttrValue.indexOf( '?' );
    if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
    {
        return FALSE;
    }

    sal_Int32 start = SCHEME.getLength();
    *pName = rAttrValue.copy( start, params - start );

    OUString aToken;
    OUString aLanguage;
    params++;
    do
    {
        aToken = rAttrValue.getToken( 0, '&', params );
        sal_Int32 dummy = 0;

        if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
        {
            aLanguage = aToken.getToken( 1, '=', dummy );
        }
        else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
        {
            OUString tmp = aToken.getToken( 1, '=', dummy );
            if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
            {
                *pLocation = GetXMLToken( XML_DOCUMENT );
            }
            else
            {
                *pLocation = GetXMLToken( XML_APPLICATION );
            }
        }
    } while ( params >= 0 );

    if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
    {
        return TRUE;
    }
    return FALSE;
}

bool ParseURL(
    const OUString& rAttrValue,
    OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
    return ParseURLAsString( rAttrValue, pName, pLocation );
#else
    Reference< com::sun::star::lang::XMultiServiceFactory >
        xSMgr = ::comphelper::getProcessServiceFactory();

    Reference< com::sun::star::uri::XUriReferenceFactory >
        xFactory( xSMgr->createInstance( OUString::createFromAscii(
            "com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );

    if ( xFactory.is() )
    {
        Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
            xFactory->parse( rAttrValue ), UNO_QUERY );

        if ( xUrl.is() )
        {
            OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
            if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
            {
                OUString aLanguage = xUrl->getParameter( aLanguageKey );

                if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
                {
                    *pName = xUrl->getName();

                    OUString tmp =
                        xUrl->getParameter( GetXMLToken( XML_LOCATION ) );

                    OUString doc = GetXMLToken( XML_DOCUMENT );

                    if ( tmp.equalsIgnoreAsciiCase( doc ) )
                    {
                        *pLocation = doc;
                    }
                    else
                    {
                        *pLocation = GetXMLToken( XML_APPLICATION );
                    }
                    return TRUE;
                }
            }
        }
        return FALSE;
    }
    else
    {
        return ParseURLAsString( rAttrValue, pName, pLocation );
    }
#endif
}

void XMLEventOASISTransformerContext::StartElement(
    const Reference< XAttributeList >& rAttrList )
{
    XMLTransformerActions *pActions =
        GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
    OSL_ENSURE( pActions, "go no actions" );

    Reference< XAttributeList > xAttrList( rAttrList );
    XMLMutableAttributeList *pMutableAttrList = 0;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix =
            GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
                                                                 &aLocalName );
        XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
        XMLTransformerActions::const_iterator aIter =
            pActions->find( aKey );
        if( !(aIter == pActions->end() ) )
        {
            if( !pMutableAttrList )
            {
                pMutableAttrList =
                        new XMLMutableAttributeList( xAttrList );
                xAttrList = pMutableAttrList;
            }
            const OUString& rAttrValue = xAttrList->getValueByIndex( i );
            switch( (*aIter).second.m_nActionType )
            {
            case XML_ATACTION_HREF:
                {
                    OUString aAttrValue( rAttrValue );
                    OUString aName, aLocation;

                    bool bNeedsTransform =
                        ParseURL( rAttrValue, &aName, &aLocation );

                    if ( bNeedsTransform )
                    {
                        pMutableAttrList->RemoveAttributeByIndex( i );

                        OUString aAttrQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );

                        pMutableAttrList->AddAttribute( aAttrQName, aName );

                        sal_Int16 idx = pMutableAttrList->GetIndexByName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            GetXMLToken( XML_LANGUAGE ) ) );

                        pMutableAttrList->SetValueByIndex( idx,
                            OUString::createFromAscii("StarBasic") );

                        OUString aLocQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                                GetXMLToken( XML_LOCATION ) ) );

                        pMutableAttrList->AddAttribute( aLocQName, aLocation );
                    }
                }
                break;
            case XML_ATACTION_EVENT_NAME:
                {
                    // Check if the event belongs to a form or control by
                    // cehcking the 2nd ancestor element, f.i.:
                    // <form:button><form:event-listeners><form:event-listener>
                    const XMLTransformerContext *pObjContext =
                        GetTransformer().GetAncestorContext( 1 );
                    sal_Bool bForm = pObjContext &&

                        pObjContext->HasNamespace(XML_NAMESPACE_FORM );
                    pMutableAttrList->SetValueByIndex( i,
                                   GetTransformer().GetEventName( rAttrValue,
                                                                    bForm ) );
                }
                break;
            case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
                {
                    OUString aAttrValue( rAttrValue );
                    sal_uInt16 nValPrefix =
                        static_cast<sal_uInt16>((*aIter).second.m_nParam1);
                    if( GetTransformer().RemoveNamespacePrefix(
                                aAttrValue, nValPrefix ) )
                        pMutableAttrList->SetValueByIndex( i, aAttrValue );
                }
                break;
            case XML_ATACTION_MACRO_NAME:
                {
                    OUString aName, aLocation;
                    bool bNeedsTransform =
                        ParseURL( rAttrValue, &aName, &aLocation );

                    if ( bNeedsTransform )
                    {
                        pMutableAttrList->SetValueByIndex( i, aName );

                        sal_Int16 idx = pMutableAttrList->GetIndexByName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            GetXMLToken( XML_LANGUAGE ) ) );

                        pMutableAttrList->SetValueByIndex( idx,
                            OUString::createFromAscii("StarBasic") );

                        OUString aLocQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                                GetXMLToken( XML_LOCATION ) ) );

                        pMutableAttrList->AddAttribute( aLocQName, aLocation );
                    }
                    else
                    {
                    const OUString& rApp = GetXMLToken( XML_APPLICATION );
                    const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
                    OUString aLocation;
                    OUString aAttrValue;
                    if( rAttrValue.getLength() > rApp.getLength()+1 &&
                        rAttrValue.copy(0,rApp.getLength()).
                                    equalsIgnoreAsciiCase( rApp ) &&
                        ':' == rAttrValue[rApp.getLength()] )
                    {
                        aLocation = rApp;
                        aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
                    }
                    else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
                             rAttrValue.copy(0,rDoc.getLength()).
                                     equalsIgnoreAsciiCase( rDoc ) &&
                        ':' == rAttrValue[rDoc.getLength()] )
                    {
                        aLocation= rDoc;
                        aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
                    }
                    if( aAttrValue.getLength() )
                        pMutableAttrList->SetValueByIndex( i,
                                            aAttrValue );
                    if( aLocation.getLength() )
                    {
                        OUString aAttrQName( GetTransformer().GetNamespaceMap().
                                GetQNameByKey( XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                        // draw bug
                        aAttrQName = GetTransformer().GetNamespaceMap().
                                GetQNameByKey( XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_LIBRARY ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                    }
                    }
                }
                break;
            case XML_ATACTION_COPY:
                break;
            default:
                OSL_ENSURE( !this, "unknown action" );
                break;
            }
        }
    }

    XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<|endoftext|>


<commit_before>#ifndef ___INANITY_INPUT_WIN32_MANAGER_HPP___
#define ___INANITY_INPUT_WIN32_MANAGER_HPP___

#include "Manager.hpp"
#include "Key.hpp"
#include "../platform/windows.hpp"

BEGIN_INANITY_INPUT

/// General class for Win32 input managers.
class Win32Manager : public Manager
{
private:
	int cursorX, cursorY;

protected:
	Win32Manager();

	static Key ConvertKey(USHORT key, USHORT makeCode, USHORT flags);

public:
	virtual bool ProcessWindowMessage(UINT msg, WPARAM wParam, LPARAM lParam);
};

END_INANITY_INPUT

#endif
<commit_msg>fix mistake<commit_after>#ifndef ___INANITY_INPUT_WIN32_MANAGER_HPP___
#define ___INANITY_INPUT_WIN32_MANAGER_HPP___

#include "Manager.hpp"
#include "Key.hpp"
#include "../platform/windows.hpp"

BEGIN_INANITY_INPUT

/// General class for Win32 input managers.
class Win32Manager : public Manager
{
private:
	int lastCursorX, lastCursorY;

protected:
	Win32Manager();

	static Key ConvertKey(USHORT key, USHORT makeCode, USHORT flags);

public:
	virtual bool ProcessWindowMessage(UINT msg, WPARAM wParam, LPARAM lParam);
};

END_INANITY_INPUT

#endif
<|endoftext|>


<commit_before>#include "CoBaB.h"

SearchObject::SearchObject() {

}

QString SearchObject::getMedium() {
    return mMedium;
}

void SearchObject::setMedium(QString medium) {
    mMedium = medium;
}

Annotation *SearchObject::getAnnotation() {
    return mAnnotation;
}

void SearchObject::setAnnotation(Annotation *annotation) {
    mAnnotation = annotation;
}

QRect *SearchObject::getROI() {
    return mROI;
}

void SearchObject::setROI(QRect *roi) {
    mROI = roi;
}

QString SearchObject::getSourceDataset() {
    return mSourceDataset;
}

void SearchObject::setSourceDataset(QString dataset) {
    mSourceDataset = dataset;
}

int SearchObject::getMediumIndex() {
    return mMediumIndex;
}

void SearchObject::setMediumIndex(int index) {
    mMediumIndex = index;
}

void SearchObject::toStream(QDataStream in) {

    in << *this;

}

void SearchObject::fromStream(QDataStream out) {

    out >> *this;

}

QDataStream& operator >>(QDataStream &in, SearchObject &searchObject) {

    //read object from stream

    QString medium;
    int mediumIndex;
    Annotation *ann = new Annotation("", "");
    QRect *roi;
    QString source;

    //skip opening bracket
    in.skipRawData(1);

    in >> medium;
    searchObject.setMedium(medium);

    //skip coma
    in.skipRawData(2);

    in >> mediumIndex;
    searchObject.setMediumIndex(mediumIndex);

    in.skipRawData(2);

    in >> *ann;
    searchObject.setAnnotation(ann);

    in.skipRawData(2);

    in >> *roi;
    searchObject.setROI(roi);

    in.skipRawData(2);

    in >> source;
    searchObject.setSourceDataset(source);

    in.skipRawData(1);

    return in;
}

QDataStream& operator <<(QDataStream &out, SearchObject &searchObject) {

    //write object to stream
    out << "(" << searchObject.getMedium() << ", "
        << searchObject.getMediumIndex() << ", "
        << searchObject.getAnnotation() << ", "
        << searchObject.getROI() << ", "
        << searchObject.getSourceDataset() << ")";
    return out;
}

<commit_msg>Fixing errors<commit_after>#include "CoBaB.h"

SearchObject::SearchObject() {

}

QString SearchObject::getMedium() {
    return mMedium;
}

void SearchObject::setMedium(QString medium) {
    mMedium = medium;
}

Annotation *SearchObject::getAnnotation() {
    return mAnnotation;
}

void SearchObject::setAnnotation(Annotation *annotation) {
    mAnnotation = annotation;
}

QRect *SearchObject::getROI() {
    return mROI;
}

void SearchObject::setROI(QRect *roi) {
    mROI = roi;
}

QString SearchObject::getSourceDataset() {
    return mSourceDataset;
}

void SearchObject::setSourceDataset(QString dataset) {
    mSourceDataset = dataset;
}

int SearchObject::getMediumIndex() {
    return mMediumIndex;
}

void SearchObject::setMediumIndex(int index) {
    mMediumIndex = index;
}

void SearchObject::toStream(QDataStream in) {

    in << *this;

}

void SearchObject::fromStream(QDataStream out) {

    out >> *this;

}

QDataStream& operator >>(QDataStream &in, SearchObject &searchObject) {

    //read object from stream

    QString medium;
    int mediumIndex;
    Annotation *ann = new Annotation("", "");
    QRect *roi = new QRect();
    QString source;

    //skip opening bracket
    in.skipRawData(1);

    in >> medium;
    searchObject.setMedium(medium);

    //skip coma
    in.skipRawData(2);

    in >> mediumIndex;
    searchObject.setMediumIndex(mediumIndex);

    in.skipRawData(2);

    in >> *ann;
    searchObject.setAnnotation(ann);

    in.skipRawData(2);

    in >> *roi;
    searchObject.setROI(roi);

    in.skipRawData(2);

    in >> source;
    searchObject.setSourceDataset(source);

    in.skipRawData(1);

    return in;
}

QDataStream& operator <<(QDataStream &out, SearchObject &searchObject) {

    //write object to stream
    out << "(" << searchObject.getMedium() << ", "
        << searchObject.getMediumIndex() << ", "
        << searchObject.getAnnotation() << ", "
        << searchObject.getROI() << ", "
        << searchObject.getSourceDataset() << ")";
    return out;
}

<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <fstream>
#include <iostream>
#include <vector>

#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Chunks/DocumentFilters.h"
#include "BitFunnel/Chunks/Factories.h"
#include "BitFunnel/Chunks/IChunkManifestIngestor.h"
#include "BitFunnel/Chunks/IChunkWriter.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/Exceptions.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IConfiguration.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/IngestChunks.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Utilities/ReadLines.h"
#include "BitFunnel/Utilities/Stopwatch.h"
#include "CmdLineParser/CmdLineParser.h"
#include "FilterChunks.h"
#include "LoggerInterfaces/Check.h"

namespace BitFunnel
{
    FilterChunks::FilterChunks(IFileSystem& fileSystem)
        : m_fileSystem(fileSystem)
    {
    }

    int FilterChunks::Main(std::istream& /*input*/,
                           std::ostream& output,
                           int argc,
                           char const *argv[])
    {
        CmdLine::CmdLineParser parser(
            "FilterChunks",
            "Copies a set of chunk files specified by a manifest "
            "while filtering their documents based on a set of predicates.");

        CmdLine::RequiredParameter<char const *> manifestFileName(
            "manifestFile",
            "Path to a file containing the paths to the chunk files to be copied. "
            "One chunk file per line. Paths are relative to working directory.");

        CmdLine::RequiredParameter<char const *> outputPath(
            "outDir",
            "Path to the output directory where the filtered "
            "chunk files will be written.");

        // TODO: This parameter should be unsigned, but it doesn't seem to work
        // with CmdLineParser.
        CmdLine::OptionalParameter<int> gramSize(
            "gramsize",
            "Set the maximum ngram size for phrases.",
            1u,
            CmdLine::GreaterThan(0));

        CmdLine::OptionalParameterList random(
            "random",
            "Copy a random fraction of the corpus.");
        CmdLine::RequiredParameter<int> seed(
            "seed",
            "random number generator seed.");
        CmdLine::RequiredParameter<double> fraction(
            "fraction",
            "fraction of corpus to copy.",
            CmdLine::Range(CmdLine::GreaterThanOrEqual(0.0),
                           CmdLine::LessThanOrEqual(1.0)));
        random.AddParameter(seed);
        random.AddParameter(fraction);

        CmdLine::OptionalParameterList size(
            "size",
            "Sample documents by posting count.");
        CmdLine::RequiredParameter<int> minCount(
            "min postings",
            "minimum number of postings (inclusive).",
            CmdLine::GreaterThanOrEqual(0));
        CmdLine::RequiredParameter<int> maxCount(
            "max postings",
            "maximum number of postings (inclusive).");
        size.AddParameter(minCount);
        size.AddParameter(maxCount);

        CmdLine::OptionalParameter<int> count(
            "count",
            "Maximum number of documents.",
            1u,
            CmdLine::GreaterThan(0));

        CmdLine::OptionalParameter<const char *> writer(
            "writer",
            "Specify chunk writer (annotate or copy)",
            "copy");

        parser.AddParameter(manifestFileName);
        parser.AddParameter(outputPath);
        parser.AddParameter(gramSize);
        parser.AddParameter(random);
        parser.AddParameter(size);
        parser.AddParameter(count);
        parser.AddParameter(writer);

        int returnCode = 1;

        if (parser.TryParse(output, argc, argv))
        {
            try
            {
                CompositeFilter filter;

                if (size.IsActivated())
                {
                    CHECK_LE(minCount, maxCount)
                        << "Invalid posting count range.";
                    filter.AddFilter(
                        std::unique_ptr<IDocumentFilter>(
                            new PostingCountFilter(
                                static_cast<unsigned>(minCount),
                                static_cast<unsigned>(maxCount))));
                }

                if (random.IsActivated())
                {
                    filter.AddFilter(
                        std::unique_ptr<IDocumentFilter>(
                            new RandomDocumentFilter(fraction,
                                                     static_cast<unsigned>(seed))));
                }

                if (count.IsActivated())
                {
                    filter.AddFilter(
                        std::unique_ptr<IDocumentFilter>(
                            new DocumentCountFilter(static_cast<unsigned>(count))));
                }

                FilterChunkList(output,
                                outputPath,
                                manifestFileName,
                                gramSize,
                                filter,
                                writer);

                returnCode = 0;
            }
            catch (RecoverableError e)
            {
                output << "Error: " << e.what() << std::endl;
            }
            catch (...)
            {
                output << "Unexpected error." << std::endl;
            }
        }

        return returnCode;
    }

    void FilterChunks::FilterChunkList(
        std::ostream& output,
        char const * outputDirectory,
        char const * chunkListFileName,
        // TODO: gramSize should be unsigned once CmdLineParser supports unsigned.
        int gramSize,
        IDocumentFilter & filter,
        char const * writer) const
    {
        // TODO: cast of gramSize can be removed when it's fixed to be unsigned.
        auto index = Factories::CreateSimpleIndex(m_fileSystem);
        index->ConfigureForStatistics(outputDirectory,
                                      static_cast<size_t>(gramSize),
                                      false);
        index->StartIndex();

        // TODO: Add try/catch around file operations.
        output
            << "Loading chunk list file '" << chunkListFileName << "'" << std::endl
            << "Output directory: '" << outputDirectory << "'" << std::endl;

        std::vector<std::string> filePaths = ReadLines(m_fileSystem, chunkListFileName);

        output << "Reading " << filePaths.size() << " files\n";

        IConfiguration const & configuration = index->GetConfiguration();
        IIngestor & ingestor = index->GetIngestor();

        // Create special file manager for output.
        auto fileManager = Factories::CreateFileManager(
            outputDirectory,
            outputDirectory,
            outputDirectory,
            index->GetFileSystem());

        // Select IChunkWriterFactory based on name provided on command line.
        std::unique_ptr<IChunkWriterFactory> chunkWriterFactory;
        if (!strcmp(writer, "copy"))
        {
            chunkWriterFactory = Factories::CreateCopyingChunkWriterFactory(*fileManager);
        }
        else if (!strcmp(writer, "annotate"))
        {
            chunkWriterFactory =
                Factories::CreateAnnotatingChunkWriterFactory(
                    *fileManager,
                    ingestor.GetShardDefinition());
        }
        else
        {
            FatalError error("Invalid writer. Use `copy` or `annotate`.");
            throw error;
        }

        auto manifest = Factories::CreateChunkManifestIngestor(
            m_fileSystem,
            chunkWriterFactory.get(),
            filePaths,
            configuration,
            ingestor,
            filter,
            false);

        output << "Filtering chunks . . ." << std::endl;

        Stopwatch stopwatch;

        {
            // Block scopes manifestFile.
            auto manifestFile = fileManager->Manifest().OpenForWrite();

            // DESIGN NOTE: Using single-threaded code here to avoid two
            // threads writing to manifestFile and filter.
            // If corpus filtering was performance critical and not disk
            // bound, we might consider adding synchronization to allow
            // multiple threads.
            for (size_t i = 0; i < filePaths.size(); ++i)
            {
                // Copy chunks.
                manifest->IngestChunk(i);

                // Add corresponding entry to manifest file.
                *manifestFile
                    << fileManager->Chunk(i).GetName()
                    << std::endl;
            }
        }

        const double elapsedTime = stopwatch.ElapsedTime();
        const size_t totalSourceBytes = ingestor.GetTotalSouceBytesIngested();

        output
            << "Filtering complete." << std::endl
            << "  Ingestion time = " << elapsedTime << std::endl
            << "  Ingestion rate (bytes/s): "
            << totalSourceBytes / elapsedTime << std::endl;
    }
}
<commit_msg>Catch all exceptions to ensure helpful error message is output<commit_after>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <fstream>
#include <iostream>
#include <vector>

#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Chunks/DocumentFilters.h"
#include "BitFunnel/Chunks/Factories.h"
#include "BitFunnel/Chunks/IChunkManifestIngestor.h"
#include "BitFunnel/Chunks/IChunkWriter.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/Exceptions.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IConfiguration.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/IngestChunks.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Utilities/ReadLines.h"
#include "BitFunnel/Utilities/Stopwatch.h"
#include "CmdLineParser/CmdLineParser.h"
#include "FilterChunks.h"
#include "LoggerInterfaces/Check.h"

namespace BitFunnel
{
    FilterChunks::FilterChunks(IFileSystem& fileSystem)
        : m_fileSystem(fileSystem)
    {
    }

    int FilterChunks::Main(std::istream& /*input*/,
                           std::ostream& output,
                           int argc,
                           char const *argv[])
    {
        CmdLine::CmdLineParser parser(
            "FilterChunks",
            "Copies a set of chunk files specified by a manifest "
            "while filtering their documents based on a set of predicates.");

        CmdLine::RequiredParameter<char const *> manifestFileName(
            "manifestFile",
            "Path to a file containing the paths to the chunk files to be copied. "
            "One chunk file per line. Paths are relative to working directory.");

        CmdLine::RequiredParameter<char const *> outputPath(
            "outDir",
            "Path to the output directory where the filtered "
            "chunk files will be written.");

        // TODO: This parameter should be unsigned, but it doesn't seem to work
        // with CmdLineParser.
        CmdLine::OptionalParameter<int> gramSize(
            "gramsize",
            "Set the maximum ngram size for phrases.",
            1u,
            CmdLine::GreaterThan(0));

        CmdLine::OptionalParameterList random(
            "random",
            "Copy a random fraction of the corpus.");
        CmdLine::RequiredParameter<int> seed(
            "seed",
            "random number generator seed.");
        CmdLine::RequiredParameter<double> fraction(
            "fraction",
            "fraction of corpus to copy.",
            CmdLine::Range(CmdLine::GreaterThanOrEqual(0.0),
                           CmdLine::LessThanOrEqual(1.0)));
        random.AddParameter(seed);
        random.AddParameter(fraction);

        CmdLine::OptionalParameterList size(
            "size",
            "Sample documents by posting count.");
        CmdLine::RequiredParameter<int> minCount(
            "min postings",
            "minimum number of postings (inclusive).",
            CmdLine::GreaterThanOrEqual(0));
        CmdLine::RequiredParameter<int> maxCount(
            "max postings",
            "maximum number of postings (inclusive).");
        size.AddParameter(minCount);
        size.AddParameter(maxCount);

        CmdLine::OptionalParameter<int> count(
            "count",
            "Maximum number of documents.",
            1u,
            CmdLine::GreaterThan(0));

        CmdLine::OptionalParameter<const char *> writer(
            "writer",
            "Specify chunk writer (annotate or copy)",
            "copy");

        parser.AddParameter(manifestFileName);
        parser.AddParameter(outputPath);
        parser.AddParameter(gramSize);
        parser.AddParameter(random);
        parser.AddParameter(size);
        parser.AddParameter(count);
        parser.AddParameter(writer);

        int returnCode = 1;

        if (parser.TryParse(output, argc, argv))
        {
            try
            {
                CompositeFilter filter;

                if (size.IsActivated())
                {
                    CHECK_LE(minCount, maxCount)
                        << "Invalid posting count range.";
                    filter.AddFilter(
                        std::unique_ptr<IDocumentFilter>(
                            new PostingCountFilter(
                                static_cast<unsigned>(minCount),
                                static_cast<unsigned>(maxCount))));
                }

                if (random.IsActivated())
                {
                    filter.AddFilter(
                        std::unique_ptr<IDocumentFilter>(
                            new RandomDocumentFilter(fraction,
                                                     static_cast<unsigned>(seed))));
                }

                if (count.IsActivated())
                {
                    filter.AddFilter(
                        std::unique_ptr<IDocumentFilter>(
                            new DocumentCountFilter(static_cast<unsigned>(count))));
                }

                FilterChunkList(output,
                                outputPath,
                                manifestFileName,
                                gramSize,
                                filter,
                                writer);

                returnCode = 0;
            }
            catch (std::exception e)
            {
                output << "Error: " << e.what() << std::endl;
            }
            catch (Logging::CheckException e)
            {
                output << "Error: " << e.GetMessage().c_str() << std::endl;
            }
            catch (...)
            {
                output << "Unexpected error." << std::endl;
            }
        }

        return returnCode;
    }

    void FilterChunks::FilterChunkList(
        std::ostream& output,
        char const * outputDirectory,
        char const * chunkListFileName,
        // TODO: gramSize should be unsigned once CmdLineParser supports unsigned.
        int gramSize,
        IDocumentFilter & filter,
        char const * writer) const
    {
        // TODO: cast of gramSize can be removed when it's fixed to be unsigned.
        auto index = Factories::CreateSimpleIndex(m_fileSystem);
        index->ConfigureForStatistics(outputDirectory,
                                      static_cast<size_t>(gramSize),
                                      false);
        index->StartIndex();

        // TODO: Add try/catch around file operations.
        output
            << "Loading chunk list file '" << chunkListFileName << "'" << std::endl
            << "Output directory: '" << outputDirectory << "'" << std::endl;

        std::vector<std::string> filePaths = ReadLines(m_fileSystem, chunkListFileName);

        output << "Reading " << filePaths.size() << " files\n";

        IConfiguration const & configuration = index->GetConfiguration();
        IIngestor & ingestor = index->GetIngestor();

        // Create special file manager for output.
        auto fileManager = Factories::CreateFileManager(
            outputDirectory,
            outputDirectory,
            outputDirectory,
            index->GetFileSystem());

        // Select IChunkWriterFactory based on name provided on command line.
        std::unique_ptr<IChunkWriterFactory> chunkWriterFactory;
        if (!strcmp(writer, "copy"))
        {
            chunkWriterFactory = Factories::CreateCopyingChunkWriterFactory(*fileManager);
        }
        else if (!strcmp(writer, "annotate"))
        {
            chunkWriterFactory =
                Factories::CreateAnnotatingChunkWriterFactory(
                    *fileManager,
                    ingestor.GetShardDefinition());
        }
        else
        {
            FatalError error("Invalid writer. Use `copy` or `annotate`.");
            throw error;
        }

        auto manifest = Factories::CreateChunkManifestIngestor(
            m_fileSystem,
            chunkWriterFactory.get(),
            filePaths,
            configuration,
            ingestor,
            filter,
            false);

        output << "Filtering chunks . . ." << std::endl;

        Stopwatch stopwatch;

        {
            // Block scopes manifestFile.
            auto manifestFile = fileManager->Manifest().OpenForWrite();

            // DESIGN NOTE: Using single-threaded code here to avoid two
            // threads writing to manifestFile and filter.
            // If corpus filtering was performance critical and not disk
            // bound, we might consider adding synchronization to allow
            // multiple threads.
            for (size_t i = 0; i < filePaths.size(); ++i)
            {
                // Copy chunks.
                manifest->IngestChunk(i);

                // Add corresponding entry to manifest file.
                *manifestFile
                    << fileManager->Chunk(i).GetName()
                    << std::endl;
            }
        }

        const double elapsedTime = stopwatch.ElapsedTime();
        const size_t totalSourceBytes = ingestor.GetTotalSouceBytesIngested();

        output
            << "Filtering complete." << std::endl
            << "  Ingestion time = " << elapsedTime << std::endl
            << "  Ingestion rate (bytes/s): "
            << totalSourceBytes / elapsedTime << std::endl;
    }
}
<|endoftext|>


<commit_before>/**
 * Shader.cxx
 *
 * Author
 *     Andrew Brown <adb1413@rit.edu>
 */
#include "config.h"
#include <stdexcept>
#include "glycerin/Shader.hxx"
using namespace std;
namespace Glycerin {

/**
 * Constructs a shader.
 *
 * @param handle OpenGL identifier for shader
 */
Shader::Shader(const GLuint handle) : _handle(handle) {
    // pass
}

/**
 * Constructs a shader by copying another shader.
 *
 * @param shader Shader to copy
 */
Shader::Shader(const Shader& shader) : _handle(shader._handle) {
    // pass
}

/**
 * Destroys the shader.
 */
Shader::~Shader() {
    // pass
}

/**
 * Compiles the shader.
 */
void Shader::compile() {
    glCompileShader(_handle);
}

/**
 * Creates a new shader of a particular type.
 *
 * @param type Kind of shader, e.g. `GL_VERTEX_SHADER` or `GL_FRAGMENT_SHADER`
 * @return New shader of specified type
 * @throw std::runtime_error if shader could not be created
 */
Shader Shader::create(const GLenum type) {

    // Create a handle
    const GLuint handle = glCreateShader(type);
    if (handle == 0) {
        throw runtime_error("[Shader] Could not create shader!");
    }

    // Make the shader
    return Shader(handle);
}

/**
 * Deletes the shader.
 */
void Shader::dispose() {
    glDeleteShader(_handle);
}

/**
 * Returns the OpenGL identifier for the shader.
 */
GLuint Shader::handle() const {
    return _handle;
}

/**
 * Copies the handle of another shader.
 *
 * @param shader Shader to copy
 * @return Reference to this shader to support chaining
 */
Shader& Shader::operator=(const Shader &shader) {
    _handle = shader._handle;
}

/**
 * Checks if another shader is equal to this one.
 *
 * @param shader Shader to check
 * @return `true` if shaders represent same OpenGL shader
 */
bool Shader::operator==(const Shader &shader) const {
    return _handle == shader.handle();
}

/**
 * Checks if another shader is not equal to this one.
 *
 * @param shader Shader to check
 * @return `true` if shaders do not represent same OpenGL shader
 */
bool Shader::operator!=(const Shader &shader) const {
    return _handle != shader.handle();
}

/**
 * Returns the shader's source code.
 */
string Shader::source() const {

    // Get the size of the source code
    GLint len;
    glGetShaderiv(_handle, GL_SHADER_SOURCE_LENGTH, &len);
    if (len == 0) {
        return "";
    }

    // Put the source code into a buffer and make a string from it
    char* const buf = new char[len];
    glGetShaderSource(_handle, len, NULL, buf);
    const string str(buf);

    // Delete the buffer
    delete[] buf;

    // Return the string
    return str;
}

/**
 * Returns the shader's log.
 */
string Shader::log() const {

    // Allocate a character buffer large enough for the log
    GLsizei count;
    glGetShaderiv(_handle, GL_INFO_LOG_LENGTH, &count);
    GLchar* buf = new GLchar[count + 1];

    // Put the log into the buffer and make a string from it
    GLsizei returned;
    glGetShaderInfoLog(_handle, count, &returned, buf);
    buf[returned] = '\0';
    string str(buf);

    // Delete the buffer
    delete[] buf;

    // Return the string
    return str;
}

/**
 * Returns the kind of this shader, e.g. `GL_VERTEX_SHADER` or `GL_FRAGMENT_SHADER`.
 */
GLenum Shader::type() const {
    GLint type;
    glGetShaderiv(_handle, GL_SHADER_TYPE, &type);
    return type;
}

/**
 * Returns `true` if shader is compiled.
 */
bool Shader::compiled() const {
    GLint compiled;
    glGetShaderiv(_handle, GL_COMPILE_STATUS, &compiled);
    return compiled;
}

/**
 * Changes the shader's source code.
 *
 * @param source Code for shader
 * @throws invalid_argument if source code is empty
 */
void Shader::source(const std::string& source) {
    const char* buf = source.c_str();
    const char** ptr = &buf;
    glShaderSource(_handle, 1, ptr, NULL);
}

/**
 * Wraps an existing OpenGL shader.
 *
 * @param handle OpenGL identifier for shader
 * @return Wrapper for OpenGL shader
 * @throws std::invalid_argument if handle is not a valid OpenGL shader
 */
Shader Shader::wrap(const GLuint handle) {
    if (!glIsShader(handle)) {
        throw invalid_argument("[Shader] Handle is not a valid shader!");
    }
    return Shader(handle);
}

} /* namespace Glycerin */
<commit_msg>Shader operators use attributes directly (ref #55)<commit_after>/**
 * Shader.cxx
 *
 * Author
 *     Andrew Brown <adb1413@rit.edu>
 */
#include "config.h"
#include <stdexcept>
#include "glycerin/Shader.hxx"
using namespace std;
namespace Glycerin {

/**
 * Constructs a shader.
 *
 * @param handle OpenGL identifier for shader
 */
Shader::Shader(const GLuint handle) : _handle(handle) {
    // pass
}

/**
 * Constructs a shader by copying another shader.
 *
 * @param shader Shader to copy
 */
Shader::Shader(const Shader& shader) : _handle(shader._handle) {
    // pass
}

/**
 * Destroys the shader.
 */
Shader::~Shader() {
    // pass
}

/**
 * Compiles the shader.
 */
void Shader::compile() {
    glCompileShader(_handle);
}

/**
 * Creates a new shader of a particular type.
 *
 * @param type Kind of shader, e.g. `GL_VERTEX_SHADER` or `GL_FRAGMENT_SHADER`
 * @return New shader of specified type
 * @throw std::runtime_error if shader could not be created
 */
Shader Shader::create(const GLenum type) {

    // Create a handle
    const GLuint handle = glCreateShader(type);
    if (handle == 0) {
        throw runtime_error("[Shader] Could not create shader!");
    }

    // Make the shader
    return Shader(handle);
}

/**
 * Deletes the shader.
 */
void Shader::dispose() {
    glDeleteShader(_handle);
}

/**
 * Returns the OpenGL identifier for the shader.
 */
GLuint Shader::handle() const {
    return _handle;
}

/**
 * Copies the handle of another shader.
 *
 * @param shader Shader to copy
 * @return Reference to this shader to support chaining
 */
Shader& Shader::operator=(const Shader &shader) {
    _handle = shader._handle;
}

/**
 * Checks if another shader is equal to this one.
 *
 * @param shader Shader to check
 * @return `true` if shaders represent same OpenGL shader
 */
bool Shader::operator==(const Shader &shader) const {
    return _handle == shader._handle;
}

/**
 * Checks if another shader is not equal to this one.
 *
 * @param shader Shader to check
 * @return `true` if shaders do not represent same OpenGL shader
 */
bool Shader::operator!=(const Shader &shader) const {
    return _handle != shader._handle;
}

/**
 * Returns the shader's source code.
 */
string Shader::source() const {

    // Get the size of the source code
    GLint len;
    glGetShaderiv(_handle, GL_SHADER_SOURCE_LENGTH, &len);
    if (len == 0) {
        return "";
    }

    // Put the source code into a buffer and make a string from it
    char* const buf = new char[len];
    glGetShaderSource(_handle, len, NULL, buf);
    const string str(buf);

    // Delete the buffer
    delete[] buf;

    // Return the string
    return str;
}

/**
 * Returns the shader's log.
 */
string Shader::log() const {

    // Allocate a character buffer large enough for the log
    GLsizei count;
    glGetShaderiv(_handle, GL_INFO_LOG_LENGTH, &count);
    GLchar* buf = new GLchar[count + 1];

    // Put the log into the buffer and make a string from it
    GLsizei returned;
    glGetShaderInfoLog(_handle, count, &returned, buf);
    buf[returned] = '\0';
    string str(buf);

    // Delete the buffer
    delete[] buf;

    // Return the string
    return str;
}

/**
 * Returns the kind of this shader, e.g. `GL_VERTEX_SHADER` or `GL_FRAGMENT_SHADER`.
 */
GLenum Shader::type() const {
    GLint type;
    glGetShaderiv(_handle, GL_SHADER_TYPE, &type);
    return type;
}

/**
 * Returns `true` if shader is compiled.
 */
bool Shader::compiled() const {
    GLint compiled;
    glGetShaderiv(_handle, GL_COMPILE_STATUS, &compiled);
    return compiled;
}

/**
 * Changes the shader's source code.
 *
 * @param source Code for shader
 * @throws invalid_argument if source code is empty
 */
void Shader::source(const std::string& source) {
    const char* buf = source.c_str();
    const char** ptr = &buf;
    glShaderSource(_handle, 1, ptr, NULL);
}

/**
 * Wraps an existing OpenGL shader.
 *
 * @param handle OpenGL identifier for shader
 * @return Wrapper for OpenGL shader
 * @throws std::invalid_argument if handle is not a valid OpenGL shader
 */
Shader Shader::wrap(const GLuint handle) {
    if (!glIsShader(handle)) {
        throw invalid_argument("[Shader] Handle is not a valid shader!");
    }
    return Shader(handle);
}

} /* namespace Glycerin */
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.9  2001/10/10 14:17:50  peiyongz
 * <URI>:<LocalPart> where <URI> can be optional.
 *
 * Revision 1.8  2001/10/09 20:46:19  peiyongz
 * NOTATION: checkContent(): <URI>:<localPart>
 *
 * Revision 1.7  2001/10/02 18:59:29  peiyongz
 * Invalid_Facet_Tag to display the tag name
 *
 * Revision 1.6  2001/09/24 15:33:15  peiyongz
 * DTV Reorganization: virtual methods moved to *.cpp
 *
 * Revision 1.5  2001/09/20 15:14:47  peiyongz
 * DTV reorganization: inherit from AbstractStringVaildator
 *
 * Revision 1.3  2001/08/21 18:42:53  peiyongz
 * Bugzilla# 2816: cleanUp() declared with external linkage and called
 *                          before defined as inline
 *
 * Revision 1.2  2001/08/14 22:11:56  peiyongz
 * new exception message added
 *
 * Revision 1.1  2001/07/05 20:15:27  peiyongz
 * NOTATIONDatatypeValidator
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <validators/datatype/NOTATIONDatatypeValidator.hpp>
#include <util/XMLUri.hpp>
#include <validators/datatype/InvalidDatatypeFacetException.hpp>
#include <validators/datatype/InvalidDatatypeValueException.hpp>

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
NOTATIONDatatypeValidator::NOTATIONDatatypeValidator()
:AbstractStringValidator(0, 0, 0, DatatypeValidator::NOTATION)
{}

NOTATIONDatatypeValidator::~NOTATIONDatatypeValidator()
{}

NOTATIONDatatypeValidator::NOTATIONDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefVectorOf<XMLCh>*           const enums
                        , const int                           finalSet)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::NOTATION)
{
    init(enums);
}

DatatypeValidator* NOTATIONDatatypeValidator::newInstance(
                                      RefHashTableOf<KVStringPair>* const facets
                                    , RefVectorOf<XMLCh>*           const enums
                                    , const int                           finalSet)
{
    return (DatatypeValidator*) new NOTATIONDatatypeValidator(this, facets, enums, finalSet);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------
void NOTATIONDatatypeValidator::assignAdditionalFacet( const XMLCh* const key
                                                     , const XMLCh* const)
{
    ThrowXML1(InvalidDatatypeFacetException
            , XMLExcepts::FACET_Invalid_Tag
            , key);
}

void NOTATIONDatatypeValidator::inheritAdditionalFacet()
{}

void NOTATIONDatatypeValidator::checkAdditionalFacetConstraints() const
{}

void NOTATIONDatatypeValidator::checkAdditionalFacet(const XMLCh* const) const
{}

void NOTATIONDatatypeValidator::checkValueSpace(const XMLCh* const content)
{
    //
    //  NOTATATION: <URI>:<localPart>
    //  where URI is optional
    //        ':' and localPart must be present
    //
    int contentLength = XMLString::stringLen(content);
    int colonPosition = XMLString::lastIndexOf(content, chColon);

    if ((colonPosition == -1)                ||  // no ':'
        (colonPosition == contentLength - 1)  )  // <URI>':'
        ThrowXML1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_NOTATION_Invalid
                , content);

    // Extract URI
    XMLCh* uriPart = new XMLCh[colonPosition + 1];
    ArrayJanitor<XMLCh> jan1(uriPart);
    XMLString::subString(uriPart, content, 0, colonPosition);

    try
    {
        // no relative uri support here
        XMLUri  newURI(uriPart);
    }
    catch (...)
    {
        ThrowXML1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_NOTATION_Invalid
                , content);
    }

    // Extract localpart
    XMLCh* localPart = new XMLCh[contentLength - colonPosition];
    ArrayJanitor<XMLCh> jan2(localPart);
    XMLString::subString(localPart, content, colonPosition + 1, contentLength);

    if ( !XMLString::isValidNCName(localPart))
    {
        ThrowXML1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_NOTATION_Invalid
                , content);
    }

}

int NOTATIONDatatypeValidator::getLength(const XMLCh* const content) const
{
    return XMLString::stringLen(content);
}

/**
  * End of file NOTATIONDatatypeValidator.cpp
  */
<commit_msg>extract/validate URI iff present<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.10  2001/10/10 15:11:21  peiyongz
 * extract/validate URI iff present
 *
 * Revision 1.9  2001/10/10 14:17:50  peiyongz
 * <URI>:<LocalPart> where <URI> can be optional.
 *
 * Revision 1.8  2001/10/09 20:46:19  peiyongz
 * NOTATION: checkContent(): <URI>:<localPart>
 *
 * Revision 1.7  2001/10/02 18:59:29  peiyongz
 * Invalid_Facet_Tag to display the tag name
 *
 * Revision 1.6  2001/09/24 15:33:15  peiyongz
 * DTV Reorganization: virtual methods moved to *.cpp
 *
 * Revision 1.5  2001/09/20 15:14:47  peiyongz
 * DTV reorganization: inherit from AbstractStringVaildator
 *
 * Revision 1.3  2001/08/21 18:42:53  peiyongz
 * Bugzilla# 2816: cleanUp() declared with external linkage and called
 *                          before defined as inline
 *
 * Revision 1.2  2001/08/14 22:11:56  peiyongz
 * new exception message added
 *
 * Revision 1.1  2001/07/05 20:15:27  peiyongz
 * NOTATIONDatatypeValidator
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <validators/datatype/NOTATIONDatatypeValidator.hpp>
#include <util/XMLUri.hpp>
#include <validators/datatype/InvalidDatatypeFacetException.hpp>
#include <validators/datatype/InvalidDatatypeValueException.hpp>

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
NOTATIONDatatypeValidator::NOTATIONDatatypeValidator()
:AbstractStringValidator(0, 0, 0, DatatypeValidator::NOTATION)
{}

NOTATIONDatatypeValidator::~NOTATIONDatatypeValidator()
{}

NOTATIONDatatypeValidator::NOTATIONDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefVectorOf<XMLCh>*           const enums
                        , const int                           finalSet)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::NOTATION)
{
    init(enums);
}

DatatypeValidator* NOTATIONDatatypeValidator::newInstance(
                                      RefHashTableOf<KVStringPair>* const facets
                                    , RefVectorOf<XMLCh>*           const enums
                                    , const int                           finalSet)
{
    return (DatatypeValidator*) new NOTATIONDatatypeValidator(this, facets, enums, finalSet);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------
void NOTATIONDatatypeValidator::assignAdditionalFacet( const XMLCh* const key
                                                     , const XMLCh* const)
{
    ThrowXML1(InvalidDatatypeFacetException
            , XMLExcepts::FACET_Invalid_Tag
            , key);
}

void NOTATIONDatatypeValidator::inheritAdditionalFacet()
{}

void NOTATIONDatatypeValidator::checkAdditionalFacetConstraints() const
{}

void NOTATIONDatatypeValidator::checkAdditionalFacet(const XMLCh* const) const
{}

void NOTATIONDatatypeValidator::checkValueSpace(const XMLCh* const content)
{
    //
    //  NOTATATION: <URI>:<localPart>
    //  where URI is optional
    //        ':' and localPart must be present
    //
    int contentLength = XMLString::stringLen(content);
    int colonPosition = XMLString::lastIndexOf(content, chColon);

    if ((colonPosition == -1)                ||  // no ':'
        (colonPosition == contentLength - 1)  )  // <URI>':'
        ThrowXML1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_NOTATION_Invalid
                , content);

    if (colonPosition > 0)
    {
        // Extract URI
        XMLCh* uriPart = new XMLCh[colonPosition + 1];
        ArrayJanitor<XMLCh> jan1(uriPart);
        XMLString::subString(uriPart, content, 0, colonPosition);

        try
        {
            // no relative uri support here
            XMLUri  newURI(uriPart);
        }
        catch (...)
        {
            ThrowXML1(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_NOTATION_Invalid
                    , content);
        }
    }

    // Extract localpart
    XMLCh* localPart = new XMLCh[contentLength - colonPosition];
    ArrayJanitor<XMLCh> jan2(localPart);
    XMLString::subString(localPart, content, colonPosition + 1, contentLength);

    if ( !XMLString::isValidNCName(localPart))
    {
        ThrowXML1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_NOTATION_Invalid
                , content);
    }

}

int NOTATIONDatatypeValidator::getLength(const XMLCh* const content) const
{
    return XMLString::stringLen(content);
}

/**
  * End of file NOTATIONDatatypeValidator.cpp
  */
<|endoftext|>