text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<sect1 id="zend.locale.introduction">
    <title>Introduction</title>

    <para>
        <classname>Zend_Locale</classname> is the Frameworks answer to the question, "How can the
        same application be used around the whole world?" Most people will say, "That's easy. Let's
        translate all our output to several languages." However, using simple translation tables to
        map phrases from one language to another is not sufficient. Different regions will have
        different conventions for first names, surnames, salutory titles, formatting of numbers,
        dates, times, currencies, etc.
    </para>

    <para>
        We need <ulink
            url="http://en.wikipedia.org/wiki/Internationalization_and_localization">Localization
            and complementary Internationalization</ulink>. Both are often abbreviated to
        <emphasis>L10n</emphasis> and <emphasis>I18n</emphasis>. Internationalization
        refers more to support for use of systems, regardless of special needs unique to groups of
        users related by language, region, number format conventions, financial conventions, time
        and date conventions, etc. Localization involves adding explicit support to systems for
        special needs of these unique groups, such as language translation, and support for local
        customs or conventions for communicating plurals, dates, times, currencies, names, symbols,
        sorting and ordering, etc. <emphasis>L10n</emphasis> and <emphasis>I18n</emphasis>
        compliment each other. Zend Framework provides support for these through a combination of
        components, including <classname>Zend_Locale</classname>, <classname>Zend_Date</classname>,
        <classname>Zend_Measure</classname>, <classname>Zend_Translate</classname>,
        <classname>Zend_Currency</classname>, and <classname>Zend_TimeSync</classname>.
    </para>

    <tip>
        <title>Zend_Locale and setLocale()</title>

        <para>
            <ulink url="http://php.net/setlocale">PHP's documentation</ulink> states that
            <methodname>setlocale()</methodname> is not threadsave because it is maintained per
            process and not per thread. This means that, in multithreaded environments, you can have
            the problem that the locale changes while the script never has changed the locale
            itself. This can lead to unexpected behaviour when you use
            <methodname>setlocale()</methodname> in your scripts.
        </para>

        <para>
            When you are using <classname>Zend_Locale</classname> you will not have this
            limitations, because <classname>Zend_Locale</classname> is not related to or coupled
            with <acronym>PHP</acronym>'s <methodname>setlocale()</methodname>.
        </para>
    </tip>

    <sect2 id="zend.locale.whatislocalization">
        <title>What is Localization</title>

        <para>
            Localization means that an application (or homepage) can be used from different users
            which speak different languages. But as you already have expected Localization means
            more than only translating strings. It includes
        </para>

        <itemizedlist mark='opencircle'>
            <listitem>
                <para>
                    <classname>Zend_Locale</classname> - Backend support of locales available for
                    localization support within other Zend Framework components.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Translate</classname> - Translating of strings.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Date</classname> - Localization of dates, times.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Calendar</classname> - Localization of calendars (support for
                    non-Gregorian calendar systems)
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Currency</classname> - Localization of currencies.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Locale_Format</classname> - Parsing and generating localized
                    numbers.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Locale_Data</classname> - Retrieve localized standard strings
                    as country names, language names and <ulink
                        url="http://unicode.org/cldr/">more from the
                        <acronym>CLDR</acronym></ulink>.
                </para>
            </listitem>
        </itemizedlist>
    </sect2>

    <sect2 id="zend.locale.whatis">
        <title>What is a Locale?</title>

        <para>
            Each computer user makes use of Locales, even when they don't know it. Applications
            lacking localization support, normally have implicit support for one particular locale
            (the locale of the author). When a class or function makes use of localization, we say
            it is <emphasis>locale-aware</emphasis>. How does the code know which localization the
            user is expecting?
        </para>

        <para>
            A locale string or object identifying a supported locale gives
            <classname>Zend_Locale</classname> and its subclasses access to information about the
            language and region expected by the user. Correct formatting, normalization, and
            conversions are made based on this information.
        </para>
    </sect2>

    <sect2 id="zend.locale.representation">
        <title>How are Locales Represented?</title>

        <para>
            Locale identifiers consist of information about the user's language and
            preferred/primary geographic region (e.g. state or province of home or workplace). The
            locale identifier strings used in Zend Framework are internationally defined standard
            abbreviations of language and region, written as <emphasis>language_REGION</emphasis>.
            Both the language and region parts are abbreviated to alphabetic,
            <acronym>ASCII</acronym> characters.
        </para>

        <note>
            <para>
                Be aware that there exist not only locales with 2 characters as most people think.
                Also there are languages and regions which are not only abbreviated with 2
                characters. Therefor you should NOT strip the region and language yourself, but use
                <classname>Zend_Locale</classname> when you want to strip language or region from a
                locale string. Otherwise you could have unexpected behaviour within your code when
                you do this yourself.
            </para>
        </note>

        <para>
            A user from USA would expect the language English and the region
            <constant>USA</constant>, yielding the locale identifier "en_US". A user in Germany
            would expect the language German and the region Germany,
            yielding the locale identifier "de_DE". See the <ulink
                url="http://unicode.org/cldr/data/diff/supplemental/languages_and_territories.html">list
                of pre-defined locale and region combinations</ulink>, if you need to select a
            specific locale within Zend Framework.
        </para>

        <example id="zend.locale.representation.example-1">
            <title>Choosing a specific locale</title>

            <programlisting language="php"><![CDATA[
$locale = new Zend_Locale('de_DE'); // German language _ Germany
]]></programlisting>
        </example>

        <para>
            A German user in America might expect the language German and the region
            <constant>USA</constant>, but these non-standard mixes are not supported directly as
            recognized "locales". Instead, if an invalid combination is used, then it will
            automatically be truncated by dropping the region code. For example, "de_IS" would be
            truncated to "de", and "xh_RU" would be truncated to "xh", because neither of these
            combinations are valid. Additionally, if the base language code is not supported (e.g.
            "zz_US") or does not exist, then a default "root" locale will be used. The "root" locale
            has default definitions for internationally recognized representations of dates, times,
            numbers, currencies, etc. The truncation process depends on the requested information,
            since some combinations of language and region might be valid for one type of data (e.g.
            dates), but not for another (e.g. currency format).
        </para>

        <para>
            Beware of historical changes, as Zend Framework components do not know about or attempt
            to track the numerous timezone changes made over many years by many regions. For
            example, <ulink url="http://www.statoids.com/tus.html">we can see a historical
                list</ulink> showing dozens of changes made by governments to when and if a
            particular region observes Daylight Savings Time, and even which timezone a particular
            geographic area belongs. Thus, when performing date math, the math performed by Zend
            Framework components will not adjust for these changes, but instead will give the
            correct time for the timezone using current, modern rules for <acronym>DST</acronym> and
            timezone assignment for geographic regions.
        </para>
    </sect2>

    <sect2 id="zend.locale.selection">
        <title>Selecting the Right Locale</title>

        <para>
            For most situations, <command>new Zend_Locale()</command> will automatically select the
            correct locale, with preference given to information provided by the user's web browser.
            However, if <command>new Zend_Locale(Zend_Locale::ENVIRONMENT)</command> is used, then
            preference will be given to using the host server's environment configuration, as
            described below.
        </para>

        <example id="zend.locale.selection.example-1">
            <title>Automatically selecting a locale</title>

            <programlisting language="php"><![CDATA[
$locale  = new Zend_Locale();

// default behavior, same as above
$locale1 = new Zend_Locale(Zend_Locale::BROWSER);

// prefer settings on host server
$locale2 = new Zend_Locale(Zend_Locale::ENVIRONMENT);

// perfer framework app default settings
$locale3 = new Zend_Locale(Zend_Locale::FRAMEWORK);
]]></programlisting>
        </example>

        <para>
            The search algorithm used by <classname>Zend_Locale</classname> for automatic selection
            of a locale uses three sources of information:

            <orderedlist>
                <listitem>
                    <para>
                        const <constant>Zend_Locale::BROWSER</constant> - The user's Web browser
                        provides information with each request, which is published by
                        <acronym>PHP</acronym> in the global variable
                        <varname>$_SERVER['HTTP_ACCEPT_LANGUAGE']</varname>. if no matching locale
                        can be found, then preference is given to <constant>ENVIRONMENT</constant>
                        and lastly <constant>FRAMEWORK</constant>.
                    </para>
                </listitem>

                <listitem>
                    <para>
                        const <constant>Zend_Locale::ENVIRONMENT</constant> - <acronym>PHP</acronym>
                        publishes the host server's locale via the <acronym>PHP</acronym> internal
                        function <methodname>setlocale()</methodname>. If no matching locale can be
                        found, then preference is given to <constant>FRAMEWORK</constant> and lastly
                        <constant>BROWSER</constant>.
                    </para>
                </listitem>

                <listitem>
                    <para>
                        const <constant>Zend_Locale::FRAMEWORK</constant> - When Zend Framework has
                        a standardized way of specifying component defaults (planned, but not yet
                        available), then using this constant during instantiation will give
                        preference to choosing a locale based on these defaults. If no matching
                        locale can be found, then preference is given to
                        <constant>ENVIRONMENT</constant> and lastly <constant>BROWSER</constant>.
                    </para>
                </listitem>
            </orderedlist>
        </para>
    </sect2>

    <sect2 id="zend.locale.selection.automatic">
        <title>Usage of automatic Locales</title>

        <para>
            <classname>Zend_Locale</classname> provides three additional locales. These locales do
            not belong to any language or region. They are "automatic" locales which means that they
            have the same effect as the method <methodname>getDefault()</methodname> but without the
            negative effects like creating an instance. These "automatic" locales can be used
            anywhere, where also a standard locale and also the definition of a locale, its string
            representation, can be used. This offers simplicity for situations like working with
            locales which are provided by a browser.
        </para>

        <para>
            There are three locales which have a slightly different behaviour:

            <orderedlist>
                <listitem>
                    <para>
                        '<property>browser</property>' - <classname>Zend_Locale</classname> should
                        work with the information which is provided by the user's Web browser. It
                        is published by <acronym>PHP</acronym> in the global variable
                        <constant>$_SERVER['HTTP_ACCEPT_LANGUAGE']</constant>.
                    </para>

                    <para>
                        If a user provides more than one locale within his browser,
                        <classname>Zend_Locale</classname> will use the first found locale. If the
                        user does not provide a locale or the script is being called from the
                        command line the automatic locale '<property>environment</property>' will
                        automatically be used and returned.
                    </para>
                </listitem>

                <listitem>
                    <para>
                        '<property>environment</property>' - <classname>Zend_Locale</classname>
                        should work with the information which is provided by the host server. It
                        is published by <acronym>PHP</acronym> via the internal function
                        <methodname>setlocale()</methodname>.
                    </para>

                    <para>
                        If a environment provides more than one locale,
                        <classname>Zend_Locale</classname> will use the first found locale. If the
                        host does not provide a locale the automatic locale
                        '<property>browser</property>' will automatically be used and returned.
                    </para>
                </listitem>

                <listitem>
                    <para>
                        '<property>auto</property>' - <classname>Zend_Locale</classname> should
                        automatically detect any locale which can be worked with. It will first
                        search for a users locale and then, if not successful, search for the host
                        locale.
                    </para>

                    <para>
                        If no locale can be detected, it will throw an exception and tell you that
                        the automatic detection has been failed.
                    </para>
                </listitem>
            </orderedlist>
        </para>

        <example id="zend.locale.selection.automatic.example-1">
            <title>Using automatic locales</title>

            <programlisting language="php"><![CDATA[
// without automatic detection
//$locale = new Zend_Locale(Zend_Locale::BROWSER);
//$date = new Zend_Date($locale);

// with automatic detection
$date = new Zend_Date('auto');
]]></programlisting>
        </example>
    </sect2>

    <sect2 id="zend.locale.defaultlocale">
        <title>Using a default Locale</title>

        <para>
            In some environments it is not possible to detect a locale automatically. You can expect
            this behaviour when you get an request from command line or the requesting browser has
            no language tag set and additionally your server has the default locale 'C' set or
            another proprietary locale.
        </para>

        <para>
            In such cases <classname>Zend_Locale</classname> will normally throw an exception with a
            message that the automatic detection of any locale was not successful. You have two
            options to handle such a situation. Either through setting a new locale per hand, or
            defining a default locale.
        </para>

        <example id="zend.locale.defaultlocale.example-1">
            <title>Handling locale exceptions</title>

            <programlisting language="php"><![CDATA[
// within the bootstrap file
try {
    $locale = new Zend_Locale('auto');
} catch (Zend_Locale_Exception $e) {
    $locale = new Zend_Locale('de');
}

// within your model/controller
$date = new Zend_Date($locale);
]]></programlisting>
        </example>

        <para>
            But this has one big negative effect. You will have to set your locale object within
            every class using <classname>Zend_Locale</classname>. This could become very unhandy if
            you are using multiple classes.
        </para>

        <para>
            Since Zend Framework Release 1.5 there is a much better way to handle this. You can set
            a default locale which the static <methodname>setDefault()</methodname> method. Of
            course, every unknown or not fully qualified locale will also throw an exception.
            <methodname>setDefault()</methodname> should be the first call before you initiate any
            class using <classname>Zend_Locale</classname>. See the following example for details:
        </para>

        <example id="zend.locale.defaultlocale.example-2">
            <title>Setting a default locale</title>

            <programlisting language="php"><![CDATA[
// within the bootstrap file
Zend_Locale::setDefault('de');

// within your model/controller
$date = new Zend_Date();
]]></programlisting>
        </example>

        <para>
            In the case that no locale can be detected, automatically the locale
            <emphasis>de</emphasis> will be used. Otherwise, the detected locale will be used.
        </para>
    </sect2>

    <sect2 id="zend.locale.interoperate">
        <title>ZF Locale-Aware Classes</title>

        <para>
            In the Zend Framework, locale-aware classes rely on <classname>Zend_Locale</classname>
            to automatically select a locale, as explained above. For example, in a Zend Framework
            web application, constructing a date using <classname>Zend_Date</classname> without
            specifying a locale results in an object with a locale based on information provided by
            the current user's web browser.
        </para>

        <example id="zend.locale.interoperate.example-1">
            <title>Dates default to correct locale of web users</title>

            <programlisting language="php"><![CDATA[
$date = new Zend_Date('2006',Zend_Date::YEAR);
]]></programlisting>
        </example>

        <para>
            To override this default behavior, and force locale-aware Zend Framework components to
            use specific locales, regardless of the origin of your website visitors, explicitly
            specify a locale as the third argument to the constructor.
        </para>

        <example id="zend.locale.interoperate.example-2">
            <title>Overriding default locale selection</title>

            <programlisting language="php"><![CDATA[
$usLocale = new Zend_Locale('en_US');
$date = new Zend_Date('2006', Zend_Date::YEAR, $usLocale);
$temp = new Zend_Measure_Temperature('100,10',
                                     Zend_Measure::TEMPERATURE,
                                     $usLocale);
]]></programlisting>
        </example>

        <para>
            If you know many objects should all use the same default locale, explicitly specify the
            default locale to avoid the overhead of each object determining the default locale.
        </para>

        <example id="zend.locale.interoperate.example-3">
            <title>Performance optimization when using a default locale</title>

            <programlisting language="php"><![CDATA[
$locale = new Zend_Locale();
$date = new Zend_Date('2006', Zend_Date::YEAR, $locale);
$temp = new Zend_Measure_Temperature('100,10',
                                     Zend_Measure::TEMPERATURE,
                                     $locale);
]]></programlisting>
        </example>
    </sect2>

    <sect2 id="zend.locale.frameworkwidelocale">
        <title>Application wide locale</title>

        <para>
            Zend Framework allows the usage of an application wide locale. You simply set an
            instance of <classname>Zend_Locale</classname> to the registry with the key
            'Zend_Locale'. Then this instance will be used within all locale aware classes of
            Zend Framework. This way you set one locale within your registry and then you can forget
            about setting it again. It will automatically be used in all other classes. See the
            below example for the right usage:
        </para>

        <example id="zend.locale.frameworkwidelocale.example">
            <title>Usage of an application wide locale</title>

            <programlisting language="php"><![CDATA[
// within your bootstrap
$locale = new Zend_Locale('de_AT');
Zend_Registry::set('Zend_Locale', $locale);

// within your model or controller
$date = new Zend_Date();
// print $date->getLocale();
echo $date->getDate();
]]></programlisting>
        </example>
    </sect2>

    <sect2 id="zend.locale.formatoptions">
        <title>Zend_Locale_Format::setOptions(array $options)</title>

        <para>
            The 'precision' option of a value is used to truncate or stretch extra digits. A value
            of '-1' disables modification of the number of digits in the fractional part of the
            value. The 'locale' option helps when parsing numbers and dates using separators and
            month names. The date format 'format_type' option selects between
            <acronym>CLDR</acronym>/ISO date format specifier tokens and <acronym>PHP</acronym>'s
            date() tokens. The 'fix_date' option enables or disables heuristics that attempt to
            correct invalid dates. The 'number_format' option specifies a default number format for
            use with <methodname>toNumber()</methodname> (see <link
                linkend= "zend.locale.number.localize">this section</link>).
        </para>

        <para>
            The 'date_format' option can be used to specify a default date format string, but beware
            of using getDate(), checkdateFormat() and getTime() after using setOptions() with a
            'date_format'. To use these four methods with the default date format for a locale, use
            array('date_format' => null, 'locale' => $locale) for their options.
        </para>

        <example id="zend.locale.formatoptions.example-1">
            <title>Dates default to correct locale of web users</title>

            <programlisting language="php"><![CDATA[
Zend_Locale_Format::setOptions(array('locale' => 'en_US',
                                     'fix_date' => true,
                                     'format_type' => 'php'));
]]></programlisting>
        </example>

        <para>
            For working with the standard definitions of a locale the option
            <constant>Zend_Locale_Format::STANDARD</constant> can be used. Setting the option
            <constant>Zend_Locale_Format::STANDARD</constant> for <property>date_format</property>
            uses the standard definitions from the actual set locale. Setting it for
            <property>number_format</property> uses the standard number format for this locale.
            And setting it for locale uses the standard locale for this environment or browser.
        </para>

        <example id="zend.locale.formatoptions.example-2">
            <title>Using STANDARD definitions for setOptions()</title>

            <programlisting language="php"><![CDATA[
Zend_Locale_Format::setOptions(array('locale' => 'en_US',
                                     'date_format' => 'dd.MMMM.YYYY'));
// overriding the global set date format
$date = Zend_Locale_Format::getDate('2007-04-20',
                                    array('date_format' =>
                                              Zend_Locale_Format::STANDARD);

// global setting of the standard locale
Zend_Locale_Format::setOptions(array('locale' => Zend_Locale_Format::STANDARD,
                                     'date_format' => 'dd.MMMM.YYYY'));
]]></programlisting>
        </example>
    </sect2>

    <sect2 id="zend.locale.cache">
        <title>Speed up Zend_Locale and its subclasses</title>

        <para>
            <classname>Zend_Locale</classname> and its subclasses can be speeded up by the usage of
            <classname>Zend_Cache</classname>. Use the static method
            <methodname>Zend_Locale::setCache($cache)</methodname> if you are using
            <classname>Zend_Locale</classname>. <classname>Zend_Locale_Format</classname> can be
            speeded up the using the option <property>cache</property> within
            <classname>Zend_Locale_Format::setOptions(array('cache' => $adapter));</classname>.
            If you are using both classes you should only set the cache for
            <classname>Zend_Locale</classname>, otherwise the last set cache will overwrite the
            previous set cache. For convenience there are also the static methods
            <methodname>getCache()</methodname>, <methodname>hasCache()</methodname>,
            <methodname>clearCache()</methodname> and <methodname>removeCache()</methodname>.
        </para>

        <para>
            When no cache is set, then <classname>Zend_Locale</classname> will automatically set a
            cache itself. Sometimes it is wished to prevent that a cache is set, even if this
            degrades performance. In this case the static
            <methodname>disableCache(true)</methodname> method should be used. It does not only
            disable the actual set cache, without erasing it, but also prevents that a cache is
            automatically generated when no cache is set.
        </para>
    </sect2>
</sect1>
<!--
vim:se ts=4 sw=4 et:
-->


text:
package org.apache.camel.builder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.camel.Endpoint;
import org.apache.camel.model.FromDefinition;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.ProcessorDefinitionHelper;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.util.EndpointHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@link AdviceWithTask} tasks which are used by the {@link AdviceWithRouteBuilder}.
 */
public final class AdviceWithTasks {

    private static final Logger LOG = LoggerFactory.getLogger(AdviceWithTasks.class);

    private AdviceWithTasks() {
        // utility class
    }

    /**
     * Match by is used for pluggable match by logic.
     */
    private interface MatchBy {

        String getId();

        boolean match(ProcessorDefinition<?> processor);
    }

    /**
     * Will match by id of the processor.
     */
    private static final class MatchById implements MatchBy {

        private final String id;

        private MatchById(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        public boolean match(ProcessorDefinition<?> processor) {
            if (id.equals("*")) {
                // make sure the processor which id isn't be set is matched.
                return true;
            }
            return EndpointHelper.matchPattern(processor.getId(), id);
        }
    }

    /**
     * Will match by the to string representation of the processor.
     */
    private static final class MatchByToString implements MatchBy {

        private final String toString;

        private MatchByToString(String toString) {
            this.toString = toString;
        }

        public String getId() {
            return toString;
        }

        public boolean match(ProcessorDefinition<?> processor) {
            return EndpointHelper.matchPattern(processor.toString(), toString);
        }
    }

    /**
     * Will match by the type of the processor.
     */
    private static final class MatchByType implements MatchBy {

        private final Class<?> type;

        private MatchByType(Class<?> type) {
            this.type = type;
        }

        public String getId() {
            return type.getSimpleName();
        }

        public boolean match(ProcessorDefinition<?> processor) {
            return type.isAssignableFrom(processor.getClass());
        }
    }

    public static AdviceWithTask replaceByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> replace,
                                                   boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByToString(toString);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doReplace(route, new MatchByToString(toString), replace, it);
    }

    public static AdviceWithTask replaceById(final RouteDefinition route, final String id, final ProcessorDefinition<?> replace,
                                             boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchById(id);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doReplace(route, matchBy, replace, it);
    }

    public static AdviceWithTask replaceByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> replace,
                                               boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByType(type);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doReplace(route, matchBy, replace, it);
    }

    private static AdviceWithTask doReplace(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> replace,
                                            final Iterator<ProcessorDefinition<?>> it) {
        return new AdviceWithTask() {
            public void task() throws Exception {
                boolean match = false;
                while (it.hasNext()) {
                    ProcessorDefinition<?> output = it.next();
                    if (matchBy.match(output)) {
                        List<ProcessorDefinition<?>> outputs = getParentOutputs(output.getParent());
                        if (outputs != null) {
                            int index = outputs.indexOf(output);
                            if (index != -1) {
                                match = true;
                                outputs.add(index + 1, replace);
                                Object old = outputs.remove(index);
                                LOG.info("AdviceWith (" + matchBy.getId() + ") : [" + old + "] --> replace [" + replace + "]");
                            }
                        }
                    }
                }

                if (!match) {
                    throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route);
                }
            }
        };
    }

    public static AdviceWithTask removeByToString(final RouteDefinition route, final String toString,
                                                  boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByToString(toString);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doRemove(route, matchBy, it);
    }

    public static AdviceWithTask removeById(final RouteDefinition route, final String id,
                                            boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchById(id);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doRemove(route, matchBy, it);
    }

    public static AdviceWithTask removeByType(final RouteDefinition route, final Class<?> type,
                                              boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByType(type);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doRemove(route, matchBy, it);
    }

    private static AdviceWithTask doRemove(final RouteDefinition route, final MatchBy matchBy,
                                           final Iterator<ProcessorDefinition<?>> it) {
        return new AdviceWithTask() {
            public void task() throws Exception {
                boolean match = false;
                while (it.hasNext()) {
                    ProcessorDefinition<?> output = it.next();
                    if (matchBy.match(output)) {
                        List<ProcessorDefinition<?>> outputs = getParentOutputs(output.getParent());
                        if (outputs != null) {
                            int index = outputs.indexOf(output);
                            if (index != -1) {
                                match = true;
                                Object old = outputs.remove(index);
                                LOG.info("AdviceWith (" + matchBy.getId() + ") : [" + old + "] --> remove");
                            }
                        }
                    }
                }

                if (!match) {
                    throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route);
                }
            }
        };
    }

    public static AdviceWithTask beforeByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> before,
                                                  boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByToString(toString);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doBefore(route, matchBy, before, it);
    }

    public static AdviceWithTask beforeById(final RouteDefinition route, final String id, final ProcessorDefinition<?> before,
                                            boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchById(id);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doBefore(route, matchBy, before, it);
    }

    public static AdviceWithTask beforeByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> before,
                                              boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByType(type);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doBefore(route, matchBy, before, it);
    }

    private static AdviceWithTask doBefore(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> before,
                                           final Iterator<ProcessorDefinition<?>> it) {
        return new AdviceWithTask() {
            public void task() throws Exception {
                boolean match = false;
                while (it.hasNext()) {
                    ProcessorDefinition<?> output = it.next();
                    if (matchBy.match(output)) {
                        List<ProcessorDefinition<?>> outputs = getParentOutputs(output.getParent());
                        if (outputs != null) {
                            int index = outputs.indexOf(output);
                            if (index != -1) {
                                match = true;
                                Object existing = outputs.get(index);
                                outputs.add(index, before);
                                LOG.info("AdviceWith (" + matchBy.getId() + ") : [" + existing + "] --> before [" + before + "]");
                            }
                        }
                    }
                }

                if (!match) {
                    throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route);
                }
            }
        };
    }

    public static AdviceWithTask afterByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> after,
                                                 boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByToString(toString);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doAfter(route, matchBy, after, it);
    }

    public static AdviceWithTask afterById(final RouteDefinition route, final String id, final ProcessorDefinition<?> after,
                                           boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchById(id);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doAfter(route, matchBy, after, it);
    }

    public static AdviceWithTask afterByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> after,
                                             boolean selectFirst, boolean selectLast, int selectFrom, int selectTo) {
        MatchBy matchBy = new MatchByType(type);
        Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo);
        return doAfter(route, matchBy, after, it);
    }

    private static AdviceWithTask doAfter(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> after,
                                          final Iterator<ProcessorDefinition<?>> it) {
        return new AdviceWithTask() {
            public void task() throws Exception {
                boolean match = false;
                while (it.hasNext()) {
                    ProcessorDefinition<?> output = it.next();
                    if (matchBy.match(output)) {
                        List<ProcessorDefinition<?>> outputs = getParentOutputs(output.getParent());
                        if (outputs != null) {
                            int index = outputs.indexOf(output);
                            if (index != -1) {
                                match = true;
                                Object existing = outputs.get(index);
                                outputs.add(index + 1, after);
                                LOG.info("AdviceWith (" + matchBy.getId() + ") : [" + existing + "] --> after [" + after + "]");
                            }
                        }
                    }
                }

                if (!match) {
                    throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route);
                }
            }
        };
    }

    /**
     * Gets the outputs from the given parent.
     *

     * This implementation deals with that outputs can be abstract and retrieves the correct parent output.
     *
     * @param parent the parent
     * @return <tt>null</tt> if no parent
     */
    private static List<ProcessorDefinition<?>> getParentOutputs(ProcessorDefinition<?> parent) {
        if (parent == null) {
            return null;
        }
        List<ProcessorDefinition<?>> outputs = parent.getOutputs();
        if (outputs.size() == 1 && outputs.get(0).isAbstract()) {
            // if the output is abstract then get its output, as
            outputs = outputs.get(0).getOutputs();
        }
        return outputs;
    }

    public static AdviceWithTask replaceFromWith(final RouteDefinition route, final String uri) {
        return new AdviceWithTask() {
            public void task() throws Exception {
                FromDefinition from = route.getInputs().get(0);
                LOG.info("AdviceWith replace input from [{}] --> [{}]", from.getUriOrRef(), uri);
                from.setEndpoint(null);
                from.setRef(null);
                from.setUri(uri);
            }
        };
    }

    public static AdviceWithTask replaceFrom(final RouteDefinition route, final Endpoint endpoint) {
        return new AdviceWithTask() {
            public void task() throws Exception {
                FromDefinition from = route.getInputs().get(0);
                LOG.info("AdviceWith replace input from [{}] --> [{}]", from.getUriOrRef(), endpoint.getEndpointUri());
                from.setRef(null);
                from.setUri(null);
                from.setEndpoint(endpoint);
            }
        };
    }

    /**
     * Create iterator which walks the route, and only returns nodes which matches the given set of criteria.
     *
     * @param route        the route
     * @param matchBy      match by which must match
     * @param selectFirst  optional to select only the first
     * @param selectLast   optional to select only the last
     * @param selectFrom   optional to select index/range
     * @param selectTo     optional to select index/range
     *
     * @return the iterator
     */
    private static Iterator<ProcessorDefinition<?>> createMatchByIterator(final RouteDefinition route, final MatchBy matchBy,
                                                               final boolean selectFirst, final boolean selectLast,
                                                               final int selectFrom, final int selectTo) {

        // first iterator and apply match by
        List<ProcessorDefinition<?>> matched = new ArrayList<ProcessorDefinition<?>>();

        @SuppressWarnings("rawtypes")
        Iterator<ProcessorDefinition> itAll = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class);
        while (itAll.hasNext()) {
            ProcessorDefinition<?> next = itAll.next();
            if (matchBy.match(next)) {
                matched.add(next);
            }
        }

        // and then apply the selector iterator
        return createSelectorIterator(matched, selectFirst, selectLast, selectFrom, selectTo);
    }

    private static Iterator<ProcessorDefinition<?>> createSelectorIterator(final List<ProcessorDefinition<?>> list, final boolean selectFirst,
                                                                           final boolean selectLast, final int selectFrom, final int selectTo) {
        return new Iterator<ProcessorDefinition<?>>() {
            private int current;
            private boolean done;

            @Override
            public boolean hasNext() {
                if (list.isEmpty() || done) {
                    return false;
                }

                if (selectFirst) {
                    done = true;
                    // spool to first
                    current = 0;
                    return true;
                }

                if (selectLast) {
                    done = true;
                    // spool to last
                    current = list.size() - 1;
                    return true;
                }

                if (selectFrom >= 0 && selectTo >= 0) {
                    // check for out of bounds
                    if (selectFrom >= list.size() || selectTo >= list.size()) {
                        return false;
                    }
                    if (current < selectFrom) {
                        // spool to beginning of range
                        current = selectFrom;
                    }
                    return current >= selectFrom && current <= selectTo;
                }

                return current < list.size();
            }

            @Override
            public ProcessorDefinition<?> next() {
                ProcessorDefinition<?> answer = list.get(current);
                current++;
                return answer;
            }

            @Override
            public void remove() {
                // noop
            }
        };
    }

}

redpajama_set_name: RedPajamaGithub


text:
@interface RegisterViewController : ViewController <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *firstNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *lastNameTextDField;
@property (weak, nonatomic) IBOutlet UITextField *emailTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@property (weak, nonatomic) IBOutlet UILabel *firstnameERROR;
@property (weak, nonatomic) IBOutlet UILabel *lastnameERROR;
@property (weak, nonatomic) IBOutlet UILabel *errorTextField;
@property (weak, nonatomic) IBOutlet UILabel *passERROR;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingIndicator;

- (IBAction)registerDoctor:(id)sender;

@end


text:
#include "MHGroveBLE.h"

/*
Some notes about the Seeed Grove BLE:

The commands and responses are sent and received WITHOUT any delimiters like
"\r\n". After sending the command, you just wait for the response. You know the
reponse is complete if you don't receive any more stuff so you have to wait for
a timeout.

How utterly stupid! But that's the way it is.
*/

/** Hard timeout for generic command responses. */
static const unsigned long kGenericCommandTimeout = 1000;
/** Soft timeout for early completion of response handling. */
static const unsigned long kReceiveResponseEarlyTimeout = 50;
/** Hard timeout for the "wait for device" handling. */
static const unsigned long kWaitForDeviceTimeout = 5000;
/** Soft timeout for the "wait for device" handling: once this timeout is
 reached, resend the "AT" command.
 */
static const unsigned long kWaitForDeviceRetryTimeout = 500;
/** Timeout for reads while in the connected state. */
static const unsigned long kConnectedReadTimeout = 50;

/** Internal state. */
enum class MHGroveBLE::InternalState {
  /** Initial state. */
  startup,
  /** Send "AT" periodically and wait until the device responds. */
  waitForDeviceAfterStartup,
  /** Reset all settings to their factory defaults. */
  renew,
  /** After "renew" was sent, we need to give the device half a second to apply
   the factory defaults. If we don't wait after "renew", the communication may
   break down unexpectedly (i.e. the device suddenly doesn't send a response to
   a query).
   */
  waitAfterRenew,
  /** Get the firmware version. */
  getFirmwareVersion,
  /** Set the Bluetooth name. */
  setName,
  /** Set the Bluetooth pin. */
  setPIN,
  /** Set authentication to needing a PIN (if PIN is set). */
  setPINAuth,
  /** Set that we want to be notified about connections. */
  setNotification,
  /** Reset after setting the device up. */
  reset,
  /** Send "AT" periodically and wait until the device responds. */
  waitForDeviceAfterReset,
  /** Initialization is done, inform the handler. */
  initializationComplete,

  /** Waiting for a connection. */
  waitingForConnection,
  /** A peer has connected. */
  connected,

  /** An unrecoverable error occurred, operation is halted. */
  panicked
};

/** Return value for `receiveResponse`. */
enum class MHGroveBLE::ResponseState {
  /** Still receiving data. */
  receiving,
  /** Nothing received so far, need to resend the command. */
  needRetry,
  /** The timeout has been reached, no data received. */
  timedOut,
  /** The retry or timeout time has been reached, we have data in `rxBuffer`. */
  success
};

/** Internal helper: calculate whether a timeout occurred.

 Handles `millies()` overflow.
 */
static bool isTimeout(unsigned long now, unsigned long referenceTime, unsigned long duration)
{
  return (now - referenceTime) >= duration;
}

MHGroveBLE::MHGroveBLE(
  Stream & device,
  const char * name,
  unsigned int rxBufferSize
) :
  device(device),
  name(name),
  rxBufferSize(rxBufferSize),
  internalState(InternalState::startup)
{
  rxBuffer.reserve(rxBufferSize);
}

void MHGroveBLE::runOnce()
{
  switch (internalState) {
    case InternalState::startup:
      transitionToState(InternalState::waitForDeviceAfterStartup);
      break;

    case InternalState::waitForDeviceAfterStartup:
    case InternalState::waitForDeviceAfterReset:
      handleWaitForDevice();
      break;

    case InternalState::waitAfterRenew:
      if (isTimeout(millis(), timeoutReferenceTime, timeoutDuration)) {
        transitionToState(InternalState::getFirmwareVersion);
      }
      break;

    case InternalState::renew:
    case InternalState::setName:
    case InternalState::setPIN:
    case InternalState::setPINAuth:
    case InternalState::setNotification:
      handleGenericCommand();
      break;

    case InternalState::getFirmwareVersion:
      handleGetFirmwareVersion();
      break;

    case InternalState::reset:
      handleReset();
      break;

    case InternalState::initializationComplete:
      // It should not be possible to end up here since we immediately
      // transition to the `waitingForConnection` state.
      break;

    case InternalState::waitingForConnection:
      handleWaitForConnect();
      break;

    case InternalState::connected:
      handleConnected();
      break;

    case InternalState::panicked:
      // Once we've panicked we won't do anything again.
      break;
  }
}

MHGroveBLE::State MHGroveBLE::getState() {
  switch (internalState) {
    case InternalState::panicked:   return State::panicked;
    case InternalState::waitingForConnection: return State::waitingForConnection;
    case InternalState::connected:  return State::connected;
    default:                        return State::initializing;
  }
}

void MHGroveBLE::setPIN(const char * aPin)
{
  pin = aPin;
}

void MHGroveBLE::setOnReady(void (*onFunc)())
{
  onReady = onFunc;
}

void MHGroveBLE::setOnPanic(void (*onFunc)())
{
  onPanic = onFunc;
}

void MHGroveBLE::setOnConnect(void (*onFunc)())
{
  onConnect = onFunc;
}

void MHGroveBLE::setOnDisconnect(void (*onFunc)())
{
  onDisconnect = onFunc;
}

void MHGroveBLE::setOnDataReceived(void (*onFunc)(const String &))
{
  onDataReceived = onFunc;

}

void MHGroveBLE::setDebug(void (*debugFunc)(const char *))
{
  debug = debugFunc;
}

bool MHGroveBLE::send(const String & data)
{
  if (internalState != InternalState::connected) {
    return false;
  }

  device.print(data);
  return true;
}

/*******************************************************************************
 * Private section
 ******************************************************************************/

void MHGroveBLE::transitionToState(MHGroveBLE::InternalState nextState)
{
  unsigned long now = millis();
  InternalState skipToState = nextState;

  if (debug) {
    String text = F("Transitioning to state: ");
    text += (int)nextState;
    debug(text.c_str());
  }

  // Set most commonly needed values.
  softTimeoutReferenceTime = 0;
  softTimeoutDuration = 0;
  timeoutReferenceTime = now;
  timeoutDuration = kGenericCommandTimeout;

  switch (nextState) {
    case InternalState::startup:
      break;

    case InternalState::waitForDeviceAfterStartup:
      sendCommand(F("AT"));
      softTimeoutReferenceTime = now;
      softTimeoutDuration = kWaitForDeviceRetryTimeout;
      timeoutDuration = kWaitForDeviceTimeout;
      break;

    case InternalState::renew:
      sendCommand(F("AT+RENEW"));
      genericNextInternalState = InternalState::waitAfterRenew;
      break;

    case InternalState::waitAfterRenew:
      // Documentation says that we should wait for 500ms after "AT+RENEW",
      // but that's too short: communication wasn't stable with this delay.
      // Even 600ms didn't work, while 750ms did work. Let's stay on the safe
      // side and grant the device a full second.
      timeoutDuration = 1000;
      // The transition to the next state is handled in `runOnce()`.
      break;

    case InternalState::getFirmwareVersion:
      sendCommand(F("AT+VERS?"));
      genericNextInternalState = InternalState::setName;
      break;

    case InternalState::setName: {
      String command = F("AT+NAME");
      command += name;
      sendCommand(command);
      genericNextInternalState = InternalState::setPIN;
      break;
    }

    case InternalState::setPIN:
      if (pin) {
        String command = F("AT+PASS");
        command += pin;
        sendCommand(command);
        genericNextInternalState = InternalState::setPINAuth;
      } else {
        skipToState = InternalState::setNotification;
      }
      break;

    case InternalState::setPINAuth:
      // The documentation explicitly says not to issue this command if the
      // firmwareVersion is less than 515.
      if (pin && firmwareVersion >= 515) {
        sendCommand(F("AT+TYPE2")); // Auth with PIN
        genericNextInternalState = InternalState::setNotification;
      } else {
        skipToState = InternalState::setNotification;
      }
      break;

    case InternalState::setNotification:
      sendCommand(F("AT+NOTI1"));
      genericNextInternalState = InternalState::reset;
      break;

    case InternalState::reset:
      sendCommand(F("AT+RESET"));
      break;

    case InternalState::waitForDeviceAfterReset:
      sendCommand(F("AT"));
      softTimeoutReferenceTime = now;
      softTimeoutDuration = kWaitForDeviceRetryTimeout;
      timeoutReferenceTime = now;
      timeoutDuration = kWaitForDeviceTimeout;
      break;

    case InternalState::initializationComplete:
      // When we've reached the `initializationComplete` state, we just want to
      // inform the handler and then continue to the `waitingForConnection`
      // state right away.
      if (onReady) {
        onReady();
      }
      skipToState = InternalState::waitingForConnection;
      break;

    case InternalState::waitingForConnection:
      if (internalState == InternalState::connected && onDisconnect) {
        onDisconnect();
      }
      rxBuffer = "";
      break;

    case InternalState::connected:
      if (onConnect) {
        onConnect();
      }
      timeoutReferenceTime = 0;
      timeoutDuration = 0;
      break;

    case InternalState::panicked:
      if (debug) {
        debug("Panic!");
      }
      if (onPanic) {
        onPanic();
      }
      break;
  }

  internalState = nextState;

  if (skipToState != nextState) {
    transitionToState(skipToState);
  }
}

void MHGroveBLE::sendCommand(const String & command)
{
  if (debug) {
    String text = F("Sending command: ");
    text += command;
    debug(text.c_str());
  }

  device.print(command);

  // Clear the receive buffer after sending a command.
  rxBuffer = "";
}

bool MHGroveBLE::readIntoBuffer()
{
  bool didReceive = false;

  while (device.available() > 0) {
    int value = device.read();
    if (value < 0) {
      // Shouldn't happen? We asked whether there's stuff available!
      break;
    }

    if (rxBuffer.length() == rxBufferSize) {
      // We don't want to grow the receive buffer. Discard old data.
      rxBuffer.remove(0, 1);
    }

    rxBuffer += (char)value;
    didReceive = true;
  }

  return didReceive;
}

MHGroveBLE::ResponseState MHGroveBLE::receiveResponse()
{
  unsigned long now = millis();

  bool timeoutReached = isTimeout(now, timeoutReferenceTime, timeoutDuration);
  bool softTimeoutReached =
    softTimeoutDuration > 0
    ? isTimeout(now, softTimeoutReferenceTime, softTimeoutDuration)
    : false;

  if (readIntoBuffer()) {
    // We've read response data! We don't need to wait for the complete timeout
    // now, it's enough to wait until the response text is likely complete.
    softTimeoutReferenceTime = now;
    softTimeoutDuration = kReceiveResponseEarlyTimeout;
  }

  if (softTimeoutReached || timeoutReached) {
    if (rxBuffer.length() > 0) {
      // We reached a timeout and have data! We're done.
      if (debug) {
        String text = F("Received response: ");
        text += rxBuffer;
        debug(text.c_str());
      }
      return ResponseState::success;

    } else if (timeoutReached) {
      // The hard timeout has been reached.
      return ResponseState::timedOut;

    } else {
      // The retry timeout (soft timeout) has been reached without any data.
      // Reset the reference time to start the next retry phase.
      softTimeoutReferenceTime = now;
      return ResponseState::needRetry;
    }

  } else {
    // No timeout reached yet, keep on reading.
    return ResponseState::receiving;
  }
}

void MHGroveBLE::handleWaitForDevice()
{
  switch (receiveResponse()) {
    case ResponseState::receiving:
      break;

    case ResponseState::needRetry:
      sendCommand(F("AT"));
      break;

    case ResponseState::timedOut:
      panic();
      break;

    case ResponseState::success:
      switch (internalState) {
        case InternalState::waitForDeviceAfterStartup:
          transitionToState(InternalState::renew);
          break;

        case InternalState::waitForDeviceAfterReset:
          transitionToState(InternalState::initializationComplete);
          break;

        default:
          // Bug! Must not happen.
          panic();
      }
      break;
  }
}

void MHGroveBLE::handleGenericCommand()
{
  switch (receiveResponse()) {
    case ResponseState::receiving:
      break;

    case ResponseState::needRetry: // Bug, must not happen
    case ResponseState::timedOut:
      panic();
      break;

    case ResponseState::success:
      transitionToState(genericNextInternalState);
      break;
  }
}

void MHGroveBLE::handleGetFirmwareVersion()
{
  switch (receiveResponse()) {
    case ResponseState::receiving:
      break;

    case ResponseState::needRetry: // Bug, must not happen
    case ResponseState::timedOut:
      panic();
      break;

    case ResponseState::success:
      // We expect a string like "HMSoft V540".
      if (rxBuffer.startsWith(F("HMSoft V"))) {
        rxBuffer.remove(0, 8);
        firmwareVersion = rxBuffer.toInt();
        if (debug) {
          String text = F("Detected firmware version: ");
          text += firmwareVersion;
          debug(text.c_str());
        }
      }

      transitionToState(genericNextInternalState);
      break;
  }
}

void MHGroveBLE::handleReset()
{
  switch (receiveResponse()) {
    case ResponseState::receiving:
      break;

    case ResponseState::needRetry: // Bug, must not happen
      panic();
      break;

    case ResponseState::timedOut:
      // Try waiting for the device.
      // Fall-through
    case ResponseState::success:
      transitionToState(InternalState::waitForDeviceAfterReset);
      break;
  }
}

void MHGroveBLE::handleWaitForConnect()
{
  if (!readIntoBuffer()) {
    return;
  }

  if (rxBuffer.indexOf(F("OK+CONN")) != -1) {
    rxBuffer = "";
    // Once we've received this string immediately transition to the "connected"
    // state. There's no point in waiting for a timeout like when we're waiting
    // for AT command responses.
    // The point of doing this with `indexOf` is to recover if we have received
    // garbage before.
    transitionToState(InternalState::connected);
  }
}

void MHGroveBLE::handleConnected()
{
  unsigned long now = millis();
  bool connectionClosed = false;
  bool dataWasRead = readIntoBuffer();
  bool timeoutReached =
    timeoutDuration > 0
    ? isTimeout(now, timeoutReferenceTime, timeoutDuration)
    : false;

  if (!dataWasRead && !timeoutReached) {
    // Nothing happened, no need to react yet.
    return;
  }

  if (dataWasRead) {
    // Every time we read data we need to reset our timeout to avoid
    // timing out in the middle of a stream.
    timeoutReferenceTime = now;
    timeoutDuration = kConnectedReadTimeout;
  }

  // Pass the data to the handler if either the timeout occurred or if the
  // receive buffer is full. The later is necessary to not lose any data.
  if (timeoutReached || rxBuffer.length() == rxBufferSize) {
    // The Grove BLE sends "OK+LOST" when the connection is closed.
    // Unfortunately, an app is also able to send this string and we don't know
    // whether the Grove BLE or the app has sent it.
    // This is why `handleWaitForConnect` also needs to be able to handle
    // garbage: it's possible that an app sends "OK+LOST" and once the
    // connection is really closed, another "OK+LOST" is sent by Grove BLE
    // before the "OK+CONN" for a new connection arrives.
    int index = rxBuffer.lastIndexOf(F("OK+LOST"));
    // Check whether it's the last thing in the buffer to avoid reacting on the
    // string being part of some other text.
    if (index >= 0 && ((unsigned)index+7 == rxBuffer.length())) {
      connectionClosed = true;
      // Remove the sentinel.
      rxBuffer.remove(index);
    }

    // Pass the data to the handler...
    if (onDataReceived && rxBuffer.length() > 0) {
      onDataReceived(rxBuffer);
    }
    // ... and clear it.
    rxBuffer = "";
    timeoutReferenceTime = 0;
    timeoutDuration = 0;
  }

  if (connectionClosed) {
    transitionToState(InternalState::waitingForConnection);
  }
}

void MHGroveBLE::panic()
{
  transitionToState(InternalState::panicked);
}


text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using Mono.Unix;
//using Gtk;

using DPAP;

namespace DPAP {

	class MainClass
	{

		public static void Main (string [] args)
		{

			ServiceDiscovery sd = new ServiceDiscovery ();
			sd.Found += OnServiceFound;
			sd.Start ();

//			sd.Services [0];
			Console.ReadLine ();
			if (sd != null) {
                sd.Stop ();
                sd.Found -= OnServiceFound;
                //locator.Removed -= OnServiceRemoved;
                sd = null;
            }

		}
		private static void OnServiceFound (object o, ServiceArgs args)
		{
			Service service = args.Service;
			Client client;
//			ThreadAssist.Spawn (delegate {
        //        try {

			System.Console.WriteLine ("Connecting to {0} at {1}:{2}", service.Name, service.Address, service.Port);
		    client = new Client (service);

			foreach (Database d in client.Databases){

				Console.WriteLine ("Database " + d.Name);

				foreach (Album alb in d.Albums)
					Console.WriteLine ("\tAlbum: "+alb.Name + ", id=" + alb.getId () + " number of items:" + alb.Photos.Count);
				Console.WriteLine (d.Photos [0].FileName);
				foreach (Photo ph in d.Photos)
				{
					if (ph != null)
					{
						Console.WriteLine ("\t\tFile: " + ph.Title + " format = " + ph.Format + "size=" + ph.Width +"x" +ph.Height + " ID=" + ph.Id);
						d.DownloadPhoto (ph,"./"+ph.Title);
					}
				}

			}
			//client.Logout ();
			//Console.WriteLine ("Press <enter> to exit...");

		}
	}
}


text:
<?php

namespace MongoDB\Tests\Operation;

use MongoDB\BSON\ObjectId;
use MongoDB\BulkWriteResult;
use MongoDB\Collection;
use MongoDB\Driver\BulkWrite as Bulk;
use MongoDB\Driver\WriteConcern;
use MongoDB\Exception\BadMethodCallException;
use MongoDB\Model\BSONDocument;
use MongoDB\Operation\BulkWrite;
use MongoDB\Tests\CommandObserver;

use function version_compare;

class BulkWriteFunctionalTest extends FunctionalTestCase
{
    /** @var Collection */
    private $collection;

    public function setUp(): void
    {
        parent::setUp();

        $this->collection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName());
    }

    public function testInserts(): void
    {
        $ops = [
            ['insertOne' => [['_id' => 1, 'x' => 11]]],
            ['insertOne' => [['x' => 22]]],
            ['insertOne' => [(object) ['_id' => 'foo', 'x' => 33]]],
            ['insertOne' => [new BSONDocument(['_id' => 'bar', 'x' => 44])]],
        ];

        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

        $this->assertInstanceOf(BulkWriteResult::class, $result);
        $this->assertSame(4, $result->getInsertedCount());

        $insertedIds = $result->getInsertedIds();
        $this->assertSame(1, $insertedIds[0]);
        $this->assertInstanceOf(ObjectId::class, $insertedIds[1]);
        $this->assertSame('foo', $insertedIds[2]);
        $this->assertSame('bar', $insertedIds[3]);

        $expected = [
            ['_id' => 1, 'x' => 11],
            ['_id' => $insertedIds[1], 'x' => 22],
            ['_id' => 'foo', 'x' => 33],
            ['_id' => 'bar', 'x' => 44],
        ];

        $this->assertSameDocuments($expected, $this->collection->find());
    }

    public function testUpdates(): void
    {
        $this->createFixtures(4);

        $ops = [
            ['updateOne' => [['_id' => 2], ['$inc' => ['x' => 1]]]],
            ['updateMany' => [['_id' => ['$gt' => 2]], ['$inc' => ['x' => -1]]]],
            ['updateOne' => [['_id' => 5], ['$set' => ['x' => 55]], ['upsert' => true]]],
            ['updateOne' => [['x' => 66], ['$set' => ['x' => 66]], ['upsert' => true]]],
            ['updateMany' => [['x' => ['$gt' => 50]], ['$inc' => ['x' => 1]]]],
        ];

        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

        $this->assertInstanceOf(BulkWriteResult::class, $result);
        $this->assertSame(5, $result->getMatchedCount());
        $this->assertSame(5, $result->getModifiedCount());
        $this->assertSame(2, $result->getUpsertedCount());

        $upsertedIds = $result->getUpsertedIds();
        $this->assertSame(5, $upsertedIds[2]);
        $this->assertInstanceOf(ObjectId::class, $upsertedIds[3]);

        $expected = [
            ['_id' => 1, 'x' => 11],
            ['_id' => 2, 'x' => 23],
            ['_id' => 3, 'x' => 32],
            ['_id' => 4, 'x' => 43],
            ['_id' => 5, 'x' => 56],
            ['_id' => $upsertedIds[3], 'x' => 67],
        ];

        $this->assertSameDocuments($expected, $this->collection->find());
    }

    public function testDeletes(): void
    {
        $this->createFixtures(4);

        $ops = [
            ['deleteOne' => [['_id' => 1]]],
            ['deleteMany' => [['_id' => ['$gt' => 2]]]],
        ];

        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

        $this->assertInstanceOf(BulkWriteResult::class, $result);
        $this->assertSame(3, $result->getDeletedCount());

        $expected = [
            ['_id' => 2, 'x' => 22],
        ];

        $this->assertSameDocuments($expected, $this->collection->find());
    }

    public function testMixedOrderedOperations(): void
    {
        $this->createFixtures(3);

        $ops = [
            ['updateOne' => [['_id' => ['$gt' => 1]], ['$inc' => ['x' => 1]]]],
            ['updateMany' => [['_id' => ['$gt' => 1]], ['$inc' => ['x' => 1]]]],
            ['insertOne' => [['_id' => 4, 'x' => 44]]],
            ['deleteMany' => [['x' => ['$nin' => [24, 34]]]]],
            ['replaceOne' => [['_id' => 4], ['_id' => 4, 'x' => 44], ['upsert' => true]]],
        ];

        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

        $this->assertInstanceOf(BulkWriteResult::class, $result);

        $this->assertSame(1, $result->getInsertedCount());
        $this->assertSame([2 => 4], $result->getInsertedIds());

        $this->assertSame(3, $result->getMatchedCount());
        $this->assertSame(3, $result->getModifiedCount());
        $this->assertSame(1, $result->getUpsertedCount());
        $this->assertSame([4 => 4], $result->getUpsertedIds());

        $this->assertSame(2, $result->getDeletedCount());

        $expected = [
            ['_id' => 2, 'x' => 24],
            ['_id' => 3, 'x' => 34],
            ['_id' => 4, 'x' => 44],
        ];

        $this->assertSameDocuments($expected, $this->collection->find());
    }

    public function testUnacknowledgedWriteConcern()
    {
        $ops = [['insertOne' => [['_id' => 1]]]];
        $options = ['writeConcern' => new WriteConcern(0)];
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops, $options);
        $result = $operation->execute($this->getPrimaryServer());

        $this->assertFalse($result->isAcknowledged());

        return $result;
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesDeletedCount(BulkWriteResult $result): void
    {
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageMatches('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
        $result->getDeletedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesInsertCount(BulkWriteResult $result): void
    {
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageMatches('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
        $result->getInsertedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesMatchedCount(BulkWriteResult $result): void
    {
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageMatches('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
        $result->getMatchedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesModifiedCount(BulkWriteResult $result): void
    {
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageMatches('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
        $result->getModifiedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesUpsertedCount(BulkWriteResult $result): void
    {
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageMatches('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
        $result->getUpsertedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesUpsertedIds(BulkWriteResult $result): void
    {
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageMatches('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
        $result->getUpsertedIds();
    }

    public function testSessionOption(): void
    {
        (new CommandObserver())->observe(
            function (): void {
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['session' => $this->createSession()]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function (array $event): void {
                $this->assertObjectHasAttribute('lsid', $event['started']->getCommand());
            }
        );
    }

    public function testBypassDocumentValidationSetWhenTrue(): void
    {
        (new CommandObserver())->observe(
            function (): void {
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['bypassDocumentValidation' => true]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function (array $event): void {
                $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
                $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation);
            }
        );
    }

    public function testBypassDocumentValidationUnsetWhenFalse(): void
    {
        (new CommandObserver())->observe(
            function (): void {
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['bypassDocumentValidation' => false]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function (array $event): void {
                $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
            }
        );
    }

    public function testBulkWriteWithPipelineUpdates(): void
    {
        if (version_compare($this->getServerVersion(), '4.2.0', '<')) {
            $this->markTestSkipped('Pipeline-style updates are not supported');
        }

        $this->createFixtures(4);

        $ops = [
            ['updateOne' => [['_id' => 2], [['$addFields' => ['y' => 2]]]]],
            ['updateMany' => [['_id' => ['$gt' => 2]], [['$addFields' => ['y' => '$_id']]]]],
        ];

        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

        $this->assertInstanceOf(BulkWriteResult::class, $result);
        $this->assertSame(3, $result->getMatchedCount());
        $this->assertSame(3, $result->getModifiedCount());

        $expected = [
            ['_id' => 1, 'x' => 11],
            ['_id' => 2, 'x' => 22, 'y' => 2],
            ['_id' => 3, 'x' => 33, 'y' => 3],
            ['_id' => 4, 'x' => 44, 'y' => 4],
        ];

        $this->assertSameDocuments($expected, $this->collection->find());
    }

    /**
     * Create data fixtures.
     */
    private function createFixtures(int $n): void
    {
        $bulkWrite = new Bulk(['ordered' => true]);

        for ($i = 1; $i <= $n; $i++) {
            $bulkWrite->insert([
                '_id' => $i,
                'x' => (integer) ($i . $i),
            ]);
        }

        $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);

        $this->assertEquals($n, $result->getInsertedCount());
    }
}


text:
/**
 * @module modules/histogram-sk
 *
 * @description A visual representation of the command name counts totalled by
 * commands-sk when a frame is loaded, and a controller for the set of included
 * command names in the filter (also in commands-sk).
 *
 * It's not an indepentent model-view-controller, just a view-controller for a
 * model in commands-sk. The main reason it's a seperate module is that it's
 * visually self-contained in different element elsewhere on the page, and as
 * far as I know commandsSk cannot export two different elements.
 *
 * Due to the functionality depending on the integration with commands-sk,
 * this module is tested in debugger-page-sk_test.ts.
 *
 * @evt toggle-command-inclusion: Emitted when a row is clicked, indicating it's
 * inclusion in the command filter should be toggled.
 */
import { define } from 'elements-sk/define';
import { html } from 'lit-html';
import { ElementDocSk } from '../element-doc-sk/element-doc-sk';

import {
  HistogramUpdateEventDetail, HistogramEntry,
  HistogramUpdateEvent,
  ToggleCommandInclusionEvent,
  ToggleCommandInclusionEventDetail,
} from '../events';

export class HistogramSk extends ElementDocSk {
  private static template = (ele: HistogramSk) => html`

  Histogram

      frame
      range
      name

    ${ele._hist.map((item: HistogramEntry) => HistogramSk.rowTemplate(ele, item))}

${ele._total()}	Total

`;

  private static rowTemplate = (ele: HistogramSk, item: HistogramEntry) => html`

 { ele._toggle(item.name); }} id="hist-row-${item.name.toLowerCase()}"
    class="${ele._incl.has(item.name.toLowerCase()) ? '' : 'pinkBackground'}">
  ${item.countInFrame}
  ${item.countInRange}
  ${item.name}

`;

  // counts of command occurrences
  private _hist: HistogramEntry[] = [];

  // commands which the filter includes
  private _incl = new Set<string>();

  private _total(): number {
    let total = 0;
    for (const item of this._hist) {
      total += item.countInRange;
    }
    return total;
  }

  constructor() {
    super(HistogramSk.template);
  }

  connectedCallback(): void {
    super.connectedCallback();
    this._render();

    this.addDocumentEventListener(HistogramUpdateEvent, (e) => {
      const detail = (e as CustomEvent<HistogramUpdateEventDetail>).detail;
      // event may update one or both items
      if (detail.hist) {
        this._hist = detail.hist;
      }
      if (detail.included) {
        this._incl = detail.included;
      }
      this._render();
    });
  }

  // Toggle the given item in or out of the included set in commands-sk
  private _toggle(name: string) {
    const lowerName = name.toLowerCase();
    // short cut to change our own appearance
    if (this._incl.has(lowerName)) {
      this._incl.delete(lowerName);
    } else {
      this._incl.add(lowerName);
    }
    this._render();

    // but make sure to tell the module that actually owns this model
    this.dispatchEvent(
      new CustomEvent<ToggleCommandInclusionEventDetail>(
        ToggleCommandInclusionEvent, {
          detail: { name: lowerName },
          bubbles: true,
        },
      ),
    );
  }
}

define('histogram-sk', HistogramSk);


text:
package com.pwittchen.network.events.library.task;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.pwittchen.network.events.library.config.NetworkEventsConfig;
import com.pwittchen.network.events.library.helper.NetworkHelper;

/**
 * Pings remote host in order to check if we have access
 * to the Internet network through WiFi network
 */
public class PingTask extends AsyncTask<Void, Void, Boolean> {
    private Context context;

    public PingTask(Context context) {
        this.context = context;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return NetworkHelper.ping(NetworkEventsConfig.getRemoteHostForPing());
    }

    @Override
    protected void onPostExecute(Boolean connectedToInternet) {
        super.onPostExecute(connectedToInternet);
        Intent intent = new Intent(NetworkEventsConfig.getIntentNameForInternetConnectionChange());
        intent.putExtra(NetworkEventsConfig.getIntentNameExtraForInternetConnectionChange(), connectedToInternet);
        context.sendBroadcast(intent);
    }
}


text:
  Nègrepelisse est
      une commune géographiquement positionnée dans le département de Tarn-et-Garonne en Midi-Pyrénées. Elle totalisait 4 511 habitants en 2008.

Le parc d'habitations, à Nègrepelisse, se décomposait en 2011 en 411 appartements et 1 826 maisons soit
 un marché relativement équilibré.

À Nègrepelisse le salaire médian mensuel par individu est situé à approximativement 1 859 €  net. C'est inférieur à la moyenne du pays.

À proximité de Nègrepelisse sont situées les communes de
Vaïssac localisée à 6 km, 704 habitants,
Saint-Etienne-de-Tulmont localisée à 5 km, 3 138 habitants,
Bioule localisée à 2 km, 878 habitants,
Montricoux située à 7 km, 1 021 habitants,
Léojac localisée à 9 km, 1 057 habitants,
Albias localisée à 6 km, 2 573 habitants,
 entre autres. De plus, Nègrepelisse est située à seulement quatorze km de Montauban.

À Nègrepelisse, la valeur moyenne à la vente d'un appartement s'évalue à 1 612 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 528 € du m². À la location le prix moyen se situe à 8,41 € du m² mensuel.

La ville propose de multiples  équipements, elle propose entre autres un bassin de natation, un terrain de tennis, trois terrains de sport et une base nautique.

La commune dispose s'agissant de l'éducation des jeunes de un collège.
Pour les très jeunes, la commune peut se prévaloir de disposer de une maternelle et deux écoles primaires.
Nègrepelisse dispose des installations éducatives permettant une éducation de proximité.
Lors d'un projet immobilier à Nègrepelisse, il est important regarder la notoriété des écoles de la communes


text:
<?php

// ----------------------------------------------------------------------
// Original Author of file: Walid Nouh
// Purpose of file:
// ----------------------------------------------------------------------
if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access directly to this file");
}

/**
* Rule class store all informations about a GLPI rule :
*   - description
*   - criterias
*   - actions
**/
class RuleDictionnarySoftware extends RuleCached {

   var $additional_fields_for_dictionnary = array('manufacturer');

   // From Rule
   public $right    = 'rule_dictionnary_software';
   public $can_sort = true;

   function getTitle() {
      global $LANG;

      return $LANG['rulesengine'][35];
   }

   function maxActionsCount() {
      return 4;
   }

   function showCacheRuleHeader() {
      global $LANG;

      echo "
" . $LANG['rulesengine'][100] . " : " . $this->fields["name"];
      echo "
";

      echo "
" . $LANG['rulesengine'][104] . "	";
      echo "" . $LANG['entity'][0]." ".$LANG['rulesengine'][104]."	";
      echo "" . $LANG['common'][5]." ".$LANG['rulesengine'][108]."	";
      echo "" . $LANG['rulesengine'][105] . "	";
      echo "" . $LANG['rulesengine'][78] . "	";
      echo "" . $LANG['common'][5] . "	";
      echo "" . $LANG['rulesengine'][132] . "	";
      echo "" . $LANG['software'][46] . "	\n";
      echo "" . $LANG['ldap'][27] . "
\n";
   }

   function showCacheRuleDetail($fields) {
      global $LANG;

      echo "" . $fields["old_value"] . "	";
      echo "" . Dropdown::getDropdownName("glpi_entities",
                                                               $fields["entities_id"]) . "	";
      echo "" . $fields["manufacturer"] . "	";
      echo "".($fields["new_value"] != '' ? $fields["new_value"]
                                                               : $LANG['rulesengine'][106])."	";
      echo "". ($fields["version"] != '' ? $fields["version"]
                                                              : $LANG['rulesengine'][106])."	";
      echo "".
             ((isset($fields["new_manufacturer"]) && $fields["new_manufacturer"] != '')
              ? Dropdown::getDropdownName("glpi_manufacturers", $fields["new_manufacturer"])
              : $LANG['rulesengine'][106]) . "	";
      echo "";
      if ($fields["ignore_ocs_import"] == '') {
         echo " ";
      } else {
         echo Dropdown::getYesNo($fields["ignore_ocs_import"]);
      }
      echo "	";
      echo "".
             ((isset($fields["is_helpdesk_visible"]) && $fields["is_helpdesk_visible"] != '')
              ? Dropdown::getYesNo($fields["is_helpdesk_visible"])
              : $LANG['rulesengine'][106]) . "	";
      echo "".
            (isset($fields['new_entities_id']) && strlen($fields['new_entities_id'])
               ? Dropdown::getDropdownName('glpi_entities', $fields['new_entities_id'])
               : $LANG['rulesengine'][106]) . "	";
   }

   function getCriterias() {
      global $LANG;

      $criterias = array();
      $criterias['name']['field'] = 'name';
      $criterias['name']['name']  = $LANG['help'][31];
      $criterias['name']['table'] = 'glpi_softwares';

      $criterias['manufacturer']['field'] = 'name';
      $criterias['manufacturer']['name']  = $LANG['common'][5];
      $criterias['manufacturer']['table'] = 'glpi_manufacturers';

      $criterias['entities_id']['field'] = 'completename';
      $criterias['entities_id']['name']  = $LANG['entity'][0];
      $criterias['entities_id']['table'] = 'glpi_entities';
      $criterias['entities_id']['type']  = 'dropdown';

      return $criterias;
   }

   function getActions() {
      global $LANG;

      $actions = array();
      $actions['name']['name']          = $LANG['help'][31];
      $actions['name']['force_actions'] = array('assign', 'regex_result');

      $actions['_ignore_ocs_import']['name'] = $LANG['rulesengine'][132];
      $actions['_ignore_ocs_import']['type'] = 'yesonly';

      $actions['version']['name']          = $LANG['rulesengine'][78];
      $actions['version']['force_actions'] = array('assign','regex_result', 'append_regex_result');

      $actions['manufacturer']['name']  = $LANG['common'][5];
      $actions['manufacturer']['table'] = 'glpi_manufacturers';
      $actions['manufacturer']['type']  = 'dropdown';

      $actions['is_helpdesk_visible']['name']  = $LANG['software'][46];
      $actions['is_helpdesk_visible']['table'] = 'glpi_softwares';
      $actions['is_helpdesk_visible']['type']  = 'yesno';

      $actions['new_entities_id']['name']  = $LANG['entity'][0];
      $actions['new_entities_id']['table'] = 'glpi_entities';
      $actions['new_entities_id']['type']  = 'dropdown';

      return $actions;
   }

   function addSpecificParamsForPreview($params) {

      if (isset($_POST["version"])) {
         $params["version"] = $_POST["version"];
      }
      return $params;
   }

   /**
    * Function used to display type specific criterias during rule's preview
    *
    * @param $fields fields values
   **/
   function showSpecificCriteriasForPreview($fields) {

      if (isset($this->fields['id'])) {
         $this->getRuleWithCriteriasAndActions($this->fields['id'],0,1);
      }

      //if there's a least one action with type == append_regex_result, then need to display
      //this field as a criteria
      foreach ($this->actions as $action) {
         if ($action->fields["action_type"] == "append_regex_result") {
            $value = (isset($fields[$action->fields['field']])?$fields[$action->fields['field']]:'');
            //Get actions for this type of rule
            $actions = $this->getActions();

            //display the additionnal field
            echo "
";
            echo "".$this->fields['match']."	";
            echo "".$actions[$action->fields['field']]['name']."	";
            echo "<input type='text' name='version' value='$value'>
";
         }
      }
   }

}

?>