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

#include "qgeotiledmapobjectinfo_p.h"

#include "qgeotiledmapdata.h"
#include "qgeotiledmapdata_p.h"

#include <QGraphicsScene>

#include <QPolygonF>

#include <QDebug>

QTM_BEGIN_NAMESPACE

QGeoTiledMapObjectInfo::QGeoTiledMapObjectInfo(QGeoMapData *mapData, QGeoMapObject *mapObject)
        : QGeoMapObjectInfo(mapData, mapObject),
        graphicsItem(0)
{
    tiledMapData = static_cast<QGeoTiledMapData*>(mapData);
    tiledMapDataPrivate = static_cast<QGeoTiledMapDataPrivate*>(tiledMapData->d_ptr);
}

QGeoTiledMapObjectInfo::~QGeoTiledMapObjectInfo()
{
    if (graphicsItem)
        delete graphicsItem;
}

void QGeoTiledMapObjectInfo::addToParent()
{
    if (graphicsItem) {
        QGeoTiledMapObjectInfo *parentInfo
                = static_cast<QGeoTiledMapObjectInfo*>(parentObjectInfo());

        if (parentInfo)
            graphicsItem->setParentItem(parentInfo->graphicsItem);
        else
            tiledMapDataPrivate->scene->addItem(graphicsItem);

        tiledMapDataPrivate->itemMap.insert(graphicsItem, mapObject());
        graphicsItem->setVisible(mapObject()->isVisible());
        graphicsItem->setFlag(QGraphicsItem::ItemIsSelectable);
        graphicsItem->setSelected(mapObject()->isSelected());
    }
}

void QGeoTiledMapObjectInfo::removeFromParent()
{
    if (graphicsItem) {
        tiledMapDataPrivate->scene->removeItem(graphicsItem);
        tiledMapDataPrivate->itemMap.remove(graphicsItem);
    }
}

void QGeoTiledMapObjectInfo::visibleChanged(bool visible)
{
    if (graphicsItem) {
        graphicsItem->setVisible(visible);
        updateItem();
    }
}

void QGeoTiledMapObjectInfo::selectedChanged(bool selected)
{
    if (graphicsItem) {
        graphicsItem->setSelected(selected);
        updateItem();
    }
}

QGeoBoundingBox QGeoTiledMapObjectInfo::boundingBox() const
{
    if (!graphicsItem)
        return QGeoBoundingBox();

    QRectF rect1 = graphicsItem->boundingRect();
    QGeoCoordinate topLeft1 = tiledMapData->worldPixelToCoordinate(rect1.topLeft().toPoint());
    QGeoCoordinate bottomRight1 = tiledMapData->worldPixelToCoordinate(rect1.bottomRight().toPoint());

    QGeoBoundingBox box1 = QGeoBoundingBox(topLeft1, bottomRight1);

    return box1;
}

bool QGeoTiledMapObjectInfo::contains(const QGeoCoordinate &coord) const
{
    QPoint point = tiledMapData->coordinateToWorldPixel(coord);

    if (graphicsItem && graphicsItem->contains(point))
        return true;

    return false;
}

void QGeoTiledMapObjectInfo::updateItem()
{
    // TODO use bounding rectangle of graphics items
    if (graphicsItem)
        tiledMapData->geoMap()->update();
}

QPolygonF QGeoTiledMapObjectInfo::createPolygon(const QList<QGeoCoordinate> &path,
        QGeoTiledMapData *tiledMapData,
        bool closedPath,
        qreal ypole)
{
    QPolygonF points;

    QGeoCoordinate lastCoord = closedPath ? path.last() : path.first();
    QPointF lastPoint = tiledMapData->coordinateToWorldPixel(lastCoord);

    int width = tiledMapData->maxZoomSize().width();

    for (int i = 0; i < path.size(); ++i) {
        const QGeoCoordinate &coord = path.at(i);

        if (!coord.isValid())
            continue;

        const qreal lng = coord.longitude();
        const qreal lastLng = lastCoord.longitude();

        // is the dateline crossed = different sign AND gap is large enough
        const bool crossesDateline = lastLng * lng < 0 && abs(lastLng - lng) > 180;

        // calculate base point
        QPointF point = tiledMapData->coordinateToWorldPixel(coord);

        // if the dateline is crossed, draw "around" the map over the chosen pole
        if (crossesDateline) {
            // is the shortest route east = dateline crossed XOR longitude is east by simple comparison
            const bool goesEast = crossesDateline != (lng > lastLng);
            // direction = positive if east, negative otherwise
            const qreal dir = goesEast ? 1 : -1;

            // lastPoint on this side
            const QPointF & L = lastPoint;

            // point on the other side
            const QPointF & P = point;

            // lastPoint on the other side
            QPointF L_ = L - QPointF(width * dir, 0);

            // point on this side
            QPointF P_ = P + QPointF(width * dir, 0);

            // TODO: make a better algorithm to make sure the off-screen points P' and L' are far enough from the dateline so the lines to the poles don't flicker through.
            // this works for now :)
            L_ += (L_ - P) * 7;
            P_ += (P_ - L) * 7;

            // pole point on this side
            QPointF O1 = QPointF(P_.x(), ypole);
            // pole point on the other side
            QPointF O2 = QPointF(L_.x(), ypole);

            //points.append(L); // implicit
            points.append(P_); // P'
            points.append(O1);
            points.append(O2);
            points.append(L_); // L'
            points.append(P);
        } else {
            // add point to polygon
            points.append(point);
        }

        lastCoord = coord;
        lastPoint = point;
    }

    return points;
}

QTM_END_NAMESPACE

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

#include "qgeotiledmapobjectinfo_p.h"

#include "qgeotiledmapdata.h"
#include "qgeotiledmapdata_p.h"

#include <QGraphicsScene>

#include <QPolygonF>

#include <QDebug>

QTM_BEGIN_NAMESPACE

QGeoTiledMapObjectInfo::QGeoTiledMapObjectInfo(QGeoMapData *mapData, QGeoMapObject *mapObject)
        : QGeoMapObjectInfo(mapData, mapObject),
        graphicsItem(0)
{
    tiledMapData = static_cast<QGeoTiledMapData*>(mapData);
    tiledMapDataPrivate = static_cast<QGeoTiledMapDataPrivate*>(tiledMapData->d_ptr);
}

QGeoTiledMapObjectInfo::~QGeoTiledMapObjectInfo()
{
    if (graphicsItem)
        delete graphicsItem;
}

void QGeoTiledMapObjectInfo::addToParent()
{
    if (graphicsItem) {
        QGeoTiledMapObjectInfo *parentInfo
                = static_cast<QGeoTiledMapObjectInfo*>(parentObjectInfo());

        if (parentInfo)
            graphicsItem->setParentItem(parentInfo->graphicsItem);
        else
            tiledMapDataPrivate->scene->addItem(graphicsItem);

        tiledMapDataPrivate->itemMap.insert(graphicsItem, mapObject());
        graphicsItem->setVisible(mapObject()->isVisible());
        graphicsItem->setFlag(QGraphicsItem::ItemIsSelectable);
        graphicsItem->setSelected(mapObject()->isSelected());
    }
}

void QGeoTiledMapObjectInfo::removeFromParent()
{
    if (graphicsItem) {
        tiledMapDataPrivate->scene->removeItem(graphicsItem);
        tiledMapDataPrivate->itemMap.remove(graphicsItem);
    }
}

void QGeoTiledMapObjectInfo::visibleChanged(bool visible)
{
    if (graphicsItem) {
        graphicsItem->setVisible(visible);
        updateItem();
    }
}

void QGeoTiledMapObjectInfo::selectedChanged(bool selected)
{
    if (graphicsItem) {
        graphicsItem->setSelected(selected);
        updateItem();
    }
}

QGeoBoundingBox QGeoTiledMapObjectInfo::boundingBox() const
{
    if (!graphicsItem)
        return QGeoBoundingBox();

    QRectF rect1 = graphicsItem->boundingRect();
    QGeoCoordinate topLeft1 = tiledMapData->worldPixelToCoordinate(rect1.topLeft().toPoint());
    QGeoCoordinate bottomRight1 = tiledMapData->worldPixelToCoordinate(rect1.bottomRight().toPoint());

    QGeoBoundingBox box1 = QGeoBoundingBox(topLeft1, bottomRight1);

    return box1;
}

bool QGeoTiledMapObjectInfo::contains(const QGeoCoordinate &coord) const
{
    QPoint point = tiledMapData->coordinateToWorldPixel(coord);

    //if (graphicsItem && graphicsItem->contains(point))
    if (graphicsItem && graphicsItem->mapToParent(graphicsItem->shape()).contains(point))
        return true;

    return false;
}

void QGeoTiledMapObjectInfo::updateItem()
{
    // TODO use bounding rectangle of graphics items
    if (graphicsItem)
        tiledMapData->geoMap()->update();
}

QPolygonF QGeoTiledMapObjectInfo::createPolygon(const QList<QGeoCoordinate> &path,
        QGeoTiledMapData *tiledMapData,
        bool closedPath,
        qreal ypole)
{
    QPolygonF points;

    QGeoCoordinate lastCoord = closedPath ? path.last() : path.first();
    QPointF lastPoint = tiledMapData->coordinateToWorldPixel(lastCoord);

    int width = tiledMapData->maxZoomSize().width();

    for (int i = 0; i < path.size(); ++i) {
        const QGeoCoordinate &coord = path.at(i);

        if (!coord.isValid())
            continue;

        const qreal lng = coord.longitude();
        const qreal lastLng = lastCoord.longitude();

        // is the dateline crossed = different sign AND gap is large enough
        const bool crossesDateline = lastLng * lng < 0 && abs(lastLng - lng) > 180;

        // calculate base point
        QPointF point = tiledMapData->coordinateToWorldPixel(coord);

        // if the dateline is crossed, draw "around" the map over the chosen pole
        if (crossesDateline) {
            // is the shortest route east = dateline crossed XOR longitude is east by simple comparison
            const bool goesEast = crossesDateline != (lng > lastLng);
            // direction = positive if east, negative otherwise
            const qreal dir = goesEast ? 1 : -1;

            // lastPoint on this side
            const QPointF & L = lastPoint;

            // point on the other side
            const QPointF & P = point;

            // lastPoint on the other side
            QPointF L_ = L - QPointF(width * dir, 0);

            // point on this side
            QPointF P_ = P + QPointF(width * dir, 0);

            // TODO: make a better algorithm to make sure the off-screen points P' and L' are far enough from the dateline so the lines to the poles don't flicker through.
            // this works for now :)
            L_ += (L_ - P) * 7;
            P_ += (P_ - L) * 7;

            // pole point on this side
            QPointF O1 = QPointF(P_.x(), ypole);
            // pole point on the other side
            QPointF O2 = QPointF(L_.x(), ypole);

            //points.append(L); // implicit
            points.append(P_); // P'
            points.append(O1);
            points.append(O2);
            points.append(L_); // L'
            points.append(P);
        } else {
            // add point to polygon
            points.append(point);
        }

        lastCoord = coord;
        lastPoint = point;
    }

    return points;
}

QTM_END_NAMESPACE

<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include "circle.hpp"

	bool is_odd(int i){
		return (i % 2) != 0;
	}

	bool is_even(int i){
		return (i % 2) == 0;
	}

TEST_CASE("describe_factorial", "[aufgbae3]")
{
	//ihre Loesung :

	std::set<Circle> set0;

	for (int i = 0; i < 5; ++i) {

		float rad= std::rand() % 10;
		Circle c(rad, 0.0f, 0.0f);
		set0.insert(c);
	}

	std::set<Circle> set1;

	Circle c1(6.0f, 0.0f, 0.0f);
	Circle c2(5.0f, 0.0f, 0.0f);
	Circle c3(7.0f, 0.0f, 0.0f);
	Circle c4(2.0f, 0.0f, 0.0f);

	set1.insert(c1);
	set1.insert(c2);
	set1.insert(c3);
	set1.insert(c4);

REQUIRE(std::is_sorted(set0.begin(), set0.end()));
REQUIRE(std::is_sorted(set1.begin(), set1.end()));

}

template<typename T>
void swap(T& a, T& b) {
	T c(a);
	a = b;
	b = c;
}

TEST_CASE("describe_swap", "[aufgabe3.8]"){

	Circle c1(6.0f, 0.0f, 0.0f);
	Circle c2(5.0f, 0.0f, 0.0f);

	swap(c1, c2);

	REQUIRE(c1.get_r()==5.0f);
	REQUIRE(c2.get_r()==6.0f);

}

int main (int argc, char* argv[])
{
	return Catch::Session().run (argc, argv);
}<commit_msg>3.9 finished<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <list>
#include "circle.hpp"

	bool is_odd(int i){
		return (i % 2) != 0;
	}

	bool is_even(int i){
		return (i % 2) == 0;
	}

TEST_CASE("describe_sort", "[sort]")
{
	//ihre Loesung :

	std::set<Circle> set0;

	for (int i = 0; i < 5; ++i) {

		float rad= std::rand() % 10;
		Circle c(rad, 0.0f, 0.0f);
		set0.insert(c);
	}

	std::set<Circle> set1;

	Circle c1(6.0f, 0.0f, 0.0f);
	Circle c2(5.0f, 0.0f, 0.0f);
	Circle c3(7.0f, 0.0f, 0.0f);
	Circle c4(2.0f, 0.0f, 0.0f);

	set1.insert(c1);
	set1.insert(c2);
	set1.insert(c3);
	set1.insert(c4);

REQUIRE(std::is_sorted(set0.begin(), set0.end()));
REQUIRE(std::is_sorted(set1.begin(), set1.end()));

}

template<typename T>
void swap(T& a, T& b) {
	T c(a);
	a = b;
	b = c;
}

TEST_CASE("describe_swap", "[aufgabe3.8]"){

	Circle c1(6.0f, 0.0f, 0.0f);
	Circle c2(5.0f, 0.0f, 0.0f);
	int a = 0;
	int b = 1;

	swap(c1, c2);
	swap(a, b);

	REQUIRE(c1.get_r()==5.0f);
	REQUIRE(c2.get_r()==6.0f);

	REQUIRE(a == 1);
	REQUIRE(b == 0);

}

TEST_CASE("describe_sort2", "[sort2]"){

	std::list<Circle> list0(5);
	for (int i = 0; i < 5; ++i) {

		float rad = std::rand() % 10;
		Circle c(rad, 0.0f, 0.0f);
		list0.push_back(c);
	}

	list0.sort([](Circle a, Circle b) {
		return a.get_r() < b.get_r();
	});

	REQUIRE(std::is_sorted(list0.begin(), list0.end()));
}

int main (int argc, char* argv[])
{
	return Catch::Session().run (argc, argv);
}<|endoftext|>


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

#include "folly/wangle/bootstrap/ServerBootstrap.h"
#include "folly/wangle/bootstrap/ClientBootstrap.h"
#include "folly/wangle/channel/ChannelHandler.h"

#include <glog/logging.h>
#include <gtest/gtest.h>

using namespace folly::wangle;
using namespace folly;

typedef ChannelPipeline<IOBufQueue&, std::unique_ptr<IOBuf>> Pipeline;

class TestServer : public ServerBootstrap<Pipeline> {
  Pipeline* newPipeline(std::shared_ptr<AsyncSocket>) {
    return nullptr;
  }
};

class TestClient : public ClientBootstrap<Pipeline> {
  Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {
    CHECK(sock->good());

    // We probably aren't connected immedately, check after a small delay
    EventBaseManager::get()->getEventBase()->runAfterDelay([sock](){
      CHECK(sock->readable());
    }, 100);
    return nullptr;
  }
};

class TestPipelineFactory : public PipelineFactory<Pipeline> {
 public:
  Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {
    pipelines++;
    return new Pipeline();
  }
  std::atomic<int> pipelines{0};
};

TEST(Bootstrap, Basic) {
  TestServer server;
  TestClient client;
}

TEST(Bootstrap, ServerWithPipeline) {
  TestServer server;
  server.childPipeline(std::make_shared<TestPipelineFactory>());
  server.bind(0);
  server.stop();
}

TEST(Bootstrap, ClientServerTest) {
  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.bind(0);
  auto base = EventBaseManager::get()->getEventBase();

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);
  base->loop();
  server.stop();

  CHECK(factory->pipelines == 1);
}

TEST(Bootstrap, ClientConnectionManagerTest) {
  // Create a single IO thread, and verify that
  // client connections are pooled properly

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(std::make_shared<IOThreadPoolExecutor>(1));
  server.bind(0);
  auto base = EventBaseManager::get()->getEventBase();

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);

  TestClient client2;
  client2.connect(address);

  base->loop();
  server.stop();

  CHECK(factory->pipelines == 2);
}

TEST(Bootstrap, ServerAcceptGroupTest) {
  // Verify that server is using the accept IO group

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(std::make_shared<IOThreadPoolExecutor>(1), nullptr);
  server.bind(0);

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  boost::barrier barrier(2);
  auto thread = std::thread([&](){
    TestClient client;
    client.connect(address);
    EventBaseManager::get()->getEventBase()->loop();
    barrier.wait();
  });
  barrier.wait();
  server.stop();
  thread.join();

  CHECK(factory->pipelines == 1);
}

TEST(Bootstrap, ServerAcceptGroup2Test) {
  // Verify that server is using the accept IO group

  // Check if reuse port is supported, if not, don't run this test
  try {
    EventBase base;
    auto serverSocket = AsyncServerSocket::newSocket(&base);
    serverSocket->bind(0);
    serverSocket->listen(0);
    serverSocket->startAccepting();
    serverSocket->setReusePortEnabled(true);
    serverSocket->stopAccepting();
  } catch(...) {
    LOG(INFO) << "Reuse port probably not supported";
    return;
  }

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(std::make_shared<IOThreadPoolExecutor>(4), nullptr);
  server.bind(0);

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);
  EventBaseManager::get()->getEventBase()->loop();

  server.stop();

  CHECK(factory->pipelines == 1);
}

TEST(Bootstrap, SharedThreadPool) {
  auto pool = std::make_shared<IOThreadPoolExecutor>(2);

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(pool, pool);

  server.bind(0);

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);

  TestClient client2;
  client2.connect(address);

  TestClient client3;
  client3.connect(address);

  TestClient client4;
  client4.connect(address);

  TestClient client5;
  client5.connect(address);

  EventBaseManager::get()->getEventBase()->loop();

  server.stop();
  CHECK(factory->pipelines == 5);
}
<commit_msg>fix bootstrap test on older kernels<commit_after>/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "folly/wangle/bootstrap/ServerBootstrap.h"
#include "folly/wangle/bootstrap/ClientBootstrap.h"
#include "folly/wangle/channel/ChannelHandler.h"

#include <glog/logging.h>
#include <gtest/gtest.h>

using namespace folly::wangle;
using namespace folly;

typedef ChannelPipeline<IOBufQueue&, std::unique_ptr<IOBuf>> Pipeline;

class TestServer : public ServerBootstrap<Pipeline> {
  Pipeline* newPipeline(std::shared_ptr<AsyncSocket>) {
    return nullptr;
  }
};

class TestClient : public ClientBootstrap<Pipeline> {
  Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {
    CHECK(sock->good());

    // We probably aren't connected immedately, check after a small delay
    EventBaseManager::get()->getEventBase()->runAfterDelay([sock](){
      CHECK(sock->readable());
    }, 100);
    return nullptr;
  }
};

class TestPipelineFactory : public PipelineFactory<Pipeline> {
 public:
  Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {
    pipelines++;
    return new Pipeline();
  }
  std::atomic<int> pipelines{0};
};

TEST(Bootstrap, Basic) {
  TestServer server;
  TestClient client;
}

TEST(Bootstrap, ServerWithPipeline) {
  TestServer server;
  server.childPipeline(std::make_shared<TestPipelineFactory>());
  server.bind(0);
  server.stop();
}

TEST(Bootstrap, ClientServerTest) {
  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.bind(0);
  auto base = EventBaseManager::get()->getEventBase();

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);
  base->loop();
  server.stop();

  CHECK(factory->pipelines == 1);
}

TEST(Bootstrap, ClientConnectionManagerTest) {
  // Create a single IO thread, and verify that
  // client connections are pooled properly

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(std::make_shared<IOThreadPoolExecutor>(1));
  server.bind(0);
  auto base = EventBaseManager::get()->getEventBase();

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);

  TestClient client2;
  client2.connect(address);

  base->loop();
  server.stop();

  CHECK(factory->pipelines == 2);
}

TEST(Bootstrap, ServerAcceptGroupTest) {
  // Verify that server is using the accept IO group

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(std::make_shared<IOThreadPoolExecutor>(1), nullptr);
  server.bind(0);

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  boost::barrier barrier(2);
  auto thread = std::thread([&](){
    TestClient client;
    client.connect(address);
    EventBaseManager::get()->getEventBase()->loop();
    barrier.wait();
  });
  barrier.wait();
  server.stop();
  thread.join();

  CHECK(factory->pipelines == 1);
}

TEST(Bootstrap, ServerAcceptGroup2Test) {
  // Verify that server is using the accept IO group

  // Check if reuse port is supported, if not, don't run this test
  try {
    EventBase base;
    auto serverSocket = AsyncServerSocket::newSocket(&base);
    serverSocket->bind(0);
    serverSocket->listen(0);
    serverSocket->startAccepting();
    serverSocket->setReusePortEnabled(true);
    serverSocket->stopAccepting();
  } catch(...) {
    LOG(INFO) << "Reuse port probably not supported";
    return;
  }

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(std::make_shared<IOThreadPoolExecutor>(4), nullptr);
  server.bind(0);

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);
  EventBaseManager::get()->getEventBase()->loop();

  server.stop();

  CHECK(factory->pipelines == 1);
}

TEST(Bootstrap, SharedThreadPool) {
  // Check if reuse port is supported, if not, don't run this test
  try {
    EventBase base;
    auto serverSocket = AsyncServerSocket::newSocket(&base);
    serverSocket->bind(0);
    serverSocket->listen(0);
    serverSocket->startAccepting();
    serverSocket->setReusePortEnabled(true);
    serverSocket->stopAccepting();
  } catch(...) {
    LOG(INFO) << "Reuse port probably not supported";
    return;
  }

  auto pool = std::make_shared<IOThreadPoolExecutor>(2);

  TestServer server;
  auto factory = std::make_shared<TestPipelineFactory>();
  server.childPipeline(factory);
  server.group(pool, pool);

  server.bind(0);

  SocketAddress address;
  server.getSockets()[0]->getAddress(&address);

  TestClient client;
  client.connect(address);

  TestClient client2;
  client2.connect(address);

  TestClient client3;
  client3.connect(address);

  TestClient client4;
  client4.connect(address);

  TestClient client5;
  client5.connect(address);

  EventBaseManager::get()->getEventBase()->loop();

  server.stop();
  CHECK(factory->pipelines == 5);
}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "AdaptivityAction.h"

#ifdef LIBMESH_ENABLE_AMR

#include "FEProblem.h"
#include "NonlinearSystem.h"
#include "Adaptivity.h"
#include "Executioner.h"
#include "MooseEnum.h"

// libMesh includes
#include "libmesh/transient_system.h"

template<>
InputParameters validParams<AdaptivityAction>()
{
  InputParameters params = validParams<Action>();
  MooseEnum estimators("KellyErrorEstimator LaplacianErrorEstimator PatchRecoveryErrorEstimator", "KellyErrorEstimator");

  params.addParam<unsigned int>("steps",                       0, "The number of adaptivity steps to perform at any one time for steady state");
  params.addParam<unsigned int>("initial_adaptivity",          0, "The number of adaptivity steps to perform using the initial conditions");
  params.addParam<Real> ("refine_fraction",                    0.0, "The fraction of elements or error to refine. Should be between 0 and 1.");
  params.addParam<Real> ("coarsen_fraction",                   0.0, "The fraction of elements or error to coarsen. Should be between 0 and 1.");
  params.addParam<unsigned int> ("max_h_level",                0, "Maximum number of times a single element can be refined. If 0 then infinite.");
  params.addParam<MooseEnum> ("error_estimator",               estimators, "The class name of the error estimator you want to use.");
  params.addDeprecatedParam<bool> ("print_changed_info", false,
                                   "Determines whether information about the mesh is printed when adaptivity occurs",
                                   "Use the Console output parameter 'print_mesh_changed_info'");
  params.addParam<Real>("start_time", -std::numeric_limits<Real>::max(), "The time that adaptivity will be active after.");
  params.addParam<Real>("stop_time", std::numeric_limits<Real>::max(), "The time after which adaptivity will no longer be active.");
  params.addParam<std::vector<std::string> > ("weight_names", "List of names of variables that will be associated with weight_values");
  params.addParam<std::vector<Real> > ("weight_values", "List of values between 0 and 1 to weight the associated weight_names error by");
  params.addParam<unsigned int>("cycles_per_step", 1, "The number of adaptivity cycles per step");

  params.addParam<bool>("show_initial_progress", true, "Show the progress of the initial adaptivity");
  return params;
}

AdaptivityAction::AdaptivityAction(InputParameters params) :
    Action(params)
{
}

void
AdaptivityAction::act()
{
  NonlinearSystem & system = _problem->getNonlinearSystem();

  Adaptivity & adapt = _problem->adaptivity();

  adapt.init(getParam<unsigned int>("steps"), getParam<unsigned int>("initial_adaptivity"));

  adapt.setErrorEstimator(getParam<MooseEnum>("error_estimator"));

  adapt.setParam("cycles_per_step", getParam<unsigned int>("cycles_per_step"));
  adapt.setParam("refine fraction", getParam<Real>("refine_fraction"));
  adapt.setParam("coarsen fraction", getParam<Real>("coarsen_fraction"));
  adapt.setParam("max h-level", getParam<unsigned int>("max_h_level"));

  adapt.setPrintMeshChanged(getParam<bool>("print_changed_info"));

  const std::vector<std::string> & weight_names = getParam<std::vector<std::string> >("weight_names");
  const std::vector<Real> & weight_values = getParam<std::vector<Real> >("weight_values");

  int num_weight_names  = weight_names.size();
  int num_weight_values = weight_values.size();

  if (num_weight_names)
  {
    if (num_weight_names != num_weight_values)
      mooseError("Number of weight_names must be equal to number of weight_values in Execution/Adaptivity");

    // If weights have been specified then set the default weight to zero
    std::vector<Real> weights(system.nVariables(),0);

    for (int i=0;i<num_weight_names;i++)
    {
      std::string name = weight_names[i];
      double value = weight_values[i];

      weights[system.getVariable(0, name).number()] = value;
    }

    std::vector<FEMNormType> norms(system.nVariables(), H1_SEMINORM);

    SystemNorm sys_norm(norms, weights);

    adapt.setErrorNorm(sys_norm);
  }

  adapt.setTimeActive(getParam<Real>("start_time"), getParam<Real>("stop_time"));
}

#endif //LIBMESH_ENABLE_AMR
<commit_msg>AdaptivityAction didn't get a deprecated constructor.<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "AdaptivityAction.h"

#ifdef LIBMESH_ENABLE_AMR

#include "FEProblem.h"
#include "NonlinearSystem.h"
#include "Adaptivity.h"
#include "Executioner.h"
#include "MooseEnum.h"

// libMesh includes
#include "libmesh/transient_system.h"

template<>
InputParameters validParams<AdaptivityAction>()
{
  InputParameters params = validParams<Action>();
  MooseEnum estimators("KellyErrorEstimator LaplacianErrorEstimator PatchRecoveryErrorEstimator", "KellyErrorEstimator");

  params.addParam<unsigned int>("steps",                       0, "The number of adaptivity steps to perform at any one time for steady state");
  params.addParam<unsigned int>("initial_adaptivity",          0, "The number of adaptivity steps to perform using the initial conditions");
  params.addParam<Real> ("refine_fraction",                    0.0, "The fraction of elements or error to refine. Should be between 0 and 1.");
  params.addParam<Real> ("coarsen_fraction",                   0.0, "The fraction of elements or error to coarsen. Should be between 0 and 1.");
  params.addParam<unsigned int> ("max_h_level",                0, "Maximum number of times a single element can be refined. If 0 then infinite.");
  params.addParam<MooseEnum> ("error_estimator",               estimators, "The class name of the error estimator you want to use.");
  params.addDeprecatedParam<bool> ("print_changed_info", false,
                                   "Determines whether information about the mesh is printed when adaptivity occurs",
                                   "Use the Console output parameter 'print_mesh_changed_info'");
  params.addParam<Real>("start_time", -std::numeric_limits<Real>::max(), "The time that adaptivity will be active after.");
  params.addParam<Real>("stop_time", std::numeric_limits<Real>::max(), "The time after which adaptivity will no longer be active.");
  params.addParam<std::vector<std::string> > ("weight_names", "List of names of variables that will be associated with weight_values");
  params.addParam<std::vector<Real> > ("weight_values", "List of values between 0 and 1 to weight the associated weight_names error by");
  params.addParam<unsigned int>("cycles_per_step", 1, "The number of adaptivity cycles per step");

  params.addParam<bool>("show_initial_progress", true, "Show the progress of the initial adaptivity");
  return params;
}

AdaptivityAction::AdaptivityAction(InputParameters params) :
    Action(params)
{
}

void
AdaptivityAction::act()
{
  NonlinearSystem & system = _problem->getNonlinearSystem();

  Adaptivity & adapt = _problem->adaptivity();

  adapt.init(getParam<unsigned int>("steps"), getParam<unsigned int>("initial_adaptivity"));

  adapt.setErrorEstimator(getParam<MooseEnum>("error_estimator"));

  adapt.setParam("cycles_per_step", getParam<unsigned int>("cycles_per_step"));
  adapt.setParam("refine fraction", getParam<Real>("refine_fraction"));
  adapt.setParam("coarsen fraction", getParam<Real>("coarsen_fraction"));
  adapt.setParam("max h-level", getParam<unsigned int>("max_h_level"));

  adapt.setPrintMeshChanged(getParam<bool>("print_changed_info"));

  const std::vector<std::string> & weight_names = getParam<std::vector<std::string> >("weight_names");
  const std::vector<Real> & weight_values = getParam<std::vector<Real> >("weight_values");

  int num_weight_names  = weight_names.size();
  int num_weight_values = weight_values.size();

  if (num_weight_names)
  {
    if (num_weight_names != num_weight_values)
      mooseError("Number of weight_names must be equal to number of weight_values in Execution/Adaptivity");

    // If weights have been specified then set the default weight to zero
    std::vector<Real> weights(system.nVariables(),0);

    for (int i=0;i<num_weight_names;i++)
    {
      std::string name = weight_names[i];
      double value = weight_values[i];

      weights[system.getVariable(0, name).number()] = value;
    }

    std::vector<FEMNormType> norms(system.nVariables(), H1_SEMINORM);

    SystemNorm sys_norm(norms, weights);

    adapt.setErrorNorm(sys_norm);
  }

  adapt.setTimeActive(getParam<Real>("start_time"), getParam<Real>("stop_time"));
}

// DEPRECATED CONSTRUCTOR
AdaptivityAction::AdaptivityAction(const std::string & deprecated_name, InputParameters params) :
    Action(deprecated_name, params)
{
}

#endif //LIBMESH_ENABLE_AMR
<|endoftext|>


<commit_before>// Copyright(c) 2016 Jounayd Id Salah
// Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT).
#include "memory/pch.h"
#include "memory/allocator/coLocalAllocator.h"
#include "debug/log/coAssert.h"
#include "debug/log/coLog.h"

coLocalAllocator::coLocalAllocator(coUint32 _maxStackAlloc)
	: stackBuffer(nullptr)
	, allocatedStackSize8(0)
	, maxStackAlloc(_maxStackAlloc)
{
	coASSERT(maxStackAlloc < 16 * 1024); // safety
	coAllocator* stackAllocator = coAllocator::GetStack();
	coASSERT(stackAllocator);
	stackBuffer = static_cast<coByte*>(stackAllocator->Allocate(_maxStackAlloc));
	coASSERT(stackBuffer);

	coTODO("Check for memory leaks");
}

coLocalAllocator::~coLocalAllocator()
{
	coAllocator* stackAllocator = coAllocator::GetStack();
	stackAllocator->Free(stackBuffer);
}

void* coLocalAllocator::Allocate(coUint32 _size8)
{
	const coUint32 newStackAllocated = allocatedStackSize8 + _size8;
	if (newStackAllocated <= maxStackAlloc)
	{
		void* p = stackBuffer + allocatedStackSize8;
		allocatedStackSize8 = newStackAllocated;
		return p;
	}
	else
	{
		coAllocator* defaultAllocator = coAllocator::GetHeap();
		coASSERT(defaultAllocator);
		return defaultAllocator->Allocate(_size8);
	}
}

void* coLocalAllocator::AllocateAligned(coUint32 /*_size8*/, coUint /*_alignment*/)
{
	coWARN_NOT_AVAILABLE();
	return nullptr;
}

void coLocalAllocator::Free(void* _p)
{
	if (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))
	{
		coAllocator* defaultAllocator = coAllocator::GetHeap();
		coASSERT(defaultAllocator);
		defaultAllocator->Free(_p);
	}
}

void coLocalAllocator::FreeAligned(void* _p)
{
	if (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))
	{
		coAllocator* defaultAllocator = coAllocator::GetHeap();
		coASSERT(defaultAllocator);
		defaultAllocator->FreeAligned(_p);
	}
}
<commit_msg>Added aligned local alloc implementation.<commit_after>// Copyright(c) 2016 Jounayd Id Salah
// Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT).
#include "memory/pch.h"
#include "memory/allocator/coLocalAllocator.h"
#include "debug/log/coAssert.h"
#include "debug/log/coLog.h"

coLocalAllocator::coLocalAllocator(coUint32 _maxStackAlloc)
	: stackBuffer(nullptr)
	, allocatedStackSize8(0)
	, maxStackAlloc(_maxStackAlloc)
{
	coASSERT(maxStackAlloc < 16 * 1024); // safety
	coAllocator* stackAllocator = coAllocator::GetStack();
	coASSERT(stackAllocator);
	stackBuffer = static_cast<coByte*>(stackAllocator->Allocate(_maxStackAlloc));
	coASSERT(stackBuffer);

	coTODO("Check for memory leaks");
}

coLocalAllocator::~coLocalAllocator()
{
	coAllocator* stackAllocator = coAllocator::GetStack();
	stackAllocator->Free(stackBuffer);
}

void* coLocalAllocator::Allocate(coUint32 _size8)
{
	const coUint32 newStackAllocated = allocatedStackSize8 + _size8;
	if (newStackAllocated <= maxStackAlloc)
	{
		void* p = stackBuffer + allocatedStackSize8;
		allocatedStackSize8 = newStackAllocated;
		return p;
	}
	else
	{
		coAllocator* defaultAllocator = coAllocator::GetHeap();
		coASSERT(defaultAllocator);
		return defaultAllocator->Allocate(_size8);
	}
}

void* coLocalAllocator::AllocateAligned(coUint32 _size8, coUint _alignment)
{
	const coUint32 newStackAllocated = allocatedStackSize8 + _size8 + _alignment;
	if (newStackAllocated <= maxStackAlloc)
	{
		void* buffer = stackBuffer + allocatedStackSize8;
		void* p = reinterpret_cast<void*>((reinterpret_cast<coIntPtr>(buffer) & ~(coIntPtr(_alignment - 1))) + _alignment);
		//*(reinterpret_cast<void**>(p) - 1) = buffer;
		allocatedStackSize8 = newStackAllocated;
		return p;
	}
	else
	{
		coAllocator* defaultAllocator = coAllocator::GetHeap();
		coASSERT(defaultAllocator);
		return defaultAllocator->AllocateAligned(_size8, _alignment);
	}
}

void coLocalAllocator::Free(void* _p)
{
	if (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))
	{
		coAllocator* defaultAllocator = coAllocator::GetHeap();
		coASSERT(defaultAllocator);
		defaultAllocator->Free(_p);
	}
}

void coLocalAllocator::FreeAligned(void* _p)
{
	if (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))
	{
		coAllocator* defaultAllocator = coAllocator::GetHeap();
		coASSERT(defaultAllocator);
		defaultAllocator->FreeAligned(_p);
	}
}
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015-2016, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <mutex>
#include <thread>

#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
#include <gtest/gtest.h>

#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"

using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;
using std::chrono::system_clock;

namespace grpc {
namespace testing {

namespace {

// When echo_deadline is requested, deadline seen in the ServerContext is set in
// the response in seconds.
void MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,
                       EchoResponse* response) {
  if (request->has_param() && request->param().echo_deadline()) {
    gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
    if (context->deadline() != system_clock::time_point::max()) {
      Timepoint2Timespec(context->deadline(), &deadline);
    }
    response->mutable_param()->set_request_deadline(deadline.tv_sec);
  }
}

}  // namespace

class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
 public:
  TestServiceImpl() : signal_client_(false) {}

  Status Echo(ServerContext* context, const EchoRequest* request,
              EchoResponse* response) GRPC_OVERRIDE {
    response->set_message(request->message());
    MaybeEchoDeadline(context, request, response);
    if (request->has_param() && request->param().client_cancel_after_us()) {
      {
        std::unique_lock<std::mutex> lock(mu_);
        signal_client_ = true;
      }
      while (!context->IsCancelled()) {
        gpr_sleep_until(gpr_time_add(
            gpr_now(GPR_CLOCK_REALTIME),
            gpr_time_from_micros(request->param().client_cancel_after_us(),
                                 GPR_TIMESPAN)));
      }
      return Status::CANCELLED;
    } else if (request->has_param() &&
               request->param().server_cancel_after_us()) {
      gpr_sleep_until(gpr_time_add(
          gpr_now(GPR_CLOCK_REALTIME),
          gpr_time_from_micros(request->param().server_cancel_after_us(),
                               GPR_TIMESPAN)));
      return Status::CANCELLED;
    } else {
      EXPECT_FALSE(context->IsCancelled());
    }
    return Status::OK;
  }

  // Unimplemented is left unimplemented to test the returned error.

  Status RequestStream(ServerContext* context,
                       ServerReader<EchoRequest>* reader,
                       EchoResponse* response) GRPC_OVERRIDE {
    EchoRequest request;
    response->set_message("");
    while (reader->Read(&request)) {
      response->mutable_message()->append(request.message());
    }
    return Status::OK;
  }

  // Return 3 messages.
  // TODO(yangg) make it generic by adding a parameter into EchoRequest
  Status ResponseStream(ServerContext* context, const EchoRequest* request,
                        ServerWriter<EchoResponse>* writer) GRPC_OVERRIDE {
    EchoResponse response;
    response.set_message(request->message() + "0");
    writer->Write(response);
    response.set_message(request->message() + "1");
    writer->Write(response);
    response.set_message(request->message() + "2");
    writer->Write(response);

    return Status::OK;
  }

  Status BidiStream(ServerContext* context,
                    ServerReaderWriter<EchoResponse, EchoRequest>* stream)
      GRPC_OVERRIDE {
    EchoRequest request;
    EchoResponse response;
    while (stream->Read(&request)) {
      gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
      response.set_message(request.message());
      stream->Write(response);
    }
    return Status::OK;
  }

  bool signal_client() {
    std::unique_lock<std::mutex> lock(mu_);
    return signal_client_;
  }

 private:
  bool signal_client_;
  std::mutex mu_;
};

class TestServiceImplDupPkg
    : public ::grpc::testing::duplicate::EchoTestService::Service {
 public:
  Status Echo(ServerContext* context, const EchoRequest* request,
              EchoResponse* response) GRPC_OVERRIDE {
    response->set_message("no package");
    return Status::OK;
  }
};

class AsyncClientEnd2endTest : public ::testing::Test {
 protected:
  AsyncClientEnd2endTest() : kMaxMessageSize_(8192), rpcs_outstanding_(0) {}

  void SetUp() GRPC_OVERRIDE {
    int port = grpc_pick_unused_port_or_die();
    server_address_ << "localhost:" << port;
    // Setup server
    ServerBuilder builder;
    builder.AddListeningPort(server_address_.str(),
                             InsecureServerCredentials());
    builder.RegisterService(&service_);
    builder.SetMaxMessageSize(
        kMaxMessageSize_);  // For testing max message size.
    server_ = builder.BuildAndStart();
  }

  void TearDown() GRPC_OVERRIDE { server_->Shutdown(); }

  void ResetStub() {
    std::shared_ptr<Channel> channel =
        CreateChannel(server_address_.str(), InsecureChannelCredentials());
    stub_ = grpc::testing::EchoTestService::NewStub(channel);
  }

  void Wait() {
    std::unique_lock<std::mutex> l(mu_);
    while (rpcs_outstanding_ != 0) {
      cv_.wait(l);
    }

    cq_.Shutdown();
  }

  struct AsyncClientCall {
    EchoResponse response;
    ClientContext context;
    Status status;
    std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;
  };

  void AsyncSendRpc(int num_rpcs) {
    for (int i = 0; i < num_rpcs; ++i) {
      AsyncClientCall* call = new AsyncClientCall;
      EchoRequest request;
      request.set_message(std::to_string(i));
      call->response_reader = stub_->AsyncEcho(&call->context, request, &cq_);
      call->response_reader->Finish(&call->response, &call->status,
                                    (void*)call);

      std::unique_lock<std::mutex> l(mu_);
      rpcs_outstanding_++;
    }
  }

  void AsyncCompleteRpc() {
    while (true) {
      void* got_tag;
      bool ok = false;
      if (!cq_.Next(&got_tag, &ok)) break;
      Call* call = static_cast<Call*>(got_tag);
      GPR_ASSERT(ok);
      delete call;

      bool notify;
      {
        std::unique_lock<std::mutex> l(mu_);
        rpcs_outstanding_--;
        notify = (rpcs_outstanding_ == 0);
      }
      if (notify) {
        cv_.notify_all();
      }
    }
  }

  std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
  std::unique_ptr<Server> server_;
  std::ostringstream server_address_;
  const int kMaxMessageSize_;
  TestServiceImpl service_;

  CompletionQueue cq_;
  std::mutex mu_;
  std::condition_variable cv_;
  int rpcs_outstanding_;
};

TEST_F(AsyncClientEnd2endTest, ThreadStress) {
  ResetStub();
  std::vector<std::thread*> threads;
  for (int i = 0; i < 100; ++i) {
    threads.push_back(new std::thread(
        &AsyncClientEnd2endTest_ThreadStress_Test::AsyncSendRpc, this, 1000));
  }
  for (int i = 0; i < 100; ++i) {
    threads[i]->join();
    delete threads[i];
  }

  threads.clear();

  for (int i = 0; i < 100; ++i) {
    threads.push_back(new std::thread(
        &AsyncClientEnd2endTest_ThreadStress_Test::AsyncCompleteRpc, this));
  }
  Wait();
  for (int i = 0; i < 100; ++i) {
    threads[i]->join();
    delete threads[i];
  }
}

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  grpc_test_init(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Trim some unused code copied from another test.<commit_after>/*
 *
 * Copyright 2015-2016, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <mutex>
#include <thread>

#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
#include <gtest/gtest.h>

#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"

using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;
using std::chrono::system_clock;

namespace grpc {
namespace testing {

namespace {

// When echo_deadline is requested, deadline seen in the ServerContext is set in
// the response in seconds.
void MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,
                       EchoResponse* response) {
  if (request->has_param() && request->param().echo_deadline()) {
    gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
    if (context->deadline() != system_clock::time_point::max()) {
      Timepoint2Timespec(context->deadline(), &deadline);
    }
    response->mutable_param()->set_request_deadline(deadline.tv_sec);
  }
}

}  // namespace

class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
 public:
  TestServiceImpl() : signal_client_(false) {}

  Status Echo(ServerContext* context, const EchoRequest* request,
              EchoResponse* response) GRPC_OVERRIDE {
    response->set_message(request->message());
    MaybeEchoDeadline(context, request, response);
    if (request->has_param() && request->param().client_cancel_after_us()) {
      {
        std::unique_lock<std::mutex> lock(mu_);
        signal_client_ = true;
      }
      while (!context->IsCancelled()) {
        gpr_sleep_until(gpr_time_add(
            gpr_now(GPR_CLOCK_REALTIME),
            gpr_time_from_micros(request->param().client_cancel_after_us(),
                                 GPR_TIMESPAN)));
      }
      return Status::CANCELLED;
    } else if (request->has_param() &&
               request->param().server_cancel_after_us()) {
      gpr_sleep_until(gpr_time_add(
          gpr_now(GPR_CLOCK_REALTIME),
          gpr_time_from_micros(request->param().server_cancel_after_us(),
                               GPR_TIMESPAN)));
      return Status::CANCELLED;
    } else {
      EXPECT_FALSE(context->IsCancelled());
    }
    return Status::OK;
  }

  bool signal_client() {
    std::unique_lock<std::mutex> lock(mu_);
    return signal_client_;
  }

 private:
  bool signal_client_;
  std::mutex mu_;
};

class AsyncClientEnd2endTest : public ::testing::Test {
 protected:
  AsyncClientEnd2endTest() : kMaxMessageSize_(8192), rpcs_outstanding_(0) {}

  void SetUp() GRPC_OVERRIDE {
    int port = grpc_pick_unused_port_or_die();
    server_address_ << "localhost:" << port;
    // Setup server
    ServerBuilder builder;
    builder.AddListeningPort(server_address_.str(),
                             InsecureServerCredentials());
    builder.RegisterService(&service_);
    builder.SetMaxMessageSize(
        kMaxMessageSize_);  // For testing max message size.
    server_ = builder.BuildAndStart();
  }

  void TearDown() GRPC_OVERRIDE { server_->Shutdown(); }

  void ResetStub() {
    std::shared_ptr<Channel> channel =
        CreateChannel(server_address_.str(), InsecureChannelCredentials());
    stub_ = grpc::testing::EchoTestService::NewStub(channel);
  }

  void Wait() {
    std::unique_lock<std::mutex> l(mu_);
    while (rpcs_outstanding_ != 0) {
      cv_.wait(l);
    }

    cq_.Shutdown();
  }

  struct AsyncClientCall {
    EchoResponse response;
    ClientContext context;
    Status status;
    std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;
  };

  void AsyncSendRpc(int num_rpcs) {
    for (int i = 0; i < num_rpcs; ++i) {
      AsyncClientCall* call = new AsyncClientCall;
      EchoRequest request;
      request.set_message(std::to_string(i));
      call->response_reader = stub_->AsyncEcho(&call->context, request, &cq_);
      call->response_reader->Finish(&call->response, &call->status,
                                    (void*)call);

      std::unique_lock<std::mutex> l(mu_);
      rpcs_outstanding_++;
    }
  }

  void AsyncCompleteRpc() {
    while (true) {
      void* got_tag;
      bool ok = false;
      if (!cq_.Next(&got_tag, &ok)) break;
      Call* call = static_cast<Call*>(got_tag);
      GPR_ASSERT(ok);
      delete call;

      bool notify;
      {
        std::unique_lock<std::mutex> l(mu_);
        rpcs_outstanding_--;
        notify = (rpcs_outstanding_ == 0);
      }
      if (notify) {
        cv_.notify_all();
      }
    }
  }

  std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
  std::unique_ptr<Server> server_;
  std::ostringstream server_address_;
  const int kMaxMessageSize_;
  TestServiceImpl service_;

  CompletionQueue cq_;
  std::mutex mu_;
  std::condition_variable cv_;
  int rpcs_outstanding_;
};

TEST_F(AsyncClientEnd2endTest, ThreadStress) {
  ResetStub();
  std::vector<std::thread*> threads;
  for (int i = 0; i < 100; ++i) {
    threads.push_back(new std::thread(
        &AsyncClientEnd2endTest_ThreadStress_Test::AsyncSendRpc, this, 1000));
  }
  for (int i = 0; i < 100; ++i) {
    threads[i]->join();
    delete threads[i];
  }

  threads.clear();

  for (int i = 0; i < 100; ++i) {
    threads.push_back(new std::thread(
        &AsyncClientEnd2endTest_ThreadStress_Test::AsyncCompleteRpc, this));
  }
  Wait();
  for (int i = 0; i < 100; ++i) {
    threads[i]->join();
    delete threads[i];
  }
}

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  grpc_test_init(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/*
 * iapitest - test pluggable apis
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "lsUtil.hpp"
#include "irods_buffer_encryption.hpp"
#include <string>
#include <iostream>

// =-=-=-=-=-=-=-
// NOTE:: these track the same structs in
//     :: the api example libhelloworld.cpp
typedef struct {
    int  _this;
    char _that [64];
} helloInp_t;

typedef struct {
    double _value;
} otherOut_t;

typedef struct {
    int  _this;
    char _that [64];
    otherOut_t _other;
} helloOut_t;

void usage();

int
main( int argc, char **argv ) {

    rodsEnv myEnv;
    int status = getRodsEnv( &myEnv );
    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
        exit( 1 );
    }

    rErrMsg_t errMsg;
    rcComm_t *conn;
    conn = rcConnect(
               myEnv.rodsHost,
               myEnv.rodsPort,
               myEnv.rodsUserName,
               myEnv.rodsZone,
               0, &errMsg );

    if ( conn == NULL ) {
        exit( 2 );
    }

    // =-=-=-=-=-=-=-
    // initialize pluggable api table
    irods::pack_entry_table& pk_tbl = irods::get_pack_table();
    irods::api_entry_table& api_tbl = irods::get_client_api_table();
    init_api_table( api_tbl, pk_tbl );

    if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {
        status = clientLogin( conn );
        if ( status != 0 ) {
            rcDisconnect( conn );
            exit( 7 );
        }
    }

    helloInp_t inp;
    memset( &inp, 0, sizeof( inp ) );
    inp._this = 42;
    strncpy( inp._that, "hello, world.", 64 );

    helloOut_t* out = 0;
    void* tmp_out = static_cast< void* >( out );
    status = procApiRequest( conn, 1300, &inp, NULL,
                             &tmp_out, NULL );
    if ( status < 0 ) {
        printf( "\n\nERROR - failed to call our api\n\n\n" );
        return 0;
    }
    else {
        if ( out != NULL ) {
            printf( "\n\nthis [%d]  that [%s] other [%f]\n", out->_this, out->_that, out->_other._value );
        }
    }

    rcDisconnect( conn );
}

<commit_msg>[#2014] additional updates to iapitest<commit_after>/*
 * iapitest - test pluggable apis
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "lsUtil.hpp"
#include "irods_buffer_encryption.hpp"
#include <string>
#include <iostream>

// =-=-=-=-=-=-=-
// NOTE:: these track the same structs in
//     :: the api example libhelloworld.cpp
typedef struct {
    int  _this;
    char _that [64];
} helloInp_t;

typedef struct {
    double _value;
} otherOut_t;

typedef struct {
    int  _this;
    char _that [64];
    otherOut_t _other;
} helloOut_t;

void usage();

int
main( int argc, char **argv ) {

    rodsEnv myEnv;
    int status = getRodsEnv( &myEnv );
    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
        exit( 1 );
    }

    rErrMsg_t errMsg;
    rcComm_t *conn;
    conn = rcConnect(
               myEnv.rodsHost,
               myEnv.rodsPort,
               myEnv.rodsUserName,
               myEnv.rodsZone,
               0, &errMsg );

    if ( conn == NULL ) {
        exit( 2 );
    }

    // =-=-=-=-=-=-=-
    // initialize pluggable api table
    irods::pack_entry_table& pk_tbl = irods::get_pack_table();
    irods::api_entry_table& api_tbl = irods::get_client_api_table();
    init_api_table( api_tbl, pk_tbl );

    if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {
        status = clientLogin( conn );
        if ( status != 0 ) {
            rcDisconnect( conn );
            exit( 7 );
        }
    }

    helloInp_t inp;
    memset( &inp, 0, sizeof( inp ) );
    inp._this = 42;
    strncpy( inp._that, "hello, world.", 64 );

    helloOut_t* out = 0;
    void* tmp_out = static_cast< void* >( out );
    status = procApiRequest( conn, 1300, &inp, NULL,
                             &( tmp_out ), NULL );
    if ( status < 0 ) {
        printf( "\n\nERROR - failed to call our api\n\n\n" );
        return 0;
    }
    else {
        if ( out != NULL ) {
            printf( "\n\nthis [%d]  that [%s] other [%f]\n", out->_this, out->_that, out->_other._value );
        }
    }

    rcDisconnect( conn );
}

<|endoftext|>


<commit_before>/*
    Kopete Yahoo Protocol
    Notifies about incoming filetransfers

    Copyright (c) 2006 André Duffeck <andre.duffeck@kdemail.net>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "filetransfernotifiertask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <QString>
#include <QFile>
#include <QPixmap>
#include <kdebug.h>
#include <kcodecs.h>

FileTransferNotifierTask::FileTransferNotifierTask(Task* parent) : Task(parent)
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}

FileTransferNotifierTask::~FileTransferNotifierTask()
{

}

bool FileTransferNotifierTask::take( Transfer* transfer )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	if ( !forMe( transfer ) )
		return false;

	YMSGTransfer *t = static_cast<YMSGTransfer*>(transfer);

	if( t->service() == Yahoo::ServiceFileTransfer )
		parseFileTransfer( t );
	else if( t->service() == Yahoo::ServiceFileTransfer7 )
		parseFileTransfer7( t );
	else if( t->service() == Yahoo::ServicePeerToPeer )
		acceptFileTransfer( t );

	return true;
}

bool FileTransferNotifierTask::forMe( const Transfer *transfer ) const
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
	const YMSGTransfer *t = 0L;
	t = dynamic_cast<const YMSGTransfer*>(transfer);
	if (!t)
		return false;

	if( t->service() == Yahoo::ServiceP2PFileXfer ||
		t->service() == Yahoo::ServicePeerToPeer ||
		t->service() == Yahoo::ServiceFileTransfer ||
		t->service() == Yahoo::ServiceFileTransfer7
	)
		return true;
	else
		return false;
}

void FileTransferNotifierTask::parseFileTransfer( YMSGTransfer *t )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	QString from;		/* key = 4  */
	QString to;		/* key = 5  */
	QString url;		/* key = 20  */
	long expires;		/* key = 38  */
	QString msg;		/* key = 14  */
	QString filename;	/* key = 27  */
	unsigned long size;	/* key = 28  */

	from = t->firstParam( 4 );
	to = t->firstParam( 5 );
	url = t->firstParam( 20 );
	expires = t->firstParam( 38 ).toLong();
	msg = t->firstParam( 14 );
	filename = t->firstParam( 27 );
	size = t->firstParam( 28 ).toULong();

	if( from.startsWith( "FILE_TRANSFER_SYSTEM" ) )
	{
		client()->notifyError( "Fileupload result received.", msg, Client::Notice );
		return;
	}

	if( url.isEmpty() )
		return;

	unsigned int left = url.findRev( '/' ) + 1;
	unsigned int right = url.findRev( '?' );
	filename = url.mid( left, right - left );

	emit incomingFileTransfer( from, url, expires, msg, filename, size, QPixmap() );
}

void FileTransferNotifierTask::parseFileTransfer7( YMSGTransfer *t )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	QString from;		/* key = 4  */
	QString to;		/* key = 5  */
	QString url;		/* key = 20  */
	long expires;		/* key = 38  */
	QString msg;		/* key = 14  */
	QString filename;	/* key = 27  */
	unsigned long size;	/* key = 28  */
	QByteArray preview;	/* key = 267 */
	QPixmap previewPixmap;

	if( t->firstParam( 222 ).toInt() == 2 )
		return;					// user cancelled the file transfer

	from = t->firstParam( 4 );
	to = t->firstParam( 5 );
	url = t->firstParam( 265 );
	msg = t->firstParam( 14 );
	expires = t->firstParam( 38 ).toLong();
	filename = t->firstParam( 27 );
	size = t->firstParam( 28 ).toULong();
	preview = KCodecs::base64Decode( t->firstParam( 267 ) );

	if( preview.size() > 0 )
	{
		previewPixmap.loadFromData( preview );
	}

	emit incomingFileTransfer( from, url, expires, msg, filename, size, previewPixmap );
}

void FileTransferNotifierTask::acceptFileTransfer( YMSGTransfer *transfer )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	YMSGTransfer *t = new YMSGTransfer(Yahoo::ServicePeerToPeer);
	t->setId( client()->sessionID() );
	t->setParam( 4, client()->userId().toLocal8Bit() );
	t->setParam( 5, transfer->firstParam( 4 ) );
	t->setParam( 11, transfer->firstParam( 11 ) );

	send( t );
}

#include "filetransfernotifiertask.moc"
<commit_msg>deprecated--<commit_after>/*
    Kopete Yahoo Protocol
    Notifies about incoming filetransfers

    Copyright (c) 2006 André Duffeck <andre.duffeck@kdemail.net>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "filetransfernotifiertask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <QString>
#include <QFile>
#include <QPixmap>
#include <kdebug.h>
#include <kcodecs.h>

FileTransferNotifierTask::FileTransferNotifierTask(Task* parent) : Task(parent)
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}

FileTransferNotifierTask::~FileTransferNotifierTask()
{

}

bool FileTransferNotifierTask::take( Transfer* transfer )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	if ( !forMe( transfer ) )
		return false;

	YMSGTransfer *t = static_cast<YMSGTransfer*>(transfer);

	if( t->service() == Yahoo::ServiceFileTransfer )
		parseFileTransfer( t );
	else if( t->service() == Yahoo::ServiceFileTransfer7 )
		parseFileTransfer7( t );
	else if( t->service() == Yahoo::ServicePeerToPeer )
		acceptFileTransfer( t );

	return true;
}

bool FileTransferNotifierTask::forMe( const Transfer *transfer ) const
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
	const YMSGTransfer *t = 0L;
	t = dynamic_cast<const YMSGTransfer*>(transfer);
	if (!t)
		return false;

	if( t->service() == Yahoo::ServiceP2PFileXfer ||
		t->service() == Yahoo::ServicePeerToPeer ||
		t->service() == Yahoo::ServiceFileTransfer ||
		t->service() == Yahoo::ServiceFileTransfer7
	)
		return true;
	else
		return false;
}

void FileTransferNotifierTask::parseFileTransfer( YMSGTransfer *t )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	QString from;		/* key = 4  */
	QString to;		/* key = 5  */
	QString url;		/* key = 20  */
	long expires;		/* key = 38  */
	QString msg;		/* key = 14  */
	QString filename;	/* key = 27  */
	unsigned long size;	/* key = 28  */

	from = t->firstParam( 4 );
	to = t->firstParam( 5 );
	url = t->firstParam( 20 );
	expires = t->firstParam( 38 ).toLong();
	msg = t->firstParam( 14 );
	filename = t->firstParam( 27 );
	size = t->firstParam( 28 ).toULong();

	if( from.startsWith( "FILE_TRANSFER_SYSTEM" ) )
	{
		client()->notifyError( "Fileupload result received.", msg, Client::Notice );
		return;
	}

	if( url.isEmpty() )
		return;

	unsigned int left = url.lastIndexOf( '/' ) + 1;
	unsigned int right = url.lastIndexOf( '?' );
	filename = url.mid( left, right - left );

	emit incomingFileTransfer( from, url, expires, msg, filename, size, QPixmap() );
}

void FileTransferNotifierTask::parseFileTransfer7( YMSGTransfer *t )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	QString from;		/* key = 4  */
	QString to;		/* key = 5  */
	QString url;		/* key = 20  */
	long expires;		/* key = 38  */
	QString msg;		/* key = 14  */
	QString filename;	/* key = 27  */
	unsigned long size;	/* key = 28  */
	QByteArray preview;	/* key = 267 */
	QPixmap previewPixmap;

	if( t->firstParam( 222 ).toInt() == 2 )
		return;					// user cancelled the file transfer

	from = t->firstParam( 4 );
	to = t->firstParam( 5 );
	url = t->firstParam( 265 );
	msg = t->firstParam( 14 );
	expires = t->firstParam( 38 ).toLong();
	filename = t->firstParam( 27 );
	size = t->firstParam( 28 ).toULong();
	preview = KCodecs::base64Decode( t->firstParam( 267 ) );

	if( preview.size() > 0 )
	{
		previewPixmap.loadFromData( preview );
	}

	emit incomingFileTransfer( from, url, expires, msg, filename, size, previewPixmap );
}

void FileTransferNotifierTask::acceptFileTransfer( YMSGTransfer *transfer )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	YMSGTransfer *t = new YMSGTransfer(Yahoo::ServicePeerToPeer);
	t->setId( client()->sessionID() );
	t->setParam( 4, client()->userId().toLocal8Bit() );
	t->setParam( 5, transfer->firstParam( 4 ) );
	t->setParam( 11, transfer->firstParam( 11 ) );

	send( t );
}

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