<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may 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.

#if !(defined(QNX) || defined(QNX__) || defined(__QNX__))

#include "iceoryx_utils/platform/time.hpp"
#include "iceoryx_utils/posix_wrapper/semaphore.hpp"
#include "test.hpp"

#include <atomic>
#include <chrono>
#include <thread>

using namespace ::testing;

typedef iox::posix::Semaphore* CreateSemaphore();

iox::posix::Semaphore* CreateNamedSemaphore()
{
    static int i = 10;
    auto semaphore =
        iox::posix::Semaphore::create(std::string("/fuuSem" + std::to_string(i++)).c_str(), S_IRUSR | S_IWUSR, 0);
    return (semaphore.has_error()) ? nullptr : new iox::posix::Semaphore(std::move(*semaphore));
}

iox::posix::Semaphore* CreateUnnamedSemaphore()
{
    auto semaphore = iox::posix::Semaphore::create(0);
    return (semaphore.has_error()) ? nullptr : new iox::posix::Semaphore(std::move(*semaphore));
}

class Semaphore_test : public TestWithParam<CreateSemaphore*>
{
  public:
    Semaphore_test()
        : sut((*GetParam())())
    {
    }

    ~Semaphore_test()
    {
        delete sut;
        delete syncSemaphore;
    }

    void SetUp()
    {
        internal::CaptureStderr();
        ASSERT_THAT(sut, Ne(nullptr));
        ASSERT_THAT(syncSemaphore, Ne(nullptr));
    }

    void TearDown()
    {
        std::string output = internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }

    iox::posix::Semaphore* sut{nullptr};
    iox::posix::Semaphore* syncSemaphore = [] {
        auto semaphore = iox::posix::Semaphore::create(0);
        return (semaphore.has_error()) ? nullptr : new iox::posix::Semaphore(std::move(*semaphore));
    }();
};

class SemaphoreCreate_test : public Test
{
  public:
    void SetUp()
    {
        internal::CaptureStderr();
    }

    void TearDown()
    {
        std::string output = internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }
};

INSTANTIATE_TEST_CASE_P(Semaphore_test, Semaphore_test, Values(&CreateNamedSemaphore, &CreateUnnamedSemaphore));

TEST_F(SemaphoreCreate_test, CreateNamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR, 10);
    EXPECT_THAT(semaphore.has_error(), Eq(false));
}

TEST_F(SemaphoreCreate_test, CreateExistingNamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create("/fuuSem1", S_IRUSR | S_IWUSR, 10);
    auto semaphore2 = iox::posix::Semaphore::create("/fuuSem1", S_IRUSR | S_IWUSR, 10);
    ASSERT_EQ(semaphore.has_error(), false);
    ASSERT_EQ(semaphore2.has_error(), true);
}

TEST_F(SemaphoreCreate_test, CreateLocalUnnamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create(10);
    EXPECT_THAT(semaphore.has_error(), Eq(false));
}

TEST_F(SemaphoreCreate_test, OpenNamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR, 10);
    auto semaphore2 = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR);
    EXPECT_THAT(semaphore.has_error(), Eq(false));
    EXPECT_THAT(semaphore2.has_error(), Eq(false));
}

TEST_F(SemaphoreCreate_test, OpenNonExistingNamedSemaphore)
{
    auto semaphore2 = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR);
    EXPECT_THAT(semaphore2.has_error(), Eq(true));
}

TEST_P(Semaphore_test, PostIncreasesSemaphoreValue)
{
    for (int i = 0; i < 12; ++i)
        sut->post();

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(12));
}

TEST_P(Semaphore_test, WaitDecreasesSemaphoreValue)
{
    for (int i = 0; i < 18; ++i)
        sut->post();
    for (int i = 0; i < 7; ++i)
        sut->wait();

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(11));
}

TEST_P(Semaphore_test, SuccessfulTryWaitDecreasesSemaphoreValue)
{
    for (int i = 0; i < 15; ++i)
        sut->post();
    for (int i = 0; i < 9; ++i)
        ASSERT_THAT(sut->tryWait(), Eq(true));

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(6));
}

TEST_P(Semaphore_test, FailingTryWaitDoesNotChangeSemaphoreValue)
{
    for (int i = 0; i < 4; ++i)
        ASSERT_THAT(sut->tryWait(), Eq(false));

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(0));
}

TEST_P(Semaphore_test, SuccessfulTimedWaitDecreasesSemaphoreValue)
{
    for (int i = 0; i < 19; ++i)
        sut->post();

    for (int i = 0; i < 12; ++i)
    {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        constexpr long TWO_MILLISECONDS{2000000};
        ts.tv_nsec += TWO_MILLISECONDS;
        ASSERT_THAT(sut->timedWait(&ts, false), Eq(true));
    }

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(7));
}

TEST_P(Semaphore_test, FailingTimedWaitDoesNotChangeSemaphoreValue)
{
    for (int i = 0; i < 4; ++i)
    {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        constexpr long TWO_MICROSECONDS{2000};
        ts.tv_nsec += TWO_MICROSECONDS;
        ASSERT_THAT(sut->timedWait(&ts, false), Eq(false));
    }

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(0));
}

TEST_P(Semaphore_test, TryWaitAfterPostIsSuccessful)
{
    sut->post();
    EXPECT_THAT(sut->tryWait(), Eq(true));
}

TEST_P(Semaphore_test, TryWaitWithNoPostIsNotSuccessful)
{
    sut->post();
    EXPECT_THAT(sut->tryWait(), Eq(true));
}

TEST_P(Semaphore_test, WaitValidAfterPostIsNonBlocking)
{
    sut->post();
    // this call should not block and should be successful
    EXPECT_THAT(sut->wait(), Eq(true));
}

TEST_P(Semaphore_test, WaitIsBlocking)
{
    std::atomic<int> counter{0};
    std::thread t1([&] {
        syncSemaphore->wait();
        sut->post();
        syncSemaphore->wait();
        counter++;
        sut->post();
    });

    EXPECT_THAT(counter.load(), Eq(0));

    syncSemaphore->post();
    sut->wait();
    EXPECT_THAT(counter.load(), Eq(0));

    syncSemaphore->post();
    sut->wait();
    EXPECT_THAT(counter.load(), Eq(1));

    t1.join();
}

TEST_P(Semaphore_test, MoveAssignment)
{
    iox::posix::Semaphore b;
    {
        b = std::move(*sut);
        EXPECT_THAT(sut->post(), Eq(false));
    }

    EXPECT_THAT(b.post(), Eq(true));
}

TEST_P(Semaphore_test, MoveCTor)
{
    iox::posix::Semaphore b(std::move(*sut));

    EXPECT_THAT(b.post(), Eq(true));
    EXPECT_THAT(sut->post(), Eq(false));
}

TEST_P(Semaphore_test, TimedWaitWithTimeout)
{
    std::atomic<bool> timedWaitFinish{false};

    std::thread t([&] {
        struct timespec ts;
        Win32Call(clock_gettime(CLOCK_REALTIME, &ts));
        constexpr long TEN_MILLISECONDS{10000000};
        ts.tv_nsec += TEN_MILLISECONDS;
        syncSemaphore->post();
        sut->wait();
        EXPECT_THAT(sut->timedWait(&ts, false), Eq(false));
        timedWaitFinish.store(true);
    });

    syncSemaphore->wait();
    sut->post();
    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    EXPECT_THAT(timedWaitFinish.load(), Eq(false));

    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    EXPECT_THAT(timedWaitFinish.load(), Eq(true));

    t.join();
}

TEST_P(Semaphore_test, TimedWaitWithoutTimeout)
{
    std::atomic<bool> timedWaitFinish{false};

    std::thread t([&] {
        SetLastError(0);
        struct timespec ts;
        Win32Call(clock_gettime(CLOCK_REALTIME, &ts));
        constexpr long TEN_MILLISECONDS{10000000};
        ts.tv_nsec += TEN_MILLISECONDS;
        syncSemaphore->post();
        sut->wait();
        EXPECT_THAT(sut->timedWait(&ts, false), Eq(true));
        timedWaitFinish.store(true);
    });

    syncSemaphore->wait();
    sut->post();
    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    EXPECT_THAT(timedWaitFinish.load(), Eq(false));

    sut->post();
    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(2));
    EXPECT_THAT(timedWaitFinish.load(), Eq(true));

    t.join();
}

#endif
<commit_msg>iox-#32 removed windows specific debugging stuff from unit test<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may 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.

#if !(defined(QNX) || defined(QNX__) || defined(__QNX__))

#include "iceoryx_utils/platform/time.hpp"
#include "iceoryx_utils/posix_wrapper/semaphore.hpp"
#include "test.hpp"

#include <atomic>
#include <chrono>
#include <thread>

using namespace ::testing;

typedef iox::posix::Semaphore* CreateSemaphore();

iox::posix::Semaphore* CreateNamedSemaphore()
{
    static int i = 10;
    auto semaphore =
        iox::posix::Semaphore::create(std::string("/fuuSem" + std::to_string(i++)).c_str(), S_IRUSR | S_IWUSR, 0);
    return (semaphore.has_error()) ? nullptr : new iox::posix::Semaphore(std::move(*semaphore));
}

iox::posix::Semaphore* CreateUnnamedSemaphore()
{
    auto semaphore = iox::posix::Semaphore::create(0);
    return (semaphore.has_error()) ? nullptr : new iox::posix::Semaphore(std::move(*semaphore));
}

class Semaphore_test : public TestWithParam<CreateSemaphore*>
{
  public:
    Semaphore_test()
        : sut((*GetParam())())
    {
    }

    ~Semaphore_test()
    {
        delete sut;
        delete syncSemaphore;
    }

    void SetUp()
    {
        internal::CaptureStderr();
        ASSERT_THAT(sut, Ne(nullptr));
        ASSERT_THAT(syncSemaphore, Ne(nullptr));
    }

    void TearDown()
    {
        std::string output = internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }

    iox::posix::Semaphore* sut{nullptr};
    iox::posix::Semaphore* syncSemaphore = [] {
        auto semaphore = iox::posix::Semaphore::create(0);
        return (semaphore.has_error()) ? nullptr : new iox::posix::Semaphore(std::move(*semaphore));
    }();
};

class SemaphoreCreate_test : public Test
{
  public:
    void SetUp()
    {
        internal::CaptureStderr();
    }

    void TearDown()
    {
        std::string output = internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }
};

INSTANTIATE_TEST_CASE_P(Semaphore_test, Semaphore_test, Values(&CreateNamedSemaphore, &CreateUnnamedSemaphore));

TEST_F(SemaphoreCreate_test, CreateNamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR, 10);
    EXPECT_THAT(semaphore.has_error(), Eq(false));
}

TEST_F(SemaphoreCreate_test, CreateExistingNamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create("/fuuSem1", S_IRUSR | S_IWUSR, 10);
    auto semaphore2 = iox::posix::Semaphore::create("/fuuSem1", S_IRUSR | S_IWUSR, 10);
    ASSERT_EQ(semaphore.has_error(), false);
    ASSERT_EQ(semaphore2.has_error(), true);
}

TEST_F(SemaphoreCreate_test, CreateLocalUnnamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create(10);
    EXPECT_THAT(semaphore.has_error(), Eq(false));
}

TEST_F(SemaphoreCreate_test, OpenNamedSemaphore)
{
    auto semaphore = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR, 10);
    auto semaphore2 = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR);
    EXPECT_THAT(semaphore.has_error(), Eq(false));
    EXPECT_THAT(semaphore2.has_error(), Eq(false));
}

TEST_F(SemaphoreCreate_test, OpenNonExistingNamedSemaphore)
{
    auto semaphore2 = iox::posix::Semaphore::create("/fuuSem", S_IRUSR | S_IWUSR);
    EXPECT_THAT(semaphore2.has_error(), Eq(true));
}

TEST_P(Semaphore_test, PostIncreasesSemaphoreValue)
{
    for (int i = 0; i < 12; ++i)
        sut->post();

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(12));
}

TEST_P(Semaphore_test, WaitDecreasesSemaphoreValue)
{
    for (int i = 0; i < 18; ++i)
        sut->post();
    for (int i = 0; i < 7; ++i)
        sut->wait();

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(11));
}

TEST_P(Semaphore_test, SuccessfulTryWaitDecreasesSemaphoreValue)
{
    for (int i = 0; i < 15; ++i)
        sut->post();
    for (int i = 0; i < 9; ++i)
        ASSERT_THAT(sut->tryWait(), Eq(true));

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(6));
}

TEST_P(Semaphore_test, FailingTryWaitDoesNotChangeSemaphoreValue)
{
    for (int i = 0; i < 4; ++i)
        ASSERT_THAT(sut->tryWait(), Eq(false));

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(0));
}

TEST_P(Semaphore_test, SuccessfulTimedWaitDecreasesSemaphoreValue)
{
    for (int i = 0; i < 19; ++i)
        sut->post();

    for (int i = 0; i < 12; ++i)
    {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        constexpr long TWO_MILLISECONDS{2000000};
        ts.tv_nsec += TWO_MILLISECONDS;
        ASSERT_THAT(sut->timedWait(&ts, false), Eq(true));
    }

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(7));
}

TEST_P(Semaphore_test, FailingTimedWaitDoesNotChangeSemaphoreValue)
{
    for (int i = 0; i < 4; ++i)
    {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        constexpr long TWO_MICROSECONDS{2000};
        ts.tv_nsec += TWO_MICROSECONDS;
        ASSERT_THAT(sut->timedWait(&ts, false), Eq(false));
    }

    int value;
    ASSERT_THAT(sut->getValue(value), Eq(true));
    EXPECT_THAT(value, Eq(0));
}

TEST_P(Semaphore_test, TryWaitAfterPostIsSuccessful)
{
    sut->post();
    EXPECT_THAT(sut->tryWait(), Eq(true));
}

TEST_P(Semaphore_test, TryWaitWithNoPostIsNotSuccessful)
{
    sut->post();
    EXPECT_THAT(sut->tryWait(), Eq(true));
}

TEST_P(Semaphore_test, WaitValidAfterPostIsNonBlocking)
{
    sut->post();
    // this call should not block and should be successful
    EXPECT_THAT(sut->wait(), Eq(true));
}

TEST_P(Semaphore_test, WaitIsBlocking)
{
    std::atomic<int> counter{0};
    std::thread t1([&] {
        syncSemaphore->wait();
        sut->post();
        syncSemaphore->wait();
        counter++;
        sut->post();
    });

    EXPECT_THAT(counter.load(), Eq(0));

    syncSemaphore->post();
    sut->wait();
    EXPECT_THAT(counter.load(), Eq(0));

    syncSemaphore->post();
    sut->wait();
    EXPECT_THAT(counter.load(), Eq(1));

    t1.join();
}

TEST_P(Semaphore_test, MoveAssignment)
{
    iox::posix::Semaphore b;
    {
        b = std::move(*sut);
        EXPECT_THAT(sut->post(), Eq(false));
    }

    EXPECT_THAT(b.post(), Eq(true));
}

TEST_P(Semaphore_test, MoveCTor)
{
    iox::posix::Semaphore b(std::move(*sut));

    EXPECT_THAT(b.post(), Eq(true));
    EXPECT_THAT(sut->post(), Eq(false));
}

TEST_P(Semaphore_test, TimedWaitWithTimeout)
{
    std::atomic<bool> timedWaitFinish{false};

    std::thread t([&] {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        constexpr long TEN_MILLISECONDS{10000000};
        ts.tv_nsec += TEN_MILLISECONDS;
        syncSemaphore->post();
        sut->wait();
        EXPECT_THAT(sut->timedWait(&ts, false), Eq(false));
        timedWaitFinish.store(true);
    });

    syncSemaphore->wait();
    sut->post();
    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    EXPECT_THAT(timedWaitFinish.load(), Eq(false));

    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    EXPECT_THAT(timedWaitFinish.load(), Eq(true));

    t.join();
}

TEST_P(Semaphore_test, TimedWaitWithoutTimeout)
{
    std::atomic<bool> timedWaitFinish{false};

    std::thread t([&] {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        constexpr long TEN_MILLISECONDS{10000000};
        ts.tv_nsec += TEN_MILLISECONDS;
        syncSemaphore->post();
        sut->wait();
        EXPECT_THAT(sut->timedWait(&ts, false), Eq(true));
        timedWaitFinish.store(true);
    });

    syncSemaphore->wait();
    sut->post();
    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    EXPECT_THAT(timedWaitFinish.load(), Eq(false));

    sut->post();
    std::this_thread::yield();
    std::this_thread::sleep_for(std::chrono::milliseconds(2));
    EXPECT_THAT(timedWaitFinish.load(), Eq(true));

    t.join();
}

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DAVEXCEPTION_HXX_
#define _DAVEXCEPTION_HXX_

#include <config_lgpl.h>
#include <rtl/ustring.hxx>

namespace webdav_ucp
{

// HTTP/WebDAV status codes

const sal_uInt16 SC_NONE                             = 0;

// 1xx (Informational - no errors)
const sal_uInt16 SC_CONTINUE                         = 100;
const sal_uInt16 SC_SWITCHING_PROTOCOLS              = 101;
// DAV extensions
const sal_uInt16 SC_PROCESSING                       = 102;

//2xx (Successful - no errors)
const sal_uInt16 SC_OK                               = 200;
const sal_uInt16 SC_CREATED                          = 201;
const sal_uInt16 SC_ACCEPTED                         = 202;
const sal_uInt16 SC_NON_AUTHORITATIVE_INFORMATION    = 203;
const sal_uInt16 SC_NO_CONTENT                       = 204;
const sal_uInt16 SC_RESET_CONTENT                    = 205;
const sal_uInt16 SC_PARTIAL_CONTENT                  = 206;
// DAV extensions
const sal_uInt16 SC_MULTISTATUS                      = 207;

//3xx (Redirection)
const sal_uInt16 SC_MULTIPLE_CHOICES                 = 300;
const sal_uInt16 SC_MOVED_PERMANENTLY                = 301;
const sal_uInt16 SC_MOVED_TEMPORARILY                = 302;
const sal_uInt16 SC_SEE_OTHER                        = 303;
const sal_uInt16 SC_NOT_MODIFIED                     = 304;
const sal_uInt16 SC_USE_PROXY                        = 305;
const sal_uInt16 SC_TEMPORARY_REDIRECT               = 307;

//4xx (Client error)
const sal_uInt16 SC_BAD_REQUEST                      = 400;
const sal_uInt16 SC_UNAUTHORIZED                     = 401;
const sal_uInt16 SC_PAYMENT_REQUIRED                 = 402;
const sal_uInt16 SC_FORBIDDEN                        = 403;
const sal_uInt16 SC_NOT_FOUND                        = 404;
const sal_uInt16 SC_METHOD_NOT_ALLOWED               = 405;
const sal_uInt16 SC_NOT_ACCEPTABLE                   = 406;
const sal_uInt16 SC_PROXY_AUTHENTICATION_REQUIRED    = 407;
const sal_uInt16 SC_REQUEST_TIMEOUT                  = 408;
const sal_uInt16 SC_CONFLICT                         = 409;
const sal_uInt16 SC_GONE                             = 410;
const sal_uInt16 SC_LENGTH_REQUIRED                  = 411;
const sal_uInt16 SC_PRECONDITION_FAILED              = 412;
const sal_uInt16 SC_REQUEST_ENTITY_TOO_LARGE         = 413;
const sal_uInt16 SC_REQUEST_URI_TOO_LONG             = 414;
const sal_uInt16 SC_UNSUPPORTED_MEDIA_TYPE           = 415;
const sal_uInt16 SC_REQUESTED_RANGE_NOT_SATISFIABLE  = 416;
const sal_uInt16 SC_EXPECTATION_FAILED               = 417;
// DAV extensions
const sal_uInt16 SC_UNPROCESSABLE_ENTITY             = 422;
const sal_uInt16 SC_LOCKED                           = 423;
const sal_uInt16 SC_FAILED_DEPENDENCY                = 424;

//5xx (Server error)
const sal_uInt16 SC_INTERNAL_SERVER_ERROR            = 500;
const sal_uInt16 SC_NOT_IMPLEMENTED                  = 501;
const sal_uInt16 SC_BAD_GATEWAY                      = 502;
const sal_uInt16 SC_SERVICE_UNAVAILABLE              = 503;
const sal_uInt16 SC_GATEWAY_TIMEOUT                  = 504;
const sal_uInt16 SC_HTTP_VERSION_NOT_SUPPORTED       = 505;
// DAV extensions
const sal_uInt16 SC_INSUFFICIENT_STORAGE             = 507;

class DAVException : std::exception
{
    public:
        enum ExceptionCode {
            DAV_HTTP_ERROR = 0, // Generic error,
                                // mData = server error message,
                                // mStatusCode = HTTP status code
            DAV_HTTP_LOOKUP,    // Name lookup failed,
                                // mData = server[:port]
            DAV_HTTP_AUTH,      // User authentication failed on server,
                                // mData = server[:port]
            DAV_HTTP_AUTHPROXY, // User authentication failed on proxy,
                                // mData = proxy server[:port]
            DAV_HTTP_CONNECT,   // Could not connect to server,
                                // mData = server[:port]
            DAV_HTTP_TIMEOUT,   // Connection timed out
                                // mData = server[:port]
            DAV_HTTP_FAILED,    // The precondition failed
                                // mData = server[:port]
            DAV_HTTP_RETRY,     // Retry request
                                // mData = server[:port]
            DAV_HTTP_REDIRECT,  // Request was redirected,
                                // mData = new URL
            DAV_SESSION_CREATE, // session creation error,
                                // mData = server[:port]
            DAV_INVALID_ARG,    // invalid argument

            DAV_LOCK_EXPIRED,   // DAV lock expired

            DAV_NOT_LOCKED,     // not locked

            DAV_LOCKED_SELF,    // locked by this OOo session

            DAV_LOCKED          // locked by third party
        };

    private:
        ExceptionCode   mExceptionCode;
        OUString   mData;
        sal_uInt16      mStatusCode;

    public:
         DAVException( ExceptionCode inExceptionCode ) :
            mExceptionCode( inExceptionCode ), mStatusCode( SC_NONE ) {};
         DAVException( ExceptionCode inExceptionCode,
                       const OUString & rData ) :
            mExceptionCode( inExceptionCode ), mData( rData ),
            mStatusCode( SC_NONE ) {};
         DAVException( ExceptionCode inExceptionCode,
                       const OUString & rData,
                       sal_uInt16 nStatusCode ) :
            mExceptionCode( inExceptionCode ), mData( rData ),
            mStatusCode( nStatusCode ) {};
        ~DAVException( ) {};

    const ExceptionCode & getError() const { return mExceptionCode; }
    const OUString & getData() const  { return mData; }
    sal_uInt16 getStatus() const { return mStatusCode; }
};

} // namespace webdav_ucp

#endif // _DAVEXCEPTION_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: looser throw spec<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DAVEXCEPTION_HXX_
#define _DAVEXCEPTION_HXX_

#include <config_lgpl.h>
#include <rtl/ustring.hxx>

namespace webdav_ucp
{

// HTTP/WebDAV status codes

const sal_uInt16 SC_NONE                             = 0;

// 1xx (Informational - no errors)
const sal_uInt16 SC_CONTINUE                         = 100;
const sal_uInt16 SC_SWITCHING_PROTOCOLS              = 101;
// DAV extensions
const sal_uInt16 SC_PROCESSING                       = 102;

//2xx (Successful - no errors)
const sal_uInt16 SC_OK                               = 200;
const sal_uInt16 SC_CREATED                          = 201;
const sal_uInt16 SC_ACCEPTED                         = 202;
const sal_uInt16 SC_NON_AUTHORITATIVE_INFORMATION    = 203;
const sal_uInt16 SC_NO_CONTENT                       = 204;
const sal_uInt16 SC_RESET_CONTENT                    = 205;
const sal_uInt16 SC_PARTIAL_CONTENT                  = 206;
// DAV extensions
const sal_uInt16 SC_MULTISTATUS                      = 207;

//3xx (Redirection)
const sal_uInt16 SC_MULTIPLE_CHOICES                 = 300;
const sal_uInt16 SC_MOVED_PERMANENTLY                = 301;
const sal_uInt16 SC_MOVED_TEMPORARILY                = 302;
const sal_uInt16 SC_SEE_OTHER                        = 303;
const sal_uInt16 SC_NOT_MODIFIED                     = 304;
const sal_uInt16 SC_USE_PROXY                        = 305;
const sal_uInt16 SC_TEMPORARY_REDIRECT               = 307;

//4xx (Client error)
const sal_uInt16 SC_BAD_REQUEST                      = 400;
const sal_uInt16 SC_UNAUTHORIZED                     = 401;
const sal_uInt16 SC_PAYMENT_REQUIRED                 = 402;
const sal_uInt16 SC_FORBIDDEN                        = 403;
const sal_uInt16 SC_NOT_FOUND                        = 404;
const sal_uInt16 SC_METHOD_NOT_ALLOWED               = 405;
const sal_uInt16 SC_NOT_ACCEPTABLE                   = 406;
const sal_uInt16 SC_PROXY_AUTHENTICATION_REQUIRED    = 407;
const sal_uInt16 SC_REQUEST_TIMEOUT                  = 408;
const sal_uInt16 SC_CONFLICT                         = 409;
const sal_uInt16 SC_GONE                             = 410;
const sal_uInt16 SC_LENGTH_REQUIRED                  = 411;
const sal_uInt16 SC_PRECONDITION_FAILED              = 412;
const sal_uInt16 SC_REQUEST_ENTITY_TOO_LARGE         = 413;
const sal_uInt16 SC_REQUEST_URI_TOO_LONG             = 414;
const sal_uInt16 SC_UNSUPPORTED_MEDIA_TYPE           = 415;
const sal_uInt16 SC_REQUESTED_RANGE_NOT_SATISFIABLE  = 416;
const sal_uInt16 SC_EXPECTATION_FAILED               = 417;
// DAV extensions
const sal_uInt16 SC_UNPROCESSABLE_ENTITY             = 422;
const sal_uInt16 SC_LOCKED                           = 423;
const sal_uInt16 SC_FAILED_DEPENDENCY                = 424;

//5xx (Server error)
const sal_uInt16 SC_INTERNAL_SERVER_ERROR            = 500;
const sal_uInt16 SC_NOT_IMPLEMENTED                  = 501;
const sal_uInt16 SC_BAD_GATEWAY                      = 502;
const sal_uInt16 SC_SERVICE_UNAVAILABLE              = 503;
const sal_uInt16 SC_GATEWAY_TIMEOUT                  = 504;
const sal_uInt16 SC_HTTP_VERSION_NOT_SUPPORTED       = 505;
// DAV extensions
const sal_uInt16 SC_INSUFFICIENT_STORAGE             = 507;

class DAVException : std::exception
{
    public:
        enum ExceptionCode {
            DAV_HTTP_ERROR = 0, // Generic error,
                                // mData = server error message,
                                // mStatusCode = HTTP status code
            DAV_HTTP_LOOKUP,    // Name lookup failed,
                                // mData = server[:port]
            DAV_HTTP_AUTH,      // User authentication failed on server,
                                // mData = server[:port]
            DAV_HTTP_AUTHPROXY, // User authentication failed on proxy,
                                // mData = proxy server[:port]
            DAV_HTTP_CONNECT,   // Could not connect to server,
                                // mData = server[:port]
            DAV_HTTP_TIMEOUT,   // Connection timed out
                                // mData = server[:port]
            DAV_HTTP_FAILED,    // The precondition failed
                                // mData = server[:port]
            DAV_HTTP_RETRY,     // Retry request
                                // mData = server[:port]
            DAV_HTTP_REDIRECT,  // Request was redirected,
                                // mData = new URL
            DAV_SESSION_CREATE, // session creation error,
                                // mData = server[:port]
            DAV_INVALID_ARG,    // invalid argument

            DAV_LOCK_EXPIRED,   // DAV lock expired

            DAV_NOT_LOCKED,     // not locked

            DAV_LOCKED_SELF,    // locked by this OOo session

            DAV_LOCKED          // locked by third party
        };

    private:
        ExceptionCode   mExceptionCode;
        OUString   mData;
        sal_uInt16      mStatusCode;

    public:
         DAVException( ExceptionCode inExceptionCode ) :
            mExceptionCode( inExceptionCode ), mStatusCode( SC_NONE ) {};
         DAVException( ExceptionCode inExceptionCode,
                       const OUString & rData ) :
            mExceptionCode( inExceptionCode ), mData( rData ),
            mStatusCode( SC_NONE ) {};
         DAVException( ExceptionCode inExceptionCode,
                       const OUString & rData,
                       sal_uInt16 nStatusCode ) :
            mExceptionCode( inExceptionCode ), mData( rData ),
            mStatusCode( nStatusCode ) {};

    const ExceptionCode & getError() const { return mExceptionCode; }
    const OUString & getData() const  { return mData; }
    sal_uInt16 getStatus() const { return mStatusCode; }
};

} // namespace webdav_ucp

#endif // _DAVEXCEPTION_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before><commit_msg>rhbz#678440: Always include User-Agent to avoid 403 from picky servers<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: systemshell.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 01:42:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"

#ifndef _SYSTEMSHELL_HXX_
#include "systemshell.hxx"
#endif

#include "osl/module.hxx"

const rtl::OUString SYM_ADD_TO_RECENTLY_USED_FILE_LIST = rtl::OUString::createFromAscii("add_to_recently_used_file_list");
const rtl::OUString LIB_RECENT_FILE = rtl::OUString::createFromAscii("librecentfile.so");

namespace SystemShell {

    typedef void (*PFUNC_ADD_TO_RECENTLY_USED_LIST)(const rtl::OUString&, const rtl::OUString&);

    //##############################
    rtl::OUString get_absolute_library_url(const rtl::OUString& /*lib_name*/)
    {
        rtl::OUString url;
        if (osl::Module::getUrlFromAddress(reinterpret_cast<oslGenericFunction>(AddToRecentDocumentList), url))
        {
            sal_Int32 index = url.lastIndexOf('/');
            url = url.copy(0, index + 1);
            url += LIB_RECENT_FILE;
        }
        return url;
    }

    //##############################
    void AddToRecentDocumentList(const rtl::OUString& aFileUrl, const rtl::OUString& aMimeType)
    {
        rtl::OUString librecentfile_url = get_absolute_library_url(LIB_RECENT_FILE);

        if (librecentfile_url.getLength())
        {
            osl::Module module(librecentfile_url);

            if (module.is())
            {
               // convert from reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST>
               // not allowed in gcc 3.3 without permissive.
                PFUNC_ADD_TO_RECENTLY_USED_LIST add_to_recently_used_file_list =
                    reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST>(module.getFunctionSymbol(SYM_ADD_TO_RECENTLY_USED_FILE_LIST));

                if (add_to_recently_used_file_list)
                    add_to_recently_used_file_list(aFileUrl, aMimeType);
            }
        }
    }

} // namespace SystemShell

<commit_msg>INTEGRATION: CWS obr05 (1.7.44); FILE MERGED 2007/06/07 13:46:02 obr 1.7.44.1: #i75190# add support for GtkRecentManager<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: systemshell.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2007-06-19 16:12:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"

#ifndef _SYSTEMSHELL_HXX_
#include "systemshell.hxx"
#endif

#include <comphelper/processfactory.hxx>

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_Hpp_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_URI_XEXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
#endif

#ifndef _COM_SUN_STAR_URI_EXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#include "osl/module.hxx"

using namespace ::com::sun::star;

#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))

const rtl::OUString SYM_ADD_TO_RECENTLY_USED_FILE_LIST = UNISTRING("add_to_recently_used_file_list");
const rtl::OUString LIB_RECENT_FILE = UNISTRING("librecentfile.so");
const rtl::OUString DEFAULT_CONTEXT = UNISTRING("DefaultContext");

void * (* sym_gtk_recent_manager_get_default) () = NULL;
void   (* sym_gtk_recent_manager_add_item) (void *, const char *) = NULL;

// We need to re-encode file urls because osl_getFileURLFromSystemPath converts
// to UTF-8 before encoding non ascii characters, which is not what other apps expect.
static rtl::OUString translateToExternalUrl(const rtl::OUString& internalUrl)
{
    rtl::OUString extUrl;

    uno::Reference< lang::XMultiServiceFactory > sm = comphelper::getProcessServiceFactory();
    if (sm.is())
    {
        uno::Reference< beans::XPropertySet > pset;
        sm->queryInterface( getCppuType( &pset )) >>= pset;
        if (pset.is())
        {
            uno::Reference< uno::XComponentContext > context;
            pset->getPropertyValue(DEFAULT_CONTEXT) >>= context;
            if (context.is())
                extUrl = uri::ExternalUriReferenceTranslator::create(context)->translateToExternal(internalUrl);
        }
    }
    return extUrl;
}

namespace SystemShell {

    typedef void (*PFUNC_ADD_TO_RECENTLY_USED_LIST)(const rtl::OUString&, const rtl::OUString&);

    //##############################
    rtl::OUString get_absolute_library_url(const rtl::OUString& /*lib_name*/)
    {
        rtl::OUString url;
        if (osl::Module::getUrlFromAddress(reinterpret_cast<oslGenericFunction>(AddToRecentDocumentList), url))
        {
            sal_Int32 index = url.lastIndexOf('/');
            url = url.copy(0, index + 1);
            url += LIB_RECENT_FILE;
        }
        return url;
    }

    bool init_recent_manager_api()
    {
        oslModule hDefault;
        if( osl_getModuleHandle( NULL, &hDefault ) )
        {
            sym_gtk_recent_manager_get_default = (void * (*)())
                osl_getAsciiFunctionSymbol(hDefault, "gtk_recent_manager_get_default");
            sym_gtk_recent_manager_add_item = (void (*)(void *, const char *))
                osl_getAsciiFunctionSymbol(hDefault, "gtk_recent_manager_add_item");

        }
        bool ret = (NULL != sym_gtk_recent_manager_get_default) && (NULL != sym_gtk_recent_manager_add_item);
        return ret;
    }

    //##############################
    void AddToRecentDocumentList(const rtl::OUString& aFileUrl, const rtl::OUString& aMimeType)
    {
        static bool bIsRecentManagerPresent = init_recent_manager_api();

        // Convert file URL for external use (see above)
        rtl::OUString externalUrl = translateToExternalUrl(aFileUrl);
        if( 0 == externalUrl.getLength() )
            externalUrl = aFileUrl;

        if( bIsRecentManagerPresent )
        {
            void * recent_manager = sym_gtk_recent_manager_get_default();
            sym_gtk_recent_manager_add_item(recent_manager, rtl::OUStringToOString(aFileUrl, RTL_TEXTENCODING_UTF8).getStr());
        }
        else
        {
            rtl::OUString librecentfile_url = get_absolute_library_url(LIB_RECENT_FILE);

            if (librecentfile_url.getLength())
            {
                osl::Module module(librecentfile_url);

                if (module.is())
                {
                    // convert from reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST>
                    // not allowed in gcc 3.3 without permissive.
                    PFUNC_ADD_TO_RECENTLY_USED_LIST add_to_recently_used_file_list =
                        reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST>(module.getFunctionSymbol(SYM_ADD_TO_RECENTLY_USED_FILE_LIST));

                    if (add_to_recently_used_file_list)
                        add_to_recently_used_file_list(aFileUrl, aMimeType);
                }
            }
        }
    }

} // namespace SystemShell

<|endoftext|>


<commit_before>//
// "$Id: Fl_Font.H 4288 2005-04-16 00:13:17Z mike $"
//
// Font definitions for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2005 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems on the following page:
//
//     http://www.fltk.org/str.php
//

// Two internal fltk data structures:
//
// Fl_Fontdesc: an entry into the fl_font() table.  There is one of these
// for each fltk font number.
//
// Fl_FontSize: a structure for an actual system font, with junk to
// help choose it and info on character sizes.  Each Fl_Fontdesc has a
// linked list of these.  These are created the first time each system
// font/size combination is used.

#ifndef FL_FONT_
#define FL_FONT_

#include <config.h>

#  if USE_XFT
typedef struct _XftFont XftFont;
#  endif // USE_XFT

class Fl_FontSize {
public:
  Fl_FontSize *next;	// linked list for this Fl_Fontdesc
#  ifdef WIN32
  HFONT fid;
  int width[256];
  TEXTMETRIC metr;
  FL_EXPORT Fl_FontSize(const char* fontname, int size);
#  elif defined(__APPLE_QD__)
  FL_EXPORT Fl_FontSize(const char* fontname, int size);
  short font, face, size;
  short ascent, descent;
  short width[256];
  bool knowMetrics;
#  elif defined(__APPLE_QUARTZ__)
  FL_EXPORT Fl_FontSize(const char* fontname, int size);
  char *q_name;
  int size;
  short ascent, descent, q_width;
#  elif USE_XFT
  XftFont* font;
  const char* encoding;
  int size;
  FL_EXPORT Fl_FontSize(const char* xfontname);
#  else
  XFontStruct* font;	// X font information
  FL_EXPORT Fl_FontSize(const char* xfontname);
#  endif
  int minsize;		// smallest point size that should use this
  int maxsize;		// largest point size that should use this
#  if HAVE_GL
  unsigned int listbase;// base of display list, 0 = none
#  endif
  FL_EXPORT ~Fl_FontSize();
};

extern FL_EXPORT Fl_FontSize *fl_fontsize; // the currently selected one

struct Fl_Fontdesc {
  const char *name;
  char fontname[128];	// "Pretty" font name
  Fl_FontSize *first;	// linked list of sizes of this style
#  ifndef WIN32
  char **xlist;		// matched X font names
  int n;		// size of xlist, negative = don't free xlist!
#  endif
};

extern FL_EXPORT Fl_Fontdesc *fl_fonts; // the table

#  ifndef WIN32
// functions for parsing X font names:
FL_EXPORT const char* fl_font_word(const char *p, int n);
FL_EXPORT char *fl_find_fontsize(char *name);
#  endif

#endif

//
// End of "$Id: Fl_Font.H 4288 2005-04-16 00:13:17Z mike $".
//
<commit_msg>Correction include config.h<commit_after>//
// "$Id: Fl_Font.H 4288 2005-04-16 00:13:17Z mike $"
//
// Font definitions for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2005 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems on the following page:
//
//     http://www.fltk.org/str.php
//

// Two internal fltk data structures:
//
// Fl_Fontdesc: an entry into the fl_font() table.  There is one of these
// for each fltk font number.
//
// Fl_FontSize: a structure for an actual system font, with junk to
// help choose it and info on character sizes.  Each Fl_Fontdesc has a
// linked list of these.  These are created the first time each system
// font/size combination is used.

#ifndef FL_FONT_
#define FL_FONT_

/*OTB Modifications: conflict name with OTB/Utilities/ITK/Utilities/nifti/znzlib/config.h*/
/*#include <config.h>
*/
#include "fltk-config.h"

#  if USE_XFT
typedef struct _XftFont XftFont;
#  endif // USE_XFT

class Fl_FontSize {
public:
  Fl_FontSize *next;	// linked list for this Fl_Fontdesc
#  ifdef WIN32
  HFONT fid;
  int width[256];
  TEXTMETRIC metr;
  FL_EXPORT Fl_FontSize(const char* fontname, int size);
#  elif defined(__APPLE_QD__)
  FL_EXPORT Fl_FontSize(const char* fontname, int size);
  short font, face, size;
  short ascent, descent;
  short width[256];
  bool knowMetrics;
#  elif defined(__APPLE_QUARTZ__)
  FL_EXPORT Fl_FontSize(const char* fontname, int size);
  char *q_name;
  int size;
  short ascent, descent, q_width;
#  elif USE_XFT
  XftFont* font;
  const char* encoding;
  int size;
  FL_EXPORT Fl_FontSize(const char* xfontname);
#  else
  XFontStruct* font;	// X font information
  FL_EXPORT Fl_FontSize(const char* xfontname);
#  endif
  int minsize;		// smallest point size that should use this
  int maxsize;		// largest point size that should use this
#  if HAVE_GL
  unsigned int listbase;// base of display list, 0 = none
#  endif
  FL_EXPORT ~Fl_FontSize();
};

extern FL_EXPORT Fl_FontSize *fl_fontsize; // the currently selected one

struct Fl_Fontdesc {
  const char *name;
  char fontname[128];	// "Pretty" font name
  Fl_FontSize *first;	// linked list of sizes of this style
#  ifndef WIN32
  char **xlist;		// matched X font names
  int n;		// size of xlist, negative = don't free xlist!
#  endif
};

extern FL_EXPORT Fl_Fontdesc *fl_fonts; // the table

#  ifndef WIN32
// functions for parsing X font names:
FL_EXPORT const char* fl_font_word(const char *p, int n);
FL_EXPORT char *fl_find_fontsize(char *name);
#  endif

#endif

//
// End of "$Id: Fl_Font.H 4288 2005-04-16 00:13:17Z mike $".
//
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include "cnfformula.h"
#include "dimacsgenerator.h"
#include "ppz.h"
#include "randomsatgenerator.h"

CNFFormula get_file_formula(std::string filename, int k){
  std::ifstream file(filename);
  if(file.is_open()){
    DimacsGenerator dg(file, k);
    return dg.generate_sat();
  }
  throw;
}

CNFFormula get_random_formula(unsigned int n, unsigned int k, unsigned int p){
  RandomSatGenerator rg(n,k,p);
  return rg.generate_formula();
}

int main(int argc, char** argv){
  CNFFormula f;
  bool formula_init = false;
  unsigned int n, k;
  namespace po = boost::program_options;
  po::options_description desc("Options");
  desc.add_options()
    ("help,h", "Print help message")
    ("n,n", po::value<unsigned int>(), "Number of variables")
    ("k,k", po::value<unsigned int>(), "Arity of a clause")
    ("file,f", po::value<std::string>(), "Get formula from file")
    ("random,r", po::value<unsigned int>(), "Get random formula with given random range")
    ("max,m", "Get maximum formula from a set of assignments")
    ("assignment,a", po::value<std::vector<std::string> >(), "List of assignments for -m")
    ("interactive,i", "Interactive mode")
    ("bruteforce", "Solve by bruteforce - warning, all case exponential time algorithm!")
    ("ppzfull", "Solve by full ppz - warning, all case superexponential time algorithm!")
    ("ppzfulloracle", "Solve by full ppz with oracle - warning, all case superexponential time algorithm!")
    ("ppzrandom", "Solve by random ppz - warning, worst case exponential time algorithm!");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  if(vm.count("help")){
    std::cout << desc << std::endl;
  }
  else if(vm.count("interactive")){
    std::cout << "interactive mode, yo" << std::endl;
  }
  else{
    if(vm.count("file")){
      if(!vm.count("k")){
        std::cerr << "Need to provide k when providing a file" << std::endl;
      }
      std::string filename = vm["file"].as<std::string>();
      k = vm["k"].as<unsigned int>();
      f = get_file_formula(filename, k);
      formula_init = true;
    }
    else if(!vm.count("n") || !vm.count("k")){
      std::cerr << "Need to provide n and k if not providing a file" << std::endl;
    }
    if(vm.count("random")){
      n = vm["n"].as<unsigned int>();
      k = vm["k"].as<unsigned int>();
      unsigned int p = vm["random"].as<unsigned int>();
      f = get_random_formula(n, k, p);
      formula_init = true;
    }
    else if(vm.count("max")){
      if(!vm.count("assignment")){
        std::cerr << "Need to provide assignments for max formulas (or -a none for empty formula)" << std::endl;
      }
//      f = get_max_formula(n, k, assignments);
      formula_init = true;
    }
  }
  if(!formula_init){
    std::cerr << "Need to provide a formula." << std::endl;
    return -1;
  }
  if(vm.count("bruteforce")){
    CNFFormula f2 = f;
    f2.bruteforce_solve_sat();
    std::cout << f2;
  }
  if(vm.count("ppzfull") || vm.count("ppzfulloracle")){
    CNFFormula f2 = f;
    Ppz ppz(&f);

    if(vm.count("ppzfull")){
      ppz.full_solve_ppz();
    }
    if(vm.count("ppzfulloracle")){
      ppz.full_solve_ppz(true);
    }
    std::cout << ppz << std::endl;
  }
  if(vm.count("ppzrandom")){
    CNFFormula f2 = f;
    Ppz ppz(&f);
    double limit = pow(2, n-1.0/k);
    ppz.random_solve_ppz(limit);
  }
}
<commit_msg>changed message for interactive (not implem yet)<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include "cnfformula.h"
#include "dimacsgenerator.h"
#include "ppz.h"
#include "randomsatgenerator.h"

CNFFormula get_file_formula(std::string filename, int k){
  std::ifstream file(filename);
  if(file.is_open()){
    DimacsGenerator dg(file, k);
    return dg.generate_sat();
  }
  throw;
}

CNFFormula get_random_formula(unsigned int n, unsigned int k, unsigned int p){
  RandomSatGenerator rg(n,k,p);
  return rg.generate_formula();
}

int main(int argc, char** argv){
  CNFFormula f;
  bool formula_init = false;
  unsigned int n, k;
  namespace po = boost::program_options;
  po::options_description desc("Options");
  desc.add_options()
    ("help,h", "Print help message")
    ("n,n", po::value<unsigned int>(), "Number of variables")
    ("k,k", po::value<unsigned int>(), "Arity of a clause")
    ("file,f", po::value<std::string>(), "Get formula from file")
    ("random,r", po::value<unsigned int>(), "Get random formula with given random range")
    ("max,m", "Get maximum formula from a set of assignments")
    ("assignment,a", po::value<std::vector<std::string> >(), "List of assignments for -m")
    ("interactive,i", "Interactive mode")
    ("bruteforce", "Solve by bruteforce - warning, all case exponential time algorithm!")
    ("ppzfull", "Solve by full ppz - warning, all case superexponential time algorithm!")
    ("ppzfulloracle", "Solve by full ppz with oracle - warning, all case superexponential time algorithm!")
    ("ppzrandom", "Solve by random ppz - warning, worst case exponential time algorithm!");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  if(vm.count("help")){
    std::cout << desc << std::endl;
  }
  else if(vm.count("interactive")){
    std::cout << "Interactive mode not implemented yet." << std::endl;
    return -1;
  }
  else{
    if(vm.count("file")){
      if(!vm.count("k")){
        std::cerr << "Need to provide k when providing a file" << std::endl;
      }
      std::string filename = vm["file"].as<std::string>();
      k = vm["k"].as<unsigned int>();
      f = get_file_formula(filename, k);
      formula_init = true;
    }
    else if(!vm.count("n") || !vm.count("k")){
      std::cerr << "Need to provide n and k if not providing a file" << std::endl;
    }
    if(vm.count("random")){
      n = vm["n"].as<unsigned int>();
      k = vm["k"].as<unsigned int>();
      unsigned int p = vm["random"].as<unsigned int>();
      f = get_random_formula(n, k, p);
      formula_init = true;
    }
    else if(vm.count("max")){
      if(!vm.count("assignment")){
        std::cerr << "Need to provide assignments for max formulas (or -a none for empty formula)" << std::endl;
      }
//      f = get_max_formula(n, k, assignments);
      formula_init = true;
    }
  }
  if(!formula_init){
    std::cerr << "Need to provide a formula." << std::endl;
    return -1;
  }
  if(vm.count("bruteforce")){
    CNFFormula f2 = f;
    f2.bruteforce_solve_sat();
    std::cout << f2;
  }
  if(vm.count("ppzfull") || vm.count("ppzfulloracle")){
    CNFFormula f2 = f;
    Ppz ppz(&f);

    if(vm.count("ppzfull")){
      ppz.full_solve_ppz();
    }
    if(vm.count("ppzfulloracle")){
      ppz.full_solve_ppz(true);
    }
    std::cout << ppz << std::endl;
  }
  if(vm.count("ppzrandom")){
    CNFFormula f2 = f;
    Ppz ppz(&f);
    double limit = pow(2, n-1.0/k);
    ppz.random_solve_ppz(limit);
  }
}
<|endoftext|>


<commit_before>/*
**
** Author(s):
**  - Pierre ROULLON <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2012, 2013 Aldebaran Robotics
** See COPYING for the license
*/

#include <stdexcept>

#include <qi/log.hpp>
#include <qi/api.hpp>
#include <qi/anyfunction.hpp>
#include <qi/session.hpp>

#include <jni.h>
#include <jnitools.hpp>
#include <session_jni.hpp>
#include <object_jni.hpp>
#include <callbridge.hpp>

#include <qi/messaging/clientauthenticator.hpp>
#include <qi/messaging/clientauthenticatorfactory.hpp>

qiLogCategory("qimessaging.jni");

jlong Java_com_aldebaran_qi_Session_qiSessionCreate()
{
  qi::Session *session = new qi::Session();

  return (jlong) session;
}

void Java_com_aldebaran_qi_Session_qiSessionDestroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pSession)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);
  delete s;
}

jboolean Java_com_aldebaran_qi_Session_qiSessionIsConnected(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pSession)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);

  return (jboolean) s->isConnected();
}

static void adaptFuture(qi::Future<void> f, qi::Promise<qi::AnyValue> p)
{
  if (f.hasError())
    p.setError(f.error());
  else
    p.setValue(qi::AnyValue(qi::typeOf<void>()));
}

jlong Java_com_aldebaran_qi_Session_qiSessionConnect(JNIEnv *env, jobject QI_UNUSED(obj), jlong pSession, jstring jurl)
{
  if (pSession == 0)
  {
    throwJavaError(env, "Given qi::Session doesn't exists (pointer null).");
    return 0;
  }

  // After this function return, callbacks are going to be set on new created Future.
  // Save the JVM pointer here to avoid big issues when callbacks will be called.
  JVM(env);
  qi::Future<qi::AnyValue> *fref = new qi::Future<qi::AnyValue>();
  qi::Promise<qi::AnyValue> promise;
  *fref = promise.future();
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);
  try
  {
    qi::Future<void> f = s->connect(qi::jni::toString(jurl));
    f.connect(adaptFuture, _1, promise);
  }
  catch (const std::exception& e)
  {
    promise.setError(e.what());
  }
  return (jlong) fref;
}

void Java_com_aldebaran_qi_Session_qiSessionClose(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pSession)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);

  s->close();
}

jobject   Java_com_aldebaran_qi_Session_service(JNIEnv* env, jobject QI_UNUSED(obj), jlong pSession, jstring jname)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);
  std::string serviceName = qi::jni::toString(jname);

  qi::AnyObject *obj = new qi::AnyObject();
  jobject proxy = 0;

  try
  {
    *obj = s->service(serviceName);
    JNIObject jniProxy(obj);
    return jniProxy.object();
  }
  catch (std::runtime_error &e)
  {
    delete obj;
    throwJavaError(env, e.what());
    return proxy;
  }
}

jint  Java_com_aldebaran_qi_Session_registerService(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pSession, jstring jname, jobject object)
{
  qi::Session*    session = reinterpret_cast<qi::Session*>(pSession);
  std::string     name    = qi::jni::toString(jname);
  JNIObject obj(object);
  jint ret = 0;

  try
  {
    ret = session->registerService(name, obj.objectPtr());
  }
  catch (std::runtime_error &e)
  {
    qiLogError() << "Throwing exception : " << e.what();
    throwJavaError(env, e.what());
    return 0;
  }

  if (ret <= 0)
  {
    throwJavaError(env, "Cannot register service");
    return 0;
  }

  return ret;
}

void  Java_com_aldebaran_qi_Session_unregisterService(JNIEnv *env, jobject obj, jlong pSession, jint serviceId)
{
  qi::Session*    session = reinterpret_cast<qi::Session*>(pSession);
  unsigned int    id = static_cast<unsigned int>(serviceId);

  session->unregisterService(id);
}

void      Java_com_aldebaran_qi_Session_onDisconnected(JNIEnv *env, jobject jobj, jlong pSession, jstring jcallbackName, jobject jobjectInstance)
{
  extern MethodInfoHandler gInfoHandler;
  qi::Session*    session = reinterpret_cast<qi::Session*>(pSession);
  std::string     callbackName = qi::jni::toString(jcallbackName);
  std::string     signature;
  qi_method_info*            data;

  // Create a new global reference on object instance.
  // jobject structure are local reference and are destroyed when returning to JVM
  jobjectInstance = env->NewGlobalRef(jobjectInstance);

  // Create a struct holding a jobject instance, jmethodId id and other needed thing for callback
  // Pass it to void * data to register_method
  signature = callbackName + "::(s)";
  data = new qi_method_info(jobjectInstance, signature, jobj);
  gInfoHandler.push(data);

  session->disconnected.connect(
      qi::AnyFunction::fromDynamicFunction(
          boost::bind(&event_callback_to_java, (void*) data, _1)));
}

class Java_ClientAuthenticator : public qi::ClientAuthenticator
{
public:
  Java_ClientAuthenticator(JNIEnv* env, jobject object)
  {
    env->GetJavaVM(&_jvm);
    _jobject = env->NewGlobalRef(object);
  }

  qi::CapabilityMap initialAuthData()
  {
    JNIEnv* env = nullptr;
#ifndef ANDROID
    _jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#else
    _jvm->AttachCurrentThread(&env, nullptr);
#endif
    jobject ca = qi::jni::Call<jobject>::invoke(env, _jobject, "initialAuthData", "()Ljava/util/Map;");
    return JNI_JavaMaptoMap(env, ca);
  }

  qi::CapabilityMap _processAuth(const qi::CapabilityMap &authData)
  {
    JNIEnv* env = nullptr;
#ifndef ANDROID
    _jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#else
    _jvm->AttachCurrentThread(&env, nullptr);
#endif
    jobject jmap = JNI_MapToJavaMap(env, authData);
    jobject ca = qi::jni::Call<jobject>::invoke(env, _jobject, "_processAuth", "(Ljava/util/Map;)Ljava/util/Map;", jmap);
    return JNI_JavaMaptoMap(env, ca);
  }

private:
  JavaVM* _jvm;
  jobject _jobject;

  static qi::CapabilityMap JNI_JavaMaptoMap(JNIEnv* env, jobject jmap)
  {
    qi::CapabilityMap result;

    jobject set = qi::jni::Call<jobject>::invoke(env, jmap, "entrySet", "()Ljava/util/Set;");
    jobject it = qi::jni::Call<jobject>::invoke(env, set, "iterator", "()Ljava/util/Iterator;");

    while (qi::jni::Call<jboolean>::invoke(env, it, "hasNext", "()Z"))
    {
      jobject entry = qi::jni::Call<jobject>::invoke(env, it, "next", "()Ljava/lang/Object;");
      jstring key = (jstring) qi::jni::Call<jobject>::invoke(env, entry, "getKey", "()Ljava/lang/Object;");
      std::string k = env->GetStringUTFChars(key, nullptr);

      // FIXME: should implement this for jobject and not only jstring
      qiLogWarning() << "FIXME: only jstring are supported";
      jobject value = qi::jni::Call<jobject>::invoke(env, entry, "getValue", "()Ljava/lang/Object;");
      std::string v2 = env->GetStringUTFChars((jstring) value, nullptr);
      qi::AnyValue v = qi::AnyValue::from(v2);

      result[k] = v;
    }

    return result;
  }

  static jobject JNI_MapToJavaMap(JNIEnv* env, qi::CapabilityMap map)
  {
    jclass mapClass = env->FindClass("java/util/HashMap");
    jmethodID init = env->GetMethodID(mapClass, "<init>", "()V");
    jobject result = env->NewObject(mapClass, init);

    qi::CapabilityMap::const_iterator it;
    for (it = map.begin(); it != map.end(); ++it)
    {
      std::string key = it->first;
      jstring k = env->NewStringUTF(key.c_str());

      const qi::AnyValue& val = it->second;
      const std::string sig = val.signature().toString();
      jobject v;

      if (sig == "I")
      {
        jclass cls = env->FindClass("java/lang/Integer");
        jmethodID mid = env->GetMethodID(cls, "<init>", "(I)V");
        v = env->NewObject(cls, mid, val.toUInt());
      }
      else if (sig == "s")
      {
        v = (jobject) env->NewStringUTF(val.toString().c_str());
      }
      else
      {
        qiLogError() << "sig " << sig << " not supported, skipping...";
        continue;
      }

      qi::jni::Call<void>::invoke(env, result, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", k, v);
    }

    return result;
  }
};

class Java_ClientAuthenticatorFactory : public qi::ClientAuthenticatorFactory
{
public:
  Java_ClientAuthenticatorFactory(JNIEnv* env, jobject object)
  {
    env->GetJavaVM(&_jvm);
    _jobject = env->NewGlobalRef(object);
  }

  qi::ClientAuthenticatorPtr newAuthenticator()
  {
    JNIEnv* env = nullptr;
#ifndef ANDROID
    _jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#else
    _jvm->AttachCurrentThread(&env, nullptr);
#endif
    jobject ca = qi::jni::Call<jobject>::invoke(env, _jobject, "newAuthenticator", "()Lcom/aldebaran/qi/ClientAuthenticator;");
    return boost::make_shared<Java_ClientAuthenticator>(env, ca);
  }

private:
  JavaVM* _jvm;
  jobject _jobject;
};

void      Java_com_aldebaran_qi_Session_setClientAuthenticatorFactory(JNIEnv* env, jobject obj, jlong pSession, jobject object)
{
  qi::Session* session = reinterpret_cast<qi::Session*>(pSession);
  session->setClientAuthenticatorFactory(boost::make_shared<Java_ClientAuthenticatorFactory>(env, object));
}
<commit_msg>Fix JNI call to HashMap.put()<commit_after>/*
**
** Author(s):
**  - Pierre ROULLON <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2012, 2013 Aldebaran Robotics
** See COPYING for the license
*/

#include <stdexcept>

#include <qi/log.hpp>
#include <qi/api.hpp>
#include <qi/anyfunction.hpp>
#include <qi/session.hpp>

#include <jni.h>
#include <jnitools.hpp>
#include <session_jni.hpp>
#include <object_jni.hpp>
#include <callbridge.hpp>

#include <qi/messaging/clientauthenticator.hpp>
#include <qi/messaging/clientauthenticatorfactory.hpp>

qiLogCategory("qimessaging.jni");

jlong Java_com_aldebaran_qi_Session_qiSessionCreate()
{
  qi::Session *session = new qi::Session();

  return (jlong) session;
}

void Java_com_aldebaran_qi_Session_qiSessionDestroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pSession)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);
  delete s;
}

jboolean Java_com_aldebaran_qi_Session_qiSessionIsConnected(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pSession)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);

  return (jboolean) s->isConnected();
}

static void adaptFuture(qi::Future<void> f, qi::Promise<qi::AnyValue> p)
{
  if (f.hasError())
    p.setError(f.error());
  else
    p.setValue(qi::AnyValue(qi::typeOf<void>()));
}

jlong Java_com_aldebaran_qi_Session_qiSessionConnect(JNIEnv *env, jobject QI_UNUSED(obj), jlong pSession, jstring jurl)
{
  if (pSession == 0)
  {
    throwJavaError(env, "Given qi::Session doesn't exists (pointer null).");
    return 0;
  }

  // After this function return, callbacks are going to be set on new created Future.
  // Save the JVM pointer here to avoid big issues when callbacks will be called.
  JVM(env);
  qi::Future<qi::AnyValue> *fref = new qi::Future<qi::AnyValue>();
  qi::Promise<qi::AnyValue> promise;
  *fref = promise.future();
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);
  try
  {
    qi::Future<void> f = s->connect(qi::jni::toString(jurl));
    f.connect(adaptFuture, _1, promise);
  }
  catch (const std::exception& e)
  {
    promise.setError(e.what());
  }
  return (jlong) fref;
}

void Java_com_aldebaran_qi_Session_qiSessionClose(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pSession)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);

  s->close();
}

jobject   Java_com_aldebaran_qi_Session_service(JNIEnv* env, jobject QI_UNUSED(obj), jlong pSession, jstring jname)
{
  qi::Session *s = reinterpret_cast<qi::Session*>(pSession);
  std::string serviceName = qi::jni::toString(jname);

  qi::AnyObject *obj = new qi::AnyObject();
  jobject proxy = 0;

  try
  {
    *obj = s->service(serviceName);
    JNIObject jniProxy(obj);
    return jniProxy.object();
  }
  catch (std::runtime_error &e)
  {
    delete obj;
    throwJavaError(env, e.what());
    return proxy;
  }
}

jint  Java_com_aldebaran_qi_Session_registerService(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pSession, jstring jname, jobject object)
{
  qi::Session*    session = reinterpret_cast<qi::Session*>(pSession);
  std::string     name    = qi::jni::toString(jname);
  JNIObject obj(object);
  jint ret = 0;

  try
  {
    ret = session->registerService(name, obj.objectPtr());
  }
  catch (std::runtime_error &e)
  {
    qiLogError() << "Throwing exception : " << e.what();
    throwJavaError(env, e.what());
    return 0;
  }

  if (ret <= 0)
  {
    throwJavaError(env, "Cannot register service");
    return 0;
  }

  return ret;
}

void  Java_com_aldebaran_qi_Session_unregisterService(JNIEnv *env, jobject obj, jlong pSession, jint serviceId)
{
  qi::Session*    session = reinterpret_cast<qi::Session*>(pSession);
  unsigned int    id = static_cast<unsigned int>(serviceId);

  session->unregisterService(id);
}

void      Java_com_aldebaran_qi_Session_onDisconnected(JNIEnv *env, jobject jobj, jlong pSession, jstring jcallbackName, jobject jobjectInstance)
{
  extern MethodInfoHandler gInfoHandler;
  qi::Session*    session = reinterpret_cast<qi::Session*>(pSession);
  std::string     callbackName = qi::jni::toString(jcallbackName);
  std::string     signature;
  qi_method_info*            data;

  // Create a new global reference on object instance.
  // jobject structure are local reference and are destroyed when returning to JVM
  jobjectInstance = env->NewGlobalRef(jobjectInstance);

  // Create a struct holding a jobject instance, jmethodId id and other needed thing for callback
  // Pass it to void * data to register_method
  signature = callbackName + "::(s)";
  data = new qi_method_info(jobjectInstance, signature, jobj);
  gInfoHandler.push(data);

  session->disconnected.connect(
      qi::AnyFunction::fromDynamicFunction(
          boost::bind(&event_callback_to_java, (void*) data, _1)));
}

class Java_ClientAuthenticator : public qi::ClientAuthenticator
{
public:
  Java_ClientAuthenticator(JNIEnv* env, jobject object)
  {
    env->GetJavaVM(&_jvm);
    _jobject = env->NewGlobalRef(object);
  }

  qi::CapabilityMap initialAuthData()
  {
    JNIEnv* env = nullptr;
#ifndef ANDROID
    _jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#else
    _jvm->AttachCurrentThread(&env, nullptr);
#endif
    jobject ca = qi::jni::Call<jobject>::invoke(env, _jobject, "initialAuthData", "()Ljava/util/Map;");
    return JNI_JavaMaptoMap(env, ca);
  }

  qi::CapabilityMap _processAuth(const qi::CapabilityMap &authData)
  {
    JNIEnv* env = nullptr;
#ifndef ANDROID
    _jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#else
    _jvm->AttachCurrentThread(&env, nullptr);
#endif
    jobject jmap = JNI_MapToJavaMap(env, authData);
    jobject ca = qi::jni::Call<jobject>::invoke(env, _jobject, "_processAuth", "(Ljava/util/Map;)Ljava/util/Map;", jmap);
    return JNI_JavaMaptoMap(env, ca);
  }

private:
  JavaVM* _jvm;
  jobject _jobject;

  static qi::CapabilityMap JNI_JavaMaptoMap(JNIEnv* env, jobject jmap)
  {
    qi::CapabilityMap result;

    jobject set = qi::jni::Call<jobject>::invoke(env, jmap, "entrySet", "()Ljava/util/Set;");
    jobject it = qi::jni::Call<jobject>::invoke(env, set, "iterator", "()Ljava/util/Iterator;");

    while (qi::jni::Call<jboolean>::invoke(env, it, "hasNext", "()Z"))
    {
      jobject entry = qi::jni::Call<jobject>::invoke(env, it, "next", "()Ljava/lang/Object;");
      jstring key = (jstring) qi::jni::Call<jobject>::invoke(env, entry, "getKey", "()Ljava/lang/Object;");
      std::string k = env->GetStringUTFChars(key, nullptr);

      // FIXME: should implement this for jobject and not only jstring
      qiLogWarning() << "FIXME: only jstring are supported";
      jobject value = qi::jni::Call<jobject>::invoke(env, entry, "getValue", "()Ljava/lang/Object;");
      std::string v2 = env->GetStringUTFChars((jstring) value, nullptr);
      qi::AnyValue v = qi::AnyValue::from(v2);

      result[k] = v;
    }

    return result;
  }

  static jobject JNI_MapToJavaMap(JNIEnv* env, qi::CapabilityMap map)
  {
    jclass mapClass = env->FindClass("java/util/HashMap");
    jmethodID init = env->GetMethodID(mapClass, "<init>", "()V");
    jobject result = env->NewObject(mapClass, init);

    qi::CapabilityMap::const_iterator it;
    for (it = map.begin(); it != map.end(); ++it)
    {
      std::string key = it->first;
      jstring k = env->NewStringUTF(key.c_str());

      const qi::AnyValue& val = it->second;
      const std::string sig = val.signature().toString();
      jobject v;

      if (sig == "I")
      {
        jclass cls = env->FindClass("java/lang/Integer");
        jmethodID mid = env->GetMethodID(cls, "<init>", "(I)V");
        v = env->NewObject(cls, mid, val.toUInt());
      }
      else if (sig == "s")
      {
        v = (jobject) env->NewStringUTF(val.toString().c_str());
      }
      else
      {
        qiLogError() << "sig " << sig << " not supported, skipping...";
        continue;
      }

      qi::jni::Call<jobject>::invoke(env, result, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", k, v);
    }

    return result;
  }
};

class Java_ClientAuthenticatorFactory : public qi::ClientAuthenticatorFactory
{
public:
  Java_ClientAuthenticatorFactory(JNIEnv* env, jobject object)
  {
    env->GetJavaVM(&_jvm);
    _jobject = env->NewGlobalRef(object);
  }

  qi::ClientAuthenticatorPtr newAuthenticator()
  {
    JNIEnv* env = nullptr;
#ifndef ANDROID
    _jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#else
    _jvm->AttachCurrentThread(&env, nullptr);
#endif
    jobject ca = qi::jni::Call<jobject>::invoke(env, _jobject, "newAuthenticator", "()Lcom/aldebaran/qi/ClientAuthenticator;");
    return boost::make_shared<Java_ClientAuthenticator>(env, ca);
  }

private:
  JavaVM* _jvm;
  jobject _jobject;
};

void      Java_com_aldebaran_qi_Session_setClientAuthenticatorFactory(JNIEnv* env, jobject obj, jlong pSession, jobject object)
{
  qi::Session* session = reinterpret_cast<qi::Session*>(pSession);
  session->setClientAuthenticatorFactory(boost::make_shared<Java_ClientAuthenticatorFactory>(env, object));
}
<|endoftext|>


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

#include "atom/renderer/atom_sandboxed_renderer_client.h"

#include <string>

#include "atom/common/api/api_messages.h"
#include "atom/common/api/atom_bindings.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/v8_value_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/api/atom_api_renderer_ipc.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "base/command_line.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_view_observer.h"
#include "ipc/ipc_message_macros.h"
#include "native_mate/converter.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebView.h"

#include "atom/common/node_includes.h"
#include "atom_natives.h"  // NOLINT: This file is generated with js2c

namespace atom {

namespace {

const std::string kIpcKey = "ipcNative";
const std::string kModuleCacheKey = "native-module-cache";

v8::Local<v8::Object> GetModuleCache(v8::Isolate* isolate) {
  mate::Dictionary global(isolate, isolate->GetCurrentContext()->Global());
  v8::Local<v8::Value> cache;

  if (!global.GetHidden(kModuleCacheKey, &cache)) {
    cache = v8::Object::New(isolate);
    global.SetHidden(kModuleCacheKey, cache);
  }

  return cache->ToObject();
}

// adapted from node.cc
v8::Local<v8::Value> GetBinding(v8::Isolate* isolate, v8::Local<v8::String> key,
    mate::Arguments* margs) {
  v8::Local<v8::Object> exports;
  std::string module_key = mate::V8ToString(key);
  mate::Dictionary cache(isolate, GetModuleCache(isolate));

  if (cache.Get(module_key.c_str(), &exports)) {
    return exports;
  }

  auto mod = node::get_builtin_module(module_key.c_str());

  if (!mod) {
    char errmsg[1024];
    snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_key.c_str());
    margs->ThrowError(errmsg);
    return exports;
  }

  exports = v8::Object::New(isolate);
  DCHECK_EQ(mod->nm_register_func, nullptr);
  DCHECK_NE(mod->nm_context_register_func, nullptr);
  mod->nm_context_register_func(exports, v8::Null(isolate),
      isolate->GetCurrentContext(), mod->nm_priv);
  cache.Set(module_key.c_str(), exports);
  return exports;
}

base::CommandLine::StringVector GetArgv() {
  return base::CommandLine::ForCurrentProcess()->argv();
}

void InitializeBindings(v8::Local<v8::Object> binding,
                        v8::Local<v8::Context> context) {
  auto isolate = context->GetIsolate();
  mate::Dictionary b(isolate, binding);
  b.SetMethod("get", GetBinding);
  b.SetMethod("crash", AtomBindings::Crash);
  b.SetMethod("hang", AtomBindings::Hang);
  b.SetMethod("getArgv", GetArgv);
  b.SetMethod("getProcessMemoryInfo", &AtomBindings::GetProcessMemoryInfo);
  b.SetMethod("getSystemMemoryInfo", &AtomBindings::GetSystemMemoryInfo);
}

class AtomSandboxedRenderViewObserver : public AtomRenderViewObserver {
 public:
  AtomSandboxedRenderViewObserver(content::RenderView* render_view,
                                  AtomSandboxedRendererClient* renderer_client)
    : AtomRenderViewObserver(render_view, nullptr),
    v8_converter_(new atom::V8ValueConverter),
    renderer_client_(renderer_client) {
      v8_converter_->SetDisableNode(true);
    }

 protected:
  void EmitIPCEvent(blink::WebFrame* frame,
                    const base::string16& channel,
                    const base::ListValue& args) override {
    if (!frame || frame->IsWebRemoteFrame())
      return;

    auto isolate = blink::MainThreadIsolate();
    v8::HandleScope handle_scope(isolate);
    auto context = frame->MainWorldScriptContext();
    v8::Context::Scope context_scope(context);
    v8::Local<v8::Value> argv[] = {
      mate::ConvertToV8(isolate, channel),
      v8_converter_->ToV8Value(&args, context)
    };
    renderer_client_->InvokeIpcCallback(
        context,
        "onMessage",
        std::vector<v8::Local<v8::Value>>(argv, argv + 2));
  }

 private:
  std::unique_ptr<atom::V8ValueConverter> v8_converter_;
  AtomSandboxedRendererClient* renderer_client_;
  DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRenderViewObserver);
};

}  // namespace

AtomSandboxedRendererClient::AtomSandboxedRendererClient() {
}

AtomSandboxedRendererClient::~AtomSandboxedRendererClient() {
}

void AtomSandboxedRendererClient::RenderFrameCreated(
    content::RenderFrame* render_frame) {
  RendererClientBase::RenderFrameCreated(render_frame);
}

void AtomSandboxedRendererClient::RenderViewCreated(
    content::RenderView* render_view) {
  new AtomSandboxedRenderViewObserver(render_view, this);
  RendererClientBase::RenderViewCreated(render_view);
}

void AtomSandboxedRendererClient::DidCreateScriptContext(
    v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  std::string preload_script = command_line->GetSwitchValueASCII(
      switches::kPreloadScript);
  if (preload_script.empty())
    return;

  auto isolate = context->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(context);
  // Wrap the bundle into a function that receives the binding object and the
  // preload script path as arguments.
  std::string preload_bundle_native(node::preload_bundle_data,
      node::preload_bundle_data + sizeof(node::preload_bundle_data));
  std::stringstream ss;
  ss << "(function(binding, preloadPath, require) {\n";
  ss << preload_bundle_native << "\n";
  ss << "})";
  std::string preload_wrapper = ss.str();
  // Compile the wrapper and run it to get the function object
  auto script = v8::Script::Compile(
      mate::ConvertToV8(isolate, preload_wrapper)->ToString());
  auto func = v8::Handle<v8::Function>::Cast(
      script->Run(context).ToLocalChecked());
  // Create and initialize the binding object
  auto binding = v8::Object::New(isolate);
  InitializeBindings(binding, context);
  AddRenderBindings(isolate, binding);
  v8::Local<v8::Value> args[] = {
    binding,
    mate::ConvertToV8(isolate, preload_script)
  };
  // Execute the function with proper arguments
  ignore_result(func->Call(context, v8::Null(isolate), 2, args));
}

void AtomSandboxedRendererClient::WillReleaseScriptContext(
    v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
  auto isolate = context->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(context);
  InvokeIpcCallback(context, "onExit", std::vector<v8::Local<v8::Value>>());
}

void AtomSandboxedRendererClient::InvokeIpcCallback(
    v8::Handle<v8::Context> context,
    const std::string& callback_name,
    std::vector<v8::Handle<v8::Value>> args) {
  auto isolate = context->GetIsolate();
  auto binding_key = mate::ConvertToV8(isolate, kIpcKey)->ToString();
  auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
  auto global_object = context->Global();
  v8::Local<v8::Value> value;
  if (!global_object->GetPrivate(context, private_binding_key).ToLocal(&value))
    return;
  if (value.IsEmpty() || !value->IsObject())
    return;
  auto binding = value->ToObject();
  auto callback_key = mate::ConvertToV8(isolate, callback_name)->ToString();
  auto callback_value = binding->Get(callback_key);
  DCHECK(callback_value->IsFunction());  // set by sandboxed_renderer/init.js
  auto callback = v8::Handle<v8::Function>::Cast(callback_value);
  ignore_result(callback->Call(context, binding, args.size(), args.data()));
}

}  // namespace atom
<commit_msg>:bug: #10470 - prevent to load preload in each iframe context<commit_after>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/renderer/atom_sandboxed_renderer_client.h"

#include <string>

#include "atom/common/api/api_messages.h"
#include "atom/common/api/atom_bindings.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/v8_value_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/api/atom_api_renderer_ipc.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "base/command_line.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_view_observer.h"
#include "ipc/ipc_message_macros.h"
#include "native_mate/converter.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebView.h"

#include "atom/common/node_includes.h"
#include "atom_natives.h"  // NOLINT: This file is generated with js2c

namespace atom {

namespace {

const std::string kIpcKey = "ipcNative";
const std::string kModuleCacheKey = "native-module-cache";

v8::Local<v8::Object> GetModuleCache(v8::Isolate* isolate) {
  mate::Dictionary global(isolate, isolate->GetCurrentContext()->Global());
  v8::Local<v8::Value> cache;

  if (!global.GetHidden(kModuleCacheKey, &cache)) {
    cache = v8::Object::New(isolate);
    global.SetHidden(kModuleCacheKey, cache);
  }

  return cache->ToObject();
}

// adapted from node.cc
v8::Local<v8::Value> GetBinding(v8::Isolate* isolate, v8::Local<v8::String> key,
    mate::Arguments* margs) {
  v8::Local<v8::Object> exports;
  std::string module_key = mate::V8ToString(key);
  mate::Dictionary cache(isolate, GetModuleCache(isolate));

  if (cache.Get(module_key.c_str(), &exports)) {
    return exports;
  }

  auto mod = node::get_builtin_module(module_key.c_str());

  if (!mod) {
    char errmsg[1024];
    snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_key.c_str());
    margs->ThrowError(errmsg);
    return exports;
  }

  exports = v8::Object::New(isolate);
  DCHECK_EQ(mod->nm_register_func, nullptr);
  DCHECK_NE(mod->nm_context_register_func, nullptr);
  mod->nm_context_register_func(exports, v8::Null(isolate),
      isolate->GetCurrentContext(), mod->nm_priv);
  cache.Set(module_key.c_str(), exports);
  return exports;
}

base::CommandLine::StringVector GetArgv() {
  return base::CommandLine::ForCurrentProcess()->argv();
}

void InitializeBindings(v8::Local<v8::Object> binding,
                        v8::Local<v8::Context> context) {
  auto isolate = context->GetIsolate();
  mate::Dictionary b(isolate, binding);
  b.SetMethod("get", GetBinding);
  b.SetMethod("crash", AtomBindings::Crash);
  b.SetMethod("hang", AtomBindings::Hang);
  b.SetMethod("getArgv", GetArgv);
  b.SetMethod("getProcessMemoryInfo", &AtomBindings::GetProcessMemoryInfo);
  b.SetMethod("getSystemMemoryInfo", &AtomBindings::GetSystemMemoryInfo);
}

class AtomSandboxedRenderViewObserver : public AtomRenderViewObserver {
 public:
  AtomSandboxedRenderViewObserver(content::RenderView* render_view,
                                  AtomSandboxedRendererClient* renderer_client)
    : AtomRenderViewObserver(render_view, nullptr),
    v8_converter_(new atom::V8ValueConverter),
    renderer_client_(renderer_client) {
      v8_converter_->SetDisableNode(true);
    }

 protected:
  void EmitIPCEvent(blink::WebFrame* frame,
                    const base::string16& channel,
                    const base::ListValue& args) override {
    if (!frame || frame->IsWebRemoteFrame())
      return;

    auto isolate = blink::MainThreadIsolate();
    v8::HandleScope handle_scope(isolate);
    auto context = frame->MainWorldScriptContext();
    v8::Context::Scope context_scope(context);
    v8::Local<v8::Value> argv[] = {
      mate::ConvertToV8(isolate, channel),
      v8_converter_->ToV8Value(&args, context)
    };
    renderer_client_->InvokeIpcCallback(
        context,
        "onMessage",
        std::vector<v8::Local<v8::Value>>(argv, argv + 2));
  }

 private:
  std::unique_ptr<atom::V8ValueConverter> v8_converter_;
  AtomSandboxedRendererClient* renderer_client_;
  DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRenderViewObserver);
};

}  // namespace

AtomSandboxedRendererClient::AtomSandboxedRendererClient() {
}

AtomSandboxedRendererClient::~AtomSandboxedRendererClient() {
}

void AtomSandboxedRendererClient::RenderFrameCreated(
    content::RenderFrame* render_frame) {
  RendererClientBase::RenderFrameCreated(render_frame);
}

void AtomSandboxedRendererClient::RenderViewCreated(
    content::RenderView* render_view) {
  new AtomSandboxedRenderViewObserver(render_view, this);
  RendererClientBase::RenderViewCreated(render_view);
}

void AtomSandboxedRendererClient::DidCreateScriptContext(
    v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {

  // Only allow preload for the main frame
  if (!render_frame->IsMainFrame())
    return;

  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  std::string preload_script = command_line->GetSwitchValueASCII(
      switches::kPreloadScript);
  if (preload_script.empty())
    return;

  auto isolate = context->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(context);
  // Wrap the bundle into a function that receives the binding object and the
  // preload script path as arguments.
  std::string preload_bundle_native(node::preload_bundle_data,
      node::preload_bundle_data + sizeof(node::preload_bundle_data));
  std::stringstream ss;
  ss << "(function(binding, preloadPath, require) {\n";
  ss << preload_bundle_native << "\n";
  ss << "})";
  std::string preload_wrapper = ss.str();
  // Compile the wrapper and run it to get the function object
  auto script = v8::Script::Compile(
      mate::ConvertToV8(isolate, preload_wrapper)->ToString());
  auto func = v8::Handle<v8::Function>::Cast(
      script->Run(context).ToLocalChecked());
  // Create and initialize the binding object
  auto binding = v8::Object::New(isolate);
  InitializeBindings(binding, context);
  AddRenderBindings(isolate, binding);
  v8::Local<v8::Value> args[] = {
    binding,
    mate::ConvertToV8(isolate, preload_script)
  };
  // Execute the function with proper arguments
  ignore_result(func->Call(context, v8::Null(isolate), 2, args));
}

void AtomSandboxedRendererClient::WillReleaseScriptContext(
    v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {

  // Only allow preload for the main frame
  if (!render_frame->IsMainFrame())
    return;

  auto isolate = context->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(context);
  InvokeIpcCallback(context, "onExit", std::vector<v8::Local<v8::Value>>());
}

void AtomSandboxedRendererClient::InvokeIpcCallback(
    v8::Handle<v8::Context> context,
    const std::string& callback_name,
    std::vector<v8::Handle<v8::Value>> args) {
  auto isolate = context->GetIsolate();
  auto binding_key = mate::ConvertToV8(isolate, kIpcKey)->ToString();
  auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
  auto global_object = context->Global();
  v8::Local<v8::Value> value;
  if (!global_object->GetPrivate(context, private_binding_key).ToLocal(&value))
    return;
  if (value.IsEmpty() || !value->IsObject())
    return;
  auto binding = value->ToObject();
  auto callback_key = mate::ConvertToV8(isolate, callback_name)->ToString();
  auto callback_value = binding->Get(callback_key);
  DCHECK(callback_value->IsFunction());  // set by sandboxed_renderer/init.js
  auto callback = v8::Handle<v8::Function>::Cast(callback_value);
  ignore_result(callback->Call(context, binding, args.size(), args.data()));
}

}  // namespace atom
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "ContextCreatorTest.h"
#include "ContextCreator.h"
#include <string>

extern const char gc_contextName[] = "eviction_context";

class Creator:
  public ContextCreator<gc_contextName, int> {
};

class VoidCreator:
  public ContextCreator<gc_contextName>
{
public:
  VoidCreator(void):
    m_totalDestroyed(0)
  {}

  size_t m_totalDestroyed;

  void NotifyContextDestroyed(t_contextList::iterator q, CoreContext* pContext) override {
    m_totalDestroyed++;
    ContextCreator<gc_contextName>::NotifyContextDestroyed(q, pContext);
  }
};

class GlobalSignal {
public:
  GlobalSignal(void):
    m_shouldContinue(false)
  {}

private:
  boost::mutex m_lock;
  bool m_shouldContinue;
  boost::condition_variable s_continueCond;

public:
  void Signal(void) {
    (boost::lock_guard<boost::mutex>)m_lock,
    (m_shouldContinue = true),
    s_continueCond.notify_all();
  }

  void Delay(void) {
    boost::unique_lock<boost::mutex> lk(m_lock);
    s_continueCond.wait(lk, [this] () {return m_shouldContinue;});
  }
};

class WaitMember:
  public CoreThread
{
public:
  WaitMember(void) {
    Ready();
  }

private:
  AutoRequired<GlobalSignal> m_signal;

public:

  void Run(void) override {
    // Wait for our event to be signalled, then leave
    m_signal->Delay();
  }
};

TEST_F(ContextCreatorTest, ValidateSimpleEviction) {
  // Create a context and verify it gets evicted from the context creator:
  AutoRequired<Creator> creator;
  std::weak_ptr<CoreContext> ctxtWeak;

  {
    std::shared_ptr<CoreContext> ctxt;

    // Make a context:
    ctxt = *creator->CreateContext(1);

    // Obtain a weak pointer, in order to ensure proper teardown:
    ctxtWeak = ctxt;
  }

  // Context must be destroyed as a precondition of the subsequent assertion
  ASSERT_TRUE(ctxtWeak.expired()) << "Expected the context to be destroyed";

  // Verify that our creator is now empty:
  EXPECT_EQ(0UL, creator->GetSize()) << "Context creator is non-empty after all created contexts were destroyed";
}

TEST_F(ContextCreatorTest, ValidateMultipleEviction) {
  // Number of dependent contexts to be created
  const size_t count = 100;

  // Teardown lock, counter, and condition:
  boost::mutex lock;
  boost::condition cond;
  int counter = count;

  // Obtain creator pointer:
  AutoRequired<Creator> creator;

  // Set up a signal manager at global context scope:
  AutoRequired<GlobalSignal> signal;

  {
    // Array of objects to test destruction on, and corresponding collection of contexts:
    std::shared_ptr<WaitMember> members[count];

    // Create a few contexts:
    for(int i = count; i--;) {
      std::shared_ptr<CoreContext> ctxt = *creator->CreateContext(i);
      CurrentContextPusher pshr(ctxt);

      // Trivial validation that the newly created context is an empty context:
      ASSERT_EQ(static_cast<size_t>(0), ctxt->GetMemberCount()) << "A created context was not empty";

      // Add in an object to test asynchronous destruction:
      AutoRequired<WaitMember> obj;
      members[i] = obj;

      // Add a notifier to signal a continue condition when we have everything we need:
      ctxt->AddTeardownListener([&lock, &cond, &counter] {
        (boost::lock_guard<boost::mutex>)lock,
        counter--,
        cond.notify_all();
      });

      // Kick off the context:
      ctxt->InitiateCoreThreads();
    }

    // Signal all members and then release everything:
    signal->Signal();
  }

  // Wait for all contexts to be destroyed
  boost::unique_lock<boost::mutex> lk(lock);
  cond.wait(lk, [&counter] {return counter == 0;});

  // Validate that everything expires:
  EXPECT_EQ(static_cast<size_t>(0), creator->GetSize()) << "Not all contexts were evicted as expected";
}

TEST_F(ContextCreatorTest, VoidKeyType) {
  AutoRequired<VoidCreator> vc;

  {
    std::shared_ptr<CoreContext> ctxt;

    {
      auto created = vc->CreateContext();
      ctxt = *created;
      EXPECT_EQ(1UL, vc->GetSize()) << "Requested that a context be created, but the void creator did not have any members";
    }
    EXPECT_EQ(1UL, vc->GetSize()) << "A created context was apparently destroyed after firing bolts";
    EXPECT_EQ(0UL, vc->m_totalDestroyed) << "The void creator received a NotifyContextDestroyed call unexpectedly early";
  }

  EXPECT_EQ(0UL, vc->GetSize()) << "A void context creator was not correctly updated when its dependent context went out of scope";
  EXPECT_EQ(1UL, vc->m_totalDestroyed) << "The void creator did not receive the expected number of NotifyContextDestroyed calls";
}
<commit_msg>Adding a guard to prevent a test from hanging<commit_after>#include "stdafx.h"
#include "ContextCreatorTest.h"
#include "ContextCreator.h"
#include <string>

extern const char gc_contextName[] = "eviction_context";

class Creator:
  public ContextCreator<gc_contextName, int> {
};

class VoidCreator:
  public ContextCreator<gc_contextName>
{
public:
  VoidCreator(void):
    m_totalDestroyed(0)
  {}

  size_t m_totalDestroyed;

  void NotifyContextDestroyed(t_contextList::iterator q, CoreContext* pContext) override {
    m_totalDestroyed++;
    ContextCreator<gc_contextName>::NotifyContextDestroyed(q, pContext);
  }
};

class GlobalSignal {
public:
  GlobalSignal(void):
    m_shouldContinue(false)
  {}

private:
  boost::mutex m_lock;
  bool m_shouldContinue;
  boost::condition_variable s_continueCond;

public:
  void Signal(void) {
    (boost::lock_guard<boost::mutex>)m_lock,
    (m_shouldContinue = true),
    s_continueCond.notify_all();
  }

  void Delay(void) {
    boost::unique_lock<boost::mutex> lk(m_lock);
    s_continueCond.wait(lk, [this] () {return m_shouldContinue;});
  }
};

class WaitMember:
  public CoreThread
{
public:
  WaitMember(void) {
    Ready();
  }

  AutoRequired<GlobalSignal> m_signal;

  void Run(void) override {
    // Wait for our event to be signalled, then leave
    m_signal->Delay();
  }
};

TEST_F(ContextCreatorTest, ValidateSimpleEviction) {
  // Create a context and verify it gets evicted from the context creator:
  AutoRequired<Creator> creator;
  std::weak_ptr<CoreContext> ctxtWeak;

  {
    std::shared_ptr<CoreContext> ctxt;

    // Make a context:
    ctxt = *creator->CreateContext(1);

    // Obtain a weak pointer, in order to ensure proper teardown:
    ctxtWeak = ctxt;
  }

  // Context must be destroyed as a precondition of the subsequent assertion
  ASSERT_TRUE(ctxtWeak.expired()) << "Expected the context to be destroyed";

  // Verify that our creator is now empty:
  EXPECT_EQ(0UL, creator->GetSize()) << "Context creator is non-empty after all created contexts were destroyed";
}

TEST_F(ContextCreatorTest, ValidateMultipleEviction) {
  // Number of dependent contexts to be created
  const size_t count = 100;

  // Teardown lock, counter, and condition:
  boost::mutex lock;
  boost::condition cond;
  int counter = count;

  // Obtain creator pointer:
  AutoRequired<Creator> creator;

  // Set up a signal manager at global context scope:
  AutoRequired<GlobalSignal> signal;

  {
    // Array of objects to test destruction on, and corresponding collection of contexts:
    std::shared_ptr<WaitMember> members[count];

    // Create a few contexts:
    for(int i = count; i--;) {
      AutoCreateContext ctxt;
      CurrentContextPusher pshr(ctxt);

      // Trivial validation that the newly created context is an empty context:
      ASSERT_EQ(static_cast<size_t>(0), ctxt->GetMemberCount()) << "A created context was not empty";

      // Add in an object to test asynchronous destruction:
      AutoRequired<WaitMember> obj;
      members[i] = obj;
      ASSERT_EQ(signal, obj->m_signal) << "Dependent context wiring did not correctly match to the enclosing scope";

      // Add a notifier to signal a continue condition when we have everything we need:
      ctxt->AddTeardownListener([&lock, &cond, &counter] {
        (boost::lock_guard<boost::mutex>)lock,
        counter--,
        cond.notify_all();
      });

      // Kick off the context:
      ctxt->InitiateCoreThreads();
    }

    // Signal all members and then release everything:
    signal->Signal();
  }

  // Wait for all contexts to be destroyed
  boost::unique_lock<boost::mutex> lk(lock);
  cond.wait(lk, [&counter] {return counter == 0;});

  // Validate that everything expires:
  EXPECT_EQ(static_cast<size_t>(0), creator->GetSize()) << "Not all contexts were evicted as expected";
}

TEST_F(ContextCreatorTest, VoidKeyType) {
  AutoRequired<VoidCreator> vc;

  {
    std::shared_ptr<CoreContext> ctxt;

    {
      auto created = vc->CreateContext();
      ctxt = *created;
      EXPECT_EQ(1UL, vc->GetSize()) << "Requested that a context be created, but the void creator did not have any members";
    }
    EXPECT_EQ(1UL, vc->GetSize()) << "A created context was apparently destroyed after firing bolts";
    EXPECT_EQ(0UL, vc->m_totalDestroyed) << "The void creator received a NotifyContextDestroyed call unexpectedly early";
  }

  EXPECT_EQ(0UL, vc->GetSize()) << "A void context creator was not correctly updated when its dependent context went out of scope";
  EXPECT_EQ(1UL, vc->m_totalDestroyed) << "The void creator did not receive the expected number of NotifyContextDestroyed calls";
}
<|endoftext|>