<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CmsTemplateTest.h"
#include <integration/IntegrationCommon.h>

#include <decaf/lang/Thread.h>
#include <activemq/connector/stomp/StompConnector.h>
#include <decaf/util/Properties.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/util/UUID.h>
#include <decaf/util/Properties.h>
#include <decaf/util/StringTokenizer.h>
#include <activemq/connector/ConnectorFactoryMap.h>
#include <decaf/net/SocketFactory.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/net/Socket.h>
#include <decaf/lang/exceptions/NullPointerException.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQConsumer.h>
#include <activemq/core/ActiveMQProducer.h>
#include <decaf/util/StringTokenizer.h>
#include <decaf/lang/Boolean.h>

#include <cms/Connection.h>
#include <cms/MessageConsumer.h>
#include <cms/MessageProducer.h>
#include <cms/MessageListener.h>
#include <cms/Startable.h>
#include <cms/Closeable.h>
#include <cms/MessageListener.h>
#include <cms/ExceptionListener.h>
#include <cms/Topic.h>
#include <cms/Queue.h>
#include <cms/TemporaryTopic.h>
#include <cms/TemporaryQueue.h>
#include <cms/Session.h>
#include <cms/BytesMessage.h>
#include <cms/TextMessage.h>
#include <cms/MapMessage.h>

using namespace activemq::connector::stomp;
using namespace activemq::transport;
using namespace activemq::util;
using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::util;
using namespace activemq::connector;
using namespace activemq::exceptions;
using namespace decaf::net;
using namespace activemq::transport;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
using namespace decaf::util;

using namespace integration;
using namespace integration::connector::stomp;
using namespace activemq::cmsutil;

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::setUp() {
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::tearDown() {
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testBasics()
{
    try {

        Receiver receiver( IntegrationCommon::getInstance().getStompURL(),
                false,
                "test",
                IntegrationCommon::defaultMsgCount);
        Thread rt(&receiver);
        rt.start();

        Sender sender( IntegrationCommon::getInstance().getStompURL(),
                false,
                "test",
                IntegrationCommon::defaultMsgCount);
        Thread st(&sender);
        st.start();

        st.join();
        rt.join();

        unsigned int numReceived = receiver.getNumReceived();
        if( IntegrationCommon::debug ) {
            printf("received: %d\n", numReceived );
        }
        CPPUNIT_ASSERT(
            numReceived == IntegrationCommon::defaultMsgCount );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testReceiveException()
{
    try {

        activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
        activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
        cmsTemplate.setDefaultDestinationName("hello");
        cmsTemplate.init();

        cmsTemplate.receive();
        CPPUNIT_FAIL("failed to throw expected exception");
    }
    catch( ActiveMQException& ex) {
        // Expected.
    }
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testSendException()
{
    try {

        activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
        activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
        cmsTemplate.setDefaultDestinationName("hello");
        cmsTemplate.init();

        TextMessageCreator msgCreator("hello world");
        cmsTemplate.send(&msgCreator);
        CPPUNIT_FAIL("failed to throw expected exception");
    }
    catch( ActiveMQException& ex) {
        // Expected.
    }
}
<commit_msg>AMQCPP-152 - Adding integ tests for CmsTemplate<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CmsTemplateTest.h"
#include <integration/IntegrationCommon.h>

#include <decaf/lang/Thread.h>
#include <activemq/connector/stomp/StompConnector.h>
#include <decaf/util/Properties.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/util/UUID.h>
#include <decaf/util/Properties.h>
#include <decaf/util/StringTokenizer.h>
#include <activemq/connector/ConnectorFactoryMap.h>
#include <decaf/net/SocketFactory.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/net/Socket.h>
#include <decaf/lang/exceptions/NullPointerException.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQConsumer.h>
#include <activemq/core/ActiveMQProducer.h>
#include <decaf/util/StringTokenizer.h>
#include <decaf/lang/Boolean.h>

#include <cms/Connection.h>
#include <cms/MessageConsumer.h>
#include <cms/MessageProducer.h>
#include <cms/MessageListener.h>
#include <cms/Startable.h>
#include <cms/Closeable.h>
#include <cms/MessageListener.h>
#include <cms/ExceptionListener.h>
#include <cms/Topic.h>
#include <cms/Queue.h>
#include <cms/TemporaryTopic.h>
#include <cms/TemporaryQueue.h>
#include <cms/Session.h>
#include <cms/BytesMessage.h>
#include <cms/TextMessage.h>
#include <cms/MapMessage.h>

using namespace activemq::connector::stomp;
using namespace activemq::transport;
using namespace activemq::util;
using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::util;
using namespace activemq::connector;
using namespace activemq::exceptions;
using namespace decaf::net;
using namespace activemq::transport;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
using namespace decaf::util;

using namespace integration;
using namespace integration::connector::stomp;
using namespace activemq::cmsutil;

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::setUp() {
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::tearDown() {
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testBasics()
{
    try {

        Receiver receiver( IntegrationCommon::getInstance().getStompURL(),
                false,
                "test",
                IntegrationCommon::defaultMsgCount);
        Thread rt(&receiver);
        rt.start();

        Sender sender( IntegrationCommon::getInstance().getStompURL(),
                false,
                "test",
                IntegrationCommon::defaultMsgCount);
        Thread st(&sender);
        st.start();

        st.join();
        rt.join();

        unsigned int numReceived = receiver.getNumReceived();
        if( IntegrationCommon::debug ) {
            printf("received: %d\n", numReceived );
        }
        CPPUNIT_ASSERT(
            numReceived == IntegrationCommon::defaultMsgCount );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testReceiveException()
{
    // First, try receiving from a bad url
    activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
    activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
    cmsTemplate.setDefaultDestinationName("hello");
    cmsTemplate.init();
    try {
        cmsTemplate.receive();
        CPPUNIT_FAIL("failed to throw expected exception");
    }
    catch( ActiveMQException& ex) {
        // Expected.
    }

    // Now change to a good url and verify that we can reuse the same
    // CmsTemplate successfully.
    activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getStompURL());
    cmsTemplate.setConnectionFactory(&cf2);

    // Send 1 message.
    Sender sender( IntegrationCommon::getInstance().getStompURL(),
            false,
            "hello",
            1);
    Thread st(&sender);
    st.start();

    // Receive the message.
    cms::Message* message = cmsTemplate.receive();
    CPPUNIT_ASSERT(message != NULL);
    delete message;
}

////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testSendException()
{
    // First, try sending to a bad url.
    activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
    activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
    cmsTemplate.setDefaultDestinationName("hello");
    cmsTemplate.init();
    try {
        TextMessageCreator msgCreator("hello world");
        cmsTemplate.send(&msgCreator);
        CPPUNIT_FAIL("failed to throw expected exception");
    }
    catch( ActiveMQException& ex) {
        // Expected.
    }

    // Now change to a good url and verify that we can reuse the same
    // CmsTemplate successfully.
    activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getStompURL());
    cmsTemplate.setConnectionFactory(&cf2);
    TextMessageCreator msgCreator("hello world");
    cmsTemplate.send(&msgCreator);
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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 "bump_user.h"

#include <fclaw2d_include_all.h>

#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch.h>

#include <fc2d_clawpack46_options.h>
#include <fc2d_clawpack5_options.h>
#include <fc2d_cudaclaw_options.h>

#include <fc2d_clawpack46.h>
#include <fc2d_clawpack5.h>

#include <fc2d_cudaclaw.h>
#include <fc2d_cuda_profiler.h>

static
fclaw2d_domain_t* create_domain(sc_MPI_Comm mpicomm,
                                fclaw_options_t* fclaw_opt,
                                user_options_t* user)
{
    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t         *domain;
    fclaw2d_map_context_t    *cont = NULL;

    switch (user->example)
    {
    case 0:
        /* Use [ax,bx]x[ay,by] */
        conn = p4est_connectivity_new_unitsquare();
        cont = fclaw2d_map_new_nomap();
        break;
    case 1:
        printf("Warning : Five patch square not tested.");
        exit(0);
        conn = p4est_connectivity_new_unitsquare();
        cont = fclaw2d_map_new_fivepatch(fclaw_opt->scale,user->alpha);
        break;
    default:
        SC_ABORT_NOT_REACHED ();
    }

    domain = fclaw2d_domain_new_conn_map (mpicomm, fclaw_opt->minlevel, conn, cont);
    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
    return domain;
}

static
void run_program(fclaw2d_global_t* glob)
{
    /* ---------------------------------------------------------------
       Set domain data.
       --------------------------------------------------------------- */
    fclaw2d_domain_data_new(glob->domain);

    user_options_t* user_opt = bump_get_options(glob);

    /* Initialize virtual table for ForestClaw */
    fclaw2d_vtables_initialize(glob);

    /* Initialize virtual tables for solvers */
    if(user_opt->cuda)
    {
        fc2d_cudaclaw_options_t *clawopt = fc2d_cudaclaw_get_options(glob);

        fc2d_cudaclaw_initialize_GPUs(glob);

        /* this has to be done after GPUs have been initialized */
        cudaclaw_set_method_parameters(clawopt->order, clawopt->mthlim, clawopt->mwaves);
        fc2d_cudaclaw_solver_initialize();
    }
    else
    {
        if (user_opt->claw_version == 4)
        {
            fc2d_clawpack46_solver_initialize();
        }
        else if (user_opt->claw_version == 5)
        {
            fc2d_clawpack5_solver_initialize();
        }
    }

    bump_link_solvers(glob);

    /* ---------------------------------------------------------------
       Run
       --------------------------------------------------------------- */

    if (user_opt->cuda == 1)
    {
        PROFILE_CUDA_GROUP("Allocate GPU and GPU buffers",1);
        fc2d_cudaclaw_allocate_buffers(glob);
    }

    fclaw2d_initialize(glob);
    fclaw2d_run(glob);

    if (user_opt->cuda == 1)
    {
        PROFILE_CUDA_GROUP("De-allocate GPU and GPU buffers",1);
        fc2d_cudaclaw_deallocate_buffers(glob);
    }

    fclaw2d_finalize(glob);
}

int
main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t                *options;
    user_options_t              *user_opt;
    fclaw_options_t             *fclaw_opt;
    fclaw2d_clawpatch_options_t *clawpatch_opt;
    fc2d_clawpack46_options_t   *claw46_opt;
    fc2d_clawpack5_options_t    *claw5_opt;
    fc2d_cudaclaw_options_t     *cuclaw5_opt;

    fclaw2d_global_t            *glob;
    fclaw2d_domain_t            *domain;
    sc_MPI_Comm mpicomm;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, NULL);

    /* Create new options packages */
    fclaw_opt =                   fclaw_options_register(app,"fclaw_options.ini");
    clawpatch_opt =   fclaw2d_clawpatch_options_register(app,"fclaw_options.ini");
    claw46_opt =        fc2d_clawpack46_options_register(app,"fclaw_options.ini");
    claw5_opt =          fc2d_clawpack5_options_register(app,"fclaw_options.ini");
    cuclaw_opt =          fc2d_cudaclaw_options_register(app,"fclaw_options.ini");
    user_opt =                bump_options_register(app,"fclaw_options.ini");

    /* Read configuration file(s) and command line, and process options */
    options = fclaw_app_get_options (app);
    retval = fclaw_options_read_from_file(options);
    vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    /* Run the program */
    if (!retval & !vexit)
    {
        /* Options have been checked and are valid */

        mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
        domain = create_domain(mpicomm, fclaw_opt,user_opt);

        /* Create global structure which stores the domain, timers, etc */
        glob = fclaw2d_global_new();
        fclaw2d_global_store_domain(glob, domain);

        /* Store option packages in glob */
        fclaw2d_options_store           (glob, fclaw_opt);
        fclaw2d_clawpatch_options_store (glob, clawpatch_opt);
        fc2d_clawpack46_options_store   (glob, claw46_opt);
        fc2d_clawpack5_options_store    (glob, claw5_opt);
        fc2d_cudaclaw_options_store     (glob, cuclaw_opt);
        bump_options_store              (glob, user_opt);

        run_program(glob);

        fclaw2d_global_destroy(glob);
    }

    fclaw_app_destroy (app);

    return 0;
}

<commit_msg>(cuda/bump) Fix call to method_parameter<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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 "bump_user.h"

#include <fclaw2d_include_all.h>

#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch.h>

#include <fc2d_clawpack46_options.h>
#include <fc2d_clawpack5_options.h>
#include <fc2d_cudaclaw_options.h>

#include <fc2d_clawpack46.h>
#include <fc2d_clawpack5.h>

#include <fc2d_cudaclaw.h>
#include <fc2d_cuda_profiler.h>

static
fclaw2d_domain_t* create_domain(sc_MPI_Comm mpicomm,
                                fclaw_options_t* fclaw_opt,
                                user_options_t* user)
{
    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t         *domain;
    fclaw2d_map_context_t    *cont = NULL;

    switch (user->example)
    {
    case 0:
        /* Use [ax,bx]x[ay,by] */
        conn = p4est_connectivity_new_unitsquare();
        cont = fclaw2d_map_new_nomap();
        break;
    case 1:
        printf("Warning : Five patch square not tested.");
        exit(0);
        conn = p4est_connectivity_new_unitsquare();
        cont = fclaw2d_map_new_fivepatch(fclaw_opt->scale,user->alpha);
        break;
    default:
        SC_ABORT_NOT_REACHED ();
    }

    domain = fclaw2d_domain_new_conn_map (mpicomm, fclaw_opt->minlevel, conn, cont);
    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
    return domain;
}

static
void run_program(fclaw2d_global_t* glob)
{
    /* ---------------------------------------------------------------
       Set domain data.
       --------------------------------------------------------------- */
    fclaw2d_domain_data_new(glob->domain);

    user_options_t* user_opt = bump_get_options(glob);

    /* Initialize virtual table for ForestClaw */
    fclaw2d_vtables_initialize(glob);

    /* Initialize virtual tables for solvers */
    if(user_opt->cuda)
    {
        fc2d_cudaclaw_options_t *clawopt = fc2d_cudaclaw_get_options(glob);

        fc2d_cudaclaw_initialize_GPUs(glob);

        /* this has to be done after GPUs have been initialized */
        cudaclaw_set_method_parameters(clawopt->order,
                                       clawopt->mthlim,
                                       clawopt->mwaves,
                                       clawopt->use_fwaves);
        fc2d_cudaclaw_solver_initialize();
    }
    else
    {
        if (user_opt->claw_version == 4)
        {
            fc2d_clawpack46_solver_initialize();
        }
        else if (user_opt->claw_version == 5)
        {
            fc2d_clawpack5_solver_initialize();
        }
    }

    bump_link_solvers(glob);

    /* ---------------------------------------------------------------
       Run
       --------------------------------------------------------------- */

    if (user_opt->cuda == 1)
    {
        PROFILE_CUDA_GROUP("Allocate GPU and GPU buffers",1);
        fc2d_cudaclaw_allocate_buffers(glob);
    }

    fclaw2d_initialize(glob);
    fclaw2d_run(glob);

    if (user_opt->cuda == 1)
    {
        PROFILE_CUDA_GROUP("De-allocate GPU and GPU buffers",1);
        fc2d_cudaclaw_deallocate_buffers(glob);
    }

    fclaw2d_finalize(glob);
}

int
main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t                *options;
    user_options_t              *user_opt;
    fclaw_options_t             *fclaw_opt;
    fclaw2d_clawpatch_options_t *clawpatch_opt;
    fc2d_clawpack46_options_t   *claw46_opt;
    fc2d_clawpack5_options_t    *claw5_opt;
    fc2d_cudaclaw_options_t     *cuclaw5_opt;

    fclaw2d_global_t            *glob;
    fclaw2d_domain_t            *domain;
    sc_MPI_Comm mpicomm;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, NULL);

    /* Create new options packages */
    fclaw_opt =                   fclaw_options_register(app,"fclaw_options.ini");
    clawpatch_opt =   fclaw2d_clawpatch_options_register(app,"fclaw_options.ini");
    claw46_opt =        fc2d_clawpack46_options_register(app,"fclaw_options.ini");
    claw5_opt =          fc2d_clawpack5_options_register(app,"fclaw_options.ini");
    cuclaw_opt =          fc2d_cudaclaw_options_register(app,"fclaw_options.ini");
    user_opt =                bump_options_register(app,"fclaw_options.ini");

    /* Read configuration file(s) and command line, and process options */
    options = fclaw_app_get_options (app);
    retval = fclaw_options_read_from_file(options);
    vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    /* Run the program */
    if (!retval & !vexit)
    {
        /* Options have been checked and are valid */

        mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
        domain = create_domain(mpicomm, fclaw_opt,user_opt);

        /* Create global structure which stores the domain, timers, etc */
        glob = fclaw2d_global_new();
        fclaw2d_global_store_domain(glob, domain);

        /* Store option packages in glob */
        fclaw2d_options_store           (glob, fclaw_opt);
        fclaw2d_clawpatch_options_store (glob, clawpatch_opt);
        fc2d_clawpack46_options_store   (glob, claw46_opt);
        fc2d_clawpack5_options_store    (glob, claw5_opt);
        fc2d_cudaclaw_options_store     (glob, cuclaw_opt);
        bump_options_store              (glob, user_opt);

        run_program(glob);

        fclaw2d_global_destroy(glob);
    }

    fclaw_app_destroy (app);

    return 0;
}

<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (C) 2018 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * 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 OWNER 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.
 *
 ****************************************************************************/

/**
 * @file BerzierQuad.hpp
 *
 * Quadratic bezier lib
 *
 * A quadratic bezier function/spline is completely defined by three 3D points in space and a time scaling factor.
 * pt0 and pt1 define the start and end points of the spline. ctrl point is a point in space that effects the curvature
 * of the spline. The time scaling factor (= duration) defines the time it takes to travel along the spline from pt0 to
 * pt1.
 * A bezier spline is a continuous function from which position, velocity and acceleration can be extracted. For a given spline,
 * acceleration stays constant.
 */

#pragma once

#include <matrix/math.hpp>

namespace bezier
{
template<typename Tp>
class BezierQuad
{
public:

	using Vector3_t = matrix::Vector<Tp, 3>;

	/**
	 * Empty constructor
	 */
	BezierQuad(void) :
		_pt0(Vector3_t()), _ctrl(Vector3_t()), _pt1(Vector3_t()), _duration(1.0f) {}

	/**
	 * Constructor from array
	 */
	BezierQuad(const Tp pt0[3], const Tp ctrl[3], const Tp pt1[3], Tp duration = 1.0f) :
		_pt0(Vector3_t(pt0)), _ctrl(Vector3_t(ctrl)), _pt1(Vector3_t(pt1)), _duration(duration) {}

	/**
	 * Constructor from vector
	 */
	BezierQuad(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
		   Tp duration = 1.0f):
		_pt0(pt0), _ctrl(ctrl), _pt1(pt1), _duration(duration) {}

	/*
	 * Get bezier points
	 */
	void getBezier(Vector3_t &pt0, Vector3_t &ctrl, Vector3_t &pt1);

	/*
	 * Return pt0
	 */
	Vector3_t getPt0() {return _pt0;}

	/*
	 * Return ctrl
	 */
	Vector3_t getCtrl() {return _ctrl;}

	/*
	 * Return pt1
	 */
	Vector3_t getPt1() {return _pt1;}

	/**
	 * Set new bezier points and duration
	 */
	void setBezier(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
		       Tp duration = (Tp)1);

	/*
	 * Set duration
	 *
	 * @param time is the total time it takes to travel along the bezier spline.
	 */
	void setDuration(const Tp time) {_duration = time;}

	/**
	 * Return point on bezier point corresponding to time t
	 *
	 * @param t is a time in seconds in between [0, duration]
	 * @return a point on bezier
	 */
	Vector3_t getPoint(const Tp t);

	/*
	 * Distance to closest point given a position
	 *
	 * @param pose is a position in 3D space from which distance to bezier is computed.
	 * @return distance to closest point on bezier
	 */
	Tp getDistToClosestPoint(const Vector3_t &pose);

	/*
	 * Return velocity on bezier corresponding to time t
	 *
	 * @param t is a time in seconds in between [0, duration]
	 * @return velocity vector at time t
	 */
	Vector3_t getVelocity(const Tp t);

	/*
	 * Return acceleration on bezier corresponding to time t
	 *
	 * @return constant acceleration of bezier
	 */
	Vector3_t getAcceleration();

	/*
	 * Get all states on bezier corresponding to time t
	 */
	void getStates(Vector3_t &point, Vector3_t &vel, Vector3_t &acc, const Tp t);

	/*
	 * Get states on bezier which are closest to pose in space
	 *
	 * @param point is a posiiton on the spline that is closest to a given pose
	 * @param vel is the velocity at that given point
	 * @param acc is the acceleration for that spline
	 * @param pose represent a position in space from which closest point is computed
	 */
	void getStatesClosest(Vector3_t &point, Vector3_t &vel, Vector3_t &acc,
			      const Vector3_t pose);

	/*
	 * Compute bezier from velocity at bezier end points and ctrl point
	 *
	 * The bezier end points are fully defined by a given control point ctrl, the duration and
	 * the desired velocity vectors at the end points.
	 */
	void setBezFromVel(const Vector3_t &ctrl, const Vector3_t &vel0, const Vector3_t &vel1,
			   const Tp duration = (Tp)1);

	/*
	 * Return the arc length of a bezier spline
	 *
	 * The arc length is computed with simpsons integration.
	 * @param resolution in meters.
	 */
	Tp getArcLength(const Tp resolution);

private:

	Vector3_t _pt0; /**< Bezier starting point */
	Vector3_t _ctrl; /**< Bezier control point */
	Vector3_t _pt1; /**< bezier end point */
	Tp _duration = (Tp)1; /**< Total time to travle along spline */

	Tp _cached_arc_length = (Tp)0; /**< The saved arc length of the spline */
	Tp _cached_resolution = (Tp)(-1); /**< The resolution used to compute the arc length.
									Negative number means that cache is not up to date. */

	/*
	 * Golden section search
	 */
	Tp _goldenSectionSearch(const Vector3_t &pose);

	/*
	 * Get squared distance from 3D pose in space and a point on bezier.
	 *
	 * @param t is the time in between [0, duration] that defines a point on the bezier.
	 * @param pose is a 3D pose in space.
	 */
	Tp _getDistanceSquared(const Tp t, const Vector3_t &pose);

};

using BezierQuad_f = BezierQuad<float>;
using BezierQuad_d = BezierQuad<double>;
}

// include implementation
#include "BezierQuad.cpp"
<commit_msg>clang modernize: remove void argument<commit_after>/****************************************************************************
 *
 *   Copyright (C) 2018 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * 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 OWNER 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.
 *
 ****************************************************************************/

/**
 * @file BerzierQuad.hpp
 *
 * Quadratic bezier lib
 *
 * A quadratic bezier function/spline is completely defined by three 3D points in space and a time scaling factor.
 * pt0 and pt1 define the start and end points of the spline. ctrl point is a point in space that effects the curvature
 * of the spline. The time scaling factor (= duration) defines the time it takes to travel along the spline from pt0 to
 * pt1.
 * A bezier spline is a continuous function from which position, velocity and acceleration can be extracted. For a given spline,
 * acceleration stays constant.
 */

#pragma once

#include <matrix/math.hpp>

namespace bezier
{
template<typename Tp>
class BezierQuad
{
public:

	using Vector3_t = matrix::Vector<Tp, 3>;

	/**
	 * Empty constructor
	 */
	BezierQuad() :
		_pt0(Vector3_t()), _ctrl(Vector3_t()), _pt1(Vector3_t()), _duration(1.0f) {}

	/**
	 * Constructor from array
	 */
	BezierQuad(const Tp pt0[3], const Tp ctrl[3], const Tp pt1[3], Tp duration = 1.0f) :
		_pt0(Vector3_t(pt0)), _ctrl(Vector3_t(ctrl)), _pt1(Vector3_t(pt1)), _duration(duration) {}

	/**
	 * Constructor from vector
	 */
	BezierQuad(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
		   Tp duration = 1.0f):
		_pt0(pt0), _ctrl(ctrl), _pt1(pt1), _duration(duration) {}

	/*
	 * Get bezier points
	 */
	void getBezier(Vector3_t &pt0, Vector3_t &ctrl, Vector3_t &pt1);

	/*
	 * Return pt0
	 */
	Vector3_t getPt0() {return _pt0;}

	/*
	 * Return ctrl
	 */
	Vector3_t getCtrl() {return _ctrl;}

	/*
	 * Return pt1
	 */
	Vector3_t getPt1() {return _pt1;}

	/**
	 * Set new bezier points and duration
	 */
	void setBezier(const Vector3_t &pt0, const Vector3_t &ctrl, const Vector3_t &pt1,
		       Tp duration = (Tp)1);

	/*
	 * Set duration
	 *
	 * @param time is the total time it takes to travel along the bezier spline.
	 */
	void setDuration(const Tp time) {_duration = time;}

	/**
	 * Return point on bezier point corresponding to time t
	 *
	 * @param t is a time in seconds in between [0, duration]
	 * @return a point on bezier
	 */
	Vector3_t getPoint(const Tp t);

	/*
	 * Distance to closest point given a position
	 *
	 * @param pose is a position in 3D space from which distance to bezier is computed.
	 * @return distance to closest point on bezier
	 */
	Tp getDistToClosestPoint(const Vector3_t &pose);

	/*
	 * Return velocity on bezier corresponding to time t
	 *
	 * @param t is a time in seconds in between [0, duration]
	 * @return velocity vector at time t
	 */
	Vector3_t getVelocity(const Tp t);

	/*
	 * Return acceleration on bezier corresponding to time t
	 *
	 * @return constant acceleration of bezier
	 */
	Vector3_t getAcceleration();

	/*
	 * Get all states on bezier corresponding to time t
	 */
	void getStates(Vector3_t &point, Vector3_t &vel, Vector3_t &acc, const Tp t);

	/*
	 * Get states on bezier which are closest to pose in space
	 *
	 * @param point is a posiiton on the spline that is closest to a given pose
	 * @param vel is the velocity at that given point
	 * @param acc is the acceleration for that spline
	 * @param pose represent a position in space from which closest point is computed
	 */
	void getStatesClosest(Vector3_t &point, Vector3_t &vel, Vector3_t &acc,
			      const Vector3_t pose);

	/*
	 * Compute bezier from velocity at bezier end points and ctrl point
	 *
	 * The bezier end points are fully defined by a given control point ctrl, the duration and
	 * the desired velocity vectors at the end points.
	 */
	void setBezFromVel(const Vector3_t &ctrl, const Vector3_t &vel0, const Vector3_t &vel1,
			   const Tp duration = (Tp)1);

	/*
	 * Return the arc length of a bezier spline
	 *
	 * The arc length is computed with simpsons integration.
	 * @param resolution in meters.
	 */
	Tp getArcLength(const Tp resolution);

private:

	Vector3_t _pt0; /**< Bezier starting point */
	Vector3_t _ctrl; /**< Bezier control point */
	Vector3_t _pt1; /**< bezier end point */
	Tp _duration = (Tp)1; /**< Total time to travle along spline */

	Tp _cached_arc_length = (Tp)0; /**< The saved arc length of the spline */
	Tp _cached_resolution = (Tp)(-1); /**< The resolution used to compute the arc length.
									Negative number means that cache is not up to date. */

	/*
	 * Golden section search
	 */
	Tp _goldenSectionSearch(const Vector3_t &pose);

	/*
	 * Get squared distance from 3D pose in space and a point on bezier.
	 *
	 * @param t is the time in between [0, duration] that defines a point on the bezier.
	 * @param pose is a 3D pose in space.
	 */
	Tp _getDistanceSquared(const Tp t, const Vector3_t &pose);

};

using BezierQuad_f = BezierQuad<float>;
using BezierQuad_d = BezierQuad<double>;
}

// include implementation
#include "BezierQuad.cpp"
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/net_converter.h"

#include <string>
#include <vector>

#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "native_mate/dictionary.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/cert/x509_certificate.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "storage/browser/blob/upload_blob_element_reader.h"

#include "atom/common/node_includes.h"

namespace mate {

// static
v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8(
    v8::Isolate* isolate, const net::AuthChallengeInfo* val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("isProxy", val->is_proxy);
  dict.Set("scheme", val->scheme);
  dict.Set("host", val->challenger.host());
  dict.Set("port", static_cast<uint32_t>(val->challenger.port()));
  dict.Set("realm", val->realm);
  return mate::ConvertToV8(isolate, dict);
}

// static
v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
    v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) {
  mate::Dictionary dict(isolate, v8::Object::New(isolate));
  std::string encoded_data;
  net::X509Certificate::GetPEMEncoded(
      val->os_cert_handle(), &encoded_data);

  dict.Set("data", encoded_data);
  dict.Set("issuer", val->issuer());
  dict.Set("issuerName", val->issuer().GetDisplayName());
  dict.Set("subject", val->subject());
  dict.Set("subjectName", val->subject().GetDisplayName());
  dict.Set("serialNumber", base::HexEncode(val->serial_number().data(),
                                           val->serial_number().size()));
  dict.Set("validStart", val->valid_start().ToDoubleT());
  dict.Set("validExpiry", val->valid_expiry().ToDoubleT());
  dict.Set("fingerprint",
           net::HashValue(
              val->CalculateFingerprint256(val->os_cert_handle())).ToString());

  auto intermediates = val->GetIntermediateCertificates();
  if (!intermediates.empty()) {
    net::X509Certificate::OSCertHandles issuer_intermediates(
        val->GetIntermediateCertificates().begin() + 1,
        val->GetIntermediateCertificates().end());
    const scoped_refptr<net::X509Certificate>& issuer_cert =
        net::X509Certificate::CreateFromHandle(
            val->GetIntermediateCertificates().front(),
            issuer_intermediates);
    dict.Set("issuerCert", issuer_cert);

    std::vector<std::string> intermediates_encoded;
    for (size_t i = 0; i < intermediates.size(); i++) {
      auto native_cert = intermediates[i];
      std::string encoded;
      net::X509Certificate::GetPEMEncoded(native_cert, &encoded);
      intermediates_encoded.push_back(encoded);
    }

    dict.Set("intermediates", intermediates_encoded);
  }

  return dict.GetHandle();
}

bool Converter<scoped_refptr<net::X509Certificate>>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val,
    scoped_refptr<net::X509Certificate>* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;

  std::string data;
  dict.Get("data", &data);

  auto certificate_list = net::X509Certificate::CreateCertificateListFromBytes(
    data.c_str(), data.length(),
    net::X509Certificate::FORMAT_SINGLE_CERTIFICATE);
  if (certificate_list.empty())
    return false;

  auto certificate = certificate_list.front();
  if (!certificate)
    return false;

  *out = certificate;
  return true;
}

// static
v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8(
    v8::Isolate* isolate, const net::CertPrincipal& val) {
  mate::Dictionary dict(isolate, v8::Object::New(isolate));

  dict.Set("commonName", val.common_name);
  dict.Set("organizations", val.organization_names);
  dict.Set("organizationUnits", val.organization_unit_names);
  dict.Set("locality", val.locality_name);
  dict.Set("state", val.state_or_province_name);
  dict.Set("country", val.country_name);

  return dict.GetHandle();
}

// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
    v8::Isolate* isolate,
    net::HttpResponseHeaders* headers) {
  base::DictionaryValue response_headers;
  if (headers) {
    size_t iter = 0;
    std::string key;
    std::string value;
    while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
      key = base::ToLowerASCII(key);
      if (response_headers.HasKey(key)) {
        base::ListValue* values = nullptr;
        if (response_headers.GetList(key, &values))
          values->AppendString(value);
      } else {
        std::unique_ptr<base::ListValue> values(new base::ListValue());
        values->AppendString(value);
        response_headers.Set(key, std::move(values));
      }
    }
  }
  return ConvertToV8(isolate, response_headers);
}

}  // namespace mate

namespace atom {

void FillRequestDetails(base::DictionaryValue* details,
                        const net::URLRequest* request) {
  details->SetString("method", request->method());
  std::string url;
  if (!request->url_chain().empty()) url = request->url().spec();
  details->SetStringWithoutPathExpansion("url", url);
  details->SetString("referrer", request->referrer());
  std::unique_ptr<base::ListValue> list(new base::ListValue);
  GetUploadData(list.get(), request);
  if (!list->empty())
    details->Set("uploadData", std::move(list));
}

void GetUploadData(base::ListValue* upload_data_list,
                   const net::URLRequest* request) {
  const net::UploadDataStream* upload_data = request->get_upload();
  if (!upload_data)
    return;
  const std::vector<std::unique_ptr<net::UploadElementReader>>* readers =
      upload_data->GetElementReaders();
  for (const auto& reader : *readers) {
    std::unique_ptr<base::DictionaryValue> upload_data_dict(
        new base::DictionaryValue);
    if (reader->AsBytesReader()) {
      const net::UploadBytesElementReader* bytes_reader =
          reader->AsBytesReader();
      std::unique_ptr<base::Value> bytes(
          base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(),
                                                    bytes_reader->length()));
      upload_data_dict->Set("bytes", std::move(bytes));
    } else if (reader->AsFileReader()) {
      const net::UploadFileElementReader* file_reader =
          reader->AsFileReader();
      auto file_path = file_reader->path().AsUTF8Unsafe();
      upload_data_dict->SetStringWithoutPathExpansion("file", file_path);
    } else {
      const storage::UploadBlobElementReader* blob_reader =
          static_cast<storage::UploadBlobElementReader*>(reader.get());
      upload_data_dict->SetString("blobUUID", blob_reader->uuid());
    }
    upload_data_list->Append(std::move(upload_data_dict));
  }
}

}  // namespace atom
<commit_msg>Decode all the intermediates<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/net_converter.h"

#include <string>
#include <vector>

#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "native_mate/dictionary.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/cert/x509_certificate.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "storage/browser/blob/upload_blob_element_reader.h"

#include "atom/common/node_includes.h"

namespace mate {

// static
v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8(
    v8::Isolate* isolate, const net::AuthChallengeInfo* val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("isProxy", val->is_proxy);
  dict.Set("scheme", val->scheme);
  dict.Set("host", val->challenger.host());
  dict.Set("port", static_cast<uint32_t>(val->challenger.port()));
  dict.Set("realm", val->realm);
  return mate::ConvertToV8(isolate, dict);
}

// static
v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
    v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) {
  mate::Dictionary dict(isolate, v8::Object::New(isolate));
  std::string encoded_data;
  net::X509Certificate::GetPEMEncoded(
      val->os_cert_handle(), &encoded_data);

  dict.Set("data", encoded_data);
  dict.Set("issuer", val->issuer());
  dict.Set("issuerName", val->issuer().GetDisplayName());
  dict.Set("subject", val->subject());
  dict.Set("subjectName", val->subject().GetDisplayName());
  dict.Set("serialNumber", base::HexEncode(val->serial_number().data(),
                                           val->serial_number().size()));
  dict.Set("validStart", val->valid_start().ToDoubleT());
  dict.Set("validExpiry", val->valid_expiry().ToDoubleT());
  dict.Set("fingerprint",
           net::HashValue(
              val->CalculateFingerprint256(val->os_cert_handle())).ToString());

  auto intermediates = val->GetIntermediateCertificates();
  if (!intermediates.empty()) {
    net::X509Certificate::OSCertHandles issuer_intermediates(
        val->GetIntermediateCertificates().begin() + 1,
        val->GetIntermediateCertificates().end());
    const scoped_refptr<net::X509Certificate>& issuer_cert =
        net::X509Certificate::CreateFromHandle(
            val->GetIntermediateCertificates().front(),
            issuer_intermediates);
    dict.Set("issuerCert", issuer_cert);

    std::vector<std::string> intermediates_encoded;
    for (size_t i = 0; i < intermediates.size(); i++) {
      auto native_cert = intermediates[i];
      std::string encoded;
      net::X509Certificate::GetPEMEncoded(native_cert, &encoded);
      intermediates_encoded.push_back(encoded);
    }

    dict.Set("intermediates", intermediates_encoded);
  }

  return dict.GetHandle();
}

bool CertFromData(const std::string& data,
    scoped_refptr<net::X509Certificate>* out) {
  auto cert_list = net::X509Certificate::CreateCertificateListFromBytes(
    data.c_str(), data.length(),
    net::X509Certificate::FORMAT_SINGLE_CERTIFICATE);
  if (cert_list.empty())
    return false;

  auto leaf_cert = cert_list.front();
  if (!leaf_cert)
    return false;

  *out = leaf_cert;

  return true;
}

bool Converter<scoped_refptr<net::X509Certificate>>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val,
    scoped_refptr<net::X509Certificate>* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;

  std::string data;
  dict.Get("data", &data);
  scoped_refptr<net::X509Certificate> leaf_cert;
  if (!CertFromData(data, &leaf_cert))
    return false;

  std::vector<std::string> intermediates_encoded;
  dict.Get("intermediates", &intermediates_encoded);
  std::vector<net::X509Certificate::OSCertHandle> intermediates;
  for (size_t i = 0; i < intermediates_encoded.size(); i++) {
    auto data = intermediates_encoded[i];
    scoped_refptr<net::X509Certificate> cert;
    if (!CertFromData(data, &cert))
      return false;

    intermediates.push_back(cert->os_cert_handle());
  }

  auto cert = net::X509Certificate::CreateFromHandle(
    leaf_cert->os_cert_handle(), intermediates);
  if (!cert)
    return false;

  *out = cert;
  return true;
}

// static
v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8(
    v8::Isolate* isolate, const net::CertPrincipal& val) {
  mate::Dictionary dict(isolate, v8::Object::New(isolate));

  dict.Set("commonName", val.common_name);
  dict.Set("organizations", val.organization_names);
  dict.Set("organizationUnits", val.organization_unit_names);
  dict.Set("locality", val.locality_name);
  dict.Set("state", val.state_or_province_name);
  dict.Set("country", val.country_name);

  return dict.GetHandle();
}

// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
    v8::Isolate* isolate,
    net::HttpResponseHeaders* headers) {
  base::DictionaryValue response_headers;
  if (headers) {
    size_t iter = 0;
    std::string key;
    std::string value;
    while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
      key = base::ToLowerASCII(key);
      if (response_headers.HasKey(key)) {
        base::ListValue* values = nullptr;
        if (response_headers.GetList(key, &values))
          values->AppendString(value);
      } else {
        std::unique_ptr<base::ListValue> values(new base::ListValue());
        values->AppendString(value);
        response_headers.Set(key, std::move(values));
      }
    }
  }
  return ConvertToV8(isolate, response_headers);
}

}  // namespace mate

namespace atom {

void FillRequestDetails(base::DictionaryValue* details,
                        const net::URLRequest* request) {
  details->SetString("method", request->method());
  std::string url;
  if (!request->url_chain().empty()) url = request->url().spec();
  details->SetStringWithoutPathExpansion("url", url);
  details->SetString("referrer", request->referrer());
  std::unique_ptr<base::ListValue> list(new base::ListValue);
  GetUploadData(list.get(), request);
  if (!list->empty())
    details->Set("uploadData", std::move(list));
}

void GetUploadData(base::ListValue* upload_data_list,
                   const net::URLRequest* request) {
  const net::UploadDataStream* upload_data = request->get_upload();
  if (!upload_data)
    return;
  const std::vector<std::unique_ptr<net::UploadElementReader>>* readers =
      upload_data->GetElementReaders();
  for (const auto& reader : *readers) {
    std::unique_ptr<base::DictionaryValue> upload_data_dict(
        new base::DictionaryValue);
    if (reader->AsBytesReader()) {
      const net::UploadBytesElementReader* bytes_reader =
          reader->AsBytesReader();
      std::unique_ptr<base::Value> bytes(
          base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(),
                                                    bytes_reader->length()));
      upload_data_dict->Set("bytes", std::move(bytes));
    } else if (reader->AsFileReader()) {
      const net::UploadFileElementReader* file_reader =
          reader->AsFileReader();
      auto file_path = file_reader->path().AsUTF8Unsafe();
      upload_data_dict->SetStringWithoutPathExpansion("file", file_path);
    } else {
      const storage::UploadBlobElementReader* blob_reader =
          static_cast<storage::UploadBlobElementReader*>(reader.get());
      upload_data_dict->SetString("blobUUID", blob_reader->uuid());
    }
    upload_data_list->Append(std::move(upload_data_dict));
  }
}

}  // namespace atom
<|endoftext|>


<commit_before>//
// Copyright (c) 2015 CNRS
// Author: Mylene Campana, Joseph Mirabel
//
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
# define HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH

#include <hpp/util/exception-factory.hh>

# include <hpp/fcl/collision.h>
# include <hpp/fcl/distance.h>

# include <hpp/pinocchio/configuration.hh>
# include <pinocchio/multibody/liegroup/liegroup.hpp>

# include <hpp/constraints/generic-transformation.hh>

namespace hpp {
  namespace core {
    namespace pathOptimization {
      HPP_PREDEF_CLASS (CollisionFunction);
      typedef boost::shared_ptr <CollisionFunction> CollisionFunctionPtr_t;
      typedef pinocchio::Transform3f Transform3f;
      namespace eigen {
	typedef Eigen::Matrix <value_type, 3, 1> vector3_t;
      } // namespace eigen

      class CollisionFunction : public DifferentiableFunction
      {
      public:
       virtual ~CollisionFunction () {}
       template <typename SplinePtr_t>
       static CollisionFunctionPtr_t create
       (const DevicePtr_t& robot, const SplinePtr_t& freeSpline,
        const SplinePtr_t& collSpline,
        const CollisionPathValidationReportPtr_t& report)
       {
         const value_type& tColl = report->parameter;
         bool success;
         Configuration_t qColl = (*collSpline) (tColl, success);
         assert(success);

         HPP_STATIC_CAST_REF_CHECK (CollisionValidationReport,
             *(report->configurationReport));
         CollisionObjectConstPtr_t object1 =
           HPP_STATIC_PTR_CAST (CollisionValidationReport,
               report->configurationReport)->object1;
         CollisionObjectConstPtr_t object2 =
           HPP_STATIC_PTR_CAST (CollisionValidationReport,
               report->configurationReport)->object2;

         hppDout (info, "Collision at ratio (in [0,1]) = " << tColl / collSpline->length());
         hppDout (info, "obj1 = " << object1->name()
             << " and obj2 = " << object2->name());
         hppDout (info, "qColl = " << qColl.transpose());

         // Backtrack collision in previous path (x0) to create constraint
         value_type tFree = tColl * freeSpline->length () / collSpline->length();

         Configuration_t qFree = (*freeSpline) (tFree, success);
         assert(success);
         hppDout (info, "qFree = " << qFree.transpose());

         return create (robot, qFree, qColl, object1, object2);
       }
       static CollisionFunctionPtr_t create
       (const DevicePtr_t& robot, const Configuration_t& qFree,
	const Configuration_t& qColl, const CollisionObjectConstPtr_t& object1,
	const CollisionObjectConstPtr_t& object2)
       {
         CollisionFunction* ptr = new CollisionFunction
           (robot, qFree, qColl, object1, object2);
         CollisionFunctionPtr_t shPtr (ptr);
         return shPtr;
       }
      protected:
       CollisionFunction (const DevicePtr_t& robot,
                            const Configuration_t& qFree,
                            const Configuration_t& qColl,
			    const CollisionObjectConstPtr_t& object1,
			    const CollisionObjectConstPtr_t& object2)
         : DifferentiableFunction (robot->configSize (), robot->numberDof (),
                                   1, ""), robot_ (robot), qFree_ (qFree),
           J_ (), difference_ ()

       {
	 difference_.resize (robot->numberDof ());
	 // Compute contact point in configuration qColl
	 robot_->currentConfiguration (qColl);
	 robot_->computeForwardKinematics ();
         robot_->updateGeometryPlacements ();
	 fcl::CollisionResult result;
         fcl::CollisionRequest collisionRequest (1, true, false, 1, false, true, fcl::GST_INDEP);
         fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
         if (result.numContacts() != 1) {
           result.clear();
           collisionRequest.enable_contact = false;
           fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
           if (result.isCollision()) {
             hppDout (error, "FCL does not returns the same result when asking or not for the contact points.");
           }

           HPP_THROW(std::invalid_argument,
               "Object " << object1->name() << " and " << object2->name()
               << " are not in collision in configuration\n"
               << qColl.transpose().format(IPythonFormat)
               << "\nqFree is\n" << qFree.transpose().format(IPythonFormat));
         }
	 assert (result.numContacts () == 1);
	 const vector3_t& contactPoint (result.getContact (0).pos);
	 hppDout (info, "contact point = " << contactPoint.transpose());

	 JointConstPtr_t joint1 = object1->joint ();
         // FIXME this copy can probably be avoided.
         Transform3f M1 (joint1->currentTransformation ());
         if (object2->joint ()) { // object2 = body part
           JointConstPtr_t joint2 = object2->joint ();
           Transform3f M2 (joint2->currentTransformation ());
           // Position of contact point in each object local frame
           vector3_t x1_J1 = M1.actInv (contactPoint);
           vector3_t x2_J2 = M2.actInv (contactPoint);
           // Compute contact points in configuration qFree
           robot_->currentConfiguration (qFree);
           robot_->computeForwardKinematics ();
           M2 = joint2->currentTransformation ();
           M1 = joint1->currentTransformation ();
           // Position of x2 in local frame of joint1
           vector3_t x2_J1 (M1.actInv (M2.act (x2_J2)));
           hppDout (info, "x1 in J1 = " << x1_J1.transpose());
           hppDout (info, "x2 in J1 = " << x2_J1.transpose());
           eigen::vector3_t u=x2_J1 - x1_J1;
           matrix3_t rot;
           rot.setIdentity();
           DifferentiableFunctionPtr_t f = constraints::RelativePosition::create
             ("", robot_, joint1, joint2, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
           matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
           f->jacobian (Jpos, qFree);
           J_ = u.transpose () * Jpos;
           assert (J_.rows () == 1);
         } else{ // object2 = fixed obstacle and has no joint
           vector3_t x1_J1 (M1.actInv(contactPoint));
           vector3_t x2_J2 (contactPoint);
           // Compute contact points in configuration qFree
           robot_->currentConfiguration (qFree);
           robot_->computeForwardKinematics ();
           Transform3f M1 (joint1->currentTransformation ());
           // position of x1 in global frame
           vector3_t x1_J2 (M1.act (x1_J1));
           hppDout (info, "x1 in J2 = " << x1_J2.transpose());
           eigen::vector3_t u=x1_J2 - x2_J2;
           matrix3_t rot;
           rot.setIdentity();
           DifferentiableFunctionPtr_t f = constraints::Position::create
             ("", robot_, joint1, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
           matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
           f->jacobian (Jpos, qFree);
           J_ = u.transpose () * Jpos;
           assert (J_.rows () == 1);
         }
       }

       virtual void impl_compute (vectorOut_t result, vectorIn_t argument)
         const
       {
         pinocchio::difference<se3::LieGroupTpl> (robot_, argument, qFree_, difference_);
         result = J_ * difference_;
       }
       virtual void impl_jacobian (matrixOut_t jacobian, vectorIn_t) const
       {
         jacobian = J_;
       }
      private:
	DevicePtr_t robot_;
	Configuration_t qFree_;
	matrix_t J_;
	mutable vector_t difference_;
      }; // class CollisionFunction
    } // namespace pathOptimization
  } // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
<commit_msg>Normalize direction in collision constraint<commit_after>//
// Copyright (c) 2015 CNRS
// Author: Mylene Campana, Joseph Mirabel
//
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
# define HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH

#include <hpp/util/exception-factory.hh>

# include <hpp/fcl/collision.h>
# include <hpp/fcl/distance.h>

# include <hpp/pinocchio/configuration.hh>
# include <pinocchio/multibody/liegroup/liegroup.hpp>

# include <hpp/constraints/generic-transformation.hh>

namespace hpp {
  namespace core {
    namespace pathOptimization {
      HPP_PREDEF_CLASS (CollisionFunction);
      typedef boost::shared_ptr <CollisionFunction> CollisionFunctionPtr_t;
      typedef pinocchio::Transform3f Transform3f;
      namespace eigen {
	typedef Eigen::Matrix <value_type, 3, 1> vector3_t;
      } // namespace eigen

      class CollisionFunction : public DifferentiableFunction
      {
      public:
       virtual ~CollisionFunction () {}
       template <typename SplinePtr_t>
       static CollisionFunctionPtr_t create
       (const DevicePtr_t& robot, const SplinePtr_t& freeSpline,
        const SplinePtr_t& collSpline,
        const CollisionPathValidationReportPtr_t& report)
       {
         const value_type& tColl = report->parameter;
         bool success;
         Configuration_t qColl = (*collSpline) (tColl, success);
         assert(success);

         HPP_STATIC_CAST_REF_CHECK (CollisionValidationReport,
             *(report->configurationReport));
         CollisionObjectConstPtr_t object1 =
           HPP_STATIC_PTR_CAST (CollisionValidationReport,
               report->configurationReport)->object1;
         CollisionObjectConstPtr_t object2 =
           HPP_STATIC_PTR_CAST (CollisionValidationReport,
               report->configurationReport)->object2;

         hppDout (info, "Collision at ratio (in [0,1]) = " << tColl / collSpline->length());
         hppDout (info, "obj1 = " << object1->name()
             << " and obj2 = " << object2->name());
         hppDout (info, "qColl = " << qColl.transpose());

         // Backtrack collision in previous path (x0) to create constraint
         value_type tFree = tColl * freeSpline->length () / collSpline->length();

         Configuration_t qFree = (*freeSpline) (tFree, success);
         assert(success);
         hppDout (info, "qFree = " << qFree.transpose());

         return create (robot, qFree, qColl, object1, object2);
       }
       static CollisionFunctionPtr_t create
       (const DevicePtr_t& robot, const Configuration_t& qFree,
	const Configuration_t& qColl, const CollisionObjectConstPtr_t& object1,
	const CollisionObjectConstPtr_t& object2)
       {
         CollisionFunction* ptr = new CollisionFunction
           (robot, qFree, qColl, object1, object2);
         CollisionFunctionPtr_t shPtr (ptr);
         return shPtr;
       }
      protected:
       CollisionFunction (const DevicePtr_t& robot,
                            const Configuration_t& qFree,
                            const Configuration_t& qColl,
			    const CollisionObjectConstPtr_t& object1,
			    const CollisionObjectConstPtr_t& object2)
         : DifferentiableFunction (robot->configSize (), robot->numberDof (),
                                   1, ""), robot_ (robot), qFree_ (qFree),
           J_ (), difference_ ()

       {
	 difference_.resize (robot->numberDof ());
	 // Compute contact point in configuration qColl
	 robot_->currentConfiguration (qColl);
	 robot_->computeForwardKinematics ();
         robot_->updateGeometryPlacements ();
	 fcl::CollisionResult result;
         fcl::CollisionRequest collisionRequest (1, true, false, 1, false, true, fcl::GST_INDEP);
         fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
         if (result.numContacts() != 1) {
           result.clear();
           collisionRequest.enable_contact = false;
           fcl::collide (object1->fcl (), object2->fcl (), collisionRequest, result);
           if (result.isCollision()) {
             hppDout (error, "FCL does not returns the same result when asking or not for the contact points.");
           }

           HPP_THROW(std::invalid_argument,
               "Object " << object1->name() << " and " << object2->name()
               << " are not in collision in configuration\n"
               << qColl.transpose().format(IPythonFormat)
               << "\nqFree is\n" << qFree.transpose().format(IPythonFormat));
         }
	 assert (result.numContacts () == 1);
	 const vector3_t& contactPoint (result.getContact (0).pos);
	 hppDout (info, "contact point = " << contactPoint.transpose());

	 JointConstPtr_t joint1 = object1->joint ();
         // FIXME this copy can probably be avoided.
         Transform3f M1 (joint1->currentTransformation ());
         if (object2->joint ()) { // object2 = body part
           JointConstPtr_t joint2 = object2->joint ();
           Transform3f M2 (joint2->currentTransformation ());
           // Position of contact point in each object local frame
           vector3_t x1_J1 = M1.actInv (contactPoint);
           vector3_t x2_J2 = M2.actInv (contactPoint);
           // Compute contact points in configuration qFree
           robot_->currentConfiguration (qFree);
           robot_->computeForwardKinematics ();
           M2 = joint2->currentTransformation ();
           M1 = joint1->currentTransformation ();
           // Position of x2 in local frame of joint1
           vector3_t x2_J1 (M1.actInv (M2.act (x2_J2)));
           hppDout (info, "x1 in J1 = " << x1_J1.transpose());
           hppDout (info, "x2 in J1 = " << x2_J1.transpose());
           eigen::vector3_t u=x2_J1 - x1_J1;
           matrix3_t rot;
           rot.setIdentity();
           DifferentiableFunctionPtr_t f = constraints::RelativePosition::create
             ("", robot_, joint1, joint2, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
           matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
           f->jacobian (Jpos, qFree);
           J_ = u.transpose () * Jpos;
           assert (J_.rows () == 1);
         } else{ // object2 = fixed obstacle and has no joint
           vector3_t x1_J1 (M1.actInv(contactPoint));
           vector3_t x2_J2 (contactPoint);
           // Compute contact points in configuration qFree
           robot_->currentConfiguration (qFree);
           robot_->computeForwardKinematics ();
           Transform3f M1 (joint1->currentTransformation ());
           // position of x1 in global frame
           vector3_t x1_J2 (M1.act (x1_J1));
           hppDout (info, "x1 in J2 = " << x1_J2.transpose());
           eigen::vector3_t u=x1_J2 - x2_J2;
           u.normalize();
           matrix3_t rot;
           rot.setIdentity();
           DifferentiableFunctionPtr_t f = constraints::Position::create
             ("", robot_, joint1, Transform3f(rot,x1_J1), Transform3f(rot,x2_J2));
           matrix_t Jpos (f->outputSize (), f->inputDerivativeSize ());
           f->jacobian (Jpos, qFree);
           J_ = u.transpose () * Jpos;
           assert (J_.rows () == 1);
         }
       }

       virtual void impl_compute (vectorOut_t result, vectorIn_t argument)
         const
       {
         pinocchio::difference<se3::LieGroupTpl> (robot_, argument, qFree_, difference_);
         result = J_ * difference_;
       }
       virtual void impl_jacobian (matrixOut_t jacobian, vectorIn_t) const
       {
         jacobian = J_;
       }
      private:
	DevicePtr_t robot_;
	Configuration_t qFree_;
	matrix_t J_;
	mutable vector_t difference_;
      }; // class CollisionFunction
    } // namespace pathOptimization
  } // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_OPTIMIZATION_SPLINE_GRADIENT_BASED_COLLISION_CONSTRAINTS_HH
<|endoftext|>