<commit_before>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/filesystem/operations.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionPlugin.hpp>

#ifdef PION_WIN32
	#include <windows.h>
#else
	#include <dlfcn.h>
#endif

#include <iostream>

namespace pion {	// begin namespace pion

// static members of PionPlugin

const std::string			PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string			PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef PION_WIN32
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string			PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string>	PionPlugin::m_plugin_dirs;
PionPlugin::PluginMap		PionPlugin::m_plugin_map;
boost::mutex				PionPlugin::m_plugin_mutex;
PionPlugin::StaticEntryPointList	*PionPlugin::m_entry_points_ptr = NULL;

// PionPlugin member functions

void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
								 const std::string& start_path)
{
#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)
	// try prepending PION_CYGWIN_DIRECTORY if not complete
	if (! final_path.is_complete() && final_path.has_root_directory()) {
		final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);
	}
#endif
}

void PionPlugin::addPluginDirectory(const std::string& dir)
{
	boost::filesystem::path plugin_path = boost::filesystem::system_complete(dir);
	checkCygwinPath(plugin_path, dir);
	if (! boost::filesystem::exists(plugin_path) )
		throw DirectoryNotFoundException(dir);
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.push_back(plugin_path.directory_string());
}

void PionPlugin::resetPluginDirectories(void)
{
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.clear();
}

void PionPlugin::open(const std::string& plugin_name)
{
	std::string plugin_file;

	if (!findPluginFile(plugin_file, plugin_name))
		throw PluginNotFoundException(plugin_name);

	openFile(plugin_file);
}

void PionPlugin::openFile(const std::string& plugin_file)
{
	releaseData();	// make sure we're not already pointing to something

	// use a temporary object first since openPlugin() may throw
	PionPluginData plugin_data(getPluginName(plugin_file));

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// open up the shared library using our temporary data object
		openPlugin(plugin_file, plugin_data);	// may throw

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_data);
		m_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,
											m_plugin_data) );
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::openStaticLinked(const std::string& plugin_name,
								  void *create_func,
								  void *destroy_func)
{
	releaseData();	// make sure we're not already pointing to something

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_name);
		m_plugin_data->m_lib_handle = NULL; // this will indicate that we are using statically linked plug-in
		m_plugin_data->m_create_func = create_func;
		m_plugin_data->m_destroy_func = destroy_func;
		m_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,
										   m_plugin_data));
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::releaseData(void)
{
	if (m_plugin_data != NULL) {
		boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
		// double-check after locking mutex
		if (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {
			// no more references to the plug-in library

			// release the shared object
			closeDynamicLibrary(m_plugin_data->m_lib_handle);

			// remove it from the plug-in map
			PluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);
			// check itr just to be safe (it SHOULD always find a match)
			if (itr != m_plugin_map.end())
				m_plugin_map.erase(itr);

			// release the heap object
			delete m_plugin_data;
		}
		m_plugin_data = NULL;
	}
}

void PionPlugin::grabData(const PionPlugin& p)
{
	releaseData();	// make sure we're not already pointing to something
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);
	if (m_plugin_data != NULL) {
		++ m_plugin_data->m_references;
	}
}

bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
						  const std::string& extension)
{
	// first, try the name as-is
	if (checkForFile(path_to_file, name, "", extension))
		return true;

	// nope, check search paths
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
		 i != m_plugin_dirs.end(); ++i)
	{
		if (checkForFile(path_to_file, *i, name, extension))
			return true;
	}

	// no plug-in file found
	return false;
}

bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
							  const std::string& name, const std::string& extension)
{
	// check for cygwin path oddities
	boost::filesystem::path cygwin_safe_path(start_path);
	checkCygwinPath(cygwin_safe_path, start_path);
	boost::filesystem::path test_path(cygwin_safe_path);

	// if a name is specified, append it to the test path
	if (! name.empty())
		test_path /= name;

	// check for existence of plug-in (without extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// next, try appending the plug-in extension
	if (name.empty()) {
		// no "name" specified -> append it directly to start_path
		test_path = boost::filesystem::path(start_path + extension);
		// in this case, we need to re-check for the cygwin oddities
		checkCygwinPath(test_path, start_path + extension);
	} else {
		// name is specified, so we can just re-use cygwin_safe_path
		test_path = cygwin_safe_path /
			boost::filesystem::path(name + extension);
	}

	// re-check for existence of plug-in (after adding extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// no plug-in file found
	return false;
}

void PionPlugin::openPlugin(const std::string& plugin_file,
							PionPluginData& plugin_data)
{
	// get the name of the plugin (for create/destroy symbol names)
	plugin_data.m_plugin_name = getPluginName(plugin_file);

	// attempt to open the plugin; note that this tries all search paths
	// and also tries a variety of platform-specific extensions
	plugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());
	if (plugin_data.m_lib_handle == NULL)
		throw PluginNotFoundException(plugin_file);

	// find the function used to create new plugin objects
	plugin_data.m_create_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_CREATE + plugin_data.m_plugin_name);
	if (plugin_data.m_create_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingCreateException(plugin_file);
	}

	// find the function used to destroy existing plugin objects
	plugin_data.m_destroy_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);
	if (plugin_data.m_destroy_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingDestroyException(plugin_file);
	}
}

std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
	// strip path
#ifdef PION_WIN32
	std::string::size_type pos = plugin_file.find_last_of('\\');
#else
	std::string::size_type pos = plugin_file.find_last_of('/');
#endif
	std::string plugin_name = (pos == std::string::npos ?
							   plugin_file : plugin_file.substr(pos+1));
	pos = plugin_name.find('.');

	// truncate extension
	if (pos != std::string::npos)
		plugin_name.resize(pos);

	return plugin_name;
}

void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef PION_WIN32
	#ifdef BOOST_MSVC
		return LoadLibraryA(plugin_file.c_str());
	#else
		return LoadLibrary(plugin_file.c_str());
	#endif
#else
	std::cout << "trying to open " << plugin_file << std::endl;
	return dlopen(plugin_file.c_str(), RTLD_LAZY);
#endif
}

void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef PION_WIN32
	FreeLibrary((HINSTANCE) lib_handle);
#else
	dlclose(lib_handle);
#endif
}

void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef PION_WIN32
	return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
	return dlsym(lib_handle, symbol.c_str());
#endif
}

bool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,
									  void **create_func,
									  void **destroy_func)
{
	// check simple case first: no entry points exist
	if (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())
		return false;

	// try to find the entry point for the plugin
	for (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();
		 i != m_entry_points_ptr->end(); ++i) {
			if (i->m_plugin_name==plugin_name) {
				*create_func  = i->m_create_func;
				*destroy_func = i->m_destroy_func;
				return true;
			}
	}
	return false;
}

void PionPlugin::addStaticEntryPoint(const std::string& plugin_name,
									 void *create_func,
									 void *destroy_func)
{
	// make sure that this function can only be called by one thread at a time
	static boost::mutex			entrypoint_mutex;
	boost::mutex::scoped_lock	entrypoint_lock(entrypoint_mutex);

	// create the entry point list if it doesn't already exist
	if (m_entry_points_ptr == NULL)
		m_entry_points_ptr = new StaticEntryPointList;

	// insert it into the entry point list
	m_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));
}

}	// end namespace pion
<commit_msg>Removed debugging info left in from previous commit<commit_after>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/filesystem/operations.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionPlugin.hpp>

#ifdef PION_WIN32
	#include <windows.h>
#else
	#include <dlfcn.h>
#endif

namespace pion {	// begin namespace pion

// static members of PionPlugin

const std::string			PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string			PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef PION_WIN32
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
	const std::string			PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string			PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string>	PionPlugin::m_plugin_dirs;
PionPlugin::PluginMap		PionPlugin::m_plugin_map;
boost::mutex				PionPlugin::m_plugin_mutex;
PionPlugin::StaticEntryPointList	*PionPlugin::m_entry_points_ptr = NULL;

// PionPlugin member functions

void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
								 const std::string& start_path)
{
#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)
	// try prepending PION_CYGWIN_DIRECTORY if not complete
	if (! final_path.is_complete() && final_path.has_root_directory()) {
		final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);
	}
#endif
}

void PionPlugin::addPluginDirectory(const std::string& dir)
{
	boost::filesystem::path plugin_path = boost::filesystem::system_complete(dir);
	checkCygwinPath(plugin_path, dir);
	if (! boost::filesystem::exists(plugin_path) )
		throw DirectoryNotFoundException(dir);
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.push_back(plugin_path.directory_string());
}

void PionPlugin::resetPluginDirectories(void)
{
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_dirs.clear();
}

void PionPlugin::open(const std::string& plugin_name)
{
	std::string plugin_file;

	if (!findPluginFile(plugin_file, plugin_name))
		throw PluginNotFoundException(plugin_name);

	openFile(plugin_file);
}

void PionPlugin::openFile(const std::string& plugin_file)
{
	releaseData();	// make sure we're not already pointing to something

	// use a temporary object first since openPlugin() may throw
	PionPluginData plugin_data(getPluginName(plugin_file));

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// open up the shared library using our temporary data object
		openPlugin(plugin_file, plugin_data);	// may throw

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_data);
		m_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,
											m_plugin_data) );
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::openStaticLinked(const std::string& plugin_name,
								  void *create_func,
								  void *destroy_func)
{
	releaseData();	// make sure we're not already pointing to something

	// check to see if we already have a matching shared library
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	PluginMap::iterator itr = m_plugin_map.find(plugin_name);
	if (itr == m_plugin_map.end()) {
		// no plug-ins found with the same name

		// all is good -> insert it into the plug-in map
		m_plugin_data = new PionPluginData(plugin_name);
		m_plugin_data->m_lib_handle = NULL; // this will indicate that we are using statically linked plug-in
		m_plugin_data->m_create_func = create_func;
		m_plugin_data->m_destroy_func = destroy_func;
		m_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,
										   m_plugin_data));
	} else {
		// found an existing plug-in with the same name
		m_plugin_data = itr->second;
	}

	// increment the number of references
	++ m_plugin_data->m_references;
}

void PionPlugin::releaseData(void)
{
	if (m_plugin_data != NULL) {
		boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
		// double-check after locking mutex
		if (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {
			// no more references to the plug-in library

			// release the shared object
			closeDynamicLibrary(m_plugin_data->m_lib_handle);

			// remove it from the plug-in map
			PluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);
			// check itr just to be safe (it SHOULD always find a match)
			if (itr != m_plugin_map.end())
				m_plugin_map.erase(itr);

			// release the heap object
			delete m_plugin_data;
		}
		m_plugin_data = NULL;
	}
}

void PionPlugin::grabData(const PionPlugin& p)
{
	releaseData();	// make sure we're not already pointing to something
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	m_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);
	if (m_plugin_data != NULL) {
		++ m_plugin_data->m_references;
	}
}

bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
						  const std::string& extension)
{
	// first, try the name as-is
	if (checkForFile(path_to_file, name, "", extension))
		return true;

	// nope, check search paths
	boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
	for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
		 i != m_plugin_dirs.end(); ++i)
	{
		if (checkForFile(path_to_file, *i, name, extension))
			return true;
	}

	// no plug-in file found
	return false;
}

bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
							  const std::string& name, const std::string& extension)
{
	// check for cygwin path oddities
	boost::filesystem::path cygwin_safe_path(start_path);
	checkCygwinPath(cygwin_safe_path, start_path);
	boost::filesystem::path test_path(cygwin_safe_path);

	// if a name is specified, append it to the test path
	if (! name.empty())
		test_path /= name;

	// check for existence of plug-in (without extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// next, try appending the plug-in extension
	if (name.empty()) {
		// no "name" specified -> append it directly to start_path
		test_path = boost::filesystem::path(start_path + extension);
		// in this case, we need to re-check for the cygwin oddities
		checkCygwinPath(test_path, start_path + extension);
	} else {
		// name is specified, so we can just re-use cygwin_safe_path
		test_path = cygwin_safe_path /
			boost::filesystem::path(name + extension);
	}

	// re-check for existence of plug-in (after adding extension)
	if (boost::filesystem::exists(test_path)) {
		final_path = test_path.file_string();
		return true;
	}

	// no plug-in file found
	return false;
}

void PionPlugin::openPlugin(const std::string& plugin_file,
							PionPluginData& plugin_data)
{
	// get the name of the plugin (for create/destroy symbol names)
	plugin_data.m_plugin_name = getPluginName(plugin_file);

	// attempt to open the plugin; note that this tries all search paths
	// and also tries a variety of platform-specific extensions
	plugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());
	if (plugin_data.m_lib_handle == NULL)
		throw PluginNotFoundException(plugin_file);

	// find the function used to create new plugin objects
	plugin_data.m_create_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_CREATE + plugin_data.m_plugin_name);
	if (plugin_data.m_create_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingCreateException(plugin_file);
	}

	// find the function used to destroy existing plugin objects
	plugin_data.m_destroy_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);
	if (plugin_data.m_destroy_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingDestroyException(plugin_file);
	}
}

std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
	// strip path
#ifdef PION_WIN32
	std::string::size_type pos = plugin_file.find_last_of('\\');
#else
	std::string::size_type pos = plugin_file.find_last_of('/');
#endif
	std::string plugin_name = (pos == std::string::npos ?
							   plugin_file : plugin_file.substr(pos+1));
	pos = plugin_name.find('.');

	// truncate extension
	if (pos != std::string::npos)
		plugin_name.resize(pos);

	return plugin_name;
}

void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef PION_WIN32
	#ifdef BOOST_MSVC
		return LoadLibraryA(plugin_file.c_str());
	#else
		return LoadLibrary(plugin_file.c_str());
	#endif
#else
	return dlopen(plugin_file.c_str(), RTLD_LAZY);
#endif
}

void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef PION_WIN32
	FreeLibrary((HINSTANCE) lib_handle);
#else
	dlclose(lib_handle);
#endif
}

void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef PION_WIN32
	return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
	return dlsym(lib_handle, symbol.c_str());
#endif
}

bool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,
									  void **create_func,
									  void **destroy_func)
{
	// check simple case first: no entry points exist
	if (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())
		return false;

	// try to find the entry point for the plugin
	for (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();
		 i != m_entry_points_ptr->end(); ++i) {
			if (i->m_plugin_name==plugin_name) {
				*create_func  = i->m_create_func;
				*destroy_func = i->m_destroy_func;
				return true;
			}
	}
	return false;
}

void PionPlugin::addStaticEntryPoint(const std::string& plugin_name,
									 void *create_func,
									 void *destroy_func)
{
	// make sure that this function can only be called by one thread at a time
	static boost::mutex			entrypoint_mutex;
	boost::mutex::scoped_lock	entrypoint_lock(entrypoint_mutex);

	// create the entry point list if it doesn't already exist
	if (m_entry_points_ptr == NULL)
		m_entry_points_ptr = new StaticEntryPointList;

	// insert it into the entry point list
	m_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));
}

}	// end namespace pion
<|endoftext|>


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

#ifndef CONFIGMGR_WRAPEXCEPTION_HXX
#define CONFIGMGR_WRAPEXCEPTION_HXX

#include <com/sun/star/configuration/MissingBootstrapFileException.hpp>
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#include <com/sun/star/configuration/InstallationIncompleteException.hpp>
#include <com/sun/star/configuration/CannotLoadConfigurationException.hpp>
#include <com/sun/star/configuration/backend/BackendSetupException.hpp>
#include <com/sun/star/configuration/backend/AuthenticationFailedException.hpp>
#include <com/sun/star/configuration/backend/InvalidAuthenticationMechanismException.hpp>
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>
#include <com/sun/star/configuration/backend/InsufficientAccessRightsException.hpp>

#include <com/sun/star/configuration/backend/BackendAccessException.hpp>
#include <com/sun/star/configuration/backend/ConnectionLostException.hpp>
#include <com/sun/star/configuration/backend/MalformedDataException.hpp>

#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/xml/sax/SAXException.hpp>
#include <com/sun/star/xml/sax/SAXParseException.hpp>

#define WRAP_EXCEPTION( ETyp, Raise ) \
    catch (ETyp & _e_) { Raise( uno::makeAny(_e_) ); }

#define WRAP_EXCEPTION1( ETyp, Raise, Arg ) \
    catch (ETyp & _e_) { Raise( uno::makeAny(_e_), (Arg) ); }

#define PASS_EXCEPTION( ETyp ) \
    catch (ETyp & ) { throw; }

#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::CannotConnectException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendSetupException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise)     \
    WRAP_EXCEPTION(::com::sun::star::configuration::MissingBootstrapFileException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::InvalidBootstrapFileException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::InstallationIncompleteException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::CannotLoadConfigurationException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise)                   \
    WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetRuntimeException, Raise)            \
    WRAP_EXCEPTION(::com::sun::star::lang::DisposedException, Raise)                        \
    WRAP_EXCEPTION(::com::sun::star::uno::RuntimeException, Raise)      \
    WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)

#define WRAP_CONFIGBACKEND_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::ConnectionLostException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise)     \

#define WRAP_CONFIGDATA_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::MalformedDataException, Raise)     \
    WRAP_CONFIGBACKEND_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise)                   \

#define WRAP_SAX_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXParseException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXException, Raise)         \

#define WRAP_OTHER_EXCEPTIONS( Raise ) \
    WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)

#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::CannotConnectException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendSetupException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg)     \
    WRAP_EXCEPTION1(::com::sun::star::configuration::MissingBootstrapFileException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::InvalidBootstrapFileException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::InstallationIncompleteException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::CannotLoadConfigurationException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg)                   \
    WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetRuntimeException, Raise, Arg)            \
    WRAP_EXCEPTION1(::com::sun::star::lang::DisposedException, Raise, Arg)                        \
    WRAP_EXCEPTION1(::com::sun::star::uno::RuntimeException, Raise, Arg)      \
    WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)

#define WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::ConnectionLostException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg)     \

#define WRAP_CONFIGDATA_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::MalformedDataException, Raise, Arg)     \
    WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg)                   \

#define WRAP_SAX_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXParseException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXException, Raise, Arg)         \

#define WRAP_OTHER_EXCEPTIONS1( Raise, Arg ) \
    WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)

#endif // CONFIGMGR_WRAPEXCEPTION_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.130); FILE MERGED 2008/03/31 12:22:46 rt 1.4.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: wrapexception.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CONFIGMGR_WRAPEXCEPTION_HXX
#define CONFIGMGR_WRAPEXCEPTION_HXX

#include <com/sun/star/configuration/MissingBootstrapFileException.hpp>
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#include <com/sun/star/configuration/InstallationIncompleteException.hpp>
#include <com/sun/star/configuration/CannotLoadConfigurationException.hpp>
#include <com/sun/star/configuration/backend/BackendSetupException.hpp>
#include <com/sun/star/configuration/backend/AuthenticationFailedException.hpp>
#include <com/sun/star/configuration/backend/InvalidAuthenticationMechanismException.hpp>
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>
#include <com/sun/star/configuration/backend/InsufficientAccessRightsException.hpp>

#include <com/sun/star/configuration/backend/BackendAccessException.hpp>
#include <com/sun/star/configuration/backend/ConnectionLostException.hpp>
#include <com/sun/star/configuration/backend/MalformedDataException.hpp>

#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/xml/sax/SAXException.hpp>
#include <com/sun/star/xml/sax/SAXParseException.hpp>

#define WRAP_EXCEPTION( ETyp, Raise ) \
    catch (ETyp & _e_) { Raise( uno::makeAny(_e_) ); }

#define WRAP_EXCEPTION1( ETyp, Raise, Arg ) \
    catch (ETyp & _e_) { Raise( uno::makeAny(_e_), (Arg) ); }

#define PASS_EXCEPTION( ETyp ) \
    catch (ETyp & ) { throw; }

#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::CannotConnectException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendSetupException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise)     \
    WRAP_EXCEPTION(::com::sun::star::configuration::MissingBootstrapFileException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::InvalidBootstrapFileException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::InstallationIncompleteException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::CannotLoadConfigurationException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise)                   \
    WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetRuntimeException, Raise)            \
    WRAP_EXCEPTION(::com::sun::star::lang::DisposedException, Raise)                        \
    WRAP_EXCEPTION(::com::sun::star::uno::RuntimeException, Raise)      \
    WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)

#define WRAP_CONFIGBACKEND_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::ConnectionLostException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::BackendAccessException, Raise)     \

#define WRAP_CONFIGDATA_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::configuration::backend::MalformedDataException, Raise)     \
    WRAP_CONFIGBACKEND_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::lang::WrappedTargetException, Raise)                   \

#define WRAP_SAX_EXCEPTIONS( Raise )      \
    WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXParseException, Raise)    \
    WRAP_EXCEPTION(::com::sun::star::xml::sax::SAXException, Raise)         \

#define WRAP_OTHER_EXCEPTIONS( Raise ) \
    WRAP_EXCEPTION(::com::sun::star::uno::Exception, Raise)

#define WRAP_CONFIGBACKEND_CREATION_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::AuthenticationFailedException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InvalidAuthenticationMechanismException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::CannotConnectException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendSetupException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg)     \
    WRAP_EXCEPTION1(::com::sun::star::configuration::MissingBootstrapFileException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::InvalidBootstrapFileException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::InstallationIncompleteException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::CannotLoadConfigurationException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg)                   \
    WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetRuntimeException, Raise, Arg)            \
    WRAP_EXCEPTION1(::com::sun::star::lang::DisposedException, Raise, Arg)                        \
    WRAP_EXCEPTION1(::com::sun::star::uno::RuntimeException, Raise, Arg)      \
    WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)

#define WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::InsufficientAccessRightsException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::ConnectionLostException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::BackendAccessException, Raise, Arg)     \

#define WRAP_CONFIGDATA_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::configuration::backend::MalformedDataException, Raise, Arg)     \
    WRAP_CONFIGBACKEND_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::lang::WrappedTargetException, Raise, Arg)                   \

#define WRAP_SAX_EXCEPTIONS1( Raise, Arg )      \
    WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXParseException, Raise, Arg)    \
    WRAP_EXCEPTION1(::com::sun::star::xml::sax::SAXException, Raise, Arg)         \

#define WRAP_OTHER_EXCEPTIONS1( Raise, Arg ) \
    WRAP_EXCEPTION1(::com::sun::star::uno::Exception, Raise, Arg)

#endif // CONFIGMGR_WRAPEXCEPTION_HXX
<|endoftext|>


<commit_before>#include <iostream>
#include <dlfcn.h>
using namespace std;

int main(int argc, char *argv[] ) {
  void *hdl = dlopen("build/liblua", RTLD_NOW);
  if(hdl == 0) {
    cout << dlerror() << endl;
    return -1;
  }
  cout << "hdl=" << (long)hdl << endl;
  void *f = dlsym(hdl, "lua_createtable");
  cout << "f=" << (long)f << endl;
  return 0;
}

<commit_msg>update<commit_after>#include <iostream>
#include <dlfcn.h>
using namespace std;

int main(int argc, char *argv[] ) {
  void *hdl = dlopen("libbar.dylib", RTLD_NOW);
  if(hdl == 0) {
    cout << dlerror() << endl;
    return -1;
  }
  cout << "hdl=" << (long)hdl << endl;
  void *f = dlsym(hdl, "lua_createtable");
  cout << "f=" << (long)f << endl;
  return 0;
}

<|endoftext|>


<commit_before>#include <Python.h>

#include "s2.h"
#include "s2cap.h"
#include "s2cellid.h"
#include "s2latlng.h"
#include "s2regioncoverer.h"

const double kEarthCircumferenceMeters = 6371008.8 * M_PI * 2;

// Generates a list of cells at the target s2 cell levels which cover
// a cap of radius 'radius_meters' with center at lat & lng.
static PyObject *GetCellIDs(PyObject *self, PyObject *args) {
  double lat, lon;
  unsigned short int radius;
  if (!PyArg_ParseTuple(args, "ddH", &lat, &lon, &radius))
    return NULL;
  const S2Cap region = S2Cap::FromAxisAngle(
      S2LatLng::FromDegrees(lat, lon).ToPoint(),
      S1Angle::Degrees(360 * radius / kEarthCircumferenceMeters));
  S2RegionCoverer coverer;
  coverer.set_min_level(15);
  coverer.set_max_level(15);

  vector<S2CellId> covering;
  coverer.GetCovering(region, &covering);
  PyObject *cells, *cell;
  cells = PyTuple_New(covering.size());
  for (size_t i = 0; i < covering.size(); ++i) {
    cell = PyLong_FromUnsignedLongLong(covering[i].id());
    PyTuple_SetItem(cells, i, cell);
  }
  return cells;
}

/* List of functions defined in the module */
static PyMethodDef PogeoMethods[] = {
    {"get_cell_ids", GetCellIDs, METH_VARARGS,
     "Get the cell IDs for the given coordinates."},
    {NULL, NULL, 0, NULL} /* sentinel */
};

static struct PyModuleDef pogeomodule = {
    PyModuleDef_HEAD_INIT, "pogeo", /* name of module */
    NULL,                           /* module documentation, may be NULL */
    -1, /* size of per-interpreter state of the module,
           or -1 if the module keeps state in global variables. */
    PogeoMethods
};

PyMODINIT_FUNC PyInit_pogeo(void) { return PyModule_Create(&pogeomodule); }
<commit_msg>Make radius parameter optional<commit_after>#include <Python.h>

#include "s2.h"
#include "s2cap.h"
#include "s2cellid.h"
#include "s2latlng.h"
#include "s2regioncoverer.h"

const double kEarthCircumferenceMeters = 6371008.8 * M_PI * 2;

// Generates a list of cells at the target s2 cell levels which cover
// a cap of radius 'radius_meters' with center at lat & lng.
static PyObject *GetCellIDs(PyObject *self, PyObject *args) {
  double lat, lon;
  unsigned short int radius;
  radius = 500;
  if (!PyArg_ParseTuple(args, "dd|H", &lat, &lon, &radius))
    return NULL;
  const S2Cap region = S2Cap::FromAxisAngle(
      S2LatLng::FromDegrees(lat, lon).ToPoint(),
      S1Angle::Degrees(360 * radius / kEarthCircumferenceMeters));
  S2RegionCoverer coverer;
  coverer.set_min_level(15);
  coverer.set_max_level(15);

  vector<S2CellId> covering;
  coverer.GetCovering(region, &covering);
  PyObject *cells, *cell;
  cells = PyTuple_New(covering.size());
  for (size_t i = 0; i < covering.size(); ++i) {
    cell = PyLong_FromUnsignedLongLong(covering[i].id());
    PyTuple_SetItem(cells, i, cell);
  }
  return cells;
}

/* List of functions defined in the module */
static PyMethodDef PogeoMethods[] = {
    {"get_cell_ids", GetCellIDs, METH_VARARGS,
     "Get the cell IDs for the given coordinates."},
    {NULL, NULL, 0, NULL} /* sentinel */
};

static struct PyModuleDef pogeomodule = {
    PyModuleDef_HEAD_INIT, "pogeo", /* name of module */
    NULL,                           /* module documentation, may be NULL */
    -1, /* size of per-interpreter state of the module,
           or -1 if the module keeps state in global variables. */
    PogeoMethods
};

PyMODINIT_FUNC PyInit_pogeo(void) { return PyModule_Create(&pogeomodule); }
<|endoftext|>


<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    dialogs/exportsecretkeydialog.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2008 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "exportsecretkeydialog.h"

#include "ui_exportsecretkeydialog.h"

#include <utils/formatting.h>

#include <gpgme++/key.h>

#include <KDebug>
#include <KMessageBox>
#include <KLocalizedString>

#include <cassert>

using namespace Kleo;
using namespace Kleo::Dialogs;
using namespace GpgME;

// This comes from gnupg's sources, agent/minip12.c
// In fact, any charset supported by iconv would work, but we don't link to iconv directly...
static const char *charsets[] = {
    "utf8",
    "iso-8859-1",
    "iso-8859-15",
    "iso-8859-2",
    "iso-8859-3",
    "iso-8859-4",
    "iso-8859-5",
    "iso-8859-6",
    "iso-8859-7",
    "iso-8859-8",
    "iso-8859-9",
    "koi8-r",
    "ibm437",
    "ibm850",
    "euc-jp",
    "big5",
};
static const unsigned int numCharsets = sizeof charsets / sizeof *charsets;

class ExportSecretKeyDialog::Private {
    friend class ::Kleo::Dialogs::ExportSecretKeyDialog;
    ExportSecretKeyDialog * const q;
public:
    explicit Private( ExportSecretKeyDialog * qq )
        : q( qq ),
          ui( q )
    {

    }

private:
    void updateWidgets() {
        const bool x509 = key.protocol() == CMS;
        ui.charsetCB->setVisible( x509 );
        ui.charsetLB->setVisible( x509 );
    }

    void updateFileName() {
        const bool x509 = key.protocol() == CMS;
        const bool armor = q->useArmor();

        static const char * extensions[] = {
            ".gpg", ".asc", ".der", ".pem"
        };
        const unsigned int idx = 2*x509+armor;
        const char * const extension = extensions[idx];

        const QString nf = i18n("Secret Key Files") + QString::fromLatin1("(*%1 *%2 *%3 *%4)")
            .arg( extensions[idx], extensions[(idx+1)%4], extensions[(idx+2)%4], extensions[(idx+3)%4] );
        ui.outputFileFR->setNameFilter( nf );

        QString fn = q->fileName();
        if ( fn.isEmpty() )
            return;

        bool found = false;
        for ( unsigned int i = 0 ; i < sizeof extensions / sizeof *extensions ; ++i )
            if ( fn.endsWith( extensions[i], Qt::CaseInsensitive ) ) {
                fn.chop( 4 );
                found = true;
                break;
            }
        if ( found )
            q->setFileName( fn + extension );
    }

    void updateLabel() {
        ui.descriptionLB->setText( i18nc("@info",
                                         "Please select export options for %1:",
                                         Formatting::formatForComboBox( key ) ) );
    }
private:
    Key key;

    struct UI : public Ui_ExportSecretKeyDialog {
        explicit UI( Dialogs::ExportSecretKeyDialog * qq )
            : Ui_ExportSecretKeyDialog()
        {
            setupUi( qq );

            outputFileFR->setExistingOnly( false );
            outputFileFR->setFilter( QDir::Files );
            outputFileFR->setNameFilter( i18n("Secret Key Files (*.pem *.der *.gpg *.asc)") );

            for ( unsigned int i = 0 ; i < numCharsets ; ++i )
                charsetCB->addItem( QString::fromLatin1( charsets[i] ) );
            charsetCB->setCurrentIndex( -1 );

        }
    } ui;
};

ExportSecretKeyDialog::ExportSecretKeyDialog( QWidget * p, Qt::WindowFlags f )
    : QDialog( p, f ), d( new Private( this ) )
{

}

ExportSecretKeyDialog::~ExportSecretKeyDialog() {}

void ExportSecretKeyDialog::setKey( const Key & key ) {
    if ( qstricmp( key.primaryFingerprint(), d->key.primaryFingerprint() ) == 0 )
        return;
    d->key = key;
    d->updateWidgets();
    d->updateLabel();
    d->updateFileName();
}

Key ExportSecretKeyDialog::key() const {
    return d->key;
}

void ExportSecretKeyDialog::setFileName( const QString & fileName ) {
    d->ui.outputFileFR->setFileName( fileName );
}

QString ExportSecretKeyDialog::fileName() const {
    return d->ui.outputFileFR->fileName();
}

void ExportSecretKeyDialog::setCharset( const QByteArray & charset ) {
    for ( unsigned int i = 0 ; i < sizeof charsets / sizeof *charsets ; ++i )
        if ( charset == charsets[i] ) {
            d->ui.charsetCB->setCurrentIndex( i );
            return;
        }
}

QByteArray ExportSecretKeyDialog::charset() const {
    if ( d->ui.charsetCB->isVisible() )
        return d->ui.charsetCB->currentText().toLatin1();
    else
        return QByteArray();
}

void ExportSecretKeyDialog::setUseArmor( bool on ) {
    d->ui.armorCB->setChecked( on );
}

bool ExportSecretKeyDialog::useArmor() const {
    return d->ui.armorCB->isChecked();
}

void ExportSecretKeyDialog::accept() {
    d->updateFileName();
    const QString fn = fileName();
    if ( fn.isEmpty() ) {
        KMessageBox::information( this, i18nc("@info",
                                              "You have to enter an output filename." ),
                                  i18nc("@title", "Incomplete data") );
        d->ui.outputFileFR->setFocus();
        return;
    }

    const QByteArray cs = charset();
    if ( d->key.protocol() == CMS && cs.isEmpty() ) {
        KMessageBox::information( this, i18nc("@info",
                                              "You have to choose a passphrase character set." ),
                                  i18nc("@title", "Incomplete data") );
        d->ui.charsetCB->setFocus();
        return;
    }

    QDialog::accept();
}

#include "moc_exportsecretkeydialog.cpp"
<commit_msg>Oops, secret key files are .12, not .der<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    dialogs/exportsecretkeydialog.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2008 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "exportsecretkeydialog.h"

#include "ui_exportsecretkeydialog.h"

#include <utils/formatting.h>

#include <gpgme++/key.h>

#include <KDebug>
#include <KMessageBox>
#include <KLocalizedString>

#include <cassert>

using namespace Kleo;
using namespace Kleo::Dialogs;
using namespace GpgME;

// This comes from gnupg's sources, agent/minip12.c
// In fact, any charset supported by iconv would work, but we don't link to iconv directly...
static const char *charsets[] = {
    "utf8",
    "iso-8859-1",
    "iso-8859-15",
    "iso-8859-2",
    "iso-8859-3",
    "iso-8859-4",
    "iso-8859-5",
    "iso-8859-6",
    "iso-8859-7",
    "iso-8859-8",
    "iso-8859-9",
    "koi8-r",
    "ibm437",
    "ibm850",
    "euc-jp",
    "big5",
};
static const unsigned int numCharsets = sizeof charsets / sizeof *charsets;

class ExportSecretKeyDialog::Private {
    friend class ::Kleo::Dialogs::ExportSecretKeyDialog;
    ExportSecretKeyDialog * const q;
public:
    explicit Private( ExportSecretKeyDialog * qq )
        : q( qq ),
          ui( q )
    {

    }

private:
    void updateWidgets() {
        const bool x509 = key.protocol() == CMS;
        ui.charsetCB->setVisible( x509 );
        ui.charsetLB->setVisible( x509 );
    }

    void updateFileName() {
        const bool x509 = key.protocol() == CMS;
        const bool armor = q->useArmor();

        static const char * extensions[] = {
            ".gpg", ".asc", ".p12", ".pem"
        };
        const unsigned int idx = 2*x509+armor;
        const char * const extension = extensions[idx];

        const QString nf = i18n("Secret Key Files") + QString::fromLatin1("(*%1 *%2 *%3 *%4)")
            .arg( extensions[idx], extensions[(idx+1)%4], extensions[(idx+2)%4], extensions[(idx+3)%4] );
        ui.outputFileFR->setNameFilter( nf );

        QString fn = q->fileName();
        if ( fn.isEmpty() )
            return;

        bool found = false;
        for ( unsigned int i = 0 ; i < sizeof extensions / sizeof *extensions ; ++i )
            if ( fn.endsWith( extensions[i], Qt::CaseInsensitive ) ) {
                fn.chop( 4 );
                found = true;
                break;
            }
        if ( found )
            q->setFileName( fn + extension );
    }

    void updateLabel() {
        ui.descriptionLB->setText( i18nc("@info",
                                         "Please select export options for %1:",
                                         Formatting::formatForComboBox( key ) ) );
    }
private:
    Key key;

    struct UI : public Ui_ExportSecretKeyDialog {
        explicit UI( Dialogs::ExportSecretKeyDialog * qq )
            : Ui_ExportSecretKeyDialog()
        {
            setupUi( qq );

            outputFileFR->setExistingOnly( false );
            outputFileFR->setFilter( QDir::Files );
            outputFileFR->setNameFilter( i18n("Secret Key Files (*.pem *.p12 *.gpg *.asc)") );

            for ( unsigned int i = 0 ; i < numCharsets ; ++i )
                charsetCB->addItem( QString::fromLatin1( charsets[i] ) );
            charsetCB->setCurrentIndex( -1 );

        }
    } ui;
};

ExportSecretKeyDialog::ExportSecretKeyDialog( QWidget * p, Qt::WindowFlags f )
    : QDialog( p, f ), d( new Private( this ) )
{

}

ExportSecretKeyDialog::~ExportSecretKeyDialog() {}

void ExportSecretKeyDialog::setKey( const Key & key ) {
    if ( qstricmp( key.primaryFingerprint(), d->key.primaryFingerprint() ) == 0 )
        return;
    d->key = key;
    d->updateWidgets();
    d->updateLabel();
    d->updateFileName();
}

Key ExportSecretKeyDialog::key() const {
    return d->key;
}

void ExportSecretKeyDialog::setFileName( const QString & fileName ) {
    d->ui.outputFileFR->setFileName( fileName );
}

QString ExportSecretKeyDialog::fileName() const {
    return d->ui.outputFileFR->fileName();
}

void ExportSecretKeyDialog::setCharset( const QByteArray & charset ) {
    for ( unsigned int i = 0 ; i < sizeof charsets / sizeof *charsets ; ++i )
        if ( charset == charsets[i] ) {
            d->ui.charsetCB->setCurrentIndex( i );
            return;
        }
}

QByteArray ExportSecretKeyDialog::charset() const {
    if ( d->ui.charsetCB->isVisible() )
        return d->ui.charsetCB->currentText().toLatin1();
    else
        return QByteArray();
}

void ExportSecretKeyDialog::setUseArmor( bool on ) {
    d->ui.armorCB->setChecked( on );
}

bool ExportSecretKeyDialog::useArmor() const {
    return d->ui.armorCB->isChecked();
}

void ExportSecretKeyDialog::accept() {
    d->updateFileName();
    const QString fn = fileName();
    if ( fn.isEmpty() ) {
        KMessageBox::information( this, i18nc("@info",
                                              "You have to enter an output filename." ),
                                  i18nc("@title", "Incomplete data") );
        d->ui.outputFileFR->setFocus();
        return;
    }

    const QByteArray cs = charset();
    if ( d->key.protocol() == CMS && cs.isEmpty() ) {
        KMessageBox::information( this, i18nc("@info",
                                              "You have to choose a passphrase character set." ),
                                  i18nc("@title", "Incomplete data") );
        d->ui.charsetCB->setFocus();
        return;
    }

    QDialog::accept();
}

#include "moc_exportsecretkeydialog.cpp"
<|endoftext|>


<commit_before>/*
 * This file is part of telepathy-integration-daemon
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "telepathyaccount.h"

#include "telepathyaccountmonitor.h"

// Ontology uri's
#include "nco.h"
#include "pimo.h"
#include "tpaccount.h"

// Full Ontologies
#include "personcontact.h"

#include <Akonadi/AgentManager>

#include <kdebug.h>

#include <Nepomuk/Thing>
#include <Nepomuk/Variant>

#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>

TelepathyAccount::TelepathyAccount(const QString &path, TelepathyAccountMonitor *parent)
 : QObject(parent),
   m_parent(parent),
   m_path(path)
{
    // We need to get the Tp::Account ready before we do any other stuff.
    m_account = m_parent->accountManager()->accountForPath(path);

    Tp::Features features;
    features << Tp::Account::FeatureCore
             << Tp::Account::FeatureProtocolInfo;

    connect(m_account->becomeReady(features),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onAccountReady(Tp::PendingOperation*)));
}

TelepathyAccount::~TelepathyAccount()
{

}

void TelepathyAccount::onAccountReady(Tp::PendingOperation *op)
{
   if (op->isError()) {
        kWarning() << "Account" << m_path << "cannot become ready:"
                   << op->errorName() << "-" << op->errorMessage();
        return;
    }

    // Check that this Account is set up in nepomuk.
    doNepomukSetup();

    // Once the nepomuk setup is complete, do the Akonadi setup.
    doAkonadiSetup();
}

void TelepathyAccount::doNepomukSetup()
{
    // Get the PIMO:Person for "me" from nepomuk
    Nepomuk::Thing me(QUrl::fromEncoded("nepomuk:/myself"));

    if (!me.exists()) {
        // The PIMO:Person representing "me" does not exist, so we need to create it.
        me.addType(Nepomuk::Vocabulary::PIMO::Person());
    }

    // Loop through all the grounding instances of this person
    Q_FOREACH (Nepomuk::Resource resource, me.groundingOccurrences()) {
        // See if this grounding instance is of type nco:contact.
        if (resource.hasType(Nepomuk::Vocabulary::NCO::Contact())) {
            // we have an NCO:Contact. See if it is for this Telepathy Account.
            if (resource.hasProperty(Nepomuk::Vocabulary::TPACCOUNT::identifier())) {
                // we have a tpaccount property. See if it is the same as the path of this account.
                if (resource.property(Nepomuk::Vocabulary::TPACCOUNT::identifier()).toString() == m_path) {
                    // Nepomuk has this account already. Don't need to do anything.
                    return;
                }
            }
        }
    }

    kDebug() << "Telepathy Account" << m_path << "does not exist is nepomuk yet. Add it.";
    // Nepomuk doesn't yet have this account. Add it.
    Nepomuk::PersonContact contact(m_path);
    contact.setLabel(m_account->nickname());

    me.addProperty(Nepomuk::Vocabulary::NCO::PersonContact(), contact);
}

void TelepathyAccount::doAkonadiSetup()
{
    // Loop over the list of Agents to find one with the unique identifier of this account and with
    // the correct type.
    Akonadi::AgentInstance::List agentList = Akonadi::AgentManager::self()->instances();

    foreach (Akonadi::AgentInstance agent, agentList) {
        if (agent.type().identifier() == "telepathy_contacts_resource") {
            if (agent.type().identifier() == "telepathy_contacts_resource") {
                // This is our agent. Nothing to do. Return.
                return;
            }
        }
    }

    // If we reach here, the agent doesn't exist for this account, so create an instance of it.
    // TODO: Implement me!
}

<commit_msg>Add some debug statements.<commit_after>/*
 * This file is part of telepathy-integration-daemon
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "telepathyaccount.h"

#include "telepathyaccountmonitor.h"

// Ontology uri's
#include "nco.h"
#include "pimo.h"
#include "tpaccount.h"

// Full Ontologies
#include "personcontact.h"

#include <Akonadi/AgentManager>

#include <kdebug.h>

#include <Nepomuk/Thing>
#include <Nepomuk/Variant>

#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>

TelepathyAccount::TelepathyAccount(const QString &path, TelepathyAccountMonitor *parent)
 : QObject(parent),
   m_parent(parent),
   m_path(path)
{
    // We need to get the Tp::Account ready before we do any other stuff.
    m_account = m_parent->accountManager()->accountForPath(path);

    Tp::Features features;
    features << Tp::Account::FeatureCore
             << Tp::Account::FeatureProtocolInfo;

    connect(m_account->becomeReady(features),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onAccountReady(Tp::PendingOperation*)));
}

TelepathyAccount::~TelepathyAccount()
{

}

void TelepathyAccount::onAccountReady(Tp::PendingOperation *op)
{
   if (op->isError()) {
        kWarning() << "Account" << m_path << "cannot become ready:"
                   << op->errorName() << "-" << op->errorMessage();
        return;
    }

    // Check that this Account is set up in nepomuk.
    doNepomukSetup();

    // Once the nepomuk setup is complete, do the Akonadi setup.
    doAkonadiSetup();
}

void TelepathyAccount::doNepomukSetup()
{
    // Get the PIMO:Person for "me" from nepomuk
    Nepomuk::Thing me(QUrl::fromEncoded("nepomuk:/myself"));

    if (!me.exists()) {
        // The PIMO:Person representing "me" does not exist, so we need to create it.
        me.addType(Nepomuk::Vocabulary::PIMO::Person());
    }

    // Loop through all the grounding instances of this person
    Q_FOREACH (Nepomuk::Resource resource, me.groundingOccurrences()) {
        // See if this grounding instance is of type nco:contact.
        if (resource.hasType(Nepomuk::Vocabulary::NCO::Contact())) {
            // we have an NCO:Contact. See if it is for this Telepathy Account.
            if (resource.hasProperty(Nepomuk::Vocabulary::TPACCOUNT::identifier())) {
                // we have a tpaccount property. See if it is the same as the path of this account.
                if (resource.property(Nepomuk::Vocabulary::TPACCOUNT::identifier()).toString() == m_path) {
                    // Nepomuk has this account already. Don't need to do anything.
                    return;
                }
            }
        }
    }

    kDebug() << "Telepathy Account" << m_path << "does not exist is nepomuk yet. Add it.";
    // Nepomuk doesn't yet have this account. Add it.
    Nepomuk::PersonContact contact(m_path);
    contact.setLabel(m_account->nickname());

    me.addProperty(Nepomuk::Vocabulary::NCO::PersonContact(), contact);
}

void TelepathyAccount::doAkonadiSetup()
{
    // Loop over the list of Agents to find one with the unique identifier of this account and with
    // the correct type.
    Akonadi::AgentInstance::List agentList = Akonadi::AgentManager::self()->instances();

    foreach (Akonadi::AgentInstance agent, agentList) {
        if (agent.type().identifier() == "telepathy_contacts_resource") {
            if (agent.type().identifier() == "telepathy_contacts_resource") {
                // This is our agent. Nothing to do. Return.
                kDebug() << "This telepathy account already has a Akonadi Resource for it.";
                return;
            }
        }
    }

    // If we reach here, the agent doesn't exist for this account, so create an instance of it.
    kDebug() << "This telepathy account doesn't already have an Akonadi Resource for it. Create one.";
    // TODO: Implement me!
}

<|endoftext|>


<commit_before>#include <QtTest>
#include <QtCore>

#include <options.h>
#include <idmapping.h>

#include <KGlobal>
#include <KStandardDirs>

#include "qtest_kde.h"

class IDMappingTest : public QObject
{
	Q_OBJECT

public:
	IDMappingTest();

private slots:
	void testMap();
	void testRemove();
	void testIsValid();
	void testRecordId();
	void testCommitRollBack();
	void cleanupTestCase();

private:
	void cleanDir();

	QString fUser;
	QString fConduit;
};

IDMappingTest::IDMappingTest() : fUser( "test-user" )
	, fConduit("test-conduit")
{
}

void IDMappingTest::testMap()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );

	QVERIFY( mapping.contains( CSL1( "hh-1" ) ) );
	QVERIFY( mapping.contains( CSL1( "pc-100" ) ) );
}

void IDMappingTest::testRemove()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.remove( CSL1( "hh-1" ) );

	QVERIFY( !mapping.contains( CSL1( "hh-1" ) ) );
	QVERIFY( !mapping.contains( CSL1( "pc-100" ) ) );

	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.remove( CSL1( "pc-100" ) );

	QVERIFY( !mapping.contains( CSL1( "hh-1" ) ) );
	QVERIFY( !mapping.contains( CSL1( "pc-100" ) ) );
}

void IDMappingTest::testIsValid()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.map( CSL1( "hh-2" ), CSL1( "pc-40" ) );
	mapping.map( CSL1( "hh-3" ), CSL1( "pc-46" ) );

	QStringList hhIds;
	hhIds << CSL1( "hh-1" ) << CSL1( "hh-2" ) << CSL1( "hh-3" );

	QStringList pcIds;
	pcIds << CSL1( "pc-100" ) << CSL1( "pc-40" ) << CSL1( "pc-46" );

	/*
	 * This is a bit tricky. There are three id's in the list and there are three
	 * mappings. Also for each id in this list exists a mapping. BUT the ids of
	 * hh and are mixed here and have a mapping all by coincidence, however this
	 * does not garantee that the mapping is valid. If for example "hh-1" maps to
	 * "pc-78" the mapping is invalid because it should map to "pc-100"
	 */
	QStringList trickyIds;
	trickyIds << CSL1( "hh-1" ) << CSL1( "pc-40" ) << CSL1( "pc-46" );

	QStringList randomIds;
	randomIds << CSL1( "random-2" ) << CSL1( "random-14" );
	randomIds	<< CSL1( "random-109" );

	QVERIFY( mapping.isValid( hhIds ) );
	QVERIFY( mapping.isValid( pcIds ) );
	QVERIFY( !mapping.isValid( trickyIds ) );
	QVERIFY( !mapping.isValid( randomIds ) );
}

void IDMappingTest::testRecordId()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.map( CSL1( "hh-2" ), CSL1( "pc-40" ) );

	QVERIFY( mapping.recordId( CSL1( "hh-1" ) ) == CSL1( "pc-100" ) );
	QVERIFY( mapping.recordId( CSL1( "pc-100" ) ) == CSL1( "hh-1" ) );
	QVERIFY( mapping.recordId( CSL1( "hh-2" ) ) == CSL1( "pc-40" ) );
	QVERIFY( mapping.recordId( CSL1( "pc-40" ) ) == CSL1( "hh-2" ) );
}

void IDMappingTest::testCommitRollBack()
{
	// Clean up things to ensure this test won't be influenced by earlier data
	// which might be there.
	cleanDir();

	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.map( CSL1( "hh-2" ), CSL1( "pc-40" ) );
	mapping.commit();

	// Should contain 2 mappings
	IDMapping mapping2( fUser, fConduit );

	QStringList hhIds, hhIds2;
	hhIds << CSL1( "hh-1" ) << CSL1( "hh-2" );
	hhIds2 << hhIds << CSL1( "hh-3" );

	QVERIFY( mapping.isValid( hhIds ) );

	mapping2.map( CSL1( "hh-3" ), CSL1( "pc-23" ) );
	mapping2.commit();

	QVERIFY( mapping2.isValid( hhIds2 ) );

	mapping2.rollback();

	QVERIFY( mapping2.isValid( hhIds ) );

	IDMapping mapping3( fUser, fConduit );

	QVERIFY( mapping3.isValid( hhIds ) );
}

void IDMappingTest::cleanDir()
{
	QString pathName = KGlobal::dirs()->saveLocation( "data",
		CSL1("kpilot/conduits/"));

	QDir dir( pathName );
	dir.cd( fUser );
	dir.cd( CSL1( "mapping" ) );
	dir.remove( fConduit + CSL1( "-mapping.xml" ) );
	dir.remove(  fConduit + CSL1( "-mapping.xml~" ) );
	dir.remove(  fConduit + CSL1( "-mapping.xml.fail" ) );
	dir.cd( CSL1( ".." ) );
	dir.rmdir( CSL1( "mapping" ) );
	dir.cd( CSL1( ".." ) );
	dir.rmdir( fUser );
}

void IDMappingTest::cleanupTestCase()
{
	//cleanDir();
}

QTEST_KDEMAIN(IDMappingTest, NoGUI)

#include "idmappingtest.moc"
<commit_msg>SVN_SILENT:  - Added copyright<commit_after>/* idmappingtest.cc			KPilot
**
** Copyright (C) 2007 by Bertjan Broeksema
** Copyright (C) 2007 by Jason "vanRijn" Kasper
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include <QtTest>
#include <QtCore>

#include <options.h>
#include <idmapping.h>

#include <KGlobal>
#include <KStandardDirs>

#include "qtest_kde.h"

class IDMappingTest : public QObject
{
	Q_OBJECT

public:
	IDMappingTest();

private slots:
	void testMap();
	void testRemove();
	void testIsValid();
	void testRecordId();
	void testCommitRollBack();
	void cleanupTestCase();

private:
	void cleanDir();

	QString fUser;
	QString fConduit;
};

IDMappingTest::IDMappingTest() : fUser( "test-user" )
	, fConduit("test-conduit")
{
}

void IDMappingTest::testMap()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );

	QVERIFY( mapping.contains( CSL1( "hh-1" ) ) );
	QVERIFY( mapping.contains( CSL1( "pc-100" ) ) );
}

void IDMappingTest::testRemove()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.remove( CSL1( "hh-1" ) );

	QVERIFY( !mapping.contains( CSL1( "hh-1" ) ) );
	QVERIFY( !mapping.contains( CSL1( "pc-100" ) ) );

	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.remove( CSL1( "pc-100" ) );

	QVERIFY( !mapping.contains( CSL1( "hh-1" ) ) );
	QVERIFY( !mapping.contains( CSL1( "pc-100" ) ) );
}

void IDMappingTest::testIsValid()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.map( CSL1( "hh-2" ), CSL1( "pc-40" ) );
	mapping.map( CSL1( "hh-3" ), CSL1( "pc-46" ) );

	QStringList hhIds;
	hhIds << CSL1( "hh-1" ) << CSL1( "hh-2" ) << CSL1( "hh-3" );

	QStringList pcIds;
	pcIds << CSL1( "pc-100" ) << CSL1( "pc-40" ) << CSL1( "pc-46" );

	/*
	 * This is a bit tricky. There are three id's in the list and there are three
	 * mappings. Also for each id in this list exists a mapping. BUT the ids of
	 * hh and are mixed here and have a mapping all by coincidence, however this
	 * does not garantee that the mapping is valid. If for example "hh-1" maps to
	 * "pc-78" the mapping is invalid because it should map to "pc-100"
	 */
	QStringList trickyIds;
	trickyIds << CSL1( "hh-1" ) << CSL1( "pc-40" ) << CSL1( "pc-46" );

	QStringList randomIds;
	randomIds << CSL1( "random-2" ) << CSL1( "random-14" );
	randomIds	<< CSL1( "random-109" );

	QVERIFY( mapping.isValid( hhIds ) );
	QVERIFY( mapping.isValid( pcIds ) );
	QVERIFY( !mapping.isValid( trickyIds ) );
	QVERIFY( !mapping.isValid( randomIds ) );
}

void IDMappingTest::testRecordId()
{
	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.map( CSL1( "hh-2" ), CSL1( "pc-40" ) );

	QVERIFY( mapping.recordId( CSL1( "hh-1" ) ) == CSL1( "pc-100" ) );
	QVERIFY( mapping.recordId( CSL1( "pc-100" ) ) == CSL1( "hh-1" ) );
	QVERIFY( mapping.recordId( CSL1( "hh-2" ) ) == CSL1( "pc-40" ) );
	QVERIFY( mapping.recordId( CSL1( "pc-40" ) ) == CSL1( "hh-2" ) );
}

void IDMappingTest::testCommitRollBack()
{
	// Clean up things to ensure this test won't be influenced by earlier data
	// which might be there.
	cleanDir();

	IDMapping mapping( fUser, fConduit );
	mapping.map( CSL1( "hh-1" ), CSL1( "pc-100" ) );
	mapping.map( CSL1( "hh-2" ), CSL1( "pc-40" ) );
	mapping.commit();

	// Should contain 2 mappings
	IDMapping mapping2( fUser, fConduit );

	QStringList hhIds, hhIds2;
	hhIds << CSL1( "hh-1" ) << CSL1( "hh-2" );
	hhIds2 << hhIds << CSL1( "hh-3" );

	QVERIFY( mapping.isValid( hhIds ) );

	mapping2.map( CSL1( "hh-3" ), CSL1( "pc-23" ) );
	mapping2.commit();

	QVERIFY( mapping2.isValid( hhIds2 ) );

	mapping2.rollback();

	QVERIFY( mapping2.isValid( hhIds ) );

	IDMapping mapping3( fUser, fConduit );

	QVERIFY( mapping3.isValid( hhIds ) );
}

void IDMappingTest::cleanDir()
{
	QString pathName = KGlobal::dirs()->saveLocation( "data",
		CSL1("kpilot/conduits/"));

	QDir dir( pathName );
	dir.cd( fUser );
	dir.cd( CSL1( "mapping" ) );
	dir.remove( fConduit + CSL1( "-mapping.xml" ) );
	dir.remove(  fConduit + CSL1( "-mapping.xml~" ) );
	dir.remove(  fConduit + CSL1( "-mapping.xml.fail" ) );
	dir.cd( CSL1( ".." ) );
	dir.rmdir( CSL1( "mapping" ) );
	dir.cd( CSL1( ".." ) );
	dir.rmdir( fUser );
}

void IDMappingTest::cleanupTestCase()
{
	cleanDir();
}

QTEST_KDEMAIN(IDMappingTest, NoGUI)

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


<commit_before>#include <functional>
#include <future>
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "feature.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "operationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "tablemerger.h"
#include "binarymathfeature.h"

using namespace Ilwis;
using namespace BaseOperations;

REGISTER_OPERATION(BinaryMathFeature)

BinaryMathFeature::BinaryMathFeature()
{
}

BinaryMathFeature::BinaryMathFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}

bool BinaryMathFeature::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    FeatureIterator iterIn1(_inputFeatureSet1);
    for_each(iterIn1, iterIn1.end(), [&](SPFeatureI feature){
        _outputFeatures->newFeatureFrom(feature, _inputFeatureSet1->coordinateSystem());
    });

    FeatureIterator iterIn2(_inputFeatureSet2);
    for_each(iterIn2, iterIn2.end(), [&](SPFeatureI feature){
        _outputFeatures->newFeatureFrom(feature, _inputFeatureSet2->coordinateSystem());
    });

    ITable attTarget = _outputFeatures->attributeTable();
    _merger.mergeTableData(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable(), attTarget);

    return true;
}

OperationImplementation *BinaryMathFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new BinaryMathFeature(metaid, expr);
}

OperationImplementation::State BinaryMathFeature::prepare(ExecutionContext *ctx, const SymbolTable &)
{
    QString featureCovName =  _expression.parm(0).value();
    if (!_inputFeatureSet1.prepare(featureCovName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,"" );
        return sPREPAREFAILED;
    }
    featureCovName =  _expression.parm(1).value();
    if (!_inputFeatureSet2.prepare(featureCovName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,"" );
        return sPREPAREFAILED;
    }
    bool ok = false;
    if ( ctx->_masterCsy != sUNDEF) {
        ok = _csyTarget.prepare(ctx->_masterCsy);
        if (!ok){
            WARN1(WARN_COULDNT_CREATE_OBJECT_FOR_1,ctx->_masterCsy);
        }
    }
    if (!ok) {
        _csyTarget = _inputFeatureSet1->coordinateSystem();
    }

    Resource resource(_inputFeatureSet1->ilwisType() | _inputFeatureSet2->ilwisType());
    _outputFeatures.prepare(resource);
    Envelope envelope = addEnvelopes();
    _outputFeatures->coordinateSystem(_csyTarget);
    _outputFeatures->envelope(envelope);

    ITable attTable = _merger.mergeMetadataTables(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable());
    attTable->recordCount(_inputFeatureSet1->featureCount() + _inputFeatureSet2->featureCount());
    _outputFeatures->attributesFromTable(attTable);

    QString outname = _expression.parm(0,false).value();
    if ( outname != sUNDEF)
        _outputFeatures->name(outname);

    return sPREPARED;
}

Envelope BinaryMathFeature::addEnvelopes() const {
    Envelope envelope = _csyTarget->convertEnvelope(_inputFeatureSet1->coordinateSystem(),_inputFeatureSet1->envelope());
    envelope += _csyTarget->convertEnvelope(_inputFeatureSet2->coordinateSystem(),_inputFeatureSet2->envelope());
    return envelope;
}

quint64 BinaryMathFeature::createMetadata()
{
    OperationResource operation({"ilwis://operations/binarymathfeatures"});
    operation.setSyntax("binarymathfeatures(featurecoverage1,featurescoverage2,add|substract)");
    operation.setDescription(TR("generates a new featurecoverage that puts all the features of both coverages into one coverage"));
    operation.setInParameterCount({3});
    operation.addInParameter(0,itFEATURE, TR("first input feature coverage"));
    operation.addInParameter(1,itFEATURE, TR("second input feature coverage"));
    operation.addInParameter(2,itSTRING , TR("Operator"),TR("operator applied to the other 2 input parameters"));
    operation.setOutParameterCount({1});
    operation.addOutParameter(0,itFEATURE, TR("output featurecoverage"));
    operation.setKeywords("features, merge");

    mastercatalog()->addItems({operation});
    return operation.id();
}
<commit_msg>set default operation<commit_after>#include <functional>
#include <future>
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "feature.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "operationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "tablemerger.h"
#include "binarymathfeature.h"

using namespace Ilwis;
using namespace BaseOperations;

REGISTER_OPERATION(BinaryMathFeature)

BinaryMathFeature::BinaryMathFeature()
{
}

BinaryMathFeature::BinaryMathFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}

bool BinaryMathFeature::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    FeatureIterator iterIn1(_inputFeatureSet1);
    for_each(iterIn1, iterIn1.end(), [&](SPFeatureI feature){
        _outputFeatures->newFeatureFrom(feature, _inputFeatureSet1->coordinateSystem());
    });

    FeatureIterator iterIn2(_inputFeatureSet2);
    for_each(iterIn2, iterIn2.end(), [&](SPFeatureI feature){
        _outputFeatures->newFeatureFrom(feature, _inputFeatureSet2->coordinateSystem());
    });

    ITable attTarget = _outputFeatures->attributeTable();
    _merger.mergeTableData(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable(), attTarget);

    return true;
}

OperationImplementation *BinaryMathFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new BinaryMathFeature(metaid, expr);
}

OperationImplementation::State BinaryMathFeature::prepare(ExecutionContext *ctx, const SymbolTable &)
{
    QString featureCovName =  _expression.parm(0).value();
    if (!_inputFeatureSet1.prepare(featureCovName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,"" );
        return sPREPAREFAILED;
    }
    featureCovName =  _expression.parm(1).value();
    if (!_inputFeatureSet2.prepare(featureCovName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,featureCovName,"" );
        return sPREPAREFAILED;
    }
    bool ok = false;
    if ( ctx->_masterCsy != sUNDEF) {
        ok = _csyTarget.prepare(ctx->_masterCsy);
        if (!ok){
            WARN1(WARN_COULDNT_CREATE_OBJECT_FOR_1,ctx->_masterCsy);
        }
    }
    if (!ok) {
        _csyTarget = _inputFeatureSet1->coordinateSystem();
    }

    Resource resource(_inputFeatureSet1->ilwisType() | _inputFeatureSet2->ilwisType());
    _outputFeatures.prepare(resource);
    Envelope envelope = addEnvelopes();
    _outputFeatures->coordinateSystem(_csyTarget);
    _outputFeatures->envelope(envelope);

    ITable attTable = _merger.mergeMetadataTables(_inputFeatureSet1->attributeTable(), _inputFeatureSet2->attributeTable());
    attTable->recordCount(_inputFeatureSet1->featureCount() + _inputFeatureSet2->featureCount());
    _outputFeatures->attributesFromTable(attTable);

    QString outname = _expression.parm(0,false).value();
    if ( outname != sUNDEF)
        _outputFeatures->name(outname);

    return sPREPARED;
}

Envelope BinaryMathFeature::addEnvelopes() const {
    Envelope envelope = _csyTarget->convertEnvelope(_inputFeatureSet1->coordinateSystem(),_inputFeatureSet1->envelope());
    envelope += _csyTarget->convertEnvelope(_inputFeatureSet2->coordinateSystem(),_inputFeatureSet2->envelope());
    return envelope;
}

quint64 BinaryMathFeature::createMetadata()
{
    OperationResource operation({"ilwis://operations/binarymathfeatures"});
    operation.setSyntax("binarymathfeatures(featurecoverage1,featurescoverage2,!add|substract)");
    operation.setDescription(TR("generates a new featurecoverage that puts all the features of both coverages into one coverage"));
    operation.setInParameterCount({3});
    operation.addInParameter(0,itFEATURE, TR("first input feature coverage"));
    operation.addInParameter(1,itFEATURE, TR("second input feature coverage"));
    operation.addInParameter(2,itSTRING , TR("Operator"),TR("operator applied to the other 2 input parameters"));
    operation.setOutParameterCount({1});
    operation.addOutParameter(0,itFEATURE, TR("output featurecoverage"));
    operation.setKeywords("features, merge");

    mastercatalog()->addItems({operation});
    return operation.id();
}
<|endoftext|>