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

#include <zookeeper.h>

#include <gmock/gmock.h>

#include <string>

#include <process/gmock.hpp>
#include <process/gtest.hpp>
#include <process/owned.hpp>

#include <stout/gtest.hpp>
#include <stout/strings.hpp>

#include "master/constants.hpp"

#include "zookeeper/authentication.hpp"
#include "zookeeper/contender.hpp"
#include "zookeeper/detector.hpp"
#include "zookeeper/group.hpp"

#include "tests/zookeeper.hpp"

using namespace mesos::internal;
using namespace mesos::internal::tests;
using namespace process;
using namespace zookeeper;

TEST_F(ZooKeeperTest, Auth)
{
  ZooKeeperTest::TestWatcher watcher;

  ZooKeeper authenticatedZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  authenticatedZk.authenticate("digest", "creator:creator");
  authenticatedZk.create("/test",
                         "42",
                         zookeeper::EVERYONE_READ_CREATOR_ALL,
                         0,
                         NULL);
  ASSERT_ZK_GET("42", &authenticatedZk, "/test");

  ZooKeeper unauthenticatedZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  ASSERT_ZK_GET("42", &unauthenticatedZk, "/test");
  ASSERT_EQ(ZNOAUTH, unauthenticatedZk.set("/test", "", -1));

  ZooKeeper nonOwnerZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  nonOwnerZk.authenticate("digest", "non-owner:non-owner");
  ASSERT_ZK_GET("42", &nonOwnerZk, "/test");
  ASSERT_EQ(ZNOAUTH, nonOwnerZk.set("/test", "", -1));
}

TEST_F(ZooKeeperTest, SessionTimeoutNegotiation)
{
  server->setMinSessionTimeout(Seconds(8));
  server->setMaxSessionTimeout(Seconds(20));
  EXPECT_EQ(Seconds(8), server->getMinSessionTimeout());
  EXPECT_EQ(Seconds(20), server->getMaxSessionTimeout());

  ZooKeeperTest::TestWatcher watcher;
  ZooKeeper zk1(server->connectString(), Seconds(7), &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);

  // The requested timeout is less than server's min value so the
  // negotiated result is the sever's min value.
  EXPECT_EQ(Seconds(8), zk1.getSessionTimeout());

  ZooKeeper zk2(server->connectString(), Seconds(22), &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);

  // The requested timeout is greater than server's max value so the
  // negotiated result is the sever's max value.
  EXPECT_EQ(Seconds(20), zk2.getSessionTimeout());
}

TEST_F(ZooKeeperTest, Create)
{
  ZooKeeperTest::TestWatcher watcher;

  ZooKeeper authenticatedZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  authenticatedZk.authenticate("digest", "creator:creator");
  EXPECT_EQ(ZOK, authenticatedZk.create("/foo/bar",
                                        "",
                                        zookeeper::EVERYONE_READ_CREATOR_ALL,
                                        0,
                                        NULL,
                                        true));
  authenticatedZk.create("/foo/bar/baz",
                         "43",
                         zookeeper::EVERYONE_CREATE_AND_READ_CREATOR_ALL,
                         0,
                         NULL);
  ASSERT_ZK_GET("43", &authenticatedZk, "/foo/bar/baz");

  ZooKeeper nonOwnerZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  nonOwnerZk.authenticate("digest", "non-owner:non-owner");
  EXPECT_EQ(ZNODEEXISTS, nonOwnerZk.create("/foo/bar/baz",
                                           "",
                                           zookeeper::EVERYONE_READ_CREATOR_ALL,
                                           0,
                                           NULL,
                                           true));
  EXPECT_EQ(ZOK, nonOwnerZk.create("/foo/bar/baz/bam",
                                   "44",
                                   zookeeper::EVERYONE_READ_CREATOR_ALL,
                                   0,
                                   NULL,
                                   true));
  ASSERT_ZK_GET("44", &nonOwnerZk, "/foo/bar/baz/bam");

  std::string result;
  EXPECT_EQ(ZOK, nonOwnerZk.create("/foo/bar/baz/",
                                   "",
                                   zookeeper::EVERYONE_READ_CREATOR_ALL,
                                   ZOO_SEQUENCE | ZOO_EPHEMERAL,
                                   &result,
                                   true));
  EXPECT_TRUE(strings::startsWith(result, "/foo/bar/baz/0"));
}

TEST_F(ZooKeeperTest, LeaderDetector)
{
  Group group(server->connectString(), NO_TIMEOUT, "/test/");

  // Initialize two members.
  Future<Group::Membership> membership1 =
    group.join("member 1");
  AWAIT_READY(membership1);
  Future<Group::Membership> membership2 =
    group.join("member 2");
  AWAIT_READY(membership2);

  LeaderDetector detector(&group);

  // Detect the leader.
  Future<Option<Group::Membership> > leader =
    detector.detect(None());
  AWAIT_READY(leader);
  ASSERT_SOME_EQ(membership1.get(), leader.get());

  // Detect next leader change.
  leader = detector.detect(leader.get());
  EXPECT_TRUE(leader.isPending());

  // Leader doesn't change after cancelling the follower.
  Future<bool> cancellation = group.cancel(membership2.get());
  AWAIT_READY(cancellation);
  EXPECT_TRUE(cancellation.get());
  EXPECT_TRUE(leader.isPending());

  // Join member 2 back.
  membership2 = group.join("member 2");
  AWAIT_READY(membership2);
  EXPECT_TRUE(leader.isPending());

  // Cancelling the incumbent leader allows member 2 to be elected.
  cancellation = group.cancel(membership1.get());
  AWAIT_READY(cancellation);
  EXPECT_TRUE(cancellation.get());
  AWAIT_READY(leader);
  EXPECT_SOME_EQ(membership2.get(), leader.get());

  // Cancelling the only member results in no leader elected.
  leader = detector.detect(leader.get().get());
  EXPECT_TRUE(leader.isPending());
  cancellation = group.cancel(membership2.get());

  AWAIT_READY(cancellation);
  EXPECT_TRUE(cancellation.get());
  AWAIT_READY(leader);
  ASSERT_TRUE(leader.get().isNone());
}

TEST_F(ZooKeeperTest, LeaderDetectorTimeoutHandling)
{
  Seconds timeout(10);
  Group group(server->connectString(), timeout, "/test/");
  LeaderDetector detector(&group);

  Future<Group::Membership> membership1 = group.join("member 1");
  AWAIT_READY(membership1);

  Future<Option<Group::Membership> > leader = detector.detect();

  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());

  leader = detector.detect(leader.get());

  server->shutdownNetwork();

  Clock::pause();

  // We may need to advance multiple times because we could have
  // advanced the clock before the timer in Group starts.
  while (leader.isPending()) {
    Clock::advance(timeout);
    Clock::settle();
  }
  Clock::resume();

  // The detect operation times out.
  EXPECT_NONE(leader.get());

  // Re-detect.
  leader = detector.detect(leader.get());

  Future<Nothing> connected = FUTURE_DISPATCH(
      group.process->self(),
      &GroupProcess::connected);
  server->startNetwork();

  AWAIT_READY(connected);
  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());

  // Wait until the old membership expires on ZK and re-detect.
  // (Restarting network doesn't delete old ZNode automatically).
  AWAIT_READY(leader.get().get().cancelled());
  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_NONE(leader.get());

  AWAIT_READY(group.join("member 1"));

  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());

  // Cancel the member and join another.
  Future<bool> cancelled = group.cancel(leader.get().get());
  AWAIT_READY(cancelled);
  EXPECT_TRUE(cancelled.get());
  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_NONE(leader.get());

  AWAIT_READY(group.join("member 2"));

  // Detect a new leader.
  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());
}

TEST_F(ZooKeeperTest, LeaderContender)
{
  Seconds timeout(10);
  Group group(server->connectString(), timeout, "/test/");

  Owned<LeaderContender> contender(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));

  // Calling withdraw before contending returns 'false' because there
  // is nothing to withdraw.
  Future<bool> withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);
  EXPECT_FALSE(withdrawn.get());

  contender->contend();

  // Immediately withdrawing after contending leads to delayed
  // cancellation.
  withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);
  EXPECT_TRUE(withdrawn.get());

  // Normal workflow.
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));

  Future<Future<Nothing> > candidated = contender->contend();
  AWAIT_READY(candidated);

  Future<Nothing> lostCandidacy = candidated.get();
  EXPECT_TRUE(lostCandidacy.isPending());

  // Expire the Group session while we are watching for updates from
  // the contender and the candidacy will be lost.
  Future<Option<int64_t> > session = group.session();
  AWAIT_READY(session);
  ASSERT_SOME(session.get());

  Future<Nothing> connected = FUTURE_DISPATCH(
      group.process->self(),
      &GroupProcess::connected);
  server->expireSession(session.get().get());
  AWAIT_READY(lostCandidacy);

  // Withdraw directly returns because candidacy is lost and there
  // is nothing to cancel.
  withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);
  EXPECT_FALSE(withdrawn.get());

  // Contend again.
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
  candidated = contender->contend();

  AWAIT_READY(connected);
  session = group.session();
  AWAIT_READY(session);
  ASSERT_SOME(session.get());

  server->expireSession(session.get().get());

  Clock::pause();
  // The retry timeout.
  Clock::advance(GroupProcess::RETRY_INTERVAL);
  Clock::settle();
  Clock::resume();

  // The contender weathered the expiration and succeeded in a retry.
  AWAIT_READY(candidated);

  withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);

  // Contend (3) and shutdown the network this time.
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
  candidated = contender->contend();
  AWAIT_READY(candidated);
  lostCandidacy = candidated.get();

  server->shutdownNetwork();

  Clock::pause();

  // We may need to advance multiple times because we could have
  // advanced the clock before the timer in Group starts.
  while (lostCandidacy.isPending()) {
    Clock::advance(timeout);
    Clock::settle();
  }

  // Server failure results in candidacy loss.
  AWAIT_READY(lostCandidacy);

  Clock::resume();

  server->startNetwork();

  // Contend again (4).
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
  candidated = contender->contend();
  AWAIT_READY(candidated);
}
<commit_msg>Removed the while loops in ZooKeeperTest.<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <zookeeper.h>

#include <gmock/gmock.h>

#include <string>

#include <process/gmock.hpp>
#include <process/gtest.hpp>
#include <process/owned.hpp>

#include <stout/gtest.hpp>
#include <stout/strings.hpp>

#include "master/constants.hpp"

#include "zookeeper/authentication.hpp"
#include "zookeeper/contender.hpp"
#include "zookeeper/detector.hpp"
#include "zookeeper/group.hpp"

#include "tests/zookeeper.hpp"

using namespace mesos::internal;
using namespace mesos::internal::tests;
using namespace process;
using namespace zookeeper;

TEST_F(ZooKeeperTest, Auth)
{
  ZooKeeperTest::TestWatcher watcher;

  ZooKeeper authenticatedZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  authenticatedZk.authenticate("digest", "creator:creator");
  authenticatedZk.create("/test",
                         "42",
                         zookeeper::EVERYONE_READ_CREATOR_ALL,
                         0,
                         NULL);
  ASSERT_ZK_GET("42", &authenticatedZk, "/test");

  ZooKeeper unauthenticatedZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  ASSERT_ZK_GET("42", &unauthenticatedZk, "/test");
  ASSERT_EQ(ZNOAUTH, unauthenticatedZk.set("/test", "", -1));

  ZooKeeper nonOwnerZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  nonOwnerZk.authenticate("digest", "non-owner:non-owner");
  ASSERT_ZK_GET("42", &nonOwnerZk, "/test");
  ASSERT_EQ(ZNOAUTH, nonOwnerZk.set("/test", "", -1));
}

TEST_F(ZooKeeperTest, SessionTimeoutNegotiation)
{
  server->setMinSessionTimeout(Seconds(8));
  server->setMaxSessionTimeout(Seconds(20));
  EXPECT_EQ(Seconds(8), server->getMinSessionTimeout());
  EXPECT_EQ(Seconds(20), server->getMaxSessionTimeout());

  ZooKeeperTest::TestWatcher watcher;
  ZooKeeper zk1(server->connectString(), Seconds(7), &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);

  // The requested timeout is less than server's min value so the
  // negotiated result is the sever's min value.
  EXPECT_EQ(Seconds(8), zk1.getSessionTimeout());

  ZooKeeper zk2(server->connectString(), Seconds(22), &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);

  // The requested timeout is greater than server's max value so the
  // negotiated result is the sever's max value.
  EXPECT_EQ(Seconds(20), zk2.getSessionTimeout());
}

TEST_F(ZooKeeperTest, Create)
{
  ZooKeeperTest::TestWatcher watcher;

  ZooKeeper authenticatedZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  authenticatedZk.authenticate("digest", "creator:creator");
  EXPECT_EQ(ZOK, authenticatedZk.create("/foo/bar",
                                        "",
                                        zookeeper::EVERYONE_READ_CREATOR_ALL,
                                        0,
                                        NULL,
                                        true));
  authenticatedZk.create("/foo/bar/baz",
                         "43",
                         zookeeper::EVERYONE_CREATE_AND_READ_CREATOR_ALL,
                         0,
                         NULL);
  ASSERT_ZK_GET("43", &authenticatedZk, "/foo/bar/baz");

  ZooKeeper nonOwnerZk(server->connectString(), NO_TIMEOUT, &watcher);
  watcher.awaitSessionEvent(ZOO_CONNECTED_STATE);
  nonOwnerZk.authenticate("digest", "non-owner:non-owner");
  EXPECT_EQ(ZNODEEXISTS, nonOwnerZk.create("/foo/bar/baz",
                                           "",
                                           zookeeper::EVERYONE_READ_CREATOR_ALL,
                                           0,
                                           NULL,
                                           true));
  EXPECT_EQ(ZOK, nonOwnerZk.create("/foo/bar/baz/bam",
                                   "44",
                                   zookeeper::EVERYONE_READ_CREATOR_ALL,
                                   0,
                                   NULL,
                                   true));
  ASSERT_ZK_GET("44", &nonOwnerZk, "/foo/bar/baz/bam");

  std::string result;
  EXPECT_EQ(ZOK, nonOwnerZk.create("/foo/bar/baz/",
                                   "",
                                   zookeeper::EVERYONE_READ_CREATOR_ALL,
                                   ZOO_SEQUENCE | ZOO_EPHEMERAL,
                                   &result,
                                   true));
  EXPECT_TRUE(strings::startsWith(result, "/foo/bar/baz/0"));
}

TEST_F(ZooKeeperTest, LeaderDetector)
{
  Group group(server->connectString(), NO_TIMEOUT, "/test/");

  // Initialize two members.
  Future<Group::Membership> membership1 =
    group.join("member 1");
  AWAIT_READY(membership1);
  Future<Group::Membership> membership2 =
    group.join("member 2");
  AWAIT_READY(membership2);

  LeaderDetector detector(&group);

  // Detect the leader.
  Future<Option<Group::Membership> > leader =
    detector.detect(None());
  AWAIT_READY(leader);
  ASSERT_SOME_EQ(membership1.get(), leader.get());

  // Detect next leader change.
  leader = detector.detect(leader.get());
  EXPECT_TRUE(leader.isPending());

  // Leader doesn't change after cancelling the follower.
  Future<bool> cancellation = group.cancel(membership2.get());
  AWAIT_READY(cancellation);
  EXPECT_TRUE(cancellation.get());
  EXPECT_TRUE(leader.isPending());

  // Join member 2 back.
  membership2 = group.join("member 2");
  AWAIT_READY(membership2);
  EXPECT_TRUE(leader.isPending());

  // Cancelling the incumbent leader allows member 2 to be elected.
  cancellation = group.cancel(membership1.get());
  AWAIT_READY(cancellation);
  EXPECT_TRUE(cancellation.get());
  AWAIT_READY(leader);
  EXPECT_SOME_EQ(membership2.get(), leader.get());

  // Cancelling the only member results in no leader elected.
  leader = detector.detect(leader.get().get());
  EXPECT_TRUE(leader.isPending());
  cancellation = group.cancel(membership2.get());

  AWAIT_READY(cancellation);
  EXPECT_TRUE(cancellation.get());
  AWAIT_READY(leader);
  ASSERT_TRUE(leader.get().isNone());
}

TEST_F(ZooKeeperTest, LeaderDetectorTimeoutHandling)
{
  Seconds timeout(10);
  Group group(server->connectString(), timeout, "/test/");
  LeaderDetector detector(&group);

  Future<Group::Membership> membership1 = group.join("member 1");
  AWAIT_READY(membership1);

  Future<Option<Group::Membership> > leader = detector.detect();

  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());

  leader = detector.detect(leader.get());

  Future<Nothing> reconnecting = FUTURE_DISPATCH(
      group.process->self(),
      &GroupProcess::reconnecting);

  server->shutdownNetwork();

  AWAIT_READY(reconnecting);

  Clock::pause();

  // Settle to make sure 'reconnecting' schedules the timeout before
  // we advance.
  Clock::settle();
  Clock::advance(timeout);

  AWAIT_READY(leader);

  Clock::resume();

  // The detect operation times out.
  EXPECT_NONE(leader.get());

  // Re-detect.
  leader = detector.detect(leader.get());

  Future<Nothing> connected = FUTURE_DISPATCH(
      group.process->self(),
      &GroupProcess::connected);
  server->startNetwork();

  AWAIT_READY(connected);
  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());

  // Wait until the old membership expires on ZK and re-detect.
  // (Restarting network doesn't delete old ZNode automatically).
  AWAIT_READY(leader.get().get().cancelled());
  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_NONE(leader.get());

  AWAIT_READY(group.join("member 1"));

  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());

  // Cancel the member and join another.
  Future<bool> cancelled = group.cancel(leader.get().get());
  AWAIT_READY(cancelled);
  EXPECT_TRUE(cancelled.get());
  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_NONE(leader.get());

  AWAIT_READY(group.join("member 2"));

  // Detect a new leader.
  leader = detector.detect(leader.get());
  AWAIT_READY(leader);
  EXPECT_SOME(leader.get());
}

TEST_F(ZooKeeperTest, LeaderContender)
{
  Seconds timeout(10);
  Group group(server->connectString(), timeout, "/test/");

  Owned<LeaderContender> contender(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));

  // Calling withdraw before contending returns 'false' because there
  // is nothing to withdraw.
  Future<bool> withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);
  EXPECT_FALSE(withdrawn.get());

  contender->contend();

  // Immediately withdrawing after contending leads to delayed
  // cancellation.
  withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);
  EXPECT_TRUE(withdrawn.get());

  // Normal workflow.
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));

  Future<Future<Nothing> > candidated = contender->contend();
  AWAIT_READY(candidated);

  Future<Nothing> lostCandidacy = candidated.get();
  EXPECT_TRUE(lostCandidacy.isPending());

  // Expire the Group session while we are watching for updates from
  // the contender and the candidacy will be lost.
  Future<Option<int64_t> > session = group.session();
  AWAIT_READY(session);
  ASSERT_SOME(session.get());

  Future<Nothing> connected = FUTURE_DISPATCH(
      group.process->self(),
      &GroupProcess::connected);
  server->expireSession(session.get().get());
  AWAIT_READY(lostCandidacy);

  // Withdraw directly returns because candidacy is lost and there
  // is nothing to cancel.
  withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);
  EXPECT_FALSE(withdrawn.get());

  // Contend again.
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
  candidated = contender->contend();

  AWAIT_READY(connected);
  session = group.session();
  AWAIT_READY(session);
  ASSERT_SOME(session.get());

  server->expireSession(session.get().get());

  Clock::pause();
  // The retry timeout.
  Clock::advance(GroupProcess::RETRY_INTERVAL);
  Clock::settle();
  Clock::resume();

  // The contender weathered the expiration and succeeded in a retry.
  AWAIT_READY(candidated);

  withdrawn = contender->withdraw();
  AWAIT_READY(withdrawn);

  // Contend (3) and shutdown the network this time.
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
  candidated = contender->contend();
  AWAIT_READY(candidated);
  lostCandidacy = candidated.get();

  Future<Nothing> reconnecting = FUTURE_DISPATCH(
      group.process->self(),
      &GroupProcess::reconnecting);

  server->shutdownNetwork();

  AWAIT_READY(reconnecting);

  Clock::pause();

  // Settle to make sure 'reconnecting()' schedules the timeout
  // before we advance.
  Clock::settle();
  Clock::advance(timeout);

  // Server failure results in candidacy loss.
  AWAIT_READY(lostCandidacy);

  Clock::resume();

  server->startNetwork();

  // Contend again (4).
  contender = Owned<LeaderContender>(
      new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
  candidated = contender->contend();
  AWAIT_READY(candidated);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EventMultiplexer.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-04-26 20:45:46 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SD_TOOLS_EVENT_MULTIPLEXER_HXX
#define SD_TOOLS_EVENT_MULTIPLEXER_HXX

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif

#include <set>
#include <memory>

class Link;

namespace sd {
class ViewShellBase;
}

namespace sd { namespace tools {

class EventMultiplexerEvent
{
public:
    typedef sal_uInt32 EventId;
    /** The EventMultiplexer itself is being disposed.  Called for a live
        EventMultiplexer.  Removing a listener as response is not necessary,
        though.
    */
    static const EventId EID_DISPOSING              = 0x00000001;

    /** The selection in the center pane has changed.
    */
    static const EventId EID_EDIT_VIEW_SELECTION    = 0x00000002;

    /** The selection in the slide sorter has changed, regardless of whether
        the slide sorter is displayed in the left pane or the center pane.
    */
    static const EventId EID_SLIDE_SORTER_SELECTION = 0x00000004;

    /** The current page has changed.
    */
    static const EventId EID_CURRENT_PAGE           = 0x00000008;

    /** The current MainViewShell (the ViewShell displayed in the center
        pane) has been removed.
    */
    static const EventId EID_MAIN_VIEW_REMOVED      = 0x00000010;

    /** A new ViewShell has been made the MainViewShell.
    */
    static const EventId EID_MAIN_VIEW_ADDED        = 0x00000020;

    /** A ViewShell has been removed from one of the panes.  Note that for
        the ViewShell in the center pane bth this event type and
        EID_MAIN_VIEW_REMOVED is broadcasted.
    */
    static const EventId EID_VIEW_REMOVED           = 0x00000040;

    /** A new ViewShell is being displayed in one of the panes.  Note that
        for the ViewShell in the center pane both this event type and
        EID_MAIN_VIEW_ADDED is broadcasted.
    */
    static const EventId EID_VIEW_ADDED             = 0x00000080;

    /** The PaneManager is being destroyed.
    */
    static const EventId EID_PANE_MANAGER_DYING     = 0x00000100;

    /** The edit mode of the ViewShell in the center pane has been modified.
    */
    static const EventId EID_EDIT_MODE              = 0x00000200;

    /** One or more pages have been inserted into or deleted from the model.
    */
    static const EventId EID_PAGE_ORDER             = 0x00000400;

    /** Text editing in one of the shapes in the MainViewShell has started.
    */
    static const EventId EID_BEGIN_TEXT_EDIT        = 0x00000800;

    /** Text editing in one of the shapes in the MainViewShell has ended.
    */
    static const EventId EID_END_TEXT_EDIT          = 0x00001000;

    /** A UNO controller has been attached to the UNO frame.
    */
    static const EventId EID_CONTROLLER_ATTACHED    = 0x00002000;

    /** A UNO controller has been detached to the UNO frame.
    */
    static const EventId EID_CONTROLLER_DETACHED    = 0x00004000;

    /** The state of a shape has changed.  The page is available in the user data.
    */
    static const EventId EID_SHAPE_CHANGED          = 0x00008000;

    /** A shape has been inserted to a page.  The page is available in the
        user data.
    */
    static const EventId EID_SHAPE_INSERTED         = 0x00010000;

    /** A shape has been removed from a page.  The page is available in the
        user data.
    */
    static const EventId EID_SHAPE_REMOVED          = 0x00020000;

    const ViewShellBase& mrBase;
    EventId meEventId;
    const void* mpUserData;

    EventMultiplexerEvent (
        const ViewShellBase& rBase,
        EventId eEventId,
        const void* pUserData);
};

/** This convenience class makes it easy to listen to various events that
    originally are broadcasted via different channels.

    There is usually one EventMultiplexer instance per ViewShellBase().
    Call the laters GetEventMultiplexer() method to get access to that
    instance.

    When a listener is registered it can specify the events it
    wants to be informed of.  This can be done with code like the following:

    mrViewShellBase.GetEventMultiplexer().AddEventListener (
        LINK(this,MasterPagesSelector,EventMultiplexerListener),
        tools::EventMultiplexerEvent::EID_MAIN_VIEW_ADDED
        | tools::EventMultiplexerEvent::EID_MAIN_VIEW_REMOVED);
*/
class EventMultiplexer
{
public:
    /** Create new EventMultiplexer for the given ViewShellBase object.
    */
    EventMultiplexer (ViewShellBase& rBase);
    ~EventMultiplexer (void);

    /** Some constants that make it easier to remove a listener for all
        event types at once.
    */
    static const EventMultiplexerEvent::EventId EID_FULL_SET = 0xffffffff;
    static const EventMultiplexerEvent::EventId EID_EMPTY_SET = 0x00000000;

    /** Add an event listener that will be informed about the specified
        event types.
        @param rCallback
            The callback to call as soon as one of the event specified by
            aEventTypeSet is received by the EventMultiplexer.
        @param aEventTypeSet
            A, possibly empty, set of event types that the listener wants to
            be informed about.
    */
    void AddEventListener (
        Link& rCallback,
        EventMultiplexerEvent::EventId aEventTypeSet);

    /** Remove an event listener for the specified event types.
        @param aEventTypeSet
            The listener will not be called anymore for any of the event
            types in this set.  Use EID_FULL_SET, the default value, to
            remove the listener for all event types it has been registered
            for.
    */
    void RemoveEventListener (
        Link& rCallback,
        EventMultiplexerEvent::EventId aEventTypeSet = EID_FULL_SET);

    /** This method is used for out-of-line events.  An event of the
        specified type will be sent to all listeners that are registered for
        that type.
        @param eEventId
            The type of the event.
        @param pUserData
            Some data sent to the listeners along with the event.
    */
    void MultiplexEvent(
        EventMultiplexerEvent::EventId eEventId,
        void* pUserData = 0);

private:
    class Implementation;
    ::std::auto_ptr<Implementation> mpImpl;
};

} } // end of namespace ::sd::tools

#endif
<commit_msg>INTEGRATION: CWS presenterview (1.5.216); FILE MERGED 2007/06/19 08:57:29 af 1.5.216.1: #i18486# Added EID_CONFIGURATION_UPDATED.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EventMultiplexer.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 13:54:08 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SD_TOOLS_EVENT_MULTIPLEXER_HXX
#define SD_TOOLS_EVENT_MULTIPLEXER_HXX

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif

#include <set>
#include <memory>

class Link;

namespace sd {
class ViewShellBase;
}

namespace sd { namespace tools {

class EventMultiplexerEvent
{
public:
    typedef sal_uInt32 EventId;
    /** The EventMultiplexer itself is being disposed.  Called for a live
        EventMultiplexer.  Removing a listener as response is not necessary,
        though.
    */
    static const EventId EID_DISPOSING              = 0x00000001;

    /** The selection in the center pane has changed.
    */
    static const EventId EID_EDIT_VIEW_SELECTION    = 0x00000002;

    /** The selection in the slide sorter has changed, regardless of whether
        the slide sorter is displayed in the left pane or the center pane.
    */
    static const EventId EID_SLIDE_SORTER_SELECTION = 0x00000004;

    /** The current page has changed.
    */
    static const EventId EID_CURRENT_PAGE           = 0x00000008;

    /** The current MainViewShell (the ViewShell displayed in the center
        pane) has been removed.
    */
    static const EventId EID_MAIN_VIEW_REMOVED      = 0x00000010;

    /** A new ViewShell has been made the MainViewShell.
    */
    static const EventId EID_MAIN_VIEW_ADDED        = 0x00000020;

    /** A ViewShell has been removed from one of the panes.  Note that for
        the ViewShell in the center pane bth this event type and
        EID_MAIN_VIEW_REMOVED is broadcasted.
    */
    static const EventId EID_VIEW_REMOVED           = 0x00000040;

    /** A new ViewShell is being displayed in one of the panes.  Note that
        for the ViewShell in the center pane both this event type and
        EID_MAIN_VIEW_ADDED is broadcasted.
    */
    static const EventId EID_VIEW_ADDED             = 0x00000080;

    /** The PaneManager is being destroyed.
    */
    static const EventId EID_PANE_MANAGER_DYING     = 0x00000100;

    /** The edit mode of the ViewShell in the center pane has been modified.
    */
    static const EventId EID_EDIT_MODE              = 0x00000200;

    /** One or more pages have been inserted into or deleted from the model.
    */
    static const EventId EID_PAGE_ORDER             = 0x00000400;

    /** Text editing in one of the shapes in the MainViewShell has started.
    */
    static const EventId EID_BEGIN_TEXT_EDIT        = 0x00000800;

    /** Text editing in one of the shapes in the MainViewShell has ended.
    */
    static const EventId EID_END_TEXT_EDIT          = 0x00001000;

    /** A UNO controller has been attached to the UNO frame.
    */
    static const EventId EID_CONTROLLER_ATTACHED    = 0x00002000;

    /** A UNO controller has been detached to the UNO frame.
    */
    static const EventId EID_CONTROLLER_DETACHED    = 0x00004000;

    /** The state of a shape has changed.  The page is available in the user data.
    */
    static const EventId EID_SHAPE_CHANGED          = 0x00008000;

    /** A shape has been inserted to a page.  The page is available in the
        user data.
    */
    static const EventId EID_SHAPE_INSERTED         = 0x00010000;

    /** A shape has been removed from a page.  The page is available in the
        user data.
    */
    static const EventId EID_SHAPE_REMOVED          = 0x00020000;

    /** A configuration update has been completed.
    */
    static const EventId EID_CONFIGURATION_UPDATED  = 0x00040000;

    const ViewShellBase& mrBase;
    EventId meEventId;
    const void* mpUserData;

    EventMultiplexerEvent (
        const ViewShellBase& rBase,
        EventId eEventId,
        const void* pUserData);
};

/** This convenience class makes it easy to listen to various events that
    originally are broadcasted via different channels.

    There is usually one EventMultiplexer instance per ViewShellBase().
    Call the laters GetEventMultiplexer() method to get access to that
    instance.

    When a listener is registered it can specify the events it
    wants to be informed of.  This can be done with code like the following:

    mrViewShellBase.GetEventMultiplexer().AddEventListener (
        LINK(this,MasterPagesSelector,EventMultiplexerListener),
        tools::EventMultiplexerEvent::EID_MAIN_VIEW_ADDED
        | tools::EventMultiplexerEvent::EID_MAIN_VIEW_REMOVED);
*/
class EventMultiplexer
{
public:
    /** Create new EventMultiplexer for the given ViewShellBase object.
    */
    EventMultiplexer (ViewShellBase& rBase);
    ~EventMultiplexer (void);

    /** Some constants that make it easier to remove a listener for all
        event types at once.
    */
    static const EventMultiplexerEvent::EventId EID_FULL_SET = 0xffffffff;
    static const EventMultiplexerEvent::EventId EID_EMPTY_SET = 0x00000000;

    /** Add an event listener that will be informed about the specified
        event types.
        @param rCallback
            The callback to call as soon as one of the event specified by
            aEventTypeSet is received by the EventMultiplexer.
        @param aEventTypeSet
            A, possibly empty, set of event types that the listener wants to
            be informed about.
    */
    void AddEventListener (
        Link& rCallback,
        EventMultiplexerEvent::EventId aEventTypeSet);

    /** Remove an event listener for the specified event types.
        @param aEventTypeSet
            The listener will not be called anymore for any of the event
            types in this set.  Use EID_FULL_SET, the default value, to
            remove the listener for all event types it has been registered
            for.
    */
    void RemoveEventListener (
        Link& rCallback,
        EventMultiplexerEvent::EventId aEventTypeSet = EID_FULL_SET);

    /** This method is used for out-of-line events.  An event of the
        specified type will be sent to all listeners that are registered for
        that type.
        @param eEventId
            The type of the event.
        @param pUserData
            Some data sent to the listeners along with the event.
    */
    void MultiplexEvent(
        EventMultiplexerEvent::EventId eEventId,
        void* pUserData = 0);

private:
    class Implementation;
    ::std::auto_ptr<Implementation> mpImpl;
};

} } // end of namespace ::sd::tools

#endif
<|endoftext|>


<commit_before>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Task for analysis
//  - reconstruction and MC output
// implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
//_________________________________________________________________________
//Necessary to read config macros
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>

#include "TChain.h"
#include "TList.h"
#include "TH2F.h"
#include "THnSparse.h"

#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliESDtrackCuts.h"

#include "AliAnalysisTaskTotEt.h"
#include "AliAnalysisEtReconstructedPhos.h"
#include "AliAnalysisEtReconstructedEmcal.h"
#include "AliAnalysisEtMonteCarloPhos.h"
#include "AliAnalysisEtMonteCarloEmcal.h"

#include <iostream>
#include <AliCentrality.h>

using namespace std;

ClassImp(AliAnalysisTaskTotEt)

//________________________________________________________________________
AliAnalysisTaskTotEt::AliAnalysisTaskTotEt(const char *name, Bool_t isMc) :
        AliAnalysisTaskTransverseEnergy(name, isMc)
        ,fRecAnalysis(0)
        ,fMCAnalysis(0)
	,fSparseHistRecVsMc(0)
	,fSparseRecVsMc(0)
{
    // Constructor

    // select if we should use EMCal or PHOS class
    // PHOS by default, EMCal if name string contains EMC
    TString t(name);
    t.ToUpper();
    if (t.Contains("EMC")) {
        if (fMCConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtMonteCarloEmcal configuration file..."<<endl;
            gROOT->LoadMacro(fMCConfigFile);
            fMCAnalysis = (AliAnalysisEtMonteCarloEmcal *) gInterpreter->ProcessLine("ConfigEtMonteCarlo()");
        }

        if (fRecoConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtReconstructedEmcal configuration file..."<<endl;
            gROOT->LoadMacro(fRecoConfigFile);
            fRecAnalysis = (AliAnalysisEtReconstructedEmcal *) gInterpreter->ProcessLine("ConfigEtReconstructed()");
        }
    }
    else {
        if (fMCConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtMonteCarloPhos configuration file..."<<endl;
            gROOT->LoadMacro(fMCConfigFile);

            fMCAnalysis = (AliAnalysisEtMonteCarloPhos *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(false)");
	    cout << fMCAnalysis << endl;
        }

        if (fRecoConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtReconstructedPhos configuration file..."<<endl;
            gROOT->LoadMacro(fRecoConfigFile);
            fRecAnalysis = (AliAnalysisEtReconstructedPhos *) gInterpreter->ProcessLine("ConfigEtReconstructed(false)");
        }
    }
    // Define input and output slots here
    // Input slot #0 works with a TChain
    DefineInput(0, TChain::Class());
    // Output slot #1 writes into a TH1 container

    DefineOutput(1, TList::Class());

}
AliAnalysisTaskTotEt::~AliAnalysisTaskTotEt() {//Destructor
//    fOutputList->Clear();
    delete fRecAnalysis;
    delete fMCAnalysis;
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserCreateOutputObjects()
{
    // Create histograms
    // Called once
    fMCAnalysis->CreateHistograms();
    fRecAnalysis->CreateHistograms();
    fOutputList = new TList;
    fOutputList->SetOwner();
    fRecAnalysis->FillOutputList(fOutputList);
    fMCAnalysis->FillOutputList(fOutputList);
    fHistEtRecvsEtMC = new TH2F("fHistEtRecvsEtMC", "Reconstructed E_{T} vs MC E_{T}", 1000, 0.000, 100, 1000, 0.0001, 100);
    fHistEtRecOverEtMC = new TH2F("fHistEtRecOverEtMC", "Reconstructed E_{T} over MC E_{T} vs centrality", 1000, 0.00, 2.0, 11, -0.5, 10.5);
    fHistDiffEtRecEtMCOverEtMC = new TH2F("fHistDiffEtRecEtMCOverEtMC", "fHistDiffEtRecEtMCOverEtMC", 10000, 0.0, 1000, 1000, -5, 5);
    fOutputList->Add(fHistEtRecvsEtMC);
    fOutputList->Add(fHistEtRecOverEtMC);
    fOutputList->Add(fHistDiffEtRecEtMCOverEtMC);

    Bool_t selectPrimaries=kTRUE;
    if (fRecAnalysis->DataSet()==2009) {
        cout<<"Setting track cuts for the 2009 p+p collisions at 900 GeV"<<endl;
        fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(selectPrimaries);
        fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
        fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
        fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
        //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
        fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2009(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
        fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
    }
    if (fRecAnalysis->DataSet()==2010) {
        cout<<"Setting track cuts for the 2010 p+p collisions at 7 GeV"<<endl;
        //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
        fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
        fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
        fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
        fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
        //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
        fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
        fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
    }

    fOutputList->Add(fEsdtrackCutsITSTPC);
    fOutputList->Add(fEsdtrackCutsTPC);
    fOutputList->Add(fEsdtrackCutsITS);
    if (fEsdtrackCutsITSTPC && fEsdtrackCutsTPC) {
        fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts());
        fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts());
        fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
        fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
        fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
        fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
        //add ITS stuff!
    }
    else {
        Printf("Error: no track cuts!");
    }

}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserExec(Option_t *)
{ // execute method

    fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent());
    if (!fESDEvent)
    {
        Printf("ERROR: Could not retrieve event");
        return;
    }

    Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber());

    AliCentrality *cent = GetCentralityObject();

    if (res == 0 && cent)
    {
        if (IsPhysicsSelected())
        {
            fRecAnalysis->SetCentralityObject(cent);
            fRecAnalysis->AnalyseEvent(fESDEvent);

            AliMCEvent* mcEvent = MCEvent();
            if (mcEvent)
            {
		fMCAnalysis->SetCentralityObject(cent);
                fMCAnalysis->AnalyseEvent(mcEvent, fESDEvent);
                //fMCAnalysis->AnalyseEvent(mcEvent);
            }
            if(fMCAnalysis)
	    {
	      fHistEtRecvsEtMC->Fill(fRecAnalysis->GetTotNeutralEtAcc(), fMCAnalysis->GetTotNeutralEtAcc());
	      if(fMCAnalysis->GetTotNeutralEtAcc()) fHistEtRecOverEtMC->Fill(fRecAnalysis->GetTotNeutralEt()/fMCAnalysis->GetTotNeutralEtAcc(), cent->GetCentralityClass10("V0M"));
	      if(fMCAnalysis->GetTotNeutralEtAcc()) fHistDiffEtRecEtMCOverEtMC->Fill(fMCAnalysis->GetTotNeutralEt(), (fRecAnalysis->GetTotNeutralEt()-fMCAnalysis->GetTotNeutralEt())/fMCAnalysis->GetTotNeutralEt());
	    }
        }
    }
    // Post output data.
    PostData(1, fOutputList);
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::Terminate(Option_t *)
{
    // Draw result to the screen
    // Called once at the end of the query

    fOutputList = dynamic_cast<TList*> (GetOutputData(1));
    if (!fOutputList) {
        printf("ERROR: Output list not available\n");
        return;
    }
}

<commit_msg>Implementing Marcelos classes<commit_after>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Task for analysis
//  - reconstruction and MC output
// implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
//_________________________________________________________________________
//Necessary to read config macros
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>

#include "TChain.h"
#include "TList.h"
#include "TFile.h"
#include "TH2F.h"
#include "THnSparse.h"

#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliESDtrackCuts.h"

#include "AliAnalysisTaskTotEt.h"
#include "AliAnalysisEtReconstructedPhos.h"
#include "AliAnalysisEtReconstructedEmcal.h"
#include "AliAnalysisEtMonteCarloPhos.h"
#include "AliAnalysisEtMonteCarloEmcal.h"
#include "AliAnalysisEmEtMonteCarlo.h"
#include "AliAnalysisEmEtReconstructed.h"

#include <iostream>
#include <AliCentrality.h>

using namespace std;

ClassImp(AliAnalysisTaskTotEt)

//________________________________________________________________________
AliAnalysisTaskTotEt::AliAnalysisTaskTotEt(const char *name, Bool_t isMc) :
AliAnalysisTaskTransverseEnergy(name, isMc)
,fRecAnalysis(0)
,fMCAnalysis(0)
,fSparseHistRecVsMc(0)
,fSparseRecVsMc(0)
{
    // Constructor

    // select if we should use EMCal or PHOS class
    // PHOS by default, EMCal if name string contains EMC
    TString t(name);
    //t.ToUpper();
    if (t.Contains("EMC")) {
		if (t.Contains("Detail")) {
			fMCAnalysis = new AliAnalysisEmEtMonteCarlo();
			fMCAnalysis->SetDataSet(2010);
			fMCAnalysis->Init();

			cout << "Instantiating AliAnalysisEmEtMonteCarlo class..."<< endl;
		}
        else if (fMCConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtMonteCarloEmcal configuration file..."<<endl;
            gROOT->LoadMacro(fMCConfigFile);
            fMCAnalysis = (AliAnalysisEtMonteCarloEmcal *) gInterpreter->ProcessLine("ConfigEtMonteCarlo()");
        }

		if (t.Contains("Detail")) {
			fRecAnalysis = new AliAnalysisEmEtReconstructed();
			fRecAnalysis->SetDataSet(2010);

			TFile *infile = new TFile("corrections.root");
			fRecAnalysis->SetCorrections((AliAnalysisHadEtCorrections *)infile->Get("hadCorrectionEMCAL"));

			fRecAnalysis->Init();

			cout << "Instantiating AliAnalysisEmEtReconstructed class..."<< endl;
		}
        else if (fRecoConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtReconstructedEmcal configuration file..."<<endl;
            gROOT->LoadMacro(fRecoConfigFile);
            fRecAnalysis = (AliAnalysisEtReconstructedEmcal *) gInterpreter->ProcessLine("ConfigEtReconstructed()");
        }
    }
    else {
        if (fMCConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtMonteCarloPhos configuration file..."<<endl;
            gROOT->LoadMacro(fMCConfigFile);

            fMCAnalysis = (AliAnalysisEtMonteCarloPhos *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(false)");
			cout << fMCAnalysis << endl;
        }

        if (fRecoConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtReconstructedPhos configuration file..."<<endl;
            gROOT->LoadMacro(fRecoConfigFile);
            fRecAnalysis = (AliAnalysisEtReconstructedPhos *) gInterpreter->ProcessLine("ConfigEtReconstructed(false)");
        }
    }
    // Define input and output slots here
    // Input slot #0 works with a TChain
    DefineInput(0, TChain::Class());
    // Output slot #1 writes into a TH1 container

    DefineOutput(1, TList::Class());

}
AliAnalysisTaskTotEt::~AliAnalysisTaskTotEt() {//Destructor
	//    fOutputList->Clear();
    delete fRecAnalysis;
    delete fMCAnalysis;
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserCreateOutputObjects()
{
    // Create histograms
    // Called once
	if (fMCAnalysis)
		fMCAnalysis->CreateHistograms();
    fRecAnalysis->CreateHistograms();
    fOutputList = new TList;
    fOutputList->SetOwner();
    fRecAnalysis->FillOutputList(fOutputList);
	if (fMCAnalysis)
		fMCAnalysis->FillOutputList(fOutputList);
    fHistEtRecvsEtMC = new TH2F("fHistEtRecvsEtMC", "Reconstructed E_{T} vs MC E_{T}", 1000, 0.000, 100, 1000, 0.0001, 100);
    fHistEtRecOverEtMC = new TH2F("fHistEtRecOverEtMC", "Reconstructed E_{T} over MC E_{T} vs centrality", 1000, 0.00, 2.0, 11, -0.5, 10.5);
    fHistDiffEtRecEtMCOverEtMC = new TH2F("fHistDiffEtRecEtMCOverEtMC", "fHistDiffEtRecEtMCOverEtMC", 10000, 0.0, 1000, 1000, -5, 5);
    fOutputList->Add(fHistEtRecvsEtMC);
    fOutputList->Add(fHistEtRecOverEtMC);
    fOutputList->Add(fHistDiffEtRecEtMCOverEtMC);

    Bool_t selectPrimaries=kTRUE;
    if (fRecAnalysis->DataSet()==2009) {
        cout<<"Setting track cuts for the 2009 p+p collisions at 900 GeV"<<endl;
        fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(selectPrimaries);
        fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
        fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
        fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
        //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
        fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2009(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
        fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
    }
    if (fRecAnalysis->DataSet()==2010) {
        cout<<"Setting track cuts for the 2010 p+p collisions at 7 GeV"<<endl;
        //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
        fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
        fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
        fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
        fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
        //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
        fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
        fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
    }

    fOutputList->Add(fEsdtrackCutsITSTPC);
    fOutputList->Add(fEsdtrackCutsTPC);
    fOutputList->Add(fEsdtrackCutsITS);
    if (fEsdtrackCutsITSTPC && fEsdtrackCutsTPC) {
        fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts());
		if (fMCAnalysis)
			fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts());
        fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
		if (fMCAnalysis)
			fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
        fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
		if (fMCAnalysis)
			fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
        //add ITS stuff!
    }
    else {
        Printf("Error: no track cuts!");
    }

}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserExec(Option_t *)
{ // execute method

    fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent());
    if (!fESDEvent)
    {
        Printf("ERROR: Could not retrieve event");
        return;
    }

    //Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber());

    AliCentrality *cent = GetCentralityObject();

    //if (res == 0 && cent)
    //{
	if (IsPhysicsSelected())
	{
		fRecAnalysis->SetCentralityObject(cent);
		fRecAnalysis->AnalyseEvent(fESDEvent);

		AliMCEvent* mcEvent = MCEvent();
		if (mcEvent)
		{
			fMCAnalysis->SetCentralityObject(cent);
			fMCAnalysis->AnalyseEvent(mcEvent, fESDEvent);
			//fMCAnalysis->AnalyseEvent(mcEvent);
		}
		if(fMCAnalysis)
	    {
			fHistEtRecvsEtMC->Fill(fRecAnalysis->GetTotNeutralEtAcc(), fMCAnalysis->GetTotNeutralEtAcc());
			if(fMCAnalysis->GetTotNeutralEtAcc()) fHistEtRecOverEtMC->Fill(fRecAnalysis->GetTotNeutralEt()/fMCAnalysis->GetTotNeutralEtAcc(), cent->GetCentralityClass10("V0M"));
			if(fMCAnalysis->GetTotNeutralEtAcc()) fHistDiffEtRecEtMCOverEtMC->Fill(fMCAnalysis->GetTotNeutralEt(), (fRecAnalysis->GetTotNeutralEt()-fMCAnalysis->GetTotNeutralEt())/fMCAnalysis->GetTotNeutralEt());
	    }
	}
    //}
    // Post output data.
    PostData(1, fOutputList);
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::Terminate(Option_t *)
{
    // Draw result to the screen
    // Called once at the end of the query

    fOutputList = dynamic_cast<TList*> (GetOutputData(1));
    if (!fOutputList) {
        printf("ERROR: Output list not available\n");
        return;
    }
}

<|endoftext|>


<commit_before>/*
 * This file is a part of Xpiks - cross platform application for
 * keywording and uploading images for microstocks
 * Copyright (C) 2014-2017 Taras Kushnir <kushnirTV@gmail.com>
 *
 * Xpiks is distributed under the GNU General Public License, version 3.0
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "currenteditableartwork.h"
#include "../Models/artworkmetadata.h"
#include "../Common/defines.h"
#include "../Commands/commandmanager.h"
#include "../KeywordsPresets/presetkeywordsmodel.h"
#include "../Commands/expandpresetcommand.h"
#include "../Models/metadataelement.h"

namespace QuickBuffer {
    CurrentEditableArtwork::CurrentEditableArtwork(Models::ArtworkMetadata *artworkMetadata, int originalIndex, Commands::CommandManager * const commandManager):
        m_CommandManager(commandManager),
        m_OriginalIndex(originalIndex)
    {
        Q_ASSERT(commandManager != nullptr);
        Q_ASSERT(artworkMetadata != nullptr);
        m_ArtworkMetadata = artworkMetadata;

        m_ArtworkMetadata->acquire();
    }

    CurrentEditableArtwork::~CurrentEditableArtwork() {
        if (m_ArtworkMetadata->release()) {
            LOG_WARNING << "Item could have been removed";
        }
    }

    QString CurrentEditableArtwork::getTitle() {
        return m_ArtworkMetadata->getTitle();
    }

    QString CurrentEditableArtwork::getDescription() {
        return m_ArtworkMetadata->getDescription();
    }

    QStringList CurrentEditableArtwork::getKeywords() {
        return m_ArtworkMetadata->getKeywords();
    }

    void CurrentEditableArtwork::setTitle(const QString &value) {
        m_ArtworkMetadata->setTitle(value);
    }

    void CurrentEditableArtwork::setDescription(const QString &value) {
        m_ArtworkMetadata->setDescription(value);
    }

    void CurrentEditableArtwork::setKeywords(const QStringList &keywords) {
        m_ArtworkMetadata->setKeywords(keywords);
    }

    bool CurrentEditableArtwork::expandPreset(int keywordIndex, int presetIndex) {
        bool success = false;
        LOG_INFO << "keyword" << keywordIndex << "preset" << presetIndex;

        std::shared_ptr<Commands::ExpandPresetCommand> expandPresetCommand(new Commands::ExpandPresetCommand(Models::MetadataElement(m_ArtworkMetadata, m_OriginalIndex), presetIndex, keywordIndex));
        std::shared_ptr<Commands::ICommandResult> result = m_CommandManager->processCommand(expandPresetCommand);
        success = result->getStatus() == 0;

        return success;
    }

    bool CurrentEditableArtwork::removePreset(int presetIndex) {
        bool success = false;
        LOG_INFO << "preset" << presetIndex;
        auto *presetsModel = m_CommandManager->getPresetsModel();
        QStringList keywords;

        if (presetsModel->tryGetPreset(presetIndex, keywords)) {
            success = m_ArtworkMetadata->removeKeywords(keywords.toSet(), false);
        }

        return success;
    }

    void CurrentEditableArtwork::spellCheck() {
        m_CommandManager->submitItemForSpellCheck(m_ArtworkMetadata->getBasicModel());
    }

    void CurrentEditableArtwork::update() {
        m_CommandManager->updateArtworks(QVector<int>() << m_OriginalIndex);
    }
}
<commit_msg>Refactored remove preset to command<commit_after>/*
 * This file is a part of Xpiks - cross platform application for
 * keywording and uploading images for microstocks
 * Copyright (C) 2014-2017 Taras Kushnir <kushnirTV@gmail.com>
 *
 * Xpiks is distributed under the GNU General Public License, version 3.0
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "currenteditableartwork.h"
#include "../Models/artworkmetadata.h"
#include "../Common/defines.h"
#include "../Commands/commandmanager.h"
#include "../KeywordsPresets/presetkeywordsmodel.h"
#include "../Commands/expandpresetcommand.h"
#include "../Models/metadataelement.h"
#include "../Commands/deletekeywordscommand.h"

namespace QuickBuffer {
    CurrentEditableArtwork::CurrentEditableArtwork(Models::ArtworkMetadata *artworkMetadata, int originalIndex, Commands::CommandManager * const commandManager):
        m_CommandManager(commandManager),
        m_OriginalIndex(originalIndex)
    {
        Q_ASSERT(commandManager != nullptr);
        Q_ASSERT(artworkMetadata != nullptr);
        m_ArtworkMetadata = artworkMetadata;

        m_ArtworkMetadata->acquire();
    }

    CurrentEditableArtwork::~CurrentEditableArtwork() {
        if (m_ArtworkMetadata->release()) {
            LOG_WARNING << "Item could have been removed";
        }
    }

    QString CurrentEditableArtwork::getTitle() {
        return m_ArtworkMetadata->getTitle();
    }

    QString CurrentEditableArtwork::getDescription() {
        return m_ArtworkMetadata->getDescription();
    }

    QStringList CurrentEditableArtwork::getKeywords() {
        return m_ArtworkMetadata->getKeywords();
    }

    void CurrentEditableArtwork::setTitle(const QString &value) {
        m_ArtworkMetadata->setTitle(value);
    }

    void CurrentEditableArtwork::setDescription(const QString &value) {
        m_ArtworkMetadata->setDescription(value);
    }

    void CurrentEditableArtwork::setKeywords(const QStringList &keywords) {
        m_ArtworkMetadata->setKeywords(keywords);
    }

    bool CurrentEditableArtwork::expandPreset(int keywordIndex, int presetIndex) {
        bool success = false;
        LOG_INFO << "keyword" << keywordIndex << "preset" << presetIndex;

        std::shared_ptr<Commands::ExpandPresetCommand> expandPresetCommand(new Commands::ExpandPresetCommand(Models::MetadataElement(m_ArtworkMetadata, m_OriginalIndex), presetIndex, keywordIndex));
        std::shared_ptr<Commands::ICommandResult> result = m_CommandManager->processCommand(expandPresetCommand);
        success = result->getStatus() == 0;

        return success;
    }

    bool CurrentEditableArtwork::removePreset(int presetIndex) {
        bool success = false;
        LOG_INFO << "preset" << presetIndex;
        auto *presetsModel = m_CommandManager->getPresetsModel();
        QStringList keywords;

        if (presetsModel->tryGetPreset(presetIndex, keywords)) {
            std::vector<Models::MetadataElement> artworksList;
            artworksList.emplace_back(m_ArtworkMetadata, m_OriginalIndex);

            std::shared_ptr<Commands::DeleteKeywordsCommand> deleteKeywordsCommand(
                        new Commands::DeleteKeywordsCommand(artworksList, keywords.toSet(), false));
            m_CommandManager->processCommand(deleteKeywordsCommand);
        }

        return success;
    }

    void CurrentEditableArtwork::spellCheck() {
        m_CommandManager->submitItemForSpellCheck(m_ArtworkMetadata->getBasicModel());
    }

    void CurrentEditableArtwork::update() {
        m_CommandManager->updateArtworks(QVector<int>() << m_OriginalIndex);
    }
}
<|endoftext|>


<commit_before>/* Copyright (C) 2003 MySQL AB

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

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

//****************************************************************************
//
// NAME
//      Backup - Database backup / restore
//
//===========================================================================
#include "Backup.hpp"

#include <Properties.hpp>
#include <Configuration.hpp>

//extern const unsigned Ndbcntr::g_sysTableCount;

Backup::Backup(Block_context& ctx) :
  SimulatedBlock(BACKUP, ctx),
  c_nodes(c_nodePool),
  c_backups(c_backupPool)
{
  BLOCK_CONSTRUCTOR(Backup);

  c_masterNodeId = getOwnNodeId();

  // Add received signals
  addRecSignal(GSN_READ_CONFIG_REQ, &Backup::execREAD_CONFIG_REQ);
  addRecSignal(GSN_STTOR, &Backup::execSTTOR);
  addRecSignal(GSN_DUMP_STATE_ORD, &Backup::execDUMP_STATE_ORD);
  addRecSignal(GSN_READ_NODESCONF, &Backup::execREAD_NODESCONF);
  addRecSignal(GSN_NODE_FAILREP, &Backup::execNODE_FAILREP);
  addRecSignal(GSN_INCL_NODEREQ, &Backup::execINCL_NODEREQ);
  addRecSignal(GSN_CONTINUEB, &Backup::execCONTINUEB);
  addRecSignal(GSN_READ_CONFIG_REQ, &Backup::execREAD_CONFIG_REQ, true);

  addRecSignal(GSN_SCAN_HBREP, &Backup::execSCAN_HBREP);
  addRecSignal(GSN_TRANSID_AI, &Backup::execTRANSID_AI);
  addRecSignal(GSN_SCAN_FRAGREF, &Backup::execSCAN_FRAGREF);
  addRecSignal(GSN_SCAN_FRAGCONF, &Backup::execSCAN_FRAGCONF);

  addRecSignal(GSN_BACKUP_TRIG_REQ, &Backup::execBACKUP_TRIG_REQ);
  addRecSignal(GSN_TRIG_ATTRINFO, &Backup::execTRIG_ATTRINFO);
  addRecSignal(GSN_FIRE_TRIG_ORD, &Backup::execFIRE_TRIG_ORD);

  addRecSignal(GSN_LIST_TABLES_CONF, &Backup::execLIST_TABLES_CONF);
  addRecSignal(GSN_GET_TABINFOREF, &Backup::execGET_TABINFOREF);
  addRecSignal(GSN_GET_TABINFO_CONF, &Backup::execGET_TABINFO_CONF);

  addRecSignal(GSN_CREATE_TRIG_REF, &Backup::execCREATE_TRIG_REF);
  addRecSignal(GSN_CREATE_TRIG_CONF, &Backup::execCREATE_TRIG_CONF);

  addRecSignal(GSN_DROP_TRIG_REF, &Backup::execDROP_TRIG_REF);
  addRecSignal(GSN_DROP_TRIG_CONF, &Backup::execDROP_TRIG_CONF);

  addRecSignal(GSN_DI_FCOUNTCONF, &Backup::execDI_FCOUNTCONF);
  addRecSignal(GSN_DIGETPRIMCONF, &Backup::execDIGETPRIMCONF);

  addRecSignal(GSN_FSOPENREF, &Backup::execFSOPENREF, true);
  addRecSignal(GSN_FSOPENCONF, &Backup::execFSOPENCONF);

  addRecSignal(GSN_FSCLOSEREF, &Backup::execFSCLOSEREF, true);
  addRecSignal(GSN_FSCLOSECONF, &Backup::execFSCLOSECONF);

  addRecSignal(GSN_FSAPPENDREF, &Backup::execFSAPPENDREF, true);
  addRecSignal(GSN_FSAPPENDCONF, &Backup::execFSAPPENDCONF);

  addRecSignal(GSN_FSREMOVEREF, &Backup::execFSREMOVEREF, true);
  addRecSignal(GSN_FSREMOVECONF, &Backup::execFSREMOVECONF);

  /*****/
  addRecSignal(GSN_BACKUP_REQ, &Backup::execBACKUP_REQ);
  addRecSignal(GSN_ABORT_BACKUP_ORD, &Backup::execABORT_BACKUP_ORD);

  addRecSignal(GSN_DEFINE_BACKUP_REQ, &Backup::execDEFINE_BACKUP_REQ);
  addRecSignal(GSN_DEFINE_BACKUP_REF, &Backup::execDEFINE_BACKUP_REF);
  addRecSignal(GSN_DEFINE_BACKUP_CONF, &Backup::execDEFINE_BACKUP_CONF);

  addRecSignal(GSN_START_BACKUP_REQ, &Backup::execSTART_BACKUP_REQ);
  addRecSignal(GSN_START_BACKUP_REF, &Backup::execSTART_BACKUP_REF);
  addRecSignal(GSN_START_BACKUP_CONF, &Backup::execSTART_BACKUP_CONF);

  addRecSignal(GSN_BACKUP_FRAGMENT_REQ, &Backup::execBACKUP_FRAGMENT_REQ);
  addRecSignal(GSN_BACKUP_FRAGMENT_REF, &Backup::execBACKUP_FRAGMENT_REF);
  addRecSignal(GSN_BACKUP_FRAGMENT_CONF, &Backup::execBACKUP_FRAGMENT_CONF);

  addRecSignal(GSN_STOP_BACKUP_REQ, &Backup::execSTOP_BACKUP_REQ);
  addRecSignal(GSN_STOP_BACKUP_REF, &Backup::execSTOP_BACKUP_REF);
  addRecSignal(GSN_STOP_BACKUP_CONF, &Backup::execSTOP_BACKUP_CONF);

  //addRecSignal(GSN_BACKUP_STATUS_REQ, &Backup::execBACKUP_STATUS_REQ);
  //addRecSignal(GSN_BACKUP_STATUS_CONF, &Backup::execBACKUP_STATUS_CONF);

  addRecSignal(GSN_UTIL_SEQUENCE_REF, &Backup::execUTIL_SEQUENCE_REF);
  addRecSignal(GSN_UTIL_SEQUENCE_CONF, &Backup::execUTIL_SEQUENCE_CONF);

  addRecSignal(GSN_WAIT_GCP_REF, &Backup::execWAIT_GCP_REF);
  addRecSignal(GSN_WAIT_GCP_CONF, &Backup::execWAIT_GCP_CONF);

  /**
   * Testing
   */
  addRecSignal(GSN_BACKUP_REF, &Backup::execBACKUP_REF);
  addRecSignal(GSN_BACKUP_CONF, &Backup::execBACKUP_CONF);
  addRecSignal(GSN_BACKUP_ABORT_REP, &Backup::execBACKUP_ABORT_REP);
  addRecSignal(GSN_BACKUP_COMPLETE_REP, &Backup::execBACKUP_COMPLETE_REP);

  addRecSignal(GSN_LCP_PREPARE_REQ, &Backup::execLCP_PREPARE_REQ);
  addRecSignal(GSN_END_LCPREQ, &Backup::execEND_LCPREQ);
}

Backup::~Backup()
{
}

BLOCK_FUNCTIONS(Backup)

template class ArrayPool<Backup::Page32>;
template class ArrayPool<Backup::Attribute>;
template class ArrayPool<Backup::Fragment>;

void
Backup::execREAD_CONFIG_REQ(Signal* signal)
{
  const ReadConfigReq * req = (ReadConfigReq*)signal->getDataPtr();
  Uint32 ref = req->senderRef;
  Uint32 senderData = req->senderData;
  ndbrequire(req->noOfParameters == 0);

  const ndb_mgm_configuration_iterator * p =
    m_ctx.m_config.getOwnConfigIterator();
  ndbrequire(p != 0);

  Uint32 noBackups = 0, noTables = 0, noAttribs = 0, noFrags = 0;
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DB_DISCLESS, &m_diskless));
  ndb_mgm_get_int_parameter(p, CFG_DB_PARALLEL_BACKUPS, &noBackups);
  //  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DB_NO_TABLES, &noTables));
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DICT_TABLE, &noTables));
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DB_NO_ATTRIBUTES, &noAttribs));
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DIH_FRAG_CONNECT, &noFrags));

  noAttribs++; //RT 527 bug fix

  c_nodePool.setSize(MAX_NDB_NODES);
  c_backupPool.setSize(noBackups + 1);
  c_backupFilePool.setSize(3 * noBackups + 1);
  c_tablePool.setSize(noBackups * noTables + 1);
  c_attributePool.setSize(noBackups * noAttribs + MAX_ATTRIBUTES_IN_TABLE);
  c_triggerPool.setSize(noBackups * 3 * noTables);
  c_fragmentPool.setSize(noBackups * noFrags + 1);

  Uint32 szDataBuf = (2 * 1024 * 1024);
  Uint32 szLogBuf = (2 * 1024 * 1024);
  Uint32 szWrite = 32768;
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_DATA_BUFFER_MEM, &szDataBuf);
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_LOG_BUFFER_MEM, &szLogBuf);
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_WRITE_SIZE, &szWrite);

  c_defaults.m_logBufferSize = szLogBuf;
  c_defaults.m_dataBufferSize = szDataBuf;
  c_defaults.m_minWriteSize = szWrite;
  c_defaults.m_maxWriteSize = 256*1024;
  c_defaults.m_lcp_buffer_size = szDataBuf;

  Uint32 szMem = 0;
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_MEM, &szMem);
  Uint32 noPages = (szMem + c_defaults.m_lcp_buffer_size + sizeof(Page32) - 1)
    / sizeof(Page32);
  // We need to allocate an additional of 2 pages. 1 page because of a bug in
  // ArrayPool and another one for DICTTAINFO.
  c_pagePool.setSize(noPages + NO_OF_PAGES_META_FILE + 2);

  { // Init all tables
    SLList<Table> tables(c_tablePool);
    TablePtr ptr;
    while(tables.seize(ptr)){
      new (ptr.p) Table(c_attributePool, c_fragmentPool);
    }
    tables.release();
  }

  {
    SLList<BackupFile> ops(c_backupFilePool);
    BackupFilePtr ptr;
    while(ops.seize(ptr)){
      new (ptr.p) BackupFile(* this, c_pagePool);
    }
    ops.release();
  }

  {
    SLList<BackupRecord> recs(c_backupPool);
    BackupRecordPtr ptr;
    while(recs.seize(ptr)){
      new (ptr.p) BackupRecord(* this, c_tablePool,
			       c_backupFilePool, c_triggerPool);
    }
    recs.release();
  }

  // Initialize BAT for interface to file system
  {
    Page32Ptr p;
    ndbrequire(c_pagePool.seizeId(p, 0));
    c_startOfPages = (Uint32 *)p.p;
    c_pagePool.release(p);

    NewVARIABLE* bat = allocateBat(1);
    bat[0].WA = c_startOfPages;
    bat[0].nrr = c_pagePool.getSize()*sizeof(Page32)/sizeof(Uint32);
  }

  ReadConfigConf * conf = (ReadConfigConf*)signal->getDataPtrSend();
  conf->senderRef = reference();
  conf->senderData = senderData;
  sendSignal(ref, GSN_READ_CONFIG_CONF, signal,
	     ReadConfigConf::SignalLength, JBB);
}

<commit_msg>ndb - backup 5.0->5.1 merge<commit_after>/* Copyright (C) 2003 MySQL AB

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

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

//****************************************************************************
//
// NAME
//      Backup - Database backup / restore
//
//===========================================================================
#include "Backup.hpp"

#include <Properties.hpp>
#include <Configuration.hpp>

//extern const unsigned Ndbcntr::g_sysTableCount;

Backup::Backup(Block_context& ctx) :
  SimulatedBlock(BACKUP, ctx),
  c_nodes(c_nodePool),
  c_backups(c_backupPool)
{
  BLOCK_CONSTRUCTOR(Backup);

  c_masterNodeId = getOwnNodeId();

  // Add received signals
  addRecSignal(GSN_READ_CONFIG_REQ, &Backup::execREAD_CONFIG_REQ);
  addRecSignal(GSN_STTOR, &Backup::execSTTOR);
  addRecSignal(GSN_DUMP_STATE_ORD, &Backup::execDUMP_STATE_ORD);
  addRecSignal(GSN_READ_NODESCONF, &Backup::execREAD_NODESCONF);
  addRecSignal(GSN_NODE_FAILREP, &Backup::execNODE_FAILREP);
  addRecSignal(GSN_INCL_NODEREQ, &Backup::execINCL_NODEREQ);
  addRecSignal(GSN_CONTINUEB, &Backup::execCONTINUEB);
  addRecSignal(GSN_READ_CONFIG_REQ, &Backup::execREAD_CONFIG_REQ, true);

  addRecSignal(GSN_SCAN_HBREP, &Backup::execSCAN_HBREP);
  addRecSignal(GSN_TRANSID_AI, &Backup::execTRANSID_AI);
  addRecSignal(GSN_SCAN_FRAGREF, &Backup::execSCAN_FRAGREF);
  addRecSignal(GSN_SCAN_FRAGCONF, &Backup::execSCAN_FRAGCONF);

  addRecSignal(GSN_BACKUP_TRIG_REQ, &Backup::execBACKUP_TRIG_REQ);
  addRecSignal(GSN_TRIG_ATTRINFO, &Backup::execTRIG_ATTRINFO);
  addRecSignal(GSN_FIRE_TRIG_ORD, &Backup::execFIRE_TRIG_ORD);

  addRecSignal(GSN_LIST_TABLES_CONF, &Backup::execLIST_TABLES_CONF);
  addRecSignal(GSN_GET_TABINFOREF, &Backup::execGET_TABINFOREF);
  addRecSignal(GSN_GET_TABINFO_CONF, &Backup::execGET_TABINFO_CONF);

  addRecSignal(GSN_CREATE_TRIG_REF, &Backup::execCREATE_TRIG_REF);
  addRecSignal(GSN_CREATE_TRIG_CONF, &Backup::execCREATE_TRIG_CONF);

  addRecSignal(GSN_DROP_TRIG_REF, &Backup::execDROP_TRIG_REF);
  addRecSignal(GSN_DROP_TRIG_CONF, &Backup::execDROP_TRIG_CONF);

  addRecSignal(GSN_DI_FCOUNTCONF, &Backup::execDI_FCOUNTCONF);
  addRecSignal(GSN_DIGETPRIMCONF, &Backup::execDIGETPRIMCONF);

  addRecSignal(GSN_FSOPENREF, &Backup::execFSOPENREF, true);
  addRecSignal(GSN_FSOPENCONF, &Backup::execFSOPENCONF);

  addRecSignal(GSN_FSCLOSEREF, &Backup::execFSCLOSEREF, true);
  addRecSignal(GSN_FSCLOSECONF, &Backup::execFSCLOSECONF);

  addRecSignal(GSN_FSAPPENDREF, &Backup::execFSAPPENDREF, true);
  addRecSignal(GSN_FSAPPENDCONF, &Backup::execFSAPPENDCONF);

  addRecSignal(GSN_FSREMOVEREF, &Backup::execFSREMOVEREF, true);
  addRecSignal(GSN_FSREMOVECONF, &Backup::execFSREMOVECONF);

  /*****/
  addRecSignal(GSN_BACKUP_REQ, &Backup::execBACKUP_REQ);
  addRecSignal(GSN_ABORT_BACKUP_ORD, &Backup::execABORT_BACKUP_ORD);

  addRecSignal(GSN_DEFINE_BACKUP_REQ, &Backup::execDEFINE_BACKUP_REQ);
  addRecSignal(GSN_DEFINE_BACKUP_REF, &Backup::execDEFINE_BACKUP_REF);
  addRecSignal(GSN_DEFINE_BACKUP_CONF, &Backup::execDEFINE_BACKUP_CONF);

  addRecSignal(GSN_START_BACKUP_REQ, &Backup::execSTART_BACKUP_REQ);
  addRecSignal(GSN_START_BACKUP_REF, &Backup::execSTART_BACKUP_REF);
  addRecSignal(GSN_START_BACKUP_CONF, &Backup::execSTART_BACKUP_CONF);

  addRecSignal(GSN_BACKUP_FRAGMENT_REQ, &Backup::execBACKUP_FRAGMENT_REQ);
  addRecSignal(GSN_BACKUP_FRAGMENT_REF, &Backup::execBACKUP_FRAGMENT_REF);
  addRecSignal(GSN_BACKUP_FRAGMENT_CONF, &Backup::execBACKUP_FRAGMENT_CONF);

  addRecSignal(GSN_STOP_BACKUP_REQ, &Backup::execSTOP_BACKUP_REQ);
  addRecSignal(GSN_STOP_BACKUP_REF, &Backup::execSTOP_BACKUP_REF);
  addRecSignal(GSN_STOP_BACKUP_CONF, &Backup::execSTOP_BACKUP_CONF);

  //addRecSignal(GSN_BACKUP_STATUS_REQ, &Backup::execBACKUP_STATUS_REQ);
  //addRecSignal(GSN_BACKUP_STATUS_CONF, &Backup::execBACKUP_STATUS_CONF);

  addRecSignal(GSN_UTIL_SEQUENCE_REF, &Backup::execUTIL_SEQUENCE_REF);
  addRecSignal(GSN_UTIL_SEQUENCE_CONF, &Backup::execUTIL_SEQUENCE_CONF);

  addRecSignal(GSN_WAIT_GCP_REF, &Backup::execWAIT_GCP_REF);
  addRecSignal(GSN_WAIT_GCP_CONF, &Backup::execWAIT_GCP_CONF);

  /**
   * Testing
   */
  addRecSignal(GSN_BACKUP_REF, &Backup::execBACKUP_REF);
  addRecSignal(GSN_BACKUP_CONF, &Backup::execBACKUP_CONF);
  addRecSignal(GSN_BACKUP_ABORT_REP, &Backup::execBACKUP_ABORT_REP);
  addRecSignal(GSN_BACKUP_COMPLETE_REP, &Backup::execBACKUP_COMPLETE_REP);

  addRecSignal(GSN_LCP_PREPARE_REQ, &Backup::execLCP_PREPARE_REQ);
  addRecSignal(GSN_END_LCPREQ, &Backup::execEND_LCPREQ);
}

Backup::~Backup()
{
}

BLOCK_FUNCTIONS(Backup)

template class ArrayPool<Backup::Page32>;
template class ArrayPool<Backup::Attribute>;
template class ArrayPool<Backup::Fragment>;

void
Backup::execREAD_CONFIG_REQ(Signal* signal)
{
  const ReadConfigReq * req = (ReadConfigReq*)signal->getDataPtr();
  Uint32 ref = req->senderRef;
  Uint32 senderData = req->senderData;
  ndbrequire(req->noOfParameters == 0);

  const ndb_mgm_configuration_iterator * p =
    m_ctx.m_config.getOwnConfigIterator();
  ndbrequire(p != 0);

  Uint32 noBackups = 0, noTables = 0, noAttribs = 0, noFrags = 0;
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DB_DISCLESS, &m_diskless));
  ndb_mgm_get_int_parameter(p, CFG_DB_PARALLEL_BACKUPS, &noBackups);
  //  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DB_NO_TABLES, &noTables));
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DICT_TABLE, &noTables));
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DB_NO_ATTRIBUTES, &noAttribs));
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DIH_FRAG_CONNECT, &noFrags));

  noAttribs++; //RT 527 bug fix

  c_nodePool.setSize(MAX_NDB_NODES);
  c_backupPool.setSize(noBackups + 1);
  c_backupFilePool.setSize(3 * noBackups + 1);
  c_tablePool.setSize(noBackups * noTables + 1);
  c_attributePool.setSize(noBackups * noAttribs + MAX_ATTRIBUTES_IN_TABLE);
  c_triggerPool.setSize(noBackups * 3 * noTables);
  c_fragmentPool.setSize(noBackups * noFrags + 1);

  Uint32 szDataBuf = (2 * 1024 * 1024);
  Uint32 szLogBuf = (2 * 1024 * 1024);
  Uint32 szWrite = 32768, maxWriteSize = (256 * 1024);
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_DATA_BUFFER_MEM, &szDataBuf);
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_LOG_BUFFER_MEM, &szLogBuf);
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_WRITE_SIZE, &szWrite);
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_MAX_WRITE_SIZE, &maxWriteSize);

  c_defaults.m_logBufferSize = szLogBuf;
  c_defaults.m_dataBufferSize = szDataBuf;
  c_defaults.m_minWriteSize = szWrite;
  c_defaults.m_maxWriteSize = maxWriteSize;
  c_defaults.m_lcp_buffer_size = szDataBuf;

  Uint32 szMem = 0;
  ndb_mgm_get_int_parameter(p, CFG_DB_BACKUP_MEM, &szMem);
  Uint32 noPages = (szMem + c_defaults.m_lcp_buffer_size + sizeof(Page32) - 1)
    / sizeof(Page32);
  // We need to allocate an additional of 2 pages. 1 page because of a bug in
  // ArrayPool and another one for DICTTAINFO.
  c_pagePool.setSize(noPages + NO_OF_PAGES_META_FILE + 2);

  { // Init all tables
    SLList<Table> tables(c_tablePool);
    TablePtr ptr;
    while(tables.seize(ptr)){
      new (ptr.p) Table(c_attributePool, c_fragmentPool);
    }
    tables.release();
  }

  {
    SLList<BackupFile> ops(c_backupFilePool);
    BackupFilePtr ptr;
    while(ops.seize(ptr)){
      new (ptr.p) BackupFile(* this, c_pagePool);
    }
    ops.release();
  }

  {
    SLList<BackupRecord> recs(c_backupPool);
    BackupRecordPtr ptr;
    while(recs.seize(ptr)){
      new (ptr.p) BackupRecord(* this, c_tablePool,
			       c_backupFilePool, c_triggerPool);
    }
    recs.release();
  }

  // Initialize BAT for interface to file system
  {
    Page32Ptr p;
    ndbrequire(c_pagePool.seizeId(p, 0));
    c_startOfPages = (Uint32 *)p.p;
    c_pagePool.release(p);

    NewVARIABLE* bat = allocateBat(1);
    bat[0].WA = c_startOfPages;
    bat[0].nrr = c_pagePool.getSize()*sizeof(Page32)/sizeof(Uint32);
  }

  ReadConfigConf * conf = (ReadConfigConf*)signal->getDataPtrSend();
  conf->senderRef = reference();
  conf->senderData = senderData;
  sendSignal(ref, GSN_READ_CONFIG_CONF, signal,
	     ReadConfigConf::SignalLength, JBB);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: parsenv2.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 12:09:54 $
 *
 *  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
 *
 ************************************************************************/

#ifndef LUIDL_PARSENV2_HXX
#define LUIDL_PARSENV2_HXX

// USED SERVICES
    // BASE CLASSES
#include <s2_luidl/tokproct.hxx>
    // COMPONENTS
#include <s2_luidl/semnode.hxx>
    // PARAMETERS
#include <ary/idl/i_language.hxx>
#include <ary/idl/i_module.hxx>

// [ed] 6/15/02 The OS X compilers require full class definitions at the time
// of template instantiation
// np:  Is this really so?
#ifdef MACOSX
#include <ary_i/codeinf2.hxx>
#endif

class ParserInfo;

namespace ary
{
    class QualifiedName;

    namespace n22
    {
        class Repository;
    }

    namespace idl
    {
        class CodeEntity;
    }

    namespace info
    {
        class CodeInformation;
    }
}

namespace csi
{
namespace uidl
{

class Token;
class SemanticNode;

class UnoIDL_PE : virtual protected TokenProcessing_Types
{
  public:
    virtual             ~UnoIDL_PE();

    virtual void        EstablishContacts(
                            UnoIDL_PE *         io_pParentPE,
                            ary::n22::Repository &
                                                io_rRepository,
                            TokenProcessing_Result &
                                                o_rResult );
//  virtual void        EstablishContacts(
//                          UnoIDL_PE *         io_pParentPE,
//                          ary::idl::Gate &
//                                                io_rGate,
//                          TokenProcessing_Result &
//                                              o_rResult );
    virtual void        Enter(
                            E_EnvStackAction    i_eWayOfEntering );
    virtual void        Leave(
                            E_EnvStackAction    i_eWayOfLeaving );
    virtual void        ProcessToken(
                            const Token &       i_rToken ) = 0;

    void                SetDocu(
                            DYN ary::info::CodeInformation *
                                                let_dpDocu );
    void                SetPublished();
    void                SetOptional();
    void                PassDocuAt(
                            ary::idl::CodeEntity &
                                                io_rCe );

    UnoIDL_PE *         Parent() const          { return aMyNode.Parent(); }

    void                SetResult(
                            E_TokenDone         i_eDone,
                            E_EnvStackAction    i_eWhat2DoWithEnvStack,
                            UnoIDL_PE *         i_pParseEnv2Push = 0 )
                                                { aMyNode.SetTokenResult( i_eDone, i_eWhat2DoWithEnvStack, i_pParseEnv2Push ); }
    virtual const ary::idl::Module &
                        CurNamespace() const;
    virtual const ParserInfo &
                        ParseInfo() const;
    ary::idl::Gate &    Gate() const            { return aMyNode.AryGate(); }
    TokenProcessing_Result &
                        TokenResult() const     { return aMyNode.TokenResult(); }
    DYN ary::info::CodeInformation *
                        ReleaseDocu()           { return pDocu.Release(); }
  protected:
                        UnoIDL_PE();
    ary::n22::Repository &
                        MyRepository()          { csv_assert(pRepository != 0);
                                                  return *pRepository;  }
  private:
    virtual void        InitData();
    virtual void        TransferData() = 0;
    virtual void        ReceiveData();

    SemanticNode        aMyNode;
    Dyn<ary::info::CodeInformation>
                        pDocu;
    ary::n22::Repository *
                        pRepository;
};

// IMPLEMENTATION

}   // namespace uidl
}   // namespace csi

#endif

<commit_msg>INTEGRATION: CWS adc18 (1.9.32); FILE MERGED 2007/10/18 15:23:22 np 1.9.32.1: #i81775#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: parsenv2.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 17:13:50 $
 *
 *  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
 *
 ************************************************************************/

#ifndef LUIDL_PARSENV2_HXX
#define LUIDL_PARSENV2_HXX

// USED SERVICES
    // BASE CLASSES
#include <s2_luidl/tokproct.hxx>
    // COMPONENTS
#include <s2_luidl/semnode.hxx>
    // PARAMETERS
#include <ary/idl/i_types4idl.hxx>
#include <ary/idl/i_module.hxx>

class ParserInfo;

namespace ary
{
    class QualifiedName;
    class Repository;

namespace doc
{
    class OldIdlDocu;
}

namespace idl
{
    class CodeEntity;
}
}

namespace csi
{
namespace uidl
{

class Token;
class SemanticNode;

class UnoIDL_PE : virtual protected TokenProcessing_Types
{
  public:
    virtual             ~UnoIDL_PE();

    virtual void        EstablishContacts(
                            UnoIDL_PE *         io_pParentPE,
                            ary::Repository &
                                                io_rRepository,
                            TokenProcessing_Result &
                                                o_rResult );
//  virtual void        EstablishContacts(
//                          UnoIDL_PE *         io_pParentPE,
//                          ary::idl::Gate &
//                                                io_rGate,
//                          TokenProcessing_Result &
//                                              o_rResult );
    virtual void        Enter(
                            E_EnvStackAction    i_eWayOfEntering );
    virtual void        Leave(
                            E_EnvStackAction    i_eWayOfLeaving );
    virtual void        ProcessToken(
                            const Token &       i_rToken ) = 0;

    void                SetDocu(
                            DYN ary::doc::OldIdlDocu *
                                                let_dpDocu );
    void                SetPublished();
    void                SetOptional();
    void                PassDocuAt(
                            ary::idl::CodeEntity &
                                                io_rCe );

    UnoIDL_PE *         Parent() const          { return aMyNode.Parent(); }

    void                SetResult(
                            E_TokenDone         i_eDone,
                            E_EnvStackAction    i_eWhat2DoWithEnvStack,
                            UnoIDL_PE *         i_pParseEnv2Push = 0 )
                                                { aMyNode.SetTokenResult( i_eDone, i_eWhat2DoWithEnvStack, i_pParseEnv2Push ); }
    virtual const ary::idl::Module &
                        CurNamespace() const;
    virtual const ParserInfo &
                        ParseInfo() const;
    ary::idl::Gate &    Gate() const            { return aMyNode.AryGate(); }
    TokenProcessing_Result &
                        TokenResult() const     { return aMyNode.TokenResult(); }
    DYN ary::doc::OldIdlDocu *
                        ReleaseDocu()           { return pDocu.Release(); }
  protected:
                        UnoIDL_PE();
    ary::Repository &   MyRepository()          { csv_assert(pRepository != 0);
                                                  return *pRepository;  }
  private:
    virtual void        InitData();
    virtual void        TransferData() = 0;
    virtual void        ReceiveData();

    SemanticNode        aMyNode;
    Dyn<ary::doc::OldIdlDocu>
                        pDocu;
    ary::Repository *   pRepository;
};

}   // namespace uidl
}   // namespace csi
#endif
<|endoftext|>