<commit_before>/*

Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "../typedefs.h"
#include "../algorithms/tiny_components.hpp"
#include "../data_structures/static_graph.hpp"
#include "../data_structures/coordinate_calculation.hpp"
#include "../util/fingerprint.hpp"
#include "../util/graph_loader.hpp"
#include "../util/make_unique.hpp"
#include "../util/osrm_exception.hpp"
#include "../util/simple_logger.hpp"

#include <boost/filesystem.hpp>

#if defined(__APPLE__) || defined(_WIN32)
#include <gdal.h>
#include <ogrsf_frmts.h>
#else
#include <gdal/gdal.h>
#include <gdal/ogrsf_frmts.h>
#endif

#include <osrm/coordinate.hpp>

#include <fstream>
#include <memory>
#include <string>
#include <vector>

namespace
{

struct TarjanEdgeData
{
    TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {}
    TarjanEdgeData(int distance, unsigned name_id) : distance(distance), name_id(name_id) {}
    int distance;
    unsigned name_id;
};

using TarjanGraph = StaticGraph<TarjanEdgeData>;
using TarjanEdge = TarjanGraph::InputEdge;

void DeleteFileIfExists(const std::string &file_name)
{
    if (boost::filesystem::exists(file_name))
    {
        boost::filesystem::remove(file_name);
    }
}
}

int main(int argc, char *argv[])
{
    std::vector<QueryNode> coordinate_list;
    std::vector<TurnRestriction> restriction_list;
    std::vector<NodeID> bollard_node_list;
    std::vector<NodeID> traffic_lights_list;

    LogPolicy::GetInstance().Unmute();
    try
    {
        // enable logging
        if (argc < 3)
        {
            SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0]
                                             << " <osrm> <osrm.restrictions>";
            return -1;
        }

        SimpleLogger().Write() << "Using restrictions from file: " << argv[2];
        std::ifstream restriction_ifstream(argv[2], std::ios::binary);
        const FingerPrint fingerprint_orig;
        FingerPrint fingerprint_loaded;
        restriction_ifstream.read((char *)&fingerprint_loaded, sizeof(FingerPrint));

        // check fingerprint and warn if necessary
        if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig))
        {
            SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. "
                                                           "Reprocess to get rid of this warning.";
        }

        if (!restriction_ifstream.good())
        {
            throw osrm::exception("Could not access <osrm-restrictions> files");
        }
        uint32_t usable_restrictions = 0;
        restriction_ifstream.read((char *)&usable_restrictions, sizeof(uint32_t));
        restriction_list.resize(usable_restrictions);

        // load restrictions
        if (usable_restrictions > 0)
        {
            restriction_ifstream.read((char *)&(restriction_list[0]),
                                      usable_restrictions * sizeof(TurnRestriction));
        }
        restriction_ifstream.close();

        std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary);
        if (!input_stream.is_open())
        {
            throw osrm::exception("Cannot open osrm file");
        }

        // load graph data
        std::vector<ImportEdge> edge_list;
        const NodeID number_of_nodes =
            readBinaryOSRMGraphFromStream(input_stream, edge_list, bollard_node_list,
                                          traffic_lights_list, &coordinate_list, restriction_list);
        input_stream.close();

        BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions,
                         "size of restriction_list changed");

        SimpleLogger().Write() << restriction_list.size() << " restrictions, "
                               << bollard_node_list.size() << " bollard nodes, "
                               << traffic_lights_list.size() << " traffic lights";

        traffic_lights_list.clear();
        traffic_lights_list.shrink_to_fit();

        // Building an node-based graph
        std::vector<TarjanEdge> graph_edge_list;
        for (const NodeBasedEdge &input_edge : edge_list)
        {
            if (input_edge.source == input_edge.target)
            {
                continue;
            }

            if (input_edge.forward)
            {
                graph_edge_list.emplace_back(input_edge.source, input_edge.target,
                                             (std::max)((int)input_edge.weight, 1),
                                             input_edge.name_id);
            }
            if (input_edge.backward)
            {
                graph_edge_list.emplace_back(input_edge.target, input_edge.source,
                                             (std::max)((int)input_edge.weight, 1),
                                             input_edge.name_id);
            }
        }
        edge_list.clear();
        edge_list.shrink_to_fit();
        BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(),
                         "input edge vector not properly deallocated");

        tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end());
        auto graph = std::make_shared<TarjanGraph>(number_of_nodes, graph_edge_list);
        edge_list.clear();
        edge_list.shrink_to_fit();

        SimpleLogger().Write() << "Starting SCC graph traversal";

        RestrictionMap restriction_map(restriction_list);
        auto tarjan =
            osrm::make_unique<TarjanSCC<TarjanGraph>>(graph, restriction_map, bollard_node_list);
        tarjan->run();
        SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components()
                               << " many components";
        SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs";

        // output
        TIMER_START(SCC_RUN_SETUP);

        // remove files from previous run if exist
        DeleteFileIfExists("component.dbf");
        DeleteFileIfExists("component.shx");
        DeleteFileIfExists("component.shp");

        Percent p(graph->GetNumberOfNodes());

        OGRRegisterAll();

        const char *pszDriverName = "ESRI Shapefile";
        OGRSFDriver *poDriver =
            OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName);
        if (nullptr == poDriver)
        {
            throw osrm::exception("ESRI Shapefile driver not available");
        }
        OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr);

        if (nullptr == poDS)
        {
            throw osrm::exception("Creation of output file failed");
        }

        OGRSpatialReference *poSRS = new OGRSpatialReference();
        poSRS->importFromEPSG(4326);

        OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr);

        if (nullptr == poLayer)
        {
            throw osrm::exception("Layer creation failed.");
        }
        TIMER_STOP(SCC_RUN_SETUP);
        SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000.
                               << "s";

        uint64_t total_network_distance = 0;
        p.reinit(graph->GetNumberOfNodes());
        TIMER_START(SCC_OUTPUT);
        for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes()))
        {
            p.printIncrement();
            for (const auto current_edge : graph->GetAdjacentEdgeRange(source))
            {
                const TarjanGraph::NodeIterator target = graph->GetTarget(current_edge);

                if (source < target || graph->EndEdges(target) == graph->FindEdge(target, source))
                {
                    total_network_distance +=
                        100 * coordinate_calculation::euclidean_distance(
                                  coordinate_list[source].lat, coordinate_list[source].lon,
                                  coordinate_list[target].lat, coordinate_list[target].lon);

                    BOOST_ASSERT(current_edge != SPECIAL_EDGEID);
                    BOOST_ASSERT(source != SPECIAL_NODEID);
                    BOOST_ASSERT(target != SPECIAL_NODEID);

                    const unsigned size_of_containing_component = std::min(
                        tarjan->get_component_size(source), tarjan->get_component_size(target));

                    // edges that end on bollard nodes may actually be in two distinct components
                    if (size_of_containing_component < 1000)
                    {
                        OGRLineString lineString;
                        lineString.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION,
                                            coordinate_list[source].lat / COORDINATE_PRECISION);
                        lineString.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION,
                                            coordinate_list[target].lat / COORDINATE_PRECISION);

                        OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());

                        poFeature->SetGeometry(&lineString);
                        if (OGRERR_NONE != poLayer->CreateFeature(poFeature))
                        {
                            throw osrm::exception("Failed to create feature in shapefile.");
                        }
                        OGRFeature::DestroyFeature(poFeature);
                    }
                }
            }
        }
        OGRSpatialReference::DestroySpatialReference(poSRS);
        OGRDataSource::DestroyDataSource(poDS);
        TIMER_STOP(SCC_OUTPUT);
        SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000.
                               << "s";

        SimpleLogger().Write() << "total network distance: "
                               << (uint64_t)total_network_distance / 100 / 1000. << " km";

        SimpleLogger().Write() << "finished component analysis";
    }
    catch (const std::exception &e)
    {
        SimpleLogger().Write(logWARNING) << "[exception] " << e.what();
    }
    return 0;
}
<commit_msg>reduce number of old-style casts<commit_after>/*

Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "../typedefs.h"
#include "../algorithms/tiny_components.hpp"
#include "../data_structures/static_graph.hpp"
#include "../data_structures/coordinate_calculation.hpp"
#include "../util/fingerprint.hpp"
#include "../util/graph_loader.hpp"
#include "../util/make_unique.hpp"
#include "../util/osrm_exception.hpp"
#include "../util/simple_logger.hpp"

#include <boost/filesystem.hpp>

#if defined(__APPLE__) || defined(_WIN32)
#include <gdal.h>
#include <ogrsf_frmts.h>
#else
#include <gdal/gdal.h>
#include <gdal/ogrsf_frmts.h>
#endif

#include <osrm/coordinate.hpp>

#include <fstream>
#include <memory>
#include <string>
#include <vector>

namespace
{

struct TarjanEdgeData
{
    TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {}
    TarjanEdgeData(unsigned distance, unsigned name_id) : distance(distance), name_id(name_id) {}
    unsigned distance;
    unsigned name_id;
};

using TarjanGraph = StaticGraph<TarjanEdgeData>;
using TarjanEdge = TarjanGraph::InputEdge;

void DeleteFileIfExists(const std::string &file_name)
{
    if (boost::filesystem::exists(file_name))
    {
        boost::filesystem::remove(file_name);
    }
}
}

int main(int argc, char *argv[])
{
    std::vector<QueryNode> coordinate_list;
    std::vector<TurnRestriction> restriction_list;
    std::vector<NodeID> bollard_node_list;
    std::vector<NodeID> traffic_lights_list;

    LogPolicy::GetInstance().Unmute();
    try
    {
        // enable logging
        if (argc < 3)
        {
            SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0]
                                             << " <osrm> <osrm.restrictions>";
            return -1;
        }

        SimpleLogger().Write() << "Using restrictions from file: " << argv[2];
        std::ifstream restriction_ifstream(argv[2], std::ios::binary);
        const FingerPrint fingerprint_orig;
        FingerPrint fingerprint_loaded;
        restriction_ifstream.read(reinterpret_cast<char *>(&fingerprint_loaded),
                                  sizeof(FingerPrint));

        // check fingerprint and warn if necessary
        if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig))
        {
            SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. "
                                                           "Reprocess to get rid of this warning.";
        }

        if (!restriction_ifstream.good())
        {
            throw osrm::exception("Could not access <osrm-restrictions> files");
        }
        uint32_t usable_restrictions = 0;
        restriction_ifstream.read(reinterpret_cast<char *>(&usable_restrictions), sizeof(uint32_t));
        restriction_list.resize(usable_restrictions);

        // load restrictions
        if (usable_restrictions > 0)
        {
            restriction_ifstream.read(reinterpret_cast<char *>(&restriction_list[0]),
                                      usable_restrictions * sizeof(TurnRestriction));
        }
        restriction_ifstream.close();

        std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary);
        if (!input_stream.is_open())
        {
            throw osrm::exception("Cannot open osrm file");
        }

        // load graph data
        std::vector<ImportEdge> edge_list;
        const NodeID number_of_nodes =
            readBinaryOSRMGraphFromStream(input_stream, edge_list, bollard_node_list,
                                          traffic_lights_list, &coordinate_list, restriction_list);
        input_stream.close();

        BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions,
                         "size of restriction_list changed");

        SimpleLogger().Write() << restriction_list.size() << " restrictions, "
                               << bollard_node_list.size() << " bollard nodes, "
                               << traffic_lights_list.size() << " traffic lights";

        traffic_lights_list.clear();
        traffic_lights_list.shrink_to_fit();

        // Building an node-based graph
        std::vector<TarjanEdge> graph_edge_list;
        for (const auto &input_edge : edge_list)
        {
            if (input_edge.source == input_edge.target)
            {
                continue;
            }

            if (input_edge.forward)
            {
                graph_edge_list.emplace_back(input_edge.source, input_edge.target,
                                             (std::max)(input_edge.weight, 1), input_edge.name_id);
            }
            if (input_edge.backward)
            {
                graph_edge_list.emplace_back(input_edge.target, input_edge.source,
                                             (std::max)(input_edge.weight, 1), input_edge.name_id);
            }
        }
        edge_list.clear();
        edge_list.shrink_to_fit();
        BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(),
                         "input edge vector not properly deallocated");

        tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end());
        auto graph = std::make_shared<TarjanGraph>(number_of_nodes, graph_edge_list);
        edge_list.clear();
        edge_list.shrink_to_fit();

        SimpleLogger().Write() << "Starting SCC graph traversal";

        RestrictionMap restriction_map(restriction_list);
        auto tarjan =
            osrm::make_unique<TarjanSCC<TarjanGraph>>(graph, restriction_map, bollard_node_list);
        tarjan->run();
        SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components()
                               << " many components";
        SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs";

        // output
        TIMER_START(SCC_RUN_SETUP);

        // remove files from previous run if exist
        DeleteFileIfExists("component.dbf");
        DeleteFileIfExists("component.shx");
        DeleteFileIfExists("component.shp");

        Percent p(graph->GetNumberOfNodes());

        OGRRegisterAll();

        const char *pszDriverName = "ESRI Shapefile";
        OGRSFDriver *poDriver =
            OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName);
        if (nullptr == poDriver)
        {
            throw osrm::exception("ESRI Shapefile driver not available");
        }
        OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr);

        if (nullptr == poDS)
        {
            throw osrm::exception("Creation of output file failed");
        }

        OGRSpatialReference *poSRS = new OGRSpatialReference();
        poSRS->importFromEPSG(4326);

        OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr);

        if (nullptr == poLayer)
        {
            throw osrm::exception("Layer creation failed.");
        }
        TIMER_STOP(SCC_RUN_SETUP);
        SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000.
                               << "s";

        uint64_t total_network_length = 0;
        p.reinit(graph->GetNumberOfNodes());
        TIMER_START(SCC_OUTPUT);
        for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes()))
        {
            p.printIncrement();
            for (const auto current_edge : graph->GetAdjacentEdgeRange(source))
            {
                const TarjanGraph::NodeIterator target = graph->GetTarget(current_edge);

                if (source < target || graph->EndEdges(target) == graph->FindEdge(target, source))
                {
                    total_network_length +=
                        100 * coordinate_calculation::euclidean_distance(
                                  coordinate_list[source].lat, coordinate_list[source].lon,
                                  coordinate_list[target].lat, coordinate_list[target].lon);

                    BOOST_ASSERT(current_edge != SPECIAL_EDGEID);
                    BOOST_ASSERT(source != SPECIAL_NODEID);
                    BOOST_ASSERT(target != SPECIAL_NODEID);

                    const unsigned size_of_containing_component = std::min(
                        tarjan->get_component_size(source), tarjan->get_component_size(target));

                    // edges that end on bollard nodes may actually be in two distinct components
                    if (size_of_containing_component < 1000)
                    {
                        OGRLineString lineString;
                        lineString.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION,
                                            coordinate_list[source].lat / COORDINATE_PRECISION);
                        lineString.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION,
                                            coordinate_list[target].lat / COORDINATE_PRECISION);

                        OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());

                        poFeature->SetGeometry(&lineString);
                        if (OGRERR_NONE != poLayer->CreateFeature(poFeature))
                        {
                            throw osrm::exception("Failed to create feature in shapefile.");
                        }
                        OGRFeature::DestroyFeature(poFeature);
                    }
                }
            }
        }
        OGRSpatialReference::DestroySpatialReference(poSRS);
        OGRDataSource::DestroyDataSource(poDS);
        TIMER_STOP(SCC_OUTPUT);
        SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000.
                               << "s";

        SimpleLogger().Write() << "total network distance: "
                               << static_cast<uint64_t>(total_network_length / 100 / 1000.)
                               << " km";

        SimpleLogger().Write() << "finished component analysis";
    }
    catch (const std::exception &e)
    {
        SimpleLogger().Write(logWARNING) << "[exception] " << e.what();
    }
    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.

#ifndef FASTDDS_SERVER_SERVER_CPP_
#define FASTDDS_SERVER_SERVER_CPP_

#include "server.h"

#include <iostream>
#include <sstream>
#include <regex>
#include <vector>

#include <mutex>
#include <condition_variable>
#include <csignal>

#include <fastrtps/Domain.h>
#include <fastrtps/participant/Participant.h>
#include <fastdds/dds/log/Log.hpp>

using namespace eprosima;
using namespace fastrtps;
using namespace std;

volatile sig_atomic_t g_signal_status = 0;
mutex g_signal_mutex;
condition_variable g_signal_cv;

void sigint_handler(
        int signum)
{
    //  locking here is counterproductive
    //  unique_lock<mutex> lock(g_signal_mutex);
    g_signal_status = signum;
    g_signal_cv.notify_one();
}

int main (
        int argc,
        char* argv[])
{
    // skip program name argv[0] if present
    argc -= (argc > 0);
    argv += (argc > 0);
    option::Stats stats(usage, argc, argv);
    vector<option::Option> options(stats.options_max);
    vector<option::Option> buffer(stats.buffer_max);
    option::Parser parse(usage, argc, argv, &options[0], &buffer[0]);

    // check the command line options
    if (parse.error())
    {
        return 1;
    }

    // no arguments beyond options
    int noopts = parse.nonOptionsCount();
    if ( noopts )
    {
        string sep( noopts == 1 ? "argument: " : "arguments: " );

        cout << "Unknown ";

        while ( noopts-- )
        {
            cout << sep << parse.nonOption(noopts);
            sep = ", ";
        }

        endl(cout);

        return 1;
    }

    // show help if asked to
    if (options[HELP] || argc == 0)
    {
        option::printUsage(std::cout, usage);

        return 0;
    }

    // auto att = make_unique<ParticipantAttributes>();
    // C++11 constrains
    unique_ptr<ParticipantAttributes> att(new ParticipantAttributes());
    rtps::RTPSParticipantAttributes& rtps = att->rtps;

    // Retrieve server Id: is mandatory and only specified once
    // Note there is a specific cast to pointer if the Option is valid
    option::Option* pOp = options[SERVERID];
    int server_id;

    if ( nullptr == pOp )
    {
        cout << "Specify server id is mandatory: use -i or --server-id option." << endl;
        return 1;
    }
    else if ( pOp->count() != 1)
    {
        cout << "Only one server can be created, thus, only one server id can be specified." << endl;
        return 1;
    }
    else
    {
        stringstream is;
        is << pOp->arg;

        // validation have been already done
        // Name the server according with the identifier
        if ( !( is >> server_id
                && eprosima::fastdds::rtps::get_server_client_default_guidPrefix(server_id, rtps.prefix)))
        {
            cout << "The provided server identifier is not valid" << endl;
            return 1;
        }

        // Set Participant Name
        is << "eProsima Default Server number " << server_id;
        rtps.setName(is.str().c_str());
    }

    // Choose the kind of server to create
    rtps.builtin.discovery_config.discoveryProtocol =
            options[BACKUP] ? rtps::DiscoveryProtocol_t::BACKUP : rtps::DiscoveryProtocol_t::SERVER;

    // Set up listening locators.
    // If the number of specify ports doesn't match the number of IPs the last port is used.
    // If at least one port specified replace the default one
    rtps::Locator_t locator(eprosima::fastdds::rtps::DEFAULT_ROS2_SERVER_PORT);

    // retrieve first UDP port
    option::Option* pO_port = options[PORT];
    if ( nullptr != pO_port )
    {
        stringstream is;
        is << pO_port->arg;
        uint16_t id;

        if ( !(is >> id
                && is.eof()
                && rtps::IPLocator::setPhysicalPort(locator, id)))
        {
            cout << "Invalid listening locator port specified:" << id << endl;
            return 1;
        }
    }

    rtps::IPLocator::setIPv4(locator, 0, 0, 0, 0);

    // retrieve first IP address
    pOp = options[IPADDRESS];
    if ( nullptr == pOp )
    {
        // add default locator
        rtps.builtin.metatrafficUnicastLocatorList.push_back(locator);
    }
    else
    {
        while ( pOp )
        {
            // Update locator address
            if (!rtps::IPLocator::setIPv4(locator, string(pOp->arg)))
            {
                cout << "Invalid listening locator address specified:" << pOp->arg << endl;
                return 1;
            }

            // Update UDP port
            if ( nullptr != pO_port )
            {
                stringstream is;
                is << pO_port->arg;
                uint16_t id;

                if ( !(is >> id
                        && is.eof()
                        && rtps::IPLocator::setPhysicalPort(locator, id)))
                {
                    cout << "Invalid listening locator port specified:" << id << endl;
                    return 1;
                }
            }

            // add the locator
            rtps.builtin.metatrafficUnicastLocatorList.push_back(locator);

            pOp = pOp->next();
            if (pO_port)
            {
                pO_port = pO_port->next();
            }
            else
            {
                cout << "warning: the number of specified ports doesn't match the ip" << endl
                     << "         addresses provided. Locators share its port number." << endl;
            }
        }
    }

    // Create the server
    int return_value = 0;
    Participant* pServer = Domain::createParticipant(*att, nullptr);
    att.reset();

    if ( nullptr == pServer )
    {
        cout << "Server creation failed with the given settings. Please review locators setup." << endl;
        return_value = 1;
    }
    else
    {
        unique_lock<mutex> lock(g_signal_mutex);

        // handle signal SIGINT for every thread
        signal(SIGINT, sigint_handler);

        // Print running server attributes
        cout << "### Server is running ###" << endl;
        cout << "  Server ID:          " << server_id << endl;
        cout << "  Server GUID prefix: " << pServer->getGuid().guidPrefix << endl;
        cout << "  Server Address:     " << locator << endl;
        cout << "  Participant Type    " << rtps.builtin.discovery_config.discoveryProtocol << endl;

        g_signal_cv.wait(lock, []
                {
                    return 0 != g_signal_status;
                });

        cout << endl << "### Server shut down ###" << endl;
    }

    fastdds::dds::Log::Flush();
    cout.flush();
    Domain::stopAll();

    return return_value;
}

// argument validation function definitions
/*static*/
option::ArgStatus Arg::check_server_id(
        const option::Option& option,
        bool msg)
{
    // the argument is required
    if ( nullptr != option.arg )
    {
        // It must be a number within 0 and 255
        stringstream is;
        is << option.arg;
        int id;

        if ( is >> id
                && is.eof()
                && id >= 0
                && id <  256 )
        {
            return option::ARG_OK;
        }
    }

    if (msg)
    {
        cout << "Option '" << option.name
             << "' is mandatory. Should be a key indentifier between 0 and 255." << endl;
    }

    return option::ARG_ILLEGAL;
}

/*static*/
option::ArgStatus Arg::check_server_ipv4(
        const option::Option& option,
        bool msg)
{
    static const std::regex ipv4(R"(^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)");

    // the argument is required
    if ( nullptr != option.arg )
    {
        // we must check if its a proper ip address
        if ( std::regex_match(option.arg, ipv4))
        {
            return option::ARG_OK;
        }
    }

    if (msg)
    {
        cout << "Option '" << option.name
             << "' should be a proper IPv4 address." << endl;
    }

    return option::ARG_ILLEGAL;
}

/*static*/
option::ArgStatus Arg::check_udp_port(
        const option::Option& option,
        bool msg)
{
    // the argument is required
    if ( nullptr != option.arg )
    {
        // It must be in an ephemeral port range
        stringstream is;
        is << option.arg;
        int id;

        if ( is >> id
                && is.eof()
                && id > 1024
                && id < 65536 )
        {
            return option::ARG_OK;
        }
    }

    if (msg)
    {
        cout << "Option '" << option.name
             << "' value should be an UDP port between 1025 and 65535." << endl;
    }

    return option::ARG_ILLEGAL;
}

#endif // FASTDDS_SERVER_SERVER_CPP_
<commit_msg>List all server locators (#1799)<commit_after>// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.

#ifndef FASTDDS_SERVER_SERVER_CPP_
#define FASTDDS_SERVER_SERVER_CPP_

#include "server.h"

#include <iostream>
#include <sstream>
#include <regex>
#include <vector>

#include <mutex>
#include <condition_variable>
#include <csignal>

#include <fastrtps/Domain.h>
#include <fastrtps/participant/Participant.h>
#include <fastdds/dds/log/Log.hpp>

using namespace eprosima;
using namespace fastrtps;
using namespace std;

volatile sig_atomic_t g_signal_status = 0;
mutex g_signal_mutex;
condition_variable g_signal_cv;

void sigint_handler(
        int signum)
{
    //  locking here is counterproductive
    //  unique_lock<mutex> lock(g_signal_mutex);
    g_signal_status = signum;
    g_signal_cv.notify_one();
}

int main (
        int argc,
        char* argv[])
{
    // skip program name argv[0] if present
    argc -= (argc > 0);
    argv += (argc > 0);
    option::Stats stats(usage, argc, argv);
    vector<option::Option> options(stats.options_max);
    vector<option::Option> buffer(stats.buffer_max);
    option::Parser parse(usage, argc, argv, &options[0], &buffer[0]);

    // check the command line options
    if (parse.error())
    {
        return 1;
    }

    // no arguments beyond options
    int noopts = parse.nonOptionsCount();
    if ( noopts )
    {
        string sep( noopts == 1 ? "argument: " : "arguments: " );

        cout << "Unknown ";

        while ( noopts-- )
        {
            cout << sep << parse.nonOption(noopts);
            sep = ", ";
        }

        endl(cout);

        return 1;
    }

    // show help if asked to
    if (options[HELP] || argc == 0)
    {
        option::printUsage(std::cout, usage);

        return 0;
    }

    // auto att = make_unique<ParticipantAttributes>();
    // C++11 constrains
    unique_ptr<ParticipantAttributes> att(new ParticipantAttributes());
    rtps::RTPSParticipantAttributes& rtps = att->rtps;

    // Retrieve server Id: is mandatory and only specified once
    // Note there is a specific cast to pointer if the Option is valid
    option::Option* pOp = options[SERVERID];
    int server_id;

    if ( nullptr == pOp )
    {
        cout << "Specify server id is mandatory: use -i or --server-id option." << endl;
        return 1;
    }
    else if ( pOp->count() != 1)
    {
        cout << "Only one server can be created, thus, only one server id can be specified." << endl;
        return 1;
    }
    else
    {
        stringstream is;
        is << pOp->arg;

        // validation have been already done
        // Name the server according with the identifier
        if ( !( is >> server_id
                && eprosima::fastdds::rtps::get_server_client_default_guidPrefix(server_id, rtps.prefix)))
        {
            cout << "The provided server identifier is not valid" << endl;
            return 1;
        }

        // Set Participant Name
        is << "eProsima Default Server number " << server_id;
        rtps.setName(is.str().c_str());
    }

    // Choose the kind of server to create
    rtps.builtin.discovery_config.discoveryProtocol =
            options[BACKUP] ? rtps::DiscoveryProtocol_t::BACKUP : rtps::DiscoveryProtocol_t::SERVER;

    // Set up listening locators.
    // If the number of specify ports doesn't match the number of IPs the last port is used.
    // If at least one port specified replace the default one
    rtps::Locator_t locator(eprosima::fastdds::rtps::DEFAULT_ROS2_SERVER_PORT);

    // retrieve first UDP port
    option::Option* pO_port = options[PORT];
    if ( nullptr != pO_port )
    {
        stringstream is;
        is << pO_port->arg;
        uint16_t id;

        if ( !(is >> id
                && is.eof()
                && rtps::IPLocator::setPhysicalPort(locator, id)))
        {
            cout << "Invalid listening locator port specified:" << id << endl;
            return 1;
        }
    }

    rtps::IPLocator::setIPv4(locator, 0, 0, 0, 0);

    // retrieve first IP address
    pOp = options[IPADDRESS];
    if ( nullptr == pOp )
    {
        // add default locator
        rtps.builtin.metatrafficUnicastLocatorList.push_back(locator);
    }
    else
    {
        while ( pOp )
        {
            // Update locator address
            if (!rtps::IPLocator::setIPv4(locator, string(pOp->arg)))
            {
                cout << "Invalid listening locator address specified:" << pOp->arg << endl;
                return 1;
            }

            // Update UDP port
            if ( nullptr != pO_port )
            {
                stringstream is;
                is << pO_port->arg;
                uint16_t id;

                if ( !(is >> id
                        && is.eof()
                        && rtps::IPLocator::setPhysicalPort(locator, id)))
                {
                    cout << "Invalid listening locator port specified:" << id << endl;
                    return 1;
                }
            }

            // add the locator
            rtps.builtin.metatrafficUnicastLocatorList.push_back(locator);

            pOp = pOp->next();
            if (pO_port)
            {
                pO_port = pO_port->next();
            }
            else
            {
                cout << "warning: the number of specified ports doesn't match the ip" << endl
                     << "         addresses provided. Locators share its port number." << endl;
            }
        }
    }

    // Create the server
    int return_value = 0;
    Participant* pServer = Domain::createParticipant(*att, nullptr);

    if ( nullptr == pServer )
    {
        cout << "Server creation failed with the given settings. Please review locators setup." << endl;
        return_value = 1;
    }
    else
    {
        unique_lock<mutex> lock(g_signal_mutex);

        // handle signal SIGINT for every thread
        signal(SIGINT, sigint_handler);

        // Print running server attributes
        cout << "### Server is running ###" << endl;
        cout << "  Participant Type:   " << rtps.builtin.discovery_config.discoveryProtocol << endl;
        cout << "  Server ID:          " << server_id << endl;
        cout << "  Server GUID prefix: " << pServer->getGuid().guidPrefix << endl;
        cout << "  Server Addresses:   ";
        for (auto locator_it = att->rtps.builtin.metatrafficUnicastLocatorList.begin();
                locator_it != att->rtps.builtin.metatrafficUnicastLocatorList.end();)
        {
            cout << *locator_it;
            if (++locator_it != att->rtps.builtin.metatrafficUnicastLocatorList.end())
            {
                cout << std::endl << "                      ";
            }
        }
        cout << std::endl;

        g_signal_cv.wait(lock, []
                {
                    return 0 != g_signal_status;
                });

        cout << endl << "### Server shut down ###" << endl;
    }

    att.reset();
    fastdds::dds::Log::Flush();
    cout.flush();
    Domain::stopAll();

    return return_value;
}

// argument validation function definitions
/*static*/
option::ArgStatus Arg::check_server_id(
        const option::Option& option,
        bool msg)
{
    // the argument is required
    if ( nullptr != option.arg )
    {
        // It must be a number within 0 and 255
        stringstream is;
        is << option.arg;
        int id;

        if ( is >> id
                && is.eof()
                && id >= 0
                && id <  256 )
        {
            return option::ARG_OK;
        }
    }

    if (msg)
    {
        cout << "Option '" << option.name
             << "' is mandatory. Should be a key indentifier between 0 and 255." << endl;
    }

    return option::ARG_ILLEGAL;
}

/*static*/
option::ArgStatus Arg::check_server_ipv4(
        const option::Option& option,
        bool msg)
{
    static const std::regex ipv4(R"(^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)");

    // the argument is required
    if ( nullptr != option.arg )
    {
        // we must check if its a proper ip address
        if ( std::regex_match(option.arg, ipv4))
        {
            return option::ARG_OK;
        }
    }

    if (msg)
    {
        cout << "Option '" << option.name
             << "' should be a proper IPv4 address." << endl;
    }

    return option::ARG_ILLEGAL;
}

/*static*/
option::ArgStatus Arg::check_udp_port(
        const option::Option& option,
        bool msg)
{
    // the argument is required
    if ( nullptr != option.arg )
    {
        // It must be in an ephemeral port range
        stringstream is;
        is << option.arg;
        int id;

        if ( is >> id
                && is.eof()
                && id > 1024
                && id < 65536 )
        {
            return option::ARG_OK;
        }
    }

    if (msg)
    {
        cout << "Option '" << option.name
             << "' value should be an UDP port between 1025 and 65535." << endl;
    }

    return option::ARG_ILLEGAL;
}

#endif // FASTDDS_SERVER_SERVER_CPP_
<|endoftext|>


<commit_before>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <limits>

#include "src/compiler/control-builders.h"
#include "src/compiler/generic-node-inl.h"
#include "src/compiler/node-properties-inl.h"
#include "src/compiler/pipeline.h"
#include "src/compiler/simplified-lowering.h"
#include "src/compiler/simplified-node-factory.h"
#include "src/compiler/typer.h"
#include "src/compiler/verifier.h"
#include "src/execution.h"
#include "src/parser.h"
#include "src/rewriter.h"
#include "src/scopes.h"
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/codegen-tester.h"
#include "test/cctest/compiler/graph-builder-tester.h"
#include "test/cctest/compiler/value-helper.h"

using namespace v8::internal;
using namespace v8::internal::compiler;

// TODO(titzer): rename this to VMLoweringTester
template <typename ReturnType>
class SimplifiedGraphBuilderTester : public GraphBuilderTester<ReturnType> {
 public:
  SimplifiedGraphBuilderTester(MachineRepresentation p0 = kMachineLast,
                               MachineRepresentation p1 = kMachineLast,
                               MachineRepresentation p2 = kMachineLast,
                               MachineRepresentation p3 = kMachineLast,
                               MachineRepresentation p4 = kMachineLast)
      : GraphBuilderTester<ReturnType>(p0, p1, p2, p3, p4),
        typer(this->zone()),
        source_positions(this->graph()),
        jsgraph(this->graph(), this->common(), &typer),
        lowering(&jsgraph, &source_positions) {}

  Typer typer;
  SourcePositionTable source_positions;
  JSGraph jsgraph;
  SimplifiedLowering lowering;

  // Close graph and lower one node.
  void Lower(Node* node) {
    this->End();
    if (node == NULL) {
      lowering.LowerAllNodes();
    } else {
      lowering.Lower(node);
    }
  }

  // Close graph and lower all nodes.
  void LowerAllNodes() { Lower(NULL); }

  void StoreFloat64(Node* node, double* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    this->Store(kMachineFloat64, ptr_node, node);
  }

  Node* LoadInt32(int32_t* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    return this->Load(kMachineWord32, ptr_node);
  }

  Node* LoadUint32(uint32_t* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    return this->Load(kMachineWord32, ptr_node);
  }

  Node* LoadFloat64(double* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    return this->Load(kMachineFloat64, ptr_node);
  }

  Factory* factory() { return this->isolate()->factory(); }
  Heap* heap() { return this->isolate()->heap(); }
};

// TODO(dcarney): find a home for these functions.
namespace {

FieldAccess ForJSObjectMap() {
  FieldAccess access = {kTaggedBase, JSObject::kMapOffset, Handle<Name>(),
                        Type::Any(), kMachineTagged};
  return access;
}

FieldAccess ForJSObjectProperties() {
  FieldAccess access = {kTaggedBase, JSObject::kPropertiesOffset,
                        Handle<Name>(), Type::Any(), kMachineTagged};
  return access;
}

FieldAccess ForArrayBufferBackingStore() {
  FieldAccess access = {
      kTaggedBase,                           JSArrayBuffer::kBackingStoreOffset,
      Handle<Name>(),                        Type::UntaggedPtr(),
      MachineOperatorBuilder::pointer_rep(),
  };
  return access;
}

ElementAccess ForFixedArrayElement() {
  ElementAccess access = {kTaggedBase, FixedArray::kHeaderSize, Type::Any(),
                          kMachineTagged};
  return access;
}

ElementAccess ForBackingStoreElement(MachineRepresentation rep) {
  ElementAccess access = {kUntaggedBase,
                          kNonHeapObjectHeaderSize - kHeapObjectTag,
                          Type::Any(), rep};
  return access;
}
}

// Create a simple JSObject with a unique map.
static Handle<JSObject> TestObject() {
  static int index = 0;
  char buffer[50];
  v8::base::OS::SNPrintF(buffer, 50, "({'a_%d':1})", index++);
  return Handle<JSObject>::cast(v8::Utils::OpenHandle(*CompileRun(buffer)));
}

TEST(RunLoadMap) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
  FieldAccess access = ForJSObjectMap();
  Node* load = t.LoadField(access, t.Parameter(0));
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<Map> src_map(src->map());
  Object* result = t.Call(*src);
  CHECK_EQ(*src_map, result);
}

TEST(RunStoreMap) {
  SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);
  FieldAccess access = ForJSObjectMap();
  t.StoreField(access, t.Parameter(1), t.Parameter(0));
  t.Return(t.Int32Constant(0));

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<Map> src_map(src->map());
  Handle<JSObject> dst = TestObject();
  CHECK(src->map() != dst->map());
  t.Call(*src_map, *dst);
  CHECK(*src_map == dst->map());
}

TEST(RunLoadProperties) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
  FieldAccess access = ForJSObjectProperties();
  Node* load = t.LoadField(access, t.Parameter(0));
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<FixedArray> src_props(src->properties());
  Object* result = t.Call(*src);
  CHECK_EQ(*src_props, result);
}

TEST(RunLoadStoreMap) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged, kMachineTagged);
  FieldAccess access = ForJSObjectMap();
  Node* load = t.LoadField(access, t.Parameter(0));
  t.StoreField(access, t.Parameter(1), load);
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<Map> src_map(src->map());
  Handle<JSObject> dst = TestObject();
  CHECK(src->map() != dst->map());
  Object* result = t.Call(*src, *dst);
  CHECK(result->IsMap());
  CHECK_EQ(*src_map, result);
  CHECK(*src_map == dst->map());
}

TEST(RunLoadStoreFixedArrayIndex) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
  ElementAccess access = ForFixedArrayElement();
  Node* load = t.LoadElement(access, t.Parameter(0), t.Int32Constant(0));
  t.StoreElement(access, t.Parameter(0), t.Int32Constant(1), load);
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<FixedArray> array = t.factory()->NewFixedArray(2);
  Handle<JSObject> src = TestObject();
  Handle<JSObject> dst = TestObject();
  array->set(0, *src);
  array->set(1, *dst);
  Object* result = t.Call(*array);
  CHECK_EQ(*src, result);
  CHECK_EQ(*src, array->get(0));
  CHECK_EQ(*src, array->get(1));
}

TEST(RunLoadStoreArrayBuffer) {
  SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged);
  const int index = 12;
  FieldAccess access = ForArrayBufferBackingStore();
  Node* backing_store = t.LoadField(access, t.Parameter(0));
  ElementAccess buffer_access = ForBackingStoreElement(kMachineWord8);
  Node* load =
      t.LoadElement(buffer_access, backing_store, t.Int32Constant(index));
  t.StoreElement(buffer_access, backing_store, t.Int32Constant(index + 1),
                 load);
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSArrayBuffer> array = t.factory()->NewJSArrayBuffer();
  const int array_length = 2 * index;
  Runtime::SetupArrayBufferAllocatingData(t.isolate(), array, array_length);
  uint8_t* data = reinterpret_cast<uint8_t*>(array->backing_store());
  for (int i = 0; i < array_length; i++) {
    data[i] = i;
  }
  int32_t result = t.Call(*array);
  CHECK_EQ(index, result);
  for (int i = 0; i < array_length; i++) {
    uint8_t expected = i;
    if (i == (index + 1)) expected = result;
    CHECK_EQ(data[i], expected);
  }
}

TEST(RunCopyFixedArray) {
  SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);

  const int kArraySize = 15;
  Node* one = t.Int32Constant(1);
  Node* index = t.Int32Constant(0);
  Node* limit = t.Int32Constant(kArraySize);
  t.environment()->Push(index);
  {
    LoopBuilder loop(&t);
    loop.BeginLoop();
    // Loop exit condition.
    index = t.environment()->Top();
    Node* condition = t.Int32LessThan(index, limit);
    loop.BreakUnless(condition);
    // src[index] = dst[index].
    index = t.environment()->Pop();
    ElementAccess access = ForFixedArrayElement();
    Node* src = t.Parameter(0);
    Node* load = t.LoadElement(access, src, index);
    Node* dst = t.Parameter(1);
    t.StoreElement(access, dst, index, load);
    // index++
    index = t.Int32Add(index, one);
    t.environment()->Push(index);
    // continue.
    loop.EndBody();
    loop.EndLoop();
  }
  index = t.environment()->Pop();
  t.Return(index);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<FixedArray> src = t.factory()->NewFixedArray(kArraySize);
  Handle<FixedArray> src_copy = t.factory()->NewFixedArray(kArraySize);
  Handle<FixedArray> dst = t.factory()->NewFixedArray(kArraySize);
  for (int i = 0; i < kArraySize; i++) {
    src->set(i, *TestObject());
    src_copy->set(i, src->get(i));
    dst->set(i, *TestObject());
    CHECK_NE(src_copy->get(i), dst->get(i));
  }
  CHECK_EQ(kArraySize, t.Call(*src, *dst));
  for (int i = 0; i < kArraySize; i++) {
    CHECK_EQ(src_copy->get(i), dst->get(i));
  }
}

TEST(RunLoadFieldFromUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
    int offset = static_cast<int>(i * sizeof(Smi*));
    FieldAccess access = {kUntaggedBase, offset, Handle<Name>(),
                          Type::Integral32(), kMachineTagged};

    SimplifiedGraphBuilderTester<Object*> t;
    Node* load = t.LoadField(access, t.PointerConstant(smis));
    t.Return(load);
    t.LowerAllNodes();

    if (!Pipeline::SupportedTarget()) continue;

    for (int j = -5; j <= 5; j++) {
      Smi* expected = Smi::FromInt(j);
      smis[i] = expected;
      CHECK_EQ(expected, t.Call());
    }
  }
}

TEST(RunStoreFieldToUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
    int offset = static_cast<int>(i * sizeof(Smi*));
    FieldAccess access = {kUntaggedBase, offset, Handle<Name>(),
                          Type::Integral32(), kMachineTagged};

    SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
    Node* p0 = t.Parameter(0);
    t.StoreField(access, t.PointerConstant(smis), p0);
    t.Return(p0);
    t.LowerAllNodes();

    if (!Pipeline::SupportedTarget()) continue;

    for (int j = -5; j <= 5; j++) {
      Smi* expected = Smi::FromInt(j);
      smis[i] = Smi::FromInt(-100);
      CHECK_EQ(expected, t.Call(expected));
      CHECK_EQ(expected, smis[i]);
    }
  }
}

TEST(RunLoadElementFromUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
                 Smi::FromInt(4), Smi::FromInt(5)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {    // for header sizes
    for (size_t j = i; j < ARRAY_SIZE(smis); j++) {  // for element index
      int offset = static_cast<int>(i * sizeof(Smi*));
      ElementAccess access = {kUntaggedBase, offset, Type::Integral32(),
                              kMachineTagged};

      SimplifiedGraphBuilderTester<Object*> t;
      Node* load = t.LoadElement(access, t.PointerConstant(smis),
                                 t.Int32Constant(static_cast<int>(j)));
      t.Return(load);
      t.LowerAllNodes();

      if (!Pipeline::SupportedTarget()) continue;

      for (int k = -5; k <= 5; k++) {
        Smi* expected = Smi::FromInt(k);
        smis[i + j] = expected;
        CHECK_EQ(expected, t.Call());
      }
    }
  }
}

TEST(RunStoreElementFromUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
                 Smi::FromInt(4), Smi::FromInt(5)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {    // for header sizes
    for (size_t j = i; j < ARRAY_SIZE(smis); j++) {  // for element index
      int offset = static_cast<int>(i * sizeof(Smi*));
      ElementAccess access = {kUntaggedBase, offset, Type::Integral32(),
                              kMachineTagged};

      SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
      Node* p0 = t.Parameter(0);
      t.StoreElement(access, t.PointerConstant(smis),
                     t.Int32Constant(static_cast<int>(j)), p0);
      t.Return(p0);
      t.LowerAllNodes();

      if (!Pipeline::SupportedTarget()) continue;

      for (int k = -5; k <= 5; k++) {
        Smi* expected = Smi::FromInt(k);
        smis[i + j] = Smi::FromInt(-100);
        CHECK_EQ(expected, t.Call(expected));
        CHECK_EQ(expected, smis[i + j]);
      }
    }
  }
}
<commit_msg>Fix more stack smashing bugs in test.<commit_after>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <limits>

#include "src/compiler/control-builders.h"
#include "src/compiler/generic-node-inl.h"
#include "src/compiler/node-properties-inl.h"
#include "src/compiler/pipeline.h"
#include "src/compiler/simplified-lowering.h"
#include "src/compiler/simplified-node-factory.h"
#include "src/compiler/typer.h"
#include "src/compiler/verifier.h"
#include "src/execution.h"
#include "src/parser.h"
#include "src/rewriter.h"
#include "src/scopes.h"
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/codegen-tester.h"
#include "test/cctest/compiler/graph-builder-tester.h"
#include "test/cctest/compiler/value-helper.h"

using namespace v8::internal;
using namespace v8::internal::compiler;

// TODO(titzer): rename this to VMLoweringTester
template <typename ReturnType>
class SimplifiedGraphBuilderTester : public GraphBuilderTester<ReturnType> {
 public:
  SimplifiedGraphBuilderTester(MachineRepresentation p0 = kMachineLast,
                               MachineRepresentation p1 = kMachineLast,
                               MachineRepresentation p2 = kMachineLast,
                               MachineRepresentation p3 = kMachineLast,
                               MachineRepresentation p4 = kMachineLast)
      : GraphBuilderTester<ReturnType>(p0, p1, p2, p3, p4),
        typer(this->zone()),
        source_positions(this->graph()),
        jsgraph(this->graph(), this->common(), &typer),
        lowering(&jsgraph, &source_positions) {}

  Typer typer;
  SourcePositionTable source_positions;
  JSGraph jsgraph;
  SimplifiedLowering lowering;

  // Close graph and lower one node.
  void Lower(Node* node) {
    this->End();
    if (node == NULL) {
      lowering.LowerAllNodes();
    } else {
      lowering.Lower(node);
    }
  }

  // Close graph and lower all nodes.
  void LowerAllNodes() { Lower(NULL); }

  void StoreFloat64(Node* node, double* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    this->Store(kMachineFloat64, ptr_node, node);
  }

  Node* LoadInt32(int32_t* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    return this->Load(kMachineWord32, ptr_node);
  }

  Node* LoadUint32(uint32_t* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    return this->Load(kMachineWord32, ptr_node);
  }

  Node* LoadFloat64(double* ptr) {
    Node* ptr_node = this->PointerConstant(ptr);
    return this->Load(kMachineFloat64, ptr_node);
  }

  Factory* factory() { return this->isolate()->factory(); }
  Heap* heap() { return this->isolate()->heap(); }
};

// TODO(dcarney): find a home for these functions.
namespace {

FieldAccess ForJSObjectMap() {
  FieldAccess access = {kTaggedBase, JSObject::kMapOffset, Handle<Name>(),
                        Type::Any(), kMachineTagged};
  return access;
}

FieldAccess ForJSObjectProperties() {
  FieldAccess access = {kTaggedBase, JSObject::kPropertiesOffset,
                        Handle<Name>(), Type::Any(), kMachineTagged};
  return access;
}

FieldAccess ForArrayBufferBackingStore() {
  FieldAccess access = {
      kTaggedBase,                           JSArrayBuffer::kBackingStoreOffset,
      Handle<Name>(),                        Type::UntaggedPtr(),
      MachineOperatorBuilder::pointer_rep(),
  };
  return access;
}

ElementAccess ForFixedArrayElement() {
  ElementAccess access = {kTaggedBase, FixedArray::kHeaderSize, Type::Any(),
                          kMachineTagged};
  return access;
}

ElementAccess ForBackingStoreElement(MachineRepresentation rep) {
  ElementAccess access = {kUntaggedBase,
                          kNonHeapObjectHeaderSize - kHeapObjectTag,
                          Type::Any(), rep};
  return access;
}
}

// Create a simple JSObject with a unique map.
static Handle<JSObject> TestObject() {
  static int index = 0;
  char buffer[50];
  v8::base::OS::SNPrintF(buffer, 50, "({'a_%d':1})", index++);
  return Handle<JSObject>::cast(v8::Utils::OpenHandle(*CompileRun(buffer)));
}

TEST(RunLoadMap) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
  FieldAccess access = ForJSObjectMap();
  Node* load = t.LoadField(access, t.Parameter(0));
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<Map> src_map(src->map());
  Object* result = t.Call(*src);
  CHECK_EQ(*src_map, result);
}

TEST(RunStoreMap) {
  SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);
  FieldAccess access = ForJSObjectMap();
  t.StoreField(access, t.Parameter(1), t.Parameter(0));
  t.Return(t.Int32Constant(0));

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<Map> src_map(src->map());
  Handle<JSObject> dst = TestObject();
  CHECK(src->map() != dst->map());
  t.Call(*src_map, *dst);
  CHECK(*src_map == dst->map());
}

TEST(RunLoadProperties) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
  FieldAccess access = ForJSObjectProperties();
  Node* load = t.LoadField(access, t.Parameter(0));
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<FixedArray> src_props(src->properties());
  Object* result = t.Call(*src);
  CHECK_EQ(*src_props, result);
}

TEST(RunLoadStoreMap) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged, kMachineTagged);
  FieldAccess access = ForJSObjectMap();
  Node* load = t.LoadField(access, t.Parameter(0));
  t.StoreField(access, t.Parameter(1), load);
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSObject> src = TestObject();
  Handle<Map> src_map(src->map());
  Handle<JSObject> dst = TestObject();
  CHECK(src->map() != dst->map());
  Object* result = t.Call(*src, *dst);
  CHECK(result->IsMap());
  CHECK_EQ(*src_map, result);
  CHECK(*src_map == dst->map());
}

TEST(RunLoadStoreFixedArrayIndex) {
  SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
  ElementAccess access = ForFixedArrayElement();
  Node* load = t.LoadElement(access, t.Parameter(0), t.Int32Constant(0));
  t.StoreElement(access, t.Parameter(0), t.Int32Constant(1), load);
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<FixedArray> array = t.factory()->NewFixedArray(2);
  Handle<JSObject> src = TestObject();
  Handle<JSObject> dst = TestObject();
  array->set(0, *src);
  array->set(1, *dst);
  Object* result = t.Call(*array);
  CHECK_EQ(*src, result);
  CHECK_EQ(*src, array->get(0));
  CHECK_EQ(*src, array->get(1));
}

TEST(RunLoadStoreArrayBuffer) {
  SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged);
  const int index = 12;
  FieldAccess access = ForArrayBufferBackingStore();
  Node* backing_store = t.LoadField(access, t.Parameter(0));
  ElementAccess buffer_access = ForBackingStoreElement(kMachineWord8);
  Node* load =
      t.LoadElement(buffer_access, backing_store, t.Int32Constant(index));
  t.StoreElement(buffer_access, backing_store, t.Int32Constant(index + 1),
                 load);
  t.Return(load);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<JSArrayBuffer> array = t.factory()->NewJSArrayBuffer();
  const int array_length = 2 * index;
  Runtime::SetupArrayBufferAllocatingData(t.isolate(), array, array_length);
  uint8_t* data = reinterpret_cast<uint8_t*>(array->backing_store());
  for (int i = 0; i < array_length; i++) {
    data[i] = i;
  }
  int32_t result = t.Call(*array);
  CHECK_EQ(index, result);
  for (int i = 0; i < array_length; i++) {
    uint8_t expected = i;
    if (i == (index + 1)) expected = result;
    CHECK_EQ(data[i], expected);
  }
}

TEST(RunCopyFixedArray) {
  SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);

  const int kArraySize = 15;
  Node* one = t.Int32Constant(1);
  Node* index = t.Int32Constant(0);
  Node* limit = t.Int32Constant(kArraySize);
  t.environment()->Push(index);
  {
    LoopBuilder loop(&t);
    loop.BeginLoop();
    // Loop exit condition.
    index = t.environment()->Top();
    Node* condition = t.Int32LessThan(index, limit);
    loop.BreakUnless(condition);
    // src[index] = dst[index].
    index = t.environment()->Pop();
    ElementAccess access = ForFixedArrayElement();
    Node* src = t.Parameter(0);
    Node* load = t.LoadElement(access, src, index);
    Node* dst = t.Parameter(1);
    t.StoreElement(access, dst, index, load);
    // index++
    index = t.Int32Add(index, one);
    t.environment()->Push(index);
    // continue.
    loop.EndBody();
    loop.EndLoop();
  }
  index = t.environment()->Pop();
  t.Return(index);

  t.LowerAllNodes();

  if (!Pipeline::SupportedTarget()) return;

  Handle<FixedArray> src = t.factory()->NewFixedArray(kArraySize);
  Handle<FixedArray> src_copy = t.factory()->NewFixedArray(kArraySize);
  Handle<FixedArray> dst = t.factory()->NewFixedArray(kArraySize);
  for (int i = 0; i < kArraySize; i++) {
    src->set(i, *TestObject());
    src_copy->set(i, src->get(i));
    dst->set(i, *TestObject());
    CHECK_NE(src_copy->get(i), dst->get(i));
  }
  CHECK_EQ(kArraySize, t.Call(*src, *dst));
  for (int i = 0; i < kArraySize; i++) {
    CHECK_EQ(src_copy->get(i), dst->get(i));
  }
}

TEST(RunLoadFieldFromUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
    int offset = static_cast<int>(i * sizeof(Smi*));
    FieldAccess access = {kUntaggedBase, offset, Handle<Name>(),
                          Type::Integral32(), kMachineTagged};

    SimplifiedGraphBuilderTester<Object*> t;
    Node* load = t.LoadField(access, t.PointerConstant(smis));
    t.Return(load);
    t.LowerAllNodes();

    if (!Pipeline::SupportedTarget()) continue;

    for (int j = -5; j <= 5; j++) {
      Smi* expected = Smi::FromInt(j);
      smis[i] = expected;
      CHECK_EQ(expected, t.Call());
    }
  }
}

TEST(RunStoreFieldToUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
    int offset = static_cast<int>(i * sizeof(Smi*));
    FieldAccess access = {kUntaggedBase, offset, Handle<Name>(),
                          Type::Integral32(), kMachineTagged};

    SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
    Node* p0 = t.Parameter(0);
    t.StoreField(access, t.PointerConstant(smis), p0);
    t.Return(p0);
    t.LowerAllNodes();

    if (!Pipeline::SupportedTarget()) continue;

    for (int j = -5; j <= 5; j++) {
      Smi* expected = Smi::FromInt(j);
      smis[i] = Smi::FromInt(-100);
      CHECK_EQ(expected, t.Call(expected));
      CHECK_EQ(expected, smis[i]);
    }
  }
}

TEST(RunLoadElementFromUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
                 Smi::FromInt(4), Smi::FromInt(5)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {    // for header sizes
    for (size_t j = 0; (i + j) < ARRAY_SIZE(smis); j++) {  // for element index
      int offset = static_cast<int>(i * sizeof(Smi*));
      ElementAccess access = {kUntaggedBase, offset, Type::Integral32(),
                              kMachineTagged};

      SimplifiedGraphBuilderTester<Object*> t;
      Node* load = t.LoadElement(access, t.PointerConstant(smis),
                                 t.Int32Constant(static_cast<int>(j)));
      t.Return(load);
      t.LowerAllNodes();

      if (!Pipeline::SupportedTarget()) continue;

      for (int k = -5; k <= 5; k++) {
        Smi* expected = Smi::FromInt(k);
        smis[i + j] = expected;
        CHECK_EQ(expected, t.Call());
      }
    }
  }
}

TEST(RunStoreElementFromUntaggedBase) {
  Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
                 Smi::FromInt(4), Smi::FromInt(5)};

  for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {    // for header sizes
    for (size_t j = 0; (i + j) < ARRAY_SIZE(smis); j++) {  // for element index
      int offset = static_cast<int>(i * sizeof(Smi*));
      ElementAccess access = {kUntaggedBase, offset, Type::Integral32(),
                              kMachineTagged};

      SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
      Node* p0 = t.Parameter(0);
      t.StoreElement(access, t.PointerConstant(smis),
                     t.Int32Constant(static_cast<int>(j)), p0);
      t.Return(p0);
      t.LowerAllNodes();

      if (!Pipeline::SupportedTarget()) continue;

      for (int k = -5; k <= 5; k++) {
        Smi* expected = Smi::FromInt(k);
        smis[i + j] = Smi::FromInt(-100);
        CHECK_EQ(expected, t.Call(expected));
        CHECK_EQ(expected, smis[i + j]);
      }

      // TODO(titzer): assert the contents of the array.
    }
  }
}
<|endoftext|>


<commit_before>#include "YarpLocalImageManager.hpp"

#include <sstream>

#include <yarp/os/Network.h>
#include <yarp/os/Property.h>

#include "Macros.hpp"

//-- Initialize static members
rd::YarpLocalImageManager * rd::YarpLocalImageManager::uniqueInstance = NULL;
const std::string rd::YarpLocalImageManager::id = "YARPlocal";

bool rd::YarpLocalImageManager::start()
{
    yarp::os::Network::init();

    yarp::os::Property cameraOptions;
    cameraOptions.put("device","grabber");
    cameraOptions.put("subdevice","opencv_grabber");
    cameraOptions.put("name",remote_port_name);
    RD_DEBUG("Camera id: %d\n", camera_id);
    cameraOptions.put("camera", camera_id);
    cameraDevice.open(cameraOptions);
    if(!cameraDevice.isValid())
    {
        RD_ERROR("Could not open opencv_grabber device.\n");
        return false;
    }
    RD_SUCCESS("Opened opencv_grabber device.\n");

    imagePort.open(local_port_name.c_str());
    imagePort.useCallback(*this);

    if(! yarp::os::Network::connect( remote_port_name.c_str(), local_port_name.c_str(), "mjpeg" ) )
    {
        RD_WARNING("Could not connect to robot camera via mjpeg.\n");
        if (!yarp::os::Network::connect(remote_port_name.c_str(), local_port_name.c_str()))
        {
            RD_WARNING("Could not connect to robot camera.\n");
            return false;
        }
    }

    RD_SUCCESS("Connected to robot camera.\n");

    stopped = false;
    enabled = false;
    return true;

}

bool rd::YarpLocalImageManager::stop()
{
    imagePort.disableCallback();
    imagePort.interrupt();
    imagePort.close();

    cameraDevice.close();

    stopped = true;
    enabled = false;

    return true;
}

bool rd::YarpLocalImageManager::isStopped() const
{
    return stopped;
}

bool rd::YarpLocalImageManager::setEnabled(bool enabled)
{
    this->enabled = enabled;
    return true;
}

bool rd::YarpLocalImageManager::configure(const std::string & parameter, const std::string & value)
{
    if ( parameter.compare("remote_img_port") == 0 && value.compare("") != 0)
    {
        remote_port_name = value;
        return true;
    }
    else if ( parameter.compare("local_img_port") == 0 && value.compare("") != 0)
    {
        local_port_name = value;
        return true;
    }
    else if (parameter.compare("camera_id") == 0)
    {
        std::stringstream ss(value);
        ss >> camera_id;
        return true;
    }
    else
        return ImageManager::configure(parameter, value);
}

rd::Image rd::YarpLocalImageManager::getImage() const
{
    semaphore.wait();
    Image return_image = image;
    semaphore.post();

    return return_image;
}

bool rd::YarpLocalImageManager::RegisterManager()
{
    if (uniqueInstance == NULL)
    {
        uniqueInstance = new YarpLocalImageManager();
    }

    return Register( uniqueInstance, id);
}

rd::YarpLocalImageManager::~YarpLocalImageManager()
{
    uniqueInstance = NULL;
}

void rd::YarpLocalImageManager::onRead(Image &image)
{
    semaphore.wait();
    this->image=image;
    semaphore.post();

    //-- Notify listeners
    if (enabled)
    {
        for (std::vector<ImageEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it)
        {
            (*it)->onImageArrived(this);
        }
    }
    else
    {
        RD_WARNING("YarpImageManager is disabled!\n");
    }
}

rd::YarpLocalImageManager::YarpLocalImageManager()
{
    stopped = true;
    enabled = false;
    camera_id = -1;
}
<commit_msg>Set default camera_id to '0' (as CV_CAP_ANY)<commit_after>#include "YarpLocalImageManager.hpp"

#include <sstream>

#include <yarp/os/Network.h>
#include <yarp/os/Property.h>

#include "Macros.hpp"

//-- Initialize static members
rd::YarpLocalImageManager * rd::YarpLocalImageManager::uniqueInstance = NULL;
const std::string rd::YarpLocalImageManager::id = "YARPlocal";

bool rd::YarpLocalImageManager::start()
{
    yarp::os::Network::init();

    yarp::os::Property cameraOptions;
    cameraOptions.put("device","grabber");
    cameraOptions.put("subdevice","opencv_grabber");
    cameraOptions.put("name",remote_port_name);
    RD_DEBUG("Camera id: %d\n", camera_id);
    cameraOptions.put("camera", camera_id);
    cameraDevice.open(cameraOptions);
    if(!cameraDevice.isValid())
    {
        RD_ERROR("Could not open opencv_grabber device.\n");
        return false;
    }
    RD_SUCCESS("Opened opencv_grabber device.\n");

    imagePort.open(local_port_name.c_str());
    imagePort.useCallback(*this);

    if(! yarp::os::Network::connect( remote_port_name.c_str(), local_port_name.c_str(), "mjpeg" ) )
    {
        RD_WARNING("Could not connect to robot camera via mjpeg.\n");
        if (!yarp::os::Network::connect(remote_port_name.c_str(), local_port_name.c_str()))
        {
            RD_WARNING("Could not connect to robot camera.\n");
            return false;
        }
    }

    RD_SUCCESS("Connected to robot camera.\n");

    stopped = false;
    enabled = false;
    return true;

}

bool rd::YarpLocalImageManager::stop()
{
    imagePort.disableCallback();
    imagePort.interrupt();
    imagePort.close();

    cameraDevice.close();

    stopped = true;
    enabled = false;

    return true;
}

bool rd::YarpLocalImageManager::isStopped() const
{
    return stopped;
}

bool rd::YarpLocalImageManager::setEnabled(bool enabled)
{
    this->enabled = enabled;
    return true;
}

bool rd::YarpLocalImageManager::configure(const std::string & parameter, const std::string & value)
{
    if ( parameter.compare("remote_img_port") == 0 && value.compare("") != 0)
    {
        remote_port_name = value;
        return true;
    }
    else if ( parameter.compare("local_img_port") == 0 && value.compare("") != 0)
    {
        local_port_name = value;
        return true;
    }
    else if (parameter.compare("camera_id") == 0)
    {
        std::stringstream ss(value);
        ss >> camera_id;
        return true;
    }
    else
        return ImageManager::configure(parameter, value);
}

rd::Image rd::YarpLocalImageManager::getImage() const
{
    semaphore.wait();
    Image return_image = image;
    semaphore.post();

    return return_image;
}

bool rd::YarpLocalImageManager::RegisterManager()
{
    if (uniqueInstance == NULL)
    {
        uniqueInstance = new YarpLocalImageManager();
    }

    return Register( uniqueInstance, id);
}

rd::YarpLocalImageManager::~YarpLocalImageManager()
{
    uniqueInstance = NULL;
}

void rd::YarpLocalImageManager::onRead(Image &image)
{
    semaphore.wait();
    this->image=image;
    semaphore.post();
    //-- Notify listeners
    if (enabled)
    {
        for (std::vector<ImageEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it)
        {
            (*it)->onImageArrived(this);
        }
    }
    else
    {
        RD_WARNING("YarpImageManager is disabled!\n");
    }
}

rd::YarpLocalImageManager::YarpLocalImageManager()
{
    stopped = true;
    enabled = false;
    camera_id = 0; // see OpenCV C API: CV_CAP_ANY
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QLibraryInfo>
#include <QDir>
#include <QProcess>
#include <QDebug>

#define CONCURRENT

#ifdef CONCURRENT
#include <QFutureSynchronizer>
#include <QtConcurrentRun>
#endif

class tst_examples : public QObject
{
    Q_OBJECT
public:
    tst_examples();

private slots:
#ifndef CONCURRENT
    void examples_data();
#endif
    void examples();

    void namingConvention();
private:
    QString qmlruntime;
    QStringList excludedDirs;

    void namingConvention(const QDir &);
    QStringList findQmlFiles(const QDir &);
};

tst_examples::tst_examples()
{
    QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath);

#if defined(Q_WS_MAC)
    qmlruntime = QDir(binaries).absoluteFilePath("qml.app/Contents/MacOS/qml");
#elif defined(Q_WS_WIN)
    qmlruntime = QDir(binaries).absoluteFilePath("qml.exe");
#else
    qmlruntime = QDir(binaries).absoluteFilePath("qml");
#endif

    // Add directories you want excluded here
    excludedDirs << "examples/declarative/extending";
    excludedDirs << "examples/declarative/plugins";
    excludedDirs << "examples/declarative/proxywidgets";
    excludedDirs << "examples/declarative/gestures";

#ifdef QT_NO_WEBKIT
    excludedDirs << "examples/declarative/webview";
    excludedDirs << "demos/declarative/webbrowser";
#endif

#ifdef QT_NO_XMLPATTERNS
    excludedDirs << "examples/declarative/xmldata";
    excludedDirs << "demos/declarative/twitter";
    excludedDirs << "demos/declarative/flickr";
    excludedDirs << "demos/declarative/photoviewer";
#endif
}

/*
This tests that the demos and examples follow the naming convention required
to have them tested by the examples() test.
*/
void tst_examples::namingConvention(const QDir &d)
{
    for (int ii = 0; ii < excludedDirs.count(); ++ii) {
        QString s = excludedDirs.at(ii);
        if (d.absolutePath().endsWith(s))
            return;
    }

    QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
                                    QDir::Files);

    bool seenQml = !files.isEmpty();
    bool seenLowercase = false;

    foreach (const QString &file, files) {
        if (file.at(0).isLower())
            seenLowercase = true;
    }

    if (!seenQml) {
        QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
                QDir::NoSymLinks);
        foreach (const QString &dir, dirs) {
            QDir sub = d;
            sub.cd(dir);
            namingConvention(sub);
        }
    } else if(!seenLowercase) {
        QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__);
    }
}

void tst_examples::namingConvention()
{
    QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath);
    QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath);

    namingConvention(QDir(examples));
    namingConvention(QDir(demos));
}

QStringList tst_examples::findQmlFiles(const QDir &d)
{
    for (int ii = 0; ii < excludedDirs.count(); ++ii) {
        QString s = excludedDirs.at(ii);
        if (d.absolutePath().endsWith(s))
            return QStringList();
    }

    QStringList rv;

    QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
                                    QDir::Files);
    foreach (const QString &file, files) {
        if (file.at(0).isLower()) {
            rv << d.absoluteFilePath(file);
        }
    }

    QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
                                   QDir::NoSymLinks);
    foreach (const QString &dir, dirs) {
        QDir sub = d;
        sub.cd(dir);
        rv << findQmlFiles(sub);
    }

    return rv;
}

/*
This test runs all the examples in the declarative UI source tree and ensures
that they start and exit cleanly.

Examples are any .qml files under the examples/ or demos/ directory that start
with a lower case letter.
*/
#ifndef CONCURRENT
void tst_examples::examples_data()
{
    QTest::addColumn<QString>("file");

    QString examples = QLatin1String(SRCDIR) + "/../../../../demos/declarative/";
    QString demos = QLatin1String(SRCDIR) + "/../../../../examples/declarative/";
    QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/";

    qWarning() << examples << demos << snippets;

    QStringList files;
    files << findQmlFiles(QDir(examples));
    files << findQmlFiles(QDir(demos));
    files << findQmlFiles(QDir(snippets));

    qWarning() << files;

    foreach (const QString &file, files)
        QTest::newRow(file.toLatin1().constData()) << file;
}
#endif

#ifdef CONCURRENT
#define THREADS 5

struct Example {
public:
    Example() : result(Unknown) {}

    enum Result { Pass, Unknown, Fail };
    Result result;
    QString file;
    QString qmlruntime;

    void run();
};

void Example::run()
{
    QFileInfo fi(file);
    QFileInfo dir(fi.path());
    QString script = SRCDIR "/data/"+dir.baseName()+"/"+fi.baseName();
    QFileInfo testdata(script+".qml");
    QStringList arguments;
    arguments << "-script" << (testdata.exists() ? script : QLatin1String(SRCDIR "/data/dummytest"))
              << "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure"
              << file;
#ifdef Q_WS_QWS
    arguments << "-qws";
#endif

    QProcess p;
    p.start(qmlruntime, arguments);
    if (!p.waitForFinished()) {
        result = Fail;
        return;
    }

    if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0)
        qWarning() << p.readAllStandardOutput() << p.readAllStandardError();

    if (p.exitStatus() != QProcess::NormalExit ||
        p.exitCode() != 0) {
        result = Fail;
        return;
    } else {
        result = Pass;
        return;
    }
}

#endif
void tst_examples::examples()
{
#ifdef CONCURRENT
    QThreadPool::globalInstance()->setMaxThreadCount(5);

    QString examples = QLatin1String(SRCDIR) + "/../../../../demos/declarative/";
    QString demos = QLatin1String(SRCDIR) + "/../../../../examples/declarative/";
    QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/";

    QStringList files;
    files << findQmlFiles(QDir(examples));
    files << findQmlFiles(QDir(demos));
    files << findQmlFiles(QDir(snippets));

    QList<Example> tests;

    for (int ii = 0; ii < files.count(); ++ii) {
        Example e;
        e.file = files.at(ii);
        e.qmlruntime = qmlruntime;
        tests << e;
    }

    QFutureSynchronizer<void> sync;

    for (int ii = 0; ii < tests.count(); ++ii) {
        Example *e = &tests[ii];
        QFuture<void> r = QtConcurrent::run(e, &Example::run);
        sync.addFuture(r);
    }

    sync.waitForFinished();

    for (int ii = 0; ii < tests.count(); ++ii) {
        if (tests.at(ii).result != Example::Pass)
            qWarning() << tests.at(ii).file << ":failed";
        if (tests.at(ii).result != Example::Pass)
            QFAIL(qPrintable(tests.at(ii).file));
    }

#else

    QFETCH(QString, file);

    QFileInfo fi(file);
    QFileInfo dir(fi.path());
    QString script = SRCDIR "/data/"+dir.baseName()+"/"+fi.baseName();
    QFileInfo testdata(script+".qml");
    QStringList arguments;
    arguments << "-script" << (testdata.exists() ? script : QLatin1String(SRCDIR "/data/dummytest"))
              << "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure"
              << file;
#ifdef Q_WS_QWS
    arguments << "-qws";
#endif

    QProcess p;
    p.start(qmlruntime, arguments);
    QVERIFY(p.waitForFinished());
    if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0)
        qWarning() << p.readAllStandardOutput() << p.readAllStandardError();
    QCOMPARE(p.exitStatus(), QProcess::NormalExit);
    QCOMPARE(p.exitCode(), 0);
#endif
}

QTEST_MAIN(tst_examples)

#include "tst_examples.moc"
<commit_msg>Remove double fail message<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QLibraryInfo>
#include <QDir>
#include <QProcess>
#include <QDebug>

#define CONCURRENT

#ifdef CONCURRENT
#include <QFutureSynchronizer>
#include <QtConcurrentRun>
#endif

class tst_examples : public QObject
{
    Q_OBJECT
public:
    tst_examples();

private slots:
#ifndef CONCURRENT
    void examples_data();
#endif
    void examples();

    void namingConvention();
private:
    QString qmlruntime;
    QStringList excludedDirs;

    void namingConvention(const QDir &);
    QStringList findQmlFiles(const QDir &);
};

tst_examples::tst_examples()
{
    QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath);

#if defined(Q_WS_MAC)
    qmlruntime = QDir(binaries).absoluteFilePath("qml.app/Contents/MacOS/qml");
#elif defined(Q_WS_WIN)
    qmlruntime = QDir(binaries).absoluteFilePath("qml.exe");
#else
    qmlruntime = QDir(binaries).absoluteFilePath("qml");
#endif

    // Add directories you want excluded here
    excludedDirs << "examples/declarative/extending";
    excludedDirs << "examples/declarative/plugins";
    excludedDirs << "examples/declarative/proxywidgets";
    excludedDirs << "examples/declarative/gestures";

#ifdef QT_NO_WEBKIT
    excludedDirs << "examples/declarative/webview";
    excludedDirs << "demos/declarative/webbrowser";
#endif

#ifdef QT_NO_XMLPATTERNS
    excludedDirs << "examples/declarative/xmldata";
    excludedDirs << "demos/declarative/twitter";
    excludedDirs << "demos/declarative/flickr";
    excludedDirs << "demos/declarative/photoviewer";
#endif
}

/*
This tests that the demos and examples follow the naming convention required
to have them tested by the examples() test.
*/
void tst_examples::namingConvention(const QDir &d)
{
    for (int ii = 0; ii < excludedDirs.count(); ++ii) {
        QString s = excludedDirs.at(ii);
        if (d.absolutePath().endsWith(s))
            return;
    }

    QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
                                    QDir::Files);

    bool seenQml = !files.isEmpty();
    bool seenLowercase = false;

    foreach (const QString &file, files) {
        if (file.at(0).isLower())
            seenLowercase = true;
    }

    if (!seenQml) {
        QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
                QDir::NoSymLinks);
        foreach (const QString &dir, dirs) {
            QDir sub = d;
            sub.cd(dir);
            namingConvention(sub);
        }
    } else if(!seenLowercase) {
        QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__);
    }
}

void tst_examples::namingConvention()
{
    QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath);
    QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath);

    namingConvention(QDir(examples));
    namingConvention(QDir(demos));
}

QStringList tst_examples::findQmlFiles(const QDir &d)
{
    for (int ii = 0; ii < excludedDirs.count(); ++ii) {
        QString s = excludedDirs.at(ii);
        if (d.absolutePath().endsWith(s))
            return QStringList();
    }

    QStringList rv;

    QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
                                    QDir::Files);
    foreach (const QString &file, files) {
        if (file.at(0).isLower()) {
            rv << d.absoluteFilePath(file);
        }
    }

    QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
                                   QDir::NoSymLinks);
    foreach (const QString &dir, dirs) {
        QDir sub = d;
        sub.cd(dir);
        rv << findQmlFiles(sub);
    }

    return rv;
}

/*
This test runs all the examples in the declarative UI source tree and ensures
that they start and exit cleanly.

Examples are any .qml files under the examples/ or demos/ directory that start
with a lower case letter.
*/
#ifndef CONCURRENT
void tst_examples::examples_data()
{
    QTest::addColumn<QString>("file");

    QString examples = QLatin1String(SRCDIR) + "/../../../../demos/declarative/";
    QString demos = QLatin1String(SRCDIR) + "/../../../../examples/declarative/";
    QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/";

    qWarning() << examples << demos << snippets;

    QStringList files;
    files << findQmlFiles(QDir(examples));
    files << findQmlFiles(QDir(demos));
    files << findQmlFiles(QDir(snippets));

    qWarning() << files;

    foreach (const QString &file, files)
        QTest::newRow(file.toLatin1().constData()) << file;
}
#endif

#ifdef CONCURRENT
#define THREADS 5

struct Example {
public:
    Example() : result(Unknown) {}

    enum Result { Pass, Unknown, Fail };
    Result result;
    QString file;
    QString qmlruntime;

    void run();
};

void Example::run()
{
    QFileInfo fi(file);
    QFileInfo dir(fi.path());
    QString script = SRCDIR "/data/"+dir.baseName()+"/"+fi.baseName();
    QFileInfo testdata(script+".qml");
    QStringList arguments;
    arguments << "-script" << (testdata.exists() ? script : QLatin1String(SRCDIR "/data/dummytest"))
              << "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure"
              << file;
#ifdef Q_WS_QWS
    arguments << "-qws";
#endif

    QProcess p;
    p.start(qmlruntime, arguments);
    if (!p.waitForFinished()) {
        result = Fail;
        return;
    }

    if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0)
        qWarning() << p.readAllStandardOutput() << p.readAllStandardError();

    if (p.exitStatus() != QProcess::NormalExit ||
        p.exitCode() != 0) {
        result = Fail;
        return;
    } else {
        result = Pass;
        return;
    }
}

#endif
void tst_examples::examples()
{
#ifdef CONCURRENT
    QThreadPool::globalInstance()->setMaxThreadCount(5);

    QString examples = QLatin1String(SRCDIR) + "/../../../../demos/declarative/";
    QString demos = QLatin1String(SRCDIR) + "/../../../../examples/declarative/";
    QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/";

    QStringList files;
    files << findQmlFiles(QDir(examples));
    files << findQmlFiles(QDir(demos));
    files << findQmlFiles(QDir(snippets));

    QList<Example> tests;

    for (int ii = 0; ii < files.count(); ++ii) {
        Example e;
        e.file = files.at(ii);
        e.qmlruntime = qmlruntime;
        tests << e;
    }

    QFutureSynchronizer<void> sync;

    for (int ii = 0; ii < tests.count(); ++ii) {
        Example *e = &tests[ii];
        QFuture<void> r = QtConcurrent::run(e, &Example::run);
        sync.addFuture(r);
    }

    sync.waitForFinished();

    for (int ii = 0; ii < tests.count(); ++ii) {
        if (tests.at(ii).result != Example::Pass)
            QFAIL(qPrintable(tests.at(ii).file));
    }

#else

    QFETCH(QString, file);

    QFileInfo fi(file);
    QFileInfo dir(fi.path());
    QString script = SRCDIR "/data/"+dir.baseName()+"/"+fi.baseName();
    QFileInfo testdata(script+".qml");
    QStringList arguments;
    arguments << "-script" << (testdata.exists() ? script : QLatin1String(SRCDIR "/data/dummytest"))
              << "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure"
              << file;
#ifdef Q_WS_QWS
    arguments << "-qws";
#endif

    QProcess p;
    p.start(qmlruntime, arguments);
    QVERIFY(p.waitForFinished());
    if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0)
        qWarning() << p.readAllStandardOutput() << p.readAllStandardError();
    QCOMPARE(p.exitStatus(), QProcess::NormalExit);
    QCOMPARE(p.exitCode(), 0);
#endif
}

QTEST_MAIN(tst_examples)

#include "tst_examples.moc"
<|endoftext|>