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

using namespace std;

namespace mbed {

RPC::RPC(const char *name) {
    _from_construct = false;
    if (name != NULL) {
        _name = new char[strlen(name) + 1];
        strcpy(_name, name);
    } else {
        _name = new char[12];
        sprintf(_name, "obj%p", this);
    }
    // put this object at head of the list
    _next = _head;
    _head = this;
}

RPC::~RPC() {
    // remove this object from the list
    if (_head == this) { // first in the list, so just drop me
        _head = _next;
    } else {            // find the object before me, then drop me
        RPC* p = _head;
        while (p->_next != this) {
            p = p->_next;
        }
        p->_next = _next;
    }
}

const rpc_method *RPC::get_rpc_methods() {
    static const rpc_method methods[] = {
        {"delete", rpc_method_caller<RPC, &RPC::delete_self> },
        RPC_METHOD_END
    };
    return methods;
}

RPC *RPC::lookup(const char *name) {
    size_t len = strlen(name);
    for (RPC *p = _head; p != NULL; p = p->_next) {
        /* Check that p->_name matches name and is the correct length */
        if (strncmp(p->_name, name, len) == 0 && (strlen(p->_name) == len)) {
            return p;
        }
    }
    return NULL;
}

void RPC::delete_self() {
    delete[] _name;
    if (_from_construct) {
        delete this;
    }
}

void RPC::list_objs(Arguments *args, Reply *result) {
    for (RPC *ptr = RPC::_head; ptr != NULL; ptr = ptr->_next) {
        if (ptr->_from_construct) {
            result->putData<const char*>(ptr->_name);
        }
    }
}

void RPC::clear(Arguments*, Reply*) {
    RPC *ptr = RPC::_head;
    while (ptr != NULL) {
        RPC *tmp = ptr;
        ptr = ptr->_next;
        delete[] tmp->_name;
        if (tmp->_from_construct) {
            delete tmp;
        }
    }
}

const rpc_function RPC::_RPC_funcs[] = {
    {"clear", &RPC::clear },
    { "objects", &RPC::list_objs },
    RPC_METHOD_END
};

rpc_class RPC::_RPC_class = { "RPC", _RPC_funcs, NULL };

RPC *RPC::_head = NULL;

rpc_class *RPC::_classes = &_RPC_class;

bool RPC::call(const char *request, char *reply) {
    if (request == NULL) return false;

    Arguments args(request);
    Reply r(reply);

    /* If there's no name print object and class names to result */
    if (args.obj_name == NULL) {
        for (RPC *p = RPC::_head; p != NULL; p = p->_next) {
            r.putData<const char*>(p->_name);
        }
        for (rpc_class *c = RPC::_classes; c != NULL; c = c->next) {
            r.putData<const char*>(c->name);
        }
        return true;
    }

    /* First try matching an instance */
    RPC *p = lookup(args.obj_name);
    if (p != NULL) {
        /* Get the list of methods we support */
        const rpc_method *cur_method = p->get_rpc_methods();

        /* When there's no method print method names to result */
        if (args.method_name == NULL) {
            while (true) {
                for (; cur_method->name != NULL; cur_method++) {
                    r.putData<const char*>(cur_method->name);
                }

                /* write_name_arr's args are references, so result and cur_method will have changed */
                if (cur_method->super != 0) {
                    cur_method = cur_method->super(p);
                } else {
                    return true;
                }
            }
        }

        /* Look through the methods for the one whose name matches */
        while (true) {
            for (; cur_method->name != NULL; cur_method++) {
                if (strcmp(cur_method->name, args.method_name) == 0) {
                    (cur_method->method_caller)(p, &args, &r);
                    return true;
                }
            }

            if (cur_method->super != 0) {
                cur_method = cur_method->super(p);
            } else {
                /* end of methods and no match */
                return false;
            }

        }
    }

    /* Then try a class */
    for (const rpc_class *q = _classes; q != NULL; q = q->next) {
        if (strcmp(q->name, args.obj_name) == 0) {
            /* Matched the class name, so get its functions */
            const rpc_function *cur_func = q->static_functions;
            if (args.method_name == NULL) {
                for (; cur_func->name != NULL; cur_func++) {
                    r.putData<const char*>(cur_func->name);
                }
                return true;
            } else {
                /* Otherwise call the appropriate function */
                for (; cur_func->name != NULL; cur_func++) {
                    if (strcmp(cur_func->name, args.method_name) == 0) {
                        (cur_func->function_caller)(&args, &r);
                        return true;
                    }
                }
                return false;
            }
        }
    }

    return false;
}

} // namespace mbed
<commit_msg>Populated reply message<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "rpc.h"

using namespace std;

namespace mbed {

RPC::RPC(const char *name) {
    _from_construct = false;
    if (name != NULL) {
        _name = new char[strlen(name) + 1];
        strcpy(_name, name);
    } else {
        _name = new char[12];
        sprintf(_name, "obj%p", this);
    }
    // put this object at head of the list
    _next = _head;
    _head = this;
}

RPC::~RPC() {
    // remove this object from the list
    if (_head == this) { // first in the list, so just drop me
        _head = _next;
    } else {            // find the object before me, then drop me
        RPC* p = _head;
        while (p->_next != this) {
            p = p->_next;
        }
        p->_next = _next;
    }
}

const rpc_method *RPC::get_rpc_methods() {
    static const rpc_method methods[] = {
        {"delete", rpc_method_caller<RPC, &RPC::delete_self> },
        RPC_METHOD_END
    };
    return methods;
}

RPC *RPC::lookup(const char *name) {
    size_t len = strlen(name);
    for (RPC *p = _head; p != NULL; p = p->_next) {
        /* Check that p->_name matches name and is the correct length */
        if (strncmp(p->_name, name, len) == 0 && (strlen(p->_name) == len)) {
            return p;
        }
    }
    return NULL;
}

void RPC::delete_self() {
    delete[] _name;
    if (_from_construct) {
        delete this;
    }
}

void RPC::list_objs(Arguments *args, Reply *result) {
    for (RPC *ptr = RPC::_head; ptr != NULL; ptr = ptr->_next) {
        if (ptr->_from_construct) {
            result->putData<const char*>(ptr->_name);
        }
    }
}

void RPC::clear(Arguments*, Reply*) {
    RPC *ptr = RPC::_head;
    while (ptr != NULL) {
        RPC *tmp = ptr;
        ptr = ptr->_next;
        delete[] tmp->_name;
        if (tmp->_from_construct) {
            delete tmp;
        }
    }
}

const rpc_function RPC::_RPC_funcs[] = {
    {"clear", &RPC::clear },
    { "objects", &RPC::list_objs },
    RPC_METHOD_END
};

rpc_class RPC::_RPC_class = { "RPC", _RPC_funcs, NULL };

RPC *RPC::_head = NULL;

rpc_class *RPC::_classes = &_RPC_class;

bool RPC::call(const char *request, char *reply) {
    if (request == NULL) return false;

    Arguments args(request);
    Reply r(reply);

    /* If there's no name print object and class names to result */
    if (args.obj_name == NULL) {
        for (RPC *p = RPC::_head; p != NULL; p = p->_next) {
            r.putData<const char*>(p->_name);
        }
        for (rpc_class *c = RPC::_classes; c != NULL; c = c->next) {
            r.putData<const char*>(c->name);
        }
        return true;
    }

    /* First try matching an instance */
    RPC *p = lookup(args.obj_name);
    if (p != NULL) {
        /* Get the list of methods we support */
        const rpc_method *cur_method = p->get_rpc_methods();

        /* When there's no method print method names to result */
        if (args.method_name == NULL) {
            while (true) {
                for (; cur_method->name != NULL; cur_method++) {
                    r.putData<const char*>(cur_method->name);
                }

                /* write_name_arr's args are references, so result and cur_method will have changed */
                if (cur_method->super != 0) {
                    cur_method = cur_method->super(p);
                } else {
                    return true;
                }
            }
        }

        /* Look through the methods for the one whose name matches */
        while (true) {
            for (; cur_method->name != NULL; cur_method++) {
                r.putData<const char*>(cur_method->name);
                if (strcmp(cur_method->name, args.method_name) == 0) {
                    (cur_method->method_caller)(p, &args, &r);
                    return true;
                }
            }

            if (cur_method->super != 0) {
                cur_method = cur_method->super(p);
            } else {
                /* end of methods and no match */
                return false;
            }

        }
    }

    /* Then try a class */
    for (const rpc_class *q = _classes; q != NULL; q = q->next) {
        if (strcmp(q->name, args.obj_name) == 0) {
            /* Matched the class name, so get its functions */
            const rpc_function *cur_func = q->static_functions;
            if (args.method_name == NULL) {
                for (; cur_func->name != NULL; cur_func++) {
                    r.putData<const char*>(cur_func->name);
                }
                return true;
            } else {
                /* Otherwise call the appropriate function */
                for (; cur_func->name != NULL; cur_func++) {
                    if (strcmp(cur_func->name, args.method_name) == 0) {
                        (cur_func->function_caller)(&args, &r);
                        return true;
                    }
                }
                return false;
            }
        }
    }

    return false;
}

} // namespace mbed
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: locale.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-20 10:16:57 $
 *
 *  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 _COMPHELPER_LOCALE_HXX_
#define _COMPHELPER_LOCALE_HXX_

//_______________________________________________
// includes

#include <vector>

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

//_______________________________________________
// namespace

namespace comphelper{

//_______________________________________________
// definitions

/** @short  A Locale object represents a specific geographical, political, or cultural region.

    @descr  This Locale class can be used to:
            - provide the different parts of a Locale (Language, Country, Variant)
            - converting it from/to ISO formated string values (like e.g. "en-US")
            - provide some predefined (static) Locale objects
 */
class Locale
{
    //-------------------------------------------
    // const

    public:

        /** @short seperates LANGUAGE and COUNTRY part of an ISO formated Locale. */
        static const sal_Unicode SEPERATOR_LC;

        /** @short seperates COUNTRY and VARIANT part of an ISO formated Locale. */
        static const sal_Unicode SEPERATOR_CV;

        /** @short seperates COUNTRY and VARIANT part of an ISO formated Locale.
            @descr Its true for some linux derivates only :-( */
        static const sal_Unicode SEPERATOR_CV_LINUX;

        /** @short some predefined Locale objects. */
        static const Locale EN_US();
        static const Locale DE_DE();
        static const Locale DE_CH();
        static const Locale DE_AT();
        static const Locale AR();
        static const Locale CA();
        static const Locale CS();
        static const Locale DA();
        static const Locale EL();
        static const Locale ES();
        static const Locale FI();
        static const Locale FR();
        static const Locale HE();
        static const Locale HI_IN();
        static const Locale HU();
        static const Locale IT();
        static const Locale JA();
        static const Locale KO();
        static const Locale NL();
        static const Locale PL();
        static const Locale PT();
        static const Locale PT_BR();
        static const Locale RU();
        static const Locale SK();
        static const Locale SL();
        static const Locale SV();
        static const Locale TH();
        static const Locale TR();
        static const Locale X_DEFAULT();
        static const Locale X_COMMENT();
        static const Locale X_TRANSLATE();
        static const Locale X_NOTRANSLATE();
        static const Locale ZH_CN();
        static const Locale ZH_TW();

    //-------------------------------------------
    // types

    public:

        /** @short will be throw during convertion, if a Locale cant be interpreted. */
        struct MalFormedLocaleException
        {
            public:
                ::rtl::OUString Message;

                MalFormedLocaleException()
                {}

                MalFormedLocaleException(const ::rtl::OUString& sMessage)
                    : Message(sMessage)
                {}
        };

    //-------------------------------------------
    // member

    private :

        //---------------------------------------
        /** @short  must be a valid ISO Language Code.

            @descr  These codes are the lower-case two-letter codes as defined by ISO-639.
                    You can find a full list of these codes at a number of sites, such as:

                    http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
         */
        ::rtl::OUString m_sLanguage;

        //---------------------------------------
        /** @short  must be a valid ISO Country Code.
            @descr  These codes are the upper-case two-letter codes as defined by ISO-3166.
                    You can find a full list of these codes at a number of sites, such as:

                    http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
         */
        ::rtl::OUString m_sCountry;

        //---------------------------------------
        /** @short  Variant codes are vendor and browser-specific.
            @descr  For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX.
                    Where there are two variants, separate them with an underscore, and
                    put the most important one first. For example, a Traditional Spanish collation
                    might be referenced, with "ES", "ES", "Traditional_WIN".
         */
        ::rtl::OUString m_sVariant;

    //-------------------------------------------
    // interface

    public :

        //---------------------------------------
        /** @short  needed by outside users!

            @descr  Otherwise it wouldnt be possible to use
                    any instance of such Locale static ...
         */
        Locale();

        //---------------------------------------
        /** @short      construct a Locale from an ISO formated string value.

            @seealso    fromISO()

            @param      sISO
                        an ISO formated string value, which can be parsed and
                        tokenized into a Lamnguage, Country and Variant part.

            @throw      MalFormedLocaleException
                        if conversion failed.
          */
        Locale(const ::rtl::OUString& sISO)
            throw(MalFormedLocaleException);

        //---------------------------------------
        /** @short      construct a Locale from language, country and variant.

            @seealso    setLanguage()
            @seealso    setCountry()
            @seealso    setVariant()

            @param      sLanguage
                        lowercase two-letter ISO-639 code.

            @param      sCountry
                        uppercase two-letter ISO-3166 code.

            @param      sVariant
                        vendor and browser specific code.
          */
        Locale(const ::rtl::OUString& sLanguage                   ,
               const ::rtl::OUString& sCountry                    ,
               const ::rtl::OUString& sVariant = ::rtl::OUString());

        //---------------------------------------
        /** @short  copy constructor.

            @param  aCopy
                    the copy object.
         */
        Locale(const Locale& aCopy);

        //---------------------------------------
        /** @short  returns the language code for this locale.

            @descr  That will either be the empty string or
                    a lowercase ISO 639 code.

            @return [string]
                    the language code.
         */
        ::rtl::OUString getLanguage() const;

        //---------------------------------------
        /** @short  returns the country/region code for this locale.

            @descr  That will either be the empty string or an
                    upercase ISO 3166 2-letter code.

            @return [string]
                    the country code.
         */
        ::rtl::OUString getCountry() const;

        //---------------------------------------
        /** @short  returns the variant code for this locale.

            @return [string]
                    the variant code.
         */
        ::rtl::OUString getVariant() const;

        //---------------------------------------
        /** @short  set the new language code for this locale.

            @descr  That will either be the empty string or
                    a lowercase ISO 639 code.

            @param  sLanguage
                    the language code.
         */
        void setLanguage(const ::rtl::OUString& sLanguage);

        //---------------------------------------
        /** @short  set the new country/region code for this locale.

            @descr  That will either be the empty string or an
                    upercase ISO 3166 2-letter code.

            @param  sCountry
                    the country code.
         */
        void setCountry(const ::rtl::OUString& sCountry);

        //---------------------------------------
        /** @short  set the new variant code for this locale.

            @param  sVariant
                    the variant code.
         */
        void setVariant(const ::rtl::OUString& sVariant);

        //---------------------------------------
        /** @short      take over new Locale informations.

            @seealso    Locale(const ::rtl::OUString& sISO)

            @param      sISO
                        an ISO formated string value, which can be parsed and
                        tokenized into a Lamnguage, Country and Variant part.
                        e.g. "en-US" or "en-US_WIN"

            @throw      MalFormedLocaleException
                        if conversion failed.
          */
        void fromISO(const ::rtl::OUString& sISO)
            throw(MalFormedLocaleException);

        //---------------------------------------
        /** @short  converts this Locale to an ISO formated string value.

            @descr  The different parts of this Locale will be assempled
                    e.g. to "en-US" or "en-US_WIN"

            @return [string]
                    the ISO formated string.
          */
        ::rtl::OUString toISO() const;

        //---------------------------------------
        /** @short  check, if two Locale objects are equals.

            @descr  All parts of a Locale (means Language, Country and Variant)
                    will be checked.

            @param  aComparable
                    the Locale object for compare.

            @return [boolean]
                    TRUE if both objects uses the same values for
                    Language, Country and Variant.
         */
        sal_Bool equals(const Locale& aComparable) const;

        //---------------------------------------
        /** @short  check, if two Locale objects
                    uses the same language.

            @descr  The Country and Variant parts of a Locale
                    wont be checked here.

            @return [boolean]
                    TRUE if both objects uses the same
                    Language value.
         */
        sal_Bool similar(const Locale& aComparable) const;

        //---------------------------------------
        /** @short      search for an equal or at least for a similar
                        Locale in a list of possible ones.

            @descr      First it searches for a Locale, which is equals
                        to the reference Locale.
                        (means: same Language, Country, Variant)

                        If the reference Locale couldnt be located, it will
                        tried again - but we are checking for "similar" Locales then.
                        (means: same Language)

                        If no similar Locale could be located, we search
                        for a Locale "en-US" inside the given Locale list.

                        If "en-US" could not be located, we search for
                        a Locale "en" inside the given list.

                        Further fallbacks are not implemented :-)

            @seealso    equals()
            @seealso    similar()

            @param      lISOList
                        the list of possible Locales
                        (as formated ISO strings).

            @param      sReferenceISO
                        the reference Locale, which should be searched
                        if its equals or similar to any Locale inside
                        the provided Locale list.

            @return     An iterator, which points to the found element
                        inside the given Locale list.
                        If no matching Locale could be found, it points
                        to the end of the list.

            @throw      [MalFormedLocaleException]
                        if at least one ISO formated string couldnt
                        be converted to a valid Locale Object.
         */
        static ::std::vector< ::rtl::OUString >::const_iterator getFallback(const ::std::vector< ::rtl::OUString >& lISOList     ,
                                                                            const ::rtl::OUString&                  sReferenceISO)
            throw(MalFormedLocaleException);

        //---------------------------------------
        /** @short      search for the next possible fallback locale.

            @descr      Instead of getFallback(vector<>, string) this method
                        uses the given locale and decide by using an algorithm
                        which locale can be the next possible one.

                        Algorithm:
                        - if locale has country return language only
                        - if locale different "en-US" return "en-US"
                        - if locale "en-US" return "en"

            @param      aLocale [in/out]!
                        the incoming value will be used to start
                        search for a possible fallback ...
                        and in case such fallback was found this parameter
                        will be used for return too.

            @return     TRUE if the parameter aLocale contains a new fallback value;
                        FALSE otherwise.
         */
        static sal_Bool getFallback(Locale& aLocale);

        //---------------------------------------
        /** @short      assign elements of another locale
                        to this instance.

            @param      rCopy
                        another locale object.
         */
        void operator=(const Locale& rCopy);

        //---------------------------------------
        /** @short      check if two Locale objects are equals.

            @seealso    equals()

            @param      aComparable
                        the Locale object for compare.

            @return     [boolean]
                        TRUE if both objects uses the same values for
                        Language, Country and Variant.
         */
        sal_Bool operator==(const Locale& aComparable) const;

        //---------------------------------------
        /** @short  check if two Locale objects are different.

            @param  aComparable
                    the Locale object for compare.

            @return [boolean]
                    TRUE if at least one part of such Locale
                    isnt the same.
         */
        sal_Bool operator!=(const Locale& aComparable) const;
};

} // namespace salhelper

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

#ifndef _COMPHELPER_LOCALE_HXX_
#define _COMPHELPER_LOCALE_HXX_

//_______________________________________________
// includes

#include <vector>

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

//_______________________________________________
// namespace

namespace comphelper{

//_______________________________________________
// definitions

/** @short  A Locale object represents a specific geographical, political, or cultural region.

    @descr  This Locale class can be used to:
            - provide the different parts of a Locale (Language, Country, Variant)
            - converting it from/to ISO formated string values (like e.g. "en-US")
            - provide some predefined (static) Locale objects
 */
class Locale
{
    //-------------------------------------------
    // const

    public:

        /** @short seperates LANGUAGE and COUNTRY part of an ISO formated Locale. */
        static const sal_Unicode SEPERATOR_LC;

        /** @short seperates COUNTRY and VARIANT part of an ISO formated Locale. */
        static const sal_Unicode SEPERATOR_CV;

        /** @short seperates COUNTRY and VARIANT part of an ISO formated Locale.
            @descr Its true for some linux derivates only :-( */
        static const sal_Unicode SEPERATOR_CV_LINUX;

        /** @short some predefined Locale objects. */
        static const Locale EN_US();
        static const Locale EN();
        static const Locale DE_DE();
        static const Locale DE_CH();
        static const Locale DE_AT();
        static const Locale AR();
        static const Locale CA();
        static const Locale CS();
        static const Locale DA();
        static const Locale EL();
        static const Locale ES();
        static const Locale FI();
        static const Locale FR();
        static const Locale HE();
        static const Locale HI_IN();
        static const Locale HU();
        static const Locale IT();
        static const Locale JA();
        static const Locale KO();
        static const Locale NL();
        static const Locale PL();
        static const Locale PT();
        static const Locale PT_BR();
        static const Locale RU();
        static const Locale SK();
        static const Locale SL();
        static const Locale SV();
        static const Locale TH();
        static const Locale TR();
        static const Locale X_DEFAULT();
        static const Locale X_COMMENT();
        static const Locale X_TRANSLATE();
        static const Locale X_NOTRANSLATE();
        static const Locale ZH_CN();
        static const Locale ZH_TW();

    //-------------------------------------------
    // types

    public:

        /** @short will be throw during convertion, if a Locale cant be interpreted. */
        struct MalFormedLocaleException
        {
            public:
                ::rtl::OUString Message;

                MalFormedLocaleException()
                {}

                MalFormedLocaleException(const ::rtl::OUString& sMessage)
                    : Message(sMessage)
                {}
        };

    //-------------------------------------------
    // member

    private :

        //---------------------------------------
        /** @short  must be a valid ISO Language Code.

            @descr  These codes are the lower-case two-letter codes as defined by ISO-639.
                    You can find a full list of these codes at a number of sites, such as:

                    http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
         */
        ::rtl::OUString m_sLanguage;

        //---------------------------------------
        /** @short  must be a valid ISO Country Code.
            @descr  These codes are the upper-case two-letter codes as defined by ISO-3166.
                    You can find a full list of these codes at a number of sites, such as:

                    http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
         */
        ::rtl::OUString m_sCountry;

        //---------------------------------------
        /** @short  Variant codes are vendor and browser-specific.
            @descr  For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX.
                    Where there are two variants, separate them with an underscore, and
                    put the most important one first. For example, a Traditional Spanish collation
                    might be referenced, with "ES", "ES", "Traditional_WIN".
         */
        ::rtl::OUString m_sVariant;

    //-------------------------------------------
    // interface

    public :

        //---------------------------------------
        /** @short  needed by outside users!

            @descr  Otherwise it wouldnt be possible to use
                    any instance of such Locale static ...
         */
        Locale();

        //---------------------------------------
        /** @short      construct a Locale from an ISO formated string value.

            @seealso    fromISO()

            @param      sISO
                        an ISO formated string value, which can be parsed and
                        tokenized into a Lamnguage, Country and Variant part.

            @throw      MalFormedLocaleException
                        if conversion failed.
          */
        Locale(const ::rtl::OUString& sISO)
            throw(MalFormedLocaleException);

        //---------------------------------------
        /** @short      construct a Locale from language, country and variant.

            @seealso    setLanguage()
            @seealso    setCountry()
            @seealso    setVariant()

            @param      sLanguage
                        lowercase two-letter ISO-639 code.

            @param      sCountry
                        uppercase two-letter ISO-3166 code.

            @param      sVariant
                        vendor and browser specific code.
          */
        Locale(const ::rtl::OUString& sLanguage                   ,
               const ::rtl::OUString& sCountry                    ,
               const ::rtl::OUString& sVariant = ::rtl::OUString());

        //---------------------------------------
        /** @short  copy constructor.

            @param  aCopy
                    the copy object.
         */
        Locale(const Locale& aCopy);

        //---------------------------------------
        /** @short  returns the language code for this locale.

            @descr  That will either be the empty string or
                    a lowercase ISO 639 code.

            @return [string]
                    the language code.
         */
        ::rtl::OUString getLanguage() const;

        //---------------------------------------
        /** @short  returns the country/region code for this locale.

            @descr  That will either be the empty string or an
                    upercase ISO 3166 2-letter code.

            @return [string]
                    the country code.
         */
        ::rtl::OUString getCountry() const;

        //---------------------------------------
        /** @short  returns the variant code for this locale.

            @return [string]
                    the variant code.
         */
        ::rtl::OUString getVariant() const;

        //---------------------------------------
        /** @short  set the new language code for this locale.

            @descr  That will either be the empty string or
                    a lowercase ISO 639 code.

            @param  sLanguage
                    the language code.
         */
        void setLanguage(const ::rtl::OUString& sLanguage);

        //---------------------------------------
        /** @short  set the new country/region code for this locale.

            @descr  That will either be the empty string or an
                    upercase ISO 3166 2-letter code.

            @param  sCountry
                    the country code.
         */
        void setCountry(const ::rtl::OUString& sCountry);

        //---------------------------------------
        /** @short  set the new variant code for this locale.

            @param  sVariant
                    the variant code.
         */
        void setVariant(const ::rtl::OUString& sVariant);

        //---------------------------------------
        /** @short      take over new Locale informations.

            @seealso    Locale(const ::rtl::OUString& sISO)

            @param      sISO
                        an ISO formated string value, which can be parsed and
                        tokenized into a Lamnguage, Country and Variant part.
                        e.g. "en-US" or "en-US_WIN"

            @throw      MalFormedLocaleException
                        if conversion failed.
          */
        void fromISO(const ::rtl::OUString& sISO)
            throw(MalFormedLocaleException);

        //---------------------------------------
        /** @short  converts this Locale to an ISO formated string value.

            @descr  The different parts of this Locale will be assempled
                    e.g. to "en-US" or "en-US_WIN"

            @return [string]
                    the ISO formated string.
          */
        ::rtl::OUString toISO() const;

        //---------------------------------------
        /** @short  check, if two Locale objects are equals.

            @descr  All parts of a Locale (means Language, Country and Variant)
                    will be checked.

            @param  aComparable
                    the Locale object for compare.

            @return [boolean]
                    TRUE if both objects uses the same values for
                    Language, Country and Variant.
         */
        sal_Bool equals(const Locale& aComparable) const;

        //---------------------------------------
        /** @short  check, if two Locale objects
                    uses the same language.

            @descr  The Country and Variant parts of a Locale
                    wont be checked here.

            @return [boolean]
                    TRUE if both objects uses the same
                    Language value.
         */
        sal_Bool similar(const Locale& aComparable) const;

        //---------------------------------------
        /** @short      search for an equal or at least for a similar
                        Locale in a list of possible ones.

            @descr      First it searches for a Locale, which is equals
                        to the reference Locale.
                        (means: same Language, Country, Variant)

                        If the reference Locale couldnt be located, it will
                        tried again - but we are checking for "similar" Locales then.
                        (means: same Language)

                        If no similar Locale could be located, we search
                        for a Locale "en-US" inside the given Locale list.

                        If "en-US" could not be located, we search for
                        a Locale "en" inside the given list.

                        Further fallbacks are not implemented :-)

            @seealso    equals()
            @seealso    similar()

            @param      lISOList
                        the list of possible Locales
                        (as formated ISO strings).

            @param      sReferenceISO
                        the reference Locale, which should be searched
                        if its equals or similar to any Locale inside
                        the provided Locale list.

            @return     An iterator, which points to the found element
                        inside the given Locale list.
                        If no matching Locale could be found, it points
                        to the end of the list.

            @throw      [MalFormedLocaleException]
                        if at least one ISO formated string couldnt
                        be converted to a valid Locale Object.
         */
        static ::std::vector< ::rtl::OUString >::const_iterator getFallback(const ::std::vector< ::rtl::OUString >& lISOList     ,
                                                                            const ::rtl::OUString&                  sReferenceISO)
            throw(MalFormedLocaleException);

        //---------------------------------------
        /** @short      search for the next possible fallback locale.

            @descr      Instead of getFallback(vector<>, string) this method
                        uses the given locale and decide by using an algorithm
                        which locale can be the next possible one.

                        Algorithm:
                        - if locale has country return language only
                        - if locale different "en-US" return "en-US"
                        - if locale "en-US" return "en"

            @param      aLocale [in/out]!
                        the incoming value will be used to start
                        search for a possible fallback ...
                        and in case such fallback was found this parameter
                        will be used for return too.

            @return     TRUE if the parameter aLocale contains a new fallback value;
                        FALSE otherwise.
         */
        static sal_Bool getFallback(Locale& aLocale);

        //---------------------------------------
        /** @short      assign elements of another locale
                        to this instance.

            @param      rCopy
                        another locale object.
         */
        void operator=(const Locale& rCopy);

        //---------------------------------------
        /** @short      check if two Locale objects are equals.

            @seealso    equals()

            @param      aComparable
                        the Locale object for compare.

            @return     [boolean]
                        TRUE if both objects uses the same values for
                        Language, Country and Variant.
         */
        sal_Bool operator==(const Locale& aComparable) const;

        //---------------------------------------
        /** @short  check if two Locale objects are different.

            @param  aComparable
                    the Locale object for compare.

            @return [boolean]
                    TRUE if at least one part of such Locale
                    isnt the same.
         */
        sal_Bool operator!=(const Locale& aComparable) const;
};

} // namespace salhelper

#endif // _COMPHELPER_LOCALE_HXX_
<|endoftext|>


<commit_before>#include "xalt_config.h"
#include "xalt_version.h"
#include <iostream>
#include <time.h>
#include "epoch.h"
#define DATESZ 100

int main(int argc, char* argv[])
{
  char    dateStr[DATESZ];
  time_t  now = (time_t) epoch();
  strftime(dateStr,DATESZ, "%c", localtime(&now));

  std::cout << "*------------------------------------------------------------------------------*\n";
  std::cout << "                      XALT Configuration Report\n";
  std::cout << "*------------------------------------------------------------------------------*\n\n";
  std::cout << "Today's DATE:              " << dateStr            << "\n";
  std::cout << "XALT_VERSION:              " << XALT_VERSION       << "\n";
  std::cout << "XALT_GIT_VERSION:          " << XALT_GIT_VERSION   << "\n";
  std::cout << "XALT_VERSION_STR:          " << XALT_VERSION_STR   << "\n";
  std::cout << "*------------------------------------------------------------------------------*\n\n";
  std::cout << "XALT_TRANSMISSION_STYLE:   " << TRANSMISSION       << "\n";
  std::cout << "XALT_ETC_DIR:              " << XALT_ETC_DIR       << "\n";
  std::cout << "XALT_CONFIG_PY:            " << XALT_CONFIG_PY     << "\n";
  std::cout << "XALT_SYSTEM_PATH:          " << XALT_SYSTEM_PATH   << "\n";
  std::cout << "XALT_SYSLOG_MSG_SZ:        " << SYSLOG_MSG_SZ      << "\n";
  std::cout << "HAVE_32BIT:                " << HAVE_32BIT         << "\n";

  return 0;
}
<commit_msg>small change to test git version generation<commit_after>#include "xalt_config.h"
#include "xalt_version.h"
#include <iostream>
#include <time.h>
#include "epoch.h"

const int dateSZ=100

int main(int argc, char* argv[])
{
  char    dateStr[dateSZ];
  time_t  now = (time_t) epoch();
  strftime(dateStr,dateSZ, "%c", localtime(&now));

  std::cout << "*------------------------------------------------------------------------------*\n";
  std::cout << "                      XALT Configuration Report\n";
  std::cout << "*------------------------------------------------------------------------------*\n\n";
  std::cout << "Today's DATE:              " << dateStr            << "\n";
  std::cout << "XALT_VERSION:              " << XALT_VERSION       << "\n";
  std::cout << "XALT_GIT_VERSION:          " << XALT_GIT_VERSION   << "\n";
  std::cout << "XALT_VERSION_STR:          " << XALT_VERSION_STR   << "\n";
  std::cout << "*------------------------------------------------------------------------------*\n\n";
  std::cout << "XALT_TRANSMISSION_STYLE:   " << TRANSMISSION       << "\n";
  std::cout << "XALT_ETC_DIR:              " << XALT_ETC_DIR       << "\n";
  std::cout << "XALT_CONFIG_PY:            " << XALT_CONFIG_PY     << "\n";
  std::cout << "XALT_SYSTEM_PATH:          " << XALT_SYSTEM_PATH   << "\n";
  std::cout << "XALT_SYSLOG_MSG_SZ:        " << SYSLOG_MSG_SZ      << "\n";
  std::cout << "HAVE_32BIT:                " << HAVE_32BIT         << "\n";

  return 0;
}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetCommonToolsTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetCommonToolsTest
#include <boost/test/unit_test.hpp>
#include <map>
#include "JPetCommonTools.h"

BOOST_AUTO_TEST_SUITE(CommonToolsTestSuite)

BOOST_AUTO_TEST_CASE(findSubstringTest)
{
  std::string str("There are two needles in this haystack with needles.");
  std::string str2("needle");

  std::size_t found = JPetCommonTools::findSubstring(str, str2);
  BOOST_REQUIRE_EQUAL(found != std::string::npos, true);
}

BOOST_AUTO_TEST_CASE(ItoaTest)
{
  int testNumber = 64;

  std::string intAsASting = JPetCommonTools::Itoa(testNumber);
  BOOST_REQUIRE_EQUAL(intAsASting == "64", true);
}

BOOST_AUTO_TEST_CASE(intToStringTest)
{
  int testNumber = 64;

  std::string intAsASting = JPetCommonTools::intToString(testNumber);
  BOOST_REQUIRE_EQUAL(intAsASting == "64", true);
}

BOOST_AUTO_TEST_CASE(doubleToStringTest)
{
  double testNumber = 256.3264;

  std::string doubleAsASting = JPetCommonTools::doubleToString(testNumber);
  BOOST_REQUIRE_EQUAL(doubleAsASting == "256.326", true);
}

BOOST_AUTO_TEST_CASE(stringToIntTest)
{
  std::string testString = "1024";

  int stringAsAInt = JPetCommonTools::stringToInt(testString);
  BOOST_REQUIRE_EQUAL(stringAsAInt == 1024, true);
}

BOOST_AUTO_TEST_CASE(toBoolTest)
{
  std::string testString = "0";

  bool stringAsABool = JPetCommonTools::to_bool(testString);
  BOOST_REQUIRE_EQUAL(stringAsABool == false, true);
}

BOOST_AUTO_TEST_CASE(ifFileExistingTest)
{
  std::string fileTest = "run_tests.pl";

  bool ifFileExisting = JPetCommonTools::ifFileExisting(fileTest);
  BOOST_REQUIRE_EQUAL(ifFileExisting, true);
}

BOOST_AUTO_TEST_CASE(mapAreEqualTest)
{
  std::map<int, int> mapTestLeft, mapTestRight;
  bool areMapsEqual = JPetCommonTools::mapComparator(mapTestLeft, mapTestRight);
  BOOST_REQUIRE_EQUAL(areMapsEqual, true);
}

BOOST_AUTO_TEST_CASE(mapAreNotEqualTest)
{
  std::map<char,int> first;
  first['a']=10;
  first['b']=30;
  first['c']=50;
  first['d']=70;
  std::map<char,int> second;

  bool areMapsEqual = JPetCommonTools::mapComparator(first, second);
  BOOST_REQUIRE_EQUAL(areMapsEqual, false);
}

BOOST_AUTO_TEST_CASE(stripFileNameSuffixTest)
{
  std::string fileTest = "run_tests.pl";

  std::string stripFileNameSuffix = JPetCommonTools::stripFileNameSuffix(fileTest);
  BOOST_REQUIRE_EQUAL(stripFileNameSuffix == "run_tests", true);
}

BOOST_AUTO_TEST_CASE(currentFullPathTest)
{
  std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string();

  std::string currentFullPath = JPetCommonTools::currentFullPath();
  BOOST_REQUIRE_EQUAL(currentFullPath == currentFullPathTest, true);
}

BOOST_AUTO_TEST_CASE(extractPathFromFileTest)
{
  std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string();
  std::string currentFullPathTestWithFileName = currentFullPathTest + "/" + "run_tests.pl";

  std::string result = JPetCommonTools::extractPathFromFile(currentFullPathTestWithFileName);
  BOOST_REQUIRE_EQUAL(result.compare(currentFullPathTest), 0);
}

BOOST_AUTO_TEST_CASE(isDirectory)
{
  BOOST_REQUIRE(JPetCommonTools::isDirectory(boost::filesystem::initial_path().string()));
  BOOST_REQUIRE(!JPetCommonTools::isDirectory("fake/directory/baba"));
}

BOOST_AUTO_TEST_CASE(appendSlashToPathIfAbsent)
{
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent(""), "");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("./"), "./");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home/"), "/home/");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home"), "/home/");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("home/bbl/be"), "home/bbl/be/");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("test"), "test/");
}

BOOST_AUTO_TEST_CASE(tryToUnzipSomethingNotExistingFile)
{
  BOOST_REQUIRE_EQUAL(JPetCommonTools::unzipFile("kiko.gz"), false);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Added test which checks if wrongly zipped file will be found<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetCommonToolsTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetCommonToolsTest
#include <boost/test/unit_test.hpp>
#include <map>
#include "JPetCommonTools.h"

BOOST_AUTO_TEST_SUITE(CommonToolsTestSuite)

BOOST_AUTO_TEST_CASE(findSubstringTest)
{
  std::string str("There are two needles in this haystack with needles.");
  std::string str2("needle");

  std::size_t found = JPetCommonTools::findSubstring(str, str2);
  BOOST_REQUIRE_EQUAL(found != std::string::npos, true);
}

BOOST_AUTO_TEST_CASE(ItoaTest)
{
  int testNumber = 64;

  std::string intAsASting = JPetCommonTools::Itoa(testNumber);
  BOOST_REQUIRE_EQUAL(intAsASting == "64", true);
}

BOOST_AUTO_TEST_CASE(intToStringTest)
{
  int testNumber = 64;

  std::string intAsASting = JPetCommonTools::intToString(testNumber);
  BOOST_REQUIRE_EQUAL(intAsASting == "64", true);
}

BOOST_AUTO_TEST_CASE(doubleToStringTest)
{
  double testNumber = 256.3264;

  std::string doubleAsASting = JPetCommonTools::doubleToString(testNumber);
  BOOST_REQUIRE_EQUAL(doubleAsASting == "256.326", true);
}

BOOST_AUTO_TEST_CASE(stringToIntTest)
{
  std::string testString = "1024";

  int stringAsAInt = JPetCommonTools::stringToInt(testString);
  BOOST_REQUIRE_EQUAL(stringAsAInt == 1024, true);
}

BOOST_AUTO_TEST_CASE(toBoolTest)
{
  std::string testString = "0";

  bool stringAsABool = JPetCommonTools::to_bool(testString);
  BOOST_REQUIRE_EQUAL(stringAsABool == false, true);
}

BOOST_AUTO_TEST_CASE(ifFileExistingTest)
{
  std::string fileTest = "run_tests.pl";

  bool ifFileExisting = JPetCommonTools::ifFileExisting(fileTest);
  BOOST_REQUIRE_EQUAL(ifFileExisting, true);
}

BOOST_AUTO_TEST_CASE(mapAreEqualTest)
{
  std::map<int, int> mapTestLeft, mapTestRight;
  bool areMapsEqual = JPetCommonTools::mapComparator(mapTestLeft, mapTestRight);
  BOOST_REQUIRE_EQUAL(areMapsEqual, true);
}

BOOST_AUTO_TEST_CASE(mapAreNotEqualTest)
{
  std::map<char,int> first;
  first['a']=10;
  first['b']=30;
  first['c']=50;
  first['d']=70;
  std::map<char,int> second;

  bool areMapsEqual = JPetCommonTools::mapComparator(first, second);
  BOOST_REQUIRE_EQUAL(areMapsEqual, false);
}

BOOST_AUTO_TEST_CASE(stripFileNameSuffixTest)
{
  std::string fileTest = "run_tests.pl";

  std::string stripFileNameSuffix = JPetCommonTools::stripFileNameSuffix(fileTest);
  BOOST_REQUIRE_EQUAL(stripFileNameSuffix == "run_tests", true);
}

BOOST_AUTO_TEST_CASE(currentFullPathTest)
{
  std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string();

  std::string currentFullPath = JPetCommonTools::currentFullPath();
  BOOST_REQUIRE_EQUAL(currentFullPath == currentFullPathTest, true);
}

BOOST_AUTO_TEST_CASE(extractPathFromFileTest)
{
  std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string();
  std::string currentFullPathTestWithFileName = currentFullPathTest + "/" + "run_tests.pl";

  std::string result = JPetCommonTools::extractPathFromFile(currentFullPathTestWithFileName);
  BOOST_REQUIRE_EQUAL(result.compare(currentFullPathTest), 0);
}

BOOST_AUTO_TEST_CASE(isDirectory)
{
  BOOST_REQUIRE(JPetCommonTools::isDirectory(boost::filesystem::initial_path().string()));
  BOOST_REQUIRE(!JPetCommonTools::isDirectory("fake/directory/baba"));
}

BOOST_AUTO_TEST_CASE(appendSlashToPathIfAbsent)
{
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent(""), "");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("./"), "./");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home/"), "/home/");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home"), "/home/");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("home/bbl/be"), "home/bbl/be/");
  BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("test"), "test/");
}

BOOST_AUTO_TEST_CASE(tryToUnzipSomethingNotExistingFile)
{
  BOOST_REQUIRE_EQUAL(JPetCommonTools::unzipFile("kiko.gz"), true);
  std::string initialPath= boost::filesystem::path(boost::filesystem::current_path()).string();
  initialPath = initialPath.substr(0, initialPath.find("build") );
  std::string wrongZipPath = initialPath + "j-pet-framework/unitTestData/JPetCommonToolsTest/wrongZip.gz";
  BOOST_REQUIRE_EQUAL(JPetCommonTools::unzipFile( wrongZipPath.c_str() ), true);

}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>


<commit_before>// kmfolderdir.cpp

#include <config.h>

#include "kmfolderdir.h"
#include "kmfoldersearch.h"
#include "kmfoldercachedimap.h"
#include "kmfolder.h"

#include <assert.h>
#include <errno.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kstandarddirs.h>

#include <QDir>
#include <QList>
#include <QByteArray>

//=============================================================================
//=============================================================================
KMFolderRootDir::KMFolderRootDir(KMFolderMgr* manager, const QString& path,
                                 KMFolderDirType dirType)
  : KMFolderDir( 0, 0, path, dirType ),
    mPath( path ),
    mManager( manager )
{
}

//-----------------------------------------------------------------------------
KMFolderRootDir::~KMFolderRootDir()
{
  // WABA: We can't let KMFolderDir do this because by the time its
  // desctructor gets called, KMFolderRootDir is already destructed
  // Most notably the path.
  clear();
}

//-----------------------------------------------------------------------------
void KMFolderRootDir::setPath(const QString& aPath)
{
  mPath = aPath;
}

//-----------------------------------------------------------------------------
QString KMFolderRootDir::path() const
{
  return mPath;
}

//-----------------------------------------------------------------------------
QString KMFolderRootDir::prettyUrl() const
{
  if ( !mBaseURL.isEmpty() )
    return i18n( mBaseURL.data() );
  else
    return QString();
}

//-----------------------------------------------------------------------------
void KMFolderRootDir::setBaseURL( const QByteArray &baseURL )
{
  mBaseURL = baseURL;
}

//-----------------------------------------------------------------------------
KMFolderMgr* KMFolderRootDir::manager() const
{
  return mManager;
}

//=============================================================================
//=============================================================================
KMFolderDir::KMFolderDir( KMFolder * owner, KMFolderDir* parent,
                          const QString& name, KMFolderDirType dirType )
  : KMFolderNode( parent, name ), KMFolderNodeList(),
    mOwner( owner ), mDirType( dirType )
{}

//-----------------------------------------------------------------------------
KMFolderDir::~KMFolderDir()
{
  clear();
  qDeleteAll( *this );
}

//-----------------------------------------------------------------------------
KMFolder* KMFolderDir::createFolder(const QString& aFolderName, bool aSysFldr, KMFolderType aFolderType)
{
  KMFolder* fld;

  assert(!aFolderName.isEmpty());
  // FIXME urgs, is this still needed
  if (mDirType == KMImapDir)
    fld = new KMFolder( this, aFolderName, KMFolderTypeImap );
  else
    fld = new KMFolder( this, aFolderName, aFolderType );

  assert(fld != 0);
  fld->setSystemFolder(aSysFldr);

  KMFolderNode* fNode = 0;
  QList<KMFolderNode*>::const_iterator it;
  int index = 0;
  for ( it = begin(); it != end(); ++it ) {
    fNode = *it;
    if (fNode->name().toLower() > fld->name().toLower()) {
      insert( index, fld );
      break;
    }
    ++index;
  }

  if (!fNode)
    append(fld);

  fld->correctUnreadMsgsCount();
  return fld;
}

//----------------------------------------------------------------------------
QString KMFolderDir::path() const
{
  static QString p;

  if (parent())
  {
    p = parent()->path();
    p.append("/");
    p.append(name());
  }
  else p = "";

  return p;
}

//----------------------------------------------------------------------------
QString KMFolderDir::label() const
{
  if ( mOwner )
    return mOwner->label();
  else
    return QString();
}

//-----------------------------------------------------------------------------
QString KMFolderDir::prettyUrl() const
{
  QString parentUrl;
  if ( parent() )
    parentUrl = parent()->prettyUrl();
  if ( !parentUrl.isEmpty() )
    return parentUrl + '/' + label();
  else
    return label();
}

//-----------------------------------------------------------------------------
bool KMFolderDir::reload(void)
{
  QDir             dir;
  KMFolder*        folder;
  QFileInfo        fileInfo;
  QStringList      diList;
  QList<KMFolder*> folderList;

  clear();

  const QString fldPath = path();
  dir.setFilter(QDir::Files | QDir::Dirs | QDir::Hidden);
  dir.setNameFilters(QStringList("*"));

  if (!dir.cd(fldPath))
  {
    QString msg = i18n("<qt>Cannot enter folder %1.</qt>", fldPath);
    KMessageBox::information(0, msg);
    return false;
  }

  QFileInfoList fiList = dir.entryInfoList();
  if (fiList.isEmpty())
  {
    QString msg = i18n("<qt>Folder %1 is unreadable.</qt>", fldPath);
    KMessageBox::information(0, msg);
    return false;
  }

  Q_FOREACH( fileInfo, fiList )
  {
    const QString fname = fileInfo.fileName();
    if( ( fname[0] == '.' ) && !fname.endsWith( ".directory" ) ) {
      // ignore all hidden files except our subfolder containers
      continue;
    }
    if( fname == ".directory" ) {
      // ignore .directory files (not created by us)
      continue;
    }
    // Collect subdirectories.
    if ( fileInfo.isDir() &&
         fname.startsWith( "." ) && fname.endsWith( ".directory" ) ) {
       diList.append(fname);
       continue;
    }

    if ( mDirType == KMImapDir
      && path().startsWith( KMFolderImap::cacheLocation() ) )
    {
       // Is the below needed for dimap as well?
       if ( KMFolderImap::encodeFileName(
                KMFolderImap::decodeFileName( fname ) ) == fname )
       {
          folder = new KMFolder(  this, KMFolderImap::decodeFileName( fname ),
                                  KMFolderTypeImap );
          append(folder);
          folderList.append(folder);
       }
    }
    else if ( mDirType == KMDImapDir
           && path().startsWith( KMFolderCachedImap::cacheLocation() ) )
    {
       if (fileInfo.isDir()) // a directory
       {
          // For this to be a cached IMAP folder, it must be in the KMail dimap
          // subdir and must be have a uidcache file or be a maildir folder
          QString maildir(fname + "/new");
          QString imapcachefile = QString::fromLatin1(".%1.uidcache").arg(fname);
          if ( dir.exists( imapcachefile) || dir.exists( maildir ) )
          {
             folder = new KMFolder( this, fname, KMFolderTypeCachedImap );
             append(folder);
             folderList.append(folder);
          }
       }
    }
    else if ( mDirType == KMSearchDir)
    {
       folder = new KMFolder( this, fname, KMFolderTypeSearch );
       append(folder);
       folderList.append(folder);
    }
    else if ( mDirType == KMStandardDir )
    {
       // This is neither an imap, dimap nor a search folder. Can be either
       // mbox or maildir.
       if (fileInfo.isDir())
       {
          // Maildir folder
          if( dir.exists( fname + "/new" ) )
          {
             folder = new KMFolder( this, fname, KMFolderTypeMaildir );
             append(folder);
             folderList.append(folder);
          }
       }
       else
       {
          // all other files are folders (at the moment ;-)
          folder = new KMFolder( this, fname, KMFolderTypeMbox );
          append(folder);
          folderList.append(folder);
       }
    }
  }

  QList<KMFolder*>::const_iterator jt;
  for ( jt = folderList.begin();
      ( ( folder = *jt ) && ( jt != folderList.end() ) ); ++jt )
  {
    for(QStringList::Iterator it = diList.begin();
        it != diList.end();
        ++it)
      if (*it == '.' + folder->fileName() + ".directory")
      {
        KMFolderDir* folderDir = new KMFolderDir( folder, this, *it, mDirType);
        folderDir->reload();
        append(folderDir);
        folder->setChild(folderDir);
        break;
      }
  }
  return true;
}

//-----------------------------------------------------------------------------
KMFolderNode* KMFolderDir::hasNamedFolder(const QString& aName)
{
  QList<KMFolderNode*>::const_iterator it;
  for ( it = begin(); it != end(); ++it ) {
    if ( (*it) && (*it)->name() == aName)
      return (*it);
  }
  return 0;
}

//-----------------------------------------------------------------------------
KMFolderMgr* KMFolderDir::manager() const
{
  return parent()->manager();
}

#include "kmfolderdir.moc"

<commit_msg>Fix newly created subfolders not being shown. For real, this time.<commit_after>// kmfolderdir.cpp

#include <config.h>

#include "kmfolderdir.h"
#include "kmfoldersearch.h"
#include "kmfoldercachedimap.h"
#include "kmfolder.h"

#include <assert.h>
#include <errno.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kstandarddirs.h>

#include <QDir>
#include <QList>
#include <QByteArray>

//=============================================================================
//=============================================================================
KMFolderRootDir::KMFolderRootDir(KMFolderMgr* manager, const QString& path,
                                 KMFolderDirType dirType)
  : KMFolderDir( 0, 0, path, dirType ),
    mPath( path ),
    mManager( manager )
{
}

//-----------------------------------------------------------------------------
KMFolderRootDir::~KMFolderRootDir()
{
  // WABA: We can't let KMFolderDir do this because by the time its
  // desctructor gets called, KMFolderRootDir is already destructed
  // Most notably the path.
  clear();
}

//-----------------------------------------------------------------------------
void KMFolderRootDir::setPath(const QString& aPath)
{
  mPath = aPath;
}

//-----------------------------------------------------------------------------
QString KMFolderRootDir::path() const
{
  return mPath;
}

//-----------------------------------------------------------------------------
QString KMFolderRootDir::prettyUrl() const
{
  if ( !mBaseURL.isEmpty() )
    return i18n( mBaseURL.data() );
  else
    return QString();
}

//-----------------------------------------------------------------------------
void KMFolderRootDir::setBaseURL( const QByteArray &baseURL )
{
  mBaseURL = baseURL;
}

//-----------------------------------------------------------------------------
KMFolderMgr* KMFolderRootDir::manager() const
{
  return mManager;
}

//=============================================================================
//=============================================================================
KMFolderDir::KMFolderDir( KMFolder * owner, KMFolderDir* parent,
                          const QString& name, KMFolderDirType dirType )
  : KMFolderNode( parent, name ), KMFolderNodeList(),
    mOwner( owner ), mDirType( dirType )
{}

//-----------------------------------------------------------------------------
KMFolderDir::~KMFolderDir()
{
  clear();
  qDeleteAll( *this );
}

//-----------------------------------------------------------------------------
KMFolder* KMFolderDir::createFolder(const QString& aFolderName, bool aSysFldr, KMFolderType aFolderType)
{
  KMFolder* fld;

  assert(!aFolderName.isEmpty());
  // FIXME urgs, is this still needed
  if (mDirType == KMImapDir)
    fld = new KMFolder( this, aFolderName, KMFolderTypeImap );
  else
    fld = new KMFolder( this, aFolderName, aFolderType );

  assert(fld != 0);
  fld->setSystemFolder(aSysFldr);

  bool inserted = false;
  QList<KMFolderNode*>::const_iterator it;
  int index = 0;
  for ( it = begin(); it != end(); ++it ) {
    KMFolderNode* fNode = *it;
    if (fNode->name().toLower() > fld->name().toLower()) {
      insert( index, fld );
      inserted = true;
      break;
    }
    ++index;
  }

  if ( !inserted )
    append(fld);

  fld->correctUnreadMsgsCount();
  return fld;
}

//----------------------------------------------------------------------------
QString KMFolderDir::path() const
{
  static QString p;

  if (parent())
  {
    p = parent()->path();
    p.append("/");
    p.append(name());
  }
  else p = "";

  return p;
}

//----------------------------------------------------------------------------
QString KMFolderDir::label() const
{
  if ( mOwner )
    return mOwner->label();
  else
    return QString();
}

//-----------------------------------------------------------------------------
QString KMFolderDir::prettyUrl() const
{
  QString parentUrl;
  if ( parent() )
    parentUrl = parent()->prettyUrl();
  if ( !parentUrl.isEmpty() )
    return parentUrl + '/' + label();
  else
    return label();
}

//-----------------------------------------------------------------------------
bool KMFolderDir::reload(void)
{
  QDir             dir;
  KMFolder*        folder;
  QFileInfo        fileInfo;
  QStringList      diList;
  QList<KMFolder*> folderList;

  clear();

  const QString fldPath = path();
  dir.setFilter(QDir::Files | QDir::Dirs | QDir::Hidden);
  dir.setNameFilters(QStringList("*"));

  if (!dir.cd(fldPath))
  {
    QString msg = i18n("<qt>Cannot enter folder %1.</qt>", fldPath);
    KMessageBox::information(0, msg);
    return false;
  }

  QFileInfoList fiList = dir.entryInfoList();
  if (fiList.isEmpty())
  {
    QString msg = i18n("<qt>Folder %1 is unreadable.</qt>", fldPath);
    KMessageBox::information(0, msg);
    return false;
  }

  Q_FOREACH( fileInfo, fiList )
  {
    const QString fname = fileInfo.fileName();
    if( ( fname[0] == '.' ) && !fname.endsWith( ".directory" ) ) {
      // ignore all hidden files except our subfolder containers
      continue;
    }
    if( fname == ".directory" ) {
      // ignore .directory files (not created by us)
      continue;
    }
    // Collect subdirectories.
    if ( fileInfo.isDir() &&
         fname.startsWith( "." ) && fname.endsWith( ".directory" ) ) {
       diList.append(fname);
       continue;
    }

    if ( mDirType == KMImapDir
      && path().startsWith( KMFolderImap::cacheLocation() ) )
    {
       // Is the below needed for dimap as well?
       if ( KMFolderImap::encodeFileName(
                KMFolderImap::decodeFileName( fname ) ) == fname )
       {
          folder = new KMFolder(  this, KMFolderImap::decodeFileName( fname ),
                                  KMFolderTypeImap );
          append(folder);
          folderList.append(folder);
       }
    }
    else if ( mDirType == KMDImapDir
           && path().startsWith( KMFolderCachedImap::cacheLocation() ) )
    {
       if (fileInfo.isDir()) // a directory
       {
          // For this to be a cached IMAP folder, it must be in the KMail dimap
          // subdir and must be have a uidcache file or be a maildir folder
          QString maildir(fname + "/new");
          QString imapcachefile = QString::fromLatin1(".%1.uidcache").arg(fname);
          if ( dir.exists( imapcachefile) || dir.exists( maildir ) )
          {
             folder = new KMFolder( this, fname, KMFolderTypeCachedImap );
             append(folder);
             folderList.append(folder);
          }
       }
    }
    else if ( mDirType == KMSearchDir)
    {
       folder = new KMFolder( this, fname, KMFolderTypeSearch );
       append(folder);
       folderList.append(folder);
    }
    else if ( mDirType == KMStandardDir )
    {
       // This is neither an imap, dimap nor a search folder. Can be either
       // mbox or maildir.
       if (fileInfo.isDir())
       {
          // Maildir folder
          if( dir.exists( fname + "/new" ) )
          {
             folder = new KMFolder( this, fname, KMFolderTypeMaildir );
             append(folder);
             folderList.append(folder);
          }
       }
       else
       {
          // all other files are folders (at the moment ;-)
          folder = new KMFolder( this, fname, KMFolderTypeMbox );
          append(folder);
          folderList.append(folder);
       }
    }
  }

  QList<KMFolder*>::const_iterator jt;
  for ( jt = folderList.begin();
      ( ( folder = *jt ) && ( jt != folderList.end() ) ); ++jt )
  {
    for(QStringList::Iterator it = diList.begin();
        it != diList.end();
        ++it)
      if (*it == '.' + folder->fileName() + ".directory")
      {
        KMFolderDir* folderDir = new KMFolderDir( folder, this, *it, mDirType);
        folderDir->reload();
        append(folderDir);
        folder->setChild(folderDir);
        break;
      }
  }
  return true;
}

//-----------------------------------------------------------------------------
KMFolderNode* KMFolderDir::hasNamedFolder(const QString& aName)
{
  QList<KMFolderNode*>::const_iterator it;
  for ( it = begin(); it != end(); ++it ) {
    if ( (*it) && (*it)->name() == aName)
      return (*it);
  }
  return 0;
}

//-----------------------------------------------------------------------------
KMFolderMgr* KMFolderDir::manager() const
{
  return parent()->manager();
}

#include "kmfolderdir.moc"

<|endoftext|>