<commit_before>/***************************************************************************
 *   Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This 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 Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QSettings>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>

#include <config-akonadi.h>

#include <akapplication.h>
#include <akdbus.h>
#include <akdebug.h>
#include "protocol_p.h"

#include "controlmanagerinterface.h"
#include "akonadistarter.h"
#include "xdgbasedirs_p.h"

#if defined(HAVE_UNISTD_H) && !defined(Q_WS_WIN)
#include <unistd.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

static bool startServer()
{
  if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Control ) )
       || QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Server ) ) ) {
    qWarning() << "Akonadi is already running.";
    return false;
  }
  AkonadiStarter starter;
  return starter.start();
}

static bool stopServer()
{
  org::freedesktop::Akonadi::ControlManager iface( AkDBus::serviceName( AkDBus::Control ),
                                                   QLatin1String( "/ControlManager" ),
                                                   QDBusConnection::sessionBus(), 0 );
  if ( !iface.isValid() ) {
    qWarning() << "Akonadi is not running.";
    return false;
  }

  iface.shutdown();

  return true;
}

static bool checkAkonadiControlStatus()
{
  const bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Control ) );
  fprintf( stderr, "Akonadi Control: %s\n", registered ? "running" : "stopped" );
  return registered;
}

static bool checkAkonadiServerStatus()
{
  const bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Server ) );
  fprintf( stderr, "Akonadi Server: %s\n", registered ? "running" : "stopped" );
  return registered;
}

static bool checkSearchSupportStatus()
{
  QStringList searchMethods;
  searchMethods << QLatin1String( "Remote Search" );

  const QString pluginOverride = QString::fromLatin1( qgetenv( "AKONADI_OVERRIDE_SEARCHPLUGIN" ) );
  if ( !pluginOverride.isEmpty() ) {
    searchMethods << pluginOverride;
  } else {
    const QStringList dirs = Akonadi::XdgBaseDirs::findPluginDirs();
    Q_FOREACH ( const QString &pluginDir, dirs ) {
      QDir dir( pluginDir + QLatin1String( "/akonadi" ) );
      const QStringList desktopFiles = dir.entryList( QStringList() << QLatin1String( "*.desktop" ), QDir::Files );
      Q_FOREACH ( const QString &desktopFileName, desktopFiles ) {
        QSettings desktop( pluginDir + QLatin1String( "/akonadi/" ) + desktopFileName, QSettings::IniFormat );
        desktop.beginGroup( QLatin1String( "Desktop Entry" ) );
        if ( desktop.value( QLatin1String( "Type" ) ).toString() != QLatin1String( "AkonadiSearchPlugin" ) ) {
          continue;
        }
        if ( !desktop.value( QLatin1String( "X-Akonadi-LoadByDefault" ), true ).toBool() ) {
          continue;
        }

        searchMethods << desktop.value( QLatin1String( "Name" ) ).toString();
      }
    }
  }

  // There's always at least server-search available
  fprintf( stderr, "Akonadi Server Search Support: available (%s)\n", qPrintable( searchMethods.join( QLatin1String( ", " ) ) ) );
  return true;
}

static bool statusServer()
{
  checkAkonadiControlStatus();
  checkAkonadiServerStatus();
  checkSearchSupportStatus();
  return true;
}

int main( int argc, char **argv )
{
  AkCoreApplication app( argc, argv );
  app.setDescription( QLatin1String( "Akonadi server manipulation tool\n"
      "Usage: akonadictl [command]\n\n"
      "Commands:\n"
      "  start      : Starts the Akonadi server with all its processes\n"
      "  stop       : Stops the Akonadi server and all its processes cleanly\n"
      "  restart    : Restart Akonadi server with all its processes\n"
      "  status     : Shows a status overview of the Akonadi server\n"
      "  vacuum     : Vacuum internal storage (WARNING: needs a lot of time and disk space!)\n"
      "  fsck       : Check (and attempt to fix) consistency of the internal storage (can take some time)" ) );

  app.parseCommandLine();

  QStringList optionsList;
  optionsList.append( QLatin1String( "start" ) );
  optionsList.append( QLatin1String( "stop" ) );
  optionsList.append( QLatin1String( "status" ) );
  optionsList.append( QLatin1String( "restart" ) );
  optionsList.append( QLatin1String( "vacuum" ) );
  optionsList.append( QLatin1String( "fsck" ) );

  QStringList arguments = QCoreApplication::instance()->arguments();
  if ( AkApplication::hasInstanceIdentifier() ) { // HACK: we should port all of this to boost::program_options...
    arguments.removeFirst();
    arguments.removeFirst();
  }
  if ( arguments.count() != 2 ) {
    app.printUsage();
    return 1;
  } else if ( !optionsList.contains( arguments[1] ) ) {
    app.printUsage();
    return 2;
  }

  if ( arguments[1] == QLatin1String( "start" ) ) {
    if ( !startServer() ) {
      return 3;
    }
  } else if ( arguments[1] == QLatin1String( "stop" ) ) {
    if ( !stopServer() ) {
      return 4;
    }
  } else if ( arguments[1] == QLatin1String( "status" ) ) {
    if ( !statusServer() ) {
      return 5;
    }
  } else if ( arguments[1] == QLatin1String( "restart" ) ) {
      if ( !stopServer() ) {
        return 4;
      } else {
        do {
#if defined(HAVE_UNISTD_H) && !defined(Q_WS_WIN)
          usleep( 100000 );
#else
          Sleep( 100000 );
#endif
        } while ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Control ) ) );
        if ( !startServer() ) {
          return 3;
        }
      }
  } else if ( arguments[1] == QLatin1String( "vacuum" ) ) {
    QDBusInterface iface( AkDBus::serviceName( AkDBus::StorageJanitor ), QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ) );
    iface.call( QDBus::NoBlock, QLatin1String( "vacuum" ) );
  } else if ( arguments[1] == QLatin1String( "fsck" ) ) {
    QDBusInterface iface( AkDBus::serviceName( AkDBus::StorageJanitor ), QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ) );
    iface.call( QDBus::NoBlock, QLatin1String( "check" ) );
  }
  return 0;
}
<commit_msg>Print available agent types in 'akonadictl status' output<commit_after>/***************************************************************************
 *   Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This 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 Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QSettings>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>

#include <config-akonadi.h>

#include <akapplication.h>
#include <akdbus.h>
#include <akdebug.h>
#include "protocol_p.h"

#include "controlmanagerinterface.h"
#include "akonadistarter.h"
#include "xdgbasedirs_p.h"
#include <QSettings>

#if defined(HAVE_UNISTD_H) && !defined(Q_WS_WIN)
#include <unistd.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

static bool startServer()
{
  if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Control ) )
       || QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Server ) ) ) {
    qWarning() << "Akonadi is already running.";
    return false;
  }
  AkonadiStarter starter;
  return starter.start();
}

static bool stopServer()
{
  org::freedesktop::Akonadi::ControlManager iface( AkDBus::serviceName( AkDBus::Control ),
                                                   QLatin1String( "/ControlManager" ),
                                                   QDBusConnection::sessionBus(), 0 );
  if ( !iface.isValid() ) {
    qWarning() << "Akonadi is not running.";
    return false;
  }

  iface.shutdown();

  return true;
}

static bool checkAkonadiControlStatus()
{
  const bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Control ) );
  fprintf( stderr, "Akonadi Control: %s\n", registered ? "running" : "stopped" );
  return registered;
}

static bool checkAkonadiServerStatus()
{
  const bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Server ) );
  fprintf( stderr, "Akonadi Server: %s\n", registered ? "running" : "stopped" );
  return registered;
}

static bool checkSearchSupportStatus()
{
  QStringList searchMethods;
  searchMethods << QLatin1String( "Remote Search" );

  const QString pluginOverride = QString::fromLatin1( qgetenv( "AKONADI_OVERRIDE_SEARCHPLUGIN" ) );
  if ( !pluginOverride.isEmpty() ) {
    searchMethods << pluginOverride;
  } else {
    const QStringList dirs = Akonadi::XdgBaseDirs::findPluginDirs();
    Q_FOREACH ( const QString &pluginDir, dirs ) {
      QDir dir( pluginDir + QLatin1String( "/akonadi" ) );
      const QStringList desktopFiles = dir.entryList( QStringList() << QLatin1String( "*.desktop" ), QDir::Files );
      Q_FOREACH ( const QString &desktopFileName, desktopFiles ) {
        QSettings desktop( pluginDir + QLatin1String( "/akonadi/" ) + desktopFileName, QSettings::IniFormat );
        desktop.beginGroup( QLatin1String( "Desktop Entry" ) );
        if ( desktop.value( QLatin1String( "Type" ) ).toString() != QLatin1String( "AkonadiSearchPlugin" ) ) {
          continue;
        }
        if ( !desktop.value( QLatin1String( "X-Akonadi-LoadByDefault" ), true ).toBool() ) {
          continue;
        }

        searchMethods << desktop.value( QLatin1String( "Name" ) ).toString();
      }
    }
  }

  // There's always at least server-search available
  fprintf( stderr, "Akonadi Server Search Support: available (%s)\n", qPrintable( searchMethods.join( QLatin1String( ", " ) ) ) );
  return true;
}

static bool checkAvailableAgentTypes()
{
  const QStringList dirs = Akonadi::XdgBaseDirs::findAllResourceDirs( "data", QLatin1String( "akonadi/agents" ) );
  QStringList types;
  Q_FOREACH ( const QString &pluginDir, dirs ) {
    QDir dir( pluginDir );
    const QStringList plugins = dir.entryList( QStringList() << QLatin1String( "*.desktop" ), QDir::Files );
    Q_FOREACH ( const QString &plugin, plugins ) {
      QSettings pluginInfo( pluginDir + QLatin1String("/") + plugin, QSettings::IniFormat );
      pluginInfo.beginGroup( QLatin1String( "Desktop Entry" ) );
      types << pluginInfo.value( QLatin1String( "X-Akonadi-Identifier" ) ).toString();
    }
  }

  // Remove duplicates from multiple pluginDirs
  types.removeDuplicates();
  types.sort();

  fprintf( stderr, "Available Agent Types: ");
  if ( types.isEmpty() ) {
    fprintf( stderr, "No agent types found! \n");
  } else {
    fprintf( stderr, "%s\n", qPrintable( types.join( QLatin1String( ", " ) ) ) );
  }

  return true;
}

static bool statusServer()
{
  checkAkonadiControlStatus();
  checkAkonadiServerStatus();
  checkSearchSupportStatus();
  checkAvailableAgentTypes();
  return true;
}

int main( int argc, char **argv )
{
  AkCoreApplication app( argc, argv );
  app.setDescription( QLatin1String( "Akonadi server manipulation tool\n"
      "Usage: akonadictl [command]\n\n"
      "Commands:\n"
      "  start      : Starts the Akonadi server with all its processes\n"
      "  stop       : Stops the Akonadi server and all its processes cleanly\n"
      "  restart    : Restart Akonadi server with all its processes\n"
      "  status     : Shows a status overview of the Akonadi server\n"
      "  vacuum     : Vacuum internal storage (WARNING: needs a lot of time and disk space!)\n"
      "  fsck       : Check (and attempt to fix) consistency of the internal storage (can take some time)" ) );

  app.parseCommandLine();

  QStringList optionsList;
  optionsList.append( QLatin1String( "start" ) );
  optionsList.append( QLatin1String( "stop" ) );
  optionsList.append( QLatin1String( "status" ) );
  optionsList.append( QLatin1String( "restart" ) );
  optionsList.append( QLatin1String( "vacuum" ) );
  optionsList.append( QLatin1String( "fsck" ) );

  QStringList arguments = QCoreApplication::instance()->arguments();
  if ( AkApplication::hasInstanceIdentifier() ) { // HACK: we should port all of this to boost::program_options...
    arguments.removeFirst();
    arguments.removeFirst();
  }
  if ( arguments.count() != 2 ) {
    app.printUsage();
    return 1;
  } else if ( !optionsList.contains( arguments[1] ) ) {
    app.printUsage();
    return 2;
  }

  if ( arguments[1] == QLatin1String( "start" ) ) {
    if ( !startServer() ) {
      return 3;
    }
  } else if ( arguments[1] == QLatin1String( "stop" ) ) {
    if ( !stopServer() ) {
      return 4;
    }
  } else if ( arguments[1] == QLatin1String( "status" ) ) {
    if ( !statusServer() ) {
      return 5;
    }
  } else if ( arguments[1] == QLatin1String( "restart" ) ) {
      if ( !stopServer() ) {
        return 4;
      } else {
        do {
#if defined(HAVE_UNISTD_H) && !defined(Q_WS_WIN)
          usleep( 100000 );
#else
          Sleep( 100000 );
#endif
        } while ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AkDBus::serviceName( AkDBus::Control ) ) );
        if ( !startServer() ) {
          return 3;
        }
      }
  } else if ( arguments[1] == QLatin1String( "vacuum" ) ) {
    QDBusInterface iface( AkDBus::serviceName( AkDBus::StorageJanitor ), QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ) );
    iface.call( QDBus::NoBlock, QLatin1String( "vacuum" ) );
  } else if ( arguments[1] == QLatin1String( "fsck" ) ) {
    QDBusInterface iface( AkDBus::serviceName( AkDBus::StorageJanitor ), QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ) );
    iface.call( QDBus::NoBlock, QLatin1String( "check" ) );
  }
  return 0;
}
<|endoftext|>


<commit_before>/* Copyright 2014 Open Source Robotics Foundation, 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.
 */

#ifndef RCLCPP_RCLCPP_NODE_IMPL_HPP_
#define RCLCPP_RCLCPP_NODE_IMPL_HPP_

#include <memory>
#include <string>

#include <rmw/rmw.h>
#include <rmw/get_type_support_handle.h>
#include <rmw/get_service_type_support_handle.h>

#include <rosidl_generator_cpp/MessageTypeSupport.h>
#include <rosidl_generator_cpp/ServiceTypeSupport.h>

#include <rclcpp/contexts/default_context.hpp>

#ifndef RCLCPP_RCLCPP_NODE_HPP_
#include "node.hpp"
#endif

using namespace rclcpp;
using namespace rclcpp::node;

using rclcpp::contexts::default_context::DefaultContext;

Node::Node(std::string node_name)
  : Node(node_name, DefaultContext::make_shared())
{}

Node::Node(std::string node_name, context::Context::SharedPtr context)
  : name_(node_name), context_(context),
    number_of_subscriptions_(0), number_of_timers_(0), number_of_services_(0)
{
  node_handle_ = rmw_create_node(name_.c_str());
  using rclcpp::callback_group::CallbackGroupType;
  default_callback_group_ = \
    create_callback_group(CallbackGroupType::MutuallyExclusive);
}

rclcpp::callback_group::CallbackGroup::SharedPtr
Node::create_callback_group(
  rclcpp::callback_group::CallbackGroupType group_type)
{
  using rclcpp::callback_group::CallbackGroup;
  using rclcpp::callback_group::CallbackGroupType;
  auto group = CallbackGroup::SharedPtr(new CallbackGroup(group_type));
  callback_groups_.push_back(group);
  return group;
}

template<typename MessageT>
publisher::Publisher::SharedPtr
Node::create_publisher(std::string topic_name, size_t queue_size)
{
  using rmw::get_type_support_handle;
  auto type_support_handle = get_type_support_handle<MessageT>();
  rmw_publisher_t * publisher_handle = rmw_create_publisher(
    node_handle_, type_support_handle, topic_name.c_str(), queue_size);

  return publisher::Publisher::make_shared(publisher_handle);
}

bool
Node::group_in_node(callback_group::CallbackGroup::SharedPtr &group)
{
  bool group_belongs_to_this_node = false;
  for (auto &weak_group : this->callback_groups_)
  {
    auto cur_group = weak_group.lock();
    if (cur_group && cur_group == group)
    {
      group_belongs_to_this_node = true;
    }
  }
  return group_belongs_to_this_node;
}

template<typename MessageT>
typename subscription::Subscription<MessageT>::SharedPtr
Node::create_subscription(
  std::string topic_name,
  size_t queue_size,
  std::function<void(const std::shared_ptr<MessageT> &)> callback,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  using rmw::get_type_support_handle;
  auto type_support_handle = get_type_support_handle<MessageT>();
  rmw_subscription_t * subscriber_handle = rmw_create_subscription(
    node_handle_, type_support_handle, topic_name.c_str(), queue_size);

  using namespace rclcpp::subscription;

  auto sub = Subscription<MessageT>::make_shared(subscriber_handle,
                                                 topic_name,
                                                 callback);
  auto sub_base_ptr = std::dynamic_pointer_cast<SubscriptionBase>(sub);
  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO: use custom exception
      throw std::runtime_error("Cannot create timer, group not in node.");
    }
    group->add_subscription(sub_base_ptr);
  }
  else
  {
    default_callback_group_->add_subscription(sub_base_ptr);
  }
  number_of_subscriptions_++;
  return sub;
}

rclcpp::timer::WallTimer::SharedPtr
Node::create_wall_timer(std::chrono::nanoseconds period,
                        rclcpp::timer::CallbackType callback,
                        rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  auto timer = rclcpp::timer::WallTimer::make_shared(period, callback);
  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO: use custom exception
      throw std::runtime_error("Cannot create timer, group not in node.");
    }
    group->add_timer(timer);
  }
  else
  {
    default_callback_group_->add_timer(timer);
  }
  number_of_timers_++;
  return timer;
}

rclcpp::timer::WallTimer::SharedPtr
Node::create_wall_timer(
  std::chrono::duration<long double, std::nano> period,
  rclcpp::timer::CallbackType callback,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  return create_wall_timer(
    std::chrono::duration_cast<std::chrono::nanoseconds>(period),
    callback,
    group);
}

template<typename ServiceT>
typename client::Client<ServiceT>::SharedPtr
Node::create_client(
  std::string service_name,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  using rosidl_generator_cpp::get_service_type_support_handle;
  auto service_type_support_handle =
    get_service_type_support_handle<ServiceT>();

  rmw_client_t * client_handle = rmw_create_client(
    this->node_handle_, service_type_support_handle, service_name.c_str());

  using namespace rclcpp::client;

  auto cli = Client<ServiceT>::make_shared(client_handle,
                                           service_name);

  auto cli_base_ptr = std::dynamic_pointer_cast<ClientBase>(cli);
  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO(esteve): use custom exception
      throw std::runtime_error("Cannot create client, group not in node.");
    }
    group->add_client(cli_base_ptr);
  }
  else
  {
    default_callback_group_->add_client(cli_base_ptr);
  }
  number_of_clients_++;

  return cli;
}

template <typename ServiceT>
typename service::Service<ServiceT>::SharedPtr
Node::create_service(
  std::string service_name,
  std::function<void(const std::shared_ptr<typename ServiceT::Request> &,
                     std::shared_ptr<typename ServiceT::Response>&)> callback,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  using rosidl_generator_cpp::get_service_type_support_handle;
  auto service_type_support_handle =
    get_service_type_support_handle<ServiceT>();

  rmw_service_t * service_handle = rmw_create_service(
    this->node_handle_, service_type_support_handle, service_name.c_str());

  using namespace rclcpp::service;

  auto serv = Service<ServiceT>::make_shared(service_handle,
                                             service_name,
                                             callback);
  auto serv_base_ptr = std::dynamic_pointer_cast<ServiceBase>(serv);

  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO: use custom exception
      throw std::runtime_error("Cannot create service, group not in node.");
    }
    group->add_service(serv_base_ptr);
  }
  else
  {
    default_callback_group_->add_service(serv_base_ptr);
  }
  number_of_services_++;

  return serv;
}

#endif /* RCLCPP_RCLCPP_NODE_IMPL_HPP_ */
<commit_msg>Removed unused include<commit_after>/* Copyright 2014 Open Source Robotics Foundation, 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.
 */

#ifndef RCLCPP_RCLCPP_NODE_IMPL_HPP_
#define RCLCPP_RCLCPP_NODE_IMPL_HPP_

#include <memory>
#include <string>

#include <rmw/rmw.h>
#include <rmw/get_type_support_handle.h>

#include <rosidl_generator_cpp/MessageTypeSupport.h>
#include <rosidl_generator_cpp/ServiceTypeSupport.h>

#include <rclcpp/contexts/default_context.hpp>

#ifndef RCLCPP_RCLCPP_NODE_HPP_
#include "node.hpp"
#endif

using namespace rclcpp;
using namespace rclcpp::node;

using rclcpp::contexts::default_context::DefaultContext;

Node::Node(std::string node_name)
  : Node(node_name, DefaultContext::make_shared())
{}

Node::Node(std::string node_name, context::Context::SharedPtr context)
  : name_(node_name), context_(context),
    number_of_subscriptions_(0), number_of_timers_(0), number_of_services_(0)
{
  node_handle_ = rmw_create_node(name_.c_str());
  using rclcpp::callback_group::CallbackGroupType;
  default_callback_group_ = \
    create_callback_group(CallbackGroupType::MutuallyExclusive);
}

rclcpp::callback_group::CallbackGroup::SharedPtr
Node::create_callback_group(
  rclcpp::callback_group::CallbackGroupType group_type)
{
  using rclcpp::callback_group::CallbackGroup;
  using rclcpp::callback_group::CallbackGroupType;
  auto group = CallbackGroup::SharedPtr(new CallbackGroup(group_type));
  callback_groups_.push_back(group);
  return group;
}

template<typename MessageT>
publisher::Publisher::SharedPtr
Node::create_publisher(std::string topic_name, size_t queue_size)
{
  using rmw::get_type_support_handle;
  auto type_support_handle = get_type_support_handle<MessageT>();
  rmw_publisher_t * publisher_handle = rmw_create_publisher(
    node_handle_, type_support_handle, topic_name.c_str(), queue_size);

  return publisher::Publisher::make_shared(publisher_handle);
}

bool
Node::group_in_node(callback_group::CallbackGroup::SharedPtr &group)
{
  bool group_belongs_to_this_node = false;
  for (auto &weak_group : this->callback_groups_)
  {
    auto cur_group = weak_group.lock();
    if (cur_group && cur_group == group)
    {
      group_belongs_to_this_node = true;
    }
  }
  return group_belongs_to_this_node;
}

template<typename MessageT>
typename subscription::Subscription<MessageT>::SharedPtr
Node::create_subscription(
  std::string topic_name,
  size_t queue_size,
  std::function<void(const std::shared_ptr<MessageT> &)> callback,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  using rmw::get_type_support_handle;
  auto type_support_handle = get_type_support_handle<MessageT>();
  rmw_subscription_t * subscriber_handle = rmw_create_subscription(
    node_handle_, type_support_handle, topic_name.c_str(), queue_size);

  using namespace rclcpp::subscription;

  auto sub = Subscription<MessageT>::make_shared(subscriber_handle,
                                                 topic_name,
                                                 callback);
  auto sub_base_ptr = std::dynamic_pointer_cast<SubscriptionBase>(sub);
  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO: use custom exception
      throw std::runtime_error("Cannot create timer, group not in node.");
    }
    group->add_subscription(sub_base_ptr);
  }
  else
  {
    default_callback_group_->add_subscription(sub_base_ptr);
  }
  number_of_subscriptions_++;
  return sub;
}

rclcpp::timer::WallTimer::SharedPtr
Node::create_wall_timer(std::chrono::nanoseconds period,
                        rclcpp::timer::CallbackType callback,
                        rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  auto timer = rclcpp::timer::WallTimer::make_shared(period, callback);
  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO: use custom exception
      throw std::runtime_error("Cannot create timer, group not in node.");
    }
    group->add_timer(timer);
  }
  else
  {
    default_callback_group_->add_timer(timer);
  }
  number_of_timers_++;
  return timer;
}

rclcpp::timer::WallTimer::SharedPtr
Node::create_wall_timer(
  std::chrono::duration<long double, std::nano> period,
  rclcpp::timer::CallbackType callback,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  return create_wall_timer(
    std::chrono::duration_cast<std::chrono::nanoseconds>(period),
    callback,
    group);
}

template<typename ServiceT>
typename client::Client<ServiceT>::SharedPtr
Node::create_client(
  std::string service_name,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  using rosidl_generator_cpp::get_service_type_support_handle;
  auto service_type_support_handle =
    get_service_type_support_handle<ServiceT>();

  rmw_client_t * client_handle = rmw_create_client(
    this->node_handle_, service_type_support_handle, service_name.c_str());

  using namespace rclcpp::client;

  auto cli = Client<ServiceT>::make_shared(client_handle,
                                           service_name);

  auto cli_base_ptr = std::dynamic_pointer_cast<ClientBase>(cli);
  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO(esteve): use custom exception
      throw std::runtime_error("Cannot create client, group not in node.");
    }
    group->add_client(cli_base_ptr);
  }
  else
  {
    default_callback_group_->add_client(cli_base_ptr);
  }
  number_of_clients_++;

  return cli;
}

template <typename ServiceT>
typename service::Service<ServiceT>::SharedPtr
Node::create_service(
  std::string service_name,
  std::function<void(const std::shared_ptr<typename ServiceT::Request> &,
                     std::shared_ptr<typename ServiceT::Response>&)> callback,
  rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  using rosidl_generator_cpp::get_service_type_support_handle;
  auto service_type_support_handle =
    get_service_type_support_handle<ServiceT>();

  rmw_service_t * service_handle = rmw_create_service(
    this->node_handle_, service_type_support_handle, service_name.c_str());

  using namespace rclcpp::service;

  auto serv = Service<ServiceT>::make_shared(service_handle,
                                             service_name,
                                             callback);
  auto serv_base_ptr = std::dynamic_pointer_cast<ServiceBase>(serv);

  if (group)
  {
    if (!group_in_node(group))
    {
      // TODO: use custom exception
      throw std::runtime_error("Cannot create service, group not in node.");
    }
    group->add_service(serv_base_ptr);
  }
  else
  {
    default_callback_group_->add_service(serv_base_ptr);
  }
  number_of_services_++;

  return serv;
}

#endif /* RCLCPP_RCLCPP_NODE_IMPL_HPP_ */
<|endoftext|>


<commit_before>// Copyright 2014 Open Source Robotics Foundation, 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.

#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_
#define RCLCPP_RCLCPP_UTILITIES_HPP_

// TODO(wjwwood): remove
#include <iostream>

#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstring>
#include <mutex>
#include <thread>

#include <rmw/macros.h>
#include <rmw/rmw.h>

// Determine if sigaction is available
#if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#define HAS_SIGACTION
#endif

namespace
{
volatile sig_atomic_t g_signal_status = 0;
rmw_guard_condition_t * g_sigint_guard_cond_handle = \
  rmw_create_guard_condition();
std::condition_variable g_interrupt_condition_variable;
std::mutex g_interrupt_mutex;

#ifdef HAS_SIGACTION
struct sigaction old_action;
#else
void (* old_signal_handler)(int) = 0;
#endif

void
#ifdef HAS_SIGACTION
signal_handler(int signal_value, siginfo_t * siginfo, void * context)
#else
signal_handler(int signal_value)
#endif
{
  // TODO(wjwwood): remove
  std::cout << "signal_handler(" << signal_value << ")" << std::endl;
#ifdef HAS_SIGACTION
  if (old_action.sa_flags & SA_SIGINFO) {
    if (old_action.sa_sigaction != NULL) {
      old_action.sa_sigaction(signal_value, siginfo, context);
    }
  } else {
    if (
      old_action.sa_handler != NULL && // Is set
      old_action.sa_handler != SIG_DFL && // Is not default
      old_action.sa_handler != SIG_IGN) // Is not ignored
    {
      old_action.sa_handler(signal_value);
    }
  }
#else
  if (old_signal_handler) {
    old_signal_handler(signal_value);
  }
#endif
  g_signal_status = signal_value;
  rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  g_interrupt_condition_variable.notify_all();
}
} // namespace

namespace rclcpp
{

RMW_THREAD_LOCAL size_t thread_id = 0;

namespace utilities
{

void
init(int argc, char * argv[])
{
  // TODO(wjwwood): Handle rmw_ret_t's value.
  rmw_init();
#ifdef HAS_SIGACTION
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = ::signal_handler;
  action.sa_flags = SA_SIGINFO;
  ssize_t ret = sigaction(SIGINT, &action, &old_action);
  if (ret == -1)
#else
  ::old_signal_handler = std::signal(SIGINT, ::signal_handler);
  if (::old_signal_handler == SIG_ERR)
#endif
  {
    throw std::runtime_error(
      std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") +
      // TODO(wjwwood): use strerror_r on POSIX and strerror_s on Windows.
      std::strerror(errno));
  }
}

bool
ok()
{
  return ::g_signal_status == 0;
}

void
shutdown()
{
  g_signal_status = SIGINT;
  rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  g_interrupt_condition_variable.notify_all();
}

rmw_guard_condition_t *
get_global_sigint_guard_condition()
{
  return ::g_sigint_guard_cond_handle;
}

bool
sleep_for(const std::chrono::nanoseconds & nanoseconds)
{
  // TODO: determine if posix's nanosleep(2) is more efficient here
  std::unique_lock<std::mutex> lock(::g_interrupt_mutex);
  auto cvs = ::g_interrupt_condition_variable.wait_for(lock, nanoseconds);
  return cvs == std::cv_status::no_timeout;
}

} /* namespace utilities */
} /* namespace rclcpp */

#ifdef HAS_SIGACTION
#undef HAS_SIGACTION
#endif

#endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */
<commit_msg>explicitly ignore remaining uncrustify issues<commit_after>// Copyright 2014 Open Source Robotics Foundation, 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.

#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_
#define RCLCPP_RCLCPP_UTILITIES_HPP_

// TODO(wjwwood): remove
#include <iostream>

#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstring>
#include <mutex>
#include <thread>

#include <rmw/macros.h>
#include <rmw/rmw.h>

// Determine if sigaction is available
#if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#define HAS_SIGACTION
#endif

namespace
{
volatile sig_atomic_t g_signal_status = 0;
rmw_guard_condition_t * g_sigint_guard_cond_handle = \
  rmw_create_guard_condition();
std::condition_variable g_interrupt_condition_variable;
std::mutex g_interrupt_mutex;

#ifdef HAS_SIGACTION
struct sigaction old_action;
#else
void (* old_signal_handler)(int) = 0;
#endif

void
#ifdef HAS_SIGACTION
signal_handler(int signal_value, siginfo_t * siginfo, void * context)
#else
signal_handler(int signal_value)
#endif
{
  // TODO(wjwwood): remove
  std::cout << "signal_handler(" << signal_value << ")" << std::endl;
#ifdef HAS_SIGACTION
  if (old_action.sa_flags & SA_SIGINFO) {
    if (old_action.sa_sigaction != NULL) {
      old_action.sa_sigaction(signal_value, siginfo, context);
    }
  } else {
    // *INDENT-OFF*
    if (
      old_action.sa_handler != NULL && // Is set
      old_action.sa_handler != SIG_DFL && // Is not default
      old_action.sa_handler != SIG_IGN) // Is not ignored
    // *INDENT-ON*
    {
      old_action.sa_handler(signal_value);
    }
  }
#else
  if (old_signal_handler) {
    old_signal_handler(signal_value);
  }
#endif
  g_signal_status = signal_value;
  rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  g_interrupt_condition_variable.notify_all();
}
} // namespace

namespace rclcpp
{

RMW_THREAD_LOCAL size_t thread_id = 0;

namespace utilities
{

void
init(int argc, char * argv[])
{
  // TODO(wjwwood): Handle rmw_ret_t's value.
  rmw_init();
#ifdef HAS_SIGACTION
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = ::signal_handler;
  action.sa_flags = SA_SIGINFO;
  ssize_t ret = sigaction(SIGINT, &action, &old_action);
  if (ret == -1)
#else
  ::old_signal_handler = std::signal(SIGINT, ::signal_handler);
  if (::old_signal_handler == SIG_ERR)
#endif
  {
    // *INDENT-OFF*
    throw std::runtime_error(
      std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") +
      // TODO(wjwwood): use strerror_r on POSIX and strerror_s on Windows.
      std::strerror(errno));
    // *INDENT-ON*
  }
}

bool
ok()
{
  return ::g_signal_status == 0;
}

void
shutdown()
{
  g_signal_status = SIGINT;
  rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  g_interrupt_condition_variable.notify_all();
}

rmw_guard_condition_t *
get_global_sigint_guard_condition()
{
  return ::g_sigint_guard_cond_handle;
}

bool
sleep_for(const std::chrono::nanoseconds & nanoseconds)
{
  // TODO: determine if posix's nanosleep(2) is more efficient here
  std::unique_lock<std::mutex> lock(::g_interrupt_mutex);
  auto cvs = ::g_interrupt_condition_variable.wait_for(lock, nanoseconds);
  return cvs == std::cv_status::no_timeout;
}

} /* namespace utilities */
} /* namespace rclcpp */

#ifdef HAS_SIGACTION
#undef HAS_SIGACTION
#endif

#endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EConnection.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-03-29 12:16:30 $
 *
 *  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 _CONNECTIVITY_FLAT_ECONNECTION_HXX_
#include "flat/EConnection.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_EDATABASEMETADATA_HXX_
#include "flat/EDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_CATALOG_HXX_
#include "flat/ECatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _CONNECTIVITY_FLAT_ODRIVER_HXX_
#include "flat/EDriver.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_FLAT_DPREPAREDSTATEMENT_HXX_
#include "flat/EPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_DSTATEMENT_HXX_
#include "flat/EStatement.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif

using namespace connectivity::flat;
using namespace connectivity::file;

typedef connectivity::file::OConnection  OConnection_B;

//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

// --------------------------------------------------------------------------------
OFlatConnection::OFlatConnection(ODriver*   _pDriver) : OConnection(_pDriver)
    ,m_bHeaderLine(sal_True)
    ,m_cFieldDelimiter(';')
    ,m_cStringDelimiter('"')
    ,m_cDecimalDelimiter(',')
    ,m_cThousandDelimiter('.')
{
}
//-----------------------------------------------------------------------------
OFlatConnection::~OFlatConnection()
{
}

// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OFlatConnection, "com.sun.star.sdbc.drivers.flat.Connection", "com.sun.star.sdbc.Connection")

//-----------------------------------------------------------------------------
void OFlatConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info)  throw(SQLException)
{
    osl_incrementInterlockedCount( &m_refCount );

    ::rtl::OUString aExt;
    const PropertyValue *pBegin  = info.getConstArray();
    const PropertyValue *pEnd    = pBegin + info.getLength();
    for(;pBegin != pEnd;++pBegin)
    {
        if(!pBegin->Name.compareToAscii("HeaderLine"))
            m_bHeaderLine = cppu::any2bool(pBegin->Value);
        else if(!pBegin->Name.compareToAscii("FieldDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cFieldDelimiter = aVal.toChar();
        }
        else if(!pBegin->Name.compareToAscii("StringDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cStringDelimiter = aVal.toChar();
        }
        else if(!pBegin->Name.compareToAscii("DecimalDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cDecimalDelimiter = aVal.toChar();
        }
        else if(!pBegin->Name.compareToAscii("ThousandDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cThousandDelimiter = aVal.toChar();
        }
    }

    osl_decrementInterlockedCount( &m_refCount );
    OConnection::construct(url,info);
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OFlatConnection::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
    if(!xMetaData.is())
    {
        xMetaData = new OFlatDatabaseMetaData(this);
        m_xMetaData = xMetaData;
    }

    return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OFlatConnection::createCatalog()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    Reference< XTablesSupplier > xTab = m_xCatalog;
    if(!xTab.is())
    {
        OFlatCatalog *pCat = new OFlatCatalog(this);
        xTab = pCat;
        m_xCatalog = xTab;
    }
    return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OFlatConnection::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OFlatStatement* pStmt = new OFlatStatement(this);

    Reference< XStatement > xStmt = pStmt;
    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OFlatConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OFlatPreparedStatement* pStmt = new OFlatPreparedStatement(this);
    Reference< XPreparedStatement > xStmt = pStmt;
    pStmt->construct(sql);

    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OFlatConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    return NULL;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.11.28); FILE MERGED 2005/11/16 12:59:04 fs 1.11.28.1: #i57457# warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EConnection.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:28:00 $
 *
 *  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 _CONNECTIVITY_FLAT_ECONNECTION_HXX_
#include "flat/EConnection.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_EDATABASEMETADATA_HXX_
#include "flat/EDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_CATALOG_HXX_
#include "flat/ECatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _CONNECTIVITY_FLAT_ODRIVER_HXX_
#include "flat/EDriver.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_FLAT_DPREPAREDSTATEMENT_HXX_
#include "flat/EPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_DSTATEMENT_HXX_
#include "flat/EStatement.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

using namespace connectivity::flat;
using namespace connectivity::file;

typedef connectivity::file::OConnection  OConnection_B;

//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

// --------------------------------------------------------------------------------
OFlatConnection::OFlatConnection(ODriver*   _pDriver) : OConnection(_pDriver)
    ,m_bHeaderLine(sal_True)
    ,m_cFieldDelimiter(';')
    ,m_cStringDelimiter('"')
    ,m_cDecimalDelimiter(',')
    ,m_cThousandDelimiter('.')
{
}
//-----------------------------------------------------------------------------
OFlatConnection::~OFlatConnection()
{
}

// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OFlatConnection, "com.sun.star.sdbc.drivers.flat.Connection", "com.sun.star.sdbc.Connection")

//-----------------------------------------------------------------------------
void OFlatConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info)  throw(SQLException)
{
    osl_incrementInterlockedCount( &m_refCount );

    ::rtl::OUString aExt;
    const PropertyValue *pBegin  = info.getConstArray();
    const PropertyValue *pEnd    = pBegin + info.getLength();
    for(;pBegin != pEnd;++pBegin)
    {
        if(!pBegin->Name.compareToAscii("HeaderLine"))
            m_bHeaderLine = cppu::any2bool(pBegin->Value);
        else if(!pBegin->Name.compareToAscii("FieldDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cFieldDelimiter = aVal.toChar();
        }
        else if(!pBegin->Name.compareToAscii("StringDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cStringDelimiter = aVal.toChar();
        }
        else if(!pBegin->Name.compareToAscii("DecimalDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cDecimalDelimiter = aVal.toChar();
        }
        else if(!pBegin->Name.compareToAscii("ThousandDelimiter"))
        {
            ::rtl::OUString aVal;
            pBegin->Value >>= aVal; m_cThousandDelimiter = aVal.toChar();
        }
    }

    osl_decrementInterlockedCount( &m_refCount );
    OConnection::construct(url,info);
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OFlatConnection::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
    if(!xMetaData.is())
    {
        xMetaData = new OFlatDatabaseMetaData(this);
        m_xMetaData = xMetaData;
    }

    return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OFlatConnection::createCatalog()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    Reference< XTablesSupplier > xTab = m_xCatalog;
    if(!xTab.is())
    {
        OFlatCatalog *pCat = new OFlatCatalog(this);
        xTab = pCat;
        m_xCatalog = xTab;
    }
    return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OFlatConnection::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OFlatStatement* pStmt = new OFlatStatement(this);

    Reference< XStatement > xStmt = pStmt;
    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OFlatConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OFlatPreparedStatement* pStmt = new OFlatPreparedStatement(this);
    Reference< XPreparedStatement > xStmt = pStmt;
    pStmt->construct(sql);

    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OFlatConnection::prepareCall( const ::rtl::OUString& /*sql*/ ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    ::dbtools::throwFeatureNotImplementedException( "XConnection::prepareCall", *this );
    return NULL;
}

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/shell/shell_download_manager_delegate.h"

#include "base/bind.h"
#include "base/file_util.h"
#include "base/utf_string_conversions.h"
#include "content/browser/browser_context.h"
#include "content/browser/browser_thread.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/download/download_state_info.h"
#include "net/base/net_util.h"

namespace content {

ShellDownloadManagerDelegate::ShellDownloadManagerDelegate()
    : download_manager_(NULL) {
}

ShellDownloadManagerDelegate::~ShellDownloadManagerDelegate(){
}

void ShellDownloadManagerDelegate::SetDownloadManager(
    DownloadManager* download_manager) {
  download_manager_ = download_manager;
}

void ShellDownloadManagerDelegate::Shutdown() {
}

bool ShellDownloadManagerDelegate::ShouldStartDownload(int32 download_id) {
  DownloadItem* download =
      download_manager_->GetActiveDownloadItem(download_id);
  DownloadStateInfo state = download->state_info();

  if (!state.force_file_name.empty())
    return true;

  FilePath generated_name = net::GenerateFileName(
      download->GetURL(),
      download->content_disposition(),
      download->referrer_charset(),
      download->suggested_filename(),
      download->mime_type(),
      string16(UTF8ToUTF16("download")));

  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(
          &ShellDownloadManagerDelegate::GenerateFilename,
          this, download_id, state, generated_name));
  return false;
}

void ShellDownloadManagerDelegate::GenerateFilename(
    int32 download_id,
    DownloadStateInfo state,
    const FilePath& generated_name) {
  if (state.suggested_path.empty()) {
    state.suggested_path = download_manager_->browser_context()->GetPath().
        Append(FILE_PATH_LITERAL("Downloads"));
    if (!file_util::PathExists(state.suggested_path))
      file_util::CreateDirectory(state.suggested_path);
  }

  state.suggested_path = state.suggested_path.Append(generated_name);

  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(
          &ShellDownloadManagerDelegate::RestartDownload,
          this, download_id, state));
}

void ShellDownloadManagerDelegate::RestartDownload(
    int32 download_id,
    DownloadStateInfo state) {
  DownloadItem* download =
      download_manager_->GetActiveDownloadItem(download_id);
  if (!download)
    return;
  download->SetFileCheckResults(state);
  download_manager_->RestartDownload(download_id);
}

void ShellDownloadManagerDelegate::ChooseDownloadPath(
    TabContents* tab_contents,
    const FilePath& suggested_path,
    void* data) {
}

bool ShellDownloadManagerDelegate::OverrideIntermediatePath(
    DownloadItem* item,
    FilePath* intermediate_path) {
  return false;
}

TabContents* ShellDownloadManagerDelegate::
    GetAlternativeTabContentsToNotifyForDownload() {
  return NULL;
}

bool ShellDownloadManagerDelegate::ShouldOpenFileBasedOnExtension(
    const FilePath& path) {
  return false;
}

bool ShellDownloadManagerDelegate::ShouldOpenDownload(DownloadItem* item) {
  return true;
}

bool ShellDownloadManagerDelegate::ShouldCompleteDownload(DownloadItem* item) {
  return true;
}

bool ShellDownloadManagerDelegate::GenerateFileHash() {
  return false;
}

void ShellDownloadManagerDelegate::OnResponseCompleted(
    DownloadItem* item,
    const std::string& hash) {
}

void ShellDownloadManagerDelegate::AddItemToPersistentStore(
    DownloadItem* item) {
}

void ShellDownloadManagerDelegate::UpdateItemInPersistentStore(
    DownloadItem* item) {
}

void ShellDownloadManagerDelegate::UpdatePathForItemInPersistentStore(
    DownloadItem* item,
    const FilePath& new_path) {
}

void ShellDownloadManagerDelegate::RemoveItemFromPersistentStore(
    DownloadItem* item) {
}

void ShellDownloadManagerDelegate::RemoveItemsFromPersistentStoreBetween(
    const base::Time remove_begin,
    const base::Time remove_end) {
}

void ShellDownloadManagerDelegate::GetSaveDir(
    TabContents* tab_contents,
    FilePath* website_save_dir,
    FilePath* download_save_dir) {
}

void ShellDownloadManagerDelegate::ChooseSavePath(
    const base::WeakPtr<SavePackage>& save_package,
    const FilePath& suggested_path,
    bool can_save_as_complete) {
}

void ShellDownloadManagerDelegate::DownloadProgressUpdated() {
}

}  // namespace content
<commit_msg>Always prompt the user for the download location in content_shell, as an indication that a download is happening since we don't have a downloads UI.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/shell/shell_download_manager_delegate.h"

#if defined(OS_WIN)
#include <windows.h>
#include <commdlg.h>
#endif

#include "base/bind.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "content/browser/browser_context.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/download/download_state_info.h"
#include "net/base/net_util.h"

namespace content {

ShellDownloadManagerDelegate::ShellDownloadManagerDelegate()
    : download_manager_(NULL) {
}

ShellDownloadManagerDelegate::~ShellDownloadManagerDelegate(){
}

void ShellDownloadManagerDelegate::SetDownloadManager(
    DownloadManager* download_manager) {
  download_manager_ = download_manager;
}

void ShellDownloadManagerDelegate::Shutdown() {
}

bool ShellDownloadManagerDelegate::ShouldStartDownload(int32 download_id) {
  DownloadItem* download =
      download_manager_->GetActiveDownloadItem(download_id);
  DownloadStateInfo state = download->state_info();

  if (!state.force_file_name.empty())
    return true;

  FilePath generated_name = net::GenerateFileName(
      download->GetURL(),
      download->content_disposition(),
      download->referrer_charset(),
      download->suggested_filename(),
      download->mime_type(),
      string16(UTF8ToUTF16("download")));

  // Since we have no download UI, show the user a dialog always.
  state.prompt_user_for_save_location = true;

  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(
          &ShellDownloadManagerDelegate::GenerateFilename,
          this, download_id, state, generated_name));
  return false;
}

void ShellDownloadManagerDelegate::GenerateFilename(
    int32 download_id,
    DownloadStateInfo state,
    const FilePath& generated_name) {
  if (state.suggested_path.empty()) {
    state.suggested_path = download_manager_->browser_context()->GetPath().
        Append(FILE_PATH_LITERAL("Downloads"));
    if (!file_util::PathExists(state.suggested_path))
      file_util::CreateDirectory(state.suggested_path);
  }

  state.suggested_path = state.suggested_path.Append(generated_name);

  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(
          &ShellDownloadManagerDelegate::RestartDownload,
          this, download_id, state));
}

void ShellDownloadManagerDelegate::RestartDownload(
    int32 download_id,
    DownloadStateInfo state) {
  DownloadItem* download =
      download_manager_->GetActiveDownloadItem(download_id);
  if (!download)
    return;
  download->SetFileCheckResults(state);
  download_manager_->RestartDownload(download_id);
}

void ShellDownloadManagerDelegate::ChooseDownloadPath(
    TabContents* tab_contents,
    const FilePath& suggested_path,
    void* data) {
  FilePath result;
#if defined(OS_WIN)
  std::wstring file_part = FilePath(suggested_path).BaseName().value();
  wchar_t file_name[MAX_PATH];
  base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name));
  OPENFILENAME save_as;
  ZeroMemory(&save_as, sizeof(save_as));
  save_as.lStructSize = sizeof(OPENFILENAME);
  save_as.hwndOwner = tab_contents->GetNativeView();
  save_as.lpstrFile = file_name;
  save_as.nMaxFile = arraysize(file_name);

  std::wstring directory;
  if (!suggested_path.empty())
    directory = suggested_path.DirName().value();

  save_as.lpstrInitialDir = directory.c_str();
  save_as.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING |
                  OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;

  if (GetSaveFileName(&save_as))
    result = FilePath(std::wstring(save_as.lpstrFile));
#else
  NOTIMPLEMENTED();
#endif

  if (result.empty()) {
    download_manager_->FileSelectionCanceled(data);
  } else {
    download_manager_->FileSelected(result, data);
  }
}

bool ShellDownloadManagerDelegate::OverrideIntermediatePath(
    DownloadItem* item,
    FilePath* intermediate_path) {
  return false;
}

TabContents* ShellDownloadManagerDelegate::
    GetAlternativeTabContentsToNotifyForDownload() {
  return NULL;
}

bool ShellDownloadManagerDelegate::ShouldOpenFileBasedOnExtension(
    const FilePath& path) {
  return false;
}

bool ShellDownloadManagerDelegate::ShouldOpenDownload(DownloadItem* item) {
  return true;
}

bool ShellDownloadManagerDelegate::ShouldCompleteDownload(DownloadItem* item) {
  return true;
}

bool ShellDownloadManagerDelegate::GenerateFileHash() {
  return false;
}

void ShellDownloadManagerDelegate::OnResponseCompleted(
    DownloadItem* item,
    const std::string& hash) {
}

void ShellDownloadManagerDelegate::AddItemToPersistentStore(
    DownloadItem* item) {
}

void ShellDownloadManagerDelegate::UpdateItemInPersistentStore(
    DownloadItem* item) {
}

void ShellDownloadManagerDelegate::UpdatePathForItemInPersistentStore(
    DownloadItem* item,
    const FilePath& new_path) {
}

void ShellDownloadManagerDelegate::RemoveItemFromPersistentStore(
    DownloadItem* item) {
}

void ShellDownloadManagerDelegate::RemoveItemsFromPersistentStoreBetween(
    const base::Time remove_begin,
    const base::Time remove_end) {
}

void ShellDownloadManagerDelegate::GetSaveDir(
    TabContents* tab_contents,
    FilePath* website_save_dir,
    FilePath* download_save_dir) {
}

void ShellDownloadManagerDelegate::ChooseSavePath(
    const base::WeakPtr<SavePackage>& save_package,
    const FilePath& suggested_path,
    bool can_save_as_complete) {
}

void ShellDownloadManagerDelegate::DownloadProgressUpdated() {
}

}  // namespace content
<|endoftext|>


<commit_before><commit_msg>Fix units bug in cextract<commit_after><|endoftext|>


<commit_before>#include "h5test.h"
#include "h5writer.h"
#include "parallel.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"

struct Var_t
{
  const char * name;
  const char * descript;
};

Var_t varT[] =
  {
    {"T", "Temp in K"},
    {"p", "Pressure in N/m^2"},
    {"u", "X Velocity in m/s"},
    {"v", "Y Velocity in m/s"},
    {"w", "Z Velocity in m/s"},
    {"a", "A Velocity in m/s"},
    {"b", "B Velocity in m/s"},
    {"c", "C Velocity in m/s"},
    {"d", "D Velocity in m/s"},
    {"e", "E Velocity in m/s"},
  };

H5::H5()
  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
    m_nIOUnits(1), m_factor(1), m_stripeSz(-1), m_numvar(1),
    m_nWritersPer(1)
{}

void H5::writer(CmdLineOptions& cmd)
{

  hid_t   file_id;       //file      identifier
  hid_t   group_id;      //group     identifier
  hid_t   dset_id;       //Dataset   identifier
  hid_t   filespace;     //Dataspace id in file
  hid_t   memspace;      //Dataspace id in memory.
  hid_t   plist_id;      //Property List id
  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1];
  hsize_t is, num;
  const char * fn = "unstruct.h5";

  // compute size info

  double lSz     = 1.0;

  m_numvar    = cmd.nvar;
  num         = cmd.localSz;
  lSz         = num;
  is          = P.myProc*num;
  count[0]    = 1;
  h5stride[0] = 1;
  starts[0]   = is;
  sz[0]       = num;
  gsz[0]      = cmd.globalSz;
  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);

  int iTotalSz = m_totalSz/(1024*1024);

  // Initialize data buffer
  double xk = num*P.myProc;

  double *data = new double[num];
  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn,MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info = MPI_INFO_NULL;
  MPI_Info_create(&info);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_MAX_STRIPES,         cmd.stripes,
                                T3PIO_MAX_STRIPE_SIZE,     cmd.stripeSz,
                                T3PIO_MAX_WRITERS,         cmd.maxWriters,
                                T3PIO_MAX_WRITER_PER_NODE, cmd.maxWritersPer,
                                T3PIO_FACTOR,              cmd.factor,
                                T3PIO_RESULTS,             &results);

      m_factor      = results.factor;
      m_nStripes    = results.numStripes;
      m_nIOUnits    = results.numIO;
      m_stripeSz    = results.stripeSize;
      m_nWritersPer = results.nWritersPer;
    }

  plist_id = H5Pcreate(H5P_FILE_ACCESS);
  H5Pset_fapl_mpio(plist_id, P.comm, info);

  // Create file collectively
  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);
  H5Pclose(plist_id);

  // Create Group
  group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

  std::string timeZ, timeL;
  dateZ(timeZ);
  add_attribute(group_id,"Zulu Time", timeZ.c_str());

  dateL(timeL);
  add_attribute(group_id,"Local Time", timeL.c_str());

  for (int ivar = 0; ivar < m_numvar; ++ivar)
    {

      // Create the dataspace for the dataset
      filespace = H5Screate_simple(1, &gsz[0], NULL);
      memspace  = H5Screate_simple(1, sz,      NULL);

      if (cmd.h5chunk)
        {
          plist_id = H5Pcreate(H5P_DATASET_CREATE);
          H5Pset_chunk(plist_id,1, sz);

          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, plist_id, H5P_DEFAULT);
          H5Pclose(plist_id);
          H5Sclose(filespace);

          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
        }
      else if (cmd.h5slab)
        {
          // Create the dataset w/ default properties and close filespace
          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
          H5Sclose(filespace);

          // Select hyperslab in the file.
          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
        }

      plist_id = H5Pcreate(H5P_DATASET_XFER);
      H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE);

      add_attribute(dset_id, "Variable Description", varT[ivar].descript);

      t1   = walltime();

      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
                               plist_id, data);
      t2   = walltime();
      m_t += (t2 - t1);

      H5Dclose(dset_id);
      H5Sclose(filespace);
      H5Sclose(memspace);
      H5Pclose(plist_id);
    }

  m_rate = m_totalSz /(m_t * 1024.0 * 1024.0);
  free(data);
  H5Gclose(group_id);
  H5Fclose(file_id);
}

void H5::add_attribute(hid_t id, const char* descript, const char* value)
{
  hid_t attr_id, aspace_id, atype_id;
  hsize_t attrlen, num[1];

  attrlen = strlen(value);
  num[0]  = 1;

  atype_id = H5Tcopy(H5T_C_S1);
  H5Tset_size(atype_id, attrlen);

  aspace_id = H5Screate_simple(1,num, NULL);

  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite(attr_id, atype_id, value);
  H5Aclose(attr_id);
  H5Sclose(aspace_id);
}
<commit_msg>spacing<commit_after>#include "h5test.h"
#include "h5writer.h"
#include "parallel.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"

struct Var_t
{
  const char * name;
  const char * descript;
};

Var_t varT[] =
  {
    {"T", "Temp in K"},
    {"p", "Pressure in N/m^2"},
    {"u", "X Velocity in m/s"},
    {"v", "Y Velocity in m/s"},
    {"w", "Z Velocity in m/s"},
    {"a", "A Velocity in m/s"},
    {"b", "B Velocity in m/s"},
    {"c", "C Velocity in m/s"},
    {"d", "D Velocity in m/s"},
    {"e", "E Velocity in m/s"},
  };

H5::H5()
  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
    m_nIOUnits(1), m_factor(1), m_stripeSz(-1), m_numvar(1),
    m_nWritersPer(1)
{}

void H5::writer(CmdLineOptions& cmd)
{

  hid_t   file_id;       //file      identifier
  hid_t   group_id;      //group     identifier
  hid_t   dset_id;       //Dataset   identifier
  hid_t   filespace;     //Dataspace id in file
  hid_t   memspace;      //Dataspace id in memory.
  hid_t   plist_id;      //Property List id
  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1];
  hsize_t is, num;
  const char * fn = "unstruct.h5";

  // compute size info

  double lSz     = 1.0;

  m_numvar    = cmd.nvar;
  num         = cmd.localSz;
  lSz         = num;
  is          = P.myProc*num;
  count[0]    = 1;
  h5stride[0] = 1;
  starts[0]   = is;
  sz[0]       = num;
  gsz[0]      = cmd.globalSz;
  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);

  int iTotalSz = m_totalSz/(1024*1024);

  // Initialize data buffer
  double xk = num*P.myProc;

  double *data = new double[num];
  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info = MPI_INFO_NULL;
  MPI_Info_create(&info);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_MAX_STRIPES,         cmd.stripes,
                                T3PIO_MAX_STRIPE_SIZE,     cmd.stripeSz,
                                T3PIO_MAX_WRITERS,         cmd.maxWriters,
                                T3PIO_MAX_WRITER_PER_NODE, cmd.maxWritersPer,
                                T3PIO_FACTOR,              cmd.factor,
                                T3PIO_RESULTS,             &results);

      m_factor      = results.factor;
      m_nStripes    = results.numStripes;
      m_nIOUnits    = results.numIO;
      m_stripeSz    = results.stripeSize;
      m_nWritersPer = results.nWritersPer;
    }

  plist_id = H5Pcreate(H5P_FILE_ACCESS);
  H5Pset_fapl_mpio(plist_id, P.comm, info);

  // Create file collectively
  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);
  H5Pclose(plist_id);

  // Create Group
  group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

  std::string timeZ, timeL;
  dateZ(timeZ);
  add_attribute(group_id,"Zulu Time", timeZ.c_str());

  dateL(timeL);
  add_attribute(group_id,"Local Time", timeL.c_str());

  for (int ivar = 0; ivar < m_numvar; ++ivar)
    {

      // Create the dataspace for the dataset
      filespace = H5Screate_simple(1, &gsz[0], NULL);
      memspace  = H5Screate_simple(1, sz,      NULL);

      if (cmd.h5chunk)
        {
          plist_id = H5Pcreate(H5P_DATASET_CREATE);
          H5Pset_chunk(plist_id,1, sz);

          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, plist_id, H5P_DEFAULT);
          H5Pclose(plist_id);
          H5Sclose(filespace);

          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
        }
      else if (cmd.h5slab)
        {
          // Create the dataset w/ default properties and close filespace
          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
          H5Sclose(filespace);

          // Select hyperslab in the file.
          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
        }

      plist_id = H5Pcreate(H5P_DATASET_XFER);
      H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE);

      add_attribute(dset_id, "Variable Description", varT[ivar].descript);

      t1   = walltime();

      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
                               plist_id, data);
      t2   = walltime();
      m_t += (t2 - t1);

      H5Dclose(dset_id);
      H5Sclose(filespace);
      H5Sclose(memspace);
      H5Pclose(plist_id);
    }

  m_rate = m_totalSz /(m_t * 1024.0 * 1024.0);
  free(data);
  H5Gclose(group_id);
  H5Fclose(file_id);
}

void H5::add_attribute(hid_t id, const char* descript, const char* value)
{
  hid_t attr_id, aspace_id, atype_id;
  hsize_t attrlen, num[1];

  attrlen = strlen(value);
  num[0]  = 1;

  atype_id = H5Tcopy(H5T_C_S1);
  H5Tset_size(atype_id, attrlen);

  aspace_id = H5Screate_simple(1,num, NULL);

  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite(attr_id, atype_id, value);
  H5Aclose(attr_id);
  H5Sclose(aspace_id);
}
<|endoftext|>


<commit_before>// Copyright 2010-2011 Google
// 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 "base/callback.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/concise_iterator.h"
#include "base/stl_util-inl.h"
#include "constraint_solver/constraint_solveri.h"

namespace operations_research {

// ----- Base Class -----

void NoGoodManager::EnterSearch() {
  Init();
}

void NoGoodManager::BeginNextDecision(DecisionBuilder* const db) {
  Apply();
}

bool NoGoodManager::AcceptSolution() {
  Apply();
  return true;
}

NoGood* NoGoodManager::MakeNoGood() {
  return new NoGood();
}

// ----- Base class for NoGood terms -----

class NoGoodTerm {
 public:
  enum TermStatus {
    ALWAYS_TRUE,
    ALWAYS_FALSE,
    UNDECIDED
  };
  NoGoodTerm() {}
  virtual ~NoGoodTerm() {}

  virtual TermStatus Evaluate() const = 0;
  virtual void ApplyReverse() = 0;
  virtual string DebugString() const = 0;
 private:
  DISALLOW_COPY_AND_ASSIGN(NoGoodTerm);
};

// ----- IntegerVariableNoGoodTerm -----

// IntVar == int64 specialization.
class IntegerVariableNoGoodTerm : public NoGoodTerm {
 public:
  IntegerVariableNoGoodTerm(IntVar* const var, int64 value, bool assign)
      : integer_variable_(var), value_(value), assign_(assign) {
    CHECK_NOTNULL(integer_variable_);
  }

  virtual TermStatus Evaluate() const {
    if (!integer_variable_->Contains(value_)) {
      return assign_ ? ALWAYS_FALSE : ALWAYS_TRUE;
    } else if (integer_variable_->Bound()) {
      return assign_ ? ALWAYS_TRUE : ALWAYS_FALSE;
    } else {
      return UNDECIDED;
    }
  }

  virtual void ApplyReverse() {
    if (assign_) {
      integer_variable_->RemoveValue(value_);
    } else {
      integer_variable_->SetValue(value_);
    }
  }

  virtual string DebugString() const {
    return StringPrintf("(%s %s %lld)",
                        integer_variable_->name().c_str(),
                        assign_ ? "==" : "!=",
                        value_);
  }

  IntVar* integer_variable() const { return integer_variable_; }
  int64 value() const { return value_; }
  bool assign() const { return assign_; }

 private:
  IntVar* const integer_variable_;
  const int64 value_;
  const bool assign_;
  DISALLOW_COPY_AND_ASSIGN(IntegerVariableNoGoodTerm);
};

// ----- NoGood -----

NoGood::~NoGood() {
  STLDeleteElements(&terms_);
}

void NoGood::AddIntegerVariableEqualValueTerm(IntVar* const var, int64 value) {
  terms_.push_back(new IntegerVariableNoGoodTerm(var, value, true));
}

void NoGood::AddIntegerVariableNotEqualValueTerm(IntVar* const var,
                                                 int64 value) {
  terms_.push_back(new IntegerVariableNoGoodTerm(var, value, false));
}

void NoGood::Apply(Solver* const solver) {
  NoGoodTerm* first_undecided = NULL;
  for (int i = 0; i < terms_.size(); ++i) {
    switch (terms_[i]->Evaluate()) {
      case NoGoodTerm::ALWAYS_TRUE: {
        break;
      }
      case NoGoodTerm::ALWAYS_FALSE: {
        return;
      }
      case NoGoodTerm::UNDECIDED: {
        if (first_undecided == NULL) {
          first_undecided = terms_[i];
        } else {
          // more than one undecided, we cannot deduce anything.
          return;
        }
        break;
      }
    }
  }
  if (first_undecided == NULL && terms_.size() > 0) {
    solver->Fail();
  }
  if (first_undecided != NULL) {
    first_undecided->ApplyReverse();
  }
}

string NoGood::DebugString() const {
  string result = "(";
  for (int i = 0; i < terms_.size(); ++i) {
    if (i != 0) {
      result.append(" && ");
    }
    result.append(terms_[i]->DebugString());
  }
  result.append(")");
  return result;
}

// ----- NoGoodManager -----

// This implementation is very naive. It will be kept in the future as
// a reference point.

class NaiveNoGoodManager : public NoGoodManager {
 public:
  explicit NaiveNoGoodManager(Solver* const solver) : NoGoodManager(solver) {}
  virtual ~NaiveNoGoodManager() {
    Clear();
  }

  virtual void Clear() {
    STLDeleteElements(&nogoods_);
  }

  virtual void Init() {}

  virtual void AddNoGood(NoGood* const nogood) {
    nogoods_.push_back(nogood);
  }

  virtual int NoGoodCount() const {
    return nogoods_.size();
  }

  virtual void Apply() {
    Solver* const s = solver();
    for (int i = 0; i < nogoods_.size(); ++i) {
      nogoods_[i]->Apply(s);
    }
  }

  string DebugString() const {
    return StringPrintf("NaiveNoGoodManager(%d)", NoGoodCount());
  }

 private:
  std::vector<NoGood*> nogoods_;
};

// ----- API -----

NoGoodManager* Solver::MakeNoGoodManager() {
  return RevAlloc(new NaiveNoGoodManager(this));
}

}  // namespace operations_research
<commit_msg>rename ApplyReverse to Refute<commit_after>// Copyright 2010-2011 Google
// 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 "base/callback.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/concise_iterator.h"
#include "base/stl_util-inl.h"
#include "constraint_solver/constraint_solveri.h"

namespace operations_research {

// ----- Base Class -----

void NoGoodManager::EnterSearch() {
  Init();
}

void NoGoodManager::BeginNextDecision(DecisionBuilder* const db) {
  Apply();
}

bool NoGoodManager::AcceptSolution() {
  Apply();
  return true;
}

NoGood* NoGoodManager::MakeNoGood() {
  return new NoGood();
}

// ----- Base class for NoGood terms -----

class NoGoodTerm {
 public:
  enum TermStatus {
    ALWAYS_TRUE,
    ALWAYS_FALSE,
    UNDECIDED
  };
  NoGoodTerm() {}
  virtual ~NoGoodTerm() {}

  virtual TermStatus Evaluate() const = 0;
  virtual void Refute() = 0;
  virtual string DebugString() const = 0;
 private:
  DISALLOW_COPY_AND_ASSIGN(NoGoodTerm);
};

// ----- IntegerVariableNoGoodTerm -----

// IntVar == int64 specialization.
class IntegerVariableNoGoodTerm : public NoGoodTerm {
 public:
  IntegerVariableNoGoodTerm(IntVar* const var, int64 value, bool assign)
      : integer_variable_(var), value_(value), assign_(assign) {
    CHECK_NOTNULL(integer_variable_);
  }

  virtual TermStatus Evaluate() const {
    if (!integer_variable_->Contains(value_)) {
      return assign_ ? ALWAYS_FALSE : ALWAYS_TRUE;
    } else if (integer_variable_->Bound()) {
      return assign_ ? ALWAYS_TRUE : ALWAYS_FALSE;
    } else {
      return UNDECIDED;
    }
  }

  virtual void Refute() {
    if (assign_) {
      integer_variable_->RemoveValue(value_);
    } else {
      integer_variable_->SetValue(value_);
    }
  }

  virtual string DebugString() const {
    return StringPrintf("(%s %s %lld)",
                        integer_variable_->name().c_str(),
                        assign_ ? "==" : "!=",
                        value_);
  }

  IntVar* integer_variable() const { return integer_variable_; }
  int64 value() const { return value_; }
  bool assign() const { return assign_; }

 private:
  IntVar* const integer_variable_;
  const int64 value_;
  const bool assign_;
  DISALLOW_COPY_AND_ASSIGN(IntegerVariableNoGoodTerm);
};

// ----- NoGood -----

NoGood::~NoGood() {
  STLDeleteElements(&terms_);
}

void NoGood::AddIntegerVariableEqualValueTerm(IntVar* const var, int64 value) {
  terms_.push_back(new IntegerVariableNoGoodTerm(var, value, true));
}

void NoGood::AddIntegerVariableNotEqualValueTerm(IntVar* const var,
                                                 int64 value) {
  terms_.push_back(new IntegerVariableNoGoodTerm(var, value, false));
}

void NoGood::Apply(Solver* const solver) {
  NoGoodTerm* first_undecided = NULL;
  for (int i = 0; i < terms_.size(); ++i) {
    switch (terms_[i]->Evaluate()) {
      case NoGoodTerm::ALWAYS_TRUE: {
        break;
      }
      case NoGoodTerm::ALWAYS_FALSE: {
        return;
      }
      case NoGoodTerm::UNDECIDED: {
        if (first_undecided == NULL) {
          first_undecided = terms_[i];
        } else {
          // more than one undecided, we cannot deduce anything.
          return;
        }
        break;
      }
    }
  }
  if (first_undecided == NULL && terms_.size() > 0) {
    solver->Fail();
  }
  if (first_undecided != NULL) {
    first_undecided->Refute();
  }
}

string NoGood::DebugString() const {
  string result = "(";
  for (int i = 0; i < terms_.size(); ++i) {
    if (i != 0) {
      result.append(" && ");
    }
    result.append(terms_[i]->DebugString());
  }
  result.append(")");
  return result;
}

// ----- NoGoodManager -----

// This implementation is very naive. It will be kept in the future as
// a reference point.

class NaiveNoGoodManager : public NoGoodManager {
 public:
  explicit NaiveNoGoodManager(Solver* const solver) : NoGoodManager(solver) {}
  virtual ~NaiveNoGoodManager() {
    Clear();
  }

  virtual void Clear() {
    STLDeleteElements(&nogoods_);
  }

  virtual void Init() {}

  virtual void AddNoGood(NoGood* const nogood) {
    nogoods_.push_back(nogood);
  }

  virtual int NoGoodCount() const {
    return nogoods_.size();
  }

  virtual void Apply() {
    Solver* const s = solver();
    for (int i = 0; i < nogoods_.size(); ++i) {
      nogoods_[i]->Apply(s);
    }
  }

  string DebugString() const {
    return StringPrintf("NaiveNoGoodManager(%d)", NoGoodCount());
  }

 private:
  std::vector<NoGood*> nogoods_;
};

// ----- API -----

NoGoodManager* Solver::MakeNoGoodManager() {
  return RevAlloc(new NaiveNoGoodManager(this));
}

}  // namespace operations_research
<|endoftext|>