<commit_before>#ifndef STAN_MATH_PRIM_PROB_EXP_MOD_NORMAL_LPDF_HPP
#define STAN_MATH_PRIM_PROB_EXP_MOD_NORMAL_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/erfc.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <cmath>

namespace stan {
namespace math {

template <bool propto, typename T_y, typename T_loc, typename T_scale,
          typename T_inv_scale>
return_type_t<T_y, T_loc, T_scale, T_inv_scale> exp_mod_normal_lpdf(
    const T_y& y, const T_loc& mu, const T_scale& sigma,
    const T_inv_scale& lambda) {
  static const char* function = "exp_mod_normal_lpdf";
  using T_partials_return = partials_return_t<T_y, T_loc, T_scale, T_inv_scale>;

  if (size_zero(y, mu, sigma, lambda)) {
    return 0.0;
  }

  T_partials_return logp(0.0);

  check_not_nan(function, "Random variable", y);
  check_finite(function, "Location parameter", mu);
  check_positive_finite(function, "Inv_scale parameter", lambda);
  check_positive_finite(function, "Scale parameter", sigma);
  check_consistent_sizes(function, "Random variable", y, "Location parameter",
                         mu, "Scale parameter", sigma, "Inv_scale paramter",
                         lambda);

  if (!include_summand<propto, T_y, T_loc, T_scale, T_inv_scale>::value) {
    return 0.0;
  }

  using std::exp;
  using std::log;
  using std::sqrt;

  operands_and_partials<T_y, T_loc, T_scale, T_inv_scale> ops_partials(
      y, mu, sigma, lambda);

  scalar_seq_view<T_y> y_vec(y);
  scalar_seq_view<T_loc> mu_vec(mu);
  scalar_seq_view<T_scale> sigma_vec(sigma);
  scalar_seq_view<T_inv_scale> lambda_vec(lambda);
  size_t N = max_size(y, mu, sigma, lambda);

  for (size_t n = 0; n < N; n++) {
    const T_partials_return y_dbl = value_of(y_vec[n]);
    const T_partials_return mu_dbl = value_of(mu_vec[n]);
    const T_partials_return sigma_dbl = value_of(sigma_vec[n]);
    const T_partials_return lambda_dbl = value_of(lambda_vec[n]);

    const T_partials_return inv_sqrt2_inv_sigma = INV_SQRT_TWO / sigma_dbl;
    const T_partials_return sigma_sq = square(sigma_dbl);
    const T_partials_return lambda_sigma_sq = lambda_dbl * sigma_sq;
    const T_partials_return term1 = lambda_sigma_sq - y_dbl;
    const T_partials_return term2 = (mu_dbl + term1) * inv_sqrt2_inv_sigma;
    const T_partials_return erfc_term2 = erfc(term2);
    const T_partials_return deriv_logerfc
        = NEG_TWO_OVER_SQRT_PI * exp(-square(term2)) / erfc_term2;

    if (include_summand<propto>::value) {
      logp -= LOG_TWO;
    }
    if (include_summand<propto, T_inv_scale>::value) {
      logp += log(lambda_dbl);
    }
    logp += lambda_dbl * (mu_dbl + 0.5 * (term1 - y_dbl)) + log(erfc_term2);

    if (!is_constant_all<T_y>::value) {
      ops_partials.edge1_.partials_[n]
          -= lambda_dbl + deriv_logerfc * inv_sqrt2_inv_sigma;
    }
    if (!is_constant_all<T_loc>::value) {
      ops_partials.edge2_.partials_[n]
          += lambda_dbl + deriv_logerfc * inv_sqrt2_inv_sigma;
    }
    if (!is_constant_all<T_scale>::value) {
      ops_partials.edge3_.partials_[n]
          += sigma_dbl * lambda_dbl * lambda_dbl
             + deriv_logerfc
                   * ((y_dbl - mu_dbl) / sigma_sq
                      + lambda_dbl) * INV_SQRT_TWO;
    }
    if (!is_constant_all<T_inv_scale>::value) {
      ops_partials.edge4_.partials_[n]
          += 1 / lambda_dbl + lambda_sigma_sq + mu_dbl - y_dbl
             + deriv_logerfc * sigma_dbl * INV_SQRT_TWO;
    }
  }
  return ops_partials.build(logp);
}

template <typename T_y, typename T_loc, typename T_scale, typename T_inv_scale>
inline return_type_t<T_y, T_loc, T_scale, T_inv_scale> exp_mod_normal_lpdf(
    const T_y& y, const T_loc& mu, const T_scale& sigma,
    const T_inv_scale& lambda) {
  return exp_mod_normal_lpdf<false>(y, mu, sigma, lambda);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>Slightly clearer reformulation<commit_after>#ifndef STAN_MATH_PRIM_PROB_EXP_MOD_NORMAL_LPDF_HPP
#define STAN_MATH_PRIM_PROB_EXP_MOD_NORMAL_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/erfc.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <cmath>

namespace stan {
namespace math {

template <bool propto, typename T_y, typename T_loc, typename T_scale,
          typename T_inv_scale>
return_type_t<T_y, T_loc, T_scale, T_inv_scale> exp_mod_normal_lpdf(
    const T_y& y, const T_loc& mu, const T_scale& sigma,
    const T_inv_scale& lambda) {
  static const char* function = "exp_mod_normal_lpdf";
  using T_partials_return = partials_return_t<T_y, T_loc, T_scale, T_inv_scale>;

  if (size_zero(y, mu, sigma, lambda)) {
    return 0.0;
  }

  T_partials_return logp(0.0);

  check_not_nan(function, "Random variable", y);
  check_finite(function, "Location parameter", mu);
  check_positive_finite(function, "Inv_scale parameter", lambda);
  check_positive_finite(function, "Scale parameter", sigma);
  check_consistent_sizes(function, "Random variable", y, "Location parameter",
                         mu, "Scale parameter", sigma, "Inv_scale paramter",
                         lambda);

  if (!include_summand<propto, T_y, T_loc, T_scale, T_inv_scale>::value) {
    return 0.0;
  }

  using std::exp;
  using std::log;
  using std::sqrt;

  operands_and_partials<T_y, T_loc, T_scale, T_inv_scale> ops_partials(
      y, mu, sigma, lambda);

  scalar_seq_view<T_y> y_vec(y);
  scalar_seq_view<T_loc> mu_vec(mu);
  scalar_seq_view<T_scale> sigma_vec(sigma);
  scalar_seq_view<T_inv_scale> lambda_vec(lambda);
  size_t N = max_size(y, mu, sigma, lambda);

  for (size_t n = 0; n < N; n++) {
    const T_partials_return y_dbl = value_of(y_vec[n]);
    const T_partials_return mu_dbl = value_of(mu_vec[n]);
    const T_partials_return sigma_dbl = value_of(sigma_vec[n]);
    const T_partials_return lambda_dbl = value_of(lambda_vec[n]);

    const T_partials_return inv_sigma = 1 / sigma_dbl;
    const T_partials_return sigma_sq = square(sigma_dbl);
    const T_partials_return lambda_sigma_sq = lambda_dbl * sigma_sq;
    const T_partials_return mu_minus_y = mu_dbl - y_dbl;
    const T_partials_return inner_term
        = (mu_minus_y + lambda_sigma_sq) * INV_SQRT_TWO * inv_sigma;
    const T_partials_return erfc_calc = erfc(inner_term);
    const T_partials_return deriv_logerfc
        = -SQRT_TWO_OVER_SQRT_PI * exp(-square(inner_term)) / erfc_calc;

    if (include_summand<propto>::value) {
      logp -= LOG_TWO;
    }
    if (include_summand<propto, T_inv_scale>::value) {
      logp += log(lambda_dbl);
    }
    logp += lambda_dbl * (mu_minus_y + 0.5 * lambda_sigma_sq) + log(erfc_calc);

    if (!is_constant_all<T_y>::value) {
      ops_partials.edge1_.partials_[n]
          -= lambda_dbl + deriv_logerfc * inv_sigma;
    }
    if (!is_constant_all<T_loc>::value) {
      ops_partials.edge2_.partials_[n]
          += lambda_dbl + deriv_logerfc * inv_sigma;
    }
    if (!is_constant_all<T_scale>::value) {
      ops_partials.edge3_.partials_[n]
          += sigma_dbl * square(lambda_dbl)
             + deriv_logerfc * (-mu_minus_y / sigma_sq + lambda_dbl);
    }
    if (!is_constant_all<T_inv_scale>::value) {
      ops_partials.edge4_.partials_[n] += 1 / lambda_dbl + lambda_sigma_sq
                                          + mu_minus_y
                                          + deriv_logerfc * sigma_dbl;
    }
  }
  return ops_partials.build(logp);
}

template <typename T_y, typename T_loc, typename T_scale, typename T_inv_scale>
inline return_type_t<T_y, T_loc, T_scale, T_inv_scale> exp_mod_normal_lpdf(
    const T_y& y, const T_loc& mu, const T_scale& sigma,
    const T_inv_scale& lambda) {
  return exp_mod_normal_lpdf<false>(y, mu, sigma, lambda);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_MAT_FUNCTOR_INTEGRATOR_DAE_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_INTEGRATOR_DAE_HPP

#include <stan/math/rev/mat/functor/idas_forward_system.hpp>
#include <stan/math/rev/mat/functor/idas_integrator.hpp>
#include <ostream>
#include <vector>

namespace stan {
namespace math {
/**
 * Return the solutions for a semi-explicit DAE system with residual
 * specified by functor F,
 * given the specified consistent initial state yy0 and yp0.
 *
 * @tparam DAE type of DAE system
 * @tparam Tpar scalar type of parameter theta
 * @param[in] f functor for the base ordinary differential equation
 * @param[in] yy0 initial state
 * @param[in] yp0 initial derivative state
 * @param[in] t0 initial time
 * @param[in] ts times of the desired solutions, in strictly
 * increasing order, all greater than the initial time
 * @param[in] theta parameters
 * @param[in] x_r real data
 * @param[in] x_i int data
 * @param[in] rtol relative tolerance passed to IDAS, requred <10^-3
 * @param[in] atol absolute tolerance passed to IDAS, problem-dependent
 * @param[in] max_num_steps maximal number of admissable steps
 * between time-points
 * @param[in] msgs message
 * @return a vector of states, each state being a vector of the
 * same size as the state variable, corresponding to a time in ts.
 */
template <typename F, typename Tpar>
std::vector<std::vector<Tpar> > integrate_dae(
    const F& f, const std::vector<double>& yy0, const std::vector<double>& yp0,
    double t0, const std::vector<double>& ts, const std::vector<Tpar>& theta,
    const std::vector<double>& x_r, const std::vector<int>& x_i,
    const double rtol, const double atol,
    const int64_t max_num_steps = idas_integrator::IDAS_MAX_STEPS,
    std::ostream* msgs = nullptr) {

  /* it doesn't matter here what values @c eq_id has, as we
     don't allow yy0 or yp0 to be parameters */
  const std::vector<int> dummy_eq_id(yy0.size(), 0);

  stan::math::idas_integrator solver(rtol, atol, max_num_steps);
  stan::math::idas_forward_system<F, double, double, Tpar> dae{
      f, dummy_eq_id, yy0, yp0, theta, x_r, x_i, msgs};

  dae.check_ic_consistency(t0, atol);

  return solver.integrate(dae, t0, ts);
}
}  // namespace math
}  // namespace stan

#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.2-svn328729-1~exp1~20180509124008.99 (branches/release_50)<commit_after>#ifndef STAN_MATH_REV_MAT_FUNCTOR_INTEGRATOR_DAE_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_INTEGRATOR_DAE_HPP

#include <stan/math/rev/mat/functor/idas_forward_system.hpp>
#include <stan/math/rev/mat/functor/idas_integrator.hpp>
#include <ostream>
#include <vector>

namespace stan {
namespace math {
/**
 * Return the solutions for a semi-explicit DAE system with residual
 * specified by functor F,
 * given the specified consistent initial state yy0 and yp0.
 *
 * @tparam DAE type of DAE system
 * @tparam Tpar scalar type of parameter theta
 * @param[in] f functor for the base ordinary differential equation
 * @param[in] yy0 initial state
 * @param[in] yp0 initial derivative state
 * @param[in] t0 initial time
 * @param[in] ts times of the desired solutions, in strictly
 * increasing order, all greater than the initial time
 * @param[in] theta parameters
 * @param[in] x_r real data
 * @param[in] x_i int data
 * @param[in] rtol relative tolerance passed to IDAS, requred <10^-3
 * @param[in] atol absolute tolerance passed to IDAS, problem-dependent
 * @param[in] max_num_steps maximal number of admissable steps
 * between time-points
 * @param[in] msgs message
 * @return a vector of states, each state being a vector of the
 * same size as the state variable, corresponding to a time in ts.
 */
template <typename F, typename Tpar>
std::vector<std::vector<Tpar> > integrate_dae(
    const F& f, const std::vector<double>& yy0, const std::vector<double>& yp0,
    double t0, const std::vector<double>& ts, const std::vector<Tpar>& theta,
    const std::vector<double>& x_r, const std::vector<int>& x_i,
    const double rtol, const double atol,
    const int64_t max_num_steps = idas_integrator::IDAS_MAX_STEPS,
    std::ostream* msgs = nullptr) {
  /* it doesn't matter here what values @c eq_id has, as we
     don't allow yy0 or yp0 to be parameters */
  const std::vector<int> dummy_eq_id(yy0.size(), 0);

  stan::math::idas_integrator solver(rtol, atol, max_num_steps);
  stan::math::idas_forward_system<F, double, double, Tpar> dae{
      f, dummy_eq_id, yy0, yp0, theta, x_r, x_i, msgs};

  dae.check_ic_consistency(t0, atol);

  return solver.integrate(dae, t0, ts);
}
}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: namingservice.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:03: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
 *
 ************************************************************************/

#include <hash_map>

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h>
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx>
#endif

#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _CPPUHELPER_COMPONENT_HXX_
#include <cppuhelper/component.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif

#include <com/sun/star/uno/XNamingService.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>

using namespace cppu;
using namespace rtl;
using namespace osl;
using namespace std;

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;

#define SERVICENAME "com.sun.star.uno.NamingService"
#define IMPLNAME    "com.sun.star.comp.stoc.NamingService"

namespace stoc_namingservice
{
static rtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;

static Sequence< OUString > ns_getSupportedServiceNames()
{
    static Sequence < OUString > *pNames = 0;
    if( ! pNames )
    {
        MutexGuard guard( Mutex::getGlobalMutex() );
        if( !pNames )
        {
            static Sequence< OUString > seqNames(1);
            seqNames.getArray()[0] = OUString(RTL_CONSTASCII_USTRINGPARAM(SERVICENAME));
            pNames = &seqNames;
        }
    }
    return *pNames;
}

static OUString ns_getImplementationName()
{
    static OUString *pImplName = 0;
    if( ! pImplName )
    {
        MutexGuard guard( Mutex::getGlobalMutex() );
        if( ! pImplName )
        {
            static OUString implName( RTL_CONSTASCII_USTRINGPARAM( IMPLNAME ) );
            pImplName = &implName;
        }
    }
    return *pImplName;
}

struct equalOWString_Impl
{
  sal_Bool operator()(const OUString & s1, const OUString & s2) const
        { return s1 == s2; }
};

struct hashOWString_Impl
{
    size_t operator()(const OUString & rName) const
        { return rName.hashCode(); }
};

typedef hash_map
<
    OUString,
    Reference<XInterface >,
    hashOWString_Impl,
    equalOWString_Impl
> HashMap_OWString_Interface;

//==================================================================================================
class NamingService_Impl
    : public WeakImplHelper2 < XServiceInfo, XNamingService >
{
    Mutex                               aMutex;
    HashMap_OWString_Interface          aMap;
public:
    NamingService_Impl();
    ~NamingService_Impl();

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName()
    throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName )
    throw(::com::sun::star::uno::RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
    throw(::com::sun::star::uno::RuntimeException);
    static Sequence< OUString > SAL_CALL getSupportedServiceNames_Static()
    {
        OUString aStr( OUString::createFromAscii( SERVICENAME ) );
        return Sequence< OUString >( &aStr, 1 );
    }

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getRegisteredObject( const ::rtl::OUString& Name ) throw(Exception, RuntimeException);
    virtual void SAL_CALL registerObject( const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& Object ) throw(Exception, RuntimeException);
    virtual void SAL_CALL revokeObject( const ::rtl::OUString& Name ) throw(Exception, RuntimeException);
};

//==================================================================================================
static Reference<XInterface> SAL_CALL NamingService_Impl_create( const Reference<XComponentContext> & )
{
    return *new NamingService_Impl();
}

//==================================================================================================
NamingService_Impl::NamingService_Impl()
{
    g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}

//==================================================================================================
NamingService_Impl::~NamingService_Impl()
{
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XServiceInfo
OUString NamingService_Impl::getImplementationName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return ns_getImplementationName();
}

// XServiceInfo
sal_Bool NamingService_Impl::supportsService( const OUString & rServiceName )
    throw(::com::sun::star::uno::RuntimeException)
{
    const Sequence< OUString > & rSNL = getSupportedServiceNames();
    const OUString * pArray = rSNL.getConstArray();
    for ( sal_Int32 nPos = rSNL.getLength(); nPos--; )
    {
        if (pArray[nPos] == rServiceName)
            return sal_True;
    }
    return sal_False;
}

// XServiceInfo
Sequence< OUString > NamingService_Impl::getSupportedServiceNames()
    throw(::com::sun::star::uno::RuntimeException)
{
    return ns_getSupportedServiceNames();
}

// XServiceInfo
Reference< XInterface > NamingService_Impl::getRegisteredObject( const OUString& Name ) throw(Exception, RuntimeException)
{
    Guard< Mutex > aGuard( aMutex );
    Reference< XInterface > xRet;
    HashMap_OWString_Interface::iterator aIt = aMap.find( Name );
    if( aIt != aMap.end() )
        xRet = (*aIt).second;
    return xRet;
}

// XServiceInfo
void NamingService_Impl::registerObject( const OUString& Name, const Reference< XInterface >& Object ) throw(Exception, RuntimeException)
{
    Guard< Mutex > aGuard( aMutex );
    aMap[ Name ] = Object;
}

// XServiceInfo
void NamingService_Impl::revokeObject( const OUString& Name ) throw(Exception, RuntimeException)
{
    Guard< Mutex > aGuard( aMutex );
    aMap.erase( Name );
}

}

using namespace stoc_namingservice;
static struct ImplementationEntry g_entries[] =
{
    {
        NamingService_Impl_create, ns_getImplementationName,
        ns_getSupportedServiceNames, createSingleComponentFactory,
        &g_moduleCount.modCnt , 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

extern "C"
{
sal_Bool SAL_CALL component_canUnload( TimeValue *pTime )
{
    return g_moduleCount.canUnload( &g_moduleCount , pTime );
}

//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.10); FILE MERGED 2006/09/01 17:41:13 kaib 1.7.10.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: namingservice.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 17:31:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include <hash_map>

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h>
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx>
#endif

#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _CPPUHELPER_COMPONENT_HXX_
#include <cppuhelper/component.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif

#include <com/sun/star/uno/XNamingService.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>

using namespace cppu;
using namespace rtl;
using namespace osl;
using namespace std;

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;

#define SERVICENAME "com.sun.star.uno.NamingService"
#define IMPLNAME    "com.sun.star.comp.stoc.NamingService"

namespace stoc_namingservice
{
static rtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;

static Sequence< OUString > ns_getSupportedServiceNames()
{
    static Sequence < OUString > *pNames = 0;
    if( ! pNames )
    {
        MutexGuard guard( Mutex::getGlobalMutex() );
        if( !pNames )
        {
            static Sequence< OUString > seqNames(1);
            seqNames.getArray()[0] = OUString(RTL_CONSTASCII_USTRINGPARAM(SERVICENAME));
            pNames = &seqNames;
        }
    }
    return *pNames;
}

static OUString ns_getImplementationName()
{
    static OUString *pImplName = 0;
    if( ! pImplName )
    {
        MutexGuard guard( Mutex::getGlobalMutex() );
        if( ! pImplName )
        {
            static OUString implName( RTL_CONSTASCII_USTRINGPARAM( IMPLNAME ) );
            pImplName = &implName;
        }
    }
    return *pImplName;
}

struct equalOWString_Impl
{
  sal_Bool operator()(const OUString & s1, const OUString & s2) const
        { return s1 == s2; }
};

struct hashOWString_Impl
{
    size_t operator()(const OUString & rName) const
        { return rName.hashCode(); }
};

typedef hash_map
<
    OUString,
    Reference<XInterface >,
    hashOWString_Impl,
    equalOWString_Impl
> HashMap_OWString_Interface;

//==================================================================================================
class NamingService_Impl
    : public WeakImplHelper2 < XServiceInfo, XNamingService >
{
    Mutex                               aMutex;
    HashMap_OWString_Interface          aMap;
public:
    NamingService_Impl();
    ~NamingService_Impl();

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName()
    throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName )
    throw(::com::sun::star::uno::RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
    throw(::com::sun::star::uno::RuntimeException);
    static Sequence< OUString > SAL_CALL getSupportedServiceNames_Static()
    {
        OUString aStr( OUString::createFromAscii( SERVICENAME ) );
        return Sequence< OUString >( &aStr, 1 );
    }

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getRegisteredObject( const ::rtl::OUString& Name ) throw(Exception, RuntimeException);
    virtual void SAL_CALL registerObject( const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& Object ) throw(Exception, RuntimeException);
    virtual void SAL_CALL revokeObject( const ::rtl::OUString& Name ) throw(Exception, RuntimeException);
};

//==================================================================================================
static Reference<XInterface> SAL_CALL NamingService_Impl_create( const Reference<XComponentContext> & )
{
    return *new NamingService_Impl();
}

//==================================================================================================
NamingService_Impl::NamingService_Impl()
{
    g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}

//==================================================================================================
NamingService_Impl::~NamingService_Impl()
{
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XServiceInfo
OUString NamingService_Impl::getImplementationName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return ns_getImplementationName();
}

// XServiceInfo
sal_Bool NamingService_Impl::supportsService( const OUString & rServiceName )
    throw(::com::sun::star::uno::RuntimeException)
{
    const Sequence< OUString > & rSNL = getSupportedServiceNames();
    const OUString * pArray = rSNL.getConstArray();
    for ( sal_Int32 nPos = rSNL.getLength(); nPos--; )
    {
        if (pArray[nPos] == rServiceName)
            return sal_True;
    }
    return sal_False;
}

// XServiceInfo
Sequence< OUString > NamingService_Impl::getSupportedServiceNames()
    throw(::com::sun::star::uno::RuntimeException)
{
    return ns_getSupportedServiceNames();
}

// XServiceInfo
Reference< XInterface > NamingService_Impl::getRegisteredObject( const OUString& Name ) throw(Exception, RuntimeException)
{
    Guard< Mutex > aGuard( aMutex );
    Reference< XInterface > xRet;
    HashMap_OWString_Interface::iterator aIt = aMap.find( Name );
    if( aIt != aMap.end() )
        xRet = (*aIt).second;
    return xRet;
}

// XServiceInfo
void NamingService_Impl::registerObject( const OUString& Name, const Reference< XInterface >& Object ) throw(Exception, RuntimeException)
{
    Guard< Mutex > aGuard( aMutex );
    aMap[ Name ] = Object;
}

// XServiceInfo
void NamingService_Impl::revokeObject( const OUString& Name ) throw(Exception, RuntimeException)
{
    Guard< Mutex > aGuard( aMutex );
    aMap.erase( Name );
}

}

using namespace stoc_namingservice;
static struct ImplementationEntry g_entries[] =
{
    {
        NamingService_Impl_create, ns_getImplementationName,
        ns_getSupportedServiceNames, createSingleComponentFactory,
        &g_moduleCount.modCnt , 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

extern "C"
{
sal_Bool SAL_CALL component_canUnload( TimeValue *pTime )
{
    return g_moduleCount.canUnload( &g_moduleCount , pTime );
}

//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "keeper.hpp"

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

#include "../common/membership.hpp"
#include "../common/exception.hpp"
#include "../common/util.hpp"
#include "server_util.hpp"

using namespace jubatus;
using namespace jubatus::framework;

namespace {

std::string make_logfile_name(const keeper_argv& a) {
  std::ostringstream logfile;
  if (a.logdir != ""){
    logfile << a.logdir << '/';
    logfile << a.program_name << '.';
    logfile << a.eth << '_' << a.port;
    logfile << ".zklog.";
    logfile << getpid();
  }
  return logfile.str();
}

}

keeper::keeper(const keeper_argv& a)
  : pfi::network::mprpc::rpc_server(a.timeout),
    a_(a),
    zk_(common::create_lock_service("cached_zk", a.z, a.timeout, make_logfile_name(a)))
    //    zk_(common::create_lock_service("zk", a.z, a.timeout))
{
  ls = zk_;
  jubatus::common::prepare_jubatus(*zk_, a_.type, "");
  register_keeper(*zk_, a_.type, a_.eth, a_.port);
}

keeper::~keeper(){
}

int keeper::run()
{
  try {
    jubatus::util::set_exit_on_term();
    jubatus::util::ignore_sigpipe();
    if (this->serv(a_.port, a_.threadnum)) {
      return 0;
    } else {
      LOG(FATAL) << "failed starting server: any process using port " << a_.port << "?";
      return -1;
    }
  } catch (const jubatus::exception::jubatus_exception& e) {
    LOG(FATAL) << e.diagnostic_information(true);
    return -1;
  }
}

void keeper::get_members_(const std::string& name, std::vector<std::pair<std::string, int> >& ret){
  using namespace std;
  ret.clear();
  vector<string> list;
  string path;
  common::build_actor_path(path, a_.type, name);
  path += "/nodes";

  {
    pfi::concurrent::scoped_lock lk(mutex_);
    zk_->list(path, list);
  }
  vector<string>::const_iterator it;

  if(list.empty()){
    throw JUBATUS_EXCEPTION(no_worker(name));
  }

  // FIXME:
  // do you return all server list? it can be very large
  for(it = list.begin(); it!= list.end(); ++it){
    string ip;
    int port;
    common::revert(*it, ip, port);
    ret.push_back(make_pair(ip,port));
  }
}

void keeper::get_members_from_cht_(const std::string& name, const std::string& id,
                                   std::vector<std::pair<std::string, int> >& ret, size_t n)
{
  ret.clear();
  pfi::concurrent::scoped_lock lk(mutex_);
  jubatus::common::cht ht(zk_, a_.type, name);
  ht.find(id, ret, n);

  if(ret.empty()){
    throw JUBATUS_EXCEPTION(no_worker(name));
  }
}
<commit_msg>Fix keeper to finalize zookeeper before exiting: #184<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "keeper.hpp"

#include <cstdlib>
#include <iostream>
#include <glog/logging.h>

#include "../common/membership.hpp"
#include "../common/exception.hpp"
#include "../common/util.hpp"
#include "server_util.hpp"

using namespace jubatus;
using namespace jubatus::framework;

namespace {

std::string make_logfile_name(const keeper_argv& a) {
  std::ostringstream logfile;
  if (a.logdir != ""){
    logfile << a.logdir << '/';
    logfile << a.program_name << '.';
    logfile << a.eth << '_' << a.port;
    logfile << ".zklog.";
    logfile << getpid();
  }
  return logfile.str();
}

}

keeper::keeper(const keeper_argv& a)
  : pfi::network::mprpc::rpc_server(a.timeout),
    a_(a),
    zk_(common::create_lock_service("cached_zk", a.z, a.timeout, make_logfile_name(a)))
    //    zk_(common::create_lock_service("zk", a.z, a.timeout))
{
  ls = zk_;
  jubatus::common::prepare_jubatus(*zk_, a_.type, "");
  register_keeper(*zk_, a_.type, a_.eth, a_.port);
}

keeper::~keeper(){
}

int keeper::run()
{
  try {
    ::atexit(jubatus::framework::atexit);
    jubatus::util::set_exit_on_term();
    jubatus::util::ignore_sigpipe();
    if (this->serv(a_.port, a_.threadnum)) {
      return 0;
    } else {
      LOG(FATAL) << "failed starting server: any process using port " << a_.port << "?";
      return -1;
    }
  } catch (const jubatus::exception::jubatus_exception& e) {
    LOG(FATAL) << e.diagnostic_information(true);
    return -1;
  }
}

void keeper::get_members_(const std::string& name, std::vector<std::pair<std::string, int> >& ret){
  using namespace std;
  ret.clear();
  vector<string> list;
  string path;
  common::build_actor_path(path, a_.type, name);
  path += "/nodes";

  {
    pfi::concurrent::scoped_lock lk(mutex_);
    zk_->list(path, list);
  }
  vector<string>::const_iterator it;

  if(list.empty()){
    throw JUBATUS_EXCEPTION(no_worker(name));
  }

  // FIXME:
  // do you return all server list? it can be very large
  for(it = list.begin(); it!= list.end(); ++it){
    string ip;
    int port;
    common::revert(*it, ip, port);
    ret.push_back(make_pair(ip,port));
  }
}

void keeper::get_members_from_cht_(const std::string& name, const std::string& id,
                                   std::vector<std::pair<std::string, int> >& ret, size_t n)
{
  ret.clear();
  pfi::concurrent::scoped_lock lk(mutex_);
  jubatus::common::cht ht(zk_, a_.type, name);
  ht.find(id, ret, n);

  if(ret.empty()){
    throw JUBATUS_EXCEPTION(no_worker(name));
  }
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * konsolekalendar.cpp                                                         *
 *                                                                             *
 * KonsoleKalendar is a command line interface to KDE calendars                *
 * Copyright (C) 2002-2004  Tuukka Pasanen <illuusio@mailcity.com>             *
 * Copyright (C) 2003-2005  Allen Winter <winter@kde.org>
 *                                                                             *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
 *                                                                             *
 * As a special exception, permission is given to link this program            *
 * with any edition of Qt, and distribute the resulting executable,            *
 * without including the source code for Qt in the source distribution.        *
 *                                                                             *
 ******************************************************************************/
/**
 * @file konsolekalendar.cpp
 * Provides the KonsoleKalendar class definition.
 * @author Tuukka Pasanen
 * @author Allen Winter
 */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#include <qdatetime.h>
#include <qfile.h>
#include <qtextstream.h>

#include <kdebug.h>
#include <klocale.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/resourcecalendar.h>
#include <libkcal/calendarresources.h>
#include <libkcal/calendar.h>
#include <libkcal/event.h>
#include <libkcal/htmlexport.h>
#include <libkdepim/kpimprefs.h>

#include "konsolekalendar.h"
#include "konsolekalendaradd.h"
#include "konsolekalendarchange.h"
#include "konsolekalendardelete.h"
#include "konsolekalendarexports.h"

using namespace KCal;
using namespace std;

KonsoleKalendar::KonsoleKalendar( KonsoleKalendarVariables *variables )
{
  m_variables = variables;
  // m_Calendar =  new ResourceCalendar;
}

KonsoleKalendar::~KonsoleKalendar()
{
}

bool KonsoleKalendar::importCalendar()
{
  KonsoleKalendarAdd add( m_variables );

  kdDebug() << "konsolecalendar.cpp::importCalendar() | importing now!"
            << endl;
  return( add.addImportedCalendar() );
}

bool KonsoleKalendar::createCalendar()
{
  bool status = false;
  CalendarLocal newCalendar( KPimPrefs::timezone() );

  if ( m_variables->isDryRun() ) {
    cout << i18n( "Create Calendar <Dry Run>: %1" ).
      arg( m_variables->getCalendarFile() ).local8Bit()
         << endl;
  } else {
    kdDebug() << "konsolekalendar.cpp::createCalendar() | "
              << "Creating calendar file: "
              << m_variables->getCalendarFile().local8Bit()
              << endl;

    if ( m_variables->isVerbose() ) {
      cout << i18n( "Create Calendar <Verbose>: %1" ).
        arg( m_variables->getCalendarFile() ).local8Bit()
           << endl;
    }

    if ( newCalendar.save( m_variables->getCalendarFile() ) ) {
      newCalendar.close();
      status = true;
    }
  }
  return status;
}

bool KonsoleKalendar::showInstance()
{
  bool status = true;
  QFile f;
  QString title;
  Event::List *eventList;
  Event *event;

  if ( m_variables->isDryRun() ) {
    cout << i18n( "View Events <Dry Run>:" ).local8Bit()
         << endl;
    printSpecs();
  } else {

    kdDebug() << "konsolekalendar.cpp::showInstance() | "
              << "open export file"
              << endl;

    if ( m_variables->isExportFile() ) {
      f.setName( m_variables->getExportFile() );
      if ( !f.open( IO_WriteOnly ) ) {
	status = false;
	kdDebug() << "konsolekalendar.cpp::showInstance() | "
                  << "unable to open export file "
                  << m_variables->getExportFile()
                  << endl;
      }
    } else {
      f.open( IO_WriteOnly, stdout );
    }

    if ( status ) {
      kdDebug() << "konsolekalendar.cpp::showInstance() | "
                << "opened successful"
                << endl;

      if ( m_variables->isVerbose() ) {
	cout << i18n( "View Event <Verbose>:" ).local8Bit()
             << endl;
	printSpecs();
      }

      QTextStream ts( &f );

      if ( m_variables->getExportType() != ExportTypeHTML &&
           m_variables->getExportType() != ExportTypeMonthHTML ) {

	if ( m_variables->getAll() ) {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "view all events sorted list"
                    << endl;

	  Event::List sortedList =
            m_variables->getCalendar()->events( EventSortStartDate );
			if( sortedList.count()>0)
			{
          QDate dt, firstdate, lastdate;
          firstdate = sortedList.first()->dtStart().date();
          lastdate = sortedList.last()->dtStart().date();
          for ( dt = firstdate;
                dt <= lastdate && status != false;
                dt = dt.addDays(1) ) {
            Event::List events =
              m_variables->getCalendar()->events( dt,
                                                  EventSortStartDate,
                                                  SortDirectionAscending );
            status = printEventList( &ts, &events, dt );
          }
			}

	} else if ( m_variables->isUID() ) {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "view events by uid list"
                    << endl;
	  //TODO: support a list of UIDs
	  event = m_variables->getCalendar()->event( m_variables->getUID() );
	  //If this UID represents a recurring Event,
          //only the first day of the Event will be printed
	  status = printEvent ( &ts, event, event->dtStart().date() );

        } else if ( m_variables->isNext() ) {
          kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "Show next activity in calendar"
                    << endl;

          QDateTime datetime = m_variables->getStartDateTime();
          datetime = datetime.addDays( 720 );

	  QDate dt;
	  for ( dt = m_variables->getStartDateTime().date();
                dt <= datetime.date() && status != false;
                dt = dt.addDays(1) ) {
	    Event::List events =
              m_variables->getCalendar()->events( dt,
                                                  EventSortStartDate,
                                                  SortDirectionAscending );
	    status = printEventList( &ts, &events, dt );

	    // when we get next event we exit..
	    if ( events.count() ) {
	      kdDebug() << "konsolekalendar.cpp::showInstance() | "
                        << "Next event"
                        << endl;
	      return true;
	    }
          }
	} else {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "view raw events within date range list"
                    << endl;

	  QDate dt;
	  for ( dt = m_variables->getStartDateTime().date();
                dt <= m_variables->getEndDateTime().date() && status != false;
                dt = dt.addDays(1) ) {
	    Event::List events =
              m_variables->getCalendar()->events( dt,
                                                  EventSortStartDate,
                                                  SortDirectionAscending );
	    status = printEventList( &ts, &events, dt );
	  }
	}
      } else {
	QDate firstdate, lastdate;
	if ( m_variables->getAll() ) {
          // TODO: this is broken since the date on last() may not be last date
          // (this is the case for me)
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "HTML view all events sorted list"
                    << endl;
          eventList =
            new Event::List ( m_variables->getCalendar()->rawEvents() );
	  firstdate = eventList->first()->dtStart().date();
	  lastdate = eventList->last()->dtStart().date();
          delete eventList;
	} else if ( m_variables->isUID() ) {
	  // TODO
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "HTML view events by uid list" << endl;
	  cout << i18n("Sorry, export to HTML by UID is not supported yet")
            .local8Bit() << endl;
	  return( false );
	} else {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "HTML view raw events within date range list"
                    << endl;
	  firstdate = m_variables->getStartDateTime().date();
	  lastdate = m_variables->getEndDateTime().date();
	}

        HTMLExportSettings htmlSettings( "Konsolekalendar" );

        //TODO: get progname and url from the values set in main
        htmlSettings.setCreditName( "KonsoleKalendar" );
        htmlSettings.setCreditURL( "http://pim.kde.org/components/konsolekalendar.php" );

        htmlSettings.setExcludePrivate( true );
        htmlSettings.setExcludeConfidential( true );

        htmlSettings.setEventView( false );
        htmlSettings.setMonthView( false );
        if ( m_variables->getExportType() == ExportTypeMonthHTML ) {
          title = i18n( "Events:" );
          htmlSettings.setMonthView( true );
        } else {
          if ( firstdate == lastdate ) {
            title = i18n( "Events: %1" )
                    .arg(  firstdate.toString( Qt::TextDate ) );
          } else {
            title = i18n( "Events: %1 - %2" )
                    .arg( firstdate.toString( Qt::TextDate ) )
                    .arg( lastdate.toString( Qt::TextDate ) );
          }
          htmlSettings.setEventView( true );
        }
        htmlSettings.setEventTitle( title );
        htmlSettings.setEventAttendees( true );
// Not supporting Todos yet
//         title = "To-Do List for " + firstdate.toString(Qt::TextDate);
//         if ( firstdate != lastdate ) {
//           title += " - " + lastdate.toString(Qt::TextDate);
//         }
        htmlSettings.setTodoListTitle( title );
        htmlSettings.setTodoView( false );
//         htmlSettings.setTaskCategories( false );
//         htmlSettings.setTaskAttendees( false );
//         htmlSettings.setTaskDueDate( true );

        htmlSettings.setDateStart( QDateTime( firstdate ) );
        htmlSettings.setDateEnd( QDateTime( lastdate ) ) ;

        KCal::HtmlExport *Export;
        Export = new HtmlExport( m_variables->getCalendar(), &htmlSettings );
	status = Export->save( &ts );
        delete Export;
      }
      f.close();
    }
  }
  return status;
}

bool KonsoleKalendar::printEventList( QTextStream *ts,
                                      Event::List *eventList, QDate date )
{
  bool status = true;

  if ( eventList->count() ) {
    Event *singleEvent;
    Event::List::ConstIterator it;

    for ( it = eventList->begin();
          it != eventList->end() && status != false;
          ++it ) {
      singleEvent = *it;

      status = printEvent( ts, singleEvent, date );
    }
  }

  return( status );
}

bool KonsoleKalendar::printEvent( QTextStream *ts, Event *event, QDate dt )
{
  bool status = false;
  bool sameDay = true;
  KonsoleKalendarExports exports;

  if ( event ) {
    switch ( m_variables->getExportType() ) {

    case ExportTypeCSV:
      kdDebug() << "konsolekalendar.cpp::printEvent() | "
                << "CSV export"
                << endl;
      status = exports.exportAsCSV( ts, event, dt );
      break;

    case ExportTypeTextShort:
      kdDebug()
        << "konsolekalendar.cpp::printEvent() | "
        << "TEXT-SHORT export"
        << endl;
      if ( dt.daysTo( m_saveDate ) ) {
        sameDay = false;
        m_saveDate = dt;
      }
      status = exports.exportAsTxtShort( ts, event, dt, sameDay );
      break;

    case ExportTypeHTML:
      // this is handled separately for now
      break;

    default:// Default export-type is ExportTypeText
      kdDebug() << "konsolekalendar.cpp::printEvent() | "
                << "TEXT export"
                << endl;
      status = exports.exportAsTxt( ts, event, dt );
      break;
    }
  }
  return( status );
}

bool KonsoleKalendar::addEvent()
{
  kdDebug() << "konsolecalendar.cpp::addEvent() | "
            << "Create Adding"
            << endl;
  KonsoleKalendarAdd add( m_variables );
  kdDebug() << "konsolecalendar.cpp::addEvent() | "
            << "Adding Event now!"
            << endl;
  return( add.addEvent() );
}

bool KonsoleKalendar::changeEvent()
{

  kdDebug() << "konsolecalendar.cpp::changeEvent() | "
            << "Create Changing"
            << endl;
  KonsoleKalendarChange change( m_variables );
  kdDebug() << "konsolecalendar.cpp::changeEvent() | "
            << "Changing Event now!"
            << endl;
  return( change.changeEvent() );
}

bool KonsoleKalendar::deleteEvent()
{
  kdDebug() << "konsolecalendar.cpp::deleteEvent() | "
            << "Create Deleting"
            << endl;
  KonsoleKalendarDelete del( m_variables );
  kdDebug() << "konsolecalendar.cpp::deleteEvent() | "
            << "Deleting Event now!"
            << endl;
  return( del.deleteEvent() );
}

bool KonsoleKalendar::isEvent( QDateTime startdate,
                               QDateTime enddate, QString summary )
{
  // Search for an event with specified start and end datetime stamp and summary

  Event *event;
  Event::List::ConstIterator it;

  bool found = false;

  Event::List eventList( m_variables->getCalendar()->
                         rawEventsForDate( startdate.date(),
                                           EventSortStartDate,
                                           SortDirectionAscending ) );
  for ( it = eventList.begin(); it != eventList.end(); ++it ) {
    event = *it;
    if ( event->dtEnd() == enddate && event->summary() == summary ) {
      found = true;
      break;
    }
  }
  return found;
}

void KonsoleKalendar::printSpecs()
{
  cout << i18n( "  What:  %1" ).
    arg( m_variables->getSummary() ).local8Bit()
       << endl;

  cout << i18n( "  Begin: %1" ).
    arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit()
       << endl;

  cout << i18n( "  End:   %1" ).
    arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit()
       << endl;

  if ( m_variables->getFloating() == true ) {
    cout << i18n( "  No Time Associated with Event" ).local8Bit()
         << endl;
  }

  cout << i18n( "  Desc:  %1" ).
    arg( m_variables->getDescription() ).local8Bit()
       << endl;

  cout << i18n( "  Location:  %1" ).
    arg( m_variables->getLocation() ).local8Bit()
       << endl;
}
<commit_msg>fix for problem of exporting all events to HTML doesn't actually print all the events.<commit_after>/*******************************************************************************
 * konsolekalendar.cpp                                                         *
 *                                                                             *
 * KonsoleKalendar is a command line interface to KDE calendars                *
 * Copyright (C) 2002-2004  Tuukka Pasanen <illuusio@mailcity.com>             *
 * Copyright (C) 2003-2005  Allen Winter <winter@kde.org>
 *                                                                             *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
 *                                                                             *
 * As a special exception, permission is given to link this program            *
 * with any edition of Qt, and distribute the resulting executable,            *
 * without including the source code for Qt in the source distribution.        *
 *                                                                             *
 ******************************************************************************/
/**
 * @file konsolekalendar.cpp
 * Provides the KonsoleKalendar class definition.
 * @author Tuukka Pasanen
 * @author Allen Winter
 */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#include <qdatetime.h>
#include <qfile.h>
#include <qtextstream.h>

#include <kdebug.h>
#include <klocale.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/resourcecalendar.h>
#include <libkcal/calendarresources.h>
#include <libkcal/calendar.h>
#include <libkcal/event.h>
#include <libkcal/htmlexport.h>
#include <libkdepim/kpimprefs.h>

#include "konsolekalendar.h"
#include "konsolekalendaradd.h"
#include "konsolekalendarchange.h"
#include "konsolekalendardelete.h"
#include "konsolekalendarexports.h"

using namespace KCal;
using namespace std;

KonsoleKalendar::KonsoleKalendar( KonsoleKalendarVariables *variables )
{
  m_variables = variables;
}

KonsoleKalendar::~KonsoleKalendar()
{
}

bool KonsoleKalendar::importCalendar()
{
  KonsoleKalendarAdd add( m_variables );

  kdDebug() << "konsolecalendar.cpp::importCalendar() | importing now!"
            << endl;
  return( add.addImportedCalendar() );
}

bool KonsoleKalendar::createCalendar()
{
  bool status = false;
  CalendarLocal newCalendar( KPimPrefs::timezone() );

  if ( m_variables->isDryRun() ) {
    cout << i18n( "Create Calendar <Dry Run>: %1" ).
      arg( m_variables->getCalendarFile() ).local8Bit()
         << endl;
  } else {
    kdDebug() << "konsolekalendar.cpp::createCalendar() | "
              << "Creating calendar file: "
              << m_variables->getCalendarFile().local8Bit()
              << endl;

    if ( m_variables->isVerbose() ) {
      cout << i18n( "Create Calendar <Verbose>: %1" ).
        arg( m_variables->getCalendarFile() ).local8Bit()
           << endl;
    }

    if ( newCalendar.save( m_variables->getCalendarFile() ) ) {
      newCalendar.close();
      status = true;
    }
  }
  return status;
}

bool KonsoleKalendar::showInstance()
{
  bool status = true;
  QFile f;
  QString title;
  Event *event;

  if ( m_variables->isDryRun() ) {
    cout << i18n( "View Events <Dry Run>:" ).local8Bit()
         << endl;
    printSpecs();
  } else {

    kdDebug() << "konsolekalendar.cpp::showInstance() | "
              << "open export file"
              << endl;

    if ( m_variables->isExportFile() ) {
      f.setName( m_variables->getExportFile() );
      if ( !f.open( IO_WriteOnly ) ) {
	status = false;
	kdDebug() << "konsolekalendar.cpp::showInstance() | "
                  << "unable to open export file "
                  << m_variables->getExportFile()
                  << endl;
      }
    } else {
      f.open( IO_WriteOnly, stdout );
    }

    if ( status ) {
      kdDebug() << "konsolekalendar.cpp::showInstance() | "
                << "opened successful"
                << endl;

      if ( m_variables->isVerbose() ) {
	cout << i18n( "View Event <Verbose>:" ).local8Bit()
             << endl;
	printSpecs();
      }

      QTextStream ts( &f );

      if ( m_variables->getExportType() != ExportTypeHTML &&
           m_variables->getExportType() != ExportTypeMonthHTML ) {

	if ( m_variables->getAll() ) {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "view all events sorted list"
                    << endl;

	  Event::List sortedList =
            m_variables->getCalendar()->events( EventSortStartDate );
          if( sortedList.count() > 0 )
          {
            QDate dt, firstdate, lastdate;
            firstdate = sortedList.first()->dtStart().date();
            lastdate = sortedList.last()->dtStart().date();
            for ( dt = firstdate;
                  dt <= lastdate && status != false;
                  dt = dt.addDays(1) ) {
              Event::List events =
                m_variables->getCalendar()->events( dt,
                                                    EventSortStartDate,
                                                    SortDirectionAscending );
              status = printEventList( &ts, &events, dt );
            }
          }

	} else if ( m_variables->isUID() ) {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "view events by uid list"
                    << endl;
	  //TODO: support a list of UIDs
	  event = m_variables->getCalendar()->event( m_variables->getUID() );
	  //If this UID represents a recurring Event,
          //only the first day of the Event will be printed
	  status = printEvent ( &ts, event, event->dtStart().date() );

        } else if ( m_variables->isNext() ) {
          kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "Show next activity in calendar"
                    << endl;

          QDateTime datetime = m_variables->getStartDateTime();
          datetime = datetime.addDays( 720 );

	  QDate dt;
	  for ( dt = m_variables->getStartDateTime().date();
                dt <= datetime.date() && status != false;
                dt = dt.addDays(1) ) {
	    Event::List events =
              m_variables->getCalendar()->events( dt,
                                                  EventSortStartDate,
                                                  SortDirectionAscending );
	    status = printEventList( &ts, &events, dt );

	    // when we get next event we exit..
	    if ( events.count() ) {
	      kdDebug() << "konsolekalendar.cpp::showInstance() | "
                        << "Next event"
                        << endl;
	      return true;
	    }
          }
	} else {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "view raw events within date range list"
                    << endl;

	  QDate dt;
	  for ( dt = m_variables->getStartDateTime().date();
                dt <= m_variables->getEndDateTime().date() && status != false;
                dt = dt.addDays(1) ) {
	    Event::List events =
              m_variables->getCalendar()->events( dt,
                                                  EventSortStartDate,
                                                  SortDirectionAscending );
	    status = printEventList( &ts, &events, dt );
	  }
	}
      } else {
	QDate firstdate, lastdate;
	if ( m_variables->getAll() ) {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "HTML view all events sorted list"
                    << endl;
          // sort the events for this date by start date
          // in order to determine the date range.
          Event::List *events =
            new Event::List ( m_variables->getCalendar()->rawEvents(
                                EventSortStartDate,
                                SortDirectionAscending ) );
	  firstdate = events->first()->dtStart().date();
	  lastdate = events->last()->dtStart().date();
	} else if ( m_variables->isUID() ) {
	  // TODO
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "HTML view events by uid list" << endl;
	  cout << i18n("Sorry, export to HTML by UID is not supported yet")
            .local8Bit() << endl;
	  return( false );
	} else {
	  kdDebug() << "konsolekalendar.cpp::showInstance() | "
                    << "HTML view raw events within date range list"
                    << endl;
	  firstdate = m_variables->getStartDateTime().date();
	  lastdate = m_variables->getEndDateTime().date();
	}

        HTMLExportSettings htmlSettings( "Konsolekalendar" );

        //TODO: get progname and url from the values set in main
        htmlSettings.setCreditName( "KonsoleKalendar" );
        htmlSettings.setCreditURL( "http://pim.kde.org/components/konsolekalendar.php" );

        htmlSettings.setExcludePrivate( true );
        htmlSettings.setExcludeConfidential( true );

        htmlSettings.setEventView( false );
        htmlSettings.setMonthView( false );
        if ( m_variables->getExportType() == ExportTypeMonthHTML ) {
          title = i18n( "Events:" );
          htmlSettings.setMonthView( true );
        } else {
          if ( firstdate == lastdate ) {
            title = i18n( "Events: %1" )
                    .arg(  firstdate.toString( Qt::TextDate ) );
          } else {
            title = i18n( "Events: %1 - %2" )
                    .arg( firstdate.toString( Qt::TextDate ) )
                    .arg( lastdate.toString( Qt::TextDate ) );
          }
          htmlSettings.setEventView( true );
        }
        htmlSettings.setEventTitle( title );
        htmlSettings.setEventAttendees( true );
// Not supporting Todos yet
//         title = "To-Do List for " + firstdate.toString(Qt::TextDate);
//         if ( firstdate != lastdate ) {
//           title += " - " + lastdate.toString(Qt::TextDate);
//         }
        htmlSettings.setTodoListTitle( title );
        htmlSettings.setTodoView( false );
//         htmlSettings.setTaskCategories( false );
//         htmlSettings.setTaskAttendees( false );
//         htmlSettings.setTaskDueDate( true );

        htmlSettings.setDateStart( QDateTime( firstdate ) );
        htmlSettings.setDateEnd( QDateTime( lastdate ) ) ;

        KCal::HtmlExport *Export;
        Export = new HtmlExport( m_variables->getCalendar(), &htmlSettings );
	status = Export->save( &ts );
        delete Export;
      }
      f.close();
    }
  }
  return status;
}

bool KonsoleKalendar::printEventList( QTextStream *ts,
                                      Event::List *eventList, QDate date )
{
  bool status = true;

  if ( eventList->count() ) {
    Event *singleEvent;
    Event::List::ConstIterator it;

    for ( it = eventList->begin();
          it != eventList->end() && status != false;
          ++it ) {
      singleEvent = *it;

      status = printEvent( ts, singleEvent, date );
    }
  }

  return( status );
}

bool KonsoleKalendar::printEvent( QTextStream *ts, Event *event, QDate dt )
{
  bool status = false;
  bool sameDay = true;
  KonsoleKalendarExports exports;

  if ( event ) {
    switch ( m_variables->getExportType() ) {

    case ExportTypeCSV:
      kdDebug() << "konsolekalendar.cpp::printEvent() | "
                << "CSV export"
                << endl;
      status = exports.exportAsCSV( ts, event, dt );
      break;

    case ExportTypeTextShort:
      kdDebug()
        << "konsolekalendar.cpp::printEvent() | "
        << "TEXT-SHORT export"
        << endl;
      if ( dt.daysTo( m_saveDate ) ) {
        sameDay = false;
        m_saveDate = dt;
      }
      status = exports.exportAsTxtShort( ts, event, dt, sameDay );
      break;

    case ExportTypeHTML:
      // this is handled separately for now
      break;

    default:// Default export-type is ExportTypeText
      kdDebug() << "konsolekalendar.cpp::printEvent() | "
                << "TEXT export"
                << endl;
      status = exports.exportAsTxt( ts, event, dt );
      break;
    }
  }
  return( status );
}

bool KonsoleKalendar::addEvent()
{
  kdDebug() << "konsolecalendar.cpp::addEvent() | "
            << "Create Adding"
            << endl;
  KonsoleKalendarAdd add( m_variables );
  kdDebug() << "konsolecalendar.cpp::addEvent() | "
            << "Adding Event now!"
            << endl;
  return( add.addEvent() );
}

bool KonsoleKalendar::changeEvent()
{

  kdDebug() << "konsolecalendar.cpp::changeEvent() | "
            << "Create Changing"
            << endl;
  KonsoleKalendarChange change( m_variables );
  kdDebug() << "konsolecalendar.cpp::changeEvent() | "
            << "Changing Event now!"
            << endl;
  return( change.changeEvent() );
}

bool KonsoleKalendar::deleteEvent()
{
  kdDebug() << "konsolecalendar.cpp::deleteEvent() | "
            << "Create Deleting"
            << endl;
  KonsoleKalendarDelete del( m_variables );
  kdDebug() << "konsolecalendar.cpp::deleteEvent() | "
            << "Deleting Event now!"
            << endl;
  return( del.deleteEvent() );
}

bool KonsoleKalendar::isEvent( QDateTime startdate,
                               QDateTime enddate, QString summary )
{
  // Search for an event with specified start and end datetime stamp and summary

  Event *event;
  Event::List::ConstIterator it;

  bool found = false;

  Event::List eventList( m_variables->getCalendar()->
                         rawEventsForDate( startdate.date(),
                                           EventSortStartDate,
                                           SortDirectionAscending ) );
  for ( it = eventList.begin(); it != eventList.end(); ++it ) {
    event = *it;
    if ( event->dtEnd() == enddate && event->summary() == summary ) {
      found = true;
      break;
    }
  }
  return found;
}

void KonsoleKalendar::printSpecs()
{
  cout << i18n( "  What:  %1" ).
    arg( m_variables->getSummary() ).local8Bit()
       << endl;

  cout << i18n( "  Begin: %1" ).
    arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit()
       << endl;

  cout << i18n( "  End:   %1" ).
    arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit()
       << endl;

  if ( m_variables->getFloating() == true ) {
    cout << i18n( "  No Time Associated with Event" ).local8Bit()
         << endl;
  }

  cout << i18n( "  Desc:  %1" ).
    arg( m_variables->getDescription() ).local8Bit()
       << endl;

  cout << i18n( "  Location:  %1" ).
    arg( m_variables->getLocation() ).local8Bit()
       << endl;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>

ros::Publisher pub; // publishes pointcloud with removed edges
double cutoff_angle; // how many angle to cut off in the laser

void callback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
    sensor_msgs::LaserScan msg_out = *msg;
    msg_out.angle_min = msg->angle_min + cutoff_angle;
    msg_out.angle_max = msg->angle_max - cutoff_angle;
	msg_out.header = msg->header;
	pub.publish(msg_out);
}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "remove_edges_laser");
	ros::NodeHandle n;

    ros::NodeHandle pn("~");
    // topic of input cloud
    if (!pn.hasParam("input")) {
        ROS_ERROR("Could not find parameter input.");
        return -1;
    }
    std::string input;
    pn.getParam("input", input);

    // topic of output cloud
    if (!pn.hasParam("output")) {
        ROS_ERROR("Could not find parameter output.");
        return -1;
    }
    std::string output;
    pn.getParam("output", output);

    // how many pixels to cut off in the depth image
	if (!pn.hasParam("cutoff_angle")) {
        ROS_ERROR("Could not find parameter cutoff_angle.");
        return -1;
    }
    pn.getParam("cutoff_angle", cutoff_angle);

	ros::Subscriber sub = n.subscribe(input, 1, callback);
    pub = n.advertise<sensor_msgs::LaserScan>(output, 1);

    ros::spin();

	return 0;
}
<commit_msg>Now it should work<commit_after>#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>

ros::Publisher pub; // publishes pointcloud with removed edges
float cutoff_angle; // how many angle to cut off in the laser

void callback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
    float angle_min = msg->angle_min + cutoff_angle;
    float angle_max = msg->angle_max - cutoff_angle;
    int n_points = int(cutoff_angle / msg->angle_increment);
    int n_last = msg->ranges.size() - n_points;

    sensor_msgs::LaserScan msg_out;
    msg_out.ranges.insert(msg_out.ranges.begin(), msg->ranges.begin() + n_points, msg->ranges.begin() + n_last);
    msg_out.intensities.insert(msg_out.intensities.begin(), msg->intensities.begin() + n_points, msg->intensities.begin() + n_last);

    msg_out.angle_min = angle_min;
    msg_out.angle_max = angle_max;
    msg_out.angle_increment = msg->angle_increment;
    msg_out.time_increment = msg->time_increment;
    msg_out.scan_time = msg->scan_time;
    msg_out.range_min = msg->range_min;
    msg_out.range_max = msg->range_max;
	msg_out.header = msg->header;
	pub.publish(msg_out);
}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "remove_edges_laser");
	ros::NodeHandle n;

    ros::NodeHandle pn("~");
    // topic of input cloud
    if (!pn.hasParam("input")) {
        ROS_ERROR("Could not find parameter input.");
        return -1;
    }
    std::string input;
    pn.getParam("input", input);

    // topic of output cloud
    if (!pn.hasParam("output")) {
        ROS_ERROR("Could not find parameter output.");
        return -1;
    }
    std::string output;
    pn.getParam("output", output);

    // how many pixels to cut off in the depth image
	if (!pn.hasParam("cutoff_angle")) {
        ROS_ERROR("Could not find parameter cutoff_angle.");
        return -1;
    }
    double temp;
    pn.getParam("cutoff_angle", temp);
    cutoff_angle = M_PI/180.0*temp;

	ros::Subscriber sub = n.subscribe(input, 1, callback);
    pub = n.advertise<sensor_msgs::LaserScan>(output, 1);

    ros::spin();

	return 0;
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifdef _MSC_VER
#pragma warning( 4: 4786)
#define _WINSOCK2API_
#endif

// class interface header
#include "URLManager.h"

// system headers
#ifdef _WIN32
#include <winsock.h>
#endif
#ifdef HAVE_CURL
#include <curl/curl.h>
#endif
#include <iostream>

// common implementation headers
#include "bzfio.h"
#include "StateDatabase.h"

template <>
URLManager* Singleton<URLManager>::_instance = (URLManager*)0;

/******************************************************************************/
#ifdef HAVE_CURL
/******************************************************************************/

static size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);

bool URLManager::getURL(const std::string& URL, std::string &data)
{
  clearInternal();

  if (!beginGet(URL)) {
    return false;
  }

  char* newData = (char*)malloc(theLen + 1);
  memcpy(newData, theData, theLen);
  newData[theLen] = 0;

  data = newData;
  free(newData);

  return true;
}

bool URLManager::getURL(const std::string& URL, void **data, unsigned int& size)
{
  clearInternal();

  if (!beginGet(URL)) {
    return false;
  }

  *data = malloc(theLen);
  memcpy(*data, theData, theLen);
  size = theLen;
  return true;
}

bool URLManager::getFileTime(time_t& t)
{
  t = 0;
  if (errorCode != CURLE_OK) {
    return false;
  }

  long filetime;
  CURLcode result;
  result = curl_easy_getinfo((CURL*)easyHandle, CURLINFO_FILETIME, &filetime);
  if (result) {
    DEBUG1("CURLINFO_FILETIME error: %d\n", result);
    return false;
  }
  t = (time_t)filetime;

  return true;
}

bool URLManager::getURLHeader(const std::string& URL)
{
  CURL* curl = (CURL*)easyHandle;
  if (curl == NULL) {
    return false;
  }

  CURLcode result;
  errorCode = CURLE_OK;

  float timeout = 15;
  if (BZDB.isSet("httpTimeout")) {
    timeout = BZDB.eval("httpTimeout");
  }

#if LIBCURL_VERSION_NUM >= 0x070a00
  result = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, true);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOSIGNAL error: %d\n", result);
  }
#endif

  result = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_TIMEOUT error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOBODY error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  // FIXME: This could block for a _long_ time.
  result = curl_easy_perform(curl);
  if (result == (CURLcode)CURLOPT_ERRORBUFFER) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: server reported: %d\n", result);
  } else if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, NULL);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOBODY error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_HTTPGET error: %d\n", result);
  }

  return (errorCode == CURLE_OK);
}

void URLManager::freeURLData(void *data)
{
  free(data);
}

URLManager::URLManager()
{
  CURLcode result;

  easyHandle = NULL;
  theData = NULL;
  theLen = 0;
  errorCode = CURLE_OK;

  DEBUG1("LIBCURL: %s\n", curl_version());

#if LIBCURL_VERSION_NUM >= 0x070a00
  if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))
    DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
#endif

  easyHandle = curl_easy_init();
  if (!easyHandle) {
    DEBUG1("Something wrong with CURL\n");
    return;
  }
  CURL* curl = easyHandle;

  result = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFunction);
  if (result != CURLE_OK)
    DEBUG1("CURLOPT_WRITEFUNCTION error: %d\n", result);

  result = curl_easy_setopt(curl, CURLOPT_FILE, this);
  if (result != CURLE_OK)
    DEBUG1("CURLOPT_FILE error: %d\n", result);

  result = curl_easy_setopt(curl, CURLOPT_FILETIME, 1);
  if (result != CURLE_OK)
    DEBUG1("CURLOPT_FILETIME error: %d\n", result);
}

URLManager::~URLManager()
{
  clearInternal();

  if (easyHandle)
    curl_easy_cleanup((CURL*)easyHandle);

#if LIBCURL_VERSION_NUM >= 0x070a00
  curl_global_cleanup();
#endif
}

void URLManager::collectData(char* ptr, int len)
{
  unsigned char	*newData = (unsigned char*)malloc(theLen + len);
  if (theData)
    memcpy(newData, theData, theLen);

  memcpy(&(newData[theLen]), ptr, len);
  theLen += len;

  free(theData);
  theData = newData;
}

void URLManager::clearInternal()
{
  if (theData)
    free (theData);

  theData = NULL;
  theLen = 0;
  errorCode = CURLE_OK;

  return;
}

bool URLManager::beginGet(const std::string URL)
{
  CURL* curl = (CURL*)easyHandle;
  if (curl == NULL) {
    return false;
  }

  CURLcode result;
  errorCode = CURLE_OK;

  float timeout = 15;
  if (BZDB.isSet("httpTimeout"))
    timeout = BZDB.eval("httpTimeout");

#if LIBCURL_VERSION_NUM >= 0x070a00
  result = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, true);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOSIGNAL error: %d\n", result);
  }
#endif

  result = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_TIMEOUT error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  // FIXME: This could block for a _long_ time.
  result = curl_easy_perform(curl);
  if (result == (CURLcode)CURLOPT_ERRORBUFFER) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: server reported: %d\n", result);
  } else if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, NULL);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  if (!theData) {
    return false;
  }

  return (errorCode == CURLE_OK);
}

void URLManager::setProgressFunc(int (*func)(void* clientp,
					     double dltotal, double dlnow,
					     double ultotal, double ulnow),
					     void* data)
{
  CURL* curl = (CURL*)easyHandle;
  if (curl == NULL) {
    return;
  }
  CURLcode code;
  if (func != NULL) {
    code = curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, func);
    code = curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, data);
    code = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  } else {
    code = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
  }
  return;
}

static size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)
{
  int len = size * nmemb;
  ((URLManager*)stream)->collectData((char*)ptr, len);
  return len;
}

const char* URLManager::getErrorString() const
{
  if (easyHandle == NULL) {
    return "libcurl initialization error";
  }

  // LIBCURL didn't get curl_easy_strerror() until version 7.12.0.
  // BZFlag isn't currently limiting the libcurl version, so here's
  // a local function to do the same. It should be compatible with
  // curl versions all the way back to 7.9.5.

#define STRING_CASE(x)  \
  case CURLE_##x: return #x

  switch (errorCode) {
    case CURLE_OK: {
      return "Nah problems mon";
    }
    STRING_CASE(UNSUPPORTED_PROTOCOL);
    STRING_CASE(FAILED_INIT);
    STRING_CASE(URL_MALFORMAT);
    STRING_CASE(URL_MALFORMAT_USER);
    STRING_CASE(COULDNT_RESOLVE_PROXY);
    case CURLE_COULDNT_RESOLVE_HOST: {
      return "could not resolve hostname";
    }
    case CURLE_COULDNT_CONNECT: {
      return "could not connect";
    }
    STRING_CASE(FTP_WEIRD_SERVER_REPLY);
    STRING_CASE(FTP_ACCESS_DENIED);
    STRING_CASE(FTP_USER_PASSWORD_INCORRECT);
    STRING_CASE(FTP_WEIRD_PASS_REPLY);
    STRING_CASE(FTP_WEIRD_USER_REPLY);
    STRING_CASE(FTP_WEIRD_PASV_REPLY);
    STRING_CASE(FTP_WEIRD_227_FORMAT);
    STRING_CASE(FTP_CANT_GET_HOST);
    STRING_CASE(FTP_CANT_RECONNECT);
    STRING_CASE(FTP_COULDNT_SET_BINARY);
    STRING_CASE(PARTIAL_FILE);
    STRING_CASE(FTP_COULDNT_RETR_FILE);
    STRING_CASE(FTP_WRITE_ERROR);
    STRING_CASE(FTP_QUOTE_ERROR);
    STRING_CASE(HTTP_NOT_FOUND); // a.k.a. HTTP_RETURNED_ERROR
    STRING_CASE(WRITE_ERROR);
    STRING_CASE(MALFORMAT_USER);
    STRING_CASE(FTP_COULDNT_STOR_FILE);
    STRING_CASE(READ_ERROR);
    STRING_CASE(OUT_OF_MEMORY);
    STRING_CASE(OPERATION_TIMEOUTED);
    STRING_CASE(FTP_COULDNT_SET_ASCII);
    STRING_CASE(FTP_PORT_FAILED);
    STRING_CASE(FTP_COULDNT_USE_REST);
    STRING_CASE(FTP_COULDNT_GET_SIZE);
    STRING_CASE(HTTP_RANGE_ERROR);
    STRING_CASE(HTTP_POST_ERROR);
    STRING_CASE(SSL_CONNECT_ERROR);
    STRING_CASE(FTP_BAD_DOWNLOAD_RESUME); // a.k.a. BAD_DOWNLOAD_RESUME
    STRING_CASE(FILE_COULDNT_READ_FILE);
    STRING_CASE(LDAP_CANNOT_BIND);
    STRING_CASE(LDAP_SEARCH_FAILED);
    STRING_CASE(LIBRARY_NOT_FOUND);
    STRING_CASE(FUNCTION_NOT_FOUND);
    case CURLE_ABORTED_BY_CALLBACK: {
      return "aborted by user";
    }
    STRING_CASE(BAD_FUNCTION_ARGUMENT);
    STRING_CASE(BAD_CALLING_ORDER);
    STRING_CASE(HTTP_PORT_FAILED);
    STRING_CASE(BAD_PASSWORD_ENTERED);
    STRING_CASE(TOO_MANY_REDIRECTS );
    STRING_CASE(UNKNOWN_TELNET_OPTION);
    STRING_CASE(TELNET_OPTION_SYNTAX );
    STRING_CASE(OBSOLETE);
    STRING_CASE(SSL_PEER_CERTIFICATE);
    STRING_CASE(GOT_NOTHING);
    STRING_CASE(SSL_ENGINE_NOTFOUND);
    STRING_CASE(SSL_ENGINE_SETFAILED);
#if LIBCURL_VERSION_NUM >= 0x070C03
    STRING_CASE(SEND_ERROR);
    STRING_CASE(RECV_ERROR);
    STRING_CASE(SHARE_IN_USE);
    STRING_CASE(SSL_CERTPROBLEM);
    STRING_CASE(SSL_CIPHER);
    STRING_CASE(SSL_CACERT);
    STRING_CASE(BAD_CONTENT_ENCODING);
    STRING_CASE(LDAP_INVALID_URL);
    STRING_CASE(FILESIZE_EXCEEDED);
    STRING_CASE(FTP_SSL_FAILED);
#endif
    default: {
      static char buffer[256];
      sprintf(buffer, "unknown LIBCURL error, code = %i\n", errorCode);
      return buffer;
    }
  }
}

/******************************************************************************/
#else // ! HAVE_CURL
/******************************************************************************/

// stub the functions
URLManager::URLManager()
{
}
URLManager::~URLManager()
{
}
bool URLManager::getURL(const std::string&, std::string&)
{
  return false;
}
bool URLManager::getURL(const std::string&, void **, unsigned int&)
{
  return false;
}
bool URLManager::getFileTime(time_t&)
{
  return false;
}
const char* URLManager::getErrorString() const
{
  return "this client does not have libcurl support";
}
void URLManager::freeURLData(void*)
{
  return;
}
void URLManager::collectData(char*, int)
{
  return;
}
void URLManager::clearInternal()
{
  return;
}
bool URLManager::beginGet(const std::string)
{
  return false;
}
void URLManager::setProgressFunc(int (*)(void*, double, double,
						double, double), void*)
{
  return;
}

/******************************************************************************/
#endif // HAVE_CURL
/******************************************************************************/

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>ws<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifdef _MSC_VER
#pragma warning( 4: 4786)
#define _WINSOCK2API_
#endif

// class interface header
#include "URLManager.h"

// system headers
#ifdef _WIN32
#include <winsock.h>
#endif
#ifdef HAVE_CURL
#include <curl/curl.h>
#endif
#include <iostream>

// common implementation headers
#include "bzfio.h"
#include "StateDatabase.h"

template <>
URLManager* Singleton<URLManager>::_instance = (URLManager*)0;

/******************************************************************************/
#ifdef HAVE_CURL
/******************************************************************************/

static size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);

bool URLManager::getURL(const std::string& URL, std::string &data)
{
  clearInternal();

  if (!beginGet(URL)) {
    return false;
  }

  char* newData = (char*)malloc(theLen + 1);
  memcpy(newData, theData, theLen);
  newData[theLen] = 0;

  data = newData;
  free(newData);

  return true;
}

bool URLManager::getURL(const std::string& URL, void **data, unsigned int& size)
{
  clearInternal();

  if (!beginGet(URL)) {
    return false;
  }

  *data = malloc(theLen);
  memcpy(*data, theData, theLen);
  size = theLen;
  return true;
}

bool URLManager::getFileTime(time_t& t)
{
  t = 0;
  if (errorCode != CURLE_OK) {
    return false;
  }

  long filetime;
  CURLcode result;
  result = curl_easy_getinfo((CURL*)easyHandle, CURLINFO_FILETIME, &filetime);
  if (result) {
    DEBUG1("CURLINFO_FILETIME error: %d\n", result);
    return false;
  }
  t = (time_t)filetime;

  return true;
}

bool URLManager::getURLHeader(const std::string& URL)
{
  CURL* curl = (CURL*)easyHandle;
  if (curl == NULL) {
    return false;
  }

  CURLcode result;
  errorCode = CURLE_OK;

  float timeout = 15;
  if (BZDB.isSet("httpTimeout")) {
    timeout = BZDB.eval("httpTimeout");
  }

#if LIBCURL_VERSION_NUM >= 0x070a00
  result = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, true);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOSIGNAL error: %d\n", result);
  }
#endif

  result = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_TIMEOUT error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOBODY error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  // FIXME: This could block for a _long_ time.
  result = curl_easy_perform(curl);
  if (result == (CURLcode)CURLOPT_ERRORBUFFER) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: server reported: %d\n", result);
  } else if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, NULL);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOBODY error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_HTTPGET error: %d\n", result);
  }

  return (errorCode == CURLE_OK);
}

void URLManager::freeURLData(void *data)
{
  free(data);
}

URLManager::URLManager()
{
  CURLcode result;

  easyHandle = NULL;
  theData = NULL;
  theLen = 0;
  errorCode = CURLE_OK;

  DEBUG1("LIBCURL: %s\n", curl_version());

#if LIBCURL_VERSION_NUM >= 0x070a00
  if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))
    DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
#endif

  easyHandle = curl_easy_init();
  if (!easyHandle) {
    DEBUG1("Something wrong with CURL\n");
    return;
  }
  CURL* curl = easyHandle;

  result = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFunction);
  if (result != CURLE_OK)
    DEBUG1("CURLOPT_WRITEFUNCTION error: %d\n", result);

  result = curl_easy_setopt(curl, CURLOPT_FILE, this);
  if (result != CURLE_OK)
    DEBUG1("CURLOPT_FILE error: %d\n", result);

  result = curl_easy_setopt(curl, CURLOPT_FILETIME, 1);
  if (result != CURLE_OK)
    DEBUG1("CURLOPT_FILETIME error: %d\n", result);
}

URLManager::~URLManager()
{
  clearInternal();

  if (easyHandle)
    curl_easy_cleanup((CURL*)easyHandle);

#if LIBCURL_VERSION_NUM >= 0x070a00
  curl_global_cleanup();
#endif
}

void URLManager::collectData(char* ptr, int len)
{
  unsigned char	*newData = (unsigned char*)malloc(theLen + len);
  if (theData)
    memcpy(newData, theData, theLen);

  memcpy(&(newData[theLen]), ptr, len);
  theLen += len;

  free(theData);
  theData = newData;
}

void URLManager::clearInternal()
{
  if (theData)
    free (theData);

  theData = NULL;
  theLen = 0;
  errorCode = CURLE_OK;

  return;
}

bool URLManager::beginGet(const std::string URL)
{
  CURL* curl = (CURL*)easyHandle;
  if (curl == NULL) {
    return false;
  }

  CURLcode result;
  errorCode = CURLE_OK;

  float timeout = 15;
  if (BZDB.isSet("httpTimeout"))
    timeout = BZDB.eval("httpTimeout");

#if LIBCURL_VERSION_NUM >= 0x070a00
  result = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, true);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_NOSIGNAL error: %d\n", result);
  }
#endif

  result = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_TIMEOUT error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  // FIXME: This could block for a _long_ time.
  result = curl_easy_perform(curl);
  if (result == (CURLcode)CURLOPT_ERRORBUFFER) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: server reported: %d\n", result);
  } else if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("curl_easy_perform() error: %d\n", result);
  }

  result = curl_easy_setopt(curl, CURLOPT_URL, NULL);
  if (result != CURLE_OK) {
    errorCode = result;
    DEBUG1("CURLOPT_URL error: %d\n", result);
  }

  if (!theData) {
    return false;
  }

  return (errorCode == CURLE_OK);
}

void URLManager::setProgressFunc(int (*func)(void* clientp,
					     double dltotal, double dlnow,
					     double ultotal, double ulnow),
					     void* data)
{
  CURL* curl = (CURL*)easyHandle;
  if (curl == NULL) {
    return;
  }
  CURLcode code;
  if (func != NULL) {
    code = curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, func);
    code = curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, data);
    code = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  } else {
    code = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
  }
  return;
}

static size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)
{
  int len = size * nmemb;
  ((URLManager*)stream)->collectData((char*)ptr, len);
  return len;
}

const char* URLManager::getErrorString() const
{
  if (easyHandle == NULL) {
    return "libcurl initialization error";
  }

  // LIBCURL didn't get curl_easy_strerror() until version 7.12.0.
  // BZFlag isn't currently limiting the libcurl version, so here's
  // a local function to do the same. It should be compatible with
  // curl versions all the way back to 7.9.5.

#define STRING_CASE(x)  \
  case CURLE_##x: return #x

  switch (errorCode) {
    case CURLE_OK: {
      return "Nah problems mon";
    }
    STRING_CASE(UNSUPPORTED_PROTOCOL);
    STRING_CASE(FAILED_INIT);
    STRING_CASE(URL_MALFORMAT);
    STRING_CASE(URL_MALFORMAT_USER);
    STRING_CASE(COULDNT_RESOLVE_PROXY);
    case CURLE_COULDNT_RESOLVE_HOST: {
      return "could not resolve hostname";
    }
    case CURLE_COULDNT_CONNECT: {
      return "could not connect";
    }
    STRING_CASE(FTP_WEIRD_SERVER_REPLY);
    STRING_CASE(FTP_ACCESS_DENIED);
    STRING_CASE(FTP_USER_PASSWORD_INCORRECT);
    STRING_CASE(FTP_WEIRD_PASS_REPLY);
    STRING_CASE(FTP_WEIRD_USER_REPLY);
    STRING_CASE(FTP_WEIRD_PASV_REPLY);
    STRING_CASE(FTP_WEIRD_227_FORMAT);
    STRING_CASE(FTP_CANT_GET_HOST);
    STRING_CASE(FTP_CANT_RECONNECT);
    STRING_CASE(FTP_COULDNT_SET_BINARY);
    STRING_CASE(PARTIAL_FILE);
    STRING_CASE(FTP_COULDNT_RETR_FILE);
    STRING_CASE(FTP_WRITE_ERROR);
    STRING_CASE(FTP_QUOTE_ERROR);
    STRING_CASE(HTTP_NOT_FOUND); // a.k.a. HTTP_RETURNED_ERROR
    STRING_CASE(WRITE_ERROR);
    STRING_CASE(MALFORMAT_USER);
    STRING_CASE(FTP_COULDNT_STOR_FILE);
    STRING_CASE(READ_ERROR);
    STRING_CASE(OUT_OF_MEMORY);
    STRING_CASE(OPERATION_TIMEOUTED);
    STRING_CASE(FTP_COULDNT_SET_ASCII);
    STRING_CASE(FTP_PORT_FAILED);
    STRING_CASE(FTP_COULDNT_USE_REST);
    STRING_CASE(FTP_COULDNT_GET_SIZE);
    STRING_CASE(HTTP_RANGE_ERROR);
    STRING_CASE(HTTP_POST_ERROR);
    STRING_CASE(SSL_CONNECT_ERROR);
    STRING_CASE(FTP_BAD_DOWNLOAD_RESUME); // a.k.a. BAD_DOWNLOAD_RESUME
    STRING_CASE(FILE_COULDNT_READ_FILE);
    STRING_CASE(LDAP_CANNOT_BIND);
    STRING_CASE(LDAP_SEARCH_FAILED);
    STRING_CASE(LIBRARY_NOT_FOUND);
    STRING_CASE(FUNCTION_NOT_FOUND);
    case CURLE_ABORTED_BY_CALLBACK: {
      return "aborted by user";
    }
    STRING_CASE(BAD_FUNCTION_ARGUMENT);
    STRING_CASE(BAD_CALLING_ORDER);
    STRING_CASE(HTTP_PORT_FAILED);
    STRING_CASE(BAD_PASSWORD_ENTERED);
    STRING_CASE(TOO_MANY_REDIRECTS );
    STRING_CASE(UNKNOWN_TELNET_OPTION);
    STRING_CASE(TELNET_OPTION_SYNTAX );
    STRING_CASE(OBSOLETE);
    STRING_CASE(SSL_PEER_CERTIFICATE);
    STRING_CASE(GOT_NOTHING);
    STRING_CASE(SSL_ENGINE_NOTFOUND);
    STRING_CASE(SSL_ENGINE_SETFAILED);
#if LIBCURL_VERSION_NUM >= 0x070C03
    STRING_CASE(SEND_ERROR);
    STRING_CASE(RECV_ERROR);
    STRING_CASE(SHARE_IN_USE);
    STRING_CASE(SSL_CERTPROBLEM);
    STRING_CASE(SSL_CIPHER);
    STRING_CASE(SSL_CACERT);
    STRING_CASE(BAD_CONTENT_ENCODING);
    STRING_CASE(LDAP_INVALID_URL);
    STRING_CASE(FILESIZE_EXCEEDED);
    STRING_CASE(FTP_SSL_FAILED);
#endif
    default: {
      static char buffer[256];
      sprintf(buffer, "unknown LIBCURL error, code = %i\n", errorCode);
      return buffer;
    }
  }
}

/******************************************************************************/
#else // ! HAVE_CURL
/******************************************************************************/

// stub the functions
URLManager::URLManager()
{
}
URLManager::~URLManager()
{
}
bool URLManager::getURL(const std::string&, std::string&)
{
  return false;
}
bool URLManager::getURL(const std::string&, void **, unsigned int&)
{
  return false;
}
bool URLManager::getFileTime(time_t&)
{
  return false;
}
const char* URLManager::getErrorString() const
{
  return "this client does not have libcurl support";
}
void URLManager::freeURLData(void*)
{
  return;
}
void URLManager::collectData(char*, int)
{
  return;
}
void URLManager::clearInternal()
{
  return;
}
bool URLManager::beginGet(const std::string)
{
  return false;
}
void URLManager::setProgressFunc(int (*)(void*, double, double,
						double, double), void*)
{
  return;
}

/******************************************************************************/
#endif // HAVE_CURL
/******************************************************************************/

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>